commit 60cce66993093941abf7aefe9ecdbdae06454b1c Author: 墨青 Date: Sun Nov 15 23:21:59 2026 +0800 初始化 VRMify 增强版(VRMify Enhanced) 导入上游源码,为所有面向用户的品牌显示处添加「增强版 / Enhanced」标识;包含 unitypackage→VRM 的纯色 Toon 材质、兽耳 SpringBone、Unity 描边、UV 接缝白边补偿修复,以及默认不强制 T-pose。146 个单元测试通过。 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..fea53bd --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Vendored third-party files: keep byte-for-byte +ui/viewer/vendor/** -text +*.bat text eol=crlf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..8cce882 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,47 @@ +# 打 v* tag 时:测试 → 打包 Windows 绿色版 zip → 冒烟测试(tools/smoke_exe.py)→ 建一个草稿 Release(确认后在网页上点发布)。 +# 手动运行(workflow_dispatch)只打包,zip 在这次运行的 Artifacts 里,不建 Release。 +# +# 改 ui/version.py → 提交 → git tag v0.1.0 → git push origin v0.1.0 +name: Release + +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: write + +jobs: + build: + runs-on: windows-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + - run: pip install -r requirements-dev.txt + - run: python -m unittest discover -s tests + - name: Build + id: build + shell: pwsh + run: | + $expect = if ("${{ github.ref_type }}" -eq "tag") { "${{ github.ref_name }}" } else { "" } + python tools/build_release.py --expect-version "$expect" + # 打包后的 exe 实际跑一遍:启动、转换合成的 PMX / zip / FBX / unitypackage、校验输出(不过就不建 Release) + - name: Smoke test + run: python tools/smoke_exe.py "${{ steps.build.outputs.zip }}" + # 直接上传 zip 本身(archive: false),下载下来不会是「zip 套 zip」 + - uses: actions/upload-artifact@v7 + with: + path: ${{ steps.build.outputs.zip }} + archive: false + - name: Draft release + if: github.ref_type == 'tag' + shell: pwsh + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "${{ github.ref_name }}" "${{ steps.build.outputs.zip }}" --draft ` + --title "VRMify 增强版 / VRMify Enhanced ${{ github.ref_name }}" --generate-notes diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..e564731 --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,45 @@ +# 推送到 main(改了代码时)跑单元测试。用 tests/synth.py 合成的小模型,不需要真实模型; +# 真实模型的回归对比(tools/regress.py)只能在本机跑。 +name: Tests + +on: + push: + branches: [main] + paths: + - "convert/**" + - "formats/**" + - "ui/**" + - "tests/**" + - "tools/**" + - "requirements*.txt" + - ".github/workflows/test.yml" + pull_request: + paths: + - "convert/**" + - "formats/**" + - "ui/**" + - "tests/**" + - "tools/**" + - "requirements*.txt" + - ".github/workflows/test.yml" + workflow_dispatch: + +concurrency: + group: tests-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-python@v6 + with: + python-version: "3.11" + # 官方 VRM Schema 校验 + 贴图瘦身;pywebview 只有界面窗口要用,这里不装 + - run: pip install "jsonschema>=4.18" "Pillow>=10" + - run: python -m unittest discover -s tests -v diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2c8b267 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +# Python +__pycache__/ +*.py[cod] +.venv/ +venv/ + +# Packaging (python tools/build_release.py) +build/ +dist/ + +# Local models and conversion outputs (model licenses forbid redistribution) +model/ +vrm/ +vrm_new/ +ref/ + +# QA: regression baselines (derived from local models), Node dependencies, downloaded VRM schemas +tests/.golden/ +tools/qa/harness/node_modules/ +tools/qa/.schema-cache/ + +# UI settings and per-model tuning (per machine) +settings.json +edits.json +startup.log +edits/ + +# Editors and local tool config +.vscode/ +.idea/ +.claude/launch.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..bb6413e --- /dev/null +++ b/README.md @@ -0,0 +1,287 @@ +

+ +

+ +

VRMify Enhanced

+ +

VRMify Enhanced · 增强版 — upstream VRMify plus fixes for solid-colour toon materials, animal-ear spring bones, Unity outlines, UV seam white edges, and a non-forced T-pose.

+ +

+ Turn MMD / PMX models — and FBX, unitypackage, Unreal and XNALara models — into VRM avatars.
+ Drop in a file or a whole archive, preview the result, done. No Blender, no Unity, no plugins. +

+ +

+ Latest release + Windows 10 / 11 + VRM 1.0 / 0.x + License: GPL-3.0 +

+ +

+ English | 简体中文 +

+ +

+ VRMify Enhanced: files and settings on the left, the 3D preview and the Tune panel on the right +

+ +## Highlights + +- **One window, nothing to install.** A portable exe for Windows. The converter itself is plain Python, so there + is no Blender, Unity or add-on chain to set up. +- **Looks right out of the box.** MToon toon shading built from the PMX toon textures, transparency decided per + texture, optional T-pose conversion (off by default — the original rest pose is preserved unless you opt in), + and VRoid-style emotion presets that move brows, eyes and mouth together. +- **Physics that moves like a native VRM.** PMX rigid bodies become VRM 1.0 SpringBone chains and colliders, with + special care for skirts. Models without physics get hair, skirt and ribbon chains from their bone names. +- **A clean skeleton.** MMD, VRChat, Mixamo and Unity bone names map to the VRM humanoid; append (付与) bones, IK, + tip and control bones that do nothing in VRM are merged or removed, leaving a VRoid-like hierarchy. +- **Feed it what model sites hand out.** Drop a zip, 7z or rar as is: models are found inside, props and + outfit-only models are skipped, and garbled Japanese / Chinese file names in old zip files are restored. +- **See it before you use it.** A three-vrm preview (the same rules as UniVRM) with walk / run motions, expressions, + and skeleton and collider overlays. Fix presets, physics, the gaze range or the thumbnail without converting again. +- **Valid output.** Output passes the official VRM JSON Schema and avoids the data that makes UniVRM imports + fail. + +## Screenshots + + + + + + + + + + + + + + + + +
Preview with motions and lightingSkeleton overlay, bones coloured by role
Preview: idle, walk and run motions, lighting, expressionsSkeleton overlay: humanoid, weighted and physics bones; name and parent on hover
+ Tune panel with a physics chain and its colliders shown + Conversion log +
Tune: presets, gaze and physics per chain, with the chain and its colliders shown · + Log: what was converted, merged or skipped
+ +Model in the screenshots: 奥黛塔 (provided by miHoYo, edited by 观海), shown under its terms of use. + +## Quick start + +1. Download `VRMify-v-win64.zip` from [Releases](https://github.com/JiGuang283/VRMify/releases/latest), + unzip it and run `VRMify.exe`. +2. Drag model files, folders or archives into the window and click **Start conversion**. +3. Click the eye icon next to a file to preview the VRM; adjust it in **Tune** if needed. + +> [!NOTE] +> The exe isn't code-signed, so Windows may show "Windows protected your PC" the first time: click **More info → +> Run anyway**. The window uses the system WebView2 (built into Windows 11 and almost every Windows 10); without it +> the UI opens in your browser, says why at the top, and still takes dropped or added files (they are copied first). +> The interface and the conversion log are in English or Chinese (switch at the top +> right); the first start follows the system language. + +## Supported formats + +| Input | | +|---|---| +| **PMX** (MMD) | the main path: skeleton, materials, morphs and physics are all converted | +| **FBX**, **unitypackage** | Unity / VRChat-style models; facing and texture alpha are detected | +| **uemodel** (UEFormat), **psk / pskx** (Unreal ActorX) | Unreal models; uemodel parts can be aligned to a full-body reference | +| **xps** (XNALara) | | +| **zip / 7z / rar** | models inside are found and converted; 7z / rar use 7-Zip, WinRAR, Bandizip or Windows' `tar` | +| **VRM** | opens in the preview and the Tune panel | + +Output: **VRM 1.0** or **VRM 0.x** (both with SpringBone physics), or **PMX** only. + +## What the conversion does + +
+Skeleton + +- MMD standard bone names (and common English, VRChat, Mixamo and Unity names) map to the VRM humanoid; missing + required bones get placeholders so the hierarchy stays valid. +- Append (付与) bones such as 足D are merged into the bones they follow, together with their weights; helper + bones that follow a joint partly (knee or elbow helpers) share their weights with the joint. +- The log warns when part of the mesh would not follow the joint it follows in MMD, or when a humanoid bone sits + clearly in the wrong place. +- Bones that move nothing in VRM — IK, tip bones, operation centres — are removed. With "Remove control bones" + (on by default) unweighted intermediate bones such as センター or グルーブ go too, so the hierarchy is + Root > Hips. Skinning and motion are unchanged. +- Optional T-pose conversion, **off by default**: the model's original rest pose is kept. Enable "Convert to + T-pose" (or pass `--tpose`) if you want A-pose arms raised, palms down, fingers straight, thumbs 45° forward; + hips are moved to the pelvis. +
+ +
+Materials + +- MToon shading: shadow colour and the light/shadow boundary come from the PMX toon textures. +- Opaque, cutout or transparent is decided from the textures themselves; materials get unique names. +- Optional texture slimming (smaller size, JPEG for opaque textures) often halves the file. +
+ +
+Expressions + +- Blink and the vowels (aa / ih / ou / ee / oh) map from MMD, VRoid, VRChat, ARKit and common Chinese names. +- Emotion presets (happy, angry, sad, relaxed, surprised) combine brow, eye and mouth morphs like VRoid. +- Material, bone and UV morphs are converted; gaze expressions are added from the eye bones. +- `hideHighlight` (eye highlights off) and `tongue` are added under fixed names — from the model's own morphs, or + generated from the eye highlight materials. +
+ +
+Physics + +- PMX rigid bodies and joints become VRM 1.0 SpringBone chains, colliders and collider groups. +- Skirt chains get colliders placed so the skirt is pushed as one piece instead of splitting; very short chains on + arms and legs follow the bone rigidly instead of jittering. +- Models without rigid bodies (FBX and others) get chains for hair, skirts, sleeves, ribbons and tails from their bone + names. +
+ +Details and all options: [PMX → VRM](docs/pmx-to-vrm.md), [Other formats → PMX](docs/other-formats.md) +(in Chinese). + +## Using the app + +**Settings** sit in three tabs: **Convert** (target, characters only, physics, expressions, file size, where to +save; more under *Advanced*), **Other formats** (FBX / uemodel / psk / xps options) and **Metadata** (author, +version and license written into every VRM; defaults to the most restrictive terms). + +**Preview controls** + +| | | +|---|---| +| Left drag / right drag / wheel | rotate / pan / zoom toward the pointer | +| Double-click the model | orbit around that point | +| `R` or `Home`, or double-click the background | back to the selected framing | +| **Bones** switch | skeleton overlay; hover a bone for its name and parent | + +**Tune** changes a converted model without converting again: name and thumbnail, which morph each preset uses and +how strong, the gaze range, and physics stiffness and gravity overall or per chain. Hover a chain to see it with +the colliders it hits; pin it or point the camera at it. Changes are written into the VRM and reapplied the next +time the file converts. + +A face thumbnail is captured automatically after each conversion (can be turned off; a thumbnail you set yourself +is kept). + +## Command line + +```bash +python convert/pmx2vrm.py "model.pmx" -o "model.vrm" # VRM 1.0 +python convert/pmx2vrm.py "model.pmx" --spec 0x # VRM 0.x +python convert/fbx2pmx.py "model.fbx" -o "model.pmx" # other formats → PMX, then VRM +python tools/qa/check_vrm.py "model.vrm" # validate a VRM (structure + official schema) +``` + +## FAQ + +
+Unity or a game hangs while importing + +Usually UniVRM hit invalid data. Check the file with `python tools/qa/check_vrm.py file.vrm`. A Unity app's log at +`%USERPROFILE%\AppData\LocalLow\\\Player.log` names the exception. +
+ +
+The model is white or some parts have no texture + +Textures have to be next to the model, where the PMX expects them: add the whole model folder or the archive, not +just the .pmx. A texture that sits in another subfolder of the model folder is found by its name; the conversion log +lists any that are still missing or can't be read. +
+ +
+The face looks flat or has no shadows + +Faces on native VRM models such as VRoid are mostly flat too; shading comes from cast shadows (hair and so on). +Shadow colour comes from the PMX toon textures. Check it with the preview's lighting angle and shadow switch. +
+ +
+Hair or skirts jitter or clip + +SpringBone is an approximation of MMD physics. Adjust stiffness and gravity overall or per chain in Tune; hover a +chain to see which colliders it uses. +
+ +
+Holes, black edges or missing hair sheets + +Turn on "All materials double-sided" under *Advanced* on the Convert tab. Outline shells (an inverted copy around the +face or body) and the inner sides of clothes stay single-sided, otherwise they would cover the model; the log lists +them. The conversion log also shows how the triangle winding was decided. +
+ +
+An FBX faces away or its transparency is wrong + +Turn on "Extra 180° turn" or try another "Texture alpha" mode on the Other formats tab. +
+ +## Known limitations + +- VRM 0.x physics is approximated from the 1.0 result: one set of parameters and one hit radius per chain, and + sphere colliders only. +- PMX joints between neighbouring skirt chains have no SpringBone equivalent, so skirts move less as one piece than + in MMD. +- Multiply sphere maps and the shared toon07–10 textures have no MToon equivalent; PMX outlines are off by + default, but outlines configured in Unity materials (`_Outline_Width` / `_Outline_Color`) are kept. +- Expression presets are matched by name; unusual names need presets assigned in Tune. +- XPS models have no morphs. + +## Running from source + +Python 3.10 or newer. + +```bash +python -m venv .venv +.venv\Scripts\pip install -r requirements.txt # optional: pywebview (own window), Pillow (faster textures) +python ui/app.py # or double-click VRMify.bat; --browser opens it in the browser +``` + +Without the optional packages conversion still works; the UI opens in the browser and texture slimming is +unavailable. + +
+Project layout and development + +``` +convert/ converters: pmx2vrm.py (PMX → VRM) and its stages in vrmconv/, fbx2pmx / uemodel2pmx / psk2pmx / + xps2pmx, pipeline.py (the app's conversion flow), vrm_edit.py (Tune) +formats/ file formats: pmxio, vrmio (GLB), fbx_reader, uemodelio, pskio, xpsio, archive +ui/ desktop app: app.py (entry), server.py (backend), web/ (pages), viewer/ (three-vrm preview) +tests/ unit tests on small generated models (synth.py) +tools/ batch conversion, VRM checks, physics tests, regression on real models, release build +docs/ conversion notes +``` + +```bash +pip install -r requirements-dev.txt # jsonschema, pyinstaller, … +python -m unittest discover -s tests # unit tests +python tools/regress.py record # record results on your own models (kept out of the repo) +python tools/regress.py check # re-convert and compare after a change +python tools/build_release.py # → dist/VRMify-v-win64.zip +``` + +Releases: bump `ui/version.py`, commit, push a `v` tag; GitHub Actions tests, builds, smoke-tests the exe +and drafts the release. +
+ +## Contributing + +Bug reports and pull requests are welcome. When reporting a conversion problem, include the conversion log and +describe the model (where it comes from, which format) — please don't attach model files you aren't allowed to +share. Run the unit tests before opening a pull request. + +## License + +- VRMify Enhanced is licensed under [GPL-3.0](LICENSE). Based on [SaraKale/Model-To-PMX](https://github.com/SaraKale/Model-To-PMX). +- The preview uses [three.js](https://threejs.org/) and [three-vrm](https://github.com/pixiv/three-vrm) (MIT) and + ammo.js (zlib); see `ui/viewer/vendor/`. +- **Make sure you're allowed to use a model before converting it.** Many MMD models forbid redistribution or + modification, and the converted VRM is bound by the same terms. diff --git a/README_SC.md b/README_SC.md new file mode 100644 index 0000000..9cfe784 --- /dev/null +++ b/README_SC.md @@ -0,0 +1,274 @@ +

+ +

+ +

VRMify 增强版

+ +

VRMify 增强版 · Enhanced — 在上游 VRMify 基础上修复了纯色 Toon 材质丢失、兽耳动骨缺失、Unity 描边丢失、UV 接缝白边,并默认不再强制 T 姿势。

+ +

+ 把 MMD / PMX 模型(以及 FBX、unitypackage、Unreal、XNALara 模型)转成 VRM 虚拟形象。
+ 拖入文件或整个压缩包,预览确认,就完成了。不需要 Blender、Unity 或任何插件。 +

+ +

+ 最新版本 + Windows 10 / 11 + VRM 1.0 / 0.x + 许可证:GPL-3.0 +

+ +

+ English | 简体中文 +

+ +

+ VRMify 增强版:左侧是文件列表和转换设置,右侧是三维预览和调整面板 +

+ +## 亮点 + +- **一个窗口,不用安装。** Windows 绿色版 exe,转换器本身是纯 Python,不需要配置 Blender、Unity 或插件。 +- **转出来就好看。** 按 PMX 的 toon 贴图生成 MToon 卡通着色,透明按贴图逐张判定,默认保留模型原姿势 + (需要时再手动勾选「转为 T 姿势」),情绪表情像 VRoid 一样眉、眼、嘴一起变。 +- **物理手感接近原生 VRM。** PMX 刚体换算成 VRM 1.0 SpringBone 链和碰撞体,裙摆做了专门处理; + 没有物理的模型按骨骼名自动补头发、裙摆、飘带。 +- **干净的骨架。** MMD、VRChat、Mixamo、Unity 的骨名都能对应 VRM humanoid;付与骨合并,IK、末端骨、 + 控制骨这类在 VRM 里不起作用的骨去掉,层级和 VRoid 一样。 +- **模型网站下载的包直接用。** zip / 7z / rar 原样拖进来,自动找出里面的模型,跳过道具和只有衣服的模型, + 老 zip 包里乱码的日文 / 中文文件名也能还原。 +- **用之前先看。** three-vrm 预览(和 UniVRM 同一套规则),可以播放走路、跑步动作、试表情,叠加显示骨骼和 + 碰撞体。预设表情、物理、视线范围、缩略图都能直接调,不用重新转换。 +- **输出可靠。** 通过 VRM 官方 JSON Schema 校验,避开会让 UniVRM 导入失败的数据。 + +## 截图 + + + + + + + + + + + + + + + + +
预览:动作和灯光骨骼显示,按类别分色
预览:待机、走路、跑步动作,灯光,表情骨骼显示:humanoid、带权重、物理骨分色,悬停显示骨名和父骨
+ 调整面板,显示一条物理链和它的碰撞体 + 转换日志 +
调整:预设表情、视线、逐条链的物理,并显示这条链和它的碰撞体 · + 日志:转换了什么、合并或跳过了什么,一目了然
+ +截图中的模型:奥黛塔(模型提供 miHoYo,改造 观海),按其使用条款展示。 + +## 快速开始 + +1. 到 [Releases](https://github.com/JiGuang283/VRMify/releases/latest) 下载 `VRMify-v<版本>-win64.zip`, + 解压后运行 `VRMify.exe`。 +2. 把模型文件、文件夹或压缩包拖进窗口,点「开始转换」。 +3. 点文件旁的眼睛图标预览 VRM,需要的话在「调整」里修改。 + +> [!NOTE] +> 程序没有代码签名,第一次运行时 Windows 可能提示「已保护你的电脑」:点「更多信息 → 仍要运行」。 +> 窗口使用系统的 WebView2(Windows 11 自带,Windows 10 基本都有);没有时会改用浏览器打开界面,页面顶上会说明原因, +> 照样可以拖入或添加文件(会先复制一份)。 +> 界面和转换日志有中文、英文两种(右上角切换),第一次启动时跟随系统语言。 + +## 支持的格式 + +| 输入 | | +|---|---| +| **PMX**(MMD) | 主要路径:骨骼、材质、表情、物理全部转换 | +| **FBX**、**unitypackage** | Unity / VRChat 风格的模型,自动判定朝向和贴图透明 | +| **uemodel**(UEFormat)、**psk / pskx**(Unreal ActorX) | Unreal 模型;uemodel 部件可以按整身参考对齐 | +| **xps**(XNALara) | | +| **zip / 7z / rar** | 找出里面的模型并转换;7z / rar 借用 7-Zip、WinRAR、Bandizip 或 Windows 自带的 `tar` | +| **VRM** | 在预览和「调整」里打开 | + +输出:**VRM 1.0** 或 **VRM 0.x**(都带 SpringBone 物理),或只转到 **PMX**。 + +## 转换时做了什么 + +
+骨骼 + +- MMD 标准骨名(以及常见的英文、VRChat、Mixamo、Unity 骨名)对应 VRM humanoid;缺少的必需骨位补占位骨, + 保证层级合法。 +- 足D 这类付与骨连同权重并入它跟随的骨;膝盖、手肘的辅助骨这类按比例跟随关节的骨,权重按比例分给关节骨。 +- 有部分网格在 MMD 里跟着关节动、在 VRM 里却不跟,或者 humanoid 骨位置明显不对时,日志里会提示。 +- 在 VRM 里不起作用的骨(IK、末端骨、操作中心)去掉。「精简控制骨」(默认开)再去掉センター、グルーブ 这类 + 没有权重的中间骨,层级是 Root > Hips。蒙皮和动作不受影响。 +- 可选的 T-pose 转换(默认关闭,原样保留模型静止姿势):勾选「转为 T 姿势」后把 A-pose 的手臂抬平, + 手掌朝下、手指伸直、拇指斜向前 45°;hips 移到骨盆。 +
+ +
+材质 + +- MToon 着色:阴影色和明暗交界从 PMX 的 toon 贴图换算。 +- 不透明、裁剪、半透明按贴图本身判定;材质名保证不重复。 +- 可选贴图瘦身(缩小尺寸、不透明贴图存 JPEG),文件通常能小一半。 +
+ +
+表情 + +- 眨眼和口型(aa / ih / ou / ee / oh)按 MMD、VRoid、VRChat、ARKit 和常见中文表情名对应。 +- 情绪预设(开心、生气、悲伤、放松、惊讶)像 VRoid 一样组合眉、眼、嘴。 +- 材质表情、骨骼表情、UV 表情都会转换;有眼骨时补视线表情。 +- 补充固定名字的 `hideHighlight`(关掉眼睛高光)和 `tongue`(吐舌):优先用模型自带的表情,没有关闭高光的 + 表情时按眼睛高光材质生成。 +
+ +
+物理 + +- PMX 的刚体和关节换算成 VRM 1.0 SpringBone 的链、碰撞体和碰撞组。 +- 裙摆链的碰撞体会调整位置,被腿推开时整片一起动,不会从中间劈开;手臂、腿上很短的链跟着骨骼刚性移动, + 避免抖动。 +- 没有刚体的模型(FBX 等)按骨骼名自动补头发、裙摆、袖子、飘带、尾巴的链。 +
+ +更多细节和全部选项:[PMX → VRM](docs/pmx-to-vrm.md)、[其它格式 → PMX](docs/other-formats.md)。 + +## 使用 + +**设置**分三页:「转换」(目标格式、只转换人物、物理、表情、文件大小、保存位置,更多选项在「高级设置」里)、 +「其它格式」(FBX / uemodel / psk / xps 的选项)、「VRM 信息」(写进每个 VRM 的作者、版本和使用许可, +默认是最保守的授权)。 + +**预览操作** + +| | | +|---|---| +| 左键拖动 / 右键拖动 / 滚轮 | 旋转 / 平移 / 朝鼠标位置缩放 | +| 双击模型 | 以这一点为中心旋转 | +| `R` 或 `Home`,或双击空白处 | 回到当前选中的视角 | +| 「骨骼」开关 | 叠加显示骨骼;悬停显示骨名和父骨 | + +**调整**不用重新转换就能修改:名称和缩略图、每个预设对应哪个表情和强度、视线范围、整体或逐条链的物理硬度和 +重力。鼠标移到某条链上会显示这条链和它会碰到的碰撞体,也可以固定显示或让镜头对准它。修改直接写进 VRM, +下次再转同一个文件会自动套用。 + +每次转换后会自动截取脸部作为缩略图(可关闭;自己设置的缩略图不会被覆盖)。 + +## 命令行 + +```bash +python convert/pmx2vrm.py "model.pmx" -o "model.vrm" # VRM 1.0 +python convert/pmx2vrm.py "model.pmx" --spec 0x # VRM 0.x +python convert/fbx2pmx.py "model.fbx" -o "model.pmx" # 其它格式 → PMX,再转 VRM +python tools/qa/check_vrm.py "model.vrm" # 检查 VRM(结构 + 官方 Schema) +``` + +## 常见问题 + +
+模型是白的 / 部分地方没有贴图 + +贴图要和模型放在一起、在 PMX 记录的位置:加入整个模型文件夹或压缩包,不要只加 .pmx。贴图在模型文件夹的 +其它子文件夹里时会按文件名找到;仍然找不到或读不了的会在转换日志里列出来。 +
+ +
+UV 接缝处有白边 + +贴图 UV 岛之间没留边距(gutter)时,glTF / VRM 的 mipmap 采样会把岛外的白底平均进边缘, +沿 UV 接缝就出现一圈白边;Blender / Unity 用不同的插值或较低的贴图导入分辨率,往往看不出来。 +UV 数据本身没转错。勾选「贴图不生成 mipmap(消除 UV 接缝白边)」可立刻缓解(远景会有轻微锯齿); +要根治得在贴图里给每个 UV 岛做 4~8 px 的边缘外扩(padding)。 +
+ +
+Unity 或游戏导入时卡住 + +多半是 UniVRM 遇到了不合规的数据。用 `python tools/qa/check_vrm.py 文件.vrm` 检查;Unity 程序的日志在 +`%USERPROFILE%\AppData\LocalLow\<公司>\<产品>\Player.log`,里面有具体的异常。 +
+ +
+脸看起来很平、没有阴影 + +VRoid 等原生 VRM 模型的脸本来也基本是平涂,阴影主要来自头发等的投影。阴影颜色来自 PMX 的 toon 贴图, +可以在预览的「灯光」里调角度、开关投影检查。 +
+ +
+头发、裙摆抖动或穿模 + +SpringBone 是 MMD 物理的近似。在「调整」里整体或逐条链调硬度和重力;鼠标移到链上可以看到它用了哪些碰撞体。 +
+ +
+模型有破洞、黑边,或薄片头发看不见 + +在「转换」页的「高级设置」里打开「所有材质双面」。描边外壳(翻面后包在脸、身体外面的那层)和衣服的内侧面仍保持单面, +否则会盖住模型,日志里会列出。转换日志里也有三角形绕序的判定结果。 +
+ +
+FBX 朝向反了或透明不对 + +在「其它格式」页打开「额外旋转 180°」,或换一种「贴图透明通道」模式。 +
+ +## 已知限制 + +- VRM 0.x 的物理由 1.0 的结果近似换算:每条链只有一套参数和一个碰撞半径,碰撞体只有球。 +- PMX 里连接相邻裙摆链的横向关节在 SpringBone 里没有对应,裙摆整片联动的效果比 MMD 弱。 +- 乘算 sphere 贴图和共享的 toon07~10 在 MToon 里没有对应;描边默认关闭。 +- 预设表情按名字对应,名字特殊的模型需要在「调整」里指定。 +- XPS 模型没有表情。 + +## 从源码运行 + +需要 Python 3.10 或更高版本。 + +```bash +python -m venv .venv +.venv\Scripts\pip install -r requirements.txt # 可选:pywebview(独立窗口)、Pillow(贴图处理更快) +python ui/app.py # 或双击 VRMify.bat;--browser 用浏览器打开界面 +``` + +不装可选依赖也能转换,只是界面会在浏览器里打开,也不能瘦身贴图。 + +
+目录结构和开发 + +``` +convert/ 转换器:pmx2vrm.py(PMX → VRM)及其各阶段 vrmconv/,fbx2pmx / uemodel2pmx / psk2pmx / xps2pmx, + pipeline.py(界面的转换流程),vrm_edit.py(调整) +formats/ 文件格式:pmxio、vrmio(GLB)、fbx_reader、uemodelio、pskio、xpsio、archive +ui/ 桌面程序:app.py(入口)、server.py(后端)、web/(页面)、viewer/(three-vrm 预览) +tests/ 单元测试(用 synth.py 生成的小模型) +tools/ 批量转换、VRM 检查、物理测试、真实模型回归、打包发布 +docs/ 转换说明 +``` + +```bash +pip install -r requirements-dev.txt # jsonschema、pyinstaller 等 +python -m unittest discover -s tests # 单元测试 +python tools/regress.py record <模型目录> # 用自己的模型记录基准(不进仓库) +python tools/regress.py check # 改代码后重转并对比 +python tools/build_release.py # → dist/VRMify-v<版本>-win64.zip +``` + +发版:改 `ui/version.py`,提交,推送 `v<版本>` 标签;GitHub Actions 会测试、打包、冒烟测试 exe 并创建草稿 Release。 +
+ +## 参与贡献 + +欢迎提交问题和 Pull Request。反馈转换问题时请附上转换日志,并说明模型的来源和格式——不要附上你无权分享的 +模型文件。提交 Pull Request 前请先跑一遍单元测试。 + +## 许可 + +- VRMify 增强版 使用 [GPL-3.0](LICENSE) 许可。基于 [SaraKale/Model-To-PMX](https://github.com/SaraKale/Model-To-PMX)。 +- 预览使用 [three.js](https://threejs.org/)、[three-vrm](https://github.com/pixiv/three-vrm)(MIT)和 + ammo.js(zlib),见 `ui/viewer/vendor/`。 +- **转换前请确认你有权使用这个模型。** 很多 MMD 模型禁止再分发或修改,转换后的 VRM 同样受这些条款约束。 diff --git a/VRMify.bat b/VRMify.bat new file mode 100644 index 0000000..bd7cc79 --- /dev/null +++ b/VRMify.bat @@ -0,0 +1,24 @@ +@echo off +rem VRMify 增强版 (VRMify Enhanced) launcher: double-click to open the converter UI (ui\app.py). +rem Uses the project's .venv when it exists (pywebview window, Pillow for texture slimming); +rem otherwise the Python on PATH, which opens the UI in the default browser if pywebview is missing. +rem Files or folders dropped onto this .bat are added to the list. +cd /d "%~dp0" +if exist ".venv\Scripts\pythonw.exe" ( + start "" ".venv\Scripts\pythonw.exe" ui\app.py %* + exit /b +) +where pyw >nul 2>nul +if not errorlevel 1 ( + start "" pyw -3 ui\app.py %* + exit /b +) +where pythonw >nul 2>nul +if not errorlevel 1 ( + start "" pythonw ui\app.py %* + exit /b +) +echo Python 3 was not found. +echo Install Python 3.9 or newer from https://www.python.org/ and run this file again, +echo or create the project environment: uv venv .venv ^&^& uv pip install -r requirements.txt +pause diff --git a/VRMify.spec b/VRMify.spec new file mode 100644 index 0000000..3bb222b --- /dev/null +++ b/VRMify.spec @@ -0,0 +1,102 @@ +# -*- mode: python ; coding: utf-8 -*- +# VRMify 增强版 / VRMify Enhanced +# 图形界面(ui/app.py)的 PyInstaller 打包配置: +# +# pyinstaller VRMify.spec → dist/VRMify/VRMify.exe +# +# 打包环境里要装 pywebview(原生窗口 + 拖放)和 Pillow(贴图瘦身),见 requirements.txt; +# 没装的话 exe 会退回系统浏览器 / 不能瘦身贴图。settings.json、edits.json 写在 exe 旁边 +# (那里写不了时改到 %APPDATA%\VRMify)。发布用的 zip 由 tools/build_release.py 生成。 +import os +import re +import sys + +is_win = sys.platform.startswith('win') +is_mac = sys.platform == 'darwin' +app_name = 'VRMify' +icon_file = 'ui/icon.ico' if is_win else None # 由 tools/make_icon.py 生成 + +# ---- 版本号:唯一来源是 ui/version.py,写进 exe 的「属性 → 详细信息」 +with open(os.path.join('ui', 'version.py'), encoding='utf-8') as _f: + app_version = re.search(r'__version__\s*=\s*["\']([^"\']+)', _f.read()).group(1) +_v = tuple((int(x) for x in (re.findall(r'\d+', app_version) + ['0'] * 4)[:4])) +version_file = None +if is_win: + version_file = os.path.join(workpath, 'version_info.txt') + os.makedirs(workpath, exist_ok=True) + with open(version_file, 'w', encoding='utf-8') as _f: + _f.write("""VSVersionInfo( + ffi=FixedFileInfo(filevers=%(v)r, prodvers=%(v)r, mask=0x3f, flags=0x0, OS=0x40004, + fileType=0x1, subtype=0x0, date=(0, 0)), + kids=[ + StringFileInfo([StringTable('040904B0', [ + StringStruct('FileDescription', 'VRMify Enhanced'), + StringStruct('FileVersion', '%(s)s'), + StringStruct('InternalName', 'VRMify Enhanced'), + StringStruct('OriginalFilename', 'VRMify.exe'), + StringStruct('ProductName', 'VRMify Enhanced'), + StringStruct('ProductVersion', '%(s)s'), + StringStruct('LegalCopyright', 'GPL-3.0')])]), + VarFileInfo([VarStruct('Translation', [1033, 1200])]) + ] +) +""" % {'v': _v, 's': app_version}) + +a = Analysis( + ['ui/app.py'], + # 模块之间是用裸名 import 的(import pipeline / pmxio …),运行期才把子目录加进 sys.path, + # PyInstaller 的静态分析看不到,所以子目录要写进 pathex + pathex=['.', 'ui', 'convert', 'formats'], + binaries=[], + # 界面页面和预览组件(three.js / three-vrm 离线副本);server.py 在 _MEIPASS 下按同样的相对路径找 + datas=[('ui/web', 'ui/web'), ('ui/viewer', 'ui/viewer')], + hiddenimports=[ + 'server', 'version', 'pipeline', 'parallel', 'pmx2vrm', 'vrm_edit', 'logtext', + 'vrmconv', 'vrmconv.humanoid', 'vrmconv.skeleton', 'vrmconv.mesh', 'vrmconv.materials', + 'vrmconv.expressions', 'vrmconv.springbone', 'vrmconv.vrm_ext', 'vrmconv.mathutil', + 'vrmconv.textures', 'vrmconv.autophys', 'vrmconv.morphbake', 'vrmconv.checks', 'vrmconv.springbone_v0', + # 其它输入格式(pipeline 里按需 import) + 'fbx2pmx', 'fbx_reader', 'unitypackage_unpack', 'archive', 'uemodel2pmx', 'uemodelio', + 'psk2pmx', 'pskio', 'xps2pmx', 'xpsio', 'fbxout', 'pmxio', 'vrmio', 'longpath', 'unityasset', + 'zstandard', + # 浏览器模式下的文件对话框(子进程 --dialog) + 'tkinter', 'tkinter.filedialog', + ], + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + [], + exclude_binaries=True, + name=app_name, + icon=icon_file, + version=version_file, + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=False, + console=False, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) +coll = COLLECT( + exe, + a.binaries, + a.datas, + strip=False, + upx=False, + name=app_name, +) +if is_mac: + app = BUNDLE(coll, name=f'{app_name}.app', icon=icon_file, bundle_identifier='com.vrmify.app') diff --git a/convert/__init__.py b/convert/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/convert/fbx2pmx.py b/convert/fbx2pmx.py new file mode 100644 index 0000000..f2907ee --- /dev/null +++ b/convert/fbx2pmx.py @@ -0,0 +1,2418 @@ +"""fbx2pmx.py - convert a binary FBX (7.x) into a PMX 2.0 model. + +Standalone: no Autodesk FBX SDK, no Blender, no mmd_tools. + +What it maps: + Geometry -> PMX vertices + triangles + Model(Mesh) material link -> PMX materials (one draw segment per mesh) + Deformer/Skin + Cluster -> PMX bone weights (BDEF1/2/4) + Model(LimbNode) hierarchy -> PMX bones + LayerElementUV / Normal -> PMX UV0 / vertex normals + Deformer/BlendShape chain -> PMX vertex morphs (表情) + Geometry -> BlendShape -> BlendShapeChannel -> Shape, where each Shape + holds Indexes (affected control points) + Vertices (relative position + deltas). The morph panel (眉/目/口/その他) is inferred from the channel + name; every morph is written as PMX kind=1 (頂点). + +What it does NOT and cannot invent: physics rigid bodies / joints. Texture +references ARE extracted when the FBX links them via Texture/Video nodes; the +actual image files are copied into ``/textures/`` only if they can be found +on disk (the FBX often stores an absolute game path). + +Usage: + python fbx2pmx.py "model.fbx" -o "model.pmx" + python fbx2pmx.py "model.fbx" --info + python fbx2pmx.py "model.fbx" --no-morphs # skip blend shapes + python fbx2pmx.py "model.fbx" --alpha auto # per-texture alpha decision + python fbx2pmx.py "model.fbx" --keep-untextured-meshes + +Texture alpha (``--alpha``): MMD uses the **texture alpha channel as material +transparency**, and game textures often store something else there. Three +modes: ``keep`` (copy as-is), ``strip`` (always drop the alpha channel), +``auto`` (default - decide per image, see :func:`decide_alpha`). Stripped +copies are written as ``_noalpha.`` so the original is never +touched. ``--remove-alpha`` is kept as a legacy alias for ``--alpha auto``. + +Facing (``--no-auto-facing`` / ``--face-180``): FBX has no "which way does the +character look" field, and MMD always wants the model to face -Z. Because the +Z negation below already turns a +Z-facing model into a -Z-facing one, only +models authored facing -Z need an extra 180 degree turn. That is decided per +file by :func:`detect_forward_turn` (toe bones, then face-mesh centroid). + +Untextured meshes (``--keep-untextured-meshes``): meshes that carry **no +material at all** are dropped by default. Game exports (Unity / HoYo style) +often ship a sheet named ``EffectMesh`` - no material node, no texture, UVs +spread over the whole atlas, geometry a thin plate spanning the body. Exported +as a normal mesh it becomes an opaque grey slab sitting on top of the dress, +which looks exactly like "the texture got flipped" in MMD. Pass +``--keep-untextured-meshes`` to keep them anyway. +""" +import argparse +import math +import os +import shutil +import struct +import sys + +# 让 `python convert/fbx2pmx.py ...` 也能直接跑:脚本自己所在目录(convert/)和同级的 +# formats/ 都要进 sys.path。以前这里只加了 convert/,于是 `import pmxio` 之类会 +# ModuleNotFoundError —— 而 README 里给的命令行用法就是这么调的。 +_HERE = os.path.dirname(os.path.abspath(__file__)) +for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")): + if _p not in sys.path: + sys.path.insert(0, _p) +import fbx_reader as fbx +import unityasset +import vrmio + + +# --------------------------------------------------- 贴图 alpha / 朝向 ------ +# +# 这一段是 PEPlugins-FBXimport(C# 插件)里两个修复的 Python 移植, +# 原始判据见 PEPlugins-FBXimport\FbxImporterPlugin\TextureAlphaStripper.cs +# 与 FbxReader.cs 的 DetectForwardTurn / LooksLikeToe / LooksLikeFace。 +# 两边的常量、阈值、名字特征刻意保持一致,改一边要同步另一边。 + +ALPHA_KEEP = "keep" # 原样保留 alpha +ALPHA_AUTO = "auto" # 逐张贴图判一次(默认) +ALPHA_STRIP = "strip" # 一律去掉 alpha +ALPHA_MODES = (ALPHA_KEEP, ALPHA_AUTO, ALPHA_STRIP) + +ALPHA_NOALPHA_SUFFIX = "_noalpha" # 去 alpha 副本的后缀;改了要同步 docs/other-formats.md + +ALPHA_TRANSPARENT_BELOW = 8 # alpha 低于它算「全透明」 +ALPHA_OPAQUE_ABOVE = 250 # alpha 大于等于它算「实心」 +ALPHA_MOSTLY_EMPTY = 0.75 # 「几乎全是全透明」的下限 +ALPHA_ALMOST_NO_SOLID = 0.05 # 「几乎没有实心像素」的上限 +ALPHA_MAX_SAMPLES = 4000 # 每张贴图最多采样多少个 UV + +# 没有 UV 时更保守:要求「几乎全空」才敢去 +ALPHA_NOUV_EMPTY = 0.9 +ALPHA_NOUV_SOLID = 0.01 + + +def alpha_mode_of(value, legacy_remove_alpha=None): + """把界面/配置里拿到的值归一成三个 alpha 模式之一。 + + ``legacy_remove_alpha`` 供旧配置的布尔键 ``remove_alpha`` 兜底: + True -> "auto"(旧行为是「一律去 alpha」,正是要修的那个;迁移到自动判定 + 既保留「要去掉遮罩型 alpha」的意图,又不会再把真透明贴图一起削掉), + False -> "keep"。 + + ⚠ **两边都没给(``None``/``None``)时返回 "auto"**,这才是新默认。 + 所以调用方**不要**把 ``remove_alpha`` 的默认值写成 ``False`` —— 那会被 + 当成「用户显式要 keep」,把 auto 默认遮蔽掉(`convert()` / + ``--remove-alpha`` 都踩过这个坑,已改成 None)。 + """ + if isinstance(value, str) and value.lower() in ALPHA_MODES: + return value.lower() + if isinstance(value, bool): + return ALPHA_AUTO if value else ALPHA_KEEP + if legacy_remove_alpha is not None: + return ALPHA_AUTO if legacy_remove_alpha else ALPHA_KEEP + return ALPHA_AUTO + + +def looks_like_toe(name): + """脚尖骨的名字特征(刻意排除 ToeTwist / ToeNub 这类不是尖端的骨)。 + + 与 C# 的 LooksLikeToe 逐字一致:只排除 toetip / toe_nub / toeend / + toetwist 这几个写法,``Toe0Nub`` 这种驼峰串不会被排除 —— 保持与已验证 + 版本相同的行为,免得两边判据分叉。 + """ + if not name: + return False + low = name.lower() + if any(t in low for t in ("toetip", "toe_nub", "toeend", "toetwist")): + return False + return ("toe" in low or "つま先" in name or "爪先" in name or "ball" in low) + + +def looks_like_face(name): + """「一定长在正面」的网格名特征:脸 / 眼 / 瞳 / 眉 / 睫 / 嘴 / 鼻。""" + if not name: + return False + low = name.lower() + if any(t in low for t in ("face", "eye", "pupil", "iris", "brow", "lash", + "mouth", "nose", "lip")): + return True + return any(t in name for t in ("顔", "脸", "臉", "眼", "瞳", "眉", "睫", + "口", "鼻")) + + +def _detect_forward_by_toe(scene, bones): + """判据一:脚 → 脚尖的位移方向。 + + 解剖学上脚尖一定朝前,这个判据不会被「脸/眼材质叫什么」这类美术习惯影响。 + 返回 (需要转 180° 吗, 依据说明);判不出来返回 (None, 依据)。 + """ + sx = sz = 0.0 + n = 0 + hit = [] + for m in bones: + if not looks_like_toe(m.name or ""): + continue + p = m.parent + if p is None or p.cls != "LimbNode": + continue + tp = m_translation(m.world) + pp = m_translation(p.world) + dx = tp[0] - pp[0] + dz = tp[2] - pp[2] + if abs(dx) + abs(dz) < 1e-9: + continue + sx += dx + sz += dz + n += 1 + if len(hit) < 4: + hit.append(m.name) + if n == 0: + return None, "未找到脚尖骨骼" + mx = sx / n + mz = sz / n + names = "、".join(hit) + if abs(mx) > abs(mz): + # 朝 ±X(侧身 / 特殊摆位),180° 旋转修不了,只能交给用户 + return None, "脚尖骨骼(%s)朝向 X 轴,旋转 180° 无法修正" % names + need = mz < 0.0 + return need, "按脚尖骨骼(%s)判定正面朝 %s" % (names, "-Z" if need else "+Z") + + +def _detect_forward_by_face_meshes(scene): + """判据二(兜底):脸 / 眼 / 眉这些一定长在正面的网格,重心相对整体重心偏哪边。""" + face_z = 0.0 + face_n = 0 + all_z = 0.0 + all_n = 0 + left = right = None + for gid, mid in scene.geometry_model.items(): + g = scene.byid.get(gid) + model = scene.models.get(mid) + if g is None or model is None or all_n > 40000: + continue + is_face = looks_like_face(model.name or "") + verts = g.get("Vertices") + if verts is None: + continue + w = m_mul(model.world, scene._geom_matrix(scene.byid.get(mid))) + v = verts.props[0] + nverts = len(v) // 3 + step = max(1, nverts // 200) + for i in range(0, nverts, step): + p = m_point(w, v[i * 3:i * 3 + 3]) + all_z += p[2] + all_n += 1 + left = p[0] if left is None else min(left, p[0]) + right = p[0] if right is None else max(right, p[0]) + if is_face: + face_z += p[2] + face_n += 1 + if face_n < 8 or all_n < 8: + return None, "脸部网格过少" + dz = face_z / face_n - all_z / all_n + width = (right - left) if (left is not None and right is not None) else 0.0 + if width > 0.0 and abs(dz) < width * 0.02: + # 偏得太少就等于没偏,别硬判(正面对称的模型、裙摆很大的模型都可能这样) + return None, "脸部网格前后偏移不明显" + need = dz < 0.0 + return need, "按脸部网格的位置判定正面朝 %s" % ("-Z" if need else "+Z") + + +def detect_forward_turn(scene, bones=None): + """要不要额外转 180°(等价于 C# 的 Rot180Y),返回 (bool|None, 依据说明)。 + + 为什么必须判:FBX 里「角色朝哪边」完全由导出方决定,两种都很常见 —— + Unity / 游戏引擎导出的角色多朝 +Z,一部分 DCC 预设导出的朝 -Z。 + MMD 的正面固定是 -Z,而本转换的 Z 取反本来就会把 +Z 翻成 -Z, + **也就是说朝 +Z 的文件只需要 Z 取反、不能再转 180°**;朝 -Z 的才要补一次。 + + 判定在「未 FlipZ 的 FBX 原始朝向坐标系」里做(也就是本函数里 scene 给出来的 + 原始坐标),结论很直接:正面朝 +Z → 不用转;朝 -Z → 要转。 + + 判据按可靠性排序,取第一个能用的;都拿不到就返回 None(交给用户的设置)。 + """ + if bones is None: + bones = [m for m in scene.models.values() if m.cls == "LimbNode"] + need, why = _detect_forward_by_toe(scene, bones) + if need is not None: + return need, why + need2, why2 = _detect_forward_by_face_meshes(scene) + return need2, why + ";" + why2 + + +# ------------------------------------------------------------------ math ---- + +def m_ident(): + return [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0] + + +def m_mul(a, b): + o = [0.0] * 16 + for i in range(4): + ai = i * 4 + for j in range(4): + o[ai + j] = (a[ai] * b[j] + a[ai + 1] * b[4 + j] + + a[ai + 2] * b[8 + j] + a[ai + 3] * b[12 + j]) + return o + + +def m_point(m, p): + x, y, z = p + return (m[0] * x + m[1] * y + m[2] * z + m[3], + m[4] * x + m[5] * y + m[6] * z + m[7], + m[8] * x + m[9] * y + m[10] * z + m[11]) + + +def m_dir(m, p): + x, y, z = p + return (m[0] * x + m[1] * y + m[2] * z, + m[4] * x + m[5] * y + m[6] * z, + m[8] * x + m[9] * y + m[10] * z) + + +def m_translation(m): + return (m[3], m[7], m[11]) + + +# FBX 的 RotationOrder(EFbxRotationOrder):字母是「先转哪个轴」,矩阵按相反顺序相乘。 +# 0 XYZ(默认)→ Rz·Ry·Rx;6 是 SphericXYZ,按 XYZ 处理。 +_ROT_ORDER = {0: "zyx", 1: "yzx", 2: "xzy", 3: "zxy", 4: "yxz", 5: "xyz", 6: "zyx"} + + +def m_trs(t, rot_deg, s, order=0): + rx, ry, rz = (math.radians(v) for v in rot_deg) + cx, sx = math.cos(rx), math.sin(rx) + cy, sy = math.cos(ry), math.sin(ry) + cz, sz = math.cos(rz), math.sin(rz) + mats = {"x": [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0, 0, 0, 0, 1], + "y": [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0, 0, 0, 0, 1], + "z": [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]} + a, b, c = _ROT_ORDER.get(order, "zyx") + r = m_mul(mats[a], m_mul(mats[b], mats[c])) + for i in range(3): + for j in range(3): + r[i * 4 + j] *= s[j] + r[3], r[7], r[11] = t + return r + + +def parse_matrix_str(s): + vals = [float(x) for x in s.strip().strip("[]").split(",")] + return vals if len(vals) == 16 else m_ident() + + +def m_rot(rot_deg, order=0): + """欧拉角(度)→ 纯旋转矩阵,与 m_trs 同一套约定。默认 XYZ 顺序(Rz·Ry·Rx)。 + + 注意默认不要改成 Rx·Ry·Rz:实测同一份 FBX 下两种顺序的贴合度差距极大 + (Rz·Ry·Rx 中位 5.67cm vs Rx·Ry·Rz 中位 18.09cm)。节点自己写了 RotationOrder 时 + 才按它来(只作用于 Lcl Rotation;Pre / PostRotation 按 FBX SDK 的规定总是 XYZ)。 + """ + return m_trs([0.0, 0.0, 0.0], rot_deg, [1.0, 1.0, 1.0], order) + + +def m_rot_inv(rot_deg): + """纯旋转矩阵的逆(3×3 转置)。FBX 里的 Rpost⁻¹ 需要它。""" + r = m_rot(rot_deg) + o = list(r) + for i in range(3): + for j in range(3): + o[j * 4 + i] = r[i * 4 + j] + return o + + +def m_translate(v): + m = m_ident() + m[3], m[7], m[11] = v + return m + + +def m_scale(s): + m = m_ident() + m[0], m[5], m[10] = s + return m + + +# ------------------------------------------------------------- fbx scene ---- + +class Model: + """A FBX Model node (mesh, bone, root ...).""" + + __slots__ = ("id", "name", "cls", "local", "world", "parent", "children") + + def __init__(self, nid, name, cls): + self.id = nid + self.name = name + self.cls = cls + self.local = m_ident() + self.world = m_ident() + self.parent = None + self.children = [] + + +def _clean_name(s): + return s.split("\x00")[0] + + +def _ns_strip(s): + """剥掉 FBX 的 `Class::name` 命名空间前缀。 + + Autodesk 自家的导出器一律写 `"SubDeformer::Smile"` / `"Shape::Smile"`, + 而 FBX SDK 的 GetName() 会自动剥前缀、Blender 也会剥;本工程的解析器是 + 直接读字段原文,所以这里补一次,免得表情名/材质名带一截 `Shape::`。 + """ + return s.split("::")[-1] if "::" in s else s + + +class Scene: + def __init__(self, path): + self.path = path + self.ver, top = fbx.load(path) + root = fbx.FbxNode("root", [], top) + objs = root.get("Objects") + self.objects = objs.children + self.byid = {} + for c in self.objects: + if c.props and isinstance(c.props[0], int): + self.byid[c.props[0]] = c + + # connections: ['OO', child_id, parent_id] + self.parents = {} + # **按文件顺序**保留一份 (child, parent) 列表。 + # + # 这一步不是可有可无:FBX 的 LayerElementMaterial 里的材质索引,对应的 + # 是 FBX SDK `FbxNode::GetMaterial(i)` 的顺序,也就是**该节点在 + # Connections 段里被连接的先后顺序**。 + # + # 以前 _resolve_links() 直接遍历 self.parents(按 child 首次出现的顺序), + # 当同一批材质对多个网格的连接顺序与「材质节点在 Objects 段里出现的顺序」 + # 不一致时就会串位。实测 NPC_Avatar_Lady_Bow_Anastasya:Cloth01 在文件里 + # 的顺序是 Hair(490) Body(491) **Dress(492)** Body01(493) Crystal(494) + # Crystal01(495) Crystal02(496),而父节点遍历给出的却是 + # Hair Body Body01 Crystal Crystal01 **Dress** Crystal02 —— Dress 被挪到 + # 了第 6 位,于是 7 个槽位里有 5 个配错贴图(一致性只有 19%), + # 表现就是「有些部分的贴图不对 / 像被换了 UV」。 + self.conn_list = [] + self.conn_prop = {} # (child, parent) -> 属性名("OP" 连接,比如贴图接在 DiffuseColor 上) + for c in root.get("Connections").children: + if len(c.props) >= 3: + self.parents.setdefault(c.props[1], []).append(c.props[2]) + self.conn_list.append((c.props[1], c.props[2])) + if len(c.props) >= 4 and c.props[0] == "OP": + self.conn_prop[(c.props[1], c.props[2])] = str(c.props[3]) + + self._build_models() + self._resolve_links() + self._build_textures() + self._build_morphs() + + # -- helpers + def _props70(self, node): + out = {} + p70 = node.get("Properties70") + if p70: + for pr in p70.children: + if len(pr.props) >= 5: + out[pr.props[0]] = pr.props[4:] + return out + + def _local_matrix(self, node): + """节点局部矩阵,按 FBX SDK 的 EvaluateLocalTransform 完整合成: + + T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹ + + 这里最容易漏掉的是 **PreRotation**,而且漏了不会立刻露馅:节点自身的 + 平移在这个式子最左边,不受自己 PreRotation 影响,所以单看一根骨骼的 + 位置是正常的;但它的**所有后代**都活在少了一个 Rpre 的坐标系里,整条 + 骨链会歪掉/翻转。实测 "Crimson Rumor" 这个包 385 个节点里有 185 个带 + 非零 PreRotation(不少正好是 180°),漏掉它会让 83% 的骨骼偏位(最大 + 106cm)——衣服/发饰的骨链会从"垂在身侧"变成"横着翘到体外",看起来就像 + 骨骼被倒过来了。 + 判据(顶点到其主骨骼线段的距离,越小越贴合): + 只 T·R·S:中位 11.99cm / 平均 20.92cm + 带 PreRotation:中位 5.67cm / 平均 6.12cm + """ + d = self._props70(node) + + def v3(key): + v = d.get(key) + return [float(x) for x in v[:3]] if v else None + + t = v3("Lcl Translation") or [0.0, 0.0, 0.0] + r = v3("Lcl Rotation") or [0.0, 0.0, 0.0] + s = v3("Lcl Scaling") or [1.0, 1.0, 1.0] + rp = v3("RotationPivot") + pre = v3("PreRotation") + post = v3("PostRotation") + roff = v3("RotationOffset") + sp = v3("ScalingPivot") + soff = v3("ScalingOffset") + ro = d.get("RotationOrder") + order = int(ro[0]) if ro else 0 + + def neg(v): + return [-v[0], -v[1], -v[2]] + + # Rp / Sp 是**枢轴点**(平移),不是旋转:以前写成 m_rot(rp),枢轴非零的节点会被转歪 + m = m_translate(t) + if roff: + m = m_mul(m, m_translate(roff)) + if rp: + m = m_mul(m, m_translate(rp)) + if pre: + m = m_mul(m, m_rot(pre)) + m = m_mul(m, m_rot(r, order)) + if post: + m = m_mul(m, m_rot_inv(post)) + if rp: + m = m_mul(m, m_translate(neg(rp))) + if soff: + m = m_mul(m, m_translate(soff)) + if sp: + m = m_mul(m, m_translate(sp)) + m = m_mul(m, m_scale(s)) + if sp: + m = m_mul(m, m_translate(neg(sp))) + return m + + def _build_models(self): + self.models = {} + for c in self.objects: + if c.name != "Model": + continue + nid = c.props[0] + m = Model(nid, _clean_name(c.props[1]), c.props[2]) + m.local = self._local_matrix(c) + self.models[nid] = m + for nid, m in self.models.items(): + for pid in self.parents.get(nid, []): + p = self.models.get(pid) + if p is not None and m.parent is None: + m.parent = p + p.children.append(m) + for m in self.models.values(): + if m.parent is None: + self._calc_world(m, m_ident()) + + def _calc_world(self, m, parent_world): + m.world = m_mul(parent_world, m.local) + for c in m.children: + self._calc_world(c, m.world) + + def _resolve_links(self): + """child_id -> parent_id lists turned into typed dictionaries. + + **必须按 Connections 的文件顺序遍历**(self.conn_list),不能用 + self.parents —— 后者是按 child 分组、以 child 首次出现的顺序展开的, + 会把「材质 → 网格」的连接顺序打乱。原因见 Scene.__init__ 里的长注释: + LayerElementMaterial 的索引就是按连接的文件顺序来指的。 + """ + self.geometry_model = {} + self.model_material = {} # model_id -> first material id (legacy) + self.model_materials = {} # model_id -> [material id, ...] (ordered) + self.geometry_materials = {} # geometry_id -> [material id, ...] + self.geometry_skin = {} + self.cluster_skin = {} + self.cluster_bone = {} + self.texture_materials = {} # material_id -> [texture id, ...] (ordered) + self.texture_video = {} # texture_id -> video_id (embedded name) + self.texture_slot = {} # (material_id, texture_id) -> 材质属性名(DiffuseColor / NormalMap …) + + for child, pid in self.conn_list: + cn = self.byid.get(child) + if cn is None: + continue + pn = self.byid.get(pid) + if pn is None: + continue + if cn.name == "Geometry" and pn.name == "Model": + self.geometry_model[child] = pid + elif cn.name == "Material" and pn.name == "Model": + self.model_material[pid] = child + self.model_materials.setdefault(pid, []).append(child) + elif cn.name == "Material" and pn.name == "Geometry": + self.geometry_materials.setdefault(pid, []).append(child) + elif cn.name == "Deformer" and pn.name == "Geometry": + if len(cn.props) > 2 and cn.props[2] == "Skin": + self.geometry_skin[pid] = child + elif cn.name == "Deformer" and pn.name == "Deformer": + if len(cn.props) > 2 and cn.props[2] == "Cluster": + self.cluster_skin[child] = pid + elif cn.name == "Deformer" and pn.name == "Model": + # FBX SDK / Blender exporter: C:"OO", , + if len(cn.props) > 2 and cn.props[2] == "Cluster": + self.cluster_bone[child] = pid + elif cn.name == "Model" and pn.name == "Deformer": + # a few exporters reverse it: C:"OO", , + if len(pn.props) > 2 and pn.props[2] == "Cluster": + self.cluster_bone[pid] = child + elif cn.name == "Texture" and pn.name == "Material": + self.texture_materials.setdefault(pid, []).append(child) + self.texture_slot[(pid, child)] = self.conn_prop.get((child, pid), "") + elif cn.name == "Material" and pn.name == "Texture": + self.texture_materials.setdefault(cn.props[0], []).append(pid) + elif cn.name == "Texture" and pn.name == "Video": + self.texture_video[child] = pid + elif cn.name == "Video" and pn.name == "Texture": + self.texture_video[pid] = child + + +# ----------------------------------------------------------------- pmx ------ + + def _geom_matrix(self, node): + """Geometric transform of a Model node (applied to geometry, not children).""" + d = self._props70(node) + t = d.get("GeometricTranslation", [0.0, 0.0, 0.0]) + r = d.get("GeometricRotation", [0.0, 0.0, 0.0]) + s = d.get("GeometricScaling", [1.0, 1.0, 1.0]) + return m_trs([float(x) for x in t[:3]], + [float(x) for x in r[:3]], + [float(x) for x in s[:3]]) + + def _build_textures(self): + """Collect Texture nodes and their file names. + + FBX stores the image either as an embedded Video (rare here) or, as in + game exports, as an *external* file referenced by RelativeFilename / + FileName on the Texture (or its linked Video) node. We only need the + basename - the actual file is copied at convert() time if it exists. + """ + self.textures = {} # texture_id -> {"name": basename, "rel": path} + + def file_of(node): + # 文件名可能在 Properties70 里,也可能是 Texture / Video 节点的直接子节点 + # (Maya / Unity 导出的 FBX 7.x 是后者:FileName: "D:/…/body_01.tga") + d = self._props70(node) + for key in ("RelativeFilename", "FileName", "Filename"): + v = d.get(key) + if v: + return v[0] if isinstance(v, list) else v + for key in ("RelativeFilename", "FileName", "Filename"): + for ch in node.find(key): + if ch.props and isinstance(ch.props[0], str) and ch.props[0].strip("\x00"): + return ch.props[0] + return None + + for c in self.objects: + if c.name != "Texture": + continue + tid = c.props[0] + rel = file_of(c) + if not rel: + vid = self.texture_video.get(tid) + vn = self.byid.get(vid) if vid is not None else None + if vn is not None: + rel = file_of(vn) + if rel: + rel = rel.split("\x00")[0].replace("\\", "/") + name = os.path.basename(rel) if rel else _clean_name(c.props[1]) + name = name.split("\x00")[0] + self.textures[tid] = {"name": name, "rel": rel} + + def _build_morphs(self): + """Collect FBX blend shapes into morph descriptors. + + FBX chain: Geometry -> BlendShape -> BlendShapeChannel -> Shape. + Each Shape carries ``Indexes`` (the affected control points) and + ``Vertices`` (relative position *deltas*, 3 floats per control point, + in the same order as Indexes). We verified against this file that the + stored values are deltas (not absolute positions): the base eyebrow + vertex sits at y~1.5 while a morph target lists y~-0.004, so subtracting + nothing yields the intended small displacement. + + A morph is keyed by the owning geometry id so convert() can apply the + same mesh transform used for the base vertices. + """ + self.morphs = [] # [{name, geo_id, indexes, deltas}] + bs_geo = {} # blendshape_id -> geometry_id + channels = {} # blendshape_id -> [channel_id] + chan_shape = {} # channel_id -> shape_node_id + + for child, plist in self.parents.items(): + cn = self.byid.get(child) + if cn is None: + continue + cls = (cn.props[2] if (cn.name in ("Deformer", "Geometry") + and len(cn.props) > 2) else "") + if cn.name == "Deformer" and cls == "BlendShape": + for pid in plist: + if pid in self.geometry_model: # only real mesh geometries + bs_geo[child] = pid + elif cn.name == "Deformer" and cls == "BlendShapeChannel": + for pid in plist: + pn = self.byid.get(pid) + if pn is not None and len(pn.props) > 2 \ + and pn.props[2] == "BlendShape": + channels.setdefault(pid, []).append(child) + elif cn.name == "Geometry" and cls == "Shape": + for pid in plist: + pn = self.byid.get(pid) + if pn is not None and len(pn.props) > 2 \ + and pn.props[2] == "BlendShapeChannel": + chan_shape[pid] = child # channel_id -> shape_id + + for bsid, gid in bs_geo.items(): + for chid in channels.get(bsid, []): + shid = chan_shape.get(chid) + if shid is None: + continue + sh = self.byid.get(shid) + if sh is None: + continue + idxn = sh.get("Indexes") + vn = sh.get("Vertices") + if idxn is None or vn is None: + continue + indexes = idxn.props[0] + deltas = vn.props[0] + if not indexes or len(deltas) < 3 * len(indexes): + continue + name = _ns_strip(_clean_name(sh.props[1])) \ + or _ns_strip(_clean_name(self.byid[chid].props[1])) + self.morphs.append({"name": name, "geo_id": gid, + "indexes": indexes, "deltas": deltas}) + + +class PmxWriter: + #: 文本编码:0 = UTF-16LE(MMD 只认这一种),1 = UTF-8 + ENC = 0 + + def __init__(self, indices=(2, 1, 2, 2, 1, 1)): + self.buf = bytearray() + self.vi, self.ti, self.mi, self.bi, self.moi, self.ri = indices + + # -- primitives + def i32(self, v): + self.buf += struct.pack(" actual control point index (last index is negative).""" + v = pvi[i] + return ~v if v < 0 else v + + +def sample_uv(node, pvi): + """Return a per-corner list of (u, v) indexed by polygon-vertex position.""" + if node is None or pvi is None: + return None + uv = node.get("UV") + if uv is None: + return None + table = uv.props[0] + idn = node.get("UVIndex") + mir = node.get("MappingInformationType") + rir = node.get("ReferenceInformationType") + mir_s = mir.props[0] if mir is not None else "" + rir_s = rir.props[0] if rir is not None else "" + n = len(pvi) + if mir_s == "ByPolygonVertex" and rir_s == "IndexToDirect" and idn is not None: + ids = idn.props[0] + return [(table[i * 2], table[i * 2 + 1]) for i in ids] + if mir_s == "ByPolygonVertex" and (rir_s == "Direct" or idn is None): + return [(table[i * 2], table[i * 2 + 1]) for i in range(n)] + # ByControlPoint / ByVertice: the per-corner UV comes from the control point of that corner + if idn is not None and rir_s == "IndexToDirect": + ids = idn.props[0] + return [(table[ids[_cp_index(pvi, i)] * 2], table[ids[_cp_index(pvi, i)] * 2 + 1]) + for i in range(n)] + return [(table[_cp_index(pvi, i) * 2], table[_cp_index(pvi, i) * 2 + 1]) + for i in range(n)] + + +def sample_normals(node, pvi): + """Return a per-corner list of (nx, ny, nz) indexed by polygon-vertex position.""" + if node is None or pvi is None: + return None + nrm = node.get("Normals") + if nrm is None: + return None + table = nrm.props[0] + idn = node.get("NormalsIndex") + mir = node.get("MappingInformationType") + rir = node.get("ReferenceInformationType") + mir_s = mir.props[0] if mir is not None else "" + rir_s = rir.props[0] if rir is not None else "" + n = len(pvi) + if mir_s == "ByPolygonVertex" and idn is not None: + ids = idn.props[0] + return [(table[i * 3], table[i * 3 + 1], table[i * 3 + 2]) for i in ids] + if mir_s == "ByPolygonVertex" and rir_s == "Direct": + return [(table[i * 3], table[i * 3 + 1], table[i * 3 + 2]) for i in range(n)] + if idn is not None and rir_s == "IndexToDirect": + ids = idn.props[0] + return [(table[ids[_cp_index(pvi, i)] * 3], table[ids[_cp_index(pvi, i)] * 3 + 1], + table[ids[_cp_index(pvi, i)] * 3 + 2]) for i in range(n)] + return [(table[_cp_index(pvi, i) * 3], table[_cp_index(pvi, i) * 3 + 1], + table[_cp_index(pvi, i) * 3 + 2]) for i in range(n)] + + +def triangulate(pvi): + """FBX polygon list -> list of ((control_point, corner_position), x3). + + The second element matters: LayerElementUV / LayerElementNormal use + ByPolygonVertex mapping, so their lookup index is the position inside the + PolygonVertexIndex array, not the control-point index. + """ + tris = [] + cur = [] + for pos, v in enumerate(pvi): + idx = ~v if v < 0 else v + cur.append((idx, pos)) + if v < 0: + for i in range(1, len(cur) - 1): + tris.append((cur[0], cur[i], cur[i + 1])) + cur = [] + return tris + + +def polygon_starts(pvi): + """Index into the pvi array where each polygon begins (for per-poly data).""" + starts = [] + start = 0 + for i, v in enumerate(pvi): + if v < 0: + starts.append(start) + start = i + 1 + return starts + + +def _mesh_materials(g, model, scene): + """Ordered list of material node ids used by this geometry/model. + + FBX stores the material assignment either as Connections from the material + to the model (or to the geometry), and optionally refines it per-polygon via + a LayerElementMaterial. The per-polygon indices reference this ordered list. + """ + mats = list(scene.model_materials.get(model.id, [])) + if not mats: + mats = list(scene.geometry_materials.get(g.props[0], [])) + if not mats: + m = scene.model_material.get(model.id) + if m is not None: + mats = [m] + if not mats: + mats = [None] + return mats + + +def _poly_material_index(g, pvi, nmats): + """Per-triangle material index, or None if there is no LayerElementMaterial.""" + le = g.get("LayerElementMaterial") + if le is None: + return None + midx = le.get("Materials") + if midx is None: + return None + ids = midx.props[0] + mir = le.get("MappingInformationType") + rir = le.get("ReferenceInformationType") + mir_s = mir.props[0] if mir is not None else "" + rir_s = rir.props[0] if rir is not None else "" + poly_lens = [] + cur = 0 + for v in pvi: + cur += 1 + if v < 0: + poly_lens.append(cur) + cur = 0 + tri_mat = [] + if mir_s == "ByPolygon": + for pi, pl in enumerate(poly_lens): + m = ids[pi] if pi < len(ids) else 0 + for _ in range(max(0, pl - 2)): + tri_mat.append(m) + elif mir_s == "ByPolygonVertex": + corner = 0 + for pl in poly_lens: + m = ids[corner] if corner < len(ids) else 0 + for _ in range(max(0, pl - 2)): + tri_mat.append(m) + corner += pl + else: + return None + nmats = max(1, nmats) + return [max(0, min(nmats - 1, m)) for m in tri_mat] + + +def _find_file(root, basename, limit=60000): + """Bounded recursive search for a file by basename under root (returns path). + + 用 ``os.path.join(d, e.name)`` 而不是 ``e.path``:当 d 是超长路径时, + longpath 会给传给 scandir 的路径加 ``\\\\?\\`` 前缀,而 DirEntry.path + 会把这个前缀带出来,泄漏到调用方。自己用 name 拼就不会。 + """ + count = 0 + stack = [root] + while stack: + d = stack.pop() + try: + entries = os.scandir(d) + except OSError: + continue + dirs = [] + for e in entries: + count += 1 + if count > limit: + return None + if e.is_dir(): + dirs.append(os.path.join(d, e.name)) + elif e.name == basename: + return os.path.join(d, e.name) + stack.extend(dirs) + return None + + +# ----------------------------------------------------------------- alpha ---- +# Remove the alpha channel from a texture image. Returns one of: +# "stripped" - had alpha, now written as opaque RGB +# "no_alpha" - no alpha (copied verbatim) +# False - decode/encode failed; the caller copies the file as-is +# Pillow is preferred; a tiny built-in PNG/TGA reader is the fallback so the +# feature works even when Pillow is not installed (the GUI runs on plain Python). + +def _decode_png_rgba(src): + """纯标准库 PNG 解码 → (width, height, RGBA bytes),失败返回 None。 + + 只处理 8bit、非隔行的 0/2/3/4/6 型(MMD 用得到的贴图都在这个范围内)。 + alpha 统计要走这里,是因为 GUI 可能跑在没有 Pillow 的解释器上。 + """ + import zlib + try: + with open(src, "rb") as f: + data = f.read() + except OSError: + return None + if data[:8] != b"\x89PNG\r\n\x1a\n": + return None + pos = 8 + width = height = bit_depth = color_type = interlace = None + idat = bytearray() + plte = None + trns = None + while pos + 8 <= len(data): + ln = struct.unpack(">I", data[pos:pos + 4])[0] + typ = data[pos + 4:pos + 8] + cdata = data[pos + 8:pos + 8 + ln] + if typ == b"IHDR" and len(cdata) >= 13: + width, height, bit_depth, color_type, _c, _f, interlace = \ + struct.unpack(">IIBBBBB", cdata[:13]) + elif typ == b"IDAT": + idat += cdata + elif typ == b"PLTE": + plte = cdata + elif typ == b"tRNS": + trns = cdata + pos += 12 + ln + if not width or not height or interlace or bit_depth != 8 \ + or color_type not in (0, 2, 3, 4, 6): + return None + try: + raw = zlib.decompress(bytes(idat)) + except Exception: + return None + ch_in = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[color_type] + stride = width * ch_in + if len(raw) < height * (stride + 1): + return None + prev = bytearray(stride) + rows = [] + p = 0 + for _ in range(height): + ftype = raw[p] + p += 1 + line = bytearray(raw[p:p + stride]) + p += stride + _png_unfilter(ftype, line, prev, ch_in) + rows.append(line) + prev = line + out = bytearray(width * height * 4) + for y in range(height): + line = rows[y] + base = y * width * 4 + if color_type == 6: + out[base:base + width * 4] = line + elif color_type == 2: + for x in range(width): + out[base + x * 4:base + x * 4 + 3] = line[x * 3:x * 3 + 3] + out[base + x * 4 + 3] = 255 + elif color_type == 4: + for x in range(width): + g = line[x * 2] + out[base + x * 4] = g + out[base + x * 4 + 1] = g + out[base + x * 4 + 2] = g + out[base + x * 4 + 3] = line[x * 2 + 1] + elif color_type == 0: + for x in range(width): + g = line[x] + out[base + x * 4] = g + out[base + x * 4 + 1] = g + out[base + x * 4 + 2] = g + out[base + x * 4 + 3] = 255 + else: # 3 = palette + if plte is None: + return None + alpha_by = {} + if trns: + for i, a in enumerate(trns): + alpha_by[i] = a + for x in range(width): + pi = line[x] + o = pi * 3 + out[base + x * 4] = plte[o] if o + 2 < len(plte) else 0 + out[base + x * 4 + 1] = plte[o + 1] if o + 2 < len(plte) else 0 + out[base + x * 4 + 2] = plte[o + 2] if o + 2 < len(plte) else 0 + out[base + x * 4 + 3] = alpha_by.get(pi, 255) + return width, height, bytes(out) + + +def _load_alpha(src): + """→ ((宽, 高, alpha), png):alpha 是每像素 1 字节的 alpha 通道(转成 RGBA 后的那个通道; + 没有 alpha 通道的图为 None = 全不透明),拿不到位图时整个三元组为 None; + png 是用同一次解码算好的 vrmio.png_alpha_stats 结果(只有 PNG 能这样算),算不了为 NotImplemented。 + + 只取 alpha 通道:4K 贴图的 RGBA 有 64 MB,alpha 只有 16 MB(几张图会同时解,见 _copy_textures)。 + """ + try: + from PIL import Image + except ImportError: + got = _decode_png_rgba(src) + return (got and (got[0], got[1], bytes(got[2][3::4]))), NotImplemented + try: + im = Image.open(src) + if im.mode in ("RGBA", "LA", "PA"): + alpha = im.getchannel("A").tobytes() + elif "transparency" in im.info: + alpha = im.convert("RGBA").getchannel("A").tobytes() + else: + alpha = None # 转成 RGBA 后 alpha 全是 255 + got = (im.size[0], im.size[1], alpha) + except Exception: # noqa: BLE001 + return None, NotImplemented + png = NotImplemented + if im.format == "PNG": + try: + png = vrmio.png_alpha_stats_image(im) + except Exception: # noqa: BLE001 交给 PMX → VRM 自己再解 + pass + return got, png + + +def _has_any_transparency(w, h, alpha): + """整张图有没有非 255 的 alpha(count 在 C 里跑,不逐像素循环)。""" + return alpha is not None and alpha.count(255) != len(alpha) + + +def _alpha_stats_whole(w, h, alpha): + """整图 alpha 统计(4x4 网格降采样)→ (全透占比, 实心占比)。 + + 每行起点错开一点:固定步长遇到周期图案会一直踩到同一类像素,把统计系统性 + 带偏(实测「周期 10、90% 全透」的合成图被算成 80%)。C# 那边没这个错位, + 但只影响取样点不影响判据,故选得更稳的一版。 + """ + ws = max(1, w // 64) + hs = max(1, h // 64) + n = t = o = 0 + row = 0 + for y in range(0, h, hs): + base = y * w + x0 = (row * 7) % ws if ws > 1 else 0 + for x in range(x0, w, ws): + a = alpha[base + x] + n += 1 + if a < ALPHA_TRANSPARENT_BELOW: + t += 1 + elif a >= ALPHA_OPAQUE_ABOVE: + o += 1 + row += 1 + if n == 0: + return None + return t / n, o / n + + +def _alpha_stats_uv(w, h, alpha, uvs): + """按「材质实际用到的 UV 角点」定点采样 → (全透占比, 实心占比, 采样数)。 + + uvs 里已经是 MMD 口径 (u, 1-v)(v=0 在最上一行),寻址按 MMD 的 wrap 来。 + """ + if not uvs: + return None + step = max(1, len(uvs) // ALPHA_MAX_SAMPLES) + t = o = n = 0 + for i in range(0, len(uvs), step): + u, v = uvs[i] + x = int(math.floor(u * w)) % w if w else 0 + y = int(math.floor(v * h)) % h if h else 0 + a = alpha[y * w + x] + n += 1 + if a < ALPHA_TRANSPARENT_BELOW: + t += 1 + elif a >= ALPHA_OPAQUE_ABOVE: + o += 1 + if n == 0: + return None + return t / n, o / n, n + + +def decide_alpha(src, uvs=None, got=None): + """判定一张贴图的 alpha 是不是「真透明」。返回 (verdict, detail)。 + + 判据(两条统计**都要**满足才算「不是透明度」): + · 用到的 UV 区域:全透占比 >= 0.75 且实心占比 <= 0.05; + · 整张图:同样两条。 + 直觉:真透明贴图一定有「实心的衣服本体」和「镂空的花边」两部分 + (实测 Anastasya 丝袜 71% / 28%)。**整块区域几乎全透、且完全没有实心** + 只能是「这里的 alpha 根本不是管透明的」(被当成自发光 / 高光遮罩写进去了)。 + + 为什么两边互相印证:只用「用到的 UV」时,网格没有 UV 层(UV 全是 0)就会 + 退化成「只看一个像素」,样本量 1 也敢下结论;只用整图时,图集式贴图的 + 大片 padding 又会把统计带偏。要求两边都成立就把这两种情况挡在门外 —— + 代价是有时会少去一张(偏保守),而这正是要的方向:判不准就保留, + 用户还能手动选「全部去除」。 + """ + got = got or _load_alpha(src)[0] # 调用方已经解过就不再解一遍 + if got is None: + return ALPHA_KEEP, "cannot sample alpha" + w, h, alpha = got + if not _has_any_transparency(w, h, alpha): + return ALPHA_KEEP, "no transparency at all" + whole = _alpha_stats_whole(w, h, alpha) + used = _alpha_stats_uv(w, h, alpha, uvs) if uvs else None + if used is None or whole is None: + if whole is None: + return ALPHA_KEEP, "cannot sample alpha" + # 没有 UV 时更保守:要求「几乎全空」才敢去 + verdict = (ALPHA_STRIP + if (whole[0] >= ALPHA_NOUV_EMPTY and whole[1] <= ALPHA_NOUV_SOLID) + else ALPHA_KEEP) + detail = ("whole image transparent=%.1f%% opaque=%.1f%%" + % (whole[0] * 100, whole[1] * 100)) + return verdict, detail + detail = ("uv samples=%d transparent=%.1f%% opaque=%.1f%% | whole " + "transparent=%.1f%% opaque=%.1f%%" + % (used[2], used[0] * 100, used[1] * 100, + whole[0] * 100, whole[1] * 100)) + used_junk = (used[0] >= ALPHA_MOSTLY_EMPTY and used[1] <= ALPHA_ALMOST_NO_SOLID) + whole_junk = (whole[0] >= ALPHA_MOSTLY_EMPTY and whole[1] <= ALPHA_ALMOST_NO_SOLID) + return (ALPHA_STRIP if (used_junk and whole_junk) else ALPHA_KEEP), detail + + +def _opaque_copy_name(basename): + stem, ext = os.path.splitext(basename) + return stem + ALPHA_NOALPHA_SUFFIX + ext + + +def _strip_alpha(src, dst): + """Try Pillow first; fall back to the pure-stdlib reader.""" + try: + from PIL import Image + im = Image.open(src) + has_alpha = (im.mode in ("RGBA", "LA", "PA") + or (im.mode == "P" and "transparency" in im.info)) + if has_alpha: + im.convert("RGB").save(dst) + return "stripped" + shutil.copyfile(src, dst) + return "no_alpha" + except ImportError: + pass + except Exception: + return False + return _strip_alpha_pure(src, dst) + + +def _strip_alpha_pure(src, dst): + """Pure-stdlib alpha strip for PNG and TGA (the formats MMD actually uses).""" + try: + with open(src, "rb") as f: + head = f.read(18) + except OSError: + return False + if head[:8] == b"\x89PNG\r\n\x1a\n": + return _strip_png_alpha(src, dst) + # TGA has no magic; recognise it by a plausible header. + if len(head) >= 18 and head[2] in (1, 2, 3, 9, 10, 11) \ + and head[16] in (16, 24, 32): + return _strip_tga_alpha(src, dst) + # Unknown / unsupported format: keep the original, just relocate it. + try: + shutil.copyfile(src, dst) + return "no_alpha" + except OSError: + return False + + +def _png_chunk(typ, data): + import zlib + return (struct.pack(">I", len(data)) + typ + data + + struct.pack(">I", zlib.crc32(typ + data) & 0xffffffff)) + + +def _paeth(a, b, c): + p = a + b - c + pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) + if pa <= pb and pa <= pc: + return a + if pb <= pc: + return b + return c + + +def _png_unfilter(ftype, line, prev, bpp): + """Undo a PNG scanline filter in place (assumes 8-bit).""" + if ftype == 0: + return + n = len(line) + for i in range(n): + a = line[i - bpp] if i >= bpp else 0 + b = prev[i] + c = prev[i - bpp] if i >= bpp else 0 + if ftype == 1: + line[i] = (line[i] + a) & 0xff + elif ftype == 2: + line[i] = (line[i] + b) & 0xff + elif ftype == 3: + line[i] = (line[i] + ((a + b) >> 1)) & 0xff + elif ftype == 4: + line[i] = (line[i] + _paeth(a, b, c)) & 0xff + + +def _strip_png_alpha(src, dst): + import zlib + try: + with open(src, "rb") as f: + data = f.read() + except OSError: + return False + if data[:8] != b"\x89PNG\r\n\x1a\n": + return False + pos = 8 + width = height = bit_depth = color_type = interlace = None + idat = bytearray() + plte = None + other = [] + while pos + 8 <= len(data): + ln = struct.unpack(">I", data[pos:pos + 4])[0] + typ = data[pos + 4:pos + 8] + cdata = data[pos + 8:pos + 8 + ln] + if typ == b"IHDR" and len(cdata) >= 13: + width, height, bit_depth, color_type, _comp, _filt, interlace = \ + struct.unpack(">IIBBBBB", cdata[:13]) + elif typ == b"IDAT": + idat += cdata + elif typ == b"PLTE": + plte = cdata + elif typ == b"tRNS": + pass # drop transparency chunk + elif typ == b"IEND": + pass # we append our own IEND last + else: + other.append((typ, cdata)) + pos += 12 + ln + if width is None or interlace or bit_depth != 8 \ + or color_type not in (0, 2, 3, 4, 6): + try: + shutil.copyfile(src, dst) + except OSError: + return False + return "no_alpha" + raw = zlib.decompress(bytes(idat)) + ch_in = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[color_type] + stride = width * ch_in + prev = bytearray(stride) + out = bytearray() + p = 0 + for _ in range(height): + ftype = raw[p] + p += 1 + line = bytearray(raw[p:p + stride]) + p += stride + _png_unfilter(ftype, line, prev, ch_in) + out += line + prev = line + if color_type == 6: + new_ct, ch_out = 2, 3 + new = bytearray() + for y in range(height): + base = y * stride + for x in range(width): + i = base + x * 4 + new += bytes((out[i], out[i + 1], out[i + 2])) + elif color_type == 4: + new_ct, ch_out = 0, 1 + new = bytearray() + for y in range(height): + base = y * stride + for x in range(width): + new += bytes((out[base + x * 2],)) + elif color_type == 3: + if plte is None: + try: + shutil.copyfile(src, dst) + except OSError: + return False + return "no_alpha" + new_ct, ch_out = 2, 3 + pal = {i: (plte[i * 3], plte[i * 3 + 1], plte[i * 3 + 2]) + for i in range(len(plte) // 3)} + new = bytearray() + for y in range(height): + base = y * stride + for x in range(width): + r, g, b = pal.get(out[base + x], (0, 0, 0)) + new += bytes((r, g, b)) + else: # 0 or 2: already opaque + try: + shutil.copyfile(src, dst) + except OSError: + return False + return "no_alpha" + nstride = width * ch_out + new_raw = bytearray() + for y in range(height): + new_raw.append(0) + new_raw += new[y * nstride:(y + 1) * nstride] + comp = zlib.compress(bytes(new_raw), 9) + buf = bytearray(b"\x89PNG\r\n\x1a\n") + buf += _png_chunk(b"IHDR", + struct.pack(">IIBBBBB", width, height, 8, new_ct, 0, 0, 0)) + for typ, cdata in other: + buf += _png_chunk(typ, cdata) + buf += _png_chunk(b"IDAT", comp) + buf += _png_chunk(b"IEND", b"") + try: + with open(dst, "wb") as f: + f.write(bytes(buf)) + except OSError: + return False + return "stripped" + + +def _tga_decode_rle(pix, width, height, depth): + bpp = depth // 8 + out = bytearray() + count = width * height + i, n = 0, len(pix) + while len(out) < count * bpp and i < n: + h = pix[i] + i += 1 + run = (h & 0x7f) + 1 + if h & 0x80: + chunk = pix[i:i + bpp] + i += bpp + for _ in range(run): + out += chunk + else: + for _ in range(run): + out += pix[i:i + bpp] + i += bpp + return out + + +def _strip_tga_alpha(src, dst): + import struct as _s + try: + with open(src, "rb") as f: + data = f.read() + except OSError: + return False + if len(data) < 18: + return False + id_len = data[0] + cmap_type = data[1] + img_type = data[2] + if img_type not in (1, 2, 3, 9, 10, 11) or data[16] not in (16, 24, 32): + try: + shutil.copyfile(src, dst) + except OSError: + return False + return "no_alpha" + width, height = _s.unpack(" 8192 or height > 8192: + try: + shutil.copyfile(src, dst) + except OSError: + return False + return "no_alpha" + cmap_len = _s.unpack(" drop the alpha bit, scale to 8-bit + v = pix[base] | (pix[base + 1] << 8) + r = (v >> 10) & 0x1f + g = (v >> 5) & 0x1f + b = v & 0x1f + r = (r * 255 + 15) // 31 + g = (g * 255 + 15) // 31 + b = (b * 255 + 15) // 31 + out += bytes((b, g, r)) + hdr = bytearray(18) + hdr[2] = 2 # uncompressed truecolour + hdr[12:14] = _s.pack("IIBBBBB", size, size, 8, 2, 0, 0, 0)) + + _png_chunk(b"IDAT", zlib.compress(row * size, 9)) + + _png_chunk(b"IEND", b"")) + + +def _solid_texture(rgb, tdir): + """把 .mat 里的纯色写成一张贴图,返回文件名(同色复用同一张)。""" + os.makedirs(tdir, exist_ok=True) + bn = "__solid_%s.png" % "".join("%02x" % int(max(0.0, min(1.0, c)) * 255 + 0.5) + for c in rgb[:3]) + dst = os.path.join(tdir, bn) + if not os.path.isfile(dst): + with open(dst, "wb") as f: + f.write(_solid_png(rgb)) + return bn + + +def _pick_diffuse(scene, mat_id, tids): + """一个材质挂了好几张贴图时选哪张当底色: + + 1. 连接属性是 DiffuseColor / Diffuse / BaseColor 的; + 2. 贴图名里有 diffuse / albedo / basecolor 的; + 3. 名字不像法线 / 高光 / 环境图(_NRM、_SPEC、ENV …)的第一张; + 4. 都不行就第一张。 + """ + texs = [(tid, scene.textures.get(tid)) for tid in tids] + texs = [(tid, t) for tid, t in texs if t] + if not texs: + return None + slot = getattr(scene, "texture_slot", {}) + for tid, t in texs: + if slot.get((mat_id, tid), "").lower() in ("diffusecolor", "diffuse", "basecolor", "maps|base_color_map", + "maya|diffusetexture", "3dsmax|parameters|base_color_map"): + return t["name"] + for tid, t in texs: + if any(k in t["name"].lower() for k in ("diffuse", "albedo", "basecolor", "base_color")): + return t["name"] + for tid, t in texs: + n = t["name"].lower() + if not any(k in n for k in _NOT_DIFFUSE) and not slot.get((mat_id, tid), "").lower().startswith( + ("normal", "bump", "specular", "reflection", "emissive", "transparent")): + return t["name"] + return texs[0][1]["name"] + + +def _copy_textures(tex_list, fbx_path, out_dir, verbose, alpha_mode=ALPHA_AUTO, + alpha_uvs=None, known=None, fallback=None, threads=1): + """Locate each texture image on disk and copy it into ``out_dir/textures/``. + + Returns ``(out_names, stats)``: + + * ``out_names`` - ``{源文件名: 要在 PMX 里引用的文件名}``。走了 alpha 处理的 + 贴图在这里被换成 ``<名>_noalpha.png``(**原始图片一律不动**)。 + * ``stats`` - 计数与逐张的判定说明,供日志 / 界面显示;``png_alpha`` 是 + ``{原样拷贝的 PNG 的 normcase 绝对路径: vrmio.png_alpha_stats 结果}``, + 判断透明时顺便算好,接着转 VRM 时不用再解一遍(pmx2vrm 的 tex_alpha)。 + + Files referenced by the FBX but missing locally (the FBX usually stores an + absolute game path like ``G:\\...``) are simply skipped - the PMX still + references them so the user can drop the images into ``textures/`` later. + + threads:同时解几张图(Pillow 在 C 里解码、不占 GIL)。 + """ + stats = {"mode": alpha_mode, "copied": 0, "weighed": 0, + "stripped": 0, "kept": 0, "opaque": 0, "failed": 0, + "decisions": [], "missing": 0, "out_names": {}, "png_alpha": {}} + if not tex_list: + return stats["out_names"], stats + import shutil + fbx_dir = os.path.dirname(os.path.abspath(fbx_path)) + parent = os.path.dirname(fbx_dir) + search_dirs = [fbx_dir, + os.path.join(fbx_dir, "textures"), + os.path.join(fbx_dir, "tex"), + parent] + found = {} + for bn, p in (known or {}).items(): + if bn in tex_list and os.path.isfile(p): + found[bn] = p + for bn in tex_list: + if bn in found: + continue + for d in search_dirs: + if not d: + continue + p = os.path.join(d, bn) + if os.path.isfile(p): + found[bn] = p + break + if bn in found: + continue + for d in (fbx_dir, parent): + if not d or bn in found: + continue + hit = _find_file(d, bn) + if hit: + found[bn] = hit + break + # 还没找到:同名换扩展名(FBX 里写的是 face_00.psd,手上的是 face_00.tga),再查 Unity 材质 + for bn in tex_list: + if bn in found: + continue + stem = os.path.splitext(bn)[0] + for ext in (".png", ".tga", ".jpg", ".jpeg", ".bmp", ".dds"): + alt = stem + ext + if alt.lower() == bn.lower(): + continue + for d in search_dirs: + if d and os.path.isfile(os.path.join(d, alt)): + found[bn] = os.path.join(d, alt) + break + if bn not in found: + for d in (fbx_dir, parent): + hit = _find_file(d, alt) if d else None + if hit: + found[bn] = hit + break + if bn in found: + break + if bn not in found and fallback is not None: + p = fallback(bn) + if p and os.path.isfile(p): + found[bn] = p + stats["missing"] = len(tex_list) - len(found) + + if found: + tdir = os.path.join(out_dir, "textures") + os.makedirs(tdir, exist_ok=True) + items = list(found.items()) + + def weigh(item): + """先看看这张图到底有没有 alpha 可处理 → (有透明?, 判定, 说明, png_alpha_stats 结果)。 + 在线程里跑;解出来的 alpha 用完就丢,不会几张图的一起攒在内存里。""" + bn, src = item + got, png = _load_alpha(src) + if got is None or not _has_any_transparency(*got): + return False, None, None, png + if alpha_mode == ALPHA_STRIP: + return True, ALPHA_STRIP, "StripAll", png + return (True,) + decide_alpha(src, (alpha_uvs or {}).get(bn), got) + (png,) + + if alpha_mode == ALPHA_KEEP: + weighed = [None] * len(items) + elif threads > 1 and len(items) > 1: + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(min(threads, len(items))) as ex: + weighed = list(ex.map(weigh, items)) + else: + weighed = [weigh(it) for it in items] + for (bn, src), w in zip(items, weighed): + real = os.path.basename(src) # 换了扩展名 / 来自 Unity 材质时用实际文件名 + ref = real + out_bn = real + wrote_copy = False # 副本已经写过盘了,别再被原件覆盖回去 + png = NotImplemented + if w is not None: + has_a, verdict, detail, png = w + if not has_a: + stats["opaque"] += 1 + elif alpha_mode != ALPHA_STRIP: + stats["weighed"] += 1 + if has_a: + stats["decisions"].append((bn, verdict, detail)) + if verdict != ALPHA_STRIP: + stats["kept"] += 1 + else: + out_bn = _opaque_copy_name(real) + dst = os.path.join(tdir, out_bn) + res = _strip_alpha(src, dst) + if res == "stripped": + stats["stripped"] += 1 + ref = out_bn + wrote_copy = True + elif res is False: + stats["failed"] += 1 + out_bn = real + else: + # 写不出副本(格式不支持等):退回原图 + out_bn = real + dst = os.path.join(tdir, out_bn) + if wrote_copy: + stats["copied"] += 1 + stats["out_names"][bn] = ref + continue + try: + if not (os.path.abspath(src) == os.path.abspath(dst)): + shutil.copyfile(src, dst) + stats["copied"] += 1 + except OSError: + continue + stats["out_names"][bn] = ref + if png is not NotImplemented: # 原样拷贝:统计结果对拷贝出来的文件也成立 + stats["png_alpha"][os.path.normcase(os.path.abspath(dst))] = png + + if verbose and tex_list: + if stats["copied"]: + print("贴图:已复制 %d / %d 个文件到 textures 文件夹" % (stats["copied"], len(tex_list))) + if alpha_mode == ALPHA_KEEP: + pass + elif alpha_mode == ALPHA_STRIP: + print("贴图:已去除 %d 张贴图的透明通道" % stats["stripped"]) + else: + print("贴图透明通道:去除 %d 张,保留 %d 张,%d 张本身不透明" + % (stats["stripped"], stats["kept"], stats["opaque"])) + if stats["failed"]: + print("贴图:%d 张去除透明通道失败,已使用原图" % stats["failed"]) + if stats["missing"]: + print("贴图:%d 个引用的文件未找到(可稍后放入 textures 文件夹)" % stats["missing"]) + return stats["out_names"], stats + + +def _mesh_has_no_material(g, model, scene, mats=None): + """该网格是不是「一个材质都没挂」。 + + 游戏(Unity/HoYo 系)导出时常带一张名为 `EffectMesh` 的效果片:它没有 + 材质节点、没有贴图,UV 铺满整张图集,几何是一大片横跨全身的薄板。按普通 + 网格导出去,在 MMD 里就是一块不透明的灰白大板子盖在裙子上(贴图看着像被 + "翻错"了,其实是底色被压住了)。C# 插件侧的日志同样把它标成 `材质 '?'` + / 无贴图,产出的 PMX 里也不含这张网格,所以这里直接跳过。 + """ + if mats is None: + mats = _mesh_materials(g, model, scene) + if not mats: + return True + return all(m is None for m in mats) + + +def convert(scene, out_path, scale_mode="mmd", flip_z=True, verbose=True, name=None, + center=True, morphs=True, max_morphs=None, remove_alpha=None, + alpha_mode=None, auto_facing=True, face_180=False, + skip_untextured=True, threads=4): + # threads:判断贴图透明时同时解几张图(见 _copy_textures) + # ⚠ remove_alpha 的默认必须是 None(不是 False):False 会被 alpha_mode_of + # 当成「用户显式要 keep」,把「不指定就用 auto」的默认遮蔽掉。 + alpha_mode = alpha_mode_of(alpha_mode, remove_alpha) + # 确保输出目录存在(CLI 直接调用时尤其容易漏建) + _odir = os.path.dirname(os.path.abspath(out_path)) + try: + os.makedirs(_odir, exist_ok=True) + except OSError as e: + raise OSError("无法创建输出目录 %s:%s" % (_odir, e)) + + # ---- gather meshes in a stable order + geo_ids = [nid for nid, n in scene.byid.items() + if n.name == "Geometry" and nid in scene.geometry_model] + geo_ids.sort(key=lambda i: scene.byid[i].props[1]) + + # ---- bone order = model order for LimbNodes (parents first) + bones = [m for m in scene.models.values() if m.cls == "LimbNode"] + bones.sort(key=lambda m: _bone_depth(m)) + if not bones: + # No skeletal nodes: synthesise a root so skinned/weighted vertices + # still have a valid bone to bind to (otherwise the PMX is invalid). + root = Model(0, "Root", "LimbNode") + bones = [root] + bone_index = {m.id: i for i, m in enumerate(bones)} + + # ---- 朝向:要不要在 Z 取反之外再转 180°(判据见 detect_forward_turn) + if auto_facing: + turn, facing_reason = detect_forward_turn(scene, bones) + if turn is None: + turn = bool(face_180) + facing_reason += ",无法自动判定,按设置%s" % ("旋转 180°" if turn else "不旋转") + else: + turn = bool(face_180) + facing_reason = "未启用自动判定,按设置%s" % ("旋转 180°" if turn else "不旋转") + if verbose: + print("朝向:%s%s" % (facing_reason, ",旋转 180°" if turn else "")) + + # ---- per-mesh data + mesh_data = [] + skipped_untextured = [] # 无材质网格(效果片)——默认丢掉 + for gid in geo_ids: + g = scene.byid[gid] + mid = scene.geometry_model[gid] + model = scene.models[mid] + verts = g.get("Vertices").props[0] + pvi = g.get("PolygonVertexIndex").props[0] + nverts = len(verts) // 3 + tris = triangulate(pvi) + mats = _mesh_materials(g, model, scene) + if skip_untextured and _mesh_has_no_material(g, model, scene, mats): + skipped_untextured.append((model.name, len(tris))) + if verbose: + print("跳过无材质的网格 %s(%d 个三角面,通常是特效面片)" % (model.name, len(tris))) + continue + uv = sample_uv(g.get("LayerElementUV"), pvi) + nrm = sample_normals(g.get("LayerElementNormal"), pvi) + poly_mat = _poly_material_index(g, pvi, len(mats)) + mesh_data.append({ + "geo": g, "model": model, "verts": verts, "tris": tris, + "uv": uv, "nrm": nrm, "nverts": nverts, "pvi": pvi, + "mats": mats, "poly_mat": poly_mat, + "geom": scene._geom_matrix(scene.byid.get(mid)), + }) + + # ---- scale: MMD units put a character at roughly 20 units tall + if scale_mode in ("mmd", "auto", None, ""): + # 用第一个顶点初始化,避免模型整体浮空(y 全为正)时把 ymin 误当 0 导致缩放算错 + first = True + ymax = ymin = 0.0 + for md in mesh_data: + w = md["model"].world + v = md["verts"] + for i in range(md["nverts"]): + y = m_point(w, v[i * 3:i * 3 + 3])[1] + if first: + ymax = ymin = y + first = False + else: + ymax = max(ymax, y) + ymin = min(ymin, y) + height = ymax - ymin + scale = (20.0 / height) if height > 1e-6 else 1.0 + else: + scale = float(scale_mode) + + # 换轴 / 换手性 / 转向统一走这里(方向用同一套,缩放只作用在位置上)。 + # + # 为什么 turn 是「把镜像轴从 Z 换成 X」而不是「再绕 Y 转 180°」: + # FBX→MMD 必须做一次单轴反射(行列式 -1)才能把右手系变左手系,默认反射的是 + # Z。而反射 Z 会把「朝 +Z 的模型」翻成朝 -Z(正好是 MMD 要的), + # 同时把「本来就朝 -Z 的模型」翻成朝 +Z(背对镜头)。 + # 后一种要修,而「单轴反射由 Z 改成 X」与默认方案之间恰好差一个绕 Y 的 180°, + # 行列式仍是 -1,手性转换不受影响,绕序照旧交给 detect_winding 投票。 + def xfd(d): + x, y, z = d + if turn: + x = -x + if not flip_z: + z = -z + elif flip_z: + z = -z + return (x, y, z) + + def xf(p): + x, y, z = xfd(p) + return (x * scale, y * scale, z * scale) + + # ---- build vertices + pmx_verts = [] # (pos, nrm, uv, weights[(bone, w)]) + pmx_tris = [] # (a, b, c) + segments = [] # (material_id, tri_start, tri_count, mesh_index) + # (geometry_id, control_point) -> [pmx vertex indices] (used for morphs) + geo_cp_to_pmx = {} + # geometry id -> full transform (world * geometric) for that mesh + geo_w = {} + uv_by_mat = {} # 材质节点 id -> 该材质实际用到的 UV 角点(MMD 口径) + + weights_of_geo = {} + for gid in geo_ids: + skin = scene.geometry_skin.get(gid) + acc = {} + if skin is not None: + for cid, sid in scene.cluster_skin.items(): + if sid != skin: + continue + bind = scene.cluster_bone.get(cid) + if bind is None or bind not in bone_index: + continue + cl = scene.byid[cid] + idn = cl.get("Indexes") + wn = cl.get("Weights") + if idn is None or wn is None: + continue + for vi, wt in zip(idn.props[0], wn.props[0]): + if wt <= 0.0: + continue + acc.setdefault(vi, []).append((bind, float(wt))) + weights_of_geo[gid] = acc + + vbase = 0 + mesh_records = [] # 每个网格:名字、顶点 / 三角面数、包围盒、PMX 材质段(找替换网格用) + mat_entries = [] # material node id (or None) for each draw segment + for md in mesh_data: + gid = md["geo"].props[0] + model = md["model"] + # full transform for geometry-space vertices = world * geometric + w = m_mul(model.world, md["geom"]) + geo_w[gid] = w + v = md["verts"] + uv = md["uv"] + nrm = md["nrm"] + pvi = md["pvi"] + acc = weights_of_geo[gid] + # 没有蒙皮的网格(Unity 酱的眼睛、嘴、眉毛就是挂在头骨下面的普通网格): + # 整个网格跟着它在层级里最近的那根祖先骨走。以前给的是 bone_index 里随便的第一根骨, + # 结果脸部零件跟着手臂甩 + rigid_bone = None + if not acc: + p = model.parent + while p is not None and rigid_bone is None: + if p.id in bone_index: + rigid_bone = p.id + p = p.parent + mats = md["mats"] + poly_mat = md["poly_mat"] + + # Build vertices (deduplicated across the whole mesh) and tag every + # triangle with its material index. Triangles are then emitted grouped + # by material so that each PMX draw segment's faces stay contiguous in + # the index buffer (required by the format). + key_map = {} + mesh_tris = [] # list of (mat_idx, (a, b, c)) + for ti, tri in enumerate(md["tris"]): + mat_idx = poly_mat[ti] if poly_mat is not None else 0 + out = [] + for cp, corner in tri: + nval = nrm[corner] if (nrm is not None and corner < len(nrm)) else None + uval = uv[corner] if (uv is not None and corner < len(uv)) else (0.0, 0.0) + # 记下每个材质实际用到的 UV 角点(给 alpha 判定定点采样用,MMD 口径 v 上下翻) + _uvm = uv_by_mat.setdefault(mats[mat_idx] if mat_idx < len(mats) else None, []) + if len(_uvm) < 20000: + _uvm.append((uval[0], 1.0 - uval[1])) + k = (cp, round(uval[0], 5), round(uval[1], 5)) + if nval is not None: + k += (round(nval[0], 4), round(nval[1], 4), round(nval[2], 4)) + j = key_map.get(k) + if j is None: + ppos = xf(m_point(w, v[cp * 3:cp * 3 + 3])) + if nval is not None: + d = m_dir(w, nval) + ln = math.sqrt(d[0] ** 2 + d[1] ** 2 + d[2] ** 2) or 1.0 + d = (d[0] / ln, d[1] / ln, d[2] / ln) + nd = xfd(d) + else: + nd = (0.0, 1.0, 0.0) + wl = sorted(acc.get(cp, []), key=lambda t: -t[1])[:4] + if not wl: + wl = [(rigid_bone if rigid_bone is not None else next(iter(bone_index)), 1.0)] + tot = sum(x[1] for x in wl) or 1.0 + wl = [(b, wt / tot) for b, wt in wl] + j = len(pmx_verts) + key_map[k] = j + pmx_verts.append((ppos, nd, (uval[0], 1.0 - uval[1]), wl)) + geo_cp_to_pmx.setdefault((gid, cp), []).append(j) + out.append(j) + mesh_tris.append((mat_idx, (out[0], out[1], out[2]))) + + tri_before = len(pmx_tris) + for mi, mat_id in enumerate(mats): + grp = [t for (m, t) in mesh_tris if m == mi] + if not grp: + continue + mi_idx = len(mat_entries) + mat_entries.append(mat_id) + start = len(pmx_tris) + pmx_tris.extend(grp) + segments.append((mi_idx, start, len(grp), model.name)) + if len(pmx_verts) > vbase: + ps = [pv[0] for pv in pmx_verts[vbase:]] + mesh_records.append({ + "name": model.name, "nv": len(pmx_verts) - vbase, "nt": len(pmx_tris) - tri_before, + "lo": [min(p[k] for p in ps) for k in range(3)], "hi": [max(p[k] for p in ps) for k in range(3)], + "segs": [sg[0] for sg in segments if sg[1] >= tri_before]}) + vbase = len(pmx_verts) + + # ---- 互为替换的网格:只显示主网格,其余默认隐藏,各做一个材质表情来切换 + alt_groups = _alternate_groups(mesh_records) + hidden_segs = {s for _, alts in alt_groups for a in alts for s in a["segs"]} + if verbose and alt_groups: + for prim, alts in alt_groups: + print("替换网格:显示 %s,%s 默认隐藏并做成切换表情" + % (prim["name"], "、".join(a["name"] for a in alts))) + + # ---- winding check: geometric face normal must agree with the vertex + # normals we imported, otherwise MMD would render the model inside-out. + agree = 0.0 + for a, b, c in pmx_tris[:8000]: + pa, pb, pc = pmx_verts[a][0], pmx_verts[b][0], pmx_verts[c][0] + ux, uy, uz = pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2] + vx, vy, vz = pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2] + fx, fy, fz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + fl = math.sqrt(fx * fx + fy * fy + fz * fz) or 1.0 + na = pmx_verts[a][1] + agree += (fx * na[0] + fy * na[1] + fz * na[2]) / fl + flipped = agree < 0 + if flipped: + pmx_tris = [(a, c, b) for a, b, c in pmx_tris] + if verbose: + print("绕序:%s" % ("与顶点法线相反,已反转" if flipped else "与顶点法线一致")) + + # ---- textures: collect one diffuse texture per material, build global list + tex_list = [] # ordered unique basenames + tex_name_to_idx = {} + tex_index_of_mat = {} # material node id -> texture index (or None) + # Unity 导出的 FBX 常常没有贴图文件名(或指向导出者电脑上的 .psd),贴图是 Unity 材质(.mat) + # 按 GUID 指定的:在 Unity 工程 / 解开的 unitypackage 里按材质名找回来(formats/unityasset.py) + unity_map = [] + tex_paths = {} # basename -> 已知的完整路径(来自 Unity 材质 / 烘焙的纯色贴图) + tex_fallback = {} # basename -> 材质名(文件找不到时再查 Unity 材质) + solid_alpha = {} # material node id -> 纯色材质的 alpha(< 1 时) + + def unity_info(mat_name): + """材质名 → Unity .mat 的属性(贴图 + 颜色),整包只扫一次。""" + if not unity_map: + try: + unity_map.append(unityasset.material_properties( + os.path.dirname(os.path.abspath(scene.path)))) + except Exception: # noqa: BLE001 找不到就算了 + unity_map.append({}) + return unity_map[0].get(mat_name) or {} + + def unity_tex(mat_name): + return unity_info(mat_name).get("tex") + + for si, (mi_idx, start, cnt, mname) in enumerate(segments): + mat_node_id = mat_entries[si] if si < len(mat_entries) else None + if mat_node_id is None: + continue + tids = scene.texture_materials.get(mat_node_id, []) + basename = _pick_diffuse(scene, mat_node_id, tids) + mnode = scene.byid.get(mat_node_id) + mat_name = _ns_strip(_clean_name(mnode.props[1])) if mnode is not None and len(mnode.props) > 1 else "" + if not basename or not basename.lower().endswith(unityasset.IMAGE_EXT): + up = unity_tex(mat_name) if mat_name else None + if up: + basename = os.path.basename(up) + tex_paths[basename] = up + elif mat_name: + tex_fallback.setdefault(basename, mat_name) + if not basename: + # 没有贴图的材质:Unity Toon shader 的颜色只写在 .mat 的 m_Colors(_Color / + # _BaseColor),FBX 则在 Properties70 的 DiffuseColor。以前两者都没读, + # 这类材质一律落成默认白色——纯黑材质变白、纯白材质「碰巧看着正常」。 + # 这里把颜色烘焙成一张纯色贴图,走和图片贴图完全相同的链路。 + color = unity_info(mat_name).get("color") if mat_name else None + if color is None and mnode is not None: + dc = scene._props70(mnode).get("DiffuseColor") + if dc and len(dc) >= 3: + try: + color = [float(dc[0]), float(dc[1]), float(dc[2]), 1.0] + except (TypeError, ValueError): + color = None + if color is not None: + tdir = os.path.join(_odir, "textures") + basename = _solid_texture(color, tdir) + tex_paths[basename] = os.path.join(tdir, basename) + a = color[3] if len(color) > 3 else 1.0 + if a < 0.999: + solid_alpha[mat_node_id] = a + if basename: + if basename not in tex_name_to_idx: + tex_name_to_idx[basename] = len(tex_list) + tex_list.append(basename) + tex_index_of_mat[mat_node_id] = tex_name_to_idx[basename] + # 每张贴图对应「哪些材质用到了它」——alpha 自动判定按这些材质的 UV 定点采样, + # 而不是扫整图(整图的空白 padding 会把统计带偏)。 + alpha_uvs = {} + for mat_node_id, tix in tex_index_of_mat.items(): + if 0 <= tix < len(tex_list): + bn = tex_list[tix] + lst = uv_by_mat.get(mat_node_id) + if lst: + alpha_uvs.setdefault(bn, []).extend(lst) + # copy image files next to the pmx when they can be found locally + tex_out_names, tex_stats = _copy_textures( + tex_list, scene.path, _odir, verbose, alpha_mode=alpha_mode, + alpha_uvs=alpha_uvs, known=tex_paths, + fallback=lambda bn: unity_tex(tex_fallback[bn]) if bn in tex_fallback else None, + threads=threads) + # 走了 alpha 处理的贴图在 PMX 里要引用 <名>_noalpha.png + tex_list = [tex_out_names.get(bn, bn) for bn in tex_list] + + # ---- index widths depend on the final vertex / triangle / material / texture counts + # (multi-material meshes raise the material count above the per-mesh guess) + nv = len(pmx_verts) + nt = len(pmx_tris) + vi_size = pick_index_size(nv, signed=False) + ti_size = pick_index_size(max(len(tex_list), 1) + 1, signed=True) + mi_size = pick_index_size(max(len(segments), 1), signed=True) + bi_size = pick_index_size(max(len(bones), 1) + 1, signed=True) + + pw = PmxWriter((vi_size, ti_size, mi_size, bi_size, 1, 1)) + + # ---- bone names / positions are taken in the SAME pmx space + bpos = {} + for m in bones: + node = scene.byid.get(m.id) + bw = m_mul(m.world, scene._geom_matrix(node) if node else m_ident()) + bpos[m.id] = xf(m_translation(bw)) + + # ---- optional centering / grounding (MMD convention: origin-centered, feet at y=0) + if center and nv: + xs = [p[0] for p, _, _, _ in pmx_verts] + ys = [p[1] for p, _, _, _ in pmx_verts] + zs = [p[2] for p, _, _, _ in pmx_verts] + off = (-(min(xs) + max(xs)) / 2.0, -min(ys), -(min(zs) + max(zs)) / 2.0) + pmx_verts = [((p[0] + off[0], p[1] + off[1], p[2] + off[2]), n, uv, wl) + for p, n, uv, wl in pmx_verts] + for k in bpos: + x, y, z = bpos[k] + bpos[k] = (x + off[0], y + off[1], z + off[2]) + if verbose: + print("居中:偏移 (%.2f, %.2f, %.2f)" % off) + + model_name = (name or os.path.splitext(os.path.basename(out_path))[0]).strip() + if not model_name: + model_name = "Model" + pw.header(model_name, model_name, + "Converted from FBX by fbx2pmx.py", + "Converted from FBX by fbx2pmx.py") + + # vertices + pw.i32(nv) + for pos, nd, uv, wl in pmx_verts: + pw.f32(pos[0]); pw.f32(pos[1]); pw.f32(pos[2]) + pw.f32(nd[0]); pw.f32(nd[1]); pw.f32(nd[2]) + pw.f32(uv[0]); pw.f32(uv[1]) + n = len(wl) + if n == 1: + pw.buf += bytes([0]) + pw.idx(bone_index[wl[0][0]], bi_size) + wsum = 1.0 + elif n == 2: + pw.buf += bytes([1]) + pw.idx(bone_index[wl[0][0]], bi_size) + pw.idx(bone_index[wl[1][0]], bi_size) + pw.f32(wl[0][1]) + wsum = 1.0 + else: + while len(wl) < 4: + wl.append((wl[-1][0], 0.0)) # pad with zero weight + pw.buf += bytes([2]) + for b, _ in wl: + pw.idx(bone_index[b], bi_size) + for _, wt in wl: + pw.f32(wt) + wsum = 1.0 + # 顶点 edge scale 用 PMX 的标准值 1.0:有没有轮廓线由材质的 edge_size 决定, + # 没有描边的材质 edge_size=0,MMD 里仍不会出现黑边。以前一律写 0, + # 结果即便 .mat 里开了描边,「只转 PMX」时也永远看不到。 + pw.f32(1.0) + + # faces + pw.i32(nt * 3) + for tri in pmx_tris: + pw.uidx(tri[0], vi_size) + pw.uidx(tri[1], vi_size) + pw.uidx(tri[2], vi_size) + + # textures + pw.i32(len(tex_list)) + for bn in tex_list: + pw.text("textures\\" + bn) + + # materials (one PMX material per draw segment, in segment order) + pw.i32(len(segments)) + n_outline = 0 + for si, (mi_idx, start, cnt, mname) in enumerate(segments): + mat_node_id = mat_entries[si] if si < len(mat_entries) else None + mat = scene.byid.get(mat_node_id) if mat_node_id else None + mlabel = _clean_name(mat.props[1]) if mat else (mname or ("Material%d" % si)) + diffuse = [1.0, 1.0, 1.0, 1.0] + # 材质颜色不写进 PMX diffuse:MMD / MToon 的显示色是 diffuse×0.6 + ambient(0.5), + # 纯黑 diffuse 会被 ambient 抬成 0.5 灰,纯白会被压到 0.6。没有贴图的纯色材质 + # 已经在上面烘焙成 __solid_*.png,走贴图链路才能精确还原黑 / 白。 + # (以前这里是 `mat.get("DiffuseColor")`:FBX 的颜色在 Properties70 的 P 节点里, + # Material 节点并没有同名的子节点,所以这句恒为 None,所有材质都是默认白。) + if mat_node_id in solid_alpha: + diffuse[3] = solid_alpha[mat_node_id] + if mi_idx in hidden_segs: + diffuse[3] = 0.0 # 替换网格默认隐藏(切换表情把它显示出来) + pw.text(mlabel); pw.text(mlabel) + for v4 in diffuse: + pw.f32(v4) + pw.f32(0.0); pw.f32(0.0); pw.f32(0.0) # specular + # shininess:C# 参考实现 MaterialDefaults.UseFbxShininess = false + # → 一律写默认值 25(不是 0)。specular 是 0 所以不影响观感, + # 只是让材质和 FbxImporterPlugin 的产物逐字段一致。 + pw.f32(25.0) # shininess + pw.f32(0.5); pw.f32(0.5); pw.f32(0.5) # ambient (按需求默认 0.5 0.5 0.5) + # Unity Toon shader 的描边(.mat 里的 _Outline_Width / _Outline_Color)FBX 里没有, + # 这里还原成 PMX 的边缘字段,PMX → VRM 阶段再转成 MToon 的 outlineWidth*。 + # UCTS 的宽度是 shader 内部系数,按经验换成 PMX edge_size:materials.py 会再乘 + # 0.001 换成米,20 → 3.0 → 约 3 mm 的轮廓线;上限 6 防止异常值画出粗黑边。 + ol = unity_info(mlabel).get("outline") or unity_info(_ns_strip(mlabel)).get("outline") + edge_size = min(6.0, max(0.0, ol["width"] * 0.15)) if ol else 0.0 + edge_col = tuple(ol["color"]) + (1.0,) if ol else (0.0, 0.0, 0.0, 0.0) + if ol: + n_outline += 1 + # 描画フラグ:BothDraw | Shadow(0x01 | 0x02);有 Unity 描边时再开 0x10(画边缘)。 + # 以前一律不写 0x10、edge_size 写 0,配合「描边(按 PMX 轮廓线)」选项默认关闭, + # 导致 unitypackage 里开了描边的材质转出来完全没有轮廓线。 + pw.buf += bytes([0x01 | 0x02 | (0x10 if ol else 0)]) + for v in edge_col: + pw.f32(v) + pw.f32(edge_size) + tex_idx = tex_index_of_mat.get(mat_node_id, -1) if mat_node_id else -1 + pw.idx(tex_idx, ti_size) # texture + pw.idx(-1, ti_size) # sphere + pw.buf += bytes([0]) # sphere mode + # toon:**不使用**。 + # + # PMX 里 toon 字段的宽度由「共有Toonフラグ」决定,两个方向都别搞反 + # (PMX 规范 + mmd_tools 的 `is_shared_toon_texture` 一致): + # flag = 1 → 共享/内建 toon。字段是 **1 字节编号**,引用 MMD 安装目录 + # `Data/` 下的 toon01.bmp … toon10.bmp。 + # ⚠ **编号 0 就是 toon01.bmp,不是「不使用」**:mmd_tools + # 源码里写死了这个 +1 + # toon_path = "toon%02d.bmp" % (shared + 1) + # 而 MMD 的 Data 目录里**没有 toon00.bmp**(只有 01..10)。 + # flag = 0 → 本模型**纹理表**里的贴图,字段是**纹理索引宽度**, + # **-1 = なし(不使用)**。 + # + # 2026-09-24 修:以前写的是 flag=1 + 编号 0,注释误以为「0 = toon00.bmp + # = 不使用」,实际等于给每个材质硬套一层 toon01.bmp,用户反馈「PMX 还是 + # 自动上了 Toon 路径」。对照实测:用户本机那份公认正常的 Anastasya.pmx + # 全部 13 个材质都是 flag=0 / -1。 + pw.buf += bytes([0]) # toon: 引用本模型纹理表 + pw.idx(-1, ti_size) # -1 = 不使用 toon + pw.text("") + pw.i32(cnt * 3) + + # bones + pw.i32(len(bones)) + for m in bones: + pw.text(m.name); pw.text(m.name) + p = bpos[m.id] + pw.f32(p[0]); pw.f32(p[1]); pw.f32(p[2]) + par = m.parent + while par is not None and par.id not in bone_index: + par = par.parent + pw.idx(bone_index[par.id] if par else -1, bi_size) + pw.i32(0) # deform layer + child_bone = next((c for c in m.children if c.id in bone_index), None) + bflag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # rot/move/visible/operable + if child_bone is not None: + bflag |= 0x0001 # tail stored as bone index + pw.buf += struct.pack(" PMX vertex morphs (表情) + written_morphs = 0 + morph_list = [] + if morphs and getattr(scene, "morphs", None): + merged = {} + for m in scene.morphs: + gid = m["geo_id"] + w = geo_w.get(gid) + if w is None: + continue + indexes = m["indexes"] + deltas = m["deltas"] + # 自动检测 Shape.Vertices 是「相对偏移」还是「绝对坐标」:不同导出器写法不同。 + # 相对偏移写法下 shape 值本身即位移(量级小);绝对坐标写法下 shape 与 base 同量级(大), + # 此时真正的位移应为 shape − base。实测 Kiana 为相对偏移写法。 + base_node = scene.byid.get(gid) + base = base_node.get("Vertices").props[0] if base_node else None + is_relative = True + if base is not None and indexes: + rel_sum = abs_sum = 0.0 + for k in range(min(len(indexes), 64)): + cp = indexes[k] + dx, dy, dz = deltas[k * 3], deltas[k * 3 + 1], deltas[k * 3 + 2] + rel_sum += abs(dx) + abs(dy) + abs(dz) + bx, by, bz = base[cp * 3], base[cp * 3 + 1], base[cp * 3 + 2] + abs_sum += abs(dx - bx) + abs(dy - by) + abs(dz - bz) + is_relative = rel_sum <= abs_sum + offsets = [] + for k in range(len(indexes)): + cp = indexes[k] + dx = deltas[k * 3] + dy = deltas[k * 3 + 1] + dz = deltas[k * 3 + 2] + if not is_relative and base is not None: + bx, by, bz = base[cp * 3], base[cp * 3 + 1], base[cp * 3 + 2] + dx -= bx; dy -= by; dz -= bz + off = xf(m_dir(w, (dx, dy, dz))) # same linear transform as base + for vidx in geo_cp_to_pmx.get((gid, cp), []): + offsets.append((vidx, off)) + if not offsets: + continue + nm = m["name"] + low = nm.lower() + # panel: which FACS tab the morph shows in (1=眉 2=目 3=口 4=その他) + if low.startswith("eyebrow") or "brow" in low: + panel = 1 + elif low.startswith("eye") or "eyeshape" in low: + panel = 2 + elif low.startswith("mouth"): + panel = 3 + else: + panel = 4 + kind = 1 # 1 = 頂点 (vertex) morph; PMX type, not FACS tab + # 不同网格上的同名 blend shape 是同一个表情的几部分(Unity 酱的眼睛和睫毛各有一个 + # EYE_DEF_C,Unity 的动画也是按名字一起驱动):合成一个 PMX 表情。以前各写一个, + # VRM 里就成了 EYE_DEF_C 和 EYE_DEF_C_2,眨眼只闭一半 + same = merged.get(nm) + if same is not None: + same["offsets"].extend(offsets) + continue + merged[nm] = {"name": nm, "name_en": nm, "panel": panel, "kind": kind, "offsets": offsets} + morph_list.append(merged[nm]) + if max_morphs is not None and len(morph_list) > max_morphs: + if verbose: + print("表情:共 %d 个,按上限只导出前 %d 个" % (len(morph_list), max_morphs)) + morph_list = morph_list[:max_morphs] + if verbose: + print("表情:由 %d 个 BlendShape 生成 %d 个顶点表情" % (len(scene.morphs), len(morph_list))) + if morphs and alt_groups: + # 材质表情(kind 8):替换网格的 alpha +1(显示),主网格的 alpha ×0(隐藏) + show = [0.0] * 3 + [1.0] + [0.0] * 24 + hide = [1.0] * 3 + [0.0] + [1.0] * 24 + used_names = {mo["name"] for mo in morph_list} + for prim, alts in alt_groups: + for a in alts: + nm = a["name"] + while nm in used_names: + nm += "_" + used_names.add(nm) + offs = [(s, 1, show) for s in a["segs"]] + [(s, 0, hide) for s in prim["segs"]] + morph_list.append({"name": nm, "name_en": nm, "panel": 4, "kind": 8, "offsets": offs}) + written_morphs = len(morph_list) + pw.i32(len(morph_list)) + for mo in morph_list: + pw.text(mo["name"]); pw.text(mo["name_en"]) + pw.buf += bytes([mo["panel"]]) + pw.buf += bytes([mo["kind"]]) + pw.i32(len(mo["offsets"])) + if mo["kind"] == 8: + for mi, op, vals in mo["offsets"]: + pw.idx(mi, mi_size) + pw.buf += bytes([op]) + for x in vals: + pw.f32(x) + continue + for vidx, off in mo["offsets"]: + pw.uidx(vidx, vi_size) + pw.f32(off[0]); pw.f32(off[1]); pw.f32(off[2]) + + # display frames: one, listing every bone + pw.i32(1) + pw.text("Root"); pw.text("Root") + pw.buf += bytes([1]) + pw.i32(len(bones)) + for m in bones: + pw.buf += bytes([0]) # 要素対象 0 = ボーン + pw.idx(bone_index[m.id], bi_size) + + # rigid bodies / joints + pw.i32(0) + pw.i32(0) + + with open(out_path, "wb") as f: + f.write(pw.buf) + return {"verts": nv, "tris": nt, "bones": len(bones), + "materials": len(segments), "bytes": len(pw.buf), + "morphs": written_morphs, "scale": scale, "vi_size": vi_size, + "face_turn": bool(turn), "facing_reason": facing_reason, + "alpha_mode": alpha_mode, "alpha": tex_stats, + "textures": list(tex_list), "unity_outline": n_outline, + "skipped_untextured": skipped_untextured} + + +def _bone_depth(m): + d = 0 + p = m.parent + while p is not None: + d += 1 + p = p.parent + return (d, m.name) + + +# ------------------------------------------------------------------ cli ----- + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("fbx") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--scale", default="mmd", + help="'mmd' (auto, ~20 units tall), 'raw' (1.0), or a number") + ap.add_argument("--no-flip-z", action="store_true", + help="keep FBX handedness (default converts to MMD)") + ap.add_argument("--no-center", action="store_true", + help="do not re-center/ground the model (keep FBX world position)") + ap.add_argument("--no-morphs", action="store_true", + help="do not export FBX blend shapes as PMX morphs (表情)") + ap.add_argument("--alpha", choices=list(ALPHA_MODES), default=None, + help="texture alpha: keep | auto (default) | strip") + ap.add_argument("--remove-alpha", action="store_true", default=None, + help="legacy alias for --alpha (maps to auto, NOT strip: " + "it only strips mask-like alpha, keeps real transparency)") + ap.add_argument("--no-auto-facing", action="store_true", + help="disable per-file facing detection (toe / face mesh)") + ap.add_argument("--face-180", action="store_true", + help="force an extra 180 degree turn (manual override)") + ap.add_argument("--keep-untextured-meshes", action="store_true", + help="keep meshes that carry no material at all (default: " + "skip them; these are game 'effect sheets' that would " + "render as an opaque grey board over the model)") + ap.add_argument("--max-morphs", type=int, default=None, + help="cap the number of exported morphs (default: no limit)") + ap.add_argument("--info", action="store_true") + a = ap.parse_args() + + scene = Scene(a.fbx) + print("FBX 版本 %d · 对象 %d 个" % (scene.ver, len(scene.objects))) + print("模型 %d 个(其中骨骼 %d)· 几何体 %d · 材质 %d" + % (len(scene.models), + sum(1 for m in scene.models.values() if m.cls == "LimbNode"), + sum(1 for n in scene.objects if n.name == "Geometry"), + sum(1 for n in scene.objects if n.name == "Material"))) + if a.info: + return 0 + + out = a.out or (os.path.splitext(a.fbx)[0] + ".pmx") + scale = a.scale + if scale not in ("mmd", "raw"): + try: + scale = float(scale) + except ValueError: + scale = "mmd" + if scale == "raw": + scale = 1.0 + st = convert(scene, out, scale_mode=scale, flip_z=not a.no_flip_z, + center=not a.no_center, morphs=not a.no_morphs, + max_morphs=a.max_morphs, + alpha_mode=a.alpha, remove_alpha=a.remove_alpha, + auto_facing=not a.no_auto_facing, face_180=a.face_180, + skip_untextured=not a.keep_untextured_meshes, + name=os.path.splitext(os.path.basename(a.fbx))[0]) + print("\n已写出 %s" % out) + print("顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d · 缩放 %.4f" + % (st["verts"], st["tris"], st["bones"], st["materials"], + st["morphs"], st["scale"])) + if st["skipped_untextured"]: + print("跳过无材质的网格 %d 个:%s" + % (len(st["skipped_untextured"]), + "、".join("%s(%d 个三角面)" % (n, t) for n, t in st["skipped_untextured"]))) + print("大小 %.2f MB(顶点索引 %d 字节)" + % (st["bytes"] / 1048576, st["vi_size"])) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/convert/logtext.py b/convert/logtext.py new file mode 100644 index 0000000..0aee1d5 --- /dev/null +++ b/convert/logtext.py @@ -0,0 +1,459 @@ +# -*- coding: utf-8 -*- +"""转换日志的英文版。转换器里的日志直接写中文句子;界面是英文时按这里的对照表翻译。 + + logtext.to_en(msg) → 英文;对不上的返回 None(界面照常显示中文) + +TEMPLATES 的中文句式和代码里的 log(...) / raise 一一对应(tests/test_logtext.py 扫描源码,漏了会报错), +句式里的 %d / %s / %.1f 匹配成参数。参数是程序生成的中文(「需要反转」「左」、另一条句式)时再翻译, +模型里的名字(骨骼、材质、文件名)原样保留。英文句式里用 {0} {1} … 引用参数,顺序可以和中文不同。 +""" +import re + +TEMPLATES = { + # ---- 流程(pipeline / server / parallel) + "→ %s": "→ {0}", + "· %s": "· {0}", + "输出目录:%s": "Output folder: {0}", + "解压出 %d 个文件,其中模型 %d 个:%s": "Extracted {0} files, {1} of them models: {2}", + "解压内层压缩包 %s": "Extracting the inner archive {0}", + "用 %s 解压": "Extracting with {0}", + "%s共有 %d 个模型,并行转换 %d 个": "{1} models {0}, converting {2} at a time", + "压缩包中": "in the archive", + "包中": "in the package", + "解包 %s:%d 个文件,%d 个 FBX": "Unpacked {0}: {1} files, {2} FBX", + "读取 FBX:%s": "Reading FBX: {0}", + "PMX → VRM:%s": "PMX → VRM: {0}", + "跳过 %s:%s(如需转换,请在「转换」页关闭「只转换人物」)": + "Skipped {0}: {1} (to convert it anyway, turn off \"Characters only\" on the Convert tab)", + "未识别到人形骨架,可能是道具": "no humanoid skeleton found, probably a prop", + "头部没有网格,可能只有服装或配件": "nothing is attached to the head, probably only clothes or accessories", + "手部没有网格,可能只有服装或配件": "nothing is attached to the hands, probably only clothes or accessories", + "%s 转换失败:%s": "{0} failed: {1}", + "没有执行": "not run", + "已应用保存的调整(%d 项)": "Applied the saved Tune edits ({0})", + "已写出 %s": "Wrote {0}", + "无法启动子进程,改为逐个转换": "Couldn't start worker processes, converting one at a time", + "完成,用时 %.1f 秒": "Done in {0} s", + "并行转换 %d 个文件(共 %d 个)": "Converting {0} files at a time ({1} in total)", + "已停止,%d 个文件未转换": "Stopped, {0} files not converted", + "预览:未找到人物模型,忽略「只转换人物」生成预览": + "Preview: no character found, previewing without \"Characters only\"", + "调整写入 %s 失败:%s": "Writing the Tune edits to {0} failed: {1}", + "调整已写入 %s": "Tune edits written to {0}", + "缩略图已自动生成并写入 %s": "Thumbnail generated and written to {0}", + # ---- 错误(raise,界面显示在文件下面) + "包中没有 FBX 文件": "The package has no FBX files", + "无法转换此文件:%s": "Can't convert this file: {0}", + "压缩包中没有可转换的模型(PMX / FBX / uemodel / psk / xps)": + "The archive has no models to convert (PMX / FBX / uemodel / psk / xps)", + "不支持的输入:%s": "Unsupported input: {0}", + "无法创建输出目录 %s:%s": "Can't create the output folder {0}: {1}", + "此 PMX 没有可用的面数据": "This PMX has no faces to convert", + "不是 VRM 文件": "Not a VRM file", + "不是支持的压缩包:%s": "Not a supported archive: {0}", + "既不是二进制 FBX,也解析不出 ASCII FBX 节点:%s": "Neither a binary FBX nor readable as ASCII FBX: {0}", + "不是 PMX 文件:%s": "Not a PMX file: {0}", + "PMX 解析后仍有 %d 字节未读完(已读 %d / 共 %d),说明某一段的结构与写入程序不一致,请反馈此模型文件。": + "{0} bytes left after reading the PMX ({1} of {2} read): a section doesn't match what the writing " + "program produced. Please report this model file.", + "改写后回读校验失败,未写入:%s": "Verification after rewriting failed, nothing written: {0}", + "%s读取「%s」时越过文件末尾(偏移 %d / 文件 %d 字节)。可能是某一段的结构与写入程序不一致,请反馈此模型文件。": + "{0}reading \"{1}\" went past the end of the file (offset {2} of {3} bytes). A section may not match what " + "the writing program produced. Please report this model file.", + "%s「%s」长度 %d 超出文件剩余字节(偏移 %d / %d)。": "{0}\"{1}\" length {2} is past the end of the file (offset {3} / {4}).", + "PMX 解析错位(段落:%s):": "PMX out of step (section: {0}): ", + "头部": "header", "顶点": "vertices", "面": "faces", "贴图": "textures", "材质": "materials", "骨骼": "bones", + "表情": "morphs", "表示枠": "display frames", "刚体": "rigid bodies", "关节": "joints", + "顶点[%d]": "vertex [{0}]", "材质[%d]": "material [{0}]", "骨骼[%d]": "bone [{0}]", "表情[%d]": "morph [{0}]", + "表示枠[%d]": "display frame [{0}]", "刚体[%d]": "rigid body [{0}]", "关节[%d]": "joint [{0}]", + "该模型是 PMX 2.1 且含 %d 个 SoftBody,本转换器暂不支持 SoftBody。": + "This is a PMX 2.1 model with {0} SoftBodies; SoftBody isn't supported yet.", + "未知的 PMX 表情类型 %d": "Unknown PMX morph type {0}", + "不是 UEFormat 文件(魔数不是 UEFORMAT):%s": "Not a UEFormat file (magic isn't UEFORMAT): {0}", + "不是模型文件(Identifier=%r):%s": "Not a model file (Identifier={0}): {1}", + "UEFormat 版本 %d 高于本库支持的 %d:%s": "UEFormat version {0} is newer than the supported {1}: {2}", + "解析失步:消费 %d 字节,文件 %d 字节(差 %d)": "Parsing went out of step: read {0} bytes of {1} (off by {2})", + "不支持的压缩格式 %r:%s": "Unsupported compression {0}: {1}", + "该 .uemodel 是 ZSTD 压缩体,但运行环境缺少 zstandard 库,无法解压:%s": + "This .uemodel is ZSTD compressed but the zstandard library is missing: {0}", + "ZSTD 解压失败:%s(%s)": "ZSTD decompression failed: {0} ({1})", + "GZIP 解压失败:%s(%s)": "GZIP decompression failed: {0} ({1})", + "不是 GLB/VRM 文件:%s": "Not a GLB / VRM file: {0}", + "GLB 里没有 JSON chunk": "The GLB has no JSON chunk", + "此文件中没有网格数据(PNTS / VTXW 为空)": "The file has no mesh data (PNTS / VTXW are empty)", + "此文件中没有面数据(FACE 块为空)": "The file has no faces (the FACE block is empty)", + "此 .uemodel 中没有 LOD 数据": "This .uemodel has no LODs", + "此文件中没有网格数据": "The file has no mesh data", + "骨骼数异常(%d),文件可能不是 XPS 或已损坏": "Bad bone count ({0}): not an XPS file, or damaged", + "网格数异常(%d)": "Bad mesh count ({0})", + "文件太小,不是 XPS 模型": "The file is too small to be an XPS model", + "文件中没有骨骼数据": "The file has no bones", + "文件中没有网格数据": "The file has no meshes", + "文件在偏移 %d 处提前结束(还需 %d 字节,仅剩 %d)": "The file ends early at offset {0} ({1} more bytes needed, {2} left)", + "网格 %d 的 UV 层数/贴图数异常(%d / %d)": "Mesh {0} has a bad UV layer / texture count ({1} / {2})", + "网格 %d 的顶点数异常(%d)": "Mesh {0} has a bad vertex count ({1})", + "网格 %d 的三角面数异常(%d)": "Mesh {0} has a bad triangle count ({1})", + "XPS 头部异常(countOfUnknownInts=%d)": "Bad XPS header (countOfUnknownInts={0})", + "字符串长度编码异常(偏移 %d)": "Bad string length encoding (offset {0})", + "顶点权重根数异常(%d)": "Bad number of vertex weights ({0})", + # ---- PMX → VRM + "PMX:顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d": + "PMX: {0} vertices · {1} triangles · {2} bones · {3} materials · {4} morphs", + "权重:左右对称的 %d 对顶点,右侧主要绑在 %s(%s),左侧却绑在 %s(%s),动作时这部分会变形。可能是模型的权重错误,建议在 PmxEditor 中检查": + "Weights: in {0} mirrored vertex pairs the right side follows {1} ({2}) but the left follows {3} ({4}), " + "so this part will deform when moving. Probably a weight mistake in the model; check it in PmxEditor", + "绕序自动判定(手性修正后):与法线同向 %d 面 / 反向 %d 面 → %s": + "Winding (after the handedness fix): {0} faces agree with the normals / {1} oppose → {2}", + "需要反转": "flip", + "保持不变": "keep", + "反转": "flipped", + "无": "none", + "Z 轴取反": "Z mirrored", + "X 轴取反": "X mirrored", + "缩放:%.5f(MMD 单位 → 米)· 手性修正:%s · 绕序:%s": + "Scale: {0} (MMD units → metres) · handedness fix: {1} · winding: {2}", + "视线:左右 %.1f° · 下 %.1f° · 上 %.1f°(%s)": "Gaze: sideways {0}° · down {1}° · up {2}° ({3})", + "视线:%s": "Gaze: {0}", + "按眼球结构计算,瞳孔最多移动约 %d%% 瞳孔宽度": "from the eyeball shape, the pupil moves at most about {0}% of its width", + "算出 %.1f°,限制到 %.0f°": "{0}° computed, limited to {1}°", + "眼骨上没有瞳孔顶点,使用默认值 10°": "no pupil vertices on the eye bones, using the default 10°", + "眼骨上的顶点不像一只眼睛(宽 %.2f、支点到表面 %.2f,两眼相距 %.2f),使用默认值 10°": + "the eye bone vertices don't look like an eye (width {0}, pivot to surface {1}, eyes {2} apart), " + "using the default 10°", + "网格:按材质分为 %d 个部分": "Mesh: {0} parts by material", + "网格:按表情分为 %d 个(%s)": "Mesh: split into {0} by morphs ({1})", + "%s:%d 个表情": "{0}: {1} morphs", + "已写出 %s(%.2f MB)· 节点 %d · morph target %d · 表情 %d": + "Wrote {0} ({1} MB) · {2} nodes · {3} morph targets · {4} expressions", + "骨骼:已去掉 %d 个不起作用的节点(%s),保留 %d 个": "Bones: removed {0} nodes that do nothing ({1}), {2} kept", + "无权重且不属于 humanoid、物理的骨,包括中间的控制骨": + "unweighted, not humanoid or physics, including the intermediate control bones", + "IK、末端骨、已合并的付与骨等无权重且不属于 humanoid、物理的骨": + "IK, tip and merged append bones and others that are unweighted and not humanoid or physics", + "表情:补充视线表情 %s(由转动眼骨烘焙,lookAt 仍使用骨骼)": + "Expressions: added gaze expressions {0} (baked from turning the eye bones; lookAt still uses the bones)", + # ---- 骨骼(skeleton / humanoid) + "朝向:模型%s,已绕 Y 轴旋转 %d° 校正(左右肩 / 胯不在 X 轴上)": + "Facing: the model {0}, turned {1}° about Y (shoulders / hips weren't along X)", + "背向前方": "faces backwards", + "朝向侧面": "faces sideways", + "付与骨合并:%d 根(%s)→ 权重并入付与親": "Append bones merged: {0} ({1}) → weights moved to their append parents", + "付与骨合并:%s 与付与親的位置略有偏差,合并后绕付与親的位置转动": + "Append bones merged: {0} sat slightly off their append parents and now turn about the parents' positions", + "材质:%d 个 Unity 材质开了描边(_Outline_Width),已转成 MToon 轮廓线": + "Materials: {0} Unity materials have outlines (_Outline_Width), converted to MToon outlines", + "材质:%d 个材质是描边外壳或内侧面(%s),「所有材质双面」时仍保持单面,否则会盖住模型或重叠闪烁": + "Materials: {0} are outline shells or inner sides ({1}) and stay single-sided with \"All materials double-sided\"; " + "otherwise they would cover the model or flicker against the outer layer", + "贴图:%d 张不在模型记录的位置,已按文件名在模型文件夹里找到(%s)": + "Textures: {0} weren't where the model says; found them by name in the model folder ({1})", + "贴图:%d 张找不到(%s),用到它们的材质只有底色。贴图要和模型放在一起:请加入整个文件夹或压缩包": + "Textures: {0} not found ({1}); materials using them show only their base color. Textures must be next to " + "the model: add the whole folder or archive", + "贴图:%d 张读取失败(%s),用到它们的材质只有底色": "Textures: {0} couldn't be read ({1}); materials using them show only their base color", + "系统里没有 WebView2 运行时(Windows 的网页组件),所以用浏览器打开。安装后重新打开程序就是独立窗口。": + "WebView2 (the Windows web component) is not installed, so VRMify Enhanced opened in the browser. " + "Install it and start VRMify Enhanced again to get its own window.", + "没有安装 pywebview,所以用浏览器打开(pip install pywebview 后就是独立窗口)。": + "pywebview is not installed, so VRMify Enhanced opened in the browser (pip install pywebview for its own window).", + "上传中断": "Upload interrupted", + "独立窗口启动失败(%s),所以用浏览器打开。": "VRMify Enhanced's window failed to start ({0}), so it opened in the browser.", + "拖放不可用(%s),请用「添加文件」": "Drag and drop is unavailable ({0}); use \"Add files\"", + "浏览器模式下只加入了 %s 本身,旁边的贴图没有一起传过来,转出来可能没有贴图:请拖入整个模型文件夹或压缩包": + "In browser mode only {0} itself was added; the textures next to it weren't passed along, so the result may " + "have no textures: drop the whole model folder or archive", + "付与骨:%d 根按比例跟随关节的骨(%s)→ 权重按付与率分给关节骨,共 %d 个顶点": + "Append bones: {0} bones that follow a joint partly ({1}) → their weights were shared with the joint " + "by the append rate, {2} vertices", + "自检:%d 个顶点主要挂在 %s 上,MMD 里跟着 %s 转 %d%%,VRM 里只跟 %d%%,动作时这部分会变形": + "Self-check: {0} vertices mainly on {1} turn {3}% with {2} in MMD but only {4}% in the VRM; " + "this part will deform when animated", + "自检:humanoid 骨 %s(%s)在身体的另一侧,可能对应错了骨骼,动作时这部分会被拉开": + "Self-check: humanoid bone {0} ({1}) is on the other side of the body; it may be the wrong bone, " + "and this part will be pulled away when animated", + "自检:humanoid 骨 %s(%s)离 %s 有 %d cm,可能对应错了骨骼,动作时这部分会被拉开": + "Self-check: humanoid bone {0} ({1}) is {3} cm from {2}; it may be the wrong bone, " + "and this part will be pulled away when animated", + "自检:humanoid 骨 %s(%s)离网格超过 %d cm,可能对应错了骨骼,动作时这部分会被拉开": + "Self-check: humanoid bone {0} ({1}) is more than {2} cm from the mesh; it may be the wrong bone, " + "and this part will be pulled away when animated", + "hips:已移至骨盆,下移 %.1f cm(原与 spine 相距 %.1f mm)": "hips: moved down to the pelvis by {0} cm (was {1} mm from spine)", + "骨骼:模型缺少 %s,已生成占位骨骼": "Bones: the model has no {0}, added a placeholder bone", + "骨骼:%s 与 %s 对应同一根骨骼,已忽略 %s": "Bones: {0} and {1} are the same bone, {2} ignored", + "骨骼层级:%s(%s)不在 %s(%s)之下,已移至其下(原父骨骼 %s)": + "Bone hierarchy: {0} ({1}) wasn't under {2} ({3}), moved there (parent was {4})", + "骨骼层级:%s(%s)无法修正,已从 humanoid 中移除": "Bone hierarchy: {0} ({1}) can't be fixed, removed from the humanoid", + "骨骼层级:%s(%s)无法修正,部分软件可能无法加载": "Bone hierarchy: {0} ({1}) can't be fixed, some programs may not load it", + "T-pose:%s 上臂 %.1f° · 前臂 %.1f°": "T-pose: {0} upper arm {1}° · forearm {2}°", + "T-pose:%s 手 %.1f° · 掌心 %.1f° · 四指最多 %.1f° · 拇指最多 %.1f°": + "T-pose: {0} hand {1}° · palm {2}° · fingers up to {3}° · thumb up to {4}°", + "骨骼:拇指只有两节(%s),已在手腕和第二节之间补上掌根那节,0.x 和 1.0 的拇指各节对应一致": + "Bones: two-segment thumbs ({0}), so the root segment was added between the wrist and the second " + "segment and the thumb segments match between 0.x and 1.0", + "左": "left", + "右": "right", + "肩": "shoulder", "上臂": "upper arm", "前臂": "forearm", "手": "hand", + "大腿": "thigh", "小腿": "lower leg", "脚": "foot", "脚趾": "toes", + # ---- 物理(springbone / autophys) + "物理:模型不含物理刚体,已按骨骼名和骨架结构自动添加 %d 根摆动骨(头发、裙摆、袖子、飘带、兽耳等)和 %d 个身体碰撞体": + "Physics: the model has no rigid bodies, so {0} swaying bones (hair, skirts, sleeves, ribbons, " + "animal ears …) and {1} body colliders were added from the bone names and the skeleton", + "物理:识别到 %d 根兽耳骨,已加入摆动链": + "Physics: {0} animal-ear bones detected and added to the swaying chains", + "SpringBone:%d 条链(裙摆类 %d、头发等 %d)· 碰撞体 %d · 碰撞组 %d": + "SpringBone: {0} chains ({1} skirt-like, {2} hair and others) · {3} colliders · {4} collider groups", + "SpringBone:MMD 物理骨 %d 根 → SpringBone 关节 %d 个(头发等每节至少 %.0f cm、裙摆至少 %.0f cm,中间的骨骼刚性跟随)": + "SpringBone: {0} MMD physics bones → {1} SpringBone joints (at least {2} cm per segment for hair, " + "{3} cm for skirts; the bones in between follow rigidly)", + "SpringBone:按设置跳过 %d 条下半身物理链(裙摆等)": "SpringBone: skipped {0} lower-body chains (skirts …) as set", + "SpringBone:按设置跳过 %d 条下半身物理链,没有可输出的链": "SpringBone: skipped {0} lower-body chains as set, no chains left", + "SpringBone:%d 条短链(不足 %.0f cm,四肢上不足 %.0f cm)不转换,以免末端高频抖动": + "SpringBone: {0} short chains (under {1} cm, under {2} cm on limbs) left out to avoid jittery tips", + "SpringBone:%d 条链的末端没有子骨骼,已补充末端节点": "SpringBone: {0} chains had no bone past their end, tip nodes added", + "SpringBone:静止姿势下与碰撞体重叠,已%s": "SpringBone: overlapping colliders at rest, so {0}", + "取消 %d 处链与碰撞体的碰撞": "turned off {0} chain–collider pairs", + "缩小 %d 个节点的碰撞半径": "shrank the hit radius of {0} nodes", + "SpringBone:%d 个链间横向关节(裙摆等)无法表达,已舍弃%s": + "SpringBone: {0} sideways joints between chains (skirts …) can't be expressed and were dropped{1}", + ";已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开": + "; {0} skirt–leg collisions were adjusted to the skirt panels' direction so the legs split the skirt less", + "已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开": + "{0} skirt–leg collisions were adjusted to the skirt panels' direction so the legs split the skirt less", + "SpringBone:已按裙片朝向修正 %d 处裙摆与腿的碰撞方向": + "SpringBone: {0} skirt–leg collisions adjusted to the skirt panels' direction", + "SpringBone(0.x):%d 根随关节刚性转动的骨(中间节、链末端的配饰)权重并到关节上(%d 个顶点),0.x 会让组里所有子骨都摆动": + "SpringBone (0.x): the weights of {0} bones that only follow a joint rigidly (in-between segments, " + "accessories at chain ends) were moved onto that joint ({1} vertices), since 0.x sways every bone in a group", + "SpringBone(0.x):%d 条链 → %d 个摆动组%s · 碰撞组 %d(胶囊换成 %d 个球)": + "SpringBone (0.x): {0} chains → {1} spring groups{2} · {3} collider groups (capsules as {4} spheres)", + "(%d 条分叉链并入上层链的组)": " ({0} branching chains joined the group of the chain they hang from)", + "SpringBone(0.x):每组只有一个碰撞半径,静止时会重叠的碰撞体缩小 %d 处、取消 %d 处": + "SpringBone (0.x): one hit radius per group, so colliders that would overlap at rest were shrunk " + "{0} times and turned off {1} times", + # ---- 表情 + "表情预设:%s": "Preset expressions: {0}", + "%s · 未找到:%s": "{0} · not found: {1}", + "表情:导出 %d 个 morph target(%s存储)": "Expressions: {0} morph targets ({1})", + "稀疏": "sparse", + "密集": "dense", + "表情:%d 个包含材质变化(转为材质颜色绑定)": "Expressions: {0} change materials (written as material colour binds)", + "表情:%d 个 UV 表情转为贴图偏移": "Expressions: {0} UV morphs written as texture offsets", + "表情:%d 处 UV 表情不是整个材质统一平移 / 缩放,VRM 无法表示,已跳过": + "Expressions: {0} UV morphs don't move or scale a whole material evenly, which VRM can't express; skipped", + "表情:补充 hideHighlight(%s)": "Expressions: added hideHighlight ({0})", + "表情:补充 hideHighlight(隐藏材质 %s)": "Expressions: added hideHighlight (hides the materials {0})", + "表情:未找到眼睛高光材质或关闭高光的表情,未补充 hideHighlight": + "Expressions: no eye highlight material or highlight-off morph found, hideHighlight not added", + "表情:补充 tongue(%s)": "Expressions: added tongue ({0})", + # ---- 材质 / 贴图 + "材质透明模式:不透明 %d · 裁剪(MASK)%d · 半透明(BLEND)%d": + "Material transparency: {0} opaque · {1} cutout (MASK) · {2} semi-transparent (BLEND)", + "材质:%d 个材质的贴图有透明部分,但模型只用到不透明的区域,按不透明处理": + "Materials: {0} materials' textures have transparent parts the model doesn't use; treated as opaque", + "材质:%d 个加算球面贴图转为 MToon 的 matcap": "Materials: {0} additive sphere maps became MToon matcaps", + "材质:%d 个材质的乘算球面贴图(.sph)在 MToon 中没有对应项,已忽略": + "Materials: {0} multiplicative sphere maps (.sph) have no MToon equivalent and were left out", + "贴图:未安装 Pillow,缩小贴图和 JPEG 存储未生效": "Textures: Pillow isn't installed, so resizing and JPEG storage were skipped", + "贴图:%d 张瘦身(%s%s)%.1f MB → %.1f MB": "Textures: {0} slimmed ({1}{2}) {3} MB → {4} MB", + "最大边长 %d": "max size {0}", + "不透明转 JPEG": "opaque ones as JPEG", + "、不透明转 JPEG": ", opaque ones as JPEG", + # ---- FBX → PMX + "FBX 版本 %d · 对象 %d 个": "FBX version {0} · {1} objects", + "模型 %d 个(其中骨骼 %d)· 几何体 %d · 材质 %d": "{0} models ({1} bones) · {2} geometries · {3} materials", + "顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d · 缩放 %.4f": + "{0} vertices · {1} triangles · {2} bones · {3} materials · {4} morphs · scale {5}", + "大小 %.2f MB(顶点索引 %d 字节)": "Size {0} MB ({1}-byte vertex indices)", + "朝向:%s%s": "Facing: {0}{1}", + ",旋转 180°": ", turned 180°", + "未启用自动判定,按设置%s": "auto-detection off, {0} as set", + "旋转 180°": "turned 180°", + "不旋转": "not turned", + "未找到脚尖骨骼": "no toe bones found", + "脚尖骨骼(%s)朝向 X 轴,旋转 180° 无法修正": "the toe bones ({0}) point along X, turning 180° can't fix that", + "按脚尖骨骼(%s)判定正面朝 %s": "the toe bones ({0}) show the front faces {1}", + "脸部网格过少": "too few face meshes", + "脸部网格前后偏移不明显": "the face meshes don't sit clearly to the front or back", + "按脸部网格的位置判定正面朝 %s": "the face meshes show the front faces {0}", + "%s,无法自动判定,按设置%s": "{0}, can't decide automatically, {1} as set", + "绕序:%s": "Winding: {0}", + "与顶点法线相反,已反转": "opposite to the vertex normals, flipped", + "与顶点法线一致": "matches the vertex normals", + "跳过无材质的网格 %d 个:%s": "Skipped {0} meshes without materials: {1}", + "%s(%d 个三角面)": "{0} ({1} triangles)", + "跳过无材质的网格 %s(%d 个三角面,通常是特效面片)": "Skipped the mesh {0} without a material ({1} triangles, usually an effect plane)", + "贴图:已复制 %d / %d 个文件到 textures 文件夹": "Textures: copied {0} / {1} files to the textures folder", + "贴图:%d 个引用的文件未找到(可稍后放入 textures 文件夹)": + "Textures: {0} referenced files not found (they can be put into the textures folder later)", + "贴图:已去除 %d 张贴图的透明通道": "Textures: removed the alpha channel of {0} textures", + "贴图透明通道:去除 %d 张,保留 %d 张,%d 张本身不透明": "Texture alpha: removed in {0}, kept in {1}, {2} have none", + "贴图:%d 张去除透明通道失败,已使用原图": "Textures: removing the alpha channel failed for {0}, the originals were used", + "替换网格:显示 %s,%s 默认隐藏并做成切换表情": "Alternative meshes: showing {0}; {1} hidden by default, with morphs to switch", + "居中:偏移 (%.2f, %.2f, %.2f)": "Centred: offset ({0}, {1}, {2})", + "表情:由 %d 个 BlendShape 生成 %d 个顶点表情": "Morphs: {1} vertex morphs from {0} BlendShapes", + "表情:共 %d 个,按上限只导出前 %d 个": "Morphs: {0} in total, only the first {1} exported (limit)", + # ---- PSK / XPS / uemodel → PMX,PMX → FBX + "提示:同一目录下有同名的 %s。PmxEditor 打开此 PMX 时会尝试将其作为「アンカーデータ」(锚点 / 权重数据)加载,并提示「アンカーデータの読み込みに失敗しました。」,点击确定即可,不影响模型。如需避免,可移动或重命名 PMX,或在 PmxEditor 中关闭[ファイル]→[アンカーデータの自動読み込み/保存]。": + "Note: there is a {0} with the same name in the folder. PmxEditor will try to load it as anchor data when " + "opening this PMX and report that it failed; click OK, the model is fine. To avoid it, move or rename the " + "PMX, or turn off automatic anchor data loading in PmxEditor's File menu.", + "读取 %s:顶点 %d · 楔 %d · 三角面 %d · 材质 %d · 骨骼 %d · 权重 %d": + "Read {0}: {1} vertices · {2} wedges · {3} triangles · {4} materials · {5} bones · {6} weights", + "表情 %d 个 · 附加 UV %d 套 · %s": "{0} morphs · {1} extra UV sets · {2}", + "含法线": "with normals", + "不含法线(将自动计算)": "no normals (they will be computed)", + "骨骼:%d 根%s": "Bones: {0}{1}", + "(其中 %d 根改为 MMD 标准日文名,原英文名保留在英文名中)": + " ({0} renamed to the standard MMD Japanese names, the original names kept as English names)", + "材质:%d 个 · 关联到贴图 %d 个%s": "Materials: {0} · {1} with textures{2}", + "(源目录中没有同名贴图,导出为无贴图模型)": " (no matching textures in the source folder, exported without textures)", + "已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d": + "Wrote {0} ({1} MB) · {2} vertices · {3} triangles · {4} bones · {5} materials · {6} morphs", + "已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d": + "Wrote {0} ({1} MB) · {2} vertices · {3} triangles · {4} bones · {5} materials", + "网格:%d 个楔的点索引越界,已改用第 0 个点": "Mesh: {0} wedges pointed past the vertex list, now use vertex 0", + "缩放:源高 %.2f 单位 × %.6f → %.2f(MMD 标准身高 20)": "Scale: source height {0} units × {1} → {2} (MMD standard height 20)", + "缩放:源高 %.3f 单位 × %.6f → %.2f(MMD 标准身高 20)": "Scale: source height {0} units × {1} → {2} (MMD standard height 20)", + "缩放:保持源尺寸(scale=1.0),源高 %.2f 单位": "Scale: kept as is (scale=1.0), source height {0} units", + "缩放:保持源尺寸(scale=1.0),源高 %.3f 单位": "Scale: kept as is (scale=1.0), source height {0} units", + "缩放:源高 %.2f 单位 × %.6f → %.2f": "Scale: source height {0} units × {1} → {2}", + "缩放:源高 %.3f 单位 × %.6f → %.2f": "Scale: source height {0} units × {1} → {2}", + "缩放:源高 %.2f cm × %.6f → %.2f": "Scale: source height {0} cm × {1} → {2}", + "居中:偏移 (%.3f, %.3f, %.3f)": "Centred: offset ({0}, {1}, {2})", + "居中:按参考模型包围盒(偏移 (%.3f, %.3f, %.3f))": "Centred on the reference model's bounding box (offset ({0}, {1}, {2}))", + "权重:%d 个顶点没有权重,已绑定到第 0 根骨骼": "Weights: {0} vertices had no weights, bound to bone 0", + "权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)": + "Weights: dropped {0} weights beyond the 4th bone per vertex (PMX allows 4)", + "提示:%d 条第 5 及以后的骨骼权重被丢弃(PMX 最多 4 根)": "Note: dropped {0} weights beyond the 4th bone (PMX allows 4)", + "表情:%d 个(顶点表情)": "Morphs: {0} (vertex morphs)", + "足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)": "Leg IK: added {0} bones (足IK / つま先IK under センター)", + "足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨": "Leg IK: the source skeleton has no complete leg chains, no IK bones added", + "绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s": "Winding: {0} faces agree with the normals / {1} oppose → {2}", + "绕序:缺少法线数据,按坐标轴反射统一反转(保持正面朝外)": + "Winding: no normals, flipped everywhere for the axis mirroring (front faces stay outside)", + "绕序:法线数据不完整,按坐标轴反射统一反转(保持正面朝外)": + "Winding: incomplete normals, flipped everywhere for the axis mirroring (front faces stay outside)", + "绕序:%d 个顶点没有法线,判定时使用平均法线": "Winding: {0} vertices had no normals, the average normal was used", + "已写出 %s(ASCII FBX 7.4 · %.2f MB)": "Wrote {0} (ASCII FBX 7.4 · {1} MB)", + "FBX 导出失败:%s": "FBX export failed: {0}", + "读取 %s:骨骼 %d 根 · 网格 %d 个 · 顶点 %d · 三角面 %d": "Read {0}: {1} bones · {2} meshes · {3} vertices · {4} triangles", + "骨骼:%d 根%s%s": "Bones: {0}{1}{2}", + ";%d 根 unused 占位骨单独放进 unused 表示枠": "; {0} unused placeholder bones put into their own unused display frame", + "%d 根 unused 占位骨单独放进 unused 表示枠": "{0} unused placeholder bones put into their own unused display frame", + "贴图:源目录中未找到 %s": "Textures: {0} not found in the source folder", + "对齐:匹配 %d 根骨骼,其中 %d 根位置一致(残差 ≤ %.4f cm)": "Alignment: matched {0} bones, {1} in the same place (residual ≤ {2} cm)", + "对齐:平移 (%.4f, %.4f, %.4f) cm": "Alignment: moved by ({0}, {1}, {2}) cm", + "UEFormat v%d · %s · 骨骼 %d · LOD %d": "UEFormat v{0} · {1} · {2} bones · {3} LODs", + "使用 LOD[%d] %s:顶点 %d · 三角面 %d · 材质 %d · 表情 %d · UV %d": + "Using LOD[{0}] {1}: {2} vertices · {3} triangles · {4} materials · {5} morphs · {6} UV sets", + "骨骼:%d 根(原始 %d 根)": "Bones: {0} ({1} originally)", + "材质:%d 个 · 关联到贴图 %d 个 · 拷贝贴图 %d 张%s": "Materials: {0} · {1} with textures · {2} textures copied{3}", + "(注意:%d 个材质的面区间不连续)": " (note: {0} materials have non-contiguous face ranges)", + "对齐:部件的 %d 根骨骼中没有与参考模型同名或相近的骨骼,已跳过对齐": + "Alignment: none of the part's {0} bones match the reference model by name, skipped", + "对齐:位置一致的骨骼只有 %d 根(共匹配 %d 根 · 最大残差 %.4f cm),结果不可靠,已跳过": + "Alignment: only {0} bones in the same place ({1} matched · max residual {2} cm), unreliable, skipped", + "对齐:参考模型的骨架跨度 %.1f cm,小于本文件的 %.1f cm,参考模型本身可能是部件(参考与部件可能选反了),已跳过对齐": + "Alignment: the reference skeleton spans {0} cm, less than this file's {1} cm; the reference may itself be " + "a part (reference and part swapped?), skipped", + "提示:该文件有 %d 个 LOD,只导出第 %d 个": "Note: the file has {0} LODs, only LOD {1} exported", + "对齐后:源高 %.2f cm → %.2f cm(缩放不变)": "After alignment: source height {0} cm → {1} cm (scale unchanged)", + "对齐:已按 %s 对齐(源坐标整体平移)": "Alignment: aligned to {0} (source coordinates moved as a whole)", + "对齐失败(匹配 %d / %d),按模型自身原点导出": "Alignment failed ({0} / {1} matched), exported at the model's own origin", + "对齐失败:%s(按模型自身原点导出)": "Alignment failed: {0} (exported at the model's own origin)", + "FBX:%d 顶点 · %d 三角面 · %d 骨骼 · %d 材质(ASCII 7.4,%s-up,前方 %s)%s": + "FBX: {0} vertices · {1} triangles · {2} bones · {3} materials (ASCII 7.4, {4}-up, front {5}){6}", + "· %d 个顶点表情写入 BlendShape": " · {0} vertex morphs written as BlendShapes", + "FBX:%d 个 Cluster · %d 个表情 Shape · 引用贴图 %d 张 · %.2f MB": + "FBX: {0} clusters · {1} morph shapes · {2} textures referenced · {3} MB", + "PSK:顶点 %d · 楔 %d · 面 %d · 骨骼 %d · 材质 %d · 权重 %d%s": + "PSK: {0} vertices · {1} wedges · {2} faces · {3} bones · {4} materials · {5} weights{6}", + " · 表情 %d": " · {0} morphs", + "提示:%d 个楔的点索引越界,已夹回合法范围": "Note: {0} wedges pointed past the vertex list, clamped", + "提示:顶点数 %d 超过 16 位索引上限,已改用 FACE3200": "Note: {0} vertices exceed 16-bit indices, FACE3200 used", + "提示:%d 个面的楔索引越界(文件可能显示为破面)": "Note: {0} faces point past the wedge list (the file may show holes)", + "XPS 格式:旧版 XNALara 二进制格式(无 Generic Item 2 头)": "XPS format: old XNALara binary (no Generic Item 2 header)", + "XPS 格式:Generic Item 2 · 版本 %d.%d · 作者 %s": "XPS format: Generic Item 2 · version {0}.{1} · author {2}", + "XPS 格式:旧版格式含切线数据(转换时忽略)": "XPS format: old format with tangents (ignored)", + "网格 %d 有 %d 个三角面索引越界,已跳过": "Mesh {0}: {1} triangles point past the vertex list, skipped", +} +# 转换失败时日志里的整段 traceback、程序本身的英文消息:不翻译 + +_PH = re.compile(r"%(?:\([^)]*\))?[-+ #0]*\d*(?:\.\d+)?[dsfrgx]|%%") + + +def _compile(zh): + out, pos = [], 0 + for m in _PH.finditer(zh): + out.append(re.escape(zh[pos:m.start()])) + ph = m.group() + if ph == "%%": + out.append("%") + elif ph[-1] == "d": + out.append(r"(-?\d+)") + elif ph[-1] in "fg": + out.append(r"(-?[\d.]+(?:e[-+]?\d+)?|nan|inf)") + else: + out.append(r"(.*?)") + pos = m.end() + out.append(re.escape(zh[pos:])) + return re.compile("".join(out), re.S) + + +# 固定文字多的先试:「已写出 %s」不能抢在「已写出 %s(%.2f MB)· …」前面 +_RULES = sorted(((_compile(zh.strip()), en) for zh, en in TEMPLATES.items() if _PH.search(zh)), + key=lambda r: -len(_PH.sub("", r[0].pattern))) +_FIXED = {zh.strip(): en for zh, en in TEMPLATES.items() if not _PH.search(zh)} +_ERROR = re.compile(r"([A-Za-z_][\w.]*(?:Error|Exception|Warning)): (.*)", re.S) +_CJK = re.compile("[ -〿぀-ヿ一-鿿＀-￯]") + + +def _arg(s): + """参数:程序生成的中文翻成英文,模型里的名字原样。列表(、/ ;)逐项处理: + 「身体:13 个表情、头绳:1 个表情」不能整个当成一句「%s:%d 个表情」。""" + if not s or not _CJK.search(s): + return s + if s in _FIXED: + return _FIXED[s] + for sep, out in ((";", "; "), ("、", ", ")): + if sep in s: + # 整句对得上、拆开的各项一个都对不上(「按脚尖骨骼(Toe.L、Toe.R)判定…」)就按整句 + parts = s.split(sep) + whole = _translate(s) + if whole is not None and not any(_CJK.search(p) and _translate(p) is not None for p in parts): + return whole + return out.join(_arg(p) for p in parts) + t = _translate(s) + if t is not None: + return t + m = _ERROR.fullmatch(s) + if m: + return "%s: %s" % (m.group(1), _arg(m.group(2))) + return s + + +def _translate(s): + if s in _FIXED: + return _FIXED[s] + for rx, en in _RULES: + m = rx.fullmatch(s) + if m: + return en.format(*(_arg(g) for g in m.groups())) + return None + + +def to_en(msg): + """一条日志的英文(开头的「[模型名] 」保留);对照表里没有的返回 None。""" + if not msg or not _CJK.search(msg): + return None + m = re.match(r"((?:\[[^\]\n]*\] )*)(.*)", msg, re.S) + prefix, body = m.group(1), m.group(2).strip() + if "\n" in body: # traceback 之类 + return None + t = _translate(body) + if t is None: + e = _ERROR.fullmatch(body) + if e: + inner = _translate(e.group(2)) + t = inner and "%s: %s" % (e.group(1), inner) + return prefix + t if t is not None else None diff --git a/convert/parallel.py b/convert/parallel.py new file mode 100644 index 0000000..c681f12 --- /dev/null +++ b/convert/parallel.py @@ -0,0 +1,240 @@ +# -*- coding: utf-8 -*- +"""多进程并行转换:几个文件(或一个包里的几个模型)同时转。 + +转换是纯 Python、吃 CPU 的活,线程受 GIL 限制快不了,所以开子进程(spawn)。每个任务的日志经队列送回主进程, +交给这个任务自己的 log 回调(界面按文件分开显示);任务结束的回调在主进程里、并且在它的日志都送完之后调用。 + + results = parallel.run([(key, func, args, kwargs), ...], jobs, log_for, start=None, done=None, should_stop=None) + +func 必须是模块顶层函数(子进程要能按名字导入),调用方式是 func(*args, log=..., **kwargs)。 +子进程里不再开并行(in_worker()),免得「4 个文件 × 每个包 4 个模型」叠出 16 个进程。 +单个转换内部贴图解码用的线程数见 threads()。 +打包的 exe 要在入口调用 multiprocessing.freeze_support()(ui/app.py),否则子进程会再开一个程序。 +""" +import concurrent.futures as cf +import functools +import multiprocessing as mp +import os +import queue +import threading +import traceback + +WORKER_ENV = "VRMIFY_WORKER" +MAX_AUTO = 8 # 自动时最多同时跑几个:再多也快不了多少(内存带宽、硬盘、进程启动),还多占内存 +GB_PER_JOB = 1.5 # 不知道任务多大时按这么多算(十几万顶点的模型转换时进程峰值约 0.5 GB) +MEM_SHARE = 0.8 # 并行的任务加起来最多占可用内存的这么多 + + +def in_worker(): + return os.environ.get(WORKER_ENV) == "1" + + +def free_memory_gb(): + """可用物理内存(GB);拿不到时按 8 GB 算。""" + try: + if os.name == "nt": + import ctypes + + class MS(ctypes.Structure): + _fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), + ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), + ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), + ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), + ("ullAvailExtendedVirtual", ctypes.c_ulonglong)] + m = MS() + m.dwLength = ctypes.sizeof(m) + if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(m)): + return m.ullAvailPhys / 1024 ** 3 + else: + return os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE") / 1024 ** 3 + except (OSError, ValueError, AttributeError): + pass + return 8.0 + + +@functools.lru_cache(maxsize=None) +def cores(): + """物理核数(超线程的两个逻辑核算一个);拿不到时按逻辑核数。""" + n = 0 + try: + if os.name == "nt": + import ctypes + + class INFO(ctypes.Structure): # SYSTEM_LOGICAL_PROCESSOR_INFORMATION + _fields_ = [("mask", ctypes.c_size_t), ("relationship", ctypes.c_int), + ("_", ctypes.c_ulonglong * 2)] + k32, size = ctypes.windll.kernel32, ctypes.c_ulong(0) + k32.GetLogicalProcessorInformation(None, ctypes.byref(size)) + buf = (INFO * (size.value // ctypes.sizeof(INFO)))() + if k32.GetLogicalProcessorInformation(buf, ctypes.byref(size)): + n = sum(1 for i in buf if i.relationship == 0) # RelationProcessorCore + elif os.path.exists("/proc/cpuinfo"): + seen, phys = set(), "0" + with open("/proc/cpuinfo", encoding="utf-8", errors="replace") as f: + for line in f: + key, _, val = line.partition(":") + if key.strip() == "physical id": + phys = val.strip() + elif key.strip() == "core id": + seen.add((phys, val.strip())) + n = len(seen) + except (OSError, ValueError, AttributeError): + n = 0 + return n or os.cpu_count() or 1 + + +def threads(): + """一个转换内部同时处理几张贴图(Pillow 在 C 里解码 / 编码、不占 GIL,线程就够):最多 4 个; + 在并行转换的子进程里最多 2 个(核和内存已经被别的子进程占着,一张 4K 贴图解开约 64 MB)。""" + return max(1, min(2 if in_worker() else 4, os.cpu_count() or 1)) + + +def auto_jobs(): + """自动时最多同时跑几个(还没看内存):物理核数 − 1(留一个给界面和系统),最多 MAX_AUTO。 + 8 核 16 线程上 20 个包:4 个 11.6 秒、8 个 9.1 秒、16 个 8.3 秒——超过物理核数快不了多少。""" + return max(1, min(MAX_AUTO, cores() - 1)) + + +def jobs_for(n_tasks, setting=0, mem_gb=None): + """同时跑几个:setting > 0 时按设置;0 = 自动(auto_jobs,再看可用内存)。 + + mem_gb:每个任务的内存峰值估计(GB,见 pipeline.memory_estimate)。给了就取「最大的几个加起来 + 不超过可用内存的 MEM_SHARE」——同时在跑的任意几个都不会超;不给按每个 GB_PER_JOB 算。 + """ + if n_tasks <= 1 or in_worker(): + return 1 + try: + setting = int(setting or 0) + except (TypeError, ValueError): + setting = 0 + if setting > 0: + return min(setting, n_tasks) + cap = max(1, min(auto_jobs(), n_tasks)) + free = free_memory_gb() + if not mem_gb: + return max(1, min(cap, int(free // GB_PER_JOB))) + k, tot = 0, 0.0 + for m in sorted(mem_gb, reverse=True)[:cap]: + tot += m + if tot > free * MEM_SHARE: + break + k += 1 + return max(1, k) + + +_QUEUE = None + + +def _init(q): + global _QUEUE + _QUEUE = q + os.environ[WORKER_ENV] = "1" + _lower_priority() + + +def _lower_priority(): + """子进程降到「低于正常」:电脑空闲时照样用满 CPU,用户同时在用别的程序(或这个界面)时先让给它们。""" + try: + if os.name == "nt": + import ctypes + k32 = ctypes.windll.kernel32 + k32.SetPriorityClass(k32.GetCurrentProcess(), 0x4000) # BELOW_NORMAL_PRIORITY_CLASS + else: + os.nice(5) + except (OSError, AttributeError): + pass + + +def _call(key, func, args, kwargs): + def log(msg, tag=None): + _QUEUE.put((key, str(msg), tag)) + try: + out = (True, func(*args, log=log, **kwargs)) + except Exception as e: # noqa: BLE001 一个任务失败不影响其它 + out = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc())) + _QUEUE.put((key, None, "__done__")) # 这个任务的日志到此为止 + return out + + +def run(tasks, jobs, log_for, start=None, done=None, should_stop=None): + """→ {key: (成功?, 结果 或 (错误摘要, 完整 traceback))}。should_stop() 为真后不再开始新任务。""" + ctx = mp.get_context("spawn") + q = ctx.Queue() + finished = {key: threading.Event() for key, *_ in tasks} + stop_pump = threading.Event() + + def pump(): + while not (stop_pump.is_set() and q.empty()): + try: + key, msg, tag = q.get(timeout=0.2) + except queue.Empty: + continue + if tag == "__stop__": # 收尾时放进来的,不用再等 0.2 秒超时 + break + if tag == "__done__": + finished[key].set() + else: + log_for(key)(msg, tag) + + th = threading.Thread(target=pump, daemon=True) + th.start() + by_key = {t[0]: t for t in tasks} + results, pending, running, started = {}, list(tasks), {}, set() + broken = False + try: + with cf.ProcessPoolExecutor(max_workers=jobs, mp_context=ctx, initializer=_init, initargs=(q,)) as ex: + while (pending or running) and not broken: + while pending and len(running) < jobs and not (should_stop and should_stop()): + key, func, args, kwargs = pending.pop(0) + if start and key not in started: + start(key) + started.add(key) + try: + running[ex.submit(_call, key, func, args, kwargs)] = key + except cf.process.BrokenProcessPool: + pending.insert(0, by_key[key]) + broken = True + break + if broken or not running: + break # 停止了:剩下的不开始 + fin, _ = cf.wait(running, return_when=cf.FIRST_COMPLETED) + for f in fin: + key = running.pop(f) + try: + res = f.result() + except cf.process.BrokenProcessPool: + # 子进程开不起来 / 被杀(杀毒软件拦截、内存不够):这个任务和剩下的都在本进程里转 + pending.insert(0, by_key[key]) + broken = True + continue + finished[key].wait(10) # 先把它的日志送完 + results[key] = res + if done: + done(key, *res) + if broken: + pending = [by_key[k] for k in running.values()] + pending + running.clear() + except cf.process.BrokenProcessPool: + broken = True + finally: + stop_pump.set() + q.put((None, None, "__stop__")) # 子进程都已退出,它们的日志都在这之前 + th.join(5) + if broken: + pending = [t for t in pending if t[0] not in results] + for key, func, args, kwargs in pending: + if should_stop and should_stop(): + break + log = log_for(key) + if key == pending[0][0]: + log("无法启动子进程,改为逐个转换", "warn") + if start and key not in started: + start(key) + try: + res = (True, func(*args, log=log, **kwargs)) + except Exception as e: # noqa: BLE001 + res = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc())) + results[key] = res + if done: + done(key, *res) + return results diff --git a/convert/pipeline.py b/convert/pipeline.py new file mode 100644 index 0000000..e40bae7 --- /dev/null +++ b/convert/pipeline.py @@ -0,0 +1,675 @@ +# -*- coding: utf-8 -*- +"""转换流程(与界面无关):识别输入格式 → 必要时先转 PMX → 再转 VRM。 + + import pipeline + outs = pipeline.convert_file(path, opts, log) # → [输出文件路径, ...] + +压缩包(模型网站下载的整包:zip / 7z / rar / tar.gz 等)会先解压到临时目录,再转换里面的模型: +有 PMX 就转 PMX,没有再转其它能识别的格式;包里只有另一个压缩包时再解一层。输出放在压缩包 +旁边(或指定的输出文件夹),临时目录随后删除。zip 用 Python 自带的 zipfile(处理 GBK / cp932 +文件名),其它格式见 formats/archive.py(7-Zip / WinRAR / Bandizip / Windows 自带的 tar)。 + +opts 是纯 JSON 可序列化的 dict(界面直接存取),缺的键用 DEFAULTS 补齐: + + target "vrm"(默认)| "pmx"(非 PMX 输入只转到 PMX 为止) + output {"mode": "app" | "beside" | "folder", "folder": 路径, "subfolder": 是否建「名字_日期_序号」子文件夹} + app = 程序目录下的 vrm 文件夹(界面用;路径由调用方放在 "app_folder",没有时同 beside) + vrm {"spec": "1.0" | "0.x", "avatar_only", "spring", "spring_skirt", "spring_stiffness", "auto_spring", + "morphs", "gaze", "combo_expr", "extra_expr", "outline", "tpose", "double_sided", "collapse_bones", "auto_thumb", + "tex_max": 0 | 4096 | 2048 | 1024, "tex_jpeg", "tex_no_mip"} + avatar_only:只转人物,道具(认不出人形骨架)和只有衣服 / 配件的模型跳过(见 not_an_avatar); + 一个文件里的模型全被跳过时 convert_file 返回 [] + meta VRM 作者 / 许可信息(键见 vrmconv/vrm_ext.build_vrm1),标题用模型文件名 + fbx {"alpha": "auto" | "keep" | "strip", "auto_facing", "face_180", "morphs", "center", "flip_z"} + uemodel {"alpha", "align_ref"} + psk {"jp_bones", "ik", "morphs", "alpha"} + xps {"jp_bones", "ik", "hide_unused", "double_sided", "edge"} + jobs 同时转几个(多个文件、或一个包里的几个模型):0 = 自动(见 parallel.jobs_for),1 = 一个一个转 + +log(msg, tag=None):tag 为 None / "info" / "ok" / "warn" / "err" / "head"。 +""" +import contextlib +import copy +import io +import os +import re +import shutil +import sys +import tempfile +import time +import traceback +import zipfile + +_HERE = os.path.dirname(os.path.abspath(__file__)) +for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")): + if _p not in sys.path: + sys.path.insert(0, _p) + +import archive # noqa: E402 +import parallel # noqa: E402 + +KINDS = {".pmx": "pmx", ".vrm": "vrm", ".fbx": "fbx", ".unitypackage": "unitypackage", + ".uemodel": "uemodel", ".psk": "psk", ".pskx": "psk", ".xps": "xps", ".zip": "zip"} +ARCHIVES = {"zip", "7z", "rar", "tar"} +CONVERTIBLE = {"pmx", "fbx", "unitypackage", "uemodel", "psk", "xps"} | ARCHIVES + +DEFAULTS = { + "target": "vrm", + "jobs": 0, + "output": {"mode": "beside", "folder": "", "subfolder": True}, + "vrm": {"spec": "1.0", "avatar_only": True, "spring": True, "spring_skirt": True, "spring_stiffness": 1.0, "auto_spring": True, "gaze": True, "combo_expr": True, "extra_expr": True, + "morphs": True, "outline": False, "unity_outline": True, + "tpose": False, "double_sided": False, + "collapse_bones": True, "auto_thumb": True, "tex_max": 0, "tex_jpeg": False, + "tex_no_mip": False}, + "meta": {"author": "", "version": "", "contact": "", "copyright": "", "license_url": "", + "avatar_permission": "everyone", "commercial_usage": "personalNonProfit", + "credit_notation": "required", "allow_redistribution": False, + "modification": "prohibited"}, + "fbx": {"alpha": "auto", "auto_facing": True, "face_180": False, "morphs": True, + "center": True, "flip_z": True}, + "uemodel": {"alpha": True, "align_ref": ""}, + "psk": {"jp_bones": True, "ik": True, "morphs": True, "alpha": True}, + "xps": {"jp_bones": True, "ik": True, "hide_unused": True, "double_sided": True, "edge": False}, +} + + +def classify(path): + """→ "pmx" / "vrm" / "fbx" / "unitypackage" / "uemodel" / "psk" / "xps" / + "zip" / "7z" / "rar" / "tar",不支持的为 None(分卷压缩包只认第一卷)。""" + return KINDS.get(os.path.splitext(path)[1].lower()) or archive.kind(path) + + +def merged(opts): + """用户选项和 DEFAULTS 合并(两层),不改动传入的 dict。""" + out = copy.deepcopy(DEFAULTS) + for k, v in (opts or {}).items(): + if isinstance(v, dict) and isinstance(out.get(k), dict): + out[k].update(v) + else: + out[k] = v + return out + + +def find_inputs(folder): + """文件夹里(递归)所有能转换或预览的文件。""" + found = [] + for d, dirs, files in os.walk(folder): + dirs[:] = [x for x in dirs if not x.startswith(".")] + for f in sorted(files): + if classify(f): + found.append(os.path.join(d, f)) + return found + + +def _score(text): + """文件名解码结果像不像正常的中日文:常用汉字、假名、ASCII 加分,半角片假名等乱码特征扣分。""" + sc = 0 + for ch in text: + o = ord(ch) + if o < 0x80 or 0x4E00 <= o <= 0x9FFF or 0x3040 <= o <= 0x30FF or 0x3000 <= o <= 0x303F or 0xFF01 <= o <= 0xFF5E: + sc += 1 + elif 0xFF61 <= o <= 0xFF9F or 0xE000 <= o <= 0xF8FF: + sc -= 3 # 半角片假名 / 私用区:GBK 被当成 cp932 解的典型样子 + return sc + + +def _decodings(raw, first): + """一个文件名的候选解码,按「常用字多」排序(同分时 first 优先),只保留严格解码得通的。 + + 同一个包里常混着 GBK(中文系统)和 cp932(日文系统)的名字,而一种编码的字节按另一种解, + 得到的多半是生僻字(「武器」的 cp932 字节按 GBK 解成「晲婍」)。用 GB2312 能不能编码当作 + 「常用字」的判断:它收了常用汉字和日文假名,GBK 扩展区的生僻字和半角片假名都不在里面。 + """ + tries = [raw] + # cp932 的「ダメ文字」:第二字节是 0x5C(反斜杠),有的打包工具把它当路径分隔符改成了 / + fixed = re.sub(rb"([\x81-\x9f\xe0-\xfc])/", rb"\1\\", raw) + if fixed != raw: + tries.append(fixed) + out = [] + for r in tries: + for enc in (first, "gbk", "cp932", "utf-8"): + try: + name = r.decode(enc) + except UnicodeDecodeError: + continue + if name not in out: + out.append(name) + if not out: + return [raw.decode(first, "replace")] + + def common(n): + k = 0 + for ch in n: + try: + ch.encode("gb2312") + k += 1 + except UnicodeEncodeError: + pass + return k + order = {n: i for i, n in enumerate(out)} + out.sort(key=lambda n: (-common(n), order[n])) + return out + + +def zip_members(zf): + """→ [(ZipInfo, [候选文件名, …])],第一个是默认用的。 + + 没设 UTF-8 标志的压缩包,文件名是打包那台电脑的本地编码(中文系统 GBK,日文系统 cp932), + 而且同一个包里可能两种混着(作者的日文原文件 + 后加的中文文件)。先给整包选一种主编码 + (严格解得通、且「像正常中日文」得分最高的),每个文件再按常用字多少挑解法(见 _decodings), + 解压后还会用 PMX 里记录的贴图路径纠正(见 extract_zip)。 + """ + infos = zf.infolist() + legacy = [i.filename.encode("cp437") for i in infos if not i.flag_bits & 0x800] + best, best_score = "gbk", None + for enc in ("utf-8", "gbk", "cp932"): + try: + text = "".join(r.decode(enc) for r in legacy) + except UnicodeDecodeError: + continue + sc = _score(text) + (len(text) if enc == "utf-8" else 0) # 严格 UTF-8 解得通基本就是它 + if best_score is None or sc > best_score: + best, best_score = enc, sc + return [(i, [i.filename] if i.flag_bits & 0x800 else _decodings(i.filename.encode("cp437"), best)) + for i in infos] + + +def _safe_parts(name): + parts = [p for p in name.replace("\\", "/").split("/") if p not in ("", ".", "..")] + if parts and ":" in parts[0]: # 盘符 + parts = parts[1:] + return parts + + +def extract_zip(path, dest): + """安全解压(去掉绝对路径和 ..,不会写到 dest 外面),返回解出的文件数。 + + 文件名按 zip_members 的默认解码落盘后,再读每个 PMX:某个文件换一种解码正好是 PMX 引用的 + 贴图路径(或 PMX 自己的模型名),就改成那个名字——否则贴图对不上,转出来没有贴图。 + """ + import pmxio + entries = [] # (落盘相对路径, [候选相对路径]) + n = 0 + with zipfile.ZipFile(path) as zf: + for info, names in zip_members(zf): + if info.is_dir(): + continue + cands = ["/".join(_safe_parts(x)) for x in names] + cands = [c for c in cands if c] + if not cands: + continue + target = os.path.join(dest, *cands[0].split("/")) + os.makedirs(os.path.dirname(target), exist_ok=True) + with zf.open(info) as src, open(target, "wb") as f: + shutil.copyfileobj(src, f) + entries.append((cands[0], cands)) + n += 1 + if all(len(c) == 1 for _, c in entries): + return n + wanted = set() # PMX 期望存在的相对路径(小写) + pmx_names = {} # PMX 相对路径 → 内部模型名 + for rel, _ in entries: + if not rel.lower().endswith(".pmx"): + continue + try: + m = pmxio.read_pmx(os.path.join(dest, *rel.split("/"))) + except Exception: # noqa: BLE001 读不了就不纠正 + continue + base = rel.rsplit("/", 1)[0] + "/" if "/" in rel else "" + for t in m["textures"]: + wanted.add((base + "/".join(_safe_parts(t))).lower()) + pmx_names[rel] = (m.get("name") or "").strip() + for rel, cands in entries: + if len(cands) < 2: + continue + fix = None + if rel.lower() not in wanted: + fix = next((c for c in cands[1:] if c.lower() in wanted), None) + if fix is None and rel in pmx_names: + stem = lambda c: os.path.splitext(c.rsplit("/", 1)[-1])[0] + if stem(rel) != pmx_names[rel]: + fix = next((c for c in cands[1:] if stem(c) == pmx_names[rel]), None) + if fix: + os.renames(os.path.join(dest, *rel.split("/")), os.path.join(dest, *fix.split("/"))) + return n + + +GAMES = {"崩坏:星穹铁道": "星穹铁道"} # 下载站的游戏名 → 简称 + + +def nice_name(stem): + """「<名字>_by_<游戏>_<哈希>」(模之屋的下载命名)→「<游戏>—<名字>」,去掉「(修模绑骨后)」 + 这类说明和结尾的版本号;「(星)」这种有意义的括号保留。其它名字原样返回。""" + name, sep, rest = stem.partition("_by_") + if not sep: + return stem + game = rest.rsplit("_", 1)[0] + game = GAMES.get(game, game) + name = name.strip("【】") + m = re.search(r"[((][^((]*$", name) + if m and re.search(r"修|绑|更新|版", m.group()): + name = name[:m.start()] + name = re.sub(r"\d+(\.\d+)*$", "", name) + for pre in (game + "—", game + "_"): + if name.startswith(pre): + name = name[len(pre):] + return game + "—" + name.strip("_— ") + + +def output_dir(path, opts): + """按 output 选项决定这个源文件的输出目录(会建好)。""" + o = opts["output"] + if o.get("mode") == "folder" and o.get("folder"): + base = o["folder"] + elif o.get("mode") == "app" and o.get("app_folder"): + base = o["app_folder"] + else: + base = os.path.dirname(os.path.abspath(path)) + if o.get("subfolder", True): + stem = nice_name(os.path.splitext(os.path.basename(path))[0]) + day = time.strftime("%Y%m%d") + for n in range(1, 10000): + d = os.path.join(base, "%s_%s_%03d" % (stem, day, n)) + if not os.path.exists(d): + base = d + break + os.makedirs(base, exist_ok=True) + return base + + +class _LogWriter(io.TextIOBase): + """把 print() 的输出转成 log 回调(fbx2pmx 用 print 汇报进度)。""" + + def __init__(self, log): + self._log = log + self._buf = "" + + def write(self, s): + self._buf += s + while "\n" in self._buf: + line, self._buf = self._buf.split("\n", 1) + if line.strip(): + self._log(line.rstrip(), None) + return len(s) + + def flush(self): + if self._buf.strip(): + self._log(self._buf.rstrip(), None) + self._buf = "" + + +def _fmt_opts(opts, kind): + """某个输入格式的选项。转 VRM 时格式自己的「导出表情」跟着 VRM 的「表情」开关走(界面里只显示那一个; + 格式的开关只在「只转 PMX」时显示和生效)。""" + o = opts[kind] + if opts["target"] != "pmx" and "morphs" in o: + o = dict(o, morphs=opts["vrm"]["morphs"]) + return o + + +def to_pmx(path, kind, out_dir, opts, log): + """非 PMX 输入 → PMX,返回写出的 PMX 路径列表(unitypackage 可能有多个)。""" + stem = os.path.splitext(os.path.basename(path))[0] + # 有的转换器只在拷贝贴图时才建输出目录:没有贴图的模型(白模)写 PMX 时目录还不存在 + os.makedirs(out_dir, exist_ok=True) + if kind in ("fbx", "unitypackage"): + fbxs, dest = _unpack_fbxs(path, log) if kind == "unitypackage" else ([path], None) + try: + return _fbxs_to_pmx(fbxs, out_dir, _fmt_opts(opts, "fbx"), log) + finally: + if dest: + shutil.rmtree(dest, ignore_errors=True) + out = os.path.join(out_dir, stem + ".pmx") + if kind == "uemodel": + import uemodel2pmx + o = opts["uemodel"] + uemodel2pmx.convert(path, out, scale_mode="auto", log=log, name=stem, + remove_alpha=o["alpha"], align_to=o.get("align_ref") or None, + force_double_sided=opts["vrm"]["double_sided"]) + elif kind == "psk": + import psk2pmx + o = _fmt_opts(opts, "psk") + psk2pmx.convert(path, out, scale_mode="auto", log=log, name=stem, + jp_bones=o["jp_bones"], make_ik=o["ik"], export_morphs=o["morphs"], + remove_alpha=o["alpha"], force_double_sided=opts["vrm"]["double_sided"]) + elif kind == "xps": + import xps2pmx + o = opts["xps"] + xps2pmx.convert(path, out, scale_mode="auto", log=log, name=stem, + jp_bones=o["jp_bones"], make_ik=o["ik"], hide_unused=o["hide_unused"], + all_double_sided=o["double_sided"], enable_edge=o["edge"], + force_double_sided=opts["vrm"]["double_sided"]) + else: + raise ValueError("不支持的输入:%s" % kind) + return [out] + + +def _unpack_fbxs(path, log): + """unitypackage 解到临时目录(几百个资源文件,转完就删)→ ([FBX,大的在前], 临时目录)。""" + from unitypackage_unpack import unpack + dest = tempfile.mkdtemp(prefix="vrmify_unitypackage_") + with contextlib.redirect_stdout(_LogWriter(log)): + unpack(path, dest, verbose=False) + n = sum(len(fs) for _, _, fs in os.walk(dest)) + fbxs = [p for p in find_files(dest, ".fbx") if os.path.getsize(p) > 1024] + log("解包 %s:%d 个文件,%d 个 FBX" % (os.path.basename(path), n, len(fbxs)), "info") + if not fbxs: + shutil.rmtree(dest, ignore_errors=True) + raise RuntimeError("包中没有 FBX 文件") + fbxs.sort(key=lambda p: -os.path.getsize(p)) + return fbxs, dest + + +def _unique_names(paths): + """包里每个模型的输出名(文件名去掉扩展名);不同文件夹下的同名模型加 _2、_3,免得输出互相覆盖。""" + names, used = [], set() + for p in paths: + base = name = os.path.splitext(os.path.basename(p))[0] + k = 2 + while name.lower() in used: + name = "%s_%d" % (base, k) + k += 1 + used.add(name.lower()) + names.append(name) + return names + + +def _fbx_to_pmx(fbx, out, name, o, log): + """→ fbx2pmx.convert 的统计(其中 ["alpha"]["png_alpha"] 是已经算好的贴图透明统计)。""" + import fbx2pmx + log("读取 FBX:%s" % os.path.basename(fbx), "info") + w = _LogWriter(log) + with contextlib.redirect_stdout(w): + scene = fbx2pmx.Scene(fbx) + st = fbx2pmx.convert(scene, out, scale_mode="auto", flip_z=o["flip_z"], + name=name, center=o["center"], morphs=o["morphs"], + alpha_mode=o["alpha"], auto_facing=o["auto_facing"], + face_180=o["face_180"], threads=parallel.threads()) + w.flush() + return st + + +def _fbxs_to_pmx(fbxs, out_dir, o, log): + """FBX → PMX(写进 out_dir,贴图在 out_dir/textures),返回 PMX 路径列表。""" + outs = [] + for fbx, name in zip(fbxs, _unique_names(fbxs)): + out = os.path.join(out_dir, name + ".pmx") + _fbx_to_pmx(fbx, out, name, o, log) + outs.append(out) + return outs + + +def fbx_to_vrm(fbx, name, out_dir, opts, log, edits=None): + """一个 FBX → VRM;中间的 PMX 和贴图放自己的临时目录。→ [VRM 路径],被「只转换人物」跳过时为 []。 + 并行时在子进程里跑(parallel.run)。""" + import pmxio + work = tempfile.mkdtemp(prefix="vrmify_work_") + try: + pmx = os.path.join(work, name + ".pmx") + st = _fbx_to_pmx(fbx, pmx, name, _fmt_opts(opts, "fbx"), log) + n_ol = st.get("unity_outline", 0) if opts["vrm"].get("unity_outline", True) else 0 + if n_ol: + # Unity 材质里的描边是源模型的设定,跟「描边(按 PMX 轮廓线)」这个针对 MMD + # 模型的开关无关,所以单独透传,避免用户没勾那个选项时描边被整条丢掉。 + log("材质:%d 个 Unity 材质开了描边(_Outline_Width),已转成 MToon 轮廓线" % n_ol, "info") + # 中间的 PMX 只读一次,「是不是人物」的检查和转 VRM 共用 + return _to_vrm(pmx, out_dir, opts, log, edits=edits, model=pmxio.read_pmx(pmx), + tex_alpha=st["alpha"]["png_alpha"], unity_outline=bool(n_ol), + step="PMX → VRM:%s.pmx" % name) + finally: + shutil.rmtree(work, ignore_errors=True) + + +def _to_vrm(pmx, out_dir, opts, log, name=None, edits=None, model=None, step=None, **known): + """PMX → [VRM 路径]。opts["vrm"]["avatar_only"] 时先看是不是人物(not_an_avatar),不是就跳过、返回 []; + 检查用的模型和顶点权重接着给转换用。step:确定要转时先记一行日志。known 见 pmx_to_vrm。""" + if opts["vrm"].get("avatar_only", True): + import pmxio + from vrmconv import mesh + if model is None: + model = pmxio.read_pmx(pmx) + weights = mesh.vertex_weights(model["vertices"], len(model["bones"]), {}) + why = not_an_avatar(model, weights) + if why: + log("跳过 %s:%s(如需转换,请在「转换」页关闭「只转换人物」)" + % (name or os.path.splitext(os.path.basename(pmx))[0], why), "warn") + return [] + known["raw_weights"] = weights + if step: + log(step, "info") + return [pmx_to_vrm(pmx, out_dir, opts, log, name=name, edits=edits, model=model, **known)] + + +def _fbxs_to_vrm(fbxs, out_dir, opts, log, edits=None, name=None): + """几个 FBX(unitypackage 里常有好几套服装)→ VRM(见 _convert_each)。 + name:只有一个 FBX 时用它当输出名(压缩包里有同名模型时由调用方改过名)。""" + names = [name] if name and len(fbxs) == 1 else _unique_names(fbxs) + if len(fbxs) == 1: + return fbx_to_vrm(fbxs[0], names[0], out_dir, opts, log, edits=edits) + return _convert_each([(fbx_to_vrm, (fbx, names[i], out_dir, opts), {"edits": edits}) + for i, fbx in enumerate(fbxs)], names, [os.path.getsize(f) for f in fbxs], opts, log, + "包中") + + +SMALL_MODEL = 1 << 20 # 输入文件小于 1 MB 的模型(道具、配件)转得比开子进程还快,不为它们并行 +UNKNOWN_GB = 1.0 # 看不到里面的包(unitypackage / 7z / rar / tar)按这么多估 + + +def _model_gb(size): + """一个模型文件(PMX / FBX / …,size 字节)转换时的进程内存峰值估计(GB)。 + 实测 VRM 1.0(主要花在 PMX 读进来的逐顶点字典上):PMX 约 0.09 GB + 文件大小 × 28 + (爱弥斯 16 MB → 0.51 GB,开拓者 2.2 MB → 0.15 GB);FBX 更省(12 MB → 0.14 GB)。按 × 35 估、留余量。""" + return min(parallel.GB_PER_JOB, 0.15 + size * 35 / 1024 ** 3) + + +def memory_estimate(path): + """转换这个文件时的进程内存峰值估计(GB),给 parallel.jobs_for 决定同时转几个。 + 压缩包里的模型是一个一个转的,按最大的那个估:zip 直接看目录;看不到里面的按 UNKNOWN_GB + (Marycia 154 MB 的 unitypackage 实测峰值 0.44 GB)。""" + kind = classify(path) + try: + if kind == "zip": + with zipfile.ZipFile(path) as zf: + infos = zf.infolist() + inner = [classify(i.filename) for i in infos] + if any(k in ARCHIVES or k == "unitypackage" for k in inner): + return UNKNOWN_GB + sizes = [i.file_size for i, k in zip(infos, inner) if k in CONVERTIBLE] + return _model_gb(max(sizes)) if sizes else UNKNOWN_GB + if kind in ARCHIVES or kind == "unitypackage": + return UNKNOWN_GB + return _model_gb(os.path.getsize(path)) + except (OSError, zipfile.BadZipFile, ValueError): + return UNKNOWN_GB + + +def _convert_each(tasks, names, sizes, opts, log, where): + """几个模型(unitypackage 里的几套服装、压缩包里的几个模型)→ 输出路径列表:能并行时同时转, + 各自的日志前面带上模型名(parallel.run);某个模型失败不影响其它的,都失败才报错。 + + tasks:[(func, args, kwargs)],按 func(*args, log=…, **kwargs) 调用、返回输出路径列表; + func 要是模块顶层函数(子进程按名字导入)。names / sizes:每个任务的模型名、输入文件大小。 + where:日志里说「包里」还是「压缩包里」。 + """ + if len(tasks) == 1: # 只有一个:直接转,出错照常抛出 + func, args, kw = tasks[0] + return func(*args, log=log, **kw) + big = sum(1 for s in sizes if s >= SMALL_MODEL) # 一个人物 + 几个小道具:一个一个转更快 + jobs = parallel.jobs_for(big, opts.get("jobs"), [_model_gb(s) for s in sizes if s >= SMALL_MODEL]) if big > 1 else 1 + keyed = [(i,) + tuple(t) for i, t in enumerate(tasks)] + if jobs > 1: + log("%s共有 %d 个模型,并行转换 %d 个" % (where, len(tasks), jobs), "info") + results = parallel.run(keyed, jobs, lambda i: (lambda m, t=None: log("[%s] %s" % (names[i], m), t))) + else: + results = {} + for i, func, args, kw in keyed: + try: + results[i] = (True, func(*args, log=log, **kw)) + except Exception as e: # noqa: BLE001 一个模型失败不影响其它的 + results[i] = (False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc())) + outs, errors = [], [] + for i in range(len(tasks)): + ok, r = results.get(i, (False, ("没有执行", ""))) + if ok: + outs += r + else: + errors.append(r[0]) + log("%s 转换失败:%s" % (names[i], r[1] or r[0]), "err") + if errors and not outs: + raise RuntimeError(errors[0]) + return outs + + +def find_files(root, ext): + return [os.path.join(d, f) for d, _, fs in os.walk(root) for f in fs if f.lower().endswith(ext)] + + +def pmx_to_vrm(pmx, out_dir, opts, log, name=None, edits=None, **known): + """PMX → VRM,返回 VRM 路径。edits:界面里对这个模型做的调整(见 vrm_edit),转完套上。 + known:调用方已经读好 / 算好的 model、raw_weights、tex_alpha(见 pmx2vrm.convert)。""" + import pmx2vrm + o = opts["vrm"] + stem = name or os.path.splitext(os.path.basename(pmx))[0] + out = os.path.join(out_dir, stem + ".vrm") + spec = "1.0" if str(o["spec"]).startswith("1") else "0.x" + meta = dict(opts.get("meta") or {}, title=stem) + pmx2vrm.convert(pmx, out, spec=spec, meta=meta, log=log, + max_morphs=None if o["morphs"] else 0, + force_double_sided=o["double_sided"], tpose=o["tpose"], + outline=o["outline"], spring=o["spring"], spring_skirt=o["spring_skirt"], + spring_stiffness=float(o["spring_stiffness"]), + tex_max=int(o.get("tex_max") or 0), tex_jpeg=bool(o.get("tex_jpeg")), + tex_no_mip=bool(o.get("tex_no_mip", False)), + auto_spring=bool(o.get("auto_spring", True)), gaze=bool(o.get("gaze", True)), + combo_expr=bool(o.get("combo_expr", True)), extra_expr=bool(o.get("extra_expr", True)), + collapse_bones=bool(o.get("collapse_bones", True)), threads=parallel.threads(), **known) + if edits: + import vrm_edit + if not vrm_edit.is_empty(edits): + n = vrm_edit.apply(out, edits) + log("已应用保存的调整(%d 项)" % n, "info") + return out + + +def convert_file(path, opts=None, log=None, out_dir=None, edits=None): + """转换一个文件,返回输出文件列表。out_dir 不给时按 opts["output"] 决定; + edits:这个文件在界面里的调整(vrm_edit),套到每个输出的 VRM 上。""" + opts = merged(opts) + log = log or (lambda m, t=None: None) + kind = classify(path) + if kind not in CONVERTIBLE: + raise ValueError("无法转换此文件:%s" % os.path.basename(path)) + out_dir = out_dir or output_dir(path, opts) + log("→ %s" % os.path.basename(path), "head") + log("输出目录:%s" % out_dir, "info") + if kind in ARCHIVES: + return _convert_archive(path, kind, out_dir, opts, log, edits) + return _convert_model(path, kind, out_dir, opts, log, edits) + + +def extract_archive(path, kind, dest, log=None): + """解压任意支持的压缩包,返回文件数。""" + if kind == "zip": + return extract_zip(path, dest) + return archive.extract(path, dest, log) + + +def _convert_archive(path, kind, out_dir, opts, log, edits=None): + tmp = tempfile.mkdtemp(prefix="vrmify_%s_" % kind) + try: + n = extract_archive(path, kind, tmp, log) + found = find_inputs(tmp) + inner = [p for p in found if classify(p) in CONVERTIBLE - ARCHIVES] + if not inner: # 包里套包(zip 里放 7z 之类):再解一层 + for i, p in enumerate(x for x in found if classify(x) in ARCHIVES): + sub = os.path.join(tmp, "__inner%d" % i) + log("解压内层压缩包 %s" % os.path.relpath(p, tmp), "info") + n += extract_archive(p, classify(p), sub, log) + inner += [q for q in find_inputs(sub) if classify(q) in CONVERTIBLE - ARCHIVES] + pmx = [p for p in inner if classify(p) == "pmx"] + todo = pmx or inner # 有 PMX 就只转 PMX(同包里的 FBX 等通常是同一个模型) + log("解压出 %d 个文件,其中模型 %d 个:%s" % (n, len(todo), "、".join( + os.path.relpath(p, tmp) for p in todo)), "info") + if not todo: + raise RuntimeError("压缩包中没有可转换的模型(PMX / FBX / uemodel / psk / xps)") + names = _unique_names(todo) + # 只转 PMX 时几个模型的贴图都写进输出目录的同一个 textures 文件夹:一个一个转 + each = dict(opts, jobs=1) if opts["target"] == "pmx" else opts + return _convert_each([(_convert_inner, (p, os.path.relpath(p, tmp), out_dir, opts), + {"edits": edits, "name": names[i]}) for i, p in enumerate(todo)], + names, [os.path.getsize(p) for p in todo], each, log, "压缩包中") + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +def _convert_inner(path, rel, out_dir, opts, log, edits=None, name=None): + """压缩包里的一个模型(rel:在包里的相对路径,日志用)。并行时在子进程里跑(见 _convert_each)。""" + log("→ %s" % rel, "head") + return _convert_model(path, classify(path), out_dir, opts, log, edits, name=name) + + +def _convert_model(path, kind, out_dir, opts, log, edits=None, name=None): + """name:转 VRM 时的输出名(不给时用文件名;unitypackage 里的几个模型各用各的文件名)。""" + if kind == "pmx": + return _to_vrm(path, out_dir, opts, log, name=name, edits=edits) + if opts["target"] == "pmx": # 只转 PMX:道具在 MMD 里照样有用,不挑 + pmxs = to_pmx(path, kind, out_dir, opts, log) + for p in pmxs: + log("已写出 %s" % os.path.basename(p), "ok") + return pmxs + # 转 VRM 时中间的 PMX 和它的贴图只是过渡:放临时目录,转完删掉,输出目录只留 VRM + if kind in ("fbx", "unitypackage"): + fbxs, dest = _unpack_fbxs(path, log) if kind == "unitypackage" else ([path], None) + try: + return _fbxs_to_vrm(fbxs, out_dir, opts, log, edits, name=name if kind == "fbx" else None) + finally: + if dest: + shutil.rmtree(dest, ignore_errors=True) + work = tempfile.mkdtemp(prefix="vrmify_work_") + try: + outs = [] + for p in to_pmx(path, kind, work, opts, log): + outs += _to_vrm(p, out_dir, opts, log, name=name, edits=edits, + step="PMX → VRM:%s" % os.path.basename(p)) + return outs + finally: + shutil.rmtree(work, ignore_errors=True) + + +def not_an_avatar(model, weights=None): + """看起来不是人物时返回原因,否则 None(「只转换人物」用)。 + + * 道具:骨架里认不出头或腰(剑、椅子、请柬……一般只有一两根骨)。模之屋的模型包里常带着。 + * 只有衣服 / 配件:VRChat 等的模型包里常有单独的服装 FBX,骨架是完整的,网格只有衣服。判断: + 头部(头骨及其子骨,包括头发、眼睛)没挂任何顶点,或者两只手都没挂顶点(认不出手时不看手)。 + model:PMX 路径或读好的模型(pmxio.read_pmx);weights:已经算好的不带别名的顶点权重。 + """ + import pmxio + from vrmconv import mesh + from vrmconv.humanoid import _map_humanoid + m = model if isinstance(model, dict) else pmxio.read_pmx(model) + human = _map_humanoid(m["bones"], True, {}) + parents = [b["parent"] for b in m["bones"]] + + def subtree(root): + out, grew = {root}, True + while grew: + grew = False + for i, p in enumerate(parents): + if p in out and i not in out: + out.add(i) + grew = True + return out + + if "head" not in human or "hips" not in human: + return "未识别到人形骨架,可能是道具" + if weights is None: + weights = mesh.vertex_weights(m["vertices"], len(m["bones"]), {}) + used = {b for wl in weights for b, w in wl if w > 0.3} + if not used & subtree(human["head"]): + return "头部没有网格,可能只有服装或配件" + hands = [human[h] for h in ("leftHand", "rightHand") if h in human] + if len(hands) == 2 and not used & (subtree(hands[0]) | subtree(hands[1])): + return "手部没有网格,可能只有服装或配件" + return None diff --git a/convert/pmx2vrm.py b/convert/pmx2vrm.py new file mode 100644 index 0000000..e29a8e2 --- /dev/null +++ b/convert/pmx2vrm.py @@ -0,0 +1,492 @@ +# -*- coding: utf-8 -*- +"""pmx2vrm.py - 把 PMX 模型转成 VRM(glTF 2.0 / GLB 容器),纯 Python 标准库。 + +不需要 Blender、不需要 mmd_tools、不需要 Unity。 + +坐标约定(数值均指文件里存的原始数字) +-------- +PMX(MMD) 正面 -Z,角色左手侧 +X,Y 向上(DirectX 左手系,逆时针缠绕) +VRM 0.x 正面 -Z,角色左手侧 -X,Y 向上(glTF 右手系、逆时针为正面) +VRM 1.0 正面 +Z,角色左手侧 +X,Y 向上 + +所以: + * PMX(DirectX 左手系)与 glTF(右手系)手性相反:同一组数字直接 + 解释是镜像人形,必须反射一个轴——转 0.x 取反 X;转 1.0 取反 Z。 + * 两种情况三角绕序都要反转(反射把「外面看逆时针」颠倒了)。 + * 尺寸:MMD 模型约 20 单位高,VRM 用米,默认按 1.6 m 归一。 + +用法: + python pmx2vrm.py model.pmx -o model.vrm + python pmx2vrm.py model.pmx --spec 0x --title "名字" --author "作者" +""" +import argparse +import os +import sys + +# 让 `python convert/pmx2vrm.py ...` 也能直接跑:脚本自己所在目录(convert/)和同级的 +# formats/ 都要进 sys.path。以前这里只加了 convert/,于是 `import pmxio` 之类会 +# ModuleNotFoundError —— 而 README 里给的命令行用法就是这么调的。 +_HERE = os.path.dirname(os.path.abspath(__file__)) +for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")): + if _p not in sys.path: + sys.path.insert(0, _p) +import pmxio # noqa: E402 +import vrmio # noqa: E402 +from vrmconv import autophys, checks, expressions, mesh, morphbake, skeleton, springbone_v0, textures, vrm_ext # noqa: E402 +from vrmconv.materials import MaterialBuilder # noqa: E402 +from vrmconv.springbone import _build_springs # noqa: E402 + + +# ---------------------------------------------------------------- 主流程 -- +def convert(pmx_path, vrm_path, spec="1.0", scale_mode="auto", + rotate="auto", reverse_winding="auto", meta=None, + max_morphs=None, log=None, force_double_sided=False, + tpose=False, outline=False, unity_outline=False, sparse_morphs=True, + spring=True, spring_skirt=True, spring_stiffness=1.0, + spring_gravity=0.0, spring_gravity_skirt=0.1, spring_center=True, + spring_opts=None, tex_max=0, tex_jpeg=False, tex_no_mip=False, auto_spring=True, gaze=True, + combo_expr=True, extra_expr=True, collapse_bones=True, model=None, raw_weights=None, tex_alpha=None, + threads=4): + """PMX → VRM,返回统计 dict。log(msg, tag=None) 用于输出进度。 + + 各阶段在 vrmconv/ 里:skeleton(骨骼、T-pose、节点)→ springbone(物理)→ + mesh + materials(网格、MToon)→ expressions(表情)→ vrm_ext(VRM 扩展)。 + + auto_spring:模型完全没有物理刚体时,按骨骼名 / 结构自动补(vrmconv/autophys)。 + tex_max / tex_jpeg:贴图最大边长(0 = 原样)/ 不透明贴图改存 JPEG(需要 Pillow,见 vrmconv/textures)。 + tex_no_mip:贴图采样器禁用 mipmap,缓解 UV 岛无 gutter 时沿接缝渗出的白边(默认 False)。 + gaze:有左右眼骨时补 lookUp / lookDown / lookLeft / lookRight 表情(转眼骨烘焙成顶点偏移, + 见 vrmconv/morphbake;模型自己有对应表情时不补)。 + combo_expr:情绪预设(happy / angry / sad / relaxed / surprised)组合眉、眼、嘴的表情, + 像 VRoid 一样整张脸一起变(见 vrmconv/expressions.COMBO);False 时每个预设只对应一个表情。 + extra_expr:补充自定义表情 hideHighlight(关掉眼睛高光)和 tongue(吐舌),见 expressions.add_extras。 + collapse_bones:没有权重的中间骨(全ての親 / センター / グルーブ / 腰 / 肩P 之类)也去掉, + 层级像 VRoid(Root > Hips);False 时留着它们(连接保留骨所需的祖先)。IK、合并掉的付与骨、末端骨这类完全不起作用的骨总会去掉(见 _prune_nodes)。 + meta:title / author / version / contact / copyright / license_url / avatar_permission / + commercial_usage / credit_notation / allow_redistribution / modification(见 vrm_ext)。 + model / raw_weights / tex_alpha:调用方已经有的,省得再算一遍——读好的 PMX(pmxio.read_pmx, + 会被改动)、不带付与别名的顶点权重(mesh.vertex_weights(..., {}))、贴图透明统计 + {normcase 绝对路径: vrmio.png_alpha_stats 的结果}(FBX 转换判断透明时已经解过贴图)。 + threads:同时处理几张贴图(解码、瘦身)。 + + reverse_winding: + "auto"(默认)——用「几何面法线 vs 顶点法线」投票自动判定; + True / False ——手动强制反转 / 不反转。 + + 手性说明(2026-09-18 重写):PMX(MMD / DirectX 左手系)数值上 + 脸朝 -Z、左手在 +X;同一组数字按 glTF 右手系直接解释是镜像人形, + 必须做一次镜面反射(0.x 取反 x;1.0 取反 z)。反射会把 + 「从外面看逆时针」颠倒成顺时针,所以 auto 绕序判定(用反射后的 + 数据投票)正常会判「反转」。以前不做反射(或用 y180 纯旋转, + 旋转改不了手性)会让转出的模型左右翻转。 + """ + # 确保输出目录存在(CLI 直接调用时尤其容易漏建) + _odir = os.path.dirname(os.path.abspath(vrm_path)) + try: + os.makedirs(_odir, exist_ok=True) + except OSError as e: + raise OSError("无法创建输出目录 %s:%s" % (_odir, e)) + + def _log(msg, tag=None): + if log is not None: + try: + log(msg, tag) + except TypeError: + log(msg) + + if model is None: + model = pmxio.read_pmx(pmx_path) + skeleton.fix_facing(model, _log) + base_dir = os.path.dirname(os.path.abspath(pmx_path)) + verts = model["vertices"] + bones = model["bones"] + faces = model["faces"] + materials = model["materials"] + is1 = str(spec).startswith("1") + + # ---- 缩放 + if scale_mode in ("auto", "mmd", None, ""): + ys = [v["pos"][1] for v in verts] or [0.0] + height = max(ys) - min(ys) + scale = (1.6 / height) if height > 1e-6 else 0.08 + else: + scale = float(scale_mode) + + # ---- 手性修正(2026-09-18 重写,别改回「绕 Y 旋转 180°」) + # PMX(左手系)数值:脸 -Z、左手 +X(实测小食Taberu: + # 両目 Z=-0.75,左腕 X=+1.34 / 右腕 X=-1.34)。 + # glTF(右手系)里合法人形:脸 -Z ⇒ 左手 -X;脸 +Z ⇒ 左手 +X。 + # 所以必须反射一个轴:0.x(脸 -Z)取反 x;1.0(脸 +Z)取反 z。 + # y180 是纯旋转,改不了手性 → 转出的 VRM 左右翻转(实测 Blender 可见)。 + # rotate="none" 仅用于调试(原样输出,左右是反的)。 + if rotate in ("auto", "y180", None, ""): # y180 为旧值,视同 auto + mx, mz = (1.0, -1.0) if is1 else (-1.0, 1.0) + else: # "none" + mx, mz = 1.0, 1.0 + + def xf(p): + x, y, z = p + return (x * mx * scale, y * scale, z * mz * scale) + + def xf_dir(p): + x, y, z = p + return (x * mx, y, z * mz) + + def unit(left_amount, up_amount, front_amount): + if is1: # VRM 1.0:左 +X、前 +Z + return (left_amount, up_amount, front_amount) + return (-left_amount, up_amount, -front_amount) + + _log("PMX:顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d" + % (len(verts), len(faces) // 3, len(bones), len(materials), + len(model["morphs"]))) + + # ---- 骨骼预处理(都在 PMX 坐标里做,最后统一过 xf):付与骨合并、humanoid、T-pose + # 骨骼表情烘焙用不带别名的权重,网格用带别名的:先算前者,后者只重算挂在别名骨上的顶点 + if raw_weights is None: + raw_weights = mesh.vertex_weights(verts, len(bones), {}) + bs = skeleton.prepare_bones(bones, is1, _log, weighted={b for wl in raw_weights for b, w in wl if w > 0}) + vweights = mesh.vertex_weights(verts, len(bones), bs.alias, base=raw_weights) + for n, rb, rp, lb, lp in mesh.mirror_mismatches(verts, raw_weights, vweights, bs.human_b): + _log("权重:左右对称的 %d 对顶点,右侧主要绑在 %s(%s),左侧却绑在 %s(%s)," + "动作时这部分会变形。可能是模型的权重错误,建议在 PmxEditor 中检查" + % (n, bones[rb]["name"], mesh.LIMB_PART.get(rp, rp), bones[lb]["name"], + mesh.LIMB_PART.get(lp, lp)), "warn") + glob, bpos, vpos, vnrm, vmat = skeleton.apply_tpose(verts, bones, bs, vweights, tpose, _log) + + # ---- 缠绕顺序自动判定:必须用「镜像后」的数据投票。 + # 镜像反射会把「从外面看逆时针」颠倒成顺时针,所以正常情况下 + # auto 在这里会判定为「需要反转」——这不是回到老 bug, + # 老 bug 是「没有反射时硬编码反转」。 + if reverse_winding in ("auto", None, ""): + flip, ag, dis = pmxio.detect_winding( + [xf(p) for p in vpos], [xf_dir(n) for n in vnrm], faces) + reverse_winding = bool(flip) + _log("绕序自动判定(手性修正后):与法线同向 %d 面 / 反向 %d 面 → %s" + % (ag, dis, "需要反转" if flip else "保持不变")) + else: + reverse_winding = bool(reverse_winding) + + _log("缩放:%.5f(MMD 单位 → 米)· 手性修正:%s · 绕序:%s" + % (scale, + ("Z 轴取反" if is1 else "X 轴取反") if (mx, mz) != (1.0, 1.0) else "无", + "反转" if reverse_winding else "保持不变")) + + # ---- 骨骼 → glTF 节点;humanoid 缺的必需骨位补占位 + tree = skeleton.NodeTree(bones, bs, bpos, xf) + # 0.x 的两节拇指(没有掌根那节):补上 ThumbProximal,和 1.0 一样从第二节(Intermediate)开始对应 + roots = [] if is1 else [s + "ThumbProximal" for s in ("left", "right") + if s + "ThumbIntermediate" in bs.human_b and s + "ThumbProximal" not in bs.human_b] + human = tree.humanoid(bs.human_b, bs.required, unit, _log, roots) + tree.lower_hips(human, _log) + + # ---- PMX 物理 → SpringBone(1.0 写 VRMC_springBone;0.x 由同一份结果换算成 secondaryAnimation) + spring_ext = None + if spring and auto_spring and autophys.needed(model): + autophys.synthesize(model, bs.parents, bs.alias, bs.human_b, _log) + # 按比例跟随的付与骨拆权重:放在自动补物理之后,补出来的摆动骨也算带物理、不拆 + vweights = skeleton.split_partial(bones, bs, vweights, model.get("rigid_bodies"), _log) + checks.report(bones, bs, raw_weights, vweights, bpos, vpos, scale, _log) + if spring: + spring_ext = _build_springs( + model, bs.parents, bs.alias, bs.human_b, glob, bpos, scale, xf, + tree.bone_node, tree.node_pos, tree.add_node, + include_lower=spring_skirt, stiffness_mul=spring_stiffness, + gravity=spring_gravity, gravity_lower=spring_gravity_skirt, + set_parent=tree.set_parent, cloth=(vnrm, vweights, xf_dir), log=_log, + **(spring_opts or {})) + if spring_ext and not is1: + vweights = springbone_v0.fold(tree, bones, vweights, spring_ext, human.values(), _log) + human = _prune_nodes(tree, bones, vweights, human, spring_ext, collapse_bones, _log) + nodes, top_nodes = tree.gltf_nodes() + if spring_ext and not is1: + springbone_v0.order_children(nodes, spring_ext) + + # ---- 视线转角:按眼球几何算(lookAt 和补的视线表情都用它) + look, note = None, None + if "leftEye" in bs.human_b or "rightEye" in bs.human_b: + look, note = morphbake.eye_look_range(model, vweights, bs.parents, + [bs.human_b.get("leftEye"), bs.human_b.get("rightEye")]) + if look: + _log("视线:左右 %.1f° · 下 %.1f° · 上 %.1f°(%s)" + % (look["lookLeft"], look["lookDown"], look["lookUp"], note)) + elif note: + _log("视线:" + note, "warn") + + # ---- 逐材质构建网格(材质表情会影响材质的 alphaMode,表情要先整理) + gb = vrmio.GLBBuilder() + gb.samplers.append(vrmio.default_sampler(tex_no_mip)) + gaze_extra = _gaze(model, bs.human_b, is1, gaze, _log, look) + if extra_expr and max_morphs != 0: + expressions.add_extras(model, _log) + flat = expressions._flatten_morphs(model["morphs"], model, gaze_extra, weights=raw_weights) + gaze_split = morphbake.split_gaze(flat, {n for n, _ in gaze_extra}) + # max_morphs: None = 全部;0 = 不导出;n = 只取前 n 个 + if max_morphs is not None and max_morphs >= 0: + flat = flat[:int(max_morphs)] + # unity_outline:源 Unity 材质自己开了描边(FBX → PMX 时写进了 edge 字段)。 + # 它和「按 PMX 轮廓线描边」是两回事,前者要无条件保留,后者由用户开关决定。 + mats = MaterialBuilder(model, base_dir, gb, is1, flat, outline=(outline or unity_outline), + force_double_sided=force_double_sided, + tex_opt=textures.Optimizer(tex_max, tex_jpeg), known_alpha=tex_alpha) + mats.prefetch(threads) + prims, mat_gidx = mesh.build_primitives(model, xf, xf_dir, vpos, vnrm, vweights, + reverse_winding, mats.make) + # skin.joints 只放留下的骨;JOINTS_0 从 PMX 骨序号换成在 joints 里的位置 + joint_bones = [i for i in range(len(bones)) if tree.bone_node(i) is not None] + mesh.remap_joints(prims, {b: k for k, b in enumerate(joint_bones)}) + _log("网格:按材质分为 %d 个部分" % len(prims)) + mats.log_summary(_log) + if not prims: + raise RuntimeError("此 PMX 没有可用的面数据") + mesh.write_accessors(gb, prims) + + # ---- 表情 → morph target + VRM expression + expr = expressions.build_expressions(flat, prims, mats, mat_gidx, gb, xf, vmat, + is1, sparse_morphs, _log, combo=combo_expr, + hidden={d for _, d, _ in gaze_split.values()}) + target_names = expr["target_names"] + _gaze_binds(expr, gaze_split, look, is1) + + # ---- 按表情分网格(每个网格只带动得到它的 morph target) + groups = mesh.group_meshes(prims, len(target_names)) + gltf_meshes, where = mesh.build_meshes(gb, prims, groups, target_names, + model["name"] or "body", sparse_morphs, prim_names=not is1) + if len(gltf_meshes) > 1: + _log("网格:按表情分为 %d 个(%s)" % (len(gltf_meshes), "、".join( + "%s:%d 个表情" % (m["name"], len(m.get("extras", {}).get("targetNames", ()))) for m in gltf_meshes))) + + inv = [] + for i in joint_bones: + p = tree.node_pos(tree.bone_node(i)) # 节点位置(hips 下移过) + inv.extend([1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + -p[0], -p[1], -p[2], 1.0]) + if not inv: + inv = [1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0] + ibm = gb.add_accessor(inv, vrmio.FLOAT, "MAT4", minmax=False) + + mesh_nodes = [] + taken = {n.get("name") for n in nodes} + for k, m in enumerate(gltf_meshes): + mesh_nodes.append(len(nodes)) + # 网格按材质起名,可能和骨骼重名(「髪」):Unity 里按名字找物体的会找错,加后缀 + nm = expressions.uniq_name("mesh" if len(gltf_meshes) == 1 else m["name"], taken) + taken.add(nm) + nodes.append({"name": nm, "mesh": k, "skin": 0}) + root_index = len(nodes) + nodes.append({"name": "root", + "children": list(top_nodes) + mesh_nodes}) + + joints = [tree.bone_node(i) for i in joint_bones] + if not joints: + joints = [0] + + gltf = { + "asset": {"version": "2.0", "generator": "VRMify Enhanced"}, + "scene": 0, + "scenes": [{"nodes": [root_index]}], + "nodes": nodes, + "meshes": gltf_meshes, + "skins": [{"joints": joints, "inverseBindMatrices": ibm, + "skeleton": root_index}], + "materials": mats.materials, + "accessors": gb.accessors, + "bufferViews": gb.bufferViews, + "buffers": [{"byteLength": len(gb.bin)}], + } + if gb.images: + gltf["images"] = gb.images + gltf["textures"] = gb.textures + gltf["samplers"] = gb.samplers + + # 绑定的 morph target 序号 → 各网格里的;1.0 的 node 指向网格节点,0.x 的 mesh 指向网格号 + mesh.remap_binds(expr, where, mesh_nodes, is1) + + # ---- VRM 扩展 + meta = meta or {} + title = meta.get("title") or model["name"] or "PMX Model" + if is1: + gltf["extensionsUsed"] = ["VRMC_vrm", "VRMC_materials_mtoon"] + gltf["extensions"] = {"VRMC_vrm": vrm_ext.build_vrm1(meta, title, human, + mesh_nodes, expr, look)} + if spring_ext: + if spring_center: + # center = 根节点:在模型自身的空间里模拟。应用里人物整体移动(走路的 + # 根运动、平移)时,头发/裙摆不会因惯性被甩、往后拖压到腿上,只对身体本身 + # 的动作有反应。实测走路时头发摆幅 0.73→0.15、胸部配饰 0.28→0.05、 + # 裙摆穿进大腿的顶点 10→3。规范要求 center 是链首关节或其祖先,根节点满足 + for sp in spring_ext["springs"]: + sp["center"] = root_index + gltf["extensionsUsed"].append("VRMC_springBone") + gltf["extensions"]["VRMC_springBone"] = spring_ext + else: + gltf["extensionsUsed"] = ["VRM"] + secondary = (springbone_v0.to_secondary(spring_ext, nodes, root_index if spring_center else None, _log) + if spring_ext else None) + gltf["extensions"] = {"VRM": vrm_ext.build_vrm0(meta, title, human, expr, + mats.props_0x, look, len(gltf_meshes), + secondary)} + + size = vrmio.write_glb(gltf, gb.bin, vrm_path) + n_expr = (len(expr["preset"]) + len(expr["custom"])) if is1 else len(expr["blend_groups"]) + _log("已写出 %s(%.2f MB)· 节点 %d · morph target %d · 表情 %d" + % (os.path.basename(vrm_path), size / 1048576.0, len(nodes), + len(target_names), n_expr), "ok") + return {"nodes": len(nodes), "primitives": len(prims), "meshes": len(gltf_meshes), + "morphs": len(target_names), "bytes": size, "scale": scale, + "vertices": sum(p["vcount"] for p in prims)} + + +def _prune_nodes(tree, bones, vweights, human, spring_ext, collapse, log): + """去掉不起作用的节点,返回新的 humanoid 骨位 → 节点。 + + 留下:humanoid 骨、有权重的骨、SpringBone 关节和碰撞体,以及连接它们的祖先(collapse 时祖先不留)。 + MMD 模型里 IK、合并进主骨的付与骨(足D 等)、末端骨(先)、操作中心之类的骨不带动任何顶点, + 在 VRM 里只是空节点,Blender / Unity 里看起来像一堆挂错位置的碎骨头。 + """ + if not bones: + return human + core = set(human.values()) + for wl in vweights: + for b, w in wl: + if w > 0: + core.add(tree.bone_node(b)) + refs = [] + if spring_ext: + refs = [j for sp in spring_ext["springs"] for j in sp["joints"]] + spring_ext.get("colliders", []) + core.update(o["node"] for o in refs) + before = len(tree.names) + new = tree.prune(core, collapse) + for o in refs: + o["node"] = new[o["node"]] + if before > len(tree.names): + log("骨骼:已去掉 %d 个不起作用的节点(%s),保留 %d 个" + % (before - len(tree.names), + "无权重且不属于 humanoid、物理的骨,包括中间的控制骨" if collapse + else "IK、末端骨、已合并的付与骨等无权重且不属于 humanoid、物理的骨", len(tree.names))) + return {k: new[v] for k, v in human.items()} + + +# -------------------------------------------------------------------- cli -- +def _gaze(model, human_b, is1, enabled, log, look=None): + """要补的视线表情 → [(名字, 骨骼表情 offsets)](交给 _flatten_morphs 烘焙)。""" + if not enabled or "leftEye" not in human_b or "rightEye" not in human_b: + return [] + have = set() + for mo in model["morphs"]: + p = expressions._table_preset(mo["name"], True) or expressions._preset_en(mo["name"], True) + if p: + have.add(p) + # 左右(上下)都要补时按 GAZE_MAX 烘焙,之后拆成横向 + 深度两个场、权重给出实际角度(morphbake.split_gaze); + # 只补一边的按实际角度烘焙 + deg = dict(look or morphbake.GAZE_DEG) + for a, b, axis in morphbake.GAZE_PAIRS: + if a not in have and b not in have: + deg[a] = deg[b] = morphbake.GAZE_MAX[axis] + out = [(n, offs) for n, offs in morphbake.gaze_offsets(human_b["leftEye"], human_b["rightEye"], deg) + if n not in have] + if out: + log("表情:补充视线表情 %s(由转动眼骨烘焙,lookAt 仍使用骨骼)" % " / ".join(n for n, _ in out)) + return out + + +def _gaze_binds(expr, split, look, is1): + """拆过的视线表情 → 横向场 + 深度场两个绑定,权重按实际视线角度(vrm_edit 改视线角度时同样重算)。""" + names = expr["target_names"] + for p, (tan, depth, axis) in split.items(): + wt, wd = morphbake.gaze_weights((look or morphbake.GAZE_DEG)[p], axis) + slots = [(len(names) - 1 - names[::-1].index(n), w) for n, w in ((tan, wt), (depth, wd))] + if is1: + obj = expr["preset"].get(p) + if obj and (obj.get("extras") or {}).get("source") == p: + obj["morphTargetBinds"] = [{"node": 0, "index": i, "weight": w} for i, w in slots] + else: + for gr in expr["blend_groups"]: + if gr["name"] == p and gr["presetName"] == p.lower(): + gr["binds"] = [{"mesh": 0, "index": i, "weight": round(w * 100, 4)} for i, w in slots] + + +def main(argv=None): + ap = argparse.ArgumentParser(description="PMX → VRM(纯 Python)") + ap.add_argument("pmx") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--spec", default="1.0", choices=["1.0", "0x"]) + ap.add_argument("--scale", default="auto", + help="auto(归一到 1.6 m)或具体倍率") + ap.add_argument("--rotate", default="auto", choices=["auto", "none", "y180"]) + ap.add_argument("--flip-winding", action="store_true", + help="强制反转三角形缠绕顺序(默认自动判定)") + ap.add_argument("--force-double-sided", action="store_true", + help="所有材质强制双面(模型仍有镂空时的兜底手段)") + ap.add_argument("--tpose", action="store_true", + help="把 A-pose 手臂抬成 VRM 规范的 T-pose(默认保留原始姿势,不重摆骨架)") + ap.add_argument("--keep-pose", action="store_true", help=argparse.SUPPRESS) # 旧版兼容:默认已是保留原姿势 + ap.add_argument("--no-spring", action="store_true", + help="不把 PMX 物理转成 SpringBone(默认转换,仅 VRM 1.0)") + ap.add_argument("--no-spring-skirt", action="store_true", + help="跳过下半身(hips / 腿)下的物理链,通常是裙摆") + ap.add_argument("--spring-stiffness", type=float, default=1.0, + help="SpringBone 硬度整体倍率(默认 1.0,越大越硬)") + ap.add_argument("--spring-gravity", type=float, default=0.0, + help="SpringBone 重力(头发等,默认 0:保持 PMX 原造型;" + "斜着散开的长发加重力会被拉垂)") + ap.add_argument("--spring-gravity-skirt", type=float, default=0.1, + help="下半身(裙摆)SpringBone 重力(默认 0.1,抬腿时裙片落回腿上)") + ap.add_argument("--no-auto-spring", action="store_true", + help="模型没有物理刚体时不自动补(默认按骨骼名给头发、裙摆、袖子等加 SpringBone)") + ap.add_argument("--no-combo-expr", action="store_true", + help="情绪预设不组合眉 / 眼 / 嘴(默认组合,像 VRoid;关掉时每个预设只对应一个 PMX 表情)") + ap.add_argument("--keep-control-bones", action="store_true", + help="保留没有权重的中间骨(全ての親 / センター / グルーブ / 腰 等;默认去掉,层级像 VRoid)") + ap.add_argument("--no-extra-expr", action="store_true", + help="不补充 hideHighlight(关掉眼睛高光)、tongue(吐舌)表情") + ap.add_argument("--no-gaze", action="store_true", + help="不补视线表情(默认有左右眼骨时补 lookUp / lookDown / lookLeft / lookRight)") + ap.add_argument("--no-spring-center", action="store_true", + help="SpringBone 不设 center(默认以模型根节点为 center,人物整体移动时" + "头发/裙摆不会被甩)") + ap.add_argument("--outline", action="store_true", + help="按 PMX 的轮廓线设置写出 MToon 描边(默认不描边)") + ap.add_argument("--dense-morphs", action="store_true", + help="表情用密集存储(默认稀疏存储,文件小很多)") + ap.add_argument("--max-morphs", type=int, default=None, + help="只导出前 N 个表情(0 = 不导出,默认全部)") + ap.add_argument("--tex-max", type=int, default=0, + help="贴图最大边长(如 2048 / 1024,默认 0 = 原样;需要 Pillow)") + ap.add_argument("--tex-jpeg", action="store_true", + help="不透明贴图改存 JPEG(文件小很多;需要 Pillow)") + ap.add_argument("--tex-no-mip", action="store_true", + help="贴图不生成 mipmap,缓解 UV 岛无边距时沿接缝渗出的白边(远景会有轻微锯齿)") + ap.add_argument("--title", default=None) + ap.add_argument("--author", default=None) + a = ap.parse_args(argv) + + out = a.out or (os.path.splitext(a.pmx)[0] + ".vrm") + meta = {} + if a.title: + meta["title"] = a.title + if a.author: + meta["author"] = a.author + st = convert(a.pmx, out, spec=("1.0" if a.spec == "1.0" else "0.x"), + scale_mode=a.scale, rotate=a.rotate, + reverse_winding=(True if a.flip_winding else "auto"), + meta=meta, max_morphs=a.max_morphs, + force_double_sided=a.force_double_sided, + tpose=a.tpose, outline=a.outline, + spring=not a.no_spring, spring_skirt=not a.no_spring_skirt, + spring_stiffness=a.spring_stiffness, + spring_gravity=a.spring_gravity, + spring_gravity_skirt=a.spring_gravity_skirt, + spring_center=not a.no_spring_center, auto_spring=not a.no_auto_spring, + sparse_morphs=not a.dense_morphs, + tex_max=a.tex_max, tex_jpeg=a.tex_jpeg, tex_no_mip=a.tex_no_mip, gaze=not a.no_gaze, combo_expr=not a.no_combo_expr, extra_expr=not a.no_extra_expr, + collapse_bones=not a.keep_control_bones, + log=lambda msg, tag=None: print(msg)) + print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/convert/psk2pmx.py b/convert/psk2pmx.py new file mode 100644 index 0000000..a85903c --- /dev/null +++ b/convert/psk2pmx.py @@ -0,0 +1,757 @@ +# -*- coding: utf-8 -*- +"""PSK / PSKX(Unreal ActorX)→ MMD PMX,纯 Python 标准库。 + +和项目里其它转换器保持同一套口径: + · 换轴 (x, y, z)_psk → (x, z, y)_pmx(Y/Z 对调,详见 convert() 里的长注释) + · 缩放 按包围盒高度归一到 MMD 常规的 20 单位 + · 居中 x/z 取包围盒中心、y 脚底归零 + · 骨骼 Bip001 这套 3dsMax Biped 命名默认转成 MMD 标准日文骨名, + 英文原名写进骨骼的英文名(name_en)字段,两边都不丢 + · 表情 PSK 的 MRPHINFO/MRPHDATA(顶点位移增量)→ PMX 顶点表情 + · 材质 按材质名在源目录找同名贴图;toon 一律不使用 + +骨骼世界矩阵的坑见 formats/pskio.py 头部注释(四元数要取共轭)。 +""" +import os +import re +import shutil +import sys + +BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _sub in ("formats", "convert"): + _p = os.path.join(BASE, _sub) + if os.path.isdir(_p) and _p not in sys.path: + sys.path.insert(0, _p) + +import pskio +import pmxio + + +# --------------------------------------------------------- toon(不使用) ------ +# PMX 材质的 toon 字段由「共有Toonフラグ」决定宽度,两个方向都别搞反 +# (PMX 规范 + mmd_tools 的 `is_shared_toon_texture` 一致): +# +# flag = 1 → 共享/内建 toon。字段是 **1 字节编号**,引用 MMD 安装目录 +# `Data/` 下的 toon01.bmp … toon10.bmp。 +# ⚠ **编号 0 就是 toon01.bmp,不是「不使用」**。mmd_tools 源码里 +# 写死了这个 +1: +# toon_path = "toon%02d.bmp" % (shared_toon_texture + 1) +# MMD 的 Data 目录里**根本没有 toon00.bmp**(只有 toon01..toon10), +# 所以「编号 0 = toon00.bmp = 不使用 toon」这个说法是错的。 +# +# flag = 0 → 本模型**纹理表**里的贴图。字段是**纹理索引宽度**(ti), +# **-1 = なし(不使用)**。 +# +# 所以「不使用 toon」唯一正确的写法是 `toon_flag = 0, toon = -1`。 +# +# 2026-09-24 修正:以前四个转换器都写 `flag=1, toon=0`(注释误以为 0 是 +# toon00.bmp = 不使用),实际等于给每个材质硬套了一层 **toon01.bmp**,用户反馈 +# 「PMX 文件还是自动上了 Toon 路径」。 +# 对照实测:用户本机那份公认正常的 `Anastasya.pmx`,全部 13 个材质都是 +# `toon_flag=0 / toon=-1`;而本工具产出的 `R2T1FeiBiMd10011.pmx` 是 `flag=1/0`。 +_TOON_NONE_FLAG = 0 +_TOON_NONE_INDEX = -1 + + +def _log_default(msg, tag=None): + print(msg) + + +# ------------------------------------------------------------- 骨名映射 ------ +# Bip001(3dsMax Biped)→ MMD 标准骨名。映射不到的保留原名。 +_BONE_JP = { + "Root": "全ての親", + "Bip001": "グルーブ", + "Bip001Pelvis": "センター", + "Bip001Spine": "上半身", + "Bip001Spine1": "上半身1", + "Bip001Spine2": "上半身2", + "Bip001Neck": "首", + "Bip001Head": "頭", + "Bip001LClavicle": "左肩", + "Bip001RClavicle": "右肩", + "Bip001LUpperArm": "左腕", + "Bip001RUpperArm": "右腕", + "Bip001LForearm": "左ひじ", + "Bip001RForearm": "右ひじ", + "Bip001LHand": "左手首", + "Bip001RHand": "右手首", + "Bip001LThigh": "左足", + "Bip001RThigh": "右足", + "Bip001LCalf": "左ひざ", + "Bip001RCalf": "右ひざ", + "Bip001LFoot": "左足首", + "Bip001RFoot": "右足首", + "Bip001LToe0": "左つま先", + "Bip001RToe0": "右つま先", +} + +# 手指:Bip001LFinger0 / LFinger01 / LFinger1 / LFinger11 ... +# 拇指从 0 起,其余手指从 1 起(MMD 标准骨名的惯例)。 +_FINGER_JP = ("親指", "人指", "中指", "薬指", "小指") +_FW = ("0", "1", "2", "3", "4", "5") +_SIDE_JP = {"L": "左", "R": "右"} +_FINGER_RE = re.compile(r"^Bip001([LR])Finger(\d)(\d?)$") + + +def bone_jp(name): + """单根骨骼名 → MMD 日文名;没有对应条目就返回 None(保留原名)。""" + if name in _BONE_JP: + return _BONE_JP[name] + m = _FINGER_RE.match(name or "") + if m: + side, finger, seg = m.group(1), int(m.group(2)), m.group(3) + if 0 <= finger < len(_FINGER_JP): + base = 0 if finger == 0 else 1 # 拇指从 0、其余从 1 + idx = base + (int(seg) if seg else 0) + if idx < len(_FW): + return "%s%s%s" % (_SIDE_JP[side], _FINGER_JP[finger], _FW[idx]) + return None + + +# ----------------------------------------------------------------- 小工具 ---- +def _uniq(name, used): + base = (name or "").strip() or "bone" + if base not in used: + used.add(base) + return base + i = 1 + while "%s_%d" % (base, i) in used: + i += 1 + nm = "%s_%d" % (base, i) + used.add(nm) + return nm + + +def _morph_panel(name): + """PMX 表情面板:1=眉 2=目 3=口 4=その他(只影响 MMD 里的分组)。""" + n = (name or "").lower() + if n.startswith("b_") or "brow" in n or n.startswith("mayu"): + return 1 + if n.startswith("e_") or "pupil" in n or "eye" in n or n.startswith("hitomi"): + return 2 + if (n.startswith("l_") or n.startswith("r_") or n.startswith("aa") + or n.startswith("mouth") or "lip" in n or "tooth" in n + or "tongue" in n or n.startswith("kuch")): + return 3 + return 4 + + +_TEX_EXT = (".png", ".bmp", ".tga", ".jpg", ".jpeg", ".dds") + + +def _copy_tex(src, dst, remove_alpha): + """拷贴图;remove_alpha 时复用 uemodel2pmx 那套去 alpha 逻辑。""" + if remove_alpha: + try: + import uemodel2pmx + r = uemodel2pmx._copy_texture(src, dst, True) + if r: + return r + except Exception: + pass + shutil.copyfile(src, dst) + return "copied" + + +def _find_texture(folder, mat_name): + """按材质名在同目录(含 Textures 子目录)找贴图文件,返回绝对路径或 None。""" + cands = [] + nm = mat_name or "" + cands.append(nm) + if nm.startswith("MI_"): + cands.append(nm[3:]) + if nm.startswith("M_"): + cands.append(nm[2:]) + for base in list(cands): + for suf in ("_D", "_Diffuse", "_BaseColor", "_Albedo", "_d", "_C"): + cands.append(base + suf) + dirs = [folder] + for sub in ("Textures", "textures", "Texture"): + d = os.path.join(folder, sub) + if os.path.isdir(d): + dirs.append(d) + parent = os.path.dirname(folder) + for sub in ("Textures", "textures"): + d = os.path.join(parent, sub) + if os.path.isdir(d): + dirs.append(d) + + lower = {} + for d in dirs: + try: + for f in os.listdir(d): + st, ext = os.path.splitext(f) + if ext.lower() in _TEX_EXT: + lower.setdefault((d, st.lower()), f) + except OSError: + pass + for base in cands: + if not base: + continue + for (d, st), f in lower.items(): + if st == base.lower(): + return os.path.join(d, f) + return None + + +# ------------------------------------------------------------------- 主体 ---- +def _warn_anchor_collision(out_path, log): + """提示 `.psk` 同名冲突(PmxEditor 的「アンカーデータ」误读)。 + + PmxEditor 打开 `xxx.pmx` 时会自动去找**同名**的 `xxx.psk`,当成它的 + 「アンカー(锚点/权重编辑)数据」加载 —— 见菜单 + `[ファイル] → [アンカーデータの自動読み込み/保存]` 与它的 readme: + 「モデルファイル名と同名のアンカーデータファイル(*.psk)がある場合自動読み込み」 + 而 `*.psk` 恰好又是 Unreal ActorX 网格的扩展名,也就是本工具的**输入**格式。 + 于是「源 psk 和输出 pmx 同名同目录」这种最自然的用法,一定会让 PmxEditor 弹: + + アンカーデータの読み込みに失敗しました。 + + 这个报错**不影响模型**(点确定后模型照常显示),但很吓人,所以主动说一声。 + """ + d = os.path.dirname(os.path.abspath(out_path)) or "." + stem = os.path.splitext(os.path.basename(out_path))[0] + clash = [f for f in (stem + ".psk", stem + ".pskx") + if os.path.isfile(os.path.join(d, f))] + if not clash: + return + log("提示:同一目录下有同名的 %s。PmxEditor 打开此 PMX 时会尝试将其作为" + "「アンカーデータ」(锚点 / 权重数据)加载,并提示" + "「アンカーデータの読み込みに失敗しました。」,点击确定即可,不影响模型。" + "如需避免,可移动或重命名 PMX,或在 PmxEditor 中关闭" + "[ファイル]→[アンカーデータの自動読み込み/保存]。" + % " / ".join(clash), "warn") + + +def convert(path, out_path, scale_mode="mmd", log=None, name=None, + enable_edge=False, force_double_sided=False, textures=True, + keep_add_uv=True, remove_alpha=True, flip_winding="auto", + center=True, jp_bones=True, make_ik=True, export_morphs=True, + fbx_path=None): + """PSK/PSKX → PMX。返回统计 dict。""" + _l = log or _log_default + + m = pskio.read_psk(path) + kind = "PSKX" if m.face32 else "PSK" + _l("读取 %s:顶点 %d · 楔 %d · 三角面 %d · 材质 %d · 骨骼 %d · 权重 %d" + % (kind, len(m.points), len(m.wedges), len(m.faces), + len(m.materials), len(m.bones), len(m.weights))) + if not m.points or not m.wedges: + raise ValueError("此文件中没有网格数据(PNTS / VTXW 为空)") + if not m.faces: + raise ValueError("此文件中没有面数据(FACE 块为空)") + _l("表情 %d 个 · 附加 UV %d 套 · %s" + % (len(m.morphs), len(m.extra_uvs), + "含法线" if m.normals else "不含法线(将自动计算)")) + + # ---- 坐标变换 + # + # 实测(R2T1FeiBiMd10011.psk / R2T1AimisiMd10011.pskx 两个文件一致): + # Bip001LHand 在 +X、Bip001RHand 在 -X → PSK 的 +X = 模型**左手** + # 脚踝 → 脚尖的方向 ≈ (0, -0.47, -0.88) → PSK 的 -Y = 模型**正面** + # (另有一条独立佐证:整体包围盒在 +Y 侧明显更长,那是头发/披风/背包) + # 整体 +Z = 上 + # 而 MMD/PMX 的约定是:**正面 -Z、左手 +X、上 +Y** + # (见 pmx2vrm.py 里对实测模型「小食Taberu」的记录:両目 Z=-0.75、 + # 左腕 X=+1.34;本机 F:\测试\...\Anastasya.pmx 复核同样成立)。 + # + # 所以只要把 PSK 的 Y 和 Z 对调就同时满足三条: + # 左手 +X → +X ✓ 上 +Z → +Y ✓ 正面 -Y → -Z ✓ + # + # 注意这里**不是** uemodel2pmx 那种 (x, z, -y): + # (x, z, -y) 行列式 +1(纯旋转,不改手性),会把正面 -Y 送到 **+Z**, + # 于是人物在 MMD 里背对镜头 —— 这正是 2026-09-24 修掉的那个 bug。 + # (x, z, y) 行列式 -1,正好把 PSK 的右手系翻成 MMD 的左手系,手性才对上。 + # 因为绕序会跟着反射一起翻,flip_winding="auto" 的投票(以及没有法线时的 + # 兜底)都要相应反转,见下面「绕序」那一段。 + def xf(p): + return (p[0], p[2], p[1]) + + # ---- 顶点:一个 wedge 对应一个 PMX 顶点(UV/材质分流都在 wedge 上) + n_wedge = len(m.wedges) + n_point = len(m.points) + raw_pos = [] + bad_wedge = 0 + for pi, u, v, _mi in m.wedges: + if not (0 <= pi < n_point): + pi = 0 + bad_wedge += 1 + raw_pos.append(m.points[pi]) + if bad_wedge: + _l("网格:%d 个楔的点索引越界,已改用第 0 个点" % bad_wedge, "warn") + + pts = [xf(p) for p in raw_pos] + ys = [p[1] for p in pts] + lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0) + if scale_mode in ("mmd", "auto", None): + scale = 20.0 / max(hi_y, 1e-6) + if hi_y <= 0: + scale = 20.0 / max(abs(lo_y), 1e-6) + _l("缩放:源高 %.2f 单位 × %.6f → %.2f(MMD 标准身高 20)" + % (hi_y, scale, hi_y * scale)) + elif scale_mode in ("raw", "none", 1, 1.0): + # 与 fbx2pmx 的 --scale raw 对齐:保持源尺寸不动。 + # (以前这里只认 "mmd" 和数字,写 --scale raw 会直接 + # ValueError: could not convert string to float: 'raw'。) + scale = 1.0 + _l("缩放:保持源尺寸(scale=1.0),源高 %.2f 单位" % hi_y) + else: + scale = float(scale_mode) + _l("缩放:源高 %.2f 单位 × %.6f → %.2f" + % (hi_y, scale, hi_y * scale)) + + if center and pts: + xs = [p[0] for p in pts] + zs = [p[2] for p in pts] + off = (-(min(xs) + max(xs)) * 0.5 * scale, + -lo_y * scale, + -(min(zs) + max(zs)) * 0.5 * scale) + _l("居中:偏移 (%.3f, %.3f, %.3f)" % off, "info") + else: + off = (0.0, 0.0, 0.0) + + def sp(p): + t = xf(p) + return (t[0] * scale + off[0], t[1] * scale + off[1], + t[2] * scale + off[2]) + + def sdir(d): + """源位移 → PMX 位移(只换轴 + 缩放,不带平移)。""" + t = xf(d) + return (t[0] * scale, t[1] * scale, t[2] * scale) + + # ---- 骨骼世界坐标 + _wrot, wpos = pskio.bone_world(m) + bone_pos = [sp(p) for p in wpos] + n_src = len(m.bones) + + # ---- 骨骼顺序:DFS,保证父在子前面 + kids = [[] for _ in range(n_src)] + roots = [] + for i, b in enumerate(m.bones): + p = b.parent_index + if 0 <= p < n_src and p != i: + kids[p].append(i) + else: + roots.append(i) + order = [] + seen = [False] * n_src + stack = list(reversed(roots)) + while stack: + i = stack.pop() + if seen[i]: + continue + seen[i] = True + order.append(i) + stack.extend(reversed(kids[i])) + for i in range(n_src): + if not seen[i]: + seen[i] = True + order.append(i) + + slot = {bi: k for k, bi in enumerate(order)} + used = set() + pmx_bones = [] + n_renamed = 0 + for src in order: + b = m.bones[src] + jp = bone_jp(b.name) if jp_bones else None + main_name = jp if jp else b.name + if jp: + n_renamed += 1 + p = b.parent_index if 0 <= b.parent_index < n_src else -1 + pmx_bones.append({ + "name": _uniq(main_name, used), + "name_en": b.name or "bone", + "pos": bone_pos[src], + "parent": slot.get(p, -1), + "layer": 0, "flag": 0, "tail_kind": 0, "tail": (0.0, 0.0, 0.0), + "inherit_rot": None, "inherit_mov": None, "fixed_axis": None, + "local_axis": None, "external": None, "ik": None, + "_kids": [], + }) + for src in order: + b = m.bones[src] + p = b.parent_index if 0 <= b.parent_index < n_src else -1 + if p in slot and slot[p] != slot[src]: + pmx_bones[slot[p]]["_kids"].append(slot[src]) + + for bk in pmx_bones: + flag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # 可旋转/可移动/可显示/可操作 + k = bk.pop("_kids") + if k: + flag |= 0x0001 # 尾 = 骨骼(取第一个子骨骼) + bk["tail_kind"] = 1 + bk["tail"] = k[0] + else: + p = bk["parent"] + if 0 <= p < len(pmx_bones): + d = (bk["pos"][0] - pmx_bones[p]["pos"][0], + bk["pos"][1] - pmx_bones[p]["pos"][1], + bk["pos"][2] - pmx_bones[p]["pos"][2]) + ln = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5 + bk["tail"] = ((d[0] / ln, d[1] / ln, d[2] / ln) if ln > 1e-9 + else (0.0, 1.0, 0.0)) + else: + bk["tail"] = (0.0, 1.0, 0.0) + bk["flag"] = flag + _l("骨骼:%d 根%s" + % (len(pmx_bones), + "" if not jp_bones else "(其中 %d 根改为 MMD 标准日文名," + "原英文名保留在英文名中)" % n_renamed)) + + # ---- 足 IK(MMD 摆姿势几乎必用;源骨架没有,这里补标准的一套) + def find_bone(jp_name): + for i, b in enumerate(pmx_bones): + if b["name"] == jp_name: + return i + return -1 + + ik_made = 0 + if make_ik: + ground_y = min(p[1] for p in (sp(x) for x in raw_pos)) if raw_pos else 0.0 + center_i = find_bone("センター") + for side, s in (("左", "L"), ("右", "R")): + i_ankle = find_bone(side + "足首") + i_knee = find_bone(side + "ひざ") + i_leg = find_bone(side + "足") + i_toe = find_bone(side + "つま先") + if min(i_ankle, i_knee, i_leg) < 0: + continue + ankle = pmx_bones[i_ankle]["pos"] + i_legik = len(pmx_bones) + pmx_bones.append({ + "name": _uniq(side + "足IK", used), + "name_en": "LegIK_" + s, + "pos": (ankle[0], ground_y, ankle[2]), + "parent": center_i if center_i >= 0 else 0, + "layer": 0, + "flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020, + "tail_kind": 0, "tail": (0.0, 1.0, 0.0), + "inherit_rot": None, "inherit_mov": None, + "fixed_axis": None, "local_axis": None, "external": None, + "ik": {"target": i_ankle, "iterations": 40, + "limit_angle": 1.0, + "links": [{"bone": i_knee, "min": None, "max": None}, + {"bone": i_leg, "min": None, "max": None}]}, + }) + ik_made += 1 + if i_toe >= 0: + toe = pmx_bones[i_toe]["pos"] + pmx_bones.append({ + "name": _uniq(side + "つま先IK", used), + "name_en": "ToeIK_" + s, + "pos": (toe[0], ground_y, toe[2]), + "parent": i_legik, + "layer": 0, + "flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020, + "tail_kind": 0, "tail": (0.0, 1.0, 0.0), + "inherit_rot": None, "inherit_mov": None, + "fixed_axis": None, "local_axis": None, + "external": None, + "ik": {"target": i_toe, "iterations": 3, + "limit_angle": 1.0, + "links": [{"bone": i_ankle, + "min": None, "max": None}]}, + }) + ik_made += 1 + if ik_made: + _l("足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)" % ik_made, + "info") + else: + _l("足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨", "info") + + # ---- 面:按材质排序,保证 PMX 材质吃连续的面段 + nmats = max(1, len(m.materials)) + tri = [] + for (i0, i1, i2), mi in m.faces: + if i0 >= n_wedge or i1 >= n_wedge or i2 >= n_wedge: + continue + if not (0 <= mi < nmats): + mi = 0 + tri.append((mi, i0, i1, i2)) + tri.sort(key=lambda t: t[0]) + + # ---- 绕序自动判定(用变换后的数据投票;缩放/平移不影响手性) + # xf 是一次反射(行列式 -1),几何绕序会跟着翻,所以下面「没有法线」的兜底 + # 也从「保持不变」改成「反转」——不然没带 VTXNORMS 的 psk 会整片背面朝外。 + pos_t = [sp(p) for p in raw_pos] + if m.normals and len(m.normals) == n_point: + nrm_t = [] + for pi, _u, _v, _mi in m.wedges: + n = m.normals[pi] if 0 <= pi < len(m.normals) else (0.0, 0.0, 1.0) + t = xf(n) + ln = (t[0] ** 2 + t[1] ** 2 + t[2] ** 2) ** 0.5 or 1.0 + nrm_t.append((t[0] / ln, t[1] / ln, t[2] / ln)) + else: + nrm_t = [] + face_idx = [] + for _mi, a, b, c in tri: + face_idx.extend((a, b, c)) + if flip_winding in ("auto", None, ""): + if nrm_t: + need_flip, ag, dis = pmxio.detect_winding(pos_t, nrm_t, face_idx) + _l("绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s" + % (ag, dis, "需要反转" if need_flip else "保持不变")) + else: + need_flip = True + _l("绕序:缺少法线数据,按坐标轴反射统一反转(保持正面朝外)", "info") + else: + need_flip = bool(flip_winding) + + pmx_faces = [] + for _mi, a, b, c in tri: + pmx_faces.extend((c, b, a) if need_flip else (a, b, c)) + + # ---- 权重:RAWWEIGHTS 是按「点」索引的,楔要按 point_index 去查 + per_point = {} + for w, pi, bi in m.weights: + if 0 <= pi < n_point: + per_point.setdefault(pi, []).append((w, bi)) + + n_dropped = 0 + no_weight = 0 + pmx_verts = [] + n_add = min(4, len(m.extra_uvs)) if keep_add_uv else 0 + for wi, (pi, u, v, _mi) in enumerate(m.wedges): + P = sp(m.points[pi] if 0 <= pi < n_point else (0.0, 0.0, 0.0)) + if nrm_t: + N = nrm_t[wi] + else: + N = (0.0, 0.0, 1.0) + wl = [(b, w) for w, b in per_point.get(pi, []) if w > 1e-6] + if len(wl) > 4: + n_dropped += len(wl) - 4 + wl.sort(key=lambda t: -t[1]) + wl = wl[:4] + wl = [(b, w) for b, w in wl if 0 <= b < n_src] + if not wl: + no_weight += 1 + wl = [(0, 1.0)] + tot = sum(w for _, w in wl) or 1.0 + wl = [(slot.get(b, 0), w / tot) for b, w in wl] + if len(wl) == 1: + wtype, wbones, wweights = 0, [wl[0][0]], [] + elif len(wl) == 2: + wtype, wbones, wweights = 1, [wl[0][0], wl[1][0]], [wl[0][1]] + else: + wtype = 2 + wbones = [wl[k][0] if k < len(wl) else wl[0][0] for k in range(4)] + wweights = [wl[k][1] if k < len(wl) else 0.0 for k in range(4)] + add = [] + for k in range(n_add): + st = m.extra_uvs[k] + uv = st[wi] if wi < len(st) else (0.0, 0.0) + add.append((uv[0], uv[1], 0.0, 0.0)) + pmx_verts.append({"pos": P, "normal": N, "uv": (u, v), + "add_uv": add, "wtype": wtype, "wbones": wbones, + "wweights": wweights, "sdef": None, "edge": 1.0}) + if no_weight: + _l("权重:%d 个顶点没有权重,已绑定到第 0 根骨骼" % no_weight, "warn") + if n_dropped: + _l("权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)" + % n_dropped, "info") + + # ---- 材质 + 贴图 + folder = os.path.dirname(os.path.abspath(path)) + out_dir = os.path.dirname(os.path.abspath(out_path)) + tex_dir = os.path.join(out_dir, "textures") + pmx_textures = [] + tex_slot = {} + n_linked = 0 + + def use_texture(mat_name): + if mat_name in tex_slot: + return tex_slot[mat_name] + real = _find_texture(folder, mat_name) + if real is None: + real = _find_texture(out_dir, mat_name) + if real is None: + tex_slot[mat_name] = -1 + return -1 + ext = os.path.splitext(real)[1].lower() + if ext not in _TEX_EXT: + tex_slot[mat_name] = -1 + return -1 + dst = os.path.join(tex_dir, os.path.basename(real)) + try: + os.makedirs(tex_dir, exist_ok=True) + _copy_tex(real, dst, remove_alpha) + except OSError: + tex_slot[mat_name] = -1 + return -1 + pmx_textures.append("textures/" + os.path.basename(real)) + tex_slot[mat_name] = len(pmx_textures) - 1 + return tex_slot[mat_name] + + counts = [0] * nmats + for _mi, _a, _b, _c in tri: + counts[_mi] += 1 + + pmx_materials = [] + for k in range(nmats): + mt = m.materials[k] if k < len(m.materials) else None + mname = (mt.name if mt and mt.name else "mat%d" % k) + ti = use_texture(mname) if textures else -1 + if ti >= 0: + n_linked += 1 + flag = 0x0E | (0x10 if enable_edge else 0) + if force_double_sided: + flag |= 0x01 + pmx_materials.append({ + "name": mname, "name_en": mname, + "diffuse": (1.0, 1.0, 1.0, 1.0), + "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, + "ambient": (0.5, 0.5, 0.5), + "flag": flag, + "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, + "tex": ti, "sph": -1, "sph_mode": 0, + # toon:**不使用**。见文件顶部 _TOON_NONE_FLAG 的说明。 + "toon_flag": _TOON_NONE_FLAG, "toon": _TOON_NONE_INDEX, "memo": "", + "faces": counts[k], + }) + # 空材质(源里声明了但一个面都没用上)会让 PMX 出现 0 面材质段,去掉更干净 + pmx_materials = [x for x in pmx_materials if x["faces"] > 0] + if not pmx_materials: + pmx_materials.append({ + "name": "material_0", "name_en": "material_0", + "diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, "ambient": (0.5, 0.5, 0.5), + "flag": 0x0E | (0x10 if enable_edge else 0), + "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, "tex": -1, "sph": -1, + "sph_mode": 0, "toon_flag": _TOON_NONE_FLAG, + "toon": _TOON_NONE_INDEX, "memo": "", + "faces": len(pmx_faces) // 3, + }) + # PMX 材质的「面数」字段其实是**索引数**(每个三角面占 3 个) + for x in pmx_materials: + x["faces"] = int(x["faces"]) * 3 + _l("材质:%d 个 · 关联到贴图 %d 个%s" + % (len(pmx_materials), n_linked, + "" if n_linked else "(源目录中没有同名贴图,导出为无贴图模型)")) + + # ---- 表情:MRPH 的位移是按「点」索引的,要摊到该点对应的所有楔上 + point_to_wedges = {} + for wi, (pi, _u, _v, _mi) in enumerate(m.wedges): + if 0 <= pi < n_point: + point_to_wedges.setdefault(pi, []).append(wi) + + used_mo = set() + pmx_morphs = [] + if export_morphs: + for mo in m.morphs: + offs = [] + for pi, d in mo.offsets: + dp = sdir(d) + if abs(dp[0]) + abs(dp[1]) + abs(dp[2]) < 1e-9: + continue + for wi in point_to_wedges.get(pi, ()): + if wi < len(pmx_verts): + offs.append((wi, dp)) + if not offs: + continue + nm = _uniq(mo.name, used_mo) + pmx_morphs.append({"name": nm, "name_en": mo.name or nm, + "panel": _morph_panel(mo.name), "kind": 1, + "offsets": offs}) + _l("表情:%d 个(顶点表情)" % len(pmx_morphs)) + + # ---- 表示枠 / 模型信息 + frames = [] + if pmx_bones: + frames.append({"name": "Root", "name_en": "Root", "special": 0, + "items": [(0, i) for i in range(len(pmx_bones))]}) + if pmx_morphs: + frames.append({"name": "表情", "name_en": "Exp", "special": 1, + "items": [(1, i) for i in range(len(pmx_morphs))]}) + + stem = os.path.splitext(os.path.basename(path))[0] + title = name or stem + comment = ["由 %s 转换:%s" % (kind, os.path.basename(path)), + "骨骼 %d 根 · 材质 %d 个 · 表情 %d 个" % (len(pmx_bones), + len(pmx_materials), + len(pmx_morphs)), + "converted by psk2pmx.py"] + model = pmxio.new_model(title) + model["name"] = title + model["name_en"] = stem + model["comment"] = "\r\n".join(comment) + model["comment_en"] = "\r\n".join(comment) + model["vertices"] = pmx_verts + model["faces"] = pmx_faces + model["textures"] = pmx_textures + model["materials"] = pmx_materials + model["bones"] = pmx_bones + model["morphs"] = pmx_morphs + model["frames"] = frames + model["add_uv"] = n_add + if not enable_edge: + pmxio.strip_edges(model, force_double_sided=False) + + size = pmxio.write_pmx(model, out_path) + _l("已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d" + % (os.path.basename(out_path), size / 1048576.0, len(pmx_verts), + len(pmx_faces) // 3, len(pmx_bones), len(pmx_materials), + len(pmx_morphs)), "ok") + _warn_anchor_collision(out_path, _l) + + st = {"bytes": size, "vertices": len(pmx_verts), + "tris": len(pmx_faces) // 3, "bones": len(pmx_bones), + "materials": len(pmx_materials), "morphs": len(pmx_morphs), + "textures": len(pmx_textures), "scale": scale} + + if fbx_path: + try: + import fbxout + st["fbx"] = fbxout.export_model( + fbx_path, pmx_verts, pmx_faces, pmx_materials, + pmx_bones, pmx_morphs, + mirror_z=True, reverse_winding=True, tex_dir=tex_dir, + log=_l, name=title) + _l("已写出 %s(ASCII FBX 7.4 · %.2f MB)" + % (os.path.basename(fbx_path), + st["fbx"]["bytes"] / 1048576.0), "ok") + except Exception as e: + st["fbx_error"] = str(e) + _l("FBX 导出失败:%s" % e, "err") + return st + + +def main(argv=None): + import argparse + ap = argparse.ArgumentParser(description="PSK / PSKX → MMD PMX(纯 Python)") + ap.add_argument("src") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--scale", default="mmd", + help="mmd(归一到 20 单位,默认)/ raw(保持源尺寸)/ 具体倍率") + ap.add_argument("--edge", action="store_true", help="给材质开启 MMD 轮廓线") + ap.add_argument("--force-double-sided", action="store_true") + ap.add_argument("--no-textures", action="store_true") + ap.add_argument("--keep-alpha", action="store_true", help="保留贴图 alpha") + ap.add_argument("--no-add-uv", action="store_true") + ap.add_argument("--raw-bone-names", action="store_true", + help="骨骼保留原始英文名,不转 MMD 日文标准名") + ap.add_argument("--no-ik", action="store_true", help="不补 MMD 足 IK 骨") + ap.add_argument("--no-morphs", action="store_true") + ap.add_argument("--fbx", action="store_true", help="同时导出 FBX") + ap.add_argument("--name", default=None) + a = ap.parse_args(argv) + out = a.out or (os.path.splitext(a.src)[0] + ".pmx") + fbx = (os.path.splitext(out)[0] + ".fbx") if a.fbx else None + st = convert(a.src, out, scale_mode=a.scale, + log=lambda m_, t=None: print(m_), name=a.name, + enable_edge=a.edge, force_double_sided=a.force_double_sided, + textures=not a.no_textures, keep_add_uv=not a.no_add_uv, + remove_alpha=not a.keep_alpha, jp_bones=not a.raw_bone_names, + make_ik=not a.no_ik, export_morphs=not a.no_morphs, + fbx_path=fbx) + print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/convert/uemodel2pmx.py b/convert/uemodel2pmx.py new file mode 100644 index 0000000..1d4d836 --- /dev/null +++ b/convert/uemodel2pmx.py @@ -0,0 +1,1066 @@ +# -*- coding: utf-8 -*- +"""uemodel2pmx.py - UEFormat(.uemodel) → MMD 的 PMX 2.0,纯 Python 标准库。 + +UEFormat 是 FortnitePorting / FModel / CUE4Parse 生态的公开交换格式 +(规范 https://github.com/h4lfheart/UEFormat),.uemodel 就是它的模型容器。 + +坐标(实测样本 R2T1XinMd10011.uemodel,别凭"UE 惯例"想当然) + 数据里 +X = 模型左侧、+Y = 前方、+Z = 上方、单位 cm。 + 证据:Bip001LHand.x = +33.445 / Bip001RHand.x = -33.445(左右轴 = X); + 趾-踝 = (+0.56, +9.13, -10.70)(水平分量主要落在 +Y ⇒ 前方 = +Y); + 包围盒 z 0.00..174.43 ⇒ 上方 = +Z、身高 174.43 cm。 + MMD/PMX 是 +X = 左侧、+Y = 上方、脸朝 -Z(前方 = -Z)。 + 两者同为**左手系**,只差绕 Z 的 90°: + (x, y, z)_ue → (x, z, -y)_pmx 行列式 = +1,不改手性 + 所以**不做镜面反射**(不需要像 VRM 那样取反某个轴)。 + +绕序 + 不做反射 ⇒ 手性不变,但 UE/D3D 的正面缠绕与 MMD 相反:实测几何法线 · 顶点法线 + 反向 23339 面 / 同向 6661 面。所以**必须反转三角形绕序**,由 + pmxio.detect_winding 在变换后的数据上自动投票决定(与 pmx2vrm 同一套口径)。 + +其他 + * WEIGHTS 是**稀疏表**(骨索引 + 顶点索引 + 权重的三元组,一个顶点最多见过 8 条), + 转 PMX 时按权重取前 4 条归一化后写成 BDEF1/2/4。 + * 贴图不在 .uemodel 里。导出目录里通常同时有 MI_<材质名>.json(材质实例, + 里面 Textures.MainTex 指向基础色贴图)和导出好的 T_*.png,照它关联即可。 + * 表情(MORPHTARGETS)是顶点位移,直接转成 PMX 顶点表情。 + +用法: + python uemodel2pmx.py model.uemodel -o model.pmx + python uemodel2pmx.py model.uemodel --scale fixed --fbx +""" + +import argparse +import json +import os +import shutil +import sys + +_HERE = os.path.dirname(os.path.abspath(__file__)) +for _p in (_HERE, os.path.join(os.path.dirname(_HERE), "formats")): + if _p not in sys.path: + sys.path.insert(0, _p) + +import pmxio # noqa: E402 +import uemodelio # noqa: E402 + + +def _log_default(msg, tag=None): + try: + print(msg) + except UnicodeEncodeError: + print(msg.encode("utf-8", "replace").decode("ascii", "replace")) + + +# --------------------------------------------------------------- 矩阵 / 四元 -- +def _qmat(q): + x, y, z, w = q + n = (x * x + y * y + z * z + w * w) ** 0.5 or 1.0 + x, y, z, w = x / n, y / n, z / n, w / n + return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]] + + +def _mm(a, b): + return [[a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] + for j in range(3)] for i in range(3)] + + +def _mv(m, v): + return (m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2], + m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2], + m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2]) + + +def _add(a, b): + return (a[0] + b[0], a[1] + b[1], a[2] + b[2]) + + +# --------------------------------------------------------------- 贴图关联 -- +class _FolderIndex(object): + """目录文件索引(大小写不敏感),避免每个材质都 listdir。""" + + def __init__(self, folder): + self.map = {} + try: + for fn in os.listdir(folder): + self.map.setdefault(fn.lower(), fn) + except OSError: + pass + + def get(self, name): + return self.map.get((name or "").lower()) + + +def _mat_json(folder, idx, mat): + """找出材质对应的 MI_*.json:先按材质名,再按材质资源路径的最后一段。""" + cands = [] + nm = (mat.name or "").strip() + if nm: + cands.append(nm + ".json") + tail = (mat.path or "").split("/")[-1] + if tail: + tail = tail.split(".")[-1] + if tail: + cands.append(tail + ".json") + for c in cands: + real = idx.get(c) + if real and os.path.isfile(os.path.join(folder, real)): + return os.path.join(folder, real) + return None + + +def _read_mat_json(path): + """读材质实例 json,取基础色贴图名 / 颜色 / 不透明度。""" + out = {"tex": "", "color": None, "blend": None, "translucent": False} + try: + with open(path, "r", encoding="utf-8-sig") as f: + d = json.load(f) + except Exception: + return out + texs = d.get("Textures") or {} + for key in ("MainTex", "BaseColor", "T_BaseColor", "Diffuse"): + v = texs.get(key) + if v: + out["tex"] = str(v).split("/")[-1].split(".")[0] + break + pars = d.get("Parameters") or {} + cols = pars.get("Colors") or {} + tint = cols.get("BaseColorTint") or cols.get("BaseColor") or {} + if tint: + try: + out["color"] = (float(tint.get("R", 1.0)), float(tint.get("G", 1.0)), + float(tint.get("B", 1.0)), float(tint.get("A", 1.0))) + except (TypeError, ValueError): + out["color"] = None + out["blend"] = pars.get("BlendMode") + out["translucent"] = bool(pars.get("IsTranslucent")) + return out + + +def find_material_texture(folder, mat, idx=None): + """在 uemodel 导出目录里找出某个材质的基础色贴图文件(绝对路径)。 + + 路径是 `MI_<材质名>.json` → `Textures.MainTex` → 同目录的 `T_*.png`。 + GUI 预览也走这里,保证「预览看到的贴图」和「转换后拷进 PMX 的贴图」一致。 + 找不到返回 None(调用方自行回退到纯色)。 + """ + idx = idx if idx is not None else _FolderIndex(folder) + jp = _mat_json(folder, idx, mat) + if not jp: + return None + name = (_read_mat_json(jp) or {}).get("tex") + if not name: + return None + for ext in (".png", ".PNG", ".tga", ".TGA", ".jpg", ".jpeg", ".bmp", + ".dds", ".DDS"): + r = idx.get(name + ext) + if r: + return os.path.join(folder, r) + return None + + +# ----------------------------------------------------------------- 表情面板 -- +def _morph_panel(name): + """PMX 表情面板:1=眉 2=目 3=口 4=その他(只影响 MMD 里的分组,不影响变形)。""" + n = (name or "").lower() + if n.startswith("b_") or "brow" in n or n.startswith("mayu"): + return 1 + if n.startswith("e_") or "pupil" in n or "eye" in n or n.startswith("hitomi"): + return 2 + if (n.startswith("l_") or n.startswith("r_") or n.startswith("aa") + or n.startswith("mouth") or "lip" in n or "tooth" in n + or "tongue" in n or n.startswith("kuch")): + return 3 + return 4 + + +def _uniq(name, used): + base = (name or "").strip() or "bone" + if base not in used: + used.add(base) + return base + i = 1 + while "%s_%d" % (base, i) in used: + i += 1 + nm = "%s_%d" % (base, i) + used.add(nm) + return nm + + +def _copy_texture(src, dst, remove_alpha): + """拷贴图;remove_alpha 时写成不透明 RGB。 + + **UE 的贴图 alpha 几乎都是数据遮罩而不是透明度**(实测本样本 Face_D 里 + alpha=255 的像素是 0 个、Cloth_D 只有 165 个)——原样拷进 MMD 会因为 + 「MMD 把贴图 alpha 当透明」而整个模型几乎全透。所以 UE 路径默认去 alpha。 + 复用 fbx2pmx 里那套(有 Pillow 用 Pillow,否则纯标准库解 PNG/TGA)。 + """ + if remove_alpha: + try: + import fbx2pmx + r = fbx2pmx._strip_alpha(src, dst) + if r: + return r + except Exception: + pass + shutil.copyfile(src, dst) + return "copied" + + +# --------------------------------------------------------------------- 主体 -- +def _bone_tokens(nm): + """把骨名切成有意义的 token(去掉纯数字序号与命名空间前缀)。 + + `clavicle_l_adjust` → ('clavicle','l') + `spine_01_adjust` → ('spine',) + `Bip001-L-Clavicle` → ('clavicle','l') ← 序号与 `Bip` 一律丢掉 + `neck_01_adjust` → ('neck',) + `head_adjust` → ('head',) + """ + s = _strip_ns(nm or "") + low = s.lower() + for suf in ("_adjust", "-adjust", ".adjust", "adjust", "_adj", "_ctrl"): + if low.endswith(suf) and len(low) > len(suf): + s = s[:len(s) - len(suf)] + low = s.lower() + break + for pre in ("adjust_", "adj_", "ctrl_"): + if low.startswith(pre) and len(low) > len(pre): + s = s[len(pre):] + low = s.lower() + break + toks = [] + for part in s.replace("-", "_").replace(".", "_").replace(" ", "_").split("_"): + part = "".join(c for c in part.lower() if c.isalnum()) + if not part: + continue + # 去掉尾部的数字序号:`bip001` → `bip`、`spine1` → `spine`、`01` → 空 + core = part.rstrip("0123456789") + if not core: + continue + # `bip` 只是 Biped 包的壳,不带语义;`bn` / `bone` 同理 + if core in ("bip", "bn", "bone", "b"): + continue + toks.append(core) + # 左右标记**统一挪到末尾**:`clavicle_l` 与 `l_clavicle` 是同一根骨的不同写法 + # (`Bn_l_hairA_001` 是前者、`Bip001-L-Clavicle` 切出来是后者), + # 不归一化就永远对不上。 + side = [t for t in toks if t in ("l", "r", "lf", "rt", "left", "right")] + body = [t for t in toks if t not in ("l", "r", "lf", "rt", "left", "right")] + if side: + s0 = side[0] + s0 = {"lf": "l", "left": "l", "rt": "r", "right": "r"}.get(s0, s0) + body.append(s0) + return tuple(body) + + +def _bone_world(m): + """骨骼局部坐标(T·R·S,父左乘)→ 源世界坐标列表。与主体同一套公式。""" + n = len(m.skeleton.bones) + world = [None] * n + state = [0] * n + + def build(i, depth=0): + if i < 0 or i >= n or state[i] == 2 or depth > 512: + return + b = m.skeleton.bones[i] + if state[i] == 1: # 环:当根处理 + world[i] = (_qmat(b.rot), tuple(b.pos)) + state[i] = 2 + return + state[i] = 1 + p = b.parent + if p < 0 or p >= n: + world[i] = (_qmat(b.rot), tuple(b.pos)) + else: + build(p, depth + 1) + pr, pt = world[p] + if pr is None: + world[i] = (_qmat(b.rot), tuple(b.pos)) + else: + world[i] = (_mm(pr, _qmat(b.rot)), + _add(_mv(pr, b.pos), pt)) + state[i] = 2 + + for i in range(n): + build(i) + for i in range(n): + if world[i] is None: + world[i] = (_qmat(m.skeleton.bones[i].rot), + tuple(m.skeleton.bones[i].pos)) + return [world[i][1] for i in range(n)] + + +# 「部件文件」自带的、指明它挂在参考模型哪个位置的调节骨。命名是各家约定, +# 但 *_adjust 这个后缀在本样本(鸣潮 / 黑鸟 042)里非常稳定,且能精确命中 +# 参考模型的 Bip001 骨(误差 < 1e-4 cm)。 +_ALIGN_SUFFIXES = ("_adjust",) + + +def _norm_bone(nm): + """骨名归一化,用于跨 LOD / 跨部件的模糊配对。 + + 去掉命名空间前缀与常见前后缀、只留字母数字,再小写。 + 例:`clavicle_l_adjust` → `claviclel`;`adjust_clavicle_l` → `claviclel`; + `Bip001-L-Clavicle` → `bip001lclavicle`(**不同**,所以匹配要按 + 「全名 → 去前后缀 → 归一化」三级依次放宽,见 find_align_offset)。 + """ + s = (nm or "").strip() + low = s.lower() + for suf in ("_adjust", "-adjust", ".adjust", "adjust", "_adj", "_ctrl", + "_control", "_ref", "_target", "_offset", "_helper"): + if low.endswith(suf) and len(low) > len(suf): + s = s[:len(s) - len(suf)] + low = s.lower() + break + for pre in ("adjust_", "adjust-", "adj_", "ctrl_", "control_", "ref_", + "target_", "offset_", "helper_"): + if low.startswith(pre) and len(low) > len(pre): + s = s[len(pre):] + low = s.lower() + break + return "".join(c for c in s.lower() if c.isalnum()) + + +def _strip_ns(nm): + """再去掉一层命名空间前缀(`xxx:yyy` / `xxx|yyy` / `xxx.yyy`)。""" + out = [] + for sep in (":", "|", "/"): + if sep in nm: + out = nm.split(sep) + break + return nm if not out else out[-1] + + +def _bone_alias(nm): + """一个骨名可能对应的所有归一化别名(含去命名空间版本)。""" + al = set() + if not nm: + return al + for base in (nm, _strip_ns(nm)): + al.add(_norm_bone(base)) + # UE/Maya 里常见的 _ 编号前缀:`1_head` → `head` + b2 = base + for sep in ("_", "-", "."): + parts = b2.split(sep) + if len(parts) > 1 and parts[0].isdigit(): + al.add(_norm_bone(sep.join(parts[1:]))) + al.discard("") + return al + + +def _bone_spread(m): + """骨骼世界坐标的包围盒对角线长度(源 cm)。用来判断「这是整身还是部件」。 + + 整身模型骨架铺开(脚 0 → 头 ~150cm),对角线上百 cm; + 局部空间部件(如头骨局部)骨架挤在原点附近,对角线很小。 + """ + ws = _bone_world(m) + if not ws: + return 0.0 + xs = [p[0] for p in ws] + ys = [p[1] for p in ws] + zs = [p[2] for p in ws] + dx = max(xs) - min(xs) + dy = max(ys) - min(ys) + dz = max(zs) - min(zs) + return (dx * dx + dy * dy + dz * dz) ** 0.5 + + +def _bbox_diag(m): + """第 0 个 LOD 顶点包围盒对角线长度(源 cm),用于「部件是否已落在参考内」。""" + if not m.lods: + return 0.0 + vs = m.lods[0].vertices + if not vs: + return 0.0 + xs = [v[0] for v in vs] + ys = [v[1] for v in vs] + zs = [v[2] for v in vs] + dx = max(xs) - min(xs) + dy = max(ys) - min(ys) + dz = max(zs) - min(zs) + return (dx * dx + dy * dy + dz * dz) ** 0.5 + + +def find_align_offset(part, ref, log=None): + """求「部件 uemodel」挂到「参考 uemodel」上所需的刚性平移(源 cm)。 + + UEFormat 一个角色常被拆成多个 .uemodel(身体 / 头发+皮肤 / 服装…)。 + 但**部件文件不一定和整身共用同一世界原点**:实测 + `Blackbird042_nighty_hair_skin.uemodel` 的坐标是**头部骨的局部空间** + (它的 `head_adjust` 就在原点,`clavicle_l_adjust` = (1.812, -1.916, -10.748)), + 而它自带的 `*_adjust` 骨加一个平移后能**精确**落在参考模型的 + `Bip001-L-Clavicle` = (1.812, 0.194, 137.905) 上,平移量 + = 参考模型 `Bip001-Head` 的世界坐标 = (0, 2.110, 148.653)。 + + 匹配顺序(逐级放宽,先精确后模糊): + ① 部件骨名**原样**在参考模型里找同名骨; + ② 去掉 `_adjust` 之类后缀 / `adjust_` 之类前缀后再找; + ③ 归一化(只留字母数字、小写)后找——这一级能吃下 + `Bip001-L-Clavicle` ↔ `bip001lclavicle` 这种前缀差异。 + 命中骨对的位移差按 0.02cm 分箱投票,取票数最高的一档求精确平均; + 要求 ≥3 票且最大残差 ≤0.05cm,否则判定不可信、放弃对齐。 + + 返回 (offset, n_hits, total) 或 (None, 0, 0)。 + """ + _l = log or _log_default + pn = [b.name or "" for b in part.skeleton.bones] + rn = [b.name or "" for b in ref.skeleton.bones] + pw = _bone_world(part) + rw = _bone_world(ref) + + # 参考模型:多级索引(全名 / 去前后缀 / 归一化别名 / token 序列)→ 骨世界坐标 + idx_exact, idx_alias = {}, {} + tok_map = {} + for i, nm in enumerate(rn): + if not nm: + continue + idx_exact.setdefault(nm.lower(), rw[i]) + for a in _bone_alias(nm): + idx_alias.setdefault(a, rw[i]) + tok_map.setdefault(_bone_tokens(nm), []).append(rw[i]) + # 歧义时取**列表第一根**:骨骼按父先子后排列,第一根就是层级最靠上的那根 + # (`Bip001-Spine` 先于 `Bip001-Spine1/2`,正是部件 adjust 骨要挂的那个)。 + tok_first = {k: v[0] for k, v in tok_map.items()} + + # 逐骨求「部件骨 → 参考骨」的位移差,按 0.02cm 分箱投票 + BIN = 0.02 + votes = {} + n_matched = 0 + for i, nm in enumerate(pn): + if not nm: + continue + target = idx_exact.get(nm.lower()) + if target is None: + # ② 只去掉本侧后缀/前缀(`clavicle_l_adjust` → `clavicle_l`), + # 避免直接归一化把 `Bip001-L-Clavicle` 也一起搅进来 + cands = [] + low = nm.lower() + for suf in ("_adjust", "-adjust", ".adjust", "_adj", "_ctrl"): + if low.endswith(suf): + cands.append(nm[:len(nm) - len(suf)]) + for pre in ("adjust_", "adj_", "ctrl_"): + if low.startswith(pre): + cands.append(nm[len(pre):]) + for c in cands: + target = idx_exact.get(c.lower()) + if target is not None: + break + if target is None: + # ③ 归一化兜底 + for a in _bone_alias(nm): + target = idx_alias.get(a) + if target is not None: + break + if target is None: + # ④ token 序列(已丢掉数字序号与 bip/bn/bone 包壳), + # 这一级吃下 `clavicle_l_adjust` ↔ `Bip001-L-Clavicle`、 + # `spine_01_adjust` ↔ `Bip001-Spine` 这类前缀/编号差异。 + # token 有歧义时(`Bip001-Spine/Spine1/Spine2` 都归成 ('spine',)) + # 取层级最靠上的第一根,靠后面的「分箱投票 + 残差复核」兜底: + # 选错了那一票就会落在别的箱里、票数不够而被整体否决。 + target = tok_first.get(_bone_tokens(nm)) + if target is None: + continue + n_matched += 1 + d = (target[0] - pw[i][0], target[1] - pw[i][1], target[2] - pw[i][2]) + k = (round(d[0] / BIN), round(d[1] / BIN), round(d[2] / BIN)) + votes.setdefault(k, []).append((pw[i], target, nm)) + + if not votes: + _l("对齐:部件的 %d 根骨骼中没有与参考模型同名或相近的骨骼,已跳过对齐" + % len(pn), "warn") + return None, 0, len(pn) + best_key = max(votes.items(), key=lambda kv: len(kv[1]))[0] + lst = votes[best_key] + n = float(len(lst)) + avg = (sum(t[1][0] - t[0][0] for t in lst) / n, + sum(t[1][1] - t[0][1] for t in lst) / n, + sum(t[1][2] - t[0][2] for t in lst) / n) + # 用平均位移复核:命中够多、且残差足够小才算可信 + res = [(abs(t[1][0] - t[0][0] - avg[0]) + abs(t[1][1] - t[0][1] - avg[1]) + + abs(t[1][2] - t[0][2] - avg[2])) for t in lst] + spread = max(res) if res else 9e9 + if len(lst) < 3 or spread > 0.05: + _l("对齐:位置一致的骨骼只有 %d 根(共匹配 %d 根 · 最大残差 %.4f cm),结果不可靠,已跳过" + % (len(lst), n_matched, spread), "warn") + return None, len(lst), len(pn) + + # ---- 方向守卫:参考模型必须是「整身(世界空间)」才有资格当参考。 + # + # 对齐是**单向**的:它把「部件」搬进「参考」的空间。如果用户把方向选反了 + # (拿部件当参考、拿整身当部件 —— 实测很容易发生:两个文件都勾了「自动对齐」 + # 并都选了同一个参考),整身反而会被搬进部件的头骨局部空间, + # 表现成「整个材质和骨骼整体往下掉 15.5 单位」。数学上这个平移是**成立**的 + # (残差极小、票数充足),所以光靠残差判据拦不住,必须另加几何判据: + # + # ① 参考骨架的铺开程度必须明显大于部件(整身 150cm vs 部件几十 cm); + # ② 若参考的骨架反而比部件还挤,说明参考自己就是局部空间的部件 → 拒绝。 + p_spread = _bone_spread(part) + r_spread = _bone_spread(ref) + if p_spread > 0 and r_spread < p_spread * 0.8: + _l("对齐:参考模型的骨架跨度 %.1f cm,小于本文件的 %.1f cm," + "参考模型本身可能是部件(参考与部件可能选反了),已跳过对齐" + % (r_spread, p_spread), "warn") + return None, len(lst), len(pn) + + _l("对齐:匹配 %d 根骨骼,其中 %d 根位置一致(残差 ≤ %.4f cm)" + % (n_matched, len(lst), spread)) + _l("对齐:平移 (%.4f, %.4f, %.4f) cm" % avg) + return avg, len(lst), len(pn) + + +def convert(path, out_path, scale_mode="fixed", lod_index=0, log=None, + name=None, enable_edge=False, force_double_sided=False, + textures=True, keep_add_uv=True, fbx_path=None, + remove_alpha=True, flip_winding="auto", center=True, + align_to=None): + """uemodel → PMX。返回统计 dict。fbx_path 非空时同时导出 ASCII FBX。 + + align_to:可选,参考模型(整身 .uemodel)路径。给了就把本文件当成 + 「挂在参考模型某处的部件」,按自带的 *_adjust 骨与参考模型同名骨求平移, + 把它放回参考模型的世界位置(见 `find_align_offset` 的说明)。 + """ + _l = log or _log_default + + m = uemodelio.read_uemodel(path) + _l("UEFormat v%d · %s · 骨骼 %d · LOD %d" + % (m.version, m.name or os.path.basename(path), + len(m.skeleton.bones), len(m.lods))) + if not m.lods: + raise ValueError("此 .uemodel 中没有 LOD 数据") + + # 选 LOD:越界就退到最后一个(LOD 号越大越粗) + if lod_index < 0 or lod_index >= len(m.lods): + lod_index = 0 + lod = m.lods[lod_index] + _l("使用 LOD[%d] %s:顶点 %d · 三角面 %d · 材质 %d · 表情 %d · UV %d" + % (lod_index, lod.name, len(lod.vertices), len(lod.indices) // 3, + len(lod.materials), len(lod.morphs), len(lod.uvs))) + if len(m.lods) > 1: + _l("提示:该文件有 %d 个 LOD,只导出第 %d 个" + % (len(m.lods), lod_index), "info") + + # ---- 坐标变换:(x, y, z)_ue → (x, z, -y)_pmx(左手系→左手系,无镜面) + def xf(p): + return (p[0], p[2], -p[1]) + + # ---- 缩放:UE 单位 = 1 cm,MMD 惯例 1 单位 = 8 cm(≈ 20 单位 = 160cm 身高)。 + # 用**固定**比例(UE cm → MMD 单位),而不是「按身高归一到 20 单位」: + # UEFormat 一个角色常被拆成多个 .uemodel(身体 / 头发+皮肤 / 服装…), + # 每个都是同一世界尺度下的部件。若按各自身高都归一化到 20,部件会被 + # 各自放大成「整只角色」大小,载入同一场景就互相错位,表现成 + # 「某部件比例变大」——这正是与 Blender+mmd_tools 不一致的根源 + # (mmd_tools 对所有文件用同一固定比例,部件间相对大小保持正确)。 + # 固定比例对**整身**模型同样没问题:161cm 角色 → 161/8 ≈ 20.1 单位, + # 仍是 MMD 的标准身高。要「每个文件都拉到 20 单位」时用 --scale mmd。 + # + # 注意 scale 必须**在骨骼之前**算出来:骨骼世界坐标和顶点共用同一个 + # scale,否则会出现「网格高 20、骨链却还在源尺度」的鬼模型。 + UE_CM_PER_MMD = 8.0 + vs_src = lod.vertices + pts = [xf(v) for v in vs_src] + ys = [p[1] for p in pts] + lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0) + head = max(abs(lo_y), abs(hi_y), 1e-6) + if scale_mode in ("fixed", "auto", None, ""): + scale = 1.0 / UE_CM_PER_MMD + elif scale_mode == "mmd": + scale = 20.0 / max(hi_y, 1e-6) + if hi_y <= 0: + scale = 20.0 / head + else: + scale = float(scale_mode) + src_h = hi_y - lo_y + _l("缩放:源高 %.2f cm × %.6f → %.2f" + % (src_h, scale, src_h * scale)) + + # ---- 部件对齐:把本文件(头发/皮肤等)放回参考模型的世界位置。 + # 必须在「换轴 + 缩放」之前做,因为位移是**源 cm**,跟着顶点一起缩放。 + # 注意 align_off 一定要**同时**加到顶点和骨骼上(与 scale 同理)。 + align_off = (0.0, 0.0, 0.0) + align_ref_pts = [] + if align_to: + try: + ref = uemodelio.read_uemodel(align_to) + off, hit, tot = find_align_offset(m, ref, log=_l) + if off is not None: + align_off = off + # 居中基准也要取自参考模型(否则各自居中 = 又错位) + if ref.lods: + align_ref_pts = ref.lods[0].vertices + _l("对齐:已按 %s 对齐(源坐标整体平移)" + % os.path.basename(align_to), "ok") + else: + _l("对齐失败(匹配 %d / %d),按模型自身原点导出" % (hit, tot), "warn") + except Exception as e: + _l("对齐失败:%s(按模型自身原点导出)" % e, "warn") + + if align_off != (0.0, 0.0, 0.0): + aoff = xf(align_off) + pts = [(p[0] + aoff[0], p[1] + aoff[1], p[2] + aoff[2]) for p in pts] + ys = [p[1] for p in pts] + lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0) + _l("对齐后:源高 %.2f cm → %.2f cm(缩放不变)" % (src_h, hi_y - lo_y)) + + # ---- 居中:x/z 取包围盒中心、y 脚底归零(与 fbx2pmx 的 center=True 同口径) + # + # ⚠ 部件(align_to 生效时)不能按**自己**的包围盒居中:那会把刚对齐好的 + # 位置又拉回原点,等于白对齐 —— 部件和整身各自居中后当然还是错位的。 + # 所以对齐时改用**参考模型**的居中基准(由参考模型的顶点包围盒算), + # 这样部件和整身共用同一套偏移,相对位置才对得上。 + if center and pts: + if align_ref_pts: + refs = [xf(v) for v in align_ref_pts] + ra = [p[0] for p in refs] + rb = [p[1] for p in refs] + rc = [p[2] for p in refs] + off = (-(min(ra) + max(ra)) * 0.5 * scale, + -min(rb) * scale, + -(min(rc) + max(rc)) * 0.5 * scale) + _l("居中:按参考模型包围盒(偏移 (%.3f, %.3f, %.3f))" % off, "info") + else: + xs = [p[0] for p in pts] + zs = [p[2] for p in pts] + off = (-(min(xs) + max(xs)) * 0.5 * scale, + -lo_y * scale, + -(min(zs) + max(zs)) * 0.5 * scale) + _l("居中:偏移 (%.3f, %.3f, %.3f)" % off, "info") + else: + off = (0.0, 0.0, 0.0) + + def sp(p): + """源坐标 → PMX 坐标(对齐 + 换轴 + 缩放 + 居中),顶点和骨骼共用。""" + q = (p[0] + align_off[0], p[1] + align_off[1], p[2] + align_off[2]) \ + if align_off != (0.0, 0.0, 0.0) else p + t = xf(q) + return (t[0] * scale + off[0], t[1] * scale + off[1], + t[2] * scale + off[2]) + + src_bones = m.skeleton.bones + n_src = len(src_bones) + + # 世界矩阵(局部 = T·R·S,父亲左乘) + world = [None] * n_src + state = [0] * n_src + + def build(i, depth=0): + if i < 0 or i >= n_src or state[i] == 2 or depth > 512: + return + if state[i] == 1: # 环:当成根处理,别死循环 + q = _qmat(src_bones[i].rot) + world[i] = (q, tuple(src_bones[i].pos)) + state[i] = 2 + return + state[i] = 1 + b = src_bones[i] + p = b.parent + if p < 0 or p >= n_src: + world[i] = (_qmat(b.rot), tuple(b.pos)) + else: + build(p, depth + 1) + pr, pt = world[p] + if pr is None: + world[i] = (_qmat(b.rot), tuple(b.pos)) + else: + r = _mm(pr, _qmat(b.rot)) + t = _add(_mv(pr, b.pos), pt) + world[i] = (r, t) + state[i] = 2 + + for i in range(n_src): + build(i) + for i in range(n_src): + if world[i] is None: + world[i] = (_qmat(src_bones[i].rot), tuple(src_bones[i].pos)) + + bone_pos = [sp(world[i][1]) for i in range(n_src)] + + # ---- 骨骼顺序:DFS,保证父在子前面(PMXEditor 的骨顺表依赖这个) + kids = [[] for _ in range(n_src)] + roots = [] + for i, b in enumerate(src_bones): + p = b.parent + if 0 <= p < n_src and p != i: + kids[p].append(i) + else: + roots.append(i) + order = [] + seen = [False] * n_src + stack = list(reversed(roots)) + while stack: + i = stack.pop() + if seen[i]: + continue + seen[i] = True + order.append(i) + stack.extend(reversed(kids[i])) + for i in range(n_src): + if not seen[i]: # 环里漏掉的补到最后 + seen[i] = True + order.append(i) + + slot = {bi: k for k, bi in enumerate(order)} + used = set() + pmx_bones = [] + for src in order: + b = src_bones[src] + p = b.parent if 0 <= b.parent < n_src else -1 + pmx_bones.append({ + "name": _uniq(b.name, used), + "name_en": b.name or "bone", + "pos": bone_pos[src], + "parent": slot.get(p, -1), + "layer": 0, "flag": 0, "tail_kind": 0, "tail": (0.0, 0.0, 0.0), + "inherit_rot": None, "inherit_mov": None, "fixed_axis": None, + "local_axis": None, "external": None, "ik": None, + "_kids": [], + }) + for src in order: + b = src_bones[src] + p = b.parent if 0 <= b.parent < n_src else -1 + if p in slot and slot[p] != slot[src]: + pmx_bones[slot[p]]["_kids"].append(slot[src]) + + for bk in pmx_bones: + flag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # 可旋转/可移动/可显示/可操作 + k = bk.pop("_kids") + if k: + flag |= 0x0001 # 尾 = 骨骼(取第一个子骨骼) + bk["tail_kind"] = 1 + bk["tail"] = k[0] + else: + p = bk["parent"] + if 0 <= p < len(pmx_bones): + d = (bk["pos"][0] - pmx_bones[p]["pos"][0], + bk["pos"][1] - pmx_bones[p]["pos"][1], + bk["pos"][2] - pmx_bones[p]["pos"][2]) + ln = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5 + bk["tail"] = ((d[0] / ln, d[1] / ln, d[2] / ln) if ln > 1e-9 + else (0.0, 1.0, 0.0)) + else: + bk["tail"] = (0.0, 1.0, 0.0) + bk["flag"] = flag + _l("骨骼:%d 根(原始 %d 根)" % (len(pmx_bones), n_src)) + + # ---- 绕序自动判定(必须用变换后的数据投票;缩放/平移不影响手性判定) + pos_t = pts + nrm_t = [xf(n) for n in lod.normals] if lod.normals else [] + if flip_winding in ("auto", None, ""): + need_flip, ag, dis = pmxio.detect_winding(pos_t, nrm_t, lod.indices) + _l("绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s" + % (ag, dis, "需要反转" if need_flip else "保持不变")) + else: + need_flip = bool(flip_winding) + + # ---- 顶点 + per_vertex = {} + for w in lod.weights: + if 0 <= w.vertex: + per_vertex.setdefault(w.vertex, []).append((w.bone, w.weight)) + + uv0 = lod.uvs[0].uvs if lod.uvs else [] + extra = [] + if keep_add_uv: + for st in lod.uvs[1:]: + extra.append(st.uvs) + pmx_verts = [] + n_weights_dropped = 0 + for i, v in enumerate(vs_src): + P = sp(v) + nv = lod.normals[i] if i < len(lod.normals) else (0.0, 0.0, 1.0) + N = xf(nv) + ln = (N[0] ** 2 + N[1] ** 2 + N[2] ** 2) ** 0.5 or 1.0 + N = (N[0] / ln, N[1] / ln, N[2] / ln) + U = uv0[i] if i < len(uv0) else (0.0, 0.0) + wl = [(b, w) for b, w in per_vertex.get(i, []) if w > 1e-6] + if len(wl) > 4: + n_weights_dropped += len(wl) - 4 + wl.sort(key=lambda t: -t[1]) + wl = wl[:4] + wl = [(b, w) for b, w in wl if 0 <= b < len(pmx_bones)] + if not wl: + wl = [(0, 1.0)] + tot = sum(w for _, w in wl) or 1.0 + wl = [(b, w / tot) for b, w in wl] + if len(wl) == 1: + wtype, wbones, wweights = 0, [wl[0][0]], [] + elif len(wl) == 2: + wtype, wbones, wweights = 1, [wl[0][0], wl[1][0]], [wl[0][1]] + else: + wtype = 2 + wbones = [wl[k][0] if k < len(wl) else wl[0][0] for k in range(4)] + wweights = [wl[k][1] if k < len(wl) else 0.0 for k in range(4)] + add = [] + for st in extra: + uv = st[i] if i < len(st) else (0.0, 0.0) + add.append((uv[0], uv[1], 0.0, 0.0)) + pmx_verts.append({"pos": P, "normal": N, "uv": (U[0], U[1]), + "add_uv": add, "wtype": wtype, "wbones": wbones, + "wweights": wweights, "sdef": None, "edge": 1.0}) + + # ---- 面 + pmx_faces = [] + idx = lod.indices + nv_tot = len(vs_src) + for t in range(0, len(idx) - 2, 3): + a, b, c = idx[t], idx[t + 1], idx[t + 2] + if a >= nv_tot or b >= nv_tot or c >= nv_tot: + continue + if need_flip: + a, c = c, a + pmx_faces.extend((a, b, c)) + + # ---- 材质 + 贴图 + folder = os.path.dirname(os.path.abspath(path)) + out_dir = os.path.dirname(os.path.abspath(out_path)) + tex_dir = os.path.join(out_dir, "textures") + idx_dir = _FolderIndex(folder) + pmx_textures = [] + tex_slot = {} + copied = [] + n_linked = 0 + + def use_texture(name): + if not name: + return -1 + if name in tex_slot: + return tex_slot[name] + real = None + for ext in (".png", ".PNG", ".tga", ".TGA", ".jpg", ".jpeg", ".bmp", ".dds"): + r = idx_dir.get(name + ext) + if r: + real = r + break + if real is None: + tex_slot[name] = -1 + return -1 + src = os.path.join(folder, real) + # MMD 只认 png/tga/bmp/jpg/dds;其它后缀统一按 png 拷过去 + ext = os.path.splitext(real)[1].lower() + dst_name = name + (ext if ext in (".png", ".tga", ".bmp", ".jpg", + ".jpeg", ".dds") else ".png") + try: + os.makedirs(tex_dir, exist_ok=True) + _copy_texture(src, os.path.join(tex_dir, dst_name), remove_alpha) + except OSError: + tex_slot[name] = -1 + return -1 + pmx_textures.append("textures/" + dst_name) + copied.append(dst_name) + tex_slot[name] = len(pmx_textures) - 1 + return tex_slot[name] + + pmx_materials = [] + expect = 0 + noncontig = 0 + for mt in lod.materials: + info = {"tex": "", "color": None, "blend": None, "translucent": False} + n_face = max(0, mt.num_faces) + # PMX 的材质按顺序吃连续的面段,所以 uemodel 里 first_index 必须依次接上; + # 对不上就记账,最后统一在日志里说清楚(不静默)。 + if mt.first_index // 3 != expect: + noncontig += 1 + expect = mt.first_index // 3 + n_face + ti = -1 + diff = (1.0, 1.0, 1.0, 1.0) + if textures: + jp = _mat_json(folder, idx_dir, mt) + if jp: + info = _read_mat_json(jp) + ti = use_texture(info["tex"]) + if ti >= 0: + n_linked += 1 + if info["color"]: + diff = info["color"] + flag = 0x0E | (0x10 if enable_edge else 0) + if force_double_sided: + flag |= 0x01 + pmx_materials.append({ + "name": mt.name or ("mat%d" % len(pmx_materials)), + "name_en": mt.name or ("mat%d" % len(pmx_materials)), + "diffuse": (diff[0], diff[1], diff[2], diff[3]), + "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, + "ambient": (0.5, 0.5, 0.5), + "flag": flag, + "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, + "tex": ti, "sph": -1, "sph_mode": 0, + # toon:**不使用**。 + # ⚠ 方向极易搞反:flag=1 才是内建 toon(1 字节编号,引用 MMD 的 + # toon01.bmp..toon10.bmp,**编号 0 = toon01.bmp 而不是「不使用」**, + # 见 mmd_tools 的 `"toon%02d.bmp" % (shared + 1)`,且 MMD 的 Data + # 目录里根本没有 toon00.bmp);flag=0 是本模型纹理表索引, + # **-1 = なし**。所以「不使用 toon」= flag 0 + 索引 -1。 + # 2026-09-24 修:以前写 flag=1/0,等于硬套一层 toon01.bmp。 + "toon_flag": 0, "toon": -1, "memo": "", + "faces": n_face, + "_tex_file": (os.path.basename(pmx_textures[ti]) + if isinstance(ti, int) and 0 <= ti < len(pmx_textures) + else None), + }) + if len(pmx_materials) == 0: + pmx_materials.append({ + "name": "material_0", "name_en": "material_0", + "diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, "ambient": (0.5, 0.5, 0.5), + "flag": 0x0E | (0x10 if enable_edge else 0), "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, "tex": -1, "sph": -1, + "sph_mode": 0, "toon_flag": 0, "toon": -1, "memo": "", + "faces": len(pmx_faces) // 3, + }) + else: + cover = sum(x["faces"] for x in pmx_materials) + if cover != len(pmx_faces) // 3: + pmx_materials[0]["faces"] += len(pmx_faces) // 3 - cover + # PMX 材质的「面数」字段其实是**索引数**(每个三角面占 3 个),不是三角面数! + # 上面按三角面记账更直观,写出前统一 ×3。fbx2pmx(`pw.i32(cnt * 3)`)也是 + # 这个口径;写成三角面数会让 MMD 只画 1/3 的面、 + # PMX→VRM 也会把面段整体错位。 + for x in pmx_materials: + x["faces"] = int(x["faces"]) * 3 + _l("材质:%d 个 · 关联到贴图 %d 个 · 拷贝贴图 %d 张%s" + % (len(pmx_materials), n_linked, len(copied), + "" if not noncontig else "(注意:%d 个材质的面区间不连续)" % noncontig)) + + # ---- 表情(MORPHTARGETS → PMX 顶点表情) + # UEFormat 规范:struct FMorphData { FVector PositionDelta; FVector TangentZDelta; + # uint VertexIndex; } —— **是位移增量,不是绝对坐标**(实测样本也是:|delta| + # 0.5~2.5 而顶点坐标 ~134)。所以 PMX 的顶点表情偏移 = 「换轴 + 缩放」后的位移, + # **不能**套带居中平移的 sp()、更不能再减一次顶点自身坐标 —— 那等于把顶点搬到 + # 绝对坐标 pos(≈ 原点),一拖表情滑块整束头发就塌到脚底、留下从头顶拖到地面的 + # 长条拉伸面(用户报的「表情顶点拉伸」就是这个)。 + def sdir(d): + """源位移 → PMX 位移(只换轴 + 缩放,不平移、也不加对齐)。""" + t = xf(d) + return (t[0] * scale, t[1] * scale, t[2] * scale) + + used_mo = set() + pmx_morphs = [] + for mop in lod.morphs: + offs = [] + for d in mop.deltas: + if not (0 <= d.vertex < len(pmx_verts)): + continue + if abs(d.pos[0]) + abs(d.pos[1]) + abs(d.pos[2]) < 1e-9: + continue + dp = sdir(d.pos) + if abs(dp[0]) + abs(dp[1]) + abs(dp[2]) < 1e-9: + continue + offs.append((d.vertex, dp)) + if not offs: + continue + nm = _uniq(mop.name, used_mo) + pmx_morphs.append({"name": nm, "name_en": mop.name or nm, + "panel": _morph_panel(mop.name), "kind": 1, + "offsets": offs}) + _l("表情:%d 个(顶点表情)" % len(pmx_morphs)) + + # ---- 表示枠 / 模型信息 + frames = [] + if pmx_bones: + frames.append({"name": "Root", "name_en": "Root", "special": 0, + "items": [(0, i) for i in range(len(pmx_bones))]}) + if pmx_morphs: + frames.append({"name": "表情", "name_en": "Exp", "special": 1, + "items": [(1, i) for i in range(len(pmx_morphs))]}) + + stem = os.path.splitext(os.path.basename(path))[0] + title = name or m.name or stem + comment = ["由 UEFormat(.uemodel) 转换:%s" % os.path.basename(path), + "UEFormat v%d · LOD[%d] %s" % (m.version, lod_index, lod.name), + "骨骼/表情沿用原名称;英文骨名无法直接套用 MMD 日文标准动作数据", + "converted by uemodel2pmx.py"] + model = pmxio.new_model(title) + model["name"] = title + model["name_en"] = title + model["comment"] = "\r\n".join(comment) + model["comment_en"] = "\r\n".join(comment) + model["vertices"] = pmx_verts + model["faces"] = pmx_faces + model["textures"] = pmx_textures + model["materials"] = pmx_materials + model["bones"] = pmx_bones + model["morphs"] = pmx_morphs + model["frames"] = frames + model["add_uv"] = len(extra) if extra else 0 + if not enable_edge: + pmxio.strip_edges(model, force_double_sided=False) + + size = pmxio.write_pmx(model, out_path) + _l("已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d · 表情 %d" + % (os.path.basename(out_path), size / 1048576.0, len(pmx_verts), + len(pmx_faces) // 3, len(pmx_bones), len(pmx_materials), + len(pmx_morphs)), "ok") + if n_weights_dropped: + _l("提示:%d 条第 5 及以后的骨骼权重被丢弃(PMX 最多 4 根)" + % n_weights_dropped, "info") + + # height = **输出 PMX 里**的真实高度(源高度 × scale),不是源高度本身: + # 之前写成 hi_y-lo_y,mmd 模式下会误报成源高度,容易让人以为缩放没生效。 + st = {"bytes": size, "vertices": len(pmx_verts), + "tris": len(pmx_faces) // 3, "bones": len(pmx_bones), + "materials": len(pmx_materials), "morphs": len(pmx_morphs), + "textures": len(pmx_textures), "scale": scale, "lod": lod_index, + "height": (hi_y - lo_y) * scale, "src_height": src_h, + "align_off": align_off, + "aligned": align_off != (0.0, 0.0, 0.0)} + + # ---- 可选:同时导出 FBX(与 PMX 同一姿势,Y-up 右手系,便于进 Blender/UE) + if fbx_path: + try: + import fbxout + st["fbx"] = fbxout.export_model( + fbx_path, pmx_verts, pmx_faces, pmx_materials, + pmx_bones, pmx_morphs, + mirror_z=True, reverse_winding=True, tex_dir=tex_dir, + log=_l, name=title) + _l("已写出 %s(ASCII FBX 7.4 · %.2f MB)" + % (os.path.basename(fbx_path), + st["fbx"]["bytes"] / 1048576.0), "ok") + except Exception as e: + st["fbx_error"] = str(e) + _l("FBX 导出失败:%s" % e, "err") + return st + + +def main(argv=None): + ap = argparse.ArgumentParser(description="UEFormat(.uemodel) → MMD PMX(纯 Python)") + ap.add_argument("src") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--scale", default="fixed", + help="fixed(默认:UE cm→MMD 1/8,部件保持相对大小)" + " / mmd(每个文件归一到 20 单位) / 具体倍率") + ap.add_argument("--lod", type=int, default=0) + ap.add_argument("--edge", action="store_true", help="给材质开启 MMD 轮廓线") + ap.add_argument("--force-double-sided", action="store_true") + ap.add_argument("--no-textures", action="store_true", help="不关联/拷贴图") + ap.add_argument("--keep-alpha", action="store_true", + help="保留贴图 alpha(默认去掉:UE 贴图的 alpha 多是数据遮罩," + "留着会让 MMD 里整个模型透明)") + ap.add_argument("--no-add-uv", action="store_true", help="不写附加 UV") + ap.add_argument("--align-to", default=None, + help="参考模型(整身 .uemodel)路径:按 *_adjust 骨求平移," + "把本文件当成挂在它上面的部件放回正确位置") + ap.add_argument("--fbx", action="store_true", help="同时导出 FBX") + ap.add_argument("--name", default=None) + a = ap.parse_args(argv) + out = a.out or (os.path.splitext(a.src)[0] + ".pmx") + fbx = (os.path.splitext(out)[0] + ".fbx") if a.fbx else None + st = convert(a.src, out, scale_mode=a.scale, lod_index=a.lod, + log=lambda m_, t=None: print(m_), name=a.name, + enable_edge=a.edge, force_double_sided=a.force_double_sided, + textures=not a.no_textures, keep_add_uv=not a.no_add_uv, + remove_alpha=not a.keep_alpha, fbx_path=fbx, + align_to=a.align_to) + print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/convert/vrm_edit.py b/convert/vrm_edit.py new file mode 100644 index 0000000..3b0912f --- /dev/null +++ b/convert/vrm_edit.py @@ -0,0 +1,545 @@ +# -*- coding: utf-8 -*- +"""转换好的 VRM 再调整(不用重新转换):预设表情指定和强度、视线范围、SpringBone 参数、标题、缩略图。 + + import vrm_edit + info = vrm_edit.describe(path) # 界面要的:可选表情、当前预设指定、物理链、标题 + vrm_edit.apply(path, edits) # 套用调整,原地改写文件 + +edits(纯 JSON,界面按源文件存): + + {"title": "名字", + "expressions": {"happy": "笑い", "blink": "", ...}, 预设 → 来源表情 id("" = 不设这个预设) + "intensity": {"angry": 0.8, ...}, 预设强度 ×(形态键权重相乘,单个权重最多到 1) + "lookAt": {"h": 15.0, "down": 10.0, "up": 7.0}, 视线最大转角(度):左右 / 向下 / 向上;不给 = 转换时的值 + "spring": {"stiffness": 1.0, "drag": 1.0, "gravity": 0.0, 整体:硬度 ×、阻尼 ×、重力 + + "chains": {"链 key": {"stiffness": 1.0, "gravity": 0.0, "off": false}}}, + "thumbnails": {"模型名": {"path": "缩略图 PNG 的路径", "auto": true}}} + +缩略图按模型分开(一个包里几个模型各用各的):模型名 = 输出 VRM 的文件名去掉扩展名(model_key)。 +旧版的 "thumbnail": "路径" 对这个文件的所有模型都有效,没有按模型设置的模型仍然用它。 + +可重复套用:第一次调整时把原始的表情 / 物理 / meta 存进 glTF 根节点的 extras.vrmconv_base, +以后每次都先还原再套用,不会越调越歪;edits 为空就是还原成转换时的样子。 +来源表情 id:转换时给预设表情记了来源 PMX 表情名(extras.source),自定义表情就是它的名字。 +""" +import copy +import os +import time + +import vrmio +from vrmconv import morphbake + +PRESETS_1 = ["happy", "angry", "sad", "relaxed", "surprised", "neutral", + "aa", "ih", "ou", "ee", "oh", "blink", "blinkLeft", "blinkRight", + "lookUp", "lookDown", "lookLeft", "lookRight"] +PRESETS_0 = ["joy", "angry", "sorrow", "fun", "neutral", "a", "i", "u", "e", "o", + "blink", "blink_l", "blink_r", "lookup", "lookdown", "lookleft", "lookright"] +BASE_KEY = "vrmconv_base" +SPRING_DEFAULTS = {"stiffness": 1.0, "gravityPower": 0.0, "dragForce": 0.5} + + +def _uniq(name, used): + if name not in used: + return name + k = 2 + while "%s_%d" % (name, k) in used: + k += 1 + return "%s_%d" % (name, k) + + +def _num(v, default): + try: + v = float(v) + except (TypeError, ValueError): + return default + return v if v == v and abs(v) < 1e6 else default + + +# ------------------------------------------------------------- baseline -- +def _base(g, create): + """glTF 根 extras 里的原始值;create=True 时没有就现在记下来。""" + ext = g.get("extensions", {}) + b = g.get("extras", {}).get(BASE_KEY) + if b is not None or not create: + return b + if "VRMC_vrm" in ext: + v = ext["VRMC_vrm"] + b = {"spec": "1.0", "expressions": copy.deepcopy(v.get("expressions")), + "meta": copy.deepcopy(v["meta"]), + "springBone": copy.deepcopy(ext.get("VRMC_springBone"))} + else: + v = ext["VRM"] + b = {"spec": "0.x", "groups": copy.deepcopy(v.get("blendShapeMaster", {}).get("blendShapeGroups", [])), + "meta": copy.deepcopy(v["meta"])} + b["thumb"] = None + _base_look(b, v) + _base_secondary(b, v) + g.setdefault("extras", {})[BASE_KEY] = b + return b + + +_LOOK_1 = {"h": ("rangeMapHorizontalInner", "rangeMapHorizontalOuter"), "down": ("rangeMapVerticalDown",), + "up": ("rangeMapVerticalUp",)} +_LOOK_0 = {"h": ("lookAtHorizontalInner", "lookAtHorizontalOuter"), "down": ("lookAtVerticalDown",), + "up": ("lookAtVerticalUp",)} + + +def _base_look(b, vrm): + """基准里记下转换时的视线设置(以前调整过、基准里还没有这一项的文件,补记当前的—— + 那时还没有视线调整,当前值就是转换时的值)。""" + if "look" not in b: + b["look"] = copy.deepcopy(vrm.get("lookAt") if b["spec"] == "1.0" else + {k: vrm.get("firstPerson", {}).get(k) for ks in _LOOK_0.values() for k in ks}) + + +def _base_secondary(b, vrm): + """0.x 的基准里记下转换时的物理(以前调整过、基准里还没有这一项的文件,补记当前的—— + 那时还不能调 0.x 的物理,当前值就是转换时的值)。""" + if b["spec"] != "1.0" and "secondary" not in b: + b["secondary"] = copy.deepcopy(vrm.get("secondaryAnimation")) + + +def _subtree(nodes, roots): + out, stack = [], list(roots) + while stack: + n = stack.pop(0) + if 0 <= n < len(nodes) and n not in out: + out.append(n) + stack[:0] = nodes[n].get("children", []) + return out + + +def _look_deg(b): + """基准里的视线最大转角 → {"h", "down", "up"}(度),没有视线设置时 None。""" + look = b.get("look") or {} + out = {} + for k, names in (_LOOK_1 if b["spec"] == "1.0" else _LOOK_0).items(): + m = look.get(names[0]) + if not m: + return None + out[k] = m.get("outputScale") if b["spec"] == "1.0" else m.get("yRange") + return out + + +def _apply_look(vrm, b, edits, g=None): + """视线:先还原转换时的设置,再套用 edits(左右 / 向下 / 向上的最大转角)。 + 转换时补的视线表情(lookLeft 等,横向场 + 深度场两个绑定,见 morphbake.split_gaze)按新角度重算权重。""" + is1 = b["spec"] == "1.0" + if is1: + if b.get("look") is not None: + vrm["lookAt"] = copy.deepcopy(b["look"]) + else: + for k, m in (b.get("look") or {}).items(): + if m is not None: + vrm.setdefault("firstPerson", {})[k] = copy.deepcopy(m) + if not edits or _look_deg(b) is None: + return + target = vrm["lookAt"] if is1 else vrm["firstPerson"] + for k, names in (_LOOK_1 if is1 else _LOOK_0).items(): + deg = _num(edits.get(k), None) + if deg is None: + continue + deg = min(90.0, max(0.0, deg)) + for n in names: + target[n]["outputScale" if is1 else "yRange"] = deg + if g is not None: + _gaze_weights(g, vrm, is1, edits) + + +def _target_name(g, bind, is1): + """表情绑定指向的 morph target 名(找不到时 None)。1.0 的 node 是网格节点,0.x 的 mesh 是网格号。""" + try: + m = g["nodes"][bind["node"]]["mesh"] if is1 else bind["mesh"] + names = g["meshes"][m]["extras"]["targetNames"] + return names[bind["index"]] if 0 <= bind["index"] < len(names) else None + except (KeyError, IndexError, TypeError): + return None + + +def _gaze_weights(g, vrm, is1, edits): + depth = set(morphbake.GAZE_DEPTH.values()) + for p, key in morphbake.GAZE_KEY.items(): + deg = _num(edits.get(key), None) + if deg is None: + continue + axis = "h" if key == "h" else "v" + wt, wd = morphbake.gaze_weights(deg, axis) + if is1: + obj = (vrm.get("expressions") or {}).get("preset", {}).get(p) + binds = obj and (obj.get("extras") or {}).get("source") == p and obj.get("morphTargetBinds") + scale = 1.0 + else: + gr = next((x for x in vrm.get("blendShapeMaster", {}).get("blendShapeGroups", []) + if x.get("name") == p and x.get("presetName") == p.lower()), None) + binds = gr and gr.get("binds") + scale = 100.0 + # 只认转换时补的那种:横向场 + 深度场(眼睛分在几个网格里时每个网格各一对) + names = [_target_name(g, bd, is1) for bd in binds or ()] + if not names or None in names or len(set(names)) != 2 or not depth.intersection(names): + continue + for bd, n in zip(binds, names): + bd["weight"] = round((wd if n in depth else wt) * scale, 6) + + +def _apply_intensity(vrm, is1, edits): + """预设强度:把预设里的形态键权重乘上系数(单个权重最多到 1 / 100)。材质颜色、贴图偏移不变。""" + for p, f in (edits or {}).items(): + f = _num(f, 1.0) + if f == 1.0: + continue + f = max(0.0, f) + if is1: + obj = ((vrm.get("expressions") or {}).get("preset") or {}).get(p) + for bd in (obj or {}).get("morphTargetBinds", []): + bd["weight"] = round(min(1.0, bd["weight"] * f), 4) + else: + for gr in vrm.get("blendShapeMaster", {}).get("blendShapeGroups", []): + if gr.get("presetName") == p: + for bd in gr.get("binds", []): + bd["weight"] = round(min(100.0, bd["weight"] * f), 2) + + +def _sources_1(expressions): + """VRM 1.0 原始表情 → (pool {id: 表情}, 预设指定 {预设: id})。""" + pool, assign = {}, {} + for p, obj in ((expressions or {}).get("preset") or {}).items(): + sid = (obj.get("extras") or {}).get("source") or "@" + p + if sid in pool: + sid = "@" + p + pool[sid] = obj + assign[p] = sid + for name, obj in ((expressions or {}).get("custom") or {}).items(): + pool[_uniq(name, pool)] = obj + return pool, assign + + +def _sources_0(groups): + pool, assign = {}, {} + for gr in groups: + sid = _uniq(gr.get("name") or "expression", pool) + pool[sid] = gr + p = str(gr.get("presetName") or "unknown").lower() + if p in PRESETS_0 and p not in assign: + assign[p] = sid + return pool, assign + + +def _chain_keys(springs): + keys, used = [], set() + for i, sp in enumerate(springs or []): + k = _uniq(sp.get("name") or "spring%d" % i, used) + used.add(k) + keys.append(k) + return keys + + +# 1.0 关节参数名 → 0.x 组参数名(硬度是规范里拼错的 stiffiness) +_FIELDS_0 = {"stiffness": "stiffiness", "gravityPower": "gravityPower", "dragForce": "dragForce"} + + +def _group_keys(groups): + return _chain_keys([{"name": grp.get("comment")} for grp in groups]) + + +def _label(sid): + return sid[1:] if sid.startswith("@") else sid + + +# -------------------------------------------------------------- describe -- +def describe(path): + """→ 界面要的信息(都按转换时的原始值,不含已套用的调整)。""" + g, _ = vrmio.read_glb(path) + ext = g.get("extensions", {}) + if "VRMC_vrm" not in ext and "VRM" not in ext: + raise ValueError("不是 VRM 文件") + b = _base(g, create=True) + out = {"spec": b["spec"], "springs": []} + if b["spec"] == "1.0": + pool, assign = _sources_1(b["expressions"]) + out["presets"] = PRESETS_1 + out["title"] = b["meta"].get("name", "") + sb = b.get("springBone") or {} + for k, sp in zip(_chain_keys(sb.get("springs")), sb.get("springs") or []): + out["springs"].append({ + "key": k, "name": sp.get("name") or k, + "joints": [{"node": j["node"], **{f: j.get(f, d) for f, d in SPRING_DEFAULTS.items()}} + for j in sp.get("joints", [])]}) + else: + pool, assign = _sources_0(b["groups"]) + out["presets"] = PRESETS_0 + out["title"] = b["meta"].get("title", "") + # 0.x 的一个摆动组 = 界面里的一条链;组根下面整棵子树都是关节,参数整组共用 + _base_secondary(b, ext["VRM"]) + groups = (b.get("secondary") or {}).get("boneGroups") or [] + for k, grp in zip(_group_keys(groups), groups): + par = {f: grp.get(f0, SPRING_DEFAULTS[f]) for f, f0 in _FIELDS_0.items()} + out["springs"].append({ + "key": k, "name": grp.get("comment") or k, + "joints": [dict(node=n, **par) for n in _subtree(g["nodes"], grp.get("bones") or [])]}) + out["expressions"] = [{"id": sid, "label": _label(sid)} for sid in pool] + out["assign"] = assign + _base_look(b, ext["VRMC_vrm"] if b["spec"] == "1.0" else ext["VRM"]) + out["look"] = _look_deg(b) # 转换时的视线最大转角(没有视线设置时 None) + return out + + +# ----------------------------------------------------------------- apply -- +def _apply_expr_1(vrm, base_expr, edits): + pool, assign = _sources_1(base_expr) + for p, sid in (edits or {}).items(): + if p in PRESETS_1: + if not sid: + assign.pop(p, None) + elif sid in pool: + assign[p] = sid + preset, custom, used = {}, {}, set(assign.values()) + for p in PRESETS_1: + sid = assign.get(p) + if sid: + obj = copy.deepcopy(pool[sid]) + if sid.startswith("@"): + obj.pop("extras", None) + else: + obj["extras"] = dict(obj.get("extras") or {}, source=sid) + preset[p] = obj + for sid, obj in pool.items(): + if sid in used: + continue + obj = copy.deepcopy(obj) + obj.pop("extras", None) + # 规范:自定义表情名不能和预设名重名 + name = _uniq(_label(sid) if not sid.startswith("@") else "orig_" + sid[1:], + set(custom) | set(PRESETS_1)) + custom[name] = obj + expressions = {} + if preset: + expressions["preset"] = preset + if custom: + expressions["custom"] = custom + if expressions: + vrm["expressions"] = expressions + else: + vrm.pop("expressions", None) + + +def _apply_expr_0(vrm, base_groups, edits): + pool, assign = _sources_0(base_groups) + for p, sid in (edits or {}).items(): + if p in PRESETS_0: + if not sid: + assign.pop(p, None) + elif sid in pool: + assign[p] = sid + by_sid = {} + for p, sid in assign.items(): + by_sid.setdefault(sid, []).append(p) + groups = [] + for sid, gr in pool.items(): + ps = by_sid.get(sid) or ["unknown"] + for k, p in enumerate(ps): # 一个表情指定给多个预设:复制一份 + ng = copy.deepcopy(gr) + ng["presetName"] = p + if k: + ng["name"] = "%s_%s" % (ng.get("name") or sid, p) + groups.append(ng) + vrm.setdefault("blendShapeMaster", {})["blendShapeGroups"] = groups + + +def _apply_spring(g, base_sb, edits): + ext = g["extensions"] + used = g.setdefault("extensionsUsed", []) + if base_sb is None: + return + sb = copy.deepcopy(base_sb) + if edits: + gs = _num(edits.get("stiffness"), 1.0) + gd = _num(edits.get("drag"), 1.0) + gg = _num(edits.get("gravity"), 0.0) + chains = edits.get("chains") or {} + springs = [] + for k, sp in zip(_chain_keys(sb.get("springs")), sb.get("springs") or []): + c = chains.get(k) or {} + if c.get("off"): + continue + cs, cg = _num(c.get("stiffness"), 1.0), _num(c.get("gravity"), 0.0) + for j in sp.get("joints", []): + st = j.get("stiffness", SPRING_DEFAULTS["stiffness"]) + gp = j.get("gravityPower", SPRING_DEFAULTS["gravityPower"]) + dr = j.get("dragForce", SPRING_DEFAULTS["dragForce"]) + j["stiffness"] = round(max(0.0, st * gs * cs), 4) + j["gravityPower"] = round(max(0.0, gp + gg + cg), 4) + j["dragForce"] = round(min(1.0, max(0.0, dr * gd)), 4) + springs.append(sp) + sb["springs"] = springs + if sb.get("springs"): + ext["VRMC_springBone"] = sb + if "VRMC_springBone" not in used: + used.append("VRMC_springBone") + else: # 全部关掉:规范要求 springs 非空,整个扩展去掉 + ext.pop("VRMC_springBone", None) + if "VRMC_springBone" in used: + used.remove("VRMC_springBone") + + +def _apply_secondary(vrm, base_sa, edits): + """0.x:和 _apply_spring 一样的倍率 / 按链覆盖 / 关闭,作用在每个摆动组的参数上。""" + if base_sa is None: + return + sa = copy.deepcopy(base_sa) + if edits: + gs = _num(edits.get("stiffness"), 1.0) + gd = _num(edits.get("drag"), 1.0) + gg = _num(edits.get("gravity"), 0.0) + chains = edits.get("chains") or {} + groups = [] + for k, grp in zip(_group_keys(sa.get("boneGroups") or []), sa.get("boneGroups") or []): + c = chains.get(k) or {} + if c.get("off"): + continue + cs, cg = _num(c.get("stiffness"), 1.0), _num(c.get("gravity"), 0.0) + st = grp.get("stiffiness", SPRING_DEFAULTS["stiffness"]) + gp = grp.get("gravityPower", SPRING_DEFAULTS["gravityPower"]) + dr = grp.get("dragForce", SPRING_DEFAULTS["dragForce"]) + grp["stiffiness"] = round(max(0.0, st * gs * cs), 4) + grp["gravityPower"] = round(max(0.0, gp + gg + cg), 4) + grp["dragForce"] = round(min(1.0, max(0.0, dr * gd)), 4) + groups.append(grp) + sa["boneGroups"] = groups + vrm["secondaryAnimation"] = sa + + +def _drop_thumb(g, bin_data, thumb): + """去掉上一次加的缩略图。它总是追加在最后,在末尾时连数据一起截掉。""" + if not thumb: + return bin_data + tex, img, bv = thumb.get("texture"), thumb.get("image"), thumb.get("bufferView") + if tex is not None and tex == len(g.get("textures", [])) - 1: + g["textures"].pop() + if not g["textures"]: + del g["textures"] + if img is not None and img == len(g.get("images", [])) - 1: + g["images"].pop() + if not g["images"]: + del g["images"] + bvs = g.get("bufferViews", []) + if bv is not None and bv == len(bvs) - 1: + v = bvs.pop() + if v.get("byteOffset", 0) + v["byteLength"] >= len(bin_data) - 3: + bin_data = bin_data[:v.get("byteOffset", 0)] + return bin_data + + +def _add_thumb(g, bin_data, png, is1): + bin_data = bytearray(bin_data) + while len(bin_data) % 4: + bin_data += b"\x00" + off = len(bin_data) + bin_data += png + bvs = g.setdefault("bufferViews", []) + bvs.append({"buffer": 0, "byteOffset": off, "byteLength": len(png)}) + imgs = g.setdefault("images", []) + mime = "image/jpeg" if png[:3] == b"\xff\xd8\xff" else "image/png" + imgs.append({"name": "thumbnail", "bufferView": len(bvs) - 1, "mimeType": mime}) + thumb = {"bufferView": len(bvs) - 1, "image": len(imgs) - 1, "texture": None} + if not is1: # 0.x 的 meta.texture 是贴图(texture)序号 + texs = g.setdefault("textures", []) + if not g.get("samplers"): + g["samplers"] = [vrmio.default_sampler()] + texs.append({"sampler": 0, "source": len(imgs) - 1}) + thumb["texture"] = len(texs) - 1 + return bytes(bin_data), thumb + + +def model_key(path): + """缩略图按模型存的键:VRM 文件名去掉扩展名。""" + return os.path.splitext(os.path.basename(path))[0] + + +def thumb_for(edits, path): + """这个 VRM 的缩略图 PNG 路径:按模型设置的,否则旧版对所有模型的那张;没有 → None。""" + t = ((edits or {}).get("thumbnails") or {}).get(model_key(path)) + return (t or {}).get("path") or (edits or {}).get("thumbnail") or None + + +def is_empty(edits): + if not edits: + return True + sp = edits.get("spring") or {} + neutral_spring = (_num(sp.get("stiffness"), 1.0) == 1.0 and _num(sp.get("drag"), 1.0) == 1.0 + and _num(sp.get("gravity"), 0.0) == 0.0 + and not any(c.get("off") or _num(c.get("stiffness"), 1.0) != 1.0 + or _num(c.get("gravity"), 0.0) != 0.0 + for c in (sp.get("chains") or {}).values())) + return (not edits.get("title") and not edits.get("expressions") and neutral_spring + and not edits.get("thumbnail") and not edits.get("lookAt") + and not any((t or {}).get("path") for t in (edits.get("thumbnails") or {}).values()) + and all(_num(v, 1.0) == 1.0 for v in (edits.get("intensity") or {}).values())) + + +def apply(path, edits, out_path=None): + """把 edits 套到 VRM 上(先还原成转换时的样子再套),写到 out_path(默认原地)。返回改了几项。""" + g, bin_data = vrmio.read_glb(path) + ext = g.get("extensions", {}) + if "VRMC_vrm" not in ext and "VRM" not in ext: + raise ValueError("不是 VRM 文件") + edits = edits or {} + empty = is_empty(edits) + b = _base(g, create=not empty) + if b is None: # 从没调过、这次也没有调整 + if out_path and out_path != path: + vrmio.write_glb(g, bin_data, out_path) + return 0 + is1 = b["spec"] == "1.0" + vrm = ext["VRMC_vrm"] if is1 else ext["VRM"] + # ---- 还原 + bin_data = _drop_thumb(g, bin_data, b.get("thumb")) + b["thumb"] = None + vrm["meta"] = copy.deepcopy(b["meta"]) + n = 0 + # ---- 套用 + _base_look(b, vrm) + if is1: + _apply_expr_1(vrm, b["expressions"], edits.get("expressions")) + _apply_spring(g, b.get("springBone"), edits.get("spring")) + else: + _apply_expr_0(vrm, b["groups"], edits.get("expressions")) + _base_secondary(b, vrm) + _apply_secondary(vrm, b.get("secondary"), edits.get("spring")) + _apply_intensity(vrm, is1, edits.get("intensity")) + _apply_look(vrm, b, edits.get("lookAt"), g) + n += bool(edits.get("expressions")) + bool(edits.get("spring")) + bool(edits.get("lookAt")) + n += any(_num(v, 1.0) != 1.0 for v in (edits.get("intensity") or {}).values()) + if edits.get("title"): + vrm["meta"]["name" if is1 else "title"] = str(edits["title"]) + n += 1 + thumb = thumb_for(edits, path) + if thumb and os.path.isfile(thumb): + with open(thumb, "rb") as f: + png = f.read() + bin_data, b["thumb"] = _add_thumb(g, bin_data, png, is1) + if is1: + vrm["meta"]["thumbnailImage"] = b["thumb"]["image"] + else: + vrm["meta"]["texture"] = b["thumb"]["texture"] + n += 1 + if empty: # 全部还原:不留痕迹 + del g["extras"][BASE_KEY] + if not g["extras"]: + del g["extras"] + if g.get("buffers"): + g["buffers"][0]["byteLength"] = len(bin_data) + _write(g, bin_data, out_path or path) + return n + + +def _write(g, bin_data, path): + tmp = path + ".tmp" + vrmio.write_glb(g, bin_data, tmp) + for k in range(20): # 预览正在读这个文件时 Windows 不让替换,稍等再试 + try: + os.replace(tmp, path) + return + except PermissionError: + if k == 19: + raise + time.sleep(0.1) diff --git a/convert/vrmconv/__init__.py b/convert/vrmconv/__init__.py new file mode 100644 index 0000000..fb1423a --- /dev/null +++ b/convert/vrmconv/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +"""PMX → VRM 转换的各个阶段(入口是 convert/pmx2vrm.py 的 convert())。 + + humanoid MMD 骨骼名 → VRM 骨位、付与骨合并、层级修正、A-pose → T-pose + skeleton 骨骼预处理流程、glTF 节点树、占位骨 + mesh 顶点权重、按材质切 primitive、写 accessor + materials MToon 材质(toon 渐变 → 阴影色 / 明暗交界,线性颜色,透明判定) + expressions 顶点 / 材质表情 → morph target 与 VRM 表情 + springbone PMX 刚体物理 → VRMC_springBone + vrm_ext VRMC_vrm / VRM 0.x 扩展本体 + mathutil 3x3 矩阵小工具 + +依赖 formats/ 下的 pmxio、vrmio(作为顶层模块导入,调用方负责把 formats/ 放进 sys.path)。 +""" diff --git a/convert/vrmconv/autophys.py b/convert/vrmconv/autophys.py new file mode 100644 index 0000000..0a4d16c --- /dev/null +++ b/convert/vrmconv/autophys.py @@ -0,0 +1,199 @@ +# -*- coding: utf-8 -*- +"""没有物理的模型(FBX / psk / xps 转来的 PMX 常见):按骨骼名和骨架结构自动补一套 MMD 刚体, +再交给 springbone._build_springs 按同一套规则转成 VRM SpringBone。 + +* 摆动链(动态刚体,mode 1):名字像头发 / 裙摆 / 袖子 / 飘带 / 尾巴的非人形骨; + 另外挂在头骨下面、不像五官和头饰的非人形骨也算头发(Query 酱的头发骨叫 H01_Front、H02_L)。 + 兽耳(Ear_0_L → Ear_1_L → … 这种挂在头下、连成多节的链)单独识别:_FACE 里的 ear/耳 + 是为了挡住人形模型的单根耳饰 / 表情骨,但兽耳必须能摆,否则导出的 VRM 耳朵完全不动。 + 胸部骨、扭转骨、IK、辅助骨不动。 +* 碰撞体(跟随骨骼的刚体,mode 0):头(球)、胸 / 腰(球)、上下臂和大小腿(胶囊), + 尺寸按身高比例给。 +裙摆 / 头发的区分、抽稀、硬度、碰撞的取舍都沿用 _build_springs(按挂点和高度自动判断)。 +""" +import math +import re + +_SWING = re.compile( + r"hair|kami|髪|ahoge|bang|fringe|pony|twin|braid|" + r"skirt|スカート|suso|裾|dress|" + r"sode|sleeve|袖|" + r"ribbon|ribon|リボン|necktie|cape|cloak|mantle|scarf|マフラー|tassel|frill|フリル|" + r"tail|尻尾|shippo|しっぽ|coat|jacket_?(?:l|r|b|f)", re.I) +_NEVER = re.compile( + r"mune|bust|breast|chichi|oppai|胸|pai_|^pai|twist|twst|捩|roll|(?:^|_)ik|ik(?:$|_)|helper|ctrl|" + r"control|adj|root|dummy|ダミー|先$|tip$|nub$|ndl|offset|target|master|aim|socket|attach|" + r"weapon|gun|holster|pocket|pouch|buckle|shell|prop|point", re.I) +_FACE = re.compile( + r"eye|目|jaw|顎|tongue|舌|teeth|tooth|歯|mouth|口|brow|眉|lid|瞼|cheek|頬|nose|鼻|face|顔|" + r"lip|唇|chin|smile|crease|corner|nostril|temple|forehead|lash|pupil|iris|dimple|" + r"hat|cap|crown|glass|megane|眼鏡|horn|角|acc|ear|耳|head_?end|headtop|top$", re.I) +# 兽耳:日语模型常写作 mimi / みみ。耳环、耳机之类是挂件,不是耳朵骨 +_EAR = re.compile(r"ear|耳|mimi|みみ", re.I) +_EAR_NOT = re.compile( + r"earring|ear_ring|ear_?pierce|pierce|耳环|耳饰|earphone|headphone|イヤホン|イヤリング", re.I) + + +def _ear_chains(bones, parents, nb, human, alias, head, under): + """→ 兽耳骨集合。条件:挂在头骨下、名字像耳朵、且至少两节连成链。 + + _FACE 把 ear/耳 当五官挡掉了,但那只该挡人形模型的单根耳饰 / 表情骨; + Ear_0_L → Ear_1_L → Ear_2_L 这种多节兽耳是正经的动骨链,要放行。 + 只认「有同组父骨或子骨」的骨,孤零零一根 ear 骨仍交给 _FACE 拦住。 + """ + if head is None: + return set() + ear = {b for b in range(nb) + if b not in human and b not in alias + and _EAR.search(bones[b]["name"] or "") + and not _EAR_NOT.search(bones[b]["name"] or "") + and under(b, head)} + if len(ear) < 2: + return set() + has_child = {parents[b] for b in ear if parents[b] in ear} + return {b for b in ear if parents[b] in ear or b in has_child} + +_ARM_SEG = (("leftUpperArm", "leftLowerArm"), ("leftLowerArm", "leftHand"), + ("rightUpperArm", "rightLowerArm"), ("rightLowerArm", "rightHand")) +_LEG_SEG = (("leftUpperLeg", "leftLowerLeg"), ("leftLowerLeg", "leftFoot"), + ("rightUpperLeg", "rightLowerLeg"), ("rightLowerLeg", "rightFoot")) + + +def _rot_for_dir(d): + """胶囊沿局部 Y:求 PMX 刚体旋转(Ry·Rx·Rz,取 ry=0)使 Y 轴指向 d。""" + n = math.sqrt(sum(x * x for x in d)) or 1.0 + dx, dy, dz = (x / n for x in d) + rz = math.asin(max(-1.0, min(1.0, -dx))) + rx = math.atan2(dz, dy) + return (rx, 0.0, rz) + + +def _rb(name, bone, pos, mode, radius, height=0.0, rot=(0.0, 0.0, 0.0)): + return {"name": name, "name_en": name, "bone": bone, "group": 1 if mode else 0, "mask": 0xFFFF, + "shape": 2 if height > 0 else 0, "size": (radius, height, 0.0), "pos": tuple(pos), + "rot": tuple(rot), "mass": 1.0, "move_damp": 0.5, "rot_damp": 0.5, "repulsion": 0.0, + "friction": 0.5, "mode": mode} + + +def _leaf_tails(model, dyn, children): + """链尾骨没有子骨时(FBX 里的单根发束骨很常见),按它带动的顶点估计长度: + 以这根骨为主权重的顶点里离骨头最远的那个,取 90% 当 tail。 + 不估的话 tail 只有默认的一小截,整条链被当成「过短」不做物理。""" + bones = model["bones"] + dset = set(dyn) + leaves = [b for b in dyn if not any(c in dset for c in children[b]) + and not any(c not in dset for c in children[b])] + if not leaves: + return + far = {b: (0.0, None) for b in leaves} + for v in model.get("vertices") or []: + ws = v.get("wweights") or [1.0] + bs = v.get("wbones") or [] + if not bs: + continue + k = max(range(min(len(bs), len(ws)) or 1), key=lambda i: ws[i] if i < len(ws) else 0) + b = bs[k] + if b in far: + p, q = v["pos"], bones[b]["pos"] + d = sum((p[i] - q[i]) ** 2 for i in range(3)) + if d > far[b][0]: + far[b] = (d, p) + for b, (d, p) in far.items(): + if p is None: + continue + q = bones[b]["pos"] + off = tuple((p[i] - q[i]) * 0.9 for i in range(3)) + cur = bones[b].get("tail") + cur_len = math.sqrt(sum(x * x for x in cur)) if bones[b].get("tail_kind") == 0 and cur else 0.0 + if math.sqrt(d) * 0.9 > cur_len: + bones[b]["tail_kind"] = 0 + bones[b]["tail"] = off + + +def needed(model): + """模型里没有任何会动的刚体(mode 1/2)时才自动补。""" + return not any(rb.get("mode") in (1, 2) for rb in model.get("rigid_bodies") or []) + + +def synthesize(model, parents, alias, human_b, log=None): + """往 model["rigid_bodies"] 里追加自动生成的刚体。返回 (摆动骨数, 碰撞体数)。""" + bones = model["bones"] + nb = len(bones) + human = set(human_b.values()) + head = human_b.get("head") + ys = [v["pos"][1] for v in model.get("vertices") or []] or [b["pos"][1] for b in bones] or [0.0] + H = max(1e-6, max(ys) - min(ys)) # 模型身高(PMX 单位) + children = [[] for _ in range(nb)] + for i, p in enumerate(parents): + if 0 <= p < nb: + children[p].append(i) + + def under(b, anc): + p = parents[b] + seen = set() + while 0 <= p < nb and p not in seen: + if p == anc: + return True + if p in human: # 中间隔着别的人形骨:不算直接挂在 anc 下面 + return False + seen.add(p) + p = parents[p] + return False + + ear_dyn = _ear_chains(bones, parents, nb, human, alias, head, under) + + def swing(b): + if b in human or b in alias: + return False + nm = bones[b]["name"] or "" + if b in ear_dyn: # 多节兽耳链优先于 _FACE 的「五官」排除 + return True + if _NEVER.search(nm): + return False + if _SWING.search(nm): + return True + # 名字看不出来、挂在头下面的:只有模型里一根名字像头发的骨都没有时才当头发 + # (Query 酱的 H01_Front)。有表情骨架的模型头下面是几十根嘴唇 / 眼睑骨,不能动 + return by_struct and head is not None and under(b, head) and not _FACE.search(nm) + + by_struct = not any(re.search(r"hair|kami|髪|bang|fringe|pony|twin|braid", bones[b]["name"] or "", re.I) + for b in range(nb) if b not in human) + dyn = [b for b in range(nb) if swing(b)] + _leaf_tails(model, dyn, children) + rbs = model.setdefault("rigid_bodies", []) + for b in dyn: + nm = (bones[b]["name"] or "").lower() + lower = bool(re.search(r"skirt|スカート|suso|裾|dress", nm)) + rbs.append(_rb("auto_" + (bones[b]["name"] or str(b)), b, bones[b]["pos"], 1, + H * (0.02 if lower else 0.012))) + + # ---- 碰撞体 + n_col = 0 + pos = {k: bones[v]["pos"] for k, v in human_b.items()} + if "head" in human_b: + c = pos["head"] + rbs.append(_rb("auto_col_head", human_b["head"], (c[0], c[1] + H * 0.045, c[2]), 0, H * 0.055)) + n_col += 1 + for k, r in (("upperChest", 0.065), ("chest", 0.065), ("spine", 0.06), ("hips", 0.06)): + if k in human_b and not (k == "chest" and "upperChest" in human_b): + rbs.append(_rb("auto_col_" + k, human_b[k], pos[k], 0, H * r)) + n_col += 1 + for a, b in _ARM_SEG + _LEG_SEG: + if a not in human_b or b not in human_b: + continue + p0, p1 = pos[a], pos[b] + d = [p1[k] - p0[k] for k in range(3)] + ln = math.sqrt(sum(x * x for x in d)) + if ln < 1e-6: + continue + r = H * (0.04 if "UpperLeg" in a else 0.03 if "LowerLeg" in a else 0.028) + mid = [(p0[k] + p1[k]) / 2 for k in range(3)] + rbs.append(_rb("auto_col_" + a, human_b[a], mid, 0, r, max(0.0, ln - 2 * r) or ln * 0.5, + _rot_for_dir(d))) + n_col += 1 + if log and dyn: + log("物理:模型不含物理刚体,已按骨骼名和骨架结构自动添加 %d 根摆动骨(头发、裙摆、袖子、飘带、兽耳等)" + "和 %d 个身体碰撞体" % (len(dyn), n_col)) + if log and ear_dyn: + log("物理:识别到 %d 根兽耳骨,已加入摆动链" % len(ear_dyn)) + return len(dyn), n_col diff --git a/convert/vrmconv/checks.py b/convert/vrmconv/checks.py new file mode 100644 index 0000000..5140f4f --- /dev/null +++ b/convert/vrmconv/checks.py @@ -0,0 +1,149 @@ +# -*- coding: utf-8 -*- +"""转换后的自检:只在日志里提示,不改输出。 + + follow 网格在 MMD 里跟着哪些关节动、在 VRM 里还跟不跟(付与骨没处理到之类) + odd_bones humanoid 骨位置明显不对:在身体另一侧、离父骨太远、离网格太远(多半是把模型外面的控制骨当成了 humanoid 骨) +""" +import math + +from .humanoid import _clean_parents, _vrm_anchor + +MIN_VERTS = 20 # 少于这么多顶点的不提示(个别顶点权重刷错很常见,看不出来) + + +def follow(bones, bs, raw_weights, vweights, tol=0.3): + """→ [(顶点数, 骨, humanoid 骨位, MMD 里的跟随率, VRM 里的跟随率)],按顶点数从多到少。 + + MMD 里顶点跟某个关节转多少:按原始权重,累加每根骨沿父骨链和付与(按付与率)得到的该关节的旋转; + VRM 里:按最终权重,累加祖先里有该关节的骨。差 tol 以上的顶点按「主要挂在哪根骨上」归类。 + hips 不比(MMD 的 上半身 不在 下半身 下,VRM 要求在,这是有意改的)。 + """ + n = len(bones) + if not n: + return [] + orig = _clean_parents(bones) + slot = {i: h for h, i in bs.human_b.items() if h != "hips"} + memo_l, memo_m = {}, {} + + def local(i, depth=0): # 骨自己的旋转里有哪些关节:{骨位: 比例} + if i in memo_l: + return memo_l[i] + out = {slot[i]: 1.0} if i in slot else {} + ir = bones[i].get("inherit_rot") + if ir and depth < 16 and 0 <= ir[0] < n and ir[0] != i: + for h, r in local(ir[0], depth + 1).items(): + out[h] = out.get(h, 0.0) + ir[1] * r + memo_l[i] = out + return out + + order = sorted(range(n), key=lambda i: _depth(orig, i)) # 父在前(PMX 的骨序不一定是) + for i in order: + out = dict(memo_m.get(orig[i], {})) if orig[i] >= 0 else {} + for h, r in local(i).items(): + out[h] = out.get(h, 0.0) + r + memo_m[i] = out + + vrm = {} + + def vrm_of(b): + if b not in vrm: + s, k, seen = set(), b, set() + while 0 <= k < n and k not in seen: + if k in slot: + s.add(slot[k]) + seen.add(k) + k = bs.parents[k] + vrm[b] = s + return vrm[b] + + # 只看可能不一致的骨上的顶点:MMD 的跟随和它(并入后)在 VRM 里的祖先不一样的 + odd = set() + for b in range(n): + want = memo_m[b] + got = vrm_of(bs.alias.get(b, b)) + if any(abs(r - (1.0 if h in got else 0.0)) >= tol for h, r in want.items()) or \ + any(h not in want for h in got): + odd.add(b) + found = {} + for vi, wl in enumerate(raw_weights): + if odd.isdisjoint(b for b, _ in wl): + continue + want = {} + for b, w in wl: + for h, r in memo_m[b].items(): + want[h] = want.get(h, 0.0) + w * r + got = {} + for b, w in vweights[vi]: + for h in vrm_of(b): + got[h] = got.get(h, 0.0) + w + for h, r in want.items(): + if r - got.get(h, 0.0) >= tol: + main = max(wl, key=lambda t: t[1])[0] + e = found.setdefault((main, h), [0, 0.0, 0.0]) + e[0] += 1 + e[1] += r + e[2] += got.get(h, 0.0) + return sorted(((c, b, h, sw / c, sg / c) for (b, h), (c, sw, sg) in found.items() if c >= MIN_VERTS), + key=lambda t: -t[0]) + + +def _depth(parents, i): + d, seen = 0, set() + while 0 <= parents[i] < len(parents) and i not in seen: + seen.add(i) + i = parents[i] + d += 1 + return d + + +def odd_bones(bs, bpos, vpos, far=0.1, seg=0.35, side=0.02): + """→ [(humanoid 骨位, 骨, 原因, 数值)]:位置明显不对的 humanoid 骨(PMX 坐标、T-pose 后,角色左边是 +X)。 + + 多半是模型外面的控制骨(调整用的「肩調整」之类)被当成了 humanoid 骨,动作时肩膀、手臂会被拉过去: + side 左边的骨在身体右侧(或反过来)超过模型高度的 side 倍 + seg 离 humanoid 父骨位超过模型高度的 seg 倍(大腿、小腿最长也只有 1/4 左右) + far 附近(模型高度的 far 倍以内)没有任何顶点:关节都在身体里,离皮肤顶多几厘米。用网格哈希,不逐点算 + 数值:side / far 是模型高度的倍数,seg 是 (父骨位, 距离 / 模型高度)。 + """ + if not vpos or not bs.human_b: + return [] + ys = [p[1] for p in vpos] + h = max(ys) - min(ys) + if h <= 1e-6: + return [] + cell = h * far / 2 + occ = {(int(p[0] // cell), int(p[1] // cell), int(p[2] // cell)) for p in vpos} + out = [] + for slot_, i in bs.human_b.items(): + p = bpos[i] + if (slot_.startswith("left") and p[0] < -side * h) or (slot_.startswith("right") and p[0] > side * h): + out.append((slot_, i, "side", abs(p[0]) / h)) + continue + par = _vrm_anchor(slot_, bs.human_b) + if par and math.dist(p, bpos[bs.human_b[par]]) > seg * h: + out.append((slot_, i, "seg", (par, math.dist(p, bpos[bs.human_b[par]]) / h))) + continue + x, y, z = (int(c // cell) for c in p) + if not any((x + dx, y + dy, z + dz) in occ + for dx in (-2, -1, 0, 1, 2) for dy in (-2, -1, 0, 1, 2) for dz in (-2, -1, 0, 1, 2)): + out.append((slot_, i, "far", far)) + return out + + +def report(bones, bs, raw_weights, vweights, bpos, vpos, scale, log): + """跑两项检查,把问题写进日志(warn)。""" + for c, b, h, want, got in follow(bones, bs, raw_weights, vweights)[:6]: + log("自检:%d 个顶点主要挂在 %s 上,MMD 里跟着 %s 转 %d%%,VRM 里只跟 %d%%,动作时这部分会变形" + % (c, bones[b]["name"], h, round(want * 100), round(got * 100)), "warn") + ys = [p[1] for p in vpos] or [0.0] + cm = (max(ys) - min(ys)) * scale * 100 + for h, i, why, v in odd_bones(bs, bpos, vpos)[:6]: + name = bones[i]["name"] + if why == "side": + log("自检:humanoid 骨 %s(%s)在身体的另一侧,可能对应错了骨骼,动作时这部分会被拉开" % (h, name), "warn") + elif why == "seg": + log("自检:humanoid 骨 %s(%s)离 %s 有 %d cm,可能对应错了骨骼,动作时这部分会被拉开" + % (h, name, v[0], round(v[1] * cm)), "warn") + else: + log("自检:humanoid 骨 %s(%s)离网格超过 %d cm,可能对应错了骨骼,动作时这部分会被拉开" + % (h, name, round(v * cm)), "warn") diff --git a/convert/vrmconv/expressions.py b/convert/vrmconv/expressions.py new file mode 100644 index 0000000..a8a577b --- /dev/null +++ b/convert/vrmconv/expressions.py @@ -0,0 +1,787 @@ +# -*- coding: utf-8 -*- +"""表情:PMX 顶点 / 材质表情(含グループ展开)→ morph target + VRM 表情(1.0 expressions / 0.x blendShapeGroups)。""" +import re +import unicodedata + +import vrmio + +from . import morphbake +from .materials import _lin_rgb, _mmd_color, _morph_material +from .mathutil import _m3vec + +# MMD 标准表情名 → VRM 预设 +# 单眼眨眼(ウィンク…)不在表里:名字靠不住,按顶点在哪一边决定(wink_presets) +EXPR_1_0 = { + "まばたき": "blink", "瞬き": "blink", + "びっくり": "surprised", "怒り": "angry", "怒る": "angry", + "悲しみ": "sad", "困る": "sad", + "にこり": "happy", "笑い": "happy", "にやり": "happy", + "あ": "aa", "あ2": "aa", "い": "ih", "う": "ou", "え": "ee", "お": "oh", +} +# 「真面目」是严肃的眉毛,不是 relaxed(放松、愉快);relaxed 交给下面的组合。 +# 注意:MMD 标准表情里的「上」「下」是**眉毛**表情(眉パネル),不是视线, +# 所以不映射到 lookUp / lookDown(以前映射了,VRM 里一看上方眉毛就跳起来)。 +# MMD 没有标准的视线表情,视线交给 lookAt(type=bone)。 +# VRM 0.x 的 presetName 规范里是小写枚举(three-vrm 也只认小写,"Joy" 会被当成自定义表情) +EXPR_0X = { + "まばたき": "blink", "瞬き": "blink", + "怒り": "angry", "悲しみ": "sorrow", "困る": "sorrow", + "にこり": "joy", "笑い": "joy", + "あ": "a", "あ2": "a", "い": "i", "う": "u", "え": "e", "お": "o", +} + + +# 中文表情名(整张脸,单独对应一个预设;比日文名、英文名优先级低)。左右单眼的「左眨眼」等走 _WINK +EXPR_CN = {"眨眼": "blink", "闭眼": "blink", "啊": "aa", "阿": "aa", "咿": "ih", "伊": "ih", "呜": "ou", "乌": "ou", + "诶": "ee", "欸": "ee", "哦": "oh", "喔": "oh", "开心": "happy", "高兴": "happy", "微笑": "happy", + "生气": "angry", "愤怒": "angry", "伤心": "sad", "难过": "sad", "悲伤": "sad", + "惊讶": "surprised", "吃惊": "surprised", "放松": "relaxed"} + +# 英文表情名(FBX 等转来的模型)→ VRM 1.0 预设。只在日文名没占用这个预设时才用。 +# VRChat:vrc.v_aa / vrc.blink_left VRoid:Fcl_MTH_A / Fcl_EYE_Close_L / Fcl_ALL_Joy +# Unity 酱:MTH_A / EYE_DEF_C(闭眼) 通用:blink、mouth_a、happy … +_EN_VOWEL = {"a": "aa", "aa": "aa", "i": "ih", "ih": "ih", "u": "ou", "ou": "ou", + "e": "ee", "ee": "ee", "o": "oh", "oh": "oh"} +_EN_EMO = {"joy": "happy", "happy": "happy", "smile": "happy", "angry": "angry", "anger": "angry", + "sorrow": "sad", "sad": "sad", "fun": "relaxed", "relaxed": "relaxed", + "surprised": "surprised", "surprise": "surprised", "neutral": "neutral"} +_TO_0X = {"happy": "joy", "aa": "a", "ih": "i", "ou": "u", "ee": "e", "oh": "o", "sad": "sorrow", + "relaxed": "fun", "blinkLeft": "blink_l", "blinkRight": "blink_r", "lookUp": "lookup", + "lookDown": "lookdown", "lookLeft": "lookleft", "lookRight": "lookright"} + + +# 情绪预设组合眉 / 眼 / 嘴(像 VRoid 的 Fcl_ALL_*)。MMD 的情绪表情是按面板拆开的, +# 一个预设只对应一个表情时,sad / angry 只动眉毛、happy / surprised 只动眼睛,游戏里很弱。 +# 每个部位:(PMX 面板:1 眉 / 2 目 / 3 口, [(候选表情名, 权重)],取第一个模型里有的)。 +# 闭眼类的眼睛表情(なごみ、笑い)不用半权重:很多模型是把瞳孔压扁来闭眼,一半时瞳孔缩成小点。 +# 眼睛是闭着笑的预设(BLINK_BLEND)设 overrideBlink: blend,不然再眨眼会闭两遍; +# 别的预设不设——游戏播难过、生气时照样眨眼,blend 会把眨眼压没。 +# 候选可以是一个名字,也可以是几个名字的元组(ARKit 的左右各一个:都有才算,一起用); +# EN 是「英文部位名」:VRoid 的 Fcl_BRW_Angry / Fcl_EYE_Joy / Fcl_MTH_Sad、Mouth_Sad 之类(_en_part)。 +# 每个部位按 MMD 名 → 英文部位名 → ARKit 的顺序找,取第一个模型里有的。 +EN = "@en" +_L_R = lambda a: (a + "Left", a + "Right") # noqa: E731 ARKit 的左右一对 +COMBO = { + "happy": [(1, [("にこり", 1.0), ("にこり2", 1.0), ("喜び", 1.0), ("上", 0.3), (EN, 1.0)]), + (2, [("笑い", 1.0), ("笑い2", 1.0), ("喜び", 1.0), ("なごみ", 1.0), (EN, 1.0), + (_L_R("eyeBlink"), 0.8)]), + (3, [("にやり", 1.0), ("口角上げ", 1.0), ("にやり2", 1.0), (EN, 1.0), (_L_R("mouthSmile"), 1.0)])], + # 生气比 MMD 原表情含蓄(和 VRoid 的 Angry 差不多):VRM 预设通常和眨眼、口型、别的预设叠着用 + # (游戏常拿 angry 当「痛苦、用力」,再叠 ih / oh / 闭眼)。满值的「怒り」皱眉太重、「キリッ」是瞪眼、 + # 「∧」拱起的嘴叠上张嘴就成了龇牙,所以都降权重,嘴优先用嘴角下撇 + "angry": [(1, [("怒り", 0.5), (EN, 0.5), (_L_R("browDown"), 0.5)]), + (2, [("怒り目", 0.3), ("キリッ", 0.3), ("じと目", 0.25), ("ジト目", 0.25), (EN, 0.3), + (_L_R("eyeSquint"), 0.3)]), + (3, [("口角下げ", 0.4), ("ムッ", 0.4), ("∧", 0.3), ("怒った", 0.3), (EN, 0.4), + (_L_R("mouthFrown"), 0.4)])], + # 难过不用「じと目」「∧」:半眯眼 + 撇嘴就是生气的样子(游戏里 sad 和 angry 分不出来)。 + # 星铁系模型没有难过的眼形,只用眉毛 +「心配する」(担心的波浪嘴) + "sad": [(1, [("困る", 1.0), ("悲しい", 1.0), ("悲しむ", 1.0), (EN, 1.0), ("browInnerUp", 1.0)]), + (2, [("悲しむ", 0.6), ("垂れ目", 0.6), (EN, 0.6)]), + (3, [("心配する", 1.0), ("口角下げ", 0.5), (EN, 1.0), (_L_R("mouthFrown"), 0.7)])], + "relaxed": [(1, [("にこり", 0.5), ("喜び", 0.5), ("上", 0.2), (EN, 0.5)]), + (2, [("慈愛", 1.0), ("笑い目", 1.0), ("喜び", 0.7), ("なごみ", 1.0), (EN, 1.0), + (_L_R("eyeBlink"), 0.4)]), + (3, [("にやり", 0.6), ("口角上げ", 0.6), (EN, 0.6), (_L_R("mouthSmile"), 0.6)])], + # 惊讶只睁眼、抬眉,不张嘴:常和口型(aa / oh)、生气叠用,再带张嘴会撑得过大 + "surprised": [(1, [("上", 0.7), (EN, 0.7), (("browInnerUp",) + _L_R("browOuterUp"), 0.7)]), + (2, [("びっくり", 1.0), ("見開く", 1.0), ("驚かす", 1.0), (EN, 1.0), (_L_R("eyeWide"), 1.0)])], +} +# 名字对应不上单个表情时的退路(1.0 名):ARKit 的眨眼、口型(粗略:张嘴 / 嘟嘴 / 噘圆 / 咧嘴)。 +# ARKit 的笑眼用 eyeBlink 半闭(eyeSquint 只抬下眼睑,很多模型几乎看不出来)。 +# 第一项必须有,后面的有就加上 +FALLBACK = {"blink": [(_L_R("eyeBlink"), 1.0)], + "aa": [(("jawOpen",), 1.0)], "ou": [(("mouthPucker",), 1.0)], + "oh": [(("mouthFunnel",), 1.0), (("jawOpen",), 0.3)], + # mouthStretch 单用是嘴角往下拉的苦脸:e / i 要和 mouthSmile、一点张嘴混起来 + "ee": [(_L_R("mouthStretch"), 0.4), (_L_R("mouthSmile"), 0.4), (("jawOpen",), 0.25)], + "ih": [(_L_R("mouthStretch"), 0.3), (_L_R("mouthSmile"), 0.3), (("jawOpen",), 0.12)]} +# VRM 0.x 没有 surprised 预设:和 VRoid 的 0.x 一样写成 unknown、名字叫 Surprised +BLINK_BLEND = {"happy", "relaxed"} +_COMBO_0X = {"happy": "joy", "angry": "angry", "sad": "sorrow", "relaxed": "fun", "surprised": None} +PRESETS_1 = {"happy", "angry", "sad", "relaxed", "surprised", "neutral", "aa", "ih", "ou", "ee", "oh", + "blink", "blinkLeft", "blinkRight", "lookUp", "lookDown", "lookLeft", "lookRight"} +PRESETS_0 = {"neutral", "a", "i", "u", "e", "o", "blink", "joy", "angry", "sorrow", "fun", + "lookup", "lookdown", "lookleft", "lookright", "blink_l", "blink_r"} + + +def _covers(big, small): + """big 的偏移已经包含了 small(八成以上顶点相同、幅度一半以上):两个一起用就动两遍。 + 比如有的模型「キリッ」「垂れ目」里自带了「怒り」「困る」的眉毛。""" + shared = [v for v in small if v in big] + if not small or len(shared) < 0.8 * len(small): + return False + a = sum(abs(big[v][0]) + abs(big[v][1]) + abs(big[v][2]) for v in shared) + b = sum(abs(small[v][0]) + abs(small[v][1]) + abs(small[v][2]) for v in shared) + return b > 0 and a >= 0.5 * b + + +def _key(name): + """比较用的名字:全角半角统一(キリッ = キリッ、2 = 2)、小写、去掉 blendShape. / vrc. 前缀和 + 英文分隔符(_ . - 空格),结尾的 _L / _R 写成 left / right(eyeBlink_L = eyeBlinkLeft)。 + ∧ ω ▲ 这类符号表情名不动。""" + s = unicodedata.normalize("NFKC", name or "").strip().lower() + s = re.sub(r"^(?:blendshape\d*|vrc)\.", "", s) + s = re.sub(r"[_.\- ]+([lr])$", lambda m: "left" if m.group(1) == "l" else "right", s) + return re.sub(r"[_.\- ]+", "", s) + + +_TABLE_KEY = {True: {_key(n): p for n, p in EXPR_1_0.items()}, False: {_key(n): p for n, p in EXPR_0X.items()}} +_CN_KEY = {_key(n): p for n, p in EXPR_CN.items()} + + +class Lookup: + """模型里的表情名索引:按 _key 找;找不到时认变体后缀 A / B / 1 / 2 / 3(怒りA、にこりB、笑い2), + 不认 L / R 这类单边的。""" + + def __init__(self, names): + self.names = list(names) + self.by_key = {} + for n in self.names: + self.by_key.setdefault(_key(n), n) + + def get(self, cand): + k = _key(cand) + if k in self.by_key: + return self.by_key[k] + for suf in ("a", "b", "1", "2", "3"): + if k + suf in self.by_key: + return self.by_key[k + suf] + return None + + def all(self, cands): + """几个名字都有 → 实际名字的元组;缺一个就 None。""" + got = tuple(self.get(c) for c in cands) + return got if all(got) and len(set(got)) == len(got) else None + + +_EN_PART_WORD = {"brow": 1, "brw": 1, "eyebrow": 1, "eyebrows": 1, + "eye": 2, "eyes": 2, "mouth": 3, "mth": 3, "lip": 3, "lips": 3} +# 每种情绪的英文词,按优先顺序(嘴:smile 是抿嘴笑,laugh 是张嘴大笑,先用 smile) +_EN_FEEL_WORDS = {"happy": ["joy", "happy", "smile", "laugh"], "angry": ["angry", "anger", "mad"], + "sad": ["sorrow", "sad", "trouble", "worried", "worry"], + "relaxed": ["fun", "relaxed", "relax", "gentle"], + "surprised": ["surprised", "surprise", "shock", "wide"]} +_EN_SIDE = {"l", "r", "left", "right"} + + +def _en_words(name): + """Fcl_BRW_Angry → [fcl, brw, angry];Mouth_Smile1 → [mouth, smile];eyeSmileLeft → [eye, smile, left]。""" + s = unicodedata.normalize("NFKC", name or "") + s = re.sub(r"([a-z])([A-Z])", r"_", s).lower() + return [re.sub(r"\d+$", "", w) for w in re.split(r"[^a-z0-9]+", s) if w] + + +def _en_part(lookup, preset, part): + """英文部位名里找「这个部位 + 这种情绪」的表情:VRoid 的 Fcl_EYE_Joy、通用的 Mouth_Sad 等。 + 单边的(带 L / R)不算;有几个时按情绪词的优先顺序、再按模型里的顺序。""" + best = None + for k, n in enumerate(lookup.names): + ws = _en_words(n) + if not ws or set(ws) & _EN_SIDE or "all" in ws: + continue + parts = {_EN_PART_WORD[w] for w in ws if w in _EN_PART_WORD} + feels = [i for i, w in enumerate(_EN_FEEL_WORDS[preset]) if w in ws] + if parts == {part} and feels: + rank = (min(feels), k) + if best is None or rank < best[0]: + best = (rank, n) + return best[1] if best else None + + +def _covers_any(deltas, a, b): + """两组表情(各是名字元组)动的是不是同一批顶点(任一方向 _covers)。""" + def merged(names): + out = {} + for n in names: + for v, d in deltas[n].items(): + o = out.get(v, (0.0, 0.0, 0.0)) + out[v] = (o[0] + d[0], o[1] + d[1], o[2] + d[2]) + return out + da, db = merged(a), merged(b) + return _covers(da, db) or _covers(db, da) + + +def combo_recipes(deltas, panel, lookup=None): + """→ {预设(1.0 名): [(表情名, 权重, 部位 1 眉 / 2 目 / 3 口)]}(ARKit 左右一对时同一部位有两项)。 + + deltas:表情名 → 顶点偏移(只算有顶点偏移的表情);panel:表情名 → PMX 面板。 + 每个部位按 COMBO 的候选顺序找(名字按 Lookup 规则匹配)。MMD 名的候选放在别的脸部面板 + (眉 / 目 / 口)时不算(比如眼睛面板的「喜び」不当眉毛);「其他」面板不限制(有的模型眉毛放在那里)。 + 和已选的部位动同一批顶点(_covers)的候选跳过、换下一个。至少两个部位找到才组合。 + """ + lookup = lookup or Lookup(deltas) + out = {} + for p, parts in COMBO.items(): + got = [] # [(名字元组, 权重, 部位)] + for pn, cands in parts: + for c, w in cands: + if c == EN: + n = _en_part(lookup, p, pn) + names = (n,) if n else None + elif isinstance(c, tuple): + names = lookup.all(c) + else: + n = lookup.get(c) + names = (n,) if n and panel.get(n) in (pn, 0, 4, None) else None + if not names or any(n not in deltas for n in names): + continue + if all(not set(names) & set(g[0]) and not _covers_any(deltas, names, g[0]) for g in got): + got.append((names, w, pn)) + break + if len(got) >= 2: + out[p] = [(n, w, pn) for names, w, pn in got for n in names] + return out + + +_WINK = re.compile(r"ウィンク|ウィンク|wink", re.I) +_BLINK_SIDE = re.compile(r"(?:blink|eye_?close[d]?|eye_def_c)[._ ]?(?:l|r|left|right)$|[左右]眨眼|眨眼[左右]", re.I) + + +def _wink_rank(name): + """单眼闭眼的表情 → 优先级(0 = 名字就是单眼闭眼:eyeBlinkLeft、blink_R、左眨眼; + 1 = ウィンク;2 = ウィンク2 这类笑眼版);不是单眼闭眼 → None。""" + if _BLINK_SIDE.search(re.sub(r"(?<=[a-z])(?=[A-Z])", "_", name or "")): + return 0 + if _WINK.search(name or ""): + return 2 if re.search(r"[22]", name) else 1 + return None + + +def _wink_sides(flat, vertices): + """→ {("L" / "R", 优先级): 表情名},同一格取最前面的。 + + MMD 惯例「ウィンク」闭左眼、「ウィンク右」闭右眼、「ウィンク2」是同一只眼的笑眼版, + 但不少模型不守(鸣潮的「ウィンク2」闭右眼,有的「ウィンク」闭右眼);ARKit 的 eyeBlinkLeft + 是角色自己的左眼还是镜像也看工具。所以看顶点:PMX 里角色的左边是 +X,动的顶点九成以上在一边才算。 + """ + out = {} + for n, d, _, _ in flat: + rank = _wink_rank(n) + if not d or rank is None: + continue + left = sum(1 for v in d if vertices[v]["pos"][0] > 0) / len(d) + side = "L" if left >= 0.9 else "R" if left <= 0.1 else None + if side: + out.setdefault((side, rank), n) + return out + + +# ---- 补充的自定义表情(add_extras):名字统一,程序按名字就能找到 +# 关掉眼睛高光的表情(模型自带时用它;几组高光各有一个时合起来) +_HL_OFF = re.compile(r"(ハイライト|ハイライト|高光|目光|瞳光|eye[ _]?hi\d*|hi[ _]?light|high[ _]?light)" + r"[ _]*(消し?|消失|消去|オフ|オフ|off|なし|無し|hide|隠し?)", re.I) +# 眼睛高光材质(模型没有上面的表情时,生成一个把它们收起来的表情) +_HL_MAT = re.compile(r"目光|瞳光|ハイライト|ハイライト|高光|high[ _]?light|hi[ _]?light|eye[ _]?hi(?![a-z])", re.I) +_HL_HI = re.compile(r"(?:^|[^a-z])hi\d*(?:[^a-z]|$)", re.I) # 「hi」「hi2」「+hi」这样单独的词 +_HL_EYE = re.compile(r"目|瞳|眼|eye", re.I) +_HL_NOT = re.compile(r"髪|髮|发|hair", re.I) # 头发高光不算 +# 吐舌:按顺序取模型里第一个有的(てへぺろ 还带着眨一只眼,放最后) +TONGUE = ["舌出し", "舌だし", "ぺろっ", "ぺろり", "べー", "吐舌", "吐舌头", "tongueOut", "tongue_out", "てへぺろ"] + + +def _highlight_materials(model): + """眼睛高光材质的序号:名字像高光(目光、ハイライト、eye hi …),或名字里有单独的 hi、 + 又像眼睛(eye hi1、MI_Eye+hi);头发高光除外。""" + tex = model.get("textures") or [] + out = [] + for mi, mat in enumerate(model["materials"]): + name = mat.get("name") or "" + t = mat.get("tex", -1) + tname = tex[t].replace("\\", "/").rsplit("/", 1)[-1] if 0 <= t < len(tex) else "" + if _HL_NOT.search(name) or mat["faces"] < 3: + continue + if _HL_MAT.search(name) or (_HL_HI.search(name) and _HL_EYE.search(name)) or \ + (_HL_EYE.search(name) and _HL_MAT.search(tname)): + out.append(mi) + return out + + +def _collapse_morph(model, mats): + """把这些材质的顶点各自收到所在那一块(相连的面)的中心:面积为 0,看不见了。 + → PMX 顶点表情的 offsets(和别的材质共用的顶点不动)。""" + faces = model["faces"] + owner = {} # 顶点 → 用到它的材质(只记是不是全在 mats 里) + ranges, cur = [], 0 + for mi, mat in enumerate(model["materials"]): + ranges.append((cur, cur + mat["faces"])) + cur += mat["faces"] + want = set(mats) + for mi, (a, b) in enumerate(ranges): + inside = mi in want + for vi in faces[a:b]: + owner[vi] = owner.get(vi, True) and inside + parent = {} + + def find(x): + while parent.setdefault(x, x) != x: + parent[x] = parent[parent[x]] + x = parent[x] + return x + for mi in mats: + a, b = ranges[mi] + for k in range(a, b - 2, 3): + ra, rb, rc = find(faces[k]), find(faces[k + 1]), find(faces[k + 2]) + parent[rb] = ra + parent[find(rc)] = ra + groups = {} + for vi in parent: + if owner.get(vi): + groups.setdefault(find(vi), []).append(vi) + verts = model["vertices"] + offsets = [] + for vs in groups.values(): + c = [sum(verts[v]["pos"][j] for v in vs) / len(vs) for j in range(3)] + for v in vs: + p = verts[v]["pos"] + offsets.append((v, (c[0] - p[0], c[1] - p[1], c[2] - p[2]))) + return offsets + + +def add_extras(model, log): + """补充两个自定义表情,加在 model["morphs"] 末尾(之后和别的表情一样转换): + + hideHighlight 关掉眼睛高光:模型有对应的表情(「ハイライト消し」「eye hi off」…)就用它(几个合成一组); + 没有就按材质名找眼睛高光,生成一个把这些面收成一点的顶点表情 + tongue 吐舌:模型里「舌出し」「ぺろっ」等表情的一组副本 + 模型已经有同名表情时不补。返回补上的名字。 + """ + morphs = model["morphs"] + names = {mo["name"] for mo in morphs} + added = [] + + def group(name, subs): + morphs.append({"name": name, "name_en": name, "panel": 4, "kind": 0, "offsets": [(i, 1.0) for i in subs]}) + added.append(name) + + if "hideHighlight" not in names: + offs = [i for i, mo in enumerate(morphs) if _HL_OFF.search(mo["name"] or "")] + if offs: + group("hideHighlight", offs) + log("表情:补充 hideHighlight(%s)" % " + ".join(morphs[i]["name"] for i in offs)) + else: + mats = _highlight_materials(model) + offsets = _collapse_morph(model, mats) if mats else [] + if offsets: + morphs.append({"name": "hideHighlight", "name_en": "hideHighlight", "panel": 4, "kind": 1, + "offsets": offsets}) + added.append("hideHighlight") + log("表情:补充 hideHighlight(隐藏材质 %s)" + % "、".join(model["materials"][mi]["name"] for mi in mats)) + elif any(mo["kind"] in (1, 0) for mo in morphs): + log("表情:未找到眼睛高光材质或关闭高光的表情,未补充 hideHighlight") + if "tongue" not in names: + low = {} + for i, mo in enumerate(morphs): + low.setdefault((mo["name"] or "").strip().lower(), i) + src = next((low[n.lower()] for n in TONGUE if n.lower() in low), None) + if src is not None: + group("tongue", [src]) + log("表情:补充 tongue(%s)" % morphs[src]["name"]) + return added + + +def wink_presets(flat, vertices, is1): + """单眼眨眼 → {表情名: blinkLeft / blinkRight}(0.x:blink_l / blink_r);按 _wink_rank 的优先级。""" + sides = _wink_sides(flat, vertices) + to = {"L": "blinkLeft" if is1 else "blink_l", "R": "blinkRight" if is1 else "blink_r"} + out = {} + for side in ("L", "R"): + n = next((sides[(side, r)] for r in (0, 1, 2) if (side, r) in sides), None) + if n: + out[n] = to[side] + return out + + +def _table_preset(name, is1, keys=()): + """MMD 日文名、中文名 → 预设(按 _key 比较,キリッ / キリッ、あ2 / あ2 都认)。 + keys:模型里所有表情名的 _key;给了的话也认变体后缀(啊2、まばたきA),前提是模型里没有不带后缀的那个。""" + k = _key(name) + if k not in _TABLE_KEY[is1] and k not in _CN_KEY: + m = re.fullmatch(r"(.+?)[ab123]", k) + if m and m.group(1) not in keys: + k = m.group(1) + p = _TABLE_KEY[is1].get(k) + if p: + return p + p = _CN_KEY.get(k) + if p and not is1: + p = _TO_0X.get(p, p) + p = p if p in PRESETS_0 else None + return p + + +def _preset_en(name, is1): + s = (name or "").strip().lower().replace("-", "_").replace(" ", "_") + s = re.sub(r"^blendshape\d*\.", "", s) + p = None + m = re.fullmatch(r"(?:.*[._])?(?:mth|mouth|v)[._]?(aa|ih|ou|ee|oh|a|i|u|e|o)", s) \ + or re.fullmatch(r"(aa|ih|ou|ee|oh|a|i|u|e|o)", s) + if m: + p = _EN_VOWEL[m.group(1)] + elif re.search(r"mouth_?open$", s): + p = "aa" + elif re.fullmatch(r"(?:.*[._])?look_?(up|down|left|right)", s): + p = "look" + re.fullmatch(r"(?:.*[._])?look_?(up|down|left|right)", s).group(1).capitalize() + elif re.search(r"(blink|eye_?close[d]?|eye_def_c)[._]?(l|left)$", s): + p = "blinkLeft" + elif re.search(r"(blink|eye_?close[d]?|eye_def_c)[._]?(r|right)$", s): + p = "blinkRight" + elif re.search(r"(?:^|[._])(blink|eye_?close[d]?|eye_def_c)$", s): + p = "blink" + else: + m = re.search(r"(?:^|[._])(?:all_|face_)?([a-z]+)$", s) + if m and m.group(1) in _EN_EMO and (s == m.group(1) or re.search(r"(?:^|_)(?:fcl_)?all_|^face_", s)): + p = _EN_EMO[m.group(1)] + if p and not is1: + p = _TO_0X.get(p, p) + if p not in PRESETS_0: # surprised 在 0.x 里不是预设 + p = None + return p + + +def _flatten_morphs(morphs, model=None, extra_bone=None, weights=None): + """把顶点 / 骨骼 / UV / 材质表情(含グループ展开)整理成 + [(名字, {顶点: (dx,dy,dz)}, [(材质, 运算, 28 个值, 比率)], {顶点: (du,dv)})]。 + + 材质表情(kind 8)在 MMD 里常用来显示/隐藏部件(脸红、换道具), + VRM 对应 expression 的 materialColorBinds。材质号 -1 表示所有材质。 + 骨骼表情(kind 2)给了 model 时烘焙成顶点偏移(morphbake.BoneBaker); + UV 表情(kind 3)留给 build_expressions 换成贴图偏移。 + extra_bone:[(名字, 骨骼表情 offsets)],追加的合成表情(视线),同样烘焙。 + weights:已经算好的不带付与别名的顶点权重(mesh.vertex_weights(..., {})),给了就不再算。 + """ + baker = morphbake.BoneBaker(model, weights) if model is not None else None + cache = {} + + def resolve(i, seen): + if i in seen: + return {}, [], {} + if i in cache: + return cache[i] + seen = seen | {i} + mo = morphs[i] + k = mo["kind"] + if k == 1: + d = {} + for vi, off in mo["offsets"]: + if abs(off[0]) + abs(off[1]) + abs(off[2]) > 1e-9: + d[vi] = (off[0], off[1], off[2]) + res = d, [], {} + elif k == 2: + res = (baker.deltas(mo["offsets"]) if baker else {}), [], {} + elif k == 3: + res = {}, [], {vi: (off[0], off[1]) for vi, off in mo["offsets"] + if abs(off[0]) + abs(off[1]) > 1e-9} + elif k == 8: + res = {}, [(mi, op, vals, 1.0) for mi, op, vals in mo["offsets"]], {} + elif k == 0: + out, mats, uvs = {}, [], {} + for sub, rate in mo["offsets"]: + if not (0 <= sub < len(morphs)) or abs(rate) < 1e-9: + continue + sd, sm, su = resolve(sub, seen) + for vi, d in sd.items(): + ox, oy, oz = out.get(vi, (0.0, 0.0, 0.0)) + out[vi] = (ox + d[0] * rate, oy + d[1] * rate, + oz + d[2] * rate) + for vi, d in su.items(): + ox, oy = uvs.get(vi, (0.0, 0.0)) + uvs[vi] = (ox + d[0] * rate, oy + d[1] * rate) + mats.extend((mi, op, vals, r * rate) for mi, op, vals, r in sm) + res = out, mats, uvs + else: + res = {}, [], {} + cache[i] = res + return res + + out = [] + for i, mo in enumerate(morphs): + if mo["kind"] not in (0, 1, 2, 3, 8): + continue + d, m, u = resolve(i, frozenset()) + if d or m or u: + out.append((mo["name"], d, m, u)) + for name, offsets in extra_bone or (): + d = baker.deltas(offsets) if baker else {} + if d: + out.append((name, d, [], {})) + return out + + +def uniq_name(name, used): + """name 已在 used 里时加 _2、_3 … 直到不重名。""" + if name not in used: + return name + k = 2 + while "%s_%d" % (name, k) in used: + k += 1 + return "%s_%d" % (name, k) + + +_REPORT_ORDER = ["happy", "angry", "sad", "relaxed", "surprised", "blink", "blinkLeft", "blinkRight", + "aa", "ih", "ou", "ee", "oh"] + + +def report(expr_preset, blend_groups, is1, log, sources0=None): + """一行汇总:每个预设用了哪些表情(权重不是 1 的标 ×w),缺哪些。眨眼、「あ」缺了是警告。 + sources0:0.x 组合表情的组名 → 来源表情(「上+びっくり」;0.x 的 surprised 组名是 Surprised)。""" + got, miss = [], [] + for p in _REPORT_ORDER: + if is1: + obj = expr_preset.get(p) + src = obj and ((obj.get("extras") or {}).get("source") or p) + ws = [b["weight"] for b in (obj or {}).get("morphTargetBinds", [])] + else: + p0 = _TO_0X.get(p, p) if p != "surprised" else None + gr = next((g for g in blend_groups if g["presetName"] == p0 or + (p0 is None and g["name"] == "Surprised")), None) + src = gr and ((sources0 or {}).get(gr["name"]) or gr["name"]) + ws = [b["weight"] / 100.0 for b in (gr or {}).get("binds", [])] + if not src: + miss.append(p) + continue + names = src.split("+") if len(ws) > 1 and len(src.split("+")) == len(ws) else [src] + if len(names) == len(ws): + src = " + ".join(n if abs(w - 1) < 1e-6 else "%s×%g" % (n, round(w, 3)) for n, w in zip(names, ws)) + got.append("%s ← %s" % (p, src)) + log("表情预设:" + (";".join(got) or "无") + ("" if not miss else " · 未找到:" + "、".join(miss)), + "warn" if {"blink", "aa"} & set(miss) else None) + + +def build_expressions(flat, prims, mats, mat_gidx, gb, xf, vmat, is1, sparse_morphs, log, combo=True, hidden=()): + """表情 → 各 primitive 的 morph target + VRM 表情。 + + flat:_flatten_morphs 的结果;prims:mesh.build_primitives 的结果(往 pr["tmap"] 里写 morph target); + UV 表情能表示成整个材质的缩放 + 偏移时写 textureTransformBinds(0.x:_MainTex_ST); + mats:materials.MaterialBuilder;vmat:T-pose 后每个顶点的混合旋转(表情偏移要跟着转)。 + combo:情绪预设组合眉 / 眼 / 嘴(COMBO);原来单个对应的表情回到自定义表情。 + hidden:只做 morph target、不做表情的名字(视线表情的深度场,见 morphbake.split_gaze)。 + 返回 dict:target_names、preset / custom(1.0)、blend_groups(0.x)。 + 绑定里的 index 先是全局的 morph target 序号、node / mesh 先写 0,分好网格后由 + mesh.remap_binds 改成各网格里的序号和网格节点。 + """ + materials = mats.model["materials"] + target_names = [] + target_set = set() + expr_preset = {} + expr_custom = {} + blend_groups = [] + sources0 = {} + n_mat_expr = 0 + winks = wink_presets(flat, mats.model["vertices"], is1) + # 日文名 / 中文名占用的预设,英文名不抢 + keys = {_key(n) for n, *_ in flat} + jp_presets = {_table_preset(n, is1, keys) for n, *_ in flat} - {None} | set(winks.values()) + used_0x = set() + mat_verts = None + n_uv_expr = n_uv_bad = 0 + slot_of = {} # PMX 表情名 → morph target 序号(组合预设用) + delta_of = {} # PMX 表情名 → 顶点偏移(组合时查重叠) + for mname, deltas, _, _ in flat: + if deltas: + delta_of.setdefault(mname, deltas) + panel = {mo["name"]: mo.get("panel") for mo in mats.model["morphs"]} + lookup = Lookup(delta_of) + recipes = combo_recipes(delta_of, panel, lookup) if combo else {} + + def add_target(name, deltas): + """一个 morph target → 序号。只写进它动得到的 primitive(pr["tmap"][序号] = accessor), + 其余的在分网格(mesh.group_meshes)后按需补零。""" + slot = len(target_names) + for pr in prims: + loc = pr["local"] + items = [] + for vi, d in deltas.items(): + j = loc.get(vi) + if j is None: + continue + if vmat is not None and vmat[vi] is not None: + d = _m3vec(vmat[vi], d) + # 偏移量也要乘缩放(xf 是纯线性变换,正好适用于偏移)。 + # 以前用 xf_dir 只翻了轴没缩放,偏移大了 1/scale≈12 倍, + # 表情一开脸就拉成长刺。 + items.append((j, xf(d))) + if not items: + continue + if sparse_morphs: + # 稀疏存储:一个表情通常只动几百个顶点,密集存储每个表情 + # 每个 primitive 都要「顶点数 × 12 字节」 + items.sort() + acc = gb.add_sparse_accessor( + pr["vcount"], [j for j, _ in items], + [c for _, d in items for c in d], "VEC3") + else: + arr = [0.0] * (pr["vcount"] * 3) + for j, d in items: + arr[j * 3:j * 3 + 3] = d + acc = gb.add_accessor(arr, vrmio.FLOAT, "VEC3", 34962) + pr["tmap"][slot] = acc + # Unity 的 BlendShape 名在一个网格内必须唯一,重名时 UniVRM 导入直接抛 + # 「Blend shape name already exists」中断(开拓者 PMX 里有两个「手前」) + target_names.append(uniq_name(name, target_set)) + target_set.add(target_names[-1]) + return slot + + for mname, deltas, ops, uvs in flat: + slot = None + if deltas or mname in hidden: + slot = add_target(mname, deltas) + slot_of.setdefault(mname, slot) + if mname in hidden: + continue + + # 材质表情 → 目标颜色(权重 1 时的漫反射 RGBA) + colors = [] + for mi_, mat in enumerate(materials): + if mi_ not in mat_gidx: + continue + r = _morph_material(mat, ops, mi_) + if r is None: + continue + base = _mmd_color(mat["diffuse"], mat["ambient"]) + c = _mmd_color(*r) + if max(abs(c[k] - base[k]) for k in range(4)) < 1e-6: + continue + lit_c, shade_c, _, _ = mats.lit_shade(mat, c) + colors.append((mi_, lit_c, shade_c, max(abs(c[k] - base[k]) + for k in range(3)) > 1e-6)) + # UV 表情 → 贴图缩放 + 偏移(只用于出现在网格里的材质) + tex = [] + if uvs: + if mat_verts is None: + mat_verts = morphbake.material_vertices(mats.model) + binds, bad = morphbake.uv_binds(mats.model, uvs, mat_verts) + tex = [(mi_, sc, off) for mi_, sc, off in binds if mi_ in mat_gidx] + n_uv_bad += bad + if tex: + n_uv_expr += 1 + if slot is None and not colors and not tex: + continue + if colors: + n_mat_expr += 1 + + preset = winks.get(mname) or _table_preset(mname, is1, keys) + if not preset and not _WINK.search(mname): + preset = _preset_en(mname, is1) + if preset in jp_presets: + preset = None + if is1: + obj = {"morphTargetBinds": ([{"node": 0, "index": slot, + "weight": 1.0}] + if slot is not None else []), + "materialColorBinds": [ + b for mi_, c, sc, rgb in colors for b in ( + [{"material": mat_gidx[mi_], "type": "color", + "targetValue": _lin_rgb(c)}] + + # targetValue 规范要求正好 4 个分量:UniVRM 直接读 [3], + # 只写 RGB 会在导入时 IndexOutOfRange 中断 + ([{"material": mat_gidx[mi_], "type": "shadeColor", + "targetValue": _lin_rgb(sc) + [1.0]}] + if rgb else []))], + "textureTransformBinds": [ + {"material": mat_gidx[mi_], "scale": [sc[0], sc[1]], "offset": [off[0], off[1]]} + for mi_, sc, off in tex], + "isBinary": False} + # 规范要求这些数组非空(minItems 1):没有就不写 + for k_ in ("morphTargetBinds", "materialColorBinds", "textureTransformBinds"): + if not obj[k_]: + del obj[k_] + if preset and preset not in expr_preset: + # 记下来源的 PMX 表情名:界面里重新指定预设表情(vrm_edit)时要用 + obj["extras"] = {"source": mname} + expr_preset[preset] = obj + else: + # 自定义表情名必须唯一(PMX 里同名表情会互相覆盖) + expr_custom[uniq_name(mname, set(expr_custom) | PRESETS_1)] = obj + else: + # 同一个预设只给第一个(「あ」「あ2」都是 a 时,第二个当自定义) + if preset in used_0x: + preset = None + used_0x.add(preset) + blend_groups.append({ + "name": mname, + "presetName": preset or "unknown", + "binds": ([{"mesh": 0, "index": slot, "weight": 100}] + if slot is not None else []), + "materialValues": [ + v for mi_, c, sc, rgb in colors for v in ( + [{"materialName": mats.materials[mat_gidx[mi_]]["name"], + "propertyName": "_Color", "targetValue": c}] + + ([{"materialName": + mats.materials[mat_gidx[mi_]]["name"], + "propertyName": "_ShadeColor", + "targetValue": sc + [1.0]}] + if rgb else []))] + [ + # Unity 的 UV 原点在左下:v' = sv·v + ov 换成 ST 是 (sv, 1 - sv - ov) + {"materialName": mats.materials[mat_gidx[mi_]]["name"], + "propertyName": "_MainTex_ST", + "targetValue": [s_[0], s_[1], o_[0], 1.0 - s_[1] - o_[1]]} + for mi_, s_, o_ in tex], + "isBinary": False}) + if target_names: + log("表情:导出 %d 个 morph target(%s存储)" + % (len(target_names), "稀疏" if sparse_morphs else "密集")) + if n_mat_expr: + log("表情:%d 个包含材质变化(转为材质颜色绑定)" % n_mat_expr) + if n_uv_expr: + log("表情:%d 个 UV 表情转为贴图偏移" % n_uv_expr) + if n_uv_bad: + log("表情:%d 处 UV 表情不是整个材质统一平移 / 缩放,VRM 无法表示,已跳过" % n_uv_bad, "warn") + + for p, parts in recipes.items(): + label = "+".join(n for n, _, _ in parts) + binds = [(slot_of[n], w) for n, w, _ in parts] + if is1: + old = expr_preset.pop(p, None) + if old is not None: # 原来单个对应的表情回到自定义表情,界面里还能选 + src = (old.pop("extras", None) or {}).get("source") or p + expr_custom[uniq_name(src, set(expr_custom) | PRESETS_1)] = old + obj = {"morphTargetBinds": [{"node": 0, "index": s, "weight": w} for s, w in binds], + "isBinary": False, "extras": {"source": label}} + # 笑眼(已经闭着)时再眨眼会闭两遍(眼皮穿到脸颊里)。blend:情绪表情越强,眨眼越弱 + if p in BLINK_BLEND and any(pn == 2 for _, _, pn in parts): + obj["overrideBlink"] = "blend" + expr_preset[p] = obj + else: + p0 = _COMBO_0X[p] + if p0: + for gr in blend_groups: + if gr["presetName"] == p0: + gr["presetName"] = "unknown" + name = uniq_name(label if p0 else p.capitalize(), {g["name"] for g in blend_groups}) + sources0[name] = label + blend_groups.append({"name": name, + "presetName": p0 or "unknown", + "binds": [{"mesh": 0, "index": s, "weight": round(w * 100, 2)} for s, w in binds], + "materialValues": [], "isBinary": False}) + # ---- 名字对应不上的预设:ARKit 的眨眼 / 口型(FALLBACK),眨眼再退一步用左右单眼合起来 + def add_multi(p, binds, label): + if is1: + expr_preset[p] = {"morphTargetBinds": [{"node": 0, "index": slot_of[n], "weight": w} for n, w in binds], + "isBinary": False, "extras": {"source": label}} + else: + blend_groups.append({"name": uniq_name(label, {g["name"] for g in blend_groups}), + "presetName": _TO_0X.get(p, p), + "binds": [{"mesh": 0, "index": slot_of[n], "weight": round(w * 100, 2)} + for n, w in binds], + "materialValues": [], "isBinary": False}) + + def have(p): + return p in expr_preset if is1 else any(g["presetName"] == _TO_0X.get(p, p) for g in blend_groups) + + for p, items in FALLBACK.items(): + first = lookup.all(items[0][0]) + if have(p) or not first: + continue + binds = [(n, items[0][1]) for n in first] + for names, w in items[1:]: + binds += [(n, w) for n in lookup.all(names) or ()] + add_multi(p, binds, "+".join(n for n, _ in binds)) + by_side = {v: k for k, v in winks.items()} + lr = [by_side.get("blinkLeft" if is1 else "blink_l"), by_side.get("blinkRight" if is1 else "blink_r")] + if not have("blink") and all(n in slot_of for n in lr if n) and all(lr): + add_multi("blink", [(lr[0], 1.0), (lr[1], 1.0)], "+".join(lr)) + report(expr_preset, blend_groups, is1, log, sources0) + return {"target_names": target_names, "preset": expr_preset, "custom": expr_custom, + "blend_groups": blend_groups} diff --git a/convert/vrmconv/humanoid.py b/convert/vrmconv/humanoid.py new file mode 100644 index 0000000..44c153e --- /dev/null +++ b/convert/vrmconv/humanoid.py @@ -0,0 +1,685 @@ +# -*- coding: utf-8 -*- +"""骨骼:MMD 骨骼名 → VRM humanoid 骨位、付与骨合并、层级修正、A-pose → T-pose。""" +import math +import re + +from .mathutil import _I3, _align, _axis_angle, _m3mul, _m3T, _m3vec, _to_axis_angle + + +# --------------------------------------------------------- 骨骼名映射表 ---- +MMD_TO_VRM = { + "下半身": "hips", + "上半身": "spine", + "上半身2": "chest", + "上半身3": "upperChest", + "首": "neck", + "頭": "head", + # 「両目」是双眼共用的控制骨,不对应任何一只眼,不能映射成 leftEye + # (以前这么写,导致左右眼都绑到両目上,而真正的 左目 被挤掉)。 + "左目": "leftEye", "右目": "rightEye", + "左肩": "leftShoulder", "右肩": "rightShoulder", + "左腕": "leftUpperArm", "右腕": "rightUpperArm", + "左ひじ": "leftLowerArm", "右ひじ": "rightLowerArm", + "左肘": "leftLowerArm", "右肘": "rightLowerArm", + "左手首": "leftHand", "右手首": "rightHand", + "左足": "leftUpperLeg", "右足": "rightUpperLeg", + "左ひざ": "leftLowerLeg", "右ひざ": "rightLowerLeg", + "左足首": "leftFoot", "右足首": "rightFoot", + "左つま先": "leftToes", "右つま先": "rightToes", +} +# 手指不放进 MMD_TO_VRM:骨位名取决于规范版本和模型有哪几节,见 _finger_slots。 +# VRM 1.0:拇指 Metacarpal / Proximal / Distal,其余 Proximal / Intermediate / Distal +# VRM 0.x:拇指也是 Proximal / Intermediate / Distal(0.x 没有 Metacarpal) +# 两个版本都没有「食指~小指的 Metacarpal」,所以 人指0 之类不映射。 +_FINGERS = {"親指": "Thumb", "人指": "Index", "中指": "Middle", + "薬指": "Ring", "小指": "Little"} +_DIGITS = {"0": 0, "0": 0, "1": 1, "1": 1, "2": 2, "2": 2, "3": 3, "3": 3} + + +def _finger_key(name): + """「左人指2」→ ("left", "Index", 2);不是手指骨返回 None。""" + if not name or len(name) != 4 or name[0] not in "左右": + return None + f = _FINGERS.get(name[1:3]) + d = _DIGITS.get(name[3]) + if f is None or d is None: + return None + return ("left" if name[0] == "左" else "right"), f, d + + +def _finger_slots(finger, digits, is1): + """digits: 该手指在模型里出现的节号集合 → {节号: 骨位后缀}。""" + if finger != "Thumb": + return {d: s for d, s in ((1, "Proximal"), (2, "Intermediate"), + (3, "Distal")) if d in digits} + # 拇指按解剖位置对应:节号 0 = 掌根那节(1.0 Metacarpal / 0.x Proximal),1 = 1.0 Proximal / + # 0.x Intermediate,2 = Distal。两个版本同一根骨对应同一节,套同一个手部动作时拇指才一致 + # (以前 0.x 把没有 親指0 的两节拇指当成第一、二节,1.0 当成第二、三节) + names = ("Metacarpal", "Proximal", "Distal") if is1 else ("Proximal", "Intermediate", "Distal") + return {d: names[d] for d in (0, 1, 2) if d in digits} + +# 英文名兜底 +ALT_TO_VRM = { + "hips": "hips", "spine": "spine", "chest": "chest", + "upperchest": "upperChest", "neck": "neck", "head": "head", + "leye": "leftEye", "reye": "rightEye", + "lowerbody": "hips", "upperbody": "spine", "upperbody2": "chest", + "lshoulder": "leftShoulder", "rshoulder": "rightShoulder", + "larm": "leftUpperArm", "rarm": "rightUpperArm", + "lelbow": "leftLowerArm", "relbow": "rightLowerArm", + "lwrist": "leftHand", "rwrist": "rightHand", + "lleg": "leftUpperLeg", "rleg": "rightUpperLeg", + "lknee": "leftLowerLeg", "rknee": "rightLowerLeg", + "lankle": "leftFoot", "rankle": "rightFoot", + "ltoe": "leftToes", "rtoe": "rightToes", +} + +# 英文骨名(FBX 转来的 PMX 保留原名):去掉前缀和左右标记后**整段**匹配, +# 不会误伤 J_L_HairTail_00、skirt_L_01 这类非人形骨。 +# HumanIK / Mixamo / Unity:Character1_LeftUpLeg、mixamorig:LeftForeArm、Chr_LeftHandIndex1 +# VRoid:J_Bip_L_UpperArm、J_Bip_C_Chest Blender:thigh.L、upper_arm.R +# 3ds Max Biped:Bip001 L Thigh、Bip001 Spine1 +_EN_PREFIX = re.compile(r"^(?:character\d*|chr|bip0*1|jbipc|jbip|j|def|org|mch|armature|skeleton|root|rig|" + r"cc_base|valvebiped_bip01|bip01)(?=[a-z])") +_EN_SIDE = re.compile(r"(?:^|[^a-z])(l|r)(?:[^a-z]|$)|left|right") +_EN_BONES = { + "hips": "hips", "hip": "hips", "pelvis": "hips", + "spine": "spine", "spine0": "spine", "spine1": "chest", "spine01": "chest", "spine2": "upperChest", + "spine02": "upperChest", "chest": "chest", "upperchest": "upperChest", + "neck": "neck", "neck1": "neck", "head": "head", +} +_EN_LIMBS = { + "eye": "Eye", "shoulder": "Shoulder", "clavicle": "Shoulder", + "arm": "UpperArm", "upperarm": "UpperArm", + "forearm": "LowerArm", "lowerarm": "LowerArm", "elbow": "LowerArm", + "hand": "Hand", "wrist": "Hand", + "upleg": "UpperLeg", "upperleg": "UpperLeg", "thigh": "UpperLeg", "hip": "UpperLeg", + "leg": "LowerLeg", "lowerleg": "LowerLeg", "calf": "LowerLeg", "shin": "LowerLeg", "knee": "LowerLeg", + "foot": "Foot", "ankle": "Foot", + "toebase": "Toes", "toe": "Toes", "toes": "Toes", "toe0": "Toes", +} +_EN_FINGERS = {"thumb": "Thumb", "index": "Index", "middle": "Middle", "ring": "Ring", + "pinky": "Little", "little": "Little"} + + +def _en_bone(name, thumb_metacarpal=False): + """英文骨名 → ("slot", 骨位) / ("finger", (side, finger, 节号 0~3)) / None。 + + 节号按 MMD 的口径:拇指 0~2(VRM 1.0 的 Metacarpal / Proximal / Distal),其余手指 1~3; + HumanIK 的拇指是 Thumb1~3、指尖是 4,所以拇指减 1、第 4 节(指尖)丢掉。 + Unity / VRChat 的「Index Proximal.L」这类节名:其余手指 Proximal / Intermediate / Distal = 1~3; + 拇指在 Unity 和 VRM 0.x 里叫 Proximal / Intermediate / Distal(第一节在掌根)= 0~2, + VRM 1.0 风格叫 Metacarpal / Proximal / Distal——同一个 Proximal 指的节不一样, + 所以由调用方看整副骨架里有没有 ThumbMetacarpal(thumb_metacarpal)。 + """ + s = (name or "").split(":")[-1].split("|")[-1].lower() + m = _EN_SIDE.search(s.replace(".", "_").replace(" ", "_")) + side = None + if m: + side = "left" if (m.group(1) or m.group(0)).strip("_. ").startswith("l") else "right" + base = re.sub(r"left|right", "", s) + base = re.sub(r"(?:^|[_. ])[lr](?=[_. ]|$)", "_", base) # _L / .L / " L " / J_Bip_L_ + base = re.sub(r"[^a-z0-9]", "", base) + base = _EN_PREFIX.sub("", base) + if not base: + return None + if side is None: + v = _EN_BONES.get(base) + return ("slot", v) if v else None + if base.startswith("hand") and base[4:] and not base[4:].isdigit(): + base = base[4:] # HumanIK: LeftHandIndex1 + m = re.fullmatch(r"(thumb|index|middle|ring|pinky|little)(\d)", base) + if m: + f, d = _EN_FINGERS[m.group(1)], int(m.group(2)) + if f == "Thumb": + d -= 1 + return ("finger", (side, f, d)) if 0 <= d <= 3 and not (f != "Thumb" and d == 0) else None + m = re.fullmatch(r"(thumb|index|middle|ring|pinky|little)(metacarpal|proximal|intermediate|distal)", base) + if m: + f, seg = _EN_FINGERS[m.group(1)], m.group(2) + if f == "Thumb": + segs = {"metacarpal": 0, "proximal": 1, "distal": 2} if thumb_metacarpal else \ + {"proximal": 0, "intermediate": 1, "distal": 2} + else: + segs = {"proximal": 1, "intermediate": 2, "distal": 3} + return ("finger", (side, f, segs[seg])) if seg in segs else None + v = _EN_LIMBS.get(base) + return ("slot", side + v) if v else None + + +VRM_PARENT = { + "spine": "hips", "chest": "spine", "upperChest": "chest", + "neck": "upperChest", "head": "neck", + "leftEye": "head", "rightEye": "head", "jaw": "head", + "leftShoulder": "upperChest", "leftUpperArm": "leftShoulder", + "leftLowerArm": "leftUpperArm", "leftHand": "leftLowerArm", + "rightShoulder": "upperChest", "rightUpperArm": "rightShoulder", + "rightLowerArm": "rightUpperArm", "rightHand": "rightLowerArm", + "leftUpperLeg": "hips", "leftLowerLeg": "leftUpperLeg", + "leftFoot": "leftLowerLeg", "leftToes": "leftFoot", + "rightUpperLeg": "hips", "rightLowerLeg": "rightUpperLeg", + "rightFoot": "rightLowerLeg", "rightToes": "rightFoot", +} +for _s in ("left", "right"): + VRM_PARENT[_s + "ThumbMetacarpal"] = _s + "Hand" + VRM_PARENT[_s + "ThumbProximal"] = _s + "ThumbMetacarpal" + VRM_PARENT[_s + "ThumbIntermediate"] = _s + "ThumbProximal" + VRM_PARENT[_s + "ThumbDistal"] = _s + "ThumbIntermediate" + for _f in ("Index", "Middle", "Ring", "Little"): + VRM_PARENT[_s + _f + "Proximal"] = _s + "Hand" + VRM_PARENT[_s + _f + "Intermediate"] = _s + _f + "Proximal" + VRM_PARENT[_s + _f + "Distal"] = _s + _f + "Intermediate" + +REQUIRED_1_0 = ["hips", "spine", "head", + "leftUpperArm", "leftLowerArm", "leftHand", + "rightUpperArm", "rightLowerArm", "rightHand", + "leftUpperLeg", "leftLowerLeg", "leftFoot", + "rightUpperLeg", "rightLowerLeg", "rightFoot"] +REQUIRED_0X = REQUIRED_1_0 + ["chest", "neck"] + +# 自动补齐时的相对偏移(左、上、前) +_SYNTH = { + "spine": (0.0, 0.12, 0.0), "chest": (0.0, 0.12, 0.0), + "upperChest": (0.0, 0.10, 0.0), "neck": (0.0, 0.10, 0.0), + "head": (0.0, 0.12, 0.0), + "leftShoulder": (0.05, 0.10, 0.0), "rightShoulder": (-0.05, 0.10, 0.0), + "leftUpperArm": (0.12, 0.0, 0.0), "rightUpperArm": (-0.12, 0.0, 0.0), + "leftLowerArm": (0.25, 0.0, 0.0), "rightLowerArm": (-0.25, 0.0, 0.0), + "leftHand": (0.24, 0.0, 0.0), "rightHand": (-0.24, 0.0, 0.0), + "leftUpperLeg": (0.09, -0.08, 0.0), "rightUpperLeg": (-0.09, -0.08, 0.0), + "leftLowerLeg": (0.0, -0.40, 0.0), "rightLowerLeg": (0.0, -0.40, 0.0), + "leftFoot": (0.0, -0.40, 0.06), "rightFoot": (0.0, -0.40, 0.06), +} +_HIPS_Y = 0.90 + + +# ------------------------------------------------------------------ 工具 -- +def _norm(s): + return (s or "").strip().replace(" ", "").replace("_", "").lower() + + +def _clean_parents(bones): + """PMX 父骨索引表,越界/指向自己的记成 -1。""" + n = len(bones) + out = [] + for i, b in enumerate(bones): + p = b["parent"] + out.append(p if (0 <= p < n and p != i) else -1) + return out + + +def _is_ancestor(parents, a, b): + """a 是否是 b 的祖先(含 a == b)。遇到环也会停。""" + seen = set() + while 0 <= b < len(parents) and b not in seen: + if b == a: + return True + seen.add(b) + b = parents[b] + return False + + +def _reparent(parents, child, new_parent): + """把 child 挂到 new_parent 下;会成环就拒绝,返回是否成功。""" + if new_parent == child or _is_ancestor(parents, child, new_parent): + return False + parents[child] = new_parent + return True + + +def _append_aliases(bones, parents, eps, loose=0.5): + """「付与回転 100%」跟随付与親的骨 → 付与親,返回 {骨: 付与親}。 + + 典型是 足D / ひざD / 足首D:网格权重全在 D 骨上,D 骨靠 PMX 的付与 + 跟随 足 / ひざ / 足首 转动;而 humanoid 映射指向的是 足 / ひざ / 足首。 + glTF/VRM 没有付与机制,原样导出时转大腿网格完全不动。 + 和付与親在静止姿势下重合(差不超过 eps)、旋转也 1:1 跟随的,把权重和子骨并到付与親上是等价的。 + 不重合的(足首D 比 足首 靠后 2~3 cm 之类)也合并,条件是: + * 两者跟着同一根 humanoid 骨移动:各自的父骨往上找到的第一根 humanoid 骨相同(D 骨的父骨 + 并入后算付与親那边的)。中间隔着 腰キャンセル 之类在 VRM 里不动的骨不要紧;挂在别处 + (全ての親 下的道具骨)的不并,否则它会跟着付与親整体平移 + * 偏差不超过付与親那一节骨长(父骨→付与親、付与親→它的尾端,取长的)的 loose 倍 + * D 骨本身不是 humanoid 骨位(左目 跟随 両目 就不能并) + 合并后网格绕付与親的位置转,和 MMD 只差一个平移(偏差 2.5 cm、转 30° 时约 1 cm); + 不合并的话它在 VRM 里完全不动,挂在付与親子骨上的部分(鞋尖)却跟着转,鞋子从中间裂开。 + 付与率不是 1 的(ひざ補助 的 0.5 等)见 skeleton.split_partial;负的(腰キャンセル 的 -1)不动。 + """ + n = len(bones) + alias, near = {}, {} + for i, b in enumerate(bones): + ir = b.get("inherit_rot") + if not ir: + continue + src, rate = ir + if not (0 <= src < n) or src == i or abs(rate - 1.0) > 1e-4: + continue + im = b.get("inherit_mov") + if im and im[0] != src: + continue + if _is_ancestor(parents, i, src): # 付与親在自己下面:并过去会成环 + continue + d = math.dist(b["pos"], bones[src]["pos"]) + if d <= eps: + alias[i] = src + elif not MMD_TO_VRM.get(b["name"]): + near[i] = (src, d) + + def resolve(i): + seen = set() + while i in alias and i not in seen: + seen.add(i) + i = alias[i] + return i + hset = set(_map_humanoid(bones, True, {}).values()) if near else set() + + def anchor(i): # 往上第一根 humanoid 骨(并入的骨按付与親算) + seen = set() + while i >= 0 and i not in seen: + i = resolve(i) + if i in hset: + return i + seen.add(i) + i = parents[i] + return -1 + grew = True + while grew: # D 骨的父骨可能也是这样并进来的(ひざD → 足首D) + grew = False + for i, (src, d) in near.items(): + pi, ps = parents[i], parents[src] + if i in alias or pi < 0 or ps < 0 or anchor(pi) != anchor(ps): + continue + if d <= loose * max(math.dist(bones[ps]["pos"], bones[src]["pos"]), _bone_len(bones, parents, src)): + alias[i] = src + grew = True + return {i: resolve(i) for i in alias} + + +def _bone_len(bones, parents, i): + """骨 i 到它尾端的长度:尾端指向的骨,或尾端偏移;都没有就取到最远子骨的距离。""" + b = bones[i] + t = b.get("tail") + if b.get("tail_kind") == 1 and isinstance(t, int) and 0 <= t < len(bones) and t != i: + return math.dist(b["pos"], bones[t]["pos"]) + if b.get("tail_kind") == 0 and t and not isinstance(t, int) and any(t): + return math.hypot(*t) + return max((math.dist(b["pos"], bones[c]["pos"]) for c, p in enumerate(parents) if p == i), default=0.0) + + +def _pick_toes(bones, human, alias, weighted): + """humanoid 的脚趾:MMD 的 つま先 是足 IK 的末端点(鞋尖最前面),不是脚趾关节——动画转脚趾时 + 绕着鞋尖最前面那一点转。有 足先EX(准标准骨,脚掌和脚趾之间的关节,鞋头的权重常在它上面)就用它; + 没有的话,つま先 没挂网格就留着(转了也没影响),挂了网格就不设脚趾(VRM 里可以不设,鞋子跟着脚整体转)。 + weighted:挂了网格的骨(PMX 骨索引)。只处理 MMD 名字的骨。""" + names = {b["name"]: i for i, b in enumerate(bones) if i not in alias} + for side, jp in (("left", "左"), ("right", "右")): + slot = side + "Toes" + cur = human.get(slot) + if cur is not None and bones[cur]["name"] != jp + "つま先": + continue + ex = names.get(jp + "足先EX") + if ex is not None: + human[slot] = ex + elif cur is not None and cur in weighted: + del human[slot] + + +def _map_humanoid(bones, is1, alias): + """PMX 骨 → VRM humanoid 骨位,返回 {骨位: PMX 骨索引}。""" + human = {} + fingers = {} # (side, finger) → {节号: 骨索引} + alt = {} # PMX 英文名(name_en)对上的:骨位 → 骨索引,日文名都分完再补位 + en = {} # 英文骨名兜底:骨位 → 骨索引 + # HumanIK 的 LeftLeg 是小腿(大腿叫 LeftUpLeg);只有 Leg、没有 UpLeg / Thigh 时 Leg 才是大腿 + has_upleg = any(re.search(r"upleg|upperleg|thigh", (b["name"] or "").lower()) for b in bones) + thumb_mc = any(re.search(r"thumb.?metacarpal", b["name"] or "", re.I) for b in bones) + for i, b in enumerate(bones): + if i in alias: # 已并入付与親的骨不参与映射 + continue + fk = _finger_key(b["name"]) + if fk: + fingers.setdefault(fk[:2], {}).setdefault(fk[2], i) + continue + v = MMD_TO_VRM.get(b["name"]) + if v: + human.setdefault(v, i) + else: + # 英文名只补位:有的模型旁边另放一套控制骨(左肩調整 …),英文名和本体一样(L_Shoulder), + # 排在前面的话会抢走 左肩 的骨位,肩膀跑到模型外面 + v = ALT_TO_VRM.get(_norm(b.get("name_en") or "")) + if v: + alt.setdefault(v, i) + if not v: + r = _en_bone(b["name"], thumb_mc) + if r and r[0] == "finger": + en.setdefault(("finger",) + r[1][:2], {}).setdefault(r[1][2], i) + elif r: + slot = r[1] + if not has_upleg and slot.endswith("LowerLeg") and "leg" in _norm(b["name"]) \ + and not re.search(r"lower|calf|shin|knee", b["name"].lower()): + slot = slot.replace("LowerLeg", "UpperLeg") + en.setdefault(slot, i) + # 两种叫法的冲突(UE / Maya 常见): + # L_Clavicle + L_Shoulder:Clavicle 是肩、Shoulder 其实是上臂 + # Spine1~Spine4 而没有 Spine:第一节当 spine、最后一节当 upperChest、中间当 chest + pairs = [] # (肩骨位, 上臂骨位, 锁骨, 「肩」骨) + for side in ("left", "right"): + sh = [i for i, b in enumerate(bones) if i not in alias + and re.search(r"clavicle|shoulder", b["name"] or "", re.I) + and (_en_bone(b["name"]) or ("", ""))[1] == side + "Shoulder"] + if len(sh) == 2 and side + "UpperArm" not in en: + par = bones[sh[1]].get("parent") + a, b = (sh[0], sh[1]) if par == sh[0] else (sh[1], sh[0]) if bones[sh[0]].get("parent") == sh[1] else (None, None) + if a is not None: + en[side + "Shoulder"], en[side + "UpperArm"] = a, b + pairs.append((side + "Shoulder", side + "UpperArm", a, b)) + if "spine" not in en and "spine" not in human: + nums = sorted((int(m.group(1)), i) for i, b in enumerate(bones) + for m in [re.fullmatch(r"(?:.*[_:. ])?spine_?0*(\d+)", (b["name"] or "").lower())] if m) + if len(nums) >= 2: + seq = [i for _, i in nums] + en["spine"] = seq[0] + if len(seq) >= 3: + en["chest"] = seq[len(seq) // 2] if len(seq) >= 4 else seq[1] + en["upperChest"] = seq[-1] + else: + en["chest"] = seq[1] + en.pop("upperChest", None) + # 英文名只在 MMD 名没对上时补位(同一个模型两套都有时以 MMD 名为准) + for k, i in alt.items(): + human.setdefault(k, i) + for k, i in en.items(): + if k[0] == "finger": + if (k[1], k[2]) not in fingers: + fingers[(k[1], k[2])] = i + elif k not in human: + human[k] = i + for s_slot, u_slot, a, b in pairs: # 旧的英文名表把 L_Shoulder 当成了肩:以配对结果为准 + if human.get(s_slot) in (a, b) or human.get(u_slot) in (a, b, None): + human[s_slot], human[u_slot] = a, b + # 没有叫「下半身 / Hips」的骨:取腿和脊椎的最近公共祖先当 hips。XPS 的 root hips 被转成 + # センター(腿和上半身都直接挂在它下面),以前这时只能补一根占位骨 + if "hips" not in human and "spine" in human and ("leftUpperLeg" in human or "rightUpperLeg" in human): + def chain(i): + out, seen = [], set() + while 0 <= i < len(bones) and i not in seen: + out.append(i) + seen.add(i) + i = bones[i].get("parent", -1) + return out + leg = human.get("leftUpperLeg", human.get("rightUpperLeg")) + spine_up = set(chain(bones[human["spine"]].get("parent", -1))) + for a in chain(bones[leg].get("parent", -1)): + if a in spine_up and a not in alias and a not in human.values(): + human["hips"] = a + break + # 上半身2 / 上半身3 的名字和层级反着的模型(鸣潮的娜波摩、秧秧:上半身 → 上半身3 → 上半身2 → 首): + # 按实际的父子顺序分,下面那根是 chest、上面那根是 upperChest。按名字分的话 upperChest + # 在 chest 上面,层级改不过来只能把它从 humanoid 里去掉,躯干少一节 + if "chest" in human and "upperChest" in human: + parents = [b.get("parent", -1) for b in bones] + if _is_ancestor(parents, human["upperChest"], human["chest"]): + human["chest"], human["upperChest"] = human["upperChest"], human["chest"] + for (side, finger), digits in fingers.items(): + if finger == "Thumb" and 0 not in digits and 1 in digits and _thumb_at_root(bones, human, fingers, side, digits[1]): + digits = {d - 1: i for d, i in digits.items() if d >= 1} + for d, slot in _finger_slots(finger, digits, is1).items(): + human.setdefault(side + finger + slot, digits[d]) + return human + + +def _thumb_at_root(bones, human, fingers, side, b): + """只有 親指1、親指2 的拇指:親指1 是不是掌根那节(離手腕近)。 + + 带 親指0 的模型里,按「手腕 → 中指根」的长度算,親指0 离手腕 0.1~0.6、親指1 在 0.7~1.0。 + 老模型没有 親指0 时 親指1 一般还在 0.7 以上,是第二节;离手腕不到 0.65 的才当掌根那节。""" + hd, mid = human.get(side + "Hand"), fingers.get((side, "Middle"), {}).get(1) + if hd is None or mid is None: + return False + w = bones[hd]["pos"] + ref = math.dist(w, bones[mid]["pos"]) + return ref > 1e-6 and math.dist(w, bones[b]["pos"]) < 0.65 * ref + + +def _vrm_anchor(name, present): + """沿 VRM_PARENT 往上找第一个在 present 里的骨位(跳过模型没有的可选骨位)。""" + p = VRM_PARENT.get(name) + while p and p not in present: + p = VRM_PARENT.get(p) + return p + + +def _vrm_depth(name): + d = 0 + while name in VRM_PARENT: + name = VRM_PARENT[name] + d += 1 + return d + + +def _fix_humanoid_hierarchy(human, parents, bones, required, log): + """保证每个 humanoid 骨都在它规范父骨位的子树里,必要时改挂父骨。 + + 最常见的是 MMD 的 上半身 / 下半身 是「腰」下的兄弟骨,而 VRM 要求 + spine 是 hips 的后代——不改的话转 hips(全身朝向)只有下半身跟着转。 + 静止姿势下节点只有平移,改挂父骨不改变任何顶点位置。 + """ + for h in sorted(human, key=_vrm_depth): + if h not in human: + continue + anc = _vrm_anchor(h, human) + if anc is None: + continue + a, c = human[anc], human[h] + if a == c: + del human[h] + log("骨骼:%s 与 %s 对应同一根骨骼,已忽略 %s" % (h, anc, h), "warn") + continue + if _is_ancestor(parents, a, c): + continue + old = parents[c] + if _reparent(parents, c, a): + log("骨骼层级:%s(%s)不在 %s(%s)之下,已移至其下(原父骨骼 %s)" + % (h, bones[c]["name"], anc, bones[a]["name"], + bones[old]["name"] if old >= 0 else "无")) + elif h not in required: + del human[h] + log("骨骼层级:%s(%s)无法修正,已从 humanoid 中移除" + % (h, bones[c]["name"]), "warn") + else: + log("骨骼层级:%s(%s)无法修正,部分软件可能无法加载" + % (h, bones[c]["name"]), "warn") + + +_DIGIT_SEGS = ("Metacarpal", "Proximal", "Intermediate", "Distal") +_HAND_FINGERS = ("Thumb", "Index", "Middle", "Ring", "Little") + + +def _seg_end(bones, kids, b): + """骨 b 这一节的末端位置(PMX 坐标):PMX 的 tail(偏移或骨)→ 第一根子骨 → None。""" + bb, pos = bones[b], bones[b]["pos"] + tail = bb.get("tail", -1) + if bb.get("tail_kind") == 0 and isinstance(tail, (list, tuple)): + if sum(x * x for x in tail) > 1e-10: + return tuple(pos[k] + tail[k] for k in range(3)) + elif isinstance(tail, int) and 0 <= tail < len(bones) and tail != b: + q = bones[tail]["pos"] + if sum((q[k] - pos[k]) ** 2 for k in range(3)) > 1e-10: + return q + for c in kids.get(b, ()): + q = bones[c]["pos"] + if sum((q[k] - pos[k]) ** 2 for k in range(3)) > 1e-10: + return q + return None + + +def _cross(a, b): + return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]) + + +def _tpose_globals(bones, parents, order, human, log): + """算出把模型摆成 VRM T-pose 的逐骨全局变换。 + + VRM 规范(VRMC_vrm-1.0/tpose.md)要求静止姿势:上臂、前臂、手沿 ±X 水平伸直,掌心朝下; + 四指沿 ±X 伸直;拇指水平、指向 ±X 与正前方之间的 45°。动作数据(Unity 的 humanoid、 + VRMA、手部追踪)都是「从这个姿势开始转多少度」,静止姿势偏多少,套上任何动作后就一直 + 偏多少。MMD 模型多是手臂下垂 30~40° 的 A-pose,手指微弯、拇指贴着手掌。 + + 在 PMX 坐标里算(左 +X、前 -Z): + * 上臂、前臂各转一次对齐到水平 ±X; + * 手:先把「手腕 → 中指根」转到 ±X,再绕这个方向转,让掌心朝下(掌面横向取食指根 → 小指根); + * 四指每节转到 ±X、拇指每节转到水平 45°(指甲的侧向朝向从骨骼位置看不出来,只转方向)。 + 父骨先转、子骨跟着走,再算自己还差多少;带付与回転的骨(腕補助 等)按付与率跟转。 + 返回 {骨: (M, t)},x' = M·x + t;没有需要转的返回 None。 + """ + pos = [b["pos"] for b in bones] + kids = {} + for i, p in enumerate(parents): + kids.setdefault(p, []).append(i) + local = {} + sides = {} # side → ±1(左右手伸出去的方向) + for side in ("left", "right"): + ua = human.get(side + "UpperArm") + la = human.get(side + "LowerArm") + hd = human.get(side + "Hand") + if hd is not None: + ref = pos[ua] if ua is not None else (0.0, 0.0, 0.0) + sides[side] = 1.0 if pos[hd][0] - ref[0] >= 0 else -1.0 + if ua is None or la is None: + continue + d1 = [pos[la][k] - pos[ua][k] for k in range(3)] + tgt = (1.0 if d1[0] >= 0 else -1.0, 0.0, 0.0) + sides[side] = tgt[0] + r1, a1 = _align(d1, tgt) + if a1 > math.radians(1.0): + local[ua] = r1 + else: + r1, a1 = _I3, 0.0 + a2 = 0.0 + if hd is not None: + d2 = _m3vec(r1, [pos[hd][k] - pos[la][k] for k in range(3)]) + r2w, a2 = _align(d2, tgt) + if a2 > math.radians(1.0): + # 局部旋转作用在父骨(上臂)旋转之前的空间里 + local[la] = _m3mul(_m3mul(_m3T(r1), r2w), r1) + else: + a2 = 0.0 + if a1 or a2: + log("T-pose:%s 上臂 %.1f° · 前臂 %.1f°" + % ("左" if side == "left" else "右", + math.degrees(a1), math.degrees(a2))) + + # 手和手指:要转到的方向,在下面按父骨在前的顺序边走边算(要用父骨转过之后的朝向) + aim = {} # 骨 → (末端位置, 目标方向, 手的掌面 (食指根, 小指根) 或 None, side, 类别) + for side, sx in sides.items(): + hd = human[side + "Hand"] + chains = {} + for f in _HAND_FINGERS: + chains[f] = [human[side + f + s_] for s_ in _DIGIT_SEGS if side + f + s_ in human] + mid, idx, lit = chains["Middle"][:1], chains["Index"][:1], chains["Little"][:1] + if mid: + aim[hd] = (pos[mid[0]], (sx, 0.0, 0.0), + (idx[0], lit[0]) if idx and lit else None, side, "hand") + thumb = (sx * math.sqrt(0.5), 0.0, -math.sqrt(0.5)) + for f, ch in chains.items(): + for k, b in enumerate(ch): + end = pos[ch[k + 1]] if k + 1 < len(ch) else _seg_end(bones, kids, b) + if end is not None and k + 1 == len(ch) and k > 0: + # 末节的方向只能靠 tail / 子骨猜:FBX 转来的 PMX 末端骨 tail 是默认的朝上偏移, + # 和上一节差得远(> 60°)的不可信,这一节就跟着上一节转 + prev = [pos[b][j] - pos[ch[k - 1]][j] for j in range(3)] + if _align(prev, [end[j] - pos[b][j] for j in range(3)])[1] > math.radians(60.0): + end = None + if end is not None: + aim[b] = (end, thumb if f == "Thumb" else (sx, 0.0, 0.0), None, side, + "thumb" if f == "Thumb" else "finger") + + # 付与回転:按付与率缩放付与親的局部旋转(递归处理付与链) + memo = {} + + def local_of(i, depth=0): + if i in memo: + return memo[i] + m = local.get(i) + ir = bones[i].get("inherit_rot") + if ir and depth < 16 and 0 <= ir[0] < len(bones) and ir[0] != i: + src = local_of(ir[0], depth + 1) + if src is not None: + ax, ang = _to_axis_angle(src) + g = _axis_angle(ax, ang * ir[1]) + m = g if m is None else _m3mul(m, g) + memo[i] = m + return m + + worst = {} # (side, 类别) → 最大转角(度) + glob = {} + for i in order: + p = parents[i] + pm, pt = glob.get(p, (_I3, (0.0, 0.0, 0.0))) + lm = local_of(i) + if i in aim: + end, tgt, palm, side, kind = aim[i] + base = pm if lm is None else _m3mul(pm, lm) + fwd = [end[k] - pos[i][k] for k in range(3)] + r, a = _align(_m3vec(base, fwd), tgt) + roll = 0.0 + if palm is not None: + # 掌面法线(掌心那一侧):左手 前进方向 × (小指根 − 食指根),右手反过来 + across = [pos[palm[1]][k] - pos[palm[0]][k] for k in range(3)] + n = _m3vec(_m3mul(r, base), _cross(fwd, across)) + n = [x * tgt[0] for x in n] + n = [n[k] - tgt[k] * sum(n[j] * tgt[j] for j in range(3)) for k in range(3)] + if sum(x * x for x in n) > 1e-12: + r2, roll = _align(n, (0.0, -1.0, 0.0)) + if roll > math.radians(1.0): + r = _m3mul(r2, r) + else: + roll = 0.0 + if a > math.radians(1.0) or roll: + lm = _m3mul(_m3T(pm), _m3mul(r, base)) + local[i] = memo[i] = lm + key = (side, kind) + worst[key] = max(worst.get(key, 0.0), math.degrees(a)) + if roll: + worst[(side, "palm")] = math.degrees(roll) + if lm is None: + glob[i] = (pm, pt) + continue + # 绕骨骼自身位置旋转:x → R(x − p) + p,再叠父骨变换 + rp = _m3vec(lm, pos[i]) + lt = (pos[i][0] - rp[0], pos[i][1] - rp[1], pos[i][2] - rp[2]) + m = _m3mul(pm, lm) + t = _m3vec(pm, lt) + glob[i] = (m, (t[0] + pt[0], t[1] + pt[1], t[2] + pt[2])) + for side in sides: + w = [worst.get((side, k), 0.0) for k in ("hand", "palm", "finger", "thumb")] + if any(w): + log("T-pose:%s 手 %.1f° · 掌心 %.1f° · 四指最多 %.1f° · 拇指最多 %.1f°" + % (("左" if side == "left" else "右",) + tuple(w))) + if not local: + return None + return glob + + +def _topo_bones(parents): + """把骨骼重排成「父在前」,返回 (新序号→原序号, 原序号→新序号)。 + + 用「祖先链深度」排序:父节点的深度永远比子节点小 1,排序后父必在前。 + 比递归/DFS 稳,遇到坏数据(成环)也不会死循环。 + """ + n = len(parents) + depth = [0] * n + for i in range(n): + seen = set() + d = 0 + k = i + while d <= n + 5: + p = parents[k] + if not (0 <= p < n) or p == k or p in seen: + break + seen.add(p) + d += 1 + k = p + depth[i] = d + order = sorted(range(n), key=lambda i: (depth[i], i)) + remap = {old: new for new, old in enumerate(order)} + return order, remap diff --git a/convert/vrmconv/materials.py b/convert/vrmconv/materials.py new file mode 100644 index 0000000..6e994a9 --- /dev/null +++ b/convert/vrmconv/materials.py @@ -0,0 +1,633 @@ +# -*- coding: utf-8 -*- +"""材质:PMX 材质 → glTF 材质 + MToon(1.0 的 VRMC_materials_mtoon / 0.x 的 materialProperties)。 + +颜色按 MMD 的显示公式算,阴影色和明暗交界按 PMX 的 toon 渐变换算,VRM 1.0 的颜色因子写线性值; +透明模式看漫反射 alpha、贴图的 alpha 分布(只算材质的 UV 用到的部分)和材质表情。 +""" +import io +import math +import os + +import vrmio + +ALPHA_GRID = 1024 # 统计 UV 覆盖区域的透明度时,贴图 alpha 缩到的最长边(像素) + + +def _alpha_grid(data): + """贴图字节 → 缩小的 alpha 通道(Pillow 灰度图;最近邻缩小,不造出假的中间值)。 + 没有 alpha、没装 Pillow 或解不开时为 None。""" + try: + from PIL import Image + im = Image.open(io.BytesIO(data)) + if im.mode in ("RGBA", "LA", "PA"): + a = im.getchannel("A") + elif im.mode == "P" and "transparency" in im.info: + a = im.convert("RGBA").getchannel("A") + else: + return None + k = ALPHA_GRID / max(a.size) + if k < 1: + a = a.resize((max(1, round(a.width * k)), max(1, round(a.height * k))), Image.NEAREST) + return a + except Exception: # noqa: BLE001 解不开就按整张图的统计 + return None + + +def _lin(c): + """sRGB(gamma)分量 → 线性分量。 + + MMD 在 gamma 空间里算颜色(材质色、toon 贴图都是 sRGB 值,直接相乘);glTF 的 + baseColorFactor 和 VRM 1.0 MToon 的各个颜色因子规定是线性值,引擎会按线性来乘 + 贴图。以前把 gamma 值原样写进去:阴影色 0.8 实际显示成 sRGB 0.9,只暗 10%, + 在游戏的环境光下基本看不见(原生 VRoid 皮肤的阴影色 0.x 写 (0.97, 0.81, 0.86), + 读进来是线性 (0.93, 0.63, 0.72))。gamma 空间的乘法 a·b 对应线性的 lin(a)·lin(b), + 所以换算后效果和 MMD 一致。VRM 0.x 的 materialProperties 本来就是 gamma 值,不用转。 + """ + c = max(0.0, min(1.0, c)) + return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4 + + +def _lin_rgb(rgb): + """颜色列表的 RGB 分量转线性,第 4 个(alpha)原样保留。""" + return [round(_lin(v), 5) if i < 3 else v for i, v in enumerate(rgb)] + + +def _mmd_color(diffuse, ambient): + """MMD 实际显示的材质颜色(RGBA)。 + + MMD 默认着色器:颜色 = saturate(漫反射 × 光源色 + 环境色),光源色默认 + 154/255 ≈ 0.6;alpha 取漫反射 alpha。常见的「漫反射 1、环境色 0.5」算出来 + 就是白色,但有的材质靠环境色调色(比如脸红:漫反射白、环境色偏红), + 只用漫反射会把颜色丢掉。 + """ + return [min(1.0, max(0.0, diffuse[k] * 0.6 + ambient[k])) + for k in range(3)] + [diffuse[3]] + + +# MMD 共享 toon(toon01~toon06.bmp)的渐变:上半白、v=0.5 处硬切到下半的颜色。 +# 取自 three.js MMDLoader 内嵌的 DEFAULT_TOON_TEXTURES;它的 toon07~10 是全白的 +# 占位图,不可信,这几张当作「不知道」走默认阴影 +_SHARED_TOON = { + 0: ((255, 255, 255), (205, 205, 205)), + 1: ((255, 255, 255), (245, 225, 225)), + 2: ((255, 255, 255), (154, 154, 154)), + 3: ((255, 255, 255), (248, 239, 235)), + 4: ((255, 255, 255), (254, 232, 223)), + 5: ((255, 237, 97), (195, 172, 3)), +} + + +def _toon_column(rows, w, h): + """toon 贴图 → 从上(v=0,正对光)到下(v=1,背光 / 自阴影)的平均颜色(0~1)。""" + xs = sorted({0, w // 4, w // 2, (3 * w) // 4, w - 1}) + return [tuple(sum(rows[y][x][k] for x in xs) / (255.0 * len(xs)) for k in range(3)) + for y in range(h)] + + +def _toon_shading(col): + """MMD toon 渐变 → MToon 1.0 的 (亮部色, 阴影色, shadingShift, shadingToony)。 + + MMD:颜色 ×= toon(v),v = 0.5 − 0.5·N·L;自阴影(投影)里取最下端 toon(1)。 + MToon 1.0:shading = linearstep(−1+toony, 1−toony, N·L + shift) × 投影, + 颜色 = lerp(阴影色, 亮部色, shading)。所以 + 亮部色 = toon 最上端,阴影色 = 最下端(投影里正好也是它), + 明暗交界在亮度降到一半的 v_mid 处:N·L = 1 − 2·v_mid → shift = 2·v_mid − 1, + 过渡宽度 Δv(亮度 10%→90%)对应 N·L 的 2·Δv → toony = 1 − Δv。 + 星铁 / 鸣潮的皮肤 toon 在 v≈0.75 以后才变暗,换算出来 shift≈+0.6:脸上基本全亮、 + 只有投影是粉色——和原生 VRoid 皮肤(0.x ShadeShift −1 / Toony 1)的效果一致。 + 渐变几乎没有明暗差(纯白 toon)时阴影色 = 亮部色:MMD 里这种材质本来就没有阴影。 + """ + if not col: + return None + lum = [0.299 * c[0] + 0.587 * c[1] + 0.114 * c[2] for c in col] + top, bot = lum[0], lum[-1] + if top - bot < 0.02: + return col[0], col[0], 0.0, 0.9 + n = len(col) + + def first_below(level): + for i, v in enumerate(lum): + if v <= level: + return i / max(1, n - 1) + return 1.0 + + v_mid = first_below(top - 0.5 * (top - bot)) + dv = first_below(top - 0.9 * (top - bot)) - first_below(top - 0.1 * (top - bot)) + shift = max(-1.0, min(1.0, 2.0 * v_mid - 1.0)) + toony = max(0.0, min(1.0, 1.0 - dv)) + return col[0], col[-1], shift, toony + + +def one_sided_layers(model, samples=300, inward_min=0.7, opposite_min=0.5): + """PMX 里设计成单面、背后紧贴着一层反向表面的材质 → {材质序号: (朝里的比例, 法线相反的比例)}。 + + 两类:描边外壳(把脸 / 身体复制一份往外推、翻面、涂黑:单面时只在边缘露出一圈当轮廓线,叫 + 「顔エッジ」「outline」之类)和内侧面(裙子、袖子里面另做一层翻过来的面显示里侧的贴图)。 + 「所有材质双面」不能套到它们上:外壳会整片盖住脸和身体,内侧面会和外层重叠闪烁。 + + 名字靠不住,按几何判断,每个单面材质抽样最多 samples 个三角面: + 朝里 面的朝向(PMX 绕序的叉积)指向它所属骨骼那一段(主要权重的骨,骨头 → 骨尾) + 反向 离它最近的别的材质的顶点(模型高度的 3% 以内),顶点法线和这个面相反——外壳和它下面的表面、 + 内侧面和外层都是这样;眼睛、嘴里朝里的面旁边是方向一致的眼白、牙齿,不算 + 两项都过半(朝里 ≥ inward_min,反向 ≥ opposite_min,有效样本至少 20 个)的才算。 + """ + V, F, B = model["vertices"], model["faces"], model["bones"] + mats = model["materials"] + if not V or not B or not any(m["faces"] >= 3 and not (m["flag"] & 0x01) for m in mats): + return {} + ys = [v["pos"][1] for v in V] + h = (max(ys) - min(ys)) or 1.0 + r, eps = 0.03 * h, 0.0003 * h + tails = [] + for b in B: + t = b.get("tail") + if b.get("tail_kind") == 1 and isinstance(t, int) and 0 <= t < len(B): + tails.append(B[t]["pos"]) + elif b.get("tail_kind") == 0 and t and not isinstance(t, int): + tails.append(tuple(b["pos"][i] + t[i] for i in range(3))) + else: + tails.append(b["pos"]) + mat_of = [0] * len(V) + k = 0 + for mi, m in enumerate(mats): + for t in range(k, min(k + m["faces"], len(F))): + mat_of[F[t]] = mi + k += m["faces"] + cell = r / 4 # 细网格,由近到远一圈圈找:外壳离下面的表面通常只有零点几毫米 + grid = {} + for vi, v in enumerate(V): + p = v["pos"] + grid.setdefault((int(p[0] // cell), int(p[1] // cell), int(p[2] // cell)), []).append(vi) + + def nearest_other(p, mi): + cx, cy, cz = int(p[0] // cell), int(p[1] // cell), int(p[2] // cell) + best, bd = -1, r + for ring in range(5): # 第 ring 圈:切比雪夫距离正好是 ring 的格子 + if best >= 0 and bd <= (ring - 1) * cell: + break + rng = range(-ring, ring + 1) + for dx in rng: + for dy in rng: + for dz in rng: + if max(abs(dx), abs(dy), abs(dz)) != ring: + continue + for vi in grid.get((cx + dx, cy + dy, cz + dz), ()): + if mat_of[vi] != mi: + q = V[vi]["pos"] + dd = math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2 + (p[2] - q[2]) ** 2) + if eps < dd < bd: + best, bd = vi, dd + return best + + def bone_of(v): + ws = list(v["wweights"]) or [1.0] + bi = max(zip(ws, v["wbones"]))[1] if v["wbones"] else -1 + return bi if 0 <= bi < len(B) else -1 + + out, k = {}, 0 + for mi, m in enumerate(mats): + n = m["faces"] // 3 + start, k = k, k + m["faces"] + if n < 1 or m["flag"] & 0x01: + continue + step = max(1, n // samples) + tot, inward = 0, [] # 先只算朝里(便宜),不够的材质不用找邻居 + for t in range(start, start + n * 3, 3 * step): + if t + 2 >= len(F): + break + a, b_, c = (V[F[t + j]]["pos"] for j in range(3)) + u = (b_[0] - a[0], b_[1] - a[1], b_[2] - a[2]) + w = (c[0] - a[0], c[1] - a[1], c[2] - a[2]) + fn = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]) + ln = math.sqrt(fn[0] ** 2 + fn[1] ** 2 + fn[2] ** 2) + bi = bone_of(V[F[t]]) + if ln < 1e-12 or bi < 0: + continue + p = ((a[0] + b_[0] + c[0]) / 3, (a[1] + b_[1] + c[1]) / 3, (a[2] + b_[2] + c[2]) / 3) + s0, s1 = B[bi]["pos"], tails[bi] # 骨头 → 骨尾上离 p 最近的点 + ab = (s1[0] - s0[0], s1[1] - s0[1], s1[2] - s0[2]) + ll = ab[0] ** 2 + ab[1] ** 2 + ab[2] ** 2 + f = 0.0 if ll < 1e-12 else max(0.0, min(1.0, sum((p[i] - s0[i]) * ab[i] for i in range(3)) / ll)) + d = tuple(p[i] - s0[i] - ab[i] * f for i in range(3)) + if math.sqrt(d[0] ** 2 + d[1] ** 2 + d[2] ** 2) < eps: + continue + tot += 1 + if fn[0] * d[0] + fn[1] * d[1] + fn[2] * d[2] < 0: + inward.append((p, fn, ln)) + if tot < 20 or len(inward) < inward_min * tot: + continue + opposite = 0 + for p, fn, ln in inward: + q = nearest_other(p, mi) + if q >= 0: + nq = V[q]["normal"] + lq = math.sqrt(nq[0] ** 2 + nq[1] ** 2 + nq[2] ** 2) or 1.0 + if (fn[0] * nq[0] + fn[1] * nq[1] + fn[2] * nq[2]) / (ln * lq) < -0.5: + opposite += 1 + if opposite >= opposite_min * tot: + break + if opposite >= opposite_min * tot: + out[mi] = (len(inward) / tot, opposite / tot) + return out + + +def _morph_material(mat, ops, mi): + """把材质表情作用到材质 mi 上,返回权重为 1 时的 (漫反射 RGBA, 环境色 RGB)。 + + PMX 材质表情:运算 0 = 乘算(基础 × 值),1 = 加算(基础 + 值); + 28 个值里 [0:4] 是漫反射 RGBA、[8:11] 是环境色。グループ里的比率按 + 「基础 → 目标」线性插值(VRM 的 materialColorBinds 也是按权重插值)。 + 没有作用到这个材质返回 None。 + """ + dif = list(mat["diffuse"]) + amb = list(mat["ambient"]) + hit = False + for m, op, vals, rate in ops: + if m != mi and m != -1: + continue + hit = True + for cur, off, n in ((dif, 0, 4), (amb, 8, 3)): + for k in range(n): + v = vals[off + k] + tgt = cur[k] * v if op == 0 else cur[k] + v + cur[k] = min(1.0, max(0.0, cur[k] + (tgt - cur[k]) * rate)) + return (dif, amb) if hit else None + + +class MaterialBuilder: + """逐个 PMX 材质生成 glTF 材质,贴图写进 gb(vrmio.GLBBuilder)。 + + flat:_flatten_morphs 的结果——会把材质隐藏掉的材质表情决定该材质用 MASK。 + 结果在 self.materials(glTF materials)和 self.props_0x(0.x 的 materialProperties)。 + """ + + def __init__(self, model, base_dir, gb, is1, flat, outline=False, force_double_sided=False, + tex_opt=None, known_alpha=None): + self.model = model + self.tex_opt = tex_opt # textures.Optimizer:嵌入前缩小 / 转 JPEG(None = 原样) + # {贴图文件的 normcase 绝对路径: png_alpha_stats 结果}:调用方已经统计过的(FBX 转换时解过) + self.known_alpha = known_alpha or {} + self._pre = {} # prefetch 提前读好的贴图:PMX 贴图序号 → _load 的结果 + self.base_dir = base_dir + self.finder = vrmio.TextureFinder(base_dir) + self.tex_moved, self.tex_missing, self.tex_bad = set(), set(), set() # 贴图路径:日志里汇报 + self.gb = gb + self.is1 = is1 + self.outline = outline + self.force_double_sided = force_double_sided + # 「所有材质双面」时仍保持单面的:描边外壳、内侧面(one_sided_layers) + self.keep_one_sided = one_sided_layers(model) if force_double_sided else {} + self.materials = [] + self.props_0x = [] + self.img_cache = {} + self.tex_alpha = {} # PMX 贴图 → png_alpha_stats 结果 + self.tex_grid = {} # PMX 贴图 → _alpha_grid(只有整张图里有透明像素的贴图) + self.alpha_by_uv = 0 # 按 UV 覆盖区域统计后不再算透明的材质数 + self.toon_cache = {} + self.blend_rank = 0 + self.sph_skipped = 0 + self.morph_min_alpha = {} # PMX 材质 → 材质表情能把 alpha 压到多低 + self.morph_max_alpha = {} # PMX 材质 → 材质表情能把 alpha 抬到多高 + self.face_start = [] # PMX 材质 → 它的第一个面在 model["faces"] 里的位置 + k = 0 + for mat in model["materials"]: + self.face_start.append(k) + k += mat["faces"] + for f in flat: + ops = f[2] + for mi_, mat in enumerate(model["materials"]): + r = _morph_material(mat, ops, mi_) + if r is not None: + self.morph_min_alpha[mi_] = min(self.morph_min_alpha.get(mi_, 1.0), r[0][3]) + self.morph_max_alpha[mi_] = max(self.morph_max_alpha.get(mi_, 0.0), r[0][3]) + + def _find(self, idx): + """PMX 贴图序号 → 磁盘上的文件路径(找不到为 None;查找规则见 vrmio.TextureFinder)。""" + return self.finder.find(self.model["textures"][idx])[0] + + def _load(self, idx): + """PMX 贴图序号 → (原图数据, mime, 透明统计, 瘦身后的 (数据, mime), 缩小的 alpha),读不了为 None。 + 不改动 self 的状态,可以在线程里跑(见 prefetch)。""" + c = self._find(idx) + data, mime = vrmio.load_texture(c) if c else (None, None) + if not data: + return None + # 透明度统计用原图(瘦身后可能已是 JPEG);只有完全不透明的贴图才会转 JPEG,结论不变 + key = os.path.normcase(os.path.abspath(c)) + alpha = self.known_alpha[key] if key in self.known_alpha else vrmio.png_alpha_stats(data) + grid = _alpha_grid(data) if alpha and alpha[0] and alpha[1] >= alpha[0] * 0.001 else None + slim = self.tex_opt.process(data, mime) if self.tex_opt is not None else (data, mime) + return data, mime, alpha, slim, grid + + def prefetch(self, threads=1): + """材质要用的贴图先一起读好(读文件、透明统计、瘦身):Pillow 解码 / 编码在 C 里跑、不占 GIL, + 几张图可以同时处理。结果留给 resolve_tex,贴图写进 GLB 的顺序不变。""" + textures = self.model["textures"] + want = [] + for mat in self.model["materials"]: + if mat["faces"] < 3: # 没有三角面的材质不会生成(见 mesh.build_primitives) + continue + for idx in (mat["tex"], mat["sph"] if mat["sph_mode"] == 2 else -1): + if 0 <= idx < len(textures) and idx not in want: + want.append(idx) + if threads < 2 or len(want) < 2: + return + from concurrent.futures import ThreadPoolExecutor + with ThreadPoolExecutor(min(threads, len(want))) as ex: + self._pre.update(zip(want, ex.map(self._load, want))) + + def resolve_tex(self, idx): + """PMX 贴图序号 → glTF texture 序号(-1 = 没有 / 读不了)。""" + if idx is None or idx < 0 or idx >= len(self.model["textures"]): + return -1 + if idx in self.img_cache: + return self.img_cache[idx] + got = self._pre.pop(idx) if idx in self._pre else self._load(idx) + rel = self.model["textures"][idx] + path, how = self.finder.find(rel) + if path is None: + self.tex_missing.add(rel) + elif got is None: + self.tex_bad.add(rel) + elif how == "moved": + self.tex_moved.add(rel) + if got is None: + self.img_cache[idx] = -1 + return -1 + data, mime, self.tex_alpha[idx], slim, grid = got + if grid is not None: + self.tex_grid[idx] = grid + if self.tex_opt is not None: + data, mime = self.tex_opt.account(data, slim) + ti = self.gb.add_texture(self.gb.add_image(data, mime)) + self.img_cache[idx] = ti + return ti + + def toon_params(self, mat): + """材质的 toon 渐变 → (亮部色, 阴影色, shift, toony)(见 _toon_shading); + 没有 toon、共享 toon07~10、贴图找不到或解不了时返回 None(走默认阴影)。""" + if mat["toon_flag"]: + key = ("shared", mat["toon"]) + elif 0 <= mat["toon"] < len(self.model["textures"]): + key = ("tex", mat["toon"]) + else: + return None + if key not in self.toon_cache: + r = None + if key[0] == "shared": + st = _SHARED_TOON.get(key[1]) + if st: + t, b = [tuple(c / 255.0 for c in x) for x in st] + r = _toon_shading([t] * 16 + [b] * 16) + else: + path = self._find(key[1]) + if path: + with open(path, "rb") as f: + img = vrmio.decode_rgba(f.read()) + if img: + r = _toon_shading(_toon_column(img[2], img[0], img[1])) + self.toon_cache[key] = r + return self.toon_cache[key] + + def lit_shade(self, mat, color): + """MMD 显示色(_mmd_color)→ MToon 的 (亮部 RGBA, 阴影 RGB, shift, toony)。""" + tp = self.toon_params(mat) + if tp is None: + # 没有可用的 toon:实际几乎都是眼睛、高光、眉睫、嘴、表情贴片。按二次元的 + # 惯例(原生 VRoid 的眼睛、眉毛阴影色都是白)不画阴影,不然一进投影眼睛就发黑 + return list(color), list(color[:3]), 0.0, 0.9 + lit, dark, shift, toony = tp + return ([color[k] * lit[k] for k in range(3)] + [color[3]], + [color[k] * dark[k] for k in range(3)], shift, toony) + + def used_alpha(self, mi_, mat): + """材质贴图的透明统计(同 png_alpha_stats),只算这个材质的 UV 覆盖到的部分。 + + 有的模型几个部件共用一张大图集,或者贴图右边还拼着用不到的半透明图层(同一张图 + u 0~1/3 是颜色,后面是别的通道):按整张图统计,不透明的身体、衣服也被当成半透明, + BLEND 的排序问题让部件在转动视角时消失、前后遮挡错乱。三角面按 UV 画到缩小的 + alpha 图上,只统计盖住的像素。整张图没有透明像素的贴图不用算。""" + whole = self.tex_alpha.get(mat["tex"]) + grid = self.tex_grid.get(mat["tex"]) + if grid is None or mat["faces"] < 3: + return whole + from PIL import Image, ImageDraw + w, h = grid.size + mask = Image.new("L", (w, h), 0) + draw = ImageDraw.Draw(mask) + verts, faces = self.model["vertices"], self.model["faces"] + s = self.face_start[mi_] + for t in range(s, s + mat["faces"] - 2, 3): + uv = [verts[faces[t + k]]["uv"] for k in range(3)] + # 平铺(repeat):整个三角形移到最小角所在的那一格 + ou, ov = math.floor(min(p[0] for p in uv)), math.floor(min(p[1] for p in uv)) + draw.polygon([((u - ou) * w, (v - ov) * h) for u, v in uv], fill=255) + hist = grid.histogram(mask=mask) + st = (sum(hist), sum(hist[:250]), sum(hist[11:245])) + # UV 全落在完全透明的地方:靠 UV 表情挪过去才显示的贴片(表情符号)、靠材质表情显示的部件, + # 初始 UV 说明不了什么,按整张图 + return st if st[0] - st[1] + st[2] > 0 else whole + + @staticmethod + def _see_through(st): + return bool(st and st[0] and st[1] >= st[0] * 0.001) + + def alpha_mode(self, mi_, mat): + """OPAQUE / MASK / BLEND。 + + 以前只看漫反射 alpha,贴图自带透明通道(头发高光层、瞳孔、 + 镂空裙摆)的材质全被写成 OPAQUE,透明区域画成实心—— + 实测头发被一层黑色盖住、眼睛一片黑。现在还看贴图的 alpha 分布: + * 半透明像素占可见像素的比例低(只有抗锯齿边缘)→ MASK(裁剪, + 不需要排序,Unity 里最稳) + * 比例高(柔和的叠加层、薄纱)→ BLEND + 材质表情会把它隐藏(alpha → 0)的不透明材质用 MASK,才能真的隐藏。 + """ + st = self.used_alpha(mi_, mat) + if self._see_through(self.tex_alpha.get(mat["tex"])) and not self._see_through(st): + self.alpha_by_uv += 1 + if mat["diffuse"][3] <= 0.001 and self.morph_max_alpha.get(mi_, 0.0) > 0.5: + # 默认隐藏、靠材质表情显示的部件(FBX 的替换网格:另一种手势 / 张嘴的头): + # 用 MASK,显示出来时就是普通的不透明材质,不用 BLEND 的排序 + if self._see_through(st) and st[2] >= (st[0] - st[1] + st[2]) * 0.3: + return "BLEND" + return "MASK" + if mat["diffuse"][3] < 0.999: + return "BLEND" + if self._see_through(st): + n, trans, mid = st + visible = n - trans + mid + if visible <= 0 or mid >= visible * 0.3: + return "BLEND" + return "MASK" + if self.morph_min_alpha.get(mi_, 1.0) < 0.5: + return "MASK" + return "OPAQUE" + + def make(self, mi_, mat): + """生成一个 glTF 材质,返回它在 self.materials 里的序号。""" + ti = self.resolve_tex(mat["tex"]) + # 亮部 / 阴影色和明暗交界按 PMX 的 toon 渐变换算(MMD 的暗部和自阴影都取 + # toon 最下端的颜色)。以前一律「阴影 = 亮部 × 0.8」:灰色的阴影叠在浅色皮肤上 + # 几乎看不出来,星铁、鸣潮的脸又白又平;原生 VRoid 皮肤的阴影是粉色的 + diff, shade, shift, toony = self.lit_shade(mat, _mmd_color(mat["diffuse"], mat["ambient"])) + mode = self.alpha_mode(mi_, mat) + double = bool(mat["flag"] & 0x01) or (self.force_double_sided and mi_ not in self.keep_one_sided) + # 加算球面贴图(sph_mode 2)≈ MToon 的 matcap(同样是加算); + # 乘算(1)没有对应项,跳过 + si = -1 + if mat["sph_mode"] == 2: + si = self.resolve_tex(mat["sph"]) + elif mat["sph_mode"] == 1 and 0 <= mat["sph"] < len(self.model["textures"]): + self.sph_skipped += 1 + rq = 0 + if mode == "BLEND": # 半透明按 PMX 材质顺序排绘制顺序 + rq = min(9, self.blend_rank) + self.blend_rank += 1 + edge = self.outline and bool(mat["flag"] & 0x10) and mat["edge_size"] > 0 + # 材质名在模型内唯一:有的程序按材质名找材质, + # PMX 允许重名,重名时只会找到第一个 + name = mat["name"] or ("mat%d" % mi_) + used = {m["name"] for m in self.materials} + k = 2 + while name in used: + name = "%s_%d" % (mat["name"] or ("mat%d" % mi_), k) + k += 1 + gmat = { + "name": name, + "pbrMetallicRoughness": { + "baseColorFactor": _lin_rgb(diff), + "metallicFactor": 0.0, + "roughnessFactor": 0.9, + }, + "doubleSided": double, + "emissiveFactor": [0.0, 0.0, 0.0], + "alphaMode": mode, + } + if mode == "MASK": + gmat["alphaCutoff"] = 0.5 + if ti >= 0: + gmat["pbrMetallicRoughness"]["baseColorTexture"] = {"index": ti} + + if self.is1: + mt = { + "specVersion": "1.0", + "transparentWithZWrite": False, + "renderQueueOffsetNumber": rq, + "shadeColorFactor": _lin_rgb(shade), + "shadingShiftFactor": round(shift, 4), + "shadingToonyFactor": round(toony, 4), + "giEqualizationFactor": 0.9, + "matcapFactor": [1.0, 1.0, 1.0] if si >= 0 else [0.0, 0.0, 0.0], + "parametricRimColorFactor": [0.0, 0.0, 0.0], + "parametricRimFresnelPowerFactor": 5.0, + "parametricRimLiftFactor": 0.0, + "rimLightingMixFactor": 1.0, + "outlineWidthMode": "worldCoordinates" if edge else "none", + "outlineWidthFactor": (mat["edge_size"] * 0.001) if edge else 0.0, + "outlineColorFactor": _lin_rgb(mat["edge_color"][:3]), + "outlineLightingMixFactor": 1.0, + } + if ti >= 0: + mt["shadeMultiplyTexture"] = {"index": ti} + if si >= 0: + mt["matcapTexture"] = {"index": si} + gmat["extensions"] = {"VRMC_materials_mtoon": mt} + else: + blend = mode == "BLEND" + mask = mode == "MASK" + tex_props = {} + if ti >= 0: + tex_props["_MainTex"] = ti + tex_props["_ShadeTexture"] = ti # 以前没写,暗部只剩一块纯色 + if si >= 0: + tex_props["_SphereAdd"] = si + self.props_0x.append({ + "name": gmat["name"], + "shader": "VRM/MToon", + "renderQueue": (3000 + rq) if blend else (2450 if mask else 2000), + "floatProperties": { + "_Cutoff": 0.5, "_BumpScale": 1.0, + # 0.x:smoothstep(shift, shift + 1 − toony, N·L),换算成同样的交界和宽度 + "_ReceiveShadowRate": 1.0, + "_ShadeShift": round(max(-1.0, min(1.0, -shift - (1.0 - toony))), 4), + "_ShadeToony": round(max(0.0, 2.0 * toony - 1.0), 4), + "_LightColorAttenuation": 0.0, + "_IndirectLightIntensity": 0.1, "_RimLightingMix": 0.0, + "_RimFresnelPower": 1.0, "_RimLift": 0.0, + # 0.x 世界坐标模式的线宽单位是厘米 + "_OutlineWidth": (mat["edge_size"] * 0.1) if edge else 0.0, + "_OutlineScaledMaxDistance": 1.0, + "_OutlineLightingMix": 1.0, "_UvAnimScrollX": 0.0, + "_UvAnimScrollY": 0.0, "_UvAnimRotation": 0.0, + "_MToonVersion": 38.0, "_DebugMode": 0.0, + "_BlendMode": 2.0 if blend else (1.0 if mask else 0.0), + "_OutlineWidthMode": 1.0 if edge else 0.0, + "_OutlineColorMode": 0.0, + # Unity CullMode:0 Off / 1 Front / 2 Back。以前单面写成 1, + # 剔除的是正面 + "_CullMode": 0.0 if double else 2.0, + "_OutlineCullMode": 1.0, + # 半透明:SrcAlpha / OneMinusSrcAlpha、不写深度。 + # 以前透明材质也写 1/0/ZWrite=1,等于不透明 + "_SrcBlend": 5.0 if blend else 1.0, + "_DstBlend": 10.0 if blend else 0.0, + "_ZWrite": 0.0 if blend else 1.0, + "_AlphaToMask": 0.0, + }, + "vectorProperties": { + "_Color": [diff[0], diff[1], diff[2], diff[3]], + "_ShadeColor": shade + [1.0], + "_EmissionColor": [0.0, 0.0, 0.0, 1.0], + "_OutlineColor": list(mat["edge_color"][:3]) + [1.0], + "_RimColor": [0.0, 0.0, 0.0, 1.0], + }, + "textureProperties": tex_props, + "keywordMap": {"_NORMALMAP": False, "_ALPHATEST_ON": mask, + "_ALPHABLEND_ON": blend, + "_ALPHAPREMULTIPLY_ON": False, + "MTOON_OUTLINE_WIDTH_WORLD": edge, + "MTOON_OUTLINE_COLOR_FIXED": edge}, + "tagMap": {"RenderType": ("Transparent" if blend else + "TransparentCutout" if mask + else "Opaque")}, + }) + self.materials.append(gmat) + return len(self.materials) - 1 + + def log_summary(self, log): + modes = [m["alphaMode"] for m in self.materials] + log("材质透明模式:不透明 %d · 裁剪(MASK)%d · 半透明(BLEND)%d" + % (modes.count("OPAQUE"), modes.count("MASK"), modes.count("BLEND"))) + if self.alpha_by_uv: + log("材质:%d 个材质的贴图有透明部分,但模型只用到不透明的区域,按不透明处理" % self.alpha_by_uv) + if self.is1: + nmc = sum(1 for m in self.materials if "matcapTexture" in + m["extensions"]["VRMC_materials_mtoon"]) + else: + nmc = sum(1 for p in self.props_0x if "_SphereAdd" in p["textureProperties"]) + if nmc: + log("材质:%d 个加算球面贴图转为 MToon 的 matcap" % nmc) + if self.tex_opt is not None: + if not self.tex_opt.active and (self.tex_opt.max_size or self.tex_opt.jpeg): + log("贴图:未安装 Pillow,缩小贴图和 JPEG 存储未生效", "warn") + elif self.tex_opt.summary(): + log(self.tex_opt.summary()) + if self.sph_skipped: + log("材质:%d 个材质的乘算球面贴图(.sph)在 MToon 中没有对应项,已忽略" + % self.sph_skipped, "warn") + if self.keep_one_sided: + names = [self.model["materials"][i]["name"] for i in sorted(self.keep_one_sided)] + log("材质:%d 个材质是描边外壳或内侧面(%s),「所有材质双面」时仍保持单面,否则会盖住模型或重叠闪烁" + % (len(names), "、".join(names[:6]) + ("…" if len(names) > 6 else ""))) + + def names(rels): + rels = sorted(rels) + return "、".join(r.replace("\\", "/").rsplit("/", 1)[-1] for r in rels[:6]) + ("…" if len(rels) > 6 else "") + if self.tex_moved: + log("贴图:%d 张不在模型记录的位置,已按文件名在模型文件夹里找到(%s)" % (len(self.tex_moved), names(self.tex_moved))) + if self.tex_missing: + log("贴图:%d 张找不到(%s),用到它们的材质只有底色。贴图要和模型放在一起:请加入整个文件夹或压缩包" + % (len(self.tex_missing), names(self.tex_missing)), "warn") + if self.tex_bad: + log("贴图:%d 张读取失败(%s),用到它们的材质只有底色" % (len(self.tex_bad), names(self.tex_bad)), "warn") diff --git a/convert/vrmconv/mathutil.py b/convert/vrmconv/mathutil.py new file mode 100644 index 0000000..2ab4e21 --- /dev/null +++ b/convert/vrmconv/mathutil.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +"""3x3 矩阵小工具(行主序元组,纯 Python)。""" +import math + + +_I3 = (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) + + +def _m3mul(a, b): + return tuple(sum(a[r * 3 + k] * b[k * 3 + c] for k in range(3)) + for r in range(3) for c in range(3)) + + +def _m3vec(m, v): + return (m[0] * v[0] + m[1] * v[1] + m[2] * v[2], + m[3] * v[0] + m[4] * v[1] + m[5] * v[2], + m[6] * v[0] + m[7] * v[1] + m[8] * v[2]) + + +def _m3T(m): + return (m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]) + + +def _axis_angle(axis, ang): + x, y, z = axis + c, s = math.cos(ang), math.sin(ang) + t = 1.0 - c + return (t * x * x + c, t * x * y - s * z, t * x * z + s * y, + t * x * y + s * z, t * y * y + c, t * y * z - s * x, + t * x * z - s * y, t * y * z + s * x, t * z * z + c) + + +def _to_axis_angle(m): + ang = math.acos(max(-1.0, min(1.0, (m[0] + m[4] + m[8] - 1.0) * 0.5))) + if ang < 1e-9: + return (1.0, 0.0, 0.0), 0.0 + ax = (m[7] - m[5], m[2] - m[6], m[3] - m[1]) + ln = math.sqrt(ax[0] ** 2 + ax[1] ** 2 + ax[2] ** 2) + if ln < 1e-9: # 180°:取对角线最大的那列 + k = max(range(3), key=lambda i: m[i * 4]) + col = [(m[i * 3 + k] + (1.0 if i == k else 0.0)) for i in range(3)] + ln = math.sqrt(sum(x * x for x in col)) or 1.0 + return tuple(x / ln for x in col), ang + return (ax[0] / ln, ax[1] / ln, ax[2] / ln), ang + + +def _align(d, t): + """把方向 d 转到方向 t 的最小旋转,返回 (矩阵, 角度)。""" + ld = math.sqrt(sum(x * x for x in d)) + lt = math.sqrt(sum(x * x for x in t)) + if ld < 1e-9 or lt < 1e-9: + return _I3, 0.0 + d = [x / ld for x in d] + t = [x / lt for x in t] + ax = (d[1] * t[2] - d[2] * t[1], d[2] * t[0] - d[0] * t[2], + d[0] * t[1] - d[1] * t[0]) + s = math.sqrt(sum(x * x for x in ax)) + ang = math.atan2(s, sum(d[k] * t[k] for k in range(3))) + if s < 1e-9: + return _I3, 0.0 + return _axis_angle((ax[0] / s, ax[1] / s, ax[2] / s), ang), ang diff --git a/convert/vrmconv/mesh.py b/convert/vrmconv/mesh.py new file mode 100644 index 0000000..4a6c39b --- /dev/null +++ b/convert/vrmconv/mesh.py @@ -0,0 +1,329 @@ +# -*- coding: utf-8 -*- +"""网格:顶点权重整理、按材质切成 glTF primitive、写 accessor、按表情分成几个网格。""" +import heapq +import math + +import vrmio + + +def _weights_of(v, nb, alias): + """一个顶点的 [(PMX 骨, 权重)](见 vertex_weights)。""" + wt = v["wtype"] + bs = [x for x in v["wbones"] if 0 <= x < nb] + if not bs: + bs = [0] + if wt == 0: + return [(alias.get(bs[0], bs[0]), 1.0)] + if wt in (1, 3): # BDEF2 / SDEF(SDEF 退化成线性混合) + # 和下面的通用算法结果完全相同,只是不建字典、不排序(顶点大多是这种) + w0 = v["wweights"][0] if v["wweights"] else 1.0 + a = alias.get(bs[0], bs[0]) + b = bs[1] if len(bs) > 1 else bs[0] + b = alias.get(b, b) + wa, wb = max(0.0, w0), max(0.0, 1.0 - w0) + if a == b: + tot = wa + wb + return [(a, 1.0 if tot <= 1e-9 else tot / tot)] + if wb > wa: + a, b, wa, wb = b, a, wb, wa + tot = wa + wb + if tot <= 1e-9: + return [(a, 1.0)] + return [(a, wa / tot), (b, wb / tot)] + # BDEF4 / QDEF + ws = list(v["wweights"]) + [0.0] * 4 + wl = [(bs[k] if k < len(bs) else bs[0], ws[k]) for k in range(4)] + if sum(x[1] for x in wl) <= 1e-9: + wl = [(bs[0], 1.0)] + acc = {} + for b_, w in wl: + b_ = alias.get(b_, b_) + acc[b_] = acc.get(b_, 0.0) + max(0.0, w) + wl = sorted(acc.items(), key=lambda x: -x[1])[:4] + tot = sum(w for _, w in wl) + if tot <= 1e-9: + return [(wl[0][0] if wl else bs[0], 1.0)] + return [(b_, w / tot) for b_, w in wl] + + +def vertex_weights(verts, nb, alias, base=None): + """逐顶点 [(PMX 骨, 权重)]:已归一、已按付与别名合并、最多 4 个。 + + base:同一批顶点不带别名(alias={})的结果。给了就只重算挂在别名骨上的顶点——网格要带别名的、 + 骨骼表情烘焙要不带的,两份不用各从头算一遍。 + """ + if not nb: + return [[(0, 1.0)] for _ in verts] + if base is not None and 0 not in alias: # 没有有效骨的顶点算到骨 0 上 + if not alias: + return base + keys = set(alias) + out = list(base) + for i, v in enumerate(verts): + if not keys.isdisjoint(v["wbones"]): + out[i] = _weights_of(v, nb, alias) + return out + return [_weights_of(v, nb, alias) for v in verts] + + +LIMB_PART = {"Shoulder": "肩", "UpperArm": "上臂", "LowerArm": "前臂", "Hand": "手", + "UpperLeg": "大腿", "LowerLeg": "小腿", "Foot": "脚", "Toes": "脚趾"} + + +def mirror_mismatches(verts, raw_weights, vweights, human, min_count=20): + """左右对称位置的顶点绑在四肢的不同部位上(一边大腿、一边小腿之类)→ + [(顶点对数, 右侧骨, 右侧部位, 左侧骨, 左侧部位)](骨是 PMX 索引,部位是 humanoid 骨位去掉 left / right)。 + + 多半是模型镜像权重时弄错了:在 MMD 里同样会变形(膝盖一弯,绑在大腿上的鞋子就被扯开), + 转换器不改模型,只在日志里提示。PMX 坐标里角色的左边是 +X。只算两边都主要(≥ 0.5)挂在 + 四肢的 humanoid 骨上、而且各自几乎不挂对面那个部位(< 0.2)的顶点对,关节处正常的混合权重不算。 + """ + part = {} + for s, b in human.items(): + for side in ("left", "right"): + if s.startswith(side): + part[b] = s[len(side):] + if not part: + return [] + + def key(x, y, z): + return (round(x, 3), round(y, 3), round(z, 3)) + + def dom(wl): + return max(wl, key=lambda t: t[1]) + + def on(wl, p): + return sum(w for b, w in wl if part.get(b) == p) + + left = {key(*v["pos"]): i for i, v in enumerate(verts) if v["pos"][0] > 1e-4} + groups = {} + for i, v in enumerate(verts): + x, y, z = v["pos"] + if x >= -1e-4: + continue + j = left.get(key(-x, y, z)) + if j is None: + continue + (br, wr), (bl, wl) = dom(vweights[i]), dom(vweights[j]) + pr, pl = part.get(br), part.get(bl) + if not pr or not pl or pr == pl or wr < 0.5 or wl < 0.5: + continue + if on(vweights[i], pl) >= 0.2 or on(vweights[j], pr) >= 0.2: + continue + k = (dom(raw_weights[i])[0], pr, dom(raw_weights[j])[0], pl) + groups[k] = groups.get(k, 0) + 1 + return sorted(((n,) + k for k, n in groups.items() if n >= min_count), reverse=True) + + +def build_primitives(model, xf, xf_dir, vpos, vnrm, vweights, reverse_winding, make_material): + """按 PMX 材质切网格。make_material(PMX 材质号, 材质) → glTF 材质号(只给有面的材质调用)。 + + 返回 (prims, mat_gidx):prims 每项含 local(PMX 顶点 → 本 primitive 顶点)、顶点数据、 + 索引和 glTF 材质号;mat_gidx:PMX 材质号 → glTF 材质号(0 面的材质不在里面)。 + """ + verts = model["vertices"] + faces = model["faces"] + prims = [] + mat_gidx = {} + cursor = 0 + for mi_, mat in enumerate(model["materials"]): + cnt = mat["faces"] + tri_count = cnt // 3 + positions, normals, uvs, joints, weights = [], [], [], [], [] + local = {} + idxs = [] + + def get_local(vi): + j = local.get(vi) + if j is not None: + return j + v = verts[vi] + p = xf(vpos[vi]) + n = xf_dir(vnrm[vi]) + ln = math.sqrt(n[0] * n[0] + n[1] * n[1] + n[2] * n[2]) or 1.0 + n = (n[0] / ln, n[1] / ln, n[2] / ln) + j = len(positions) // 3 + local[vi] = j + positions.extend(p) + normals.extend(n) + uvs.extend(v["uv"]) + # JOINTS_0 的值是「skin.joints 数组的下标」,不是 glTF 节点号! + # 这里先写 PMX 骨索引 b,去掉无用节点后由 remap_joints 换成 joints 里的位置。以前错写成节点号 bone_node(b), + # 拓扑排序一旦重排骨骼(remap 非恒等)权重就整体串位—— + # 症状是 Blender 里动某根骨头、别处的顶点跟着跑。 + wl = list(vweights[vi]) + while len(wl) < 4: + wl.append((wl[0][0], 0.0)) + joints.extend([b for b, _ in wl[:4]]) + weights.extend([w for _, w in wl[:4]]) + return j + + for t in range(tri_count): + a = faces[cursor + t * 3] + b = faces[cursor + t * 3 + 1] + c = faces[cursor + t * 3 + 2] + ia, ib, ic = get_local(a), get_local(b), get_local(c) + if reverse_winding: + ia, ic = ic, ia + idxs.extend([ia, ib, ic]) + cursor += cnt + + if not idxs: + continue + # 以前 primitive 直接用 PMX 材质号,PMX 里有 0 面材质时 + # 后面的材质会整体错一位;现在用实际写出的 glTF 材质号 + mat_gidx[mi_] = make_material(mi_, mat) + prims.append({"local": local, "vcount": len(local), + "idxs": idxs, "pos": positions, "nrm": normals, + "uv": uvs, "jn": joints, "wt": weights, + "mat": mat_gidx[mi_], "mat_name": mat.get("name") or "", "tmap": {}}) + return prims, mat_gidx + + +def remap_joints(prims, slot): + """JOINTS_0 里的 PMX 骨序号 → skin.joints 里的位置(slot:PMX 骨 → 位置)。 + + 不在 slot 里的骨(去掉的节点)只会以权重 0 出现(凑满 4 个的占位),换成本顶点第一根骨。 + """ + for pr in prims: + jn = pr["jn"] + for k in range(0, len(jn), 4): + first = slot.get(jn[k], 0) + for q in range(k, k + 4): + jn[q] = slot.get(jn[q], first) + + +def write_accessors(gb, prims): + """顶点属性和索引写进 GLB,结果放在 pr["acc"] / pr["indices"]。""" + for pr in prims: + pr["acc"] = { + "POSITION": gb.add_accessor(pr["pos"], vrmio.FLOAT, "VEC3", 34962), + "NORMAL": gb.add_accessor(pr["nrm"], vrmio.FLOAT, "VEC3", 34962), + "TEXCOORD_0": gb.add_accessor(pr["uv"], vrmio.FLOAT, "VEC2", 34962), + "JOINTS_0": gb.add_accessor(pr["jn"], vrmio.UNSIGNED_SHORT, + "VEC4", 34962), + "WEIGHTS_0": gb.add_accessor(pr["wt"], vrmio.FLOAT, "VEC4", 34962), + } + pr["indices"] = gb.add_accessor(pr["idxs"], vrmio.UNSIGNED_INT, + "SCALAR", 34963, minmax=False) + + +# 多分一个网格折合多少「顶点 × morph target」:省下的不到这么多(密集存储约 1.2 MB)就不分 +MESH_COST = 100000 +MAX_MESHES = 8 + + +def group_meshes(prims, n_targets): + """按表情把 primitive 分成几个网格 → [(primitive 序号列表, 全局 morph target 序号列表)],按首个 primitive 排。 + + glTF 要求同一个网格里每个 primitive 带同样的 morph target,读取端(three.js、Unity)又多半按 + 「顶点数 × target 数」展开成密集数组:全塞在一个网格里时,身体、衣服也要陪着脸带上全部表情 + (13 万顶点 × 180 个表情 ≈ 270 MB)。这里像 VRoid 的 Face / Body / Hair 那样分开:从「target 集合 + 相同的放一起」开始,每次合并代价最小的两组(代价 = 网格顶点数 × target 数),直到再合并多出的 + 比 MESH_COST 多、且网格数不超过 MAX_MESHES。哪个 primitive 都没动到的 target 放进 target 最多的网格, + 让表情还能引用它。 + """ + by_set = {} + for i, pr in enumerate(prims): + by_set.setdefault(frozenset(pr["tmap"]), []).append(i) + groups = {} # id → [target 集合, 顶点数, primitive 序号] + for k, (ts, ids) in enumerate(by_set.items()): + groups[k] = [ts, sum(prims[i]["vcount"] for i in ids), ids] + + def extra(a, b): + ta, va, _ = groups[a] + tb, vb, _ = groups[b] + return (va + vb) * len(ta | tb) - va * len(ta) - vb * len(tb) + + heap = [(extra(a, b), a, b) for a in groups for b in groups if a < b] + heapq.heapify(heap) + nxt = len(groups) + while heap and len(groups) > 1: + d, a, b = heapq.heappop(heap) + if a not in groups or b not in groups: + continue + if d > MESH_COST and len(groups) <= MAX_MESHES: + break + ta, va, ia = groups.pop(a) + tb, vb, ib = groups.pop(b) + groups[nxt] = [ta | tb, va + vb, sorted(ia + ib)] + for c in list(groups): + if c != nxt: + heapq.heappush(heap, (extra(c, nxt), c, nxt)) + nxt += 1 + out = sorted(([ids, set(ts)] for ts, _, ids in groups.values()), key=lambda g: g[0][0]) + used = set().union(*(ts for _, ts in out)) + orphans = set(range(n_targets)) - used + if orphans: + max(out, key=lambda g: len(g[1]))[1].update(orphans) + return [(ids, sorted(ts)) for ids, ts in out] + + +def _zero_target(gb, pr, sparse): + """这个 primitive 上的全零 morph target(同一个 primitive 共用一个)。""" + if "zero" not in pr: + if sparse: # 稀疏 accessor 至少要一项 + pr["zero"] = gb.add_sparse_accessor(pr["vcount"], [], [], "VEC3") + else: + pr["zero"] = gb.add_accessor([0.0] * (pr["vcount"] * 3), vrmio.FLOAT, "VEC3", 34962) + return pr["zero"] + + +def build_meshes(gb, prims, groups, target_names, name, sparse=True, prim_names=False): + """group_meshes 的分组 → (glTF meshes, where)。where[全局 target 序号] = [(网格号, 网格内序号)]。 + + prim_names:morph target 名也写进每个 primitive 的 extras(VRM 0.x:UniVRM 自己导出时两处都写, + 老版本的读取端只看 primitive,读不到时 BlendShape 名变成编号)。""" + meshes = [] + where = [[] for _ in target_names] + for mi, (ids, slots) in enumerate(groups): + m = {"name": name if len(groups) == 1 else _mesh_name(prims, ids, name), "primitives": []} + for i in ids: + pr = prims[i] + p = {"attributes": pr["acc"], "indices": pr["indices"], "material": pr["mat"]} + if slots: + p["targets"] = [{"POSITION": pr["tmap"][s] if s in pr["tmap"] else _zero_target(gb, pr, sparse)} + for s in slots] + if prim_names: + p["extras"] = {"targetNames": [target_names[s] for s in slots]} + m["primitives"].append(p) + if slots: + m["extras"] = {"targetNames": [target_names[s] for s in slots]} + for j, s in enumerate(slots): + where[s].append((mi, j)) + meshes.append(m) + used = set() + for m in meshes: # 网格名会成为 Unity 里的物体名,别重 + base, k = m["name"], 2 + while m["name"] in used: + m["name"] = "%s_%d" % (base, k) + k += 1 + used.add(m["name"]) + return meshes, where + + +def _mesh_name(prims, ids, name): + """几个网格时按里面最大的 primitive 的材质起名(在 Unity 的层级里一眼能认出是哪一块)。""" + big = max(ids, key=lambda i: prims[i]["vcount"]) + return prims[big].get("mat_name") or name + + +def remap_binds(expr, where, mesh_nodes, is1): + """表情绑定里的全局 morph target 序号 → 各网格里的(一个 target 分在几个网格时拆成几个绑定)。 + + 1.0 的 node 是网格节点(mesh_nodes[网格号]),0.x 的 mesh 是网格号。哪个网格都没有的 target + (group_meshes 已经避免)就丢掉这个绑定。 + """ + if is1: + for grp in (expr["preset"], expr["custom"]): + for obj in grp.values(): + if "morphTargetBinds" not in obj: + continue + obj["morphTargetBinds"] = [{"node": mesh_nodes[m], "index": j, "weight": b["weight"]} + for b in obj["morphTargetBinds"] for m, j in where[b["index"]]] + if not obj["morphTargetBinds"]: + del obj["morphTargetBinds"] + else: + for g in expr["blend_groups"]: + g["binds"] = [{"mesh": m, "index": j, "weight": b["weight"]} + for b in g["binds"] for m, j in where[b["index"]]] diff --git a/convert/vrmconv/morphbake.py b/convert/vrmconv/morphbake.py new file mode 100644 index 0000000..8869fe4 --- /dev/null +++ b/convert/vrmconv/morphbake.py @@ -0,0 +1,332 @@ +# -*- coding: utf-8 -*- +"""VRM 表情只能动顶点(morph target)、材质颜色和贴图偏移,PMX 里另外两种表情要先「烘焙」: + + BoneBaker 骨骼表情(kind 2,寄り目 / +目上 / 齿轮旋转 …)→ 顶点偏移:在静止姿势下 + 按表情给的平移 / 旋转摆骨(付与骨跟着付与親转、子骨跟着父骨),线性混合蒙皮 + 算出每个顶点的位移。以前直接丢掉,含骨骼表情的グループ表情也就缺了一块。 + gaze_offsets 视线表情(lookUp / lookDown / lookLeft / lookRight):转左右眼骨的骨骼表情, + 同样烘焙成顶点偏移。lookAt 仍然是 bone 类型;有的程序(游戏的表情动画) + 直接播这四个表情,模型里没有就看不到眼珠动。 + uv_binds UV 表情(kind 3,漫符 / 表情贴图切换)→ 贴图的缩放 + 偏移(VRM 1.0 的 + textureTransformBinds、0.x 的 _MainTex_ST)。只有整个材质的 UV 按同一个 + 仿射变换移动时才能表示(漫符那种一个材质一块面片的正好是)。 + +都在 PMX 坐标里算(左手系,脸朝 -Z、左手 +X);结果和普通顶点表情一样交给 expressions。 +""" +import math + +from .mathutil import _I3, _axis_angle, _m3mul, _m3vec, _to_axis_angle +from .mesh import vertex_weights + + +def _quat_m3(q): + """PMX 骨骼表情的四元数 (x, y, z, w) → 旋转矩阵。 + + MMD 的矩阵是行向量约定(v' = v·M),换成列向量正好是标准公式,数值上不用改符号。 + """ + x, y, z, w = q + s = math.sqrt(x * x + y * y + z * z) + if s < 1e-9: + return _I3 + return _axis_angle((x / s, y / s, z / s), 2.0 * math.atan2(s, w)) + + +def _scale_rot(m, rate): + """旋转按比例缩放(付与率):轴不变、角度 × rate。""" + if m is _I3 or abs(rate - 1.0) < 1e-9: + return m + ax, ang = _to_axis_angle(m) + if abs(ang * rate) < 1e-9: + return _I3 + return _axis_angle(ax, ang * rate) + + +class BoneBaker: + """骨骼表情 → {顶点: (dx, dy, dz)}(PMX 坐标)。""" + + def __init__(self, model, weights=None): + """weights:已经算好的不带付与别名的顶点权重(mesh.vertex_weights(..., {})),没给时用到再算。""" + self.bones = model["bones"] + self.verts = model["vertices"] + self._weights = weights + self._users = None + + def _vertex_weights(self): + if self._users is None: + if self._weights is None: + self._weights = vertex_weights(self.verts, len(self.bones), {}) + users = {} + for vi, wl in enumerate(self._weights): + for b, _ in wl: + users.setdefault(b, []).append(vi) + self._users = users + return self._weights + + def deltas(self, offsets): + """offsets:[(骨, (tx, ty, tz), (qx, qy, qz, qw))],即 PMX 骨骼表情的 offsets。""" + bones = self.bones + nb = len(bones) + loc_r, loc_t = {}, {} + for b, t, q in offsets: + if not (0 <= b < nb): + continue + r = _quat_m3(q) + if r is not _I3: + loc_r[b] = _m3mul(r, loc_r.get(b, _I3)) + if abs(t[0]) + abs(t[1]) + abs(t[2]) > 1e-9: + o = loc_t.get(b, (0.0, 0.0, 0.0)) + loc_t[b] = (o[0] + t[0], o[1] + t[1], o[2] + t[2]) + if not loc_r and not loc_t: + return {} + + # 付与:付与先的局部旋转 / 移动 = 自己的 + 付与親的 × 付与率(付与親也可能是付与骨) + eff = {} + + def local(b, depth=0): + if b in eff: + return eff[b] + r, t = loc_r.get(b, _I3), loc_t.get(b, (0.0, 0.0, 0.0)) + if depth < 32: + ir = bones[b].get("inherit_rot") + if ir and 0 <= ir[0] < nb and ir[0] != b: + rs = _scale_rot(local(ir[0], depth + 1)[0], ir[1]) + if rs is not _I3: + r = rs if r is _I3 else _m3mul(rs, r) + im = bones[b].get("inherit_mov") + if im and 0 <= im[0] < nb and im[0] != b: + ts = local(im[0], depth + 1)[1] + t = (t[0] + ts[0] * im[1], t[1] + ts[1] * im[1], t[2] + ts[2] * im[1]) + eff[b] = (r, t) + return eff[b] + + # 全局:G_b = G_父 ∘ 平移(骨位置 + t) ∘ R ∘ 平移(-骨位置),只记不是恒等的 + glob = {} + state = {} + for start in range(nb): + stack = [start] + while stack: + b = stack[-1] + if b in state: + stack.pop() + continue + p = bones[b]["parent"] + if 0 <= p < nb and p not in state and p != b and len(stack) < nb: + stack.append(p) + continue + stack.pop() + r, t = local(b) + par = glob.get(p) if (0 <= p < nb and p != b) else None + if r is _I3 and abs(t[0]) + abs(t[1]) + abs(t[2]) < 1e-12 and par is None: + state[b] = True + continue + pos = bones[b]["pos"] + rp = _m3vec(r, pos) + lt = (pos[0] + t[0] - rp[0], pos[1] + t[1] - rp[1], pos[2] + t[2] - rp[2]) + if par is None: + glob[b] = (r, lt) + else: + pm, pt = par + q = _m3vec(pm, lt) + glob[b] = (_m3mul(pm, r), (q[0] + pt[0], q[1] + pt[1], q[2] + pt[2])) + state[b] = True + if not glob: + return {} + + weights = self._vertex_weights() + touched = set() + for b in glob: + touched.update(self._users.get(b, ())) + out = {} + for vi in touched: + p = self.verts[vi]["pos"] + x = y = z = 0.0 + for b, w in weights[vi]: + g = glob.get(b) + if g is None: + q = p + else: + q = _m3vec(g[0], p) + q = (q[0] + g[1][0], q[1] + g[1][1], q[2] + g[1][2]) + x += q[0] * w + y += q[1] * w + z += q[2] * w + d = (x - p[0], y - p[1], z - p[2]) + if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-7: + out[vi] = d + return out + + +# 视线表情的角度:VRoid 的 lookAt 量程(水平 / 垂直)同量级;眼骨在眼球中心附近, +# 转 12° 眼珠大约移动眼宽的 1/4 +GAZE_DEG = {"lookLeft": 12.0, "lookRight": 12.0, "lookUp": 10.0, "lookDown": 10.0} +LOOK_TRAVEL = 0.28 # 看到最边上时瞳孔走多远(瞳孔宽度的比例;VRoid 向内看约 29%) + + +def eye_look_range(model, vweights, parents, eyes): + """按眼球几何算视线最大转角 → (角度, 说明)。 + + 角度:{"lookLeft", "lookRight", "lookUp", "lookDown"}(度);算不出或测出来不合理时为 None + (调用方用默认的 10°),说明给日志用。 + + 瞳孔看起来移动多少 = 转角 × 支点到瞳孔的距离。VRoid 的眼骨支点很深(约 6 cm),转 8° 就走 + 瞳孔宽度的 29%;MMD 模型的支点常常贴着眼球(2~4 cm),固定 10° 只走 15~25%,转眼不明显。 + 所以按「瞳孔走 LOOK_TRAVEL × 瞳孔宽度」反推左右的角度(8°~20°)。上下按左右的比例: + 向下 0.7(动画眼睛竖向本来就扁,再多会钻到下眼皮里),向上 0.5(上眼皮挡着;VRoid 是 0°)。 + 瞳孔 = 跟着眼骨及其子骨(左目先 等)走的顶点(权重 > 0.5)。 + """ + bones, verts = model["bones"], model["vertices"] + real = [e for e in eyes if e is not None] + # 两眼间距:测出来的「瞳孔」比它还宽、或者支点离瞳孔比它还远,就是把别的东西也挂在眼骨上了 + # (整个眼部、脸),这时候算出来的角度不可信 + span = abs(bones[real[0]]["pos"][0] - bones[real[1]]["pos"][0]) if len(real) == 2 else None + angles = [] + for eye in real: + if eye is None: + continue + sub = {eye} + grew = True + while grew: + grew = False + for i, p in enumerate(parents): + if p in sub and i not in sub: + sub.add(i) + grew = True + pts = [verts[v]["pos"] for v in range(len(verts)) + if sum(w for b, w in vweights[v] if b in sub) > 0.5] + if len(pts) < 8: + continue + px, _, pz = bones[eye]["pos"] + xs = [q[0] for q in pts] + dist = sorted(math.hypot(q[0] - px, q[2] - pz) for q in pts) + far = dist[len(dist) // 2:] # 眼球前面(瞳孔表面)那一半 + r = sum(far) / len(far) + width = max(xs) - min(xs) + if span and (width > 0.8 * span or r > 1.5 * span): + return None, ("眼骨上的顶点不像一只眼睛(宽 %.2f、支点到表面 %.2f,两眼相距 %.2f),使用默认值 10°" + % (width, r, span)) + if r > 1e-6 and width > 1e-6: + angles.append(math.degrees(math.atan(LOOK_TRAVEL * width / r))) + if not angles: + return None, "眼骨上没有瞳孔顶点,使用默认值 10°" + raw = sum(angles) / len(angles) + h = min(20.0, max(8.0, raw)) + note = "按眼球结构计算,瞳孔最多移动约 %d%% 瞳孔宽度" % round(LOOK_TRAVEL * 100) + if h != raw: + note += ";算出 %.1f°,限制到 %.0f°" % (raw, h) + return {"lookLeft": h, "lookRight": h, "lookDown": round(h * 0.7, 2), "lookUp": round(h * 0.5, 2)}, note + + +def gaze_offsets(left_eye, right_eye, deg=None): + """→ [(表情名, 骨骼表情 offsets)]:两只眼骨一起转(角度 deg,默认 GAZE_DEG)。 + + PMX 坐标里脸朝 -Z、角色的左边是 +X、上是 +Y: + 向左看(角色自己的左边,VRM 规范的 lookLeft)= 绕 Y 轴转负角,(0,0,-1) → +X + 向上看 = 绕 X 轴转正角,(0,0,-1) → +Y + """ + out = [] + for name, axis, sign in (("lookLeft", (0.0, 1.0, 0.0), -1.0), ("lookRight", (0.0, 1.0, 0.0), 1.0), + ("lookUp", (1.0, 0.0, 0.0), 1.0), ("lookDown", (1.0, 0.0, 0.0), -1.0)): + half = math.radians((deg or GAZE_DEG)[name]) * sign * 0.5 + q = (axis[0] * math.sin(half), axis[1] * math.sin(half), axis[2] * math.sin(half), math.cos(half)) + out.append((name, [(b, (0.0, 0.0, 0.0), q) for b in (left_eye, right_eye) if b is not None])) + return out + + +# 视线表情按这个角度烘焙(和调整面板滑块的上限一样),实际角度靠权重:转眼骨 θ 时顶点的位移 +# 恰好是「横向场 × sinθ + 深度场 ×(1 − cosθ)」(Rodrigues),左右一对 ±Θ 的烘焙结果正好拆出这两个场: +# 横向 = (d(+Θ) − d(−Θ)) / 2,深度 = (d(+Θ) + d(−Θ)) / 2 +# 表情 = 横向 × sinθ/sinΘ + 深度 × (1−cosθ)/(1−cosΘ),任意 θ ≤ Θ 都和真的转眼骨一样(蒙皮是线性混合, +# 部分挂在眼骨上的眼皮也一样)。调整面板改视线角度时只改这两个权重,不用重新烘焙 +GAZE_MAX = {"h": 40.0, "v": 30.0} +GAZE_PAIRS = (("lookLeft", "lookRight", "h"), ("lookUp", "lookDown", "v")) +GAZE_DEPTH = {"h": "lookLeftRight_depth", "v": "lookUpDown_depth"} +GAZE_KEY = {"lookLeft": "h", "lookRight": "h", "lookUp": "up", "lookDown": "down"} # 对应 lookAt 的哪个转角 + + +def gaze_weights(deg, axis): + """转 deg 度 → (横向权重, 深度权重)。超过烘焙角度时按烘焙角度。""" + big = math.radians(GAZE_MAX[axis]) + t = math.radians(min(max(deg, 0.0), GAZE_MAX[axis])) + return round(math.sin(t) / math.sin(big), 6), round((1 - math.cos(t)) / (1 - math.cos(big)), 6) + + +def split_gaze(flat, names): + """flat(_flatten_morphs 的结果)里按 GAZE_MAX 烘焙的视线表情(成对的、从末尾找)拆成横向场 + 深度场: + lookLeft / lookRight / lookUp / lookDown 原地换成横向场,再追加两个深度场。 + → {预设: (横向名, 深度名, 轴)};names 是补进去的视线表情名,不成对的不拆。""" + pos = {} + for k in range(len(flat) - 1, -1, -1): + if flat[k][0] in names and flat[k][0] not in pos: + pos[flat[k][0]] = k + out = {} + for a, b, axis in GAZE_PAIRS: + if a not in pos or b not in pos: + continue + da, db = flat[pos[a]][1], flat[pos[b]][1] + tan, depth = {}, {} + for v in set(da) | set(db): + x, y = da.get(v, (0.0, 0.0, 0.0)), db.get(v, (0.0, 0.0, 0.0)) + t = tuple((x[i] - y[i]) * 0.5 for i in range(3)) + d = tuple((x[i] + y[i]) * 0.5 for i in range(3)) + if abs(t[0]) + abs(t[1]) + abs(t[2]) > 1e-9: + tan[v] = t + if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-9: + depth[v] = d + flat[pos[a]] = (a, tan, [], {}) + flat[pos[b]] = (b, {v: (-t[0], -t[1], -t[2]) for v, t in tan.items()}, [], {}) + flat.append((GAZE_DEPTH[axis], depth, [], {})) + out[a] = (a, GAZE_DEPTH[axis], axis) + out[b] = (b, GAZE_DEPTH[axis], axis) + return out + + +def material_vertices(model): + """→ [每个材质用到的顶点集合]。""" + faces = model["faces"] + out = [] + f0 = 0 + for mat in model["materials"]: + n = mat["faces"] + out.append(set(faces[f0:f0 + n])) + f0 += n + return out + + +def uv_binds(model, uvs, mat_verts=None, tol=2e-3): + """UV 表情 {顶点: (du, dv)} → ([(材质, (缩放 u, v), (偏移 u, v))], 表示不了的材质数)。 + + 每个被动到的材质:所有顶点(没动的偏移算 0)的新 UV 要能写成 + u' = su·u + ou、v' = sv·v + ov(最小二乘拟合后误差 < tol),否则算「表示不了」。 + """ + if not uvs: + return [], 0 + mat_verts = mat_verts if mat_verts is not None else material_vertices(model) + verts = model["vertices"] + out, bad = [], 0 + for mi, vs in enumerate(mat_verts): + if not vs or not any(v in uvs for v in vs): + continue + fit = [] + for k in (0, 1): + xs = [verts[v]["uv"][k] for v in vs] + ys = [xs[i] + uvs.get(v, (0.0, 0.0))[k] for i, v in enumerate(vs)] + n = len(xs) + mx, my = sum(xs) / n, sum(ys) / n + sxx = sum((x - mx) ** 2 for x in xs) + if sxx < 1e-12: # 所有顶点 UV 一样:只能是纯偏移 + s = 1.0 + else: + s = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx + o = my - s * mx + if max(abs(s * x + o - y) for x, y in zip(xs, ys)) > tol: + fit = None + break + fit.append((s, o)) + if fit is None: + bad += 1 + continue + (su, ou), (sv, ov) = fit + if abs(su - 1) < 1e-6 and abs(sv - 1) < 1e-6 and abs(ou) < 1e-6 and abs(ov) < 1e-6: + continue + out.append((mi, (su, sv), (ou, ov))) + return out, bad diff --git a/convert/vrmconv/skeleton.py b/convert/vrmconv/skeleton.py new file mode 100644 index 0000000..5d93e18 --- /dev/null +++ b/convert/vrmconv/skeleton.py @@ -0,0 +1,410 @@ +# -*- coding: utf-8 -*- +"""骨骼预处理和 glTF 节点树。 + + fix_facing 模型侧着 / 背对时绕 Y 轴转正(Unreal 的 psk / uemodel 常见) + prepare_bones 付与骨合并、humanoid 映射与层级修正、拓扑排序(PMX 坐标) + apply_tpose A-pose → T-pose:骨骼位置和顶点一起重摆 + NodeTree 骨骼 → glTF 节点(先记父节点 + 世界坐标,最后统一换算 translation, + 所以补占位骨、SpringBone 改挂父节点都可以随意改) +""" +import math +from types import SimpleNamespace + +from .humanoid import (REQUIRED_0X, REQUIRED_1_0, _HIPS_Y, _SYNTH, _append_aliases, + _bone_len, _clean_parents, _fix_humanoid_hierarchy, _is_ancestor, _map_humanoid, _pick_toes, _reparent, + _topo_bones, _tpose_globals, _vrm_anchor) +from .mathutil import _I3, _m3vec + + +def fix_facing(model, log): + """PMX 约定左手在 +X、脸朝 -Z。从 humanoid 的左右肩 / 胯算出左右方向,不在 X 轴上时 + 绕 Y 轴转最近的 90° 倍数(Unreal 的前方是另一根轴,psk / uemodel 转来的模型常常侧着; + xps / FBX 偶尔背对)。侧着的模型做 T-pose 时会把向前伸的手臂当成下垂的再转 90°。 + + 只在没有物理刚体时转(刚体的欧拉角不好跟着转,原生 PMX 本来就是正的)。返回转的角度。 + """ + bones = model["bones"] + if model.get("rigid_bodies"): + return 0 + human = _map_humanoid(bones, True, {}) + pairs = [(human[a], human[b]) for a, b in (("leftUpperArm", "rightUpperArm"), ("leftUpperLeg", "rightUpperLeg"), + ("leftShoulder", "rightShoulder")) if a in human and b in human] + if not pairs: + return 0 + sx = sum(bones[l]["pos"][0] - bones[r]["pos"][0] for l, r in pairs) + sz = sum(bones[l]["pos"][2] - bones[r]["pos"][2] for l, r in pairs) + if math.hypot(sx, sz) < 1e-6: + return 0 + quarter = round(math.atan2(sz, sx) / (math.pi / 2)) % 4 # 0 = 已经是正的 + if quarter == 0: + return 0 + t = quarter * math.pi / 2 + c, s = round(math.cos(t)), round(math.sin(t)) + + def rot(v): # 把「左」方向转到 +X:x' = x·c + z·s,z' = −x·s + z·c + return (v[0] * c + v[2] * s, v[1], -v[0] * s + v[2] * c) + + for v in model.get("vertices") or []: + v["pos"] = rot(v["pos"]) + v["normal"] = rot(v["normal"]) + if v.get("sdef"): + v["sdef"] = [rot(p) for p in v["sdef"]] + for b in bones: + b["pos"] = rot(b["pos"]) + if b.get("tail_kind") == 0 and b.get("tail") is not None and not isinstance(b["tail"], int): + b["tail"] = rot(b["tail"]) + if b.get("fixed_axis"): + b["fixed_axis"] = rot(b["fixed_axis"]) + if b.get("local_axis"): + b["local_axis"] = tuple(rot(a) for a in b["local_axis"]) + for mo in model.get("morphs") or []: + if mo["kind"] == 1: + mo["offsets"] = [(i, rot(o)) for i, o in mo["offsets"]] + elif mo["kind"] == 2: + mo["offsets"] = [(i, rot(t_), q_) for i, t_, q_ in mo["offsets"]] # 骨骼表情的平移 + deg = quarter * 90 + if log: + log("朝向:模型%s,已绕 Y 轴旋转 %d° 校正(左右肩 / 胯不在 X 轴上)" + % ("背向前方" if quarter == 2 else "朝向侧面", deg), "warn") + return deg + + +def prepare_bones(bones, is1, log, weighted=()): + """→ SimpleNamespace(parents, alias, required, human_b, order, remap)。 + + 1) 付与 100% 的骨(足D 等)并入付与親:权重与子骨都转过去 + 2) humanoid 映射 + 层级修正(上半身 挂到 下半身 下等);脚趾按 _pick_toes 选 + weighted:挂了网格的骨(PMX 骨索引),选脚趾时用。 + """ + nb = len(bones) + parents = _clean_parents(bones) + alias = _append_aliases(bones, parents, eps=0.01) + if alias: + for i, dst in alias.items(): + for c in range(nb): + if parents[c] == i: + _reparent(parents, c, dst) + log("付与骨合并:%d 根(%s)→ 权重并入付与親" + % (len(alias), "、".join(bones[i]["name"] for i in + list(alias)[:6]) + + ("…" if len(alias) > 6 else ""))) + off = [bones[i]["name"] for i, s in alias.items() if math.dist(bones[i]["pos"], bones[s]["pos"]) > 0.01] + if off: + log("付与骨合并:%s 与付与親的位置略有偏差,合并后绕付与親的位置转动" % "、".join(off)) + # 1.0 规范里 chest / neck 可选,但不少程序、动作数据默认有(比如按躯干关节生成布娃娃), + # 缺的话和 0.x 一样补占位骨 + required = REQUIRED_0X + human_b = _map_humanoid(bones, is1, alias) + _pick_toes(bones, human_b, alias, set(weighted)) + _fix_humanoid_hierarchy(human_b, parents, bones, set(required), log) + order, remap = _topo_bones(parents) + return SimpleNamespace(parents=parents, alias=alias, required=required, + human_b=human_b, order=order, remap=remap) + + +def split_partial(bones, bs, vweights, rigid_bodies, log): + """按比例跟随关节的付与骨(ひざ補助 跟 ひざ 转 0.5、尻 跟 足 转 0.5 之类)→ 新的逐顶点权重。 + + 这些骨让关节弯曲时保持体积:MMD 里绕自己的位置转关节角度的一部分。VRM 没有付与,原样导出时它们 + 只跟父骨走,关节一弯这部分就瘪下去。这里把它(和它下面的骨)上的权重按付与率拆开:付与率那份给 + 关节骨,其余留在原骨上,线性混合出来约等于转了一部分角度(误差约为不拆的一半到四分之一)。 + 静止姿势不变,在 T-pose 之后做(T-pose 里这些骨已按付与率跟转)。 + + 只拆:付与親(并入后)是 humanoid 骨、付与率在 0.05~1 之间、和关节骨跟着同一根 humanoid 骨移动 + (见 humanoid._append_aliases)、自己和下面的骨都不带物理刚体的。付与率 1 却没能并入付与親的 + (偏差超过半节骨长)在偏差不超过一节骨长时整份转过去;再远的不动——它的顶点要是都在自己的转动点 + 附近,改绕关节转反而比不动偏得多,留给自检在日志里提示。 + """ + n = len(bones) + if not n: + return vweights + hum = set(bs.human_b.values()) + phys = {rb.get("bone") for rb in rigid_bodies or () if rb.get("mode") in (1, 2)} + kids = [[] for _ in range(n)] + for c, p in enumerate(bs.parents): + if 0 <= p < n and p != c: + kids[p].append(c) + + def anchor(i): + seen = set() + while 0 <= i < n and i not in seen: + if i in hum: + return i + seen.add(i) + i = bs.parents[i] + return -1 + + def subtree(i): # 到下一根 humanoid 骨为止 + out, todo = {i}, [i] + while todo: + for c in kids[todo.pop()]: + if c not in hum and c not in out: + out.add(c) + todo.append(c) + return out + + plan, names = {}, [] + for i, b in enumerate(bones): + ir = b.get("inherit_rot") + if not ir or i in hum or i in bs.alias or not (0 <= ir[0] < n) or not (0.05 <= ir[1] <= 1.0001): + continue + s = bs.alias.get(ir[0], ir[0]) + if s not in hum or _is_ancestor(bs.parents, i, s) or _is_ancestor(bs.parents, s, i): + continue + if anchor(bs.parents[i]) != anchor(bs.parents[s]): + continue + if ir[1] >= 0.999 and math.dist(b["pos"], bones[s]["pos"]) > max( + math.dist(bones[bs.parents[s]]["pos"], bones[s]["pos"]) if bs.parents[s] >= 0 else 0.0, + _bone_len(bones, bs.parents, s)): + continue # 100% 跟随却离关节一节骨长以上:绕关节转可能比不动还偏,留给自检提示 + sub = subtree(i) + if phys.intersection(sub): + continue + for k in sub: + if k == i or not bones[k].get("inherit_rot"): + plan.setdefault(k, (s, min(1.0, ir[1]))) + names.append(bones[i]["name"]) + if not plan: + return vweights + out, nv = list(vweights), 0 + for vi, wl in enumerate(vweights): + if not any(b in plan for b, _ in wl): + continue + acc = {} + for b, w in wl: + if b in plan: + s, r = plan[b] + acc[s] = acc.get(s, 0.0) + w * r + if r < 1.0: + acc[b] = acc.get(b, 0.0) + w * (1.0 - r) + else: + acc[b] = acc.get(b, 0.0) + w + top = sorted(acc.items(), key=lambda t: -t[1])[:4] + tot = sum(w for _, w in top) or 1.0 + out[vi] = [(b, w / tot) for b, w in top] + nv += 1 + if nv: + log("付与骨:%d 根按比例跟随关节的骨(%s)→ 权重按付与率分给关节骨,共 %d 个顶点" + % (len(names), "、".join(names[:6]) + ("…" if len(names) > 6 else ""), nv)) + return out + + +def apply_tpose(verts, bones, bs, vweights, tpose, log): + """A-pose → T-pose(线性混合蒙皮),返回 (glob, bpos, vpos, vnrm, vmat)。 + + glob:每根骨的 T-pose 全局变换(没做 T-pose 时为 None);vmat:每个顶点的混合旋转, + 表情偏移要跟着转(没动的顶点为 None)。都是 PMX 坐标。 + """ + nb = len(bones) + vpos = [v["pos"] for v in verts] + vnrm = [v["normal"] for v in verts] + vmat = None + bpos = [b["pos"] for b in bones] + glob = _tpose_globals(bones, bs.parents, bs.order, bs.human_b, log) \ + if (tpose and nb) else None + if glob: + bpos = [] + for i in range(nb): + m, t = glob[i] + q = _m3vec(m, bones[i]["pos"]) + bpos.append((q[0] + t[0], q[1] + t[1], q[2] + t[2])) + vpos, vnrm, vmat = [], [], [None] * len(verts) + for vi, v in enumerate(verts): + wl = vweights[vi] + if all(glob[b_][0] is _I3 for b_, _ in wl): + vpos.append(v["pos"]) + vnrm.append(v["normal"]) + continue + m = [0.0] * 9 + t = [0.0, 0.0, 0.0] + for b_, w in wl: + gm, gt = glob[b_] + for k in range(9): + m[k] += gm[k] * w + for k in range(3): + t[k] += gt[k] * w + q = _m3vec(m, v["pos"]) + vpos.append((q[0] + t[0], q[1] + t[1], q[2] + t[2])) + vnrm.append(_m3vec(m, v["normal"])) + vmat[vi] = m + return glob, bpos, vpos, vnrm, vmat + + +class NodeTree: + """glTF 节点:名字、父节点、世界坐标(VRM 坐标)。骨骼按拓扑序排在最前面。""" + + def __init__(self, bones, bs, bpos, xf): + self.names = [] + self.parent = [] + self.wpos = [] + self._remap = bs.remap + self._of_bone = [0] * len(bones) + self._name_set = None + for new_i, old_i in enumerate(bs.order): + par = bs.parents[old_i] + self._of_bone[new_i] = len(self.names) + self.names.append(bones[old_i]["name"] or ("bone%d" % old_i)) + self.parent.append(self._of_bone[bs.remap[par]] + if (par >= 0 and bs.remap[par] < new_i) else None) + self.wpos.append(xf(bpos[old_i])) + if not bones: # 极端情况:没有骨骼 + self.names.append("root_bone") + self.parent.append(None) + self.wpos.append((0.0, 0.0, 0.0)) + + def bone_node(self, pmx_index): + """PMX 骨骼序号 → 节点序号。""" + if 0 <= pmx_index < len(self._of_bone): + return self._of_bone[self._remap[pmx_index]] + return None + + def node_pos(self, n): + return self.wpos[n] + + def is_ancestor(self, a, b): + seen = set() + while b is not None and b not in seen: + if b == a: + return True + seen.add(b) + b = self.parent[b] + return False + + def add_node(self, name, parent, pos): + """新增一个节点(重名时加 _2、_3 …),返回序号。""" + if self._name_set is None: + self._name_set = set(self.names) + nm, k = name, 2 + while nm in self._name_set: + nm = "%s_%d" % (name, k) + k += 1 + self._name_set.add(nm) + self.names.append(nm) + self.parent.append(parent) + self.wpos.append(pos) + return len(self.names) - 1 + + def set_parent(self, node, parent): + self.parent[node] = parent + + def humanoid(self, human_b, required, unit, log, roots=()): + """humanoid 骨位 → 节点;缺失的必需骨位补占位骨(vrm_*)。 + + roots:另外要补的骨位(0.x 的两节拇指缺掌根那节 ThumbProximal 时补一个,插在手和第二节之间)。 + + unit(左, 上, 前) → 当前规范下的方向向量(1.0 左 +X 前 +Z;0.x 反过来)。 + """ + human = {k: self.bone_node(v) for k, v in human_b.items()} + req = set(required) + + def ensure(name): + if name in human: + return human[name] + pname = _vrm_anchor(name, set(human) | req) + pnode = ensure(pname) if pname else None + # 已有的、规范上应挂在本骨位下的 humanoid 骨(比如缺 spine 时的 chest) + kids = [human[h] for h in list(human) + if _vrm_anchor(h, set(human) | {name}) == name + and not (pnode is not None and + self.is_ancestor(human[h], pnode))] + if kids: + kc = [sum(self.wpos[k][j] for k in kids) / len(kids) for j in range(3)] + if pnode is not None: + pos = tuple((self.wpos[pnode][j] + kc[j]) * 0.5 for j in range(3)) + else: + pos = tuple(kc) + else: + off = _SYNTH.get(name, (0.0, 0.05, 0.0)) + d = unit(off[0], off[1], off[2]) + if pnode is None: + pos = (0.0, _HIPS_Y, 0.0) if name == "hips" else d + else: + pos = tuple(self.wpos[pnode][j] + d[j] for j in range(3)) + idx = len(self.names) + self.names.append("vrm_" + name) + self.parent.append(pnode) + self.wpos.append(pos) + for k in kids: + self.parent[k] = idx + human[name] = idx + return idx + + for r in required: + if r not in human: + ensure(r) + log("骨骼:模型缺少 %s,已生成占位骨骼" % r, "warn") + added = [r for r in roots if r not in human] + for r in added: + ensure(r) + if added: + log("骨骼:拇指只有两节(%s),已在手腕和第二节之间补上掌根那节,0.x 和 1.0 的拇指各节对应一致" + % "、".join(added)) + return human + + def lower_hips(self, human, log): + """hips 放到骨盆(大腿根往上一点),不和 spine 重合。 + + MMD 的「下半身」「上半身」从腰部同一点出发,映射成 hips / spine 后两者几乎重合(0~5 mm), + hips 也比大腿根高出一截。按 hips → spine 的距离生成躯干碰撞体的程序(游戏布娃娃)会 + 得到长度为 0 的一段。VRoid 的 hips 在大腿根往上约 43%(到 spine 的高度差)处。 + 只改节点位置:子节点的局部偏移、逆绑定矩阵都按世界坐标算,网格和权重不受影响。 + """ + if not all(k in human for k in ("hips", "spine", "leftUpperLeg", "rightUpperLeg")): + return + h, s = human["hips"], human["spine"] + leg_y = (self.wpos[human["leftUpperLeg"]][1] + self.wpos[human["rightUpperLeg"]][1]) * 0.5 + gap = self.wpos[s][1] - leg_y + # MMD 模型实测 0~5 mm(不到高度差的 5%);正常绑定的 FBX 等 hips 本来就在骨盆, + # 离 spine 有高度差的 20% 以上,不动 + if gap <= 0.02 or self.wpos[s][1] - self.wpos[h][1] >= 0.1 * gap: + return + old = self.wpos[h] + self.wpos[h] = (old[0], leg_y + 0.43 * gap, old[2]) + log("hips:已移至骨盆,下移 %.1f cm(原与 spine 相距 %.1f mm)" + % ((old[1] - self.wpos[h][1]) * 100, abs(self.wpos[s][1] - old[1]) * 1000)) + + def prune(self, core, collapse=False): + """只留 core 里的节点和连接它们所需的祖先,其余(IK、合并掉的付与骨、末端骨等)删掉。 + + collapse:祖先也不留——没有权重的中间节点(MMD 的 全ての親 / センター / グルーブ / 腰 / 肩P 之类) + 一并去掉,子节点挂到最近的保留祖先上,层级像 VRoid(Root > Hips)。 + 节点位置是世界坐标,删掉中间节点不改变其余节点的位置。返回 旧序号 → 新序号(删掉的不在里面)。 + """ + keep = set(core) + if not collapse: + for n in core: + p = self.parent[n] + while p is not None and p not in keep: + keep.add(p) + p = self.parent[p] + order = [i for i in range(len(self.names)) if i in keep] + new = {o: k for k, o in enumerate(order)} + + def up(i): + p = self.parent[i] + while p is not None and p not in new: + p = self.parent[p] + return None if p is None else new[p] + + self.parent = [up(i) for i in order] + self.names = [self.names[i] for i in order] + self.wpos = [self.wpos[i] for i in order] + self._of_bone = [new.get(n) for n in self._of_bone] + self._name_set = None + return new + + def gltf_nodes(self): + """→ (glTF nodes 列表, 没有父节点的节点序号)。translation 按父节点换算成局部值。""" + nodes = [] + top = [] + for i, nm in enumerate(self.names): + p = self.parent[i] + base = self.wpos[p] if p is not None else (0.0, 0.0, 0.0) + nodes.append({"name": nm, + "translation": [self.wpos[i][j] - base[j] for j in range(3)]}) + for i, p in enumerate(self.parent): + if p is not None: + nodes[p].setdefault("children", []).append(i) + else: + top.append(i) + return nodes, top diff --git a/convert/vrmconv/springbone.py b/convert/vrmconv/springbone.py new file mode 100644 index 0000000..ffcaab4 --- /dev/null +++ b/convert/vrmconv/springbone.py @@ -0,0 +1,612 @@ +# -*- coding: utf-8 -*- +"""PMX 刚体物理 → VRMC_springBone(VRM 1.0)。""" +import math + +from .mathutil import _I3, _m3mul, _m3vec + + +_TORSO = {"hips", "spine", "chest", "upperChest"} +_ARM_PARTS = ("Shoulder", "Arm", "Hand", "Thumb", "Index", "Middle", "Ring", "Little") +_LEG_PARTS = ("Leg", "Foot", "Toes") + + +def _limb_of(role): + """humanoid 骨位 → (侧, "arm"/"leg");不是四肢返回 None。""" + for side in ("left", "right"): + if role and role.startswith(side): + if any(k in role for k in _ARM_PARTS): + return side, "arm" + if any(k in role for k in _LEG_PARTS): + return side, "leg" + return None + + +def _euler_yxz(r): + """PMX 刚体旋转(弧度,DirectX 的 Yaw-Pitch-Roll)→ 3x3 矩阵 Ry·Rx·Rz。""" + cx, sx = math.cos(r[0]), math.sin(r[0]) + cy, sy = math.cos(r[1]), math.sin(r[1]) + cz, sz = math.cos(r[2]), math.sin(r[2]) + rx = (1.0, 0.0, 0.0, 0.0, cx, -sx, 0.0, sx, cx) + ry = (cy, 0.0, sy, 0.0, 1.0, 0.0, -sy, 0.0, cy) + rz = (cz, -sz, 0.0, sz, cz, 0.0, 0.0, 0.0, 1.0) + return _m3mul(_m3mul(ry, rx), rz) + + +def _rigid_shape(rb, glob): + """刚体 → (中心, 半径, 半长轴向量),都在 PMX 坐标(T-pose 之后)。 + + 球:半长轴为 0;胶囊:沿局部 Y,size = (半径, 圆柱长度); + 盒:近似成沿最长轴的胶囊,半径取另外两轴半长的平均。 + """ + rot = _euler_yxz(rb["rot"]) + sx, sy, sz = rb["size"] + shape = rb["shape"] + if shape == 0: + r, half = sx, (0.0, 0.0, 0.0) + elif shape == 2: + ax = (rot[1], rot[4], rot[7]) + r = sx + half = tuple(ax[k] * sy * 0.5 for k in range(3)) + else: + ext = (sx, sy, sz) + k = max(range(3), key=lambda i: ext[i]) + others = [ext[i] for i in range(3) if i != k] + r = sum(others) / 2.0 + ax = (rot[k], rot[3 + k], rot[6 + k]) + hl = max(0.0, ext[k] - r) + half = tuple(ax[j] * hl for j in range(3)) + c = rb["pos"] + g = glob.get(rb["bone"]) if glob else None + if g: + m, t = g + q = _m3vec(m, c) + c = (q[0] + t[0], q[1] + t[1], q[2] + t[2]) + half = _m3vec(m, half) + return c, r, half + + +def _build_springs(model, parents, alias, human_b, glob, bpos, scale, xf, + bone_node, node_pos, add_node, include_lower=True, + stiffness_mul=1.0, gravity=0.0, gravity_lower=0.1, + seg_min=0.12, seg_min_lower=0.05, omega=0.15, omega_lower=2.0, + drag=0.6, drag_lower=0.6, hit_min_lower=0.045, + hair_arm_collide=True, stiff_min=2.0, limb_collide=False, + gravity_limb=None, omega_max=None, min_chain_len=0.05, + drag_limb=None, omega_max_lower=None, limb_min_len=0.12, + stiff_max=10.0, shrink_leg_col=True, omega_limb=0.5, + set_parent=None, cloth=None, leg_proxy=True, leg_proxy_max=1.0, leg_proxy_grid=0.005, + log=None): + """PMX 刚体物理 → VRMC_springBone(VRM 1.0)。返回扩展 dict 或 None。 + + 目标是「表现和原生 VRM 一致」,参数按 VRoid / VRM 官方示例模型 + (AvatarSample_B、VRM1_Constraint_Twist_Sample、Seed-san、Alicia) + 在同一套动作下的实测表现校准(见 docs/pmx-to-vrm.md)。 + + * 挂了物理刚体(mode 1/2)的骨 = 要模拟的骨;humanoid 骨和已并入付与親的 + 骨不参与。从「自己要动、父骨不动」的骨开始沿子骨走成链;分叉处子树最深的 + 一支继续,其余另起一条链。 + * **抽稀**:MMD 物理链切得很细(后发 1.2 m 分 24 节),原生 VRM 的发束是 + 3~7 节、每节 7~15 cm。离上一个关节不到 seg_min(头发等 12 cm)的骨不做 + 关节,刚性跟随上一个关节;相邻关节随后改挂成直接父子(set_parent)—— + 规范虽允许隔代,three-vrm 却按「子关节相对直接父节点的位置」取静止方向, + 隔代的链在拐弯处第一帧就会被转开。 + 裙摆(下半身)只并掉 seg_min_lower(5 cm)以内的:SpringBone 只在关节点 + 检测碰撞,节太稀大腿会从关节之间穿过去。 + * **硬度按「每帧回正角度」换算**:stiffness 的单位是每秒移动的米数,不随节长 + 缩放,同样的值在短节上力量大得多。stiffness = ω × 节长 × 60, + 头发等 ω=0.15(原生发束约 0.1~0.25 rad/帧),裙摆 ω=2.0(密集节需要更硬 + 才能撑住长裙、少穿模)。以前「按节数放大硬度」让长发的回正力是原生的 + 10~20 倍,每帧拉过头再被惯性甩回,就是肉眼看到的抖动(抖动/形变比约为 + 原生的 2 倍)。 + * 硬度下限 stiff_min=2.0:原生模型的硬度基本是绝对值 0.5~4、和节长无关; + 只按角度换算的话 3 cm 的胸部物理骨硬度只有 0.25,走路时整个翻过去。 + 上限 stiff_max=10:翅膀、长飘带的最后一节很长,按角度换算会到 50 以上。 + * dragForce 都是 0.6。重力:头发等 0(加了会把散开的发型拉垂); + 裙摆 gravity_lower=0.1,抬腿时裙片落回腿上而不是悬在侧面。 + * 裙摆类 = 挂在 hips 上的链,以及挂在躯干上、垂到胯部以下的链。挂在腿/脚上的 + (鞋带、腿环)是四肢配饰,和手臂上的一样处理。 + * 四肢配饰:不足 limb_min_len(12 cm)的不做 SpringBone(四肢动得快,弹簧追不上, + 只会在末端颤);不碰自己那条手臂/腿的碰撞体;手臂上的链完全不碰撞——T-pose 下 + 它们跟着手臂转了,动画放下手臂后静止方向指向身体,碰撞会把它们卡在另一侧来回翻。 + 手臂上的链(袖子)硬度单独按 omega_limb=0.5 换算:手臂是全身摆得最快的部位, + 按头发的 0.15 换算时长袖跑步时末端颤动是头发的 5~8 倍,0.5 时降到 1/3~1/4, + 仍有明显摆动(0.8 就几乎僵住了)。 + * center(在 convert 里设为模型根节点):人物整体移动时弹簧不被甩。 + * 碰撞体 ← 跟随骨骼的刚体(mode 0);按 PMX 碰撞组/掩码决定每条链和哪些碰撞体 + 碰撞。头发也碰手臂(和 VRoid 一致,放下手臂时不会穿过头发)。 + hitRadius ← 刚体半径,裙摆不小于 hit_min_lower(4.5 cm);静止时确实贴着 + 碰撞体的那几节缩到刚好不重叠(可低于下限,否则开始模拟就被推开, + 长裙从根部被撬开)。某节尾端在静止时就落在碰撞体里的,整条链不与它碰撞; + 例外是裙摆和大腿:PMX 的大腿刚体常比腿粗,贴腿的短裙静止时就在里面, + 这时给该链另配一个缩小到刚好让开的同位置碰撞体,而不是让腿完全拦不住裙片。 + * PMX 里链与链之间的横向关节(裙摆常见)在 VRM 里无法表达,舍弃。近似:裙摆链碰到的腿部 + 胶囊换成按裙片朝向平移过的副本(leg_proxy,见 leg_proxy_shift),腿不再把相邻两条链分到两边。 + cloth = (顶点法线, 顶点权重, xf_dir),用来算裙片朝向;不给就不做这一步。 + """ + def _log(msg, tag=None): + if log: + log(msg, tag) + + bones = model["bones"] + rbs = model.get("rigid_bodies") or [] + joints = model.get("joints") or [] + nb = len(bones) + if not rbs or not nb: + return None + human_set = set(human_b.values()) + vrm_of = {v: k for k, v in human_b.items()} + + dyn = {} # 骨 → 刚体序号 + for ri, rb in enumerate(rbs): + b = rb["bone"] + if rb["mode"] in (1, 2) and 0 <= b < nb and b not in alias \ + and b not in human_set and b not in dyn: + dyn[b] = ri + if not dyn: + return None + + children = [[] for _ in range(nb)] + for i, p in enumerate(parents): + if 0 <= p < nb: + children[p].append(i) + + def anchor(b): + """最近的 humanoid 祖先骨位名。""" + p = parents[b] + seen = set() + while p >= 0 and p not in seen: + if p in vrm_of: + return vrm_of[p] + seen.add(p) + p = parents[p] + return None + + depth_memo = {} + + def dyn_depth(b): + if b not in depth_memo: + depth_memo[b] = 1 + max([dyn_depth(c) for c in children[b] + if c in dyn] or [0]) + return depth_memo[b] + + # ---- 拆链 + hips_y = bpos[human_b["hips"]][1] if "hips" in human_b else None + roots = [b for b in range(nb) if b in dyn and parents[b] not in dyn] + pending = list(roots) + chains = [] # [(骨列表, 类别)] + used = set() + skipped_lower = 0 + while pending: + r = pending.pop(0) + if r in used: + continue + cat = anchor(r) + # 裙摆类只算挂在 hips 上的链(以及下面挂在躯干上、垂到胯部以下的)。 + # 挂在腿/脚上的是配饰(鞋带、腿环、脚踝蝴蝶结),不能按裙摆的高硬度处理—— + # 它们跟着动得最快的腿脚走,实测开拓者的鞋带跑步时末端颤动是全身最高 + lower = cat == "hips" + chain = [r] + used.add(r) + cur = r + while True: + kids = sorted([c for c in children[cur] if c in dyn and c not in used], + key=lambda c: -dyn_depth(c)) + if not kids: + break + pending.extend(kids[1:]) + cur = kids[0] + chain.append(cur) + used.add(cur) + # 挂在躯干上、但垂到胯部以下的链(侧面裙片、腰后飘带)也按裙摆处理: + # 它们和腿有碰撞关系,需要密集关节、重力和足够的碰撞半径。 + # 以前只看挂点,挂在上半身1 上的裙片被当成头发(稀、软、无重力), + # 抬腿时被大腿横推出去悬在侧面 + if not lower and cat in _TORSO and hips_y is not None \ + and min(bpos[b][1] for b in chain) < hips_y: + lower = True + if lower and not include_lower: + skipped_lower += 1 + continue + chains.append((chain, lower)) + + # ---- 关节参数 + joint_of = {} # 刚体 → 连接父刚体的 PMX 关节 + for j in joints: + a, b = j["rb_a"], j["rb_b"] + if 0 <= b < len(rbs) and 0 <= a < len(rbs): + ba, bb = rbs[a]["bone"], rbs[b]["bone"] + if 0 <= bb < nb and parents[bb] == ba: + joint_of.setdefault(b, j) + for j in joints: # 没有严格父子关系的就退而求其次 + b = j["rb_b"] + if 0 <= b < len(rbs): + joint_of.setdefault(b, j) + + def _stiff(w, length, lower=False): + s_ = max(w * length * 60.0, stiff_min) + cap = omega_max_lower if lower else omega_max + if cap is not None: + s_ = min(s_, cap * length * 60.0) + # 绝对上限:裙摆的回正角度是按 5 cm 左右的密集短节定的,遇到很长的一节 + # (翅膀、长飘带的最后一节)会算出 50 以上,一样会每帧拉过头 + return min(s_, stiff_max) + + def seg_params(seg, length, lower, arm): + """一节(seg = 这一节包含的骨,第一个是关节骨)的 SpringBone 参数。 + arm = 挂在手臂上的链(袖子、手肘吊坠),可单独设 omega/gravity/drag_limb。""" + w = omega_lower if lower else omega + if arm and omega_limb is not None: + w = omega_limb + g = gravity_lower if lower else gravity + if arm and gravity_limb is not None: + g = gravity_limb + d = drag_lower if lower else drag + if arm and drag_limb is not None: + d = drag_limb + rad = max(_rigid_shape(rbs[dyn[b]], None)[1] for b in seg) * scale + rad = min(0.05, max(hit_min_lower if lower else 0.01, rad)) + return {"hitRadius": round(rad, 5), + "stiffness": round(_stiff(w, length, lower) * stiffness_mul, 4), + "gravityPower": g, + "gravityDir": [0.0, -1.0, 0.0], + "dragForce": d} + + def tail_pos(b): + """链尾没有可用子骨时,造一个 tail 的位置(PMX 坐标)。""" + bb = bones[b] + lin = glob[b][0] if glob else _I3 + if bb["tail_kind"] == 0: + off = bb["tail"] + if sum(x * x for x in off) > 1e-8: + o = _m3vec(lin, off) + return tuple(bpos[b][k] + o[k] for k in range(3)) + elif 0 <= bb["tail"] < nb and bb["tail"] != b: + q = bpos[bb["tail"]] + if sum((q[k] - bpos[b][k]) ** 2 for k in range(3)) > 1e-8: + return q + p = parents[b] + if p >= 0: + d = [bpos[b][k] - bpos[p][k] for k in range(3)] + if sum(x * x for x in d) > 1e-8: + return tuple(bpos[b][k] + d[k] * 0.5 for k in range(3)) + return (bpos[b][0], bpos[b][1] - 0.5, bpos[b][2]) + + # ---- 碰撞体(跟随骨骼的刚体) + colliders = [] + col_meta = [] # (group, mask) + col_world = [] # (端点 a, 端点 b 或 None, 半径),VRM 坐标 + col_role = [] # 碰撞体所在骨的 humanoid 骨位(没有为空) + for rb in rbs: + b = rb["bone"] + if rb["mode"] != 0 or not (0 <= b < nb): + continue + b = alias.get(b, b) # 挂在 足D 上的刚体改挂到 足 + node = bone_node(b) + if node is None: + continue + c, r, half = _rigid_shape(rb, glob) + base = node_pos(node) + if sum(x * x for x in half) < 1e-12: + p0 = xf(c) + shape = {"sphere": {"offset": [p0[k] - base[k] for k in range(3)], + "radius": r * scale}} + col_world.append((p0, None, r * scale)) + else: + p0 = xf(tuple(c[k] - half[k] for k in range(3))) + p1 = xf(tuple(c[k] + half[k] for k in range(3))) + shape = {"capsule": {"offset": [p0[k] - base[k] for k in range(3)], + "radius": r * scale, + "tail": [p1[k] - base[k] for k in range(3)]}} + col_world.append((p0, p1, r * scale)) + colliders.append({"node": node, "shape": shape}) + col_meta.append((rb["group"], rb["mask"])) + col_role.append(vrm_of.get(b, "")) + + group_cache = {} + collider_groups = [] + + n_pmx_cols = len(colliders) + + def mask_ids(rb): + """按 PMX 碰撞组/掩码,该动态刚体能碰到的碰撞体(双方掩码都允许)。""" + g, m = rb["group"], rb["mask"] + return [i for i, (cg, cm) in enumerate(col_meta[:n_pmx_cols]) + if (m >> cg) & 1 and (cm >> g) & 1] + + shrunk_cache = {} + + def shrunk_collider(ci, r): + """碰撞体 ci 的缩小半径副本(同节点、同位置),相近半径的共用一个。 + 半径向下取到 5 mm 的整数倍:向上取整会吃掉让开静止裙片的余量。""" + key = (ci, math.floor(r * 200.0) / 200.0) + if key not in shrunk_cache: + shape = {k: dict(v) for k, v in colliders[ci]["shape"].items()} + for v in shape.values(): + v["radius"] = key[1] + colliders.append({"node": colliders[ci]["node"], "shape": shape}) + col_meta.append(col_meta[ci]) + col_world.append(col_world[ci][:2] + (key[1],)) + col_role.append(col_role[ci]) + shrunk_cache[key] = len(colliders) - 1 + return shrunk_cache[key] + + moved_cache = {} + + def moved_collider(ci, t): + """碰撞体 ci 平移 t(VRM 坐标)的副本,挂在同一节点上;平移量按 leg_proxy_grid 取整共用。""" + t = tuple(round(x / leg_proxy_grid) * leg_proxy_grid for x in t) + key = (ci, t) + if key not in moved_cache: + shape = {k: dict(v) for k, v in colliders[ci]["shape"].items()} + for v in shape.values(): + for f in ("offset", "tail"): + if f in v: + v[f] = [v[f][k] + t[k] for k in range(3)] + colliders.append({"node": colliders[ci]["node"], "shape": shape}) + col_meta.append(col_meta[ci]) + a, b, r = col_world[ci] + col_world.append((tuple(a[k] + t[k] for k in range(3)), + None if b is None else tuple(b[k] + t[k] for k in range(3)), r)) + col_role.append(col_role[ci]) + moved_cache[key] = len(colliders) - 1 + return moved_cache[key] + + # ---- 裙片朝向:挂在链上的顶点法线的主方向(单双面都行:n 和 -n 贡献相同) + cov = {} # 骨 → Σ w·n·nᵀ(VRM 坐标,6 个分量) + if cloth and leg_proxy: + vnrm, vweights, xf_dir = cloth + want = {b for chain, lower in chains if lower for b in chain} + for n, wl in zip(vnrm, vweights): + for b, w in wl: + if b in want and w > 0.3: + x, y, z = xf_dir(n) + c = cov.setdefault(b, [0.0] * 6) + for k, v in enumerate((x * x, y * y, z * z, x * y, x * z, y * z)): + c[k] += w * v + + def cloth_normal(chain, guess): + """链上裙片的水平法线(单位向量,方向未定);顶点太少或裙片接近水平时 None。""" + c = [0.0] * 6 + for b in chain: + for k, v in enumerate(cov.get(b, ())): + c[k] += v + if c[0] + c[1] + c[2] < 1.0: + return None + m = (c[0], c[3], c[4], c[3], c[1], c[5], c[4], c[5], c[2]) + v = guess + for _ in range(30): # 幂迭代求主特征向量 + v = _m3vec(m, v) + s = math.sqrt(sum(x * x for x in v)) or 1.0 + v = tuple(x / s for x in v) + h = math.hypot(v[0], v[2]) + if h < 0.6: + return None + return (v[0] / h, 0.0, v[2] / h) + + def leg_proxy_shift(ci, pts, normal): + """裙摆链 × 腿部胶囊:把腿平移到「静止时从裙片法线方向正对这条链」的位置。 + + SpringBone 把关节沿「腿轴 → 关节」的方向推出去。腿正好落在两条相邻链之间时 + (大腿后摆碰后裙片),两条链被推向相反的两侧,裙子从中间劈开——MMD 里链间的 + 横向关节会把它们拉在一起,整片往后推。这里给每条链单独一份平移过的腿: + 静止时离链的距离不变,但接触方向变成裙片法线,被推时整片沿法线方向走。 + 平移量不超过腿半径 × leg_proxy_max,不然真正的腿会从让出来的那一侧穿过裙子。""" + a, b, r = col_world[ci] + best = None + for q in pts: + ab = [b[k] - a[k] for k in range(3)] + l2 = sum(x * x for x in ab) or 1e-12 + t = min(1.0, max(0.0, sum((q[k] - a[k]) * ab[k] for k in range(3)) / l2)) + l_ = [a[k] + ab[k] * t for k in range(3)] + d = math.dist(q, l_) + if best is None or d < best[0]: + best = (d, q, l_) + _, q, l_ = best + vh = (q[0] - l_[0], 0.0, q[2] - l_[2]) + m = math.hypot(vh[0], vh[2]) + if m < 1e-6: + return None + n = normal if normal[0] * vh[0] + normal[2] * vh[2] >= 0 else tuple(-x for x in normal) + t = [vh[k] - n[k] * m for k in range(3)] + tl = math.hypot(t[0], t[2]) + cap = r * leg_proxy_max + if tl > cap: + t = [x * cap / tl for x in t] + return t if min(tl, cap) >= 0.005 else None + + def clearance(pt, ci): + """点到碰撞体表面的距离(负数 = 在碰撞体内部)。""" + a, b, r = col_world[ci] + if b is None: + q = a + else: + ab = [b[k] - a[k] for k in range(3)] + l2 = sum(x * x for x in ab) or 1e-12 + t = sum((pt[k] - a[k]) * ab[k] for k in range(3)) / l2 + t = min(1.0, max(0.0, t)) + q = [a[k] + ab[k] * t for k in range(3)] + return math.sqrt(sum((pt[k] - q[k]) ** 2 for k in range(3))) - r + + def groups_for(ids): + """碰撞体集合 → colliderGroups 索引列表(相同集合共用一个组)。""" + ids = tuple(sorted(ids)) + if not ids: + return [] + if ids not in group_cache: + group_cache[ids] = len(collider_groups) + collider_groups.append({"name": "pmx_collision_%d" % len(collider_groups), + "colliders": list(ids)}) + return [group_cache[ids]] + + # ---- 写 springs + springs = [] + n_virtual = 0 + n_dropped = [0] + n_shrunk = [0] + n_tiny = [0] + n_proxy = [0] + n_joints_mmd = n_joints_vrm = n_lower = 0 + for chain, lower in chains: + last = chain[-1] + real = [c for c in children[last] + if c not in dyn and c not in human_set and c not in alias] + tpos = node_pos(bone_node(real[0])) if real else xf(tail_pos(last)) + pos = {b: xf(bpos[b]) for b in chain} + anc = anchor(chain[0]) or "" + limb = _limb_of(anc) + # 过短的链(3 cm 的胸部物理骨之类)只会高频颤动、看不出有意义的摆动,不做 SpringBone。 + # 挂在手臂/腿上的短配饰(手肘吊坠、鞋带、脚踝蝴蝶结)门槛更高:四肢动得快, + # 弹簧追不上就在末端来回颤(实测是全身颤动最大的部位),不如跟着骨骼刚性移动 + length = math.dist(pos[last], tpos) + sum( + math.dist(pos[a], pos[b]) for a, b in zip(chain, chain[1:])) + if length < (max(min_chain_len, limb_min_len) if limb else min_chain_len): + n_tiny[0] += 1 + continue + if real: + tnode = bone_node(real[0]) + else: + tnode = add_node((bones[last]["name"] or "bone") + "_tail", bone_node(last), tpos) + n_virtual += 1 + # 抽稀:离上一个关节不到 seg_min 的骨不做关节(刚性跟随上一个关节) + smin = seg_min_lower if lower else seg_min + # 自动补出来的兽耳链每节只有 2~3 cm,按头发的 12 cm 抽稀会只剩「根骨 + 末端」, + # 整只耳朵变成一块刚性板。按链长自适应把各节都留住;只作用于自动生成的刚体, + # 不动 MMD 原生物理和其它模型的头发。 + nm0 = (bones[chain[0]]["name"] or "").lower() + if len(chain) >= 3 and rbs[dyn[chain[0]]].get("name", "").startswith("auto_") \ + and ("ear" in nm0 or "耳" in nm0 or "mimi" in nm0): + span = sum(math.dist(pos[a], pos[b]) for a, b in zip(chain, chain[1:])) + if span > 0: + smin = min(smin, span / len(chain) * 0.9) + kept = [chain[0]] + for b in chain[1:]: + if math.dist(pos[b], pos[kept[-1]]) >= smin: + kept.append(b) + if len(kept) > 1 and math.dist(pos[kept[-1]], tpos) < smin * 0.5: + kept.pop() # 最后一节太短:并进上一节 + n_joints_mmd += len(chain) + n_joints_vrm += len(kept) + idx = [chain.index(b) for b in kept] + [len(chain)] + arm = bool(limb) and limb[1] == "arm" + pts = [pos[b] for b in kept] + [tpos] + js = [] + for i, b in enumerate(kept): + jt = seg_params(chain[idx[i]:idx[i + 1]], math.dist(pts[i], pts[i + 1]), lower, arm) + jt["node"] = bone_node(b) + js.append(jt) + tj = dict(js[-1]) + tj["node"] = tnode + js.append(tj) + # 相邻关节改成直接父子(世界位置不变,被跳过的中间骨仍挂在原处、刚性跟随)。 + # 规范允许关节隔代,但 three-vrm 取「子关节相对它直接父节点的位置」当静止方向, + # 隔代时链在拐弯处(前裙片转到侧裙片)第一帧就被转开,实测末端偏 24 cm + if set_parent is not None: + for a_, b_ in zip(js, js[1:]): + set_parent(b_["node"], a_["node"]) + # 碰撞体:PMX 掩码允许的。挂在四肢上的链不碰同一条手臂/腿的碰撞体(本来就跟着它动, + # 碰撞只会在手臂快速转动时——比如动画第一帧从 T-pose 放下——把链甩到碰撞体另一侧 + # 卡住,表现为配饰整个翻过去、一直抖);手臂上的链默认完全不碰撞(limb_collide)。 + on_head = anc in ("head", "neck", "jaw", "leftEye", "rightEye") + normal = None + if lower and not limb and cov: + mid = pts[len(pts) // 2] + hp = xf(bpos[human_b["hips"]]) if "hips" in human_b else (0.0, 0.0, 0.0) + normal = cloth_normal(chain, (mid[0] - hp[0] + 1e-3, 0.0, mid[2] - hp[2])) + ids = [] + for ci in ([] if arm and not limb_collide else mask_ids(rbs[dyn[chain[0]]])): + role = col_role[ci] + if limb and _limb_of(role) == limb: + continue + if on_head and not hair_arm_collide and (_limb_of(role) or ("", ""))[1] == "arm": + continue + if normal and ("UpperLeg" in role or "LowerLeg" in role) and col_world[ci][1] is not None: + t = leg_proxy_shift(ci, pts[1:], normal) + if t: + ci = moved_collider(ci, t) + n_proxy[0] += 1 + # 只看各节尾端(pts[1:]):SpringBone 用「这一节的 hitRadius、在尾端位置」检测, + # 链根钉在父骨上,埋在碰撞体里也不会被推 + minc = min(clearance(pt, ci) for pt in pts[1:]) + if minc > 0.0: + ids.append(ci) + continue + # 贴腿的短裙:PMX 的大腿刚体常比腿粗,静止时裙片就在里面。整个舍弃的话 + # 这条腿完全拦不住裙片(实测穗穗走路时 4.2% 的裙摆关节进了腿里,缩小后 1.7%), + # 所以给这条链另配一个缩小到刚好让开静止裙片的同位置碰撞体 + r0 = col_world[ci][2] + r1 = r0 + minc - 0.005 + if shrink_leg_col and lower and "UpperLeg" in role and r1 >= max(0.02, r0 * 0.4): + ids.append(shrunk_collider(ci, r1)) + else: + n_dropped[0] += 1 + # 只缩静止时确实贴着碰撞体的那几节(可以低于下限);其余节保持足够的 + # 碰撞半径。不能用「一律不低于下限」——贴着胯部的那几节会在开始模拟时 + # 被推开,长裙从根部被撬开,末端偏出 30 cm 以上 + for i, jt in enumerate(js[:-1]): + for ci in ids: + c = clearance(pts[i + 1], ci) + if c < jt["hitRadius"]: + jt["hitRadius"] = round(max(0.002, c * 0.9), 5) + n_shrunk[0] += 1 + js[-1]["hitRadius"] = js[-2]["hitRadius"] + n_lower += lower + sp = {"name": bones[chain[0]]["name"] or ("spring%d" % len(springs)), + "joints": js} + cg = groups_for(ids) + if cg: + sp["colliderGroups"] = cg + springs.append(sp) + + if not springs: + if skipped_lower: + _log("SpringBone:按设置跳过 %d 条下半身物理链,没有可输出的链" + % skipped_lower) + return None + # 平移 / 缩小出来的碰撞体里,有些随后又被它自己的缩小副本取代、没有组在用:删掉并重排序号 + used = {ci for g in collider_groups for ci in g["colliders"]} + keep = [ci for ci in range(len(colliders)) if ci < n_pmx_cols or ci in used] + if len(keep) < len(colliders): + remap = {ci: k for k, ci in enumerate(keep)} + colliders = [colliders[ci] for ci in keep] + for g in collider_groups: + g["colliders"] = [remap[ci] for ci in g["colliders"]] + _log("SpringBone:%d 条链(裙摆类 %d、头发等 %d)· 碰撞体 %d · 碰撞组 %d" + % (len(springs), n_lower, len(springs) - n_lower, len(colliders), + len(collider_groups))) + if skipped_lower: + _log("SpringBone:按设置跳过 %d 条下半身物理链(裙摆等)" % skipped_lower) + if n_tiny[0]: + _log("SpringBone:%d 条短链(不足 %.0f cm,四肢上不足 %.0f cm)不转换,以免末端高频抖动" + % (n_tiny[0], min_chain_len * 100, limb_min_len * 100)) + _log("SpringBone:MMD 物理骨 %d 根 → SpringBone 关节 %d 个(头发等每节至少 %.0f cm、" + "裙摆至少 %.0f cm,中间的骨骼刚性跟随)" + % (n_joints_mmd, n_joints_vrm, seg_min * 100, seg_min_lower * 100)) + if n_virtual: + _log("SpringBone:%d 条链的末端没有子骨骼,已补充末端节点" % n_virtual) + fixes = [] + if n_dropped[0]: + fixes.append("取消 %d 处链与碰撞体的碰撞" % n_dropped[0]) + if n_shrunk[0]: + fixes.append("缩小 %d 个节点的碰撞半径" % n_shrunk[0]) + if fixes: + _log("SpringBone:静止姿势下与碰撞体重叠,已" + "、".join(fixes)) + cross = 0 + for j in joints: + a, b = j["rb_a"], j["rb_b"] + if 0 <= a < len(rbs) and 0 <= b < len(rbs): + ba, bb = rbs[a]["bone"], rbs[b]["bone"] + if ba in dyn and bb in dyn and 0 <= ba < nb and 0 <= bb < nb \ + and parents[bb] != ba and parents[ba] != bb: + cross += 1 + if cross: + _log("SpringBone:%d 个链间横向关节(裙摆等)无法表达,已舍弃%s" + % (cross, ";已按裙片朝向修正 %d 处裙摆与腿的碰撞方向,减少裙片被腿分开" + % n_proxy[0] if n_proxy[0] else ""), "warn") + elif n_proxy[0]: + _log("SpringBone:已按裙片朝向修正 %d 处裙摆与腿的碰撞方向" % n_proxy[0]) + ext = {"specVersion": "1.0", "springs": springs} + if colliders: + ext["colliders"] = colliders + if collider_groups: + ext["colliderGroups"] = collider_groups + return ext diff --git a/convert/vrmconv/springbone_v0.py b/convert/vrmconv/springbone_v0.py new file mode 100644 index 0000000..362f42e --- /dev/null +++ b/convert/vrmconv/springbone_v0.py @@ -0,0 +1,242 @@ +# -*- coding: utf-8 -*- +"""VRM 0.x 的 SpringBone(secondaryAnimation):由 springbone._build_springs 算好的 1.0 结构换算。 + +参数换算、碰撞关系、裙摆处理只在 1.0 那边维护一份,这里只处理两种结构的差别: + + * 0.x 的 boneGroups.bones 只列根骨,**整棵子树都参与模拟**,每节的方向取它的第一个子节点 + (three-vrm 的 _v0Import、UniVRM、Blender 官方插件都是这样读的)。1.0 里有些骨只是跟着 + 上一个关节刚性转动(抽稀掉的短节、链末端的配饰),照搬过去会全变成摆动骨。 + fold():把这些骨的权重并到最近的摆动关节上、子节点改挂过去,再由 _prune_nodes 删掉—— + 它们在 1.0 里本来就随那个关节刚性转动,效果完全一样。尾节点留下当不带权重的叶子。 + order_children():每个关节的下一节排在第一个子节点。 + * 同一节点落在两个组的子树里会被模拟两次:从别的链上分叉出来的链并入上层链的组; + 组内的碰撞体按关节数多数决定。 + * 参数是每组一套:硬度 / 重力 / 阻尼取组内中位数(同一条链内本来就几乎一样);碰撞半径也取 + 中位数,静止时会和碰撞体重叠的,给这一组配一个缩小的碰撞体副本(缩不下去才取消这处碰撞)。 + 取最小值的话,1.0 里为贴着腿、贴着衣服单独缩小过的那几节会让整条链都几乎不碰撞, + 反过来不缩小碰撞体的话飘带一开始模拟就被推开 3~4 cm。 + * 碰撞体只有球:胶囊沿轴线每隔一个半径放一个球(两球之间最窄处是半径的 0.87 倍; + 更密的球实测效果差不多,球数却翻倍)。offset 是 Unity 坐标,Z 和 glTF 相反。 + * 参数相同的链也不合并成一组:调整页按组调参数、开关,一组一条链才对得上。 + * 硬度的键名是规范里拼错的 stiffiness。 +""" +import math +import statistics + + +def _joint_sets(spring_ext): + """→ (模拟的关节节点, 尾节点, 关节 → 链上的下一节)。""" + sim, tails, nxt = set(), set(), {} + for sp in spring_ext["springs"]: + js = [j["node"] for j in sp["joints"]] + sim.update(js[:-1]) + tails.add(js[-1]) + for a, b in zip(js, js[1:]): + nxt[a] = b + return sim, tails, nxt + + +def _sim_ancestor(parent_of, sim, x): + p = parent_of(x) + seen = set() + while p is not None and p not in sim and p not in seen: + seen.add(p) + p = parent_of(p) + return p if p in sim else None + + +def fold(tree, bones, vweights, spring_ext, keep_nodes, log=None): + """组根子树里不是摆动关节的节点:权重并到最近的摆动关节、子节点改挂过去。返回新的 vweights。 + + 在 _prune_nodes 之前调用(节点号是 tree 的)。keep_nodes:不动的节点(humanoid 骨)。 + """ + sim, tails, _ = _joint_sets(spring_ext) + par = tree.parent + kids = [[] for _ in par] + for i, p in enumerate(par): + if p is not None: + kids[p].append(i) + up = lambda x: par[x] # noqa: E731 + roots = [sp["joints"][0]["node"] for sp in spring_ext["springs"]] + tops = [r for r in roots if _sim_ancestor(up, sim, r) is None] + sub, stack = set(), list(tops) + while stack: + x = stack.pop() + if x not in sub: + sub.add(x) + stack.extend(kids[x]) + target = {} # 节点 → 并到哪个关节 + for x in sub - sim - set(keep_nodes): + a = _sim_ancestor(up, sim, x) + if a is not None: + target[x] = a + remove = {x for x in target if x not in tails} + + bone_of = {} + for b in range(len(bones)): + n = tree.bone_node(b) + if n is not None: + bone_of.setdefault(n, b) + bmap = {} + for b in range(len(bones)): + n = tree.bone_node(b) + if n in target and target[n] in bone_of: + bmap[b] = bone_of[target[n]] + out, n_verts = [], 0 + for wl in vweights: + if not any(b in bmap and w > 0 for b, w in wl): + out.append(wl) + continue + n_verts += 1 + acc = {} + for b, w in wl: + b = bmap.get(b, b) + acc[b] = acc.get(b, 0.0) + w + out.append(sorted(acc.items(), key=lambda t: -t[1])) + + for x in range(len(par)): + if par[x] in remove and x not in remove: + tree.set_parent(x, target[par[x]]) + for c in spring_ext.get("colliders", []): + if c["node"] in remove: + a = target[c["node"]] + d = [tree.wpos[c["node"]][k] - tree.wpos[a][k] for k in range(3)] + for v in c["shape"].values(): + for f in ("offset", "tail"): + if f in v: + v[f] = [v[f][k] + d[k] for k in range(3)] + c["node"] = a + if log and (remove or bmap): + log("SpringBone(0.x):%d 根随关节刚性转动的骨(中间节、链末端的配饰)权重并到关节上(%d 个顶点)," + "0.x 会让组里所有子骨都摆动" % (len(bmap), n_verts)) + return out + + +def order_children(nodes, spring_ext): + """每个关节的下一节放到 children[0]:0.x 按第一个子节点定这一节的方向。""" + _, _, nxt = _joint_sets(spring_ext) + for a, b in nxt.items(): + ch = nodes[a].get("children") or [] + if b in ch and ch[0] != b: + ch.remove(b) + ch.insert(0, b) + + +def _world(nodes): + parent = {} + for i, nd in enumerate(nodes): + for c in nd.get("children", ()): + parent[c] = i + memo = {} + + def pos(i): + if i not in memo: + t = nodes[i].get("translation") or [0.0, 0.0, 0.0] + p = parent.get(i) + memo[i] = tuple(t) if p is None else tuple(pos(p)[k] + t[k] for k in range(3)) + return memo[i] + return pos, parent + + +def spheres(shape): + """1.0 的碰撞形状 → [(offset, radius)](glTF 局部坐标)。胶囊沿轴线每隔一个半径放一个球。""" + if "sphere" in shape: + s = shape["sphere"] + return [(tuple(s["offset"]), s["radius"])] + c = shape["capsule"] + a, b, r = c["offset"], c["tail"], c["radius"] + n = max(2, int(math.ceil(math.dist(a, b) / max(r, 1e-4))) + 1) + return [(tuple(a[k] + (b[k] - a[k]) * i / (n - 1) for k in range(3)), r) for i in range(n)] + + +def _v3(v): + """glTF → 0.x 的 {x, y, z}(Unity 坐标:Z 取反)。""" + return {"x": round(v[0], 6), "y": round(v[1], 6), "z": round(-v[2], 6) or 0.0} + + +def to_secondary(spring_ext, nodes, center=None, log=None): + """1.0 的 VRMC_springBone(节点号已是最终的)→ 0.x 的 secondaryAnimation。""" + pos, parent = _world(nodes) + sim, _, _ = _joint_sets(spring_ext) + cols = spring_ext.get("colliders", []) + cgs = spring_ext.get("colliderGroups", []) + sph = [spheres(c["shape"]) for c in cols] + + groups = {} # 顶层根 → [spring] + for sp in spring_ext["springs"]: + t = sp["joints"][0]["node"] + while True: + a = _sim_ancestor(parent.get, sim, t) + if a is None: + break + t = a + groups.setdefault(t, []).append(sp) + + v0_groups, v0_key = [], {} + + def collider_group(ci, radius=None): + key = (ci, None if radius is None else round(radius, 5)) + if key not in v0_key: + v0_key[key] = len(v0_groups) + v0_groups.append({"node": cols[ci]["node"], "colliders": [ + {"offset": _v3(o), "radius": round(r if radius is None else radius, 5)} + for o, r in sph[ci]]}) + return v0_key[key] + + def clearance(p, ci): + base = pos(cols[ci]["node"]) + return min(math.dist(p, [base[k] + o[k] for k in range(3)]) - r for o, r in sph[ci]) + + bone_groups = [] + n_shrunk = n_dropped = 0 + for top, sps in groups.items(): + js = [j for sp in sps for j in sp["joints"][:-1]] + tips = [pos(j["node"]) for sp in sps for j in sp["joints"][1:]] + + def med(k, d): + return statistics.median(j.get(k, d) for j in js) + hit = med("hitRadius", 0.0) + # 分叉链并进来以后整组只能共用一套碰撞体:按关节数多数决定(组内至少一半的关节在 1.0 里 + # 碰它才保留)。取并集的话,挂在长发上的一个小坠子(MMD 里和全身都碰)会让整条长发也去碰 + # 腿和手臂,实测摆幅只剩一半 + votes = {} + for sp in sps: + for ci in {ci for g in sp.get("colliderGroups", ()) for ci in cgs[g]["colliders"]}: + votes[ci] = votes.get(ci, 0) + len(sp["joints"]) - 1 + ids = [] + for ci in sorted(votes): + if votes[ci] * 2 < len(js): + continue + gap = min(clearance(p, ci) for p in tips) + if gap >= hit: + ids.append(collider_group(ci)) + continue + r0 = sph[ci][0][1] + r1 = r0 - (hit - gap) - 0.002 + if r1 >= max(0.01, r0 * 0.4): + ids.append(collider_group(ci, r1)) + n_shrunk += 1 + else: + n_dropped += 1 + gd = js[0].get("gravityDir", [0.0, -1.0, 0.0]) + bone_groups.append({ + "comment": sps[0].get("name") or "spring%d" % len(bone_groups), + "stiffiness": round(med("stiffness", 1.0), 4), + "gravityPower": round(med("gravityPower", 0.0), 4), + "gravityDir": _v3(gd), + "dragForce": round(med("dragForce", 0.5), 4), + "center": -1 if center is None else center, + "hitRadius": round(hit, 5), + "bones": [top], + "colliderGroups": sorted(set(ids)), + }) + if log: + n_nested = len(spring_ext["springs"]) - len(groups) + log("SpringBone(0.x):%d 条链 → %d 个摆动组%s · 碰撞组 %d(胶囊换成 %d 个球)" + % (len(spring_ext["springs"]), len(bone_groups), + "(%d 条分叉链并入上层链的组)" % n_nested if n_nested else "", + len(v0_groups), sum(len(g["colliders"]) for g in v0_groups))) + if n_shrunk or n_dropped: + log("SpringBone(0.x):每组只有一个碰撞半径,静止时会重叠的碰撞体缩小 %d 处、取消 %d 处" + % (n_shrunk, n_dropped)) + return {"boneGroups": bone_groups, "colliderGroups": v0_groups} diff --git a/convert/vrmconv/textures.py b/convert/vrmconv/textures.py new file mode 100644 index 0000000..1550c46 --- /dev/null +++ b/convert/vrmconv/textures.py @@ -0,0 +1,94 @@ +# -*- coding: utf-8 -*- +"""贴图瘦身:限制最大边长、不透明贴图改存 JPEG。 + +HoYo 系 PMX 的贴图常是 2K~4K 的 PNG,原样塞进 VRM 文件动辄上百 MB,游戏导入和加载都慢。 +缩放和 JPEG 编码要用 Pillow(可选依赖);没装 Pillow 时原样返回,转换照常进行。 + +只有完全不透明的贴图才转 JPEG:带透明通道的(头发高光、睫毛、镂空)JPEG 存不了 alpha。 +""" +import io + +try: + from PIL import Image +except ImportError: # 纯标准库环境:不瘦身 + Image = None + +JPEG_QUALITY = 90 + + +def available(): + return Image is not None + + +class Optimizer: + """max_size:最大边长(0 = 不缩放);jpeg:不透明贴图改存 JPEG。统计在 before / after / changed。""" + + def __init__(self, max_size=0, jpeg=False): + self.max_size = int(max_size or 0) + self.jpeg = bool(jpeg) + self.before = self.after = self.changed = 0 + + @property + def active(self): + return Image is not None and (self.max_size > 0 or self.jpeg) + + def __call__(self, data, mime): + """→ (data, mime)。处理失败或没变小时返回原数据。""" + return self.account(data, self.process(data, mime)) + + def process(self, data, mime): + """只做处理、不计数(几张贴图可以在不同线程里同时处理),计数交给 account。""" + if self.active: + try: + return self._process(data, mime) + except Exception: # noqa: BLE001 坏图 / 不支持的格式:原样用 + pass + return data, mime + + def account(self, data, out): + """把一张贴图 data → out(process 的结果)记进统计,返回 out。""" + self.before += len(data) + self.after += len(out[0]) + if out[0] is not data: + self.changed += 1 + return out + + def _process(self, data, mime): + im = Image.open(io.BytesIO(data)) + im.load() + w, h = im.size + resized = False + if self.max_size and max(w, h) > self.max_size: + k = self.max_size / float(max(w, h)) + if im.mode not in ("RGB", "RGBA", "L", "LA"): + im = im.convert("RGBA") + im = im.resize((max(1, round(w * k)), max(1, round(h * k))), Image.LANCZOS) + resized = True + opaque = True + if im.mode in ("RGBA", "LA", "PA") or (im.mode == "P" and "transparency" in im.info): + a = im.convert("RGBA").getchannel("A") + opaque = a.getextrema()[0] >= 255 + if self.jpeg and opaque: + buf = io.BytesIO() + # 4:4:4 不做色度抽样:二次元贴图的细线和色块边缘抽样后会发糊、渗色 + im.convert("RGB").save(buf, "JPEG", quality=JPEG_QUALITY, subsampling=0, optimize=True) + if resized or buf.tell() < len(data): + return buf.getvalue(), "image/jpeg" + if not resized: + return data, mime + buf = io.BytesIO() + if mime == "image/jpeg" and opaque: + im.convert("RGB").save(buf, "JPEG", quality=JPEG_QUALITY, subsampling=0, optimize=True) + return buf.getvalue(), "image/jpeg" + if opaque and im.mode == "RGBA": + im = im.convert("RGB") + im.save(buf, "PNG", optimize=True) + return buf.getvalue(), "image/png" + + def summary(self): + if not self.changed: + return None + return "贴图:%d 张瘦身(%s%s)%.1f MB → %.1f MB" % ( + self.changed, ("最大边长 %d" % self.max_size) if self.max_size else "", + ("、" if self.max_size and self.jpeg else "") + ("不透明转 JPEG" if self.jpeg else ""), + self.before / 1048576.0, self.after / 1048576.0) diff --git a/convert/vrmconv/vrm_ext.py b/convert/vrmconv/vrm_ext.py new file mode 100644 index 0000000..d9b61c9 --- /dev/null +++ b/convert/vrmconv/vrm_ext.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +"""VRM 扩展本体:VRM 1.0 的 VRMC_vrm、VRM 0.x 的 VRM(meta / humanoid / firstPerson / lookAt / 表情)。""" + + +def _look_deg(look): + """视线最大转角(morphbake.eye_look_range 的结果;没有时左右上下都 10°)。""" + return look or {"lookLeft": 10.0, "lookRight": 10.0, "lookDown": 10.0, "lookUp": 10.0} + + +def _degmap(xr, yr): + return {"curve": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0], + "xRange": xr, "yRange": yr} + + +def _pick(meta, key, allowed, default): + v = meta.get(key) + return v if v in allowed else default + + +def build_vrm1(meta, title, human, mesh_nodes, expr, look=None): + """VRMC_vrm。meta:用户给的作者 / 许可等;expr:expressions.build_expressions 的结果;mesh_nodes:网格节点。 + + 默认值和以前一致:谁都可以「扮演」(avatarPermission=everyone,不然有的应用拒绝加载), + 其余取保守值(仅个人非商用、禁止再分发和修改、要求署名)——转换的大多是别人的模型, + 放宽要由用户在界面里明确选。 + """ + author = meta.get("author") or "" + vrm_ext = { + "specVersion": "1.0", + "humanoid": {"humanBones": {k: {"node": v} + for k, v in human.items()}}, + "meta": { + "name": title, + "version": meta.get("version") or "1", + "authors": [author] if author else ["unknown"], + "copyrightInformation": meta.get("copyright") or "", + "contactInformation": meta.get("contact") or "", + "thirdPartyLicenses": "", + # thumbnailImage 规范要求是图片索引(整数);没有缩略图就不写, + # 写 null 过不了 VRM 1.0 schema 校验。缩略图由 vrm_edit 写入。 + "licenseUrl": meta.get("license_url") or "https://vrm.dev/licenses/1.0/", + "avatarPermission": _pick(meta, "avatar_permission", + ("onlyAuthor", "onlySeparatelyLicensedPerson", "everyone"), + "everyone"), + "allowExcessivelyViolentUsage": False, + "allowExcessivelySexualUsage": False, + "commercialUsage": _pick(meta, "commercial_usage", + ("personalNonProfit", "personalProfit", "corporation"), + "personalNonProfit"), + "allowPoliticalOrReligiousUsage": False, + "allowAntisocialOrHateUsage": False, + "creditNotation": _pick(meta, "credit_notation", ("required", "unnecessary"), "required"), + "allowRedistribution": bool(meta.get("allow_redistribution", False)), + "modification": _pick(meta, "modification", + ("prohibited", "allowModification", "allowModificationRedistribution"), + "prohibited"), + }, + "firstPerson": {"meshAnnotations": [{"node": n, "type": "auto"} for n in mesh_nodes]}, + } + if expr["preset"] or expr["custom"]: + vrm_ext["expressions"] = {} + if expr["preset"]: + vrm_ext["expressions"]["preset"] = expr["preset"] + if expr["custom"]: + vrm_ext["expressions"]["custom"] = expr["custom"] + if "leftEye" in human or "rightEye" in human: + d = _look_deg(look) + vrm_ext["lookAt"] = { + "type": "bone", + "offsetFromHeadBone": [0.0, 0.06, 0.0], + "rangeMapHorizontalInner": {"inputMaxValue": 90.0, "outputScale": d["lookLeft"]}, + "rangeMapHorizontalOuter": {"inputMaxValue": 90.0, "outputScale": d["lookLeft"]}, + "rangeMapVerticalDown": {"inputMaxValue": 90.0, "outputScale": d["lookDown"]}, + "rangeMapVerticalUp": {"inputMaxValue": 90.0, "outputScale": d["lookUp"]}, + } + return vrm_ext + + +def build_vrm0(meta, title, human, expr, material_props, look=None, n_meshes=1, secondary=None): + """VRM 0.x 的 VRM 扩展。material_props:materials.MaterialBuilder.props_0x; + secondary:springbone_v0.to_secondary 的结果(没有物理时 None)。""" + return { + "exporterVersion": "VRMify Enhanced", + "specVersion": "0.0", + "meta": { + "title": title, + "version": meta.get("version") or "1", + "author": meta.get("author") or "", + "contactInformation": meta.get("contact") or "", + "reference": "", + "allowedUserName": {"everyone": "Everyone", + "onlySeparatelyLicensedPerson": "ExplicitlyLicensedPerson", + "onlyAuthor": "OnlyAuthor"}.get( + meta.get("avatar_permission"), "Everyone"), + "violentUssageName": "Disallow", + "sexualUssageName": "Disallow", + "commercialUssageName": ("Allow" if meta.get("commercial_usage") in + ("personalProfit", "corporation") else "Disallow"), + "otherPermissionUrl": "", + # 0.x 只有 licenseName 这一项能表达再分发:没给许可链接时按「是否允许再分发」选, + # 给了链接就是 Other + 链接(作者 / 改编 / 署名之类的条件写在链接的文档里) + "licenseName": ("Other" if meta.get("license_url") or meta.get("allow_redistribution") + else "Redistribution_Prohibited"), + "otherLicenseUrl": meta.get("license_url") or "", + }, + "humanoid": { + "humanBones": [{"bone": k, "node": v, "useDefaultValues": True} + for k, v in human.items()], + "armStretch": 0.05, "legStretch": 0.05, + "upperArmTwist": 0.5, "lowerArmTwist": 0.5, + "upperLegTwist": 0.5, "lowerLegTwist": 0.5, + "feetSpacing": 0.0, "hasTranslationDoF": False, + }, + "firstPerson": { + "firstPersonBone": human.get("head", 0), + "firstPersonBoneOffset": {"x": 0.0, "y": 0.06, "z": 0.0}, + "meshAnnotations": [{"firstPersonFlag": "Auto", "mesh": k} for k in range(n_meshes)], + "lookAtTypeName": ("Bone" if ("leftEye" in human or + "rightEye" in human) + else "BlendShape"), + "lookAtHorizontalInner": _degmap(90, _look_deg(look)["lookLeft"]), + "lookAtHorizontalOuter": _degmap(90, _look_deg(look)["lookLeft"]), + "lookAtVerticalDown": _degmap(90, _look_deg(look)["lookDown"]), + "lookAtVerticalUp": _degmap(90, _look_deg(look)["lookUp"]), + }, + "blendShapeMaster": {"blendShapeGroups": expr["blend_groups"]}, + "secondaryAnimation": secondary or {"boneGroups": [], "colliderGroups": []}, + "materialProperties": material_props, + } diff --git a/convert/xps2pmx.py b/convert/xps2pmx.py new file mode 100644 index 0000000..58e470d --- /dev/null +++ b/convert/xps2pmx.py @@ -0,0 +1,759 @@ +# -*- coding: utf-8 -*- +"""XPS / XNALara → MMD PMX,纯 Python 标准库。 + +和项目里其它转换器保持同一套口径(换轴 → 归一到 20 单位 → 居中 → 骨骼转 +MMD 标准日文名 → 材质按名字找贴图),差别只在本格式的坐标系: + +换轴 +---- +实测样本(轩辕剑柒 chu hong): + `head eyeball left` 在 +X、`head eyeball right` 在 -X → XPS 的 +X = **左** + `head nose tip` z=1.030 > 头根 z=0.925, + `leg left toes` z=0.974 > 脚踝 z=0.879 → XPS 的 +Z = **正面** + `root ground` 在 y=0、头顶 y≈1.71 → XPS 的 +Y = **上** +也就是「左手 +X、正面 +Z、上 +Y」的右手系。 + +MMD/PMX 的约定是「左手 +X、正面 -Z、上 +Y」(见 psk2pmx.py 里同一段推导)。 +两边只差**一个 Z 的符号**,所以: + + (x, y, z)_xps → (x, y, -z)_pmx + +这是**一次反射**(行列式 -1,右手系 → MMD 的左手系),几何绕序会跟着翻, +所以绕序要么按法线投票自动判、要么在没法线时一律反转 —— 见下面「绕序」段。 + +注意**不能**照抄 uemodel2pmx 的 (x, z, -y),也不能照抄 psk2pmx 的 (x, z, y): +那两个是给各自格式准备的,套到 XPS 上会把人物转成躺倒或背对镜头。 + +骨骼 +---- +XPS 的骨名是英文描述式(`spine lower` / `arm left elbow` / `leg right knee`), +按规则转成 MMD 标准日文名,英文原名写进 PMX 的 name_en 字段,两边都不丢。 +以 `unused ` 开头的占位骨(XNALara 用来标记「不在姿势界面显示」的骨)默认 +保留在骨架里(权重可能引用它们,删了会破面),但放进独立的「unused」表示枠, +免得主枠里 100 多根骨挤成一团。 + +贴图 +---- +XPS 每个网格带一组贴图,第 0 个是漫反射(实测样本 4 张一组时顺序是 +`_d / _l / _n / _s`)。贴图原样拷进输出目录的 `textures/`。**不去 alpha** —— +XPS 的 alpha 就是头发/睫毛的透明度(和 UE 的「alpha 是数据遮罩」正好相反), +去掉的话头发会变成实心板。DDS 也照拷:MMD 官方支持 .dds 贴图(见 VPVP wiki +的「拡張子」表),不需要转码。 +""" +import os +import re +import shutil +import sys + +BASE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _sub in ("formats", "convert"): + _p = os.path.join(BASE, _sub) + if os.path.isdir(_p) and _p not in sys.path: + sys.path.insert(0, _p) + +import xpsio +import pmxio + +# toon 一律不使用:唯一正确的写法是 flag=0 / index=-1(原因见 psk2pmx.py 顶部) +_TOON_NONE_FLAG = 0 +_TOON_NONE_INDEX = -1 + +_TEX_EXT = (".png", ".bmp", ".tga", ".jpg", ".jpeg", ".dds", ".hdr") + + +def _log_default(msg, tag=None): + print(msg) + + +# ------------------------------------------------------------- 骨名映射 ------ +# XPS 的骨名是英文描述式,先按「整名」查表,再按「部位 + 左右」规则拆。 +_SIDE_JP = {"left": "左", "right": "右", "l": "左", "r": "右", + "lt": "左", "rt": "右"} + +# 主干(整名精确匹配,小写、空格归一化后比对) +_EXACT = { + "root ground": "全ての親", + "root": "全ての親", + "root hips": "センター", + "root pelvis": "センター", + "hips": "センター", + "pelvis": "センター", + "spine lower": "上半身", + "spine": "上半身", + "spine middle": "上半身2", + "chest": "上半身2", + "head neck lower": "首", + "neck": "首", + "head neck upper": "頭", + "head": "頭", +} + +# 部位关键词 → MMD 骨名(不带左右) +_PART = { + "shoulder": "肩", + "clavicle": "肩", + "upperarm": "腕", + "upper arm": "腕", + "arm": "腕", + "forearm": "ひじ", + "elbow": "ひじ", + "wrist": "手首", + "hand": "手首", + "thigh": "足", + "upper leg": "足", + "upperleg": "足", + "knee": "ひざ", + "shin": "ひざ", + "calf": "ひざ", + "ankle": "足首", + "foot": "足首", + "toes": "つま先", + "toe": "つま先", +} + +# 手指:XPS 的 finger 1..5,其中 1 是拇指(实测「arm left finger 1a」相对 +# 其余四指在 Y 上明显错开,是拇指的特征)。段号 a/b/c → 0/1/2。 +_FINGER_JP = {1: "親指", 2: "人指", 3: "中指", 4: "薬指", 5: "小指"} +_FW = ("0", "1", "2", "3", "4", "5") +_FINGER_RE = re.compile(r"^(?:arm|hand)?\s*([lr]|left|right)[\s_-]*" + r"(?:finger|thumb|index|middle|ring|pinky|little)" + r"[\s_-]*(\d)([a-d]?)$") + + +def _norm(name): + """骨名归一化:小写、下划线/连字符→空格、压缩空格。""" + s = (name or "").strip().lower() + s = s.replace("_", " ").replace("-", " ").replace(".", " ") + return " ".join(s.split()) + + +def bone_jp(name): + """XPS 骨名 → MMD 日文名;没有对应条目返回 None(调用方保留原名)。""" + n = _norm(name) + if not n: + return None + if n in _EXACT: + return _EXACT[n] + if n.startswith("unused"): + return None # 占位骨不映射 + + # 手指:arm left finger 2b / l finger 3a ... + m = _FINGER_RE.match(n) + if m: + side, finger, seg = m.group(1), int(m.group(2)), m.group(3) + jp = _FINGER_JP.get(finger) + if jp and side in _SIDE_JP: + # 拇指从 0 起,其余四指从 1 起(MMD 标准骨名惯例) + base = 0 if finger == 1 else 1 + idx = base + (ord(seg) - ord("a") if seg else 0) + if 0 <= idx < len(_FW): + return "%s%s%s" % (_SIDE_JP[side], jp, _FW[idx]) + return None + + # 眼珠:head eyeball left / left eye ... + if "eyeball" in n or n.endswith(" eye") or n == "eye": + side = None + for tok in n.split(): + if tok in _SIDE_JP: + side = _SIDE_JP[tok] + if side: + return side + "目" + return None + + # 四肢:arm left elbow / leg right knee / left upper arm ... + side = None + for tok in n.split(): + if tok in _SIDE_JP: + side = _SIDE_JP[tok] + break + if not side: + return None + body = " ".join(t for t in n.split() if t not in _SIDE_JP) + body = body.replace("arm ", "").replace("leg ", "").strip() + if body in _PART: + return side + _PART[body] + # 带序号的部位:XPS 的 `arm left shoulder 1 / 2` 里 1 是锁骨、2 是大臂 + m2 = re.match(r"^(.+?)\s*(\d+)$", body) + if m2: + stem, num = m2.group(1), m2.group(2) + if stem == "shoulder": + return side + ("肩" if num == "1" else "腕") + if stem in _PART: + return side + _PART[stem] + for key, jp in _PART.items(): + if body.endswith(key): + return side + jp + return None + + +# ----------------------------------------------------------------- 小工具 ---- +def _uniq(name, used): + base = (name or "").strip() or "bone" + if base not in used: + used.add(base) + return base + i = 1 + while "%s_%d" % (base, i) in used: + i += 1 + nm = "%s_%d" % (base, i) + used.add(nm) + return nm + + +def _clean_name(name): + """网格名(如 `24_Material25_0.25_0_0`)→ 给 MMD 看的材质名。 + + XPS 的网格名常常是「渲染参数 + 材质名 + 一堆数值」拼起来的,末段那些 + `_0.25_0_0` 是着色器参数,对用户没意义,去掉后更干净;去不干净就原样保留。 + """ + s = (name or "").strip() + if not s: + return "" + m = re.match(r"^\d+_(.+?)(?:_\d+(?:\.\d+)?)+$", s) + if m and m.group(1): + return m.group(1) + return s + + +def _find_texture(folder, filename): + """按 XPS 里记的贴图名找文件(同目录 + Textures 子目录,大小写不敏感)。""" + raw = (filename or "").strip().replace("\\", "/") + if not raw: + return None + base = os.path.basename(raw) + if not base: + return None + dirs = [folder] + for sub in ("Textures", "textures", "Texture", "tex"): + d = os.path.join(folder, sub) + if os.path.isdir(d): + dirs.append(d) + parent = os.path.dirname(folder) + for sub in ("Textures", "textures"): + d = os.path.join(parent, sub) + if os.path.isdir(d): + dirs.append(d) + + # 先按原名精确找 + for d in dirs: + p = os.path.join(d, base) + if os.path.isfile(p): + return p + # 再退一步:同目录(含子目录)里按小写名 + 换扩展名找 + stem = os.path.splitext(base)[0].lower() + for d in dirs: + try: + for f in os.listdir(d): + st, ext = os.path.splitext(f) + if ext.lower() in _TEX_EXT and st.lower() == stem: + return os.path.join(d, f) + except OSError: + pass + return None + + +def _copy_tex(src, dst): + """原样拷贴图(XPS 的 alpha 是真正的透明度,不能去)。""" + shutil.copyfile(src, dst) + return "copied" + + +# ------------------------------------------------------------------- 主体 ---- +def convert(path, out_path, scale_mode="mmd", log=None, name=None, + enable_edge=False, force_double_sided=False, textures=True, + center=True, jp_bones=True, make_ik=True, hide_unused=True, + all_double_sided=True, fbx_path=None): + """XPS / XNALara → PMX。返回统计 dict。""" + _l = log or _log_default + + m = xpsio.read_xps(path, log=_l) + kind = "XPS" if m.is_generic2 else "XNALara" + if not m.meshes: + raise ValueError("此文件中没有网格数据") + _l("读取 %s:骨骼 %d 根 · 网格 %d 个 · 顶点 %d · 三角面 %d" + % (kind, len(m.bones), len(m.meshes), m.n_vertices, m.n_triangles)) + + # ---- 坐标变换:一次 Z 取反(反射),详见文件顶部说明 + def xf(p): + return (p[0], p[1], -p[2]) + + # ---- 所有网格的顶点拼在一起(PMX 只有一张顶点表) + raw_pos = [] + raw_nrm = [] + raw_uv = [] + raw_w = [] # [(bone_index, weight), ...] + mesh_vert_start = [] # 每个网格在顶点表里的起始下标 + for mesh in m.meshes: + mesh_vert_start.append(len(raw_pos)) + nv = len(mesh.positions) + for vi in range(nv): + raw_pos.append(mesh.positions[vi]) + n = mesh.normals[vi] + raw_nrm.append(n if n and (n[0] or n[1] or n[2]) else None) + raw_uv.append(mesh.uvs[vi] or (0.0, 0.0)) + idxs = mesh.bone_indices[vi] or () + wts = mesh.bone_weights[vi] or () + w = [(int(b), float(wt)) for b, wt in zip(idxs, wts) + if int(b) < len(m.bones) and wt > 1e-6] + raw_w.append(w) + + n_vert = len(raw_pos) + pts = [xf(p) for p in raw_pos] + ys = [p[1] for p in pts] + lo_y, hi_y = (min(ys), max(ys)) if ys else (0.0, 1.0) + height = max(hi_y - lo_y, 1e-6) + + if scale_mode in ("mmd", "auto", None): + scale = 20.0 / height + _l("缩放:源高 %.3f 单位 × %.6f → %.2f(MMD 标准身高 20)" + % (height, scale, height * scale)) + elif scale_mode in ("raw", "none", 1, 1.0): + scale = 1.0 + _l("缩放:保持源尺寸(scale=1.0),源高 %.3f 单位" % height) + else: + scale = float(scale_mode) + _l("缩放:源高 %.3f 单位 × %.6f → %.2f" + % (height, scale, height * scale)) + + if center and pts: + xs = [p[0] for p in pts] + zs = [p[2] for p in pts] + off = (-(min(xs) + max(xs)) * 0.5 * scale, + -lo_y * scale, + -(min(zs) + max(zs)) * 0.5 * scale) + _l("居中:偏移 (%.3f, %.3f, %.3f)" % off, "info") + else: + off = (0.0, 0.0, 0.0) + + def sp(p): + t = xf(p) + return (t[0] * scale + off[0], t[1] * scale + off[1], + t[2] * scale + off[2]) + + def sn(n): + """法线:只换轴(反射会把法线也翻一次,所以 Z 同样取反)。""" + t = xf(n) + ln = (t[0] ** 2 + t[1] ** 2 + t[2] ** 2) ** 0.5 or 1.0 + return (t[0] / ln, t[1] / ln, t[2] / ln) + + # ---- 骨骼:世界坐标就是 XPS 里存的位置(不需要累乘父级) + bone_pos = [sp(b.position) for b in m.bones] + n_src = len(m.bones) + + # ---- 骨骼顺序:DFS,保证父在子前面(PMX 要求父索引 < 子索引) + kids = [[] for _ in range(n_src)] + roots = [] + for i, b in enumerate(m.bones): + p = b.parent_index + if 0 <= p < n_src and p != i: + kids[p].append(i) + else: + roots.append(i) + order = [] + seen = [False] * n_src + stack = list(reversed(roots)) + while stack: + i = stack.pop() + if seen[i]: + continue + seen[i] = True + order.append(i) + stack.extend(reversed(kids[i])) + for i in range(n_src): + if not seen[i]: + seen[i] = True + order.append(i) + + slot = {bi: k for k, bi in enumerate(order)} + used = set() + pmx_bones = [] + n_renamed = 0 + n_unused = 0 + for src in order: + b = m.bones[src] + jp = bone_jp(b.name) if jp_bones else None + main_name = jp if jp else (b.name or "bone") + if jp: + n_renamed += 1 + p = b.parent_index if 0 <= b.parent_index < n_src else -1 + pmx_bones.append({ + "name": _uniq(main_name, used), + "name_en": b.name or "bone", + "pos": bone_pos[src], + "parent": slot.get(p, -1), + "layer": 0, "flag": 0, "tail_kind": 0, "tail": (0.0, 0.0, 0.0), + "inherit_rot": None, "inherit_mov": None, "fixed_axis": None, + "local_axis": None, "external": None, "ik": None, + "_kids": [], "_unused": (b.name or "").lower().startswith("unused"), + }) + for src in order: + b = m.bones[src] + p = b.parent_index if 0 <= b.parent_index < n_src else -1 + if p in slot and slot[p] != slot[src]: + pmx_bones[slot[p]]["_kids"].append(slot[src]) + + for bk in pmx_bones: + flag = 0x0002 | 0x0004 | 0x0008 | 0x0010 # 可旋转/可移动/可显示/可操作 + k = bk.pop("_kids") + if bk.pop("_unused"): + n_unused += 1 + bk["_is_unused"] = True + else: + bk["_is_unused"] = False + if k: + flag |= 0x0001 # 尾 = 骨骼(取第一个子骨骼) + bk["tail_kind"] = 1 + bk["tail"] = k[0] + else: + p = bk["parent"] + if 0 <= p < len(pmx_bones): + d = (bk["pos"][0] - pmx_bones[p]["pos"][0], + bk["pos"][1] - pmx_bones[p]["pos"][1], + bk["pos"][2] - pmx_bones[p]["pos"][2]) + ln = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5 + bk["tail"] = ((d[0] / ln, d[1] / ln, d[2] / ln) if ln > 1e-9 + else (0.0, 1.0, 0.0)) + else: + bk["tail"] = (0.0, 1.0, 0.0) + bk["flag"] = flag + _l("骨骼:%d 根%s%s" + % (len(pmx_bones), + "" if not jp_bones else "(其中 %d 根改为 MMD 标准日文名," + "原英文名保留在英文名中)" % n_renamed, + ";%d 根 unused 占位骨单独放进 unused 表示枠" % n_unused + if n_unused else "")) + + # ---- 足 IK(MMD 摆姿势几乎必用;源骨架没有,这里补标准的一套) + def find_bone(jp_name): + for i, b in enumerate(pmx_bones): + if b["name"] == jp_name: + return i + return -1 + + ik_made = 0 + if make_ik: + ground_y = min(p[1] for p in pts) if pts else 0.0 + center_i = find_bone("センター") + for side, s in (("左", "L"), ("右", "R")): + i_ankle = find_bone(side + "足首") + i_knee = find_bone(side + "ひざ") + i_leg = find_bone(side + "足") + i_toe = find_bone(side + "つま先") + if min(i_ankle, i_knee, i_leg) < 0: + continue + ankle = pmx_bones[i_ankle]["pos"] + i_legik = len(pmx_bones) + pmx_bones.append({ + "name": _uniq(side + "足IK", used), + "name_en": "LegIK_" + s, + "pos": (ankle[0], ground_y, ankle[2]), + "parent": center_i if center_i >= 0 else 0, + "layer": 0, + "flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020, + "tail_kind": 0, "tail": (0.0, 1.0, 0.0), + "inherit_rot": None, "inherit_mov": None, + "fixed_axis": None, "local_axis": None, "external": None, + "_is_unused": False, + "ik": {"target": i_ankle, "iterations": 40, + "limit_angle": 1.0, + "links": [{"bone": i_knee, "min": None, "max": None}, + {"bone": i_leg, "min": None, "max": None}]}, + }) + ik_made += 1 + if i_toe >= 0: + toe = pmx_bones[i_toe]["pos"] + pmx_bones.append({ + "name": _uniq(side + "つま先IK", used), + "name_en": "ToeIK_" + s, + "pos": (toe[0], ground_y, toe[2]), + "parent": i_legik, + "layer": 0, + "flag": 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020, + "tail_kind": 0, "tail": (0.0, 1.0, 0.0), + "inherit_rot": None, "inherit_mov": None, + "fixed_axis": None, "local_axis": None, + "external": None, + "_is_unused": False, + "ik": {"target": i_toe, "iterations": 3, + "limit_angle": 1.0, + "links": [{"bone": i_ankle, + "min": None, "max": None}]}, + }) + ik_made += 1 + if ik_made: + _l("足 IK:已补充 %d 根(足IK / つま先IK,父骨骼 センター)" % ik_made, + "info") + else: + _l("足 IK:源骨架中没有完整的腿部骨链,未补充 IK 骨", "info") + + # ---- 面:按网格(= 材质)排序,保证 PMX 材质吃连续的面段 + nmats = len(m.meshes) + tri = [] + for mi, mesh in enumerate(m.meshes): + base = mesh_vert_start[mi] + for (a, b, c) in mesh.triangles: + tri.append((mi, base + a, base + b, base + c)) + tri.sort(key=lambda t: t[0]) + + # ---- 绕序自动判定(用变换后的数据投票) + pos_t = [sp(p) for p in raw_pos] + nrm_t = [] + n_has = 0 + for i, n in enumerate(raw_nrm): + if n is None: + nrm_t.append(None) + else: + nrm_t.append(sn(n)) + n_has += 1 + face_idx = [] + for _mi, a, b, c in tri: + face_idx.extend((a, b, c)) + if n_has >= max(1, len(raw_nrm) // 2): + # 少数顶点缺法线时用「有效法线的平均值」补上,别让投票函数拿到 None + if n_has < len(raw_nrm): + ax = ay = az = 0.0 + for n in nrm_t: + if n is not None: + ax += n[0] + ay += n[1] + az += n[2] + ln = (ax * ax + ay * ay + az * az) ** 0.5 or 1.0 + fill = (ax / ln, ay / ln, az / ln) + nrm_vote = [n if n is not None else fill for n in nrm_t] + _l("绕序:%d 个顶点没有法线,判定时使用平均法线" + % (len(raw_nrm) - n_has), "info") + else: + nrm_vote = nrm_t + need_flip, ag, dis = pmxio.detect_winding(pos_t, nrm_vote, face_idx) + _l("绕序自动判定:与法线同向 %d 面 / 反向 %d 面 → %s" + % (ag, dis, "需要反转" if need_flip else "保持不变")) + else: + # Z 取反是一次反射,几何绕序必然翻面;没有法线时一律反转 + need_flip = True + _l("绕序:法线数据不完整,按坐标轴反射统一反转(保持正面朝外)", "info") + + pmx_faces = [] + for _mi, a, b, c in tri: + pmx_faces.extend((c, b, a) if need_flip else (a, b, c)) + + # ---- 权重:XPS 的权重是按顶点索引的,直接摊到 PMX 顶点上 + n_dropped = 0 + no_weight = 0 + pmx_verts = [] + for vi in range(n_vert): + P = sp(raw_pos[vi]) + N = nrm_t[vi] if nrm_t[vi] is not None else (0.0, 0.0, 1.0) + wl = [(b, w) for b, w in raw_w[vi] if w > 1e-6] + if len(wl) > 4: + n_dropped += len(wl) - 4 + wl.sort(key=lambda t: -t[1]) + wl = wl[:4] + if not wl: + no_weight += 1 + wl = [(0, 1.0)] + tot = sum(w for _, w in wl) or 1.0 + wl = [(slot.get(b, 0), w / tot) for b, w in wl] + if len(wl) == 1: + wtype, wbones, wweights = 0, [wl[0][0]], [] + elif len(wl) == 2: + wtype, wbones, wweights = 1, [wl[0][0], wl[1][0]], [wl[0][1]] + else: + wtype = 2 + wbones = [wl[k][0] if k < len(wl) else wl[0][0] for k in range(4)] + wweights = [wl[k][1] if k < len(wl) else 0.0 for k in range(4)] + u, v = raw_uv[vi] + pmx_verts.append({"pos": P, "normal": N, "uv": (u, v), + "add_uv": [], "wtype": wtype, "wbones": wbones, + "wweights": wweights, "sdef": None, "edge": 1.0}) + if no_weight: + _l("权重:%d 个顶点没有权重,已绑定到第 0 根骨骼" % no_weight, "warn") + if n_dropped: + _l("权重:已丢弃 %d 条第 5 根及以后的骨骼权重(PMX 每个顶点最多 4 根)" + % n_dropped, "info") + + # ---- 材质 + 贴图 + folder = os.path.dirname(os.path.abspath(path)) + out_dir = os.path.dirname(os.path.abspath(out_path)) + tex_dir = os.path.join(out_dir, "textures") + pmx_textures = [] + tex_slot = {} + n_linked = 0 + n_missing = [] + + def use_texture(filename): + key = os.path.basename((filename or "").replace("\\", "/")).lower() + if key in tex_slot: + return tex_slot[key] + real = _find_texture(folder, filename) if filename else None + if real is None: + tex_slot[key] = -1 + return -1 + ext = os.path.splitext(real)[1].lower() + if ext not in _TEX_EXT: + tex_slot[key] = -1 + return -1 + dst_name = os.path.basename(real) + dst = os.path.join(tex_dir, dst_name) + try: + os.makedirs(tex_dir, exist_ok=True) + if not os.path.isfile(dst): + _copy_tex(real, dst) + except OSError: + tex_slot[key] = -1 + return -1 + rel = "textures/" + dst_name + if rel not in pmx_textures: + pmx_textures.append(rel) + tex_slot[key] = pmx_textures.index(rel) + return tex_slot[key] + + counts = [0] * max(1, nmats) + for mi, _a, _b, _c in tri: + counts[mi] += 1 + + pmx_materials = [] + for mi, mesh in enumerate(m.meshes): + mname = _clean_name(mesh.name) or ("mat%d" % mi) + diff = mesh.diffuse + ti = use_texture(diff) if textures else -1 + if ti >= 0: + n_linked += 1 + elif textures and diff: + n_missing.append(os.path.basename(diff.replace("\\", "/"))) + flag = 0x0E | (0x10 if enable_edge else 0) + if force_double_sided or all_double_sided: + flag |= 0x01 + pmx_materials.append({ + "name": mname, "name_en": mname, + "diffuse": (1.0, 1.0, 1.0, 1.0), + "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, + "ambient": (0.5, 0.5, 0.5), + "flag": flag, + "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, + "tex": ti, "sph": -1, "sph_mode": 0, + "toon_flag": _TOON_NONE_FLAG, "toon": _TOON_NONE_INDEX, "memo": "", + "faces": counts[mi], + }) + # 空材质(源里声明了但一个面都没用上)会让 PMX 出现 0 面材质段,去掉更干净 + pmx_materials = [x for x in pmx_materials if x["faces"] > 0] + if not pmx_materials: + pmx_materials.append({ + "name": "material_0", "name_en": "material_0", + "diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0.0, 0.0, 0.0), + "shininess": 0.0, "ambient": (0.5, 0.5, 0.5), + "flag": 0x0E | (0x10 if enable_edge else 0), + "edge_color": (0.0, 0.0, 0.0, 1.0), + "edge_size": 1.0 if enable_edge else 0.0, "tex": -1, "sph": -1, + "sph_mode": 0, "toon_flag": _TOON_NONE_FLAG, + "toon": _TOON_NONE_INDEX, "memo": "", + "faces": len(pmx_faces) // 3, + }) + # PMX 材质的「面数」字段其实是**索引数**(每个三角面占 3 个) + for x in pmx_materials: + x["faces"] = int(x["faces"]) * 3 + _l("材质:%d 个 · 关联到贴图 %d 个%s" + % (len(pmx_materials), n_linked, + "" if n_linked else "(源目录中没有同名贴图,导出为无贴图模型)")) + if n_missing: + _l("贴图:源目录中未找到 %s" + % " / ".join(n_missing[:8]), "warn") + + # ---- 表示枠:主干骨进 Root,unused 占位骨单独一枠,表情一枠 + main_items = [] + unused_items = [] + for i, bk in enumerate(pmx_bones): + (unused_items if (hide_unused and bk.get("_is_unused")) + else main_items).append(i) + frames = [] + if main_items: + frames.append({"name": "Root", "name_en": "Root", "special": 0, + "items": [(0, i) for i in main_items]}) + if unused_items: + frames.append({"name": "unused", "name_en": "unused", "special": 0, + "items": [(0, i) for i in unused_items]}) + + stem = os.path.splitext(os.path.basename(path))[0] + title = name or stem + comment = ["由 %s 转换:%s" % (kind, os.path.basename(path)), + "骨骼 %d 根 · 材质 %d 个 · 顶点 %d · 三角面 %d" + % (len(pmx_bones), len(pmx_materials), len(pmx_verts), + len(pmx_faces) // 3), + "converted by xps2pmx.py"] + model = pmxio.new_model(title) + model["name"] = title + model["name_en"] = stem + model["comment"] = "\r\n".join(comment) + model["comment_en"] = "\r\n".join(comment) + model["vertices"] = pmx_verts + model["faces"] = pmx_faces + model["textures"] = pmx_textures + model["materials"] = pmx_materials + model["bones"] = pmx_bones + model["morphs"] = [] + model["frames"] = frames + model["add_uv"] = 0 + if not enable_edge: + pmxio.strip_edges(model, force_double_sided=False) + + size = pmxio.write_pmx(model, out_path) + _l("已写出 %s(%.2f MB)· 顶点 %d · 三角面 %d · 骨骼 %d · 材质 %d" + % (os.path.basename(out_path), size / 1048576.0, len(pmx_verts), + len(pmx_faces) // 3, len(pmx_bones), len(pmx_materials)), "ok") + + st = {"bytes": size, "vertices": len(pmx_verts), + "tris": len(pmx_faces) // 3, "bones": len(pmx_bones), + "materials": len(pmx_materials), "morphs": 0, + "textures": len(pmx_textures), "scale": scale} + + if fbx_path: + try: + import fbxout + st["fbx"] = fbxout.export_model( + fbx_path, pmx_verts, pmx_faces, pmx_materials, + pmx_bones, [], + mirror_z=True, reverse_winding=True, tex_dir=tex_dir, + log=_l, name=title) + _l("已写出 %s(ASCII FBX 7.4 · %.2f MB)" + % (os.path.basename(fbx_path), + st["fbx"]["bytes"] / 1048576.0), "ok") + except Exception as e: + st["fbx_error"] = str(e) + _l("FBX 导出失败:%s" % e, "err") + return st + + +def main(argv=None): + import argparse + ap = argparse.ArgumentParser(description="XPS / XNALara → MMD PMX(纯 Python)") + ap.add_argument("src") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--scale", default="mmd", + help="mmd(归一到 20 单位,默认)/ raw(保持源尺寸)/ 具体倍率") + ap.add_argument("--edge", action="store_true", help="给材质开启 MMD 轮廓线") + ap.add_argument("--no-textures", action="store_true") + ap.add_argument("--raw-bone-names", action="store_true", + help="骨骼保留原始英文名,不转 MMD 日文标准名") + ap.add_argument("--no-ik", action="store_true", help="不补 MMD 足 IK 骨") + ap.add_argument("--show-unused", action="store_true", + help="unused 占位骨也放进 Root 表示枠") + ap.add_argument("--one-sided", action="store_true", + help="材质不默认开两面描画") + ap.add_argument("--fbx", action="store_true", help="同时导出 FBX") + ap.add_argument("--name", default=None) + a = ap.parse_args(argv) + out = a.out or (os.path.splitext(a.src)[0] + ".pmx") + fbx = (os.path.splitext(out)[0] + ".fbx") if a.fbx else None + st = convert(a.src, out, scale_mode=a.scale, + log=lambda m_, t=None: print(m_), name=a.name, + enable_edge=a.edge, textures=not a.no_textures, + jp_bones=not a.raw_bone_names, make_ik=not a.no_ik, + hide_unused=not a.show_unused, + all_double_sided=not a.one_sided, fbx_path=fbx) + print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/images/en/batch.webp b/docs/images/en/batch.webp new file mode 100644 index 0000000..1921485 Binary files /dev/null and b/docs/images/en/batch.webp differ diff --git a/docs/images/en/overview.webp b/docs/images/en/overview.webp new file mode 100644 index 0000000..2e89711 Binary files /dev/null and b/docs/images/en/overview.webp differ diff --git a/docs/images/en/preview.webp b/docs/images/en/preview.webp new file mode 100644 index 0000000..c0c617b Binary files /dev/null and b/docs/images/en/preview.webp differ diff --git a/docs/images/en/skeleton.webp b/docs/images/en/skeleton.webp new file mode 100644 index 0000000..ea27656 Binary files /dev/null and b/docs/images/en/skeleton.webp differ diff --git a/docs/images/en/tune.webp b/docs/images/en/tune.webp new file mode 100644 index 0000000..d6d2fe6 Binary files /dev/null and b/docs/images/en/tune.webp differ diff --git a/docs/images/zh/batch.webp b/docs/images/zh/batch.webp new file mode 100644 index 0000000..4d1a277 Binary files /dev/null and b/docs/images/zh/batch.webp differ diff --git a/docs/images/zh/overview.webp b/docs/images/zh/overview.webp new file mode 100644 index 0000000..9f31e36 Binary files /dev/null and b/docs/images/zh/overview.webp differ diff --git a/docs/images/zh/preview.webp b/docs/images/zh/preview.webp new file mode 100644 index 0000000..8907848 Binary files /dev/null and b/docs/images/zh/preview.webp differ diff --git a/docs/images/zh/skeleton.webp b/docs/images/zh/skeleton.webp new file mode 100644 index 0000000..034af54 Binary files /dev/null and b/docs/images/zh/skeleton.webp differ diff --git a/docs/images/zh/tune.webp b/docs/images/zh/tune.webp new file mode 100644 index 0000000..0db7b32 Binary files /dev/null and b/docs/images/zh/tune.webp differ diff --git a/docs/other-formats.md b/docs/other-formats.md new file mode 100644 index 0000000..317ffa7 --- /dev/null +++ b/docs/other-formats.md @@ -0,0 +1,112 @@ +# 其它格式 → PMX + +FBX、unitypackage、uemodel、psk / pskx、xps 先转成 PMX,再走 [PMX → VRM](pmx-to-vrm.md)。图形界面里默认一路转到 VRM, +中间的 PMX 和解包出来的资源放在临时目录,输出目录只有 VRM;「转换成」选「只转 PMX」时输出 PMX 和 `textures/`。 + +转出的 PMX 也能直接在 MMD / PmxEditor 里用:文本编码是 MMD 要求的 UTF-16LE,材质不使用 toon,每个顶点最多 4 根 +骨骼权重,贴图拷进 `textures/`。 + +## FBX / unitypackage + +```bash +python convert/fbx2pmx.py "model.fbx" -o "model.pmx" +python convert/fbx2pmx.py "model.fbx" --info # 只看结构,不转换 +python formats/unitypackage_unpack.py "pack.unitypackage" --list # 列出包里的文件 +python formats/unitypackage_unpack.py "pack.unitypackage" -o out # 解包 +``` + +| 参数 | 说明 | +|---|---| +| `--scale mmd` / `raw` / 倍率 | 默认缩放到 MMD 标准身高(约 20 单位);`raw` 保持 FBX 原尺寸 | +| `--alpha auto` / `keep` / `strip` | 贴图透明通道:默认逐张判定,`keep` 原样保留,`strip` 一律去掉 | +| `--no-auto-facing` / `--face-180` | 关掉朝向自动判定 / 在判定结果上再转 180° | +| `--no-morphs` / `--max-morphs N` | 不导出表情 / 最多导出 N 个 | +| `--keep-untextured-meshes` | 保留没有材质的网格(默认跳过) | +| `--no-center` | 不把模型移到原点、落到地面 | +| `--no-flip-z` | 不做右手系 → 左手系转换(调试用) | + +- **格式**:二进制和 ASCII FBX 7.x,不需要 FBX SDK。网格、UV、法线、蒙皮权重、骨骼层级、BlendShape 表情都会转换; + 四边形自动三角化,绕序按法线自动判定。 +- **朝向**:FBX 没有「正面朝哪」的字段,按脚尖骨骼方向判定,没有脚尖时看脸部网格的位置。判错时用 `--face-180`。 +- **贴图透明**:MMD 把贴图 alpha 当作材质透明度,而游戏贴图的 alpha 常常存的是别的数据(高光、遮罩),留着会让整块 + 模型变透明。`auto` 按 alpha 的分布判断是真透明还是数据遮罩;去掉 alpha 的贴图另存为 `<名字>_noalpha`,不改原文件。 +- **效果片**:没有材质的网格多是游戏里的特效面片,转出来会是一块盖在身上的灰板,默认跳过。 +- **Unity 资源**:FBX 里没写贴图文件名时(unitypackage 里常见),按 Unity 的材质文件(.mat)找回贴图。 +- **命名**:英文骨名(HumanIK / Mixamo / VRoid / Blender / 3ds Max 风格)和英文表情名(VRChat、VRoid、`MTH_A` 等) + 在转 VRM 时自动对应;PMX 里保留原来的英文骨名,所以直接套 MMD 动作(按日文骨名匹配)需要先改名。 +- **替换网格**:同一位置的几套网格(手势、张嘴的头)只显示一套,其余做成切换用的表情。 +- **unitypackage**:本质是 gzip 打包的 tar,界面里直接加即可;包里有几套服装时会同时转。只有衣服 / 配件、没有身体的 + 模型在开启「只转换人物」时跳过。 +- FBX 里没有物理(刚体、关节)。转 VRM 时会按骨骼名自动补 SpringBone。 + +## uemodel(UEFormat) + +FortnitePorting / FModel 导出的 `.uemodel`(UEFormat v1~v10)。 + +```bash +python convert/uemodel2pmx.py "model.uemodel" -o "model.pmx" +python convert/uemodel2pmx.py "part.uemodel" --align-to "body.uemodel" # 把拆开的部件放回整身模型上 +``` + +| 参数 | 说明 | +|---|---| +| `--scale fixed` / `mmd` / 倍率 | 默认 `fixed`:按 UE 厘米统一换算,几个部件保持相对大小;`mmd` 每个文件各自归一到 20 单位 | +| `--align-to 整身.uemodel` | 按 `*_adjust` 骨求平移,把部件对齐到整身模型(界面里在「其它格式」页选参考模型) | +| `--lod N` | 用第几级 LOD | +| `--keep-alpha` | 保留贴图 alpha(默认去掉:UE 贴图的 alpha 多是数据遮罩) | +| `--no-textures` / `--no-add-uv` | 不关联贴图 / 不写附加 UV | +| `--edge` / `--force-double-sided` | 开启轮廓线 / 材质双面 | +| `--fbx` | 同时写一份 ASCII FBX | + +贴图不在 `.uemodel` 里:按导出目录里的材质实例 `MI_<材质名>.json` 找基础色贴图。表情(MORPHTARGETS)转成顶点表情。 + +## psk / pskx(Unreal ActorX) + +```bash +python convert/psk2pmx.py "model.pskx" -o "model.pmx" +``` + +| 参数 | 说明 | +|---|---| +| `--scale mmd` / `raw` / 倍率 | 默认归一到 20 单位 | +| `--raw-bone-names` | 骨骼保留原始英文名(默认转 MMD 日文标准名,原名写进英文名字段) | +| `--no-ik` | 不补 MMD 的足 IK 骨 | +| `--no-morphs` | 不导出表情 | +| `--keep-alpha` | 保留贴图 alpha | +| `--no-textures` / `--no-add-uv` | 不找贴图 / 不写附加 UV | +| `--edge` / `--force-double-sided` | 开启轮廓线 / 材质双面 | +| `--fbx` | 同时写一份 ASCII FBX | + +- **骨骼**:3ds Max Biped 的 `Bip001*` 命名转成 MMD 标准日文名(Bip001Pelvis → センター、Bip001LThigh → 左足 …), + 对应不上的保留原名;按腿部骨链补 `左足IK` / `左つま先IK`,在 MMD 里可以直接摆姿势。 +- **表情**:MRPH 顶点位移转成 PMX 顶点表情;附加 UV(EXTRAUVS)写成 PMX 附加 UV。 +- **贴图**:按材质名在源文件目录里找同名图片,找不到时是白模(日志会提示)。 +- 参考实现:[io_scene_psk_psa](https://github.com/DarklightGames/io_scene_psk_psa)。 + +## xps(XNALara) + +```bash +python convert/xps2pmx.py "model.xps" -o "model.pmx" +``` + +| 参数 | 说明 | +|---|---| +| `--scale mmd` / `raw` / 倍率 | 默认归一到 20 单位 | +| `--raw-bone-names` / `--no-ik` | 保留英文骨名 / 不补足 IK | +| `--show-unused` | `unused` 占位骨也放进主表示枠(默认单独一组) | +| `--one-sided` | 材质不默认双面 | +| `--no-textures` / `--edge` / `--fbx` | 不拷贴图 / 开启轮廓线 / 同时写 FBX | + +XPS 的英文描述式骨名(`arm left elbow`、`leg right knee` …)转成 MMD 标准日文名;贴图 alpha 保留(XPS 的 alpha 就是 +头发、睫毛的透明度)。XPS 没有表情。 + +## 常见问题 + +**PmxEditor 打开时提示「アンカーデータの読み込みに失敗しました」**:PmxEditor 会自动加载和模型同名的 `.psk` 当作 +锚点数据,而 `.psk` 也是 Unreal 网格的扩展名。点确定即可,模型不受影响;把 PMX 换个名字或文件夹,或者关掉 +`[ファイル] → [アンカーデータの自動読み込み/保存]` 就不会再弹。 + +**MMD 提示无法载入 PMX**:MMD 只读 UTF-16LE 编码的 PMX。本工具输出的都是 UTF-16LE;别处来的文件可以用 +`python formats/pmxio.py "旧文件.pmx"` 转换编码(`-o` 指定输出,`--in-place` 覆盖原文件)。 + +**模型背对镜头 / 躺倒**:FBX 用 `--face-180`;其它格式的轴约定是固定的,遇到特殊的源文件可以在 PmxEditor 里绕 Y 转 180°。 diff --git a/docs/pmx-to-vrm.md b/docs/pmx-to-vrm.md new file mode 100644 index 0000000..122834a --- /dev/null +++ b/docs/pmx-to-vrm.md @@ -0,0 +1,206 @@ +# PMX → VRM 转换说明 + +PMX → VRM 的转换规则和命令行用法。转换器只用 Python 标准库,直接读写二进制格式,不依赖 Blender、 +mmd_tools、Unity 或 UniVRM。 + +## 命令行 + +```bash +# VRM 1.0(默认) +python convert/pmx2vrm.py "model.pmx" -o "model.vrm" + +# VRM 0.x(只认 0.x 的软件用) +python convert/pmx2vrm.py "model.pmx" --spec 0x --title "名字" --author "作者" + +# 检查输出(结构 + VRM 官方 JSON Schema,需要 jsonschema) +python tools/qa/check_vrm.py "model.vrm" +``` + +| 参数 | 说明 | +|---|---| +| `--spec 1.0` / `--spec 0x` | VRM 版本,默认 1.0 | +| `--scale auto` / 倍率 | 默认把身高归一到 1.6 m | +| `--tpose` | 把 A-pose 手臂、手、手指摆成 VRM 规范的 T-pose(**默认不启用,保留原始姿势**;`--keep-pose` 作为旧版兼容别名保留) | +| `--keep-control-bones` | 保留没有权重的中间骨(全ての親 / センター / グルーブ / 腰 等;默认去掉,层级像 VRoid)。IK、末端骨这类不起作用的骨总会去掉 | +| `--flip-winding` | 强制反转三角形绕序(默认自动判定) | +| `--force-double-sided` | 所有材质双面 | +| `--outline` | 按 PMX 的轮廓线设置写 MToon 描边(默认不描边)。unitypackage / FBX 里 **Unity 材质自己设置的描边**(`.mat` 的 `_Outline_Width` > 0、`_Outline_Color`)会另行保留,与这个开关无关 | +| `--no-spring` / `--no-spring-skirt` | 不转物理 / 不转挂在下半身的链(通常是裙摆) | +| `--spring-stiffness k` | SpringBone 硬度整体倍率,默认 1.0 | +| `--spring-gravity g` / `--spring-gravity-skirt g` | 头发等 / 裙摆的重力,默认 0 / 0.1 | +| `--no-auto-spring` | 模型没有物理刚体时不自动补 | +| `--no-spring-center` | 不以模型根节点为 SpringBone center | +| `--no-combo-expr` | 情绪预设不组合眉 / 眼 / 嘴,每个预设只对应一个表情 | +| `--no-gaze` | 不补视线表情 | +| `--no-extra-expr` | 不补 hideHighlight / tongue 表情 | +| `--dense-morphs` / `--max-morphs N` | 表情用密集存储 / 只导出前 N 个(0 = 不导出) | +| `--tex-max N` / `--tex-jpeg` | 贴图最大边长 / 不透明贴图存 JPEG(需要 Pillow) | +| `--tex-no-mip` | 贴图采样器禁用 mipmap。UV 岛之间没留 gutter 的贴图,mipmap 会把岛外底色混进边缘形成白边;开启后白边基本消失,但远景会有轻微锯齿(默认关闭) | +| `--title` / `--author` | 写进 VRM meta | + +在 Python 里调用:`pmx2vrm.convert(pmx_path, vrm_path, spec="1.0", ...)`,参数和上表对应,返回统计信息。 + +## 坐标系 + +| 格式 | 正面 | 角色左手侧 | 上 | 手性 | +|---|---|---|---|---| +| PMX(MMD) | -Z | +X | +Y | 左手系 | +| VRM 0.x(glTF) | -Z | -X | +Y | 右手系 | +| VRM 1.0(glTF) | +Z | +X | +Y | 右手系 | + +- PMX 和 glTF 手性相反,同一组数字直接搬过去是镜像人形,所以要反射一个轴:转 0.x 时 X 取反,转 1.0 时 Z 取反。 + 绕 Y 旋转 180° 是纯旋转,改不了手性,转出来左右是反的。 +- 反射会把「从外面看逆时针」变成顺时针,所以绕序通常要反转。转换器用反射后的数据,拿每个三角形的几何法线和 + 顶点法线投票自动判定,日志里有一行「绕序自动判定」。 +- 尺寸:MMD 模型约 20 单位高,默认归一到 1.6 m;表情偏移按同样的倍率缩放。 + +模型镂空时先看「绕序自动判定」那行:判错了(反向面占多数)加 `--flip-winding`;模型本身是薄片几何 +(头发、裙摆、飘带)依赖双面显示的,加 `--force-double-sided`。描边外壳(翻了面、紧贴在脸和身体外面的那层, +常叫「エッジ」「outline」)和衣服的内侧面按几何自动认出来,仍保持单面,否则会盖住模型或重叠闪烁,日志里会列出。 + +## 映射 + +| PMX | VRM / glTF | +|---|---| +| 骨骼层级 | glTF 节点(静止姿势只有平移),`skin.inverseBindMatrices` | +| 顶点权重 BDEF1/2/4、SDEF、QDEF | `JOINTS_0` + `WEIGHTS_0`(每顶点最多 4 根,已归一化);SDEF 按线性混合 | +| 材质 | MToon:1.0 写 `VRMC_materials_mtoon`,0.x 写 `materialProperties` | +| 加算球面贴图(.spa) | MToon matcap | +| 贴图 | 嵌入 GLB;PNG / JPEG 原样,其它格式转成 PNG | +| 顶点表情(含グループ) | morph target(默认稀疏存储)+ VRM 表情 | +| 材质表情 | 材质颜色绑定(显示 / 隐藏部件) | +| 骨骼表情 | 在静止姿势下摆骨、按线性蒙皮算出顶点位移,烘焙成 morph target | +| UV 表情 | 整个材质一起缩放 / 平移的 → 贴图偏移绑定;做不到的跳过并提示 | +| 左右眼骨 | humanoid leftEye / rightEye,lookAt 用骨骼 | +| 物理刚体 + 关节 | 1.0:`VRMC_springBone`;0.x:`secondaryAnimation` | +| 跟随骨骼的刚体 | SpringBone 碰撞体(球 / 胶囊;0.x 只有球,胶囊换成一串球) | + +### 骨骼 + +MMD 标准骨名对应 VRM humanoid:下半身 → hips、上半身 → spine、上半身2 → chest、首 → neck、頭 → head、 +腕 / ひじ / 手首 → UpperArm / LowerArm / Hand、足 / ひざ / 足首 / つま先 → UpperLeg / LowerLeg / Foot / Toes、 +目 → Eye(`両目` 是双眼共用的控制骨,不映射)。手指按版本区分: + +| MMD | VRM 1.0 | VRM 0.x | +|---|---|---| +| 親指0 / 1 / 2 | ThumbMetacarpal / Proximal / Distal | ThumbProximal / Intermediate / Distal | +| 親指1 / 2(没有 0,親指1 离手腕较远) | ThumbProximal / Distal | ThumbIntermediate / Distal,掌根补占位 ThumbProximal | +| 親指1 / 2(没有 0,親指1 在掌根) | ThumbMetacarpal / Proximal | ThumbProximal / Intermediate | +| 人指・中指・薬指・小指 1 / 2 / 3 | Proximal / Intermediate / Distal | 同左 | + +常见的英文骨名(Unity / Mixamo / VRoid / Blender 风格)也能对应。转换时自动修正: + +- **付与骨合并**:VRM 没有付与。付与回転率 1 的骨(足D / ひざD / 足首D 等,腿部网格的权重常在它们上面) + 连同权重和子骨并入付与親。和付与親不在同一位置的也并,条件是两者跟着同一根 humanoid 骨移动、偏差不超过 + 那一节骨长的一半;合并后绕付与親的位置转。 +- **按比例跟随的付与骨**:ひざ補助、ひじ補助、尻、衣服的调整骨这类跟关节转 30%~65% 的骨,权重按付与率 + 分给关节骨(线性混合,近似转了一部分角度)。带物理的不动,付与率为负的(腰キャンセル 等)不动。 +- **自检**:转换后检查两件事,有问题在日志里提示(不改输出):网格在 MMD 里跟着某个关节转、在 VRM 里却不跟; + humanoid 骨位置明显不对(在身体另一侧、离父骨或网格太远,多半是把模型外面的控制骨当成了 humanoid 骨)。 +- **层级**:VRM 要求每个 humanoid 骨在规范父骨位的子树里。MMD 的上半身和下半身是兄弟骨,转换时把上半身改挂到 + 下半身下,静止姿势下顶点不动。 +- **hips 位置**:MMD 的下半身和上半身从同一点出发,hips 和 spine 几乎重合。hips 离 spine 太近时把它移到骨盆 + (大腿根往上),和 VRoid 的比例接近;只挪节点,网格和权重不变。 +- **T-pose**(`--tpose` / 界面「转为 T 姿势」,默认关闭,不重摆骨架):按 VRM 规范的静止姿势摆——上臂、前臂、手沿水平 ±X,掌心朝下,四指伸直,拇指水平指向 + 外侧与正前方之间的 45°。动作和手部追踪都是「从这个姿势开始转多少度」,静止姿势歪多少,动起来就一直歪多少。 + 从手臂往指尖依次转,子骨和顶点(含法线、表情偏移)按蒙皮权重一起转。末节手指没有真实子骨、tail 方向又和上一节 + 差得远(FBX 转来的模型常见)时,这一节跟着上一节转。 +- **占位骨**:缺少规范必需的骨(以及 chest、neck,很多程序默认它们存在)时补 `vrm_xxx` 占位节点,并保证层级合法。 +- **去掉无效骨**:既不带权重、也不是 humanoid 骨或物理关节 / 碰撞体,下面也没有这类骨的节点(IK、末端骨、合并掉的 + 付与骨、操作中心等)不写进 VRM。「精简控制骨」(默认开,`--keep-control-bones` 关闭)再去掉没有权重的中间骨(全ての親 / センター / + グルーブ / 腰 / 肩P 等),子骨挂到最近的保留骨上,层级和 VRoid 一样是 Root > Hips。都只删节点,网格和动作不变。 + +### 材质 + +- **透明模式**:根据漫反射 alpha 和贴图 alpha 的分布自动选。只有边缘抗锯齿的用 MASK(裁剪),半透明像素多的用 + BLEND;会被材质表情隐藏的不透明材质用 MASK。贴图只统计材质的 UV 用到的区域,几个部件共用的图集、拼着用不到的 + 半透明图层不会让不透明的部件变成半透明。BLEND 材质按 PMX 材质顺序设置绘制顺序。 +- **颜色**:按 MMD 的着色公式算出显示颜色;VRM 1.0 规定颜色因子是线性值,写入时从 sRGB 换算。 +- **toon → 阴影**:MMD 的明暗来自 toon 贴图。阴影色取 toon 最暗端、亮部取最亮端,明暗交界的位置和宽度换算成 + MToon 的 shadingShift / shadingToony。动漫风格的皮肤 toon 换算后阴影色是浅粉、交界靠后,和 VRoid 原生模型 + 的观感一致。没有 toon 的材质(通常是眼睛、眉毛、嘴)不画阴影。 +- **乘算球面贴图**(.sph)在 MToon 里没有对应项,会被忽略并在日志里提示。 + +### 表情 + +- **预设对应**:按表情名对应 VRM 预设(まばたき → blink、あ → aa …)。比较时不分全角半角、大小写和分隔符, + 也认变体后缀(怒りA、まばたき2)。除了 MMD 日文名,也认 VRoid(`Fcl_ALL_Joy`)、VRChat(`vrc.v_aa`)等英文名、 + ARKit 和常见中文名(眨眼、开心 …),日文名优先。MMD 的「上」「下」是眉毛表情,不当成视线。 +- **单眼眨眼**:按动的是哪一边的顶点定 blinkLeft / blinkRight,不看名字(不同模型的命名习惯不一致)。 +- **情绪预设组合**:happy / angry / sad / relaxed / surprised 像 VRoid 一样组合眉、眼、嘴三个部位,例如 + angry = 怒り + キリッ + 口角下げ。权重按 VRoid 的预设偏含蓄,方便和眨眼、口型叠加。至少两个部位找到才组合, + 原来单个对应的表情保留为自定义表情。候选表情和权重见 `convert/vrmconv/expressions.py` 的 `COMBO`; + 只有 ARKit 表情的模型用 ARKit 的组合。happy / relaxed(笑眼)设 `overrideBlink: blend`,笑眼时不再叠加眨眼。 +- **退路**:名字对应不上时,眨眼用 ARKit 的 eyeBlinkLeft + eyeBlinkRight 或左右单眼合起来,口型用 ARKit 的 + jawOpen、mouthPucker 等。 +- 转换日志里的「表情预设」一行列出每个预设用了哪些表情、缺哪些。 +- **网格划分**:模型按表情分成几个网格(类似 VRoid 的 Face / Body / Hair),每个网格只带动得到它的 morph target。 + glTF 要求同一个网格的每个部分带同样的 morph target,而 three.js、Unity 等读取端会展开成「顶点数 × 表情数」的 + 完整数组;分开后,表情多的大模型在预览和游戏里能省下几百 MB 内存。网格名取网格里最大的材质名。 +- **存储**:默认用 glTF 稀疏 accessor,只存实际动到的顶点,文件小很多;个别不支持稀疏 accessor 的老软件用 + `--dense-morphs`。 + +### 视线 + +- lookAt 的最大转角按眼球几何算:MMD 模型的眼骨支点常贴着眼球,固定角度转眼看不出来,所以按「瞳孔移动约 + 瞳孔宽度的 28%」反推左右角度(8°~20°),向下取 0.7 倍、向上 0.5 倍;算不出时用 10°。 +- 有左右眼骨时补 lookLeft / lookRight / lookUp / lookDown 四个预设表情(转眼骨烘焙成顶点位移),给直接播放 + 这几个表情的程序用;模型自己有同名表情时不补。每个方向烘焙成「横向」「深度」两个 morph target + (`lookLeftRight_depth`、`lookUpDown_depth` 只是 morph target,不是表情),按 sin / (1 − cos) 的权重组合, + 任意角度都和直接转眼骨一致。所以在界面的「调整」里改视线角度时,这几个表情跟着变,不用重新转换。 +- 补两个自定义表情,名字固定,程序按名字就能找到(模型已有同名表情时不补): + - `hideHighlight`:关掉眼睛高光。模型自带关闭高光的表情(「ハイライト消し」「eye hi off」等,几组高光各有一个时 + 合成一个)就用它;没有就按材质名找眼睛高光(「目光」「ハイライト」「eye hi」等,头发高光除外),生成一个把这些 + 面各自收成一点的表情。高光直接画在瞳孔贴图里的模型做不了,日志里会说明。 + - `tongue`:吐舌,复制模型里的「舌出し」「ぺろっ」「べー」「tongueOut」等表情。 + +### 物理 → SpringBone + +目标是在 UniVRM、three-vrm 里的手感接近原生 VRM 模型,而不是复刻 MMD 的 Bullet 物理。参数按 VRM 官方和 VRoid +示例模型在同一套动作(待机、转身、走路、跑步、抬腿)下的表现校准。 + +- **拆链**:挂了物理刚体的骨从「自己动、父骨不动」处开始沿子骨走成链,分叉处另起一条;链尾补 `xxx_tail` 节点。 +- **分类**:挂在 hips 下、或从躯干垂到胯部以下的链算裙摆类;挂在手臂、腿上的算四肢配饰;其余(头发、胸前饰品等) + 算头发类。 +- **抽稀**:MMD 物理链切得很细,原生发束一般 3~7 节。头发类每节至少约 12 cm;裙摆类保留得密一些,因为 + SpringBone 只在关节点检测碰撞,节太稀腿会从关节之间穿过去。 +- **硬度**:SpringBone 的 stiffness 不随节长缩放,所以按「每帧回正的角度」换算:头发类软、裙摆类硬(撑住造型、 + 少穿模)、挂在手臂上的链介于两者之间,并限制在 2~10 之间。 +- **阻力和重力**:阻力 0.6;重力头发类 0(加了会把散开的发型拉垂),裙摆类 0.1(抬腿后裙片落回腿上)。 +- **短链不模拟**:总长不足 5 cm 的链和很短的四肢配饰(鞋带、手肘吊坠)跟着骨骼刚性移动,否则只会在末端高频颤动。 +- **center = 模型根节点**:在模型自身的空间里模拟,人物整体移动(走路的根运动)时头发、裙摆不会被甩到身后、 + 压到腿上;需要「走路时头发往后飘」时用 `--no-spring-center`。 +- **碰撞**:跟随骨骼的刚体转成碰撞体,按 PMX 的碰撞组 / 掩码决定每条链和哪些碰撞体碰撞。静止时就压在碰撞体 + 里的那几节缩小半径,免得一开始模拟就被弹开;挂在手臂上的链不碰撞。 +- **链间横向关节**:PMX 裙摆常用横向关节把相邻的链连成一片,SpringBone 无法表达,只能舍弃(日志提示数量)。 + 为了不让腿从两条链之间把裙子劈开,每条裙摆链配一份朝裙片法线方向平移过的腿部碰撞体,被腿碰到时整片沿法线 + 方向移动。 +- **模型没有物理时**(FBX 等转来的模型常见):按骨骼名和骨架结构自动补头发、裙摆、袖子、飘带、尾巴的链, + 身体自动加碰撞体(`--no-auto-spring` 关掉)。 + +手感不合适时,先用 `--spring-stiffness` 整体调;导入 Unity 后也可以在 UniVRM 里逐条调,或者用界面的「调整」面板。 + +**VRM 0.x**:先按上面的规则算出 1.0 的链,再换成 0.x 的结构。0.x 只列每组的根骨,根骨下面整棵子树都会摆动, +每组只有一套参数,碰撞体只有球,所以: + +- 只是跟着关节转的骨(被抽稀掉的中间节、链末端的配饰)把权重并到那个关节上、节点去掉,动起来和 1.0 一样; + 0.x 文件里的骨因此比 1.0 少。每个关节的下一节排在第一个子节点(0.x 用它定这一节的方向)。 +- 一条链一组。从别的链上分叉出来的链并入上层链的组(不然会被模拟两次);组内的碰撞体按关节数多数决定。 +- 硬度、阻尼、重力、碰撞半径取组内的中位数;静止时会和碰撞体重叠的,给这一组配一个缩小的碰撞体。 +- 胶囊碰撞体沿轴线每隔一个半径换成一个球。 + +## 已知限制 + +1. **VRM 0.x 的物理**比 1.0 粗一些:每组一套参数和一个碰撞半径、碰撞体只有球(见上文)。 +2. **物理**是近似换算:链间横向关节舍弃,整片裙子的联动不如原 PMX;腿抬得很高时裙摆最上一圈和大腿根部会有少量 + 重叠(原生 VRM 模型同样如此)。 +3. **材质**:乘算球面贴图、共享 toon07~10 没有对应;材质表情只转换显示颜色和透明度。 +4. **骨骼表情**按静止姿势和线性蒙皮烘焙,不经过 IK;权重在 0 和 1 之间时和 MMD 里略有差别(MMD 是旋转插值)。 +5. **T-pose** 用线性蒙皮重摆,肩部权重混合区在大角度时会轻微收缩;拇指要转 20~35°,虎口处会有少量拉伸。 + 拇指指甲的侧向朝向从骨骼位置看不出来,只摆方向。 +6. **表情预设**按名字对应和组合;名字都认不出的模型组合不出来,可以在界面的「调整」里手动指定。 + +## 授权信息 + +VRM meta 默认写成最保守的授权:需要署名、禁止再分发、禁止修改、仅限个人非商业使用,可以在界面的「VRM 信息」 +里改。**转换前请确认你有权使用该模型**,工具不会替你做版权检查。 diff --git a/formats/__init__.py b/formats/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/formats/archive.py b/formats/archive.py new file mode 100644 index 0000000..57e5adc --- /dev/null +++ b/formats/archive.py @@ -0,0 +1,257 @@ +# -*- coding: utf-8 -*- +"""zip 以外的压缩包:7z / rar / tar(.tar .tar.gz .tgz .tar.bz2 .tar.xz)。 + + kind(path) → "7z" / "rar" / "tar" / None(分卷包只认第一卷) + extract(path, dest) → 解出的文件数;解不了抛 RuntimeError(说明原因和怎么办) + tools() → 找到的解压工具(界面显示用) + +tar 用 Python 自带的 tarfile。7z / rar 没有可靠的纯 Python 实现,借用电脑上已有的解压工具, +按顺序找: + 1. 7-Zip(7z.exe / 7za / 7zz) 7z、rar 都行 + 2. WinRAR(UnRAR.exe / Rar.exe) rar(新版也能解 7z,失败了再换下一个) + 3. Bandizip(bz.exe) 7z、rar 都行 + 4. Windows 自带的 tar.exe(bsdtar / libarchive) + Windows 11 的版本 7z(含 LZMA)和 rar / rar5 都能解;Windows 10 的老版本解不了 LZMA 的 7z。 + 它按系统的 ANSI 编码处理文件名:简体中文系统上中文、假名没问题,GBK 里没有的字(emoji 等) + 会解压失败 + 5. py7zr(装了才用,只管 7z) +都不行时提示装 7-Zip。 + +安全:只解到 dest 里(工具自己会去掉绝对路径和 ..;解完再检查一遍,跑到外面的文件删掉), +不解链接;有密码的包不会卡住等输入(stdin 关掉、给 7-Zip 一个假密码),直接报错。 +""" +import os +import re +import shutil +import subprocess +import sys +import tarfile + +_TAR = (".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tbz", ".tar.xz", ".txz") +EXTS = (".7z", ".rar") + _TAR # 文件对话框的过滤、拖放识别都用这个 +_NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0 + + +def kind(path): + """→ "7z" / "rar" / "tar" / None。分卷包(.part2.rar、.7z.002、.r00)只认第一卷。""" + n = os.path.basename(path).lower() + m = re.search(r"\.part(\d+)\.rar$", n) + if m: + return "rar" if int(m.group(1)) == 1 else None + if n.endswith(".rar"): + return "rar" + m = re.search(r"\.7z\.(\d{3})$", n) + if m: + return "7z" if int(m.group(1)) == 1 else None + if n.endswith(".7z"): + return "7z" + if n.endswith(_TAR): + return "tar" + return None + + +# ---- 找工具 + +def _reg_paths(): + """注册表里 7-Zip / WinRAR / Bandizip 的安装目录。""" + if sys.platform != "win32": + return [] + import winreg + out = [] + for key, vals in ((r"SOFTWARE\7-Zip", ("Path64", "Path")), + (r"SOFTWARE\WinRAR", ("exe64", "exe32")), + (r"SOFTWARE\Bandizip", ("ProgramFolder",))): + for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER): + for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY): + try: + with winreg.OpenKey(hive, key, 0, winreg.KEY_READ | view) as k: + for v in vals: + try: + p = winreg.QueryValueEx(k, v)[0] + except OSError: + continue + if p: + out.append(os.path.dirname(p) if p.lower().endswith(".exe") else p) + except OSError: + continue + return out + + +def _find(names, dirs): + for d in dirs: + for n in names: + p = os.path.join(d, n) + if os.path.isfile(p): + return p + for n in names: + p = shutil.which(n) + if p: + return p + return None + + +def _bsdtar(): + """Windows 自带的 tar.exe 是 bsdtar;Git 带的 GNU tar 解不了 7z / rar,不能用 PATH 里的。""" + cands = [] + if sys.platform == "win32": + cands.append(os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "tar.exe")) + for n in ("bsdtar",): + p = shutil.which(n) + if p: + cands.append(p) + for p in cands: + if not os.path.isfile(p): + continue + try: + r = subprocess.run([p, "--version"], capture_output=True, timeout=10, + stdin=subprocess.DEVNULL, creationflags=_NO_WINDOW) + except (OSError, subprocess.SubprocessError): + continue + if b"bsdtar" in r.stdout or b"libarchive" in r.stdout: + return p + return None + + +_TOOLS = None + + +def tools(refresh=False): + """→ {"7z": 路径, "unrar": 路径, "bandizip": 路径, "bsdtar": 路径, "py7zr": bool}(找不到为 None)。""" + global _TOOLS + if _TOOLS is None or refresh: + pf = [os.environ.get(k) for k in ("ProgramW6432", "ProgramFiles", "ProgramFiles(x86)")] + pf = [p for p in pf if p] + reg = _reg_paths() + try: + import py7zr # noqa: F401 + has_py7zr = True + except Exception: # noqa: BLE001 + has_py7zr = False + _TOOLS = { + "7z": _find(("7z.exe", "7za.exe", "7zz.exe", "7z", "7za", "7zz"), + reg + [os.path.join(p, "7-Zip") for p in pf]), + "unrar": _find(("UnRAR.exe", "Rar.exe", "unrar", "rar"), + reg + [os.path.join(p, "WinRAR") for p in pf]), + "bandizip": _find(("bz.exe",), reg + [os.path.join(p, "Bandizip") for p in pf]), + "bsdtar": _bsdtar(), + "py7zr": has_py7zr, + } + return _TOOLS + + +# ---- 解压 + +def _count_and_check(dest): + """解完检查:不在 dest 里的、链接都删掉,返回普通文件数。""" + root = os.path.realpath(dest) + n = 0 + for d, dirs, files in os.walk(dest): + for name in list(dirs) + files: + p = os.path.join(d, name) + if os.path.islink(p) or not os.path.realpath(p).startswith(root + os.sep): + if os.path.isdir(p) and not os.path.islink(p): + shutil.rmtree(p, ignore_errors=True) + else: + try: + os.remove(p) + except OSError: + pass + if name in dirs: + dirs.remove(name) + elif name in files: + n += 1 + return n + + +def _safe_tar(path, dest): + n = 0 + root = os.path.realpath(dest) + with tarfile.open(path) as tf: + for m in tf: + if not m.isfile(): # 目录随文件建;链接、设备文件不解 + continue + parts = [p for p in m.name.replace("\\", "/").split("/") if p not in ("", ".", "..")] + if parts and ":" in parts[0]: + parts = parts[1:] + if not parts: + continue + target = os.path.join(dest, *parts) + if not os.path.realpath(target).startswith(root + os.sep): + continue + os.makedirs(os.path.dirname(target), exist_ok=True) + src = tf.extractfile(m) + if src is None: + continue + with src, open(target, "wb") as f: + shutil.copyfileobj(src, f) + n += 1 + return n + + +def _run(cmd, timeout=1800): + try: + r = subprocess.run(cmd, capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL, + creationflags=_NO_WINDOW) + except subprocess.TimeoutExpired: + return False, "超时" + except OSError as e: + return False, str(e) + msg = (r.stderr or r.stdout or b"").decode("utf-8", "replace").strip() + if not msg and r.returncode: + msg = (r.stdout or b"").decode(sys.getfilesystemencoding() or "utf-8", "replace").strip() + return r.returncode == 0, msg[-400:] + + +def _py7zr(path, dest): + import py7zr + with py7zr.SevenZipFile(path, "r") as z: + z.extractall(dest) + + +def extract(path, dest, log=None): + """把 7z / rar / tar 压缩包解到 dest,返回解出的文件数。""" + k = kind(path) + if k is None: + raise ValueError("不是支持的压缩包:%s" % os.path.basename(path)) + os.makedirs(dest, exist_ok=True) + if k == "tar": + return _safe_tar(path, dest) + t = tools() + src = os.path.abspath(path) + tries = [] + if t["7z"]: + # -p 给个假密码:有密码的包直接失败,不会停在「输入密码」 + tries.append(("7-Zip", [t["7z"], "x", "-y", "-bd", "-pnopassword", "-o" + dest, "--", src])) + if t["unrar"] and k == "rar": + tries.append(("WinRAR", [t["unrar"], "x", "-y", "-o+", "-p-", "-idq", src, dest + os.sep])) + if t["bandizip"]: + tries.append(("Bandizip", [t["bandizip"], "x", "-y", "-o:" + dest, src])) + if t["bsdtar"]: + tries.append(("tar", [t["bsdtar"], "-xf", src, "-C", dest])) + errors = [] + for name, cmd in tries: + ok, msg = _run(cmd) + n = _count_and_check(dest) + if ok and n: + if log: + log("用 %s 解压" % name, "info") + return n + errors.append("%s:%s" % (name, msg or "没有解出文件")) + for x in os.listdir(dest): # 解了一半的清掉再换下一个工具 + p = os.path.join(dest, x) + shutil.rmtree(p, ignore_errors=True) if os.path.isdir(p) else os.remove(p) + if k == "7z" and t["py7zr"]: + try: + _py7zr(src, dest) + n = _count_and_check(dest) + if n: + return n + except Exception as e: # noqa: BLE001 + errors.append("py7zr:%s" % e) + hint = ("没有找到能解 %s 的工具,请安装 7-Zip(https://www.7-zip.org/)后重试," + "或者先手动解压再把文件夹拖进来" % k) + if errors: + hint = ("解压失败。常见原因:有密码、分卷不全、文件损坏;只用 Windows 自带的 tar 时," + "文件名里有系统编码(简体中文系统是 GBK)以外的字符、或者是 Windows 10 上 LZMA 压缩的 7z " + "都解不了——装 7-Zip(https://www.7-zip.org/)可以解决:\n " + "\n ".join(errors)) + raise RuntimeError(hint) diff --git a/formats/fbx_reader.py b/formats/fbx_reader.py new file mode 100644 index 0000000..d3c0faa --- /dev/null +++ b/formats/fbx_reader.py @@ -0,0 +1,411 @@ +"""Standalone FBX (7.x) reader —— 二进制 + ASCII 两种都读。 + +No Autodesk FBX SDK, no Blender. Implements the record tree + property +decoding, including zlib / delta / zigzag compressed arrays. + +2026-09-18 起也支持 **ASCII FBX**(文本版):工程新加的 fbxout.py 写的就是 +ASCII(文本好调试、任何 DCC 都认),不补这条读取路径的话,自己写出来的 FBX +拖回本工具会直接「not a binary FBX」,也没法做往返自校验。 +两种格式解析成同一棵 FbxNode 树,下游(fbx2pmx / 预览)完全无感—— +尤其注意数组:二进制里 `Vertices` 的属性就是那个长数组(props[0] = [..]), +ASCII 里数据写在子节点 `a` 里,所以解析时要把 `*N { a: ... }` 折叠成同样的 +「props[0] = 数组」,否则 fbx2pmx 的 `g.get("Vertices").props[0]` 会拿到垃圾。 +""" +import os +import struct +import zlib + + +class FbxNode: + __slots__ = ("name", "props", "children", "ps", "plen", "cls") + + def __init__(self, name, props, children, ps=0, plen=0): + self.name = name + self.props = props + self.children = children + self.ps = ps # absolute offset of the property list + self.plen = plen # byte length of the property list + self.cls = props[2] if len(props) > 2 and isinstance(props[2], str) else name + + def find(self, name): + return [c for c in self.children if c.name == name] + + def get(self, name): + for c in self.children: + if c.name == name: + return c + return None + + def walk(self): + yield self + for c in self.children: + for n in c.walk(): + yield n + + def __repr__(self): + return "<%s props=%d kids=%d>" % (self.name, len(self.props), + len(self.children)) + + +def _read_prop(d, p): + t = chr(d[p]) + p += 1 + if t == "Y": + v = struct.unpack_from("> 1) ^ -(v[i] & 1) + v[i] += v[i - 1] + else: + v = list(raw) + else: + raise ValueError("unknown property type %r at %d" % (t, p)) + return v, p + + +def _read_node(d, p, wide): + if wide: + end, nprop, plen = struct.unpack_from("= 7500 + p = 27 + top = [] + while p < len(d) - 32: + try: + node, p2 = _read_node(d, p, wide) + except Exception: + break + if node is None: + break + top.append(node) + if p2 <= p: + break + p = p2 + return ver, top + + +# --------------------------------------------------------------- ASCII FBX -- +class _Arr(object): + """ASCII 里的 `*N` 数组标记,解析完用子节点 a 的数据替换掉。""" + + __slots__ = ("n",) + + def __init__(self, n): + self.n = n + + +class _AsciiParser(object): + def __init__(self, text): + self.s = text + self.i = 0 + self.n = len(text) + + # -- 词法 + def _skip(self): + """跳过空白和 `;` 行注释(换行也跳过)。""" + s, n = self.s, self.n + while self.i < n: + c = s[self.i] + if c in " \t\r\n": + self.i += 1 + elif c == ";": + j = s.find("\n", self.i) + self.i = n if j < 0 else j + 1 + else: + break + + def _skip_inline(self): + while self.i < self.n and self.s[self.i] in " \t": + self.i += 1 + + def _name(self): + s, j = self.s, self.i + while j < self.n and s[j] not in ":{ \t\r\n": + j += 1 + nm = s[self.i:j] + self.i = j + return nm + + def _string(self): + s, j = self.s, self.i + 1 + buf = [] + while j < self.n: + c = s[j] + if c == "\\": + if j + 1 < self.n: + buf.append(s[j + 1]) + j += 2 + continue + if c == '"': + j += 1 + break + buf.append(c) + j += 1 + self.i = j + return "".join(buf) + + def _number(self): + s, j = self.s, self.i + while j < self.n and s[j] in "+-.0123456789eE": + j += 1 + tok = s[self.i:j] + self.i = j + try: + return float(tok) if any(c in tok for c in ".eE") else int(tok) + except ValueError: + return 0 + + def _token(self): + s, j = self.s, self.i + while j < self.n and s[j] not in " \t\r\n,{}": + j += 1 + tok = s[self.i:j] + self.i = max(j, self.i + 1) + return tok + + # -- 语法 + def _array_block(self): + """读 `{ a: v,v,v a: v,v ... }` 这种数组块,返回展平的数值列表。 + + 实际存在的三种写法都要吃下(实测踩过): + * Autodesk 风格:整个数组一条 `a: ...` 行,可能长达几 MB; + * 分行且每行重复行标签:`a: v,v` 换行 `a: v,v`(本工程的写出器这样写); + * 分行但只有第一行有标签,后续行直接续数(可能以逗号开头)。 + """ + vals = [] + self._skip() + if not (self.i < self.n and self.s[self.i] == "{"): + return vals + self.i += 1 + while True: + self._skip() + if self.i >= self.n or self.s[self.i] == "}": + break + # 行首可能是行标签(`a`)也可能直接就是数值:先看一眼再决定 + save = self.i + self._name() + self._skip_inline() + if self.i < self.n and self.s[self.i] == ":": + self.i += 1 + else: + self.i = save + # 读这一行的数值,换行即止 + while True: + self._skip_inline() + if self.i >= self.n: + break + c = self.s[self.i] + if c in "\r\n}": + break + if c == ",": + self.i += 1 + continue + if c == '"': + vals.append(self._string()) + elif c in "+-.0123456789": + vals.append(self._number()) + else: + self._token() # 认不出的 token 丢掉,别污染数值 + if self.i < self.n and self.s[self.i] == "}": + self.i += 1 + return vals + + def node(self): + """解析一个节点。 + + 普通节点的属性必须写在同一行 —— 遇到换行即终止属性列表,否则会把 + 下一行的兄弟节点名字吃进自己的 props。真正会跨行的只有数组数据, + 那部分由 `_array_block()` 专门处理。 + """ + self._skip() + if self.i >= self.n or self.s[self.i] == "}": + return None + name = self._name() + if not name: + return None + self._skip() + if self.i < self.n and self.s[self.i] == ":": + self.i += 1 + props = [] + counts = [] + rows = [] + while True: + self._skip_inline() + if self.i >= self.n: + break + c = self.s[self.i] + if c in "{\r\n}": + break + if c == ",": + self.i += 1 + continue + if c == '"': + props.append(self._string()) + elif c == "*": + self.i += 1 + n_arr = self._number() + counts.append(n_arr) + props.append(_Arr(n_arr)) + rows.extend(self._array_block()) + elif c in "+-.0123456789": + props.append(self._number()) + else: + props.append(self._token()) + has_arr = any(isinstance(p, _Arr) for p in props) + children = [] + self._skip() + if self.i < self.n and self.s[self.i] == "{": + self.i += 1 + while True: + mark = self.i + # 数组块的 `{...}` 已经被 _array_block 吃掉,这里剩下的都是 + # 普通单行属性子节点。 + ch = self.node() + if ch is None: + break + children.append(ch) + if self.i <= mark: # 防死循环 + break + self._skip() + if self.i < self.n and self.s[self.i] == "}": + self.i += 1 + if has_arr: + # 按声明长度把行数据切回各个数组属性;只有一个数组时整份给它 + # (`*N` 与行数据不一致时以行数据为准,宁可多也别丢)。 + filled = [] + off = 0 + k = 0 + for p in props: + if isinstance(p, _Arr): + if len(counts) > 1: + n = counts[k] if k < len(counts) else 0 + filled.append(rows[off:off + n]) + off += n + else: + filled.append(rows) + k += 1 + else: + filled.append(p) + props = filled + return FbxNode(name, props, children) + + +def _load_ascii(path): + with open(path, "r", encoding="utf-8-sig", errors="replace") as f: + text = f.read() + p = _AsciiParser(text) + top = [] + while True: + mark = p.i + nd = p.node() + if nd is None: + break + top.append(nd) + if p.i <= mark: + break + ver = 7400 + for nd in top: + if nd.name == "FBXHeaderExtension": + for c in nd.children: + if c.name == "FBXVersion" and c.props: + try: + ver = int(c.props[0]) + except (TypeError, ValueError): + pass + if not top: + raise ValueError("既不是二进制 FBX,也解析不出 ASCII FBX 节点:%s" % path) + return ver, top + + +def load(path): + """返回 (version, [顶层节点])。二进制 / ASCII 自动识别。""" + with open(path, "rb") as f: + head = f.read(23) + if head[:20] == b"Kaydara FBX Binary ": + return _load_binary(path) + return _load_ascii(path) + + +def index_by_id(nodes): + """Collect every node that carries an (id, name) pair, keyed by id.""" + out = {} + for n in nodes: + if n.props and isinstance(n.props[0], int) and len(n.props) >= 3: + out[n.props[0]] = n + return out diff --git a/formats/fbxout.py b/formats/fbxout.py new file mode 100644 index 0000000..35c86c7 --- /dev/null +++ b/formats/fbxout.py @@ -0,0 +1,688 @@ +# -*- coding: utf-8 -*- +"""fbxout.py - 把网格 + 骨骼 + 蒙皮写成 **ASCII FBX 7.4**(纯标准库)。 + +为什么要 ASCII:二进制 FBX 要做 deflate + 节点表 + 32/64 位偏移宽度, +坑多且难调试(本工程读 FBX 时就踩过 7400=32 位偏移的坑)。ASCII FBX 是 +纯文本,任何 DCC(Blender / Maya / 3ds Max / Unity / UE)都认,出问题能直接 +肉眼看字节。 + +坐标系(与工程的 FBX 读取路径**互为逆操作**,可自校验) + fbx = (x, y, -z)_pmx —— 即读取侧的「Z 取反」 + PMX 左手系、fbx 右手系 ⇒ 手性和绕序一起翻,所以三角形要**反转绕序**。 + GlobalSettings 里如实声明 UpAxis=Y / FrontAxis=Z(sign +1) / CoordAxis=X, + 这样 Blender、Maya 之流会按声明把模型摆正(角色在 Blender 里仍朝 -Y)。 + 用本工程的 FBX→PMX 路径(Z 轴翻转=开)再读回来,应当与源 PMX 一致。 + +蒙皮约定(FBX SDK 的老规矩) + 对每个 Cluster:TransformLink = 绑定姿势下骨骼的世界矩阵 W, + Transform = W⁻¹ + 于是 TransformLink · Transform = I ⇒ 顶点本来就在绑定姿势里,静止时不变形; + 摆姿势时按 A_bone · (Transform · v) 的公式走。绑定姿势的骨骼只有平移 + (PMX 的骨骼本来就不带旋转),所以两个矩阵都是纯平移。 + 矩阵按**行主序**写 16 个数,平移落在最后一行(第 13/14/15 个)。 + +用法(也可直接当命令行工具,接 .pmx): + python fbxout.py model.pmx -o model.fbx +""" + +import argparse +import os +import sys +import time + +_HERE = os.path.dirname(os.path.abspath(__file__)) + + +def _log_default(msg, tag=None): + try: + print(msg) + except UnicodeEncodeError: + print(msg.encode("utf-8", "replace").decode("ascii", "replace")) + + +def _f(v): + """FBX 里的浮点写法:够短又不丢精度。""" + x = float(v) + if x == int(x) and abs(x) < 1e15: + return str(int(x)) + return "%.6g" % x + + +def _arr(w, indent, values): + """把整个数组写成一条 `a: ...` 行。 + + Autodesk 自己的 ASCII FBX 就是这么写的 —— 顶点表几 MB 全塞在一行里很正常。 + 早期版本按固定条数换行、每行重复写一次 `a:` 标签,虽然也有工具这么干, + 但那样会让不少第三方解析器(以及本工程自己)在续行处多吃/漏吃数值, + 所以统一改成一条行最保险。 + """ + w("%sa: %s" % (indent, ",".join(values))) + + +def _esc(s): + return (s or "").replace("\\", "\\\\").replace('"', '\\"') + + +def _san(s): + """名字里的非 ASCII 会被某些工具当成编码问题,统一换成下划线。""" + out = [] + for ch in (s or ""): + out.append(ch if 32 < ord(ch) < 127 else "_") + nm = "".join(out).strip() or "unnamed" + return nm[:120] + + +def _name(prefix, s): + """带 `Class::` 命名空间的名字(FBX 里的传统写法)。""" + return "%s::%s" % (prefix, _san(s)) + + +def _clip(s, n=120): + """名字清洗:去掉控制字符(换行会破坏 FBX 的行结构)并截断。 + + 与 `_san` 不同,这里**保留非 ASCII** —— 表情名用日文/中文很常见, + 而 FBX 文本本身就是 UTF-8,SDK 与 Blender 都能正确解码。 + """ + s = (s or "").strip() + s = "".join(ch for ch in s if ord(ch) >= 32) + return s[:n] + + +class _Ids(object): + def __init__(self, start=1000000, step=100000): + self.n = start + self.step = step + + def block(self): + base = self.n + self.n += self.step + return base + + +def _weights_of(vertex): + """PMX 顶点 → [(骨骼下标, 权重)]。 + + PMX 的约定:wt=1(BDEF2) 只存 w1,w2 = 1-w1;wt=3(SDEF) 同 BDEF2; + wt=4(QDEF) 同 BDEF4。把补位权重丢掉,只留真正参与的点。 + """ + wt = vertex.get("wtype", 0) + bs = list(vertex.get("wbones") or []) + ws = list(vertex.get("wweights") or []) + out = [] + if wt in (0,) or not bs: + return [(bs[0] if bs else 0, 1.0)] + if wt in (1, 3): + w1 = ws[0] if ws else 1.0 + out = [(bs[0], w1), (bs[1] if len(bs) > 1 else bs[0], 1.0 - w1)] + else: # 2=BDEF4 / 4=QDEF + for k in range(min(len(bs), 4)): + w = ws[k] if k < len(ws) else 0.0 + if w > 1e-6: + out.append((bs[k], w)) + out = [(b, w) for b, w in out if w > 1e-6] + return out or [(0, 1.0)] + + +def export_model(path, verts, faces, materials, bones, morphs=None, + mirror_z=True, reverse_winding=True, tex_dir=None, log=None, + creator="ueformat2pmx", name=None, model_name="model", + flip_v=True): + """写出 ASCII FBX。 + + verts : PMX 顶点 dict 列表(pos/normal/uv/wtype/wbones/wweights) + faces : 展平的三角索引 + materials : PMX 材质 dict 列表(用 name/diffuse/tex) + bones : PMX 骨骼 dict 列表(用 name/pos/parent) + morphs : PMX 表情 dict 列表;kind=1(顶点表情)会写成 + BlendShape/BlendShapeChannel/Shape —— 只写真正动过的控制点, + 数值是**增量**(FBX 文件里 Shape 的 Vertices 就是这个语义)。 + 骨骼/UV/材质表情 FBX 装不下,跳过。 + model_name : 网格节点名(默认 "model",传模型名更友好) + flip_v : 是否把 UV 的 V 轴翻过来(**默认必须翻**,见下面注释) + 返回统计 dict。 + """ + _l = log or _log_default + sx = 1.0 + sz = -1.0 if mirror_z else 1.0 + if name: + model_name = name + model_name = _san(model_name) + + def xf(p): + return (p[0] * sx, p[1], p[2] * sz) + + nv = len(verts) + ntris = len(faces) // 3 + out = [] + w = out.append + + # ------------------------------------------------- 表情预处理(→ Shape)-- + # **FBX 文件里 Shape 的 Vertices 是「相对基础控制点的增量」,不是绝对坐标** + # (实测确认:写全 0 → 读回等于原网格;写基础坐标 → 读回是两倍)。 + # FBX SDK / Blender 读取时会给未列在 Indexes 里的控制点补 0 增量, + # 并把结果展开成与网格控制点等长的绝对坐标数组 —— 读取端因此**不需要** + # 知道我们只写了变化点,插件侧的 FbxShape.GetControlPointAt 拿到的就是 + # 与网格一一对应的绝对坐标。 + # 于是这里只写「真正动过的控制点」:本工程样本 161 个表情、每个约 600 点, + # 合计约 3 MB;若按全量写,光这一个模型就要 300 MB 以上。 + morph_shapes = [] + for mo in (morphs or []): + if int(mo.get("kind", 1)) != 1: + continue # 只搬顶点表情;骨骼/UV/材质表情 FBX 装不下 + pairs = {} + for vi, d in (mo.get("offsets") or []): + vi = int(vi) + if 0 <= vi < nv: + pairs[vi] = d + if pairs: + morph_shapes.append((mo, pairs)) + n_shape = len(morph_shapes) + n_attr = len(bones) + 1 # 每根骨骼一个 + 网格一个 + + # 每根骨骼影响哪些顶点(Cluster 用;顺带决定 Definitions 里 Deformer 的数量) + per_bone = {} + for vi, v in enumerate(verts): + for b, wt in _weights_of(v): + if 0 <= b < len(bones): + per_bone.setdefault(b, []).append((vi, wt)) + n_cluster = len(per_bone) + n_def = 1 + n_cluster + (1 + n_shape if n_shape else 0) + + hdr_axis = "Z" if mirror_z else "-Z" + _l("FBX:%d 顶点 · %d 三角面 · %d 骨骼 · %d 材质(ASCII 7.4,%s-up,前方 %s)%s" + % (nv, ntris, len(bones), len(materials), "Y", hdr_axis, + ("· %d 个顶点表情写入 BlendShape" % n_shape) if n_shape else "")) + + ids = _Ids() + gid = ids.block() # Geometry + mid = ids.block() # Mesh Model + bone_id0 = ids.block() # 骨骼 Model 段 + mat_id0 = ids.block() # Material 段 + tex_id0 = ids.block() # Texture / Video 段 + def_id0 = ids.block() # Deformer 段(Skin + Cluster) + na_id0 = ids.block() # NodeAttribute 段(骨骼 + 网格) + morph_id0 = ids.block() # BlendShape / BlendShapeChannel / Shape 段 + bone_model = [bone_id0 + i for i in range(max(len(bones), 1))] + + # ------------------------------------------------------------ 头 + 设置 -- + w("; FBX 7.4.0 project file") + w("; 由 %s 生成(纯 Python,ASCII FBX)" % creator) + w("; ----------------------------------------------------") + w("") + t = time.localtime() + w("FBXHeaderExtension: {") + w("\tFBXHeaderVersion: 1003") + w("\tFBXVersion: 7400") + w("\tCreationTimeStamp: {") + w("\t\tVersion: 1000") + w("\t\tYear: %d" % t.tm_year) + w("\t\tMonth: %d" % t.tm_mon) + w("\t\tDay: %d" % t.tm_mday) + w("\t\tHour: %d" % t.tm_hour) + w("\t\tMinute: %d" % t.tm_min) + w("\t\tSecond: %d" % t.tm_sec) + w("\t\tMillisecond: 0") + w("\t}") + w('\tCreator: "%s"' % creator) + w("}") + w("") + w("GlobalSettings: {") + w("\tVersion: 1000") + w("\tProperties70: {") + w('\t\tP: "UpAxis", "int", "Integer", "",1') + w('\t\tP: "UpAxisSign", "int", "Integer", "",1') + w('\t\tP: "FrontAxis", "int", "Integer", "",2') + w('\t\tP: "FrontAxisSign", "int", "Integer", "",%d' + % (1 if mirror_z else -1)) + w('\t\tP: "CoordAxis", "int", "Integer", "",0') + w('\t\tP: "CoordAxisSign", "int", "Integer", "",1') + w('\t\tP: "OriginalUpAxis", "int", "Integer", "",1') + w('\t\tP: "OriginalUpAxisSign", "int", "Integer", "",1') + w('\t\tP: "UnitScaleFactor", "double", "Number", "",1') + w('\t\tP: "OriginalUnitScaleFactor", "double", "Number", "",1') + w('\t}') + w("}") + w("") + + # ------------------------------------------------------------ Definitions -- + n_tex = sum(1 for m in materials + if isinstance(m.get("tex"), int) and m["tex"] >= 0) + w("Definitions: {") + w("\tVersion: 100") + # Count = 下面 ObjectType 块的**个数**:GlobalSettings / Model / Geometry / + # Material / Deformer / NodeAttribute,有贴图时再加 Texture 与 Video。 + w("\tCount: %d" % (6 + (2 if n_tex else 0))) + w('\tObjectType: "GlobalSettings" {') + w("\t\tCount: 1") + w("\t}") + w('\tObjectType: "Model" {') + w("\t\tCount: %d" % (1 + len(bones))) + w("\t}") + w('\tObjectType: "Geometry" {') + w("\t\tCount: %d" % (1 + n_shape)) + w("\t}") + # NodeAttribute 段不能省:**Model 的「类型」是由它挂着的 NodeAttribute + # 对象决定的**,Model 行里的 "LimbNode" 只是个字符串。 + # 少了它,FBX SDK 侧 node.GetNodeAttribute() 返回 null(网格还能靠 + # Geometry 连接被 SDK 兜回来,骨骼却没有任何线索),任何按 SDK API + # 判断骨骼的导入器都会一根骨头都收不到 —— PE 的 FBX 导入插件就是这样 + # 在 PE 里「只有网格、没有骨骼」的。 + w('\tObjectType: "NodeAttribute" {') + w("\t\tCount: %d" % n_attr) + w("\t}") + if n_tex: + w('\tObjectType: "Video" {') + w("\t\tCount: %d" % n_tex) + w("\t}") + w('\tObjectType: "Texture" {') + w("\t\tCount: %d" % n_tex) + w("\t}") + w('\tObjectType: "Material" {') + w("\t\tCount: %d" % max(len(materials), 1)) + w("\t}") + w('\tObjectType: "Deformer" {') + w("\t\tCount: %d" % n_def) + w("\t}") + w("}") + w("") + + # ---------------------------------------------------------------- Objects -- + w("Objects: {") + + # Geometry + w('\tGeometry: %d, "%s", "Mesh" {' % (gid, _name("Geometry", "mesh"))) + w("\t\tVertices: *%d {" % (nv * 3)) + _arr(w, "\t\t\t", [_f(c) for v in verts for c in xf(v["pos"])]) + w("\t\t} ") + # 三角形的顶点顺序。**PVI / 法线 / UVIndex 三处必须用同一个顺序**: + # 法线与 UV 都是 ByPolygonVertex(每个多边形顶点一项,按多边形顶点顺序 + # 一一对应)。镜像手性时绕序要反转,但如果只反 PVI、不反 UVIndex 与 + # 法线,等于把每个三角形首末两个角的 UV/法线对调 —— 几何形状完全正确、 + # 贴图却整片错乱(用户报的「FBX 材质显示不对、同时导出的 PMX 正常」 + # 就是这个:实测 115563/115563 个三角形全部首末对调)。 + tris = [] + for t2 in range(ntris): + a, b, c = faces[t2 * 3], faces[t2 * 3 + 1], faces[t2 * 3 + 2] + if reverse_winding: + a, b, c = c, b, a + tris.append((a, b, c)) + + w("\t\tPolygonVertexIndex: *%d {" % (ntris * 3)) + buf = [] + for a, b, c in tris: + buf.append("%d,%d,%d" % (a, b, -(c + 1))) # 末位取反 = 多边形结束 + _arr(w, "\t\t\t", buf) + w("\t\t} ") + w("\t\tGeometryVersion: 124") + + # 法线:ByPolygonVertex(最兼容的写法) + w("\t\tLayerElementNormal: 0 {") + w("\t\t\tVersion: 101") + w('\t\t\tName: ""') + w('\t\t\tMappingInformationType: "ByPolygonVertex"') + w('\t\t\tReferenceInformationType: "Direct"') + w("\t\t\tNormals: *%d {" % (ntris * 9)) + buf = [] + for tri in tris: + for vi in tri: + n = verts[vi]["normal"] if vi < nv else (0.0, 1.0, 0.0) + buf.append("%s,%s,%s" % (_f(n[0] * sx), _f(n[1]), _f(n[2] * sz))) + _arr(w, "\t\t\t\t", buf) + w("\t\t\t} ") + w("\t\t}") + + # UV:ByPolygonVertex + IndexToDirect + # **V 轴必须翻**:MMD / PMX / UE 的 UV 原点在**左上**(v 向下),而 FBX 的 + # 通行约定(Autodesk / Blender / Maya)原点在**左下**(v 向上)。原样写出去, + # 下游按 v 向上解释就把贴图上下颠倒了 —— 表现为形状完全正确、图案整体错位 + # (脸上出现嘴/脖子处的图、腿脚出现靴子、头发出现大片黑斑)。本工程的 + # fbx2pmx 读 FBX 时同样做 `1.0 - v`,两边对称,导入导出往返才能对上。 + w("\t\tLayerElementUV: 0 {") + w("\t\t\tVersion: 101") + w('\t\t\tName: "UVChannel_1"') + w('\t\t\tMappingInformationType: "ByPolygonVertex"') + w('\t\t\tReferenceInformationType: "IndexToDirect"') + w("\t\t\tUV: *%d {" % (nv * 2)) + buf = [] + for v in verts: + u = v.get("uv") or (0.0, 0.0) + vv = (1.0 - u[1]) if flip_v else u[1] + buf.append("%s,%s" % (_f(u[0]), _f(vv))) + _arr(w, "\t\t\t\t", buf) + w("\t\t\t} ") + w("\t\t\tUVIndex: *%d {" % (ntris * 3)) + buf = [] + for tri in tris: + buf.append("%d,%d,%d" % tri) + _arr(w, "\t\t\t\t", buf) + w("\t\t\t} ") + w("\t\t}") + + # 逐面材质 + if materials: + w("\t\tLayerElementMaterial: 0 {") + w("\t\t\tVersion: 101") + w('\t\t\tName: ""') + w('\t\t\tMappingInformationType: "ByPolygon"') + w('\t\t\tReferenceInformationType: "IndexToDirect"') + w("\t\t\tMaterials: *%d {" % ntris) + per_mat = [] + for mi, mt in enumerate(materials): + per_mat.extend([mi] * (max(0, int(mt.get("faces", 0))) // 3)) + if len(per_mat) < ntris: + per_mat.extend([0] * (ntris - len(per_mat))) + del per_mat[ntris:] + _arr(w, "\t\t\t\t", [str(x) for x in per_mat]) + w("\t\t\t} ") + w("\t\t}") + + w("\t\tLayer: 0 {") + w("\t\t\tVersion: 100") + w('\t\t\tLayerElement: {') + w('\t\t\t\tType: "LayerElementNormal"') + w("\t\t\t\tTypedIndex: 0") + w("\t\t\t}") + w('\t\t\tLayerElement: {') + w('\t\t\t\tType: "LayerElementUV"') + w("\t\t\t\tTypedIndex: 0") + w("\t\t\t}") + if materials: + w('\t\t\tLayerElement: {') + w('\t\t\t\tType: "LayerElementMaterial"') + w("\t\t\t\tTypedIndex: 0") + w("\t\t\t}") + w("\t\t}") + w("\t}") + + # 骨骼:Model(LimbNode),Lcl Translation = 相对父骨骼的位置(绑定姿势只有平移) + bpos = [xf(b["pos"]) for b in bones] + for bi, b in enumerate(bones): + p = b.get("parent", -1) + if 0 <= p < len(bones): + d = (bpos[bi][0] - bpos[p][0], bpos[bi][1] - bpos[p][1], + bpos[bi][2] - bpos[p][2]) + else: + d = bpos[bi] + # 骨名写**裸名**、不加 `Model::` 前缀。本工程自己的 FBX→PMX 读取路径 + # 会把 Model 名字原样当骨名用,加前缀会让「导出再读回」的骨名变成 + # `Model::Bip001Pelvis`,导进 Blender / UE 看着也脏。 + w('\tModel: %d, "%s", "LimbNode" {' % (bone_model[bi], _san(b["name"]))) + w("\t\tVersion: 232") + w("\t\tProperties70: {") + w('\t\t\tP: "InheritType", "enum", "", "",1') + # **DefaultAttributeIndex 不能省**(网格 Model 一直有它,骨骼以前漏了): + # FBX SDK 只在 Model 显式声明这个属性之后,才会把 "OO" 连接上来的 + # NodeAttribute 挂到该节点上;缺了它 node.GetNodeAttribute() 永远是 null。 + # 这正是「骨骼在 Blender 里看得见(Blender 自己解析文件,不看这个属性), + # 在 PE 的 FBX 导入插件里却一根都没有(插件走 FBX SDK 的 API)」的原因。 + # 实测:同一份文件只补这一行,eSkeleton 节点数 0 → 489。 + w('\t\t\tP: "DefaultAttributeIndex", "int", "Integer", "",0') + w('\t\t\tP: "Lcl Translation", "Lcl Translation", "", "A",%s,%s,%s' + % (_f(d[0]), _f(d[1]), _f(d[2]))) + w('\t\t\tP: "Lcl Rotation", "Lcl Rotation", "", "A",0,0,0') + w('\t\t\tP: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1') + w('\t\t}') + w('\t\tShading: T') + w('\t\tCulling: "CullingOff"') + w("\t}") + + # 网格节点 + w('\tModel: %d, "%s", "Mesh" {' % (mid, _san(model_name))) + w("\t\tVersion: 232") + w("\t\tProperties70: {") + w('\t\t\tP: "InheritType", "enum", "", "",1') + w('\t\t\tP: "DefaultAttributeIndex", "int", "Integer", "",0') + w("\t\t}") + w("\t\tShading: T") + w('\t\tCulling: "CullingOff"') + w("\t}") + + # 节点属性:骨骼 → Skeleton,网格 → Mesh。名字照 Autodesk 的习惯留空 + # (`"NodeAttribute::"`),类型由第三个字符串决定。 + for bi in range(len(bones)): + w('\tNodeAttribute: %d, "NodeAttribute::", "LimbNode" {' % (na_id0 + bi)) + w('\t\tTypeFlags: "Skeleton"') + w("\t}") + w('\tNodeAttribute: %d, "NodeAttribute::", "Mesh" {' % (na_id0 + len(bones))) + w('\t\tTypeFlags: "Mesh"') + w("\t\tGeometryVersion: 124") + w("\t}") + + # 材质(+ 贴图 Video/Texture) + mat_ids = [] + tex_ids = [] + for mi, mt in enumerate(materials or [{"name": "material_0", + "diffuse": (1.0, 1.0, 1.0, 1.0), + "tex": -1}]): + myid = mat_id0 + mi + mat_ids.append(myid) + diff = list(mt.get("diffuse") or (1.0, 1.0, 1.0, 1.0)) + alpha = diff[3] if len(diff) > 3 else 1.0 + w('\tMaterial: %d, "%s", "" {' % (myid, _name("Material", mt.get("name")))) + w("\t\tVersion: 102") + w('\t\tShadingModel: "phong"') + w("\t\tMultiLayer: 0") + w("\t\tProperties70: {") + w('\t\t\tP: "DiffuseColor", "Color", "", "A",%s,%s,%s' + % (_f(diff[0]), _f(diff[1]), _f(diff[2]))) + w('\t\t\tP: "DiffuseFactor", "Number", "", "A",1') + w('\t\t\tP: "TransparencyFactor", "Number", "", "A",%s' + % _f(1.0 - max(0.0, min(1.0, alpha)))) + w('\t\t\tP: "SpecularColor", "Color", "", "A",0,0,0') + w('\t\t\tP: "SpecularFactor", "Number", "", "A",0') + w('\t\t\tP: "ShininessExponent", "Number", "", "A",0') + w('\t\t\tP: "EmissiveColor", "Color", "", "A",0,0,0') + w('\t\t\tP: "AmbientColor", "Color", "", "A",0.5,0.5,0.5') + w("\t\t}") + w("\t}") + ti = mt.get("tex", -1) + if isinstance(ti, int) and ti >= 0: + tex_ids.append((mi, ti)) + + # 贴图(引用文本文件名,不内嵌二进制) + tex_files = {} + if tex_ids and tex_dir is not None: + folder_idx = {} + try: + for fn in os.listdir(tex_dir): + folder_idx.setdefault(fn.lower(), fn) + except OSError: + pass + for mi, ti in tex_ids: + vid = tex_id0 + mi * 2 + tid = vid + 1 + # 文件名由调用方通过 materials[i]["_tex_file"] 传入;没有就按序号找 + fn = materials[mi].get("_tex_file") + if not fn: + hits = [v for k, v in folder_idx.items() + if k.endswith(".png") and ("tex%02d" % ti) in k] + fn = hits[0] if hits else None + if not fn: + continue + rel = "textures/" + fn + tex_files[mi] = rel + w('\tVideo: %d, "Video::tex%d", "Clip" {' % (vid, mi)) + w("\t\tType: \"Clip\"") + w("\t\tProperties70: {") + w('\t\t\tP: "Path", "KString", "XRefUrl", "", "%s"' % _esc(rel)) + w("\t\t}") + w("\t\tUseMipMap: 0") + w('\t\tFilename: "%s"' % _esc(rel)) + w('\t\tRelativeFilename: "%s"' % _esc(rel)) + w("\t}") + w('\tTexture: %d, "Texture::tex%d", "" {' % (tid, mi)) + w('\t\tType: "TextureVideoClip"') + w("\t\tVersion: 202") + w('\t\tTextureName: "Texture::tex%d"' % mi) + w('\t\tMedia: "Video::tex%d"' % mi) + w('\t\tFileName: "%s"' % _esc(rel)) + w('\t\tRelativeFilename: "%s"' % _esc(rel)) + w("\t\tModelUVTranslation: 0,0") + w("\t\tModelUVScaling: 1,1") + w('\t\tTexture_Alpha_Source: "None"') + w("\t\tCropping: 0,0,0,0") + w("\t}") + + # 蒙皮:Skin + 每个骨骼一个 Cluster + skin_id = def_id0 + w('\tDeformer: %d, "Deformer::Skin", "Skin" {' % skin_id) + w("\t\tVersion: 101") + w("\t\tLink_DeformAcuracy: 50") + w("\t}") + + # per_bone / n_cluster 已经在前面算好(Definitions 里要用到) + for bi in sorted(per_bone): + pairs = sorted(per_bone[bi]) + cx = bpos[bi] + w('\tDeformer: %d, "SubDeformer::%s", "Cluster" {' + % (skin_id + 1 + bi, _san(bones[bi]["name"]))) + w("\t\tVersion: 100") + w('\t\tUserData: "", ""') + w("\t\tIndexes: *%d {" % len(pairs)) + _arr(w, "\t\t\t", [str(x[0]) for x in pairs]) + w("\t\t} ") + w("\t\tWeights: *%d {" % len(pairs)) + _arr(w, "\t\t\t", [_f(x[1]) for x in pairs]) + w("\t\t} ") + # 行主序 4x4:TransformLink = W(骨骼世界),Transform = W⁻¹ + w("\t\tTransform: *16 {") + w("\t\t\ta: " + ",".join(["1", "0", "0", "0", "0", "1", "0", "0", + "0", "0", "1", "0", + _f(-cx[0]), _f(-cx[1]), _f(-cx[2]), "1"])) + w("\t\t} ") + w("\t\tTransformLink: *16 {") + w("\t\t\ta: " + ",".join(["1", "0", "0", "0", "0", "1", "0", "0", + "0", "0", "1", "0", + _f(cx[0]), _f(cx[1]), _f(cx[2]), "1"])) + w("\t\t} ") + w("\t}") + + # 表情:BlendShape → BlendShapeChannel(一个表情一个)→ Shape(增量) + # 名字一律写**裸名**(和骨名一样,不加 `SubDeformer::` / `Shape::` 前缀): + # · FBX SDK 侧 channel.GetName() 会把前缀剥掉,两种写法结果相同; + # · 本工程自己的 fbx2pmx 直接取字段原文,写裸名才不会把表情名变成 + # "Shape::L_P"; + # · Blender 的 shape key 名字也直接取这个字段。 + # 名字里的非 ASCII(日文表情名很常见)**保留原样** —— FBX 文本是 UTF-8, + # SDK 与 Blender 都能正确解码,换成下划线反而让用户在 PE 里认不出表情。 + shape_ids = {} + if n_shape: + w('\tDeformer: %d, "BlendShape", "BlendShape" {' % morph_id0) + w("\t\tVersion: 101") + w("\t}") + for k, (mo, pairs) in enumerate(morph_shapes): + cid = morph_id0 + 1 + k * 2 + sid = cid + 1 + shape_ids[k] = (cid, sid) + nm = _esc(_clip(mo.get("name"))) or ("morph_%d" % k) + w('\tDeformer: %d, "%s", "BlendShapeChannel" {' % (cid, nm)) + w("\t\tVersion: 100") + # 字段名是 DeformPercent(不是 DeformerPercent)——后者会被 SDK 当成 + # 未知字段默默丢掉,通道权重就一直是 0。 + w("\t\tDeformPercent: 0") + # FullWeights = 每个 target shape 的默认权重(百分比)。SDK 导出时必写。 + w("\t\tFullWeights: *1 {") + w("\t\t\ta: 100") + w("\t\t} ") + w("\t}") + keys = sorted(pairs) + w('\tGeometry: %d, "%s", "Shape" {' % (sid, nm)) + w("\t\tVersion: 100") + w("\t\tIndexes: *%d {" % len(keys)) + _arr(w, "\t\t\t", [str(x) for x in keys]) + w("\t\t} ") + w("\t\tVertices: *%d {" % (len(keys) * 3)) + buf = [] + for vi in keys: + d = xf(pairs[vi]) + buf.append("%s,%s,%s" % (_f(d[0]), _f(d[1]), _f(d[2]))) + _arr(w, "\t\t\t", buf) + w("\t\t} ") + w("\t}") + w("}") + w("") + + # ------------------------------------------------------------ Connections -- + w("Connections: {") + w('\tC: "OO",%d,0' % mid) + w('\tC: "OO",%d,%d' % (gid, mid)) + w('\tC: "OO",%d,%d' % (skin_id, gid)) + # 每个 Model 挂自己的 NodeAttribute(没有它 SDK 认不出节点类型) + w('\tC: "OO",%d,%d' % (na_id0 + len(bones), mid)) + for bi in range(len(bones)): + w('\tC: "OO",%d,%d' % (na_id0 + bi, bone_model[bi])) + # 表情链:Shape → Channel → BlendShape → Geometry + if n_shape: + w('\tC: "OO",%d,%d' % (morph_id0, gid)) + for k in range(n_shape): + cid, sid = shape_ids[k] + w('\tC: "OO",%d,%d' % (cid, morph_id0)) + w('\tC: "OO",%d,%d' % (sid, cid)) + for bi in range(len(bones)): + p = bones[bi].get("parent", -1) + if 0 <= p < len(bones): + w('\tC: "OO",%d,%d' % (bone_model[bi], bone_model[p])) + else: + w('\tC: "OO",%d,0' % bone_model[bi]) + if bi in per_bone: + w('\tC: "OO",%d,%d' % (skin_id + 1 + bi, skin_id)) + w('\tC: "OO",%d,%d' % (bone_model[bi], skin_id + 1 + bi)) + for mi, myid in enumerate(mat_ids): + w('\tC: "OO",%d,%d' % (myid, mid)) + if mi in tex_files: + tid = tex_id0 + mi * 2 + 1 + w('\tC: "OP",%d,%d, "DiffuseColor"' % (tid, myid)) + w("}") + w("") + w("Takes: {") + w('\tCurrent: ""') + w("}") + w("") + + data = "\n".join(out) + tmp = path + ".tmp" + with open(tmp, "w", encoding="utf-8", newline="\n") as f: + f.write(data) + os.replace(tmp, path) + st = {"bytes": len(data.encode("utf-8")), "vertices": nv, "tris": ntris, + "bones": len(bones), "materials": len(materials or []), + "clusters": n_cluster, "textures": len(tex_files), + "shapes": n_shape, "morphs": len(morphs or [])} + _l("FBX:%d 个 Cluster · %d 个表情 Shape · 引用贴图 %d 张 · %.2f MB" + % (n_cluster, n_shape, len(tex_files), st["bytes"] / 1048576.0)) + return st + + +def export_pmx(pmx_path, fbx_path, log=None, mirror_z=True): + """直接读 PMX 再写 FBX(命令行用)。""" + import pmxio + m = pmxio.read_pmx(pmx_path) + tex_dir = os.path.join(os.path.dirname(os.path.abspath(pmx_path)), "textures") + for mt in m["materials"]: + ti = mt.get("tex", -1) + if isinstance(ti, int) and 0 <= ti < len(m["textures"]): + mt["_tex_file"] = os.path.basename(m["textures"][ti]) + model_name = (m.get("name") or "").strip() or \ + os.path.splitext(os.path.basename(pmx_path))[0] + return export_model(fbx_path, m["vertices"], m["faces"], m["materials"], + m["bones"], m["morphs"], mirror_z=mirror_z, + reverse_winding=True, tex_dir=tex_dir, log=log, + creator="fbxout.py", model_name=model_name) + + +def main(argv=None): + ap = argparse.ArgumentParser(description="PMX → ASCII FBX 7.4(纯 Python)") + ap.add_argument("src") + ap.add_argument("-o", "--out", default=None) + ap.add_argument("--no-mirror", action="store_true", + help="不取反 Z(默认取反,与工程 FBX 读取路径互逆)") + a = ap.parse_args(argv) + out = a.out or (os.path.splitext(a.src)[0] + ".fbx") + st = export_pmx(a.src, out, log=lambda m_, t=None: print(m_), + mirror_z=not a.no_mirror) + print("完成:%s(%.2f MB)" % (out, st["bytes"] / 1048576.0)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/formats/longpath.py b/formats/longpath.py new file mode 100644 index 0000000..ec75b52 --- /dev/null +++ b/formats/longpath.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- +r"""Windows 超长路径(MAX_PATH 260)兼容层 —— 纯标准库。 + +问题 +---- +Windows 默认把路径限制在 260 字符(MAX_PATH)。Unity 资源包解出来的目录树 +本身就很深,例如:: + + Assets/NFD_Costume/HatsukoiVampire/Gimmick/Resource/Animator/ + Animation/Toggle/Accessory/NeckRibbon/Accessory_NeckRibbon_ON.anim + +再叠上「输出目录 / 文件名_日期_序号 / 文件名_extracted」这几层,很容易超过 +260。一旦超出,open() / os.makedirs() 就抛:: + + FileNotFoundError: [Errno 2] No such file or directory: 'F:\...' + +而且报错里那串路径看着完全正常,非常难排查。 + +注意:这**不是中文路径的问题**。Python 3 的 Unicode 路径本来就是好的,中文、 +日文、空格、方括号、全角符号都没问题,纯粹是「总长度」超限。所以同一台机器 +上路径浅就能转、路径深就报错,换台电脑因为存放位置不同结果又不一样。 + +绕过办法 +-------- +给路径加 ``\?\`` 前缀(Win32 扩展长度路径),直接跳过 MAX_PATH 检查。它 +**不依赖**注册表 LongPathsEnabled,也不需要管理员权限或重启,所以在别人的 +电脑上同样有效。 + +本模块把常用的文件 API 包一层: + * 路径短(< 240)→ 原样透传,行为和以前完全一致; + * 路径长 → 自动补 ``\?\``。 + +因此对现有用户零影响,只在「本来必然失败」的长路径上生效。 + +用法 +---- +``import longpath`` 即可,模块导入时自动安装(重复导入无副作用)。 +""" + +import builtins +import os +import os.path as _path +import shutil + +# 文件路径上限 260、目录上限 248。这里留余量:超过 240 就上前缀, +# 免得刚好卡在 258 那种「有时行有时不行」的位置。 +_THRESHOLD = 240 + +_PREFIX = '\\\\?\\' # \?\ +_UNC_PREFIX = '\\\\?\\UNC\\' # \?\UNC\ + +_installed = False +_originals = {} + + +def long_path(path): + r"""路径过长时返回带 ``\?\`` 前缀的绝对路径;否则原样返回。 + + 短路径一律原样返回(连 abspath 都不做),保证不改变任何现有行为。 + """ + if os.name != 'nt': + return path + if not isinstance(path, str) or not path: + return path # 只处理 str;fd / PathLike 原样放行 + if path.startswith(_PREFIX): + return path # 已经加过前缀,别重复加 + if len(path) < _THRESHOLD: + return path # 短路径不碰 + try: + p = _path.abspath(path) + except (OSError, ValueError): + return path + if len(p) < _THRESHOLD: + return path + if p.startswith('\\\\'): + # UNC:\\server\share\x → \?\UNC\server\share\x + return _UNC_PREFIX + p[2:] + return _PREFIX + p + + +def _install(): + """给 os / builtins / shutil 的相关函数套上长路径包装。幂等。""" + global _installed + if _installed or os.name != 'nt': + return + _installed = True + + # ---- 单路径参数 ------------------------------------------------------ + for name in ('makedirs', 'mkdir', 'rmdir', 'remove', 'unlink', + 'stat', 'lstat', 'chmod', 'utime', 'listdir', 'scandir', + 'access', 'truncate', 'readlink', 'startfile'): + fn = getattr(os, name, None) + if fn is None: + continue + _originals[name] = fn + + def make(fn): + def wrapper(path, *a, **kw): + return fn(long_path(path), *a, **kw) + return wrapper + setattr(os, name, make(fn)) + + # ---- 双路径参数(源、目标都要处理)------------------------------------ + for name in ('rename', 'replace'): + fn = getattr(os, name, None) + if fn is None: + continue + _originals[name] = fn + + def make2(fn): + def wrapper(src, dst, *a, **kw): + return fn(long_path(src), long_path(dst), *a, **kw) + return wrapper + setattr(os, name, make2(fn)) + + # ---- 内置 open ------------------------------------------------------- + _originals['open'] = builtins.open + + def _open(file, *a, **kw): + return _originals['open'](long_path(file), *a, **kw) + builtins.open = _open + + # ---- shutil:显式包一层(虽然底层最终也会走到上面的 open/stat)--------- + for name in ('copyfile', 'copy', 'copy2', 'copymode', 'copystat', + 'rmtree'): + fn = getattr(shutil, name, None) + if fn is None: + continue + _originals['shutil.' + name] = fn + + def makes(fn): + def wrapper(path, *a, **kw): + return fn(long_path(path), *a, **kw) + return wrapper + setattr(shutil, name, makes(fn)) + + for name in ('move',): + fn = getattr(shutil, name, None) + if fn is None: + continue + _originals['shutil.' + name] = fn + + def makes2(fn): + def wrapper(src, dst, *a, **kw): + return fn(long_path(src), long_path(dst), *a, **kw) + return wrapper + setattr(shutil, name, makes2(fn)) + + +_install() + + +def probe(base): + """自检:在 base 下建一条超长路径并写入/读回,返回 (是否成功, 说明)。 + + 给界面或命令行排查用;平时不调用。 + """ + deep = os.path.join(base, '_longpath_probe') + while len(deep) < 300: + deep = os.path.join(deep, 'LongSegmentName_0123456789') + target = os.path.join(deep, 'probe.txt') + try: + os.makedirs(deep, exist_ok=True) + with open(target, 'w', encoding='utf-8') as f: + f.write('ok') + with open(target, encoding='utf-8') as f: + got = f.read() + return got == 'ok', '长度 %d,写入并读回成功' % len(target) + except Exception as e: # pragma: no cover + return False, '%s: %s' % (type(e).__name__, e) + + +if __name__ == '__main__': # pragma: no cover + import sys + base = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() + ok, msg = probe(base) + print(('[OK] ' if ok else '[FAIL] ') + msg) diff --git a/formats/pmxio.py b/formats/pmxio.py new file mode 100644 index 0000000..c47e88d --- /dev/null +++ b/formats/pmxio.py @@ -0,0 +1,878 @@ +# -*- coding: utf-8 -*- +"""pmxio.py - 完整的 PMX 2.0 / 2.1 读写(纯 Python 标准库)。 + +读进模型的全部内容(含表情 offset、骨骼 IK/付与/轴限制、刚体、关节),并且能原样写回。 +PMX → VRM 和各格式 → PMX 的转换都基于它。 + +数据结构(dict): + model = { + "version", "enc", "add_uv", + "name", "name_en", "comment", "comment_en", + "vertices": [ {"pos":(3), "normal":(3), "uv":(2), "add_uv":[(4)...], + "wtype":0..4, "wbones":[int..], "wweights":[float..], + "sdef":(C,R0,R1) 或 None, + "edge":float} ], + "faces": [v0, v1, v2, ...], # 展平 + "textures":["相对路径", ...], + "materials":[ {"name","name_en","diffuse":(4),"specular":(3),"shininess", + "ambient":(3),"flag","edge_color":(4),"edge_size", + "tex","sph","sph_mode","toon_flag","toon","memo","faces"} ], + "bones": [ {"name","name_en","pos":(3),"parent","layer","flag", + "tail_kind":0/1,"tail":(3)或int, + "inherit_rot":(bone,ratio)或None, + "inherit_mov":(bone,ratio)或None, + "fixed_axis":(3)或None, + "local_axis":(X,Z)或None, + "external":int 或 None, + "ik":{...}或None} ], + "morphs": [ {"name","name_en","panel","kind","offsets":[...]} ], + "frames": [ {"name","name_en","special","items":[(type,index)]} ], + "rigid_bodies":[...], + "joints":[...], + } +""" +import os +import struct + +_DBG = bool(os.environ.get("PMXIO_DEBUG")) + +FLOAT = "f" +WEIGHT_BONES = {0: 1, 1: 2, 2: 4, 3: 2, 4: 4} +WEIGHT_FLOATS = {0: 0, 1: 1, 2: 4, 3: 1, 4: 4} + +# PMX 头部的文本编码取值:0 = UTF-16LE,1 = UTF-8。 +# MMD 本体只认 0(原版提示「エンコード方式がUTF16のPMXファイルしか読み込めません」, +# 汉化版误译成「不能载入编码为UTF16的PMX文件」,其实意思正好相反)。 +# PMX Editor / mmd_tools 也都默认写 0,所以输出一律用 UTF-16LE。 +ENC_UTF16 = 0 +ENC_UTF8 = 1 +MMD_ENC = ENC_UTF16 + + +# ------------------------------------------------------------------ reader -- +class _R: + def __init__(self, d): + self.d = d + self.p = 0 + self.enc = 1 + # 当前解析到的段落/条目,仅用于出错时给出能定位的信息 + self.sec = "头部" + + def _fail(self, what): + return "PMX 解析错位(段落:%s):" % self.sec + + def _need(self, n, what): + if self.p + n > len(self.d): + raise ValueError( + self._fail(what) + + "读取「%s」时越过文件末尾(偏移 %d / 文件 %d 字节)。" + "可能是某一段的结构与写入程序不一致,请反馈此模型文件。" + % (what, self.p, len(self.d))) + + def i32(self, what="int"): + self._need(4, what) + v = struct.unpack_from(" len(self.d): + raise ValueError( + self._fail(what) + + "「%s」长度 %d 超出文件剩余字节(偏移 %d / %d)。" + % (what, n, self.p, len(self.d))) + s = self.d[self.p:self.p + n] + self.p += n + return s.decode("utf-16-le" if self.enc == 0 else "utf-8", "replace") + + def idx(self, size, signed=True, what="index"): + self._need(size, what) + if size == 1: + v = struct.unpack_from("= 2.1 永远不成立, + # 必须用容差比较(否则 PMX 2.1 文件末尾会剩 4 字节 SoftBody 计数读不到)。 + if version > 2.05: + if r.p == len(d): + # 少数工具(如 MikuMikuDayo 的粒子 PMX)标着 2.1 却没写 + # SoftBody 计数字段,容错当作 0 处理,别一棒子打死。 + m["soft_bodies"] = 0 + else: + r._need(4, "softbody count") + nsoft = r.i32("softbody count") + m["soft_bodies"] = nsoft + m["consumed"] = r.p + if nsoft: + raise ValueError( + "该模型是 PMX 2.1 且含 %d 个 SoftBody,本转换器暂不支持 SoftBody。" + % nsoft) + + if m["consumed"] != m["filesize"]: + raise ValueError( + "PMX 解析后仍有 %d 字节未读完(已读 %d / 共 %d)," + "说明某一段的结构与写入程序不一致,请反馈此模型文件。" + % (m["filesize"] - m["consumed"], m["consumed"], m["filesize"])) + return m + + +# ------------------------------------------------------------------ writer -- +def _isize(count, signed=True): + """按数量挑索引字节宽度。""" + if signed: + if count <= 127: + return 1 + if count <= 32767: + return 2 + return 4 + if count <= 255: + return 1 + if count <= 65535: + return 2 + return 4 + + +class _W: + def __init__(self): + self.buf = bytearray() + + def i32(self, v): + self.buf += struct.pack("= 0 else 0, bi) + if wt in (1, 3): + ws = list(v["wweights"]) + [0.0] + w.f32(ws[0]) + elif wt in (2, 4): + ws = list(v["wweights"]) + [0.0] * 4 + for k in range(4): + w.f32(ws[k]) + if wt == 3 and v.get("sdef"): + for t in v["sdef"]: + for k in range(3): + w.f32(t[k]) + elif wt == 3: + for _ in range(9): + w.f32(0.0) + w.f32(v.get("edge", 1.0)) + + w.i32(len(faces)) + for f in faces: + w.idx(f, vi, signed=False) + + w.i32(len(m["textures"])) + for t in m["textures"]: + w.text(t, enc) + + w.i32(len(mats)) + for mm in mats: + w.text(mm["name"], enc) + w.text(mm.get("name_en", mm["name"]), enc) + for k in range(4): + w.f32(mm["diffuse"][k]) + for k in range(3): + w.f32(mm["specular"][k]) + w.f32(mm["shininess"]) + for k in range(3): + w.f32(mm["ambient"][k]) + w.u8(mm["flag"]) + for k in range(4): + w.f32(mm["edge_color"][k]) + w.f32(mm["edge_size"]) + w.idx(mm["tex"], ti) + w.idx(mm["sph"], ti) + w.u8(mm["sph_mode"]) + w.u8(mm["toon_flag"]) + # 宽度随 flag 变(见读取侧注释):flag=1 → 1 字节内建 toon 号; + # flag=0 → 纹理索引宽度。 + if mm["toon_flag"] == 0: + w.idx(mm["toon"], ti) + else: + w.u8(mm["toon"]) + w.text(mm.get("memo", ""), enc) + w.i32(mm["faces"]) + + w.i32(len(bones)) + for b in bones: + w.text(b["name"], enc) + w.text(b.get("name_en", b["name"]), enc) + for k in range(3): + w.f32(b["pos"][k]) + w.idx(b["parent"], bi) + w.i32(b.get("layer", 0)) + flag = b["flag"] + w.u16(flag) + if flag & 0x0001: + w.idx(b["tail"], bi) + else: + for k in range(3): + w.f32(b["tail"][k]) + if flag & 0x0100 or flag & 0x0200: + # 与读取侧同理:付与親/付与率只写共通的一组。 + # 两个 flag 同开时两组值理应一致;万一不一致(旧版本写出的文件), + # 以回転付与为准,避免丢信息。 + if flag & 0x0100: + gp, gr = b["inherit_rot"] + else: + gp, gr = b["inherit_mov"] + w.idx(gp, bi) + w.f32(gr) + if flag & 0x0400: + for k in range(3): + w.f32(b["fixed_axis"][k]) + if flag & 0x0800: + for t in b["local_axis"]: + for k in range(3): + w.f32(t[k]) + if flag & 0x2000: + ext = b["external"] + w.i32(ext if isinstance(ext, int) else (ext or (0,))[0]) + if flag & 0x0020: + ik = b["ik"] + w.idx(ik["target"], bi) + w.i32(ik["iterations"]) + w.f32(ik["limit_angle"]) + w.i32(len(ik["links"])) + for lk in ik["links"]: + w.idx(lk["bone"], bi) + if lk.get("min"): + w.u8(1) + for k in range(3): + w.f32(lk["min"][k]) + for k in range(3): + w.f32(lk["max"][k]) + else: + w.u8(0) + + w.i32(len(morphs)) + for mo in morphs: + w.text(mo["name"], enc) + w.text(mo.get("name_en", mo["name"]), enc) + w.u8(mo["panel"]) + kind = mo["kind"] + w.u8(kind) + w.i32(len(mo["offsets"])) + for off in mo["offsets"]: + if kind == 1: + w.idx(off[0], vi, signed=False) + for k in range(3): + w.f32(off[1][k]) + elif kind in (3, 4, 5, 6, 7): + w.idx(off[0], vi, signed=False) + for k in range(4): + w.f32(off[1][k]) + elif kind == 2: + w.idx(off[0], bi) + for k in range(3): + w.f32(off[1][k]) + for k in range(4): + w.f32(off[2][k]) + elif kind == 8: + w.idx(off[0], mi) + w.u8(off[1]) + for x in off[2]: + w.f32(x) + elif kind == 0 or kind == 9: + w.idx(off[0], moi) + w.f32(off[1]) + elif kind == 10: + w.idx(off[0], ri) + for k in range(3): + w.f32(off[1][k]) + for k in range(3): + w.f32(off[2][k]) + + frames = m.get("frames") or [] + w.i32(len(frames)) + for fr in frames: + w.text(fr["name"], enc) + w.text(fr.get("name_en", fr["name"]), enc) + w.u8(fr.get("special", 0)) + w.i32(len(fr["items"])) + for t, i in fr["items"]: + w.u8(t) + w.idx(i, bi if t == 0 else moi) + + rbs = m.get("rigid_bodies") or [] + w.i32(len(rbs)) + for rb in rbs: + w.text(rb["name"], enc) + w.text(rb.get("name_en", rb["name"]), enc) + w.idx(rb["bone"], bi) + w.u8(rb["group"]) + w.u16(rb["mask"]) + w.u8(rb["shape"]) + for k in range(3): + w.f32(rb["size"][k]) + for k in range(3): + w.f32(rb["pos"][k]) + for k in range(3): + w.f32(rb["rot"][k]) + w.f32(rb["mass"]) + w.f32(rb["move_damp"]) + w.f32(rb["rot_damp"]) + w.f32(rb["repulsion"]) + w.f32(rb["friction"]) + w.u8(rb["mode"]) + + jts = m.get("joints") or [] + w.i32(len(jts)) + for j in jts: + w.text(j["name"], enc) + w.text(j.get("name_en", j["name"]), enc) + w.u8(j["type"]) + w.idx(j["rb_a"], ri) + w.idx(j["rb_b"], ri) + for k in range(3): + w.f32(j["pos"][k]) + for k in range(3): + w.f32(j["rot"][k]) + for k in range(3): + w.f32(j["move_min"][k]) + for k in range(3): + w.f32(j["move_max"][k]) + rm = j.get("rot_min") or (0.0, 0.0, 0.0) + rx = j.get("rot_max") or (0.0, 0.0, 0.0) + for k in range(3): + w.f32(rm[k]) + for k in range(3): + w.f32(rx[k]) + for k in range(3): + w.f32(j["spring_move"][k]) + for k in range(3): + w.f32(j["spring_rot"][k]) + + # PMX 2.1 需要写 SoftBody 计数(本转换器不支持 SoftBody,恒写 0) + if m.get("version", 2.0) > 2.05: + w.i32(0) + + with open(path, "wb") as f: + f.write(w.buf) + return len(w.buf) + + +# ------------------------------------------------------- 缠绕顺序自动判定 -- +def detect_winding(positions, normals, faces, sample=4000): + """判断三角形的缠绕方向是否与法线一致。 + + positions: [(x,y,z), ...] + normals : [(x,y,z), ...] 与 positions 一一对应 + faces : [i0,i1,i2, ...] 展平的索引 + + 返回 (need_flip, agree, disagree): + need_flip=True 表示按现在的顺序算出来的几何法线与顶点法线相反, + 应该交换后两个索引。 + + 实测:PMX 与 glTF 的原始数据都是「从外面看逆时针」,几何法线与顶点法线同向。 + 注意(2026-09-18):这只对「未经手性修正的原始数据」成立。 + pmx2vrm 做镜面反射(改手性)之后,绕序会被颠倒, + 所以转换器里的 auto 判定必须用「反射后的数据」重新投票, + 那时会判「需要反转」——这是正确的,别因此改回不反转。 + 以前硬编码「必须反转」是错的,会让模型在 MMD / VRM 查看器里被背面剔除, + 表现就是大面积镂空 + 轮廓线糊成一片黑。 + """ + n_tri = len(faces) // 3 + if n_tri == 0 or not normals or len(normals) < len(positions): + return False, 0, 0 + step = 1 if n_tri <= sample else (n_tri + sample - 1) // sample + agree = disagree = 0 + for t in range(0, n_tri, step): + a = faces[t * 3] + b = faces[t * 3 + 1] + c = faces[t * 3 + 2] + if a >= len(positions) or b >= len(positions) or c >= len(positions): + continue + pa, pb, pc = positions[a], positions[b], positions[c] + e1 = (pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]) + e2 = (pc[0] - pa[0], pc[1] - pa[1], pc[2] - pa[2]) + gn = (e1[1] * e2[2] - e1[2] * e2[1], + e1[2] * e2[0] - e1[0] * e2[2], + e1[0] * e2[1] - e1[1] * e2[0]) + if abs(gn[0]) + abs(gn[1]) + abs(gn[2]) < 1e-12: + continue + na = normals[a] + nb = normals[b] + nc = normals[c] + vn = (na[0] + nb[0] + nc[0], na[1] + nb[1] + nc[1], + na[2] + nb[2] + nc[2]) + d = gn[0] * vn[0] + gn[1] * vn[1] + gn[2] * vn[2] + if d > 0: + agree += 1 + elif d < 0: + disagree += 1 + if agree + disagree == 0: + return False, 0, 0 + return (disagree > agree), agree, disagree + + +# ------------------------------------------------------------- 空模型工具 -- +def new_model(name="Model"): + return { + "version": 2.0, "enc": MMD_ENC, "add_uv": 0, + "name": name, "name_en": name, "comment": "", "comment_en": "", + "vertices": [], "faces": [], "textures": [], "materials": [], + "bones": [], "morphs": [], "frames": [], + "rigid_bodies": [], "joints": [], + } + + +def strip_edges(model, force_double_sided=True): + """去除 PMX 的黑色轮廓线(MMD 轮廓线 / edge line)。 + + 对输出到 MMD 后常见的“模型边缘出现黑边”问题,把材质的轮廓线标记、 + 粗细、颜色 alpha 全部关闭,并把每个顶点的 edge 系数置 0。 + 可选同时强制开启双面描绘,减少因背面剔除产生的黑缝/镂空。 + """ + for v in model.get("vertices", []): + v["edge"] = 0.0 + for mm in model.get("materials", []): + mm["flag"] = (mm.get("flag", 0x0F) & ~0x10) + if force_double_sided: + mm["flag"] |= 0x01 + mm["edge_size"] = 0.0 + ec = list(mm.get("edge_color") or (0.0, 0.0, 0.0, 1.0)) + while len(ec) < 4: + ec.append(1.0) + ec[3] = 0.0 + mm["edge_color"] = tuple(ec) + return model + + +# ------------------------------------------------------- 文本编码转换工具 -- +def convert_encoding(src, dst=None, enc=MMD_ENC, verbose=True): + """把已有 PMX 的文本编码改成 enc(默认 UTF-16LE —— MMD 唯一认的编码)。 + + 用于修复早先版本导出的 UTF-8 PMX:MMD 会报 + 「MMDではエンコード方式がUTF16のPMXファイルしか読み込めません」而拒绝载入。 + 不传 dst 时写到同目录的 "<名字>_utf16.pmx"(不覆盖原文件)。 + 返回 (输出路径, 字节数)。 + """ + model = read_pmx(src) + old = model.get("enc", ENC_UTF8) + model["enc"] = enc + if dst is None: + stem, _ext = os.path.splitext(src) + dst = stem + ("_utf16.pmx" if enc == ENC_UTF16 else "_utf8.pmx") + tmp = dst + ".tmp" + n = write_pmx(model, tmp) + # 回读校验:能完整解析、名称一致才认账,避免把文件改坏 + back = read_pmx(tmp) + if back["name"] != model["name"] or back["consumed"] != back["filesize"]: + os.remove(tmp) + raise ValueError("改写后回读校验失败,未写入:%s" % src) + os.replace(tmp, dst) + if verbose: + print("%-40s 编码 %d(%s) -> %d(%s) %.2f MB" % ( + os.path.basename(src), old, "UTF-8" if old else "UTF-16LE", + enc, "UTF-8" if enc else "UTF-16LE", n / 1048576.0)) + return dst, n + + +if __name__ == "__main__": + import argparse + + ap = argparse.ArgumentParser( + description="把 PMX 的文本编码改成 MMD 能读的那种(默认 UTF-16LE)") + ap.add_argument("files", nargs="+", help="要处理的 .pmx") + ap.add_argument("--enc", choices=("utf16", "utf8"), default="utf16", + help="目标编码,默认 utf16(MMD 只认这个)") + ap.add_argument("-o", "--out", default=None, help="输出路径(仅限单个输入)") + ap.add_argument("--in-place", action="store_true", + help="直接覆盖原文件(危险,建议先备份)") + a = ap.parse_args() + if a.out and len(a.files) > 1: + ap.error("-o 只能配合单个输入文件使用") + + want = ENC_UTF16 if a.enc == "utf16" else ENC_UTF8 + for p in a.files: + try: + convert_encoding(p, a.out or (p if a.in_place else None), want) + except Exception as e: + print("失败 %s:%s" % (p, e)) diff --git a/formats/pskio.py b/formats/pskio.py new file mode 100644 index 0000000..904f36c --- /dev/null +++ b/formats/pskio.py @@ -0,0 +1,522 @@ +# -*- coding: utf-8 -*- +"""PSK / PSKX 读取器(纯 Python 标准库,不需要 Blender / UE / FBX SDK)。 + +格式来源:Unreal Engine 的 ActorX 交换格式(.psk)及其扩展(.pskx)。 +二进制布局以 DarklightGames/io_scene_psk_psa 的 psk_psa_py 为准, +并由本项目实测的样本文件(含 FACE3200 / VERTEXCOLOR / MRPHINFO / MRPHDATA +等扩展块)逐字段复核过。 + +文件结构 +-------- +整份文件是「块(section)」的线性序列,每个块: + + struct Section { char name[20]; int32 type_flags; int32 data_size; + int32 data_count; } // 共 32 字节 + 紧接 data_size * data_count 字节的数据 + +块名与记录布局(offset 都是相对记录开头): + + PNTS0000 Vector3 12 x,y,z 顶点(绑定姿势,物体空间) + VTXW0000 Wedge16 / Wedge32 16 uint32 point_index; float u, v; + uint32 material_index + FACE0000 Face16 12 uint16 i[3]; uint8 mat; uint8 aux; + int32 smoothing + FACE3200 Face32 18 uint32 i[3]; uint8 mat; uint8 aux; + int32 smoothing(紧凑排列) + MATT0000 Material 88 char name[64]; int32 ×6 + REFSKELT Bone 120 char name[64]; int32 flags; + int32 children_count; int32 parent_index; + Quat rotation(x,y,z,w); Vector3 location; + float length; Vector3 size + RAWWEIGHTS Weight 12 float weight; int32 point_index; + int32 bone_index + VTXNORMS Vector3 12 顶点法线 + VERTEXCOLOR Color 4 r,g,b,a(各 1 字节) + EXTRAUVS* Vector2 8 附加 UV(pskx,可有多套) + MRPHINFO MorphInfo 68 char name[64]; int32 vertex_count + MRPHDATA MorphData 28 Vector3 position_delta; + Vector3 tangent_z_delta; int32 point_index + +两个实测坑(都已处理): +1) 部分游戏导出的文件在真正的 PSK 数据前面多写了 32 字节外层头(又是一个 + ACTRHEAD,type_flags 位置放的是版本号 20220723)。按块序列顺序读即可自然 + 跳过:外层 ACTRHEAD 的 data_count=0,读完就落到第二个 ACTRHEAD 上。 +2) 四元数要取共轭((x,y,z,w) → 取 (x,y,z) 的负号)后才是引擎常用右手系下 + 的旋转;不共轭的话骨骼世界坐标会整条链歪出去(实测头骨能偏 30 多个单位)。 +""" +import os +import struct + +__all__ = ["Psk", "PskBone", "PskMaterial", "PskMorph", "read_psk", + "bone_world", "quat_to_matrix", "write_psk"] + +# 写入时用的块头版本号:实测样本(二重螺旋 R2T1*)的两个 ACTRHEAD 都放的是 +# 20220723,照抄以保证同一套文件能被同一批工具读。标准 ActorX 写的是 1999801 +# 之类的日期串,但那只是个标记,读者一般不校验。 +PSK_VERSION = 20220723 + +# ------------------------------------------------------------------ data --- +class PskBone(object): + __slots__ = ("name", "flags", "children_count", "parent_index", + "rotation", "location", "length", "size") + + def __init__(self, name, flags, children_count, parent_index, + rotation, location, length, size): + self.name = name + self.flags = flags + self.children_count = children_count + self.parent_index = parent_index + self.rotation = rotation # (x, y, z, w) + self.location = location # (x, y, z) + self.length = length + self.size = size # (x, y, z) + + +class PskMaterial(object): + __slots__ = ("name", "texture_index", "poly_flags", "aux_material", + "aux_flags", "lod_bias", "lod_style") + + def __init__(self, name, texture_index, poly_flags, aux_material, + aux_flags, lod_bias, lod_style): + self.name = name + self.texture_index = texture_index + self.poly_flags = poly_flags + self.aux_material = aux_material + self.aux_flags = aux_flags + self.lod_bias = lod_bias + self.lod_style = lod_style + + +class PskMorph(object): + """一个表情目标:名字 + 顶点位移列表 [(point_index, (dx,dy,dz)), ...]。""" + __slots__ = ("name", "offsets") + + def __init__(self, name, offsets): + self.name = name + self.offsets = offsets + + +class Psk(object): + def __init__(self): + self.points = [] # [(x,y,z), ...] + self.wedges = [] # [(point_index, u, v, material_index), ...] + self.faces = [] # [((i0,i1,i2), material_index), ...] + self.materials = [] # [PskMaterial, ...] + self.bones = [] # [PskBone, ...] + self.weights = [] # [(weight, point_index, bone_index), ...] + self.normals = [] # [(x,y,z), ...] + self.colors = [] # [(r,g,b,a), ...] + self.extra_uvs = [] # [[(u,v), ...], ...] + self.morphs = [] # [PskMorph, ...] + self.face32 = False # 索引用的是 FACE3200(32 位)还是 FACE0000 + + @property + def has_normals(self): + return bool(self.normals) + + @property + def has_morphs(self): + return bool(self.morphs) + + +# ------------------------------------------------------------------ math --- +def quat_to_matrix(q): + """(x, y, z, w) → 3×3 旋转矩阵。 + + 列向量约定:v' = M · v(与 bone_world / _mvec / _mmul 一致,别写成转置)。 + 校验:绕 Z 轴 +90° 的四元数 (0,0,0.7071,0.7071) 应把 (1,0,0) 变成 (0,1,0)。 + """ + x, y, z, w = q + return ((1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)), + (2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)), + (2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y))) + + +def _mmul(a, b): + return tuple(tuple(sum(a[i][k] * b[k][j] for k in range(3)) + for j in range(3)) for i in range(3)) + + +def _mvec(m, v): + """列向量:M · v。""" + return tuple(sum(m[i][k] * v[k] for k in range(3)) for i in range(3)) + + +def bone_world(psk): + """算每根骨骼的世界(物体空间)旋转矩阵与位置。 + + PSK 的 rotation/location 都是**相对父骨骼**的局部值,世界值沿父链累乘。 + 四元数先取共轭再转成矩阵(见文件头注释第 2 点)。 + + 返回 (world_rot, world_pos),都是按骨骼下标索引的列表。 + """ + bones = psk.bones + n = len(bones) + wrot = [None] * n + wpos = [None] * n + state = [0] * n # 0 未算 / 1 计算中 / 2 已完成 + + def calc(i, depth=0): + if state[i] == 2 or depth > 512: + return + if state[i] == 1: # 环:当成根,别死循环 + x, y, z, w = bones[i].rotation + wrot[i] = quat_to_matrix((-x, -y, -z, w)) + wpos[i] = tuple(bones[i].location) + state[i] = 2 + return + state[i] = 1 + b = bones[i] + x, y, z, w = b.rotation + r = quat_to_matrix((-x, -y, -z, w)) + p = b.parent_index + if p < 0 or p >= n or p == i: + wrot[i] = r + wpos[i] = tuple(b.location) + else: + calc(p, depth + 1) + pr, pt = wrot[p], wpos[p] + if pr is None: + wrot[i] = r + wpos[i] = tuple(b.location) + else: + wrot[i] = _mmul(pr, r) + t = _mvec(pr, b.location) + wpos[i] = (pt[0] + t[0], pt[1] + t[1], pt[2] + t[2]) + state[i] = 2 + + for i in range(n): + calc(i) + for i in range(n): + if wrot[i] is None: + x, y, z, w = bones[i].rotation + wrot[i] = quat_to_matrix((-x, -y, -z, w)) + wpos[i] = tuple(bones[i].location) + return wrot, wpos + + +# ----------------------------------------------------------------- reader --- +def _cstr(raw): + return raw.split(b"\x00")[0].decode("ascii", "replace") + + +def read_psk(path): + """读 .psk / .pskx,返回 Psk。""" + with open(path, "rb") as fp: + data = fp.read() + psk = Psk() + off = 0 + total = len(data) + morph_infos = [] # [(name, vertex_count), ...] + morph_raw = [] # [(delta, tangent_z, point_index), ...] + + while off + 32 <= total: + name = data[off:off + 20].split(b"\x00")[0] + if not name or not all(32 < c < 127 for c in name): + break # 不是块头了(尾部填充 / 未知数据) + try: + _flag, dsize, dcount = struct.unpack_from(" total: + break # 块头不可信,停在这里 + nm = name.decode("ascii") + + if nm == "PNTS0000" and dsize >= 12: + psk.points = [struct.unpack_from("<3f", data, body + i * dsize) + for i in range(dcount)] + elif nm == "VTXW0000": + if dsize >= 16: + psk.wedges = [struct.unpack_from("= 12: # 老式 16 位 point_index + for i in range(dcount): + pi = struct.unpack_from("= 12: + for i in range(dcount): + o = body + i * dsize + a, b, c = struct.unpack_from("<3H", data, o) + psk.faces.append(((a, b, c), data[o + 6])) + psk.face32 = False + elif nm == "FACE3200" and dsize >= 18: + for i in range(dcount): + o = body + i * dsize + a, b, c = struct.unpack_from("<3I", data, o) + psk.faces.append(((a, b, c), data[o + 12])) + psk.face32 = True + elif nm == "MATT0000" and dsize >= 88: + for i in range(dcount): + o = body + i * dsize + psk.materials.append(PskMaterial( + _cstr(data[o:o + 64]), + *struct.unpack_from("<6i", data, o + 64))) + elif nm == "REFSKELT" and dsize >= 120: + for i in range(dcount): + o = body + i * dsize + psk.bones.append(PskBone( + _cstr(data[o:o + 64]), + *struct.unpack_from("<3i", data, o + 64), + rotation=struct.unpack_from("<4f", data, o + 76), + location=struct.unpack_from("<3f", data, o + 92), + length=struct.unpack_from("= 12: + psk.weights = [struct.unpack_from("= 12: + psk.normals = [struct.unpack_from("<3f", data, body + i * dsize) + for i in range(dcount)] + elif nm == "VERTEXCOLOR" and dsize >= 4: + psk.colors = [tuple(data[body + i * dsize: body + i * dsize + 4]) + for i in range(dcount)] + elif nm == "MRPHINFO" and dsize >= 68: + for i in range(dcount): + o = body + i * dsize + morph_infos.append((_cstr(data[o:o + 64]), + struct.unpack_from("= 28: + for i in range(dcount): + o = body + i * dsize + morph_raw.append((struct.unpack_from("<3f", data, o), + struct.unpack_from("<3f", data, o + 12), + struct.unpack_from("= 8: + psk.extra_uvs.append([struct.unpack_from("<2f", data, + body + i * dsize) + for i in range(dcount)]) + # 其余块(含 ACTRHEAD)直接按大小跳过 + off = body + nbytes + + # 16 位 point_index 的老工具会把高 16 位写成垃圾;点数还装得下 16 位时 + # 统一截掉高位(与 psk_psa_py 的 read_psk 同口径)。 + if psk.points and len(psk.points) <= 65536: + psk.wedges = [(w[0] & 0xFFFF, w[1], w[2], w[3]) for w in psk.wedges] + + # MRPHDATA 是按 MRPHINFO 的顺序连续排布的:第 i 个表情吃前 vertex_count 条。 + if morph_infos and morph_raw: + pos = 0 + for name, cnt in morph_infos: + chunk = morph_raw[pos:pos + max(0, cnt)] + pos += max(0, cnt) + offs = [(pi, d) for d, _tz, pi in chunk + if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-9] + if offs: + psk.morphs.append(PskMorph(name, offs)) + if pos < len(morph_raw): # 名字数和数据条数对不上,兜底塞成一个 + rest = [(pi, d) for d, _tz, pi in morph_raw[pos:] + if abs(d[0]) + abs(d[1]) + abs(d[2]) > 1e-9] + if rest: + psk.morphs.append(PskMorph("morph_rest", rest)) + return psk + + +# ----------------------------------------------------------------- writer --- +# 写入的块顺序照抄实测样本(读的一侧对顺序不敏感,但保持一致最省事): +# ACTRHEAD ×2 → PNTS0000 → VTXW0000 → FACE0000/FACE3200 → MATT0000 +# → VTXNORMS → REFSKELT → RAWWEIGHTS → VERTEXCOLOR → EXTRAUVS* +# → MRPHINFO → MRPHDATA +# 其中 VTXNORMS / VERTEXCOLOR / EXTRAUVS* / MRPH* 都属于「非标准扩展块」 +# (DarklightGames 插件把带这些块的文件叫 .pskx,且只导进不导出), +# 所以 pskx=False 时会整段跳过,写出的就是 Epic 那套标准 .psk。 +def _chunk(name, dsize, dcount, payload, flag=0): + head = name.encode("ascii")[:20].ljust(20, b"\x00") + return head + struct.pack("= n: + return seq[:n] + return seq + [fill] * (n - len(seq)) + + +def write_psk(psk, path, pskx=True, version=None, headers=2, face32=None, + log=None): + """把 Psk 写成 .psk / .pskx 二进制,返回字节数。 + + pskx : True → 连 VTXNORMS / VERTEXCOLOR / EXTRAUVS* / MRPH* 一起写 + (信息最全,与实测样本一致) + False → 只写标准块(PNTS/VTXW/FACE/MATT/REFSKELT/RAWWEIGHTS), + 扩展内容会被丢弃并在日志里计数 + face32 : None 自动(顶点数 > 65535 就用 FACE3200),也可强制 True/False + headers : 开头的 ACTRHEAD 个数,实测样本是 2(外层那个是游戏多写的) + """ + def _l(msg, tag=None): + if log: + log(msg, tag) + + n_point = len(psk.points) + n_wedge = len(psk.wedges) + + # ---- 索引合法性:越界的一律夹回范围内,别写出打不开的文件 + bad_w = 0 + wedges = [] + for pi, u, v, mi in psk.wedges: + ip = int(pi) + if not (0 <= ip < n_point) and n_point: + ip = min(max(ip, 0), n_point - 1) + bad_w += 1 + wedges.append((ip, float(u), float(v), int(mi or 0))) + if bad_w: + _l("提示:%d 个楔的点索引越界,已夹回合法范围" % bad_w, "warn") + + max_idx = 0 + for f in psk.faces: + try: + max_idx = max(max_idx, int(f[0][0]), int(f[0][1]), int(f[0][2])) + except (TypeError, IndexError, ValueError): + pass + if face32 is None: + face32 = bool(getattr(psk, "face32", False)) or max_idx > 0xFFFF or \ + n_wedge > 0xFFFF + if not face32 and (max_idx > 0xFFFF or n_wedge > 0xFFFF): + _l("提示:顶点数 %d 超过 16 位索引上限,已改用 FACE3200" % n_wedge, + "warn") + face32 = True + + bad_f = 0 + faces = [] + for tri, mi in psk.faces: + a, b, c = int(tri[0]), int(tri[1]), int(tri[2]) + if n_wedge and not (0 <= a < n_wedge and 0 <= b < n_wedge + and 0 <= c < n_wedge): + bad_f += 1 + faces.append(((a, b, c), int(mi or 0))) + if bad_f: + _l("提示:%d 个面的楔索引越界(文件可能显示为破面)" % bad_f, "warn") + + out = [] + ver = int(version if version is not None else PSK_VERSION) + for _ in range(int(headers)): + out.append(_chunk("ACTRHEAD", 0, 0, b"", ver)) + + out.append(_chunk("PNTS0000", 12, n_point, + b"".join(struct.pack("<3f", *p) for p in psk.points))) + out.append(_chunk("VTXW0000", 16, n_wedge, + b"".join(struct.pack("= 10(AttributeFormatRestructure) + 头部: 同上,但在 ObjectName 之后多了 FString ObjectPath + 主体: FDataAttributeSet = i32 Count + Count × (FString Name + i32 ByteSize + 负载) + 数组长度写在负载内部的 TArray 前缀里(i32 Count + 元素)。 + +读取端按版本自动分派;写出端两版都能写。 + +坐标与单位(实测样本 + UE 约定) + UE 是**左手系、Z 轴向上**,X 向前、Y 向右;1 单位 = 1 cm。 + MMD/PMX 是左手系、Y 轴向上、脸朝 -Z。两边手性相同(行列式 +1), + 所以只需要换轴、**不需要反绕序**(见 convert/uemodel2pmx.py)。 + +自检口径:`read_uemodel()` 结束时必须 `r.p == len(r.b)`,与 pmxio 的 +`consumed == filesize` 一个路子;分块负载也逐个按 ByteSize 切片消费, +任何一段读偏都会在末尾暴露成「末尾字节数不符」。 +""" + +import os +import struct +import sys + +MAGIC = b"UEFORMAT" +IDENT_MODEL = "UEMODEL" + +VERSION_LATEST = 10 # AttributeFormatRestructure +V_SERIALIZE_BINORMAL = 1 # NORMALS 里开始带 binormalSign +V_MULTI_VCOLOR = 2 # VERTEXCOLORS 支持多套 +V_LOD_RESTRUCTURE = 4 # LOD 变成 name + 独立大小 +V_VIRTUAL_BONES = 5 +V_MATERIAL_PATH = 6 +V_ASSET_METADATA = 7 +V_PRESERVE_TRANSFORM = 8 # BONES 带 scale +V_ATTR_RESTRUCTURE = 10 # 布局大改(见模块 docstring) + + +def _repair_version(v): + """老版本写出来的 0 号版本其实等于 1(BinormalSign 已经在了)。""" + return V_SERIALIZE_BINORMAL if v == 0 else v + + +# ------------------------------------------------------------------ 数据结构 -- +class Bone(object): + __slots__ = ("name", "parent", "pos", "rot", "scale") + + def __init__(self, name="", parent=-1, pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), scale=(1.0, 1.0, 1.0)): + self.name = name + self.parent = parent + self.pos = pos + self.rot = rot + self.scale = scale + + +class Socket(object): + __slots__ = ("name", "bone", "pos", "rot", "scale") + + def __init__(self, name="", bone="", pos=(0.0, 0.0, 0.0), + rot=(0.0, 0.0, 0.0, 1.0), scale=(1.0, 1.0, 1.0)): + self.name = name + self.bone = bone + self.pos = pos + self.rot = rot + self.scale = scale + + +class Skeleton(object): + __slots__ = ("path", "bones", "sockets", "virtual_bones") + + def __init__(self): + self.path = "" + self.bones = [] + self.sockets = [] + self.virtual_bones = [] # [(source, target, virtual)] + + +class VertexColor(object): + __slots__ = ("name", "data") # data: [(r,g,b,a)] 0~255 + + def __init__(self, name="COL0", data=None): + self.name = name + self.data = data or [] + + +class Material(object): + __slots__ = ("name", "path", "first_index", "num_faces") + + def __init__(self, name="", path="", first_index=0, num_faces=0): + self.name = name + self.path = path + self.first_index = first_index # 索引入缓冲(顶点索引)里的起点 + self.num_faces = num_faces # 三角面数 + + @property + def first_face(self): + return self.first_index // 3 + + +class Weight(object): + __slots__ = ("bone", "vertex", "weight") + + def __init__(self, bone=0, vertex=0, weight=0.0): + self.bone = bone + self.vertex = vertex + self.weight = weight + + +class MorphDelta(object): + __slots__ = ("pos", "normal", "vertex") + + def __init__(self, pos=(0.0, 0.0, 0.0), normal=(0.0, 0.0, 0.0), vertex=0): + self.pos = pos + self.normal = normal + self.vertex = vertex + + +class Morph(object): + __slots__ = ("name", "deltas") + + def __init__(self, name="", deltas=None): + self.name = name + self.deltas = deltas or [] + + +class UVSet(object): + __slots__ = ("name", "uvs") + + def __init__(self, name="UV0", uvs=None): + self.name = name + self.uvs = uvs or [] + + +class Collision(object): + __slots__ = ("name", "vertices", "indices", "faces") + + def __init__(self, name="", vertices=None, indices=None): + self.name = name + self.vertices = vertices or [] + self.indices = indices or [] + + +class LOD(object): + def __init__(self, name="LOD0"): + self.name = name + self.vertices = [] # [(x, y, z)] + self.normals = [] # [(x, y, z)] + self.binormals = [] # 每顶点 binormal sign(FNormal 的第一个 float) + self.tangents = [] # [(x, y, z)] + self.uvs = [] # [UVSet] + self.indices = [] # 三角面顶点索引(每 3 个一面) + self.colors = [] # [VertexColor] + self.materials = [] # [Material] + self.weights = [] # [Weight](稀疏:一个顶点可能有多条) + self.morphs = [] # [Morph] + + def stats(self): + return {"verts": len(self.vertices), "tris": len(self.indices) // 3, + "mats": len(self.materials), "weights": len(self.weights), + "morphs": len(self.morphs), "uvsets": len(self.uvs)} + + +class UEModel(object): + def __init__(self): + self.identifier = IDENT_MODEL + self.version = VERSION_LATEST + self.name = "" + self.path = "" + self.compressed = False + self.lods = [] + self.skeleton = Skeleton() + self.collisions = [] + + def stats(self): + return {"version": self.version, "lods": len(self.lods), + "bones": len(self.skeleton.bones), + "sockets": len(self.skeleton.sockets), + "collisions": len(self.collisions), + "skinned": bool(self.lods and self.lods[0].weights)} + + +# --------------------------------------------------------------------- 读取 -- +class _R(object): + __slots__ = ("b", "p") + + def __init__(self, data): + self.b = data + self.p = 0 + + def eof(self): + return self.p >= len(self.b) + + def left(self): + return len(self.b) - self.p + + def u8(self): + v = self.b[self.p] + self.p += 1 + return v + + def bool(self): + return self.u8() != 0 + + def i16(self): + v = struct.unpack_from(" 0 else () + self.p += 4 * n + return v + + def bytes(self, n): + v = self.b[self.p:self.p + n] + self.p += n + return v + + def fstr(self): + n = self.i32() + if n <= 0: + return "" + raw = self.b[self.p:self.p + n] + self.p += n + return raw.rstrip(b"\x00").decode("utf-8", "replace") + + +def _chunks(r, version): + """按版本迭代「分块」,产出 (name, array_size, payload_reader)。 + + 负载一律按声明字节数切出来单独给一个 reader —— 与官方 iter_chunks 的 + 「读完 seek 到下一个块」等价,任何一段读偏都不会污染后面的分块。 + """ + if version >= V_ATTR_RESTRUCTURE: + count = r.i32() + for _ in range(count): + name = r.fstr() + size = r.i32() + yield name, None, _R(r.bytes(max(0, size))) + else: + while not r.eof(): + name = r.fstr() + arr = r.i32() + size = r.i32() + yield name, arr, _R(r.bytes(max(0, size))) + + +def _arr_len(payload, version, array_size): + """取「数组元素个数」:v10 在负载里,v9 在分块头。""" + if version >= V_ATTR_RESTRUCTURE: + return payload.i32() + return array_size if array_size is not None else 0 + + +def _read_lod(r, version): + lod = LOD(name=r.fstr()) + if version >= V_ATTR_RESTRUCTURE: + body = r + else: + body = _R(r.bytes(max(0, r.i32()))) + + for name, arr, pl in _chunks(body, version): + if name == "VERTICES": + n = _arr_len(pl, version, arr) + lod.vertices = [tuple(pl.vec(3)) for _ in range(n)] + elif name == "NORMALS": + n = _arr_len(pl, version, arr) + if version >= V_SERIALIZE_BINORMAL: + for _ in range(n): + sign = pl.f32() + lod.binormals.append(sign) + lod.normals.append(tuple(pl.vec(3))) + else: + lod.normals = [tuple(pl.vec(3)) for _ in range(n)] + elif name == "TANGENTS": + n = _arr_len(pl, version, arr) + lod.tangents = [tuple(pl.vec(3)) for _ in range(n)] + elif name == "TEXCOORDS": + n = _arr_len(pl, version, arr) + for _ in range(n): + # v10 起每个 UV 通道带名字,v9 没有 + uname = pl.fstr() if version >= V_ATTR_RESTRUCTURE else "" + c = pl.i32() + uv = [tuple(pl.vec(2)) for _ in range(max(0, c))] + lod.uvs.append(UVSet(uname or ("UV%d" % len(lod.uvs)), uv)) + elif name == "INDICES": + n = _arr_len(pl, version, arr) + lod.indices = list(pl.ints(max(0, n))) + elif name == "VERTEXCOLORS": + n = _arr_len(pl, version, arr) + for _ in range(n): + vc = VertexColor(name="COL0") + if version >= V_MULTI_VCOLOR: + vc.name = pl.fstr() + c = pl.i32() + raw = pl.bytes(max(0, c) * 4) + vc.data = [tuple(raw[i * 4:i * 4 + 4]) for i in range(max(0, c))] + lod.colors.append(vc) + elif name == "MATERIALS": + n = _arr_len(pl, version, arr) + for _ in range(n): + mat = Material(name=pl.fstr()) + if version >= V_MATERIAL_PATH: + mat.path = pl.fstr() + mat.first_index = pl.i32() + mat.num_faces = pl.i32() + lod.materials.append(mat) + elif name == "WEIGHTS": + n = _arr_len(pl, version, arr) + for _ in range(n): + b = pl.u16() if version >= V_ATTR_RESTRUCTURE else pl.i16() + lod.weights.append(Weight(b, pl.i32(), pl.f32())) + elif name == "MORPHTARGETS": + n = _arr_len(pl, version, arr) + for _ in range(n): + mo = Morph(name=pl.fstr()) + c = pl.i32() + for _ in range(max(0, c)): + p = tuple(pl.vec(3)) + nn = tuple(pl.vec(3)) + mo.deltas.append(MorphDelta(p, nn, pl.i32())) + lod.morphs.append(mo) + # 未知分块按声明大小跳过(已经按 ByteSize 切片,天然安全) + return lod + + +def _read_bones(payload, n, version): + """骨骼数组:v10 带 scale;v9 不带。带自动回退以兼容不同写入器。""" + with_scale = version >= V_ATTR_RESTRUCTURE + bones = [] + try: + for _ in range(n): + b = Bone(name=payload.fstr()) + b.parent = payload.i32() + b.pos = tuple(payload.vec(3)) + b.rot = tuple(payload.vec(4)) + b.scale = tuple(payload.vec(3)) if with_scale else () + bones.append(b) + except struct.error: + return None + if payload.p != len(payload.b): + return None + if not with_scale: + # 若按「无 scale」读却没正好吃到末尾,改按「有 scale」重来 + alt = _R(payload.b) + bones2 = [] + try: + for _ in range(n): + b = Bone(name=alt.fstr()) + b.parent = alt.i32() + b.pos = tuple(alt.vec(3)) + b.rot = tuple(alt.vec(4)) + b.scale = tuple(alt.vec(3)) + bones2.append(b) + except struct.error: + return bones + if alt.p == len(alt.b): + return bones2 + return bones + + +def _read_skeleton(r, version): + sk = Skeleton() + for name, arr, pl in _chunks(r, version): + if name == "METADATA": + sk.path = pl.fstr() + elif name == "BONES": + n = _arr_len(pl, version, arr) + got = _read_bones(pl, max(0, n), version) + if got is not None: + sk.bones = got + elif name == "SOCKETS": + n = _arr_len(pl, version, arr) + for _ in range(max(0, n)): + s = Socket(name=pl.fstr(), bone=pl.fstr()) + s.pos = tuple(pl.vec(3)) + s.rot = tuple(pl.vec(4)) + s.scale = tuple(pl.vec(3)) + sk.sockets.append(s) + elif name == "VIRTUALBONES": + n = _arr_len(pl, version, arr) + for _ in range(max(0, n)): + sk.virtual_bones.append((pl.fstr(), pl.fstr(), pl.fstr())) + return sk + + +def _read_collision(h, version): + col = Collision(name=h.fstr()) + nv = h.i32() + col.vertices = [tuple(h.vec(3)) for _ in range(max(0, nv))] + ni = h.i32() + col.indices = list(h.ints(max(0, ni))) + return col + + +def _decompress_body(r, src): + """读取压缩体头部并解压,返回未压缩的字节流(分块流)。 + + 支持 UEFormat 已用到的两种压缩:ZSTD(需 zstandard 第三方库)、 + GZIP(标准库 gzip)。压缩体头部布局见 parse_uemodel 中的说明。 + """ + import io + cfmt = (r.fstr() or "").upper() + uncompressed = r.i32() + compressed = r.i32() + payload = r.bytes(compressed) if compressed > 0 else r.left() + + if cfmt == "ZSTD": + try: + import zstandard as zstd + except ImportError: + raise ValueError("该 .uemodel 是 ZSTD 压缩体,但运行环境缺少 zstandard 库," + "无法解压:%s" % src) + dctx = zstd.ZstdDecompressor() + try: + if uncompressed > 0: + return dctx.decompress(payload, uncompressed) + # 帧内未记录原始大小:改用流式解压读完整帧 + with dctx.stream_reader(io.BytesIO(payload)) as reader: + return reader.read() + except Exception as e: + raise ValueError("ZSTD 解压失败:%s(%s)" % (src, e)) + elif cfmt in ("GZIP", "GZIPSTREAM"): + import gzip + try: + return gzip.decompress(payload) + except Exception as e: + raise ValueError("GZIP 解压失败:%s(%s)" % (src, e)) + else: + raise ValueError("不支持的压缩格式 %r:%s" % (cfmt, src)) + + +def read_uemodel(path, verbose=False): + """读 .uemodel。返回 UEModel;末尾字节数不符直接抛 ValueError。""" + with open(path, "rb") as f: + data = f.read() + return parse_uemodel(data, verbose=verbose, src=path) + + +def parse_uemodel(data, verbose=False, src=""): + r = _R(data) + if r.bytes(8) != MAGIC: + raise ValueError("不是 UEFormat 文件(魔数不是 UEFORMAT):%s" % src) + + m = UEModel() + m.identifier = r.fstr() + m.version = r.u8() + m.name = r.fstr() + if m.version >= V_ATTR_RESTRUCTURE: + m.path = r.fstr() # v10 起才有 ObjectPath + m.compressed = r.bool() + if m.compressed: + # 压缩体头部紧跟在 bIsCompressed 之后(UEFormat 规范): + # FString CompressionFormat + i32 UncompressedSize + # + i32 CompressedSize + CompressedData + # 解压后得到的就是未压缩的「分块流」,从偏移 0 起按普通流程解析即可。 + raw = _decompress_body(r, src) + r = _R(raw) + + if m.identifier not in ("UEMODEL", ""): + raise ValueError("不是模型文件(Identifier=%r):%s" % (m.identifier, src)) + if m.version > VERSION_LATEST: + raise ValueError("UEFormat 版本 %d 高于本库支持的 %d:%s" + % (m.version, VERSION_LATEST, src)) + + ver = _repair_version(m.version) + for name, arr, pl in _chunks(r, ver): + if name == "LODS": + n = _arr_len(pl, ver, arr) + for _ in range(max(0, n)): + m.lods.append(_read_lod(pl, ver)) + elif name == "SKELETON": + m.skeleton = _read_skeleton(pl, ver) + elif name == "COLLISION": + n = _arr_len(pl, ver, arr) + for _ in range(max(0, n)): + m.collisions.append(_read_collision(pl, ver)) + # 未知顶层分块忽略 + + if r.p != len(r.b): + raise ValueError("解析失步:消费 %d 字节,文件 %d 字节(差 %d)" + % (r.p, len(r.b), len(r.b) - r.p)) + if verbose: + print_uemodel(m, src=src) + return m + + +# --------------------------------------------------------------------- 写出 -- +class _W(object): + __slots__ = ("buf",) + + def __init__(self): + self.buf = bytearray() + + def u8(self, v): + self.buf.append(v & 0xFF) + + def bool(self, v): + self.u8(1 if v else 0) + + def i16(self, v): + self.buf += struct.pack("= V_ATTR_RESTRUCTURE: + w.i32(len(items)) + for name, arr, payload in items: + w.raw(_pack_chunk(name, arr, payload, version)) + return w.get() + + +def _pack_vec_array(vecs, version, width=3): + w = _W() + if version >= V_ATTR_RESTRUCTURE: + w.i32(len(vecs)) + for v in vecs: + w.vec(v) + return w.get() + + +def _pack_indices(idx, version): + w = _W() + if version >= V_ATTR_RESTRUCTURE: + w.i32(len(idx)) + for v in idx: + w.u32(v) + return w.get() + + +def _pack_lod(lod, version): + w = _W() + items = [] + nv = len(lod.vertices) + + items.append(("VERTICES", nv, _pack_vec_array(lod.vertices, version))) + + nrm = _W() + if version >= V_ATTR_RESTRUCTURE: + nrm.i32(nv) + for i in range(nv): + n = lod.normals[i] if i < len(lod.normals) else (0.0, 0.0, 1.0) + sign = lod.binormals[i] if i < len(lod.binormals) else 1.0 + nrm.f32(sign) + nrm.vec(n) + if version < V_SERIALIZE_BINORMAL: + # 极老版本(本库不产出):只写向量 + old = _W() + for i in range(nv): + old.vec(lod.normals[i] if i < len(lod.normals) else (0.0, 1.0, 0.0)) + items.append(("NORMALS", nv, old.get())) + else: + items.append(("NORMALS", nv, nrm.get())) + + if lod.tangents: + items.append(("TANGENTS", nv, _pack_vec_array(lod.tangents, version))) + + tex = _W() + if version >= V_ATTR_RESTRUCTURE: + tex.i32(len(lod.uvs)) + for i, st in enumerate(lod.uvs): + if version >= V_ATTR_RESTRUCTURE: + tex.fstr(st.name or ("UV%d" % i)) + tex.i32(len(st.uvs)) + for uv in st.uvs: + tex.vec(uv) + items.append(("TEXCOORDS", len(lod.uvs), tex.get())) + + items.append(("INDICES", len(lod.indices), + _pack_indices(lod.indices, version))) + + if lod.colors: + vc = _W() + if version >= V_ATTR_RESTRUCTURE: + vc.i32(len(lod.colors)) + for st in lod.colors: + if version >= V_MULTI_VCOLOR: + vc.fstr(st.name or "COL0") + vc.i32(len(st.data)) + for c in st.data: + vc.u8(c[0] if len(c) > 0 else 255) + vc.u8(c[1] if len(c) > 1 else 255) + vc.u8(c[2] if len(c) > 2 else 255) + vc.u8(c[3] if len(c) > 3 else 255) + items.append(("VERTEXCOLORS", len(lod.colors), vc.get())) + + if lod.materials: + mm = _W() + if version >= V_ATTR_RESTRUCTURE: + mm.i32(len(lod.materials)) + for mt in lod.materials: + mm.fstr(mt.name) + if version >= V_MATERIAL_PATH: + mm.fstr(mt.path) + mm.i32(mt.first_index) + mm.i32(mt.num_faces) + items.append(("MATERIALS", len(lod.materials), mm.get())) + + if lod.weights: + wt = _W() + if version >= V_ATTR_RESTRUCTURE: + wt.i32(len(lod.weights)) + for x in lod.weights: + if version >= V_ATTR_RESTRUCTURE: + wt.u16(x.bone) + else: + wt.i16(x.bone) + wt.i32(x.vertex) + wt.f32(x.weight) + items.append(("WEIGHTS", len(lod.weights), wt.get())) + + if lod.morphs: + mo = _W() + if version >= V_ATTR_RESTRUCTURE: + mo.i32(len(lod.morphs)) + for m in lod.morphs: + mo.fstr(m.name) + mo.i32(len(m.deltas)) + for d in m.deltas: + mo.vec(d.pos) + mo.vec(d.normal) + mo.i32(d.vertex) + items.append(("MORPHTARGETS", len(lod.morphs), mo.get())) + + body = _pack_attrset(items, version) + if version >= V_ATTR_RESTRUCTURE: + # v10 的 UEModelLOD = FString Name + FDataAttributeSet(规范 docs/uemodel.md): + # 名字照写,但属性集**自带** i32 Count 定界,不再套一层 ByteSize。 + # 曾经漏写这里的名 → 读取端读了名,整条 LOD 流错位,末尾报「解析失步」。 + w.fstr(lod.name or "") + w.raw(body) + else: + w.fstr(lod.name) + w.i32(len(body)) + w.raw(body) + return w.get() + + +def _pack_skeleton(sk, version): + items = [] + if sk.path: + w = _W() + w.fstr(sk.path) + items.append(("METADATA", 1, w.get())) + + bw = _W() + if version >= V_ATTR_RESTRUCTURE: + bw.i32(len(sk.bones)) + for b in sk.bones: + bw.fstr(b.name) + bw.i32(b.parent) + bw.vec(b.pos) + bw.vec(b.rot if len(b.rot) == 4 else (0.0, 0.0, 0.0, 1.0)) + if version >= V_ATTR_RESTRUCTURE: + bw.vec(b.scale if len(b.scale) == 3 else (1.0, 1.0, 1.0)) + items.append(("BONES", len(sk.bones), bw.get())) + + if sk.sockets: + sw = _W() + if version >= V_ATTR_RESTRUCTURE: + sw.i32(len(sk.sockets)) + for s in sk.sockets: + sw.fstr(s.name) + sw.fstr(s.bone) + sw.vec(s.pos) + sw.vec(s.rot) + sw.vec(s.scale) + items.append(("SOCKETS", len(sk.sockets), sw.get())) + + if sk.virtual_bones: + vw = _W() + if version >= V_ATTR_RESTRUCTURE: + vw.i32(len(sk.virtual_bones)) + for t in sk.virtual_bones: + vw.fstr(t[0]) + vw.fstr(t[1]) + vw.fstr(t[2]) + items.append(("VIRTUALBONES", len(sk.virtual_bones), vw.get())) + + return _pack_attrset(items, version) + + +def _pack_collision(col, version): + w = _W() + w.fstr(col.name) + w.i32(len(col.vertices)) + for v in col.vertices: + w.vec(v) + w.i32(len(col.indices)) + for i in col.indices: + w.i32(i) + return w.get() + + +def build_uemodel_bytes(m, version=None): + """把 UEModel 序列化成字节。version=None 用 m.version。""" + ver = _repair_version(int(version if version else m.version)) + w = _W() + w.raw(MAGIC) + w.fstr(m.identifier or IDENT_MODEL) + w.u8(ver) + w.fstr(m.name) + if ver >= V_ATTR_RESTRUCTURE: + w.fstr(m.path or "") + w.bool(False) + + items = [] + lw = _W() + if ver >= V_ATTR_RESTRUCTURE: + lw.i32(len(m.lods)) + for lod in m.lods: + lw.raw(_pack_lod(lod, ver)) + items.append(("LODS", len(m.lods), lw.get())) + + items.append(("SKELETON", 1, _pack_skeleton(m.skeleton, ver))) + + if m.collisions: + cw = _W() + if ver >= V_ATTR_RESTRUCTURE: + cw.i32(len(m.collisions)) + for col in m.collisions: + cw.raw(_pack_collision(col, ver)) + items.append(("COLLISION", len(m.collisions), cw.get())) + + w.raw(_pack_attrset(items, ver)) + return w.get() + + +def write_uemodel(m, path, version=None): + data = build_uemodel_bytes(m, version=version) + tmp = path + ".tmp" + with open(tmp, "wb") as f: + f.write(data) + os.replace(tmp, path) + return len(data) + + +# ----------------------------------------------------------------- 文本输出 -- +def print_uemodel(m, src=""): + if src: + print("文件:%s" % src) + print("UEFormat v%d · %s · 名称 %s" % (m.version, m.identifier, m.name)) + if m.path: + print(" 资源路径:%s" % m.path) + sk = m.skeleton + print(" 骨骼 %d · 插槽 %d · 虚拟骨 %d · 碰撞 %d" + % (len(sk.bones), len(sk.sockets), len(sk.virtual_bones), + len(m.collisions))) + if sk.path: + print(" 骨骼资源:%s" % sk.path) + for i, lod in enumerate(m.lods): + st = lod.stats() + print(" LOD[%d] %-8s 顶点 %d · 三角面 %d · 材质 %d · 权重 %d · 表情 %d · UV %d" + % (i, lod.name, st["verts"], st["tris"], st["mats"], + st["weights"], st["morphs"], st["uvsets"])) + for mt in lod.materials[:40]: + print(" 材质 %-42s 面 %6d 起 %d" + % (mt.name[:42], mt.num_faces, mt.first_index)) + if len(lod.materials) > 40: + print(" …另有 %d 个材质" % (len(lod.materials) - 40)) + for mo in lod.morphs[:40]: + print(" 表情 %-30s 顶点 %d" % (mo.name[:30], len(mo.deltas))) + if len(lod.morphs) > 40: + print(" …另有 %d 个表情" % (len(lod.morphs) - 40)) + if sk.bones: + print(" 前 12 根骨骼:") + for b in sk.bones[:12]: + print(" %-28s parent=%-4d pos=(%.3f, %.3f, %.3f)" + % (b.name[:28], b.parent, b.pos[0], b.pos[1], b.pos[2])) + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + if not argv: + print("用法:python formats/uemodelio.py [--roundtrip]") + return 1 + path = argv[0] + m = read_uemodel(path, verbose=True) + if "--roundtrip" in argv: + for ver in (9, 10): + tmp = os.path.join(os.path.dirname(os.path.abspath(path)), "_rt_v%d.uemodel" % ver) + write_uemodel(m, tmp, version=ver) + back = read_uemodel(tmp) + ok = (len(back.lods) == len(m.lods) + and back.skeleton.bones and len(back.skeleton.bones) == len(m.skeleton.bones)) + print("往返 v%d:%d 字节 → %s" % (ver, os.path.getsize(tmp), + "一致" if ok else "不一致")) + os.remove(tmp) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/formats/unityasset.py b/formats/unityasset.py new file mode 100644 index 0000000..b8c4ccf --- /dev/null +++ b/formats/unityasset.py @@ -0,0 +1,270 @@ +# -*- coding: utf-8 -*- +"""Unity 工程 / 解开的 unitypackage 里的材质 → 底色贴图。 + +Unity 导出的 FBX 常常不带贴图文件名(Texture 节点的 FileName 是空的),贴图是在 Unity 的 +材质(.mat,YAML 文本)里按 GUID 指定的: + + m_Name: mat_Body + m_TexEnvs: _MainTex / _Main_Texture / _BaseMap … → m_Texture: {fileID: 2800000, guid: 1db2…} + +而 GUID 写在贴图旁边的 .meta 里(`guid: 1db2…`)。这里把两边对起来:材质名 → 贴图路径。 +FBX 里的材质名和 .mat 的 m_Name 一致(Unity 导入 FBX 时按材质名找 / 建 .mat)。 + +新旧两种 .mat 序列化格式都认: + * Unity 5+: m_TexEnvs:\\n - _MainTex:\\n m_Texture: {…} + * Unity 4.x: m_TexEnvs:\\n data:\\n first:\\n name: _MainTex\\n second:\\n m_Texture: {…} +二进制序列化的 .mat 读不了,跳过。 +""" +import os +import re + +IMAGE_EXT = (".png", ".tga", ".jpg", ".jpeg", ".bmp", ".dds", ".psd", ".tif", ".tiff") +# 当底色用的槽位,按优先级 +MAIN_SLOTS = ("_maintex", "_main_texture", "_basemap", "_basecolormap", "_basetexture", "_albedo", + "_albedomap", "_diffuse", "_diffusemap", "_colortex", "_tex") +# 当主色用的槽位,按优先级(_ShadeColor / _OutlineColor 这些不能当底色) +COLOR_SLOTS = ("_color", "_basecolor", "_maincolor", "_tintcolor", "_diffusecolor", + "_maintexcolor", "_color0", "_basecolour", "_maincolour", "_colour") +NOT_MAIN = ("normal", "bump", "spec", "metal", "rough", "occlusion", "emission", "emissive", "mask", + "matcap", "sphere", "ramp", "shade", "outline", "rim", "detail", "parallax", "height", "noise") + +_GUID = re.compile(r"guid:\s*([0-9a-fA-F]{32})") +_NAME = re.compile(r"^\s*m_Name:\s*(.*?)\s*$", re.M) +_COLOR = re.compile(r"\{\s*r:\s*([-+0-9.eE]+)\s*,\s*g:\s*([-+0-9.eE]+)\s*," + r"\s*b:\s*([-+0-9.eE]+)\s*,\s*a:\s*([-+0-9.eE]+)\s*\}") +# Toon shader 的描边在 shader 的 Outline pass 里,参数只写在 .mat(FBX 没有对应信息) +OUTLINE_WIDTH_SLOTS = ("_outline_width", "_outlinewidth", "_outline_size", "_outlinesize") +OUTLINE_COLOR_SLOTS = ("_outline_color", "_outlinecolor") + + +def find_root(start, max_up=8): + """Unity 资源的根:往上找 Assets 文件夹;没有(解开的 unitypackage 去掉了 Assets/)时, + 只要上一层还像 Unity 资源文件夹(有 .meta 文件)就继续往上,最后至少往上两层。""" + d = os.path.abspath(start) + for _ in range(max_up): + if os.path.basename(d).lower() == "assets": + return d + parent = os.path.dirname(d) + if parent == d: + break + d = parent + d = os.path.abspath(start) + for k in range(max_up): + parent = os.path.dirname(d) + if parent == d: + break + try: + unityish = any(n.lower().endswith(".meta") for n in os.listdir(parent)) + except OSError: + unityish = False + if not unityish and k >= 2: + break + d = parent + return d + + +def _walk(root, limit): + n = 0 + for d, dirs, files in os.walk(root): + dirs[:] = [x for x in dirs if x.lower() not in ("library", "temp", "obj", ".git", "node_modules")] + for f in files: + n += 1 + if n > limit: + return + yield d, f + + +def _slots(text): + """→ [(槽位名, guid)],按文件里的顺序。""" + out = [] + i = text.find("m_TexEnvs:") + if i < 0: + return out + end = len(text) + for key in ("m_Floats:", "m_Ints:", "m_Colors:"): + j = text.find(key, i) + if j > 0: + end = min(end, j) + block = text[i:end] + # Unity 5+: - _MainTex: Unity 4: name: _MainTex + marks = [(m.start(), m.group(1)) for m in re.finditer(r"^\s*-\s*([A-Za-z_][\w]*):\s*$", block, re.M)] + marks += [(m.start(), m.group(1)) for m in re.finditer(r"^\s*name:\s*([A-Za-z_][\w]*)\s*$", block, re.M)] + marks.sort() + for k, (pos, name) in enumerate(marks): + seg = block[pos:marks[k + 1][0] if k + 1 < len(marks) else len(block)] + m = re.search(r"m_Texture:\s*\{[^}]*\}", seg) + if not m: + continue + g = _GUID.search(m.group(0)) # 空槽位是 {fileID: 0},没有 guid + if g: + out.append((name, g.group(1).lower())) + return out + + +def _main_guid(slots): + if not slots: + return None + by = {n.lower(): g for n, g in slots} + for s in MAIN_SLOTS: + if s in by: + return by[s] + for n, g in slots: + if not any(k in n.lower() for k in NOT_MAIN): + return g + return None + + +def _colors(text): + """→ {颜色槽位名(小写): [r, g, b, a]}。 + + Unity 5+ 写 `- _Color: {r: 0, g: 0, b: 0, a: 1}`,Unity 4.x 写 + `name: _Color` 再在 second 段里给 `{r: …, a: …}`(字段名可能是 val / m_Color); + m_Colors 也可能套在 m_SavedProperties 里。两种都按块扫描。 + """ + i = text.find("m_Colors:") + if i < 0: + return {} + end = len(text) + for key in ("m_TexEnvs:", "m_Floats:", "m_Ints:", "m_SavedProperties:", "---"): + j = text.find(key, i + len("m_Colors:")) + if j > 0: + end = min(end, j) + block = text[i:end] + out = {} + for m in re.finditer(r"^\s*-\s*([A-Za-z_][\w]*):\s*(\{[^}]*\})", block, re.M): + v = _COLOR.search(m.group(2)) + if v: + out[m.group(1).lower()] = [float(x) for x in v.groups()] + marks = [(m.start(), m.group(1)) for m in + re.finditer(r"^\s*name:\s*([A-Za-z_][\w]*)\s*$", block, re.M)] + for k, (pos, name) in enumerate(marks): + seg = block[pos:marks[k + 1][0] if k + 1 < len(marks) else len(block)] + v = _COLOR.search(seg) + if v: + out[name.lower()] = [float(x) for x in v.groups()] + return out + + +def _main_color(colors): + """→ 底色 [r, g, b, a];只认主色槽位,阴影色 / 描边色不算。""" + if not colors: + return None + for s in COLOR_SLOTS: + if s in colors: + return colors[s] + for n, c in colors.items(): + if not any(k in n for k in NOT_MAIN): + return c + return None + + +def _floats(text): + """→ {属性名(小写): float},m_Floats 段里的 `- _Key: 1.0`。""" + i = text.find("m_Floats:") + if i < 0: + return {} + end = len(text) + for key in ("m_Colors:", "m_TexEnvs:", "m_Ints:", "m_BuildTextureStacks:", "---"): + j = text.find(key, i + len("m_Floats:")) + if j > 0: + end = min(end, j) + out = {} + for m in re.finditer(r"^\s*-\s*([A-Za-z_][\w]*):\s*([-+0-9.eE]+)\s*$", text[i:end], re.M): + try: + out[m.group(1).lower()] = float(m.group(2)) + except ValueError: + pass + return out + + +def _outline(text): + """→ {"width", "color": [r,g,b], "mode"} 或 None。 + + UCTS / Toon_DoubleShadeWithFeather 这类 shader 的描边是一个额外的 Outline pass: + `m_ShaderKeywords` 里有 `_OUTLINE_NML` / `_OUTLINE_POS`,宽度在 `m_Floats._Outline_Width`、 + 颜色在 `m_Colors._Outline_Color`。FBX 里完全没有对应信息,必须在这里读出来。 + 注意 `_OUTLINE` 只是 NML/POS 模式枚举(0 = NML),不是开关;宽度 > 0 才算开了描边。 + """ + fl = _floats(text) + width = next((fl[k] for k in OUTLINE_WIDTH_SLOTS if fl.get(k, 0) > 0), 0.0) + if width <= 0: + return None + col = _colors(text) + rgb = next((col[k][:3] for k in OUTLINE_COLOR_SLOTS if k in col), [0.0, 0.0, 0.0]) + return {"width": width, "color": [float(x) for x in rgb], + "mode": "POS" if "_OUTLINE_POS" in text else "NML"} + + +def material_properties(start, limit=50000): + """→ {材质名: {"tex": 底色贴图绝对路径或 None, "color": [r,g,b,a] 或 None}}。 + + start 是 FBX 所在文件夹。没有贴图、只有 m_Colors 的材质(Toon shader 的纯黑 / + 纯白)也在这里返回,颜色交给 fbx2pmx 烘焙成一张纯色贴图;找不到 Unity 资源返回 {}。 + """ + root = find_root(start) + guid_path = {} + mats = [] + for d, f in _walk(root, limit): + low = f.lower() + if low.endswith(".meta"): + asset = f[:-5] + if asset.lower().endswith(IMAGE_EXT): + try: + with open(os.path.join(d, f), encoding="utf-8", errors="replace") as fh: + m = _GUID.search(fh.read(2000)) + except OSError: + continue + if m and os.path.isfile(os.path.join(d, asset)): + guid_path[m.group(1).lower()] = os.path.join(d, asset) + elif low.endswith(".mat"): + mats.append(os.path.join(d, f)) + # 注意不能因为「一张图片 .meta 都没有」就提前返回:纯色材质的 .mat 里本来就没有 + # 贴图 GUID,以前的 `not mats or not guid_path` 会把它们全部丢掉。 + if not mats: + return {} + # 同名材质可能有好几份(每套衣服一个文件夹,各有一个 mat_Hair)。按 Unity 导入 FBX 时的 + # 查找顺序(Recursive-Up)挑:FBX 所在文件夹及其 Materials/,再往上一层……直到 Assets; + # 都不在这条链上的(别的角色 / 别的衣服的材质)排最后 + chain = [] + d = os.path.normcase(os.path.abspath(start)) + while True: + chain.append(d) + if os.path.basename(d).lower() == "assets" or os.path.dirname(d) == d: + break + d = os.path.dirname(d) + + def rank(mat_path): + md = os.path.normcase(os.path.dirname(os.path.abspath(mat_path))) + for k, a in enumerate(chain): + if md.lower() == a.lower() or md.lower() == os.path.join(a, "materials").lower(): + return k + return 1000 + + best = {} + for p in mats: + try: + with open(p, "rb") as fh: + raw = fh.read(200000) + except OSError: + continue + if not raw.startswith(b"%YAML"): + continue # 二进制序列化的材质 + text = raw.decode("utf-8", "replace") + nm = _NAME.search(text) + name = nm.group(1).strip().strip('"') if nm else os.path.splitext(os.path.basename(p))[0] + tex = guid_path.get(_main_guid(_slots(text)) or "") + color = _main_color(_colors(text)) + outline = _outline(text) + if tex is None and color is None and outline is None: + continue + r = rank(p) + prop = {"tex": tex, "color": color, "outline": outline} + for key in {name, os.path.splitext(os.path.basename(p))[0]}: + if key not in best or r < best[key][0]: + best[key] = (r, prop) + return {k: v[1] for k, v in best.items()} + + +def material_textures(start, limit=50000): + """→ {材质名: 底色贴图的绝对路径}。兼容旧调用,只返回有贴图的材质。""" + return {k: v["tex"] for k, v in material_properties(start, limit).items() if v["tex"]} diff --git a/formats/unitypackage_unpack.py b/formats/unitypackage_unpack.py new file mode 100644 index 0000000..69f6207 --- /dev/null +++ b/formats/unitypackage_unpack.py @@ -0,0 +1,140 @@ +"""Unpack a .unitypackage without Unity. + +一个 .unitypackage 只是一个经过 gzip 压缩的 tar 归档文件。每个资源都存放在一个以其 32 位十六进制 GUID 命名的文件夹中,该文件夹包含: + asset the real file (FBX, prefab, png, ...) + asset.meta Unity metadata (importer type, guid) + pathname original path inside Assets/ + preview.png optional thumbnail + +解包后的落盘规则: + asset → <输出目录>/ 例:.../FBX/model.fbx + 辅助文件 → 与资产同层,名字带上资产名 例:.../FBX/model.fbx.meta + (asset.meta → <名>.meta,pathname / preview.png → <名>.pathname 等) + 文件夹资源 → 建出同名空文件夹(tar 里没有它的 asset 本体) +辅助文件之所以带上资产名,是因为同一目录下常有两个以上资产,若统一叫 +asset.meta / pathname 就会互相覆盖,只剩最后一个。 + +Usage: + python unitypackage_unpack.py [-o OUTDIR] [--list] + +# 先看包里有什么(不解包) +python unitypackage_unpack.py "Sexy Sailor_Sapphy_v1.00.unitypackage" --list + +# 解包到默认目录(<文件名>_extracted) +python unitypackage_unpack.py "Sexy Sailor_Sapphy_v1.00.unitypackage" + +# 解包到指定目录 +python unitypackage_unpack.py "Sexy Sailor_Sapphy_v1.00.unitypackage" -o "D:/output/Sapphy" + +只要路径里带空格或中文,就套一层双引号,否则 shell 会按空格切参数。 +""" +import argparse +import os +import shutil +import sys +import tarfile + +# Windows 超长路径支持:Unity 包里的目录树很深,再叠上输出目录很容易超 260 +# 字符而报 FileNotFoundError。这个模块导入即生效,短路径行为不变。 +# 单独把本文件拷出去用时可能找不到,所以吞掉 ImportError。 +try: + import longpath # noqa: F401 +except ImportError: # pragma: no cover + pass + + +def _members(src): + """按包里的顺序逐个给出 (GUID, 文件名, 内容),整个包只解压一遍(流式读 tar)。 + + 以前先 getmembers() 走一遍、再按成员回头读 pathname、再逐个解出:gzip 不能往回跳, + 每次回头都从头再解,161 MB 的包要解三遍。""" + with tarfile.open(src, 'r|gz') as t: + for m in t: + if m.isfile(): + guid, fn = m.name.split('/', 1) + yield guid, fn, t.extractfile(m).read() + + +def _target(outdir, raw, guid, fn): + """一个成员的落盘路径,以及它是不是「文件夹」资源的辅助文件(要建出空文件夹)。""" + # pathname 以 '/' 结尾 = 这是一个「文件夹」资源(Unity 里文件夹也是资源)。 + # tar 里没有它的 asset 本体,只有 asset.meta / pathname / preview.png。 + is_folder = raw.endswith('/') or not raw or raw == guid + # 去掉开头的 "Assets/"(以前用 lstrip('Assets/'),那是按字符集剥: + # "Assets/shaders/x" 会被剥成 "haders/x") + rel = (raw[len('Assets/'):] if raw.startswith('Assets/') else raw).rstrip('/') or guid + if fn == 'asset': + return os.path.join(outdir, rel), rel, False + # asset.meta / pathname / preview.png 是辅助文件:跟资产放在同一层, + # 名字里带上资产名(asset.meta 按 Unity 习惯写成 <名>.meta)。 + # 早先直接写 <父目录>/<文件名>,同一目录下有两个以上资产时, + # 后一个会把前一个**静默覆盖**(实测 172 个输出里 51 个碰撞、 + # 168 个成员被覆盖,其中 92 个 asset.meta + 92 个 pathname)。 + name = os.path.basename(rel) or guid + aux = name + '.meta' if fn == 'asset.meta' else name + '.' + fn + return os.path.join(outdir, os.path.dirname(rel), aux), rel, is_folder + + +def unpack(src, outdir, list_only=False, verbose=True): + """解包到 outdir;verbose=False 时不逐个列出文件(界面 / 流水线自己记一行汇总)。 + + 一个资源的成员在包里是挨着的(asset、asset.meta、pathname、preview.png),落盘路径要等 + 读到 pathname 才知道:之前的成员先留在内存里(最多一个资源的大小),读到它再按原顺序写出。""" + if list_only: + paths, sizes = {}, [] + for guid, fn, data in _members(src): + if fn == 'pathname': + paths[guid] = data.decode('utf-8', 'replace').strip() + elif fn == 'asset': + sizes.append((guid, len(data))) + for guid, size in sizes: + print('%10d %s' % (size, paths.get(guid, '?'))) + return 0 + + if os.path.isdir(outdir): + shutil.rmtree(outdir) + os.makedirs(outdir) + paths, pending = {}, {} + n = 0 + + def write(guid, fn, data): + dst, rel, folder = _target(outdir, paths.get(guid, ''), guid, fn) + os.makedirs(os.path.dirname(dst), exist_ok=True) + if folder: + # 文件夹资源的 asset 本体不存在,不在这里建的话空文件夹会丢 + os.makedirs(os.path.join(outdir, rel), exist_ok=True) + with open(dst, 'wb') as w: + w.write(data) + if verbose: + print(' %8.1f KB %s' % (len(data) / 1024, os.path.relpath(dst, outdir))) + + for guid, fn, data in _members(src): + if fn == 'pathname': + paths[guid] = data.decode('utf-8', 'replace').strip() + if guid in paths: + for item in pending.pop(guid, ()): + write(guid, *item) + write(guid, fn, data) + else: + pending.setdefault(guid, []).append((fn, data)) + n += 1 + for guid, items in pending.items(): # 没有 pathname 的资源:按 GUID 落盘 + for item in items: + write(guid, *item) + if verbose: + print('\n%d files -> %s' % (n, outdir)) + return 0 + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('src') + ap.add_argument('-o', '--out', default=None) + ap.add_argument('--list', action='store_true') + a = ap.parse_args() + out = a.out or os.path.splitext(a.src)[0] + '_extracted' + return unpack(a.src, out, a.list) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/formats/vrmio.py b/formats/vrmio.py new file mode 100644 index 0000000..602cae0 --- /dev/null +++ b/formats/vrmio.py @@ -0,0 +1,983 @@ +# -*- coding: utf-8 -*- +"""vrmio.py - GLB / glTF 容器读写 + 纯 Python 图片编解码。 + +只依赖标准库。提供: + GLBBuilder —— 构造 glTF JSON + 单一 BIN chunk + read_glb —— 拆开 .vrm/.glb 得到 (json dict, bin bytes) + write_glb —— 打包成 .vrm/.glb + to_png / decode_image / save_image —— 贴图处理 +""" +import io +import json +import os +import struct +import zlib + +GLB_MAGIC = 0x46546C67 # "glTF" +CHUNK_JSON = 0x4E4F534A # "JSON" +CHUNK_BIN = 0x004E4942 # "BIN\0" + +FLOAT = 5126 +UNSIGNED_BYTE = 5121 +SHORT = 5122 +UNSIGNED_SHORT = 5123 +UNSIGNED_INT = 5125 + +_COMP_FMT = {FLOAT: "= 0 and world[p] else loc + return world + + +def _depth(i, parent): + d = 0 + while parent[i] >= 0: + d += 1 + i = parent[i] + return d + + +def world_translation(m): + return (m[12], m[13], m[14]) + + +# ----------------------------------------------------------------- images -- +def encode_png(width, height, rows_rgba): + """rows_rgba: 每行为 bytes,长度 width*4。""" + raw = bytearray() + for r in rows_rgba: + raw.append(0) + raw += r + + def chunk(typ, data): + return (struct.pack(">I", len(data)) + typ + data + + struct.pack(">I", zlib.crc32(typ + data) & 0xFFFFFFFF)) + + out = bytearray(b"\x89PNG\r\n\x1a\n") + out += chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, + 8, 6, 0, 0, 0)) + out += chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + out += chunk(b"IEND", b"") + return bytes(out) + + +def _png_from_rgba(w, h, pix): + """pix: bytes,长度 w*h*4,按行自上而下。""" + rows = [pix[y * w * 4:(y + 1) * w * 4] for y in range(h)] + return encode_png(w, h, rows) + + +def _decode_bmp(data): + if data[:2] != b"BM": + return None + off = struct.unpack_from(" 0 + h = abs(h) + stride = ((w * bpp + 31) // 32) * 4 + pix = bytearray(w * h * 4) + src = off + for y in range(h): + sy = (h - 1 - y) if flip else y + row = data[src + sy * stride: src + sy * stride + stride] + for x in range(w): + if bpp == 24: + b, g, r = row[x * 3], row[x * 3 + 1], row[x * 3 + 2] + a = 255 + else: + b, g, r, a = row[x * 4], row[x * 4 + 1], row[x * 4 + 2], row[x * 4 + 3] + o = (y * w + x) * 4 + pix[o] = r + pix[o + 1] = g + pix[o + 2] = b + pix[o + 3] = a + return _png_from_rgba(w, h, bytes(pix)) + + +def _decode_tga(data): + idlen = data[0] + cmap_type = data[1] + img_type = data[2] + w = struct.unpack_from("= w * h: + break + b, g, r = px[0], px[1], px[2] + a = px[3] if bpp == 4 else 255 + o = idx * 4 + pix[o] = r + pix[o + 1] = g + pix[o + 2] = b + pix[o + 3] = a + idx += 1 + if not top: # 底到顶存储,翻过来 + rows = [bytes(pix[y * w * 4:(y + 1) * w * 4]) for y in range(h)] + rows.reverse() + pix = bytearray(b"".join(rows)) + return _png_from_rgba(w, h, bytes(pix)) + + +# ------------------------------------------------------------------- DDS ---- +# XPS / XNALara 的贴图大量是 DDS(实测轩辕剑柒的样本是 2048×2048 的 DXT1 与 +# 512×512 的 DXT5)。MMD 本体虽然认 .dds(见 VPVP wiki 的「拡張子」表,所以 +# 转换时原样拷过去就行),但 GUI 预览的图片解码走的是纯标准库路线,没装 +# Pillow 时只认 PNG/TGA/BMP,DDS 会解不出来、预览变灰模。这里补一个 +# DXT1/DXT3/DXT5 与未压缩 RGB(A) 的解码,解成 PNG 后预览就能正常显示。 + +# 一个索引字节 → 4 个 2 位索引(低位在前),DXT 全系都用这个位序 +_DXT_Q = tuple(((b & 3), ((b >> 2) & 3), ((b >> 4) & 3), ((b >> 6) & 3)) + for b in range(256)) + + +def _rgb565(v): + r = (v >> 11) & 0x1F + g = (v >> 5) & 0x3F + b = v & 0x1F + return ((r << 3) | (r >> 2), (g << 2) | (g >> 4), (b << 3) | (b >> 2)) + + +def _dxt_palette(c0, c1, allow_transparent): + """(c0, c1) → 4 个 RGBA 字节串。 + + allow_transparent(只有 DXT1 传 True)时,c0 <= c1 表示用「3 色 + 全透明」 + 档,第 4 个是透明黑 —— 这是 DXT1 唯一的 alpha 来源。 + """ + r0, g0, b0 = _rgb565(c0) + r1, g1, b1 = _rgb565(c1) + p0 = bytes((r0, g0, b0, 255)) + p1 = bytes((r1, g1, b1, 255)) + if allow_transparent and c0 <= c1: + return (p0, p1, + bytes(((r0 + r1) // 2, (g0 + g1) // 2, (b0 + b1) // 2, 255)), + b"\x00\x00\x00\x00") + return (p0, p1, + bytes(((2 * r0 + r1) // 3, (2 * g0 + g1) // 3, (2 * b0 + b1) // 3, + 255)), + bytes(((r0 + 2 * r1) // 3, (g0 + 2 * g1) // 3, (b0 + 2 * b1) // 3, + 255))) + + +def _dxt5_alpha_ramp(a0, a1): + """DXT5 的 8 个 alpha 值:a0 > a1 是 6 插值档,否则 4 插值 + 0/255。""" + if a0 > a1: + return (a0, a1) + tuple( + ((7 - i) * a0 + i * a1) // 7 for i in range(1, 7)) + return (a0, a1) + tuple( + ((5 - i) * a0 + i * a1) // 5 for i in range(1, 5)) + (0, 255) + + +def _decode_dds(data): + """DDS → PNG 字节;不支持的子格式返回 None。""" + if data[:4] != b"DDS " or len(data) < 128: + return None + hdr = struct.unpack_from("<7I", data, 4) + height, width = hdr[2], hdr[3] + if not width or not height or width > 16384 or height > 16384: + return None + fourcc = data[84:88] + rgb_bits = struct.unpack_from("= height: + break + q = Q[(bits >> (8 * r)) & 0xFF] + row = (pal[q[0]] + pal[q[1]] + pal[q[2]] + pal[q[3]]) + o = (y0 + r) * stride + x0 * 4 + if x0 + 4 <= width: + pix[o:o + 16] = row + else: + pix[o:o + (width - x0) * 4] = \ + row[:(width - x0) * 4] + elif fourcc == b"DXT3": + for by in range(bh): + y0 = by * 4 + for bx in range(bw): + al = data[off:off + 8] + c0 = data[off + 8] | (data[off + 9] << 8) + c1 = data[off + 10] | (data[off + 11] << 8) + bits = struct.unpack_from("= height: + break + o = (y0 + r) * stride + x0 * 4 + for k in range(4): + if x0 + k >= width: + break + i = r * 4 + k + n = (al[i >> 1] >> (4 * (i & 1))) & 0xF + c = pal[(bits >> (2 * i)) & 3] + pix[o + k * 4] = c[0] + pix[o + k * 4 + 1] = c[1] + pix[o + k * 4 + 2] = c[2] + pix[o + k * 4 + 3] = n * 17 + else: # DXT5 + for by in range(bh): + y0 = by * 4 + for bx in range(bw): + ramp = _dxt5_alpha_ramp(data[off], data[off + 1]) + abits = int.from_bytes(data[off + 2:off + 8], "little") + c0 = data[off + 8] | (data[off + 9] << 8) + c1 = data[off + 10] | (data[off + 11] << 8) + bits = struct.unpack_from("= height: + break + o = (y0 + r) * stride + x0 * 4 + for k in range(4): + if x0 + k >= width: + break + i = r * 4 + k + c = pal[(bits >> (2 * i)) & 3] + pix[o + k * 4] = c[0] + pix[o + k * 4 + 1] = c[1] + pix[o + k * 4 + 2] = c[2] + pix[o + k * 4 + 3] = ramp[(abits >> (3 * i)) & 7] + return _png_from_rgba(width, height, bytes(pix)) + + if fourcc == b"\x00\x00\x00\x00" and rgb_bits in (24, 32): + rmask, gmask, bmask, amask = struct.unpack_from("<4I", data, 92) + bpp = rgb_bits // 8 + if len(data) < 128 + width * height * bpp: + return None + # 常见布局走快路:24 位 BGR / 32 位 BGRA + if (rgb_bits == 24 and rmask == 0xFF0000 and gmask == 0xFF00 + and bmask == 0xFF): + src = data[128:128 + width * height * 3] + for i in range(width * height): + o = i * 4 + pix[o] = src[i * 3 + 2] + pix[o + 1] = src[i * 3 + 1] + pix[o + 2] = src[i * 3] + pix[o + 3] = 255 + return _png_from_rgba(width, height, bytes(pix)) + if (rgb_bits == 32 and rmask == 0xFF0000 and gmask == 0xFF00 + and bmask == 0xFF and amask == 0xFF000000): + src = data[128:128 + width * height * 4] + for i in range(width * height): + o = i * 4 + pix[o] = src[i * 4 + 2] + pix[o + 1] = src[i * 4 + 1] + pix[o + 2] = src[i * 4] + pix[o + 3] = src[i * 4 + 3] + return _png_from_rgba(width, height, bytes(pix)) + # 其它掩码:按位段通用抽取 + def _shift(mask): + if not mask: + return 0, 0 + s = 0 + while not (mask >> s) & 1: + s += 1 + bits = bin(mask >> s).count("1") + return s, bits + + rs, rb = _shift(rmask) + gs, gb = _shift(gmask) + bs, bb = _shift(bmask) + as_, ab = _shift(amask) + + def _comp(v, s, n, default=255): + if not n: + return default + x = (v >> s) & ((1 << n) - 1) + return x * 255 // ((1 << n) - 1) + + src = data[128:128 + width * height * bpp] + for i in range(width * height): + v = int.from_bytes(src[i * bpp:(i + 1) * bpp], "little") + o = i * 4 + pix[o] = _comp(v, rs, rb) + pix[o + 1] = _comp(v, gs, gb) + pix[o + 2] = _comp(v, bs, bb) + pix[o + 3] = _comp(v, as_, ab, 255) + return _png_from_rgba(width, height, bytes(pix)) + return None + + +def _bmp_pil(Image, data): + """BMP → Pillow 图像。24 / 32 位的像素和 _decode_bmp 一样(32 位的第 4 个字节当 alpha,Pillow 自己 + 打开时会把它当成填充字节丢掉);纯 Python 版不认的(8 位调色板 / 灰度等)交给 Pillow 自己解。""" + off = struct.unpack_from(" 0 else 1) + + +def _decode_pil(data, kind): + """BMP / TGA / DDS → PNG 字节,用 Pillow(C 解码,比下面的纯 Python 版快几十倍)。 + 没装 Pillow 或它解不了时返回 None,交给纯 Python 版。没有 alpha 的图存成 RGB PNG。""" + try: + from PIL import Image + except ImportError: + return None + try: + if kind == "BMP": + im = _bmp_pil(Image, data) + if im is None: + return None + else: + im = Image.open(io.BytesIO(data), formats=[kind]) + im.load() + if im.mode not in ("RGB", "RGBA"): + alpha = im.mode in ("LA", "PA", "La", "RGBa") or "transparency" in im.info + im = im.convert("RGBA" if alpha else "RGB") + buf = io.BytesIO() + im.save(buf, "PNG") + return buf.getvalue() + except Exception: # noqa: BLE001 罕见子格式:纯 Python 版再试 + return None + + +def decode_image(data): + """任意常见贴图字节 → PNG 字节;无法处理时返回 None。BMP / TGA / DDS 装了 Pillow 时用 Pillow 解。""" + if not data: + return None + if data[:8] == b"\x89PNG\r\n\x1a\n": + return data + if data[:3] == b"\xff\xd8\xff": + return data # JPEG 直接透传 + for kind, ok, pure in ( + ("BMP", data[:2] == b"BM", _decode_bmp), + ("DDS", data[:4] == b"DDS ", _decode_dds), + ("TGA", len(data) > 18 and data[2] in (2, 3, 10, 11) and data[1] in (0, 1), _decode_tga)): + if ok: + out = _decode_pil(data, kind) + if out: + return out + try: + return pure(data) + except Exception: + return None + return None + + +def decode_rgba(data, max_pixels=4 << 20): + """贴图字节 → (宽, 高, 行列表),每行是 (r, g, b, a) 元组的列表;失败返回 None。 + + 纯 Python,给 toon 渐变这类小图取色用(BMP / TGA / DDS 先转成 PNG)。 + 只支持 8 位、非隔行的 PNG;超过 max_pixels 的大图不解(太慢)。 + """ + if not data: + return None + if data[:8] != b"\x89PNG\r\n\x1a\n": + data = decode_image(data) + if not data or data[:8] != b"\x89PNG\r\n\x1a\n": + return None + p = 8 + idat = [] + w = h = bd = ct = il = 0 + plte = trns = None + while p + 8 <= len(data): + ln, ty = struct.unpack(">I4s", data[p:p + 8]) + body = data[p + 8:p + 8 + ln] + p += 12 + ln + if ty == b"IHDR": + w, h, bd, ct, _, _, il = struct.unpack(">IIBBBBB", body[:13]) + elif ty == b"IDAT": + idat.append(body) + elif ty == b"PLTE": + plte = body + elif ty == b"tRNS": + trns = body + elif ty == b"IEND": + break + if bd != 8 or il or ct not in (0, 2, 3, 4, 6) or w * h > max_pixels: + return None + if ct == 3 and not plte: + return None + bpp = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[ct] + stride = w * bpp + try: + raw = zlib.decompress(b"".join(idat)) + except zlib.error: + return None + if len(raw) < h * (stride + 1): + return None + rows = [] + prev = bytearray(stride) + for y in range(h): + base = y * (stride + 1) + f = raw[base] + out = bytearray(raw[base + 1:base + 1 + stride]) + if f == 1: + for x in range(bpp, stride): + out[x] = (out[x] + out[x - bpp]) & 255 + elif f == 2: + for x in range(stride): + out[x] = (out[x] + prev[x]) & 255 + elif f == 3: + for x in range(stride): + left = out[x - bpp] if x >= bpp else 0 + out[x] = (out[x] + ((left + prev[x]) >> 1)) & 255 + elif f == 4: + for x in range(stride): + a = out[x - bpp] if x >= bpp else 0 + b = prev[x] + c = prev[x - bpp] if x >= bpp else 0 + pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c) + out[x] = (out[x] + (a if pa <= pb and pa <= pc + else (b if pb <= pc else c))) & 255 + prev = out + if ct == 6: + rows.append([tuple(out[i:i + 4]) for i in range(0, stride, 4)]) + elif ct == 2: + rows.append([tuple(out[i:i + 3]) + (255,) for i in range(0, stride, 3)]) + elif ct == 0: + rows.append([(v, v, v, 255) for v in out]) + elif ct == 4: + rows.append([(out[i], out[i], out[i], out[i + 1]) for i in range(0, stride, 2)]) + else: + rows.append([tuple(plte[3 * v:3 * v + 3]) + + ((trns[v] if trns and v < len(trns) else 255),) for v in out]) + return w, h, rows + + +def png_alpha_stats_image(im): + """已经用 Pillow 打开的 PNG → 和 png_alpha_stats 相同的结果(解码时出错会抛异常)。 + FBX 转换判断透明时已经解过一遍贴图,用它算好交给后面的 PMX → VRM,不用再解一遍。""" + if im.mode in ("RGBA", "LA", "PA"): + a = im.getchannel("A") + elif im.mode == "P" and "transparency" in im.info: + a = im.convert("RGBA").getchannel("A") + else: + return None # 没有 alpha(tRNS 色键和纯 Python 版一样忽略) + h = a.histogram() + return (sum(h), sum(h[:250]), sum(h[11:245])) + + +def _png_alpha_stats_pil(data): + """png_alpha_stats 的 Pillow 版(C 解码,比纯 Python 版快十倍以上,统计整张图)。 + 没有 alpha 通道的图看文件头就知道,不解码。没装 Pillow 或解不开时返回 NotImplemented,交给纯 Python 版。""" + try: + from PIL import Image + except ImportError: + return NotImplemented + try: + return png_alpha_stats_image(Image.open(io.BytesIO(data))) + except Exception: # noqa: BLE001 坏图 / 罕见格式:纯 Python 版有自己的保守处理 + return NotImplemented + + +def png_alpha_stats(data, max_rows=512): + """统计 PNG 的透明度分布,用来决定材质的 alphaMode。 + + 返回 (采样像素数, 透明像素数 a<250, 半透明像素数 10I4s", data[p:p + 8]) + body = data[p + 8:p + 8 + ln] + p += 12 + ln + if ty == b"IHDR": + w, h, bd, ct, _, _, il = struct.unpack(">IIBBBBB", body[:13]) + elif ty == b"IDAT": + idat.append(body) + elif ty == b"tRNS": + trns = body + elif ty == b"IEND": + break + if ct == 3: + if not trns: + return None + lut = bytes(trns) + b"\xff" * (256 - len(trns)) + elif ct not in (4, 6): + return None # tRNS 色键这种少见情况忽略 + if il or bd not in (8, 16) and ct != 3: + return (1, 1, 1) # 隔行/罕见位深:保守地当半透明 + try: + raw = zlib.decompress(b"".join(idat)) + except zlib.error: + return (1, 1, 1) + if ct == 3: + if bd != 8: + return (1, 1, 1) + bpp, aoff = 1, 0 + else: + ch = 4 if ct == 6 else 2 + bpp = ch * (bd // 8) + aoff = bpp - (bd // 8) # 16 位取 alpha 的高字节 + stride = w * bpp + if len(raw) < h * (stride + 1): + return (1, 1, 1) + step = max(1, h // max_rows) + filt = [raw[y * (stride + 1)] for y in range(h)] + + def unfilter(y, prev): + """只还原第 y 行 alpha(调色板图还原索引),prev 为上一行结果或 None。""" + base = y * (stride + 1) + 1 + src = raw[base + aoff:base + stride:bpp] + f = filt[y] + if f == 0: + return bytearray(src) + out = bytearray(len(src)) + if f == 1: + a = 0 + for x, v in enumerate(src): + a = (v + a) & 255 + out[x] = a + return out + up = prev if prev is not None else bytes(len(src)) + if f == 2: + for x, v in enumerate(src): + out[x] = (v + up[x]) & 255 + return out + a = c = 0 + for x, v in enumerate(src): + b = up[x] + if f == 3: + a = (v + ((a + b) >> 1)) & 255 + else: + pa = b - c + pb = a - c + pc = abs(pa + pb) + pa = abs(pa) + pb = abs(pb) + pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) + a = (v + pr) & 255 + out[x] = a + c = b + return out + + n = trans = mid = 0 + last_y, last_row = -1, None + for t in range(0, h, step): + if last_y >= 0 and t - last_y <= step: + y, prev = last_y + 1, last_row + else: + y = t + while y > 0 and filt[y] > 1 and y > last_y + 1: + y -= 1 + prev = last_row if y == last_y + 1 else None + row = prev + while y <= t: + row = unfilter(y, prev) + prev = row + y += 1 + last_y, last_row = t, row + if ct == 3: + row = row.translate(lut) + n += len(row) + for v in row: + if v < 250: + trans += 1 + if 10 < v < 245: + mid += 1 + return (n, trans, mid) + + +IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".tga", ".dds", ".spa", ".sph", ".gif", ".webp", ".tif", ".tiff") + + +class TextureFinder: + """模型里记的贴图路径(相对模型所在文件夹)→ 磁盘上的文件。 + + 依次试:记的相对路径;模型文件夹里的同名文件(作者留了自己电脑上的绝对路径之类);模型文件夹的 + 子文件夹里的同名文件(不分大小写,比如记的是 body.png、实际在 tex/body.png);同名不同扩展名 + (记的 .png、实际是 .tga / .dds)。子文件夹按需建一次索引,最多看 max_files 个文件(不只是图片)、max_depth 层, + 拖进来的是「下载」这种大文件夹时也不会慢。find 可以在线程里调用。 + """ + + def __init__(self, base_dir, max_files=20000, max_depth=6): + import threading + self.base_dir = base_dir + self.max_files, self.max_depth = max_files, max_depth + self._index = None + self._lock = threading.Lock() + + def _build(self): + by_name, by_stem, n = {}, {}, 0 + root = os.path.abspath(self.base_dir) + depth0 = root.rstrip("\\/").count(os.sep) + for d, dirs, files in os.walk(root): + if d.count(os.sep) - depth0 >= self.max_depth: + dirs[:] = [] + dirs.sort() + n += len(files) # 所有文件都算数:模型放在「下载」这种大文件夹里时不会一直找下去 + for f in sorted(files): + low = f.lower() + if low.endswith(IMAGE_EXTS): + p = os.path.join(d, f) + by_name.setdefault(low, []).append(p) + by_stem.setdefault(os.path.splitext(low)[0], []).append(p) + if n >= self.max_files: + break + return by_name, by_stem + + def find(self, rel): + """→ (路径, how):how 是 "exact"(就在记的位置)、"moved"(在别处按文件名找到的);找不到为 (None, None)。""" + rel = (rel or "").replace("\\", "/").strip() + if not rel: + return None, None + c = os.path.join(self.base_dir, *[x for x in rel.split("/") if x]) if not os.path.isabs(rel) else rel + if os.path.isfile(c): + return c, "exact" + name = rel.rsplit("/", 1)[-1] + c = os.path.join(self.base_dir, name) + if os.path.isfile(c): + return c, "moved" + with self._lock: + if self._index is None: + self._index = self._build() + by_name, by_stem = self._index + cands = by_name.get(name.lower()) or by_stem.get(os.path.splitext(name.lower())[0]) or [] + if not cands: + return None, None + # 几个同名的:选所在子文件夹和记的路径对得最多的,再选层级浅的 + want = [x.lower() for x in rel.split("/")[:-1]] + + def score(p): + parts = os.path.relpath(os.path.dirname(p), self.base_dir).lower().replace("\\", "/").split("/") + return (-sum(1 for x in want if x in parts), len(parts), p) + return min(cands, key=score), "moved" + + +def load_texture(path): + """读取磁盘贴图,返回 (bytes, mime);失败返回 (None, None)。""" + try: + with open(path, "rb") as f: + data = f.read() + except OSError: + return None, None + if data[:8] == b"\x89PNG\r\n\x1a\n": + return data, "image/png" + if data[:3] == b"\xff\xd8\xff": + return data, "image/jpeg" + out = decode_image(data) + if out is None: + return None, None + return out, ("image/png" if out[:8] == b"\x89PNG\r\n\x1a\n" else "image/jpeg") + + +def save_image(data, path): + if data[:8] == b"\x89PNG\r\n\x1a\n": + p = os.path.splitext(path)[0] + ".png" + elif data[:3] == b"\xff\xd8\xff": + p = os.path.splitext(path)[0] + ".jpg" + elif data[:4] == b"RIFF" and data[8:12] == b"WEBP": + p = os.path.splitext(path)[0] + ".webp" + elif data[:4] == b"\xabKTX": + p = os.path.splitext(path)[0] + ".ktx2" + else: + p = path + with open(p, "wb") as f: + f.write(data) + return p diff --git a/formats/xpsio.py b/formats/xpsio.py new file mode 100644 index 0000000..543be37 --- /dev/null +++ b/formats/xpsio.py @@ -0,0 +1,400 @@ +# -*- coding: utf-8 -*- +"""XPS / XNALara 模型读取器(纯 Python 标准库,不需要 Blender / XPS 本体)。 + +格式来源 +-------- +XNALara(后被 XPS / XNA Posing Studio 继承)的二进制模型格式。字段布局以 +GLLara 的公开文档 `Documentation/XNALara Model File Format.md` 为准,并由本项目 +实测样本(轩辕剑柒 chu hong,XPS 11.8 导出)逐字段复核过。 + +两种变体 +-------- +1) **Generic Item 2**(XPS 自己的格式,现在最常遇到) + 第一个 uint32 是魔数 323232(0x0004EEA0),据此识别: + + uint32 magic = 323232 + uint16 majorVersion + uint16 minorVersion + string toolAuthor // 固定 "XNAaraL" + uint32 countOfUnknownInts + string unknownString1 // 作者名 / 机器名,不需要 + string unknownString2 + string unknownString3 // 含原始文件路径 + uint32 unknownInts[countOfUnknownInts] + uint32 numBones + Bone bones[numBones] + uint32 numMeshes + Mesh meshes[numMeshes] + ... // 之后还有一段与转换无关的尾部数据 + +2) **旧版 XNALara 二进制**(没有魔数,直接就是 numBones) + 结构与上面相同,只是没有 header 那一段;顶点里**多一套切线**。 + + 要判断是哪种,只看文件头 4 字节是不是 323232 即可(文档明确这么写)。 + +骨骼 +---- + string name + uint16 parentIndex // 65535(0xFFFF) = 没有父级 + float defaultPositionX // **世界坐标**,不是相对父级的位移 + float defaultPositionY + float defaultPositionZ + +网格 +---- + string name + uint32 numUVLayers + uint32 numTextures + Texture textures[numTextures] // { string filename; uint32 uvLayer; } + uint32 numVertices + Vertex vertices[numVertices] + uint32 numTriangles // ⚠ 是**三角面数**,不是索引数 + uint32 indices[numTriangles * 3] // 索引数组长度是三角面数的 3 倍 + +顶点(随版本/UV 层数/是否有骨骼而变) +------------------------------------- + 通用项: + float vertex[3] + float normal[3] + uint8 color[4] + float texCoord[2][numUVLayers] + 只有旧版 XNALara(非 Generic Item 2)**且** majorVersion < 2 时才有: + float tangent[4][numUVLayers] + 有骨骼时: + // Generic Item 2 且 majorVersion >= 3: + uint16 boneCountForVertex // 每顶点独立,通常 4,也可能更高 + uint16 boneIndex[boneCountForVertex] + float boneWeight[boneCountForVertex] + // 其余情况:固定 4 根 + uint16 boneIndex[4] + float boneWeight[4] + +实测记录(轩辕剑柒 chu hong,majorVersion=3,minorVersion=15) +----------------------------------------------------------- +* 136 根骨骼 / 9 个网格 / 57415 顶点 / 82592 三角面,全部自洽。 +* 每个顶点 boneCount 恒为 4,顶点步长 62 字节(1 套 UV)。 +* 轴向实测:`head eyeball left` 在 +X、`head eyeball right` 在 -X → **+X = 左**; + `head nose tip` 与 `leg left toes` 的 Z 都**大于**各自的父级(鼻尖 1.030 > 头根 + 0.925,脚尖 0.974 > 脚踝 0.879)→ **+Z = 正面**;`root ground` 在 y=0、头顶 + y≈1.71(米)→ **+Y = 上**。也就是「左手 +X、正面 +Z、上 +Y」的**右手系**。 + MMD/PMX 是「左手 +X、正面 -Z、上 +Y」,所以只要**把 Z 取反**即可对齐 + (详见 convert/xps2pmx.py 里 xf() 的说明)。 +* 尾部还有 129 字节与模型无关的数据,读完最后一个网格直接停即可。 +""" +import os +import struct + +__all__ = ["Xps", "XpsBone", "XpsMesh", "read_xps", "XPS_MAGIC"] + +# Generic Item 2 的魔数:0x0004EEA0 == 323232 +XPS_MAGIC = 323232 + +# 顶点里索引/权重最多取多少根(PMX 上限就是 4,这里读进来后由转换器再裁) +MAX_BONES_PER_VERTEX = 64 + + +class XpsBone(object): + __slots__ = ("name", "parent_index", "position") + + def __init__(self, name, parent_index, position): + self.name = name + self.parent_index = parent_index # 65535 = 无父级 + self.position = position # (x, y, z) 世界坐标 + + +class XpsMesh(object): + __slots__ = ("name", "uv_layers", "textures", "positions", "normals", + "colors", "uvs", "bone_indices", "bone_weights", + "triangles", "bone_counts") + + def __init__(self, name, uv_layers): + self.name = name + self.uv_layers = uv_layers + self.textures = [] # [(filename, uv_layer), ...] + self.positions = [] # [(x, y, z), ...] + self.normals = [] # [(x, y, z), ...] + self.colors = [] # [(r, g, b, a), ...] + self.uvs = [] # [(u, v), ...] 第 0 套(MMD 只吃第 0 套) + self.bone_indices = [] # [[bone_index, ...], ...] + self.bone_weights = [] # [[weight, ...], ...] + self.bone_counts = [] # [int, ...] 每个顶点的权重根数 + self.triangles = [] # [(i0, i1, i2), ...] + + @property + def n_vertices(self): + return len(self.positions) + + @property + def n_triangles(self): + return len(self.triangles) + + @property + def diffuse(self): + """基础色贴图文件名:XPS 约定 textures[0] 就是 diffuse。 + + 实测样本里 4 张一组时顺序是 `_d / _l / _n / _s`(漫反射 / 光照图 / + 法线 / 高光),只有 1 张时就是 `_d`,所以取第 0 个总是对的。 + """ + return self.textures[0][0] if self.textures else "" + + +class Xps(object): + def __init__(self): + self.magic = 0 + self.version_major = 0 + self.version_minor = 0 + self.author = "" + self.paths = [] # header 里那三条字符串(作者名/机器名/路径) + self.is_generic2 = False # True = XPS 的 Generic Item 2 + self.bones = [] # [XpsBone, ...] + self.meshes = [] # [XpsMesh, ...] + self.tail = b"" # 网格之后的剩余字节(与转换无关) + + @property + def n_vertices(self): + return sum(len(m.positions) for m in self.meshes) + + @property + def n_triangles(self): + return sum(len(m.triangles) for m in self.meshes) + + +# ------------------------------------------------------------------ 读取 ------ +class _R(object): + """把整份文件读进内存后按偏移取数(比逐字段 read() 快得多)。""" + + __slots__ = ("d", "o", "n") + + def __init__(self, data): + self.d = data + self.o = 0 + self.n = len(data) + + def need(self, k): + if self.o + k > self.n: + raise ValueError("文件在偏移 %d 处提前结束(还需 %d 字节,仅剩 %d)" + % (self.o, k, self.n - self.o)) + + def u8(self): + v = self.d[self.o] + self.o += 1 + return v + + def u16(self): + self.need(2) + v = struct.unpack_from(" 28: + raise ValueError("字符串长度编码异常(偏移 %d)" % (self.o - 1)) + if ln == 0: + return "" + raw = self.raw(ln) + try: + return raw.decode("utf-8") + except UnicodeDecodeError: + return raw.decode("latin-1") + + +def _read_bones(r): + n = r.u32() + if n > 100000: + raise ValueError("骨骼数异常(%d),文件可能不是 XPS 或已损坏" % n) + bones = [] + for _ in range(n): + name = r.string() + parent = r.u16() + pos = r.vec(3) + bones.append(XpsBone(name, 0xFFFF if parent == 0xFFFF else parent, pos)) + return bones + + +def _read_vertex(r, nuv, has_bones, has_tangent, variable_bone_count): + """读一个顶点,返回 (pos, nrm, col, uv0, idxs, wts)。""" + pos = r.vec(3) + nrm = r.vec(3) + col = struct.unpack_from("<4B", r.d, r.o) + r.o += 4 + uvs = r.vec(2 * nuv) if nuv else () + if has_tangent: + r.o += 16 * nuv # 旧版才有切线,MMD 用不上,跳过 + idxs = () + wts = () + if has_bones: + if variable_bone_count: + bc = r.u16() + if bc > MAX_BONES_PER_VERTEX: + raise ValueError("顶点权重根数异常(%d)" % bc) + else: + bc = 4 + if bc: + r.need(2 * bc + 4 * bc) + idxs = struct.unpack_from("<%dH" % bc, r.d, r.o) + r.o += 2 * bc + wts = struct.unpack_from("<%df" % bc, r.d, r.o) + r.o += 4 * bc + uv0 = (uvs[0], uvs[1]) if nuv else (0.0, 0.0) + return pos, nrm, col, uv0, idxs, wts + + +def _read_meshes(r, has_bones, has_tangent, variable_bone_count, log): + n_mesh = r.u32() + if n_mesh > 100000: + raise ValueError("网格数异常(%d)" % n_mesh) + meshes = [] + for mi in range(n_mesh): + name = r.string() + nuv = r.u32() + ntex = r.u32() + if nuv > 8 or ntex > 64: + raise ValueError("网格 %d 的 UV 层数/贴图数异常(%d / %d)" + % (mi, nuv, ntex)) + mesh = XpsMesh(name, nuv) + for _ in range(ntex): + fn = r.string() + ul = r.u32() + mesh.textures.append((fn, ul)) + nv = r.u32() + if nv > 40000000: + raise ValueError("网格 %d 的顶点数异常(%d)" % (mi, nv)) + mesh.positions = [None] * nv + mesh.normals = [None] * nv + mesh.colors = [None] * nv + mesh.uvs = [None] * nv + mesh.bone_indices = [None] * nv + mesh.bone_weights = [None] * nv + mesh.bone_counts = [0] * nv + for vi in range(nv): + pos, nrm, col, uv0, idxs, wts = _read_vertex( + r, nuv, has_bones, has_tangent, variable_bone_count) + mesh.positions[vi] = pos + mesh.normals[vi] = nrm + mesh.colors[vi] = col + mesh.uvs[vi] = uv0 + mesh.bone_indices[vi] = idxs + mesh.bone_weights[vi] = wts + mesh.bone_counts[vi] = len(idxs) + ntri = r.u32() + if ntri > 40000000: + raise ValueError("网格 %d 的三角面数异常(%d)" % (mi, ntri)) + r.need(12 * ntri) + flat = struct.unpack_from("<%dI" % (3 * ntri), r.d, r.o) + r.o += 12 * ntri + if nv: + bad = 0 + tris = [] + for k in range(0, len(flat), 3): + a, b, c = flat[k], flat[k + 1], flat[k + 2] + if a >= nv or b >= nv or c >= nv: + bad += 1 + continue + tris.append((a, b, c)) + mesh.triangles = tris + if bad and log: + log("网格 %d 有 %d 个三角面索引越界,已跳过" % (mi, bad), "warn") + meshes.append(mesh) + return meshes + + +def read_xps(path, log=None): + """读取 .xps(XPS Generic Item 2 或旧版 XNALara 二进制)→ Xps。""" + with open(path, "rb") as f: + data = f.read() + if len(data) < 8: + raise ValueError("文件太小,不是 XPS 模型") + r = _R(data) + m = Xps() + m.magic = r.u32() + m.is_generic2 = (m.magic == XPS_MAGIC) + + if m.is_generic2: + m.version_major = r.u16() + m.version_minor = r.u16() + m.author = r.string() + n_unk = r.u32() + if n_unk > 1000000: + raise ValueError("XPS 头部异常(countOfUnknownInts=%d)" % n_unk) + m.paths = [r.string(), r.string(), r.string()] + r.o += 4 * n_unk # 一段与模型无关的整数设置 + has_bones = True + else: + # 旧版 XNALara:没有 header,第一个 uint32 就是骨骼数。 + # 把已经读掉的 4 字节退回去,后面按同一套结构读。 + r.o = 0 + m.version_major = 1 + has_bones = True + if log: + log("XPS 格式:旧版 XNALara 二进制格式(无 Generic Item 2 头)", "info") + + # 切线:只有旧版 XNALara 且 majorVersion < 2 才有 + has_tangent = (not m.is_generic2) and m.version_major < 2 + # 变长权重根数:Generic Item 2 且 majorVersion >= 3 + variable_bone_count = m.is_generic2 and m.version_major >= 3 + + if log: + if m.is_generic2: + log("XPS 格式:Generic Item 2 · 版本 %d.%d · 作者 %s" + % (m.version_major, m.version_minor, m.author or "?"), "info") + if has_tangent: + log("XPS 格式:旧版格式含切线数据(转换时忽略)", "info") + + m.bones = _read_bones(r) + if not m.bones: + raise ValueError("文件中没有骨骼数据") + m.meshes = _read_meshes(r, has_bones, has_tangent, variable_bone_count, log) + m.tail = data[r.o:] + if not m.meshes: + raise ValueError("文件中没有网格数据") + return m + + +# ------------------------------------------------------------------- CLI ------ +def main(argv=None): + import argparse + ap = argparse.ArgumentParser(description="查看 XPS / XNALara 模型结构") + ap.add_argument("src") + a = ap.parse_args(argv) + m = read_xps(a.src, log=lambda s, t=None: print(s)) + print("骨骼 %d · 网格 %d · 顶点 %d · 三角面 %d" + % (len(m.bones), len(m.meshes), m.n_vertices, m.n_triangles)) + return 0 + + +if __name__ == "__main__": + import sys + sys.exit(main()) diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..05d95b6 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,5 @@ +-r requirements.txt +# tests / QA: official VRM JSON Schema validation +jsonschema>=4.18 +# packaging: pyinstaller VRMify.spec +pyinstaller>=6 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3526233 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +# Optional runtime packages — the converter itself is pure standard library. +# pywebview: native window for the GUI (drag & drop); without it the UI opens in the browser. +pywebview>=5 +# Pillow: texture slimming (max size / JPEG), ~10x faster texture alpha checks and BMP / TGA / DDS decoding; +# without it textures are embedded as-is and the checks and decoding fall back to pure Python. +Pillow>=10 diff --git a/tests/synth.py b/tests/synth.py new file mode 100644 index 0000000..79c3cc3 --- /dev/null +++ b/tests/synth.py @@ -0,0 +1,191 @@ +# -*- coding: utf-8 -*- +"""合成一个很小的 MMD 人形 PMX,给测试用(仓库里不能放真实模型:模型的许可不允许再分发)。 + +骨架用 MMD 标准日文骨名(A 姿势的手臂、双眼),每根骨挂一个小方块网格; +头上一条三节的头发链挂物理刚体(→ SpringBone);两张贴图:一张不透明、一张带透明; +几个标准表情(まばたき / あ / にこり / 笑い)和一个材质表情。 +eyes=True 时再加:眼珠(挂在左右眼骨上)、骨骼表情「寄り目」、含骨骼表情的グループ「見開く」、 +一块漫符面片(独立材质)和移动它 UV 的 UV 表情「怒マーク」。 +""" +import math +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _p in ("formats", "convert"): + _d = os.path.join(ROOT, _p) + if _d not in sys.path: + sys.path.insert(0, _d) +import pmxio # noqa: E402 +import vrmio # noqa: E402 + +# 名字, 父骨, 位置(MMD 单位:脸朝 -Z,角色左手在 +X) +_BONES = [ + ("センター", None, (0, 8, 0)), + ("下半身", "センター", (0, 11, 0)), + ("上半身", "センター", (0, 11.5, 0)), + ("上半身2", "上半身", (0, 13, 0)), + ("首", "上半身2", (0, 15.5, 0)), + ("頭", "首", (0, 16.5, 0)), + ("左目", "頭", (0.35, 17.4, -0.8)), + ("右目", "頭", (-0.35, 17.4, -0.8)), +] +for _s, _x in (("左", 1), ("右", -1)): + _BONES += [ + (_s + "肩", "上半身2", (0.4 * _x, 15, 0)), + (_s + "腕", _s + "肩", (1.4 * _x, 15, 0)), + (_s + "ひじ", _s + "腕", (3.2 * _x, 13.7, 0)), + (_s + "手首", _s + "ひじ", (4.9 * _x, 12.5, 0)), + (_s + "足", "下半身", (0.9 * _x, 10.5, 0)), + (_s + "ひざ", _s + "足", (0.9 * _x, 6, 0)), + (_s + "足首", _s + "ひざ", (0.9 * _x, 1.2, 0)), + (_s + "つま先", _s + "足首", (0.9 * _x, 0.2, -1.2)), + ] +_BONES += [ + ("髪1", "頭", (0, 17.5, 0.9)), + ("髪2", "髪1", (0, 15.6, 1.2)), + ("髪3", "髪2", (0, 13.7, 1.4)), + ("髪先", "髪3", (0, 11.8, 1.5)), +] + +# VRChat 风格的英文骨名(build(english=True))。FBX 导出(fbxout)会把非 ASCII 的名字换成下划线, +# 日文骨名的模型导出成 FBX 后就认不出人形骨架了 +EN = {"センター": "Root", "下半身": "Hips", "上半身": "Spine", "上半身2": "Chest", "首": "Neck", "頭": "Head", + "左目": "Eye.L", "右目": "Eye.R", "髪1": "Hair1", "髪2": "Hair2", "髪3": "Hair3"} +for _s, _t in (("左", "L"), ("右", "R")): + EN.update({_s + "肩": "Shoulder." + _t, _s + "腕": "Upper_arm." + _t, _s + "ひじ": "Lower_arm." + _t, + _s + "手首": "Hand." + _t, _s + "足": "Upper_leg." + _t, _s + "ひざ": "Lower_leg." + _t, + _s + "足首": "Foot." + _t, _s + "つま先": "Toe." + _t}) + + +def _png(w, h, alpha): + rows = [] + for y in range(h): + r = bytearray() + for x in range(w): + a = 255 if not alpha else (0 if (x // 8 + y // 8) % 2 else 255) + r += bytes(((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), 128, a)) + rows.append(bytes(r)) + return vrmio.encode_png(w, h, rows) + + +def _box(model, center, half, bone): + """以 center 为中心、半边长 half 的方块,权重全给 bone。返回三角形索引(从外面看顺时针,MMD 的正面)。""" + v0 = len(model["vertices"]) + cx, cy, cz = center + for k in range(8): + dx = half if k & 1 else -half + dy = half if k & 2 else -half + dz = half if k & 4 else -half + n = math.sqrt(3) + model["vertices"].append({ + "pos": (cx + dx, cy + dy, cz + dz), "normal": (dx / half / n, dy / half / n, dz / half / n), + "uv": ((dx / half + 1) / 2, (dy / half + 1) / 2), "wtype": 0, "wbones": [bone], + "wweights": [1.0], "edge": 1.0}) + quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)] + tris = [] + for a, b, c, d in quads: + tris += [v0 + a, v0 + b, v0 + c, v0 + a, v0 + c, v0 + d] + return tris + + +def _material(name, tex, faces, toon=-1): + return {"name": name, "name_en": name, "diffuse": (1.0, 1.0, 1.0, 1.0), "specular": (0, 0, 0), + "shininess": 5.0, "ambient": (0.5, 0.5, 0.5), "flag": 0x01 | 0x02 | 0x04 | 0x10, + "edge_color": (0, 0, 0, 1), "edge_size": 1.0, "tex": tex, "sph": -1, "sph_mode": 0, + "toon_flag": 1 if toon >= 0 else 0, "toon": toon, "memo": "", "faces": faces} + + +def build(folder, name="合成モデル", tex_size=256, eyes=False, english=False): + """在 folder 里写出 .pmx 和贴图,返回 PMX 路径。english:骨名换成英文(见 EN)。""" + os.makedirs(os.path.join(folder, "tex"), exist_ok=True) + with open(os.path.join(folder, "tex", "body.png"), "wb") as f: + f.write(_png(tex_size, tex_size, alpha=False)) + with open(os.path.join(folder, "tex", "hair.png"), "wb") as f: + f.write(_png(64, 64, alpha=True)) + + m = pmxio.new_model(name) + m["textures"] = ["tex\\body.png", "tex\\hair.png"] + index = {n: i for i, (n, _, _) in enumerate(_BONES)} + for i, (n, parent, pos) in enumerate(_BONES): + flag = 0x0001 | 0x0002 | 0x0008 | 0x0010 + if n == "センター": + flag |= 0x0004 + m["bones"].append({"name": n, "name_en": n, "pos": pos, "parent": index[parent] if parent else -1, + "layer": 0, "flag": flag, "tail": -1}) + for n, _, _ in _BONES: # tail:第一个子骨 + kids = [index[c] for c, p, _ in _BONES if p == n] + if kids: + m["bones"][index[n]]["tail"] = kids[0] + + body, hair = [], [] + for n, _, pos in _BONES: + if n.startswith("髪"): + hair += _box(m, pos, 0.35, index[n]) + elif not n.endswith("目"): + body += _box(m, pos, 0.5 if n != "頭" else 1.0, index[n]) + m["faces"] = body + hair + m["materials"] = [_material("体", 0, len(body), toon=1), _material("髪", 1, len(hair))] + if eyes: + eye = [] + for n in ("左目", "右目"): + x, y, z = _BONES[index[n]][2] + eye += _box(m, (x, y, z - 0.25), 0.12, index[n]) # 眼骨在眼珠后面 + v0 = len(m["vertices"]) + for k, (dx, dy) in enumerate(((0, 0), (1, 0), (1, 1), (0, 1))): + m["vertices"].append({"pos": (0.6 + dx * 0.4, 18 + dy * 0.4, -1.05), "normal": (0, 0, -1), + "uv": (dx * 0.25, dy * 0.25), "wtype": 0, "wbones": [index["頭"]], + "wweights": [1.0], "edge": 0.0}) + emo = [v0, v0 + 1, v0 + 2, v0, v0 + 2, v0 + 3] + m["faces"] += eye + emo + m["materials"] += [_material("目", 0, len(eye)), _material("漫符", 1, len(emo))] + + # 表情:动头部方块(「頭」是第 6 根有网格的骨 → 第 6 个方块) + hv = 5 * 8 + m["morphs"] = [ + {"name": "まばたき", "name_en": "blink", "panel": 1, "kind": 1, + "offsets": [(hv + k, (0.0, -0.2, 0.0)) for k in range(4)]}, + {"name": "あ", "name_en": "a", "panel": 2, "kind": 1, + "offsets": [(hv + k, (0.0, -0.3, 0.0)) for k in range(2)]}, + {"name": "にこり", "name_en": "smile", "panel": 3, "kind": 1, + "offsets": [(hv + k, (0.1, 0.1, 0.0)) for k in range(4, 8)]}, + {"name": "笑い", "name_en": "laugh", "panel": 3, "kind": 1, + "offsets": [(hv + k, (0.2, 0.0, 0.0)) for k in range(4, 8)]}, + {"name": "照れ", "name_en": "blush", "panel": 4, "kind": 8, + "offsets": [(0, 0, (1, 0.8, 0.8, 1) + (1,) * 24)]}, + ] + if eyes: + s = math.sin(math.radians(5)) + c = math.cos(math.radians(5)) + m["morphs"] += [ + # 两眼往中间转 10°(PMX 四元数 x, y, z, w;左眼在 +X,绕 Y 转正角朝 -X) + {"name": "寄り目", "name_en": "cross", "panel": 2, "kind": 2, + "offsets": [(index["左目"], (0, 0, 0), (0, s, 0, c)), (index["右目"], (0, 0, 0), (0, -s, 0, c))]}, + {"name": "見開く", "name_en": "wide", "panel": 2, "kind": 0, + "offsets": [(0, -0.5), (5, 1.0)]}, # まばたき × -0.5 + 寄り目 + # 漫符面片的 UV 整体移到贴图右边一格 + {"name": "怒マーク", "name_en": "anger", "panel": 4, "kind": 3, + "offsets": [(v0 + k, (0.5, 0.25, 0, 0)) for k in range(4)]}, + ] + + # 物理:頭(跟随骨骼)+ 头发三节(物理) + def rb(nm, bone, pos, mode, r=0.6): + return {"name": nm, "name_en": nm, "bone": index[bone], "group": 1 if mode else 0, + "mask": 0xFFFF & ~(1 << 1), "shape": 0, "size": (r, 0, 0), "pos": pos, "rot": (0, 0, 0), + "mass": 1.0, "move_damp": 0.5, "rot_damp": 0.5, "repulsion": 0.0, "friction": 0.5, + "mode": mode} + m["rigid_bodies"] = [rb("頭", "頭", (0, 17.2, 0), 0, 1.6), rb("髪1", "髪1", (0, 16.5, 1.0), 0), + rb("髪2", "髪2", (0, 14.6, 1.3), 1), rb("髪3", "髪3", (0, 12.7, 1.45), 1)] + + def joint(nm, a, b, pos): + return {"name": nm, "name_en": nm, "type": 0, "rb_a": a, "rb_b": b, "pos": pos, "rot": (0, 0, 0), + "move_min": (0, 0, 0), "move_max": (0, 0, 0), "rot_min": (-0.5, -0.5, -0.5), + "rot_max": (0.5, 0.5, 0.5), "spring_move": (0, 0, 0), "spring_rot": (10, 10, 10)} + m["joints"] = [joint("髪1-2", 1, 2, (0, 15.6, 1.2)), joint("髪2-3", 2, 3, (0, 13.7, 1.4))] + if english: + for b in m["bones"]: + b["name"] = b["name_en"] = EN.get(b["name"], b["name"]) + + path = os.path.join(folder, name + ".pmx") + pmxio.write_pmx(m, path) + return path diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..b544597 --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,594 @@ +# -*- coding: utf-8 -*- +"""界面启动的兜底逻辑:数据目录写不了时改放 %APPDATA%,没有 WebView2 / 窗口起不来时改用浏览器。""" +import json +import os +import re +import sys +import tempfile +import types +import unittest +from unittest import mock + +HERE = os.path.dirname(os.path.abspath(__file__)) +UI = os.path.join(os.path.dirname(HERE), "ui") +if UI not in sys.path: + sys.path.insert(0, UI) +os.environ.setdefault("VRMIFY_DATA", tempfile.mkdtemp(prefix="m2v_data_")) +import app # noqa: E402 +import server # noqa: E402 +import logtext # noqa: E402,I100 +import version # noqa: E402 + + +class VersionTest(unittest.TestCase): + def test_semver(self): + self.assertRegex(version.__version__, r"^\d+\.\d+\.\d+$") + + +class DataDirTest(unittest.TestCase): + def test_env_override(self): + with mock.patch.dict(os.environ, {"VRMIFY_DATA": "X:/somewhere"}): + self.assertEqual(server._data_dir(), "X:/somewhere") + + def test_beside_program(self): + env = {k: v for k, v in os.environ.items() if k != "VRMIFY_DATA"} + with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(server, "_writable", lambda d: True): + self.assertEqual(server._data_dir(), server.ROOT) + + def test_fallback_to_appdata(self): + env = {k: v for k, v in os.environ.items() if k != "VRMIFY_DATA"} + env["APPDATA"] = "Y:/AppData/Roaming" + with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(server, "_writable", lambda d: False): + self.assertEqual(server._data_dir(), os.path.join("Y:/AppData/Roaming", "VRMify")) + + def test_appdata_renamed_from_old_name(self): + """改名前的 %APPDATA%\\Model-To-VRM 还在、新的没有时改名过去,里面的设置跟着走。""" + base = tempfile.mkdtemp(prefix="m2v_appdata_") + os.makedirs(os.path.join(base, "Model-To-VRM")) + open(os.path.join(base, "Model-To-VRM", "settings.json"), "w").close() + env = {k: v for k, v in os.environ.items() if k != "VRMIFY_DATA"} + env["APPDATA"] = base + with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(server, "_writable", lambda d: False): + self.assertEqual(server._data_dir(), os.path.join(base, "VRMify")) + self.assertTrue(os.path.isfile(os.path.join(base, "VRMify", "settings.json"))) + self.assertFalse(os.path.exists(os.path.join(base, "Model-To-VRM"))) + + def test_writable(self): + self.assertTrue(server._writable(tempfile.mkdtemp(prefix="m2v_w_"))) + + +class OutputDefaultTest(unittest.TestCase): + """界面默认保存到程序目录下的 vrm;旧设置文件里是旧默认值(源文件旁)的换成新默认。""" + + def load(self, saved): + path = os.path.join(tempfile.mkdtemp(prefix="m2v_set_"), "settings.json") + if saved is not None: + with open(path, "w", encoding="utf-8") as f: + json.dump(saved, f) + with mock.patch.object(server, "SETTINGS", path): + return server.Backend._load_settings(None)[0]["output"] + + def test_fresh(self): + self.assertEqual(self.load(None)["mode"], "app") + + def test_old_default_migrates(self): + old = {"opts": {"output": {"mode": "beside", "folder": "", "subfolder": True}}} + self.assertEqual(self.load(old)["mode"], "app") + + def test_own_choice_kept(self): + mine = {"opts": {"output": {"mode": "folder", "folder": "D:/out", "subfolder": True}}} + self.assertEqual(self.load(mine)["mode"], "folder") + # 新版存过的「源文件旁」是自己选的 + self.assertEqual(self.load({"v": 2, "opts": {"output": {"mode": "beside", "folder": "", "subfolder": True}}})["mode"], + "beside") + + def test_app_folder_used(self): + import pipeline + out = tempfile.mkdtemp(prefix="m2v_app_") + opts = pipeline.merged({"output": {"mode": "app", "app_folder": out, "subfolder": False}}) + self.assertEqual(pipeline.output_dir("X:/models/a.pmx", opts), out) + opts["output"].pop("app_folder") # 没给路径(命令行)时同「源文件旁」 + self.assertEqual(pipeline.output_dir(os.path.join(out, "a.pmx"), opts), out) + + +class LayoutTest(unittest.TestCase): + """拖动调的栏宽存进 settings.json:只收认识的键、夹在范围里;传 None 是恢复默认。""" + + def test_widths_saved_and_clamped(self): + path = os.path.join(tempfile.mkdtemp(prefix="m2v_ui_"), "settings.json") + with mock.patch.object(server, "SETTINGS", path): + b = server.Backend.__new__(server.Backend) + b.lock = __import__("threading").RLock() + b.opts, b.lang, b.ui = server.Backend._load_settings(None) + self.assertEqual(b.ui, {}) + b.set_options(ui={"left": 520.6, "side": 50, "bogus": 3, "sideWide": "x"}) + self.assertEqual(b.ui, {"left": 520, "side": 220}) + b.set_options(ui={"sideWide": 400}) + b.set_options(ui={"left": None}) + self.assertEqual(server.Backend._load_settings(None)[2], {"side": 220, "sideWide": 400}) + + +class SkippedStatusTest(unittest.TestCase): + """文件里的模型全被「只转换人物」跳过:状态是「已跳过」不是「完成」;关掉这个选项后回到「待转换」。""" + + def test_skipped(self): + tmp = tempfile.mkdtemp(prefix="m2v_skip_") + prop = os.path.join(tmp, "剑.pmx") + with open(prop, "wb") as f: + f.write(b"PMX ") + with mock.patch.object(server, "SETTINGS", os.path.join(tmp, "settings.json")), \ + mock.patch.object(server, "EDITS", os.path.join(tmp, "edits.json")): + b = server.Backend() + try: + b.add_paths([prop]) + fid = next(iter(b.files)) + with mock.patch.object(server.pipeline, "convert_file", return_value=[]): + b._run([fid], b.opts) + self.assertEqual(b.files[fid]["status"], "skipped") + end = [e for _, e in b.events if e["type"] == "busy" and not e["busy"]][-1] + self.assertEqual((end["done"], end["skipped"], end["failed"]), (0, 1, 0)) + b.set_options(dict(b.opts, vrm=dict(b.opts["vrm"], avatar_only=False))) + self.assertEqual(b.files[fid]["status"], "pending") + finally: + b.close() + + +class PreviewCacheTest(unittest.TestCase): + """还没转换的文件(压缩包、FBX …)预览时先转一份临时 VRM:换了转换设置要重新转,同样的设置用缓存, + 连点不重复转,转的途中又换了设置时旧的那份不推给页面,每个文件只留最近几份。""" + + def setUp(self): + import threading + self.tmp = tempfile.mkdtemp(prefix="m2v_pv_") + src = os.path.join(self.tmp, "a.fbx") + with open(src, "wb") as f: + f.write(b"Kaydara FBX Binary") + self.patches = [mock.patch.object(server, "SETTINGS", os.path.join(self.tmp, "settings.json")), + mock.patch.object(server, "EDITS", os.path.join(self.tmp, "edits.json")), + mock.patch.object(server.pipeline, "convert_file", self.fake)] + for p in self.patches: + p.start() + self.calls, self.gate = [], threading.Event() + self.gate.set() + self.b = server.Backend() + self.b.add_paths([src]) + self.fid = next(iter(self.b.files)) + + def tearDown(self): + self.gate.set() + self.b.close() + for p in self.patches: + p.stop() + + def fake(self, src, opts, log=None, out_dir=None, edits=None): + self.gate.wait(10) + self.calls.append((opts["vrm"]["spec"], opts["vrm"]["spring_stiffness"])) + p = os.path.join(out_dir, "a.vrm") + with open(p, "wb") as f: + f.write(b"glTF") + return [p] + + def wait(self): + import time + for _ in range(500): + with self.b.lock: + if not self.b.preview_jobs: + return + time.sleep(0.01) + self.fail("preview conversion did not finish") + + def setopt(self, **vrm): + self.b.set_options(dict(self.b.opts, vrm=dict(self.b.opts["vrm"], **vrm))) + + def shown(self): + """推给页面的预览事件个数。""" + return len([e for _, e in self.b.events if e["type"] == "preview" and e.get("url")]) + + def test_settings_change_reconverts(self): + self.assertEqual(self.b.preview(self.fid), {"pending": True}) + self.wait() + self.assertIn("url", self.b.preview(self.fid)) # 同样的设置:直接用缓存 + self.assertEqual(self.calls, [("1.0", 1.0)]) + self.setopt(spec="0.x") + self.assertEqual(self.b.preview(self.fid), {"pending": True}) # 换了版本:重新转 + self.wait() + self.assertEqual(self.calls[-1], ("0.x", 1.0)) + self.setopt(spec="1.0") + self.assertIn("url", self.b.preview(self.fid)) # 改回来:之前那份还在 + self.assertEqual(len(self.calls), 2) + # 只改输出位置不算换设置 + self.b.set_options(dict(self.b.opts, output={"mode": "folder", "folder": self.tmp, "subfolder": False})) + self.assertIn("url", self.b.preview(self.fid)) + + def test_no_duplicate_job(self): + self.gate.clear() + self.assertEqual(self.b.preview(self.fid), {"pending": True}) + self.assertEqual(self.b.preview(self.fid), {"pending": True}) + self.gate.set() + self.wait() + self.assertEqual(len(self.calls), 1) + self.assertEqual(self.shown(), 1) + + def test_superseded_job_not_shown(self): + self.gate.clear() + self.b.preview(self.fid) # 1.0,还在转 + self.setopt(spec="0.x") + self.b.preview(self.fid) # 用户换成 0.x 又点了预览 + self.gate.set() + self.wait() + self.assertEqual(sorted(c[0] for c in self.calls), ["0.x", "1.0"]) + self.assertEqual(self.shown(), 1) # 只推 0.x 那份 + f = self.b.files[self.fid] + want = f["previews"][f["preview_want"]] + self.assertEqual(f["preview_path"], want[1]) + + def test_old_previews_removed(self): + dirs = [] + for k in range(5): + self.setopt(spring_stiffness=1.0 + k) + self.b.preview(self.fid) + self.wait() + dirs.append(os.path.dirname(self.b.files[self.fid]["preview_path"])) + cache = self.b.files[self.fid]["previews"] + self.assertEqual(len(cache), server._PREVIEW_KEEP) + self.assertEqual([os.path.isdir(d) for d in dirs], [False, False, True, True, True]) + + +class AutoThumbTest(unittest.TestCase): + """转换后自动生成的缩略图:记成 auto;手动设置过的不覆盖;不算「调整过」;关掉选项后转换不再带上。""" + + def test_auto_vs_manual(self): + import base64 + sys.path[:0] = [os.path.join(os.path.dirname(HERE), p) for p in ("convert", "formats")] + [HERE] + import pmx2vrm + import synth + import vrmio + tmp = tempfile.mkdtemp(prefix="m2v_thumb_") + pmx = synth.build(os.path.join(tmp, "src")) + vrm = os.path.join(tmp, "out.vrm") + pmx2vrm.convert(pmx, vrm) + png = "data:image/png;base64," + base64.b64encode(vrmio.encode_png(2, 2, [b"\xff" * 8] * 2)).decode() + with mock.patch.object(server, "SETTINGS", os.path.join(tmp, "settings.json")), \ + mock.patch.object(server, "EDITS", os.path.join(tmp, "edits.json")), \ + mock.patch.object(server, "EDITS_DIR", os.path.join(tmp, "edits")): + b = server.Backend() + try: + b.add_paths([pmx]) + fid = next(iter(b.files)) + f = b.files[fid] + f.update(status="done", outputs=b._outputs([vrm])) + + def meta_thumb(): + return vrmio.read_glb(vrm)[0]["extensions"]["VRMC_vrm"]["meta"].get("thumbnailImage") + + self.assertTrue(b.tune_thumb(fid, png, auto=True)["ok"]) + self.assertTrue(b.edits_for(f)["thumbnails"]["out"]["auto"]) # 按模型(VRM 文件名)存 + self.assertIsNotNone(meta_thumb()) + self.assertFalse(b._entry(f)["tuned"]) # 只有自动缩略图:不算调整过 + b.tune_save(fid, {"title": "名前"}) # 调整面板保存:缩略图和标记都留着 + self.assertTrue(b.edits_for(f)["thumbnails"]["out"]["auto"]) + self.assertIsNotNone(meta_thumb()) + b.set_options(dict(b.opts, vrm=dict(b.opts["vrm"], auto_thumb=False))) + self.assertNotIn("thumbnails", b._convert_edits(f)) # 关掉后转换不再套用自动截的 + self.assertEqual(b._convert_edits(f)["title"], "名前") + self.assertTrue(b.tune_thumb(fid, png)["ok"]) # 手动设置:去掉标记 + self.assertFalse(b.edits_for(f)["thumbnails"]["out"]["auto"]) + self.assertTrue(b.tune_thumb(fid, png, auto=True)["skipped"]) + self.assertIn("thumbnails", b._convert_edits(f)) + finally: + b.close() + + def test_per_model(self): + """一个包里几个模型:缩略图各存各的、只写进自己的 VRM;旧版按文件存的那张分给各个模型。""" + import base64 + sys.path[:0] = [os.path.join(os.path.dirname(HERE), p) for p in ("convert", "formats")] + [HERE] + import pmx2vrm + import synth + import vrm_edit + import vrmio + tmp = tempfile.mkdtemp(prefix="m2v_thumbs_") + pmx = synth.build(os.path.join(tmp, "src")) + vrms = [os.path.join(tmp, n + ".vrm") for n in ("a", "b")] + for v in vrms: + pmx2vrm.convert(pmx, v) + + def png(c): + return "data:image/png;base64," + base64.b64encode(vrmio.encode_png(2, 2, [bytes([c]) * 8] * 2)).decode() + + def thumb(v): + g, bin_data = vrmio.read_glb(v) + i = g["extensions"]["VRMC_vrm"]["meta"].get("thumbnailImage") + if i is None: + return None + bv = g["bufferViews"][g["images"][i]["bufferView"]] + return bin_data[bv.get("byteOffset", 0):bv.get("byteOffset", 0) + bv["byteLength"]] + + with mock.patch.object(server, "SETTINGS", os.path.join(tmp, "settings.json")), mock.patch.object(server, "EDITS", os.path.join(tmp, "edits.json")), mock.patch.object(server, "EDITS_DIR", os.path.join(tmp, "edits")): + b = server.Backend() + try: + b.add_paths([pmx]) + fid = next(iter(b.files)) + f = b.files[fid] + f.update(status="done", outputs=b._outputs(vrms)) + self.assertTrue(b.tune_thumb(fid, png(0x10), auto=True, model="a")["ok"]) + self.assertIsNotNone(thumb(vrms[0])) + self.assertIsNone(thumb(vrms[1])) # 只写进 a + self.assertTrue(b.tune_thumb(fid, png(0x20), auto=True, model="b")["ok"]) + self.assertNotEqual(thumb(vrms[0]), thumb(vrms[1])) + self.assertEqual(b.tune_info(fid, "b")["model"], "b") + self.assertTrue(b.tune_info(fid, "b")["thumbnail_auto"]) + b.tune_thumb(fid, png(0x30), model="a") # 手动设置 a:a 不再自动更新,b 照常 + self.assertTrue(b.tune_thumb(fid, png(0x40), auto=True, model="a")["skipped"]) + self.assertTrue(b.tune_thumb(fid, png(0x50), auto=True, model="b")["ok"]) + b.tune_thumb(fid, "", model="b") # 去掉 b 的,a 的留着 + self.assertIsNone(thumb(vrms[1])) + self.assertIsNotNone(thumb(vrms[0])) + # 旧版:一张对所有模型;给 a 单独设置后 b 仍用旧的那张 + old = os.path.join(tmp, "old.png") + with open(old, "wb") as fh: + fh.write(base64.b64decode(png(0x60).split(",", 1)[1])) + b.edits[b._key(f)] = {"thumbnail": old} + self.assertEqual(vrm_edit.thumb_for(b.edits_for(f), vrms[1]), old) + b.tune_thumb(fid, png(0x70), model="a") + e = b.edits_for(f) + self.assertNotIn("thumbnail", e) + self.assertEqual(e["thumbnails"]["b"]["path"], old) + self.assertNotEqual(e["thumbnails"]["a"]["path"], old) + finally: + b.close() + + +class LanguageTest(unittest.TestCase): + """界面语言:没选过时跟系统;日志事件带英文版(convert/logtext.py)。""" + + def test_default_follows_the_system(self): + tmp = tempfile.mkdtemp(prefix="m2v_lang_") + settings = os.path.join(tmp, "settings.json") + with mock.patch.object(server, "SETTINGS", settings), \ + mock.patch.object(server, "EDITS", os.path.join(tmp, "edits.json")): + for sys_lang in ("en", "zh_CN"): + with mock.patch.object(server, "system_lang", return_value=sys_lang): + b = server.Backend() + try: + self.assertEqual(b.lang, sys_lang) + finally: + b.close() + with open(settings, "w", encoding="utf-8") as f: + json.dump({"v": 2, "lang": "zh_CN"}, f) + with mock.patch.object(server, "system_lang", return_value="en"): + b = server.Backend() + try: + self.assertEqual(b.lang, "zh_CN") # 选过的不变 + finally: + b.close() + self.assertIn(server.system_lang(), server.LANGS) + + def test_log_events_carry_english(self): + tmp = tempfile.mkdtemp(prefix="m2v_lang_") + with mock.patch.object(server, "SETTINGS", os.path.join(tmp, "settings.json")), \ + mock.patch.object(server, "EDITS", os.path.join(tmp, "edits.json")): + b = server.Backend() + try: + b.log("完成,用时 1.5 秒", "ok") + b.log("没有对照的一句") + ev = [e for _, e in b.events if e["type"] == "log"][-2:] + self.assertEqual(ev[0]["en"], "Done in 1.5 s") + self.assertIsNone(ev[1]["en"]) + finally: + b.close() + + +class StalePreviewTest(unittest.TestCase): + def test_sweep(self): + """启动时删一天以前遗留的预览临时目录,新的不动。""" + root = tempfile.mkdtemp(prefix="m2v_tmproot_") + old, new, other = (os.path.join(root, n) for n in ("model2vrm_preview_old", "vrmify_preview_new", "keep_me")) + for d in (old, new, other): + os.makedirs(os.path.join(d, "sub")) + past = 1_000_000_000 + for d in (old, other): + os.utime(os.path.join(d, "sub"), (past, past)) + os.utime(d, (past, past)) + with mock.patch.object(server.tempfile, "gettempdir", lambda: root): + server._sweep_stale_previews() + self.assertFalse(os.path.exists(old)) + self.assertTrue(os.path.exists(new)) + self.assertTrue(os.path.exists(other)) + + +class WindowFallbackTest(unittest.TestCase): + """pywebview 换成假模块,_browser_loop 换成记录调用,看 main() 走哪条路。""" + + def run_main(self, webview2, start_error=None, loader=None): + """webview2:注册表检测的结果;loader:WebView2 加载器报的版本(None = 没有)。→ (_browser_loop 的调用, backend, 假模块)""" + fake = types.ModuleType("webview") + fake.settings = {"WEBVIEW2_RUNTIME_PATH": None} + fake.create_window = lambda *a, **k: types.SimpleNamespace() + + def start(cb=None, **kw): + if start_error: + raise start_error + fake.start = start + calls, made = [], [] + real_serve = server.serve + + def serve(port=0): + r = real_serve(port) + made.append(r[0]) + return r + with mock.patch.dict(sys.modules, {"webview": fake}), mock.patch.object(app, "_webview2_ok", lambda: webview2), mock.patch.object(app, "_webview2_loader_version", lambda: loader), mock.patch.object(server, "serve", serve), mock.patch.object(app, "_browser_loop", lambda *a: calls.append(a)): + app.main(["--port", "0"]) + return calls, made[0], fake + + def test_window(self): + calls, b, fake = self.run_main(webview2=True) + self.assertEqual(calls, []) + self.assertIsNone(b.mode_note) + self.assertIsNone(fake.settings["WEBVIEW2_RUNTIME_PATH"]) + + def test_no_webview2(self): + calls, b, _ = self.run_main(webview2=False) + self.assertEqual(len(calls), 1) + self.assertTrue(calls[0][2]) # 打开浏览器 + self.assertEqual(b.mode_note["kind"], "no_webview2") + self.assertEqual(b.state()["mode_note"]["kind"], "no_webview2") + with open(b.mode_note["log"], encoding="utf-8") as f: + self.assertIn("WebView2", f.read()) # 原因也写进 startup.log + + def test_registry_misses_but_loader_finds(self): + """注册表里没有记录、加载器却查到运行时(精简过的系统):照常开窗口,告诉 pywebview 用 WebView2。""" + calls, b, fake = self.run_main(webview2=False, loader="120.0.1.2") + self.assertEqual(calls, []) + self.assertIsNone(b.mode_note) + self.assertTrue(fake.settings["WEBVIEW2_RUNTIME_PATH"]) + + def test_window_fails(self): + calls, b, _ = self.run_main(webview2=True, start_error=RuntimeError("boom")) + self.assertEqual(len(calls), 1) + self.assertTrue(calls[0][2]) + self.assertEqual(b.mode_note["kind"], "window_failed") + self.assertIn("boom", b.mode_note["zh"]) + with open(b.mode_note["log"], encoding="utf-8") as f: + self.assertIn("Traceback", f.read()) + + def test_webview2_check_runs(self): + self.assertIsInstance(app._webview2_ok(), bool) + + +class ModelRouteTest(unittest.TestCase): + """/model//<相对路径>:PMX 原生预览读模型和贴图的接口。""" + + @classmethod + def setUpClass(cls): + cls.backend, cls.srv, cls.url = server.serve(0) + cls.tmp = tempfile.mkdtemp(prefix="m2v_route_") + cls.folder = os.path.join(cls.tmp, "模型") + os.makedirs(os.path.join(cls.folder, "tex")) + with open(os.path.join(cls.folder, "a.pmx"), "wb") as f: + f.write(b"PMX " + bytes([0, 0, 0, 64])) + with open(os.path.join(cls.folder, "tex", "s.spa"), "wb") as f: + f.write(b"BM" + bytes(60)) + with open(os.path.join(cls.tmp, "secret.txt"), "w") as f: + f.write("outside") + try: + from PIL import Image + Image.new("RGB", (4, 4), (255, 0, 0)).save(os.path.join(cls.folder, "tex", "c.dds")) + cls.dds = True + except Exception: # noqa: BLE001 + cls.dds = False + cls.base = cls.url.rstrip("/") + cls.backend.dir_url(os.path.join(cls.folder, "a.pmx")).rsplit("/", 1)[0] + + @classmethod + def tearDownClass(cls): + cls.srv.shutdown() + cls.srv.server_close() + cls.backend.close() + + def get(self, path): + import urllib.error + import urllib.request + try: + with urllib.request.urlopen(self.base + "/" + path) as r: + return r.status, r.headers.get("Content-Type"), r.read() + except urllib.error.HTTPError as e: + e.close() + return e.code, None, b"" + + def test_files(self): + st, ct, data = self.get("a.pmx") + self.assertEqual((st, data[:4]), (200, b"PMX ")) + st, ct, _ = self.get("tex/s.spa") + self.assertEqual((st, ct), (200, "image/bmp")) # 球面贴图其实是 BMP + st, ct, _ = self.get("tex%5Cs.spa") # PMX 里写的是反斜杠路径 + self.assertEqual(st, 200) + if self.dds: + st, ct, data = self.get("tex/c.dds") + self.assertEqual((st, ct, data[:4]), (200, "image/png", bytes([0x89]) + b"PNG")) + + def test_moved_texture(self): + """PMX 记的位置没有、文件夹里别处有同名贴图:和转换时一样按文件名找到。""" + deep = os.path.join(self.folder, "sub", "deep") + os.makedirs(deep, exist_ok=True) + with open(os.path.join(deep, "moved.png"), "wb") as f: + f.write(bytes([0x89]) + b"PNG\r\n\x1a\n") + self.assertEqual(self.get("moved.png")[:2], (200, "image/png")) + self.assertEqual(self.get("textures/moved.png")[0], 200) + self.assertEqual(self.get("nothere.png")[0], 404) + + def test_outside_refused(self): + self.assertEqual(self.get("../secret.txt")[0], 404) + self.assertEqual(self.get("%2E%2E/secret.txt")[0], 404) + self.assertEqual(self.get("missing.png")[0], 404) + import urllib.error + import urllib.request + with self.assertRaises(urllib.error.HTTPError) as cm: + urllib.request.urlopen(self.url + "model/nosuchtoken/a.pmx") + cm.exception.close() + + +if __name__ == "__main__": + unittest.main() + + +class UploadTest(unittest.TestCase): + """浏览器模式:拖入 / 选择的文件传到临时文件夹再加入列表。""" + + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="m2v_up_") + self.p = mock.patch.object(server, "UPLOADS", os.path.join(self.tmp, "uploads")) + self.p.start() + self.backend, self.srv, self.url = server.serve(0) + + def tearDown(self): + self.srv.shutdown() + self.srv.server_close() + self.backend.close() + self.p.stop() + import shutil + shutil.rmtree(self.tmp, ignore_errors=True) + + def post(self, key, path, data): + import urllib.parse + import urllib.request + q = urllib.parse.urlencode({"key": key, "path": path}) + with urllib.request.urlopen(urllib.request.Request(self.url + "api/upload?" + q, data=data, method="POST")) as r: + return json.loads(r.read()) + + def done(self, items): + import urllib.request + req = urllib.request.Request(self.url + "api/upload/done", data=json.dumps({"items": items}).encode(), + headers={"Content-Type": "application/json"}, method="POST") + with urllib.request.urlopen(req) as r: + return json.loads(r.read()) + + def test_folder(self): + self.assertEqual(self.post("k1", "模型/a.pmx", b"PMX data"), {"ok": True}) + self.assertEqual(self.post("k1", "模型/tex/b.png", b"png"), {"ok": True}) + added = self.done([{"key": "k1", "roots": ["模型"]}])["added"] + self.assertEqual(len(added), 1) + f = self.backend.files[added[0]] + self.assertTrue(f["path"].startswith(server.UPLOADS)) + self.assertEqual(os.path.relpath(f["path"], server.UPLOADS).split(os.sep)[1:], ["模型", "a.pmx"]) + self.assertTrue(os.path.isfile(os.path.join(os.path.dirname(f["path"]), "tex", "b.png"))) + # 同样的东西再传一次:落在同一个位置(调整按路径保存),已经在列表里就不重复加 + self.assertEqual(self.post("k1", "模型/a.pmx", b"PMX data"), {"ok": True}) + self.assertEqual(self.done([{"key": "k1", "roots": ["模型"]}])["added"], []) + # 「保存在源文件旁边」:传进来的文件改存到程序目录 + opts = {"output": {"mode": "beside"}} + self.assertEqual(self.backend._opts_for(f["path"], opts)["output"]["mode"], "app") + self.assertIs(self.backend._opts_for(os.path.join(self.tmp, "x.pmx"), opts), opts) + + def test_paths_stay_inside(self): + self.post("k2", "../../evil.pmx", b"x") + self.post("k2", "a:b?.pmx", b"x") + names = sorted(os.listdir(self.backend._upload_dir("k2"))) + self.assertEqual(names, ["a_b_.pmx", "evil.pmx"]) + + def test_lone_pmx_warns(self): + self.post("k3", "单独.pmx", b"x") + after = self.backend.events[-1][0] if self.backend.events else 0 + self.assertEqual(len(self.done([{"key": "k3", "roots": ["单独.pmx"]}])["added"]), 1) + logs = [e["msg"] for s, e in self.backend.events if s > after and e["type"] == "log"] + self.assertTrue(any("单独.pmx" in m and "贴图" in m for m in logs), logs) + self.assertTrue(all(logtext.to_en(m) for m in logs)) + diff --git a/tests/test_convert.py b/tests/test_convert.py new file mode 100644 index 0000000..5879d67 --- /dev/null +++ b/tests/test_convert.py @@ -0,0 +1,2118 @@ +# -*- coding: utf-8 -*- +"""不依赖真实模型的测试:用 tests/synth.py 合成的 PMX 跑转换、后调整(vrm_edit)、压缩包输入。 + + python -m unittest discover -s tests -v + +Schema 校验需要 jsonschema(requirements-dev.txt),贴图瘦身需要 Pillow;缺了对应的测试会跳过。 +""" +import copy +import io +import math +import os +import random +import shutil +import struct +import subprocess +import sys +import tarfile +import tempfile +import unittest +import zipfile + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +for _p in (HERE, os.path.join(ROOT, "convert"), os.path.join(ROOT, "formats"), os.path.join(ROOT, "tools", "qa")): + if _p not in sys.path: + sys.path.insert(0, _p) +import archive # noqa: E402 +import check_vrm # noqa: E402 +import pipeline # noqa: E402 +import pmxio # noqa: E402 +import pmx2vrm # noqa: E402 +import synth # noqa: E402 +import vrm_edit # noqa: E402 +import vrmio # noqa: E402 +from vrmconv import expressions, mesh, morphbake, textures # noqa: E402 + +_VALIDATORS = None + + +def validators(): + global _VALIDATORS + if _VALIDATORS is None: + _VALIDATORS = check_vrm.load_validators() + return _VALIDATORS[0] + + +class Base(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.mkdtemp(prefix="m2v_test_") + cls.pmx = synth.build(os.path.join(cls.tmp, "src")) + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmp, ignore_errors=True) + + def convert(self, name, **kw): + out = os.path.join(self.tmp, name + ".vrm") + pmx2vrm.convert(self.pmx, out, **kw) + return out + + def assertValid(self, path): + errs, _, summary = check_vrm.check(path, validators()) + self.assertEqual(errs, [], "\n".join(errs)) + return summary + + +class ConvertTest(Base): + def test_vrm1(self): + out = self.convert("v1") + s = self.assertValid(out) + self.assertEqual(s["spec"], "1.0") + self.assertEqual(s["springs"], 1) + g, _ = vrmio.read_glb(out) + ex = g["extensions"]["VRMC_vrm"]["expressions"] + self.assertEqual(set(ex["preset"]), {"blink", "aa", "happy"}) + # 来源 PMX 表情名记在 extras 里(vrm_edit 靠它重新指定预设) + self.assertEqual(ex["preset"]["happy"]["extras"]["source"], "にこり") + self.assertIn("笑い", ex["custom"]) + self.assertIn("照れ", ex["custom"]) + # 只输出通用 VRM:不加某个程序私有的自定义表情;synth 没有眼睛高光、吐舌,不补 + self.assertFalse({"faceRed", "faceBlue", "hideHighlight", "tongue"} & set(ex["custom"])) + + def test_vrm0_lowercase_presets(self): + out = self.convert("v0", spec="0.x") + self.assertValid(out) + g, _ = vrmio.read_glb(out) + groups = g["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"] + presets = [gr["presetName"] for gr in groups] + self.assertTrue(all(p == p.lower() for p in presets), presets) + self.assertEqual(presets.count("joy"), 1) # にこり 和 笑い 只能有一个是 joy + self.assertIn("blink", presets) + # morph target 名网格和图元两处都写(UniVRM 的 0.x 导出也是这样,老读取端只看图元) + for m in g["meshes"]: + for pr in m["primitives"]: + self.assertEqual(pr["extras"]["targetNames"], m["extras"]["targetNames"]) + # 1.0 只写网格那一处(输出和以前一样) + g1, _ = vrmio.read_glb(self.convert("v1n")) + self.assertTrue(all("extras" not in pr for m in g1["meshes"] for pr in m["primitives"])) + + def test_meta(self): + meta = {"title": "T", "author": "me", "avatar_permission": "onlyAuthor", + "commercial_usage": "corporation", "allow_redistribution": True, + "modification": "allowModification", "credit_notation": "unnecessary", "bogus": 1} + out = self.convert("meta", meta=meta) + self.assertValid(out) + m = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["meta"] + self.assertEqual((m["name"], m["authors"], m["avatarPermission"], m["commercialUsage"]), + ("T", ["me"], "onlyAuthor", "corporation")) + self.assertTrue(m["allowRedistribution"]) + self.assertEqual((m["modification"], m["creditNotation"]), ("allowModification", "unnecessary")) + out0 = self.convert("meta0", spec="0.x", meta=meta) + m0 = vrmio.read_glb(out0)[0]["extensions"]["VRM"]["meta"] + self.assertEqual((m0["allowedUserName"], m0["commercialUssageName"]), ("OnlyAuthor", "Allow")) + self.assertEqual((m0["licenseName"], m0["otherLicenseUrl"]), ("Other", "")) + # 默认不允许再分发:0.x 只有 licenseName 能表达 + m0 = vrmio.read_glb(self.convert("meta0d", spec="0.x"))[0]["extensions"]["VRM"]["meta"] + self.assertEqual(m0["licenseName"], "Redistribution_Prohibited") + m0 = vrmio.read_glb(self.convert("meta0u", spec="0.x", meta={"license_url": "https://example.com/l"})) + m0 = m0[0]["extensions"]["VRM"]["meta"] + self.assertEqual((m0["licenseName"], m0["otherLicenseUrl"]), ("Other", "https://example.com/l")) + + def test_auto_spring(self): + # 去掉所有刚体:头发骨(髪1~3)应按名字自动补成 SpringBone,身体补碰撞体 + import pmxio + m = pmxio.read_pmx(self.pmx) + m["rigid_bodies"], m["joints"] = [], [] + bare = os.path.join(self.tmp, "src", "nophys.pmx") + pmxio.write_pmx(m, bare) + out = os.path.join(self.tmp, "auto.vrm") + pmx2vrm.convert(bare, out) + s = self.assertValid(out) + self.assertEqual(s["springs"], 1) + self.assertGreaterEqual(s["colliders"], 5) + out2 = os.path.join(self.tmp, "noauto.vrm") + pmx2vrm.convert(bare, out2, auto_spring=False) + self.assertNotIn("VRMC_springBone", vrmio.read_glb(out2)[0]["extensions"]) + + def test_sideways_model_is_turned(self): + # 侧着的模型(Unreal 来的 psk 常见):转正后和正面的结果一样 + import pmxio + m = pmxio.read_pmx(self.pmx) + m["rigid_bodies"], m["joints"] = [], [] + front = os.path.join(self.tmp, "src", "front.pmx") + pmxio.write_pmx(m, front) + + def turn(v): # 绕 Y 转 -90°:左手从 +X 转到 +Z + return (-v[2], v[1], v[0]) + for v in m["vertices"]: + v["pos"], v["normal"] = turn(v["pos"]), turn(v["normal"]) + for b in m["bones"]: + b["pos"] = turn(b["pos"]) + for mo in m["morphs"]: + if mo["kind"] == 1: + mo["offsets"] = [(i, turn(o)) for i, o in mo["offsets"]] + side = os.path.join(self.tmp, "src", "side.pmx") + pmxio.write_pmx(m, side) + a, b = os.path.join(self.tmp, "front.vrm"), os.path.join(self.tmp, "side.vrm") + pmx2vrm.convert(front, a) + pmx2vrm.convert(side, b) + ga, gb = vrmio.read_glb(a)[0], vrmio.read_glb(b)[0] + ha = ga["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"]["leftHand"]["node"] + hb = gb["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"]["leftHand"]["node"] + wa, wb = vrmio.node_world_matrices(ga)[ha], vrmio.node_world_matrices(gb)[hb] + for k in range(3): + self.assertAlmostEqual(vrmio.world_translation(wa)[k], vrmio.world_translation(wb)[k], places=3) + + def test_deterministic(self): + a, b = self.convert("det_a"), self.convert("det_b") + with open(a, "rb") as fa, open(b, "rb") as fb: + self.assertEqual(fa.read(), fb.read()) + + def test_threads_same_output(self): + """贴图在几个线程里同时处理(读文件、透明统计、瘦身),写出的文件和一张张处理时完全相同。""" + runs = [{}] + if textures.available(): + runs.append({"tex_max": 32, "tex_jpeg": True}) + for k, kw in enumerate(runs): + a, b = self.convert("thr1_%d" % k, threads=1, **kw), self.convert("thr4_%d" % k, threads=4, **kw) + with open(a, "rb") as fa, open(b, "rb") as fb: + self.assertEqual(fa.read(), fb.read(), kw) + + @unittest.skipUnless(textures.available(), "需要 Pillow") + def test_texture_slimming(self): + big = synth.build(os.path.join(self.tmp, "big"), tex_size=1024) + plain, small = os.path.join(self.tmp, "tex_plain.vrm"), os.path.join(self.tmp, "tex_small.vrm") + pmx2vrm.convert(big, plain) + pmx2vrm.convert(big, small, tex_max=256, tex_jpeg=True) + self.assertValid(small) + self.assertLess(os.path.getsize(small), os.path.getsize(plain)) + g, _ = vrmio.read_glb(small) + mimes = sorted(i["mimeType"] for i in g["images"]) + # 不透明的身体贴图 → JPEG;带透明的头发贴图保持 PNG(裁剪模式要用 alpha) + self.assertEqual(mimes, ["image/jpeg", "image/png"]) + hair = [m for m in g["materials"] if m["name"] == "髪"][0] + self.assertEqual(hair["alphaMode"], "MASK") + + +class AlphaStatsTest(unittest.TestCase): + """贴图透明度统计:装了 Pillow 时走 Pillow(快),结论要和纯 Python 版一致。""" + + @staticmethod + def png(alpha_of): + w = h = 64 + rows = [bytes(v for x in range(w) for v in (200, 120, 90, alpha_of(x, y))) for y in range(h)] + return vrmio.encode_png(w, h, rows) + + @unittest.skipUnless(textures.available(), "需要 Pillow") + def test_pillow_matches_pure_python(self): + from unittest import mock + cases = {"不透明": lambda x, y: 255, "镂空": lambda x, y: 0 if (x // 4 + y // 4) % 2 else 255, + "半透明": lambda x, y: 128, "渐变": lambda x, y: x * 4} + for name, f in cases.items(): + data = self.png(f) + fast = vrmio.png_alpha_stats(data) + with mock.patch.object(vrmio, "_png_alpha_stats_pil", return_value=NotImplemented): + slow = vrmio.png_alpha_stats(data) + self.assertEqual([round(fast[1] / fast[0], 3), round(fast[2] / fast[0], 3)], + [round(slow[1] / slow[0], 3), round(slow[2] / slow[0], 3)], name) + self.assertIsNone(vrmio.png_alpha_stats(b"not a png")) + + @unittest.skipUnless(textures.available(), "需要 Pillow") + def test_only_the_covered_area_counts(self): + """贴图拼着用不到的半透明图层时,材质只按 UV 用到的部分判断透明模式; + UV 全落在完全透明处(靠 UV 表情挪过去才显示的贴片)时按整张图。""" + from vrmconv.materials import MaterialBuilder + tmp = tempfile.mkdtemp(prefix="m2v_cov_") + # u < 0.5 不透明 · 0.5~0.75 半透明 · 0.75 以后完全透明(整张图看是半透明为主) + with open(os.path.join(tmp, "atlas.png"), "wb") as f: + f.write(self.png(lambda x, y: 255 if x < 32 else 128 if x < 48 else 0)) + + def quad(u0, u1): + return [{"uv": (u, v)} for u, v in ((u0, 0.1), (u1, 0.1), (u1, 0.9), (u0, 0.9))] + verts = quad(0.05, 0.45) + quad(0.55, 0.70) + quad(0.80, 0.95) + faces = [k for q in range(3) for k in (4 * q, 4 * q + 1, 4 * q + 2, 4 * q, 4 * q + 2, 4 * q + 3)] + mats = [{"name": n, "diffuse": [1.0, 1.0, 1.0, 1.0], "tex": 0, "faces": 6} for n in ("body", "veil", "emote")] + model = {"vertices": verts, "faces": faces, "materials": mats, "textures": ["atlas.png"]} + mb = MaterialBuilder(model, tmp, vrmio.GLBBuilder(), True, []) + mb.resolve_tex(0) + self.assertEqual([mb.alpha_mode(i, m) for i, m in enumerate(mats)], ["OPAQUE", "BLEND", "BLEND"]) + self.assertEqual(mb.alpha_by_uv, 1) + + +class DecodeImageTest(unittest.TestCase): + """BMP / TGA 转 PNG:装了 Pillow 时走 Pillow,像素要和纯 Python 版一样(32 位 BMP 的第 4 个字节当 alpha)。""" + + @staticmethod + def bmp32(w, h, top_down): + px = bytes(v for i in range(w * h) for v in (i % 256, 40, 200, (i * 7) % 256)) # BGRA + hdr = struct.pack(" 1 else bs[0], 1.0 - w0)] + else: + ws = list(v["wweights"]) + [0.0] * 4 + wl = [(bs[k] if k < len(bs) else bs[0], ws[k]) for k in range(4)] + if sum(x[1] for x in wl) <= 1e-9: + wl = [(bs[0], 1.0)] + acc = {} + for b, w in wl: + b = alias.get(b, b) + acc[b] = acc.get(b, 0.0) + max(0.0, w) + wl = sorted(acc.items(), key=lambda x: -x[1])[:4] + tot = sum(w for _, w in wl) + if tot <= 1e-9: + return [(wl[0][0] if wl else bs[0], 1.0)] + return [(b, w / tot) for b, w in wl] + + def test_cases(self): + def vw(wt, bs, ws, alias=None): + return mesh.vertex_weights([{"wtype": wt, "wbones": bs, "wweights": ws}], 4, alias or {})[0] + self.assertEqual(vw(0, [2], []), [(2, 1.0)]) + self.assertEqual(vw(1, [1, 2], [0.25]), [(2, 0.75), (1, 0.25)]) + self.assertEqual(vw(1, [1, 2], [1.0]), [(1, 1.0), (2, 0.0)]) # 零权重也保留 + self.assertEqual(vw(1, [1, 2], [0.5]), [(1, 0.5), (2, 0.5)]) # 一样大时保持原顺序 + self.assertEqual(vw(1, [1, 2], [0.25], {2: 1}), [(1, 1.0)]) # 别名并到同一根骨 + self.assertEqual(vw(1, [9, 2], [0.25]), [(2, 1.0)]) # 无效骨丢掉 + self.assertEqual(vw(2, [1, 2, 3, 0], [0.5, 0.25, 0.25, 0.0]), [(1, 0.5), (2, 0.25), (3, 0.25), (0, 0.0)]) + + def test_random(self): + rnd = random.Random(7) + vals = [0.0, -0.0, 1.0, 0.5, 0.3, 0.7, -0.2, 1.2, 1e-12, 0.1, 0.9] + verts = [] + for _ in range(5000): + wt = rnd.choice([0, 1, 2, 3, 4]) + n = {0: 0, 1: 1, 2: 4, 3: 1, 4: 4}[wt] + verts.append({"wtype": wt, "wbones": [rnd.choice([-1, 0, 1, 2, 3, 5, 9]) for _ in range(rnd.randint(0, 4))], + "wweights": [rnd.choice(vals) for _ in range(rnd.choice([n, 0]))]}) + base = mesh.vertex_weights(verts, 6, {}) + for alias in ({}, {2: 1}, {3: 0, 5: 2}, {0: 1}, {1: 2, 2: 3}): + want = [self.reference(v, 6, alias) for v in verts] + self.assertEqual(mesh.vertex_weights(verts, 6, alias), want, alias) + self.assertEqual(mesh.vertex_weights(verts, 6, alias, base=base), want, alias) + + +class EditTest(Base): + def setUp(self): + self.v1 = self.convert("e1") + self.v0 = self.convert("e0", spec="0.x") + thumb = os.path.join(self.tmp, "thumb.png") + with open(thumb, "wb") as f: + f.write(synth._png(32, 32, alpha=False)) + self.edits = {"title": "改名", "thumbnail": thumb, + "expressions": {"happy": "笑い", "joy": "笑い", "blink": "", "aa": "まばたき"}, + "spring": {"stiffness": 2.0, "gravity": 0.2, "chains": {}}} + + def _read(self, p): + with open(p, "rb") as f: + return f.read() + + def test_apply_restore_1(self): + orig = self._read(self.v1) + info = vrm_edit.describe(self.v1) + self.assertEqual(info["assign"]["happy"], "にこり") + self.assertEqual(len(info["springs"]), 1) + vrm_edit.apply(self.v1, self.edits) + self.assertValid(self.v1) + g, _ = vrmio.read_glb(self.v1) + v = g["extensions"]["VRMC_vrm"] + self.assertEqual(v["meta"]["name"], "改名") + self.assertIsInstance(v["meta"]["thumbnailImage"], int) + self.assertNotIn("blink", v["expressions"]["preset"]) + self.assertEqual(v["expressions"]["preset"]["happy"]["extras"]["source"], "笑い") + self.assertIn("にこり", v["expressions"]["custom"]) # 原来的 happy 回到自定义 + j = g["extensions"]["VRMC_springBone"]["springs"][0]["joints"][0] + base = info["springs"][0]["joints"][0] + self.assertAlmostEqual(j["stiffness"], round(base["stiffness"] * 2, 4)) + self.assertAlmostEqual(j["gravityPower"], round(base["gravityPower"] + 0.2, 4)) + # 再套一次结果不变(从原始值重新套,不累乘) + once = self._read(self.v1) + vrm_edit.apply(self.v1, self.edits) + self.assertEqual(self._read(self.v1), once) + # describe 看到的仍是原始值 + self.assertEqual(vrm_edit.describe(self.v1)["assign"], info["assign"]) + # 空调整 = 还原 + vrm_edit.apply(self.v1, {}) + g0, b0 = vrmio.read_glb(self.v1) + self.assertNotIn("extras", g0) + self.assertEqual(len(self._read(self.v1)), len(orig)) + + def test_intensity(self): + """预设强度:形态键权重相乘,单个最多到 1;还原后回到原值。""" + def happy(): + g, _ = vrmio.read_glb(self.v1) + return [b["weight"] for b in g["extensions"]["VRMC_vrm"]["expressions"]["preset"]["happy"]["morphTargetBinds"]] + orig = happy() + vrm_edit.apply(self.v1, {"intensity": {"happy": 0.5}}) + self.assertValid(self.v1) + self.assertEqual(happy(), [round(w * 0.5, 4) for w in orig]) + vrm_edit.apply(self.v1, {"intensity": {"happy": 2.0}}) + self.assertEqual(happy(), [min(1.0, w * 2) for w in orig]) + vrm_edit.apply(self.v1, {"intensity": {"happy": 1.0}}) # 100% = 没调 + self.assertEqual(happy(), orig) + g, _ = vrmio.read_glb(self.v1) + self.assertNotIn("extras", g) + + def test_intensity_0x(self): + vrm_edit.apply(self.v0, {"intensity": {"joy": 0.5}}) + self.assertValid(self.v0) + g, _ = vrmio.read_glb(self.v0) + joy = [gr for gr in g["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"] if gr["presetName"] == "joy"] + self.assertEqual([b["weight"] for b in joy[0]["binds"]], [50.0]) + vrm_edit.apply(self.v0, {}) + + def test_chain_off(self): + info = vrm_edit.describe(self.v1) + key = info["springs"][0]["key"] + vrm_edit.apply(self.v1, {"spring": {"chains": {key: {"off": True}}}}) + self.assertValid(self.v1) + g, _ = vrmio.read_glb(self.v1) + self.assertNotIn("VRMC_springBone", g["extensions"]) # 唯一的链关掉 → 整个扩展去掉 + self.assertNotIn("VRMC_springBone", g["extensionsUsed"]) + vrm_edit.apply(self.v1, {}) + self.assertIn("VRMC_springBone", vrmio.read_glb(self.v1)[0]["extensions"]) + + def test_apply_restore_0(self): + orig = vrmio.read_glb(self.v0) + vrm_edit.apply(self.v0, self.edits) + self.assertValid(self.v0) + g, _ = vrmio.read_glb(self.v0) + v = g["extensions"]["VRM"] + self.assertEqual(v["meta"]["title"], "改名") + self.assertIsInstance(v["meta"]["texture"], int) + by = {gr["presetName"]: gr["name"] for gr in v["blendShapeMaster"]["blendShapeGroups"]} + self.assertEqual(by["joy"], "笑い") + self.assertNotIn("blink", by) + vrm_edit.apply(self.v0, {}) + self.assertEqual(vrmio.read_glb(self.v0), orig) + + def test_spring_0x(self): + """0.x 的摆动组在调整页里是「链」:倍率作用在组参数上,关掉 = 去掉这一组,空调整还原。""" + orig = vrmio.read_glb(self.v0) + info = vrm_edit.describe(self.v0) + self.assertEqual(info["spec"], "0.x") + self.assertEqual(len(info["springs"]), 1) + c = info["springs"][0] + g, _ = vrmio.read_glb(self.v0) + grp = g["extensions"]["VRM"]["secondaryAnimation"]["boneGroups"][0] + # 组根下面整棵子树都是关节 + self.assertEqual(c["joints"][0]["node"], grp["bones"][0]) + self.assertGreaterEqual(len(c["joints"]), 2) + self.assertEqual(c["joints"][0]["stiffness"], grp["stiffiness"]) + vrm_edit.apply(self.v0, {"spring": {"stiffness": 2.0, "drag": 0.5, "gravity": 0.2, "chains": {}}}) + self.assertValid(self.v0) + new = vrmio.read_glb(self.v0)[0]["extensions"]["VRM"]["secondaryAnimation"]["boneGroups"][0] + self.assertAlmostEqual(new["stiffiness"], round(grp["stiffiness"] * 2, 4)) + self.assertAlmostEqual(new["dragForce"], round(grp["dragForce"] * 0.5, 4)) + self.assertAlmostEqual(new["gravityPower"], round(grp["gravityPower"] + 0.2, 4)) + self.assertNotIn("stiffness", new) + vrm_edit.apply(self.v0, {"spring": {"chains": {c["key"]: {"off": True}}}}) + self.assertValid(self.v0) + self.assertEqual(vrmio.read_glb(self.v0)[0]["extensions"]["VRM"]["secondaryAnimation"]["boneGroups"], []) + vrm_edit.apply(self.v0, {}) + self.assertEqual(vrmio.read_glb(self.v0), orig) + + def test_spring_0x_old_baseline(self): + """以前调整过(基准里还没有 0.x 物理)的文件:当前的物理就是转换时的,补记进基准。""" + g, b = vrmio.read_glb(self.v0) + orig = copy.deepcopy(g["extensions"]["VRM"]["secondaryAnimation"]) + vrm_edit.apply(self.v0, {"title": "x"}) + g, b = vrmio.read_glb(self.v0) + del g["extras"]["vrmconv_base"]["secondary"] + vrmio.write_glb(g, b, self.v0) + vrm_edit.apply(self.v0, {"spring": {"stiffness": 2.0}}) + vrm_edit.apply(self.v0, {}) + self.assertEqual(vrmio.read_glb(self.v0)[0]["extensions"]["VRM"]["secondaryAnimation"], orig) + + def test_is_empty(self): + self.assertTrue(vrm_edit.is_empty({})) + self.assertTrue(vrm_edit.is_empty({"spring": {"stiffness": 1.0, "chains": {"a": {}}}, "title": ""})) + self.assertFalse(vrm_edit.is_empty({"spring": {"chains": {"a": {"off": True}}}})) + + +def morph_deltas(g, b, name): + """VRM 里某个 morph target 的 [(顶点位置, 偏移)](只要有偏移的顶点;按表情分了几个网格时合起来)。""" + out = [] + for m in g["meshes"]: + names = (m.get("extras") or {}).get("targetNames") or [] + if name not in names: + continue + t = names.index(name) + for pr in m["primitives"]: + pos = vrmio.read_accessor(g, b, pr["attributes"]["POSITION"]) + d = vrmio.read_accessor(g, b, pr["targets"][t]["POSITION"]) + for i in range(0, len(d), 3): + if abs(d[i]) + abs(d[i + 1]) + abs(d[i + 2]) > 1e-7: + out.append((pos[i:i + 3], d[i:i + 3])) + return out + + +def bind_names(g, binds, is1=True): + """表情绑定 → [(morph target 名, 权重)](一个 target 分在几个网格里时只列一次)。""" + out = [] + for bd in binds: + x = (vrm_edit._target_name(g, bd, is1), bd["weight"]) + if x not in out: + out.append(x) + return out + + +class MorphBakeTest(Base): + """骨骼表情 / 视线表情烘焙成顶点偏移,UV 表情换成贴图偏移。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.pmx = synth.build(os.path.join(cls.tmp, "eyes"), "眼モデル", eyes=True) + + def test_vrm1(self): + out = self.convert("eyes1") + self.assertValid(out) + g, b = vrmio.read_glb(out) + ex = g["extensions"]["VRMC_vrm"]["expressions"] + for k in ("lookUp", "lookDown", "lookLeft", "lookRight"): + self.assertIn(k, ex["preset"]) + # VRM 1.0:角色的左边是 +X、上是 +Y + left = morph_deltas(g, b, "lookLeft") + self.assertEqual(len(left), 16) # 两个眼珠方块 + self.assertTrue(all(d[0] > 0 for _, d in left)) + self.assertTrue(all(d[1] > 0 for _, d in morph_deltas(g, b, "lookUp"))) + # 寄り目:两眼往中间(左眼 x>0 往 -X,右眼往 +X) + cross = morph_deltas(g, b, "寄り目") + self.assertEqual(len(cross), 16) + self.assertTrue(all((p[0] > 0) == (d[0] < 0) for p, d in cross)) + # グループ里的骨骼表情也在 + self.assertEqual(len(morph_deltas(g, b, "見開く")), 16 + 4) + # UV 表情 → textureTransformBinds:整块往右下移 (0.5, 0.25) + tt = ex["custom"]["怒マーク"]["textureTransformBinds"] + self.assertEqual(len(tt), 1) + self.assertEqual(g["materials"][tt[0]["material"]]["name"], "漫符") + self.assertEqual([round(x, 4) for x in tt[0]["scale"] + tt[0]["offset"]], [1, 1, 0.5, 0.25]) + self.assertNotIn("morphTargetBinds", ex["custom"]["怒マーク"]) + + def test_vrm0(self): + out = self.convert("eyes0", spec="0.x") + self.assertValid(out) + groups = vrmio.read_glb(out)[0]["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"] + by = {x["name"]: x for x in groups} + self.assertEqual(by["lookLeft"]["presetName"], "lookleft") + mv = by["怒マーク"]["materialValues"] + self.assertEqual(mv[0]["propertyName"], "_MainTex_ST") + # Unity 的 v 从下往上:(sx, sy, ox, 1 - sy - oy) + self.assertEqual([round(x, 4) for x in mv[0]["targetValue"]], [1, 1, 0.5, -0.25]) + + def test_look_range_from_eye_geometry(self): + """lookAt 的最大转角按眼球几何算:瞳孔走到 LOOK_TRAVEL × 瞳孔宽度;上下按比例缩小。""" + out = self.convert("eyes_look") + g, _ = vrmio.read_glb(out) + la = g["extensions"]["VRMC_vrm"]["lookAt"] + h = la["rangeMapHorizontalOuter"]["outputScale"] + self.assertTrue(8.0 <= h <= 20.0, h) + self.assertNotEqual(h, 10.0) # 不是以前的固定值 + self.assertEqual(la["rangeMapHorizontalInner"]["outputScale"], h) + self.assertAlmostEqual(la["rangeMapVerticalDown"]["outputScale"], h * 0.7, places=1) + self.assertAlmostEqual(la["rangeMapVerticalUp"]["outputScale"], h * 0.5, places=1) + # 没有眼骨下的顶点、或者挂在眼骨上的东西不像一只眼睛时退回 10°(日志说明原因) + m = pmxio.read_pmx(self.pmx) + parents = [b["parent"] for b in m["bones"]] + idx = {b["name"]: i for i, b in enumerate(m["bones"])} + eyes = [idx["左目"], idx["右目"]] + look, note = morphbake.eye_look_range(m, [[] for _ in m["vertices"]], parents, eyes) + self.assertIsNone(look) + self.assertIn("10°", note) + whole = [[(idx["左目"], 1.0)] for _ in m["vertices"]] # 整个模型都挂在左眼上 + look, note = morphbake.eye_look_range(m, whole, parents, eyes) + self.assertIsNone(look) + self.assertIn("不像一只眼睛", note) + look, note = morphbake.eye_look_range(m, mesh.vertex_weights(m["vertices"], len(m["bones"]), {}), + parents, eyes) + self.assertIsNotNone(look) + + def test_tune_look(self): + """调整面板改视线最大转角:describe 给转换时的值,apply 改 rangeMap,空调整还原。""" + out = self.convert("eyes_tune") + info = vrm_edit.describe(out) + orig = info["look"] + self.assertTrue(8.0 <= orig["h"] <= 20.0) + vrm_edit.apply(out, {"lookAt": {"h": 25, "down": 5, "up": 0}}) + self.assertValid(out) + la = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["lookAt"] + self.assertEqual([la[k]["outputScale"] for k in ("rangeMapHorizontalInner", "rangeMapHorizontalOuter", + "rangeMapVerticalDown", "rangeMapVerticalUp")], [25, 25, 5, 0]) + self.assertEqual(vrm_edit.describe(out)["look"], orig) # describe 仍是转换时的值 + vrm_edit.apply(out, {}) + la = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["lookAt"] + self.assertEqual(la["rangeMapHorizontalOuter"]["outputScale"], orig["h"]) + self.assertEqual(la["rangeMapVerticalUp"]["outputScale"], orig["up"]) + + def test_gaze_fields_exact(self): + """视线表情 = 横向场 × sinθ/sinΘ + 深度场 × (1−cosθ)/(1−cosΘ):任意角度都等于直接转眼骨。""" + m = pmxio.read_pmx(self.pmx) + idx = {b["name"]: i for i, b in enumerate(m["bones"])} + eyes = (idx["左目"], idx["右目"]) + flat = [(n, morphbake.BoneBaker(m).deltas(o), [], {}) for n, o in morphbake.gaze_offsets( + *eyes, {"lookLeft": 40.0, "lookRight": 40.0, "lookUp": 30.0, "lookDown": 30.0})] + split = morphbake.split_gaze(flat, {"lookLeft", "lookRight", "lookUp", "lookDown"}) + self.assertEqual(split["lookDown"], ("lookDown", "lookUpDown_depth", "v")) + field = {n: d for n, d, _, _ in flat} + for p, deg in (("lookLeft", 13.0), ("lookDown", 7.5), ("lookRight", 40.0)): + tan, depth, axis = split[p] + wt, wd = morphbake.gaze_weights(deg, axis) + direct = morphbake.BoneBaker(m).deltas(dict(morphbake.gaze_offsets( + *eyes, {"lookLeft": deg, "lookRight": deg, "lookUp": deg, "lookDown": deg}))[p]) + for v, d in direct.items(): + t, z = field[tan].get(v, (0, 0, 0)), field[depth].get(v, (0, 0, 0)) + for k in range(3): + self.assertAlmostEqual(t[k] * wt + z[k] * wd, d[k], places=5) + + def test_tune_look_moves_gaze_expressions(self): + out = self.convert("eyes_gaze_w") + g = vrmio.read_glb(out)[0] + ex = g["extensions"]["VRMC_vrm"]["expressions"] + self.assertNotIn("lookLeftRight_depth", ex.get("custom", {})) # 深度场只是 morph target + h = vrm_edit.describe(out)["look"]["h"] + binds = ex["preset"]["lookLeft"]["morphTargetBinds"] + self.assertEqual([n for n, _ in bind_names(g, binds)], ["lookLeft", "lookLeftRight_depth"]) + self.assertEqual([b["weight"] for b in binds], list(morphbake.gaze_weights(h, "h"))) + vrm_edit.apply(out, {"lookAt": {"h": 30, "down": 5}}) + self.assertValid(out) + ex = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["expressions"]["preset"] + self.assertEqual([b["weight"] for b in ex["lookRight"]["morphTargetBinds"]], list(morphbake.gaze_weights(30, "h"))) + self.assertEqual([b["weight"] for b in ex["lookDown"]["morphTargetBinds"]], list(morphbake.gaze_weights(5, "v"))) + vrm_edit.apply(out, {}) # 还原 + ex = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["expressions"]["preset"] + self.assertEqual([b["weight"] for b in ex["lookLeft"]["morphTargetBinds"]], list(morphbake.gaze_weights(h, "h"))) + + def test_no_gaze(self): + out = self.convert("eyes_nogaze", gaze=False) + ex = vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["expressions"] + self.assertNotIn("lookLeft", ex["preset"]) + self.assertIn("寄り目", ex["custom"]) + + def test_plain_model_has_no_gaze(self): + """眼骨上没有网格(synth 默认):转眼骨动不了任何顶点,不补。""" + pmx = synth.build(os.path.join(self.tmp, "plain")) + out = os.path.join(self.tmp, "plain.vrm") + pmx2vrm.convert(pmx, out) + self.assertNotIn("lookLeft", vrmio.read_glb(out)[0]["extensions"]["VRMC_vrm"]["expressions"]["preset"]) + + +class ExtraExprTest(Base): + """补充的自定义表情:hideHighlight(关掉眼睛高光)、tongue(吐舌)。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(synth.build(os.path.join(cls.tmp, "hl"), "高光モデル", eyes=True)) + for mat in m["materials"]: + if mat["name"] == "目": + mat["name"] = "目光" # 眼珠方块当成高光材质 + head = next(i for i, b in enumerate(m["bones"]) if b["name"] == "頭") + vs = [i for i, v in enumerate(m["vertices"]) if v["wbones"] == [head]][:4] + m["morphs"].append({"name": "ぺろっ", "name_en": "tongue", "panel": 3, "kind": 1, + "offsets": [(i, (0.0, -0.1, 0.0)) for i in vs]}) + cls.pmx = os.path.join(cls.tmp, "hl", "高光モデル.pmx") + pmxio.write_pmx(m, cls.pmx) + + def test_generated(self): + out = self.convert("hl1") + self.assertValid(out) + g, b = vrmio.read_glb(out) + cu = g["extensions"]["VRMC_vrm"]["expressions"]["custom"] + self.assertIn("hideHighlight", cu) + self.assertIn("tongue", cu) + self.assertEqual(len(morph_deltas(g, b, "tongue")), 4) + # 两个眼珠方块各自收成一点 + hl = morph_deltas(g, b, "hideHighlight") + self.assertEqual(len(hl), 16) + ends = {tuple(round(p[k] + d[k], 5) for k in range(3)) for p, d in hl} + self.assertEqual(len(ends), 2) + g0 = vrmio.read_glb(self.convert("hl0", spec="0.x"))[0] + names = [gr["name"] for gr in g0["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"]] + self.assertIn("hideHighlight", names) + self.assertIn("tongue", names) + off = vrmio.read_glb(self.convert("hl_off", extra_expr=False))[0] + self.assertFalse({"hideHighlight", "tongue"} & set(off["extensions"]["VRMC_vrm"]["expressions"]["custom"])) + + def test_own_morphs_first(self): + """模型自带关闭高光的表情(这里两组高光各一个):合成一组用,不生成;材质名不像高光也行。""" + m = pmxio.read_pmx(self.pmx) + mi = [i for i, x in enumerate(m["materials"]) if x["name"] == "目光"][0] + m["materials"][mi]["name"] = "eye" + zero = [0.0] * 28 + for k, nm in enumerate(("eye hi1 off", "eye hi2 off")): + m["morphs"].append({"name": nm, "name_en": nm, "panel": 4, "kind": 8, "offsets": [(mi, 0, zero)]}) + m["morphs"].append({"name": "eye hi change", "name_en": "", "panel": 4, "kind": 8, "offsets": [(mi, 0, zero)]}) + logs = [] + added = expressions.add_extras(m, lambda s, t=None: logs.append(s)) + self.assertEqual(added, ["hideHighlight", "tongue"]) + hl = m["morphs"][-2] + self.assertEqual(hl["kind"], 0) + self.assertEqual([m["morphs"][i]["name"] for i, _ in hl["offsets"]], ["eye hi1 off", "eye hi2 off"]) + self.assertEqual(expressions._highlight_materials(m), []) + # 已经有同名表情:不补 + self.assertEqual(expressions.add_extras(m, lambda *a: None), []) + + def test_material_names(self): + def mats(*names): + return {"materials": [{"name": n, "faces": 3} for n in names], "textures": []} + hl = expressions._highlight_materials + self.assertEqual(hl(mats("目光", "ハイライト", "MI_Eye hi", "eye hi1", "MI_Eye1+hi2", "eye+hi")), [0, 1, 2, 3, 4, 5]) + self.assertEqual(hl(mats("髪高光", "目", "白目", "hip", "Chihiro", "hi")), []) + + +class SplitMeshTest(Base): + """按表情分网格:和全放在一个网格里比,每个材质上的顶点、每个表情的偏移、表情绑定都一样。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.pmx = synth.build(os.path.join(cls.tmp, "eyes"), "眼モデル", eyes=True) + + def convert_with(self, name, cost, **kw): + old = mesh.MESH_COST + mesh.MESH_COST = cost + try: + return self.convert(name, **kw) + finally: + mesh.MESH_COST = old + + @staticmethod + def by_material(g, b): + """材质号 → (顶点属性, {morph target 名: 偏移}),偏移全零的不列。""" + out = {} + for m in g["meshes"]: + names = (m.get("extras") or {}).get("targetNames") or [] + for pr in m["primitives"]: + attrs = {k: vrmio.read_accessor(g, b, a) for k, a in pr["attributes"].items()} + attrs["indices"] = vrmio.read_accessor(g, b, pr["indices"]) + self_t = {} + for t, n in zip(pr.get("targets", []), names): + d = list(vrmio.read_accessor(g, b, t["POSITION"])) + if any(d): + self_t[n] = d + out[pr["material"]] = (attrs, self_t) + return out + + def check_same(self, one, split, is1): + self.assertValid(split) + ga, ba = vrmio.read_glb(one) + gb, bb = vrmio.read_glb(split) + self.assertEqual(len(ga["meshes"]), 1) + self.assertGreater(len(gb["meshes"]), 1) + self.assertEqual(self.by_material(ga, ba), self.by_material(gb, bb)) + for m in gb["meshes"]: # 每个网格里的 primitive 带同样多的 target + n = len((m.get("extras") or {}).get("targetNames") or []) + self.assertEqual({len(pr.get("targets", [])) for pr in m["primitives"]}, {n}) + if is1: + ea, eb = (g["extensions"]["VRMC_vrm"]["expressions"] for g in (ga, gb)) + for grp in ("preset", "custom"): + self.assertEqual(set(ea[grp]), set(eb[grp])) + for k, x in ea[grp].items(): + y = eb[grp][k] + self.assertEqual(sorted(bind_names(ga, x.get("morphTargetBinds", []))), + sorted(bind_names(gb, y.get("morphTargetBinds", []))), k) + nodes = [n["mesh"] for n in gb["nodes"] if "mesh" in n] + self.assertEqual(sorted(nodes), list(range(len(gb["meshes"])))) + fp = gb["extensions"]["VRMC_vrm"]["firstPerson"]["meshAnnotations"] + self.assertEqual(len(fp), len(gb["meshes"])) + else: + ea, eb = (g["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"] for g in (ga, gb)) + self.assertEqual([x["name"] for x in ea], [x["name"] for x in eb]) + for x, y in zip(ea, eb): + self.assertEqual(sorted(bind_names(ga, x["binds"], False)), sorted(bind_names(gb, y["binds"], False))) + self.assertEqual(len(gb["extensions"]["VRM"]["firstPerson"]["meshAnnotations"]), len(gb["meshes"])) + return gb + + def test_vrm1(self): + g = self.check_same(self.convert_with("one1", 10 ** 12), self.convert_with("split1", 0), True) + # 没有表情动到的 primitive 不带 morph target + self.assertTrue(any("extras" not in m for m in g["meshes"])) + + def test_vrm0(self): + self.check_same(self.convert_with("one0", 10 ** 12, spec="0.x"), + self.convert_with("split0", 0, spec="0.x"), False) + + def test_tune_look_split(self): + """视线表情的横向场 / 深度场分在几个网格里时,调整视线角度照样按名字改权重。""" + out = self.convert_with("split_tune", 0) + vrm_edit.apply(out, {"lookAt": {"h": 30}}) + self.assertValid(out) + g = vrmio.read_glb(out)[0] + wt, wd = morphbake.gaze_weights(30, "h") + binds = g["extensions"]["VRMC_vrm"]["expressions"]["preset"]["lookLeft"]["morphTargetBinds"] + self.assertEqual(sorted(bind_names(g, binds)), sorted([("lookLeft", wt), ("lookLeftRight_depth", wd)])) + + +class GroupMeshesTest(unittest.TestCase): + def test_group(self): + def pr(v, ts): + return {"vcount": v, "tmap": dict.fromkeys(ts, 0)} + prims = [pr(1000, (0, 1, 2)), pr(1000, (0, 1, 2)), pr(50000, ()), pr(50000, (5,)), pr(10, (3,))] + # 同样的 target 放一起;小块并进表情多的;大块之间只差一个 target 也并(多一个网格不划算); + # 哪儿都没动到的 target 4 放进 target 最多的网格 + self.assertEqual(mesh.group_meshes(prims, 6), [([0, 1, 4], [0, 1, 2, 3, 4]), ([2, 3], [5])]) + old = mesh.MESH_COST + mesh.MESH_COST = 0 + try: + self.assertEqual(mesh.group_meshes(prims, 6), + [([0, 1], [0, 1, 2, 4]), ([2], []), ([3], [5]), ([4], [3])]) + finally: + mesh.MESH_COST = old + self.assertEqual(mesh.group_meshes([pr(5, ())], 0), [([0], [])]) + + +class GlbWriteTest(unittest.TestCase): + def test_roundtrip(self): + d = tempfile.mkdtemp(prefix="m2v_glb_") + try: + for data in (bytearray(b"abcde"), memoryview(b"abcdefgh"), b""): + p = os.path.join(d, "x.glb") + size = vrmio.write_glb({"asset": {"version": "2.0"}}, data, p) + self.assertEqual(size, os.path.getsize(p)) + g, b = vrmio.read_glb(p) + self.assertEqual(g, {"asset": {"version": "2.0"}}) + self.assertEqual(bytes(b[:len(data)]), bytes(data)) + self.assertEqual(len(b) % 4, 0) + finally: + shutil.rmtree(d, ignore_errors=True) + + +class FormatOptsTest(unittest.TestCase): + def test_morphs_follow_vrm_switch(self): + """转 VRM 时格式自己的「导出表情」跟着 VRM 的「表情」开关(界面里只显示那一个);只转 PMX 时用格式自己的。""" + opts = pipeline.merged({"vrm": {"morphs": False}, "fbx": {"morphs": True}, "psk": {"morphs": True}}) + self.assertFalse(pipeline._fmt_opts(opts, "fbx")["morphs"]) + self.assertFalse(pipeline._fmt_opts(opts, "psk")["morphs"]) + self.assertTrue(opts["fbx"]["morphs"]) # 存着的设置不变 + opts["target"] = "pmx" + self.assertTrue(pipeline._fmt_opts(opts, "fbx")["morphs"]) + self.assertEqual(pipeline._fmt_opts(opts, "uemodel"), opts["uemodel"]) + + +class JobsBudgetTest(unittest.TestCase): + """同时转几个:按每个任务的内存估计,最大的几个加起来不超过可用内存的 MEM_SHARE。""" + + def jobs(self, n, mem=None, free=4.0, cpu=8): + from unittest import mock + par = pipeline.parallel + with mock.patch.object(par, "free_memory_gb", return_value=free), mock.patch.object(par, "cores", return_value=cpu), mock.patch.dict(os.environ, {par.WORKER_ENV: ""}): + return par.jobs_for(n, 0, mem) + + def test_jobs(self): + self.assertEqual(self.jobs(4), 2) # 不知道多大:每个 1.5 GB + self.assertEqual(self.jobs(4, [0.5] * 4), 4) + self.assertEqual(self.jobs(4, [1.0] * 4), 3) + self.assertEqual(self.jobs(4, [0.25, 1.5, 0.25, 1.5]), 2) # 两个大的可能同时在跑 + self.assertEqual(self.jobs(4, [1.5] * 4, free=1.0), 1) + self.assertEqual(self.jobs(4, [0.2] * 4, cpu=3), 2) # 物理核数 − 1 + self.assertEqual(self.jobs(4, [0.2] * 4, cpu=1), 1) + self.assertEqual(self.jobs(20, [0.2] * 20, free=30, cpu=16), 8) # 最多 MAX_AUTO + self.assertEqual(self.jobs(20, [1.0] * 20, free=5, cpu=16), 4) # 内存不够时更少 + self.assertEqual(self.jobs(1, [0.2]), 1) + + def test_estimate(self): + d = tempfile.mkdtemp(prefix="m2v_mem_") + try: + pmx = os.path.join(d, "a.pmx") + with open(pmx, "wb") as f: + f.write(b"\0" * (4 << 20)) + self.assertAlmostEqual(pipeline.memory_estimate(pmx), 0.15 + 4 * 35 / 1024) + z = os.path.join(d, "a.zip") + with zipfile.ZipFile(z, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("m/body.pmx", b"\0" * (16 << 20)) # 按解压后的大小估 + zf.writestr("m/prop.pmx", b"\0" * 1000) + zf.writestr("m/tex.png", b"\0" * (64 << 20)) + self.assertAlmostEqual(pipeline.memory_estimate(z), 0.15 + 16 * 35 / 1024) + with zipfile.ZipFile(z, "w") as zf: + zf.writestr("m/a.unitypackage", b"x") + self.assertEqual(pipeline.memory_estimate(z), pipeline.UNKNOWN_GB) + self.assertEqual(pipeline.memory_estimate(os.path.join(d, "x.7z")), pipeline.UNKNOWN_GB) + big = os.path.join(d, "big.fbx") + with open(big, "wb") as f: + f.truncate(200 << 20) + self.assertEqual(pipeline.memory_estimate(big), pipeline.parallel.GB_PER_JOB) + finally: + shutil.rmtree(d, ignore_errors=True) + + +class ComboTest(Base): + """情绪预设组合眉 / 眼 / 嘴:按 PMX 面板挑表情,原来单个对应的回到自定义。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(synth.build(os.path.join(cls.tmp, "combo"), "組合モデル")) + hv = 5 * 8 # 头部方块的顶点 + # 「怒り目」带着「怒り」的眉毛(同样的顶点、更大的偏移):和怒り一起用会动两遍,跳过它用キリッ + for name, panel, vs in (("怒り", 1, (0, 1)), ("怒り目", 2, (0, 1, 2)), ("キリッ", 2, (2, 3)), + ("∧", 3, (4, 5)), ("喜び", 2, (2, 3)), ("上", 1, (6,)), ("びっくり", 2, (7,))): + m["morphs"].append({"name": name, "name_en": name, "panel": panel, "kind": 1, + "offsets": [(hv + k, (0.0, 0.05 * panel, 0.0)) for k in vs]}) + # 单眼眨眼按顶点在哪边定(角色的左边是 +X),不按名字:这里故意和 MMD 惯例反着来 + left = [hv + k for k in range(8) if m["vertices"][hv + k]["pos"][0] > 0] + right = [hv + k for k in range(8) if m["vertices"][hv + k]["pos"][0] < 0] + for name, vs in (("ウィンク2", left), ("ウィンク", right), ("ウィンク右", left)): + m["morphs"].append({"name": name, "name_en": name, "panel": 2, "kind": 1, + "offsets": [(v, (0.0, -0.01, 0.0)) for v in vs]}) + cls.pmx = os.path.join(cls.tmp, "combo", "組合モデル.pmx") + pmxio.write_pmx(m, cls.pmx) + + def binds(self, g, obj): + return bind_names(g, obj["morphTargetBinds"]) + + def test_vrm1(self): + out = self.convert("combo1") + self.assertValid(out) + g = vrmio.read_glb(out)[0] + ex = g["extensions"]["VRMC_vrm"]["expressions"] + self.assertEqual(self.binds(g, ex["preset"]["angry"]), [("怒り", 0.5), ("キリッ", 0.3), ("∧", 0.3)]) + self.assertEqual(ex["preset"]["angry"]["extras"]["source"], "怒り+キリッ+∧") + self.assertIn("怒り", ex["custom"]) # 原来单个对应的还在 + self.assertNotIn("overrideBlink", ex["preset"]["angry"]) # 生气时照样眨眼 + self.assertEqual(ex["preset"]["happy"]["overrideBlink"], "blend") # 笑眼不再叠加眨眼 + # synth 的「にこり」「笑い」在口面板,不当眉毛 / 眼睛:眉毛用「上」、眼睛用「喜び」 + self.assertEqual(self.binds(g, ex["preset"]["happy"]), [("上", 0.3), ("喜び", 1.0)]) + self.assertIn("にこり", ex["custom"]) + # 只找到一个部位(嘴)→ 不组合,没有 sad + self.assertNotIn("sad", ex["preset"]) + + def test_wink_by_side(self): + out = self.convert("wink1") + g = vrmio.read_glb(out)[0] + ex = g["extensions"]["VRMC_vrm"]["expressions"] + self.assertEqual(self.binds(g, ex["preset"]["blinkRight"]), [("ウィンク", 1.0)]) + # 左边有「ウィンク2」「ウィンク右」两个:名字里没有「2」的优先 + self.assertEqual(self.binds(g, ex["preset"]["blinkLeft"]), [("ウィンク右", 1.0)]) + self.assertIn("ウィンク2", ex["custom"]) + + def test_vrm0(self): + out = self.convert("combo0", spec="0.x") + self.assertValid(out) + groups = vrmio.read_glb(out)[0]["extensions"]["VRM"]["blendShapeMaster"]["blendShapeGroups"] + by = {x["name"]: x for x in groups} + self.assertEqual(by["怒り+キリッ+∧"]["presetName"], "angry") + self.assertEqual([b["weight"] for b in by["怒り+キリッ+∧"]["binds"]], [50, 30, 30]) + self.assertEqual(by["怒り"]["presetName"], "unknown") + # 0.x 没有 surprised 预设:和 VRoid 一样是 unknown + 名字 Surprised + self.assertEqual(by["Surprised"]["presetName"], "unknown") + self.assertEqual([b["weight"] for b in by["Surprised"]["binds"]], [70, 100]) + self.assertNotIn("surprised", {x["presetName"] for x in groups}) + + def test_off(self): + out = self.convert("combo_off", combo_expr=False) + g = vrmio.read_glb(out)[0] + self.assertEqual(self.binds(g, g["extensions"]["VRMC_vrm"]["expressions"]["preset"]["angry"]), + [("怒り", 1.0)]) + + def test_tune_back_to_single(self): + out = self.convert("combo_edit") + info = vrm_edit.describe(out) + self.assertEqual(info["assign"]["angry"], "怒り+キリッ+∧") + vrm_edit.apply(out, {"expressions": {"angry": "怒り"}}) + self.assertValid(out) + g = vrmio.read_glb(out)[0] + ex = g["extensions"]["VRMC_vrm"]["expressions"] + self.assertEqual(self.binds(g, ex["preset"]["angry"]), [("怒り", 1.0)]) + self.assertIn("怒り+キリッ+∧", ex["custom"]) + + +class OtherNamingTest(Base): + """不按 MMD 标准起名的模型:ARKit(左右各一个)、中文名;名字靠不住的单眼眨眼按顶点定左右。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(synth.build(os.path.join(cls.tmp, "arkit"), "ARKitモデル")) + hv = 5 * 8 + left = [hv + k for k in range(8) if m["vertices"][hv + k]["pos"][0] > 0] + right = [hv + k for k in range(8) if m["vertices"][hv + k]["pos"][0] < 0] + rename = {"まばたき": "眨眼", "あ": "啊2", "にこり": "Mouth_Smile1", "笑い": "Mouth_Laugh1"} + for mo in m["morphs"]: + mo["name"] = rename.get(mo["name"], mo["name"]) + mo["panel"] = 4 + # 左右各一组:eyeBlinkLeft 故意放在角色右边(-X),看是不是按顶点认 + for name, vs in (("eyeBlinkLeft", right), ("eyeBlinkRight", left), ("eyeWideLeft", left[:2]), + ("eyeWideRight", right[:2]), ("browInnerUp", left[2:3] + right[2:3]), + ("browOuterUpLeft", left[3:4]), ("browOuterUpRight", right[3:4]), + ("jawOpen", left[:1] + right[:1]), ("mouthPucker", left[1:2] + right[1:2])): + m["morphs"].append({"name": name, "name_en": name, "panel": 4, "kind": 1, + "offsets": [(v, (0.0, -0.01, 0.001)) for v in vs]}) + cls.pmx = os.path.join(cls.tmp, "arkit", "ARKitモデル.pmx") + pmxio.write_pmx(m, cls.pmx) + + def test_presets(self): + logs = [] + out = os.path.join(self.tmp, "arkit.vrm") + pmx2vrm.convert(self.pmx, out, log=lambda s, t=None: logs.append((s, t))) + self.assertValid(out) + g = vrmio.read_glb(out)[0] + pre = g["extensions"]["VRMC_vrm"]["expressions"]["preset"] + + def binds(p): + return bind_names(g, pre[p]["morphTargetBinds"]) + self.assertEqual(binds("blink"), [("眨眼", 1.0)]) # 中文名 + self.assertEqual(binds("aa"), [("啊2", 1.0)]) # 中文名 + 变体后缀 + self.assertEqual(binds("ou"), [("mouthPucker", 1.0)]) # ARKit 退路 + self.assertEqual(binds("blinkLeft"), [("eyeBlinkRight", 1.0)]) # 按顶点:它在角色左边 + self.assertEqual(binds("blinkRight"), [("eyeBlinkLeft", 1.0)]) + # 惊讶 = ARKit 的抬眉(三个)+ 睁眼(左右一对) + self.assertEqual(sorted(n for n, _ in binds("surprised")), + sorted(["browInnerUp", "browOuterUpLeft", "browOuterUpRight", "eyeWideLeft", "eyeWideRight"])) + rep = [s for s, t in logs if s.startswith("表情预设:")] + self.assertEqual(len(rep), 1) + self.assertIn("surprised ← browInnerUp×0.7", rep[0]) + self.assertIn("未找到:", rep[0]) + + +class SkeletonTest(Base): + """MMD 式的骨架:下半身 / 上半身从同一点出发、缺上半身2。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(synth.build(os.path.join(cls.tmp, "mmd"), "MMD骨架")) + idx = {b["name"]: i for i, b in enumerate(m["bones"])} + m["bones"][idx["下半身"]]["pos"] = m["bones"][idx["上半身"]]["pos"] # 和上半身同一点 + for b in m["bones"]: # 去掉上半身2 + if b["parent"] == idx["上半身2"]: + b["parent"] = idx["上半身"] + m["bones"][idx["上半身2"]]["name"] = "未使用" + m["bones"][idx["上半身2"]]["parent"] = idx["上半身"] + cls.pmx = os.path.join(cls.tmp, "mmd", "MMD骨架.pmx") + pmxio.write_pmx(m, cls.pmx) + + def test_material_names_unique(self): + """PMX 允许材质重名;按材质名找材质的程序(脸部染色)只会找到第一个。""" + m = pmxio.read_pmx(self.pmx) + for mat in m["materials"]: + mat["name"] = "体" + pmx = os.path.join(self.tmp, "mmd", "同名材质.pmx") + pmxio.write_pmx(m, pmx) + out = os.path.join(self.tmp, "dup.vrm") + pmx2vrm.convert(pmx, out) + self.assertValid(out) + names = [x["name"] for x in vrmio.read_glb(out)[0]["materials"]] + self.assertEqual(names, ["体", "体_2"]) + + def world(self, g, node): + par = {c: i for i, n in enumerate(g["nodes"]) for c in n.get("children", [])} + x = [0.0, 0.0, 0.0] + while node is not None: + x = [a + b for a, b in zip(x, g["nodes"][node].get("translation", [0, 0, 0]))] + node = par.get(node) + return x + + def test_upper_chest_by_hierarchy(self): + """上半身3 在 上半身 和 上半身2 之间(名字和层级反着):按层级分,上半身3 是 chest。""" + m = pmxio.read_pmx(synth.build(os.path.join(self.tmp, "uc"), "上半身3")) + idx = {b["name"]: i for i, b in enumerate(m["bones"])} + m["bones"].append({"name": "上半身3", "name_en": "", "pos": (0, 12.2, 0), "parent": idx["上半身"], + "layer": 0, "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, "tail": idx["上半身2"]}) + m["bones"][idx["上半身2"]]["parent"] = len(m["bones"]) - 1 + pmx = os.path.join(self.tmp, "uc", "上半身3.pmx") + pmxio.write_pmx(m, pmx) + out, logs = os.path.join(self.tmp, "uc.vrm"), [] + pmx2vrm.convert(pmx, out, log=lambda s, t=None: logs.append(s)) + self.assertValid(out) + g = vrmio.read_glb(out)[0] + hb = g["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"] + self.assertEqual(g["nodes"][hb["chest"]["node"]]["name"], "上半身3") + self.assertEqual(g["nodes"][hb["upperChest"]["node"]]["name"], "上半身2") + self.assertFalse([s for s in logs if "无法修正" in s], logs) + + def test_hips_and_chest(self): + out = self.convert("mmd1") + self.assertValid(out) + g, b = vrmio.read_glb(out) + hb = {k: v["node"] for k, v in g["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"].items()} + hips, spine, leg = (self.world(g, hb[k]) for k in ("hips", "spine", "leftUpperLeg")) + # hips 移到骨盆:在大腿根和 spine 之间,不和 spine 重合 + self.assertGreater(spine[1] - hips[1], 0.3 * (spine[1] - leg[1])) + self.assertGreater(hips[1], leg[1]) + # 1.0 也补 chest / neck(游戏的布娃娃要) + self.assertIn("chest", hb) + self.assertIn("neck", hb) + # 蒙皮:每根骨的逆绑定矩阵 = 节点世界坐标取反(hips 挪过也一致) + skin = g["skins"][0] + m = vrmio.read_accessor(g, b, skin["inverseBindMatrices"]) + for k, j in enumerate(skin["joints"]): + w = self.world(g, j) + for a in range(3): + self.assertAlmostEqual(-m[16 * k + 12 + a], w[a], places=5) + + +class PruneTest(Base): + """不起作用的骨(IK、末端骨)去掉;collapse_bones 时没有权重的中间骨(全ての親 / センター)也去掉。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(cls.pmx) + B = m["bones"] + idx = {b["name"]: i for i, b in enumerate(B)} + for v in m["vertices"]: # センター 不带顶点 + v["wbones"] = [idx["下半身"] if b == idx["センター"] else b for b in v["wbones"]] + B.append({"name": "全ての親", "name_en": "", "pos": (0, 0, 0), "parent": -1, "layer": 0, + "flag": 0x001F, "tail": -1}) + B[idx["センター"]]["parent"] = len(B) - 1 + B.append({"name": "左足IK", "name_en": "", "pos": (0.9, 1.2, 0), "parent": len(B) - 1, "layer": 0, + "flag": 0x001F, "tail": -1}) + B.append({"name": "左手先", "name_en": "", "pos": (5.5, 12, 0), "parent": idx["左手首"], "layer": 0, + "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, "tail": -1}) + cls.pmx = os.path.join(cls.tmp, "src", "prune.pmx") + pmxio.write_pmx(m, cls.pmx) + + def bone_weights(self, g, b): + """骨名 → 挂在上面的权重之和(和节点序号无关,比较两种输出用)。""" + J, out = g["skins"][0]["joints"], {} + for m in g["meshes"]: + for pr in m["primitives"]: + jn = vrmio.read_accessor(g, b, pr["attributes"]["JOINTS_0"]) + wt = vrmio.read_accessor(g, b, pr["attributes"]["WEIGHTS_0"]) + for j, w in zip(jn, wt): + if w > 0: + nm = g["nodes"][J[j]]["name"] + out[nm] = round(out.get(nm, 0) + w, 4) + return out + + def test_prune(self): + out = self.convert("prune", collapse_bones=False) + self.assertValid(out) + g, b = vrmio.read_glb(out) + names = [n["name"] for n in g["nodes"]] + self.assertNotIn("左足IK", names) + self.assertNotIn("左手先", names) + self.assertIn("全ての親", names) # センター → 下半身 之间的祖先留着 + self.assertIn("センター", names) + J = g["skins"][0]["joints"] + self.assertEqual(len(J), len(set(J))) + out2 = self.convert("collapse", collapse_bones=True) + self.assertValid(out2) + g2, b2 = vrmio.read_glb(out2) + names2 = [n["name"] for n in g2["nodes"]] + self.assertFalse({"全ての親", "センター", "左足IK"} & set(names2)) + hips = g2["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"]["hips"]["node"] + root = g2["scenes"][0]["nodes"][0] + self.assertIn(hips, g2["nodes"][root]["children"]) + self.assertEqual(self.bone_weights(g, b), self.bone_weights(g2, b2)) + # 节点世界坐标不变 + w1 = {g["nodes"][j]["name"]: SkeletonTest.world(self, g, j) for j in J} + for j in g2["skins"][0]["joints"]: + nm = g2["nodes"][j]["name"] + for a, c in zip(SkeletonTest.world(self, g2, j), w1[nm]): + self.assertAlmostEqual(a, c, places=5) + + +class SkirtTest(Base): + """左腿后面一片后裙:两条链分在腿轴两侧(A 在内侧、B 在外侧),裙片朝后。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(cls.pmx) + cls.add_skirt(m) + cls.pmx = os.path.join(cls.tmp, "src", "裙.pmx") + pmxio.write_pmx(m, cls.pmx) + + @staticmethod + def add_skirt(m): + idx = {b["name"]: i for i, b in enumerate(m["bones"])} + z, ys = 1.5, (10.6, 9.0, 7.4, 5.8) + cols = {"A": 0.35, "B": 1.45} # 左腿轴在 x = 0.9 + for c, x in cols.items(): + parent = idx["下半身"] + for k, y in enumerate(ys): + idx["後裙%s%d" % (c, k)] = len(m["bones"]) + m["bones"].append({"name": "後裙%s%d" % (c, k), "name_en": "", "pos": (x, y, z), + "parent": parent, "layer": 0, "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, + "tail": -1}) + parent = idx["後裙%s%d" % (c, k)] + v0, xs = len(m["vertices"]), [0.2 + 0.2 * i for i in range(8)] + for y in ys: + for x in xs: + c = "A" if x < 0.9 else "B" + k = min(range(3), key=lambda k: abs(ys[k] - y)) + m["vertices"].append({"pos": (x, y, z), "normal": (0, 0, 1), "uv": (0, 0), "wtype": 0, + "wbones": [idx["後裙%s%d" % (c, k)]], "wweights": [1.0], "edge": 0.0}) + faces = [] + for r in range(len(ys) - 1): + for i in range(len(xs) - 1): + a, b = v0 + r * len(xs) + i, v0 + (r + 1) * len(xs) + i + faces += [a, b, b + 1, a, b + 1, a + 1] + m["faces"] += faces + m["materials"].append(dict(m["materials"][0], name="裙", faces=len(faces))) + + def rb(nm, bone, pos, mode, shape=0, size=(0.3, 0, 0)): + return {"name": nm, "name_en": nm, "bone": idx[bone], "group": 0 if mode == 0 else 2, "mask": 0xFFFF, + "shape": shape, "size": size, "pos": pos, "rot": (0, 0, 0), "mass": 1.0, "move_damp": 0.5, + "rot_damp": 0.5, "repulsion": 0.0, "friction": 0.5, "mode": mode} + m["rigid_bodies"].append(rb("左足", "左足", (0.9, 8.25, 0), 0, shape=2, size=(0.6, 3.5, 0))) + for c, x in cols.items(): + for k in range(3): + m["rigid_bodies"].append(rb("後裙%s%d" % (c, k), "後裙%s%d" % (c, k), (x, ys[k], z), 1)) + + def leg_shifts(self, out): + """每条裙链用到的左腿碰撞体,相对原碰撞体(挂在左足上、半径最大的那个)的平移。""" + g = vrmio.read_glb(out)[0] + sb = g["extensions"]["VRMC_springBone"] + leg = next(i for i, n in enumerate(g["nodes"]) if n.get("name") == "左足") + caps = {i: c["shape"]["capsule"] for i, c in enumerate(sb["colliders"]) + if c["node"] == leg and "capsule" in c["shape"]} + orig = caps[min(caps)] + res = {} + for sp in sb["springs"]: + if not sp["name"].startswith("後裙"): + continue + ids = [i for gi in sp.get("colliderGroups", []) for i in sb["colliderGroups"][gi]["colliders"] if i in caps] + self.assertEqual(len(ids), 1) + res[sp["name"][2]] = [caps[ids[0]]["offset"][k] - orig["offset"][k] for k in range(3)] + return res + + def test_leg_pushes_along_panel(self): + out = self.convert("skirt") + self.assertValid(out) + d = self.leg_shifts(out) + # 两条链各自的腿往自己那一侧挪(A 内侧 -x、B 外侧 +x),前后几乎不动: + # 被腿碰到时两条链都沿裙片法线往后推,而不是被腿轴分到两边 + self.assertLess(d["A"][0], -0.03) + self.assertGreater(d["B"][0], 0.03) + for c in "AB": + self.assertLess(abs(d[c][2]), 0.015) + self.assertAlmostEqual(d[c][1], 0.0, places=6) + + def test_leg_proxy_off(self): + d = self.leg_shifts(self.convert("skirt_off", spring_opts={"leg_proxy": False})) + for c in "AB": + self.assertEqual(d[c], [0.0, 0.0, 0.0]) + + +def add_hands(m, thumb="3"): + """给合成模型加手指:顺着下垂的前臂伸出去、每节往下弯一点,掌面横着转了一个角度,拇指贴着手掌。 + thumb:"3" = 親指0~2;"2far" = 只有 親指1、2(親指1 在第二节的位置);"2near" = 只有两节、親指1 在掌根。""" + B = m["bones"] + idx = {b["name"]: i for i, b in enumerate(B)} + + def bone(name, parent, pos): + idx[name] = len(B) + B.append({"name": name, "name_en": "", "pos": tuple(pos), "parent": idx[parent], "layer": 0, + "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, "tail": -1}) + f = synth._box(m, pos, 0.06, idx[name]) + m["faces"] += f + m["materials"].append(dict(m["materials"][0], name="手_" + name, faces=len(f))) + + for s, sx in (("左", 1), ("右", -1)): + w = B[idx[s + "手首"]]["pos"] + e = B[idx[s + "ひじ"]]["pos"] + fwd = [w[k] - e[k] for k in range(3)] + n = math.sqrt(sum(x * x for x in fwd)) + fwd = [x / n for x in fwd] + down = [-fwd[1] * sx, fwd[0] * sx, 0.0] # 臂所在竖直面里、朝下的方向 + if down[1] > 0: + down = [-x for x in down] + # 掌面横向:前后(-Z 是前)稍微往下歪,模拟掌心没完全朝下 + across = [0.3 * down[k] for k in range(3)] + across[2] += 1.0 + + def walk(start, offs, curls, name, side_off): + p = [start[k] + side_off * across[k] for k in range(3)] + out = [] + for k, (L, c) in enumerate(zip(offs, curls)): + c = math.radians(c) + d = [math.cos(c) * fwd[j] + math.sin(c) * down[j] for j in range(3)] + p = [p[j] + L * d[j] for j in range(3)] + out.append(list(p)) + return out + base = [w[k] + 0.55 * fwd[k] for k in range(3)] + for f, z in (("人指", -0.25), ("中指", -0.08), ("薬指", 0.08), ("小指", 0.25)): + pts = walk(base, (0.0, 0.3, 0.25, 0.2), (0, 15, 30, 45), f, z) + parent = s + "手首" + for k, nm in enumerate(("1", "2", "3", "先")): + bone(s + f + nm, parent, pts[k]) + parent = s + f + nm + tb = [w[k] + 0.1 * fwd[k] - 0.25 * across[k] for k in range(3)] + names = {"3": ("0", "1", "2", "先"), "2far": ("1", "2", "先"), "2near": ("1", "2", "先")}[thumb] + lens = {"3": (0.0, 0.3, 0.25, 0.2), "2far": (0.3, 0.25, 0.2), "2near": (0.0, 0.25, 0.2)}[thumb] + p = list(tb) + parent = s + "手首" + for nm, L in zip(names, lens): + p = [p[j] + L * (0.8 * fwd[j] - 0.6 * across[j]) for j in range(3)] + bone(s + "親指" + nm, parent, p) + parent = s + "親指" + nm + return m + + +class HandTPoseTest(Base): + """手、四指、拇指也摆成 VRM T-pose(tpose.md):手和四指沿 ±X、掌心朝下,拇指水平指向 ±X 与正前方的 45°。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.src = {} + for kind in ("3", "2far", "2near"): + m = add_hands(pmxio.read_pmx(cls.pmx), kind) + cls.src[kind] = os.path.join(cls.tmp, "src", "hand_%s.pmx" % kind) + pmxio.write_pmx(m, cls.src[kind]) + + def conv(self, kind, spec, **kw): + # 这组用例测的就是 T-pose 功能本身;转换的默认已改成「不强制 T-pose」,这里显式打开 + kw.setdefault("tpose", True) + out = os.path.join(self.tmp, "hand_%s_%s_%d.vrm" % (kind, spec, len(kw))) + pmx2vrm.convert(self.src[kind], out, spec=spec, **kw) + self.assertValid(out) + g = vrmio.read_glb(out)[0] + if spec == "1.0": + hb = {k: v["node"] for k, v in g["extensions"]["VRMC_vrm"]["humanoid"]["humanBones"].items()} + else: + hb = {x["bone"]: x["node"] for x in g["extensions"]["VRM"]["humanoid"]["humanBones"]} + return g, hb + + def angle(self, a, b): + c = sum(x * y for x, y in zip(a, b)) / math.sqrt(sum(x * x for x in a) * sum(x * x for x in b)) + return math.degrees(math.acos(max(-1.0, min(1.0, c)))) + + def test_spec_pose(self): + for spec in ("1.0", "0.x"): + g, hb = self.conv("3", spec) + P = {k: SkeletonTest.world(self, g, n) for k, n in hb.items()} + front = 1.0 if spec == "1.0" else -1.0 # 1.0 前 +Z;0.x 前 -Z(左 -X) + for side in ("left", "right"): + sx = (1.0 if side == "left" else -1.0) * (1.0 if spec == "1.0" else -1.0) + X, T = (sx, 0, 0), (sx, 0, front) + seg = lambda a, b: [P[side + b][k] - P[side + a][k] for k in range(3)] # noqa: E731 + self.assertLess(self.angle(seg("UpperArm", "LowerArm"), X), 0.5) + self.assertLess(self.angle(seg("Hand", "MiddleProximal"), X), 0.5, (spec, side)) + for f in ("Index", "Middle", "Ring", "Little"): + self.assertLess(self.angle(seg(f + "Proximal", f + "Intermediate"), X), 0.5) + self.assertLess(self.angle(seg(f + "Intermediate", f + "Distal"), X), 0.5) + th = ("ThumbMetacarpal", "ThumbProximal", "ThumbDistal") if spec == "1.0" else \ + ("ThumbProximal", "ThumbIntermediate", "ThumbDistal") + self.assertLess(self.angle(seg(th[0], th[1]), T), 0.5, (spec, side)) + self.assertLess(self.angle(seg(th[1], th[2]), T), 0.5) + # 掌心朝下:掌面水平(食指根和小指根一样高),拇指在前面 + self.assertAlmostEqual(P[side + "IndexProximal"][1], P[side + "LittleProximal"][1], places=3) + self.assertGreater((P[side + "IndexProximal"][2] - P[side + "LittleProximal"][2]) * front, 0) + + def test_keep_pose(self): + g, hb = self.conv("3", "1.0", tpose=False) + P = {k: SkeletonTest.world(self, g, n) for k, n in hb.items()} + d = [P["leftIndexDistal"][k] - P["leftIndexIntermediate"][k] for k in range(3)] + self.assertGreater(self.angle(d, (1, 0, 0)), 20) # 不摆:手指还是弯的、手臂下垂 + + def test_two_segment_thumb(self): + names = lambda g, hb: {k: g["nodes"][n]["name"] for k, n in hb.items() if "leftThumb" in k} # noqa: E731 + # 親指1 在第二节的位置:1.0 是 Proximal / Distal;0.x 是 Intermediate / Distal,掌根那节补占位 + g, hb = self.conv("2far", "1.0") + self.assertEqual(names(g, hb), {"leftThumbProximal": "左親指1", "leftThumbDistal": "左親指2"}) + g, hb = self.conv("2far", "0.x") + self.assertEqual(names(g, hb), {"leftThumbProximal": "vrm_leftThumbProximal", + "leftThumbIntermediate": "左親指1", "leftThumbDistal": "左親指2"}) + self.assertIn(hb["leftThumbIntermediate"], g["nodes"][hb["leftThumbProximal"]]["children"]) + # 親指1 在掌根:两个版本都从掌根那节开始 + g, hb = self.conv("2near", "1.0") + self.assertEqual(names(g, hb), {"leftThumbMetacarpal": "左親指1", "leftThumbProximal": "左親指2"}) + g, hb = self.conv("2near", "0.x") + self.assertEqual(names(g, hb), {"leftThumbProximal": "左親指1", "leftThumbIntermediate": "左親指2"}) + + +class SpringV0Test(Base): + """VRM 0.x 的 SpringBone(secondaryAnimation):组根下面整棵子树都会摆动。 + + 在 SkirtTest 的模型(两条后裙链 + 左腿胶囊)上再改头发:髪2 和 髪3 之间插一根很短的物理骨 髪2b + (抽稀后刚性跟随 髪2)、髪3 下挂一个不带物理的发饰、髪2 上分叉出一条 髪B。三根骨都带顶点。""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + m = pmxio.read_pmx(cls.pmx) + SkirtTest.add_skirt(m) + B = m["bones"] + idx = {b["name"]: i for i, b in enumerate(B)} + + def bone(name, parent, pos): + idx[name] = len(B) + B.append({"name": name, "name_en": "", "pos": pos, "parent": idx[parent], "layer": 0, + "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, "tail": -1}) + bone("髪2b", "髪2", (0, 15.0, 1.25)) + B[idx["髪3"]]["parent"] = idx["髪2b"] + bone("髪飾り", "髪3", (0, 13.0, 1.9)) + bone("髪B", "髪2", (1.0, 14.6, 1.3)) + bone("髪B先", "髪B", (1.2, 12.8, 1.4)) + for name in ("髪2b", "髪飾り", "髪B"): + f = synth._box(m, B[idx[name]]["pos"], 0.2, idx[name]) + m["faces"] += f + m["materials"].append(dict(m["materials"][1], name="髪_" + name, faces=len(f))) + rbi = {r["name"]: i for i, r in enumerate(m["rigid_bodies"])} + rb0 = m["rigid_bodies"][rbi["髪2"]] + for name in ("髪2b", "髪B"): + m["rigid_bodies"].append(dict(rb0, name=name, name_en=name, bone=idx[name], pos=B[idx[name]]["pos"])) + rbi[name] = len(m["rigid_bodies"]) - 1 + j0 = m["joints"][0] + m["joints"] += [dict(j0, name="髪2-2b", rb_a=rbi["髪2"], rb_b=rbi["髪2b"]), + dict(j0, name="髪2-B", rb_a=rbi["髪2"], rb_b=rbi["髪B"])] + cls.pmx = os.path.join(cls.tmp, "src", "spring0.pmx") + pmxio.write_pmx(m, cls.pmx) + cls.log0 = [] + cls.v0 = os.path.join(cls.tmp, "s0.vrm") + pmx2vrm.convert(cls.pmx, cls.v0, spec="0.x", log=lambda msg, tag=None: cls.log0.append(msg)) + cls.v1 = os.path.join(cls.tmp, "s1.vrm") + pmx2vrm.convert(cls.pmx, cls.v1) + + def node(self, g, name): + return next(i for i, n in enumerate(g["nodes"]) if n.get("name") == name) + + def test_groups(self): + s = self.assertValid(self.v0) # check_vrm:同一节点不在两个组的子树里、0.0 schema + g, _ = vrmio.read_glb(self.v0) + sa = g["extensions"]["VRM"]["secondaryAnimation"] + roots = {g["nodes"][r]["name"] for grp in sa["boneGroups"] for r in grp["bones"]} + # 头发一组(分叉出来的 髪B 并进 髪2 的组,不另列根),两条裙链各一组 + self.assertEqual(roots, {"髪2", "後裙A0", "後裙B0"}) + self.assertEqual(s["springs"], 3) + for grp in sa["boneGroups"]: + self.assertIn("stiffiness", grp) + self.assertNotIn("stiffness", grp) + self.assertEqual(grp["center"], g["scenes"][0]["nodes"][0]) + self.assertEqual(grp["gravityDir"], {"x": 0.0, "y": -1.0, "z": 0.0}) + # 刚性跟随的中间骨、发饰被并掉;尾节点 髪先 留着当叶子;髪3 直接挂在 髪2 下面、排第一个 + names = {n["name"] for n in g["nodes"]} + self.assertFalse({"髪2b", "髪飾り"} & names) + self.assertIn("髪先", names) + h2 = self.node(g, "髪2") + self.assertEqual(g["nodes"][h2]["children"][0], self.node(g, "髪3")) + self.assertIn(self.node(g, "髪B"), g["nodes"][h2]["children"]) + self.assertTrue(any("1 条分叉链并入上层链的组" in x for x in self.log0), self.log0) + + def test_weights_folded(self): + g1, b1 = vrmio.read_glb(self.v1) + g0, b0 = vrmio.read_glb(self.v0) + w1, w0 = PruneTest.bone_weights(self, g1, b1), PruneTest.bone_weights(self, g0, b0) + self.assertAlmostEqual(w0["髪2"], w1["髪2"] + w1["髪2b"], places=3) + self.assertAlmostEqual(w0["髪3"], w1["髪3"] + w1["髪飾り"] + w1["髪先"], places=3) + self.assertNotIn("髪先", w0) + self.assertAlmostEqual(w0["髪B"], w1["髪B"], places=3) + self.assertAlmostEqual(sum(w0.values()), sum(w1.values()), places=2) + self.assertIn("髪2b", {n["name"] for n in g1["nodes"]}) # 1.0 不受影响 + + def test_colliders(self): + g, _ = vrmio.read_glb(self.v0) + sa = g["extensions"]["VRM"]["secondaryAnimation"] + leg = self.node(g, "左足") + legs = [c for c in sa["colliderGroups"] if c["node"] == leg] + self.assertTrue(legs) + for c in legs: + self.assertGreaterEqual(len(c["colliders"]), 3) # 胶囊 → 一串球 + # 裙链碰得到左腿 + for grp in sa["boneGroups"]: + if g["nodes"][grp["bones"][0]]["name"].startswith("後裙"): + self.assertTrue(any(sa["colliderGroups"][i]["node"] == leg for i in grp["colliderGroups"])) + + def test_to_secondary_shapes(self): + """胶囊沿轴线每隔一个半径一个球、offset 的 Z 取反;静止时就在碰撞体里、缩不下去的不碰。""" + from vrmconv import springbone_v0 + nodes = [{"name": "root", "translation": [0, 0, 0], "children": [1, 3]}, + {"name": "a", "translation": [0, 1, 0], "children": [2]}, + {"name": "b", "translation": [0, -0.2, 0]}, + {"name": "leg", "translation": [0.1, 0.5, 0]}] + j = {"stiffness": 1.0, "gravityPower": 0.0, "dragForce": 0.4, "hitRadius": 0.05} + ext = {"springs": [{"name": "s", "joints": [dict(j, node=1), dict(j, node=2)], "colliderGroups": [0]}], + "colliders": [{"node": 3, "shape": {"capsule": {"offset": [0, 0, 0.1], "tail": [0, 0.2, 0.1], + "radius": 0.05}}}, + {"node": 0, "shape": {"sphere": {"offset": [0, 0.8, 0], "radius": 0.08}}}], + "colliderGroups": [{"colliders": [0, 1]}]} + sa = springbone_v0.to_secondary(ext, nodes, center=0) + cap = sa["colliderGroups"][0] + self.assertEqual(len(cap["colliders"]), 5) # 0.2 / 0.05 + 1 + self.assertEqual([c["offset"]["z"] for c in cap["colliders"]], [-0.1] * 5) + self.assertEqual([c["offset"]["y"] for c in cap["colliders"]], [0.0, 0.05, 0.1, 0.15, 0.2]) + # 球心 (0, 0.8, 0)、半径 0.08;尾端 b 也在 (0, 0.8, 0):静止就在里面,缩不下去 → 这一组不碰它 + self.assertEqual(len(sa["colliderGroups"]), 1) + grp = sa["boneGroups"][0] + self.assertEqual((grp["bones"], grp["colliderGroups"], grp["center"]), ([1], [0], 0)) + self.assertEqual(grp["stiffiness"], 1.0) + + def test_spring_off(self): + out = self.convert("s0off", spec="0.x", spring=False) + g, _ = vrmio.read_glb(out) + self.assertEqual(g["extensions"]["VRM"]["secondaryAnimation"]["boneGroups"], []) + self.assertIn("髪2b", {n["name"] for n in g["nodes"]}) # 没有物理就不并权重 + + +class SnapshotTest(Base): + """tools/qa/snapshots.py:无界面浏览器里用预览组件拍表情对照表(没有 Edge / Chrome 时跳过)。""" + + def test_sheet(self): + import snapshots + if not snapshots.find_browser(): + self.skipTest("没有 Edge / Chrome") + out = os.path.join(self.tmp, "snap.png") + a, b = self.convert("snap_a"), self.convert("snap_b", combo_expr=False) + snapshots.shoot([(a, a), (b, b)], out, size=64, timeout=180) + with open(out, "rb") as f: + head = f.read(24) + self.assertEqual(head[:8], b"\x89PNG\r\n\x1a\n") + w, h = int.from_bytes(head[16:20], "big"), int.from_bytes(head[20:24], "big") + n = len(snapshots.SHOTS) + self.assertEqual(w, 150 + n * (64 + 6) + 6) # 一段放下标准的一组,两个模型两行 + self.assertEqual(h, 6 + 2 * (64 + 20 + 6) + 6) + # 浏览器连同子进程(GPU、渲染进程)都结束了,临时配置目录也删了 + self.assertEqual(snapshots.browser_procs(), []) + self.assertFalse([d for d in os.listdir(tempfile.gettempdir()) if d.startswith(snapshots.PROFILE_PREFIX)]) + + def test_cleanup_stale(self): + """遗留的截图浏览器(配置目录里记的进程已经不在了)连同配置目录一起清掉;正在跑的不动。""" + import snapshots + tmp = tempfile.mkdtemp(prefix="m2v_snaptmp_") + sleeper = [sys.executable, "-c", "import time; time.sleep(120)"] + owner = subprocess.Popen(sleeper) # 「正在跑的截图」的主进程 + gone = subprocess.Popen([sys.executable, "-c", "pass"]) + gone.wait() # 已经退出的主进程 + procs = [] + try: + for name, pid in (("stale", gone.pid), ("live", owner.pid)): + d = os.path.join(tmp, snapshots.PROFILE_PREFIX + name) + os.makedirs(d) + with open(os.path.join(d, snapshots.OWNER_FILE), "w") as f: + f.write(str(pid)) + # 冒充浏览器:命令行里带配置目录 + procs.append(subprocess.Popen(sleeper + ["--user-data-dir=" + d])) + snapshots.cleanup_stale(tmp) + self.assertIsNotNone(procs[0].wait(30)) # 遗留的结束了 + self.assertIsNone(procs[1].poll()) # 正在跑的还在 + self.assertEqual(os.listdir(tmp), [snapshots.PROFILE_PREFIX + "live"]) + finally: + for p in procs + [owner]: + p.kill() + p.wait() + shutil.rmtree(tmp, ignore_errors=True) + + +class PipelineTest(Base): + def _pack_files(self): + src = os.path.dirname(self.pmx) + return [(os.path.join(d, fn), os.path.join("包", os.path.relpath(os.path.join(d, fn), src))) + for d, _, fs in os.walk(src) for fn in fs] + + def _variant_pmx(self, name, outfit=False): + """synth 模型换成英文骨名(synth.EN,导出 FBX 后还认得出人形骨架);outfit=True 时改成「只有衣服」: + 头部(头骨和头发)的顶点都改挂到上半身。""" + m = pmxio.read_pmx(self.pmx) + names = [b["name"] for b in m["bones"]] + if outfit: + head = {names.index("頭")} + for i, b in enumerate(m["bones"]): + if b["parent"] in head or names[i].startswith("髪"): + head.add(i) + spine = names.index("上半身") + for v in m["vertices"]: + if set(v["wbones"]) & head: + v.update(wtype=0, wbones=[spine], wweights=[]) + for b in m["bones"]: + b["name"] = b["name_en"] = synth.EN.get(b["name"], b["name"]) + out = os.path.join(self.tmp, "variant_src", name + ".pmx") + os.makedirs(os.path.dirname(out), exist_ok=True) + pmxio.write_pmx(m, out) + return out + + def _outfit_pmx(self): + return self._variant_pmx("Outfit", outfit=True) + + def _prop_pmx(self, folder): + """道具:一根骨、一个方块(剑、椅子这类)。""" + m = pmxio.new_model("剑") + m["bones"].append({"name": "センター", "name_en": "center", "pos": (0, 0, 0), "parent": -1, + "layer": 0, "flag": 0x001F, "tail": -1}) + m["faces"] = synth._box(m, (0, 1, 0), 0.5, 0) + m["materials"] = [synth._material("剣", -1, len(m["faces"]))] + os.makedirs(folder, exist_ok=True) + out = os.path.join(folder, "剑.pmx") + pmxio.write_pmx(m, out) + return out + + def test_not_an_avatar(self): + self.assertIsNone(pipeline.not_an_avatar(self.pmx)) + self.assertIn("头部", pipeline.not_an_avatar(self._outfit_pmx())) + self.assertIn("道具", pipeline.not_an_avatar(self._prop_pmx(os.path.join(self.tmp, "prop_a")))) + + def test_avatar_only(self): + """「只转换人物」(默认开):道具跳过(只有它的文件返回 []),压缩包里只转人物;关掉就都转。""" + prop = self._prop_pmx(os.path.join(self.tmp, "prop_b")) + logs = [] + out = os.path.join(self.tmp, "prop_out") + self.assertEqual(pipeline.convert_file(prop, {}, out_dir=out, log=lambda m, t=None: logs.append((m, t))), []) + self.assertTrue(any(m.startswith("跳过 剑:未识别到人形骨架") and t == "warn" for m, t in logs), logs) + self.assertEqual(len(pipeline.convert_file(prop, {"vrm": {"avatar_only": False}}, out_dir=out)), 1) + z = os.path.join(self.tmp, "with_prop.zip") + with zipfile.ZipFile(z, "w") as zf: + for p, arc in self._pack_files(): + zf.write(p, arc) + zf.write(prop, "包/剑.pmx") + stem = os.path.splitext(os.path.basename(self.pmx))[0] + outs = pipeline.convert_file(z, {}, out_dir=os.path.join(self.tmp, "with_prop_a")) + self.assertEqual([os.path.basename(p) for p in outs], [stem + ".vrm"]) + outs = pipeline.convert_file(z, {"vrm": {"avatar_only": False}}, out_dir=os.path.join(self.tmp, "with_prop_b")) + self.assertEqual(sorted(os.path.basename(p) for p in outs), sorted([stem + ".vrm", "剑.vrm"])) + + @unittest.skipUnless(textures.available(), "需要 Pillow") + def test_fbx_texture_stats_reused(self): + """FBX → VRM:判断透明时顺便算好的贴图统计交给转 VRM 那一步,贴图不再解第二遍;结果和再解一遍完全相同。""" + import fbx2pmx + import fbxout + from unittest import mock + src = os.path.join(self.tmp, "stats_src") + shutil.copytree(os.path.join(os.path.dirname(self.pmx), "tex"), os.path.join(src, "tex")) + fbx = os.path.join(src, "体.fbx") + fbxout.export_pmx(self._variant_pmx("Body"), fbx, log=lambda *a, **k: None) + with mock.patch.object(vrmio, "png_alpha_stats", wraps=vrmio.png_alpha_stats) as stats: + a = pipeline.convert_file(fbx, {}, out_dir=os.path.join(self.tmp, "stats_a"))[0] + self.assertEqual(len(vrmio.read_glb(a)[0]["images"]), 2) + self.assertEqual(stats.call_count, 0) + load = fbx2pmx._load_alpha + with mock.patch.object(fbx2pmx, "_load_alpha", lambda p: (load(p)[0], NotImplemented)): + b = pipeline.convert_file(fbx, {}, out_dir=os.path.join(self.tmp, "stats_b"))[0] + with open(a, "rb") as fa, open(b, "rb") as fb: + self.assertEqual(fa.read(), fb.read()) + + def test_fbx_output_is_only_vrm(self): + """FBX → VRM:中间的 PMX 和贴图放临时目录,输出目录只有 VRM;只转 PMX 时才留 PMX + 贴图。""" + import fbxout + fbx = os.path.join(self.tmp, "fbx_src", "体.fbx") + os.makedirs(os.path.dirname(fbx), exist_ok=True) + fbxout.export_pmx(self._variant_pmx("Body"), fbx, log=lambda *a, **k: None) + out = os.path.join(self.tmp, "fbx_out") + outs = pipeline.convert_file(fbx, {}, out_dir=out) + self.assertEqual([os.path.basename(p) for p in outs], ["体.vrm"]) + self.assertEqual(os.listdir(out), ["体.vrm"]) + out_pmx = os.path.join(self.tmp, "fbx_out_pmx") + outs = pipeline.convert_file(fbx, {"target": "pmx"}, out_dir=out_pmx) + self.assertEqual([os.path.basename(p) for p in outs], ["体.pmx"]) + self.assertIn("体.pmx", os.listdir(out_pmx)) + + def test_unitypackage_skips_outfit(self): + """unitypackage:解到临时目录、日志一行汇总;包里只有衣服的 FBX 跳过,输出目录只有角色的 VRM。""" + import fbxout + src = os.path.join(self.tmp, "up_src") + os.makedirs(src, exist_ok=True) + avatar, outfit = os.path.join(src, "Avatar.fbx"), os.path.join(src, "Outfit.fbx") + fbxout.export_pmx(self._variant_pmx("Avatar"), avatar, log=lambda *a, **k: None) + fbxout.export_pmx(self._outfit_pmx(), outfit, log=lambda *a, **k: None) + pkg = os.path.join(self.tmp, "Avatar.unitypackage") + with tarfile.open(pkg, "w:gz") as tf: + for k, (fn, rel) in enumerate(((avatar, "Assets/Model/Avatar.fbx"), (outfit, "Assets/Model/Outfit.fbx"))): + guid = "%032x" % (k + 1) + tf.add(fn, guid + "/asset") + info = tarfile.TarInfo(guid + "/pathname") + data = rel.encode("utf-8") + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + logs = [] + out = os.path.join(self.tmp, "up_out") + outs = pipeline.convert_file(pkg, {}, out_dir=out, log=lambda m, t=None: logs.append((m, t))) + self.assertEqual([os.path.basename(p) for p in outs], ["Avatar.vrm"]) + self.assertEqual(os.listdir(out), ["Avatar.vrm"]) + self.assertTrue(any("跳过 Outfit" in m and t == "warn" for m, t in logs), logs) + self.assertTrue(any(m.startswith("解包 Avatar.unitypackage:") for m, _ in logs)) + self.assertFalse(any(" KB " in m for m, _ in logs)) # 不再逐个列文件 + + def test_unitypackage_solid_color_materials(self): + """unitypackage 里 Toon 材质没有贴图、颜色只写在 .mat 的 m_Colors(纯黑 / 纯白)时, + 颜色必须烘焙成贴图:以前这两个材质都退化成默认白,黑的变白、白的「碰巧看着正常」。""" + import fbxout + m = pmxio.read_pmx(self.pmx) + for b in m["bones"]: + b["name"] = b["name_en"] = synth.EN.get(b["name"], b["name"]) + for i, nm in enumerate(("mat_Black", "mat_White")): + m["materials"][i].update(name=nm, name_en=nm, tex=-1, toon_flag=0, toon=-1) + src = os.path.join(self.tmp, "solid_src") + os.makedirs(src, exist_ok=True) + pmx = os.path.join(src, "solid.pmx") + pmxio.write_pmx(m, pmx) + fbx = os.path.join(src, "solid.fbx") + fbxout.export_pmx(pmx, fbx, log=lambda *a, **k: None) + + def mat_text(nm, v): + return ("%%YAML 1.1\n%%TAG !u! tag:unity3d.com,2011:\n--- !u!21 &2100000\nMaterial:\n" + " m_Name: %s\n m_SavedProperties:\n m_Colors:\n" + " - _ShadeColor: {r: 0.5, g: 0.5, b: 0.5, a: 1}\n" + " - _Color: {r: %s, g: %s, b: %s, a: 1}\n" + " m_TexEnvs:\n - _MainTex:\n m_Texture: {fileID: 0}\n" + " m_Floats: []\n") % (nm, v, v, v) + + files = [(fbx, "Assets/Model/solid.fbx")] + for nm, v in (("mat_Black", "0"), ("mat_White", "1")): + p = os.path.join(src, nm + ".mat") + with open(p, "w", encoding="utf-8") as f: + f.write(mat_text(nm, v)) + files.append((p, "Assets/Model/%s.mat" % nm)) + pkg = os.path.join(self.tmp, "solid.unitypackage") + with tarfile.open(pkg, "w:gz") as tf: + for k, (fn, rel) in enumerate(files, 1): + guid = "%032x" % k + tf.add(fn, guid + "/asset") + info = tarfile.TarInfo(guid + "/pathname") + data = rel.encode("utf-8") + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + + outs = pipeline.convert_file(pkg, {}, out_dir=os.path.join(self.tmp, "solid_out")) + self.assertEqual([os.path.basename(p) for p in outs], ["solid.vrm"]) + doc, blob = vrmio.read_glb(outs[0]) + mats = {g["name"].split("::")[-1]: g for g in doc["materials"]} + for nm, want in (("mat_Black", (0, 0, 0)), ("mat_White", (255, 255, 255))): + pbr = mats[nm]["pbrMetallicRoughness"] + self.assertEqual(pbr["baseColorFactor"], [1.0, 1.0, 1.0, 1.0], nm) + ti = pbr["baseColorTexture"]["index"] + img = doc["images"][doc["textures"][ti]["source"]] + bv = doc["bufferViews"][img["bufferView"]] + data = blob[bv["byteOffset"]:bv["byteOffset"] + bv["byteLength"]] + self.assertEqual(vrmio.decode_rgba(data)[2][0][0][:3], want, nm) + + def test_animal_ears_get_springbone(self): + """没有物理刚体的模型:头下的多节兽耳链要自动补物理,且不能被抽稀成「根骨 + 末端」 + 一根刚性板(每节只有 2~3 cm,按头发的 12 cm 抽稀会全部并掉)。""" + m = pmxio.read_pmx(self.pmx) + m["rigid_bodies"] = [] + m["joints"] = [] + head = next(i for i, b in enumerate(m["bones"]) if b["name"] == "頭") + for side, x in (("L", 1), ("R", -1)): + parent = head + chain = list(range(len(m["bones"]), len(m["bones"]) + 4)) + for k, idx in enumerate(chain): + nm = "Ear_%d_%s" % (k, side) + m["bones"].append({"name": nm, "name_en": nm, + "pos": (x * (1.0 + 0.2 * k), 18.0 + 0.35 * k, 0.0), + "parent": parent, "layer": 0, + "flag": 0x0001 | 0x0002 | 0x0008 | 0x0010, + "tail": chain[k + 1] if k + 1 < len(chain) else -1}) + parent = idx + pmx = os.path.join(self.tmp, "ears.pmx") + pmxio.write_pmx(m, pmx) + out = pipeline.convert_file(pmx, {}, out_dir=os.path.join(self.tmp, "ears_out"))[0] + doc, _ = vrmio.read_glb(out) + ears = [s for s in doc["extensions"]["VRMC_springBone"]["springs"] + if "Ear_0_" in (doc["nodes"][s["joints"][0]["node"]].get("name") or "")] + self.assertEqual(len(ears), 2) + for s in ears: # 4 节骨 + 末端节点 + self.assertGreaterEqual(len(s["joints"]), 4) + + def test_unitypackage_outline(self): + """Unity Toon 材质开了描边(_Outline_Width > 0)时,即使「描边(按 PMX 轮廓线)」 + 没勾也要转成 MToon 描边;宽度 0 的材质保持不描边。""" + import fbxout + m = pmxio.read_pmx(self.pmx) + for b in m["bones"]: + b["name"] = b["name_en"] = synth.EN.get(b["name"], b["name"]) + for i, nm in enumerate(("mat_Ink", "mat_Plain")): + m["materials"][i].update(name=nm, name_en=nm, tex=-1, toon_flag=0, toon=-1) + src = os.path.join(self.tmp, "outline_src") + os.makedirs(src, exist_ok=True) + pmx = os.path.join(src, "outline.pmx") + pmxio.write_pmx(m, pmx) + fbx = os.path.join(src, "outline.fbx") + fbxout.export_pmx(pmx, fbx, log=lambda *a, **k: None) + + def mat_text(nm, width): + return ("%%YAML 1.1\n%%TAG !u! tag:unity3d.com,2011:\n--- !u!21 &2100000\nMaterial:\n" + " m_Name: %s\n m_ShaderKeywords: _OUTLINE_NML\n m_SavedProperties:\n" + " m_TexEnvs:\n - _MainTex:\n m_Texture: {fileID: 0}\n" + " m_Floats:\n - _Outline_Width: %s\n" + " m_Colors:\n - _Color: {r: 1, g: 1, b: 1, a: 1}\n" + " - _Outline_Color: {r: 0, g: 0, b: 0, a: 1}\n") % (nm, width) + + files = [(fbx, "Assets/Model/outline.fbx")] + for nm, w in (("mat_Ink", 20), ("mat_Plain", 0)): + p = os.path.join(src, nm + ".mat") + with open(p, "w", encoding="utf-8") as f: + f.write(mat_text(nm, w)) + files.append((p, "Assets/Model/%s.mat" % nm)) + pkg = os.path.join(self.tmp, "outline.unitypackage") + with tarfile.open(pkg, "w:gz") as tf: + for k, (fn, rel) in enumerate(files, 1): + guid = "%032x" % k + tf.add(fn, guid + "/asset") + info = tarfile.TarInfo(guid + "/pathname") + data = rel.encode("utf-8") + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + + outs = pipeline.convert_file(pkg, {}, out_dir=os.path.join(self.tmp, "outline_out")) + doc, _ = vrmio.read_glb(outs[0]) + mats = {g["name"].split("::")[-1]: g["extensions"]["VRMC_materials_mtoon"] + for g in doc["materials"]} + self.assertEqual(mats["mat_Ink"]["outlineWidthMode"], "worldCoordinates") + self.assertGreater(mats["mat_Ink"]["outlineWidthFactor"], 0.0) + self.assertEqual(mats["mat_Ink"]["outlineColorFactor"], [0.0, 0.0, 0.0]) + self.assertEqual(mats["mat_Plain"]["outlineWidthMode"], "none") + + def test_defaults_do_not_force_tpose_and_no_mip_is_opt_in(self): + """T-pose 默认不强制;贴图 mipmap 默认保留,只有显式勾 tex_no_mip 才关掉。""" + self.assertFalse(pipeline.DEFAULTS["vrm"]["tpose"]) + self.assertFalse(pipeline.DEFAULTS["vrm"]["tex_no_mip"]) + outs = pipeline.convert_file(self.pmx, {}, out_dir=os.path.join(self.tmp, "sampler_default")) + doc, _ = vrmio.read_glb(outs[0]) + self.assertEqual(doc["samplers"][0]["minFilter"], 9987) # LINEAR_MIPMAP_LINEAR + outs = pipeline.convert_file(self.pmx, {"vrm": {"tex_no_mip": True}}, + out_dir=os.path.join(self.tmp, "sampler_nomip")) + doc, _ = vrmio.read_glb(outs[0]) + self.assertEqual(doc["samplers"][0]["minFilter"], 9729) # LINEAR + self.assertEqual(doc["samplers"][0]["magFilter"], 9729) + + def test_archive_models_in_parallel(self): + """压缩包里有几个模型:同时转(子进程);不同文件夹下的同名模型输出名加 _2,不会互相覆盖。""" + from unittest import mock + z = os.path.join(self.tmp, "two.zip") + with zipfile.ZipFile(z, "w") as zf: + for p, arc in self._pack_files(): + zf.write(p, arc.replace("包", "红", 1)) + zf.write(p, arc.replace("包", "蓝", 1)) + logs = [] + with mock.patch.object(pipeline, "SMALL_MODEL", 0): # 合成模型很小,照样算「值得并行」 + outs = pipeline.convert_file(z, {"jobs": 2}, out_dir=os.path.join(self.tmp, "two_out"), + log=lambda m, t=None: logs.append(m)) + stem = os.path.splitext(os.path.basename(self.pmx))[0] + self.assertEqual(sorted(os.path.basename(p) for p in outs), sorted([stem + ".vrm", stem + "_2.vrm"])) + for p in outs: + self.assertValid(p) + self.assertIn("压缩包中共有 2 个模型,并行转换 2 个", logs) + + def test_archive_kinds(self): + for name, kind in (("a.zip", "zip"), ("a.7z", "7z"), ("a.7z.001", "7z"), ("a.7z.002", None), + ("a.rar", "rar"), ("a.part1.rar", "rar"), ("a.part02.rar", None), + ("a.tar.gz", "tar"), ("a.TGZ", "tar"), ("a.tar.xz", "tar"), ("a.gz", None)): + self.assertEqual(pipeline.classify(name), kind, name) + + def test_tar_gz(self): + t = os.path.join(self.tmp, "pack.tar.gz") + with tarfile.open(t, "w:gz") as tf: + for p, arc in self._pack_files(): + tf.add(p, arc) + info = tarfile.TarInfo("../evil.txt") # 跑到外面的路径:只能落在解压目录里 + tf.addfile(info, None) + outs = pipeline.convert_file(t, {}, out_dir=os.path.join(self.tmp, "tar_out")) + self.assertEqual(len(outs), 1) + self.assertValid(outs[0]) + self.assertFalse(os.path.exists(os.path.join(self.tmp, "evil.txt"))) + + def test_nested_archive(self): + """zip 里只有一个 tar.gz:再解一层。""" + inner = os.path.join(self.tmp, "inner.tar.gz") + with tarfile.open(inner, "w:gz") as tf: + for p, arc in self._pack_files(): + tf.add(p, arc) + z = os.path.join(self.tmp, "outer.zip") + with zipfile.ZipFile(z, "w") as zf: + zf.write(inner, "model.tar.gz") + outs = pipeline.convert_file(z, {}, out_dir=os.path.join(self.tmp, "nested_out")) + self.assertEqual([os.path.splitext(os.path.basename(o))[0] for o in outs], ["合成モデル"]) + + def test_7z_via_bsdtar(self): + tar = archive.tools()["bsdtar"] + if not tar: + self.skipTest("没有 bsdtar") + src = os.path.dirname(self.pmx) + s = os.path.join(self.tmp, "pack.7z") + r = subprocess.run([tar, "-c", "-f", s, "--format", "7zip", "-C", os.path.dirname(src), + os.path.basename(src)], capture_output=True) + if r.returncode: + self.skipTest("bsdtar 写不了 7z:%s" % r.stderr[-200:]) + outs = pipeline.convert_file(s, {}, out_dir=os.path.join(self.tmp, "7z_out")) + self.assertEqual(len(outs), 1) + self.assertValid(outs[0]) + + def test_no_tool_message(self): + saved = archive._TOOLS + archive._TOOLS = {"7z": None, "unrar": None, "bandizip": None, "bsdtar": None, "py7zr": False} + try: + p = os.path.join(self.tmp, "x.rar") + with open(p, "wb") as f: + f.write(b"Rar!" + bytes([0x1A, 0x07, 0x00])) + with self.assertRaises(RuntimeError) as cm: + pipeline.convert_file(p, {}, out_dir=os.path.join(self.tmp, "rar_out")) + self.assertIn("7-Zip", str(cm.exception)) + finally: + archive._TOOLS = saved + + def test_zip_with_edits(self): + z = os.path.join(self.tmp, "pack.zip") + src = os.path.dirname(self.pmx) + with zipfile.ZipFile(z, "w") as zf: + for d, _, fs in os.walk(src): + for fn in fs: + p = os.path.join(d, fn) + zf.write(p, os.path.join("包", os.path.relpath(p, src))) + out_dir = os.path.join(self.tmp, "zip_out") + opts = copy.deepcopy(pipeline.DEFAULTS) + opts["meta"]["author"] = "someone" + outs = pipeline.convert_file(z, opts, out_dir=out_dir, edits={"title": "zip 模型"}) + self.assertEqual(len(outs), 1) + self.assertValid(outs[0]) + m = vrmio.read_glb(outs[0])[0]["extensions"]["VRMC_vrm"]["meta"] + self.assertEqual((m["name"], m["authors"]), ("zip 模型", ["someone"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_fbx_helpers.py b/tests/test_fbx_helpers.py new file mode 100644 index 0000000..25bf486 --- /dev/null +++ b/tests/test_fbx_helpers.py @@ -0,0 +1,400 @@ +# -*- coding: utf-8 -*- +"""FBX / Unity 资源相关的小函数:英文骨名、英文表情名、Unity 材质找贴图、欧拉角顺序、替换网格。 + +不需要真实模型(Unity 酱、Query 酱实测中发现的问题都在这里留了用例)。 +""" +import io +import math +import os +import shutil +import sys +import tarfile +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +for _p in (os.path.join(ROOT, "convert"), os.path.join(ROOT, "formats")): + if _p not in sys.path: + sys.path.insert(0, _p) +import fbx2pmx # noqa: E402 +import unityasset # noqa: E402 +import unitypackage_unpack # noqa: E402 +from vrmconv.expressions import _preset_en # noqa: E402 +from vrmconv.humanoid import _en_bone, _map_humanoid # noqa: E402 + + +class BoneNameTest(unittest.TestCase): + def test_conventions(self): + cases = { + "Character1_Hips": ("slot", "hips"), "Character1_Spine1": ("slot", "chest"), + "Character1_LeftUpLeg": ("slot", "leftUpperLeg"), "Character1_LeftLeg": ("slot", "leftLowerLeg"), + "Chr_RightForeArm": ("slot", "rightLowerArm"), "mixamorig:LeftHand": ("slot", "leftHand"), + "J_Bip_C_UpperChest": ("slot", "upperChest"), "J_Bip_L_UpperArm": ("slot", "leftUpperArm"), + "thigh.L": ("slot", "leftUpperLeg"), "Bip001 R Calf": ("slot", "rightLowerLeg"), + "Bip001 Pelvis": ("slot", "hips"), "Eye_R": ("slot", "rightEye"), + "Character1_LeftHandThumb1": ("finger", ("left", "Thumb", 0)), + "Character1_RightHandIndex3": ("finger", ("right", "Index", 3)), + } + for name, want in cases.items(): + self.assertEqual(_en_bone(name), want, name) + + def test_not_humanoid(self): + for name in ("J_L_HairTail_00", "skirt_L_01", "Pai_L", "J_Mune_root_00", "Root", "H02_L", + "Character1_RightHandPinky4", "J_L_Sode_A00"): + self.assertIsNone(_en_bone(name), name) + + def test_leg_without_upleg(self): + # 只有 Leg(没有 UpLeg / Thigh)时 Leg 是大腿 + names = ["Hips", "Spine", "Leg_L", "Knee_L", "Foot_L"] + bones = [{"name": n, "name_en": n} for n in names] + human = _map_humanoid(bones, True, {}) + self.assertEqual(human.get("leftUpperLeg"), 2) + self.assertEqual(human.get("leftLowerLeg"), 3) + + def test_unity_finger_names(self): + """Unity / VRChat 的「Index Proximal.L」:其余手指 1~3;拇指 Proximal / Intermediate / Distal = 0~2, + 有 ThumbMetacarpal(VRM 1.0 风格)时 Metacarpal / Proximal / Distal = 0~2。""" + self.assertEqual(_en_bone("Index Proximal.L"), ("finger", ("left", "Index", 1))) + self.assertEqual(_en_bone("Little Distal.R"), ("finger", ("right", "Little", 3))) + self.assertEqual(_en_bone("Thumb Proximal.L"), ("finger", ("left", "Thumb", 0))) + self.assertEqual(_en_bone("Thumb Intermediate.L"), ("finger", ("left", "Thumb", 1))) + self.assertEqual(_en_bone("J_Bip_L_ThumbProximal", True), ("finger", ("left", "Thumb", 1))) + self.assertEqual(_en_bone("J_Bip_L_ThumbMetacarpal", True), ("finger", ("left", "Thumb", 0))) + names = ["Hips", "Spine", "Chest", "Neck", "Head", "Upper_arm.L", "Lower_arm.L", "Hand.L"] + ["%s %s.L" % (f, s) for f in ("Thumb", "Index", "Middle", "Ring", "Little") + for s in ("Proximal", "Intermediate", "Distal")] + human = _map_humanoid([{"name": n, "name_en": n} for n in names], True, {}) + self.assertEqual(names[human["leftThumbMetacarpal"]], "Thumb Proximal.L") + self.assertEqual(names[human["leftThumbDistal"]], "Thumb Distal.L") + self.assertEqual(names[human["leftIndexProximal"]], "Index Proximal.L") + self.assertEqual(names[human["leftLittleDistal"]], "Little Distal.L") + + def test_mmd_names_win(self): + bones = [{"name": "下半身", "name_en": ""}, {"name": "Hips", "name_en": ""}] + self.assertEqual(_map_humanoid(bones, True, {})["hips"], 0) + + def test_mmd_names_win_over_earlier_name_en(self): + """模型旁边另放的控制骨(左肩調整,英文名和本体一样是 L_Shoulder)排在前面,也不能抢走 左肩。""" + bones = [{"name": "左肩調整", "name_en": "L_Shoulder"}, {"name": "上半身3", "name_en": ""}, + {"name": "左肩", "name_en": "L_Shoulder"}, {"name": "右肩調整", "name_en": "R_Shoulder"}] + human = _map_humanoid(bones, True, {}) + self.assertEqual(human["leftShoulder"], 2) + self.assertEqual(human["rightShoulder"], 3) # 没有日文名的,英文名照常补位 + + +class ExpressionNameTest(unittest.TestCase): + def test_presets(self): + cases = {"MTH_A": "aa", "Fcl_MTH_E": "ee", "vrc.v_oh": "oh", "EYE_DEF_C": "blink", + "Fcl_EYE_Close_L": "blinkLeft", "Blink_R": "blinkRight", "Fcl_ALL_Joy": "happy", + "Head_02_MouthOpen": "aa", "happy": "happy"} + for name, want in cases.items(): + self.assertEqual(_preset_en(name, True), want, name) + self.assertEqual(_preset_en("Fcl_ALL_Joy", False), "joy") + self.assertEqual(_preset_en("vrc.blink_left", False), "blink_l") + + def test_lookup(self): + from vrmconv.expressions import Lookup + lk = Lookup(["怒りA", "キリッ", "eyeBlink_L", "EyeBlink_R", "上L", "にこり2"]) + self.assertEqual(lk.get("怒り"), "怒りA") # 变体后缀 + self.assertEqual(lk.get("キリッ"), "キリッ") # 半角片假名 + self.assertEqual(lk.get("にこり2"), "にこり2") # 全角数字 + self.assertEqual(lk.all(("eyeBlinkLeft", "eyeBlinkRight")), ("eyeBlink_L", "EyeBlink_R")) + self.assertIsNone(lk.get("上")) # 单边的不算 + self.assertIsNone(lk.all(("eyeBlinkLeft", "eyeWideRight"))) + + def test_en_parts_and_arkit(self): + from vrmconv.expressions import Lookup, _en_part, combo_recipes + lk = Lookup(["Fcl_BRW_Angry", "Fcl_EYE_Joy", "Mouth_Laugh1", "Mouth_Smile1", "Eye_Smile_L", "Fcl_ALL_Sorrow"]) + self.assertEqual(_en_part(lk, "angry", 1), "Fcl_BRW_Angry") + self.assertEqual(_en_part(lk, "happy", 2), "Fcl_EYE_Joy") # 单边的 Eye_Smile_L 不算 + self.assertEqual(_en_part(lk, "happy", 3), "Mouth_Smile1") # smile 先于 laugh + self.assertIsNone(_en_part(lk, "sad", 1)) # ALL 是整张脸,不当部位 + # 只有 ARKit:各部位都从 ARKit 来;每个表情动不同的顶点,不会被当成重叠 + names = ["browDownLeft", "browDownRight", "eyeSquintLeft", "eyeSquintRight", "mouthFrownLeft", + "mouthFrownRight", "browInnerUp"] + deltas = {n: {k: (0.0, 0.1, 0.0)} for k, n in enumerate(names)} + r = combo_recipes(deltas, {}) + self.assertEqual(r["angry"], [("browDownLeft", 0.5, 1), ("browDownRight", 0.5, 1), + ("eyeSquintLeft", 0.3, 2), ("eyeSquintRight", 0.3, 2), + ("mouthFrownLeft", 0.4, 3), ("mouthFrownRight", 0.4, 3)]) + self.assertEqual([n for n, _, _ in r["sad"]], ["browInnerUp", "mouthFrownLeft", "mouthFrownRight"]) + + def test_not_presets(self): + for name in ("MTH_SMILE1", "Fcl_BRW_Angry", "Key 1", "eye_a", "Basis", "EYE_SMILE1"): + self.assertIsNone(_preset_en(name, True), name) + + +MAT_U5 = """%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + m_Name: mat_Body + m_SavedProperties: + m_TexEnvs: + - _BumpMap: + m_Texture: {fileID: 2800000, guid: bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, type: 3} + - _MainTex: + m_Texture: {fileID: 2800000, guid: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, type: 3} + m_Floats: [] +""" +MAT_U4 = """%YAML 1.1 +--- !u!21 &2100000 +Material: + m_Name: mat_Hair + m_SavedProperties: + m_TexEnvs: + data: + first: + name: _MainTex + second: + m_Texture: {fileID: 0} + data: + first: + name: _Main_Texture + second: + m_Texture: {fileID: 2800000, guid: cccccccccccccccccccccccccccccccc, type: 3} + m_Floats: + data: + first: + name: _Cutoff +""" + + +def _write(path, data): + with open(path, "wb" if isinstance(data, bytes) else "w", **({} if isinstance(data, bytes) else {"encoding": "utf-8"})) as f: + f.write(data) + + +class UnityAssetTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.mkdtemp(prefix="m2v_unity_") + a = os.path.join(self.tmp, "Assets") + for sub in ("Chara/Models", "Chara/Materials", "Chara/Textures", "Other/Materials"): + os.makedirs(os.path.join(a, sub)) + + def tex(name, guid): + p = os.path.join(a, "Chara/Textures", name) + open(p, "wb").write(b"x") + open(p + ".meta", "w").write("fileFormatVersion: 2\nguid: %s\n" % guid) + tex("tex_body.tga", "a" * 32) + tex("tex_body_n.tga", "b" * 32) + tex("tex_hair.png", "c" * 32) + tex("tex_other.png", "d" * 32) + _write(os.path.join(a, "Chara/Materials/mat_Body.mat"), MAT_U5) + _write(os.path.join(a, "Chara/Materials/mat_Hair.mat"), MAT_U4) + # 别处的同名材质:不在 FBX 的上级链上,不该被选中 + _write(os.path.join(a, "Other/Materials/mat_Body.mat"), MAT_U5.replace("a" * 32, "d" * 32)) + self.models = os.path.join(a, "Chara/Models") + + def tearDown(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + def test_lookup(self): + m = unityasset.material_textures(self.models) + self.assertEqual(os.path.basename(m["mat_Body"]), "tex_body.tga") # _MainTex,不是法线 + self.assertEqual(os.path.basename(m["mat_Hair"]), "tex_hair.png") # Unity 4 格式、空的 _MainTex 跳过 + + def test_root(self): + self.assertEqual(os.path.basename(unityasset.find_root(self.models)), "Assets") + + def test_solid_color_mat(self): + """Toon 材质常常没有贴图,颜色只在 m_Colors 里:以前 `not guid_path` 直接返回 {}, + 这类材质全被当成默认白色丢掉。Unity 5 / Unity 4 两种写法都要认。""" + tmp = tempfile.mkdtemp(prefix="m2v_solid_") + try: + mats = os.path.join(tmp, "Assets", "Materials") + os.makedirs(mats) + u5 = """%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!21 &2100000 +Material: + m_Name: mat_Black + m_SavedProperties: + m_Colors: + - _ShadeColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + - _Color: {r: 0, g: 0, b: 0, a: 1} + m_TexEnvs: + - _MainTex: + m_Texture: {fileID: 0} + m_Floats: [] +""" + u4 = """%YAML 1.1 +--- !u!21 &2100000 +Material: + m_Name: mat_White + m_SavedProperties: + m_Colors: + data: + first: + name: _Color + second: + val: {r: 1, g: 1, b: 1, a: 1} + m_TexEnvs: [] +""" + _write(os.path.join(mats, "mat_Black.mat"), u5) + _write(os.path.join(mats, "mat_White.mat"), u4) + props = unityasset.material_properties(mats) + self.assertIsNone(props["mat_Black"]["tex"]) + self.assertEqual(props["mat_Black"]["color"], [0.0, 0.0, 0.0, 1.0]) + self.assertIsNone(props["mat_White"]["tex"]) + self.assertEqual(props["mat_White"]["color"], [1.0, 1.0, 1.0, 1.0]) + # 兼容旧接口:只返回有贴图的材质 + self.assertEqual(unityasset.material_textures(mats), {}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + def test_outline_settings(self): + """UCTS / Toon shader 的描边只在 .mat 里(FBX 完全没有):宽度、颜色要读出来; + `_Outline_Width: 0` 是没开描边,不能一律给所有材质加轮廓线。""" + tmp = tempfile.mkdtemp(prefix="m2v_outline_") + try: + mats = os.path.join(tmp, "Assets", "Materials") + os.makedirs(mats) + + def mat(nm, width): + return """%%YAML 1.1 +--- !u!21 &2100000 +Material: + m_Name: %s + m_ShaderKeywords: _EMISSIVE_SIMPLE _OUTLINE_NML + m_SavedProperties: + m_TexEnvs: [] + m_Floats: + - _Outline_Width: %s + - _Farthest_Distance: 100 + m_Colors: + - _Color: {r: 1, g: 1, b: 1, a: 1} + - _Outline_Color: {r: 0.2, g: 0.1, b: 0.3, a: 1} +""" % (nm, width) + + _write(os.path.join(mats, "mat_Base.mat"), mat("mat_Base", 20)) + _write(os.path.join(mats, "mat_NoOutline.mat"), mat("mat_NoOutline", 0)) + props = unityasset.material_properties(mats) + ol = props["mat_Base"]["outline"] + self.assertAlmostEqual(ol["width"], 20.0) + self.assertEqual(ol["color"], [0.2, 0.1, 0.3]) + self.assertEqual(ol["mode"], "NML") + self.assertIsNone(props["mat_NoOutline"]["outline"]) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + def test_solid_png(self): + import vrmio + data = fbx2pmx._solid_png((0.0, 0.0, 0.0)) + w, h, rows = vrmio.decode_rgba(data) + self.assertEqual((w, h), (4, 4)) + self.assertEqual(rows[0][0][:3], (0, 0, 0)) + self.assertEqual(rows[3][3][3], 255) + + +class UnitypackageTest(unittest.TestCase): + """unitypackage 解包(流式读一遍):一个资源的成员挨着放,pathname 在 asset 前后都行。""" + + def test_unpack(self): + tmp = tempfile.mkdtemp(prefix="m2v_up_") + try: + pkg = os.path.join(tmp, "a.unitypackage") + with tarfile.open(pkg, "w:gz") as tf: + for name, data in ( + ("a1/asset", b"FBX"), ("a1/asset.meta", b"m1"), ("a1/pathname", b"Assets/Chara/model.fbx"), + ("a1/preview.png", b"png"), + ("b2/pathname", b"Assets/Chara/tex.png"), ("b2/asset", b"PNG"), # pathname 在前 + ("c3/asset.meta", b"m3"), ("c3/pathname", b"Assets/Empty/"), # 文件夹资源:没有 asset + ("d4/asset", b"lost")): # 没有 pathname + info = tarfile.TarInfo(name) + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + out = os.path.join(tmp, "out") + unitypackage_unpack.unpack(pkg, out, verbose=False) + got = {} + for d, ds, fs in os.walk(out): + for x in ds: + got[os.path.relpath(os.path.join(d, x), out).replace("\\", "/")] = None + for x in fs: + with open(os.path.join(d, x), "rb") as f: + got[os.path.relpath(os.path.join(d, x), out).replace("\\", "/")] = f.read() + self.assertEqual(got, { + "Chara": None, "Chara/model.fbx": b"FBX", "Chara/model.fbx.meta": b"m1", + "Chara/model.fbx.pathname": b"Assets/Chara/model.fbx", "Chara/model.fbx.preview.png": b"png", + "Chara/tex.png": b"PNG", "Chara/tex.png.pathname": b"Assets/Chara/tex.png", + "Empty": None, "Empty.meta": b"m3", "Empty.pathname": b"Assets/Empty/", + "d4": b"lost"}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + + +class FbxMathTest(unittest.TestCase): + def test_rotation_order(self): + # 默认(XYZ)和以前一样:Rz·Ry·Rx + r = (30.0, 40.0, 50.0) + m_x = fbx2pmx.m_trs([0, 0, 0], (r[0], 0, 0), [1, 1, 1]) + m_y = fbx2pmx.m_trs([0, 0, 0], (0, r[1], 0), [1, 1, 1]) + m_z = fbx2pmx.m_trs([0, 0, 0], (0, 0, r[2]), [1, 1, 1]) + want_xyz = fbx2pmx.m_mul(m_z, fbx2pmx.m_mul(m_y, m_x)) + want_zxy = fbx2pmx.m_mul(m_y, fbx2pmx.m_mul(m_x, m_z)) # 4 = ZXY:先 Z 再 X 再 Y + for got, want in ((fbx2pmx.m_rot(r), want_xyz), (fbx2pmx.m_rot(r, 4), want_zxy)): + for a, b in zip(got, want): + self.assertAlmostEqual(a, b, places=9) + + def test_pivot_is_translation(self): + class N: + def get(self, k): + return None + sc = fbx2pmx.Scene.__new__(fbx2pmx.Scene) + sc._props70 = lambda node: {"Lcl Rotation": [0.0, 0.0, 90.0], "RotationPivot": [1.0, 0.0, 0.0]} + m = fbx2pmx.Scene._local_matrix(sc, N()) + # 绕 (1,0,0) 转 90°:原点 → (1,-1,0) + p = fbx2pmx.m_point(m, (0.0, 0.0, 0.0)) + self.assertAlmostEqual(p[0], 1.0, places=6) + self.assertAlmostEqual(p[1], -1.0, places=6) + self.assertTrue(math.isfinite(p[2])) + + +class AlternateMeshTest(unittest.TestCase): + def rec(self, name, nv=100, lo=(0, 0, 0), hi=(1, 1, 1)): + return {"name": name, "nv": nv, "nt": nv * 2, "lo": list(lo), "hi": list(hi), "segs": [len(name)]} + + def test_groups(self): + recs = [self.rec("Body", 500), self.rec("Finger_Pa"), self.rec("Finger_Nomal"), self.rec("Finger_Gu"), + self.rec("Head_01_Normal", 300, (0, 2, 0), (1, 3, 1)), + self.rec("Head_02_MouthOpen", 300, (0, 2, 0), (1, 3, 1)), + self.rec("Glove_L", 100, (5, 0, 0), (6, 1, 1))] # 同样的顶点数,但位置不同 + groups = fbx2pmx._alternate_groups(recs) + got = {p["name"]: sorted(a["name"] for a in alts) for p, alts in groups} + self.assertEqual(got, {"Finger_Nomal": ["Finger_Gu", "Finger_Pa"], + "Head_01_Normal": ["Head_02_MouthOpen"]}) + + +class AutoPhysTest(unittest.TestCase): + """自动物理的兽耳识别:BlackCyan 的 Ear_0_L…Ear_3_R 八根骨曾全被 _FACE 当五官排除。""" + def _sway(self, spec): + # spec: [(骨名, 父骨序号, 位置)],0 = 头、1 = 腰(humanoid) + from vrmconv import autophys + bones = [{"name": n, "name_en": n, "pos": p, "parent": q, "layer": 0, + "flag": 0x001F, "tail": -1} for n, q, p in spec] + model = {"bones": bones, "rigid_bodies": [], "vertices": []} + autophys.synthesize(model, [q for _, q, _ in spec], {}, {"head": 0, "hips": 1}) + return {rb["name"] for rb in model["rigid_bodies"] if rb["mode"] == 1} + + def test_animal_ear_chains_sway(self): + got = self._sway([ + ("Head", -1, (0, 10, 0)), ("Hips", -1, (0, 0, 0)), + ("Ear_0_L", 0, (1, 10.2, 0)), ("Ear_1_L", 2, (1.2, 10.5, 0)), + ("Ear_0_R", 0, (-1, 10.2, 0)), ("Ear_1_R", 4, (-1.2, 10.5, 0)), + ("Earring_L", 0, (1.5, 9.5, 0)), # 耳环是挂件,不能跟着摆 + ("Hair_0", 0, (0, 11, 0)), # 有头发骨时结构推断关闭,兽耳仍要识别 + ]) + for nm in ("Ear_0_L", "Ear_1_L", "Ear_0_R", "Ear_1_R", "Hair_0"): + self.assertIn("auto_" + nm, got) + self.assertNotIn("auto_Earring_L", got) + + def test_single_ear_bone_does_not_sway(self): + """人形模型单根的耳朵 / 表情骨仍由 _FACE 拦住(有头发骨和没头发骨两种结构都要挡)。""" + for extra in ([("Hair_0", 0, (0, 11, 0))], []): + got = self._sway([("Head", -1, (0, 10, 0)), ("Hips", -1, (0, 0, 0)), + ("Ear_L", 0, (1, 10.2, 0))] + extra) + self.assertNotIn("auto_Ear_L", got) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_logtext.py b/tests/test_logtext.py new file mode 100644 index 0000000..d3af830 --- /dev/null +++ b/tests/test_logtext.py @@ -0,0 +1,115 @@ +# -*- coding: utf-8 -*- +"""转换日志的英文版(convert/logtext.py):源码里每条中文日志 / 报错都要有翻译,翻译要对。""" +import ast +import os +import sys +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +for _p in ("convert", "formats"): + _d = os.path.join(ROOT, _p) + if _d not in sys.path: + sys.path.insert(0, _d) +import logtext # noqa: E402 + +LOG_CALLS = {"log", "_log", "_l", "lg", "say", "warn", "_warn", "note", "_note"} +PRINTS = {"fbx2pmx.py"} # 转换时 print() 被转成日志(pipeline._LogWriter) +SKIP = {"app.py"} # 启动器的控制台提示,不进日志 +# 几段拼起来的日志:句式在 TEMPLATES 里拆成了几条(「表情预设:%s」+「%s · 未找到:%s」) +COMPOSITE = {"表情预设:%s%s"} + + +def _cjk(s): + return bool(logtext._CJK.search(s)) + + +def _template(node): + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod): + return _template(node.left) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + return (_template(node.left) or "%s") + (_template(node.right) or "%s") + if isinstance(node, ast.JoinedStr): + return "".join(v.value if isinstance(v, ast.Constant) else "%s" for v in node.values) + return None + + +def source_messages(): + """→ [(位置, 句式, [参数里的中文片段])]:转换器和界面服务器里的 log(...) 和 raise X("...")。""" + out = [] + for d in ("convert", "formats", "ui"): + for dp, _, fs in os.walk(os.path.join(ROOT, d)): + if "vendor" in dp or "__pycache__" in dp: + continue + for fn in fs: + if not fn.endswith(".py") or fn in SKIP: + continue + path = os.path.join(dp, fn) + with open(path, encoding="utf-8") as f: + tree = ast.parse(f.read()) + names = LOG_CALLS | ({"print"} if fn in PRINTS else set()) + for node in ast.walk(tree): + if isinstance(node, ast.Raise) and isinstance(node.exc, ast.Call) and node.exc.args: + arg = node.exc.args[0] + elif isinstance(node, ast.Call) and node.args and \ + (node.func.id if isinstance(node.func, ast.Name) else + getattr(node.func, "attr", None)) in names: + arg = node.args[0] + else: + continue + t = _template(arg) + if not t or not _cjk(t): + continue + frags = [c.value for c in ast.walk(arg) if isinstance(c, ast.Constant) + and isinstance(c.value, str) and _cjk(c.value) and c.value != t] + out.append(("%s:%d" % (os.path.relpath(path, ROOT), node.lineno), t.strip(), frags)) + return out + + +class LogTextTest(unittest.TestCase): + def test_every_message_has_a_translation(self): + known = {k.strip() for k in logtext.TEMPLATES} + missing = [] + for where, t, frags in source_messages(): + if t not in known and t not in COMPOSITE: + missing.append("%s %s" % (where, t)) + for f in frags: + # 拼接用的片段(「视线:」+ note)随整句检查;带占位符或单独成词的要在表里 + if f.strip() not in known and not any(f in k for k in known | COMPOSITE): + missing.append("%s 片段 %s" % (where, f)) + self.assertEqual(missing, [], "logtext.TEMPLATES 里缺这些句式:\n" + "\n".join(missing)) + + def test_templates_are_consistent(self): + """英文里引用的参数个数和中文占位符个数一致。""" + import re + for zh, en in logtext.TEMPLATES.items(): + n = len([m for m in logtext._PH.findall(zh) if m != "%%"]) + used = {int(i) for i in re.findall(r"\{(\d+)\}", en)} + self.assertTrue(used <= set(range(n)), zh) + self.assertEqual(len(used), n, zh) + + def test_translations(self): + cases = { + "[艾尔莎-人类形态] 网格:按表情分为 2 个(身体:13 个表情、脸:181 个表情)": + "[艾尔莎-人类形态] Mesh: split into 2 by morphs (身体: 13 morphs, 脸: 181 morphs)", + "绕序自动判定(手性修正后):与法线同向 16 面 / 反向 3892 面 → 需要反转": + "Winding (after the handedness fix): 16 faces agree with the normals / 3892 oppose → flip", + "T-pose:左 上臂 37.0° · 前臂 0.0°": "T-pose: left upper arm 37.0° · forearm 0.0°", + "表情预设:无 · 未找到:happy、blink": "Preset expressions: none · not found: happy, blink", + "SpringBone:308 个链间横向关节(裙摆等)无法表达,已舍弃;已按裙片朝向修正 273 处裙摆与腿的碰撞方向,减少裙片被腿分开": + "SpringBone: 308 sideways joints between chains (skirts …) can't be expressed and were dropped; " + "273 skirt–leg collisions were adjusted to the skirt panels' direction so the legs split the skirt less", + "已写出 奥黛塔.vrm(26.26 MB)· 节点 551 · morph target 70 · 表情 74": + "Wrote 奥黛塔.vrm (26.26 MB) · 551 nodes · 70 morph targets · 74 expressions", + "ValueError: 不是 VRM 文件": "ValueError: Not a VRM file", + } + for zh, en in cases.items(): + self.assertEqual(logtext.to_en(zh), en) + self.assertIsNone(logtext.to_en("没有这句日志")) + self.assertIsNone(logtext.to_en("plain English")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..c73d7ff --- /dev/null +++ b/tools/README.md @@ -0,0 +1,129 @@ +# 工具 + +> VRMify 增强版 · Enhanced fork 的开发与批量处理脚本。 + +开发和批量处理用的脚本,不随程序打包。转换器本身(`convert/`、`formats/`)只用 Python 标准库; +这里的检查工具另需 `jsonschema`(`pip install -r requirements-dev.txt`)和 Node.js。 + +## 批量转换 `batch_convert.py` + +```bash +python tools/batch_convert.py model -o vrm +python tools/batch_convert.py model -o vrm --only 穗穗 爱弥斯 --variants spring +``` + +* 模型目录下每个子文件夹算一个角色,递归找所有 `.pmx`;文件夹里的 `.zip` 中的 PMX 也会解出来一起转 + (在临时目录里解压,不改动模型目录)。 +* 默认输出两份:`<输出>/有SpringBone/<角色>/` 和 `<输出>/无SpringBone/<角色>/`。 +* 「<名字>_by_<游戏>_<哈希>」形式的文件夹名会整理成「<游戏>—<名字>」。 +* `--report 结果.json` 保存每个模型的日志。 + +## 静态检查 `qa/check_vrm.py` + +```bash +python tools/qa/check_vrm.py vrm # 递归检查目录下所有 .vrm +python tools/qa/check_vrm.py a.vrm -v # 通过的也打印摘要 +``` + +检查 humanoid 结构、网格、表情绑定、SpringBone 链,以及 **VRM 官方 JSON Schema** +(第一次运行时从 vrm-c/vrm-specification 下载固定版本,缓存在 `qa/.schema-cache/`)。 +UniVRM 对不合规数据很少容错——比如材质颜色绑定少一个分量、BlendShape 重名,都会让 Unity 里的 +导入直接中断(表现为卡在加载中),这些都会被它报出来。有错误时退出码为 1。 + +## 动态测试 `qa/dynamics.py` + +```bash +cd tools/qa/harness && npm install # 第一次 +python tools/qa/dynamics.py vrm/有SpringBone -j 4 +python tools/qa/dynamics.py a.vrm --fps 30 --jitter 0.3 --motions idle,walk_real,run,leg_raise +``` + +用 three.js + three-vrm 在 Node 里无界面地跑 SpringBone(和 UniVRM 同一套规则),测: + +| 指标 | 含义 | 参考范围(VRoid / 官方示例模型) | +|---|---|---| +| 静止偏移 | 站着不动 2 秒后弹簧末端离绑定姿势的距离 | < 5 cm | +| hf | 末端 8 Hz 以上的颤动能量 / 链长 ×1000(平均 / 最大) | 头发 2~16,裙摆 3~58 | +| swing | 末端最大摆幅 / 链长 | — | +| 穿腿 | 裙摆关节落在模型自己腿部碰撞体里的比例(含静止时的重叠,和 idle 对比看) | — | +| 张开 | 相邻裙摆链末端比静止时多分开的距离(平均 / 90% / 最大,cm);腿把裙子从中间劈开时变大 | 原 PMX 的 MMD 物理:走路 4~15 | + +动作:`idle`(放下手臂、轻微晃动)、`walk_real` / `run`(带根运动的走路 / 跑步)、`leg_raise` +(抬腿 70°)等,定义在 `qa/harness/motions.mjs`。超出参考范围的数值标「!」,`--strict` 时返回 1。 + +## 回归对比 `regress.py` + +改转换代码前后,用本机的真实模型确认输出有没有变、变在哪里: + +```bash +python tools/regress.py record model/角色A model/角色B/某.pmx # 记下基准(默认 VRM 1.0,--spec 0x 记 0.x) +python tools/regress.py check # 用当前代码重转、校验、对比基准 +python tools/regress.py check --code ../旧版本的代码目录 # 用另一份代码转(比如 git worktree) +``` + +* 基准在 `tests/.golden/`(不进仓库:模型许可不允许再分发,衍生数据也只留在本机),记录 glTF JSON 全文和二进制块的 sha256。 +* `check` 对每个样本:转换 → `check_vrm` 结构和 Schema 校验 → 列出 JSON 里不同的路径(最多 20 条)、二进制块是否一致。 + 有错误或差异时退出码为 1。变化是否符合预期要自己判断,确认后重新 `record`。 + +## 骨骼自检扫描 `scan_models.py` + +```bash +python tools/scan_models.py model ~/Downloads -o 结果.txt +``` + +对目录里的每个 PMX(压缩包在临时目录里解开)只跑骨骼处理和转换时的自检,不写 VRM,几秒一个: +付与骨合并了几根、按比例拆权重的骨有几根,以及自检问题——网格在 MMD 里跟着关节转、在 VRM 里却不跟, +或者 humanoid 骨位置明显不对(在身体另一侧、离父骨或网格太远)。这些问题转换时也会写进日志。 +改骨骼相关的代码前后各跑一次对比,发版前跑一次;有自检问题时退出码为 1。 + +## 表情截图 `qa/snapshots.py` + +```bash +python tools/qa/snapshots.py a.vrm -o a.png # 全身、脸、表情预设、口型、眨眼、视线四个方向 +python tools/qa/snapshots.py 旧/a.vrm 新/a.vrm -o 对比.png # 每个输入一行,上下对照 +python tools/qa/snapshots.py model/角色/角色.pmx -o a.png # 不是 VRM 的先用当前代码转一份(临时目录) +python tools/qa/snapshots.py a.vrm --custom --cols 12 -o a.png # 再加上自定义表情,每段 12 列 +``` + +用无界面的 Edge / Chrome(`--browser` 指定路径)加载界面预览用的 `ui/viewer/viewer-core.js` 来拍, +和程序里看到的一致;WebGL 走软件渲染,不依赖显卡,一个模型几秒。模型没有的表情格子标「无」。 +改表情相关的代码前后各拍一张对照,比只看 `regress.py` 的 JSON 差异直观。 + +## 单元测试 `tests/` + +```bash +python -m unittest discover -s tests -v +``` + +不需要真实模型:`tests/synth.py` 合成一个小的 MMD 人形 PMX(标准骨名、头发物理、几个表情、两张贴图), +测转换(1.0 / 0.x、元信息、结果确定性、贴图瘦身)、转换后调整(`vrm_edit` 的套用 / 还原 / 幂等)和 zip 输入。 +装了 jsonschema 时顺带做官方 Schema 校验;没装 Pillow 时跳过贴图瘦身的测试。 + +## 程序图标 `make_icon.py` + +```bash +python tools/make_icon.py # → ui/icon.ico(exe 图标)+ ui/web/icon.png(页面图标),需要 Pillow +``` + +圆角蓝底 + 白色菱形,和界面左上角的「◆」一致;改颜色、形状就改这个脚本再重新生成。 + +## 打包发布 `build_release.py` + +```bash +python tools/build_release.py # → dist/VRMify-v<版本>-win64.zip +python tools/build_release.py --expect-version v0.1.0 # tag 和 ui/version.py 不一致时报错(Actions 里这么调用) +``` + +按 `VRMify.spec` 打包,把 `LICENSE`、README 放进程序文件夹,再压成绿色版 zip。GitHub Actions 的 +`release.yml` 用的也是它,流程见 README 的「开发」一节。 + +## 冒烟测试 `smoke_exe.py` + +```bash +python tools/smoke_exe.py dist/VRMify-v0.1.2-win64.zip # 发布 zip、解开的程序文件夹或 exe 都行 +``` + +单元测试测源码,这里测**打包以后**的 exe:用临时数据目录启动 `--no-open`,通过它自己的 HTTP 接口 +加入合成的 PMX / zip / FBX / unitypackage 并转换,检查版本号、页面和预览库、每个输出过 `check_vrm`、 +PMX 原生预览和调整面板接口。PyInstaller 漏打模块或页面资源时会在这里失败(退出码 1,并打印 exe 的输出)。 +`release.yml` 打包后自动跑,不通过就不建 Release。 diff --git a/tools/batch_convert.py b/tools/batch_convert.py new file mode 100644 index 0000000..6f1f82c --- /dev/null +++ b/tools/batch_convert.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +"""批量把一个目录下的 PMX 转成 VRM。 + + python tools/batch_convert.py [模型目录] [-o 输出目录] [--only 关键字 ...] + [--variants both|spring|nospring] [--spec 1.0|0.x] + [-j 进程数] [--report 结果.json] + +* 模型目录下每个子文件夹算一个角色,递归找其中所有 .pmx;子文件夹里的 .zip + (作者常把道具、差分模型打包在里面)也会解出其中的 .pmx 一起转。解压在临时 + 目录里进行(连同角色文件夹的贴图一起复制过去,相对路径才找得到),不改动 + 模型目录本身。 +* 输出:<输出目录>/有SpringBone/<角色>/<名>.vrm 和 <输出目录>/无SpringBone/<角色>/<名>.vrm + (--variants 只要其中一种时不分这一层)。 +* 角色文件夹名形如「<名字>_by_<游戏>_<哈希>」(模之屋的下载格式)时整理成 + 「<游戏>—<名字>」,并去掉「(修模绑骨后)」这类说明和结尾的版本号;其它名字原样使用。 +* 最后打印每个模型的结果;用占位骨补齐 humanoid 的(道具、非人形)会标出来。 +""" +import argparse +import glob +import json +import os +import shutil +import sys +import tempfile +import time +import zipfile +from concurrent.futures import ProcessPoolExecutor + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path[:0] = [os.path.join(ROOT, "convert"), os.path.join(ROOT, "formats")] +import pipeline # noqa: E402 + +char_name = pipeline.nice_name # 角色文件夹名 → 输出用的角色名 + + +def collect(model_dir, extract_dir, only=None): + """→ [(角色文件夹名, pmx 路径, 来源)];only = 文件夹名须包含其中之一的关键字。""" + jobs = [] + for d in sorted(glob.glob(os.path.join(model_dir, "*"))): + if not os.path.isdir(d): + continue + folder = os.path.basename(d) + if only and not any(k in folder for k in only): + continue + have = set() + for p in sorted(glob.glob(os.path.join(d, "**", "*.pmx"), recursive=True)): + jobs.append((folder, p, "folder")) + have.add(os.path.basename(p)) + zips = sorted(glob.glob(os.path.join(d, "*.zip"))) + if not zips: + continue + copy = os.path.join(extract_dir, folder) + for z in zips: + with zipfile.ZipFile(z) as zf: + for info, names in pipeline.zip_members(zf): + base = os.path.basename(names[0]) + if not base.lower().endswith(".pmx") or base in have: + continue + if not os.path.isdir(copy): + shutil.copytree(d, copy, ignore=shutil.ignore_patterns( + "*.zip", "*.vrm", "*.pmx")) + dst = os.path.join(copy, base) + with zf.open(info) as src, open(dst, "wb") as f: + shutil.copyfileobj(src, f) + jobs.append((folder, dst, "zip:" + os.path.basename(z))) + have.add(base) + return jobs + + +def run(job): + folder, pmx, src, out_dir, variants, spec = job + sys.path[:0] = [os.path.join(ROOT, "convert"), os.path.join(ROOT, "formats")] + import pmx2vrm + stem = os.path.splitext(os.path.basename(pmx))[0] + res = {"folder": folder, "char": char_name(folder), "pmx": pmx, "src": src, "stem": stem} + for label, spring in variants: + sub = [out_dir] + ([label] if len(variants) > 1 else []) + [res["char"], stem + ".vrm"] + out = os.path.join(*sub) + logs = [] + t = time.time() + try: + st = pmx2vrm.convert(pmx, out, spec=spec, spring=spring, meta={"title": stem}, + log=lambda m, tag=None: logs.append((tag, m))) + res[label] = {"ok": True, "out": out, "mb": st["bytes"] / 1048576.0, + "sec": time.time() - t, "logs": logs} + except Exception as e: # noqa: BLE001 一个模型失败不影响其它 + import traceback + res[label] = {"ok": False, "err": "%s: %s" % (type(e).__name__, e), + "tb": traceback.format_exc()[-2000:], "logs": logs} + return res + + +def main(argv=None): + ap = argparse.ArgumentParser(description="批量把目录下的 PMX 转成 VRM") + ap.add_argument("models", nargs="?", default=os.path.join(ROOT, "model"), + help="模型目录(每个子文件夹一个角色),默认 ./model") + ap.add_argument("-o", "--out", default=os.path.join(ROOT, "vrm"), help="输出目录,默认 ./vrm") + ap.add_argument("--only", nargs="+", metavar="关键字", + help="只转文件夹名包含这些关键字的角色,如 --only 穗穗 爱弥斯") + ap.add_argument("--variants", choices=("both", "spring", "nospring"), default="both", + help="同时输出有 / 无 SpringBone 两份(默认),或只要其中一种") + ap.add_argument("--spec", choices=("1.0", "0.x"), default="1.0", help="VRM 版本,默认 1.0") + ap.add_argument("-j", "--jobs", type=int, default=max(1, min(6, (os.cpu_count() or 2) - 1)), + help="并行进程数") + ap.add_argument("--report", help="把每个模型的结果和日志写成 JSON(给 tools/qa 用)") + a = ap.parse_args(argv) + + variants = {"both": [("有SpringBone", True), ("无SpringBone", False)], + "spring": [("有SpringBone", True)], + "nospring": [("无SpringBone", False)]}[a.variants] + if a.spec != "1.0" and a.variants != "nospring": + print("提示:VRM 0.x 不输出 SpringBone,「有SpringBone」那份会和「无」一样") + extract = tempfile.mkdtemp(prefix="vrmify_zip_") + try: + jobs = collect(a.models, extract, a.only) + names = [(char_name(f), os.path.basename(p)) for f, p, _ in jobs] + dup = {n for n in names if names.count(n) > 1} + if dup: + sys.exit("输出文件重名:%s" % sorted(dup)) + print("共 %d 个 PMX → %s" % (len(jobs), a.out)) + args = [(f, p, s, a.out, variants, a.spec) for f, p, s in jobs] + with ProcessPoolExecutor(max_workers=a.jobs) as ex: + results = list(ex.map(run, args)) + finally: + shutil.rmtree(extract, ignore_errors=True) + + n_fail = 0 + for r in results: + oks = [r[label]["ok"] for label, _ in variants] + n_fail += oks.count(False) + first = r[variants[0][0]] + ph = sum(1 for _, m in first.get("logs", []) if "占位骨骼" in m) + print("%s %-16s %-28s %s%s" % ( + "OK " if all(oks) else "FAIL", r["char"][:16], r["stem"][:28], + ("占位骨 %d 根" % ph) if ph else "", + "" if all(oks) else " " + "; ".join(r[l].get("err", "") for l, _ in variants))) + if a.report: + with open(a.report, "w", encoding="utf-8") as f: + json.dump({"variants": [l for l, _ in variants], "results": results}, f, + ensure_ascii=False, indent=1) + print("完成:%d 个模型,失败 %d 次" % (len(results), n_fail)) + return 1 if n_fail else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/build_release.py b/tools/build_release.py new file mode 100644 index 0000000..bf8a68a --- /dev/null +++ b/tools/build_release.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +"""VRMify 增强版:打包发布用的 zip(绿色版:解压后双击 VRMify.exe)。本地和 GitHub Actions 用的是同一个脚本。 + + python tools/build_release.py → dist/VRMify-v0.1.0-win64.zip + python tools/build_release.py --expect-version v0.1.0 tag 和 ui/version.py 不一致时报错退出 + +步骤:PyInstaller 按 VRMify.spec 打包 → 把 LICENSE、README 放进程序文件夹 → 压成 zip。 +需要 requirements-dev.txt 里的包(pyinstaller、pywebview、Pillow)。 +""" +import argparse +import os +import platform +import shutil +import subprocess +import sys +import zipfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "ui")) +from version import __version__ # noqa: E402 + +APP = "VRMify" +# 随程序一起发的文档:GPL-3.0 要求附上许可证;README 里有用法和源码出处 +DOCS = ["LICENSE", "README_SC.md", "README.md"] + + +def main(argv=None): + ap = argparse.ArgumentParser(description="打包发布用的 zip") + ap.add_argument("--expect-version", default="", help="tag(如 v0.1.0),必须和 ui/version.py 一致") + ap.add_argument("--dist", default=os.path.join(ROOT, "dist")) + ap.add_argument("--work", default=os.path.join(ROOT, "build")) + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + + want = a.expect_version.lstrip("vV") + if want and want != __version__: + print("版本号不一致:tag 是 %s,ui/version.py 里是 %s(先改 version.py 再打 tag)" + % (a.expect_version, __version__)) + return 1 + + subprocess.run([sys.executable, "-m", "PyInstaller", os.path.join(ROOT, "VRMify.spec"), + "--noconfirm", "--clean", "--distpath", a.dist, "--workpath", a.work], + cwd=ROOT, check=True) + app_dir = os.path.join(a.dist, APP) + for fn in DOCS: + shutil.copy2(os.path.join(ROOT, fn), os.path.join(app_dir, fn)) + + arch = "win64" if sys.platform.startswith("win") and platform.machine().endswith("64") else \ + "%s-%s" % (sys.platform, platform.machine().lower()) + out = os.path.join(a.dist, "%s-v%s-%s.zip" % (APP, __version__, arch)) + if os.path.exists(out): + os.remove(out) + with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as zf: + for d, _, fs in os.walk(app_dir): + for fn in fs: + p = os.path.join(d, fn) + zf.write(p, os.path.join(APP, os.path.relpath(p, app_dir))) + print("已生成 %s(%.1f MB)" % (out, os.path.getsize(out) / 1048576.0)) + gh_out = os.environ.get("GITHUB_OUTPUT") + if gh_out: # 给 Actions 后面的步骤用 + with open(gh_out, "a", encoding="utf-8") as f: + f.write("zip=%s\nversion=%s\n" % (out, __version__)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/make_icon.py b/tools/make_icon.py new file mode 100644 index 0000000..2963ba3 --- /dev/null +++ b/tools/make_icon.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +"""生成程序图标:圆角方块(界面的强调蓝)+ 白色菱形,和界面左上角的「◆」一致。 + + python tools/make_icon.py → ui/icon.ico(exe 图标,多尺寸)+ ui/web/icon.png(页面 favicon) + +需要 Pillow。按 4 倍分辨率画再缩小,边缘是平滑的。 +""" +import os + +from PIL import Image, ImageDraw + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOP, BOTTOM = (0x4F, 0x86, 0xF5), (0x2F, 0x5C, 0xD6) # 界面的 --accent #3a6ee8 上下各偏一点 +SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256] + + +def draw(size): + k = 4 + n = size * k + img = Image.new("RGBA", (n, n), (0, 0, 0, 0)) + # 竖直渐变的底 + grad = Image.new("RGBA", (1, n)) + for y in range(n): + t = y / max(1, n - 1) + grad.putpixel((0, y), tuple(round(TOP[i] + (BOTTOM[i] - TOP[i]) * t) for i in range(3)) + (255,)) + grad = grad.resize((n, n)) + mask = Image.new("L", (n, n), 0) + pad = round(n * 0.04) + ImageDraw.Draw(mask).rounded_rectangle((pad, pad, n - 1 - pad, n - 1 - pad), radius=round(n * 0.22), fill=255) + img.paste(grad, (0, 0), mask) + # 白色菱形(小尺寸时画大一点,免得糊成一个点) + d = ImageDraw.Draw(img) + c = n / 2 + r = n * (0.30 if size >= 32 else 0.34) + d.polygon([(c, c - r), (c + r, c), (c, c + r), (c - r, c)], fill=(255, 255, 255, 255)) + if size >= 48: # 大图标:菱形中间挖一个小菱形,多一点层次 + r2 = r * 0.38 + d.polygon([(c, c - r2), (c + r2, c), (c, c + r2), (c - r2, c)], + fill=tuple(round((TOP[i] + BOTTOM[i]) / 2) for i in range(3)) + (255,)) + return img.resize((size, size), Image.LANCZOS) + + +def main(): + imgs = [draw(s) for s in SIZES] + ico = os.path.join(ROOT, "ui", "icon.ico") + imgs[-1].save(ico, sizes=[(s, s) for s in SIZES], append_images=imgs[:-1]) + png = os.path.join(ROOT, "ui", "web", "icon.png") + draw(64).save(png, optimize=True) + print(ico) + print(png) + + +if __name__ == "__main__": + main() diff --git a/tools/qa/check_vrm.py b/tools/qa/check_vrm.py new file mode 100644 index 0000000..a90c3ad --- /dev/null +++ b/tools/qa/check_vrm.py @@ -0,0 +1,358 @@ +# -*- coding: utf-8 -*- +"""VRM 文件静态检查:结构、SpringBone、官方 JSON Schema、导入器会踩的坑。 + + python tools/qa/check_vrm.py 文件或目录 [...] [--no-schema] [-v] + +逐个文件检查(目录会递归找 .vrm),有问题的打印出来,最后汇总;有错误时退出码为 1。 + +* humanoid:骨位名合法、必需骨位齐全、每根骨的 VRM 父骨位确实是它的祖先、 + 用占位骨(vrm_*)补的骨位(道具 / 非人形模型会有,记为提示)。 +* 网格:JOINTS_0 不越界;同一网格里 morph target 不重名(Unity 遇到重名的 + BlendShape 会抛异常,UniVRM 导入直接中断)。 +* 表情:materialColorBinds 的材质号、morphTargetBinds 的 node / index 在范围内。 +* SpringBone(VRM 1.0):相邻关节是祖先关系、关节不落在 humanoid 骨上、参数有限、 + 碰撞组号合法、同一节点不重复当关节。 +* SpringBone(VRM 0.x):硬度键名是 stiffiness、参数有限、碰撞组号合法、组根子树不含 + humanoid 骨、同一节点不落在两个组的子树里(0.x 组根下面整棵子树都会摆动)。 +* Schema:用 vrm-c/vrm-specification 的官方 JSON Schema 校验 VRMC_vrm、 + VRMC_springBone、VRMC_materials_mtoon,以及 VRM 0.x 的 VRM 扩展。需要 jsonschema 包;第一次运行时从 GitHub + 下载固定版本的 schema,缓存在 tools/qa/.schema-cache/。UniVRM 对不合规的数据很少 + 容错(例如 targetValue 少一个分量就 IndexOutOfRange),所以这一项很有用。 +""" +import argparse +import json +import math +import os +import sys +import urllib.request +from collections import Counter + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.path[:0] = [os.path.join(ROOT, "formats"), os.path.join(ROOT, "convert")] +import vrmio # noqa: E402 +from vrmconv.humanoid import _vrm_anchor # noqa: E402 + +# ---------------------------------------------------------------- humanoid -- +_B10 = set("hips spine chest upperChest neck head leftEye rightEye jaw leftUpperLeg leftLowerLeg " + "leftFoot leftToes rightUpperLeg rightLowerLeg rightFoot rightToes leftShoulder " + "leftUpperArm leftLowerArm leftHand rightShoulder rightUpperArm rightLowerArm " + "rightHand".split()) +_B0 = set(_B10) +for _s in ("left", "right"): + _B10 |= {_s + "ThumbMetacarpal", _s + "ThumbProximal", _s + "ThumbDistal"} + _B0 |= {_s + "ThumbProximal", _s + "ThumbIntermediate", _s + "ThumbDistal"} + for _f in ("Index", "Middle", "Ring", "Little"): + for _j in ("Proximal", "Intermediate", "Distal"): + _B10.add(_s + _f + _j) + _B0.add(_s + _f + _j) +_REQ = ("hips spine head leftUpperArm leftLowerArm leftHand rightUpperArm rightLowerArm " + "rightHand leftUpperLeg leftLowerLeg leftFoot rightUpperLeg rightLowerLeg " + "rightFoot").split() + +# ------------------------------------------------------------------ schema -- +SPEC_COMMIT = "94e82dd346fa6cf0337c4421728640e5252dd38e" # vrm-c/vrm-specification +SPEC_URL = "https://raw.githubusercontent.com/vrm-c/vrm-specification/%s/specification/%s/schema/%s" +SPEC_FILES = { + "VRMC_vrm-1.0": [ + "VRMC_vrm.schema.json", "VRMC_vrm.meta.schema.json", "VRMC_vrm.humanoid.schema.json", + "VRMC_vrm.humanoid.humanBones.schema.json", + "VRMC_vrm.humanoid.humanBones.humanBone.schema.json", + "VRMC_vrm.firstPerson.schema.json", "VRMC_vrm.firstPerson.meshAnnotation.schema.json", + "VRMC_vrm.lookAt.schema.json", "VRMC_vrm.lookAt.rangeMap.schema.json", + "VRMC_vrm.expressions.schema.json", "VRMC_vrm.expressions.expression.schema.json", + "VRMC_vrm.expressions.expression.materialColorBind.schema.json", + "VRMC_vrm.expressions.expression.morphTargetBind.schema.json", + "VRMC_vrm.expressions.expression.textureTransformBind.schema.json"], + "VRMC_springBone-1.0": [ + "VRMC_springBone.schema.json", "VRMC_springBone.collider.schema.json", + "VRMC_springBone.colliderGroup.schema.json", "VRMC_springBone.joint.schema.json", + "VRMC_springBone.shape.schema.json", "VRMC_springBone.spring.schema.json"], + "VRMC_materials_mtoon-1.0": [ + "VRMC_materials_mtoon.schema.json", "mtoon.shadingShiftTexture.schema.json"], + "0.0": [ + "vrm.schema.json", "vrm.meta.schema.json", "vrm.humanoid.schema.json", "vrm.humanoid.bone.schema.json", + "vrm.firstperson.schema.json", "vrm.firstperson.degreemap.schema.json", + "vrm.firstperson.meshannotation.schema.json", "vrm.blendshape.schema.json", + "vrm.blendshape.group.schema.json", "vrm.blendshape.bind.schema.json", + "vrm.blendshape.materialbind.schema.json", "vrm.secondaryanimation.schema.json", + "vrm.secondaryanimation.spring.schema.json", "vrm.secondaryanimation.collidergroup.schema.json", + "vrm.material.schema.json"], +} +# glTF 本体的几个 schema 只被引用、不需要逐项校验,用最小定义代替 +_GLTF_STUBS = { + "glTFProperty.schema.json": {"type": "object"}, + "glTFid.schema.json": {"type": "integer", "minimum": 0}, + "textureInfo.schema.json": {"type": "object", "required": ["index"], + "properties": {"index": {"type": "integer", "minimum": 0}, + "texCoord": {"type": "integer", "minimum": 0}}}, +} +_BASE = "https://vrm-spec.invalid/" + + +def load_validators(): + """→ {扩展名: validator};缺 jsonschema 或下载失败时返回 (None, 原因)。""" + try: + import jsonschema + from referencing import Registry, Resource + from referencing.jsonschema import DRAFT4 + except ImportError: + return None, "未安装 jsonschema(pip install jsonschema),跳过 Schema 校验" + cache = os.path.join(HERE, ".schema-cache", SPEC_COMMIT[:12]) + docs = dict(_GLTF_STUBS) + for d, files in SPEC_FILES.items(): + for fn in files: + path = os.path.join(cache, fn) + if not os.path.isfile(path): + os.makedirs(cache, exist_ok=True) + try: + with urllib.request.urlopen(SPEC_URL % (SPEC_COMMIT, d, fn), timeout=30) as r: + data = r.read() + except OSError as e: + return None, "下载 schema 失败(%s),跳过 Schema 校验" % e + with open(path, "wb") as f: + f.write(data) + with open(path, encoding="utf-8") as f: + docs[fn] = json.load(f) + resources = [] + for fn, doc in docs.items(): + # draft-04 用 id(不是 $id)定基准 URI,相对的 $ref 才解析得到 + doc = dict({k: v for k, v in doc.items() if k not in ("$schema", "$id")}, id=_BASE + fn) + resources.append((_BASE + fn, Resource.from_contents(doc, default_specification=DRAFT4))) + registry = Registry().with_resources(resources) + out = {} + for ext, fn in (("VRMC_vrm", "VRMC_vrm"), ("VRMC_springBone", "VRMC_springBone"), + ("VRMC_materials_mtoon", "VRMC_materials_mtoon"), ("VRM", "vrm")): + schema = registry.contents(_BASE + fn + ".schema.json") + out[ext] = jsonschema.Draft4Validator(schema, registry=registry) + return out, None + + +def schema_errors(g, validators): + errs = [] + + def run(ext, obj, where): + for e in validators[ext].iter_errors(obj): + path = "/".join(str(p) for p in e.absolute_path) + errs.append("schema %s/%s: %s" % (where, path, e.message[:120])) + + ext = g.get("extensions", {}) + if "VRMC_vrm" in ext: + run("VRMC_vrm", ext["VRMC_vrm"], "VRMC_vrm") + if "VRMC_springBone" in ext: + run("VRMC_springBone", ext["VRMC_springBone"], "VRMC_springBone") + if "VRM" in ext: + run("VRM", ext["VRM"], "VRM") + for i, m in enumerate(g.get("materials", [])): + mt = m.get("extensions", {}).get("VRMC_materials_mtoon") + if mt is not None: + run("VRMC_materials_mtoon", mt, "materials/%d/mtoon" % i) + return errs + + +# ------------------------------------------------------------------ checks -- +def check(path, validators=None): + """→ (错误列表, 提示列表, 摘要 dict)""" + errs, notes = [], [] + g, b = vrmio.read_glb(path) + ext = g.get("extensions", {}) + nodes = g["nodes"] + par = {c: i for i, n in enumerate(nodes) for c in n.get("children", [])} + is1 = "VRMC_vrm" in ext + if not is1 and "VRM" not in ext: + return ["不是 VRM(没有 VRMC_vrm / VRM 扩展)"], [], {} + + # humanoid + if is1: + hb = {k: v["node"] for k, v in ext["VRMC_vrm"]["humanoid"]["humanBones"].items()} + valid, req = _B10, _REQ + else: + hb = {x["bone"]: x["node"] for x in ext["VRM"]["humanoid"]["humanBones"]} + valid, req = _B0, _REQ + ["chest", "neck"] + for k in sorted(set(hb) - valid): + errs.append("humanoid:非法骨位 %s" % k) + for k in req: + if k not in hb: + errs.append("humanoid:缺少必需骨位 %s" % k) + for h, n in hb.items(): + a = _vrm_anchor(h, hb) + if a is None: + continue + p = par.get(n) + while p is not None and p != hb[a]: + p = par.get(p) + if p is None: + errs.append("humanoid:%s 不在 %s 之下" % (h, a)) + placeholders = sorted(h for h, n in hb.items() if nodes[n].get("name", "").startswith("vrm_")) + if placeholders: + notes.append("humanoid:%d 根占位骨(%s)" % (len(placeholders), ", ".join(placeholders[:6]) + + (" …" if len(placeholders) > 6 else ""))) + + # mesh + njoints = len(g["skins"][0]["joints"]) if g.get("skins") else 0 + for mi, m in enumerate(g.get("meshes", [])): + for pr in m["primitives"]: + if "JOINTS_0" in pr["attributes"]: + if max(vrmio.read_accessor(g, b, pr["attributes"]["JOINTS_0"])) >= njoints: + errs.append("mesh %d:JOINTS_0 超出 skin.joints" % mi) + break + names = (m.get("extras") or {}).get("targetNames") or [] + for k, v in Counter(names).items(): + if v > 1: + errs.append("mesh %d:morph target 重名「%s」×%d(Unity 导入会中断)" % (mi, k, v)) + + # expressions + nm = len(g.get("materials", [])) + if is1: + groups = ext["VRMC_vrm"].get("expressions", {}) + for grp in ("preset", "custom"): + for name, e in (groups.get(grp) or {}).items(): + for bnd in e.get("materialColorBinds", []): + if not 0 <= bnd["material"] < nm: + errs.append("表情 %s:材质号 %d 越界" % (name, bnd["material"])) + for bnd in e.get("morphTargetBinds", []): + node = nodes[bnd["node"]] if 0 <= bnd["node"] < len(nodes) else {} + if "mesh" not in node: + errs.append("表情 %s:node %d 没有网格" % (name, bnd["node"])) + continue + nt = len(g["meshes"][node["mesh"]]["primitives"][0].get("targets", [])) + if not 0 <= bnd["index"] < nt: + errs.append("表情 %s:morph 索引 %d 越界(共 %d)" % (name, bnd["index"], nt)) + + # SpringBone + summary = {"spec": "1.0" if is1 else "0.x", "humanBones": len(hb), + "placeholders": len(placeholders)} + sb = ext.get("VRMC_springBone") + if sb: + hum = set(hb.values()) + seen = Counter() + ncg = len(sb.get("colliderGroups", [])) + for sp in sb["springs"]: + js = sp["joints"] + for a, c in zip(js, js[1:]): + q = par.get(c["node"]) + while q is not None and q != a["node"]: + q = par.get(q) + if q is None: + errs.append("SpringBone %s:%s 不是 %s 的后代" % ( + sp.get("name"), nodes[c["node"]]["name"], nodes[a["node"]]["name"])) + for j in js: + seen[j["node"]] += 1 + if j["node"] in hum: + errs.append("SpringBone %s:关节落在 humanoid 骨 %s 上" + % (sp.get("name"), nodes[j["node"]]["name"])) + for k in ("hitRadius", "stiffness", "gravityPower", "dragForce"): + if k in j and not math.isfinite(j[k]): + errs.append("SpringBone %s:%s 不是有限值" % (sp.get("name"), k)) + for cg in sp.get("colliderGroups", []): + if not 0 <= cg < ncg: + errs.append("SpringBone %s:碰撞组号 %d 越界" % (sp.get("name"), cg)) + for n, c in seen.items(): + if c > 1: + errs.append("SpringBone:节点 %s 在 %d 条链里当关节" % (nodes[n]["name"], c)) + summary.update(springs=len(sb["springs"]), + joints=sum(len(sp["joints"]) for sp in sb["springs"]), + colliders=len(sb.get("colliders", []))) + sa = None if is1 else ext["VRM"].get("secondaryAnimation") + if sa and sa.get("boneGroups"): + errs += _check_secondary(sa, nodes, par, set(hb.values())) + summary.update(springs=len(sa["boneGroups"]), + colliders=sum(len(c.get("colliders", [])) for c in sa.get("colliderGroups", []))) + + if validators: + errs += schema_errors(g, validators) + return errs, notes, summary + + +def _check_secondary(sa, nodes, par, hum): + """VRM 0.x 的 secondaryAnimation:组根子树整棵都会摆动,同一节点在两个组里会被模拟两次。""" + errs = [] + kids = {i: n.get("children", []) for i, n in enumerate(nodes)} + ncg = len(sa.get("colliderGroups", [])) + owner = {} + for gi, grp in enumerate(sa["boneGroups"]): + name = grp.get("comment") or "#%d" % gi + if "stiffness" in grp and "stiffiness" not in grp: + errs.append("secondaryAnimation %s:硬度要写成 stiffiness(规范里的拼写),stiffness 不会被读取" % name) + for k in ("stiffiness", "gravityPower", "dragForce", "hitRadius"): + if k in grp and not math.isfinite(grp[k]): + errs.append("secondaryAnimation %s:%s 不是有限值" % (name, k)) + for cg in grp.get("colliderGroups", []): + if not 0 <= cg < ncg: + errs.append("secondaryAnimation %s:碰撞组号 %d 越界" % (name, cg)) + for r in grp.get("bones", []): + if not 0 <= r < len(nodes): + errs.append("secondaryAnimation %s:根节点 %d 越界" % (name, r)) + continue + stack = [r] + while stack: + n = stack.pop() + if n in hum: + errs.append("secondaryAnimation %s:humanoid 骨 %s 在摆动子树里" % (name, nodes[n]["name"])) + if n in owner: + errs.append("secondaryAnimation:节点 %s 同时在组 %s 和 %s 的子树里(会被模拟两次)" + % (nodes[n]["name"], owner[n], name)) + continue + owner[n] = name + stack.extend(kids[n]) + for ci, cg in enumerate(sa.get("colliderGroups", [])): + if not 0 <= cg.get("node", -1) < len(nodes): + errs.append("secondaryAnimation:碰撞组 %d 的节点越界" % ci) + return errs + + +def iter_files(paths): + for p in paths: + if os.path.isdir(p): + for d, _, fs in os.walk(p): + for f in sorted(fs): + if f.lower().endswith(".vrm"): + yield os.path.join(d, f) + else: + yield p + + +def main(argv=None): + ap = argparse.ArgumentParser(description="VRM 文件静态检查") + ap.add_argument("paths", nargs="+", help=".vrm 文件或目录") + ap.add_argument("--no-schema", action="store_true", help="不做官方 JSON Schema 校验") + ap.add_argument("-v", "--verbose", action="store_true", help="通过的文件也打印摘要和提示") + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + validators = None + if not a.no_schema: + validators, why = load_validators() + if why: + print("提示:" + why) + n = bad = 0 + for path in iter_files(a.paths): + n += 1 + try: + errs, notes, summ = check(path, validators) + except Exception as e: # noqa: BLE001 坏文件也要继续往下查 + errs, notes, summ = ["读取失败:%s: %s" % (type(e).__name__, e)], [], {} + if errs: + bad += 1 + print("✗ %s" % path) + shown = Counter() + for e in errs: # 同类错误只列前几条 + key = e.split(":")[0] if ":" in e else e[:40] + shown[key] += 1 + if shown[key] <= 5: + print(" " + e) + for k, c in shown.items(): + if c > 5: + print(" …… %s 还有 %d 条" % (k, c - 5)) + elif a.verbose: + print("✓ %s %s" % (path, " ".join("%s=%s" % kv for kv in summ.items()))) + for t in notes: + print(" 提示:" + t) + print("检查 %d 个文件,%d 个有错误" % (n, bad)) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qa/dynamics.py b/tools/qa/dynamics.py new file mode 100644 index 0000000..c37a517 --- /dev/null +++ b/tools/qa/dynamics.py @@ -0,0 +1,147 @@ +# -*- coding: utf-8 -*- +"""SpringBone 动态测试:静止偏移 + 待机 / 带位移走路 / 跑步时的末端颤动。 + + python tools/qa/dynamics.py 文件或目录 [...] [-j 4] [--motions idle,walk_real,run] + [--fps 60] [--jitter 0] [--json 结果.json] [--strict] + +用 three.js + three-vrm 在 Node 里无界面地跑物理(和 UniVRM 同一套 SpringBone 规则), +每个文件一个进程并行。只测带 VRMC_springBone 的人形模型(占位骨补出来的道具跳过)。 +第一次用要先装依赖: cd tools/qa/harness && npm install + +指标(越小越稳;参考范围来自 VRoid / VRM 官方示例模型在同样动作下的实测): + 静止偏移 站着不动 2 秒后弹簧末端离绑定姿势的最大距离。正常 < 5 cm + hf 末端 8 Hz 以上的颤动能量 / 链长 ×1000(平均/最大)。原生模型头发 2~16、裙摆 3~58 + swing 末端最大摆幅 / 链长 + 穿腿 裙摆关节落在模型自己的腿部碰撞体里的比例(含静止时就重叠的,要和 idle 对比看) +超出范围的数值后面标「!」;--strict 时有标记就返回 1。 +""" +import argparse +import json +import os +import shutil +import struct +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +HERE = os.path.dirname(os.path.abspath(__file__)) +HARNESS = os.path.join(HERE, "harness") +LIMITS = {"rest": 0.05, "hf": {"hair": 16.0, "skirt": 60.0, "torso": 60.0, "other": 60.0}} + + +def glb_json(path): + with open(path, "rb") as f: + head = f.read(20) + n = struct.unpack_from(" LIMITS["rest"] + flag |= bad + out = ["%s %s" % ("!" if bad else "·", name), + " 静止偏移 最大 %.1f cm%s(%s)· 超过 1 cm 的 %d / %d" % ( + rest["max"] * 100, " !" if bad else "", rest["maxName"], rest["over1cm"], rest["joints"])] + for m, r in res["motions"].items(): + parts = [] + for cat in ("hair", "skirt", "torso", "other"): + c = r["cats"].get(cat) + if not c: + continue + over = c["hfMax"] > LIMITS["hf"][cat] + flag |= over + parts.append("%s hf %.1f/%.1f%s swing %.2f" % ( + {"hair": "头发", "skirt": "裙摆", "torso": "躯干", "other": "其它"}[cat], + c["hf"], c["hfMax"], "!" if over else "", c["swing"])) + if r.get("skirtInside") is not None: + parts.append("穿腿 %.1f%%" % (r["skirtInside"] * 100)) + if r.get("skirtGap"): + g = r["skirtGap"] + parts.append("张开 %.1f/%.1f/%.1f cm" % (g["mean"] * 100, g["p90"] * 100, g["max"] * 100)) + out.append(" %-9s %s" % (m, " | ".join(parts))) + if r.get("worst") and any(w["hf"] > LIMITS["hf"][w["cat"]] for w in r["worst"]): + for w in r["worst"]: + out.append(" %s:%s hf %.1f swing %.2f(%d 节,%.2f m)" % ( + w["cat"], w["chain"], w["hf"], w["swing"], w["joints"], w["length"])) + return out, flag + + +def main(argv=None): + ap = argparse.ArgumentParser(description="SpringBone 动态测试(three-vrm,无界面)") + ap.add_argument("paths", nargs="+", help=".vrm 文件或目录") + ap.add_argument("-j", "--jobs", type=int, default=4, help="并行数(每个文件一个 Node 进程)") + ap.add_argument("--motions", default="idle,walk_real,run", + help="动作:idle, walk_real, run, leg_raise, yaw_gentle, yaw_strong, walk, static") + ap.add_argument("--fps", type=float, default=60, help="物理帧率(默认 60)") + ap.add_argument("--jitter", type=float, default=0, help="帧时间抖动比例,如 0.3") + ap.add_argument("--json", help="把原始结果写成 JSON") + ap.add_argument("--strict", action="store_true", help="有超范围的数值时返回 1") + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + if not shutil.which("node"): + sys.exit("需要 Node.js(https://nodejs.org)") + if not os.path.isdir(os.path.join(HARNESS, "node_modules", "@pixiv", "three-vrm")): + sys.exit("先安装依赖:cd %s && npm install" % HARNESS) + files = list(iter_files(a.paths)) + todo = [f for f in files if testable(f)] + if len(todo) < len(files): + print("跳过 %d 个没有 SpringBone 或不是人形的文件" % (len(files) - len(todo))) + env = dict(os.environ, MOTIONS=a.motions, FPS=str(a.fps), JITTER=str(a.jitter), DETAIL="3") + with ThreadPoolExecutor(max_workers=max(1, a.jobs)) as ex: + results = list(ex.map(lambda f: run_one(f, env), todo)) + n_flag = 0 + for res in results: + lines, flag = fmt(res) + n_flag += flag + print("\n".join(lines)) + if a.json: + with open(a.json, "w", encoding="utf-8") as f: + json.dump(results, f, ensure_ascii=False, indent=1) + print("测试 %d 个文件,%d 个有超出参考范围的数值(标「!」)" % (len(results), n_flag)) + return 1 if (a.strict and n_flag) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/qa/harness/measure.mjs b/tools/qa/harness/measure.mjs new file mode 100644 index 0000000..4fe5d36 --- /dev/null +++ b/tools/qa/harness/measure.mjs @@ -0,0 +1,225 @@ +// SpringBone behaviour of one VRM, headless (three.js + three-vrm, no rendering). +// node measure.mjs model.vrm → one JSON object on stdout +// env: MOTIONS=idle,walk_real,run FPS=60 JITTER=0 (frame-time jitter ratio) DETAIL=3 +// +// rest: after 2 s standing still, how far each spring tip has moved from the bind pose +// (a correct setup stays put; large values = joints fight colliders / wrong rest dir) +// motions: per chain category (hair = under head/neck, skirt = under hips/legs, +// torso = under spine/chest/shoulders, other = arms etc.) +// hf tip energy above 8 Hz / chain length ×1000 — genuine shake (gait content < 7 Hz); +// mean and max over chains. Native VRoid/sample models: hair ≈ 2–16, skirt ≈ 3–58. +// swing peak tip deformation / chain length (anchor-local) +// skirtInside share of skirt joint samples inside the model's own leg colliders +// (counts rest overlap too — compare against idle) +import * as THREE from 'three'; +import fs from 'fs'; +import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'; +import { VRMLoaderPlugin, VRMUtils } from '@pixiv/three-vrm'; +import { MOTIONS, FRAMES } from './motions.mjs'; + +// Textures and MToon are irrelevant here and slow to decode in Node: strip them. +function stripGlb(buf) { + const jl = buf.readUInt32LE(12); + const json = JSON.parse(buf.slice(20, 20 + jl).toString('utf8')); + delete json.images; delete json.textures; delete json.samplers; + for (const m of json.materials || []) { + if (m.pbrMetallicRoughness) delete m.pbrMetallicRoughness.baseColorTexture; + delete m.extensions; delete m.normalTexture; delete m.emissiveTexture; delete m.occlusionTexture; + } + json.extensionsUsed = (json.extensionsUsed || []).filter((e) => e !== 'VRMC_materials_mtoon' && e !== 'KHR_texture_transform'); + if (json.extensions && json.extensions.VRM) json.extensions.VRM.materialProperties = []; + let js = Buffer.from(JSON.stringify(json)); + js = Buffer.concat([js, Buffer.alloc((4 - js.length % 4) % 4, 0x20)]); + const bin = buf.slice(20 + jl); + const h = Buffer.alloc(20); + h.writeUInt32LE(0x46546c67, 0); h.writeUInt32LE(2, 4); h.writeUInt32LE(20 + js.length + bin.length, 8); + h.writeUInt32LE(js.length, 12); h.writeUInt32LE(0x4e4f534a, 16); + const o = Buffer.concat([h, js, bin]); + return o.buffer.slice(o.byteOffset, o.byteOffset + o.byteLength); +} + +async function load(path) { + const loader = new GLTFLoader(); + loader.register((p) => new VRMLoaderPlugin(p)); + const warn = console.warn; console.warn = () => {}; // material-bind warnings: materials were stripped + try { + const vrm = await new Promise((r, j) => loader.parse(stripGlb(fs.readFileSync(path)), '', (g) => r(g.userData.vrm), j)); + if (vrm.meta && vrm.meta.metaVersion === '0') VRMUtils.rotateVRM0(vrm); + new THREE.Scene().add(vrm.scene); + vrm.update(0); vrm.scene.updateMatrixWorld(true); + return vrm; + } finally { console.warn = warn; } +} + +const wp = (o) => new THREE.Vector3().setFromMatrixPosition(o.matrixWorld); +const LEG = ['leftUpperLeg', 'rightUpperLeg', 'leftLowerLeg', 'rightLowerLeg']; +const LEG_CHILD = { leftUpperLeg: 'leftLowerLeg', rightUpperLeg: 'rightLowerLeg', leftLowerLeg: 'leftFoot', rightLowerLeg: 'rightFoot' }; + +async function restDrift(path) { + const vrm = await load(path); + const joints = vrm.springBoneManager ? [...vrm.springBoneManager.joints] : []; + if (!joints.length) return null; + const pos = () => joints.map((j) => wp(j.child || j.bone)); + const p0 = pos(); + for (let i = 0; i < 120; i++) vrm.update(1 / 60); + vrm.scene.updateMatrixWorld(true); + const p1 = pos(); + const d = joints.map((j, i) => [p1[i].distanceTo(p0[i]), j.bone.name]).sort((a, b) => b[0] - a[0]); + return { max: d[0][0], maxName: d[0][1], over1cm: d.filter((x) => x[0] > 0.01).length, joints: d.length, + top: d.slice(0, 5).map(([v, n]) => [n, +v.toFixed(4)]) }; +} + +function chainsOf(vrm) { + const h = vrm.humanoid, sbm = vrm.springBoneManager; + const roleOf = new Map(Object.keys(h.humanBones).map((r) => [h.getRawBoneNode(r), r])); + const joints = [...sbm.joints]; + const jbones = new Set(joints.map((j) => j.bone)); + const chains = []; + for (const j of joints) { + let p = j.bone.parent; + while (p && !jbones.has(p) && !roleOf.has(p)) p = p.parent; + if (p && jbones.has(p)) continue; // not a chain root + const path = [j]; + for (let cur = j; ;) { + const nx = joints.find((k) => { let q = k.bone.parent; while (q && q !== cur.bone && !jbones.has(q)) q = q.parent; return q === cur.bone; }); + if (!nx) break; + path.push(nx); cur = nx; + } + const tip = path[path.length - 1].child || path[path.length - 1].bone; + let anc = j.bone.parent; + while (anc && !roleOf.has(anc)) anc = anc.parent; + const role = anc ? roleOf.get(anc) : '?'; + const cat = ['head', 'neck', 'jaw'].includes(role) ? 'hair' + : (role === 'hips' || /Leg|Foot|Toes/.test(role)) ? 'skirt' + : ['spine', 'chest', 'upperChest', 'leftShoulder', 'rightShoulder'].includes(role) ? 'torso' : 'other'; + let L = 0, prev = wp(j.bone); + for (const k of path.slice(1)) { const q = wp(k.bone); L += q.distanceTo(prev); prev = q; } + L += wp(tip).distanceTo(prev); + chains.push({ root: j, tip, anchor: anc, cat, joints: path, L: Math.max(L, 0.02) }); + } + return { chains, roleOf }; +} + +async function measure(path, mname) { + const vrm = await load(path); + const h = vrm.humanoid, sbm = vrm.springBoneManager; + const { chains, roleOf } = chainsOf(vrm); + const loc = (c) => (c.anchor ? c.anchor.worldToLocal(wp(c.tip)) : wp(c.tip)); + // the leg itself: per leg bone the collider whose axis lies closest to the bone (skirt chains may also + // have shifted copies of it — see springbone.leg_proxy_shift — those are not the leg) + const legCols = []; + for (const role of LEG) { + const bone = h.getRawBoneNode(role), child = h.getRawBoneNode(LEG_CHILD[role]); + if (!bone) continue; + const end = child && child !== bone ? bone.worldToLocal(wp(child)) : new THREE.Vector3(0, -0.4, 0); + const seg = new THREE.Line3(new THREE.Vector3(), end); + let best = null; + for (const g of sbm.colliderGroups) for (const col of g.colliders) { + if (col.parent !== bone) continue; + const s = col.shape, m = s.tail ? s.offset.clone().add(s.tail).multiplyScalar(0.5) : s.offset.clone(); + const d = seg.closestPointToPoint(m, true, new THREE.Vector3()).distanceTo(m) - (s.radius || 0) * 0.01; + if (!best || d < best[0] - 1e-4) best = [d, col]; + } + if (best) legCols.push(best[1]); + } + const node = (n) => h.getNormalizedBoneNode(n); + // VRM 0.x normalized bones (after rotateVRM0) turn the other way round X and Z in three-vrm + const sg = vrm.meta && vrm.meta.metaVersion === '0' ? -1 : 1; + const rot = (n, x, y, z, order) => node(n).rotation.set(x * sg, y, z * sg, order); + for (let i = 0; i < 60; i++) vrm.update(1 / 60); // settle before measuring + vrm.scene.updateMatrixWorld(true); + const rest = chains.map(loc); + const traj = chains.map(() => []); + // skirt opening: neighbouring skirt chains (each chain's 2 nearest roots, within 2× the median + // nearest-root spacing) — how much further apart their tips get than at rest + const hipsY = wp(h.getRawBoneNode('hips')).y; + const ring = chains.filter((c) => (c.cat === 'skirt' && roleOf.get(c.anchor) === 'hips') + || (c.cat === 'torso' && wp(c.tip).y < hipsY)); + const pairs = []; + if (ring.length > 2) { + const rp = ring.map((c) => wp(c.root.bone)); + const near = ring.map((c, i) => rp.map((p, j) => [i === j ? Infinity : p.distanceTo(rp[i]), j]).sort((a, b) => a[0] - b[0])); + const med = near.map((n) => n[0][0]).sort((a, b) => a - b)[ring.length >> 1]; + const seen = new Set(); + near.forEach((n, i) => n.slice(0, 2).forEach(([d, j]) => { + const k = Math.min(i, j) + ':' + Math.max(i, j); + if (d < med * 2 && !seen.has(k)) { seen.add(k); pairs.push([ring[i], ring[j], wp(ring[i].tip).distanceTo(wp(ring[j].tip)), 0]); } + })); + } + let inside = 0, skirtTips = 0; + const N = FRAMES[mname]; + const fps = +(process.env.FPS || 60), jit = +(process.env.JITTER || 0); + let acc60 = 0, seed = 12345, nextDt = 1 / fps; + const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648); + for (let f = 0; f < N + 120; f++) { + const p = f < N ? MOTIONS[mname](f) : (mname === 'idle' ? MOTIONS[mname](N - 1) : {}); + rot('hips', 0, p.yaw || 0, p.roll || 0); + if (p.spineYaw != null) rot('spine', 0, p.spineYaw, 0); + vrm.scene.position.set(0, p.bob || 0, p.rootZ || 0); + rot('leftUpperLeg', p.lLeg || 0, 0, 0); rot('rightUpperLeg', p.rLeg || 0, 0, 0); + rot('leftLowerLeg', p.lKnee || 0, 0, 0); rot('rightLowerLeg', p.rKnee || 0, 0, 0); + if (p.armDown != null) { + const a = 1.22 * Math.min(1, p.armDown / 0.7); + rot('leftUpperArm', p.armSwingL || 0, 0, -a, 'XYZ'); rot('rightUpperArm', p.armSwingR || 0, 0, a, 'XYZ'); + rot('leftLowerArm', 0, p.armSwingL ? -0.3 : 0, 0); rot('rightLowerArm', 0, p.armSwingR ? 0.3 : 0, 0); + } + // physics at FPS (optionally jittered), motion sampled at 60 Hz + acc60 += 1 / 60; + while (acc60 >= nextDt - 1e-9) { vrm.update(nextDt); acc60 -= nextDt; nextDt = (1 / fps) * (1 + jit * (rnd() * 2 - 1)); } + vrm.scene.updateMatrixWorld(true); + chains.forEach((c, i) => traj[i].push(loc(c).sub(rest[i]))); + if (f < N) for (const p of pairs) p[3] = Math.max(p[3], wp(p[0].tip).distanceTo(wp(p[1].tip)) - p[2]); + if (legCols.length) for (const c of chains) if (c.cat === 'skirt') { + for (const j of c.joints) { + const t = wp(j.child || j.bone); skirtTips++; + for (const col of legCols) { if (col.shape.calculateCollision(col.colliderMatrix, t, 0, new THREE.Vector3()) < -0.005) { inside++; c.inside = (c.inside || 0) + 1; break; } } + } + } + } + const W0 = (mname === 'walk_real' || mname === 'run') ? 60 : 0; // skip the start-up transient + const hfOf = (i) => { // spectral energy above 8 Hz + const T = traj[i], hi = Math.min(N, T.length), n = hi - W0; + if (n < 32) return 0; + let e = 0; + for (const ax of ['x', 'y', 'z']) { + const xs = []; for (let t = W0; t < hi; t++) xs.push(T[t][ax]); + const mean = xs.reduce((a, b) => a + b, 0) / n; + for (let k = Math.ceil(8 * n / 60); k <= n / 2; k++) { + let re = 0, im = 0; + for (let t = 0; t < n; t++) { const a = 2 * Math.PI * k * t / n; re += (xs[t] - mean) * Math.cos(a); im -= (xs[t] - mean) * Math.sin(a); } + e += (re * re + im * im) * 2 / (n * n); + } + } + return Math.sqrt(e) / chains[i].L * 1000; + }; + const hf = chains.map((c, i) => hfOf(i)); + const swingOf = (i) => Math.max(0, ...traj[i].slice(W0, N).map((v) => v.length())) / chains[i].L; + const out = { cats: {} }; + for (const cat of ['hair', 'skirt', 'torso', 'other']) { + const ids = chains.map((c, i) => (c.cat === cat ? i : -1)).filter((i) => i >= 0); + if (!ids.length) continue; + out.cats[cat] = { n: ids.length, hf: ids.reduce((a, i) => a + hf[i], 0) / ids.length, + hfMax: Math.max(...ids.map((i) => hf[i])), swing: Math.max(...ids.map(swingOf)) }; + } + const nd = +(process.env.DETAIL || 3); + out.skirtInside = skirtTips ? inside / skirtTips : null; + if (inside) out.insideWorst = chains.filter((c) => c.inside).sort((a, b) => b.inside - a.inside).slice(0, nd) + .map((c) => [c.root.bone.name, +(c.inside / c.joints.length / (N + 120)).toFixed(3)]); + if (pairs.length) { + const g = pairs.map((p) => p[3]).sort((a, b) => a - b); + out.skirtGap = { pairs: g.length, mean: g.reduce((a, b) => a + b, 0) / g.length, p90: g[Math.floor(g.length * 0.9)], max: g[g.length - 1], + worst: pairs.sort((a, b) => b[3] - a[3]).slice(0, nd).map((p) => [p[0].root.bone.name, p[1].root.bone.name, +p[2].toFixed(3), +p[3].toFixed(3)]) }; + } + out.worst = chains.map((c, i) => [hf[i], i]).sort((a, b) => b[0] - a[0]).slice(0, nd) + .map(([v, i]) => ({ cat: chains[i].cat, chain: chains[i].root.bone.name, hf: +v.toFixed(2), swing: +swingOf(i).toFixed(3), + joints: chains[i].joints.length, length: +chains[i].L.toFixed(3) })); + return out; +} + +const path = process.argv[2]; +if (!path) { console.error('usage: node measure.mjs model.vrm'); process.exit(2); } +const result = { file: path, rest: await restDrift(path), motions: {} }; +if (result.rest) { + for (const m of (process.env.MOTIONS || 'idle,walk_real,run').split(',')) result.motions[m] = await measure(path, m); +} +process.stdout.write(JSON.stringify(result) + '\n'); diff --git a/tools/qa/harness/motions.mjs b/tools/qa/harness/motions.mjs new file mode 100644 index 0000000..1fced55 --- /dev/null +++ b/tools/qa/harness/motions.mjs @@ -0,0 +1,42 @@ +// Test motions for measure.mjs. Each returns per-frame pose params (radians), 60 fps, +// applied to the VRM's normalized humanoid bones. +// yaw: hips rotation about +Y +// lLeg/rLeg: thigh pitch about +X (negative = leg forward), lKnee/rKnee: knee bend (+X) +const smooth = (t) => t * t * (3 - 2 * t); + +export const MOTIONS = { + static: (f) => ({}), + yaw_gentle: (f) => ({ yaw: f < 150 ? Math.sin(f / 60 * Math.PI * 2 * 0.8) * 0.35 : 0 }), + yaw_strong: (f) => ({ yaw: f < 150 ? Math.sin(f / 60 * Math.PI * 2 * 1.2) * 0.8 : 0 }), + leg_raise: (f) => { + const k = f < 40 ? smooth(f / 40) : f < 100 ? 1 : f < 140 ? smooth(1 - (f - 100) / 40) : 0; + return { lLeg: -1.2 * k, lKnee: 1.0 * k }; + }, + walk: (f) => { + const s = Math.sin(f / 60 * Math.PI * 2 * 0.9); + const a = f < 180 ? 1 : 0; + return { + lLeg: -0.5 * s * a, rLeg: 0.5 * s * a, + lKnee: Math.max(0, s) * 0.6 * a, rKnee: Math.max(0, -s) * 0.6 * a, + yaw: Math.sin(f / 60 * Math.PI * 2 * 0.9) * 0.08 * a, + }; + }, +}; +// idle: arms lowered from the T-pose rest over 1 s (armDown 0.7 ≈ 70°), slight sway. +MOTIONS.idle = (f) => ({ armDown: 0.7 * smooth(Math.min(1, f / 60)), yaw: Math.sin(f / 60 * Math.PI * 2 * 0.25) * 0.05 }); +// Realistic gait with root motion (forward along +Z), pelvis bob/twist, arm swing. +// rootZ: metres travelled; bob: pelvis vertical offset; roll: pelvis roll; arm: forward swing +function gait(f, speed, freq, thigh, knee, bob, armSwing) { + const t = f / 60, ph = t * Math.PI * 2 * freq; + const s = Math.sin(ph); + const kneeL = knee * Math.max(0, Math.sin(ph + 0.9)), kneeR = knee * Math.max(0, Math.sin(ph + 0.9 + Math.PI)); + return { + rootZ: speed * t, bob: -bob * Math.cos(2 * ph), + yaw: 0.08 * s, roll: 0.04 * Math.sin(2 * ph), spineYaw: -0.1 * s, + lLeg: -thigh * s, rLeg: thigh * s, lKnee: 0.1 + kneeL, rKnee: 0.1 + kneeR, + armDown: 0.7 * smooth(Math.min(1, f / 40)), armSwingL: armSwing * s, armSwingR: -armSwing * s, + }; +} +MOTIONS.walk_real = (f) => (f < 300 ? gait(f, 1.2, 0.9, 0.45, 0.9, 0.025, 0.35) : { ...gait(299, 1.2, 0.9, 0, 0, 0, 0), rootZ: 1.2 * 5, lLeg: 0, rLeg: 0, lKnee: 0, rKnee: 0, yaw: 0, roll: 0, spineYaw: 0, bob: 0, armSwingL: 0, armSwingR: 0 }); +MOTIONS.run = (f) => (f < 240 ? gait(f, 3.0, 1.4, 0.8, 1.6, 0.05, 0.7) : { rootZ: 3.0 * 4, armDown: 0.7 }); +export const FRAMES = { walk_real: 300, run: 240, idle: 240, static: 120, yaw_gentle: 240, yaw_strong: 240, leg_raise: 200, walk: 270 }; diff --git a/tools/qa/harness/package-lock.json b/tools/qa/harness/package-lock.json new file mode 100644 index 0000000..edc8702 --- /dev/null +++ b/tools/qa/harness/package-lock.json @@ -0,0 +1,157 @@ +{ + "name": "vrmify-qa-harness", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "vrmify-qa-harness", + "license": "GPL-3.0", + "dependencies": { + "@pixiv/three-vrm": "3.5.5", + "three": "0.169.0" + } + }, + "node_modules/@pixiv/three-vrm": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm/-/three-vrm-3.5.5.tgz", + "integrity": "sha512-RPXy7jYAXs704NIpZlosB0U2ENu21G9DrqGWdQgRe8dShaCo1ugpj+6BVPRCy91nt+MPMA96j5rbsSzEl0HlQA==", + "license": "MIT", + "dependencies": { + "@pixiv/three-vrm-core": "3.5.5", + "@pixiv/three-vrm-materials-hdr-emissive-multiplier": "3.5.5", + "@pixiv/three-vrm-materials-mtoon": "3.5.5", + "@pixiv/three-vrm-materials-v0compat": "3.5.5", + "@pixiv/three-vrm-node-constraint": "3.5.5", + "@pixiv/three-vrm-springbone": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-core": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-core/-/three-vrm-core-3.5.5.tgz", + "integrity": "sha512-jjaXZbMVRsk2HAGVxqDLmSJyGOJqbMcJpuTHR1TY/TN1FxiKdAzSqdr/ZUcczYipNf8IL9vDT9NX2XmWj+ybRQ==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrm-0.0": "3.5.5", + "@pixiv/types-vrmc-vrm-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-materials-hdr-emissive-multiplier": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-hdr-emissive-multiplier/-/three-vrm-materials-hdr-emissive-multiplier-3.5.5.tgz", + "integrity": "sha512-XnHEqpY4ctYMucpeRcptdphOe0RrW7V5fUvojasD8Ja4MTjjrjCNFxsAvp3+HBkPZbkTM2sDCjJBJNzxN1scrA==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-materials-mtoon": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-mtoon/-/three-vrm-materials-mtoon-3.5.5.tgz", + "integrity": "sha512-7lThHf4OKBOsVenD+R6L6HffNUlKO3Twnhr3+z77MnUsSzsOanjVKJtjSIly9QJ6hgl8YJmI6RnxCKqXcpplog==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrm-0.0": "3.5.5", + "@pixiv/types-vrmc-materials-mtoon-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-materials-v0compat": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-materials-v0compat/-/three-vrm-materials-v0compat-3.5.5.tgz", + "integrity": "sha512-NjsTK4P4qdcr+RoL2gEUNgF2CY/aplNvyHHxI99N7D6CxDZ2H93FQ9aIuLCABj5b+4CIvldWMCcnS7YuLIr3Lw==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrm-0.0": "3.5.5", + "@pixiv/types-vrmc-materials-mtoon-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-node-constraint": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-node-constraint/-/three-vrm-node-constraint-3.5.5.tgz", + "integrity": "sha512-+ShEXioZ5Ctf0EZ5ZViZ4n0jhV/qtJRH0Juw8nRnMNODZXDSr+B3An2lrfRoMhowCzG63GiUG4lXWV9noMXosA==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrmc-node-constraint-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/three-vrm-springbone": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/three-vrm-springbone/-/three-vrm-springbone-3.5.5.tgz", + "integrity": "sha512-GWAWrIegGH/u1ZA+Es03Qzc2yafrQOrhtal9jzUIAgU8Wm2DYuqAABOY+du/9RpBRK8D4T8DBPvRGQqvfrQ/uA==", + "license": "MIT", + "dependencies": { + "@pixiv/types-vrm-0.0": "3.5.5", + "@pixiv/types-vrmc-springbone-1.0": "3.5.5", + "@pixiv/types-vrmc-springbone-extended-collider-1.0": "3.5.5" + }, + "peerDependencies": { + "three": ">=0.137" + } + }, + "node_modules/@pixiv/types-vrm-0.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrm-0.0/-/types-vrm-0.0-3.5.5.tgz", + "integrity": "sha512-2S/0jswMjJTwL9ky8YzDR0CIaP6ZmE+HFuyW/0h+SA+awELf+J7WGgC8lTLM1MXzokO7Z2YVljU2F0fEhlKDIQ==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-materials-hdr-emissive-multiplier-1.0/-/types-vrmc-materials-hdr-emissive-multiplier-1.0-3.5.5.tgz", + "integrity": "sha512-IuHw9ehXt2bymqfdFV+f2cCXo8kvJUfh0Zuut8qmKXoEb7HVyLGIQyS4TcQHG5yY22UTWHI1Axo5tQv35lPTgQ==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-materials-mtoon-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-materials-mtoon-1.0/-/types-vrmc-materials-mtoon-1.0-3.5.5.tgz", + "integrity": "sha512-GFVuksAJVhrWTXYmI/ucNsE611/d8N6BoZrzhUAAINndt98loyzapW2+DJu+GsUBO5yxd+vLsL0FB16XD9+TGg==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-node-constraint-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-node-constraint-1.0/-/types-vrmc-node-constraint-1.0-3.5.5.tgz", + "integrity": "sha512-8EbJ1uzkn9yJQarCChmpG12+mc2c7PimHvQ8H6/tMh/hqp5NtJND0z2lR2KeVxw9A3M+TpF+xgImhLBxGjqwzQ==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-springbone-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-springbone-1.0/-/types-vrmc-springbone-1.0-3.5.5.tgz", + "integrity": "sha512-gRQ5Y7PaGiMefvOrJ3hvoSPqpA67jiwyhwh8ItjsPi3yri/Hn3CeXplW3Cbx3ZPbfu+C3Q2MCRa2TqAUOjeMRA==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-springbone-extended-collider-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-springbone-extended-collider-1.0/-/types-vrmc-springbone-extended-collider-1.0-3.5.5.tgz", + "integrity": "sha512-+6RxLaAvVguP7upjS/OT4viNPWvac1HBRQY1nmdvfYNQuCMdrMsCZqvy2af0Fcjnda4V9JbKFIpZDC0lrw1+uQ==", + "license": "MIT" + }, + "node_modules/@pixiv/types-vrmc-vrm-1.0": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@pixiv/types-vrmc-vrm-1.0/-/types-vrmc-vrm-1.0-3.5.5.tgz", + "integrity": "sha512-WnemHHo2375BcBdumEhvrupZzsMSzTfdWlokmV9sUX2oC+OAQqJFfBjLF8ppkOhzHpl4MAPJqEfuhBJtNPm9ww==", + "license": "MIT" + }, + "node_modules/three": { + "version": "0.169.0", + "resolved": "https://registry.npmjs.org/three/-/three-0.169.0.tgz", + "integrity": "sha512-Ed906MA3dR4TS5riErd4QBsRGPcx+HBDX2O5yYE5GqJeFQTPU+M56Va/f/Oph9X7uZo3W3o4l2ZhBZ6f6qUv0w==", + "license": "MIT" + } + } +} diff --git a/tools/qa/harness/package.json b/tools/qa/harness/package.json new file mode 100644 index 0000000..d0ff2cc --- /dev/null +++ b/tools/qa/harness/package.json @@ -0,0 +1,11 @@ +{ + "name": "vrmify-qa-harness", + "private": true, + "description": "SpringBone behaviour tests for converted VRM files (three.js + three-vrm, headless)", + "type": "module", + "license": "GPL-3.0", + "dependencies": { + "@pixiv/three-vrm": "3.5.5", + "three": "0.169.0" + } +} diff --git a/tools/qa/snapshots.py b/tools/qa/snapshots.py new file mode 100644 index 0000000..a46e578 --- /dev/null +++ b/tools/qa/snapshots.py @@ -0,0 +1,357 @@ +# -*- coding: utf-8 -*- +"""表情截图对照表:每个模型一行——全身、脸、各个表情预设、口型、眨眼、视线四个方向。 + + python tools/qa/snapshots.py a.vrm -o a.png + python tools/qa/snapshots.py 旧版/a.vrm 新版/a.vrm -o 对比.png 一个输入一行,上下对照 + python tools/qa/snapshots.py model/角色/角色.pmx -o a.png 非 VRM 先用当前代码转一份(临时目录) + python tools/qa/snapshots.py a.vrm --custom -o a.png 再加上模型自己的自定义表情 + +用无界面的 Edge / Chrome 渲染,渲染部分就是界面预览用的 ui/viewer/viewer-core.js(three-vrm + MToon), +和程序里看到的一样。改表情相关代码前后各拍一张,比对哪里变了;也可以把 tools/regress.py 的样本拍下来看。 +模型自己没有的表情格子标「无」,不会拿中性脸冒充。 + +需要本机装了 Edge 或 Chrome(--browser 指定路径)。WebGL 走软件渲染(SwiftShader),不依赖显卡。 +""" +import argparse +import base64 +import json +import os +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import urllib.parse +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +VIEWER = os.path.join(ROOT, "ui", "viewer") +for _p in ("convert", "formats"): + _d = os.path.join(ROOT, _p) + if _d not in sys.path: + sys.path.insert(0, _d) + +# 列:[名字, 机位, 表情 {名字: 值}, 视线 (yaw, pitch) 或 None] +SHOTS = [["全身", "body", {}, None], ["脸", "face", {}, None]] +SHOTS += [[n, "face", {n: 1.0}, None] for n in ("happy", "angry", "sad", "relaxed", "surprised", + "aa", "ih", "ou", "ee", "oh", "blink", "blinkLeft", "blinkRight")] +SHOTS += [["look" + k, "face", {}, v] for k, v in + (("Up", (0, 90)), ("Down", (0, -90)), ("Left", (90, 0)), ("Right", (-90, 0)))] + +PAGE = r""" + + + +""" + + +def find_browser(path=None): + cands = [path] if path else [] + for env in ("PROGRAMFILES(X86)", "PROGRAMFILES", "LOCALAPPDATA"): + base = os.environ.get(env) + if base: + cands += [os.path.join(base, "Microsoft", "Edge", "Application", "msedge.exe"), + os.path.join(base, "Google", "Chrome", "Application", "chrome.exe")] + cands += [shutil.which(n) for n in ("msedge", "chrome", "google-chrome", "chromium")] + return next((c for c in cands if c and os.path.isfile(c)), None) + + +# ---- 浏览器进程的清理 +# 只结束浏览器主进程是不够的:Windows 上它的子进程(GPU、渲染进程)会留下来,软件渲染的 GPU 进程 +# 一直占满一个核。所以结束时连同整棵进程树一起结束;每次开始前再按临时配置目录名找出以前遗留的进程。 +PROFILE_PREFIX = "vrmify_snap_profile_" +OWNER_FILE = "owner.pid" # 配置目录里记着是哪个进程开的浏览器,用来判断是不是遗留的 + + +def browser_procs(marker=PROFILE_PREFIX): + """命令行里带 marker 的进程 → [(进程号, 命令行)](截图浏览器的命令行里有它的临时配置目录)。""" + try: + if os.name == "nt": + ps = ("Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -ne $PID -and " + "$_.CommandLine -like '*%s*' } | ForEach-Object { \"$($_.ProcessId)`t$($_.CommandLine)\" }" % marker) + out = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", ps], + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60).stdout + rows = [ln.split("\t", 1) for ln in out.splitlines() if "\t" in ln] + else: + out = subprocess.run(["ps", "-eo", "pid=,args="], capture_output=True, text=True, timeout=60).stdout + rows = [ln.strip().split(None, 1) for ln in out.splitlines() if marker in ln] + return [(int(p), cmd) for p, cmd in rows if p.strip().isdigit() and int(p) != os.getpid()] + except (OSError, subprocess.SubprocessError, ValueError): + return [] + + +def _kill_pid(pid): + """结束进程和它的子进程。""" + try: + if os.name == "nt": + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, timeout=60) + else: + os.kill(pid, signal.SIGKILL) + except (OSError, subprocess.SubprocessError): + pass + + +def _alive(pid): + try: + if os.name == "nt": + out = subprocess.run(["tasklist", "/FI", "PID eq %d" % pid, "/NH", "/FO", "CSV"], + capture_output=True, text=True, errors="replace", timeout=60).stdout + return '"%d"' % pid in out + os.kill(pid, 0) + return True + except (OSError, subprocess.SubprocessError): + return False + + +def stop_browser(proc, prof): + """结束这次截图的浏览器:整棵进程树;主进程先退出了的、树已经断开的,按配置目录名再找一遍。""" + if os.name == "nt": + _kill_pid(proc.pid) + else: + try: + os.killpg(proc.pid, signal.SIGKILL) # 浏览器单独一个进程组(start_new_session) + except OSError: + pass + try: + proc.wait(10) + except subprocess.TimeoutExpired: + proc.kill() + for pid, _ in browser_procs(os.path.basename(prof)): + _kill_pid(pid) + + +def cleanup_stale(tmp=None): + """以前遗留的截图浏览器和临时配置目录(异常退出、或者旧版本没关干净的)。正在跑的别的截图 + (配置目录里记的进程还活着)不动。""" + tmp = tmp or tempfile.gettempdir() + live = set() + try: + names = [n for n in os.listdir(tmp) if n.startswith(PROFILE_PREFIX)] + except OSError: + names = [] + for n in names: + try: + with open(os.path.join(tmp, n, OWNER_FILE)) as f: + owner = int(f.read().strip() or 0) + except (OSError, ValueError): + owner = 0 + if owner and owner != os.getpid() and _alive(owner): + live.add(n) + for pid, cmd in browser_procs(): + m = re.search(re.escape(PROFILE_PREFIX) + r"[^\s\"'\\/]*", cmd) + if m and m.group(0) not in live: + _kill_pid(pid) + for n in names: + if n not in live: + shutil.rmtree(os.path.join(tmp, n), ignore_errors=True) + + +def row_label(path, all_paths): + """行标签:文件名(不带扩展名);有同名的行时前面加上所在文件夹名。""" + def short(p): + return os.path.splitext(os.path.basename(p.split(" · ")[0]))[0] + (" · " + p.split(" · ")[1] if " · " in p else "") + if sum(short(q) == short(path) for q in all_paths) > 1: + return os.path.basename(os.path.dirname(os.path.abspath(path.split(" · ")[0]))) + "/" + short(path) + return short(path) + + +def to_vrms(paths, tmp, log): + """→ [(行标签, VRM 路径)];不是 VRM 的先用当前代码转(临时目录,按 VRM 1.0 的默认选项)。""" + import pipeline + out = [] + for i, p in enumerate(paths): + if p.lower().endswith(".vrm"): + out.append((p, p)) + continue + d = os.path.join(tmp, "conv%d" % i) + log("转换 %s …" % os.path.basename(p)) + vrms = [v for v in pipeline.convert_file(p, {}, out_dir=d) if v.lower().endswith(".vrm")] + if not vrms: + raise SystemExit("%s 没有转出 VRM" % p) + out += [(p if len(vrms) == 1 else "%s · %s" % (p, os.path.basename(v)), v) for v in vrms] + return out + + +def shoot(models, out_png, size=224, custom=False, browser=None, timeout=300, cols=len(SHOTS)): + exe = find_browser(browser) + if not exe: + raise SystemExit("找不到 Edge / Chrome(用 --browser 指定路径)") + files = {"/model/%d.vrm" % i: p for i, (_, p) in enumerate(models)} + models = [(row_label(label, [m[0] for m in models]), p) for label, p in models] + job = {"size": size, "custom": custom, "shots": SHOTS, "cols": cols, + "models": [{"url": "/model/%d.vrm" % i, "name": os.path.basename(p), "label": label} + for i, (label, p) in enumerate(models)]} + result, done = {}, threading.Event() + + class H(SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, data, ctype): + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + p = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path) + if p == "/": + return self._send(PAGE.encode("utf-8"), "text/html; charset=utf-8") + if p == "/job": + return self._send(json.dumps(job, ensure_ascii=False).encode("utf-8"), "application/json") + if p in files: + with open(files[p], "rb") as f: + return self._send(f.read(), "model/gltf-binary") + return super().do_GET() + + def translate_path(self, path): + p = urllib.parse.unquote(urllib.parse.urlsplit(path).path) + parts = [x for x in p[len("/viewer/"):].split("/") if x not in ("", ".", "..")] if p.startswith("/viewer/") else [] + return os.path.join(VIEWER, *parts) if parts else os.path.join(VIEWER, "__none__") + + def do_POST(self): + n = int(self.headers.get("Content-Length") or 0) + result.update(json.loads(self.rfile.read(n).decode("utf-8"))) + self._send(b"{}", "application/json") + done.set() + + cleanup_stale() + srv = ThreadingHTTPServer(("127.0.0.1", 0), H) + threading.Thread(target=srv.serve_forever, daemon=True).start() + prof = tempfile.mkdtemp(prefix=PROFILE_PREFIX) + with open(os.path.join(prof, OWNER_FILE), "w") as f: + f.write(str(os.getpid())) + url = "http://127.0.0.1:%d/" % srv.server_address[1] + proc = None + try: + proc = subprocess.Popen([exe, "--headless=new", "--use-angle=swiftshader", "--enable-unsafe-swiftshader", + "--no-first-run", "--no-default-browser-check", "--disable-extensions", + "--user-data-dir=" + prof] + # Linux 的 CI(Ubuntu 24.04 限制了非特权用户命名空间)里 Chrome 的沙箱起不来;只加载本地页面 + + ([] if os.name == "nt" else ["--no-sandbox"]) + [url], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + start_new_session=os.name != "nt") + if not done.wait(timeout): + raise SystemExit("%d 秒内浏览器没有交回截图" % timeout) + finally: + if proc is not None: + stop_browser(proc, prof) + srv.shutdown() + srv.server_close() + shutil.rmtree(prof, ignore_errors=True) + if "error" in result: + raise SystemExit("页面出错:\n" + result["error"]) + data = base64.b64decode(result["png"].split(",", 1)[1]) + os.makedirs(os.path.dirname(os.path.abspath(out_png)), exist_ok=True) + with open(out_png, "wb") as f: + f.write(data) + return out_png + + +def main(argv=None): + ap = argparse.ArgumentParser(description="表情截图对照表(每个输入一行)") + ap.add_argument("inputs", nargs="+", help=".vrm,或任何能转换的模型(先用当前代码转)") + ap.add_argument("-o", "--out", default="snapshots.png", help="输出 PNG") + ap.add_argument("--size", type=int, default=224, help="每格边长(像素)") + ap.add_argument("--custom", action="store_true", help="再加上模型自己的自定义表情") + ap.add_argument("--cols", type=int, default=len(SHOTS), help="每段多少列,超出的换到下一段(默认 %d,正好放下标准的一组)" % len(SHOTS)) + ap.add_argument("--browser", help="Edge / Chrome 的路径(默认自动找)") + ap.add_argument("--timeout", type=int, default=300) + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + tmp = tempfile.mkdtemp(prefix="vrmify_snap_") + try: + models = to_vrms(a.inputs, tmp, print) + print("截图 %d 个模型 …" % len(models)) + shoot(models, a.out, a.size, a.custom, a.browser, a.timeout, a.cols) + print("已写出 %s" % os.path.abspath(a.out)) + finally: + shutil.rmtree(tmp, ignore_errors=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/regress.py b/tools/regress.py new file mode 100644 index 0000000..0142507 --- /dev/null +++ b/tools/regress.py @@ -0,0 +1,187 @@ +# -*- coding: utf-8 -*- +"""真实模型的回归检查:改转换代码前后,同样的输入输出是否一致。 + + python tools/regress.py record 模型.pmx|目录 ... [--spec 0x] 记下基准(golden) + python tools/regress.py check 用当前代码重转、对比基准 + python tools/regress.py check --code 另一份代码的目录 用别的代码(例如 git worktree)转 + +基准存在 tests/.golden/(不进仓库:模型的许可不允许再分发,衍生的数据也只留在本机): +manifest.json 记样本路径和选项,每个样本一个 JSON(glTF JSON 全文 + 二进制块 sha256)。 +check 时每个样本都会:转换 → check_vrm 结构 / Schema 校验 → 和基准对比,列出 JSON 里 +不同的路径(最多 20 条)和二进制块是否一致;有错误或差异时退出码为 1。 +对比只是提示「哪里变了」,变化是不是预期的要自己判断,确认后重新 record。 +""" +import argparse +import hashlib +import json +import os +import shutil +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +GOLDEN = os.path.join(ROOT, "tests", ".golden") +sys.path.insert(0, os.path.join(HERE, "qa")) + + +def _use_code(root): + """让 import pmx2vrm / vrmio 来自 root 这份代码。""" + for p in (os.path.join(root, "formats"), os.path.join(root, "convert")): + sys.path.insert(0, p) + + +def _convert(pmx, out, spec): + import pmx2vrm + pmx2vrm.convert(pmx, out, spec="1.0" if spec == "1.0" else "0.x", + meta={"title": os.path.splitext(os.path.basename(pmx))[0]}) + + +def _fingerprint(path): + import vrmio + g, b = vrmio.read_glb(path) + return {"json": g, "bin_sha256": hashlib.sha256(b).hexdigest(), "bin_len": len(b), + "size": os.path.getsize(path)} + + +def _diff(a, b, path="", out=None, limit=20): + out = [] if out is None else out + if len(out) >= limit: + return out + if isinstance(a, dict) and isinstance(b, dict): + for k in list(a) + [k for k in b if k not in a]: + if k not in b: + out.append("- %s/%s" % (path, k)) + elif k not in a: + out.append("+ %s/%s" % (path, k)) + else: + _diff(a[k], b[k], "%s/%s" % (path, k), out, limit) + if len(out) >= limit: + break + elif isinstance(a, list) and isinstance(b, list): + if len(a) != len(b): + out.append("~ %s 长度 %d → %d" % (path, len(a), len(b))) + for i, (x, y) in enumerate(zip(a, b)): + _diff(x, y, "%s/%d" % (path, i), out, limit) + if len(out) >= limit: + break + elif a != b: + out.append("~ %s:%s → %s" % (path, json.dumps(a, ensure_ascii=False)[:60], + json.dumps(b, ensure_ascii=False)[:60])) + return out + + +def _samples(paths): + out = [] + for p in paths: + if os.path.isdir(p): + for d, _, fs in os.walk(p): + out += [os.path.join(d, f) for f in sorted(fs) if f.lower().endswith(".pmx")] + elif p.lower().endswith(".pmx"): + out.append(p) + return [os.path.abspath(p) for p in out] + + +def _key(path, spec): + return hashlib.md5(("%s|%s" % (os.path.normcase(path), spec)).encode("utf-8")).hexdigest()[:12] + + +def record(args): + samples = _samples(args.paths) + if not samples: + print("没有找到 PMX") + return 1 + os.makedirs(GOLDEN, exist_ok=True) + tmp = tempfile.mkdtemp(prefix="m2v_regress_") + manifest = {"spec": args.spec, "samples": samples, "recorded": time.strftime("%Y-%m-%d %H:%M"), + "code": os.path.abspath(args.code)} + try: + for n, pmx in enumerate(samples, 1): + out = os.path.join(tmp, "%d.vrm" % n) + t0 = time.time() + _convert(pmx, out, args.spec) + with open(os.path.join(GOLDEN, _key(pmx, args.spec) + ".json"), "w", encoding="utf-8") as f: + json.dump(_fingerprint(out), f, ensure_ascii=False) + print("[%d/%d] %.1fs %s" % (n, len(samples), time.time() - t0, pmx)) + finally: + shutil.rmtree(tmp, ignore_errors=True) + with open(os.path.join(GOLDEN, "manifest.json"), "w", encoding="utf-8") as f: + json.dump(manifest, f, ensure_ascii=False, indent=1) + print("基准已记录:%d 个样本 → %s" % (len(samples), GOLDEN)) + return 0 + + +def check(args): + import check_vrm + try: + with open(os.path.join(GOLDEN, "manifest.json"), encoding="utf-8") as f: + manifest = json.load(f) + except OSError: + print("还没有基准:先运行 python tools/regress.py record <模型或目录>") + return 1 + validators, why = (None, "--no-schema") if args.no_schema else check_vrm.load_validators() + if why: + print("提示:" + why) + spec = manifest["spec"] + tmp = tempfile.mkdtemp(prefix="m2v_regress_") + bad = 0 + try: + for n, pmx in enumerate(manifest["samples"], 1): + name = os.path.basename(pmx) + gpath = os.path.join(GOLDEN, _key(pmx, spec) + ".json") + if not os.path.isfile(pmx) or not os.path.isfile(gpath): + print("[%d] 跳过(找不到样本或基准):%s" % (n, pmx)) + continue + out = os.path.join(tmp, "%d.vrm" % n) + t0 = time.time() + try: + _convert(pmx, out, spec) + except Exception as e: # noqa: BLE001 + print("✗ [%d] %s 转换失败:%s: %s" % (n, name, type(e).__name__, e)) + bad += 1 + continue + errs, _, _ = check_vrm.check(out, validators) + with open(gpath, encoding="utf-8") as f: + gold = json.load(f) + cur = _fingerprint(out) + diffs = _diff(gold["json"], cur["json"]) + same_bin = gold["bin_sha256"] == cur["bin_sha256"] + ok = not errs and not diffs and same_bin + bad += not ok + print("%s [%d] %.1fs %s %.2f → %.2f MB" % ("✓" if ok else "✗", n, time.time() - t0, name, + gold["size"] / 1048576.0, cur["size"] / 1048576.0)) + for e in errs[:10]: + print(" 校验:" + e) + for d in diffs: + print(" JSON " + d) + if not same_bin: + print(" 二进制块不同(%d → %d 字节)" % (gold["bin_len"], cur["bin_len"])) + finally: + shutil.rmtree(tmp, ignore_errors=True) + print("对比 %d 个样本,%d 个有差异或错误" % (len(manifest["samples"]), bad)) + return 1 if bad else 0 + + +def main(argv=None): + ap = argparse.ArgumentParser(description="真实模型回归检查") + sub = ap.add_subparsers(dest="cmd", required=True) + r = sub.add_parser("record", help="记录基准") + r.add_argument("paths", nargs="+", help="PMX 文件或目录") + r.add_argument("--spec", default="1.0", choices=["1.0", "0x"]) + c = sub.add_parser("check", help="用当前代码重转并对比基准") + c.add_argument("--no-schema", action="store_true") + for p in (r, c): + p.add_argument("--code", default=ROOT, help="用哪份代码转换(默认本仓库)") + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + _use_code(a.code) + import pmx2vrm # noqa: F401 先从 --code 导入(check_vrm 会把本仓库的路径插到最前面) + return record(a) if a.cmd == "record" else check(a) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/scan_models.py b/tools/scan_models.py new file mode 100644 index 0000000..bdcc9de --- /dev/null +++ b/tools/scan_models.py @@ -0,0 +1,113 @@ +# -*- coding: utf-8 -*- +"""用本机的真实模型跑一遍骨骼处理和自检(不写 VRM,几秒一个),看哪些模型会在转换日志里报问题。 + + python tools/scan_models.py 目录或文件 ... # 目录递归找 PMX 和压缩包(压缩包在临时目录里解开) + python tools/scan_models.py ~/Downloads -o 结果.txt + +每个 PMX 一行:合并的付与骨数、按比例拆权重的骨数、自检问题;有问题的下面列出来。 +改骨骼相关的代码前后各跑一次对比,发版前跑一次。有自检问题时退出码为 1。 +""" +import argparse +import glob +import os +import shutil +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(HERE) +for _p in ("convert", "formats"): + sys.path.insert(0, os.path.join(ROOT, _p)) +import pipeline # noqa: E402 +import pmxio # noqa: E402 +from vrmconv import checks, mesh, skeleton # noqa: E402 + + +def pmx_files(paths, tmp): + """→ (PMX 路径, 显示名);压缩包解到 tmp 下,包里套包再解一层。""" + def inside(arc, d): + for q in pipeline.find_inputs(d): + k = pipeline.classify(q) + if k == "pmx": + yield q, os.path.basename(arc) + "/" + os.path.relpath(q, d) + elif k in pipeline.ARCHIVES: + sub = tempfile.mkdtemp(dir=tmp) + pipeline.extract_archive(q, k, sub) + yield from ((f, os.path.basename(arc) + "/" + os.path.relpath(f, sub)) + for f in glob.glob(os.path.join(sub, "**", "*.pmx"), recursive=True)) + + for p in paths: + if os.path.isdir(p): + for f in sorted(glob.glob(os.path.join(p, "**", "*"), recursive=True)): + k = pipeline.classify(f) if os.path.isfile(f) else None + if k == "pmx": + yield f, os.path.relpath(f, p) + elif k in pipeline.ARCHIVES: + yield from pmx_files([f], tmp) + elif pipeline.classify(p) == "pmx": + yield p, os.path.basename(p) + elif pipeline.classify(p) in pipeline.ARCHIVES: + d = tempfile.mkdtemp(dir=tmp) + try: + pipeline.extract_archive(p, pipeline.classify(p), d) + yield from inside(p, d) + except Exception as e: # noqa: BLE001 + print("跳过 %s:%s" % (p, e), file=sys.stderr) + + +def scan(path): + """→ (合并数, 拆分骨数, [自检问题文字]),和转换时一样的骨骼处理(VRM 1.0、T-pose)。""" + model = pmxio.read_pmx(path) + lines = [] + log = lambda m, t=None: lines.append((m, t)) # noqa: E731 + skeleton.fix_facing(model, log) + verts, bones = model["vertices"], model["bones"] + ys = [v["pos"][1] for v in verts] or [0.0] + scale = 1.6 / (max(ys) - min(ys)) if max(ys) > min(ys) else 0.08 + raw = mesh.vertex_weights(verts, len(bones), {}) + bs = skeleton.prepare_bones(bones, True, log, weighted={b for wl in raw for b, w in wl if w > 0}) + vw = mesh.vertex_weights(verts, len(bones), bs.alias, base=raw) + _, bpos, vpos, _, _ = skeleton.apply_tpose(verts, bones, bs, vw, True, log) + vw = skeleton.split_partial(bones, bs, vw, model.get("rigid_bodies"), log) + split = next((int(m.split(":")[1].split(" ")[0]) for m, _ in lines if m.startswith("付与骨:")), 0) + checks.report(bones, bs, raw, vw, bpos, vpos, scale, log) + return len(bs.alias), split, [m for m, t in lines if m.startswith("自检")] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("paths", nargs="+") + ap.add_argument("-o", "--out", help="结果另存一份到文件") + a = ap.parse_args() + out = [sys.stdout] + ([open(a.out, "w", encoding="utf-8")] if a.out else []) + + def say(s): + for f in out: + print(s, file=f, flush=True) + tmp = tempfile.mkdtemp(prefix="vrmify_scan_") + seen, n, bad, t0 = set(), 0, 0, time.time() + try: + for f, label in pmx_files(a.paths, tmp): + key = (os.path.basename(f), os.path.getsize(f)) + if key in seen: + continue + seen.add(key) + n += 1 + try: + merged, split, issues = scan(f) + except Exception as e: # noqa: BLE001 + say("错误 %s:%s: %s" % (label, type(e).__name__, e)) + continue + bad += bool(issues) + say("%s 合并 %3d · 拆分 %3d %s" % ("!!" if issues else "ok", merged, split, label)) + for m in issues: + say(" " + m) + finally: + shutil.rmtree(tmp, ignore_errors=True) + say("%d 个 PMX,%d 个有自检问题(%.0f 秒)" % (n, bad, time.time() - t0)) + return 1 if bad else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/smoke_exe.py b/tools/smoke_exe.py new file mode 100644 index 0000000..bcf4b79 --- /dev/null +++ b/tools/smoke_exe.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +"""VRMify 增强版:发布前的冒烟测试:启动打包好的 exe,通过它自己的 HTTP 接口转换几个合成模型,检查结果。 + + python tools/smoke_exe.py dist/VRMify-v0.1.2-win64.zip 发布用的 zip + python tools/smoke_exe.py dist/VRMify 解开的程序文件夹(或 exe 本身) + +单元测试测的是源码;这里测的是**打包以后**还能不能用:PyInstaller 漏打的模块(某种输入格式 +用到的 fbx2pmx / unitypackage_unpack / archive …)、漏打的页面和预览库、exe 起不来,都只在这里暴露。 + +步骤(数据目录用临时文件夹,不碰本机的 settings.json / edits.json): + 1. 用 tests/synth.py 合成 PMX,再做出 zip、FBX、unitypackage 三种输入; + 2. `VRMify.exe --no-open --port N` 启动,等 /api/ping; + 3. 版本号要和 ui/version.py 一致;页面、预览组件、three.js / three-vrm / ammo.js 都能取到; + 4. 加入四个文件 → 转换 → 等转换结束:每个都成功、各出一个 VRM,日志里没有错误; + 5. 每个 VRM 过 tools/qa/check_vrm(装了 jsonschema 时含官方 Schema); + 6. 预览(PMX 原生预览、VRM 文件)和调整面板的接口能用。 +有任何一项失败退出码为 1,exe 的输出打印在最后。GitHub Actions 的 release.yml 打包后会跑它。 +""" +import argparse +import io +import json +import os +import shutil +import socket +import subprocess +import sys +import tarfile +import tempfile +import time +import urllib.error +import urllib.request +import zipfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +for _p in ("tests", "convert", "formats", os.path.join("tools", "qa"), "ui"): + _d = os.path.join(ROOT, _p) + if _d not in sys.path: + sys.path.insert(0, _d) +APP = "VRMify" +STATIC = ["/", "/app.js", "/core.js", "/files.js", "/options.js", "/run.js", "/preview.js", "/tune.js", "/layout.js", "/i18n.js", "/viewer/viewer-core.js", "/viewer/vendor/three/three.module.min.js", + "/viewer/vendor/three-vrm/three-vrm.module.min.js", "/viewer/vendor/three/addons/libs/ammo.wasm.js", + "/viewer/vendor/three/addons/loaders/MMDLoader.js"] + + +class Failed(Exception): + pass + + +def make_inputs(folder): + """合成模型 → {名字: 路径}:PMX、zip(PMX + 贴图)、FBX、unitypackage(里面一个 FBX)。""" + import fbxout + import synth + pmx = synth.build(os.path.join(folder, "pmx"), "合成") + src = os.path.dirname(synth.build(os.path.join(folder, "zip_src"), "合成zip")) # 输出名不和 PMX 的撞 + zp = os.path.join(folder, "合成包.zip") + with zipfile.ZipFile(zp, "w") as z: + for d, _, fs in os.walk(src): + for fn in fs: + p = os.path.join(d, fn) + z.write(p, os.path.join("合成包", os.path.relpath(p, src))) + fbx = os.path.join(folder, "fbx", "Synth.fbx") + os.makedirs(os.path.dirname(fbx)) + # FBX 用英文骨名:导出会把日文名换成下划线,那样认不出人形骨架、会被「只转换人物」跳过 + fbxout.export_pmx(synth.build(os.path.join(folder, "fbx_src"), "Synth", english=True), fbx, + log=lambda *a, **k: None) + pkg = os.path.join(folder, "Synth.unitypackage") + with tarfile.open(pkg, "w:gz") as tf: + guid = "%032x" % 1 + tf.add(fbx, guid + "/asset") + info = tarfile.TarInfo(guid + "/pathname") + data = b"Assets/Synth/SynthPkg.fbx" # 输出名不和单独的 FBX 撞 + info.size = len(data) + tf.addfile(info, io.BytesIO(data)) + return {"pmx": pmx, "zip": zp, "fbx": fbx, "unitypackage": pkg} + + +def find_exe(target, tmp): + if os.path.isfile(target) and target.lower().endswith(".zip"): + with zipfile.ZipFile(target) as z: + z.extractall(os.path.join(tmp, "app")) + target = os.path.join(tmp, "app") + if os.path.isdir(target): + for d, _, fs in os.walk(target): + if APP + ".exe" in fs: + return os.path.join(d, APP + ".exe") + raise Failed("在 %s 里没找到 %s.exe" % (target, APP)) + return target + + +def free_port(): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +class Client: + def __init__(self, port): + self.base = "http://127.0.0.1:%d" % port + + def get(self, path, timeout=30): + try: + with urllib.request.urlopen(self.base + path, timeout=timeout) as r: + return r.status, r.read() + except urllib.error.HTTPError as e: + return e.code, b"" + + def json(self, path, body=None, timeout=60): + data = None if body is None else json.dumps(body).encode("utf-8") + req = urllib.request.Request(self.base + path, data=data, + headers={"Content-Type": "application/json"} if data else {}) + with urllib.request.urlopen(req, timeout=timeout) as r: + return json.loads(r.read().decode("utf-8")) + + +def run(exe, inputs, tmp, report, timeout): + import check_vrm + from version import __version__ + + port = free_port() + env = dict(os.environ, VRMIFY_DATA=os.path.join(tmp, "data")) + out_log = open(os.path.join(tmp, "exe.log"), "wb") + proc = subprocess.Popen([exe, "--no-open", "--port", str(port)], env=env, cwd=tmp, + stdout=out_log, stderr=subprocess.STDOUT) + c = Client(port) + try: + t0 = time.time() + while True: + if proc.poll() is not None: + raise Failed("exe 启动后退出了(退出码 %s)" % proc.returncode) + try: + c.get("/api/ping", timeout=2) + break + except OSError: + if time.time() - t0 > 90: + raise Failed("90 秒内 /api/ping 没有响应") + time.sleep(0.5) + report("启动 %.1f 秒" % (time.time() - t0)) + + st = c.json("/api/state") + if st.get("version") != __version__: + raise Failed("版本号 %r,ui/version.py 是 %r" % (st.get("version"), __version__)) + app_out = st.get("app_out") or "" + if not os.path.normcase(app_out).startswith(os.path.normcase(env["VRMIFY_DATA"])): + raise Failed("默认输出目录 %r 不在数据目录里" % app_out) + report("版本 %s · 默认输出 %s" % (__version__, app_out)) + + for p in STATIC: + code, body = c.get(p) + if code != 200 or not body: + raise Failed("取不到 %s(HTTP %s)" % (p, code)) + report("页面和预览库 %d 个文件都在" % len(STATIC)) + + ids = c.json("/api/add", {"paths": list(inputs.values())})["added"] + files = {f["id"]: f for f in c.json("/api/state")["files"]} + kinds = sorted(files[i]["kind"] for i in ids) + if len(ids) != len(inputs): + raise Failed("加入了 %d 个文件,应为 %d(%s)" % (len(ids), len(inputs), kinds)) + report("加入 %s" % " / ".join(kinds)) + + # 没转换之前,PMX 的预览是原生预览:/model/… 直接给 PMX 文件 + pmx_id = next(i for i in ids if files[i]["kind"] == "pmx") + pv = c.json("/api/preview", {"id": pmx_id}) + code, body = c.get(pv.get("url") or "/missing") + if code != 200 or not body.startswith(b"PMX "): + raise Failed("PMX 原生预览取不到:%s" % pv) + + seq = c.json("/api/state")["seq"] + if not c.json("/api/convert", {"ids": []}).get("started"): + raise Failed("/api/convert 没有开始") + errors, msgs, t0, finished = [], [], time.time(), None + while finished is None: + if time.time() - t0 > timeout: + raise Failed("%d 秒内没转完" % timeout) + for ev in c.json("/api/events?after=%d" % seq, timeout=30)["events"]: + seq = max(seq, ev["seq"]) + if ev.get("type") == "log": + msgs.append(ev["msg"]) + if ev.get("tag") == "err": + errors.append(ev["msg"]) + if ev.get("type") == "busy" and ev.get("busy") is False: + finished = ev + report("转换 %.1f 秒:成功 %s、失败 %s" % (time.time() - t0, finished.get("done"), finished.get("failed"))) + if errors: + raise Failed("日志里有错误:\n" + "\n".join(errors)[-3000:]) + # 几个文件会同时转:子进程也是这个 exe(靠 ui/app.py 的 freeze_support);退回一个一个转说明多进程坏了 + if any("没法同时转换" in m for m in msgs): + raise Failed("打包后的 exe 开不起转换子进程(退回了一个一个转)") + report(next((m for m in msgs if m.startswith("同时转换")), "一个一个转(这台机器的 CPU / 内存只够一个)")) + + validators, why = check_vrm.load_validators() + if why: + report(why) + files = {f["id"]: f for f in c.json("/api/state")["files"]} + vrm_url = None + for i in ids: + f = files[i] + vrms = [o for o in f["outputs"] if o["path"].lower().endswith(".vrm")] + if f["status"] != "done" or len(vrms) != 1: + raise Failed("%s:状态 %s,VRM 输出 %d 个(%s)" % (f["name"], f["status"], len(vrms), f.get("error"))) + path = vrms[0]["path"] + if not os.path.isfile(path): + raise Failed("%s:输出文件不存在 %s" % (f["name"], path)) + errs, _, summary = check_vrm.check(path, validators) + if errs: + raise Failed("%s 校验失败:\n %s" % (os.path.basename(path), "\n ".join(errs[:10]))) + report("%-14s → %s(%.2f MB)" % (f["kind"], os.path.basename(path), os.path.getsize(path) / 1048576.0)) + vrm_url = vrm_url or vrms[0]["url"] + + code, body = c.get(vrm_url) + if code != 200 or not body.startswith(b"glTF"): + raise Failed("VRM 文件预览取不到:%s" % vrm_url) + tune = c.json("/api/tune", {"id": pmx_id}) + if tune.get("error") or not tune.get("expressions"): + raise Failed("调整面板的接口异常:%s" % str(tune)[:300]) + report("预览(PMX / VRM)和调整面板接口正常") + if proc.poll() is not None: + raise Failed("exe 中途退出了(退出码 %s)" % proc.returncode) + finally: + proc.terminate() + try: + proc.wait(10) + except subprocess.TimeoutExpired: + proc.kill() + out_log.close() + + +def main(argv=None): + ap = argparse.ArgumentParser(description="打包后的 exe 冒烟测试") + ap.add_argument("target", help="发布 zip、解开的程序文件夹或 exe") + ap.add_argument("--timeout", type=int, default=300, help="转换的最长等待秒数") + ap.add_argument("--keep", action="store_true", help="保留临时文件夹(看输出和 exe 日志)") + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + tmp = tempfile.mkdtemp(prefix="vrmify_smoke_") + ok = False + try: + exe = find_exe(os.path.abspath(a.target), tmp) + print("exe:%s" % exe) + inputs = make_inputs(os.path.join(tmp, "inputs")) + run(exe, inputs, tmp, lambda m: print(" ✓ " + m, flush=True), a.timeout) + ok = True + print("冒烟测试通过") + except Failed as e: + print("✗ %s" % e) + except Exception as e: # noqa: BLE001 接口返回了意料之外的东西:同样算失败,照样打印 exe 输出 + print("✗ %s: %s" % (type(e).__name__, e)) + finally: + log = os.path.join(tmp, "exe.log") + if not ok and os.path.isfile(log): + with open(log, "rb") as f: + print("---- exe 输出(最后 4000 字)----\n" + f.read().decode("utf-8", "replace")[-4000:]) + if a.keep: + print("临时文件夹:%s" % tmp) + else: + shutil.rmtree(tmp, ignore_errors=True) + return 0 if ok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ui/app.py b/ui/app.py new file mode 100644 index 0000000..5bc824a --- /dev/null +++ b/ui/app.py @@ -0,0 +1,231 @@ +# -*- coding: utf-8 -*- +"""VRMify 增强版 图形界面入口。 + + python ui/app.py [文件或文件夹 ...] [--browser] [--port N] + +装了 pywebview 时开一个原生窗口(Windows 用系统自带的 WebView2,支持把文件直接拖进窗口); +没装、加 --browser、或者系统缺 WebView2 / 窗口打不开时用系统浏览器打开,页面关掉一分钟后自动退出。 +用了哪种、为什么,写在数据文件夹的 startup.log 里;退到浏览器时页面顶上也会显示原因。 +界面本身在 ui/web/,后端和接口在 ui/server.py。 +""" +import argparse +import json +import os +import sys +import time +import webbrowser + +HERE = os.path.dirname(os.path.abspath(__file__)) +if HERE not in sys.path: + sys.path.insert(0, HERE) + + +def _dialog(mode): + """浏览器模式下由后端以子进程调用:弹 tkinter 对话框,把选中的路径以 JSON 打到 stdout。""" + import tkinter as tk + from tkinter import filedialog + root = tk.Tk() + root.withdraw() + root.attributes("-topmost", True) + if mode == "folder": + r = filedialog.askdirectory() + paths = [r] if r else [] + elif mode == "uemodel": + r = filedialog.askopenfilename(filetypes=[("UEFormat", "*.uemodel"), ("All files", "*.*")]) + paths = [r] if r else [] + else: + paths = list(filedialog.askopenfilenames(filetypes=[ + ("Models", "*.pmx *.vrm *.zip *.7z *.rar *.tar *.tgz *.gz *.bz2 *.xz *.fbx *.unitypackage *.uemodel *.psk *.pskx *.xps"), + ("All files", "*.*")])) + root.destroy() + print(json.dumps(paths, ensure_ascii=False)) + + +def _webview2_ok(): + """Windows 上有没有 WebView2 运行时(和 pywebview 的判断一致:看 EdgeUpdate 的注册表)。 + + 没有的话 pywebview 会退回 IE 内核(MSHTML),界面用的 ES 模块 / WebGL 在 IE 里跑不起来, + 窗口一片空白——不如直接用浏览器打开。 + """ + if os.name != "nt": + return True + import platform + import winreg + keys = ("{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}", "{2CD8A007-E189-409D-A2C8-9AF4EF3C72AA}", + "{0D50BFEC-CD6A-4F9A-964C-C7416E3ACB10}", "{65C35B14-6C1D-4122-AC46-7148CC9D6497}") + for key in keys: + for root in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): + wow = "" if (platform.machine() == "x86" or root == winreg.HKEY_CURRENT_USER) else "WOW6432Node\\" + try: + with winreg.OpenKey(root, "SOFTWARE\\%sMicrosoft\\EdgeUpdate\\Clients\\%s" % (wow, key)) as k: + pv = str(winreg.QueryValueEx(k, "pv")[0]) + except OSError: + continue + try: + if tuple(int(x) for x in pv.split(".")[:3]) >= (86, 0, 622): + return True + except ValueError: + pass + return False + + +def _webview2_loader_version(): + """直接问 WebView2 的加载器(pywebview 自带的 WebView2Loader.dll)系统里装了哪个版本的运行时,没有为 None。 + + 比查注册表准:精简过的系统、删过 Edge 的机器,运行时还在,注册表里却可能没有 EdgeUpdate 的记录。 + """ + if os.name != "nt": + return None + try: + import ctypes + import sysconfig + import webview + arch = {"win-amd64": "win-x64", "win-arm64": "win-arm64"}.get(sysconfig.get_platform(), "win-x86") + lib = ctypes.WinDLL(os.path.join(os.path.dirname(webview.__file__), "lib", "runtimes", arch, "native", + "WebView2Loader.dll")) + out = ctypes.c_wchar_p() + if lib.GetAvailableCoreWebView2BrowserVersionString(None, ctypes.byref(out)) != 0 or not out.value: + return None + ver = out.value + ctypes.windll.ole32.CoTaskMemFree(out) + return ver + except Exception: # noqa: BLE001 + return None + + +def _webview2_folder(ver): + """运行时 ver 装在哪(msedgewebview2.exe 所在文件夹),找不到为 None。""" + for base in (os.environ.get("ProgramFiles(x86)"), os.environ.get("ProgramFiles"), os.environ.get("LOCALAPPDATA")): + d = os.path.join(base or "", "Microsoft", "EdgeWebView", "Application", ver) + if base and os.path.isfile(os.path.join(d, "msedgewebview2.exe")): + return d + return None + + +def _diagnose(backend, mode, reason=None, detail=""): + """启动方式和原因写进数据文件夹的 startup.log(每次启动覆盖),用户反馈问题时可以直接发过来; + 退到浏览器时把原因交给页面显示(server.Backend.mode_note)。""" + import platform + import server + from version import __version__ + path = os.path.join(server.DATA_DIR, "startup.log") + if reason: + backend.mode_note = {"zh": reason[0], "en": reason[1], "kind": reason[2], "log": path} + backend.log(reason[0], "warn") + try: + with open(path, "w", encoding="utf-8") as f: + lines = ["VRMify 增强版 %s · %s · Python %s %s" % (__version__, platform.platform(), platform.python_version(), + platform.machine()), + "%s · 窗口:%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), mode)] + lines += [reason[0]] if reason else [] + lines += [detail.rstrip()] if detail.strip() else [] + f.write("\n".join(lines) + "\n") + except OSError: + pass + + +# (中文, 英文, 种类):页面按种类决定附加什么(没有 WebView2 时给安装链接) +NO_WEBVIEW2 = ("系统里没有 WebView2 运行时(Windows 的网页组件),所以用浏览器打开。安装后重新打开程序就是独立窗口。", + "WebView2 (the Windows web component) is not installed, so VRMify Enhanced opened in the browser. " + "Install it and start VRMify Enhanced again to get its own window.", "no_webview2") +NO_PYWEBVIEW = ("没有安装 pywebview,所以用浏览器打开(pip install pywebview 后就是独立窗口)。", + "pywebview is not installed, so VRMify Enhanced opened in the browser (pip install pywebview for its own window).", + "no_pywebview") + + +def _window_failed(ex): + msg = "%s: %s" % (type(ex).__name__, ex) + return ("独立窗口启动失败(%s),所以用浏览器打开。" % msg, + "VRMify Enhanced's window failed to start (%s), so it opened in the browser." % msg, "window_failed") + + +def _browser_loop(backend, url, open_page, keep): + print("VRMify 增强版:%s(关闭页面一分钟后自动退出,Ctrl+C 立即退出)" % url, flush=True) + if open_page: + webbrowser.open(url) + backend.last_seen = time.time() + while keep or time.time() - backend.last_seen < 60 or backend.busy: + time.sleep(1) + + +def main(argv=None): + argv = sys.argv[1:] if argv is None else argv + if len(argv) >= 2 and argv[0] == "--dialog": + return _dialog(argv[1]) + ap = argparse.ArgumentParser(description="VRMify 增强版 / VRMify Enhanced") + ap.add_argument("paths", nargs="*", help="启动时加入的文件或文件夹") + ap.add_argument("--browser", action="store_true", help="用系统浏览器,不用 pywebview 窗口") + ap.add_argument("--no-open", action="store_true", help="只启动服务并打印地址(调试用)") + ap.add_argument("--port", type=int, default=0) + a = ap.parse_args(argv) + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + + import server + backend, srv, url = server.serve(a.port) + if a.paths: + backend.add_paths(a.paths) + + webview, detail = None, "" + if a.browser or a.no_open: + _diagnose(backend, "浏览器(--browser / --no-open)") + else: + try: + import webview + except ImportError: + webview = None + _diagnose(backend, "浏览器", NO_PYWEBVIEW) + if webview is not None and not _webview2_ok(): + # 注册表里没有记录(pywebview 只看注册表,会退回 IE 内核、窗口一片空白):再问加载器 + ver = _webview2_loader_version() + if ver: + folder = _webview2_folder(ver) + # 指定运行时文件夹后 pywebview 就用 WebView2;文件夹没找到时给一个不存在的路径, + # pywebview 会认为有 WebView2,建窗口时再退回系统装的运行时(加载器刚确认过有) + webview.settings["WEBVIEW2_RUNTIME_PATH"] = folder or os.path.join(HERE, "_system_webview2_") + detail = "注册表里没有 WebView2 的记录,加载器检测到运行时 %s(%s)" % (ver, folder or "系统默认位置") + else: + webview = None + _diagnose(backend, "浏览器", NO_WEBVIEW2) + try: + if webview is not None: + win = webview.create_window("VRMify 增强版 / VRMify Enhanced", url, width=1440, height=900, min_size=(1000, 640)) + backend.window = win + + def on_start(): + _diagnose(backend, "独立窗口(WebView2)", detail=detail) + # 拖进窗口的文件:pywebview 5+ 在 drop 事件里给出完整路径 + try: + from webview.dom import DOMEventHandler + + def on_drop(e): + files = (e.get("dataTransfer") or {}).get("files") or [] + backend.add_paths([f.get("pywebviewFullPath") for f in files]) + win.dom.document.events.drop += DOMEventHandler(on_drop, True, True) + except Exception as ex: # noqa: BLE001 旧版 pywebview:只能用按钮添加 + backend.log("拖放不可用(%s),请用「添加文件」" % ex, "warn") + + try: + webview.start(on_start, gui="edgechromium" if os.name == "nt" else None) + except Exception as ex: # noqa: BLE001 窗口起不来:退回浏览器 + import traceback + backend.window = None + _diagnose(backend, "浏览器", _window_failed(ex), detail + "\n" + traceback.format_exc()) + _browser_loop(backend, url, True, False) + else: + _browser_loop(backend, url, not a.no_open, a.no_open) + except KeyboardInterrupt: + pass + finally: + srv.shutdown() + backend.close() + + +if __name__ == "__main__": + # 同时转换几个文件时开的子进程(convert/parallel.py):打包的 exe 里它们也是这个 exe, + # 要先在这里接住,不然每个子进程都会再开一个程序窗口 + import multiprocessing + multiprocessing.freeze_support() + main() diff --git a/ui/icon.ico b/ui/icon.ico new file mode 100644 index 0000000..31d8b96 Binary files /dev/null and b/ui/icon.ico differ diff --git a/ui/server.py b/ui/server.py new file mode 100644 index 0000000..297a5dc --- /dev/null +++ b/ui/server.py @@ -0,0 +1,1035 @@ +# -*- coding: utf-8 -*- +"""图形界面的后端:文件列表、选项、转换任务、事件推送,和一个只监听 127.0.0.1 的 HTTP 服务。 + +页面(ui/web/)只通过 HTTP 接口和这里打交道,所以 pywebview 窗口和普通浏览器用的是同一套: + + GET /api/state 文件列表、选项、语言、是否在转换 + GET /api/events?after=N 长轮询:日志 / 文件状态 / 进度 / 预览就绪 + POST /api/add {paths} 加文件(文件夹会递归展开) + POST /api/pick {folder} 弹系统对话框选文件 / 文件夹再加入 + POST /api/upload?key=&path= 浏览器模式:上传一个文件(请求体是文件内容),存进临时文件夹 + POST /api/upload/done {items} 浏览器模式:一批传完,把 [{key, roots}] 里的顶层文件 / 文件夹加入列表 + POST /api/pick_output 选输出文件夹,返回路径 + POST /api/pick_ue_ref 选 uemodel 的整身对齐参考,返回路径(参考像部件时带 warn) + POST /api/remove {ids} · /api/clear + POST /api/options {opts, lang, ui} 保存选项、界面语言、栏宽(写 settings.json) + POST /api/convert {ids} 开始转换(ids 为空 = 全部待转的) + POST /api/stop 当前文件转完后停止 + POST /api/preview {id, output} 给某个文件准备预览(PMX 等会先快速转一份临时 VRM); + output = 输出列表里的序号时预览那个输出(PMX 输出同样先转临时 VRM) + POST /api/open {path} 在资源管理器里显示文件 + POST /api/snapshot {name, data} 把预览截图存到模型旁边 + POST /api/tune {id, model} 调整面板要的信息(可选表情、物理链、当前调整;model = 预览中的模型) + POST /api/tune/save {id, edits} 保存某个文件的调整,并套到它已有的输出 / 预览 VRM 上 + POST /api/tune/thumb {id, data, auto, model} 把预览截图存成某个模型的 VRM 缩略图(data 为空 = 去掉); + auto:转换后自动截的,用户自己设过缩略图时不覆盖 + GET /file/ 预览要读的 VRM / 缩略图(只提供登记过的文件) + GET /model//<相对路径> PMX 原生预览:PMX 和它旁边的贴图(只限登记过的模型文件夹; + 浏览器显示不了的 DDS 等现转 PNG) + +调整(表情指定、物理、标题、缩略图,见 convert/vrm_edit.py)按源文件路径存在 edits.json, +缩略图在 edits/ 里;以后再转这个文件会自动套上。 + +静态文件:/ → ui/web/,/viewer/ → ui/viewer/(three-vrm 预览组件和离线库)。 +""" +import base64 +import hashlib +import itertools +import json +import os +import shutil +import subprocess +import sys +import tempfile +import threading +import time +import traceback +import urllib.parse +import uuid +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer + +HERE = os.path.dirname(os.path.abspath(__file__)) +if getattr(sys, "frozen", False): # PyInstaller:资源在 _MEIPASS 下 + ROOT = sys._MEIPASS +else: + ROOT = os.path.dirname(HERE) + + +def _writable(folder): + try: + os.makedirs(folder, exist_ok=True) + probe = os.path.join(folder, ".write_test_%d" % os.getpid()) + with open(probe, "w") as f: + f.write("") + os.remove(probe) + return True + except OSError: + return False + + +def _data_dir(): + """settings.json / edits.json 放哪: + + * 环境变量 VRMIFY_DATA(测试 / 调试用,不动用户自己的设置); + * 否则放程序旁边(exe 所在文件夹 / 源码根目录)——绿色版解压到哪都能带着设置走; + * 程序旁边写不了(比如放进了 C:\\Program Files)时改放 %APPDATA%\\VRMify。以前叫 Model-To-VRM: + 旧文件夹还在、新的还没有时改名过去(设置、调整、输出都在里面),改不了名就接着用旧的。 + """ + env = os.environ.get("VRMIFY_DATA") + if env: + return env + beside = os.path.dirname(sys.executable) if getattr(sys, "frozen", False) else ROOT + if _writable(beside): + return beside + base = os.environ.get("APPDATA") or os.path.expanduser("~") + new, old = os.path.join(base, "VRMify"), os.path.join(base, "Model-To-VRM") + if not os.path.exists(new) and os.path.isdir(old): + try: + os.rename(old, new) + except OSError: + return old + return new + + +DATA_DIR = _data_dir() +for _p in ("convert", "formats"): + _d = os.path.join(ROOT, _p) + if _d not in sys.path: + sys.path.insert(0, _d) +# Windows 超长路径(MAX_PATH 260)兼容层:要在其它模块 import 之前装上(导入即生效), +# Unity 资源包解出的深层目录树超过 260 字符时 open / makedirs 才不会报 FileNotFoundError +import longpath # noqa: E402,F401 +import logtext # noqa: E402 +import pipeline # noqa: E402 +import parallel # noqa: E402 +import vrm_edit # noqa: E402 +from version import __version__ # noqa: E402 +import vrmio # noqa: E402 +from vrmconv import textures # noqa: E402 + +WEB = os.path.join(ROOT, "ui", "web") +VIEWER = os.path.join(ROOT, "ui", "viewer") +SETTINGS = os.path.join(DATA_DIR, "settings.json") +# 「程序目录」保存位置:程序旁边的 vrm 文件夹(和设置放一起:程序旁边写不了时在 %APPDATA%\VRMify 下) +APP_OUT = os.path.normpath(os.path.join(DATA_DIR, "vrm")) +_OLD_DEFAULT_OUTPUT = {"mode": "beside", "folder": "", "subfolder": True} +EDITS = os.path.join(DATA_DIR, "edits.json") +EDITS_DIR = os.path.join(DATA_DIR, "edits") +LANGS = ("zh_CN", "en") + + +def system_lang(): + """第一次启动(还没选过语言)时的界面语言:系统是中文就用中文,否则英文。""" + try: + if os.name == "nt": + import ctypes + return "zh_CN" if (ctypes.windll.kernel32.GetUserDefaultUILanguage() & 0x3FF) == 0x04 else "en" + import locale + loc = os.environ.get("LC_ALL") or os.environ.get("LC_MESSAGES") or os.environ.get("LANG") or (locale.getlocale()[0] or "") + return "zh_CN" if loc.lower().startswith("zh") else "en" + except Exception: # noqa: BLE001 + return "zh_CN" + + +TMP_PREFIXES = ("vrmify_", "model2vrm_") # 后一个是改名前(Model-To-VRM)的版本留下的 +# 浏览器模式下拖入 / 选择的文件:网页拿不到磁盘路径,内容传到这里再加入列表(一天没用会被 _sweep_stale_previews 删掉) +UPLOADS = os.path.join(tempfile.gettempdir(), "vrmify_uploads") +_BAD_CHARS = set('\\/:*?"<>|') | {chr(i) for i in range(32)} + + +def _safe_name(s): + s = "".join("_" if c in _BAD_CHARS else c for c in s).strip().rstrip(". ") + return s if s not in ("", ".", "..") else "_" + + + +# 预览缓存:不影响转换结果的设置不算进缓存键;每个文件最多留几份临时 VRM(压缩包转出来常有几十 MB) +_PREVIEW_IGNORE = ("target", "jobs", "output") +_PREVIEW_KEEP = 3 + + +def _preview_key(src, opts): + """临时预览 VRM 的缓存键:源文件 + 修改时间 + 转换设置的指纹。以前只有前两项, + 改了设置(VRM 版本、物理……)再点预览还是拿到用旧设置转的那份。""" + sig = json.dumps({k: v for k, v in opts.items() if k not in _PREVIEW_IGNORE}, sort_keys=True, + ensure_ascii=False) + return "%s|%s|%s" % (os.path.normcase(src), os.path.getmtime(src), + hashlib.md5(sig.encode("utf-8")).hexdigest()[:12]) + + +def _sweep_stale_previews(max_age=86400): + """删掉以前遗留的预览临时目录:正常退出时会删,程序崩溃或被强制结束时会留下来(每个几十 MB)。 + 只删一天以前的——同时开着的另一个窗口的目录还在用。""" + root = tempfile.gettempdir() + now = time.time() + try: + names = os.listdir(root) + except OSError: + return + for n in names: + p = os.path.join(root, n) + try: + if not (n.startswith(TMP_PREFIXES) and os.path.isdir(p)): + continue + # 看目录本身和下一层的最近修改时间(预览文件在下一层的子目录里) + newest = max([os.path.getmtime(p)] + [os.path.getmtime(os.path.join(p, c)) for c in os.listdir(p)]) + if now - newest > max_age: + shutil.rmtree(p, ignore_errors=True) + except OSError: + pass + + +# 界面布局(拖动分隔条调的栏宽,像素):left 左栏、side 右侧面板栏(调整面板 sideWide) +_UI_LIMITS = {"left": (300, 900), "side": (220, 900), "sideWide": (280, 900)} + + +def _clean_ui(ui): + out = {} + for k, (lo, hi) in _UI_LIMITS.items(): + v = (ui or {}).get(k) if isinstance(ui, dict) else None + if isinstance(v, (int, float)) and not isinstance(v, bool): + out[k] = int(min(hi, max(lo, v))) + return out + + +class Backend: + def __init__(self): + self.lock = threading.RLock() + self.cond = threading.Condition(self.lock) + self.files = {} # id → 文件条目(插入顺序即列表顺序) + self.events = [] # [(seq, event)] + self.seq = itertools.count(1) + self.tokens = {} # token → 路径(预览可读的文件) + self.dirs = {} # token → 文件夹(PMX 原生预览:模型和贴图都从这里读) + self.finders = {} # token → vrmio.TextureFinder(贴图不在 PMX 记的位置时按文件名找) + self.preview_jobs = set() # 正在后台转的预览(缓存键):再点预览不重复转 + self.busy = False + self.stop_flag = False + self.window = None # pywebview 窗口(有的话用它的原生对话框) + self.mode_note = None # 退到浏览器模式的原因 {zh, en, log}(app.py 设置,页面顶上显示) + self.last_seen = time.time() + _sweep_stale_previews() + self.tmp = tempfile.mkdtemp(prefix="vrmify_preview_") + self.opts, self.lang, self.ui = self._load_settings() + self.edits = self._load_edits() + + # --------------------------------------------------------- settings -- + def _load_settings(self): + try: + with open(SETTINGS, encoding="utf-8") as f: + s = json.load(f) + except (OSError, ValueError): + s = {} + lang = s.get("lang") if s.get("lang") in LANGS else system_lang() + opts = pipeline.merged(s.get("opts")) + # 界面的默认保存位置是程序目录下的 vrm。以前的设置文件(没有 v)里还是旧默认值(源文件旁)的, + # 多半是没选过,换成新默认;自己选过别的(指定文件夹、关了子文件夹)的不动 + saved = (s.get("opts") or {}).get("output") + if s.get("v", 1) < 2 and (saved is None or saved == _OLD_DEFAULT_OUTPUT): + opts["output"]["mode"] = "app" + return opts, lang, _clean_ui(s.get("ui")) + + def _save_settings(self): + try: + with open(SETTINGS, "w", encoding="utf-8") as f: + json.dump({"v": 2, "lang": self.lang, "opts": self.opts, "ui": self.ui}, f, ensure_ascii=False, indent=1) + except OSError: + pass + + # ------------------------------------------------------------ edits -- + def _load_edits(self): + try: + with open(EDITS, encoding="utf-8") as f: + d = json.load(f) + return d if isinstance(d, dict) else {} + except (OSError, ValueError): + return {} + + def _save_edits(self): + try: + with open(EDITS, "w", encoding="utf-8") as f: + json.dump(self.edits, f, ensure_ascii=False, indent=1) + except OSError: + pass + + @staticmethod + def _key(f): + return os.path.normcase(os.path.abspath(f["path"])) + + def edits_for(self, f): + with self.lock: + return json.loads(json.dumps(self.edits.get(self._key(f)) or {})) + + @staticmethod + def _user_edits(e): + """去掉自动生成的缩略图后的调整:判断「调整过」、关掉自动缩略图时转换用。""" + e = dict(e or {}) + if e.pop("thumbnail_auto", None): + e.pop("thumbnail", None) + ths = {k: t for k, t in (e.get("thumbnails") or {}).items() if not (t or {}).get("auto")} + if ths: + e["thumbnails"] = ths + else: + e.pop("thumbnails", None) + return e + + def _convert_edits(self, f): + """转换时套用的调整:关掉「自动生成缩略图」后,以前自动截的那张不再写进去。""" + e = self.edits_for(f) + return e if self.opts["vrm"].get("auto_thumb", True) else self._user_edits(e) + + # ----------------------------------------------------------- events -- + def emit(self, **ev): + with self.cond: + self.events.append((next(self.seq), ev)) + if len(self.events) > 5000: + del self.events[:1000] + self.cond.notify_all() + + def wait_events(self, after, timeout=20.0): + end = time.time() + timeout + with self.cond: + while True: + new = [{"seq": s, **e} for s, e in self.events if s > after] + left = end - time.time() + if new or left <= 0: + return new + self.cond.wait(left) + + def log(self, msg, tag=None, fid=None): + """日志按中文生成,en 是英文版(logtext;对照表里没有的为 None,界面就显示中文)。""" + msg = str(msg) + self.emit(type="log", msg=msg, en=logtext.to_en(msg), tag=tag, file=fid) + + # ------------------------------------------------------------ files -- + def _entry(self, f): + e = {k: f[k] for k in ("id", "path", "name", "kind", "size", "status", "outputs", "error")} + e["error_en"] = logtext.to_en(f["error"]) if f.get("error") else None + e["tuned"] = not vrm_edit.is_empty(self._user_edits(self.edits.get(self._key(f)))) + return e + + def state(self): + with self.lock: + return {"files": [self._entry(f) for f in self.files.values()], "opts": self.opts, + "lang": self.lang, "busy": self.busy, "ui": self.ui, + "seq": self.events[-1][0] if self.events else 0, + "native": self.window is not None, "version": __version__, + "features": {"pillow": textures.available(), "auto_jobs": parallel.auto_jobs()}, + "app_out": APP_OUT, "mode_note": self.mode_note} + + def add_paths(self, paths): + added = [] + with self.lock: + known = {os.path.normcase(os.path.abspath(f["path"])) for f in self.files.values()} + todo = [] + for p in paths: + if not p: + continue + todo.extend(pipeline.find_inputs(p) if os.path.isdir(p) else [p]) + for p in todo: + kind = pipeline.classify(p) + key = os.path.normcase(os.path.abspath(p)) + if not kind or key in known or not os.path.isfile(p): + continue + known.add(key) + fid = uuid.uuid4().hex[:10] + self.files[fid] = {"id": fid, "path": os.path.abspath(p), "name": os.path.basename(p), + "kind": kind, "size": os.path.getsize(p), + "status": "preview" if kind == "vrm" else "pending", + "outputs": [], "error": None, "preview": None, "preview_path": None} + added.append(fid) + for fid in added: + self.emit(type="file", file=self._entry(self.files[fid])) + return added + + def remove(self, ids): + with self.lock: + for i in ids: + f = self.files.get(i) + if f and f["status"] != "running": + del self.files[i] + self.emit(type="files") + + def clear(self): + with self.lock: + for i in [k for k, f in self.files.items() if f["status"] != "running"]: + del self.files[i] + self.emit(type="files") + + def set_options(self, opts=None, lang=None, ui=None): + reopen = [] + with self.lock: + if opts is not None: + was = self.opts["vrm"].get("avatar_only") + self.opts = pipeline.merged(opts) + if was and not self.opts["vrm"]["avatar_only"]: + # 关掉「只转换人物」:之前因此跳过的文件回到「待转换」,点开始就会转 + reopen = [i for i, f in self.files.items() if f["status"] == "skipped"] + if lang in LANGS: + self.lang = lang + if ui is not None: + self.ui = _clean_ui(dict(self.ui, **ui) if isinstance(ui, dict) else None) + self._save_settings() + for fid in reopen: + self._update(fid, status="pending") + + def _update(self, fid, **kw): + with self.lock: + f = self.files.get(fid) + if not f: + return + f.update(kw) + entry = self._entry(f) + self.emit(type="file", file=entry) + + def token_for(self, path): + with self.lock: + for t, p in self.tokens.items(): + if p == path: + return t + t = uuid.uuid4().hex + self.tokens[t] = path + return t + + def dir_url(self, path): + """PMX 的原生预览地址:/model/<文件夹 token>/<文件名>,贴图按 PMX 里的相对路径从同一文件夹读。""" + folder = os.path.dirname(os.path.abspath(path)) + with self.lock: + tok = next((t for t, d in self.dirs.items() if d == folder), None) + if tok is None: + tok = uuid.uuid4().hex + self.dirs[tok] = folder + return "/model/%s/%s" % (tok, urllib.parse.quote(os.path.basename(path))) + + def _outputs(self, paths): + return [{"path": p, "name": os.path.basename(p), "kind": pipeline.classify(p), + "url": "/file/%s/%s" % (self.token_for(p), urllib.parse.quote(os.path.basename(p))) + if p.lower().endswith(".vrm") else None, + "previewable": p.lower().endswith((".vrm", ".pmx"))} for p in paths] + + # ------------------------------------------------------- conversion -- + def convert(self, ids=None): + with self.lock: + if self.busy: + return False + cand = [f for f in self.files.values() + if (not ids or f["id"] in ids) and f["kind"] in pipeline.CONVERTIBLE + and f["status"] != "running"] + # 默认只转还没转 / 转失败的;都转过了就全部重转 + todo = [f["id"] for f in cand if f["status"] in ("pending", "error")] or [f["id"] for f in cand] + if not todo: + return False + self.busy, self.stop_flag = True, False + opts = json.loads(json.dumps(self.opts)) + opts["output"]["app_folder"] = APP_OUT + threading.Thread(target=self._run, args=(todo, opts), daemon=True).start() + return True + + def _run(self, ids, opts): + """转换 ids 里的文件。几个文件时按 parallel.jobs_for 同时转(子进程),一个文件就在本进程里转。 + 「停止」:已经在转的转完,还没开始的不再开始。""" + self.emit(type="busy", busy=True, total=len(ids)) + todo = [] + for fid in ids: + with self.lock: + f = self.files.get(fid) + if f: + todo.append((fid, f["path"], f["name"], self._convert_edits(f), self._opts_for(f["path"], opts))) + total = len(todo) + jobs = parallel.jobs_for(total, opts.get("jobs"), [pipeline.memory_estimate(p) for _, p, _, _, _ in todo]) + st = {"done": 0, "failed": 0, "skipped": 0, "finished": 0} + running, t0 = {}, {} + + def progress(): + self.emit(type="progress", index=st["finished"], total=total, name="、".join(running.values())) + + def start(fid): + t0[fid] = time.time() + running[fid] = next(n for i, _, n, _, _ in todo if i == fid) + self._update(fid, status="running", error=None) + progress() + + def finish(fid, ok, res): + running.pop(fid, None) + st["finished"] += 1 + if ok and res: + self._update(fid, status="done", outputs=self._outputs(res)) + self.log("完成,用时 %.1f 秒" % (time.time() - t0[fid]), "ok", fid) + st["done"] += 1 + elif ok: # 里面的模型都被「只转换人物」跳过了(原因在日志里) + self._update(fid, status="skipped", outputs=[]) + st["skipped"] += 1 + else: + summary, tb = res + self.log(tb or summary, "err", fid) + self._update(fid, status="error", error=summary) + st["failed"] += 1 + progress() + + def stopped(): + with self.lock: + return self.stop_flag + + try: + if jobs > 1: + self.log("并行转换 %d 个文件(共 %d 个)" % (jobs, total), "info") + parallel.run([(fid, pipeline.convert_file, (path, fopts), {"edits": edits}) + for fid, path, _, edits, fopts in todo], jobs, + lambda fid: (lambda m, t=None: self.log(m, t, fid)), + start=start, done=finish, should_stop=stopped) + else: + for fid, path, _, edits, fopts in todo: + if stopped(): + break + start(fid) + try: + outs = pipeline.convert_file(path, fopts, log=lambda m, t=None, fid=fid: self.log(m, t, fid), + edits=edits) + finish(fid, True, outs) + except Exception as e: # noqa: BLE001 一个文件失败不影响其它 + finish(fid, False, ("%s: %s" % (type(e).__name__, e), traceback.format_exc())) + if st["finished"] < total: + self.log("已停止,%d 个文件未转换" % (total - st["finished"]), "warn") + finally: + with self.lock: + self.busy = False + self.emit(type="busy", busy=False, done=st["done"], failed=st["failed"], skipped=st["skipped"]) + + def stop(self): + with self.lock: + self.stop_flag = True + + @staticmethod + def _uploaded(path): + try: + return os.path.commonpath([UPLOADS, os.path.abspath(path)]) == UPLOADS + except ValueError: + return False + + def _opts_for(self, path, opts): + """浏览器模式传进来的文件在临时文件夹里:「保存在源文件旁边」时改存到程序目录的 vrm 文件夹。""" + if opts["output"].get("mode") == "beside" and self._uploaded(path): + return dict(opts, output=dict(opts["output"], mode="app")) + return opts + + # ---------------------------------------------------------- uploads -- + @staticmethod + def _upload_dir(key): + return os.path.join(UPLOADS, hashlib.md5(str(key).encode("utf-8")).hexdigest()[:12]) + + def upload(self, key, rel, stream, size): + """浏览器模式:页面把拖入 / 选择的文件逐个传过来(请求体就是文件内容),存到 UPLOADS//<相对路径>。 + key 由页面按名字、大小、修改时间算:同样的东西再传一次落在同一个位置(调整按源文件路径保存,下次还能套上), + 已经在了就不重写。读满 size 字节再返回,连接才能接着用。""" + parts = [_safe_name(x) for x in str(rel or "").replace("\\", "/").split("/") if x not in ("", ".", "..")] + dest = os.path.join(self._upload_dir(key), *parts) if parts and key else None + if dest and os.path.isfile(dest) and os.path.getsize(dest) == size: + dest, keep = None, dest + else: + keep = None + tmp = dest + ".part" if dest else None + left = size + try: + if tmp: + os.makedirs(os.path.dirname(tmp), exist_ok=True) + with (open(tmp, "wb") if tmp else open(os.devnull, "wb")) as f: + while left > 0: + chunk = stream.read(min(left, 1 << 20)) + if not chunk: + break + f.write(chunk) + left -= len(chunk) + if left: + raise OSError("上传中断") + if tmp: + os.replace(tmp, dest) + except OSError as e: + if tmp and os.path.exists(tmp): + os.remove(tmp) + return {"error": str(e)} + if not (dest or keep): + return {"error": "bad path"} + return {"ok": True} + + def upload_done(self, items): + """一批文件传完:items = [{key, roots}],roots 是这批里顶层的文件 / 文件夹名,把它们加进列表。""" + paths, lone_pmx = [], [] + for it in items or []: + d = self._upload_dir(it.get("key")) + mine = [os.path.join(d, _safe_name(r)) for r in it.get("roots") or []] + mine = [p for p in mine if os.path.exists(p)] + paths += mine + # 只传了 PMX 本身(没有文件夹、也没有图片跟着):浏览器给不了它旁边的贴图 + if not any(os.path.isdir(p) or p.lower().endswith(vrmio.IMAGE_EXTS) for p in mine): + lone_pmx += [os.path.basename(p) for p in mine if p.lower().endswith(".pmx")] + added = self.add_paths(paths) + if lone_pmx: + self.log("浏览器模式下只加入了 %s 本身,旁边的贴图没有一起传过来,转出来可能没有贴图:" + "请拖入整个模型文件夹或压缩包" % "、".join(lone_pmx), "warn") + return added + + # ---------------------------------------------------------- preview -- + def preview(self, fid, output=None): + """→ {"url": …} 立即可看;或 {"pending": True}(后台快速转换完发 preview 事件)。 + + 预览的对象:指定了 output(输出列表里的序号)就是那个输出;否则依次是输出的 VRM、 + 输出的 PMX(「只转 PMX」时)、源文件本身。PMX 直接原生预览(three.js 的 MMDLoader, + MMD 的着色、IK、物理);FBX 等其它格式先快速转一份临时 VRM,按「文件 + 修改时间 + 转换设置」 + 缓存(_preview_key)。同一份正在转时再点只返回 pending;转完时用户已经换了设置(要的不是这份) + 就只存进缓存、不推给页面。 + """ + with self.lock: + f = self.files.get(fid) + if not f: + return {"error": "no such file"} + if f["kind"] == "vrm": + return {"url": self._outputs([f["path"]])[0]["url"], "name": f["name"]} + outs = f["outputs"] + if output is not None: + if not (0 <= int(output) < len(outs)) or not outs[int(output)].get("previewable"): + return {"error": "not previewable"} + o = outs[int(output)] + if o.get("url"): + return {"url": o["url"], "name": o["name"]} + src = o["path"] + else: + vrms = [o for o in outs if o.get("url")] + if vrms: + return {"url": vrms[-1]["url"], "name": vrms[-1]["name"]} + pmxs = [o for o in outs if o.get("previewable") and os.path.isfile(o["path"])] + src = pmxs[-1]["path"] if pmxs else f["path"] + if src.lower().endswith(".pmx"): + if not os.path.isfile(src): + return {"error": "file not found"} + return {"url": self.dir_url(src), "name": os.path.basename(src)} + opts = json.loads(json.dumps(self.opts)) + opts["target"] = "vrm" + try: + key = _preview_key(src, opts) + except OSError: + return {"error": "file not found"} + f["preview_want"] = key + cache = f.setdefault("previews", {}) + if key in cache and os.path.isfile(cache[key][1]): + url, vrm = cache[key][:2] + cache[key] = cache.pop(key) # 刚用过的排到最后,清理时最后删 + f["preview"], f["preview_path"] = url, vrm + return {"url": url, "name": os.path.basename(src)} + if key in self.preview_jobs: + return {"pending": True} + self.preview_jobs.add(key) + out_dir = os.path.join(self.tmp, fid, hashlib.md5(key.encode("utf-8")).hexdigest()[:10]) + name = os.path.basename(src) + + def work(): + self.emit(type="preview_busy", file=fid) + try: + os.makedirs(out_dir, exist_ok=True) + res = pipeline.convert_file(src, opts, log=lambda m, t=None: self.log(m, t, fid), + out_dir=out_dir, edits=self.edits_for(f)) + if not res and opts["vrm"].get("avatar_only"): + # 里面没有人物(道具、只有衣服),被「只转换人物」跳过了:预览还是转一份来看 + self.log("预览:未找到人物模型,忽略「只转换人物」生成预览", "info", fid) + opts["vrm"]["avatar_only"] = False + res = pipeline.convert_file(src, opts, log=lambda m, t=None: self.log(m, t, fid), + out_dir=out_dir, edits=self.edits_for(f)) + vrm = [p for p in res if p.lower().endswith(".vrm")][-1] + url = self._outputs([vrm])[0]["url"] + with self.lock: + self.preview_jobs.discard(key) + ff = self.files.get(fid) + if ff is None: + return + cache = ff.setdefault("previews", {}) + cache[key] = (url, vrm, out_dir) + # 只留最近几份:更早的连同临时文件夹一起删(正在用的总在最后,删不到) + for old in list(cache)[:-_PREVIEW_KEEP]: + shutil.rmtree(cache.pop(old)[2], ignore_errors=True) + if ff.get("preview_want") != key: # 转的时候用户又换了设置:这份只留着备用 + return + ff["preview"], ff["preview_path"] = url, vrm + self.emit(type="preview", file=fid, url=url, name=name) + except Exception as e: # noqa: BLE001 + with self.lock: + self.preview_jobs.discard(key) + self.log(traceback.format_exc(), "err", fid) + err = "%s: %s" % (type(e).__name__, e) + self.emit(type="preview", file=fid, error=err, error_en=logtext.to_en(err)) + + threading.Thread(target=work, daemon=True).start() + return {"pending": True} + + # ------------------------------------------------------------- tune -- + def _tune_targets(self, f): + """这个文件已有的 VRM:输出的 + 预览用的临时文件。""" + out = [o["path"] for o in f["outputs"] if o["path"].lower().endswith(".vrm")] + if f.get("preview_path"): + out.append(f["preview_path"]) + return [p for p in out if os.path.isfile(p)] + + def tune_info(self, fid, model=None): + """model:预览里显示的模型(vrm_edit.model_key),一个包里有几个模型时按它取信息和缩略图。""" + with self.lock: + f = self.files.get(fid) + if not f: + return {"error": "no such file"} + if f["kind"] not in pipeline.CONVERTIBLE: + return {"editable": False} + targets = self._tune_targets(f) + edits = self.edits_for(f) + if not targets: + return {"editable": True, "ready": False, "edits": edits} + if model: + targets.sort(key=lambda p: vrm_edit.model_key(p) != model) + try: + info = vrm_edit.describe(targets[0]) + except (OSError, ValueError) as e: + return {"error": str(e), "error_en": logtext.to_en(str(e))} + key = vrm_edit.model_key(targets[0]) + th = vrm_edit.thumb_for(edits, targets[0]) + own = (edits.get("thumbnails") or {}).get(key) + auto = own.get("auto") if own else edits.get("thumbnail_auto") + ok = bool(th and os.path.isfile(th)) + info.update(editable=True, ready=True, edits=edits, model=key, thumbnail_auto=bool(ok and auto), + thumbnail=("/file/%s/thumb.png" % self.token_for(th)) if ok else None) + return info + + def tune_save(self, fid, edits, done_msg=None, only=None, keep_thumbs=True): + """only:只套到这些模型(model_key)的 VRM 上。keep_thumbs:edits 里没有缩略图时沿用已存的 + (缩略图单独由 tune_thumb 设置)。""" + with self.lock: + f = self.files.get(fid) + if not f or f["kind"] not in pipeline.CONVERTIBLE: + return {"error": "no such file"} + key = self._key(f) + old = self.edits.get(key) or {} + edits = dict(edits or {}) + if keep_thumbs: + for k in ("thumbnail", "thumbnail_auto", "thumbnails"): + if k not in edits and old.get(k): + edits[k] = old[k] + if vrm_edit.is_empty(edits): + self.edits.pop(key, None) + else: + self.edits[key] = edits + self._save_edits() + targets = [p for p in self._tune_targets(f) if only is None or vrm_edit.model_key(p) in only] + applied = [] + for p in targets: + try: + vrm_edit.apply(p, edits) + applied.append(p) + except Exception as e: # noqa: BLE001 + self.log("调整写入 %s 失败:%s" % (os.path.basename(p), e), "err", fid) + if applied: + self.log((done_msg or "调整已写入 %s") % "、".join(os.path.basename(p) for p in applied), "ok", fid) + self._update(fid) + return {"ok": True, "applied": len(applied)} + + def tune_thumb(self, fid, data, auto=False, model=None): + """data:PNG data URL;空 = 去掉缩略图。model:给哪个模型(vrm_edit.model_key;不给 = 第一个)。 + + 缩略图按模型存(edits["thumbnails"]),一个包里几个模型各用各的,只写进那个模型的 VRM。 + auto:转换后自动截的(界面的「自动生成缩略图」)。记成 auto,下次转换后重新截; + 用户自己给这个模型设过缩略图(不是 auto)时不覆盖。 + """ + with self.lock: + f = self.files.get(fid) + if not f or f["kind"] not in pipeline.CONVERTIBLE: + return {"error": "no such file"} + edits = self.edits_for(f) + keys = list(dict.fromkeys(vrm_edit.model_key(p) for p in self._tune_targets(f))) + model = model or (keys[0] if keys else os.path.splitext(f["name"])[0]) + ths = edits.setdefault("thumbnails", {}) + legacy, legacy_auto = edits.pop("thumbnail", None), edits.pop("thumbnail_auto", None) + if legacy: # 旧版按文件存的一张:分给各个模型,以后都按模型存 + for k in keys + [model]: + ths.setdefault(k, {"path": legacy, "auto": bool(legacy_auto)}) + cur = ths.get(model) or {} + if auto and (not data or (cur.get("path") and not cur.get("auto"))): + return {"skipped": True} + path = None + if data: + os.makedirs(EDITS_DIR, exist_ok=True) + name = hashlib.md5(("%s|%s" % (self._key(f), model)).encode("utf-8")).hexdigest()[:16] + path = os.path.join(EDITS_DIR, name + ".png") + with open(path, "wb") as fh: + fh.write(base64.b64decode(data.split(",", 1)[1])) + ths[model] = {"path": path, "auto": bool(auto)} + else: + ths.pop(model, None) + old = cur.get("path") + if (old and old != path and os.path.dirname(os.path.abspath(old)) == os.path.abspath(EDITS_DIR) + and not any((t or {}).get("path") == old for t in ths.values())): + try: + os.remove(old) + except OSError: + pass + if not ths: + del edits["thumbnails"] + r = self.tune_save(fid, edits, done_msg="缩略图已自动生成并写入 %s" if auto else None, + only=[model], keep_thumbs=False) + if path: + r["thumbnail"] = "/file/%s/thumb.png?t=%d" % (self.token_for(path), int(time.time() * 1000)) + return r + + # ---------------------------------------------------------- dialogs -- + def pick(self, folder=False, output=False, uemodel=False): + """系统对话框。pywebview 窗口用它自己的;浏览器模式起一个 tkinter 子进程。""" + if self.window is not None: + import webview + if folder or output: + r = self.window.create_file_dialog(webview.FOLDER_DIALOG) + elif uemodel: + r = self.window.create_file_dialog( + webview.OPEN_DIALOG, file_types=("UEFormat (*.uemodel)", "All files (*.*)")) + else: + r = self.window.create_file_dialog( + webview.OPEN_DIALOG, allow_multiple=True, + file_types=("Models (*.pmx;*.vrm;*.zip;*.7z;*.rar;*.tar;*.tgz;*.gz;*.bz2;*.xz;*.fbx;*.unitypackage;*.uemodel;*.psk;*.pskx;*.xps)", + "All files (*.*)")) + return list(r or []) + mode = "folder" if (folder or output) else ("uemodel" if uemodel else "files") + cmd = ([sys.executable, "--dialog", mode] if getattr(sys, "frozen", False) + else [sys.executable, os.path.join(HERE, "app.py"), "--dialog", mode]) + try: + r = subprocess.run(cmd, capture_output=True, encoding="utf-8", timeout=600) + return json.loads(r.stdout.strip().splitlines()[-1]) if r.stdout.strip() else [] + except (OSError, ValueError, subprocess.TimeoutExpired): + return [] + + def pick_ue_ref(self): + """uemodel 对齐参考:拆开导出的部件按这个整身模型的骨架对齐。 + + 对齐是单向的(把部件搬进参考的空间),选反了(拿部件当参考)整个模型会掉下去十几单位, + 所以先看参考的骨架铺开有多大:整身通常 >120 cm,局部空间的部件只有几十 cm。 + """ + r = self.pick(uemodel=True) + if not r: + return {"path": ""} + out = {"path": r[0]} + try: + import uemodel2pmx + import uemodelio + spread = uemodel2pmx._bone_spread(uemodelio.read_uemodel(r[0])) + if spread and spread < 120.0: + out["warn"] = "%.0f" % spread + except Exception: # noqa: BLE001 读不了就交给转换阶段处理 + pass + return out + + def reveal(self, path): + if not path or not os.path.exists(path): + return False + try: + if os.name == "nt": + subprocess.Popen(["explorer", "/select,", os.path.normpath(path)]) + elif sys.platform == "darwin": + subprocess.Popen(["open", "-R", path]) + else: + subprocess.Popen(["xdg-open", os.path.dirname(path)]) + return True + except OSError: + return False + + def snapshot(self, name, data, model_url=None): + folder = None + with self.lock: + if model_url: + tok = model_url.split("/")[2] if model_url.startswith("/file/") else None + p = self.tokens.get(tok) + if p and not p.startswith(self.tmp): + folder = os.path.dirname(p) + folder = folder or os.path.join(os.path.expanduser("~"), "Pictures") + os.makedirs(folder, exist_ok=True) + name = "".join(c for c in (name or "vrm") if c not in '\\/:*?"<>|') or "vrm" + for n in range(1, 1000): + out = os.path.join(folder, "%s_preview_%02d.png" % (name, n)) + if not os.path.exists(out): + break + with open(out, "wb") as f: + f.write(base64.b64decode(data.split(",", 1)[1])) + return out + + def close(self): + shutil.rmtree(self.tmp, ignore_errors=True) + + +class Handler(SimpleHTTPRequestHandler): + backend = None + + def log_message(self, fmt, *args): + pass + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + super().end_headers() + + def guess_type(self, path): + if path.endswith((".js", ".mjs")): + return "text/javascript" + if path.endswith(".wasm"): # ammo.js 用 instantiateStreaming,类型不对会退回慢路径 + return "application/wasm" + return super().guess_type(path) + + def _send_bytes(self, data, ctype): + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def _model_file(self, tok, rel): + """/model//:只给登记过的模型文件夹里的文件;图片按内容给类型,DDS 等现转 PNG。""" + folder = self.backend.dirs.get(tok) + if not folder: + return self.send_error(404) + rel = urllib.parse.unquote(rel).replace("\\", "/") + p = os.path.normpath(os.path.join(folder, *[x for x in rel.split("/") if x not in ("", ".")])) + try: + inside = os.path.commonpath([folder, p]) == folder + except ValueError: + inside = False + if not inside or not os.path.isfile(p): + # 贴图不在 PMX 记的位置:和转换时一样按文件名在模型文件夹里找(vrmio.TextureFinder) + import vrmio + with self.backend.lock: + finder = self.backend.finders.get(tok) + if finder is None: + finder = self.backend.finders[tok] = vrmio.TextureFinder(folder) + p = finder.find(rel.rsplit("/", 1)[-1])[0] if rel.lower().endswith(vrmio.IMAGE_EXTS) else None + try: + inside = bool(p) and os.path.commonpath([folder, os.path.abspath(p)]) == folder + except ValueError: + inside = False + if not inside: + return self.send_error(404) + with open(p, "rb") as f: + data = f.read() + low = p.lower() + if low.endswith(".pmx"): + return self._send_bytes(data, "application/octet-stream") + if low.endswith(".tga"): # MMDLoader 自己用 TGALoader 解 + return self._send_bytes(data, "image/x-tga") + head = data[:8] + if head.startswith(b"\x89PNG"): + return self._send_bytes(data, "image/png") + if head.startswith(b"\xff\xd8\xff"): + return self._send_bytes(data, "image/jpeg") + if head.startswith(b"BM"): # .bmp / .spa / .sph(球面贴图其实是 BMP) + return self._send_bytes(data, "image/bmp") + if head.startswith((b"GIF8", b"RIFF")): + return self._send_bytes(data, "image/gif" if head.startswith(b"GIF8") else "image/webp") + try: # DDS 等浏览器不认的:现转 PNG + import vrmio + png = vrmio.decode_image(data) + except Exception: # noqa: BLE001 + png = None + if png: + return self._send_bytes(png, "image/png" if png[:4] == b"\x89PNG" else "image/jpeg") + return self._send_bytes(data, "application/octet-stream") + + def translate_path(self, path): + p = urllib.parse.unquote(urllib.parse.urlsplit(path).path) + root, rel = (VIEWER, p[len("/viewer/"):]) if p.startswith("/viewer/") else (WEB, p.lstrip("/")) + parts = [x for x in rel.split("/") if x not in ("", ".", "..")] + return os.path.join(root, *parts) if parts else os.path.join(root, "index.html") + + def _json(self, obj, code=200): + data = json.dumps(obj, ensure_ascii=False).encode("utf-8") + self.send_response(code) + self.send_header("Content-Type", "application/json; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + b = self.backend + b.last_seen = time.time() + u = urllib.parse.urlsplit(self.path) + if u.path == "/api/state": + return self._json(b.state()) + if u.path == "/api/events": + after = int(urllib.parse.parse_qs(u.query).get("after", ["0"])[0] or 0) + return self._json({"events": b.wait_events(after)}) + if u.path == "/api/ping": + return self._json({}) + if u.path.startswith("/model/"): + parts = u.path.split("/", 3) + return self._model_file(parts[2], parts[3] if len(parts) > 3 else "") + if u.path.startswith("/file/"): + tok = u.path.split("/")[2] + p = b.tokens.get(tok) + if not p or not os.path.isfile(p): + return self.send_error(404) + size = os.path.getsize(p) + self.send_response(200) + self.send_header("Content-Type", "image/png" if p.lower().endswith(".png") else "model/gltf-binary") + self.send_header("Content-Length", str(size)) + self.end_headers() + with open(p, "rb") as f: + shutil.copyfileobj(f, self.wfile, 1 << 20) + return + return super().do_GET() + + def do_POST(self): + b = self.backend + b.last_seen = time.time() + u = urllib.parse.urlsplit(self.path) + if u.path == "/api/upload": # 请求体是文件内容,不是 JSON + q = urllib.parse.parse_qs(u.query) + return self._json(b.upload(q.get("key", [""])[0], q.get("path", [""])[0], self.rfile, + int(self.headers.get("Content-Length", 0) or 0))) + try: + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))) or b"{}") + except ValueError: + return self._json({"error": "bad json"}, 400) + route = u.path + if route == "/api/add": + return self._json({"added": b.add_paths(body.get("paths") or [])}) + if route == "/api/upload/done": + return self._json({"added": b.upload_done(body.get("items"))}) + if route == "/api/pick": + return self._json({"added": b.add_paths(b.pick(folder=bool(body.get("folder"))))}) + if route == "/api/pick_ue_ref": + return self._json(b.pick_ue_ref()) + if route == "/api/pick_output": + r = b.pick(output=True) + return self._json({"folder": r[0] if r else ""}) + if route == "/api/remove": + b.remove(body.get("ids") or []) + return self._json({}) + if route == "/api/clear": + b.clear() + return self._json({}) + if route == "/api/options": + b.set_options(body.get("opts"), body.get("lang"), body.get("ui")) + return self._json({"opts": b.opts, "lang": b.lang}) + if route == "/api/convert": + return self._json({"started": b.convert(body.get("ids"))}) + if route == "/api/stop": + b.stop() + return self._json({}) + if route == "/api/preview": + return self._json(b.preview(body.get("id"), body.get("output"))) + if route == "/api/open": + return self._json({"ok": b.reveal(body.get("path"))}) + if route == "/api/tune": + return self._json(b.tune_info(body.get("id"), body.get("model"))) + if route == "/api/tune/save": + return self._json(b.tune_save(body.get("id"), body.get("edits"))) + if route == "/api/tune/thumb": + return self._json(b.tune_thumb(body.get("id"), body.get("data"), bool(body.get("auto")), body.get("model"))) + if route == "/api/snapshot": + return self._json({"path": b.snapshot(body.get("name"), body.get("data", ""), body.get("model"))}) + return self._json({"error": "unknown"}, 404) + + +def serve(port=0): + """启动后端和 HTTP 服务(后台线程),返回 (backend, server, url)。""" + backend = Backend() + handler = type("BoundHandler", (Handler,), {"backend": backend}) + srv = ThreadingHTTPServer(("127.0.0.1", port), handler) + srv.daemon_threads = True + threading.Thread(target=srv.serve_forever, daemon=True).start() + return backend, srv, "http://127.0.0.1:%d/" % srv.server_address[1] diff --git a/ui/version.py b/ui/version.py new file mode 100644 index 0000000..8c00de7 --- /dev/null +++ b/ui/version.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +"""版本号(唯一来源)。界面顶栏、exe 的「属性 → 详细信息」和发布包的文件名都从这里取; +发版时打的 tag(v0.1.0)必须和它一致,tools/build_release.py --expect-version 会检查。""" +__version__ = "1.0.7" diff --git a/ui/viewer/vendor/README.md b/ui/viewer/vendor/README.md new file mode 100644 index 0000000..e4e5c63 --- /dev/null +++ b/ui/viewer/vendor/README.md @@ -0,0 +1,11 @@ +# 第三方前端库(离线预览用) + +| 库 | 版本 | 许可证 | 来源 | +|---|---|---|---| +| three.js(`three.module.min.js`,`addons/` 下的 GLTFLoader、BufferGeometryUtils、OrbitControls) | 0.169.0 | MIT(`three/LICENSE`) | npm `three` | +| three.js 的 MMD 组件(`addons/loaders/MMDLoader.js`、`TGALoader.js`,`addons/libs/mmdparser.module.js`,`addons/shaders/MMDToonShader.js`,`addons/animation/MMDAnimationHelper.js`、`CCDIKSolver.js`、`MMDPhysics.js`) | 0.169.0 | MIT(`three/LICENSE`) | npm `three` 的 `examples/jsm` | +| ammo.js(Bullet 物理的 WebAssembly 版,`addons/libs/ammo.wasm.js` + `ammo.wasm.wasm`,PMX 预览的 MMD 物理用) | three 0.169.0 附带的版本 | zlib(`ammo/LICENSE`) | npm `three` 的 `examples/jsm/libs` | +| @pixiv/three-vrm(`three-vrm.module.min.js`) | 3.5.5 | MIT(`three-vrm/LICENSE`) | npm `@pixiv/three-vrm` | + +升级时和 `tools/qa/harness/package.json` 保持同一版本,预览和动态测试才是同一套物理。 +three.js 在 0.169 之后的版本里把 MMD 组件标成了弃用,升级 three 时要另找 PMX 的加载方式。 diff --git a/ui/viewer/vendor/ammo/LICENSE b/ui/viewer/vendor/ammo/LICENSE new file mode 100644 index 0000000..0fe05a5 --- /dev/null +++ b/ui/viewer/vendor/ammo/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2011 ammo.js contributors + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + +1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. +2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. +3. This notice may not be removed or altered from any source distribution. + +--- + +See AUTHORS for list of contributors. + diff --git a/ui/viewer/vendor/three-vrm/LICENSE b/ui/viewer/vendor/three-vrm/LICENSE new file mode 100644 index 0000000..ed87d5f --- /dev/null +++ b/ui/viewer/vendor/three-vrm/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2019-2026 pixiv Inc. + +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/ui/viewer/vendor/three-vrm/three-vrm.module.min.js b/ui/viewer/vendor/three-vrm/three-vrm.module.min.js new file mode 100644 index 0000000..6140e38 --- /dev/null +++ b/ui/viewer/vendor/three-vrm/three-vrm.module.min.js @@ -0,0 +1,983 @@ +/*! (c) 2019-2026 pixiv Inc. - https://github.com/pixiv/three-vrm/blob/release/LICENSE */ +var ye=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())});import*as Cn from"three";import*as Z from"three";import*as dt from"three";import*as Fn from"three";import*as D from"three";import*as Q from"three";import*as ze from"three";import*as F from"three";import*as P from"three";import*as Pe from"three";import*as J from"three";import*as I from"three";import*as mt from"three";import*as H from"three";import*as lt from"three";import*as $n from"three";var y=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())}),cn=class extends Cn.Object3D{constructor(t){super(),this.weight=0,this.isBinary=!1,this.overrideBlink="none",this.overrideLookAt="none",this.overrideMouth="none",this._binds=[],this.name=`VRMExpression_${t}`,this.expressionName=t,this.type="VRMExpression",this.visible=!1}get binds(){return this._binds}get overrideBlinkAmount(){return this.overrideBlink==="block"?0.5?1:0:this.weight}addBind(t){this._binds.push(t)}deleteBind(t){let e=this._binds.indexOf(t);e>=0&&this._binds.splice(e,1)}applyWeight(t){var e;let n=this.outputWeight;n*=(e=t==null?void 0:t.multiplier)!=null?e:1,this.isBinary&&n<1&&(n=0),this._binds.forEach(i=>i.applyWeight(n))}clearAppliedWeight(){this._binds.forEach(t=>t.clearAppliedWeight())}};function On(t,e,n){var i,r;let o=t.parser.json,s=(i=o.nodes)==null?void 0:i[e];if(s==null)return console.warn(`extractPrimitivesInternal: Attempt to use nodes[${e}] of glTF but the node doesn't exist`),null;let l=s.mesh;if(l==null)return null;let a=(r=o.meshes)==null?void 0:r[l];if(a==null)return console.warn(`extractPrimitivesInternal: Attempt to use meshes[${l}] of glTF but the mesh doesn't exist`),null;let u=a.primitives.length,d=[];return n.traverse(h=>{d.length{let o=On(t,r,i);o!=null&&n.set(r,o)}),n})}var ot={Aa:"aa",Ih:"ih",Ou:"ou",Ee:"ee",Oh:"oh",Blink:"blink",Happy:"happy",Angry:"angry",Sad:"sad",Relaxed:"relaxed",LookUp:"lookUp",Surprised:"surprised",LookDown:"lookDown",LookLeft:"lookLeft",LookRight:"lookRight",BlinkLeft:"blinkLeft",BlinkRight:"blinkRight",Neutral:"neutral"};function Un(t){return Math.max(Math.min(t,1),0)}var mn=class Bn{constructor(){this.blinkExpressionNames=["blink","blinkLeft","blinkRight"],this.lookAtExpressionNames=["lookLeft","lookRight","lookUp","lookDown"],this.mouthExpressionNames=["aa","ee","ih","oh","ou"],this._expressions=[],this._expressionMap={}}get expressions(){return this._expressions.concat()}get expressionMap(){return Object.assign({},this._expressionMap)}get presetExpressionMap(){let e={},n=new Set(Object.values(ot));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)&&(e[i]=r)}),e}get customExpressionMap(){let e={},n=new Set(Object.values(ot));return Object.entries(this._expressionMap).forEach(([i,r])=>{n.has(i)||(e[i]=r)}),e}copy(e){return this._expressions.concat().forEach(i=>{this.unregisterExpression(i)}),e._expressions.forEach(i=>{this.registerExpression(i)}),this.blinkExpressionNames=e.blinkExpressionNames.concat(),this.lookAtExpressionNames=e.lookAtExpressionNames.concat(),this.mouthExpressionNames=e.mouthExpressionNames.concat(),this}clone(){return new Bn().copy(this)}getExpression(e){var n;return(n=this._expressionMap[e])!=null?n:null}registerExpression(e){this._expressions.push(e),this._expressionMap[e.expressionName]=e}unregisterExpression(e){let n=this._expressions.indexOf(e);n===-1&&console.warn("VRMExpressionManager: The specified expressions is not registered"),this._expressions.splice(n,1),delete this._expressionMap[e.expressionName]}getValue(e){var n;let i=this.getExpression(e);return(n=i==null?void 0:i.weight)!=null?n:null}setValue(e,n){let i=this.getExpression(e);i&&(i.weight=Un(n))}resetValues(){this._expressions.forEach(e=>{e.weight=0})}getExpressionTrackName(e){let n=this.getExpression(e);return n?`${n.name}.weight`:null}update(){let e=this._calculateWeightMultipliers();this._expressions.forEach(n=>{n.clearAppliedWeight()}),this._expressions.forEach(n=>{let i=1,r=n.expressionName;this.blinkExpressionNames.indexOf(r)!==-1&&(i*=e.blink),this.lookAtExpressionNames.indexOf(r)!==-1&&(i*=e.lookAt),this.mouthExpressionNames.indexOf(r)!==-1&&(i*=e.mouth),n.applyWeight({multiplier:i})})}_calculateWeightMultipliers(){let e=1,n=1,i=1;return this._expressions.forEach(r=>{e-=r.overrideBlinkAmount,n-=r.overrideLookAtAmount,i-=r.overrideMouthAmount}),e=Math.max(0,e),n=Math.max(0,n),i=Math.max(0,i),{blink:e,lookAt:n,mouth:i}}},we={Color:"color",EmissionColor:"emissionColor",ShadeColor:"shadeColor",MatcapColor:"matcapColor",RimColor:"rimColor",OutlineColor:"outlineColor"},fr={_Color:we.Color,_EmissionColor:we.EmissionColor,_ShadeColor:we.ShadeColor,_RimColor:we.RimColor,_OutlineColor:we.OutlineColor},mr=new dt.Color,Nn=class Dn{constructor({material:e,type:n,targetValue:i,targetAlpha:r}){this.material=e,this.type=n,this.targetValue=i,this.targetAlpha=r!=null?r:1;let o=this._initColorBindState(),s=this._initAlphaBindState();this._state={color:o,alpha:s}}applyWeight(e){let{color:n,alpha:i}=this._state;if(n!=null){let{propertyName:r,deltaValue:o}=n,s=this.material[r];s!=null&&s.add(mr.copy(o).multiplyScalar(e))}if(i!=null){let{propertyName:r,deltaValue:o}=i;this.material[r]!=null&&(this.material[r]+=o*e)}}clearAppliedWeight(){let{color:e,alpha:n}=this._state;if(e!=null){let{propertyName:i,initialValue:r}=e,o=this.material[i];o!=null&&o.copy(r)}if(n!=null){let{propertyName:i,initialValue:r}=n;this.material[i]!=null&&(this.material[i]=r)}}_initColorBindState(){var e,n,i;let{material:r,type:o,targetValue:s}=this,l=this._getPropertyNameMap(),a=(n=(e=l==null?void 0:l[o])==null?void 0:e[0])!=null?n:null;if(a==null)return console.warn(`Tried to add a material color bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${o} but the material or the type is not supported.`),null;let d=r[a].clone(),h=new dt.Color(s.r-d.r,s.g-d.g,s.b-d.b);return{propertyName:a,initialValue:d,deltaValue:h}}_initAlphaBindState(){var e,n,i;let{material:r,type:o,targetAlpha:s}=this,l=this._getPropertyNameMap(),a=(n=(e=l==null?void 0:l[o])==null?void 0:e[1])!=null?n:null;if(a==null&&s!==1)return console.warn(`Tried to add a material alpha bind to the material ${(i=r.name)!=null?i:"(no name)"}, the type ${o} but the material or the type does not support alpha.`),null;if(a==null)return null;let u=r[a],d=s-u;return{propertyName:a,initialValue:u,deltaValue:d}}_getPropertyNameMap(){var e,n;return(n=(e=Object.entries(Dn._propertyNameMapMap).find(([i])=>this.material[i]===!0))==null?void 0:e[1])!=null?n:null}};Nn._propertyNameMapMap={isMeshStandardMaterial:{color:["color","opacity"],emissionColor:["emissive",null]},isMeshBasicMaterial:{color:["color","opacity"]},isMToonMaterial:{color:["color","opacity"],emissionColor:["emissive",null],outlineColor:["outlineColorFactor",null],matcapColor:["matcapFactor",null],rimColor:["parametricRimColorFactor",null],shadeColor:["shadeColorFactor",null]}};var gn=Nn,Ae=class{constructor({primitives:t,index:e,weight:n}){this.primitives=t,this.index=e,this.weight=n}applyWeight(t){this.primitives.forEach(e=>{var n;((n=e.morphTargetInfluences)==null?void 0:n[this.index])!=null&&(e.morphTargetInfluences[this.index]+=this.weight*t)})}clearAppliedWeight(){this.primitives.forEach(t=>{var e;((e=t.morphTargetInfluences)==null?void 0:e[this.index])!=null&&(t.morphTargetInfluences[this.index]=0)})}},_n=new Fn.Vector2,kn=class Wn{constructor({material:e,scale:n,offset:i}){var r,o;this.material=e,this.scale=n,this.offset=i;let s=(r=Object.entries(Wn._propertyNamesMap).find(([l])=>e[l]===!0))==null?void 0:r[1];s==null?(console.warn(`Tried to add a texture transform bind to the material ${(o=e.name)!=null?o:"(no name)"} but the material is not supported.`),this._properties=[]):(this._properties=[],s.forEach(l=>{var a;let u=(a=e[l])==null?void 0:a.clone();if(!u)return null;e[l]=u;let d=u.offset.clone(),h=u.repeat.clone(),c=i.clone().sub(d),p=n.clone().sub(h);this._properties.push({name:l,initialOffset:d,deltaOffset:c,initialScale:h,deltaScale:p})}))}applyWeight(e){this._properties.forEach(n=>{let i=this.material[n.name];i!==void 0&&(i.offset.add(_n.copy(n.deltaOffset).multiplyScalar(e)),i.repeat.add(_n.copy(n.deltaScale).multiplyScalar(e)))})}clearAppliedWeight(){this._properties.forEach(e=>{let n=this.material[e.name];n!==void 0&&(n.offset.copy(e.initialOffset),n.repeat.copy(e.initialScale))})}};kn._propertyNamesMap={isMeshStandardMaterial:["map","emissiveMap","bumpMap","normalMap","displacementMap","roughnessMap","metalnessMap","alphaMap"],isMeshBasicMaterial:["map","specularMap","alphaMap"],isMToonMaterial:["map","normalMap","emissiveMap","shadeMultiplyTexture","rimMultiplyTexture","outlineWidthMultiplyTexture","uvAnimationMaskTexture"]};var vn=kn,gr=new Set(["1.0","1.0-beta"]),Gn=class zn{get name(){return"VRMExpressionLoaderPlugin"}constructor(e){this.parser=e}afterRoot(e){return y(this,null,function*(){e.userData.vrmExpressionManager=yield this._import(e)})}_import(e){return y(this,null,function*(){let n=yield this._v1Import(e);if(n)return n;let i=yield this._v0Import(e);return i||null})}_v1Import(e){return y(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let s=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;let l=s.specVersion;if(!gr.has(l))return console.warn(`VRMExpressionLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let a=s.expressions;if(!a)return null;let u=new Set(Object.values(ot)),d=new Map;a.preset!=null&&Object.entries(a.preset).forEach(([c,p])=>{if(p!=null){if(!u.has(c)){console.warn(`VRMExpressionLoaderPlugin: Unknown preset name "${c}" detected. Ignoring the expression`);return}d.set(c,p)}}),a.custom!=null&&Object.entries(a.custom).forEach(([c,p])=>{if(u.has(c)){console.warn(`VRMExpressionLoaderPlugin: Custom expression cannot have preset name "${c}". Ignoring the expression`);return}d.set(c,p)});let h=new mn;return yield Promise.all(Array.from(d.entries()).map(c=>y(this,[c],function*([p,f]){var m,g,_,M,T,R,v;let E=new cn(p);if(e.scene.add(E),E.isBinary=(m=f.isBinary)!=null?m:!1,E.overrideBlink=(g=f.overrideBlink)!=null?g:"none",E.overrideLookAt=(_=f.overrideLookAt)!=null?_:"none",E.overrideMouth=(M=f.overrideMouth)!=null?M:"none",(T=f.morphTargetBinds)==null||T.forEach(x=>y(this,null,function*(){var S;if(x.node===void 0||x.index===void 0)return;let L=yield pn(e,x.node),A=x.index;if(!L.every(b=>Array.isArray(b.morphTargetInfluences)&&A{let L=S.material;L&&(Array.isArray(L)?x.push(...L):x.push(L))}),(R=f.materialColorBinds)==null||R.forEach(S=>y(this,null,function*(){x.filter(A=>{var b;let V=(b=this.parser.associations.get(A))==null?void 0:b.materials;return S.material===V}).forEach(A=>{E.addBind(new gn({material:A,type:S.type,targetValue:new Z.Color().fromArray(S.targetValue),targetAlpha:S.targetValue[3]}))})})),(v=f.textureTransformBinds)==null||v.forEach(S=>y(this,null,function*(){x.filter(A=>{var b;let V=(b=this.parser.associations.get(A))==null?void 0:b.materials;return S.material===V}).forEach(A=>{var b,V;E.addBind(new vn({material:A,offset:new Z.Vector2().fromArray((b=S.offset)!=null?b:[0,0]),scale:new Z.Vector2().fromArray((V=S.scale)!=null?V:[1,1])}))})}))}h.registerExpression(E)}))),h})}_v0Import(e){return y(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let o=r.blendShapeMaster;if(!o)return null;let s=new mn,l=o.blendShapeGroups;if(!l)return s;let a=new Set;return yield Promise.all(l.map(u=>y(this,null,function*(){var d;let h=u.presetName,c=h!=null&&zn.v0v1PresetNameMap[h]||null,p=c!=null?c:u.name;if(p==null){console.warn("VRMExpressionLoaderPlugin: One of custom expressions has no name. Ignoring the expression");return}if(a.has(p)){console.warn(`VRMExpressionLoaderPlugin: An expression preset ${h} has duplicated entries. Ignoring the expression`);return}a.add(p);let f=new cn(p);e.scene.add(f),f.isBinary=(d=u.isBinary)!=null?d:!1,u.binds&&u.binds.forEach(g=>y(this,null,function*(){var _;if(g.mesh===void 0||g.index===void 0)return;let M=[];if((_=i.nodes)==null||_.forEach((R,v)=>{R.mesh===g.mesh&&M.push(v)}),M.length===0){console.warn(`VRMExpressionLoaderPlugin: ${u.name} attempts to bind a morph target to the mesh #${g.mesh} but the mesh is not found or not used in the scene. Ignoring the bind.`);return}let T=g.index;yield Promise.all(M.map(R=>y(this,null,function*(){var v;let E=yield pn(e,R);if(!E.every(x=>Array.isArray(x.morphTargetInfluences)&&T{if(g.materialName===void 0||g.propertyName===void 0||g.targetValue===void 0)return;let _=[];e.scene.traverse(T=>{if(T.material){let R=T.material;Array.isArray(R)?_.push(...R.filter(v=>(v.name===g.materialName||v.name===g.materialName+" (Outline)")&&_.indexOf(v)===-1)):R.name===g.materialName&&_.indexOf(R)===-1&&_.push(R)}});let M=g.propertyName;_.forEach(T=>{if(M==="_MainTex_ST"){let v=new Z.Vector2(g.targetValue[0],g.targetValue[1]),E=new Z.Vector2(g.targetValue[2],g.targetValue[3]);E.y=1-E.y-v.y,f.addBind(new vn({material:T,scale:v,offset:E}));return}let R=fr[M];if(R){f.addBind(new gn({material:T,type:R,targetValue:new Z.Color().fromArray(g.targetValue),targetAlpha:g.targetValue[3]}));return}console.warn(M+" is not supported")})}),s.registerExpression(f)}))),s})}};Gn.v0v1PresetNameMap={a:"aa",e:"ee",i:"ih",o:"oh",u:"ou",blink:"blink",joy:"happy",angry:"angry",sorrow:"sad",fun:"relaxed",lookup:"lookUp",lookdown:"lookDown",lookleft:"lookLeft",lookright:"lookRight",blink_l:"blinkLeft",blink_r:"blinkRight",neutral:"neutral"};var ht=Gn,hs={None:"none",Block:"block",Blend:"blend"},ct=class fe{constructor(e,n){this._firstPersonOnlyLayer=fe.DEFAULT_FIRSTPERSON_ONLY_LAYER,this._thirdPersonOnlyLayer=fe.DEFAULT_THIRDPERSON_ONLY_LAYER,this._initializedLayers=!1,this.humanoid=e,this.meshAnnotations=n}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMFirstPerson: humanoid must be same in order to copy");return this.meshAnnotations=e.meshAnnotations.map(n=>({meshes:n.meshes.concat(),type:n.type})),this}clone(){return new fe(this.humanoid,this.meshAnnotations).copy(this)}get firstPersonOnlyLayer(){return this._firstPersonOnlyLayer}get thirdPersonOnlyLayer(){return this._thirdPersonOnlyLayer}setup({firstPersonOnlyLayer:e=fe.DEFAULT_FIRSTPERSON_ONLY_LAYER,thirdPersonOnlyLayer:n=fe.DEFAULT_THIRDPERSON_ONLY_LAYER}={}){this._initializedLayers||(this._firstPersonOnlyLayer=e,this._thirdPersonOnlyLayer=n,this.meshAnnotations.forEach(i=>{i.meshes.forEach(r=>{i.type==="firstPersonOnly"?(r.layers.set(this._firstPersonOnlyLayer),r.traverse(o=>o.layers.set(this._firstPersonOnlyLayer))):i.type==="thirdPersonOnly"?(r.layers.set(this._thirdPersonOnlyLayer),r.traverse(o=>o.layers.set(this._thirdPersonOnlyLayer))):i.type==="auto"&&this._createHeadlessModel(r)})}),this._initializedLayers=!0)}_excludeTriangles(e,n,i,r){let o=0;if(n!=null&&n.length>0)for(let s=0;s0&&r.includes(h[0])||d[1]>0&&r.includes(h[1])||d[2]>0&&r.includes(h[2])||d[3]>0&&r.includes(h[3]))continue;let c=n[a],p=i[a];if(c[0]>0&&r.includes(p[0])||c[1]>0&&r.includes(p[1])||c[2]>0&&r.includes(p[2])||c[3]>0&&r.includes(p[3]))continue;let f=n[u],m=i[u];f[0]>0&&r.includes(m[0])||f[1]>0&&r.includes(m[1])||f[2]>0&&r.includes(m[2])||f[3]>0&&r.includes(m[3])||(e[o++]=l,e[o++]=a,e[o++]=u)}return o}_createErasedMesh(e,n){let i=new D.SkinnedMesh(e.geometry.clone(),e.material);i.name=`${e.name}(erase)`,i.frustumCulled=e.frustumCulled,i.layers.set(this._firstPersonOnlyLayer);let r=i.geometry,o=r.getAttribute("skinIndex"),s=o instanceof D.GLBufferAttribute?[]:o.array,l=[];for(let m=0;m{this._isEraseTarget(o)&&i.push(s)}),!i.length){n.layers.enable(this._thirdPersonOnlyLayer),n.layers.enable(this._firstPersonOnlyLayer);return}n.layers.set(this._thirdPersonOnlyLayer);let r=this._createErasedMesh(n,i);e.add(r)}_createHeadlessModel(e){if(e.type==="Group")if(e.layers.set(this._thirdPersonOnlyLayer),this._isEraseTarget(e))e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer));else{let n=new D.Group;n.name=`_headless_${e.name}`,n.layers.set(this._firstPersonOnlyLayer),e.parent.add(n),e.children.filter(i=>i.type==="SkinnedMesh").forEach(i=>{let r=i;this._createHeadlessModelForSkinnedMesh(n,r)})}else if(e.type==="SkinnedMesh"){let n=e;this._createHeadlessModelForSkinnedMesh(e.parent,n)}else this._isEraseTarget(e)&&(e.layers.set(this._thirdPersonOnlyLayer),e.traverse(n=>n.layers.set(this._thirdPersonOnlyLayer)))}_isEraseTarget(e){return e===this.humanoid.getRawBoneNode("head")?!0:e.parent?this._isEraseTarget(e.parent):!1}};ct.DEFAULT_FIRSTPERSON_ONLY_LAYER=9;ct.DEFAULT_THIRDPERSON_ONLY_LAYER=10;var En=ct,_r=new Set(["1.0","1.0-beta"]),pt=class{get name(){return"VRMFirstPersonLoaderPlugin"}constructor(t){this.parser=t}afterRoot(t){return y(this,null,function*(){let e=t.userData.vrmHumanoid;if(e!==null){if(e===void 0)throw new Error("VRMFirstPersonLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");t.userData.vrmFirstPerson=yield this._import(t,e)}})}_import(t,e){return y(this,null,function*(){if(e==null)return null;let n=yield this._v1Import(t,e);if(n)return n;let i=yield this._v0Import(t,e);return i||null})}_v1Import(t,e){return y(this,null,function*(){var n,i;let r=this.parser.json;if(!(((n=r.extensionsUsed)==null?void 0:n.indexOf("VRMC_vrm"))!==-1))return null;let s=(i=r.extensions)==null?void 0:i.VRMC_vrm;if(!s)return null;let l=s.specVersion;if(!_r.has(l))return console.warn(`VRMFirstPersonLoaderPlugin: Unknown VRMC_vrm specVersion "${l}"`),null;let a=s.firstPerson,u=[],d=yield fn(t);return Array.from(d.entries()).forEach(([h,c])=>{var p,f;let m=(p=a==null?void 0:a.meshAnnotations)==null?void 0:p.find(g=>g.node===h);u.push({meshes:c,type:(f=m==null?void 0:m.type)!=null?f:"auto"})}),new En(e,u)})}_v0Import(t,e){return y(this,null,function*(){var n;let i=this.parser.json,r=(n=i.extensions)==null?void 0:n.VRM;if(!r)return null;let o=r.firstPerson;if(!o)return null;let s=[],l=yield fn(t);return Array.from(l.entries()).forEach(([a,u])=>{let d=i.nodes[a],h=o.meshAnnotations?o.meshAnnotations.find(c=>c.mesh===d.mesh):void 0;s.push({meshes:u,type:this._convertV0FlagToV1Type(h==null?void 0:h.firstPersonFlag)})}),new En(e,s)})}_convertV0FlagToV1Type(t){return t==="FirstPersonOnly"?"firstPersonOnly":t==="ThirdPersonOnly"?"thirdPersonOnly":t==="Both"?"both":"auto"}},cs={Auto:"auto",Both:"both",ThirdPersonOnly:"thirdPersonOnly",FirstPersonOnly:"firstPersonOnly"},Mn=new Q.Vector3,Rn=new Q.Vector3,vr=new Q.Quaternion,Tn=class extends Q.Group{constructor(t){super(),this.vrmHumanoid=t,this._boneAxesMap=new Map,Object.values(t.humanBones).forEach(e=>{let n=new Q.AxesHelper(1);n.matrixAutoUpdate=!1,n.material.depthTest=!1,n.material.depthWrite=!1,this.add(n),this._boneAxesMap.set(e,n)})}dispose(){Array.from(this._boneAxesMap.values()).forEach(t=>{t.geometry.dispose(),t.material.dispose()})}updateMatrixWorld(t){Array.from(this._boneAxesMap.entries()).forEach(([e,n])=>{e.node.updateWorldMatrix(!0,!1),e.node.matrixWorld.decompose(Mn,vr,Rn);let i=Mn.set(.1,.1,.1).divide(Rn);n.matrix.copy(e.node.matrixWorld).scale(i)}),super.updateMatrixWorld(t)}},tt=["hips","spine","chest","upperChest","neck","head","leftEye","rightEye","jaw","leftUpperLeg","leftLowerLeg","leftFoot","leftToes","rightUpperLeg","rightLowerLeg","rightFoot","rightToes","leftShoulder","leftUpperArm","leftLowerArm","leftHand","rightShoulder","rightUpperArm","rightLowerArm","rightHand","leftThumbMetacarpal","leftThumbProximal","leftThumbDistal","leftIndexProximal","leftIndexIntermediate","leftIndexDistal","leftMiddleProximal","leftMiddleIntermediate","leftMiddleDistal","leftRingProximal","leftRingIntermediate","leftRingDistal","leftLittleProximal","leftLittleIntermediate","leftLittleDistal","rightThumbMetacarpal","rightThumbProximal","rightThumbDistal","rightIndexProximal","rightIndexIntermediate","rightIndexDistal","rightMiddleProximal","rightMiddleIntermediate","rightMiddleDistal","rightRingProximal","rightRingIntermediate","rightRingDistal","rightLittleProximal","rightLittleIntermediate","rightLittleDistal"],ps={Hips:"hips",Spine:"spine",Chest:"chest",UpperChest:"upperChest",Neck:"neck",Head:"head",LeftEye:"leftEye",RightEye:"rightEye",Jaw:"jaw",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",LeftToes:"leftToes",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",RightToes:"rightToes",LeftShoulder:"leftShoulder",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightShoulder:"rightShoulder",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand",LeftThumbMetacarpal:"leftThumbMetacarpal",LeftThumbProximal:"leftThumbProximal",LeftThumbDistal:"leftThumbDistal",LeftIndexProximal:"leftIndexProximal",LeftIndexIntermediate:"leftIndexIntermediate",LeftIndexDistal:"leftIndexDistal",LeftMiddleProximal:"leftMiddleProximal",LeftMiddleIntermediate:"leftMiddleIntermediate",LeftMiddleDistal:"leftMiddleDistal",LeftRingProximal:"leftRingProximal",LeftRingIntermediate:"leftRingIntermediate",LeftRingDistal:"leftRingDistal",LeftLittleProximal:"leftLittleProximal",LeftLittleIntermediate:"leftLittleIntermediate",LeftLittleDistal:"leftLittleDistal",RightThumbMetacarpal:"rightThumbMetacarpal",RightThumbProximal:"rightThumbProximal",RightThumbDistal:"rightThumbDistal",RightIndexProximal:"rightIndexProximal",RightIndexIntermediate:"rightIndexIntermediate",RightIndexDistal:"rightIndexDistal",RightMiddleProximal:"rightMiddleProximal",RightMiddleIntermediate:"rightMiddleIntermediate",RightMiddleDistal:"rightMiddleDistal",RightRingProximal:"rightRingProximal",RightRingIntermediate:"rightRingIntermediate",RightRingDistal:"rightRingDistal",RightLittleProximal:"rightLittleProximal",RightLittleIntermediate:"rightLittleIntermediate",RightLittleDistal:"rightLittleDistal"},Er={hips:null,spine:"hips",chest:"spine",upperChest:"chest",neck:"upperChest",head:"neck",leftEye:"head",rightEye:"head",jaw:"head",leftUpperLeg:"hips",leftLowerLeg:"leftUpperLeg",leftFoot:"leftLowerLeg",leftToes:"leftFoot",rightUpperLeg:"hips",rightLowerLeg:"rightUpperLeg",rightFoot:"rightLowerLeg",rightToes:"rightFoot",leftShoulder:"upperChest",leftUpperArm:"leftShoulder",leftLowerArm:"leftUpperArm",leftHand:"leftLowerArm",rightShoulder:"upperChest",rightUpperArm:"rightShoulder",rightLowerArm:"rightUpperArm",rightHand:"rightLowerArm",leftThumbMetacarpal:"leftHand",leftThumbProximal:"leftThumbMetacarpal",leftThumbDistal:"leftThumbProximal",leftIndexProximal:"leftHand",leftIndexIntermediate:"leftIndexProximal",leftIndexDistal:"leftIndexIntermediate",leftMiddleProximal:"leftHand",leftMiddleIntermediate:"leftMiddleProximal",leftMiddleDistal:"leftMiddleIntermediate",leftRingProximal:"leftHand",leftRingIntermediate:"leftRingProximal",leftRingDistal:"leftRingIntermediate",leftLittleProximal:"leftHand",leftLittleIntermediate:"leftLittleProximal",leftLittleDistal:"leftLittleIntermediate",rightThumbMetacarpal:"rightHand",rightThumbProximal:"rightThumbMetacarpal",rightThumbDistal:"rightThumbProximal",rightIndexProximal:"rightHand",rightIndexIntermediate:"rightIndexProximal",rightIndexDistal:"rightIndexIntermediate",rightMiddleProximal:"rightHand",rightMiddleIntermediate:"rightMiddleProximal",rightMiddleDistal:"rightMiddleIntermediate",rightRingProximal:"rightHand",rightRingIntermediate:"rightRingProximal",rightRingDistal:"rightRingIntermediate",rightLittleProximal:"rightHand",rightLittleIntermediate:"rightLittleProximal",rightLittleDistal:"rightLittleIntermediate"};function jn(t){return t.invert?t.invert():t.inverse(),t}var se=new ze.Vector3,ae=new ze.Quaternion,st=class{constructor(t){this.humanBones=t,this.restPose=this.getAbsolutePose()}getAbsolutePose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);i&&(se.copy(i.position),ae.copy(i.quaternion),t[n]={position:se.toArray(),rotation:ae.toArray()})}),t}getPose(){let t={};return Object.keys(this.humanBones).forEach(e=>{let n=e,i=this.getBoneNode(n);if(!i)return;se.set(0,0,0),ae.identity();let r=this.restPose[n];r!=null&&r.position&&se.fromArray(r.position).negate(),r!=null&&r.rotation&&jn(ae.fromArray(r.rotation)),se.add(i.position),ae.premultiply(i.quaternion),t[n]={position:se.toArray(),rotation:ae.toArray()}}),t}setPose(t){Object.entries(t).forEach(([e,n])=>{let i=e,r=this.getBoneNode(i);if(!r)return;let o=this.restPose[i];o&&(n!=null&&n.position&&(r.position.fromArray(n.position),o.position&&r.position.add(se.fromArray(o.position))),n!=null&&n.rotation&&(r.quaternion.fromArray(n.rotation),o.rotation&&r.quaternion.multiply(ae.fromArray(o.rotation))))})}resetPose(){Object.entries(this.restPose).forEach(([t,e])=>{let n=this.getBoneNode(t);n&&(e!=null&&e.position&&n.position.fromArray(e.position),e!=null&&e.rotation&&n.quaternion.fromArray(e.rotation))})}getBone(t){var e;return(e=this.humanBones[t])!=null?e:void 0}getBoneNode(t){var e,n;return(n=(e=this.humanBones[t])==null?void 0:e.node)!=null?n:null}},nt=new F.Vector3,Mr=new F.Quaternion,Rr=new F.Vector3,xn=class Xn extends st{static _setupTransforms(e){let n=new F.Object3D;n.name="VRMHumanoidRig";let i={},r={},o={},s={};tt.forEach(a=>{var u;let d=e.getBoneNode(a);if(d){let h=new F.Vector3,c=new F.Quaternion;d.updateWorldMatrix(!0,!1),d.matrixWorld.decompose(h,c,nt),i[a]=h,r[a]=c,o[a]=d.quaternion.clone();let p=new F.Quaternion;(u=d.parent)==null||u.matrixWorld.decompose(nt,p,nt),s[a]=p}});let l={};return tt.forEach(a=>{var u;let d=e.getBoneNode(a);if(d){let h=i[a],c=a,p;for(;p==null&&(c=Er[c],c!=null);)p=i[c];let f=new F.Object3D;f.name="Normalized_"+d.name,(c?(u=l[c])==null?void 0:u.node:n).add(f),f.position.copy(h),p&&f.position.sub(p),l[a]={node:f}}}),{rigBones:l,root:n,parentWorldRotations:s,boneRotations:o}}constructor(e){let{rigBones:n,root:i,parentWorldRotations:r,boneRotations:o}=Xn._setupTransforms(e);super(n),this.original=e,this.root=i,this._parentWorldRotations=r,this._boneRotations=o}update(){tt.forEach(e=>{let n=this.original.getBoneNode(e);if(n!=null){let i=this.getBoneNode(e),r=this._parentWorldRotations[e],o=Mr.copy(r).invert(),s=this._boneRotations[e];if(n.quaternion.copy(i.quaternion).multiply(r).premultiply(o).multiply(s),e==="hips"){let l=i.getWorldPosition(Rr);n.parent.updateWorldMatrix(!0,!1);let a=n.parent.matrixWorld,u=l.applyMatrix4(a.invert());n.position.copy(u)}}})}},yn=class Qn{get restPose(){return console.warn("VRMHumanoid: restPose is deprecated. Use either rawRestPose or normalizedRestPose instead."),this.rawRestPose}get rawRestPose(){return this._rawHumanBones.restPose}get normalizedRestPose(){return this._normalizedHumanBones.restPose}get humanBones(){return this._rawHumanBones.humanBones}get rawHumanBones(){return this._rawHumanBones.humanBones}get normalizedHumanBones(){return this._normalizedHumanBones.humanBones}get normalizedHumanBonesRoot(){return this._normalizedHumanBones.root}constructor(e,n){var i;this.autoUpdateHumanBones=(i=n==null?void 0:n.autoUpdateHumanBones)!=null?i:!0,this._rawHumanBones=new st(e),this._normalizedHumanBones=new xn(this._rawHumanBones)}copy(e){return this.autoUpdateHumanBones=e.autoUpdateHumanBones,this._rawHumanBones=new st(e.humanBones),this._normalizedHumanBones=new xn(this._rawHumanBones),this}clone(){return new Qn(this.humanBones,{autoUpdateHumanBones:this.autoUpdateHumanBones}).copy(this)}getAbsolutePose(){return console.warn("VRMHumanoid: getAbsolutePose() is deprecated. Use either getRawAbsolutePose() or getNormalizedAbsolutePose() instead."),this.getRawAbsolutePose()}getRawAbsolutePose(){return this._rawHumanBones.getAbsolutePose()}getNormalizedAbsolutePose(){return this._normalizedHumanBones.getAbsolutePose()}getPose(){return console.warn("VRMHumanoid: getPose() is deprecated. Use either getRawPose() or getNormalizedPose() instead."),this.getRawPose()}getRawPose(){return this._rawHumanBones.getPose()}getNormalizedPose(){return this._normalizedHumanBones.getPose()}setPose(e){return console.warn("VRMHumanoid: setPose() is deprecated. Use either setRawPose() or setNormalizedPose() instead."),this.setRawPose(e)}setRawPose(e){return this._rawHumanBones.setPose(e)}setNormalizedPose(e){return this._normalizedHumanBones.setPose(e)}resetPose(){return console.warn("VRMHumanoid: resetPose() is deprecated. Use either resetRawPose() or resetNormalizedPose() instead."),this.resetRawPose()}resetRawPose(){return this._rawHumanBones.resetPose()}resetNormalizedPose(){return this._normalizedHumanBones.resetPose()}getBone(e){return console.warn("VRMHumanoid: getBone() is deprecated. Use either getRawBone() or getNormalizedBone() instead."),this.getRawBone(e)}getRawBone(e){return this._rawHumanBones.getBone(e)}getNormalizedBone(e){return this._normalizedHumanBones.getBone(e)}getBoneNode(e){return console.warn("VRMHumanoid: getBoneNode() is deprecated. Use either getRawBoneNode() or getNormalizedBoneNode() instead."),this.getRawBoneNode(e)}getRawBoneNode(e){return this._rawHumanBones.getBoneNode(e)}getNormalizedBoneNode(e){return this._normalizedHumanBones.getBoneNode(e)}update(){this.autoUpdateHumanBones&&this._normalizedHumanBones.update()}},Tr={Hips:"hips",Spine:"spine",Head:"head",LeftUpperLeg:"leftUpperLeg",LeftLowerLeg:"leftLowerLeg",LeftFoot:"leftFoot",RightUpperLeg:"rightUpperLeg",RightLowerLeg:"rightLowerLeg",RightFoot:"rightFoot",LeftUpperArm:"leftUpperArm",LeftLowerArm:"leftLowerArm",LeftHand:"leftHand",RightUpperArm:"rightUpperArm",RightLowerArm:"rightLowerArm",RightHand:"rightHand"},xr=new Set(["1.0","1.0-beta"]),wn={leftThumbProximal:"leftThumbMetacarpal",leftThumbIntermediate:"leftThumbProximal",rightThumbProximal:"rightThumbMetacarpal",rightThumbIntermediate:"rightThumbProximal"},ft=class{get name(){return"VRMHumanoidLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot,this.autoUpdateHumanBones=e==null?void 0:e.autoUpdateHumanBones}afterRoot(t){return y(this,null,function*(){t.userData.vrmHumanoid=yield this._import(t)})}_import(t){return y(this,null,function*(){let e=yield this._v1Import(t);if(e)return e;let n=yield this._v0Import(t);return n||null})}_v1Import(t){return y(this,null,function*(){var e,n;let i=this.parser.json;if(!(((e=i.extensionsUsed)==null?void 0:e.indexOf("VRMC_vrm"))!==-1))return null;let o=(n=i.extensions)==null?void 0:n.VRMC_vrm;if(!o)return null;let s=o.specVersion;if(!xr.has(s))return console.warn(`VRMHumanoidLoaderPlugin: Unknown VRMC_vrm specVersion "${s}"`),null;let l=o.humanoid;if(!l)return null;let a=l.humanBones.leftThumbIntermediate!=null||l.humanBones.rightThumbIntermediate!=null,u={};l.humanBones!=null&&(yield Promise.all(Object.entries(l.humanBones).map(h=>y(this,[h],function*([c,p]){let f=c,m=p.node;if(a){let _=wn[f];_!=null&&(f=_)}let g=yield this.parser.getDependency("node",m);if(g==null){console.warn(`A glTF node bound to the humanoid bone ${f} (index = ${m}) does not exist`);return}u[f]={node:g}}))));let d=new yn(this._ensureRequiredBonesExist(u),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(d.normalizedHumanBonesRoot),this.helperRoot){let h=new Tn(d);this.helperRoot.add(h),h.renderOrder=this.helperRoot.renderOrder}return d})}_v0Import(t){return y(this,null,function*(){var e;let i=(e=this.parser.json.extensions)==null?void 0:e.VRM;if(!i)return null;let r=i.humanoid;if(!r)return null;let o={};r.humanBones!=null&&(yield Promise.all(r.humanBones.map(l=>y(this,null,function*(){let a=l.bone,u=l.node;if(a==null||u==null)return;if(u<0){console.warn(`A glTF node index for the humanoid bone ${a} is negative (${u}), ignoring this bone.`);return}let d=yield this.parser.getDependency("node",u);if(d==null){console.warn(`A glTF node bound to the humanoid bone ${a} (index = ${u}) does not exist`);return}let h=wn[a],c=h!=null?h:a;if(o[c]!=null){console.warn(`Multiple bone entries for ${c} detected (index = ${u}), ignoring duplicated entries.`);return}o[c]={node:d}}))));let s=new yn(this._ensureRequiredBonesExist(o),{autoUpdateHumanBones:this.autoUpdateHumanBones});if(t.scene.add(s.normalizedHumanBonesRoot),this.helperRoot){let l=new Tn(s);this.helperRoot.add(l),l.renderOrder=this.helperRoot.renderOrder}return s})}_ensureRequiredBonesExist(t){let e=Object.values(Tr).filter(n=>t[n]==null);if(e.length>0)throw new Error(`VRMHumanoidLoaderPlugin: These humanoid bones are required but not exist: ${e.join(", ")}`);return t}},Sn=class extends Pe.BufferGeometry{constructor(){super(),this._currentTheta=0,this._currentRadius=0,this.theta=0,this.radius=0,this._currentTheta=0,this._currentRadius=0,this._attrPos=new Pe.BufferAttribute(new Float32Array(195),3),this.setAttribute("position",this._attrPos),this._attrIndex=new Pe.BufferAttribute(new Uint16Array(189),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentTheta!==this.theta&&(this._currentTheta=this.theta,t=!0),this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),t&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,0,0,0);for(let t=0;t<64;t++){let e=t/63*this._currentTheta;this._attrPos.setXYZ(t+1,this._currentRadius*Math.sin(e),0,this._currentRadius*Math.cos(e))}this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<63;t++)this._attrIndex.setXYZ(t*3,0,t+1,t+2);this._attrIndex.needsUpdate=!0}},yr=class extends J.BufferGeometry{constructor(){super(),this.radius=0,this._currentRadius=0,this.tail=new J.Vector3,this._currentTail=new J.Vector3,this._attrPos=new J.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new J.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentRadius!==this.radius&&(this._currentRadius=this.radius,t=!0),this._currentTail.equals(this.tail)||(this._currentTail.copy(this.tail),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Fe=new P.Quaternion,An=new P.Quaternion,Se=new P.Vector3,Pn=new P.Vector3,bn=Math.sqrt(2)/2,wr=new P.Quaternion(0,0,-bn,bn),Sr=new P.Vector3(0,1,0),Ar=class extends P.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.vrmLookAt=t;{let e=new Sn;e.radius=.5;let n=new P.MeshBasicMaterial({color:65280,transparent:!0,opacity:.5,side:P.DoubleSide,depthTest:!1,depthWrite:!1});this._meshPitch=new P.Mesh(e,n),this.add(this._meshPitch)}{let e=new Sn;e.radius=.5;let n=new P.MeshBasicMaterial({color:16711680,transparent:!0,opacity:.5,side:P.DoubleSide,depthTest:!1,depthWrite:!1});this._meshYaw=new P.Mesh(e,n),this.add(this._meshYaw)}{let e=new yr;e.radius=.1;let n=new P.LineBasicMaterial({color:16777215,depthTest:!1,depthWrite:!1});this._lineTarget=new P.LineSegments(e,n),this._lineTarget.frustumCulled=!1,this.add(this._lineTarget)}}dispose(){this._meshYaw.geometry.dispose(),this._meshYaw.material.dispose(),this._meshPitch.geometry.dispose(),this._meshPitch.material.dispose(),this._lineTarget.geometry.dispose(),this._lineTarget.material.dispose()}updateMatrixWorld(t){let e=P.MathUtils.DEG2RAD*this.vrmLookAt.yaw;this._meshYaw.geometry.theta=e,this._meshYaw.geometry.update();let n=P.MathUtils.DEG2RAD*this.vrmLookAt.pitch;this._meshPitch.geometry.theta=n,this._meshPitch.geometry.update(),this.vrmLookAt.getLookAtWorldPosition(Se),this.vrmLookAt.getLookAtWorldQuaternion(Fe),Fe.multiply(this.vrmLookAt.getFaceFrontQuaternion(An)),this._meshYaw.position.copy(Se),this._meshYaw.quaternion.copy(Fe),this._meshPitch.position.copy(Se),this._meshPitch.quaternion.copy(Fe),this._meshPitch.quaternion.multiply(An.setFromAxisAngle(Sr,e)),this._meshPitch.quaternion.multiply(wr);let{target:i,autoUpdate:r}=this.vrmLookAt;i!=null&&r&&(i.getWorldPosition(Pn).sub(Se),this._lineTarget.geometry.tail.copy(Pn),this._lineTarget.geometry.update(),this._lineTarget.position.copy(Se)),super.updateMatrixWorld(t)}},Pr=new mt.Vector3,br=new mt.Vector3;function at(t,e){return t.matrixWorld.decompose(Pr,e,br),e}function We(t){return[Math.atan2(-t.z,t.x),Math.atan2(t.y,Math.sqrt(t.x*t.x+t.z*t.z))]}function Hn(t){let e=Math.round(t/2/Math.PI);return t-2*Math.PI*e}var Ln=new I.Vector3(0,0,1),Hr=new I.Vector3,Lr=new I.Vector3,Ir=new I.Vector3,Vr=new I.Quaternion,it=new I.Quaternion,In=new I.Quaternion,Cr=new I.Quaternion,rt=new I.Euler,Yn=class qn{constructor(e,n){this.offsetFromHeadBone=new I.Vector3,this.autoUpdate=!0,this.faceFront=new I.Vector3(0,0,1),this.humanoid=e,this.applier=n,this._yaw=0,this._pitch=0,this._needsUpdate=!0,this._restHeadWorldQuaternion=this.getLookAtWorldQuaternion(new I.Quaternion)}get yaw(){return this._yaw}set yaw(e){this._yaw=e,this._needsUpdate=!0}get pitch(){return this._pitch}set pitch(e){this._pitch=e,this._needsUpdate=!0}get euler(){return console.warn("VRMLookAt: euler is deprecated. use getEuler() instead."),this.getEuler(new I.Euler)}getEuler(e){return e.set(I.MathUtils.DEG2RAD*this._pitch,I.MathUtils.DEG2RAD*this._yaw,0,"YXZ")}copy(e){if(this.humanoid!==e.humanoid)throw new Error("VRMLookAt: humanoid must be same in order to copy");return this.offsetFromHeadBone.copy(e.offsetFromHeadBone),this.applier=e.applier,this.autoUpdate=e.autoUpdate,this.target=e.target,this.faceFront.copy(e.faceFront),this}clone(){return new qn(this.humanoid,this.applier).copy(this)}reset(){this._yaw=0,this._pitch=0,this._needsUpdate=!0}getLookAtWorldPosition(e){let n=this.humanoid.getRawBoneNode("head");return e.copy(this.offsetFromHeadBone).applyMatrix4(n.matrixWorld)}getLookAtWorldQuaternion(e){let n=this.humanoid.getRawBoneNode("head");return at(n,e)}getFaceFrontQuaternion(e){if(this.faceFront.distanceToSquared(Ln)<.01)return e.copy(this._restHeadWorldQuaternion).invert();let[n,i]=We(this.faceFront);return rt.set(0,.5*Math.PI+n,i,"YZX"),e.setFromEuler(rt).premultiply(Cr.copy(this._restHeadWorldQuaternion).invert())}getLookAtWorldDirection(e){return this.getLookAtWorldQuaternion(it),this.getFaceFrontQuaternion(In),e.copy(Ln).applyQuaternion(it).applyQuaternion(In).applyEuler(this.getEuler(rt))}lookAt(e){let n=Vr.copy(this._restHeadWorldQuaternion).multiply(jn(this.getLookAtWorldQuaternion(it))),i=this.getLookAtWorldPosition(Lr),r=Ir.copy(e).sub(i).applyQuaternion(n).normalize(),[o,s]=We(this.faceFront),[l,a]=We(r),u=Hn(l-o),d=Hn(s-a);this._yaw=I.MathUtils.RAD2DEG*u,this._pitch=I.MathUtils.RAD2DEG*d,this._needsUpdate=!0}update(e){this.target!=null&&this.autoUpdate&&this.lookAt(this.target.getWorldPosition(Hr)),this._needsUpdate&&(this._needsUpdate=!1,this.applier.applyYawPitch(this._yaw,this._pitch))}};Yn.EULER_ORDER="YXZ";var Or=Yn,Ur=new H.Vector3(0,0,1),W=new H.Quaternion,pe=new H.Quaternion,B=new H.Euler(0,0,0,"YXZ"),Ge=class{constructor(t,e,n,i,r){this.humanoid=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r,this.faceFront=new H.Vector3(0,0,1),this._restQuatLeftEye=new H.Quaternion,this._restQuatRightEye=new H.Quaternion,this._restLeftEyeParentWorldQuat=new H.Quaternion,this._restRightEyeParentWorldQuat=new H.Quaternion;let o=this.humanoid.getRawBoneNode("leftEye"),s=this.humanoid.getRawBoneNode("rightEye");o&&(this._restQuatLeftEye.copy(o.quaternion),at(o.parent,this._restLeftEyeParentWorldQuat)),s&&(this._restQuatRightEye.copy(s.quaternion),at(s.parent,this._restRightEyeParentWorldQuat))}applyYawPitch(t,e){let n=this.humanoid.getRawBoneNode("leftEye"),i=this.humanoid.getRawBoneNode("rightEye"),r=this.humanoid.getNormalizedBoneNode("leftEye"),o=this.humanoid.getNormalizedBoneNode("rightEye");n&&(e<0?B.x=-H.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):B.x=H.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?B.y=-H.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(-t):B.y=H.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(t),W.setFromEuler(B),this._getWorldFaceFrontQuat(pe),r.quaternion.copy(pe).multiply(W).multiply(pe.invert()),W.copy(this._restLeftEyeParentWorldQuat),n.quaternion.copy(r.quaternion).multiply(W).premultiply(W.invert()).multiply(this._restQuatLeftEye)),i&&(e<0?B.x=-H.MathUtils.DEG2RAD*this.rangeMapVerticalDown.map(-e):B.x=H.MathUtils.DEG2RAD*this.rangeMapVerticalUp.map(e),t<0?B.y=-H.MathUtils.DEG2RAD*this.rangeMapHorizontalOuter.map(-t):B.y=H.MathUtils.DEG2RAD*this.rangeMapHorizontalInner.map(t),W.setFromEuler(B),this._getWorldFaceFrontQuat(pe),o.quaternion.copy(pe).multiply(W).multiply(pe.invert()),W.copy(this._restRightEyeParentWorldQuat),i.quaternion.copy(o.quaternion).multiply(W).premultiply(W.invert()).multiply(this._restQuatRightEye))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=H.MathUtils.RAD2DEG*t.y,n=H.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}_getWorldFaceFrontQuat(t){if(this.faceFront.distanceToSquared(Ur)<.01)return t.identity();let[e,n]=We(this.faceFront);return B.set(0,.5*Math.PI+e,n,"YZX"),t.setFromEuler(B)}};Ge.type="bone";var ut=class{constructor(t,e,n,i,r){this.expressions=t,this.rangeMapHorizontalInner=e,this.rangeMapHorizontalOuter=n,this.rangeMapVerticalDown=i,this.rangeMapVerticalUp=r}applyYawPitch(t,e){e<0?(this.expressions.setValue("lookDown",0),this.expressions.setValue("lookUp",this.rangeMapVerticalUp.map(-e))):(this.expressions.setValue("lookUp",0),this.expressions.setValue("lookDown",this.rangeMapVerticalDown.map(e))),t<0?(this.expressions.setValue("lookLeft",0),this.expressions.setValue("lookRight",this.rangeMapHorizontalOuter.map(-t))):(this.expressions.setValue("lookRight",0),this.expressions.setValue("lookLeft",this.rangeMapHorizontalOuter.map(t)))}lookAt(t){console.warn("VRMLookAtBoneApplier: lookAt() is deprecated. use apply() instead.");let e=lt.MathUtils.RAD2DEG*t.y,n=lt.MathUtils.RAD2DEG*t.x;this.applyYawPitch(e,n)}};ut.type="expression";var Vn=class{constructor(t,e){this.inputMaxValue=t,this.outputScale=e}map(t){return this.outputScale*Un(t/this.inputMaxValue)}},Br=new Set(["1.0","1.0-beta"]),ke=.01,gt=class{get name(){return"VRMLookAtLoaderPlugin"}constructor(t,e){this.parser=t,this.helperRoot=e==null?void 0:e.helperRoot}afterRoot(t){return y(this,null,function*(){let e=t.userData.vrmHumanoid;if(e===null)return;if(e===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmHumanoid is undefined. VRMHumanoidLoaderPlugin have to be used first");let n=t.userData.vrmExpressionManager;if(n!==null){if(n===void 0)throw new Error("VRMLookAtLoaderPlugin: vrmExpressionManager is undefined. VRMExpressionLoaderPlugin have to be used first");t.userData.vrmLookAt=yield this._import(t,e,n)}})}_import(t,e,n){return y(this,null,function*(){if(e==null||n==null)return null;let i=yield this._v1Import(t,e,n);if(i)return i;let r=yield this._v0Import(t,e,n);return r||null})}_v1Import(t,e,n){return y(this,null,function*(){var i,r,o;let s=this.parser.json;if(!(((i=s.extensionsUsed)==null?void 0:i.indexOf("VRMC_vrm"))!==-1))return null;let a=(r=s.extensions)==null?void 0:r.VRMC_vrm;if(!a)return null;let u=a.specVersion;if(!Br.has(u))return console.warn(`VRMLookAtLoaderPlugin: Unknown VRMC_vrm specVersion "${u}"`),null;let d=a.lookAt;if(!d)return null;let h=d.type==="expression"?1:10,c=this._v1ImportRangeMap(d.rangeMapHorizontalInner,h),p=this._v1ImportRangeMap(d.rangeMapHorizontalOuter,h),f=this._v1ImportRangeMap(d.rangeMapVerticalDown,h),m=this._v1ImportRangeMap(d.rangeMapVerticalUp,h),g;d.type==="expression"?g=new ut(n,c,p,f,m):g=new Ge(e,c,p,f,m);let _=this._importLookAt(e,g);return _.offsetFromHeadBone.fromArray((o=d.offsetFromHeadBone)!=null?o:[0,.06,0]),_})}_v1ImportRangeMap(t,e){var n,i;let r=(n=t==null?void 0:t.inputMaxValue)!=null?n:90,o=(i=t==null?void 0:t.outputScale)!=null?i:e;return r(console.error(s),console.warn("VRMMetaLoaderPlugin: Failed to load a thumbnail image"),null))})}},vt=class{constructor(t){this.scene=t.scene,this.meta=t.meta,this.humanoid=t.humanoid,this.expressionManager=t.expressionManager,this.firstPerson=t.firstPerson,this.lookAt=t.lookAt}update(t){this.humanoid.update(),this.lookAt&&this.lookAt.update(t),this.expressionManager&&this.expressionManager.update()}},ms=class{get name(){return"VRMC_vrm"}constructor(t,e){var n,i,r,o,s;this.parser=t;let l=e==null?void 0:e.helperRoot,a=e==null?void 0:e.autoUpdateHumanBones;this.expressionPlugin=(n=e==null?void 0:e.expressionPlugin)!=null?n:new ht(t),this.firstPersonPlugin=(i=e==null?void 0:e.firstPersonPlugin)!=null?i:new pt(t),this.humanoidPlugin=(r=e==null?void 0:e.humanoidPlugin)!=null?r:new ft(t,{helperRoot:l,autoUpdateHumanBones:a}),this.lookAtPlugin=(o=e==null?void 0:e.lookAtPlugin)!=null?o:new gt(t,{helperRoot:l}),this.metaPlugin=(s=e==null?void 0:e.metaPlugin)!=null?s:new _t(t)}afterRoot(t){return y(this,null,function*(){yield this.metaPlugin.afterRoot(t),yield this.humanoidPlugin.afterRoot(t),yield this.expressionPlugin.afterRoot(t),yield this.lookAtPlugin.afterRoot(t),yield this.firstPersonPlugin.afterRoot(t);let e=t.userData.vrmMeta,n=t.userData.vrmHumanoid;if(e&&n){let i=new vt({scene:t.scene,expressionManager:t.userData.vrmExpressionManager,firstPerson:t.userData.vrmFirstPerson,humanoid:n,lookAt:t.userData.vrmLookAt,meta:e});t.userData.vrmCore=i}})}};var be=class extends vt{constructor(e){super(e),this.materials=e.materials,this.springBoneManager=e.springBoneManager,this.nodeConstraintManager=e.nodeConstraintManager}update(e){super.update(e),this.nodeConstraintManager&&this.nodeConstraintManager.update(),this.springBoneManager&&this.springBoneManager.update(e),this.materials&&this.materials.forEach(n=>{n.update&&n.update(e)})}};import*as Xe from"three";import*as ti from"three";import*as ni from"three";import*as w from"three";import*as ii from"three";var Fr=Object.defineProperty,Zn=Object.getOwnPropertySymbols,kr=Object.prototype.hasOwnProperty,Wr=Object.prototype.propertyIsEnumerable,Jn=(t,e,n)=>e in t?Fr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kn=(t,e)=>{for(var n in e||(e={}))kr.call(e,n)&&Jn(t,n,e[n]);if(Zn)for(var n of Zn(e))Wr.call(e,n)&&Jn(t,n,e[n]);return t},le=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())}),Gr={"":3e3,srgb:3001};function zr(t,e){parseInt(ni.REVISION,10)>=152?t.colorSpace=e:t.encoding=Gr[e]}var jr=class{get pending(){return Promise.all(this._pendings)}constructor(t,e){this._parser=t,this._materialParams=e,this._pendings=[]}assignPrimitive(t,e){e!=null&&(this._materialParams[t]=e)}assignColor(t,e,n){if(e!=null){let i=new ti.Color().fromArray(e);n&&i.convertSRGBToLinear(),this._materialParams[t]=i}}assignTexture(t,e,n){return le(this,null,function*(){let i=le(this,null,function*(){if(e!=null){let r=yield this._parser.assignTexture(this._materialParams,t,e);if(r==null){console.warn("GLTFMToonMaterialParamsAssignHelper: Failed to load texture. The rendering result may be wrong");return}n&&zr(r,"srgb")}});return this._pendings.push(i),i})}assignTextureByIndex(t,e,n){return le(this,null,function*(){return this.assignTexture(t,e!=null?{index:e}:void 0,n)})}},Xr=`// #define PHONG + +varying vec3 vViewPosition; + +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif + +#include + +// #include +#ifdef MTOON_USE_UV + varying vec2 vUv; + + // COMPAT: pre-r151 uses a common uvTransform + #if THREE_VRM_THREE_REVISION < 151 + uniform mat3 uvTransform; + #endif +#endif + +// #include +// COMAPT: pre-r151 uses uv2 for lightMap and aoMap +#if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + attribute vec2 uv2; + varying vec2 vUv2; + uniform mat3 uv2Transform; + #endif +#endif + +// #include +// #include +#include +#include +#include +#include +#include +#include +#include + +#ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE + uniform sampler2D outlineWidthMultiplyTexture; + uniform mat3 outlineWidthMultiplyTextureUvTransform; +#endif + +uniform float outlineWidthFactor; + +void main() { + + // #include + #ifdef MTOON_USE_UV + // COMPAT: pre-r151 uses a common uvTransform + #if THREE_VRM_THREE_REVISION >= 151 + vUv = uv; + #else + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #endif + + // #include + // COMAPT: pre-r151 uses uv2 for lightMap and aoMap + #if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + vUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy; + #endif + #endif + + #include + + #include + #include + #include + #include + + // we need this to compute the outline properly + objectNormal = normalize( objectNormal ); + + #include + + #ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED + vNormal = normalize( transformedNormal ); + #endif + + #include + + #include + #include + // #include + #include + #include + #include + + vViewPosition = - mvPosition.xyz; + + #ifdef OUTLINE + float worldNormalLength = length( transformedNormal ); + vec3 outlineOffset = outlineWidthFactor * worldNormalLength * objectNormal; + + #ifdef USE_OUTLINEWIDTHMULTIPLYTEXTURE + vec2 outlineWidthMultiplyTextureUv = ( outlineWidthMultiplyTextureUvTransform * vec3( vUv, 1 ) ).xy; + float outlineTex = texture2D( outlineWidthMultiplyTexture, outlineWidthMultiplyTextureUv ).g; + outlineOffset *= outlineTex; + #endif + + #ifdef OUTLINE_WIDTH_SCREEN + outlineOffset *= vViewPosition.z / projectionMatrix[ 1 ].y; + #endif + + gl_Position = projectionMatrix * modelViewMatrix * vec4( outlineOffset + transformed, 1.0 ); + + gl_Position.z += 1E-6 * gl_Position.w; // anti-artifact magic + #endif + + #include + // #include + #include + #include + +}`,Qr=`// #define PHONG + +uniform vec3 litFactor; + +uniform float opacity; + +uniform vec3 shadeColorFactor; +#ifdef USE_SHADEMULTIPLYTEXTURE + uniform sampler2D shadeMultiplyTexture; + uniform mat3 shadeMultiplyTextureUvTransform; +#endif + +uniform float shadingShiftFactor; +uniform float shadingToonyFactor; + +#ifdef USE_SHADINGSHIFTTEXTURE + uniform sampler2D shadingShiftTexture; + uniform mat3 shadingShiftTextureUvTransform; + uniform float shadingShiftTextureScale; +#endif + +uniform float giEqualizationFactor; + +uniform vec3 parametricRimColorFactor; +#ifdef USE_RIMMULTIPLYTEXTURE + uniform sampler2D rimMultiplyTexture; + uniform mat3 rimMultiplyTextureUvTransform; +#endif +uniform float rimLightingMixFactor; +uniform float parametricRimFresnelPowerFactor; +uniform float parametricRimLiftFactor; + +#ifdef USE_MATCAPTEXTURE + uniform vec3 matcapFactor; + uniform sampler2D matcapTexture; + uniform mat3 matcapTextureUvTransform; +#endif + +uniform vec3 emissive; +uniform float emissiveIntensity; + +uniform vec3 outlineColorFactor; +uniform float outlineLightingMixFactor; + +#ifdef USE_UVANIMATIONMASKTEXTURE + uniform sampler2D uvAnimationMaskTexture; + uniform mat3 uvAnimationMaskTextureUvTransform; +#endif + +uniform float uvAnimationScrollXOffset; +uniform float uvAnimationScrollYOffset; +uniform float uvAnimationRotationPhase; + +#include +#include +#include +#include + +// #include +#if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + varying vec2 vUv; +#endif + +// #include +// COMAPT: pre-r151 uses uv2 for lightMap and aoMap +#if THREE_VRM_THREE_REVISION < 151 + #if defined( USE_LIGHTMAP ) || defined( USE_AOMAP ) + varying vec2 vUv2; + #endif +#endif + +#include + +#ifdef USE_MAP + uniform mat3 mapUvTransform; +#endif + +// #include + +#include + +#include +// #include +#include + +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapUvTransform; +#endif + +// #include +// #include +// #include +#include + +// #include +// COMPAT: pre-r151 doesn't have BRDF_Lambert in +#if THREE_VRM_THREE_REVISION < 151 + vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; + } +#endif + +#include + +#include + +// #include +varying vec3 vViewPosition; + +struct MToonMaterial { + vec3 diffuseColor; + vec3 shadeColor; + float shadingShift; +}; + +float linearstep( float a, float b, float t ) { + return clamp( ( t - a ) / ( b - a ), 0.0, 1.0 ); +} + +/** + * Convert NdotL into toon shading factor using shadingShift and shadingToony + */ +float getShading( + const in float dotNL, + const in float shadow, + const in float shadingShift +) { + float shading = dotNL; + shading = shading + shadingShift; + shading = linearstep( -1.0 + shadingToonyFactor, 1.0 - shadingToonyFactor, shading ); + shading *= shadow; + return shading; +} + +/** + * Mix diffuseColor and shadeColor using shading factor and light color + */ +vec3 getDiffuse( + const in MToonMaterial material, + const in float shading, + in vec3 lightColor +) { + #ifdef DEBUG_LITSHADERATE + return vec3( BRDF_Lambert( shading * lightColor ) ); + #endif + + vec3 col = lightColor * BRDF_Lambert( mix( material.shadeColor, material.diffuseColor, shading ) ); + + // The "comment out if you want to PBR absolutely" line + #ifdef V0_COMPAT_SHADE + col = min( col, material.diffuseColor ); + #endif + + return col; +} + +// COMPAT: pre-r156 uses a struct GeometricContext +#if THREE_VRM_THREE_REVISION >= 157 + void RE_Direct_MToon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { + float dotNL = clamp( dot( geometryNormal, directLight.direction ), -1.0, 1.0 ); + vec3 irradiance = directLight.color; + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + + irradiance *= dotNL; + + float shading = getShading( dotNL, shadow, material.shadingShift ); + + // toon shaded diffuse + reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); + } + + void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { + // indirect diffuse will use diffuseColor, no shadeColor involved + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + } +#else + void RE_Direct_MToon( const in IncidentLight directLight, const in GeometricContext geometry, const in MToonMaterial material, const in float shadow, inout ReflectedLight reflectedLight ) { + float dotNL = clamp( dot( geometry.normal, directLight.direction ), -1.0, 1.0 ); + vec3 irradiance = directLight.color; + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + + irradiance *= dotNL; + + float shading = getShading( dotNL, shadow, material.shadingShift ); + + // toon shaded diffuse + reflectedLight.directDiffuse += getDiffuse( material, shading, directLight.color ); + } + + void RE_IndirectDiffuse_MToon( const in vec3 irradiance, const in GeometricContext geometry, const in MToonMaterial material, inout ReflectedLight reflectedLight ) { + // indirect diffuse will use diffuseColor, no shadeColor involved + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + + // directSpecular will be used for rim lighting, not an actual specular + reflectedLight.directSpecular += irradiance; + } +#endif + +#define RE_Direct RE_Direct_MToon +#define RE_IndirectDiffuse RE_IndirectDiffuse_MToon +#define Material_LightProbeLOD( material ) (0) + +#include +// #include + +// #include +#ifdef USE_NORMALMAP + + uniform sampler2D normalMap; + uniform mat3 normalMapUvTransform; + uniform vec2 normalScale; + +#endif + +// COMPAT: pre-r151 +// USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 +#if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) + + uniform mat3 normalMatrix; + +#endif + +// COMPAT: pre-r151 +// USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( TANGENTSPACE_NORMALMAP ) ) + + // Per-Pixel Tangent Space Normal Mapping + // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html + + // three-vrm specific change: it requires \`uv\` as an input in order to support uv scrolls + + // Temporary compat against shader change @ Three.js r126, r151 + #if THREE_VRM_THREE_REVISION >= 151 + + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + + vec3 N = surf_norm; + + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + + return mat3( T * scale, B * scale, N ); + + } + + #else + + vec3 perturbNormal2Arb( vec2 uv, vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) { + + vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) ); + vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + + vec3 N = normalize( surf_norm ); + + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + + // three-vrm specific change: Workaround for the issue that happens when delta of uv = 0.0 + // TODO: Is this still required? Or shall I make a PR about it? + if ( length( T ) == 0.0 || length( B ) == 0.0 ) { + return surf_norm; + } + + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det ); + + return normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z ); + + } + + #endif + +#endif + +// #include +#include +#include + +// == post correction ========================================================== +void postCorrection() { + #include + #include + #include + #include + #include +} + +// == main procedure =========================================================== +void main() { + #include + + vec2 uv = vec2(0.5, 0.5); + + #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + uv = vUv; + + float uvAnimMask = 1.0; + #ifdef USE_UVANIMATIONMASKTEXTURE + vec2 uvAnimationMaskTextureUv = ( uvAnimationMaskTextureUvTransform * vec3( uv, 1 ) ).xy; + uvAnimMask = texture2D( uvAnimationMaskTexture, uvAnimationMaskTextureUv ).b; + #endif + + float uvRotCos = cos( uvAnimationRotationPhase * uvAnimMask ); + float uvRotSin = sin( uvAnimationRotationPhase * uvAnimMask ); + uv = mat2( uvRotCos, -uvRotSin, uvRotSin, uvRotCos ) * ( uv - 0.5 ) + 0.5; + uv = uv + vec2( uvAnimationScrollXOffset, uvAnimationScrollYOffset ) * uvAnimMask; + #endif + + #ifdef DEBUG_UV + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #if ( defined( MTOON_USE_UV ) && !defined( MTOON_UVS_VERTEX_ONLY ) ) + gl_FragColor = vec4( uv, 0.0, 1.0 ); + #endif + return; + #endif + + vec4 diffuseColor = vec4( litFactor, opacity ); + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive * emissiveIntensity; + + #include + + // #include + #ifdef USE_MAP + vec2 mapUv = ( mapUvTransform * vec3( uv, 1 ) ).xy; + vec4 sampledDiffuseColor = texture2D( map, mapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w ); + #endif + diffuseColor *= sampledDiffuseColor; + #endif + + // #include + #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) + diffuseColor.rgb *= vColor; + #endif + + // #include + + #include + + // #include + + // #include + float faceDirection = gl_FrontFacing ? 1.0 : -1.0; + + #ifdef FLAT_SHADED + + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); + + #else + + vec3 normal = normalize( vNormal ); + + #ifdef DOUBLE_SIDED + + normal *= faceDirection; + + #endif + + #endif + + #ifdef USE_NORMALMAP + + vec2 normalMapUv = ( normalMapUvTransform * vec3( uv, 1 ) ).xy; + + #endif + + #ifdef USE_NORMALMAP_TANGENTSPACE + + #ifdef USE_TANGENT + + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + + #else + + mat3 tbn = getTangentFrame( - vViewPosition, normal, normalMapUv ); + + #endif + + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + + #endif + + #endif + + #ifdef USE_CLEARCOAT_NORMALMAP + + #ifdef USE_TANGENT + + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + + #else + + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + + #endif + + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + + #endif + + #endif + + // non perturbed normal for clearcoat among others + + vec3 nonPerturbedNormal = normal; + + #ifdef OUTLINE + normal *= -1.0; + #endif + + // #include + + // COMPAT: pre-r151 + // USE_NORMALMAP_OBJECTSPACE used to be OBJECTSPACE_NORMALMAP in pre-r151 + #if defined( USE_NORMALMAP_OBJECTSPACE ) || defined( OBJECTSPACE_NORMALMAP ) + + normal = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; // overrides both flatShading and attribute normals + + #ifdef FLIP_SIDED + + normal = - normal; + + #endif + + #ifdef DOUBLE_SIDED + + normal = normal * faceDirection; + + #endif + + normal = normalize( normalMatrix * normal ); + + // COMPAT: pre-r151 + // USE_NORMALMAP_TANGENTSPACE used to be TANGENTSPACE_NORMALMAP in pre-r151 + #elif defined( USE_NORMALMAP_TANGENTSPACE ) || defined( TANGENTSPACE_NORMALMAP ) + + vec3 mapN = texture2D( normalMap, normalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + + // COMPAT: pre-r151 + #if THREE_VRM_THREE_REVISION >= 151 || defined( USE_TANGENT ) + + normal = normalize( tbn * mapN ); + + #else + + normal = perturbNormal2Arb( uv, -vViewPosition, normal, mapN, faceDirection ); + + #endif + + #endif + + // #include + #ifdef USE_EMISSIVEMAP + vec2 emissiveMapUv = ( emissiveMapUvTransform * vec3( uv, 1 ) ).xy; + totalEmissiveRadiance *= texture2D( emissiveMap, emissiveMapUv ).rgb; + #endif + + #ifdef DEBUG_NORMAL + gl_FragColor = vec4( 0.5 + 0.5 * normal, 1.0 ); + return; + #endif + + // -- MToon: lighting -------------------------------------------------------- + // accumulation + // #include + MToonMaterial material; + + material.diffuseColor = diffuseColor.rgb; + + material.shadeColor = shadeColorFactor; + #ifdef USE_SHADEMULTIPLYTEXTURE + vec2 shadeMultiplyTextureUv = ( shadeMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; + material.shadeColor *= texture2D( shadeMultiplyTexture, shadeMultiplyTextureUv ).rgb; + #endif + + #if ( defined( USE_COLOR ) && !defined( IGNORE_VERTEX_COLOR ) ) + material.shadeColor.rgb *= vColor; + #endif + + material.shadingShift = shadingShiftFactor; + #ifdef USE_SHADINGSHIFTTEXTURE + vec2 shadingShiftTextureUv = ( shadingShiftTextureUvTransform * vec3( uv, 1 ) ).xy; + material.shadingShift += texture2D( shadingShiftTexture, shadingShiftTextureUv ).r * shadingShiftTextureScale; + #endif + + // #include + + // MToon Specific changes: + // Since we want to take shadows into account of shading instead of irradiance, + // we had to modify the codes that multiplies the results of shadowmap into color of direct lights. + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + vec3 geometryPosition = - vViewPosition; + vec3 geometryNormal = normal; + vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + + vec3 geometryClearcoatNormal; + + #ifdef USE_CLEARCOAT + + geometryClearcoatNormal = clearcoatNormal; + + #endif + #else + GeometricContext geometry; + + geometry.position = - vViewPosition; + geometry.normal = normal; + geometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); + + #ifdef USE_CLEARCOAT + + geometry.clearcoatNormal = clearcoatNormal; + + #endif + #endif + + IncidentLight directLight; + + // since these variables will be used in unrolled loop, we have to define in prior + float shadow; + + #if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + + pointLight = pointLights[ i ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getPointLightInfo( pointLight, geometryPosition, directLight ); + #else + getPointLightInfo( pointLight, geometry, directLight ); + #endif + + shadow = 1.0; + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) + pointLightShadow = pointLightShadows[ i ]; + // COMPAT: pre-r166 + // r166 introduced shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #else + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #pragma unroll_loop_end + + #endif + + #if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + + SpotLight spotLight; + // COMPAT: pre-r144 uses NUM_SPOT_LIGHT_SHADOWS, r144+ uses NUM_SPOT_LIGHT_COORDS + #if THREE_VRM_THREE_REVISION >= 144 + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_COORDS > 0 + SpotLightShadow spotLightShadow; + #endif + #elif defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + + spotLight = spotLights[ i ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #else + getSpotLightInfo( spotLight, geometry, directLight ); + #endif + + shadow = 1.0; + // COMPAT: pre-r144 uses NUM_SPOT_LIGHT_SHADOWS and vSpotShadowCoord, r144+ uses NUM_SPOT_LIGHT_COORDS and vSpotLightCoord + // COMPAT: pre-r166 does not have shadowIntensity, r166+ has shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_COORDS ) + spotLightShadow = spotLightShadows[ i ]; + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + #elif THREE_VRM_THREE_REVISION >= 144 + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_COORDS ) + spotLightShadow = spotLightShadows[ i ]; + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + #elif defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0; + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #pragma unroll_loop_end + + #endif + + #if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + + directionalLight = directionalLights[ i ]; + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + getDirectionalLightInfo( directionalLight, directLight ); + #else + getDirectionalLightInfo( directionalLight, geometry, directLight ); + #endif + + shadow = 1.0; + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + // COMPAT: pre-r166 + // r166 introduced shadowIntensity + #if THREE_VRM_THREE_REVISION >= 166 + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #else + shadow = all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + #endif + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, shadow, reflectedLight ); + #else + RE_Direct( directLight, geometry, material, shadow, reflectedLight ); + #endif + + } + #pragma unroll_loop_end + + #endif + + // #if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + + // RectAreaLight rectAreaLight; + + // #pragma unroll_loop_start + // for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + + // rectAreaLight = rectAreaLights[ i ]; + // RE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight ); + + // } + // #pragma unroll_loop_end + + // #endif + + #if defined( RE_IndirectDiffuse ) + + vec3 iblIrradiance = vec3( 0.0 ); + + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + + // COMPAT: pre-r156 uses a struct GeometricContext + // COMPAT: pre-r156 doesn't have a define USE_LIGHT_PROBES + #if THREE_VRM_THREE_REVISION >= 157 + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #else + irradiance += getLightProbeIrradiance( lightProbe, geometry.normal ); + #endif + + #if ( NUM_HEMI_LIGHTS > 0 ) + + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + + // COMPAT: pre-r156 uses a struct GeometricContext + #if THREE_VRM_THREE_REVISION >= 157 + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + #else + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry.normal ); + #endif + + } + #pragma unroll_loop_end + + #endif + + #endif + + // #if defined( RE_IndirectSpecular ) + + // vec3 radiance = vec3( 0.0 ); + // vec3 clearcoatRadiance = vec3( 0.0 ); + + // #endif + + #include + #include + + // modulation + #include + + vec3 col = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + + #ifdef DEBUG_LITSHADERATE + gl_FragColor = vec4( col, diffuseColor.a ); + postCorrection(); + return; + #endif + + // -- MToon: rim lighting ----------------------------------------- + vec3 viewDir = normalize( vViewPosition ); + + #ifndef PHYSICALLY_CORRECT_LIGHTS + reflectedLight.directSpecular /= PI; + #endif + vec3 rimMix = mix( vec3( 1.0 ), reflectedLight.directSpecular, rimLightingMixFactor ); + + vec3 rim = parametricRimColorFactor * pow( saturate( 1.0 - dot( viewDir, normal ) + parametricRimLiftFactor ), parametricRimFresnelPowerFactor ); + + #ifdef USE_MATCAPTEXTURE + { + vec3 x = normalize( vec3( viewDir.z, 0.0, -viewDir.x ) ); + vec3 y = cross( viewDir, x ); // guaranteed to be normalized + vec2 sphereUv = 0.5 + 0.5 * vec2( dot( x, normal ), -dot( y, normal ) ); + sphereUv = ( matcapTextureUvTransform * vec3( sphereUv, 1 ) ).xy; + vec3 matcap = texture2D( matcapTexture, sphereUv ).rgb; + rim += matcapFactor * matcap; + } + #endif + + #ifdef USE_RIMMULTIPLYTEXTURE + vec2 rimMultiplyTextureUv = ( rimMultiplyTextureUvTransform * vec3( uv, 1 ) ).xy; + rim *= texture2D( rimMultiplyTexture, rimMultiplyTextureUv ).rgb; + #endif + + col += rimMix * rim; + + // -- MToon: Emission -------------------------------------------------------- + col += totalEmissiveRadiance; + + // #include + + // -- Almost done! ----------------------------------------------------------- + #if defined( OUTLINE ) + col = outlineColorFactor.rgb * mix( vec3( 1.0 ), col, outlineLightingMixFactor ); + #endif + + #ifdef OPAQUE + diffuseColor.a = 1.0; + #endif + + gl_FragColor = vec4( col, diffuseColor.a ); + postCorrection(); +} +`,Yr={None:"none",Normal:"normal",LitShadeRate:"litShadeRate",UV:"uv"},ei={None:"none",WorldCoordinates:"worldCoordinates",ScreenCoordinates:"screenCoordinates"},qr={3e3:"",3001:"srgb"};function Et(t){return parseInt(ii.REVISION,10)>=152?t.colorSpace:qr[t.encoding]}var $r=class extends w.ShaderMaterial{constructor(t={}){var e;super({vertexShader:Xr,fragmentShader:Qr}),this.uvAnimationScrollXSpeedFactor=0,this.uvAnimationScrollYSpeedFactor=0,this.uvAnimationRotationSpeedFactor=0,this.fog=!0,this.normalMapType=w.TangentSpaceNormalMap,this._ignoreVertexColor=!0,this._v0CompatShade=!1,this._debugMode=Yr.None,this._outlineWidthMode=ei.None,this._isOutline=!1,t.transparentWithZWrite&&(t.depthWrite=!0),delete t.transparentWithZWrite,t.fog=!0,t.lights=!0,t.clipping=!0,this.uniforms=w.UniformsUtils.merge([w.UniformsLib.common,w.UniformsLib.normalmap,w.UniformsLib.emissivemap,w.UniformsLib.fog,w.UniformsLib.lights,{litFactor:{value:new w.Color(1,1,1)},mapUvTransform:{value:new w.Matrix3},colorAlpha:{value:1},normalMapUvTransform:{value:new w.Matrix3},shadeColorFactor:{value:new w.Color(0,0,0)},shadeMultiplyTexture:{value:null},shadeMultiplyTextureUvTransform:{value:new w.Matrix3},shadingShiftFactor:{value:0},shadingShiftTexture:{value:null},shadingShiftTextureUvTransform:{value:new w.Matrix3},shadingShiftTextureScale:{value:1},shadingToonyFactor:{value:.9},giEqualizationFactor:{value:.9},matcapFactor:{value:new w.Color(1,1,1)},matcapTexture:{value:null},matcapTextureUvTransform:{value:new w.Matrix3},parametricRimColorFactor:{value:new w.Color(0,0,0)},rimMultiplyTexture:{value:null},rimMultiplyTextureUvTransform:{value:new w.Matrix3},rimLightingMixFactor:{value:1},parametricRimFresnelPowerFactor:{value:5},parametricRimLiftFactor:{value:0},emissive:{value:new w.Color(0,0,0)},emissiveIntensity:{value:1},emissiveMapUvTransform:{value:new w.Matrix3},outlineWidthMultiplyTexture:{value:null},outlineWidthMultiplyTextureUvTransform:{value:new w.Matrix3},outlineWidthFactor:{value:0},outlineColorFactor:{value:new w.Color(0,0,0)},outlineLightingMixFactor:{value:1},uvAnimationMaskTexture:{value:null},uvAnimationMaskTextureUvTransform:{value:new w.Matrix3},uvAnimationScrollXOffset:{value:0},uvAnimationScrollYOffset:{value:0},uvAnimationRotationPhase:{value:0}},(e=t.uniforms)!=null?e:{}]),this.setValues(t),this._uploadUniformsWorkaround(),this.customProgramCacheKey=()=>[...Object.entries(this._generateDefines()).map(([n,i])=>`${n}:${i}`),this.matcapTexture?`matcapTextureColorSpace:${Et(this.matcapTexture)}`:"",this.shadeMultiplyTexture?`shadeMultiplyTextureColorSpace:${Et(this.shadeMultiplyTexture)}`:"",this.rimMultiplyTexture?`rimMultiplyTextureColorSpace:${Et(this.rimMultiplyTexture)}`:""].join(","),this.onBeforeCompile=n=>{let i=parseInt(w.REVISION,10),r=Object.entries(Kn(Kn({},this._generateDefines()),this.defines)).filter(([o,s])=>!!s).map(([o,s])=>`#define ${o} ${s}`).join(` +`)+` +`;n.vertexShader=r+n.vertexShader,n.fragmentShader=r+n.fragmentShader,i<154&&(n.fragmentShader=n.fragmentShader.replace("#include ","#include "))}}get color(){return this.uniforms.litFactor.value}set color(t){this.uniforms.litFactor.value=t}get map(){return this.uniforms.map.value}set map(t){this.uniforms.map.value=t}get normalMap(){return this.uniforms.normalMap.value}set normalMap(t){this.uniforms.normalMap.value=t}get normalScale(){return this.uniforms.normalScale.value}set normalScale(t){this.uniforms.normalScale.value=t}get emissive(){return this.uniforms.emissive.value}set emissive(t){this.uniforms.emissive.value=t}get emissiveIntensity(){return this.uniforms.emissiveIntensity.value}set emissiveIntensity(t){this.uniforms.emissiveIntensity.value=t}get emissiveMap(){return this.uniforms.emissiveMap.value}set emissiveMap(t){this.uniforms.emissiveMap.value=t}get shadeColorFactor(){return this.uniforms.shadeColorFactor.value}set shadeColorFactor(t){this.uniforms.shadeColorFactor.value=t}get shadeMultiplyTexture(){return this.uniforms.shadeMultiplyTexture.value}set shadeMultiplyTexture(t){this.uniforms.shadeMultiplyTexture.value=t}get shadingShiftFactor(){return this.uniforms.shadingShiftFactor.value}set shadingShiftFactor(t){this.uniforms.shadingShiftFactor.value=t}get shadingShiftTexture(){return this.uniforms.shadingShiftTexture.value}set shadingShiftTexture(t){this.uniforms.shadingShiftTexture.value=t}get shadingShiftTextureScale(){return this.uniforms.shadingShiftTextureScale.value}set shadingShiftTextureScale(t){this.uniforms.shadingShiftTextureScale.value=t}get shadingToonyFactor(){return this.uniforms.shadingToonyFactor.value}set shadingToonyFactor(t){this.uniforms.shadingToonyFactor.value=t}get giEqualizationFactor(){return this.uniforms.giEqualizationFactor.value}set giEqualizationFactor(t){this.uniforms.giEqualizationFactor.value=t}get matcapFactor(){return this.uniforms.matcapFactor.value}set matcapFactor(t){this.uniforms.matcapFactor.value=t}get matcapTexture(){return this.uniforms.matcapTexture.value}set matcapTexture(t){this.uniforms.matcapTexture.value=t}get parametricRimColorFactor(){return this.uniforms.parametricRimColorFactor.value}set parametricRimColorFactor(t){this.uniforms.parametricRimColorFactor.value=t}get rimMultiplyTexture(){return this.uniforms.rimMultiplyTexture.value}set rimMultiplyTexture(t){this.uniforms.rimMultiplyTexture.value=t}get rimLightingMixFactor(){return this.uniforms.rimLightingMixFactor.value}set rimLightingMixFactor(t){this.uniforms.rimLightingMixFactor.value=t}get parametricRimFresnelPowerFactor(){return this.uniforms.parametricRimFresnelPowerFactor.value}set parametricRimFresnelPowerFactor(t){this.uniforms.parametricRimFresnelPowerFactor.value=t}get parametricRimLiftFactor(){return this.uniforms.parametricRimLiftFactor.value}set parametricRimLiftFactor(t){this.uniforms.parametricRimLiftFactor.value=t}get outlineWidthMultiplyTexture(){return this.uniforms.outlineWidthMultiplyTexture.value}set outlineWidthMultiplyTexture(t){this.uniforms.outlineWidthMultiplyTexture.value=t}get outlineWidthFactor(){return this.uniforms.outlineWidthFactor.value}set outlineWidthFactor(t){this.uniforms.outlineWidthFactor.value=t}get outlineColorFactor(){return this.uniforms.outlineColorFactor.value}set outlineColorFactor(t){this.uniforms.outlineColorFactor.value=t}get outlineLightingMixFactor(){return this.uniforms.outlineLightingMixFactor.value}set outlineLightingMixFactor(t){this.uniforms.outlineLightingMixFactor.value=t}get uvAnimationMaskTexture(){return this.uniforms.uvAnimationMaskTexture.value}set uvAnimationMaskTexture(t){this.uniforms.uvAnimationMaskTexture.value=t}get uvAnimationScrollXOffset(){return this.uniforms.uvAnimationScrollXOffset.value}set uvAnimationScrollXOffset(t){this.uniforms.uvAnimationScrollXOffset.value=t}get uvAnimationScrollYOffset(){return this.uniforms.uvAnimationScrollYOffset.value}set uvAnimationScrollYOffset(t){this.uniforms.uvAnimationScrollYOffset.value=t}get uvAnimationRotationPhase(){return this.uniforms.uvAnimationRotationPhase.value}set uvAnimationRotationPhase(t){this.uniforms.uvAnimationRotationPhase.value=t}get ignoreVertexColor(){return this._ignoreVertexColor}set ignoreVertexColor(t){this._ignoreVertexColor=t,this.needsUpdate=!0}get v0CompatShade(){return this._v0CompatShade}set v0CompatShade(t){this._v0CompatShade=t,this.needsUpdate=!0}get debugMode(){return this._debugMode}set debugMode(t){this._debugMode=t,this.needsUpdate=!0}get outlineWidthMode(){return this._outlineWidthMode}set outlineWidthMode(t){this._outlineWidthMode=t,this.needsUpdate=!0}get isOutline(){return this._isOutline}set isOutline(t){this._isOutline=t,this.needsUpdate=!0}get isMToonMaterial(){return!0}update(t){this._uploadUniformsWorkaround(),this._updateUVAnimation(t)}copy(t){return super.copy(t),this.map=t.map,this.normalMap=t.normalMap,this.emissiveMap=t.emissiveMap,this.shadeMultiplyTexture=t.shadeMultiplyTexture,this.shadingShiftTexture=t.shadingShiftTexture,this.matcapTexture=t.matcapTexture,this.rimMultiplyTexture=t.rimMultiplyTexture,this.outlineWidthMultiplyTexture=t.outlineWidthMultiplyTexture,this.uvAnimationMaskTexture=t.uvAnimationMaskTexture,this.normalMapType=t.normalMapType,this.uvAnimationScrollXSpeedFactor=t.uvAnimationScrollXSpeedFactor,this.uvAnimationScrollYSpeedFactor=t.uvAnimationScrollYSpeedFactor,this.uvAnimationRotationSpeedFactor=t.uvAnimationRotationSpeedFactor,this.ignoreVertexColor=t.ignoreVertexColor,this.v0CompatShade=t.v0CompatShade,this.debugMode=t.debugMode,this.outlineWidthMode=t.outlineWidthMode,this.isOutline=t.isOutline,this.needsUpdate=!0,this}_updateUVAnimation(t){this.uniforms.uvAnimationScrollXOffset.value+=t*this.uvAnimationScrollXSpeedFactor,this.uniforms.uvAnimationScrollYOffset.value+=t*this.uvAnimationScrollYSpeedFactor,this.uniforms.uvAnimationRotationPhase.value+=t*this.uvAnimationRotationSpeedFactor,this.uniforms.alphaTest.value=this.alphaTest,this.uniformsNeedUpdate=!0}_uploadUniformsWorkaround(){this.uniforms.opacity.value=this.opacity,this._updateTextureMatrix(this.uniforms.map,this.uniforms.mapUvTransform),this._updateTextureMatrix(this.uniforms.normalMap,this.uniforms.normalMapUvTransform),this._updateTextureMatrix(this.uniforms.emissiveMap,this.uniforms.emissiveMapUvTransform),this._updateTextureMatrix(this.uniforms.shadeMultiplyTexture,this.uniforms.shadeMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.shadingShiftTexture,this.uniforms.shadingShiftTextureUvTransform),this._updateTextureMatrix(this.uniforms.matcapTexture,this.uniforms.matcapTextureUvTransform),this._updateTextureMatrix(this.uniforms.rimMultiplyTexture,this.uniforms.rimMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.outlineWidthMultiplyTexture,this.uniforms.outlineWidthMultiplyTextureUvTransform),this._updateTextureMatrix(this.uniforms.uvAnimationMaskTexture,this.uniforms.uvAnimationMaskTextureUvTransform),this.uniformsNeedUpdate=!0}_generateDefines(){let t=parseInt(w.REVISION,10),e=this.outlineWidthMultiplyTexture!==null,n=this.map!==null||this.normalMap!==null||this.emissiveMap!==null||this.shadeMultiplyTexture!==null||this.shadingShiftTexture!==null||this.rimMultiplyTexture!==null||this.uvAnimationMaskTexture!==null;return{THREE_VRM_THREE_REVISION:t,OUTLINE:this._isOutline,MTOON_USE_UV:e||n,MTOON_UVS_VERTEX_ONLY:e&&!n,V0_COMPAT_SHADE:this._v0CompatShade,USE_SHADEMULTIPLYTEXTURE:this.shadeMultiplyTexture!==null,USE_SHADINGSHIFTTEXTURE:this.shadingShiftTexture!==null,USE_MATCAPTEXTURE:this.matcapTexture!==null,USE_RIMMULTIPLYTEXTURE:this.rimMultiplyTexture!==null,USE_OUTLINEWIDTHMULTIPLYTEXTURE:this._isOutline&&this.outlineWidthMultiplyTexture!==null,USE_UVANIMATIONMASKTEXTURE:this.uvAnimationMaskTexture!==null,IGNORE_VERTEX_COLOR:this._ignoreVertexColor===!0,DEBUG_NORMAL:this._debugMode==="normal",DEBUG_LITSHADERATE:this._debugMode==="litShadeRate",DEBUG_UV:this._debugMode==="uv",OUTLINE_WIDTH_SCREEN:this._isOutline&&this._outlineWidthMode===ei.ScreenCoordinates}}_updateTextureMatrix(t,e){t.value&&(t.value.matrixAutoUpdate&&t.value.updateMatrix(),e.value.copy(t.value.matrix))}},Zr=new Set(["1.0","1.0-beta"]),ri=class je{get name(){return je.EXTENSION_NAME}constructor(e,n={}){var i,r,o,s;this.parser=e,this.materialType=(i=n.materialType)!=null?i:$r,this.renderOrderOffset=(r=n.renderOrderOffset)!=null?r:0,this.v0CompatShade=(o=n.v0CompatShade)!=null?o:!1,this.debugMode=(s=n.debugMode)!=null?s:"none",this._mToonMaterialSet=new Set}beforeRoot(){return le(this,null,function*(){this._removeUnlitExtensionIfMToonExists()})}afterRoot(e){return le(this,null,function*(){e.userData.vrmMToonMaterials=Array.from(this._mToonMaterialSet)})}getMaterialType(e){return this._getMToonExtension(e)?this.materialType:null}extendMaterialParams(e,n){let i=this._getMToonExtension(e);return i?this._extendMaterialParams(i,n):null}loadMesh(e){return le(this,null,function*(){var n;let i=this.parser,o=(n=i.json.meshes)==null?void 0:n[e];if(o==null)throw new Error(`MToonMaterialLoaderPlugin: Attempt to use meshes[${e}] of glTF but the mesh doesn't exist`);let s=o.primitives,l=yield i.loadMesh(e);if(s.length===1){let a=l,u=s[0].material;u!=null&&this._setupPrimitive(a,u)}else{let a=l;for(let u=0;u{var s;this._getMToonExtension(o)&&((s=r.extensions)!=null&&s.KHR_materials_unlit)&&delete r.extensions.KHR_materials_unlit})}_getMToonExtension(e){var n,i;let s=(n=this.parser.json.materials)==null?void 0:n[e];if(s==null){console.warn(`MToonMaterialLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}let l=(i=s.extensions)==null?void 0:i[je.EXTENSION_NAME];if(l==null)return;let a=l.specVersion;if(!Zr.has(a)){console.warn(`MToonMaterialLoaderPlugin: Unknown ${je.EXTENSION_NAME} specVersion "${a}"`);return}return l}_extendMaterialParams(e,n){return le(this,null,function*(){var i;delete n.metalness,delete n.roughness;let r=new jr(this.parser,n);r.assignPrimitive("transparentWithZWrite",e.transparentWithZWrite),r.assignColor("shadeColorFactor",e.shadeColorFactor),r.assignTexture("shadeMultiplyTexture",e.shadeMultiplyTexture,!0),r.assignPrimitive("shadingShiftFactor",e.shadingShiftFactor),r.assignTexture("shadingShiftTexture",e.shadingShiftTexture,!0),r.assignPrimitive("shadingShiftTextureScale",(i=e.shadingShiftTexture)==null?void 0:i.scale),r.assignPrimitive("shadingToonyFactor",e.shadingToonyFactor),r.assignPrimitive("giEqualizationFactor",e.giEqualizationFactor),r.assignColor("matcapFactor",e.matcapFactor),r.assignTexture("matcapTexture",e.matcapTexture,!0),r.assignColor("parametricRimColorFactor",e.parametricRimColorFactor),r.assignTexture("rimMultiplyTexture",e.rimMultiplyTexture,!0),r.assignPrimitive("rimLightingMixFactor",e.rimLightingMixFactor),r.assignPrimitive("parametricRimFresnelPowerFactor",e.parametricRimFresnelPowerFactor),r.assignPrimitive("parametricRimLiftFactor",e.parametricRimLiftFactor),r.assignPrimitive("outlineWidthMode",e.outlineWidthMode),r.assignPrimitive("outlineWidthFactor",e.outlineWidthFactor),r.assignTexture("outlineWidthMultiplyTexture",e.outlineWidthMultiplyTexture,!1),r.assignColor("outlineColorFactor",e.outlineColorFactor),r.assignPrimitive("outlineLightingMixFactor",e.outlineLightingMixFactor),r.assignTexture("uvAnimationMaskTexture",e.uvAnimationMaskTexture,!1),r.assignPrimitive("uvAnimationScrollXSpeedFactor",e.uvAnimationScrollXSpeedFactor),r.assignPrimitive("uvAnimationScrollYSpeedFactor",e.uvAnimationScrollYSpeedFactor),r.assignPrimitive("uvAnimationRotationSpeedFactor",e.uvAnimationRotationSpeedFactor),r.assignPrimitive("v0CompatShade",this.v0CompatShade),r.assignPrimitive("debugMode",this.debugMode),yield r.pending})}_setupPrimitive(e,n){let i=this._getMToonExtension(n);if(i){let r=this._parseRenderOrder(i);e.renderOrder=r+this.renderOrderOffset,this._generateOutline(e),this._addToMaterialSet(e);return}}_shouldGenerateOutline(e){return typeof e.outlineWidthMode=="string"&&e.outlineWidthMode!=="none"&&typeof e.outlineWidthFactor=="number"&&e.outlineWidthFactor>0}_generateOutline(e){let n=e.material;if(!(n instanceof Xe.Material)||!this._shouldGenerateOutline(n))return;e.material=[n];let i=n.clone();i.name+=" (Outline)",i.isOutline=!0,i.side=Xe.BackSide,e.material.push(i);let r=e.geometry,o=r.index?r.index.count:r.attributes.position.count/3;r.addGroup(0,o,0),r.addGroup(0,o,1)}_addToMaterialSet(e){let n=e.material,i=new Set;Array.isArray(n)?n.forEach(r=>i.add(r)):i.add(n);for(let r of i)this._mToonMaterialSet.add(r)}_parseRenderOrder(e){var n;return(e.transparentWithZWrite?0:19)+((n=e.renderQueueOffsetNumber)!=null?n:0)}};ri.EXTENSION_NAME="VRMC_materials_mtoon";var oi=ri;var Jr=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())}),si=class Mt{get name(){return Mt.EXTENSION_NAME}constructor(e){this.parser=e}extendMaterialParams(e,n){return Jr(this,null,function*(){let i=this._getHDREmissiveMultiplierExtension(e);if(i==null)return;console.warn("VRMMaterialsHDREmissiveMultiplierLoaderPlugin: `VRMC_materials_hdr_emissiveMultiplier` is archived. Use `KHR_materials_emissive_strength` instead.");let r=i.emissiveMultiplier;n.emissiveIntensity=r})}_getHDREmissiveMultiplierExtension(e){var n,i;let s=(n=this.parser.json.materials)==null?void 0:n[e];if(s==null){console.warn(`VRMMaterialsHDREmissiveMultiplierLoaderPlugin: Attempt to use materials[${e}] of glTF but the material doesn't exist`);return}let l=(i=s.extensions)==null?void 0:i[Mt.EXTENSION_NAME];if(l!=null)return l}};si.EXTENSION_NAME="VRMC_materials_hdr_emissiveMultiplier";var ai=si;import*as hi from"three";var Kr=Object.defineProperty,eo=Object.defineProperties,to=Object.getOwnPropertyDescriptors,li=Object.getOwnPropertySymbols,no=Object.prototype.hasOwnProperty,io=Object.prototype.propertyIsEnumerable,ui=(t,e,n)=>e in t?Kr(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G=(t,e)=>{for(var n in e||(e={}))no.call(e,n)&&ui(t,n,e[n]);if(li)for(var n of li(e))io.call(e,n)&&ui(t,n,e[n]);return t},di=(t,e)=>eo(t,to(e)),ro=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())});function me(t){return Math.pow(t,2.2)}var ci=class{get name(){return"VRMMaterialsV0CompatPlugin"}constructor(t){var e;this.parser=t,this._renderQueueMapTransparent=new Map,this._renderQueueMapTransparentZWrite=new Map;let n=this.parser.json;n.extensionsUsed=(e=n.extensionsUsed)!=null?e:[],n.extensionsUsed.indexOf("KHR_texture_transform")===-1&&n.extensionsUsed.push("KHR_texture_transform")}beforeRoot(){return ro(this,null,function*(){var t;let e=this.parser.json,n=(t=e.extensions)==null?void 0:t.VRM,i=n==null?void 0:n.materialProperties;i&&(this._populateRenderQueueMap(i),i.forEach((r,o)=>{var s,l;let a=(s=e.materials)==null?void 0:s[o];if(a==null){console.warn(`VRMMaterialsV0CompatPlugin: Attempt to use materials[${o}] of glTF but the material doesn't exist`);return}if(r.shader==="VRM/MToon"){let u=this._parseV0MToonProperties(r,a);e.materials[o]=u}else if((l=r.shader)!=null&&l.startsWith("VRM/Unlit")){let u=this._parseV0UnlitProperties(r,a);e.materials[o]=u}else r.shader==="VRM_USE_GLTFSHADER"||console.warn(`VRMMaterialsV0CompatPlugin: Unknown shader: ${r.shader}`)}))})}_parseV0MToonProperties(t,e){var n,i,r,o,s,l,a,u,d,h,c,p,f,m,g,_,M,T,R,v,E,x,S,L,A,b,V,$,Re,Te,X,k,ce,xe,O,Ct,Ot,Ut,Bt,Nt,Dt,Ft,kt,Wt,Gt,zt,jt,Xt,Qt,Yt,qt,$t,Zt,Jt,Kt;let en=(i=(n=t.keywordMap)==null?void 0:n._ALPHABLEND_ON)!=null?i:!1,Ni=((r=t.floatProperties)==null?void 0:r._ZWrite)===1&&en,Di=this._v0ParseRenderQueue(t),tn=(s=(o=t.keywordMap)==null?void 0:o._ALPHATEST_ON)!=null?s:!1,Fi=en?"BLEND":tn?"MASK":"OPAQUE",ki=tn?(a=(l=t.floatProperties)==null?void 0:l._Cutoff)!=null?a:.5:void 0,Wi=((d=(u=t.floatProperties)==null?void 0:u._CullMode)!=null?d:2)===0,oe=this._portTextureTransform(t),Gi=((c=(h=t.vectorProperties)==null?void 0:h._Color)!=null?c:[1,1,1,1]).map((hn,pr)=>pr===3?hn:me(hn)),nn=(p=t.textureProperties)==null?void 0:p._MainTex,zi=nn!=null?{index:nn,extensions:G({},oe)}:void 0,ji=(m=(f=t.floatProperties)==null?void 0:f._BumpScale)!=null?m:1,rn=(g=t.textureProperties)==null?void 0:g._BumpMap,Xi=rn!=null?{index:rn,scale:ji,extensions:G({},oe)}:void 0,Qi=((M=(_=t.vectorProperties)==null?void 0:_._EmissionColor)!=null?M:[0,0,0,1]).map(me),on=(T=t.textureProperties)==null?void 0:T._EmissionMap,Yi=on!=null?{index:on,extensions:G({},oe)}:void 0,qi=((v=(R=t.vectorProperties)==null?void 0:R._ShadeColor)!=null?v:[.97,.81,.86,1]).map(me),sn=(E=t.textureProperties)==null?void 0:E._ShadeTexture,$i=sn!=null?{index:sn,extensions:G({},oe)}:void 0,Be=(S=(x=t.floatProperties)==null?void 0:x._ShadeShift)!=null?S:0,Ne=(A=(L=t.floatProperties)==null?void 0:L._ShadeToony)!=null?A:.9;Ne=hi.MathUtils.lerp(Ne,1,.5+.5*Be),Be=-Be-(1-Ne);let an=(V=(b=t.floatProperties)==null?void 0:b._IndirectLightIntensity)!=null?V:.1,Zi=an?1-an:void 0,Ke=($=t.textureProperties)==null?void 0:$._SphereAdd,Ji=Ke!=null?[1,1,1]:void 0,Ki=Ke!=null?{index:Ke}:void 0,er=(Te=(Re=t.floatProperties)==null?void 0:Re._RimLightingMix)!=null?Te:0,ln=(X=t.textureProperties)==null?void 0:X._RimTexture,tr=ln!=null?{index:ln,extensions:G({},oe)}:void 0,nr=((ce=(k=t.vectorProperties)==null?void 0:k._RimColor)!=null?ce:[0,0,0,1]).map(me),ir=(O=(xe=t.floatProperties)==null?void 0:xe._RimFresnelPower)!=null?O:1,rr=(Ot=(Ct=t.floatProperties)==null?void 0:Ct._RimLift)!=null?Ot:0,or=["none","worldCoordinates","screenCoordinates"][(Bt=(Ut=t.floatProperties)==null?void 0:Ut._OutlineWidthMode)!=null?Bt:0],et=(Dt=(Nt=t.floatProperties)==null?void 0:Nt._OutlineWidth)!=null?Dt:0;et=.01*et;let un=(Ft=t.textureProperties)==null?void 0:Ft._OutlineWidthTexture,sr=un!=null?{index:un,extensions:G({},oe)}:void 0,ar=((Wt=(kt=t.vectorProperties)==null?void 0:kt._OutlineColor)!=null?Wt:[0,0,0]).map(me),lr=((zt=(Gt=t.floatProperties)==null?void 0:Gt._OutlineColorMode)!=null?zt:0)===1?(Xt=(jt=t.floatProperties)==null?void 0:jt._OutlineLightingMix)!=null?Xt:1:0,dn=(Qt=t.textureProperties)==null?void 0:Qt._UvAnimMaskTexture,ur=dn!=null?{index:dn,extensions:G({},oe)}:void 0,dr=(qt=(Yt=t.floatProperties)==null?void 0:Yt._UvAnimScrollX)!=null?qt:0,De=(Zt=($t=t.floatProperties)==null?void 0:$t._UvAnimScrollY)!=null?Zt:0;De!=null&&(De=-De);let hr=(Kt=(Jt=t.floatProperties)==null?void 0:Jt._UvAnimRotation)!=null?Kt:0,cr={specVersion:"1.0",transparentWithZWrite:Ni,renderQueueOffsetNumber:Di,shadeColorFactor:qi,shadeMultiplyTexture:$i,shadingShiftFactor:Be,shadingToonyFactor:Ne,giEqualizationFactor:Zi,matcapFactor:Ji,matcapTexture:Ki,rimLightingMixFactor:er,rimMultiplyTexture:tr,parametricRimColorFactor:nr,parametricRimFresnelPowerFactor:ir,parametricRimLiftFactor:rr,outlineWidthMode:or,outlineWidthFactor:et,outlineWidthMultiplyTexture:sr,outlineColorFactor:ar,outlineLightingMixFactor:lr,uvAnimationMaskTexture:ur,uvAnimationScrollXSpeedFactor:dr,uvAnimationScrollYSpeedFactor:De,uvAnimationRotationSpeedFactor:hr};return di(G({},e),{pbrMetallicRoughness:{baseColorFactor:Gi,baseColorTexture:zi},normalTexture:Xi,emissiveTexture:Yi,emissiveFactor:Qi,alphaMode:Fi,alphaCutoff:ki,doubleSided:Wi,extensions:{VRMC_materials_mtoon:cr}})}_parseV0UnlitProperties(t,e){var n,i,r,o,s;let l=t.shader==="VRM/UnlitTransparentZWrite",a=t.shader==="VRM/UnlitTransparent"||l,u=this._v0ParseRenderQueue(t),d=t.shader==="VRM/UnlitCutout",h=a?"BLEND":d?"MASK":"OPAQUE",c=d?(i=(n=t.floatProperties)==null?void 0:n._Cutoff)!=null?i:.5:void 0,p=this._portTextureTransform(t),f=((o=(r=t.vectorProperties)==null?void 0:r._Color)!=null?o:[1,1,1,1]).map(me),m=(s=t.textureProperties)==null?void 0:s._MainTex,g=m!=null?{index:m,extensions:G({},p)}:void 0,_={specVersion:"1.0",transparentWithZWrite:l,renderQueueOffsetNumber:u,shadeColorFactor:f,shadeMultiplyTexture:g};return di(G({},e),{pbrMetallicRoughness:{baseColorFactor:f,baseColorTexture:g},alphaMode:h,alphaCutoff:c,extensions:{VRMC_materials_mtoon:_}})}_portTextureTransform(t){var e,n,i,r,o;let s=(e=t.vectorProperties)==null?void 0:e._MainTex;if(s==null)return{};let l=[(n=s==null?void 0:s[0])!=null?n:0,(i=s==null?void 0:s[1])!=null?i:0],a=[(r=s==null?void 0:s[2])!=null?r:1,(o=s==null?void 0:s[3])!=null?o:1];return l[1]=1-a[1]-l[1],{KHR_texture_transform:{offset:l,scale:a}}}_v0ParseRenderQueue(t){var e,n;let i=t.shader==="VRM/UnlitTransparentZWrite",r=((e=t.keywordMap)==null?void 0:e._ALPHABLEND_ON)!=null||t.shader==="VRM/UnlitTransparent"||i,o=((n=t.floatProperties)==null?void 0:n._ZWrite)===1||i,s=0;if(r){let l=t.renderQueue;l!=null&&(o?s=this._renderQueueMapTransparentZWrite.get(l):s=this._renderQueueMapTransparent.get(l))}return s}_populateRenderQueueMap(t){let e=new Set,n=new Set;t.forEach(i=>{var r,o;let s=i.shader==="VRM/UnlitTransparentZWrite",l=((r=i.keywordMap)==null?void 0:r._ALPHABLEND_ON)!=null||i.shader==="VRM/UnlitTransparent"||s,a=((o=i.floatProperties)==null?void 0:o._ZWrite)===1||s;if(l){let u=i.renderQueue;u!=null&&(a?n.add(u):e.add(u))}}),e.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${e.size} render queues for Transparent materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),n.size>10&&console.warn(`VRMMaterialsV0CompatPlugin: This VRM uses ${n.size} render queues for TransparentZWrite materials while VRM 1.0 only supports up to 10 render queues. The model might not be rendered correctly.`),Array.from(e).sort().forEach((i,r)=>{let o=Math.min(Math.max(r-e.size+1,-9),0);this._renderQueueMapTransparent.set(i,o)}),Array.from(n).sort().forEach((i,r)=>{let o=Math.min(Math.max(r,0),9);this._renderQueueMapTransparentZWrite.set(i,o)})}};import*as U from"three";import*as z from"three";import*as Tt from"three";import*as Le from"three";import*as Y from"three";var pi=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())}),K=new U.Vector3,Rt=class extends U.Group{constructor(t){super(),this._attrPosition=new U.BufferAttribute(new Float32Array([0,0,0,0,0,0]),3),this._attrPosition.setUsage(U.DynamicDrawUsage);let e=new U.BufferGeometry;e.setAttribute("position",this._attrPosition);let n=new U.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new U.Line(e,n),this.add(this._line),this.constraint=t}updateMatrixWorld(t){K.setFromMatrixPosition(this.constraint.destination.matrixWorld),this._attrPosition.setXYZ(0,K.x,K.y,K.z),this.constraint.source&&K.setFromMatrixPosition(this.constraint.source.matrixWorld),this._attrPosition.setXYZ(1,K.x,K.y,K.z),this._attrPosition.needsUpdate=!0,super.updateMatrixWorld(t)}};function fi(t,e){return e.set(t.elements[12],t.elements[13],t.elements[14])}var oo=new Tt.Vector3,so=new Tt.Vector3;function ao(t,e){return t.decompose(oo,e,so),e}function Qe(t){return t.invert?t.invert():t.inverse(),t}var xt=class{constructor(t,e){this.destination=t,this.source=e,this.weight=1}},lo=new z.Vector3,uo=new z.Vector3,ho=new z.Vector3,co=new z.Quaternion,po=new z.Quaternion,fo=new z.Quaternion,mo=class extends xt{get aimAxis(){return this._aimAxis}set aimAxis(t){this._aimAxis=t,this._v3AimAxis.set(t==="PositiveX"?1:t==="NegativeX"?-1:0,t==="PositiveY"?1:t==="NegativeY"?-1:0,t==="PositiveZ"?1:t==="NegativeZ"?-1:0)}get dependencies(){let t=new Set([this.source]);return this.destination.parent&&t.add(this.destination.parent),t}constructor(t,e){super(t,e),this._aimAxis="PositiveX",this._v3AimAxis=new z.Vector3(1,0,0),this._dstRestQuat=new z.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion)}update(){this.destination.updateWorldMatrix(!0,!1),this.source.updateWorldMatrix(!0,!1);let t=co.identity(),e=po.identity();this.destination.parent&&(ao(this.destination.parent.matrixWorld,t),Qe(e.copy(t)));let n=lo.copy(this._v3AimAxis).applyQuaternion(this._dstRestQuat).applyQuaternion(t),i=fi(this.source.matrixWorld,uo).sub(fi(this.destination.matrixWorld,ho)).normalize(),r=fo.setFromUnitVectors(n,i).premultiply(e).multiply(t).multiply(this._dstRestQuat);this.destination.quaternion.copy(this._dstRestQuat).slerp(r,this.weight)}};function go(t,e){let n=[t],i=t.parent;for(;i!==null;)n.unshift(i),i=i.parent;n.forEach(r=>{e(r)})}var _o=class{constructor(){this._constraints=new Set,this._objectConstraintsMap=new Map}get constraints(){return this._constraints}addConstraint(t){this._constraints.add(t);let e=this._objectConstraintsMap.get(t.destination);e==null&&(e=new Set,this._objectConstraintsMap.set(t.destination,e)),e.add(t)}deleteConstraint(t){this._constraints.delete(t),this._objectConstraintsMap.get(t.destination).delete(t)}setInitState(){let t=new Set,e=new Set;for(let n of this._constraints)this._processConstraint(n,t,e,i=>i.setInitState())}update(){let t=new Set,e=new Set;for(let n of this._constraints)this._processConstraint(n,t,e,i=>i.update())}_processConstraint(t,e,n,i){if(n.has(t))return;if(e.has(t))throw new Error("VRMNodeConstraintManager: Circular dependency detected while updating constraints");e.add(t);let r=t.dependencies;for(let o of r)go(o,s=>{let l=this._objectConstraintsMap.get(s);if(l)for(let a of l)this._processConstraint(a,e,n,i)});i(t),n.add(t)}},vo=new Le.Quaternion,Eo=new Le.Quaternion,Mo=class extends xt{get dependencies(){return new Set([this.source])}constructor(t,e){super(t,e),this._dstRestQuat=new Le.Quaternion,this._invSrcRestQuat=new Le.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Qe(this._invSrcRestQuat.copy(this.source.quaternion))}update(){let t=vo.copy(this._invSrcRestQuat).multiply(this.source.quaternion),e=Eo.copy(this._dstRestQuat).multiply(t);this.destination.quaternion.copy(this._dstRestQuat).slerp(e,this.weight)}},Ro=new Y.Vector3,To=new Y.Quaternion,xo=new Y.Quaternion,yo=class extends xt{get rollAxis(){return this._rollAxis}set rollAxis(t){this._rollAxis=t,this._v3RollAxis.set(t==="X"?1:0,t==="Y"?1:0,t==="Z"?1:0)}get dependencies(){return new Set([this.source])}constructor(t,e){super(t,e),this._rollAxis="X",this._v3RollAxis=new Y.Vector3(1,0,0),this._dstRestQuat=new Y.Quaternion,this._invDstRestQuat=new Y.Quaternion,this._invSrcRestQuatMulDstRestQuat=new Y.Quaternion}setInitState(){this._dstRestQuat.copy(this.destination.quaternion),Qe(this._invDstRestQuat.copy(this._dstRestQuat)),Qe(this._invSrcRestQuatMulDstRestQuat.copy(this.source.quaternion)).multiply(this._dstRestQuat)}update(){let t=To.copy(this._invDstRestQuat).multiply(this.source.quaternion).multiply(this._invSrcRestQuatMulDstRestQuat),e=Ro.copy(this._v3RollAxis).applyQuaternion(t),i=xo.setFromUnitVectors(e,this._v3RollAxis).premultiply(this._dstRestQuat).multiply(t);this.destination.quaternion.copy(this._dstRestQuat).slerp(i,this.weight)}},wo=new Set(["1.0","1.0-beta"]),mi=class He{get name(){return He.EXTENSION_NAME}constructor(e,n){this.parser=e,this.helperRoot=n==null?void 0:n.helperRoot}afterRoot(e){return pi(this,null,function*(){e.userData.vrmNodeConstraintManager=yield this._import(e)})}_import(e){return pi(this,null,function*(){var n;let i=this.parser.json;if(!(((n=i.extensionsUsed)==null?void 0:n.indexOf(He.EXTENSION_NAME))!==-1))return null;let o=new _o,s=yield this.parser.getDependencies("node");return s.forEach((l,a)=>{var u;let d=i.nodes[a],h=(u=d==null?void 0:d.extensions)==null?void 0:u[He.EXTENSION_NAME];if(h==null)return;let c=h.specVersion;if(!wo.has(c)){console.warn(`VRMNodeConstraintLoaderPlugin: Unknown ${He.EXTENSION_NAME} specVersion "${c}"`);return}let p=h.constraint;if(p.roll!=null){let f=this._importRollConstraint(l,s,p.roll);o.addConstraint(f)}else if(p.aim!=null){let f=this._importAimConstraint(l,s,p.aim);o.addConstraint(f)}else if(p.rotation!=null){let f=this._importRotationConstraint(l,s,p.rotation);o.addConstraint(f)}}),e.scene.updateMatrixWorld(),o.setInitState(),o})}_importRollConstraint(e,n,i){let{source:r,rollAxis:o,weight:s}=i,l=n[r],a=new yo(e,l);if(o!=null&&(a.rollAxis=o),s!=null&&(a.weight=s),this.helperRoot){let u=new Rt(a);this.helperRoot.add(u)}return a}_importAimConstraint(e,n,i){let{source:r,aimAxis:o,weight:s}=i,l=n[r],a=new mo(e,l);if(o!=null&&(a.aimAxis=o),s!=null&&(a.weight=s),this.helperRoot){let u=new Rt(a);this.helperRoot.add(u)}return a}_importRotationConstraint(e,n,i){let{source:r,weight:o}=i,s=n[r],l=new Mo(e,s);if(o!=null&&(l.weight=o),this.helperRoot){let a=new Rt(l);this.helperRoot.add(a)}return l}};mi.EXTENSION_NAME="VRMC_node_constraint";var gi=mi;import*as te from"three";import*as Oe from"three";import*as ve from"three";import*as Lt from"three";import*as q from"three";import*as ee from"three";import*as de from"three";import*as ne from"three";import*as he from"three";import*as qe from"three";import*as C from"three";import*as xi from"three";import*as yi from"three";import*as N from"three";var Ye=(t,e,n)=>new Promise((i,r)=>{var o=a=>{try{l(n.next(a))}catch(u){r(u)}},s=a=>{try{l(n.throw(a))}catch(u){r(u)}},l=a=>a.done?i(a.value):Promise.resolve(a.value).then(o,s);l((n=n.apply(t,e)).next())}),Ht=class{},yt=new Oe.Vector3,ue=new Oe.Vector3,Mi=class extends Ht{get type(){return"capsule"}constructor(t){var e,n,i,r;super(),this.offset=(e=t==null?void 0:t.offset)!=null?e:new Oe.Vector3(0,0,0),this.tail=(n=t==null?void 0:t.tail)!=null?n:new Oe.Vector3(0,0,0),this.radius=(i=t==null?void 0:t.radius)!=null?i:0,this.inside=(r=t==null?void 0:t.inside)!=null?r:!1}calculateCollision(t,e,n,i){yt.setFromMatrixPosition(t),ue.subVectors(this.tail,this.offset).applyMatrix4(t),ue.sub(yt);let r=ue.lengthSq();i.copy(e).sub(yt);let o=ue.dot(i);o<=0||(r<=o||ue.multiplyScalar(o/r),i.sub(ue));let s=i.length(),l=this.inside?this.radius-n-s:s-n-this.radius;return l<0&&(i.multiplyScalar(1/s),this.inside&&i.negate()),l}},wt=new ve.Vector3,_i=new ve.Matrix3,Ri=class extends Ht{get type(){return"plane"}constructor(t){var e,n;super(),this.offset=(e=t==null?void 0:t.offset)!=null?e:new ve.Vector3(0,0,0),this.normal=(n=t==null?void 0:t.normal)!=null?n:new ve.Vector3(0,0,1)}calculateCollision(t,e,n,i){i.setFromMatrixPosition(t),i.negate().add(e),_i.getNormalMatrix(t),wt.copy(this.normal).applyNormalMatrix(_i).normalize();let r=i.dot(wt)-n;return i.copy(wt),r}},So=new Lt.Vector3,Ti=class extends Ht{get type(){return"sphere"}constructor(t){var e,n,i;super(),this.offset=(e=t==null?void 0:t.offset)!=null?e:new Lt.Vector3(0,0,0),this.radius=(n=t==null?void 0:t.radius)!=null?n:0,this.inside=(i=t==null?void 0:t.inside)!=null?i:!1}calculateCollision(t,e,n,i){i.subVectors(e,So.setFromMatrixPosition(t));let r=i.length(),o=this.inside?this.radius-n-r:r-n-this.radius;return o<0&&(i.multiplyScalar(1/r),this.inside&&i.negate()),o}},j=new q.Vector3,Ao=class extends q.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new q.Vector3,this._currentTail=new q.Vector3,this._shape=t,this._attrPos=new q.BufferAttribute(new Float32Array(396),3),this.setAttribute("position",this._attrPos),this._attrIndex=new q.BufferAttribute(new Uint16Array(264),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),t=!0);let n=j.copy(this._shape.tail).divideScalar(this.worldScale);this._currentTail.distanceToSquared(n)>1e-10&&(this._currentTail.copy(n),t=!0),t&&this._buildPosition()}_buildPosition(){j.copy(this._currentTail).sub(this._currentOffset);let t=j.length()/this._currentRadius;for(let i=0;i<=16;i++){let r=i/16*Math.PI;this._attrPos.setXYZ(i,-Math.sin(r),-Math.cos(r),0),this._attrPos.setXYZ(17+i,t+Math.sin(r),Math.cos(r),0),this._attrPos.setXYZ(34+i,-Math.sin(r),0,-Math.cos(r)),this._attrPos.setXYZ(51+i,t+Math.sin(r),0,Math.cos(r))}for(let i=0;i<32;i++){let r=i/16*Math.PI;this._attrPos.setXYZ(68+i,0,Math.sin(r),Math.cos(r)),this._attrPos.setXYZ(100+i,t,Math.sin(r),Math.cos(r))}let e=Math.atan2(j.y,Math.sqrt(j.x*j.x+j.z*j.z)),n=-Math.atan2(j.z,j.x);this.rotateZ(e),this.rotateY(n),this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<34;t++){let e=(t+1)%34;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(68+t*2,34+t,34+e)}for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(136+t*2,68+t,68+e),this._attrIndex.setXY(200+t*2,100+t,100+e)}this._attrIndex.needsUpdate=!0}},Po=class extends ee.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentOffset=new ee.Vector3,this._currentNormal=new ee.Vector3,this._shape=t,this._attrPos=new ee.BufferAttribute(new Float32Array(18),3),this.setAttribute("position",this._attrPos),this._attrIndex=new ee.BufferAttribute(new Uint16Array(10),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1;this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),t=!0),this._currentNormal.equals(this._shape.normal)||(this._currentNormal.copy(this._shape.normal),t=!0),t&&this._buildPosition()}_buildPosition(){this._attrPos.setXYZ(0,-.5,-.5,0),this._attrPos.setXYZ(1,.5,-.5,0),this._attrPos.setXYZ(2,.5,.5,0),this._attrPos.setXYZ(3,-.5,.5,0),this._attrPos.setXYZ(4,0,0,0),this._attrPos.setXYZ(5,0,0,.25),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this.lookAt(this._currentNormal),this._attrPos.needsUpdate=!0}_buildIndex(){this._attrIndex.setXY(0,0,1),this._attrIndex.setXY(2,1,2),this._attrIndex.setXY(4,2,3),this._attrIndex.setXY(6,3,0),this._attrIndex.setXY(8,4,5),this._attrIndex.needsUpdate=!0}},bo=class extends de.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentOffset=new de.Vector3,this._shape=t,this._attrPos=new de.BufferAttribute(new Float32Array(288),3),this.setAttribute("position",this._attrPos),this._attrIndex=new de.BufferAttribute(new Uint16Array(192),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._shape.radius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentOffset.equals(this._shape.offset)||(this._currentOffset.copy(this._shape.offset),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentOffset.x,this._currentOffset.y,this._currentOffset.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.needsUpdate=!0}},Ho=new te.Vector3,St=class extends te.Group{constructor(t){if(super(),this.matrixAutoUpdate=!1,this.collider=t,this.collider.shape instanceof Ti)this._geometry=new bo(this.collider.shape);else if(this.collider.shape instanceof Mi)this._geometry=new Ao(this.collider.shape);else if(this.collider.shape instanceof Ri)this._geometry=new Po(this.collider.shape);else throw new Error("VRMSpringBoneColliderHelper: Unknown collider shape type detected");let e=new te.LineBasicMaterial({color:16711935,depthTest:!1,depthWrite:!1});this._line=new te.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(t){this.collider.updateWorldMatrix(!0,!1),this.matrix.copy(this.collider.matrixWorld);let e=this.matrix.elements;this._geometry.worldScale=Ho.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(t)}},Lo=class extends he.BufferGeometry{constructor(t){super(),this.worldScale=1,this._currentRadius=0,this._currentTail=new he.Vector3,this._springBone=t,this._attrPos=new he.BufferAttribute(new Float32Array(294),3),this.setAttribute("position",this._attrPos),this._attrIndex=new he.BufferAttribute(new Uint16Array(194),1),this.setIndex(this._attrIndex),this._buildIndex(),this.update()}update(){let t=!1,e=this._springBone.settings.hitRadius/this.worldScale;this._currentRadius!==e&&(this._currentRadius=e,t=!0),this._currentTail.equals(this._springBone.initialLocalChildPosition)||(this._currentTail.copy(this._springBone.initialLocalChildPosition),t=!0),t&&this._buildPosition()}_buildPosition(){for(let t=0;t<32;t++){let e=t/16*Math.PI;this._attrPos.setXYZ(t,Math.cos(e),Math.sin(e),0),this._attrPos.setXYZ(32+t,0,Math.cos(e),Math.sin(e)),this._attrPos.setXYZ(64+t,Math.sin(e),0,Math.cos(e))}this.scale(this._currentRadius,this._currentRadius,this._currentRadius),this.translate(this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.setXYZ(96,0,0,0),this._attrPos.setXYZ(97,this._currentTail.x,this._currentTail.y,this._currentTail.z),this._attrPos.needsUpdate=!0}_buildIndex(){for(let t=0;t<32;t++){let e=(t+1)%32;this._attrIndex.setXY(t*2,t,e),this._attrIndex.setXY(64+t*2,32+t,32+e),this._attrIndex.setXY(128+t*2,64+t,64+e)}this._attrIndex.setXY(192,96,97),this._attrIndex.needsUpdate=!0}},Io=new ne.Vector3,Vo=class extends ne.Group{constructor(t){super(),this.matrixAutoUpdate=!1,this.springBone=t,this._geometry=new Lo(this.springBone);let e=new ne.LineBasicMaterial({color:16776960,depthTest:!1,depthWrite:!1});this._line=new ne.LineSegments(this._geometry,e),this.add(this._line)}dispose(){this._geometry.dispose()}updateMatrixWorld(t){this.springBone.bone.updateWorldMatrix(!0,!1),this.matrix.copy(this.springBone.bone.matrixWorld);let e=this.matrix.elements;this._geometry.worldScale=Io.set(e[0],e[1],e[2]).length(),this._geometry.update(),super.updateMatrixWorld(t)}},At=class extends qe.Object3D{constructor(t){super(),this.colliderMatrix=new qe.Matrix4,this.shape=t}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),Co(this.colliderMatrix,this.matrixWorld,this.shape.offset)}};function Co(t,e,n){let i=e.elements;t.copy(e),n&&(t.elements[12]=i[0]*n.x+i[4]*n.y+i[8]*n.z+i[12],t.elements[13]=i[1]*n.x+i[5]*n.y+i[9]*n.z+i[13],t.elements[14]=i[2]*n.x+i[6]*n.y+i[10]*n.z+i[14])}var Oo=new yi.Matrix4;function Uo(t){return t.invert?t.invert():t.getInverse(Oo.copy(t)),t}var Bo=class{constructor(t){this._inverseCache=new xi.Matrix4,this._shouldUpdateInverse=!0,this.matrix=t;let e={set:(n,i,r)=>(this._shouldUpdateInverse=!0,n[i]=r,!0)};this._originalElements=t.elements,t.elements=new Proxy(t.elements,e)}get inverse(){return this._shouldUpdateInverse&&(Uo(this._inverseCache.copy(this.matrix)),this._shouldUpdateInverse=!1),this._inverseCache}revert(){this.matrix.elements=this._originalElements}},Pt=new C.Matrix4,ge=new C.Vector3,Ie=new C.Vector3,Ve=new C.Vector3,Ce=new C.Vector3,No=new C.Matrix4,Do=class{constructor(t,e,n={},i=[]){this._currentTail=new C.Vector3,this._prevTail=new C.Vector3,this._boneAxis=new C.Vector3,this._worldSpaceBoneLength=0,this._center=null,this._initialLocalMatrix=new C.Matrix4,this._initialLocalRotation=new C.Quaternion,this._initialLocalChildPosition=new C.Vector3;var r,o,s,l,a,u;this.bone=t,this.bone.matrixAutoUpdate=!1,this.child=e,this.settings={hitRadius:(r=n.hitRadius)!=null?r:0,stiffness:(o=n.stiffness)!=null?o:1,gravityPower:(s=n.gravityPower)!=null?s:0,gravityDir:(a=(l=n.gravityDir)==null?void 0:l.clone())!=null?a:new C.Vector3(0,-1,0),dragForce:(u=n.dragForce)!=null?u:.4},this.colliderGroups=i}get dependencies(){let t=new Set,e=this.bone.parent;e&&t.add(e);for(let n=0;n{e(r)})}function bt(t,e){t.children.forEach(n=>{e(n)||bt(n,e)})}function ko(t){var e;let n=new Map;for(let i of t){let r=i;do{let o=((e=n.get(r))!=null?e:0)+1;if(o===t.size)return r;n.set(r,o),r=r.parent}while(r!==null)}return null}var vi=class{constructor(){this._joints=new Set,this._sortedJoints=[],this._hasWarnedCircularDependency=!1,this._ancestors=[],this._objectSpringBonesMap=new Map,this._isSortedJointsDirty=!1,this._relevantChildrenUpdated=this._relevantChildrenUpdated.bind(this)}get joints(){return this._joints}get springBones(){return console.warn("VRMSpringBoneManager: springBones is deprecated. use joints instead."),this._joints}get colliderGroups(){let t=new Set;return this._joints.forEach(e=>{e.colliderGroups.forEach(n=>{t.add(n)})}),Array.from(t)}get colliders(){let t=new Set;return this.colliderGroups.forEach(e=>{e.colliders.forEach(n=>{t.add(n)})}),Array.from(t)}addJoint(t){this._joints.add(t);let e=this._objectSpringBonesMap.get(t.bone);e==null&&(e=new Set,this._objectSpringBonesMap.set(t.bone,e)),e.add(t),this._isSortedJointsDirty=!0}addSpringBone(t){console.warn("VRMSpringBoneManager: addSpringBone() is deprecated. use addJoint() instead."),this.addJoint(t)}deleteJoint(t){this._joints.delete(t),this._objectSpringBonesMap.get(t.bone).delete(t),this._isSortedJointsDirty=!0}deleteSpringBone(t){console.warn("VRMSpringBoneManager: deleteSpringBone() is deprecated. use deleteJoint() instead."),this.deleteJoint(t)}setInitState(){this._sortJoints();for(let t=0;t{var s,l;return((l=(s=this._objectSpringBonesMap.get(o))==null?void 0:s.size)!=null?l:0)>0?!0:(this._ancestors.push(o),!1)})),this._isSortedJointsDirty=!1}_insertJointSort(t,e,n,i,r){if(n.has(t))return;if(e.has(t)){this._hasWarnedCircularDependency||(console.warn("VRMSpringBoneManager: Circular dependency detected"),this._hasWarnedCircularDependency=!0);return}e.add(t);let o=t.dependencies;for(let s of o){let l=!1,a=null;Fo(s,u=>{let d=this._objectSpringBonesMap.get(u);if(d)for(let h of d)l=!0,this._insertJointSort(h,e,n,i,r);else l||(a=u)}),a&&r.add(a)}i.push(t),n.add(t)}_relevantChildrenUpdated(t){var e,n;return((n=(e=this._objectSpringBonesMap.get(t))==null?void 0:e.size)!=null?n:0)>0?!0:(t.updateWorldMatrix(!1,!1),!1)}},Ei="VRMC_springBone_extended_collider",Wo=new Set(["1.0","1.0-beta"]),Go=new Set(["1.0"]),wi=class _e{get name(){return _e.EXTENSION_NAME}constructor(e,n){var i;this.parser=e,this.jointHelperRoot=n==null?void 0:n.jointHelperRoot,this.colliderHelperRoot=n==null?void 0:n.colliderHelperRoot,this.useExtendedColliders=(i=n==null?void 0:n.useExtendedColliders)!=null?i:!0}afterRoot(e){return Ye(this,null,function*(){e.userData.vrmSpringBoneManager=yield this._import(e)})}_import(e){return Ye(this,null,function*(){let n=yield this._v1Import(e);if(n!=null)return n;let i=yield this._v0Import(e);return i!=null?i:null})}_v1Import(e){return Ye(this,null,function*(){var n,i,r,o,s;let l=e.parser.json;if(!(((n=l.extensionsUsed)==null?void 0:n.indexOf(_e.EXTENSION_NAME))!==-1))return null;let u=new vi,d=yield e.parser.getDependencies("node"),h=(i=l.extensions)==null?void 0:i[_e.EXTENSION_NAME];if(!h)return null;let c=h.specVersion;if(!Wo.has(c))return console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${_e.EXTENSION_NAME} specVersion "${c}"`),null;let p=(r=h.colliders)==null?void 0:r.map((m,g)=>{var _,M,T,R,v,E,x,S,L,A,b,V,$,Re,Te;let X=d[m.node];if(X==null)return console.warn(`VRMSpringBoneLoaderPlugin: The collider #${g} attempted to reference a node #${m.node} but not found. Skipping the collider`),null;let k=m.shape,ce=(_=m.extensions)==null?void 0:_[Ei];if(this.useExtendedColliders&&ce!=null){let xe=ce.specVersion;if(!Go.has(xe))console.warn(`VRMSpringBoneLoaderPlugin: Unknown ${Ei} specVersion "${xe}". Fallbacking to the ${_e.EXTENSION_NAME} definition`);else{let O=ce.shape;if(O.sphere)return this._importSphereCollider(X,{offset:new N.Vector3().fromArray((M=O.sphere.offset)!=null?M:[0,0,0]),radius:(T=O.sphere.radius)!=null?T:0,inside:(R=O.sphere.inside)!=null?R:!1});if(O.capsule)return this._importCapsuleCollider(X,{offset:new N.Vector3().fromArray((v=O.capsule.offset)!=null?v:[0,0,0]),radius:(E=O.capsule.radius)!=null?E:0,tail:new N.Vector3().fromArray((x=O.capsule.tail)!=null?x:[0,0,0]),inside:(S=O.capsule.inside)!=null?S:!1});if(O.plane)return this._importPlaneCollider(X,{offset:new N.Vector3().fromArray((L=O.plane.offset)!=null?L:[0,0,0]),normal:new N.Vector3().fromArray((A=O.plane.normal)!=null?A:[0,0,1])})}}if(k.sphere)return this._importSphereCollider(X,{offset:new N.Vector3().fromArray((b=k.sphere.offset)!=null?b:[0,0,0]),radius:(V=k.sphere.radius)!=null?V:0,inside:!1});if(k.capsule)return this._importCapsuleCollider(X,{offset:new N.Vector3().fromArray(($=k.capsule.offset)!=null?$:[0,0,0]),radius:(Re=k.capsule.radius)!=null?Re:0,tail:new N.Vector3().fromArray((Te=k.capsule.tail)!=null?Te:[0,0,0]),inside:!1});console.warn(`VRMSpringBoneLoaderPlugin: The collider #${g} has no valid shape. Skipping the collider`)}),f=(o=h.colliderGroups)==null?void 0:o.map((m,g)=>{var _;return{colliders:((_=m.colliders)!=null?_:[]).map(T=>{let R=p==null?void 0:p[T];return R==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${g} attempted to reference a collider #${T} but not found. Skipping the collider`),null):R}).filter(T=>T!=null),name:m.name}});return(s=h.springs)==null||s.forEach((m,g)=>{var _;let M=m.joints,T=(_=m.colliderGroups)==null?void 0:_.map(E=>{let x=f==null?void 0:f[E];return x==null?(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${g} attempted to reference a collider group #${E} but not found. Skipping the collider group`),null):x}).filter(E=>E!=null),R=m.center!=null?d[m.center]:void 0,v;M.forEach(E=>{if(v){let x=v.node,S=d[x],L=E.node,A=d[L],b={hitRadius:v.hitRadius,dragForce:v.dragForce,gravityPower:v.gravityPower,stiffness:v.stiffness,gravityDir:v.gravityDir!=null?new N.Vector3().fromArray(v.gravityDir):void 0},V=this._importJoint(S,A,b,T);R&&(V.center=R),u.addJoint(V)}v=E})}),u.setInitState(),u})}_v0Import(e){return Ye(this,null,function*(){var n,i,r;let o=e.parser.json;if(!(((n=o.extensionsUsed)==null?void 0:n.indexOf("VRM"))!==-1))return null;let l=(i=o.extensions)==null?void 0:i.VRM,a=l==null?void 0:l.secondaryAnimation;if(!a)return null;let u=a==null?void 0:a.boneGroups;if(!u)return null;let d=new vi,h=yield e.parser.getDependencies("node"),c=(r=a.colliderGroups)==null?void 0:r.map((p,f)=>{var m;let g=h[p.node];return g==null?(console.warn(`VRMSpringBoneLoaderPlugin: The collider group #${f} attempted to reference a node #${p.node} but not found. Skipping the collider group`),null):{colliders:((m=p.colliders)!=null?m:[]).map((M,T)=>{var R,v,E;let x=new N.Vector3(0,0,0);return M.offset&&x.set((R=M.offset.x)!=null?R:0,(v=M.offset.y)!=null?v:0,M.offset.z?-M.offset.z:0),this._importSphereCollider(g,{offset:x,radius:(E=M.radius)!=null?E:0,inside:!1})})}});return u==null||u.forEach((p,f)=>{let m=p.bones;m&&m.forEach(g=>{var _,M,T,R;let v=h[g];if(v==null){console.warn(`VRMSpringBoneLoaderPlugin: The spring bone group #${f} attempted to reference a node #${g} but not found. Skipping the node`);return}let E=new N.Vector3;p.gravityDir?E.set((_=p.gravityDir.x)!=null?_:0,(M=p.gravityDir.y)!=null?M:0,(T=p.gravityDir.z)!=null?T:0):E.set(0,-1,0);let x=p.center!=null?h[p.center]:void 0,S={hitRadius:p.hitRadius,dragForce:p.dragForce,gravityPower:p.gravityPower,stiffness:p.stiffiness,gravityDir:E},L=(R=p.colliderGroups)==null?void 0:R.map(A=>{let b=c==null?void 0:c[A];return b==null?(console.warn(`VRMSpringBoneLoaderPlugin: The spring #${f} attempted to reference a collider group #${A} but not found. Skipping the collider group`),null):b}).filter(A=>A!=null);v.traverse(A=>{var b;let V=(b=A.children[0])!=null?b:null,$=this._importJoint(A,V,S,L);x&&($.center=x),d.addJoint($)})})}),e.scene.updateMatrixWorld(),d.setInitState(),d})}_importJoint(e,n,i,r){let o=new Do(e,n,i,r);if(this.jointHelperRoot){let s=new Vo(o);this.jointHelperRoot.add(s),s.renderOrder=this.jointHelperRoot.renderOrder}return o}_importSphereCollider(e,n){let i=new Ti(n),r=new At(i);if(e.add(r),this.colliderHelperRoot){let o=new St(r);this.colliderHelperRoot.add(o),o.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importCapsuleCollider(e,n){let i=new Mi(n),r=new At(i);if(e.add(r),this.colliderHelperRoot){let o=new St(r);this.colliderHelperRoot.add(o),o.renderOrder=this.colliderHelperRoot.renderOrder}return r}_importPlaneCollider(e,n){let i=new Ri(n),r=new At(i);if(e.add(r),this.colliderHelperRoot){let o=new St(r);this.colliderHelperRoot.add(o),o.renderOrder=this.colliderHelperRoot.renderOrder}return r}};wi.EXTENSION_NAME="VRMC_springBone";var Si=wi;var It=class{get name(){return"VRMLoaderPlugin"}constructor(e,n){var o,s,l,a,u,d,h,c,p,f;this.parser=e;let i=n==null?void 0:n.helperRoot,r=n==null?void 0:n.autoUpdateHumanBones;this.expressionPlugin=(o=n==null?void 0:n.expressionPlugin)!=null?o:new ht(e),this.firstPersonPlugin=(s=n==null?void 0:n.firstPersonPlugin)!=null?s:new pt(e),this.humanoidPlugin=(l=n==null?void 0:n.humanoidPlugin)!=null?l:new ft(e,{helperRoot:i,autoUpdateHumanBones:r}),this.lookAtPlugin=(a=n==null?void 0:n.lookAtPlugin)!=null?a:new gt(e,{helperRoot:i}),this.metaPlugin=(u=n==null?void 0:n.metaPlugin)!=null?u:new _t(e),this.mtoonMaterialPlugin=(d=n==null?void 0:n.mtoonMaterialPlugin)!=null?d:new oi(e),this.materialsHDREmissiveMultiplierPlugin=(h=n==null?void 0:n.materialsHDREmissiveMultiplierPlugin)!=null?h:new ai(e),this.materialsV0CompatPlugin=(c=n==null?void 0:n.materialsV0CompatPlugin)!=null?c:new ci(e),this.springBonePlugin=(p=n==null?void 0:n.springBonePlugin)!=null?p:new Si(e,{colliderHelperRoot:i,jointHelperRoot:i}),this.nodeConstraintPlugin=(f=n==null?void 0:n.nodeConstraintPlugin)!=null?f:new gi(e,{helperRoot:i})}beforeRoot(){return ye(this,null,function*(){yield this.materialsV0CompatPlugin.beforeRoot(),yield this.mtoonMaterialPlugin.beforeRoot()})}loadMesh(e){return ye(this,null,function*(){return yield this.mtoonMaterialPlugin.loadMesh(e)})}getMaterialType(e){let n=this.mtoonMaterialPlugin.getMaterialType(e);return n!=null?n:null}extendMaterialParams(e,n){return ye(this,null,function*(){yield this.materialsHDREmissiveMultiplierPlugin.extendMaterialParams(e,n),yield this.mtoonMaterialPlugin.extendMaterialParams(e,n)})}afterRoot(e){return ye(this,null,function*(){yield this.metaPlugin.afterRoot(e),yield this.humanoidPlugin.afterRoot(e),yield this.expressionPlugin.afterRoot(e),yield this.lookAtPlugin.afterRoot(e),yield this.firstPersonPlugin.afterRoot(e),yield this.springBonePlugin.afterRoot(e),yield this.nodeConstraintPlugin.afterRoot(e),yield this.mtoonMaterialPlugin.afterRoot(e);let n=e.userData.vrmMeta,i=e.userData.vrmHumanoid;if(n&&i){let r=new be({scene:e.scene,expressionManager:e.userData.vrmExpressionManager,firstPerson:e.userData.vrmFirstPerson,humanoid:i,lookAt:e.userData.vrmLookAt,meta:n,materials:e.userData.vrmMToonMaterials,springBoneManager:e.userData.vrmSpringBoneManager,nodeConstraintManager:e.userData.vrmNodeConstraintManager});e.userData.vrm=r}})}};import*as Pi from"three";function zo(t){let e=new Set;return t.traverse(n=>{if(!n.isMesh)return;let i=n;e.add(i)}),e}function Ai(t,e,n){if(e.size===1){let s=e.values().next().value;if(s.weight===1)return t[s.index]}let i=new Float32Array(t[0].count*3),r=0;if(n)r=1;else for(let s of e)r+=s.weight;for(let s of e){let l=t[s.index],a=s.weight/r;for(let u=0;uu.getOrCreate(L)).join(","),x=`${R};${_};${E}`,S=s.get(x);S==null&&(S=T.clone(),qo(S,v,f),s.set(x,S)),M.geometry.setAttribute("skinIndex",S)}for(let M of p)M.bind(g,new Me.Matrix4)}}function jo(t){let e=new Set;return t.traverse(n=>{if(!n.isSkinnedMesh)return;let i=n;e.add(i)}),e}function Xo(t,e){let n=new Set;for(let i=0;in)return!1;return!0}var Ue=class{constructor(){this._objectIndexMap=new Map;this._index=0}get(e){return this._objectIndexMap.get(e)}getOrCreate(e){let n=this._objectIndexMap.get(e);return n==null&&(n=this._index,this._objectIndexMap.set(e,n),this._index++),n}};function Zo(t){var n,i,r,o;let e=new Me.BufferGeometry;e.name=t.name,e.setIndex(t.index);for(let[s,l]of Object.entries(t.attributes))e.setAttribute(s,l);for(let[s,l]of Object.entries(t.morphAttributes)){let a=s;e.morphAttributes[a]=l.concat()}e.morphTargetsRelative=t.morphTargetsRelative,e.groups=[];for(let s of t.groups)e.addGroup(s.start,s.count,s.materialIndex);return e.boundingSphere=(i=(n=t.boundingSphere)==null?void 0:n.clone())!=null?i:null,e.boundingBox=(o=(r=t.boundingBox)==null?void 0:r.clone())!=null?o:null,e.drawRange.start=t.drawRange.start,e.drawRange.count=t.drawRange.count,e.userData=t.userData,e}function Vi(t){if(Object.values(t).forEach(e=>{e!=null&&e.isTexture&&e.dispose()}),t.isShaderMaterial){let e=t.uniforms;e&&Object.values(e).forEach(n=>{let i=n.value;i!=null&&i.isTexture&&i.dispose()})}t.dispose()}function Jo(t){let e=t.geometry;e&&e.dispose();let n=t.skeleton;n&&n.dispose();let i=t.material;i&&(Array.isArray(i)?i.forEach(r=>Vi(r)):i&&Vi(i))}function Ci(t){t.traverse(Jo)}import*as Ze from"three";function Oi(t,e){var s,l;console.warn("VRMUtils.removeUnnecessaryJoints: removeUnnecessaryJoints is deprecated. Use combineSkeletons instead. combineSkeletons contributes more to the performance improvement. This function will be removed in the next major version.");let n=(s=e==null?void 0:e.experimentalSameBoneCounts)!=null?s:!1,i=[];t.traverse(a=>{a.type==="SkinnedMesh"&&i.push(a)});let r=new Map,o=0;for(let a of i){let d=a.geometry.getAttribute("skinIndex");if(r.has(d))continue;let h=new Map,c=new Map;for(let p=0;p{e.addGroup(s.start,s.count,s.materialIndex)}),e.boundingBox=(i=(n=t.boundingBox)==null?void 0:n.clone())!=null?i:null,e.boundingSphere=(o=(r=t.boundingSphere)==null?void 0:r.clone())!=null?o:null,e.setDrawRange(t.drawRange.start,t.drawRange.count),e.userData=t.userData}function ns(t,e,n){let i=e.array,r=new i.constructor(i.length);for(let o=0;o{if(!n.isMesh)return;let i=n,r=i.geometry,o=r.index;if(o==null)return;let s=e.get(r);if(s!=null){i.geometry=s;return}let{isVertexUsed:l,vertexCount:a,verticesUsed:u}=Ko(r.attributes,o);if(u===a)return;let{originalIndexNewIndexMap:d,newIndexOriginalIndexMap:h}=es(l),c=new ie.BufferGeometry;ts(r,c),e.set(r,c),ns(c,o,d),rs(c,r.attributes,h),ss(c,r.morphAttributes,h),i.geometry=c}),Array.from(e.keys()).forEach(n=>{n.dispose()})}function Bi(t){var e;((e=t.meta)==null?void 0:e.metaVersion)==="0"&&(t.scene.rotation.y=Math.PI)}var re=class{constructor(){}};re.combineMorphs=bi,re.combineSkeletons=Ii,re.deepDispose=Ci,re.removeUnnecessaryJoints=Oi,re.removeUnnecessaryVertices=Ui,re.rotateVRM0=Bi;export{$r as MToonMaterial,Yr as MToonMaterialDebugMode,oi as MToonMaterialLoaderPlugin,ei as MToonMaterialOutlineWidthMode,be as VRM,mo as VRMAimConstraint,vt as VRMCore,ms as VRMCoreLoaderPlugin,cn as VRMExpression,ht as VRMExpressionLoaderPlugin,mn as VRMExpressionManager,gn as VRMExpressionMaterialColorBind,we as VRMExpressionMaterialColorType,Ae as VRMExpressionMorphTargetBind,hs as VRMExpressionOverrideType,ot as VRMExpressionPresetName,vn as VRMExpressionTextureTransformBind,En as VRMFirstPerson,pt as VRMFirstPersonLoaderPlugin,cs as VRMFirstPersonMeshAnnotationType,tt as VRMHumanBoneList,ps as VRMHumanBoneName,Er as VRMHumanBoneParentMap,yn as VRMHumanoid,Tn as VRMHumanoidHelper,ft as VRMHumanoidLoaderPlugin,It as VRMLoaderPlugin,Or as VRMLookAt,Ge as VRMLookAtBoneApplier,ut as VRMLookAtExpressionApplier,Ar as VRMLookAtHelper,gt as VRMLookAtLoaderPlugin,Vn as VRMLookAtRangeMap,fs as VRMLookAtTypeName,_t as VRMMetaLoaderPlugin,xt as VRMNodeConstraint,Rt as VRMNodeConstraintHelper,gi as VRMNodeConstraintLoaderPlugin,_o as VRMNodeConstraintManager,Tr as VRMRequiredHumanBoneName,yo as VRMRollConstraint,Mo as VRMRotationConstraint,At as VRMSpringBoneCollider,St as VRMSpringBoneColliderHelper,Ht as VRMSpringBoneColliderShape,Mi as VRMSpringBoneColliderShapeCapsule,Ri as VRMSpringBoneColliderShapePlane,Ti as VRMSpringBoneColliderShapeSphere,Do as VRMSpringBoneJoint,Vo as VRMSpringBoneJointHelper,Si as VRMSpringBoneLoaderPlugin,vi as VRMSpringBoneManager,re as VRMUtils}; +/*! + * @pixiv/three-vrm-core v3.5.5 + * The implementation of core features of VRM, for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-core is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ +/*! + * @pixiv/three-vrm-materials-mtoon v3.5.5 + * MToon (toon material) module for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-materials-mtoon is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ +/*! + * @pixiv/three-vrm-materials-hdr-emissive-multiplier v3.5.5 + * Support VRMC_hdr_emissiveMultiplier for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-materials-hdr-emissive-multiplier is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ +/*! + * @pixiv/three-vrm-materials-v0compat v3.5.5 + * VRM0.0 materials compatibility layer plugin for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-materials-v0compat is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ +/*! + * @pixiv/three-vrm-node-constraint v3.5.5 + * Node constraint module for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-node-constraint is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ +/*! + * @pixiv/three-vrm-springbone v3.5.5 + * Spring bone module for @pixiv/three-vrm + * + * Copyright (c) 2019-2026 pixiv Inc. + * @pixiv/three-vrm-springbone is distributed under MIT License + * https://github.com/pixiv/three-vrm/blob/release/LICENSE + */ diff --git a/ui/viewer/vendor/three/LICENSE b/ui/viewer/vendor/three/LICENSE new file mode 100644 index 0000000..d33709f --- /dev/null +++ b/ui/viewer/vendor/three/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright © 2010-2024 three.js authors + +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/ui/viewer/vendor/three/addons/animation/CCDIKSolver.js b/ui/viewer/vendor/three/addons/animation/CCDIKSolver.js new file mode 100644 index 0000000..4a0ae53 --- /dev/null +++ b/ui/viewer/vendor/three/addons/animation/CCDIKSolver.js @@ -0,0 +1,484 @@ +import { + BufferAttribute, + BufferGeometry, + Color, + Line, + LineBasicMaterial, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + Quaternion, + SphereGeometry, + Vector3 +} from 'three'; + +const _q = new Quaternion(); +const _targetPos = new Vector3(); +const _targetVec = new Vector3(); +const _effectorPos = new Vector3(); +const _effectorVec = new Vector3(); +const _linkPos = new Vector3(); +const _invLinkQ = new Quaternion(); +const _linkScale = new Vector3(); +const _axis = new Vector3(); +const _vector = new Vector3(); +const _matrix = new Matrix4(); + + +/** + * CCD Algorithm + * - https://sites.google.com/site/auraliusproject/ccd-algorithm + * + * // ik parameter example + * // + * // target, effector, index in links are bone index in skeleton.bones. + * // the bones relation should be + * // <-- parent child --> + * // links[ n ], links[ n - 1 ], ..., links[ 0 ], effector + * iks = [ { + * target: 1, + * effector: 2, + * links: [ { index: 5, limitation: new Vector3( 1, 0, 0 ) }, { index: 4, enabled: false }, { index : 3 } ], + * iteration: 10, + * minAngle: 0.0, + * maxAngle: 1.0, + * } ]; + */ + +class CCDIKSolver { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Array} iks + */ + constructor( mesh, iks = [] ) { + + this.mesh = mesh; + this.iks = iks; + + this._valid(); + + } + + /** + * Update all IK bones. + * + * @return {CCDIKSolver} + */ + update() { + + const iks = this.iks; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + this.updateOne( iks[ i ] ); + + } + + return this; + + } + + /** + * Update one IK bone + * + * @param {Object} ik parameter + * @return {CCDIKSolver} + */ + updateOne( ik ) { + + const bones = this.mesh.skeleton.bones; + + // for reference overhead reduction in loop + const math = Math; + + const effector = bones[ ik.effector ]; + const target = bones[ ik.target ]; + + // don't use getWorldPosition() here for the performance + // because it calls updateMatrixWorld( true ) inside. + _targetPos.setFromMatrixPosition( target.matrixWorld ); + + const links = ik.links; + const iteration = ik.iteration !== undefined ? ik.iteration : 1; + + for ( let i = 0; i < iteration; i ++ ) { + + let rotated = false; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + const link = bones[ links[ j ].index ]; + + // skip this link and following links. + // this skip is used for MMD performance optimization. + if ( links[ j ].enabled === false ) break; + + const limitation = links[ j ].limitation; + const rotationMin = links[ j ].rotationMin; + const rotationMax = links[ j ].rotationMax; + + // don't use getWorldPosition/Quaternion() here for the performance + // because they call updateMatrixWorld( true ) inside. + link.matrixWorld.decompose( _linkPos, _invLinkQ, _linkScale ); + _invLinkQ.invert(); + _effectorPos.setFromMatrixPosition( effector.matrixWorld ); + + // work in link world + _effectorVec.subVectors( _effectorPos, _linkPos ); + _effectorVec.applyQuaternion( _invLinkQ ); + _effectorVec.normalize(); + + _targetVec.subVectors( _targetPos, _linkPos ); + _targetVec.applyQuaternion( _invLinkQ ); + _targetVec.normalize(); + + let angle = _targetVec.dot( _effectorVec ); + + if ( angle > 1.0 ) { + + angle = 1.0; + + } else if ( angle < - 1.0 ) { + + angle = - 1.0; + + } + + angle = math.acos( angle ); + + // skip if changing angle is too small to prevent vibration of bone + if ( angle < 1e-5 ) continue; + + if ( ik.minAngle !== undefined && angle < ik.minAngle ) { + + angle = ik.minAngle; + + } + + if ( ik.maxAngle !== undefined && angle > ik.maxAngle ) { + + angle = ik.maxAngle; + + } + + _axis.crossVectors( _effectorVec, _targetVec ); + _axis.normalize(); + + _q.setFromAxisAngle( _axis, angle ); + link.quaternion.multiply( _q ); + + // TODO: re-consider the limitation specification + if ( limitation !== undefined ) { + + let c = link.quaternion.w; + + if ( c > 1.0 ) c = 1.0; + + const c2 = math.sqrt( 1 - c * c ); + link.quaternion.set( limitation.x * c2, + limitation.y * c2, + limitation.z * c2, + c ); + + } + + if ( rotationMin !== undefined ) { + + link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).max( rotationMin ) ); + + } + + if ( rotationMax !== undefined ) { + + link.rotation.setFromVector3( _vector.setFromEuler( link.rotation ).min( rotationMax ) ); + + } + + link.updateMatrixWorld( true ); + + rotated = true; + + } + + if ( ! rotated ) break; + + } + + return this; + + } + + /** + * Creates Helper + * + * @param {number} sphereSize + * @return {CCDIKHelper} + */ + createHelper( sphereSize ) { + + return new CCDIKHelper( this.mesh, this.iks, sphereSize ); + + } + + // private methods + + _valid() { + + const iks = this.iks; + const bones = this.mesh.skeleton.bones; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + const effector = bones[ ik.effector ]; + const links = ik.links; + let link0, link1; + + link0 = effector; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + link1 = bones[ links[ j ].index ]; + + if ( link0.parent !== link1 ) { + + console.warn( 'THREE.CCDIKSolver: bone ' + link0.name + ' is not the child of bone ' + link1.name ); + + } + + link0 = link1; + + } + + } + + } + +} + +function getPosition( bone, matrixWorldInv ) { + + return _vector + .setFromMatrixPosition( bone.matrixWorld ) + .applyMatrix4( matrixWorldInv ); + +} + +function setPositionOfBoneToAttributeArray( array, index, bone, matrixWorldInv ) { + + const v = getPosition( bone, matrixWorldInv ); + + array[ index * 3 + 0 ] = v.x; + array[ index * 3 + 1 ] = v.y; + array[ index * 3 + 2 ] = v.z; + +} + +/** + * Visualize IK bones + * + * @param {SkinnedMesh} mesh + * @param {Array} iks + * @param {number} sphereSize + */ +class CCDIKHelper extends Object3D { + + constructor( mesh, iks = [], sphereSize = 0.25 ) { + + super(); + + this.root = mesh; + this.iks = iks; + + this.matrix.copy( mesh.matrixWorld ); + this.matrixAutoUpdate = false; + + this.sphereGeometry = new SphereGeometry( sphereSize, 16, 8 ); + + this.targetSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0xff8888 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.effectorSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0x88ff88 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.linkSphereMaterial = new MeshBasicMaterial( { + color: new Color( 0x8888ff ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this.lineMaterial = new LineBasicMaterial( { + color: new Color( 0xff0000 ), + depthTest: false, + depthWrite: false, + transparent: true + } ); + + this._init(); + + } + + /** + * Updates IK bones visualization. + */ + updateMatrixWorld( force ) { + + const mesh = this.root; + + if ( this.visible ) { + + let offset = 0; + + const iks = this.iks; + const bones = mesh.skeleton.bones; + + _matrix.copy( mesh.matrixWorld ).invert(); + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + + const targetBone = bones[ ik.target ]; + const effectorBone = bones[ ik.effector ]; + + const targetMesh = this.children[ offset ++ ]; + const effectorMesh = this.children[ offset ++ ]; + + targetMesh.position.copy( getPosition( targetBone, _matrix ) ); + effectorMesh.position.copy( getPosition( effectorBone, _matrix ) ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = ik.links[ j ]; + const linkBone = bones[ link.index ]; + + const linkMesh = this.children[ offset ++ ]; + + linkMesh.position.copy( getPosition( linkBone, _matrix ) ); + + } + + const line = this.children[ offset ++ ]; + const array = line.geometry.attributes.position.array; + + setPositionOfBoneToAttributeArray( array, 0, targetBone, _matrix ); + setPositionOfBoneToAttributeArray( array, 1, effectorBone, _matrix ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = ik.links[ j ]; + const linkBone = bones[ link.index ]; + setPositionOfBoneToAttributeArray( array, j + 2, linkBone, _matrix ); + + } + + line.geometry.attributes.position.needsUpdate = true; + + } + + } + + this.matrix.copy( mesh.matrixWorld ); + + super.updateMatrixWorld( force ); + + } + + /** + * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. + */ + dispose() { + + this.sphereGeometry.dispose(); + + this.targetSphereMaterial.dispose(); + this.effectorSphereMaterial.dispose(); + this.linkSphereMaterial.dispose(); + this.lineMaterial.dispose(); + + const children = this.children; + + for ( let i = 0; i < children.length; i ++ ) { + + const child = children[ i ]; + + if ( child.isLine ) child.geometry.dispose(); + + } + + } + + // private method + + _init() { + + const scope = this; + const iks = this.iks; + + function createLineGeometry( ik ) { + + const geometry = new BufferGeometry(); + const vertices = new Float32Array( ( 2 + ik.links.length ) * 3 ); + geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) ); + + return geometry; + + } + + function createTargetMesh() { + + return new Mesh( scope.sphereGeometry, scope.targetSphereMaterial ); + + } + + function createEffectorMesh() { + + return new Mesh( scope.sphereGeometry, scope.effectorSphereMaterial ); + + } + + function createLinkMesh() { + + return new Mesh( scope.sphereGeometry, scope.linkSphereMaterial ); + + } + + function createLine( ik ) { + + return new Line( createLineGeometry( ik ), scope.lineMaterial ); + + } + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + + this.add( createTargetMesh() ); + this.add( createEffectorMesh() ); + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + this.add( createLinkMesh() ); + + } + + this.add( createLine( ik ) ); + + } + + } + +} + +export { CCDIKSolver, CCDIKHelper }; diff --git a/ui/viewer/vendor/three/addons/animation/MMDAnimationHelper.js b/ui/viewer/vendor/three/addons/animation/MMDAnimationHelper.js new file mode 100644 index 0000000..b24dea1 --- /dev/null +++ b/ui/viewer/vendor/three/addons/animation/MMDAnimationHelper.js @@ -0,0 +1,1207 @@ +import { + AnimationMixer, + Object3D, + Quaternion, + Vector3 +} from 'three'; +import { CCDIKSolver } from '../animation/CCDIKSolver.js'; +import { MMDPhysics } from '../animation/MMDPhysics.js'; + +/** + * MMDAnimationHelper handles animation of MMD assets loaded by MMDLoader + * with MMD special features as IK, Grant, and Physics. + * + * Dependencies + * - ammo.js https://github.com/kripken/ammo.js + * - MMDPhysics + * - CCDIKSolver + * + * TODO + * - more precise grant skinning support. + */ +class MMDAnimationHelper { + + /** + * @param {Object} params - (optional) + * @param {boolean} params.sync - Whether animation durations of added objects are synched. Default is true. + * @param {Number} params.afterglow - Default is 0.0. + * @param {boolean} params.resetPhysicsOnLoop - Default is true. + */ + constructor( params = {} ) { + + this.meshes = []; + + this.camera = null; + this.cameraTarget = new Object3D(); + this.cameraTarget.name = 'target'; + + this.audio = null; + this.audioManager = null; + + this.objects = new WeakMap(); + + this.configuration = { + sync: params.sync !== undefined ? params.sync : true, + afterglow: params.afterglow !== undefined ? params.afterglow : 0.0, + resetPhysicsOnLoop: params.resetPhysicsOnLoop !== undefined ? params.resetPhysicsOnLoop : true, + pmxAnimation: params.pmxAnimation !== undefined ? params.pmxAnimation : false + }; + + this.enabled = { + animation: true, + ik: true, + grant: true, + physics: true, + cameraAnimation: true + }; + + this.onBeforePhysics = function ( /* mesh */ ) {}; + + // experimental + this.sharedPhysics = false; + this.masterPhysics = null; + + } + + /** + * Adds an Three.js Object to helper and setups animation. + * The anmation durations of added objects are synched + * if this.configuration.sync is true. + * + * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object + * @param {Object} params - (optional) + * @param {THREE.AnimationClip|Array} params.animation - Only for THREE.SkinnedMesh and THREE.Camera. Default is undefined. + * @param {boolean} params.physics - Only for THREE.SkinnedMesh. Default is true. + * @param {Integer} params.warmup - Only for THREE.SkinnedMesh and physics is true. Default is 60. + * @param {Number} params.unitStep - Only for THREE.SkinnedMesh and physics is true. Default is 1 / 65. + * @param {Integer} params.maxStepNum - Only for THREE.SkinnedMesh and physics is true. Default is 3. + * @param {Vector3} params.gravity - Only for THREE.SkinnedMesh and physics is true. Default ( 0, - 9.8 * 10, 0 ). + * @param {Number} params.delayTime - Only for THREE.Audio. Default is 0.0. + * @return {MMDAnimationHelper} + */ + add( object, params = {} ) { + + if ( object.isSkinnedMesh ) { + + this._addMesh( object, params ); + + } else if ( object.isCamera ) { + + this._setupCamera( object, params ); + + } else if ( object.type === 'Audio' ) { + + this._setupAudio( object, params ); + + } else { + + throw new Error( 'THREE.MMDAnimationHelper.add: ' + + 'accepts only ' + + 'THREE.SkinnedMesh or ' + + 'THREE.Camera or ' + + 'THREE.Audio instance.' ); + + } + + if ( this.configuration.sync ) this._syncDuration(); + + return this; + + } + + /** + * Removes an Three.js Object from helper. + * + * @param {THREE.SkinnedMesh|THREE.Camera|THREE.Audio} object + * @return {MMDAnimationHelper} + */ + remove( object ) { + + if ( object.isSkinnedMesh ) { + + this._removeMesh( object ); + + } else if ( object.isCamera ) { + + this._clearCamera( object ); + + } else if ( object.type === 'Audio' ) { + + this._clearAudio( object ); + + } else { + + throw new Error( 'THREE.MMDAnimationHelper.remove: ' + + 'accepts only ' + + 'THREE.SkinnedMesh or ' + + 'THREE.Camera or ' + + 'THREE.Audio instance.' ); + + } + + if ( this.configuration.sync ) this._syncDuration(); + + return this; + + } + + /** + * Updates the animation. + * + * @param {Number} delta + * @return {MMDAnimationHelper} + */ + update( delta ) { + + if ( this.audioManager !== null ) this.audioManager.control( delta ); + + for ( let i = 0; i < this.meshes.length; i ++ ) { + + this._animateMesh( this.meshes[ i ], delta ); + + } + + if ( this.sharedPhysics ) this._updateSharedPhysics( delta ); + + if ( this.camera !== null ) this._animateCamera( this.camera, delta ); + + return this; + + } + + /** + * Changes the pose of SkinnedMesh as VPD specifies. + * + * @param {THREE.SkinnedMesh} mesh + * @param {Object} vpd - VPD content parsed MMDParser + * @param {Object} params - (optional) + * @param {boolean} params.resetPose - Default is true. + * @param {boolean} params.ik - Default is true. + * @param {boolean} params.grant - Default is true. + * @return {MMDAnimationHelper} + */ + pose( mesh, vpd, params = {} ) { + + if ( params.resetPose !== false ) mesh.pose(); + + const bones = mesh.skeleton.bones; + const boneParams = vpd.bones; + + const boneNameDictionary = {}; + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + boneNameDictionary[ bones[ i ].name ] = i; + + } + + const vector = new Vector3(); + const quaternion = new Quaternion(); + + for ( let i = 0, il = boneParams.length; i < il; i ++ ) { + + const boneParam = boneParams[ i ]; + const boneIndex = boneNameDictionary[ boneParam.name ]; + + if ( boneIndex === undefined ) continue; + + const bone = bones[ boneIndex ]; + bone.position.add( vector.fromArray( boneParam.translation ) ); + bone.quaternion.multiply( quaternion.fromArray( boneParam.quaternion ) ); + + } + + mesh.updateMatrixWorld( true ); + + // PMX animation system special path + if ( this.configuration.pmxAnimation && + mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) { + + const sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() ); + const ikSolver = params.ik !== false ? this._createCCDIKSolver( mesh ) : null; + const grantSolver = params.grant !== false ? this.createGrantSolver( mesh ) : null; + this._animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ); + + } else { + + if ( params.ik !== false ) { + + this._createCCDIKSolver( mesh ).update(); + + } + + if ( params.grant !== false ) { + + this.createGrantSolver( mesh ).update(); + + } + + } + + return this; + + } + + /** + * Enabes/Disables an animation feature. + * + * @param {string} key + * @param {boolean} enabled + * @return {MMDAnimationHelper} + */ + enable( key, enabled ) { + + if ( this.enabled[ key ] === undefined ) { + + throw new Error( 'THREE.MMDAnimationHelper.enable: ' + + 'unknown key ' + key ); + + } + + this.enabled[ key ] = enabled; + + if ( key === 'physics' ) { + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + this._optimizeIK( this.meshes[ i ], enabled ); + + } + + } + + return this; + + } + + /** + * Creates an GrantSolver instance. + * + * @param {THREE.SkinnedMesh} mesh + * @return {GrantSolver} + */ + createGrantSolver( mesh ) { + + return new GrantSolver( mesh, mesh.geometry.userData.MMD.grants ); + + } + + // private methods + + _addMesh( mesh, params ) { + + if ( this.meshes.indexOf( mesh ) >= 0 ) { + + throw new Error( 'THREE.MMDAnimationHelper._addMesh: ' + + 'SkinnedMesh \'' + mesh.name + '\' has already been added.' ); + + } + + this.meshes.push( mesh ); + this.objects.set( mesh, { looped: false } ); + + this._setupMeshAnimation( mesh, params.animation ); + + if ( params.physics !== false ) { + + this._setupMeshPhysics( mesh, params ); + + } + + return this; + + } + + _setupCamera( camera, params ) { + + if ( this.camera === camera ) { + + throw new Error( 'THREE.MMDAnimationHelper._setupCamera: ' + + 'Camera \'' + camera.name + '\' has already been set.' ); + + } + + if ( this.camera ) this.clearCamera( this.camera ); + + this.camera = camera; + + camera.add( this.cameraTarget ); + + this.objects.set( camera, {} ); + + if ( params.animation !== undefined ) { + + this._setupCameraAnimation( camera, params.animation ); + + } + + return this; + + } + + _setupAudio( audio, params ) { + + if ( this.audio === audio ) { + + throw new Error( 'THREE.MMDAnimationHelper._setupAudio: ' + + 'Audio \'' + audio.name + '\' has already been set.' ); + + } + + if ( this.audio ) this.clearAudio( this.audio ); + + this.audio = audio; + this.audioManager = new AudioManager( audio, params ); + + this.objects.set( this.audioManager, { + duration: this.audioManager.duration + } ); + + return this; + + } + + _removeMesh( mesh ) { + + let found = false; + let writeIndex = 0; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + if ( this.meshes[ i ] === mesh ) { + + this.objects.delete( mesh ); + found = true; + + continue; + + } + + this.meshes[ writeIndex ++ ] = this.meshes[ i ]; + + } + + if ( ! found ) { + + throw new Error( 'THREE.MMDAnimationHelper._removeMesh: ' + + 'SkinnedMesh \'' + mesh.name + '\' has not been added yet.' ); + + } + + this.meshes.length = writeIndex; + + return this; + + } + + _clearCamera( camera ) { + + if ( camera !== this.camera ) { + + throw new Error( 'THREE.MMDAnimationHelper._clearCamera: ' + + 'Camera \'' + camera.name + '\' has not been set yet.' ); + + } + + this.camera.remove( this.cameraTarget ); + + this.objects.delete( this.camera ); + this.camera = null; + + return this; + + } + + _clearAudio( audio ) { + + if ( audio !== this.audio ) { + + throw new Error( 'THREE.MMDAnimationHelper._clearAudio: ' + + 'Audio \'' + audio.name + '\' has not been set yet.' ); + + } + + this.objects.delete( this.audioManager ); + + this.audio = null; + this.audioManager = null; + + return this; + + } + + _setupMeshAnimation( mesh, animation ) { + + const objects = this.objects.get( mesh ); + + if ( animation !== undefined ) { + + const animations = Array.isArray( animation ) + ? animation : [ animation ]; + + objects.mixer = new AnimationMixer( mesh ); + + for ( let i = 0, il = animations.length; i < il; i ++ ) { + + objects.mixer.clipAction( animations[ i ] ).play(); + + } + + // TODO: find a workaround not to access ._clip looking like a private property + objects.mixer.addEventListener( 'loop', function ( event ) { + + const tracks = event.action._clip.tracks; + + if ( tracks.length > 0 && tracks[ 0 ].name.slice( 0, 6 ) !== '.bones' ) return; + + objects.looped = true; + + } ); + + } + + objects.ikSolver = this._createCCDIKSolver( mesh ); + objects.grantSolver = this.createGrantSolver( mesh ); + + return this; + + } + + _setupCameraAnimation( camera, animation ) { + + const animations = Array.isArray( animation ) + ? animation : [ animation ]; + + const objects = this.objects.get( camera ); + + objects.mixer = new AnimationMixer( camera ); + + for ( let i = 0, il = animations.length; i < il; i ++ ) { + + objects.mixer.clipAction( animations[ i ] ).play(); + + } + + } + + _setupMeshPhysics( mesh, params ) { + + const objects = this.objects.get( mesh ); + + // shared physics is experimental + + if ( params.world === undefined && this.sharedPhysics ) { + + const masterPhysics = this._getMasterPhysics(); + + if ( masterPhysics !== null ) world = masterPhysics.world; // eslint-disable-line no-undef + + } + + objects.physics = this._createMMDPhysics( mesh, params ); + + if ( objects.mixer && params.animationWarmup !== false ) { + + this._animateMesh( mesh, 0 ); + objects.physics.reset(); + + } + + objects.physics.warmup( params.warmup !== undefined ? params.warmup : 60 ); + + this._optimizeIK( mesh, true ); + + } + + _animateMesh( mesh, delta ) { + + const objects = this.objects.get( mesh ); + + const mixer = objects.mixer; + const ikSolver = objects.ikSolver; + const grantSolver = objects.grantSolver; + const physics = objects.physics; + const looped = objects.looped; + + if ( mixer && this.enabled.animation ) { + + // alternate solution to save/restore bones but less performant? + //mesh.pose(); + //this._updatePropertyMixersBuffer( mesh ); + + this._restoreBones( mesh ); + + mixer.update( delta ); + + this._saveBones( mesh ); + + // PMX animation system special path + if ( this.configuration.pmxAnimation && + mesh.geometry.userData.MMD && mesh.geometry.userData.MMD.format === 'pmx' ) { + + if ( ! objects.sortedBonesData ) objects.sortedBonesData = this._sortBoneDataArray( mesh.geometry.userData.MMD.bones.slice() ); + + this._animatePMXMesh( + mesh, + objects.sortedBonesData, + ikSolver && this.enabled.ik ? ikSolver : null, + grantSolver && this.enabled.grant ? grantSolver : null + ); + + } else { + + if ( ikSolver && this.enabled.ik ) { + + mesh.updateMatrixWorld( true ); + ikSolver.update(); + + } + + if ( grantSolver && this.enabled.grant ) { + + grantSolver.update(); + + } + + } + + } + + if ( looped === true && this.enabled.physics ) { + + if ( physics && this.configuration.resetPhysicsOnLoop ) physics.reset(); + + objects.looped = false; + + } + + if ( physics && this.enabled.physics && ! this.sharedPhysics ) { + + this.onBeforePhysics( mesh ); + physics.update( delta ); + + } + + } + + // Sort bones in order by 1. transformationClass and 2. bone index. + // In PMX animation system, bone transformations should be processed + // in this order. + _sortBoneDataArray( boneDataArray ) { + + return boneDataArray.sort( function ( a, b ) { + + if ( a.transformationClass !== b.transformationClass ) { + + return a.transformationClass - b.transformationClass; + + } else { + + return a.index - b.index; + + } + + } ); + + } + + // PMX Animation system is a bit too complex and doesn't great match to + // Three.js Animation system. This method attempts to simulate it as much as + // possible but doesn't perfectly simulate. + // This method is more costly than the regular one so + // you are recommended to set constructor parameter "pmxAnimation: true" + // only if your PMX model animation doesn't work well. + // If you need better method you would be required to write your own. + _animatePMXMesh( mesh, sortedBonesData, ikSolver, grantSolver ) { + + _quaternionIndex = 0; + _grantResultMap.clear(); + + for ( let i = 0, il = sortedBonesData.length; i < il; i ++ ) { + + updateOne( mesh, sortedBonesData[ i ].index, ikSolver, grantSolver ); + + } + + mesh.updateMatrixWorld( true ); + return this; + + } + + _animateCamera( camera, delta ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer && this.enabled.cameraAnimation ) { + + mixer.update( delta ); + + camera.updateProjectionMatrix(); + + camera.up.set( 0, 1, 0 ); + camera.up.applyQuaternion( camera.quaternion ); + camera.lookAt( this.cameraTarget.position ); + + } + + } + + _optimizeIK( mesh, physicsEnabled ) { + + const iks = mesh.geometry.userData.MMD.iks; + const bones = mesh.geometry.userData.MMD.bones; + + for ( let i = 0, il = iks.length; i < il; i ++ ) { + + const ik = iks[ i ]; + const links = ik.links; + + for ( let j = 0, jl = links.length; j < jl; j ++ ) { + + const link = links[ j ]; + + if ( physicsEnabled === true ) { + + // disable IK of the bone the corresponding rigidBody type of which is 1 or 2 + // because its rotation will be overriden by physics + link.enabled = bones[ link.index ].rigidBodyType > 0 ? false : true; + + } else { + + link.enabled = true; + + } + + } + + } + + } + + _createCCDIKSolver( mesh ) { + + if ( CCDIKSolver === undefined ) { + + throw new Error( 'THREE.MMDAnimationHelper: Import CCDIKSolver.' ); + + } + + return new CCDIKSolver( mesh, mesh.geometry.userData.MMD.iks ); + + } + + _createMMDPhysics( mesh, params ) { + + if ( MMDPhysics === undefined ) { + + throw new Error( 'THREE.MMDPhysics: Import MMDPhysics.' ); + + } + + return new MMDPhysics( + mesh, + mesh.geometry.userData.MMD.rigidBodies, + mesh.geometry.userData.MMD.constraints, + params ); + + } + + /* + * Detects the longest duration and then sets it to them to sync. + * TODO: Not to access private properties ( ._actions and ._clip ) + */ + _syncDuration() { + + let max = 0.0; + + const objects = this.objects; + const meshes = this.meshes; + const camera = this.camera; + const audioManager = this.audioManager; + + // get the longest duration + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + const mixer = this.objects.get( meshes[ i ] ).mixer; + + if ( mixer === undefined ) continue; + + for ( let j = 0; j < mixer._actions.length; j ++ ) { + + const clip = mixer._actions[ j ]._clip; + + if ( ! objects.has( clip ) ) { + + objects.set( clip, { + duration: clip.duration + } ); + + } + + max = Math.max( max, objects.get( clip ).duration ); + + } + + } + + if ( camera !== null ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer !== undefined ) { + + for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) { + + const clip = mixer._actions[ i ]._clip; + + if ( ! objects.has( clip ) ) { + + objects.set( clip, { + duration: clip.duration + } ); + + } + + max = Math.max( max, objects.get( clip ).duration ); + + } + + } + + } + + if ( audioManager !== null ) { + + max = Math.max( max, objects.get( audioManager ).duration ); + + } + + max += this.configuration.afterglow; + + // update the duration + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const mixer = this.objects.get( this.meshes[ i ] ).mixer; + + if ( mixer === undefined ) continue; + + for ( let j = 0, jl = mixer._actions.length; j < jl; j ++ ) { + + mixer._actions[ j ]._clip.duration = max; + + } + + } + + if ( camera !== null ) { + + const mixer = this.objects.get( camera ).mixer; + + if ( mixer !== undefined ) { + + for ( let i = 0, il = mixer._actions.length; i < il; i ++ ) { + + mixer._actions[ i ]._clip.duration = max; + + } + + } + + } + + if ( audioManager !== null ) { + + audioManager.duration = max; + + } + + } + + // workaround + + _updatePropertyMixersBuffer( mesh ) { + + const mixer = this.objects.get( mesh ).mixer; + + const propertyMixers = mixer._bindings; + const accuIndex = mixer._accuIndex; + + for ( let i = 0, il = propertyMixers.length; i < il; i ++ ) { + + const propertyMixer = propertyMixers[ i ]; + const buffer = propertyMixer.buffer; + const stride = propertyMixer.valueSize; + const offset = ( accuIndex + 1 ) * stride; + + propertyMixer.binding.getValue( buffer, offset ); + + } + + } + + /* + * Avoiding these two issues by restore/save bones before/after mixer animation. + * + * 1. PropertyMixer used by AnimationMixer holds cache value in .buffer. + * Calculating IK, Grant, and Physics after mixer animation can break + * the cache coherency. + * + * 2. Applying Grant two or more times without reset the posing breaks model. + */ + _saveBones( mesh ) { + + const objects = this.objects.get( mesh ); + + const bones = mesh.skeleton.bones; + + let backupBones = objects.backupBones; + + if ( backupBones === undefined ) { + + backupBones = new Float32Array( bones.length * 7 ); + objects.backupBones = backupBones; + + } + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + const bone = bones[ i ]; + bone.position.toArray( backupBones, i * 7 ); + bone.quaternion.toArray( backupBones, i * 7 + 3 ); + + } + + } + + _restoreBones( mesh ) { + + const objects = this.objects.get( mesh ); + + const backupBones = objects.backupBones; + + if ( backupBones === undefined ) return; + + const bones = mesh.skeleton.bones; + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + const bone = bones[ i ]; + bone.position.fromArray( backupBones, i * 7 ); + bone.quaternion.fromArray( backupBones, i * 7 + 3 ); + + } + + } + + // experimental + + _getMasterPhysics() { + + if ( this.masterPhysics !== null ) return this.masterPhysics; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const physics = this.meshes[ i ].physics; + + if ( physics !== undefined && physics !== null ) { + + this.masterPhysics = physics; + return this.masterPhysics; + + } + + } + + return null; + + } + + _updateSharedPhysics( delta ) { + + if ( this.meshes.length === 0 || ! this.enabled.physics || ! this.sharedPhysics ) return; + + const physics = this._getMasterPhysics(); + + if ( physics === null ) return; + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const p = this.meshes[ i ].physics; + + if ( p !== null && p !== undefined ) { + + p.updateRigidBodies(); + + } + + } + + physics.stepSimulation( delta ); + + for ( let i = 0, il = this.meshes.length; i < il; i ++ ) { + + const p = this.meshes[ i ].physics; + + if ( p !== null && p !== undefined ) { + + p.updateBones(); + + } + + } + + } + +} + +// Keep working quaternions for less GC +const _quaternions = []; +let _quaternionIndex = 0; + +function getQuaternion() { + + if ( _quaternionIndex >= _quaternions.length ) { + + _quaternions.push( new Quaternion() ); + + } + + return _quaternions[ _quaternionIndex ++ ]; + +} + +// Save rotation whose grant and IK are already applied +// used by grant children +const _grantResultMap = new Map(); + +function updateOne( mesh, boneIndex, ikSolver, grantSolver ) { + + const bones = mesh.skeleton.bones; + const bonesData = mesh.geometry.userData.MMD.bones; + const boneData = bonesData[ boneIndex ]; + const bone = bones[ boneIndex ]; + + // Return if already updated by being referred as a grant parent. + if ( _grantResultMap.has( boneIndex ) ) return; + + const quaternion = getQuaternion(); + + // Initialize grant result here to prevent infinite loop. + // If it's referred before updating with actual result later + // result without applyting IK or grant is gotten + // but better than composing of infinite loop. + _grantResultMap.set( boneIndex, quaternion.copy( bone.quaternion ) ); + + // @TODO: Support global grant and grant position + if ( grantSolver && boneData.grant && + ! boneData.grant.isLocal && boneData.grant.affectRotation ) { + + const parentIndex = boneData.grant.parentIndex; + const ratio = boneData.grant.ratio; + + if ( ! _grantResultMap.has( parentIndex ) ) { + + updateOne( mesh, parentIndex, ikSolver, grantSolver ); + + } + + grantSolver.addGrantRotation( bone, _grantResultMap.get( parentIndex ), ratio ); + + } + + if ( ikSolver && boneData.ik ) { + + // @TODO: Updating world matrices every time solving an IK bone is + // costly. Optimize if possible. + mesh.updateMatrixWorld( true ); + ikSolver.updateOne( boneData.ik ); + + // No confident, but it seems the grant results with ik links should be updated? + const links = boneData.ik.links; + + for ( let i = 0, il = links.length; i < il; i ++ ) { + + const link = links[ i ]; + + if ( link.enabled === false ) continue; + + const linkIndex = link.index; + + if ( _grantResultMap.has( linkIndex ) ) { + + _grantResultMap.set( linkIndex, _grantResultMap.get( linkIndex ).copy( bones[ linkIndex ].quaternion ) ); + + } + + } + + } + + // Update with the actual result here + quaternion.copy( bone.quaternion ); + +} + +// + +class AudioManager { + + /** + * @param {THREE.Audio} audio + * @param {Object} params - (optional) + * @param {Nuumber} params.delayTime + */ + constructor( audio, params = {} ) { + + this.audio = audio; + + this.elapsedTime = 0.0; + this.currentTime = 0.0; + this.delayTime = params.delayTime !== undefined + ? params.delayTime : 0.0; + + this.audioDuration = this.audio.buffer.duration; + this.duration = this.audioDuration + this.delayTime; + + } + + /** + * @param {Number} delta + * @return {AudioManager} + */ + control( delta ) { + + this.elapsed += delta; + this.currentTime += delta; + + if ( this._shouldStopAudio() ) this.audio.stop(); + if ( this._shouldStartAudio() ) this.audio.play(); + + return this; + + } + + // private methods + + _shouldStartAudio() { + + if ( this.audio.isPlaying ) return false; + + while ( this.currentTime >= this.duration ) { + + this.currentTime -= this.duration; + + } + + if ( this.currentTime < this.delayTime ) return false; + + // 'duration' can be bigger than 'audioDuration + delayTime' because of sync configuration + if ( ( this.currentTime - this.delayTime ) > this.audioDuration ) return false; + + return true; + + } + + _shouldStopAudio() { + + return this.audio.isPlaying && + this.currentTime >= this.duration; + + } + +} + +const _q = new Quaternion(); + +/** + * Solver for Grant (Fuyo in Japanese. I just google translated because + * Fuyo may be MMD specific term and may not be common word in 3D CG terms.) + * Grant propagates a bone's transform to other bones transforms even if + * they are not children. + * @param {THREE.SkinnedMesh} mesh + * @param {Array} grants + */ +class GrantSolver { + + constructor( mesh, grants = [] ) { + + this.mesh = mesh; + this.grants = grants; + + } + + /** + * Solve all the grant bones + * @return {GrantSolver} + */ + update() { + + const grants = this.grants; + + for ( let i = 0, il = grants.length; i < il; i ++ ) { + + this.updateOne( grants[ i ] ); + + } + + return this; + + } + + /** + * Solve a grant bone + * @param {Object} grant - grant parameter + * @return {GrantSolver} + */ + updateOne( grant ) { + + const bones = this.mesh.skeleton.bones; + const bone = bones[ grant.index ]; + const parentBone = bones[ grant.parentIndex ]; + + if ( grant.isLocal ) { + + // TODO: implement + if ( grant.affectPosition ) { + + } + + // TODO: implement + if ( grant.affectRotation ) { + + } + + } else { + + // TODO: implement + if ( grant.affectPosition ) { + + } + + if ( grant.affectRotation ) { + + this.addGrantRotation( bone, parentBone.quaternion, grant.ratio ); + + } + + } + + return this; + + } + + addGrantRotation( bone, q, ratio ) { + + _q.set( 0, 0, 0, 1 ); + _q.slerp( q, ratio ); + bone.quaternion.multiply( _q ); + + return this; + + } + +} + +export { MMDAnimationHelper }; diff --git a/ui/viewer/vendor/three/addons/animation/MMDPhysics.js b/ui/viewer/vendor/three/addons/animation/MMDPhysics.js new file mode 100644 index 0000000..0570901 --- /dev/null +++ b/ui/viewer/vendor/three/addons/animation/MMDPhysics.js @@ -0,0 +1,1406 @@ +import { + Bone, + BoxGeometry, + CapsuleGeometry, + Color, + Euler, + Matrix4, + Mesh, + MeshBasicMaterial, + Object3D, + Quaternion, + SphereGeometry, + Vector3 +} from 'three'; + +/** + * Dependencies + * - Ammo.js https://github.com/kripken/ammo.js + * + * MMDPhysics calculates physics with Ammo(Bullet based JavaScript Physics engine) + * for MMD model loaded by MMDLoader. + * + * TODO + * - Physics in Worker + */ + +/* global Ammo */ + +class MMDPhysics { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Array} rigidBodyParams + * @param {Array} (optional) constraintParams + * @param {Object} params - (optional) + * @param {Number} params.unitStep - Default is 1 / 65. + * @param {Integer} params.maxStepNum - Default is 3. + * @param {Vector3} params.gravity - Default is ( 0, - 9.8 * 10, 0 ) + */ + constructor( mesh, rigidBodyParams, constraintParams = [], params = {} ) { + + if ( typeof Ammo === 'undefined' ) { + + throw new Error( 'THREE.MMDPhysics: Import ammo.js https://github.com/kripken/ammo.js' ); + + } + + this.manager = new ResourceManager(); + + this.mesh = mesh; + + /* + * I don't know why but 1/60 unitStep easily breaks models + * so I set it 1/65 so far. + * Don't set too small unitStep because + * the smaller unitStep can make the performance worse. + */ + this.unitStep = ( params.unitStep !== undefined ) ? params.unitStep : 1 / 65; + this.maxStepNum = ( params.maxStepNum !== undefined ) ? params.maxStepNum : 3; + this.gravity = new Vector3( 0, - 9.8 * 10, 0 ); + + if ( params.gravity !== undefined ) this.gravity.copy( params.gravity ); + + this.world = params.world !== undefined ? params.world : null; // experimental + + this.bodies = []; + this.constraints = []; + + this._init( mesh, rigidBodyParams, constraintParams ); + + } + + /** + * Advances Physics calculation and updates bones. + * + * @param {Number} delta - time in second + * @return {MMDPhysics} + */ + update( delta ) { + + const manager = this.manager; + const mesh = this.mesh; + + // rigid bodies and constrains are for + // mesh's world scale (1, 1, 1). + // Convert to (1, 1, 1) if it isn't. + + let isNonDefaultScale = false; + + const position = manager.allocThreeVector3(); + const quaternion = manager.allocThreeQuaternion(); + const scale = manager.allocThreeVector3(); + + mesh.matrixWorld.decompose( position, quaternion, scale ); + + if ( scale.x !== 1 || scale.y !== 1 || scale.z !== 1 ) { + + isNonDefaultScale = true; + + } + + let parent; + + if ( isNonDefaultScale ) { + + parent = mesh.parent; + + if ( parent !== null ) mesh.parent = null; + + scale.copy( this.mesh.scale ); + + mesh.scale.set( 1, 1, 1 ); + mesh.updateMatrixWorld( true ); + + } + + // calculate physics and update bones + + this._updateRigidBodies(); + this._stepSimulation( delta ); + this._updateBones(); + + // restore mesh if converted above + + if ( isNonDefaultScale ) { + + if ( parent !== null ) mesh.parent = parent; + + mesh.scale.copy( scale ); + + } + + manager.freeThreeVector3( scale ); + manager.freeThreeQuaternion( quaternion ); + manager.freeThreeVector3( position ); + + return this; + + } + + /** + * Resets rigid bodies transorm to current bone's. + * + * @return {MMDPhysics} + */ + reset() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].reset(); + + } + + return this; + + } + + /** + * Warm ups Rigid bodies. Calculates cycles steps. + * + * @param {Integer} cycles + * @return {MMDPhysics} + */ + warmup( cycles ) { + + for ( let i = 0; i < cycles; i ++ ) { + + this.update( 1 / 60 ); + + } + + return this; + + } + + /** + * Sets gravity. + * + * @param {Vector3} gravity + * @return {MMDPhysicsHelper} + */ + setGravity( gravity ) { + + this.world.setGravity( new Ammo.btVector3( gravity.x, gravity.y, gravity.z ) ); + this.gravity.copy( gravity ); + + return this; + + } + + /** + * Creates MMDPhysicsHelper + * + * @return {MMDPhysicsHelper} + */ + createHelper() { + + return new MMDPhysicsHelper( this.mesh, this ); + + } + + // private methods + + _init( mesh, rigidBodyParams, constraintParams ) { + + const manager = this.manager; + + // rigid body/constraint parameters are for + // mesh's default world transform as position(0, 0, 0), + // quaternion(0, 0, 0, 1) and scale(0, 0, 0) + + const parent = mesh.parent; + + if ( parent !== null ) mesh.parent = null; + + const currentPosition = manager.allocThreeVector3(); + const currentQuaternion = manager.allocThreeQuaternion(); + const currentScale = manager.allocThreeVector3(); + + currentPosition.copy( mesh.position ); + currentQuaternion.copy( mesh.quaternion ); + currentScale.copy( mesh.scale ); + + mesh.position.set( 0, 0, 0 ); + mesh.quaternion.set( 0, 0, 0, 1 ); + mesh.scale.set( 1, 1, 1 ); + + mesh.updateMatrixWorld( true ); + + if ( this.world === null ) { + + this.world = this._createWorld(); + this.setGravity( this.gravity ); + + } + + this._initRigidBodies( rigidBodyParams ); + this._initConstraints( constraintParams ); + + if ( parent !== null ) mesh.parent = parent; + + mesh.position.copy( currentPosition ); + mesh.quaternion.copy( currentQuaternion ); + mesh.scale.copy( currentScale ); + + mesh.updateMatrixWorld( true ); + + this.reset(); + + manager.freeThreeVector3( currentPosition ); + manager.freeThreeQuaternion( currentQuaternion ); + manager.freeThreeVector3( currentScale ); + + } + + _createWorld() { + + const config = new Ammo.btDefaultCollisionConfiguration(); + const dispatcher = new Ammo.btCollisionDispatcher( config ); + const cache = new Ammo.btDbvtBroadphase(); + const solver = new Ammo.btSequentialImpulseConstraintSolver(); + const world = new Ammo.btDiscreteDynamicsWorld( dispatcher, cache, solver, config ); + return world; + + } + + _initRigidBodies( rigidBodies ) { + + for ( let i = 0, il = rigidBodies.length; i < il; i ++ ) { + + this.bodies.push( new RigidBody( + this.mesh, this.world, rigidBodies[ i ], this.manager ) ); + + } + + } + + _initConstraints( constraints ) { + + for ( let i = 0, il = constraints.length; i < il; i ++ ) { + + const params = constraints[ i ]; + const bodyA = this.bodies[ params.rigidBodyIndex1 ]; + const bodyB = this.bodies[ params.rigidBodyIndex2 ]; + this.constraints.push( new Constraint( this.mesh, this.world, bodyA, bodyB, params, this.manager ) ); + + } + + } + + _stepSimulation( delta ) { + + const unitStep = this.unitStep; + let stepTime = delta; + let maxStepNum = ( ( delta / unitStep ) | 0 ) + 1; + + if ( stepTime < unitStep ) { + + stepTime = unitStep; + maxStepNum = 1; + + } + + if ( maxStepNum > this.maxStepNum ) { + + maxStepNum = this.maxStepNum; + + } + + this.world.stepSimulation( stepTime, maxStepNum, unitStep ); + + } + + _updateRigidBodies() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].updateFromBone(); + + } + + } + + _updateBones() { + + for ( let i = 0, il = this.bodies.length; i < il; i ++ ) { + + this.bodies[ i ].updateBone(); + + } + + } + +} + +/** + * This manager's responsibilies are + * + * 1. manage Ammo.js and Three.js object resources and + * improve the performance and the memory consumption by + * reusing objects. + * + * 2. provide simple Ammo object operations. + */ +class ResourceManager { + + constructor() { + + // for Three.js + this.threeVector3s = []; + this.threeMatrix4s = []; + this.threeQuaternions = []; + this.threeEulers = []; + + // for Ammo.js + this.transforms = []; + this.quaternions = []; + this.vector3s = []; + + } + + allocThreeVector3() { + + return ( this.threeVector3s.length > 0 ) + ? this.threeVector3s.pop() + : new Vector3(); + + } + + freeThreeVector3( v ) { + + this.threeVector3s.push( v ); + + } + + allocThreeMatrix4() { + + return ( this.threeMatrix4s.length > 0 ) + ? this.threeMatrix4s.pop() + : new Matrix4(); + + } + + freeThreeMatrix4( m ) { + + this.threeMatrix4s.push( m ); + + } + + allocThreeQuaternion() { + + return ( this.threeQuaternions.length > 0 ) + ? this.threeQuaternions.pop() + : new Quaternion(); + + } + + freeThreeQuaternion( q ) { + + this.threeQuaternions.push( q ); + + } + + allocThreeEuler() { + + return ( this.threeEulers.length > 0 ) + ? this.threeEulers.pop() + : new Euler(); + + } + + freeThreeEuler( e ) { + + this.threeEulers.push( e ); + + } + + allocTransform() { + + return ( this.transforms.length > 0 ) + ? this.transforms.pop() + : new Ammo.btTransform(); + + } + + freeTransform( t ) { + + this.transforms.push( t ); + + } + + allocQuaternion() { + + return ( this.quaternions.length > 0 ) + ? this.quaternions.pop() + : new Ammo.btQuaternion(); + + } + + freeQuaternion( q ) { + + this.quaternions.push( q ); + + } + + allocVector3() { + + return ( this.vector3s.length > 0 ) + ? this.vector3s.pop() + : new Ammo.btVector3(); + + } + + freeVector3( v ) { + + this.vector3s.push( v ); + + } + + setIdentity( t ) { + + t.setIdentity(); + + } + + getBasis( t ) { + + var q = this.allocQuaternion(); + t.getBasis().getRotation( q ); + return q; + + } + + getBasisAsMatrix3( t ) { + + var q = this.getBasis( t ); + var m = this.quaternionToMatrix3( q ); + this.freeQuaternion( q ); + return m; + + } + + getOrigin( t ) { + + return t.getOrigin(); + + } + + setOrigin( t, v ) { + + t.getOrigin().setValue( v.x(), v.y(), v.z() ); + + } + + copyOrigin( t1, t2 ) { + + var o = t2.getOrigin(); + this.setOrigin( t1, o ); + + } + + setBasis( t, q ) { + + t.setRotation( q ); + + } + + setBasisFromMatrix3( t, m ) { + + var q = this.matrix3ToQuaternion( m ); + this.setBasis( t, q ); + this.freeQuaternion( q ); + + } + + setOriginFromArray3( t, a ) { + + t.getOrigin().setValue( a[ 0 ], a[ 1 ], a[ 2 ] ); + + } + + setOriginFromThreeVector3( t, v ) { + + t.getOrigin().setValue( v.x, v.y, v.z ); + + } + + setBasisFromArray3( t, a ) { + + var thQ = this.allocThreeQuaternion(); + var thE = this.allocThreeEuler(); + thE.set( a[ 0 ], a[ 1 ], a[ 2 ] ); + this.setBasisFromThreeQuaternion( t, thQ.setFromEuler( thE ) ); + + this.freeThreeEuler( thE ); + this.freeThreeQuaternion( thQ ); + + } + + setBasisFromThreeQuaternion( t, a ) { + + var q = this.allocQuaternion(); + + q.setX( a.x ); + q.setY( a.y ); + q.setZ( a.z ); + q.setW( a.w ); + this.setBasis( t, q ); + + this.freeQuaternion( q ); + + } + + multiplyTransforms( t1, t2 ) { + + var t = this.allocTransform(); + this.setIdentity( t ); + + var m1 = this.getBasisAsMatrix3( t1 ); + var m2 = this.getBasisAsMatrix3( t2 ); + + var o1 = this.getOrigin( t1 ); + var o2 = this.getOrigin( t2 ); + + var v1 = this.multiplyMatrix3ByVector3( m1, o2 ); + var v2 = this.addVector3( v1, o1 ); + this.setOrigin( t, v2 ); + + var m3 = this.multiplyMatrices3( m1, m2 ); + this.setBasisFromMatrix3( t, m3 ); + + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return t; + + } + + inverseTransform( t ) { + + var t2 = this.allocTransform(); + + var m1 = this.getBasisAsMatrix3( t ); + var o = this.getOrigin( t ); + + var m2 = this.transposeMatrix3( m1 ); + var v1 = this.negativeVector3( o ); + var v2 = this.multiplyMatrix3ByVector3( m2, v1 ); + + this.setOrigin( t2, v2 ); + this.setBasisFromMatrix3( t2, m2 ); + + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return t2; + + } + + multiplyMatrices3( m1, m2 ) { + + var m3 = []; + + var v10 = this.rowOfMatrix3( m1, 0 ); + var v11 = this.rowOfMatrix3( m1, 1 ); + var v12 = this.rowOfMatrix3( m1, 2 ); + + var v20 = this.columnOfMatrix3( m2, 0 ); + var v21 = this.columnOfMatrix3( m2, 1 ); + var v22 = this.columnOfMatrix3( m2, 2 ); + + m3[ 0 ] = this.dotVectors3( v10, v20 ); + m3[ 1 ] = this.dotVectors3( v10, v21 ); + m3[ 2 ] = this.dotVectors3( v10, v22 ); + m3[ 3 ] = this.dotVectors3( v11, v20 ); + m3[ 4 ] = this.dotVectors3( v11, v21 ); + m3[ 5 ] = this.dotVectors3( v11, v22 ); + m3[ 6 ] = this.dotVectors3( v12, v20 ); + m3[ 7 ] = this.dotVectors3( v12, v21 ); + m3[ 8 ] = this.dotVectors3( v12, v22 ); + + this.freeVector3( v10 ); + this.freeVector3( v11 ); + this.freeVector3( v12 ); + this.freeVector3( v20 ); + this.freeVector3( v21 ); + this.freeVector3( v22 ); + + return m3; + + } + + addVector3( v1, v2 ) { + + var v = this.allocVector3(); + v.setValue( v1.x() + v2.x(), v1.y() + v2.y(), v1.z() + v2.z() ); + return v; + + } + + dotVectors3( v1, v2 ) { + + return v1.x() * v2.x() + v1.y() * v2.y() + v1.z() * v2.z(); + + } + + rowOfMatrix3( m, i ) { + + var v = this.allocVector3(); + v.setValue( m[ i * 3 + 0 ], m[ i * 3 + 1 ], m[ i * 3 + 2 ] ); + return v; + + } + + columnOfMatrix3( m, i ) { + + var v = this.allocVector3(); + v.setValue( m[ i + 0 ], m[ i + 3 ], m[ i + 6 ] ); + return v; + + } + + negativeVector3( v ) { + + var v2 = this.allocVector3(); + v2.setValue( - v.x(), - v.y(), - v.z() ); + return v2; + + } + + multiplyMatrix3ByVector3( m, v ) { + + var v4 = this.allocVector3(); + + var v0 = this.rowOfMatrix3( m, 0 ); + var v1 = this.rowOfMatrix3( m, 1 ); + var v2 = this.rowOfMatrix3( m, 2 ); + var x = this.dotVectors3( v0, v ); + var y = this.dotVectors3( v1, v ); + var z = this.dotVectors3( v2, v ); + + v4.setValue( x, y, z ); + + this.freeVector3( v0 ); + this.freeVector3( v1 ); + this.freeVector3( v2 ); + + return v4; + + } + + transposeMatrix3( m ) { + + var m2 = []; + m2[ 0 ] = m[ 0 ]; + m2[ 1 ] = m[ 3 ]; + m2[ 2 ] = m[ 6 ]; + m2[ 3 ] = m[ 1 ]; + m2[ 4 ] = m[ 4 ]; + m2[ 5 ] = m[ 7 ]; + m2[ 6 ] = m[ 2 ]; + m2[ 7 ] = m[ 5 ]; + m2[ 8 ] = m[ 8 ]; + return m2; + + } + + quaternionToMatrix3( q ) { + + var m = []; + + var x = q.x(); + var y = q.y(); + var z = q.z(); + var w = q.w(); + + var xx = x * x; + var yy = y * y; + var zz = z * z; + + var xy = x * y; + var yz = y * z; + var zx = z * x; + + var xw = x * w; + var yw = y * w; + var zw = z * w; + + m[ 0 ] = 1 - 2 * ( yy + zz ); + m[ 1 ] = 2 * ( xy - zw ); + m[ 2 ] = 2 * ( zx + yw ); + m[ 3 ] = 2 * ( xy + zw ); + m[ 4 ] = 1 - 2 * ( zz + xx ); + m[ 5 ] = 2 * ( yz - xw ); + m[ 6 ] = 2 * ( zx - yw ); + m[ 7 ] = 2 * ( yz + xw ); + m[ 8 ] = 1 - 2 * ( xx + yy ); + + return m; + + } + + matrix3ToQuaternion( m ) { + + var t = m[ 0 ] + m[ 4 ] + m[ 8 ]; + var s, x, y, z, w; + + if ( t > 0 ) { + + s = Math.sqrt( t + 1.0 ) * 2; + w = 0.25 * s; + x = ( m[ 7 ] - m[ 5 ] ) / s; + y = ( m[ 2 ] - m[ 6 ] ) / s; + z = ( m[ 3 ] - m[ 1 ] ) / s; + + } else if ( ( m[ 0 ] > m[ 4 ] ) && ( m[ 0 ] > m[ 8 ] ) ) { + + s = Math.sqrt( 1.0 + m[ 0 ] - m[ 4 ] - m[ 8 ] ) * 2; + w = ( m[ 7 ] - m[ 5 ] ) / s; + x = 0.25 * s; + y = ( m[ 1 ] + m[ 3 ] ) / s; + z = ( m[ 2 ] + m[ 6 ] ) / s; + + } else if ( m[ 4 ] > m[ 8 ] ) { + + s = Math.sqrt( 1.0 + m[ 4 ] - m[ 0 ] - m[ 8 ] ) * 2; + w = ( m[ 2 ] - m[ 6 ] ) / s; + x = ( m[ 1 ] + m[ 3 ] ) / s; + y = 0.25 * s; + z = ( m[ 5 ] + m[ 7 ] ) / s; + + } else { + + s = Math.sqrt( 1.0 + m[ 8 ] - m[ 0 ] - m[ 4 ] ) * 2; + w = ( m[ 3 ] - m[ 1 ] ) / s; + x = ( m[ 2 ] + m[ 6 ] ) / s; + y = ( m[ 5 ] + m[ 7 ] ) / s; + z = 0.25 * s; + + } + + var q = this.allocQuaternion(); + q.setX( x ); + q.setY( y ); + q.setZ( z ); + q.setW( w ); + return q; + + } + +} + +/** + * @param {THREE.SkinnedMesh} mesh + * @param {Ammo.btDiscreteDynamicsWorld} world + * @param {Object} params + * @param {ResourceManager} manager + */ +class RigidBody { + + constructor( mesh, world, params, manager ) { + + this.mesh = mesh; + this.world = world; + this.params = params; + this.manager = manager; + + this.body = null; + this.bone = null; + this.boneOffsetForm = null; + this.boneOffsetFormInverse = null; + + this._init(); + + } + + /** + * Resets rigid body transform to the current bone's. + * + * @return {RigidBody} + */ + reset() { + + this._setTransformFromBone(); + return this; + + } + + /** + * Updates rigid body's transform from the current bone. + * + * @return {RidigBody} + */ + updateFromBone() { + + if ( this.params.boneIndex !== - 1 && this.params.type === 0 ) { + + this._setTransformFromBone(); + + } + + return this; + + } + + /** + * Updates bone from the current ridid body's transform. + * + * @return {RidigBody} + */ + updateBone() { + + if ( this.params.type === 0 || this.params.boneIndex === - 1 ) { + + return this; + + } + + this._updateBoneRotation(); + + if ( this.params.type === 1 ) { + + this._updateBonePosition(); + + } + + this.bone.updateMatrixWorld( true ); + + if ( this.params.type === 2 ) { + + this._setPositionFromBone(); + + } + + return this; + + } + + // private methods + + _init() { + + function generateShape( p ) { + + switch ( p.shapeType ) { + + case 0: + return new Ammo.btSphereShape( p.width ); + + case 1: + return new Ammo.btBoxShape( new Ammo.btVector3( p.width, p.height, p.depth ) ); + + case 2: + return new Ammo.btCapsuleShape( p.width, p.height ); + + default: + throw new Error( 'unknown shape type ' + p.shapeType ); + + } + + } + + const manager = this.manager; + const params = this.params; + const bones = this.mesh.skeleton.bones; + const bone = ( params.boneIndex === - 1 ) + ? new Bone() + : bones[ params.boneIndex ]; + + const shape = generateShape( params ); + const weight = ( params.type === 0 ) ? 0 : params.weight; + const localInertia = manager.allocVector3(); + localInertia.setValue( 0, 0, 0 ); + + if ( weight !== 0 ) { + + shape.calculateLocalInertia( weight, localInertia ); + + } + + const boneOffsetForm = manager.allocTransform(); + manager.setIdentity( boneOffsetForm ); + manager.setOriginFromArray3( boneOffsetForm, params.position ); + manager.setBasisFromArray3( boneOffsetForm, params.rotation ); + + const vector = manager.allocThreeVector3(); + const boneForm = manager.allocTransform(); + manager.setIdentity( boneForm ); + manager.setOriginFromThreeVector3( boneForm, bone.getWorldPosition( vector ) ); + + const form = manager.multiplyTransforms( boneForm, boneOffsetForm ); + const state = new Ammo.btDefaultMotionState( form ); + + const info = new Ammo.btRigidBodyConstructionInfo( weight, state, shape, localInertia ); + info.set_m_friction( params.friction ); + info.set_m_restitution( params.restitution ); + + const body = new Ammo.btRigidBody( info ); + + if ( params.type === 0 ) { + + body.setCollisionFlags( body.getCollisionFlags() | 2 ); + + /* + * It'd be better to comment out this line though in general I should call this method + * because I'm not sure why but physics will be more like MMD's + * if I comment out. + */ + body.setActivationState( 4 ); + + } + + body.setDamping( params.positionDamping, params.rotationDamping ); + body.setSleepingThresholds( 0, 0 ); + + this.world.addRigidBody( body, 1 << params.groupIndex, params.groupTarget ); + + this.body = body; + this.bone = bone; + this.boneOffsetForm = boneOffsetForm; + this.boneOffsetFormInverse = manager.inverseTransform( boneOffsetForm ); + + manager.freeVector3( localInertia ); + manager.freeTransform( form ); + manager.freeTransform( boneForm ); + manager.freeThreeVector3( vector ); + + } + + _getBoneTransform() { + + const manager = this.manager; + const p = manager.allocThreeVector3(); + const q = manager.allocThreeQuaternion(); + const s = manager.allocThreeVector3(); + + this.bone.matrixWorld.decompose( p, q, s ); + + const tr = manager.allocTransform(); + manager.setOriginFromThreeVector3( tr, p ); + manager.setBasisFromThreeQuaternion( tr, q ); + + const form = manager.multiplyTransforms( tr, this.boneOffsetForm ); + + manager.freeTransform( tr ); + manager.freeThreeVector3( s ); + manager.freeThreeQuaternion( q ); + manager.freeThreeVector3( p ); + + return form; + + } + + _getWorldTransformForBone() { + + const manager = this.manager; + const tr = this.body.getCenterOfMassTransform(); + return manager.multiplyTransforms( tr, this.boneOffsetFormInverse ); + + } + + _setTransformFromBone() { + + const manager = this.manager; + const form = this._getBoneTransform(); + + // TODO: check the most appropriate way to set + //this.body.setWorldTransform( form ); + this.body.setCenterOfMassTransform( form ); + this.body.getMotionState().setWorldTransform( form ); + + manager.freeTransform( form ); + + } + + _setPositionFromBone() { + + const manager = this.manager; + const form = this._getBoneTransform(); + + const tr = manager.allocTransform(); + this.body.getMotionState().getWorldTransform( tr ); + manager.copyOrigin( tr, form ); + + // TODO: check the most appropriate way to set + //this.body.setWorldTransform( tr ); + this.body.setCenterOfMassTransform( tr ); + this.body.getMotionState().setWorldTransform( tr ); + + manager.freeTransform( tr ); + manager.freeTransform( form ); + + } + + _updateBoneRotation() { + + const manager = this.manager; + + const tr = this._getWorldTransformForBone(); + const q = manager.getBasis( tr ); + + const thQ = manager.allocThreeQuaternion(); + const thQ2 = manager.allocThreeQuaternion(); + const thQ3 = manager.allocThreeQuaternion(); + + thQ.set( q.x(), q.y(), q.z(), q.w() ); + thQ2.setFromRotationMatrix( this.bone.matrixWorld ); + thQ2.conjugate(); + thQ2.multiply( thQ ); + + //this.bone.quaternion.multiply( thQ2 ); + + thQ3.setFromRotationMatrix( this.bone.matrix ); + + // Renormalizing quaternion here because repeatedly transforming + // quaternion continuously accumulates floating point error and + // can end up being overflow. See #15335 + this.bone.quaternion.copy( thQ2.multiply( thQ3 ).normalize() ); + + manager.freeThreeQuaternion( thQ ); + manager.freeThreeQuaternion( thQ2 ); + manager.freeThreeQuaternion( thQ3 ); + + manager.freeQuaternion( q ); + manager.freeTransform( tr ); + + } + + _updateBonePosition() { + + const manager = this.manager; + + const tr = this._getWorldTransformForBone(); + + const thV = manager.allocThreeVector3(); + + const o = manager.getOrigin( tr ); + thV.set( o.x(), o.y(), o.z() ); + + if ( this.bone.parent ) { + + this.bone.parent.worldToLocal( thV ); + + } + + this.bone.position.copy( thV ); + + manager.freeThreeVector3( thV ); + + manager.freeTransform( tr ); + + } + +} + +// + +class Constraint { + + /** + * @param {THREE.SkinnedMesh} mesh + * @param {Ammo.btDiscreteDynamicsWorld} world + * @param {RigidBody} bodyA + * @param {RigidBody} bodyB + * @param {Object} params + * @param {ResourceManager} manager + */ + constructor( mesh, world, bodyA, bodyB, params, manager ) { + + this.mesh = mesh; + this.world = world; + this.bodyA = bodyA; + this.bodyB = bodyB; + this.params = params; + this.manager = manager; + + this.constraint = null; + + this._init(); + + } + + // private method + + _init() { + + const manager = this.manager; + const params = this.params; + const bodyA = this.bodyA; + const bodyB = this.bodyB; + + const form = manager.allocTransform(); + manager.setIdentity( form ); + manager.setOriginFromArray3( form, params.position ); + manager.setBasisFromArray3( form, params.rotation ); + + const formA = manager.allocTransform(); + const formB = manager.allocTransform(); + + bodyA.body.getMotionState().getWorldTransform( formA ); + bodyB.body.getMotionState().getWorldTransform( formB ); + + const formInverseA = manager.inverseTransform( formA ); + const formInverseB = manager.inverseTransform( formB ); + + const formA2 = manager.multiplyTransforms( formInverseA, form ); + const formB2 = manager.multiplyTransforms( formInverseB, form ); + + const constraint = new Ammo.btGeneric6DofSpringConstraint( bodyA.body, bodyB.body, formA2, formB2, true ); + + const lll = manager.allocVector3(); + const lul = manager.allocVector3(); + const all = manager.allocVector3(); + const aul = manager.allocVector3(); + + lll.setValue( params.translationLimitation1[ 0 ], + params.translationLimitation1[ 1 ], + params.translationLimitation1[ 2 ] ); + lul.setValue( params.translationLimitation2[ 0 ], + params.translationLimitation2[ 1 ], + params.translationLimitation2[ 2 ] ); + all.setValue( params.rotationLimitation1[ 0 ], + params.rotationLimitation1[ 1 ], + params.rotationLimitation1[ 2 ] ); + aul.setValue( params.rotationLimitation2[ 0 ], + params.rotationLimitation2[ 1 ], + params.rotationLimitation2[ 2 ] ); + + constraint.setLinearLowerLimit( lll ); + constraint.setLinearUpperLimit( lul ); + constraint.setAngularLowerLimit( all ); + constraint.setAngularUpperLimit( aul ); + + for ( let i = 0; i < 3; i ++ ) { + + if ( params.springPosition[ i ] !== 0 ) { + + constraint.enableSpring( i, true ); + constraint.setStiffness( i, params.springPosition[ i ] ); + + } + + } + + for ( let i = 0; i < 3; i ++ ) { + + if ( params.springRotation[ i ] !== 0 ) { + + constraint.enableSpring( i + 3, true ); + constraint.setStiffness( i + 3, params.springRotation[ i ] ); + + } + + } + + /* + * Currently(10/31/2016) official ammo.js doesn't support + * btGeneric6DofSpringConstraint.setParam method. + * You need custom ammo.js (add the method into idl) if you wanna use. + * By setting this parameter, physics will be more like MMD's + */ + if ( constraint.setParam !== undefined ) { + + for ( let i = 0; i < 6; i ++ ) { + + constraint.setParam( 2, 0.475, i ); + + } + + } + + this.world.addConstraint( constraint, true ); + this.constraint = constraint; + + manager.freeTransform( form ); + manager.freeTransform( formA ); + manager.freeTransform( formB ); + manager.freeTransform( formInverseA ); + manager.freeTransform( formInverseB ); + manager.freeTransform( formA2 ); + manager.freeTransform( formB2 ); + manager.freeVector3( lll ); + manager.freeVector3( lul ); + manager.freeVector3( all ); + manager.freeVector3( aul ); + + } + +} + +// + +const _position = new Vector3(); +const _quaternion = new Quaternion(); +const _scale = new Vector3(); +const _matrixWorldInv = new Matrix4(); + +class MMDPhysicsHelper extends Object3D { + + /** + * Visualize Rigid bodies + * + * @param {THREE.SkinnedMesh} mesh + * @param {Physics} physics + */ + constructor( mesh, physics ) { + + super(); + + this.root = mesh; + this.physics = physics; + + this.matrix.copy( mesh.matrixWorld ); + this.matrixAutoUpdate = false; + + this.materials = []; + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0xff8888 ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0x88ff88 ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this.materials.push( + new MeshBasicMaterial( { + color: new Color( 0x8888ff ), + wireframe: true, + depthTest: false, + depthWrite: false, + opacity: 0.25, + transparent: true + } ) + ); + + this._init(); + + } + + + /** + * Frees the GPU-related resources allocated by this instance. Call this method whenever this instance is no longer used in your app. + */ + dispose() { + + const materials = this.materials; + const children = this.children; + + for ( let i = 0; i < materials.length; i ++ ) { + + materials[ i ].dispose(); + + } + + for ( let i = 0; i < children.length; i ++ ) { + + const child = children[ i ]; + + if ( child.isMesh ) child.geometry.dispose(); + + } + + } + + /** + * Updates Rigid Bodies visualization. + */ + updateMatrixWorld( force ) { + + var mesh = this.root; + + if ( this.visible ) { + + var bodies = this.physics.bodies; + + _matrixWorldInv + .copy( mesh.matrixWorld ) + .decompose( _position, _quaternion, _scale ) + .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) ) + .invert(); + + for ( var i = 0, il = bodies.length; i < il; i ++ ) { + + var body = bodies[ i ].body; + var child = this.children[ i ]; + + var tr = body.getCenterOfMassTransform(); + var origin = tr.getOrigin(); + var rotation = tr.getRotation(); + + child.position + .set( origin.x(), origin.y(), origin.z() ) + .applyMatrix4( _matrixWorldInv ); + + child.quaternion + .setFromRotationMatrix( _matrixWorldInv ) + .multiply( + _quaternion.set( rotation.x(), rotation.y(), rotation.z(), rotation.w() ) + ); + + } + + } + + this.matrix + .copy( mesh.matrixWorld ) + .decompose( _position, _quaternion, _scale ) + .compose( _position, _quaternion, _scale.set( 1, 1, 1 ) ); + + super.updateMatrixWorld( force ); + + } + + // private method + + _init() { + + var bodies = this.physics.bodies; + + function createGeometry( param ) { + + switch ( param.shapeType ) { + + case 0: + return new SphereGeometry( param.width, 16, 8 ); + + case 1: + return new BoxGeometry( param.width * 2, param.height * 2, param.depth * 2, 8, 8, 8 ); + + case 2: + return new CapsuleGeometry( param.width, param.height, 8, 16 ); + + default: + return null; + + } + + } + + for ( var i = 0, il = bodies.length; i < il; i ++ ) { + + var param = bodies[ i ].params; + this.add( new Mesh( createGeometry( param ), this.materials[ param.type ] ) ); + + } + + } + +} + +export { MMDPhysics }; diff --git a/ui/viewer/vendor/three/addons/controls/OrbitControls.js b/ui/viewer/vendor/three/addons/controls/OrbitControls.js new file mode 100644 index 0000000..7360aab --- /dev/null +++ b/ui/viewer/vendor/three/addons/controls/OrbitControls.js @@ -0,0 +1,1523 @@ +import { + Controls, + MOUSE, + Quaternion, + Spherical, + TOUCH, + Vector2, + Vector3, + Plane, + Ray, + MathUtils +} from 'three'; + +// OrbitControls performs orbiting, dollying (zooming), and panning. +// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default). +// +// Orbit - left mouse / touch: one-finger move +// Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish +// Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move + +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; +const _ray = new Ray(); +const _plane = new Plane(); +const _TILT_LIMIT = Math.cos( 70 * MathUtils.DEG2RAD ); + +const _v = new Vector3(); +const _twoPI = 2 * Math.PI; + +const _STATE = { + NONE: - 1, + ROTATE: 0, + DOLLY: 1, + PAN: 2, + TOUCH_ROTATE: 3, + TOUCH_PAN: 4, + TOUCH_DOLLY_PAN: 5, + TOUCH_DOLLY_ROTATE: 6 +}; +const _EPS = 0.000001; + +class OrbitControls extends Controls { + + constructor( object, domElement = null ) { + + super( object, domElement ); + + this.state = _STATE.NONE; + + // Set to false to disable this control + this.enabled = true; + + // "target" sets the location of focus, where the object orbits around + this.target = new Vector3(); + + // Sets the 3D cursor (similar to Blender), from which the maxTargetRadius takes effect + this.cursor = new Vector3(); + + // How far you can dolly in and out ( PerspectiveCamera only ) + this.minDistance = 0; + this.maxDistance = Infinity; + + // How far you can zoom in and out ( OrthographicCamera only ) + this.minZoom = 0; + this.maxZoom = Infinity; + + // Limit camera target within a spherical area around the cursor + this.minTargetRadius = 0; + this.maxTargetRadius = Infinity; + + // How far you can orbit vertically, upper and lower limits. + // Range is 0 to Math.PI radians. + this.minPolarAngle = 0; // radians + this.maxPolarAngle = Math.PI; // radians + + // How far you can orbit horizontally, upper and lower limits. + // If set, the interval [ min, max ] must be a sub-interval of [ - 2 PI, 2 PI ], with ( max - min < 2 PI ) + this.minAzimuthAngle = - Infinity; // radians + this.maxAzimuthAngle = Infinity; // radians + + // Set to true to enable damping (inertia) + // If damping is enabled, you must call controls.update() in your animation loop + this.enableDamping = false; + this.dampingFactor = 0.05; + + // This option actually enables dollying in and out; left as "zoom" for backwards compatibility. + // Set to false to disable zooming + this.enableZoom = true; + this.zoomSpeed = 1.0; + + // Set to false to disable rotating + this.enableRotate = true; + this.rotateSpeed = 1.0; + + // Set to false to disable panning + this.enablePan = true; + this.panSpeed = 1.0; + this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up + this.keyPanSpeed = 7.0; // pixels moved per arrow key push + this.zoomToCursor = false; + + // Set to true to automatically rotate around the target + // If auto-rotate is enabled, you must call controls.update() in your animation loop + this.autoRotate = false; + this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60 + + // The four arrow keys + this.keys = { LEFT: 'ArrowLeft', UP: 'ArrowUp', RIGHT: 'ArrowRight', BOTTOM: 'ArrowDown' }; + + // Mouse buttons + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + // Touch fingers + this.touches = { ONE: TOUCH.ROTATE, TWO: TOUCH.DOLLY_PAN }; + + // for reset + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.zoom0 = this.object.zoom; + + // the target DOM element for key events + this._domElementKeyEvents = null; + + // internals + + this._lastPosition = new Vector3(); + this._lastQuaternion = new Quaternion(); + this._lastTargetPosition = new Vector3(); + + // so camera.up is the orbit axis + this._quat = new Quaternion().setFromUnitVectors( object.up, new Vector3( 0, 1, 0 ) ); + this._quatInverse = this._quat.clone().invert(); + + // current position in spherical coordinates + this._spherical = new Spherical(); + this._sphericalDelta = new Spherical(); + + this._scale = 1; + this._panOffset = new Vector3(); + + this._rotateStart = new Vector2(); + this._rotateEnd = new Vector2(); + this._rotateDelta = new Vector2(); + + this._panStart = new Vector2(); + this._panEnd = new Vector2(); + this._panDelta = new Vector2(); + + this._dollyStart = new Vector2(); + this._dollyEnd = new Vector2(); + this._dollyDelta = new Vector2(); + + this._dollyDirection = new Vector3(); + this._mouse = new Vector2(); + this._performCursorZoom = false; + + this._pointers = []; + this._pointerPositions = {}; + + this._controlActive = false; + + // event listeners + + this._onPointerMove = onPointerMove.bind( this ); + this._onPointerDown = onPointerDown.bind( this ); + this._onPointerUp = onPointerUp.bind( this ); + this._onContextMenu = onContextMenu.bind( this ); + this._onMouseWheel = onMouseWheel.bind( this ); + this._onKeyDown = onKeyDown.bind( this ); + + this._onTouchStart = onTouchStart.bind( this ); + this._onTouchMove = onTouchMove.bind( this ); + + this._onMouseDown = onMouseDown.bind( this ); + this._onMouseMove = onMouseMove.bind( this ); + + this._interceptControlDown = interceptControlDown.bind( this ); + this._interceptControlUp = interceptControlUp.bind( this ); + + // + + if ( this.domElement !== null ) { + + this.connect(); + + } + + this.update(); + + } + + connect() { + + this.domElement.addEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.addEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.addEventListener( 'contextmenu', this._onContextMenu ); + this.domElement.addEventListener( 'wheel', this._onMouseWheel, { passive: false } ); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.addEventListener( 'keydown', this._interceptControlDown, { passive: true, capture: true } ); + + this.domElement.style.touchAction = 'none'; // disable touch scroll + + } + + disconnect() { + + this.domElement.removeEventListener( 'pointerdown', this._onPointerDown ); + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + this.domElement.removeEventListener( 'pointercancel', this._onPointerUp ); + + this.domElement.removeEventListener( 'wheel', this._onMouseWheel ); + this.domElement.removeEventListener( 'contextmenu', this._onContextMenu ); + + this.stopListenToKeyEvents(); + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + document.removeEventListener( 'keydown', this._interceptControlDown, { capture: true } ); + + this.domElement.style.touchAction = 'auto'; + + } + + dispose() { + + this.disconnect(); + + } + + getPolarAngle() { + + return this._spherical.phi; + + } + + getAzimuthalAngle() { + + return this._spherical.theta; + + } + + getDistance() { + + return this.object.position.distanceTo( this.target ); + + } + + listenToKeyEvents( domElement ) { + + domElement.addEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = domElement; + + } + + stopListenToKeyEvents() { + + if ( this._domElementKeyEvents !== null ) { + + this._domElementKeyEvents.removeEventListener( 'keydown', this._onKeyDown ); + this._domElementKeyEvents = null; + + } + + } + + saveState() { + + this.target0.copy( this.target ); + this.position0.copy( this.object.position ); + this.zoom0 = this.object.zoom; + + } + + reset() { + + this.target.copy( this.target0 ); + this.object.position.copy( this.position0 ); + this.object.zoom = this.zoom0; + + this.object.updateProjectionMatrix(); + this.dispatchEvent( _changeEvent ); + + this.update(); + + this.state = _STATE.NONE; + + } + + update( deltaTime = null ) { + + const position = this.object.position; + + _v.copy( position ).sub( this.target ); + + // rotate offset to "y-axis-is-up" space + _v.applyQuaternion( this._quat ); + + // angle from z-axis around y-axis + this._spherical.setFromVector3( _v ); + + if ( this.autoRotate && this.state === _STATE.NONE ) { + + this._rotateLeft( this._getAutoRotationAngle( deltaTime ) ); + + } + + if ( this.enableDamping ) { + + this._spherical.theta += this._sphericalDelta.theta * this.dampingFactor; + this._spherical.phi += this._sphericalDelta.phi * this.dampingFactor; + + } else { + + this._spherical.theta += this._sphericalDelta.theta; + this._spherical.phi += this._sphericalDelta.phi; + + } + + // restrict theta to be between desired limits + + let min = this.minAzimuthAngle; + let max = this.maxAzimuthAngle; + + if ( isFinite( min ) && isFinite( max ) ) { + + if ( min < - Math.PI ) min += _twoPI; else if ( min > Math.PI ) min -= _twoPI; + + if ( max < - Math.PI ) max += _twoPI; else if ( max > Math.PI ) max -= _twoPI; + + if ( min <= max ) { + + this._spherical.theta = Math.max( min, Math.min( max, this._spherical.theta ) ); + + } else { + + this._spherical.theta = ( this._spherical.theta > ( min + max ) / 2 ) ? + Math.max( min, this._spherical.theta ) : + Math.min( max, this._spherical.theta ); + + } + + } + + // restrict phi to be between desired limits + this._spherical.phi = Math.max( this.minPolarAngle, Math.min( this.maxPolarAngle, this._spherical.phi ) ); + + this._spherical.makeSafe(); + + + // move target to panned location + + if ( this.enableDamping === true ) { + + this.target.addScaledVector( this._panOffset, this.dampingFactor ); + + } else { + + this.target.add( this._panOffset ); + + } + + // Limit the target distance from the cursor to create a sphere around the center of interest + this.target.sub( this.cursor ); + this.target.clampLength( this.minTargetRadius, this.maxTargetRadius ); + this.target.add( this.cursor ); + + let zoomChanged = false; + // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera + // we adjust zoom later in these cases + if ( this.zoomToCursor && this._performCursorZoom || this.object.isOrthographicCamera ) { + + this._spherical.radius = this._clampDistance( this._spherical.radius ); + + } else { + + const prevRadius = this._spherical.radius; + this._spherical.radius = this._clampDistance( this._spherical.radius * this._scale ); + zoomChanged = prevRadius != this._spherical.radius; + + } + + _v.setFromSpherical( this._spherical ); + + // rotate offset back to "camera-up-vector-is-up" space + _v.applyQuaternion( this._quatInverse ); + + position.copy( this.target ).add( _v ); + + this.object.lookAt( this.target ); + + if ( this.enableDamping === true ) { + + this._sphericalDelta.theta *= ( 1 - this.dampingFactor ); + this._sphericalDelta.phi *= ( 1 - this.dampingFactor ); + + this._panOffset.multiplyScalar( 1 - this.dampingFactor ); + + } else { + + this._sphericalDelta.set( 0, 0, 0 ); + + this._panOffset.set( 0, 0, 0 ); + + } + + // adjust camera position + if ( this.zoomToCursor && this._performCursorZoom ) { + + let newRadius = null; + if ( this.object.isPerspectiveCamera ) { + + // move the camera down the pointer ray + // this method avoids floating point error + const prevRadius = _v.length(); + newRadius = this._clampDistance( prevRadius * this._scale ); + + const radiusDelta = prevRadius - newRadius; + this.object.position.addScaledVector( this._dollyDirection, radiusDelta ); + this.object.updateMatrixWorld(); + + zoomChanged = !! radiusDelta; + + } else if ( this.object.isOrthographicCamera ) { + + // adjust the ortho camera position based on zoom changes + const mouseBefore = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseBefore.unproject( this.object ); + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + this.object.updateProjectionMatrix(); + + zoomChanged = prevZoom !== this.object.zoom; + + const mouseAfter = new Vector3( this._mouse.x, this._mouse.y, 0 ); + mouseAfter.unproject( this.object ); + + this.object.position.sub( mouseAfter ).add( mouseBefore ); + this.object.updateMatrixWorld(); + + newRadius = _v.length(); + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.' ); + this.zoomToCursor = false; + + } + + // handle the placement of the target + if ( newRadius !== null ) { + + if ( this.screenSpacePanning ) { + + // position the orbit target in front of the new camera position + this.target.set( 0, 0, - 1 ) + .transformDirection( this.object.matrix ) + .multiplyScalar( newRadius ) + .add( this.object.position ); + + } else { + + // get the ray and translation plane to compute target + _ray.origin.copy( this.object.position ); + _ray.direction.set( 0, 0, - 1 ).transformDirection( this.object.matrix ); + + // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid + // extremely large values + if ( Math.abs( this.object.up.dot( _ray.direction ) ) < _TILT_LIMIT ) { + + this.object.lookAt( this.target ); + + } else { + + _plane.setFromNormalAndCoplanarPoint( this.object.up, this.target ); + _ray.intersectPlane( _plane, this.target ); + + } + + } + + } + + } else if ( this.object.isOrthographicCamera ) { + + const prevZoom = this.object.zoom; + this.object.zoom = Math.max( this.minZoom, Math.min( this.maxZoom, this.object.zoom / this._scale ) ); + + if ( prevZoom !== this.object.zoom ) { + + this.object.updateProjectionMatrix(); + zoomChanged = true; + + } + + } + + this._scale = 1; + this._performCursorZoom = false; + + // update condition is: + // min(camera displacement, camera rotation in radians)^2 > EPS + // using small-angle approximation cos(x/2) = 1 - x^2 / 8 + + if ( zoomChanged || + this._lastPosition.distanceToSquared( this.object.position ) > _EPS || + 8 * ( 1 - this._lastQuaternion.dot( this.object.quaternion ) ) > _EPS || + this._lastTargetPosition.distanceToSquared( this.target ) > _EPS ) { + + this.dispatchEvent( _changeEvent ); + + this._lastPosition.copy( this.object.position ); + this._lastQuaternion.copy( this.object.quaternion ); + this._lastTargetPosition.copy( this.target ); + + return true; + + } + + return false; + + } + + _getAutoRotationAngle( deltaTime ) { + + if ( deltaTime !== null ) { + + return ( _twoPI / 60 * this.autoRotateSpeed ) * deltaTime; + + } else { + + return _twoPI / 60 / 60 * this.autoRotateSpeed; + + } + + } + + _getZoomScale( delta ) { + + const normalizedDelta = Math.abs( delta * 0.01 ); + return Math.pow( 0.95, this.zoomSpeed * normalizedDelta ); + + } + + _rotateLeft( angle ) { + + this._sphericalDelta.theta -= angle; + + } + + _rotateUp( angle ) { + + this._sphericalDelta.phi -= angle; + + } + + _panLeft( distance, objectMatrix ) { + + _v.setFromMatrixColumn( objectMatrix, 0 ); // get X column of objectMatrix + _v.multiplyScalar( - distance ); + + this._panOffset.add( _v ); + + } + + _panUp( distance, objectMatrix ) { + + if ( this.screenSpacePanning === true ) { + + _v.setFromMatrixColumn( objectMatrix, 1 ); + + } else { + + _v.setFromMatrixColumn( objectMatrix, 0 ); + _v.crossVectors( this.object.up, _v ); + + } + + _v.multiplyScalar( distance ); + + this._panOffset.add( _v ); + + } + + // deltaX and deltaY are in pixels; right and down are positive + _pan( deltaX, deltaY ) { + + const element = this.domElement; + + if ( this.object.isPerspectiveCamera ) { + + // perspective + const position = this.object.position; + _v.copy( position ).sub( this.target ); + let targetDistance = _v.length(); + + // half of the fov is center to top of screen + targetDistance *= Math.tan( ( this.object.fov / 2 ) * Math.PI / 180.0 ); + + // we use only clientHeight here so aspect ratio does not distort speed + this._panLeft( 2 * deltaX * targetDistance / element.clientHeight, this.object.matrix ); + this._panUp( 2 * deltaY * targetDistance / element.clientHeight, this.object.matrix ); + + } else if ( this.object.isOrthographicCamera ) { + + // orthographic + this._panLeft( deltaX * ( this.object.right - this.object.left ) / this.object.zoom / element.clientWidth, this.object.matrix ); + this._panUp( deltaY * ( this.object.top - this.object.bottom ) / this.object.zoom / element.clientHeight, this.object.matrix ); + + } else { + + // camera neither orthographic nor perspective + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.' ); + this.enablePan = false; + + } + + } + + _dollyOut( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale /= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _dollyIn( dollyScale ) { + + if ( this.object.isPerspectiveCamera || this.object.isOrthographicCamera ) { + + this._scale *= dollyScale; + + } else { + + console.warn( 'WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.' ); + this.enableZoom = false; + + } + + } + + _updateZoomParameters( x, y ) { + + if ( ! this.zoomToCursor ) { + + return; + + } + + this._performCursorZoom = true; + + const rect = this.domElement.getBoundingClientRect(); + const dx = x - rect.left; + const dy = y - rect.top; + const w = rect.width; + const h = rect.height; + + this._mouse.x = ( dx / w ) * 2 - 1; + this._mouse.y = - ( dy / h ) * 2 + 1; + + this._dollyDirection.set( this._mouse.x, this._mouse.y, 1 ).unproject( this.object ).sub( this.object.position ).normalize(); + + } + + _clampDistance( dist ) { + + return Math.max( this.minDistance, Math.min( this.maxDistance, dist ) ); + + } + + // + // event callbacks - update the object state + // + + _handleMouseDownRotate( event ) { + + this._rotateStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownDolly( event ) { + + this._updateZoomParameters( event.clientX, event.clientX ); + this._dollyStart.set( event.clientX, event.clientY ); + + } + + _handleMouseDownPan( event ) { + + this._panStart.set( event.clientX, event.clientY ); + + } + + _handleMouseMoveRotate( event ) { + + this._rotateEnd.set( event.clientX, event.clientY ); + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + this.update(); + + } + + _handleMouseMoveDolly( event ) { + + this._dollyEnd.set( event.clientX, event.clientY ); + + this._dollyDelta.subVectors( this._dollyEnd, this._dollyStart ); + + if ( this._dollyDelta.y > 0 ) { + + this._dollyOut( this._getZoomScale( this._dollyDelta.y ) ); + + } else if ( this._dollyDelta.y < 0 ) { + + this._dollyIn( this._getZoomScale( this._dollyDelta.y ) ); + + } + + this._dollyStart.copy( this._dollyEnd ); + + this.update(); + + } + + _handleMouseMovePan( event ) { + + this._panEnd.set( event.clientX, event.clientY ); + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + this.update(); + + } + + _handleMouseWheel( event ) { + + this._updateZoomParameters( event.clientX, event.clientY ); + + if ( event.deltaY < 0 ) { + + this._dollyIn( this._getZoomScale( event.deltaY ) ); + + } else if ( event.deltaY > 0 ) { + + this._dollyOut( this._getZoomScale( event.deltaY ) ); + + } + + this.update(); + + } + + _handleKeyDown( event ) { + + let needsUpdate = false; + + switch ( event.code ) { + + case this.keys.UP: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateUp( _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( 0, this.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case this.keys.BOTTOM: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateUp( - _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( 0, - this.keyPanSpeed ); + + } + + needsUpdate = true; + break; + + case this.keys.LEFT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateLeft( _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( this.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + case this.keys.RIGHT: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + this._rotateLeft( - _twoPI * this.rotateSpeed / this.domElement.clientHeight ); + + } else { + + this._pan( - this.keyPanSpeed, 0 ); + + } + + needsUpdate = true; + break; + + } + + if ( needsUpdate ) { + + // prevent the browser from scrolling on cursor keys + event.preventDefault(); + + this.update(); + + } + + + } + + _handleTouchStartRotate( event ) { + + if ( this._pointers.length === 1 ) { + + this._rotateStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateStart.set( x, y ); + + } + + } + + _handleTouchStartPan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panStart.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panStart.set( x, y ); + + } + + } + + _handleTouchStartDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyStart.set( 0, distance ); + + } + + _handleTouchStartDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enablePan ) this._handleTouchStartPan( event ); + + } + + _handleTouchStartDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchStartDolly( event ); + + if ( this.enableRotate ) this._handleTouchStartRotate( event ); + + } + + _handleTouchMoveRotate( event ) { + + if ( this._pointers.length == 1 ) { + + this._rotateEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._rotateEnd.set( x, y ); + + } + + this._rotateDelta.subVectors( this._rotateEnd, this._rotateStart ).multiplyScalar( this.rotateSpeed ); + + const element = this.domElement; + + this._rotateLeft( _twoPI * this._rotateDelta.x / element.clientHeight ); // yes, height + + this._rotateUp( _twoPI * this._rotateDelta.y / element.clientHeight ); + + this._rotateStart.copy( this._rotateEnd ); + + } + + _handleTouchMovePan( event ) { + + if ( this._pointers.length === 1 ) { + + this._panEnd.set( event.pageX, event.pageY ); + + } else { + + const position = this._getSecondPointerPosition( event ); + + const x = 0.5 * ( event.pageX + position.x ); + const y = 0.5 * ( event.pageY + position.y ); + + this._panEnd.set( x, y ); + + } + + this._panDelta.subVectors( this._panEnd, this._panStart ).multiplyScalar( this.panSpeed ); + + this._pan( this._panDelta.x, this._panDelta.y ); + + this._panStart.copy( this._panEnd ); + + } + + _handleTouchMoveDolly( event ) { + + const position = this._getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + + const distance = Math.sqrt( dx * dx + dy * dy ); + + this._dollyEnd.set( 0, distance ); + + this._dollyDelta.set( 0, Math.pow( this._dollyEnd.y / this._dollyStart.y, this.zoomSpeed ) ); + + this._dollyOut( this._dollyDelta.y ); + + this._dollyStart.copy( this._dollyEnd ); + + const centerX = ( event.pageX + position.x ) * 0.5; + const centerY = ( event.pageY + position.y ) * 0.5; + + this._updateZoomParameters( centerX, centerY ); + + } + + _handleTouchMoveDollyPan( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enablePan ) this._handleTouchMovePan( event ); + + } + + _handleTouchMoveDollyRotate( event ) { + + if ( this.enableZoom ) this._handleTouchMoveDolly( event ); + + if ( this.enableRotate ) this._handleTouchMoveRotate( event ); + + } + + // pointers + + _addPointer( event ) { + + this._pointers.push( event.pointerId ); + + } + + _removePointer( event ) { + + delete this._pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) { + + this._pointers.splice( i, 1 ); + return; + + } + + } + + } + + _isTrackingPointer( event ) { + + for ( let i = 0; i < this._pointers.length; i ++ ) { + + if ( this._pointers[ i ] == event.pointerId ) return true; + + } + + return false; + + } + + _trackPointer( event ) { + + let position = this._pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + this._pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + _getSecondPointerPosition( event ) { + + const pointerId = ( event.pointerId === this._pointers[ 0 ] ) ? this._pointers[ 1 ] : this._pointers[ 0 ]; + + return this._pointerPositions[ pointerId ]; + + } + + // + + _customWheelEvent( event ) { + + const mode = event.deltaMode; + + // minimal wheel event altered to meet delta-zoom demand + const newEvent = { + clientX: event.clientX, + clientY: event.clientY, + deltaY: event.deltaY, + }; + + switch ( mode ) { + + case 1: // LINE_MODE + newEvent.deltaY *= 16; + break; + + case 2: // PAGE_MODE + newEvent.deltaY *= 100; + break; + + } + + // detect if event was triggered by pinching + if ( event.ctrlKey && ! this._controlActive ) { + + newEvent.deltaY *= 10; + + } + + return newEvent; + + } + +} + +function onPointerDown( event ) { + + if ( this.enabled === false ) return; + + if ( this._pointers.length === 0 ) { + + this.domElement.setPointerCapture( event.pointerId ); + + this.domElement.addEventListener( 'pointermove', this._onPointerMove ); + this.domElement.addEventListener( 'pointerup', this._onPointerUp ); + + } + + // + + if ( this._isTrackingPointer( event ) ) return; + + // + + this._addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + this._onTouchStart( event ); + + } else { + + this._onMouseDown( event ); + + } + +} + +function onPointerMove( event ) { + + if ( this.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + this._onTouchMove( event ); + + } else { + + this._onMouseMove( event ); + + } + +} + +function onPointerUp( event ) { + + this._removePointer( event ); + + switch ( this._pointers.length ) { + + case 0: + + this.domElement.releasePointerCapture( event.pointerId ); + + this.domElement.removeEventListener( 'pointermove', this._onPointerMove ); + this.domElement.removeEventListener( 'pointerup', this._onPointerUp ); + + this.dispatchEvent( _endEvent ); + + this.state = _STATE.NONE; + + break; + + case 1: + + const pointerId = this._pointers[ 0 ]; + const position = this._pointerPositions[ pointerId ]; + + // minimal placeholder event - allows state correction on pointer-up + this._onTouchStart( { pointerId: pointerId, pageX: position.x, pageY: position.y } ); + + break; + + } + +} + +function onMouseDown( event ) { + + let mouseAction; + + switch ( event.button ) { + + case 0: + + mouseAction = this.mouseButtons.LEFT; + break; + + case 1: + + mouseAction = this.mouseButtons.MIDDLE; + break; + + case 2: + + mouseAction = this.mouseButtons.RIGHT; + break; + + default: + + mouseAction = - 1; + + } + + switch ( mouseAction ) { + + case MOUSE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseDownDolly( event ); + + this.state = _STATE.DOLLY; + + break; + + case MOUSE.ROTATE: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } else { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } + + break; + + case MOUSE.PAN: + + if ( event.ctrlKey || event.metaKey || event.shiftKey ) { + + if ( this.enableRotate === false ) return; + + this._handleMouseDownRotate( event ); + + this.state = _STATE.ROTATE; + + } else { + + if ( this.enablePan === false ) return; + + this._handleMouseDownPan( event ); + + this.state = _STATE.PAN; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onMouseMove( event ) { + + switch ( this.state ) { + + case _STATE.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleMouseMoveRotate( event ); + + break; + + case _STATE.DOLLY: + + if ( this.enableZoom === false ) return; + + this._handleMouseMoveDolly( event ); + + break; + + case _STATE.PAN: + + if ( this.enablePan === false ) return; + + this._handleMouseMovePan( event ); + + break; + + } + +} + +function onMouseWheel( event ) { + + if ( this.enabled === false || this.enableZoom === false || this.state !== _STATE.NONE ) return; + + event.preventDefault(); + + this.dispatchEvent( _startEvent ); + + this._handleMouseWheel( this._customWheelEvent( event ) ); + + this.dispatchEvent( _endEvent ); + +} + +function onKeyDown( event ) { + + if ( this.enabled === false || this.enablePan === false ) return; + + this._handleKeyDown( event ); + +} + +function onTouchStart( event ) { + + this._trackPointer( event ); + + switch ( this._pointers.length ) { + + case 1: + + switch ( this.touches.ONE ) { + + case TOUCH.ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchStartRotate( event ); + + this.state = _STATE.TOUCH_ROTATE; + + break; + + case TOUCH.PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchStartPan( event ); + + this.state = _STATE.TOUCH_PAN; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + case 2: + + switch ( this.touches.TWO ) { + + case TOUCH.DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchStartDollyPan( event ); + + this.state = _STATE.TOUCH_DOLLY_PAN; + + break; + + case TOUCH.DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchStartDollyRotate( event ); + + this.state = _STATE.TOUCH_DOLLY_ROTATE; + + break; + + default: + + this.state = _STATE.NONE; + + } + + break; + + default: + + this.state = _STATE.NONE; + + } + + if ( this.state !== _STATE.NONE ) { + + this.dispatchEvent( _startEvent ); + + } + +} + +function onTouchMove( event ) { + + this._trackPointer( event ); + + switch ( this.state ) { + + case _STATE.TOUCH_ROTATE: + + if ( this.enableRotate === false ) return; + + this._handleTouchMoveRotate( event ); + + this.update(); + + break; + + case _STATE.TOUCH_PAN: + + if ( this.enablePan === false ) return; + + this._handleTouchMovePan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_PAN: + + if ( this.enableZoom === false && this.enablePan === false ) return; + + this._handleTouchMoveDollyPan( event ); + + this.update(); + + break; + + case _STATE.TOUCH_DOLLY_ROTATE: + + if ( this.enableZoom === false && this.enableRotate === false ) return; + + this._handleTouchMoveDollyRotate( event ); + + this.update(); + + break; + + default: + + this.state = _STATE.NONE; + + } + +} + +function onContextMenu( event ) { + + if ( this.enabled === false ) return; + + event.preventDefault(); + +} + +function interceptControlDown( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = true; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.addEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +function interceptControlUp( event ) { + + if ( event.key === 'Control' ) { + + this._controlActive = false; + + const document = this.domElement.getRootNode(); // offscreen canvas compatibility + + document.removeEventListener( 'keyup', this._interceptControlUp, { passive: true, capture: true } ); + + } + +} + +export { OrbitControls }; diff --git a/ui/viewer/vendor/three/addons/libs/ammo.wasm.js b/ui/viewer/vendor/three/addons/libs/ammo.wasm.js new file mode 100644 index 0000000..a7f835c --- /dev/null +++ b/ui/viewer/vendor/three/addons/libs/ammo.wasm.js @@ -0,0 +1,822 @@ + +// This is ammo.js, a port of Bullet Physics to JavaScript. zlib licensed. + +var Ammo = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(Ammo) { + Ammo = Ammo || {}; + + +var b;b||(b=typeof Ammo !== 'undefined' ? Ammo : {});var ba;b.ready=new Promise(function(a){ba=a});var ca={},da;for(da in b)b.hasOwnProperty(da)&&(ca[da]=b[da]);var ea=!1,fa=!1,ha=!1,ia=!1;ea="object"===typeof window;fa="function"===typeof importScripts;ha="object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node;ia=!ea&&!ha&&!fa;var ja="",ka,la,ma,na; +if(ha)ja=fa?require("path").dirname(ja)+"/":__dirname+"/",ka=function(a,c){ma||(ma=require("fs"));na||(na=require("path"));a=na.normalize(a);return ma.readFileSync(a,c?null:"utf8")},la=function(a){a=ka(a,!0);a.buffer||(a=new Uint8Array(a));assert(a.buffer);return a},1>=2;d=za[a++];)Xa.push(105>d?Ca[++c>>1]:Aa[c]),++c;return Xa}var Za={f:function(){oa()},c:function(a,c,d){c=Ya(c,d);return Va[a].apply(null,c)},a:function(a,c,d){c=Ya(c,d);return Va[a].apply(null,c)},d:function(a,c,d){za.copyWithin(a,c,c+d)},e:function(){oa("OOM")},b:function(a){var c=Date.now();Aa[a>>2]=c/1E3|0;Aa[a+4>>2]=c%1E3*1E3|0;return 0},memory:sa,table:ua}; +(function(){function a(g){b.asm=g.exports;Ma--;b.monitorRunDependencies&&b.monitorRunDependencies(Ma);0==Ma&&(null!==Na&&(clearInterval(Na),Na=null),Oa&&(g=Oa,Oa=null,g()))}function c(g){a(g.instance)}function d(g){return Ua().then(function(n){return WebAssembly.instantiate(n,e)}).then(g,function(n){qa("failed to asynchronously prepare wasm: "+n);oa(n)})}var e={a:Za};Ma++;b.monitorRunDependencies&&b.monitorRunDependencies(Ma);if(b.instantiateWasm)try{return b.instantiateWasm(e,a)}catch(g){return qa("Module.instantiateWasm callback failed with error: "+ +g),!1}(function(){if(ra||"function"!==typeof WebAssembly.instantiateStreaming||Ra()||Pa("file://")||"function"!==typeof fetch)return d(c);fetch(Qa,{credentials:"same-origin"}).then(function(g){return WebAssembly.instantiateStreaming(g,e).then(c,function(n){qa("wasm streaming compile failed: "+n);qa("falling back to ArrayBuffer instantiation");return d(c)})})})();return{}})();var Wa=b.___wasm_call_ctors=function(){return(Wa=b.___wasm_call_ctors=b.asm.g).apply(null,arguments)}; +b.___em_js__array_bounds_check_error=function(){return(b.___em_js__array_bounds_check_error=b.asm.h).apply(null,arguments)}; +var $a=b._emscripten_bind_btCollisionWorld_getDispatcher_0=function(){return($a=b._emscripten_bind_btCollisionWorld_getDispatcher_0=b.asm.i).apply(null,arguments)},ab=b._emscripten_bind_btCollisionWorld_rayTest_3=function(){return(ab=b._emscripten_bind_btCollisionWorld_rayTest_3=b.asm.j).apply(null,arguments)},bb=b._emscripten_bind_btCollisionWorld_getPairCache_0=function(){return(bb=b._emscripten_bind_btCollisionWorld_getPairCache_0=b.asm.k).apply(null,arguments)},cb=b._emscripten_bind_btCollisionWorld_getDispatchInfo_0= +function(){return(cb=b._emscripten_bind_btCollisionWorld_getDispatchInfo_0=b.asm.l).apply(null,arguments)},db=b._emscripten_bind_btCollisionWorld_addCollisionObject_1=function(){return(db=b._emscripten_bind_btCollisionWorld_addCollisionObject_1=b.asm.m).apply(null,arguments)},eb=b._emscripten_bind_btCollisionWorld_addCollisionObject_2=function(){return(eb=b._emscripten_bind_btCollisionWorld_addCollisionObject_2=b.asm.n).apply(null,arguments)},fb=b._emscripten_bind_btCollisionWorld_addCollisionObject_3= +function(){return(fb=b._emscripten_bind_btCollisionWorld_addCollisionObject_3=b.asm.o).apply(null,arguments)},gb=b._emscripten_bind_btCollisionWorld_removeCollisionObject_1=function(){return(gb=b._emscripten_bind_btCollisionWorld_removeCollisionObject_1=b.asm.p).apply(null,arguments)},hb=b._emscripten_bind_btCollisionWorld_getBroadphase_0=function(){return(hb=b._emscripten_bind_btCollisionWorld_getBroadphase_0=b.asm.q).apply(null,arguments)},ib=b._emscripten_bind_btCollisionWorld_convexSweepTest_5= +function(){return(ib=b._emscripten_bind_btCollisionWorld_convexSweepTest_5=b.asm.r).apply(null,arguments)},jb=b._emscripten_bind_btCollisionWorld_contactPairTest_3=function(){return(jb=b._emscripten_bind_btCollisionWorld_contactPairTest_3=b.asm.s).apply(null,arguments)},kb=b._emscripten_bind_btCollisionWorld_contactTest_2=function(){return(kb=b._emscripten_bind_btCollisionWorld_contactTest_2=b.asm.t).apply(null,arguments)},lb=b._emscripten_bind_btCollisionWorld_updateSingleAabb_1=function(){return(lb= +b._emscripten_bind_btCollisionWorld_updateSingleAabb_1=b.asm.u).apply(null,arguments)},mb=b._emscripten_bind_btCollisionWorld_setDebugDrawer_1=function(){return(mb=b._emscripten_bind_btCollisionWorld_setDebugDrawer_1=b.asm.v).apply(null,arguments)},nb=b._emscripten_bind_btCollisionWorld_getDebugDrawer_0=function(){return(nb=b._emscripten_bind_btCollisionWorld_getDebugDrawer_0=b.asm.w).apply(null,arguments)},ob=b._emscripten_bind_btCollisionWorld_debugDrawWorld_0=function(){return(ob=b._emscripten_bind_btCollisionWorld_debugDrawWorld_0= +b.asm.x).apply(null,arguments)},pb=b._emscripten_bind_btCollisionWorld_debugDrawObject_3=function(){return(pb=b._emscripten_bind_btCollisionWorld_debugDrawObject_3=b.asm.y).apply(null,arguments)},qb=b._emscripten_bind_btCollisionWorld___destroy___0=function(){return(qb=b._emscripten_bind_btCollisionWorld___destroy___0=b.asm.z).apply(null,arguments)},rb=b._emscripten_bind_btCollisionShape_setLocalScaling_1=function(){return(rb=b._emscripten_bind_btCollisionShape_setLocalScaling_1=b.asm.A).apply(null, +arguments)},sb=b._emscripten_bind_btCollisionShape_getLocalScaling_0=function(){return(sb=b._emscripten_bind_btCollisionShape_getLocalScaling_0=b.asm.B).apply(null,arguments)},tb=b._emscripten_bind_btCollisionShape_calculateLocalInertia_2=function(){return(tb=b._emscripten_bind_btCollisionShape_calculateLocalInertia_2=b.asm.C).apply(null,arguments)},ub=b._emscripten_bind_btCollisionShape_setMargin_1=function(){return(ub=b._emscripten_bind_btCollisionShape_setMargin_1=b.asm.D).apply(null,arguments)}, +vb=b._emscripten_bind_btCollisionShape_getMargin_0=function(){return(vb=b._emscripten_bind_btCollisionShape_getMargin_0=b.asm.E).apply(null,arguments)},wb=b._emscripten_bind_btCollisionShape___destroy___0=function(){return(wb=b._emscripten_bind_btCollisionShape___destroy___0=b.asm.F).apply(null,arguments)},xb=b._emscripten_bind_btCollisionObject_setAnisotropicFriction_2=function(){return(xb=b._emscripten_bind_btCollisionObject_setAnisotropicFriction_2=b.asm.G).apply(null,arguments)},yb=b._emscripten_bind_btCollisionObject_getCollisionShape_0= +function(){return(yb=b._emscripten_bind_btCollisionObject_getCollisionShape_0=b.asm.H).apply(null,arguments)},zb=b._emscripten_bind_btCollisionObject_setContactProcessingThreshold_1=function(){return(zb=b._emscripten_bind_btCollisionObject_setContactProcessingThreshold_1=b.asm.I).apply(null,arguments)},Ab=b._emscripten_bind_btCollisionObject_setActivationState_1=function(){return(Ab=b._emscripten_bind_btCollisionObject_setActivationState_1=b.asm.J).apply(null,arguments)},Bb=b._emscripten_bind_btCollisionObject_forceActivationState_1= +function(){return(Bb=b._emscripten_bind_btCollisionObject_forceActivationState_1=b.asm.K).apply(null,arguments)},Cb=b._emscripten_bind_btCollisionObject_activate_0=function(){return(Cb=b._emscripten_bind_btCollisionObject_activate_0=b.asm.L).apply(null,arguments)},Db=b._emscripten_bind_btCollisionObject_activate_1=function(){return(Db=b._emscripten_bind_btCollisionObject_activate_1=b.asm.M).apply(null,arguments)},Eb=b._emscripten_bind_btCollisionObject_isActive_0=function(){return(Eb=b._emscripten_bind_btCollisionObject_isActive_0= +b.asm.N).apply(null,arguments)},Fb=b._emscripten_bind_btCollisionObject_isKinematicObject_0=function(){return(Fb=b._emscripten_bind_btCollisionObject_isKinematicObject_0=b.asm.O).apply(null,arguments)},Gb=b._emscripten_bind_btCollisionObject_isStaticObject_0=function(){return(Gb=b._emscripten_bind_btCollisionObject_isStaticObject_0=b.asm.P).apply(null,arguments)},Hb=b._emscripten_bind_btCollisionObject_isStaticOrKinematicObject_0=function(){return(Hb=b._emscripten_bind_btCollisionObject_isStaticOrKinematicObject_0= +b.asm.Q).apply(null,arguments)},Ib=b._emscripten_bind_btCollisionObject_getRestitution_0=function(){return(Ib=b._emscripten_bind_btCollisionObject_getRestitution_0=b.asm.R).apply(null,arguments)},Jb=b._emscripten_bind_btCollisionObject_getFriction_0=function(){return(Jb=b._emscripten_bind_btCollisionObject_getFriction_0=b.asm.S).apply(null,arguments)},Kb=b._emscripten_bind_btCollisionObject_getRollingFriction_0=function(){return(Kb=b._emscripten_bind_btCollisionObject_getRollingFriction_0=b.asm.T).apply(null, +arguments)},Lb=b._emscripten_bind_btCollisionObject_setRestitution_1=function(){return(Lb=b._emscripten_bind_btCollisionObject_setRestitution_1=b.asm.U).apply(null,arguments)},Mb=b._emscripten_bind_btCollisionObject_setFriction_1=function(){return(Mb=b._emscripten_bind_btCollisionObject_setFriction_1=b.asm.V).apply(null,arguments)},Nb=b._emscripten_bind_btCollisionObject_setRollingFriction_1=function(){return(Nb=b._emscripten_bind_btCollisionObject_setRollingFriction_1=b.asm.W).apply(null,arguments)}, +Ob=b._emscripten_bind_btCollisionObject_getWorldTransform_0=function(){return(Ob=b._emscripten_bind_btCollisionObject_getWorldTransform_0=b.asm.X).apply(null,arguments)},Pb=b._emscripten_bind_btCollisionObject_getCollisionFlags_0=function(){return(Pb=b._emscripten_bind_btCollisionObject_getCollisionFlags_0=b.asm.Y).apply(null,arguments)},Qb=b._emscripten_bind_btCollisionObject_setCollisionFlags_1=function(){return(Qb=b._emscripten_bind_btCollisionObject_setCollisionFlags_1=b.asm.Z).apply(null,arguments)}, +Sb=b._emscripten_bind_btCollisionObject_setWorldTransform_1=function(){return(Sb=b._emscripten_bind_btCollisionObject_setWorldTransform_1=b.asm._).apply(null,arguments)},Tb=b._emscripten_bind_btCollisionObject_setCollisionShape_1=function(){return(Tb=b._emscripten_bind_btCollisionObject_setCollisionShape_1=b.asm.$).apply(null,arguments)},Ub=b._emscripten_bind_btCollisionObject_setCcdMotionThreshold_1=function(){return(Ub=b._emscripten_bind_btCollisionObject_setCcdMotionThreshold_1=b.asm.aa).apply(null, +arguments)},Vb=b._emscripten_bind_btCollisionObject_setCcdSweptSphereRadius_1=function(){return(Vb=b._emscripten_bind_btCollisionObject_setCcdSweptSphereRadius_1=b.asm.ba).apply(null,arguments)},Wb=b._emscripten_bind_btCollisionObject_getUserIndex_0=function(){return(Wb=b._emscripten_bind_btCollisionObject_getUserIndex_0=b.asm.ca).apply(null,arguments)},Xb=b._emscripten_bind_btCollisionObject_setUserIndex_1=function(){return(Xb=b._emscripten_bind_btCollisionObject_setUserIndex_1=b.asm.da).apply(null, +arguments)},Yb=b._emscripten_bind_btCollisionObject_getUserPointer_0=function(){return(Yb=b._emscripten_bind_btCollisionObject_getUserPointer_0=b.asm.ea).apply(null,arguments)},Zb=b._emscripten_bind_btCollisionObject_setUserPointer_1=function(){return(Zb=b._emscripten_bind_btCollisionObject_setUserPointer_1=b.asm.fa).apply(null,arguments)},$b=b._emscripten_bind_btCollisionObject_getBroadphaseHandle_0=function(){return($b=b._emscripten_bind_btCollisionObject_getBroadphaseHandle_0=b.asm.ga).apply(null, +arguments)},ac=b._emscripten_bind_btCollisionObject___destroy___0=function(){return(ac=b._emscripten_bind_btCollisionObject___destroy___0=b.asm.ha).apply(null,arguments)},bc=b._emscripten_bind_btDynamicsWorld_addAction_1=function(){return(bc=b._emscripten_bind_btDynamicsWorld_addAction_1=b.asm.ia).apply(null,arguments)},cc=b._emscripten_bind_btDynamicsWorld_removeAction_1=function(){return(cc=b._emscripten_bind_btDynamicsWorld_removeAction_1=b.asm.ja).apply(null,arguments)},dc=b._emscripten_bind_btDynamicsWorld_getSolverInfo_0= +function(){return(dc=b._emscripten_bind_btDynamicsWorld_getSolverInfo_0=b.asm.ka).apply(null,arguments)},ec=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_1=function(){return(ec=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_1=b.asm.la).apply(null,arguments)},fc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_2=function(){return(fc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_2=b.asm.ma).apply(null,arguments)},hc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_3= +function(){return(hc=b._emscripten_bind_btDynamicsWorld_setInternalTickCallback_3=b.asm.na).apply(null,arguments)},ic=b._emscripten_bind_btDynamicsWorld_getDispatcher_0=function(){return(ic=b._emscripten_bind_btDynamicsWorld_getDispatcher_0=b.asm.oa).apply(null,arguments)},jc=b._emscripten_bind_btDynamicsWorld_rayTest_3=function(){return(jc=b._emscripten_bind_btDynamicsWorld_rayTest_3=b.asm.pa).apply(null,arguments)},kc=b._emscripten_bind_btDynamicsWorld_getPairCache_0=function(){return(kc=b._emscripten_bind_btDynamicsWorld_getPairCache_0= +b.asm.qa).apply(null,arguments)},lc=b._emscripten_bind_btDynamicsWorld_getDispatchInfo_0=function(){return(lc=b._emscripten_bind_btDynamicsWorld_getDispatchInfo_0=b.asm.ra).apply(null,arguments)},mc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_1=function(){return(mc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_1=b.asm.sa).apply(null,arguments)},nc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_2=function(){return(nc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_2= +b.asm.ta).apply(null,arguments)},oc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_3=function(){return(oc=b._emscripten_bind_btDynamicsWorld_addCollisionObject_3=b.asm.ua).apply(null,arguments)},pc=b._emscripten_bind_btDynamicsWorld_removeCollisionObject_1=function(){return(pc=b._emscripten_bind_btDynamicsWorld_removeCollisionObject_1=b.asm.va).apply(null,arguments)},qc=b._emscripten_bind_btDynamicsWorld_getBroadphase_0=function(){return(qc=b._emscripten_bind_btDynamicsWorld_getBroadphase_0= +b.asm.wa).apply(null,arguments)},rc=b._emscripten_bind_btDynamicsWorld_convexSweepTest_5=function(){return(rc=b._emscripten_bind_btDynamicsWorld_convexSweepTest_5=b.asm.xa).apply(null,arguments)},sc=b._emscripten_bind_btDynamicsWorld_contactPairTest_3=function(){return(sc=b._emscripten_bind_btDynamicsWorld_contactPairTest_3=b.asm.ya).apply(null,arguments)},tc=b._emscripten_bind_btDynamicsWorld_contactTest_2=function(){return(tc=b._emscripten_bind_btDynamicsWorld_contactTest_2=b.asm.za).apply(null, +arguments)},uc=b._emscripten_bind_btDynamicsWorld_updateSingleAabb_1=function(){return(uc=b._emscripten_bind_btDynamicsWorld_updateSingleAabb_1=b.asm.Aa).apply(null,arguments)},vc=b._emscripten_bind_btDynamicsWorld_setDebugDrawer_1=function(){return(vc=b._emscripten_bind_btDynamicsWorld_setDebugDrawer_1=b.asm.Ba).apply(null,arguments)},wc=b._emscripten_bind_btDynamicsWorld_getDebugDrawer_0=function(){return(wc=b._emscripten_bind_btDynamicsWorld_getDebugDrawer_0=b.asm.Ca).apply(null,arguments)},xc= +b._emscripten_bind_btDynamicsWorld_debugDrawWorld_0=function(){return(xc=b._emscripten_bind_btDynamicsWorld_debugDrawWorld_0=b.asm.Da).apply(null,arguments)},yc=b._emscripten_bind_btDynamicsWorld_debugDrawObject_3=function(){return(yc=b._emscripten_bind_btDynamicsWorld_debugDrawObject_3=b.asm.Ea).apply(null,arguments)},zc=b._emscripten_bind_btDynamicsWorld___destroy___0=function(){return(zc=b._emscripten_bind_btDynamicsWorld___destroy___0=b.asm.Fa).apply(null,arguments)},Ac=b._emscripten_bind_btTypedConstraint_enableFeedback_1= +function(){return(Ac=b._emscripten_bind_btTypedConstraint_enableFeedback_1=b.asm.Ga).apply(null,arguments)},Bc=b._emscripten_bind_btTypedConstraint_getBreakingImpulseThreshold_0=function(){return(Bc=b._emscripten_bind_btTypedConstraint_getBreakingImpulseThreshold_0=b.asm.Ha).apply(null,arguments)},Cc=b._emscripten_bind_btTypedConstraint_setBreakingImpulseThreshold_1=function(){return(Cc=b._emscripten_bind_btTypedConstraint_setBreakingImpulseThreshold_1=b.asm.Ia).apply(null,arguments)},Dc=b._emscripten_bind_btTypedConstraint_getParam_2= +function(){return(Dc=b._emscripten_bind_btTypedConstraint_getParam_2=b.asm.Ja).apply(null,arguments)},Ec=b._emscripten_bind_btTypedConstraint_setParam_3=function(){return(Ec=b._emscripten_bind_btTypedConstraint_setParam_3=b.asm.Ka).apply(null,arguments)},Fc=b._emscripten_bind_btTypedConstraint___destroy___0=function(){return(Fc=b._emscripten_bind_btTypedConstraint___destroy___0=b.asm.La).apply(null,arguments)},Gc=b._emscripten_bind_btConcaveShape_setLocalScaling_1=function(){return(Gc=b._emscripten_bind_btConcaveShape_setLocalScaling_1= +b.asm.Ma).apply(null,arguments)},Hc=b._emscripten_bind_btConcaveShape_getLocalScaling_0=function(){return(Hc=b._emscripten_bind_btConcaveShape_getLocalScaling_0=b.asm.Na).apply(null,arguments)},Ic=b._emscripten_bind_btConcaveShape_calculateLocalInertia_2=function(){return(Ic=b._emscripten_bind_btConcaveShape_calculateLocalInertia_2=b.asm.Oa).apply(null,arguments)},Jc=b._emscripten_bind_btConcaveShape___destroy___0=function(){return(Jc=b._emscripten_bind_btConcaveShape___destroy___0=b.asm.Pa).apply(null, +arguments)},Kc=b._emscripten_bind_btCapsuleShape_btCapsuleShape_2=function(){return(Kc=b._emscripten_bind_btCapsuleShape_btCapsuleShape_2=b.asm.Qa).apply(null,arguments)},Lc=b._emscripten_bind_btCapsuleShape_setMargin_1=function(){return(Lc=b._emscripten_bind_btCapsuleShape_setMargin_1=b.asm.Ra).apply(null,arguments)},Mc=b._emscripten_bind_btCapsuleShape_getMargin_0=function(){return(Mc=b._emscripten_bind_btCapsuleShape_getMargin_0=b.asm.Sa).apply(null,arguments)},Nc=b._emscripten_bind_btCapsuleShape_getUpAxis_0= +function(){return(Nc=b._emscripten_bind_btCapsuleShape_getUpAxis_0=b.asm.Ta).apply(null,arguments)},Oc=b._emscripten_bind_btCapsuleShape_getRadius_0=function(){return(Oc=b._emscripten_bind_btCapsuleShape_getRadius_0=b.asm.Ua).apply(null,arguments)},Pc=b._emscripten_bind_btCapsuleShape_getHalfHeight_0=function(){return(Pc=b._emscripten_bind_btCapsuleShape_getHalfHeight_0=b.asm.Va).apply(null,arguments)},Qc=b._emscripten_bind_btCapsuleShape_setLocalScaling_1=function(){return(Qc=b._emscripten_bind_btCapsuleShape_setLocalScaling_1= +b.asm.Wa).apply(null,arguments)},Rc=b._emscripten_bind_btCapsuleShape_getLocalScaling_0=function(){return(Rc=b._emscripten_bind_btCapsuleShape_getLocalScaling_0=b.asm.Xa).apply(null,arguments)},Sc=b._emscripten_bind_btCapsuleShape_calculateLocalInertia_2=function(){return(Sc=b._emscripten_bind_btCapsuleShape_calculateLocalInertia_2=b.asm.Ya).apply(null,arguments)},Tc=b._emscripten_bind_btCapsuleShape___destroy___0=function(){return(Tc=b._emscripten_bind_btCapsuleShape___destroy___0=b.asm.Za).apply(null, +arguments)},Uc=b._emscripten_bind_btIDebugDraw_drawLine_3=function(){return(Uc=b._emscripten_bind_btIDebugDraw_drawLine_3=b.asm._a).apply(null,arguments)},Vc=b._emscripten_bind_btIDebugDraw_drawContactPoint_5=function(){return(Vc=b._emscripten_bind_btIDebugDraw_drawContactPoint_5=b.asm.$a).apply(null,arguments)},Wc=b._emscripten_bind_btIDebugDraw_reportErrorWarning_1=function(){return(Wc=b._emscripten_bind_btIDebugDraw_reportErrorWarning_1=b.asm.ab).apply(null,arguments)},Xc=b._emscripten_bind_btIDebugDraw_draw3dText_2= +function(){return(Xc=b._emscripten_bind_btIDebugDraw_draw3dText_2=b.asm.bb).apply(null,arguments)},Yc=b._emscripten_bind_btIDebugDraw_setDebugMode_1=function(){return(Yc=b._emscripten_bind_btIDebugDraw_setDebugMode_1=b.asm.cb).apply(null,arguments)},Zc=b._emscripten_bind_btIDebugDraw_getDebugMode_0=function(){return(Zc=b._emscripten_bind_btIDebugDraw_getDebugMode_0=b.asm.db).apply(null,arguments)},$c=b._emscripten_bind_btIDebugDraw___destroy___0=function(){return($c=b._emscripten_bind_btIDebugDraw___destroy___0= +b.asm.eb).apply(null,arguments)},ad=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_0=function(){return(ad=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_0=b.asm.fb).apply(null,arguments)},bd=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_1=function(){return(bd=b._emscripten_bind_btDefaultCollisionConfiguration_btDefaultCollisionConfiguration_1=b.asm.gb).apply(null,arguments)},cd=b._emscripten_bind_btDefaultCollisionConfiguration___destroy___0= +function(){return(cd=b._emscripten_bind_btDefaultCollisionConfiguration___destroy___0=b.asm.hb).apply(null,arguments)},dd=b._emscripten_bind_btTriangleMeshShape_setLocalScaling_1=function(){return(dd=b._emscripten_bind_btTriangleMeshShape_setLocalScaling_1=b.asm.ib).apply(null,arguments)},ed=b._emscripten_bind_btTriangleMeshShape_getLocalScaling_0=function(){return(ed=b._emscripten_bind_btTriangleMeshShape_getLocalScaling_0=b.asm.jb).apply(null,arguments)},fd=b._emscripten_bind_btTriangleMeshShape_calculateLocalInertia_2= +function(){return(fd=b._emscripten_bind_btTriangleMeshShape_calculateLocalInertia_2=b.asm.kb).apply(null,arguments)},gd=b._emscripten_bind_btTriangleMeshShape___destroy___0=function(){return(gd=b._emscripten_bind_btTriangleMeshShape___destroy___0=b.asm.lb).apply(null,arguments)},hd=b._emscripten_bind_btGhostObject_btGhostObject_0=function(){return(hd=b._emscripten_bind_btGhostObject_btGhostObject_0=b.asm.mb).apply(null,arguments)},id=b._emscripten_bind_btGhostObject_getNumOverlappingObjects_0=function(){return(id= +b._emscripten_bind_btGhostObject_getNumOverlappingObjects_0=b.asm.nb).apply(null,arguments)},jd=b._emscripten_bind_btGhostObject_getOverlappingObject_1=function(){return(jd=b._emscripten_bind_btGhostObject_getOverlappingObject_1=b.asm.ob).apply(null,arguments)},kd=b._emscripten_bind_btGhostObject_setAnisotropicFriction_2=function(){return(kd=b._emscripten_bind_btGhostObject_setAnisotropicFriction_2=b.asm.pb).apply(null,arguments)},ld=b._emscripten_bind_btGhostObject_getCollisionShape_0=function(){return(ld= +b._emscripten_bind_btGhostObject_getCollisionShape_0=b.asm.qb).apply(null,arguments)},md=b._emscripten_bind_btGhostObject_setContactProcessingThreshold_1=function(){return(md=b._emscripten_bind_btGhostObject_setContactProcessingThreshold_1=b.asm.rb).apply(null,arguments)},nd=b._emscripten_bind_btGhostObject_setActivationState_1=function(){return(nd=b._emscripten_bind_btGhostObject_setActivationState_1=b.asm.sb).apply(null,arguments)},od=b._emscripten_bind_btGhostObject_forceActivationState_1=function(){return(od= +b._emscripten_bind_btGhostObject_forceActivationState_1=b.asm.tb).apply(null,arguments)},pd=b._emscripten_bind_btGhostObject_activate_0=function(){return(pd=b._emscripten_bind_btGhostObject_activate_0=b.asm.ub).apply(null,arguments)},qd=b._emscripten_bind_btGhostObject_activate_1=function(){return(qd=b._emscripten_bind_btGhostObject_activate_1=b.asm.vb).apply(null,arguments)},rd=b._emscripten_bind_btGhostObject_isActive_0=function(){return(rd=b._emscripten_bind_btGhostObject_isActive_0=b.asm.wb).apply(null, +arguments)},sd=b._emscripten_bind_btGhostObject_isKinematicObject_0=function(){return(sd=b._emscripten_bind_btGhostObject_isKinematicObject_0=b.asm.xb).apply(null,arguments)},td=b._emscripten_bind_btGhostObject_isStaticObject_0=function(){return(td=b._emscripten_bind_btGhostObject_isStaticObject_0=b.asm.yb).apply(null,arguments)},ud=b._emscripten_bind_btGhostObject_isStaticOrKinematicObject_0=function(){return(ud=b._emscripten_bind_btGhostObject_isStaticOrKinematicObject_0=b.asm.zb).apply(null,arguments)}, +vd=b._emscripten_bind_btGhostObject_getRestitution_0=function(){return(vd=b._emscripten_bind_btGhostObject_getRestitution_0=b.asm.Ab).apply(null,arguments)},wd=b._emscripten_bind_btGhostObject_getFriction_0=function(){return(wd=b._emscripten_bind_btGhostObject_getFriction_0=b.asm.Bb).apply(null,arguments)},xd=b._emscripten_bind_btGhostObject_getRollingFriction_0=function(){return(xd=b._emscripten_bind_btGhostObject_getRollingFriction_0=b.asm.Cb).apply(null,arguments)},yd=b._emscripten_bind_btGhostObject_setRestitution_1= +function(){return(yd=b._emscripten_bind_btGhostObject_setRestitution_1=b.asm.Db).apply(null,arguments)},zd=b._emscripten_bind_btGhostObject_setFriction_1=function(){return(zd=b._emscripten_bind_btGhostObject_setFriction_1=b.asm.Eb).apply(null,arguments)},Ad=b._emscripten_bind_btGhostObject_setRollingFriction_1=function(){return(Ad=b._emscripten_bind_btGhostObject_setRollingFriction_1=b.asm.Fb).apply(null,arguments)},Bd=b._emscripten_bind_btGhostObject_getWorldTransform_0=function(){return(Bd=b._emscripten_bind_btGhostObject_getWorldTransform_0= +b.asm.Gb).apply(null,arguments)},Cd=b._emscripten_bind_btGhostObject_getCollisionFlags_0=function(){return(Cd=b._emscripten_bind_btGhostObject_getCollisionFlags_0=b.asm.Hb).apply(null,arguments)},Dd=b._emscripten_bind_btGhostObject_setCollisionFlags_1=function(){return(Dd=b._emscripten_bind_btGhostObject_setCollisionFlags_1=b.asm.Ib).apply(null,arguments)},Ed=b._emscripten_bind_btGhostObject_setWorldTransform_1=function(){return(Ed=b._emscripten_bind_btGhostObject_setWorldTransform_1=b.asm.Jb).apply(null, +arguments)},Fd=b._emscripten_bind_btGhostObject_setCollisionShape_1=function(){return(Fd=b._emscripten_bind_btGhostObject_setCollisionShape_1=b.asm.Kb).apply(null,arguments)},Gd=b._emscripten_bind_btGhostObject_setCcdMotionThreshold_1=function(){return(Gd=b._emscripten_bind_btGhostObject_setCcdMotionThreshold_1=b.asm.Lb).apply(null,arguments)},Hd=b._emscripten_bind_btGhostObject_setCcdSweptSphereRadius_1=function(){return(Hd=b._emscripten_bind_btGhostObject_setCcdSweptSphereRadius_1=b.asm.Mb).apply(null, +arguments)},Id=b._emscripten_bind_btGhostObject_getUserIndex_0=function(){return(Id=b._emscripten_bind_btGhostObject_getUserIndex_0=b.asm.Nb).apply(null,arguments)},Jd=b._emscripten_bind_btGhostObject_setUserIndex_1=function(){return(Jd=b._emscripten_bind_btGhostObject_setUserIndex_1=b.asm.Ob).apply(null,arguments)},Kd=b._emscripten_bind_btGhostObject_getUserPointer_0=function(){return(Kd=b._emscripten_bind_btGhostObject_getUserPointer_0=b.asm.Pb).apply(null,arguments)},Ld=b._emscripten_bind_btGhostObject_setUserPointer_1= +function(){return(Ld=b._emscripten_bind_btGhostObject_setUserPointer_1=b.asm.Qb).apply(null,arguments)},Md=b._emscripten_bind_btGhostObject_getBroadphaseHandle_0=function(){return(Md=b._emscripten_bind_btGhostObject_getBroadphaseHandle_0=b.asm.Rb).apply(null,arguments)},Nd=b._emscripten_bind_btGhostObject___destroy___0=function(){return(Nd=b._emscripten_bind_btGhostObject___destroy___0=b.asm.Sb).apply(null,arguments)},Od=b._emscripten_bind_btConeShape_btConeShape_2=function(){return(Od=b._emscripten_bind_btConeShape_btConeShape_2= +b.asm.Tb).apply(null,arguments)},Pd=b._emscripten_bind_btConeShape_setLocalScaling_1=function(){return(Pd=b._emscripten_bind_btConeShape_setLocalScaling_1=b.asm.Ub).apply(null,arguments)},Qd=b._emscripten_bind_btConeShape_getLocalScaling_0=function(){return(Qd=b._emscripten_bind_btConeShape_getLocalScaling_0=b.asm.Vb).apply(null,arguments)},Rd=b._emscripten_bind_btConeShape_calculateLocalInertia_2=function(){return(Rd=b._emscripten_bind_btConeShape_calculateLocalInertia_2=b.asm.Wb).apply(null,arguments)}, +Sd=b._emscripten_bind_btConeShape___destroy___0=function(){return(Sd=b._emscripten_bind_btConeShape___destroy___0=b.asm.Xb).apply(null,arguments)},Td=b._emscripten_bind_btActionInterface_updateAction_2=function(){return(Td=b._emscripten_bind_btActionInterface_updateAction_2=b.asm.Yb).apply(null,arguments)},Ud=b._emscripten_bind_btActionInterface___destroy___0=function(){return(Ud=b._emscripten_bind_btActionInterface___destroy___0=b.asm.Zb).apply(null,arguments)},Vd=b._emscripten_bind_btVector3_btVector3_0= +function(){return(Vd=b._emscripten_bind_btVector3_btVector3_0=b.asm._b).apply(null,arguments)},Wd=b._emscripten_bind_btVector3_btVector3_3=function(){return(Wd=b._emscripten_bind_btVector3_btVector3_3=b.asm.$b).apply(null,arguments)},Xd=b._emscripten_bind_btVector3_length_0=function(){return(Xd=b._emscripten_bind_btVector3_length_0=b.asm.ac).apply(null,arguments)},Yd=b._emscripten_bind_btVector3_x_0=function(){return(Yd=b._emscripten_bind_btVector3_x_0=b.asm.bc).apply(null,arguments)},Zd=b._emscripten_bind_btVector3_y_0= +function(){return(Zd=b._emscripten_bind_btVector3_y_0=b.asm.cc).apply(null,arguments)},$d=b._emscripten_bind_btVector3_z_0=function(){return($d=b._emscripten_bind_btVector3_z_0=b.asm.dc).apply(null,arguments)},ae=b._emscripten_bind_btVector3_setX_1=function(){return(ae=b._emscripten_bind_btVector3_setX_1=b.asm.ec).apply(null,arguments)},be=b._emscripten_bind_btVector3_setY_1=function(){return(be=b._emscripten_bind_btVector3_setY_1=b.asm.fc).apply(null,arguments)},ce=b._emscripten_bind_btVector3_setZ_1= +function(){return(ce=b._emscripten_bind_btVector3_setZ_1=b.asm.gc).apply(null,arguments)},de=b._emscripten_bind_btVector3_setValue_3=function(){return(de=b._emscripten_bind_btVector3_setValue_3=b.asm.hc).apply(null,arguments)},ee=b._emscripten_bind_btVector3_normalize_0=function(){return(ee=b._emscripten_bind_btVector3_normalize_0=b.asm.ic).apply(null,arguments)},fe=b._emscripten_bind_btVector3_rotate_2=function(){return(fe=b._emscripten_bind_btVector3_rotate_2=b.asm.jc).apply(null,arguments)},ge= +b._emscripten_bind_btVector3_dot_1=function(){return(ge=b._emscripten_bind_btVector3_dot_1=b.asm.kc).apply(null,arguments)},he=b._emscripten_bind_btVector3_op_mul_1=function(){return(he=b._emscripten_bind_btVector3_op_mul_1=b.asm.lc).apply(null,arguments)},ie=b._emscripten_bind_btVector3_op_add_1=function(){return(ie=b._emscripten_bind_btVector3_op_add_1=b.asm.mc).apply(null,arguments)},je=b._emscripten_bind_btVector3_op_sub_1=function(){return(je=b._emscripten_bind_btVector3_op_sub_1=b.asm.nc).apply(null, +arguments)},ke=b._emscripten_bind_btVector3___destroy___0=function(){return(ke=b._emscripten_bind_btVector3___destroy___0=b.asm.oc).apply(null,arguments)},le=b._emscripten_bind_btVehicleRaycaster_castRay_3=function(){return(le=b._emscripten_bind_btVehicleRaycaster_castRay_3=b.asm.pc).apply(null,arguments)},me=b._emscripten_bind_btVehicleRaycaster___destroy___0=function(){return(me=b._emscripten_bind_btVehicleRaycaster___destroy___0=b.asm.qc).apply(null,arguments)},ne=b._emscripten_bind_btQuadWord_x_0= +function(){return(ne=b._emscripten_bind_btQuadWord_x_0=b.asm.rc).apply(null,arguments)},oe=b._emscripten_bind_btQuadWord_y_0=function(){return(oe=b._emscripten_bind_btQuadWord_y_0=b.asm.sc).apply(null,arguments)},pe=b._emscripten_bind_btQuadWord_z_0=function(){return(pe=b._emscripten_bind_btQuadWord_z_0=b.asm.tc).apply(null,arguments)},qe=b._emscripten_bind_btQuadWord_w_0=function(){return(qe=b._emscripten_bind_btQuadWord_w_0=b.asm.uc).apply(null,arguments)},re=b._emscripten_bind_btQuadWord_setX_1= +function(){return(re=b._emscripten_bind_btQuadWord_setX_1=b.asm.vc).apply(null,arguments)},se=b._emscripten_bind_btQuadWord_setY_1=function(){return(se=b._emscripten_bind_btQuadWord_setY_1=b.asm.wc).apply(null,arguments)},te=b._emscripten_bind_btQuadWord_setZ_1=function(){return(te=b._emscripten_bind_btQuadWord_setZ_1=b.asm.xc).apply(null,arguments)},ue=b._emscripten_bind_btQuadWord_setW_1=function(){return(ue=b._emscripten_bind_btQuadWord_setW_1=b.asm.yc).apply(null,arguments)},ve=b._emscripten_bind_btQuadWord___destroy___0= +function(){return(ve=b._emscripten_bind_btQuadWord___destroy___0=b.asm.zc).apply(null,arguments)},we=b._emscripten_bind_btCylinderShape_btCylinderShape_1=function(){return(we=b._emscripten_bind_btCylinderShape_btCylinderShape_1=b.asm.Ac).apply(null,arguments)},xe=b._emscripten_bind_btCylinderShape_setMargin_1=function(){return(xe=b._emscripten_bind_btCylinderShape_setMargin_1=b.asm.Bc).apply(null,arguments)},ye=b._emscripten_bind_btCylinderShape_getMargin_0=function(){return(ye=b._emscripten_bind_btCylinderShape_getMargin_0= +b.asm.Cc).apply(null,arguments)},ze=b._emscripten_bind_btCylinderShape_setLocalScaling_1=function(){return(ze=b._emscripten_bind_btCylinderShape_setLocalScaling_1=b.asm.Dc).apply(null,arguments)},Ae=b._emscripten_bind_btCylinderShape_getLocalScaling_0=function(){return(Ae=b._emscripten_bind_btCylinderShape_getLocalScaling_0=b.asm.Ec).apply(null,arguments)},Be=b._emscripten_bind_btCylinderShape_calculateLocalInertia_2=function(){return(Be=b._emscripten_bind_btCylinderShape_calculateLocalInertia_2= +b.asm.Fc).apply(null,arguments)},Ce=b._emscripten_bind_btCylinderShape___destroy___0=function(){return(Ce=b._emscripten_bind_btCylinderShape___destroy___0=b.asm.Gc).apply(null,arguments)},De=b._emscripten_bind_btDiscreteDynamicsWorld_btDiscreteDynamicsWorld_4=function(){return(De=b._emscripten_bind_btDiscreteDynamicsWorld_btDiscreteDynamicsWorld_4=b.asm.Hc).apply(null,arguments)},Ee=b._emscripten_bind_btDiscreteDynamicsWorld_setGravity_1=function(){return(Ee=b._emscripten_bind_btDiscreteDynamicsWorld_setGravity_1= +b.asm.Ic).apply(null,arguments)},Fe=b._emscripten_bind_btDiscreteDynamicsWorld_getGravity_0=function(){return(Fe=b._emscripten_bind_btDiscreteDynamicsWorld_getGravity_0=b.asm.Jc).apply(null,arguments)},Ge=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_1=function(){return(Ge=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_1=b.asm.Kc).apply(null,arguments)},He=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_3=function(){return(He=b._emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_3= +b.asm.Lc).apply(null,arguments)},Ie=b._emscripten_bind_btDiscreteDynamicsWorld_removeRigidBody_1=function(){return(Ie=b._emscripten_bind_btDiscreteDynamicsWorld_removeRigidBody_1=b.asm.Mc).apply(null,arguments)},Je=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_1=function(){return(Je=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_1=b.asm.Nc).apply(null,arguments)},Ke=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_2=function(){return(Ke=b._emscripten_bind_btDiscreteDynamicsWorld_addConstraint_2= +b.asm.Oc).apply(null,arguments)},Le=b._emscripten_bind_btDiscreteDynamicsWorld_removeConstraint_1=function(){return(Le=b._emscripten_bind_btDiscreteDynamicsWorld_removeConstraint_1=b.asm.Pc).apply(null,arguments)},Me=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_1=function(){return(Me=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_1=b.asm.Qc).apply(null,arguments)},Ne=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_2=function(){return(Ne=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_2= +b.asm.Rc).apply(null,arguments)},Oe=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_3=function(){return(Oe=b._emscripten_bind_btDiscreteDynamicsWorld_stepSimulation_3=b.asm.Sc).apply(null,arguments)},Pe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactAddedCallback_1=function(){return(Pe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactAddedCallback_1=b.asm.Tc).apply(null,arguments)},Qe=b._emscripten_bind_btDiscreteDynamicsWorld_setContactProcessedCallback_1=function(){return(Qe= +b._emscripten_bind_btDiscreteDynamicsWorld_setContactProcessedCallback_1=b.asm.Uc).apply(null,arguments)},Re=b._emscripten_bind_btDiscreteDynamicsWorld_setContactDestroyedCallback_1=function(){return(Re=b._emscripten_bind_btDiscreteDynamicsWorld_setContactDestroyedCallback_1=b.asm.Vc).apply(null,arguments)},Se=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatcher_0=function(){return(Se=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatcher_0=b.asm.Wc).apply(null,arguments)},Te=b._emscripten_bind_btDiscreteDynamicsWorld_rayTest_3= +function(){return(Te=b._emscripten_bind_btDiscreteDynamicsWorld_rayTest_3=b.asm.Xc).apply(null,arguments)},Ue=b._emscripten_bind_btDiscreteDynamicsWorld_getPairCache_0=function(){return(Ue=b._emscripten_bind_btDiscreteDynamicsWorld_getPairCache_0=b.asm.Yc).apply(null,arguments)},Ve=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatchInfo_0=function(){return(Ve=b._emscripten_bind_btDiscreteDynamicsWorld_getDispatchInfo_0=b.asm.Zc).apply(null,arguments)},We=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_1= +function(){return(We=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_1=b.asm._c).apply(null,arguments)},Xe=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_2=function(){return(Xe=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_2=b.asm.$c).apply(null,arguments)},Ye=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_3=function(){return(Ye=b._emscripten_bind_btDiscreteDynamicsWorld_addCollisionObject_3=b.asm.ad).apply(null,arguments)},Ze=b._emscripten_bind_btDiscreteDynamicsWorld_removeCollisionObject_1= +function(){return(Ze=b._emscripten_bind_btDiscreteDynamicsWorld_removeCollisionObject_1=b.asm.bd).apply(null,arguments)},$e=b._emscripten_bind_btDiscreteDynamicsWorld_getBroadphase_0=function(){return($e=b._emscripten_bind_btDiscreteDynamicsWorld_getBroadphase_0=b.asm.cd).apply(null,arguments)},af=b._emscripten_bind_btDiscreteDynamicsWorld_convexSweepTest_5=function(){return(af=b._emscripten_bind_btDiscreteDynamicsWorld_convexSweepTest_5=b.asm.dd).apply(null,arguments)},bf=b._emscripten_bind_btDiscreteDynamicsWorld_contactPairTest_3= +function(){return(bf=b._emscripten_bind_btDiscreteDynamicsWorld_contactPairTest_3=b.asm.ed).apply(null,arguments)},cf=b._emscripten_bind_btDiscreteDynamicsWorld_contactTest_2=function(){return(cf=b._emscripten_bind_btDiscreteDynamicsWorld_contactTest_2=b.asm.fd).apply(null,arguments)},df=b._emscripten_bind_btDiscreteDynamicsWorld_updateSingleAabb_1=function(){return(df=b._emscripten_bind_btDiscreteDynamicsWorld_updateSingleAabb_1=b.asm.gd).apply(null,arguments)},ef=b._emscripten_bind_btDiscreteDynamicsWorld_setDebugDrawer_1= +function(){return(ef=b._emscripten_bind_btDiscreteDynamicsWorld_setDebugDrawer_1=b.asm.hd).apply(null,arguments)},ff=b._emscripten_bind_btDiscreteDynamicsWorld_getDebugDrawer_0=function(){return(ff=b._emscripten_bind_btDiscreteDynamicsWorld_getDebugDrawer_0=b.asm.id).apply(null,arguments)},gf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawWorld_0=function(){return(gf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawWorld_0=b.asm.jd).apply(null,arguments)},hf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawObject_3= +function(){return(hf=b._emscripten_bind_btDiscreteDynamicsWorld_debugDrawObject_3=b.asm.kd).apply(null,arguments)},jf=b._emscripten_bind_btDiscreteDynamicsWorld_addAction_1=function(){return(jf=b._emscripten_bind_btDiscreteDynamicsWorld_addAction_1=b.asm.ld).apply(null,arguments)},kf=b._emscripten_bind_btDiscreteDynamicsWorld_removeAction_1=function(){return(kf=b._emscripten_bind_btDiscreteDynamicsWorld_removeAction_1=b.asm.md).apply(null,arguments)},lf=b._emscripten_bind_btDiscreteDynamicsWorld_getSolverInfo_0= +function(){return(lf=b._emscripten_bind_btDiscreteDynamicsWorld_getSolverInfo_0=b.asm.nd).apply(null,arguments)},mf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_1=function(){return(mf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_1=b.asm.od).apply(null,arguments)},nf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_2=function(){return(nf=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_2=b.asm.pd).apply(null,arguments)}, +of=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_3=function(){return(of=b._emscripten_bind_btDiscreteDynamicsWorld_setInternalTickCallback_3=b.asm.qd).apply(null,arguments)},pf=b._emscripten_bind_btDiscreteDynamicsWorld___destroy___0=function(){return(pf=b._emscripten_bind_btDiscreteDynamicsWorld___destroy___0=b.asm.rd).apply(null,arguments)},qf=b._emscripten_bind_btConvexShape_setLocalScaling_1=function(){return(qf=b._emscripten_bind_btConvexShape_setLocalScaling_1=b.asm.sd).apply(null, +arguments)},rf=b._emscripten_bind_btConvexShape_getLocalScaling_0=function(){return(rf=b._emscripten_bind_btConvexShape_getLocalScaling_0=b.asm.td).apply(null,arguments)},sf=b._emscripten_bind_btConvexShape_calculateLocalInertia_2=function(){return(sf=b._emscripten_bind_btConvexShape_calculateLocalInertia_2=b.asm.ud).apply(null,arguments)},tf=b._emscripten_bind_btConvexShape_setMargin_1=function(){return(tf=b._emscripten_bind_btConvexShape_setMargin_1=b.asm.vd).apply(null,arguments)},uf=b._emscripten_bind_btConvexShape_getMargin_0= +function(){return(uf=b._emscripten_bind_btConvexShape_getMargin_0=b.asm.wd).apply(null,arguments)},vf=b._emscripten_bind_btConvexShape___destroy___0=function(){return(vf=b._emscripten_bind_btConvexShape___destroy___0=b.asm.xd).apply(null,arguments)},wf=b._emscripten_bind_btDispatcher_getNumManifolds_0=function(){return(wf=b._emscripten_bind_btDispatcher_getNumManifolds_0=b.asm.yd).apply(null,arguments)},xf=b._emscripten_bind_btDispatcher_getManifoldByIndexInternal_1=function(){return(xf=b._emscripten_bind_btDispatcher_getManifoldByIndexInternal_1= +b.asm.zd).apply(null,arguments)},yf=b._emscripten_bind_btDispatcher___destroy___0=function(){return(yf=b._emscripten_bind_btDispatcher___destroy___0=b.asm.Ad).apply(null,arguments)},zf=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_3=function(){return(zf=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_3=b.asm.Bd).apply(null,arguments)},Af=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_5=function(){return(Af=b._emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_5= +b.asm.Cd).apply(null,arguments)},Bf=b._emscripten_bind_btGeneric6DofConstraint_setLinearLowerLimit_1=function(){return(Bf=b._emscripten_bind_btGeneric6DofConstraint_setLinearLowerLimit_1=b.asm.Dd).apply(null,arguments)},Cf=b._emscripten_bind_btGeneric6DofConstraint_setLinearUpperLimit_1=function(){return(Cf=b._emscripten_bind_btGeneric6DofConstraint_setLinearUpperLimit_1=b.asm.Ed).apply(null,arguments)},Df=b._emscripten_bind_btGeneric6DofConstraint_setAngularLowerLimit_1=function(){return(Df=b._emscripten_bind_btGeneric6DofConstraint_setAngularLowerLimit_1= +b.asm.Fd).apply(null,arguments)},Ef=b._emscripten_bind_btGeneric6DofConstraint_setAngularUpperLimit_1=function(){return(Ef=b._emscripten_bind_btGeneric6DofConstraint_setAngularUpperLimit_1=b.asm.Gd).apply(null,arguments)},Ff=b._emscripten_bind_btGeneric6DofConstraint_getFrameOffsetA_0=function(){return(Ff=b._emscripten_bind_btGeneric6DofConstraint_getFrameOffsetA_0=b.asm.Hd).apply(null,arguments)},Gf=b._emscripten_bind_btGeneric6DofConstraint_enableFeedback_1=function(){return(Gf=b._emscripten_bind_btGeneric6DofConstraint_enableFeedback_1= +b.asm.Id).apply(null,arguments)},Hf=b._emscripten_bind_btGeneric6DofConstraint_getBreakingImpulseThreshold_0=function(){return(Hf=b._emscripten_bind_btGeneric6DofConstraint_getBreakingImpulseThreshold_0=b.asm.Jd).apply(null,arguments)},If=b._emscripten_bind_btGeneric6DofConstraint_setBreakingImpulseThreshold_1=function(){return(If=b._emscripten_bind_btGeneric6DofConstraint_setBreakingImpulseThreshold_1=b.asm.Kd).apply(null,arguments)},Jf=b._emscripten_bind_btGeneric6DofConstraint_getParam_2=function(){return(Jf= +b._emscripten_bind_btGeneric6DofConstraint_getParam_2=b.asm.Ld).apply(null,arguments)},Kf=b._emscripten_bind_btGeneric6DofConstraint_setParam_3=function(){return(Kf=b._emscripten_bind_btGeneric6DofConstraint_setParam_3=b.asm.Md).apply(null,arguments)},Lf=b._emscripten_bind_btGeneric6DofConstraint___destroy___0=function(){return(Lf=b._emscripten_bind_btGeneric6DofConstraint___destroy___0=b.asm.Nd).apply(null,arguments)},Mf=b._emscripten_bind_btStridingMeshInterface_setScaling_1=function(){return(Mf= +b._emscripten_bind_btStridingMeshInterface_setScaling_1=b.asm.Od).apply(null,arguments)},Nf=b._emscripten_bind_btStridingMeshInterface___destroy___0=function(){return(Nf=b._emscripten_bind_btStridingMeshInterface___destroy___0=b.asm.Pd).apply(null,arguments)},Of=b._emscripten_bind_btMotionState_getWorldTransform_1=function(){return(Of=b._emscripten_bind_btMotionState_getWorldTransform_1=b.asm.Qd).apply(null,arguments)},Pf=b._emscripten_bind_btMotionState_setWorldTransform_1=function(){return(Pf=b._emscripten_bind_btMotionState_setWorldTransform_1= +b.asm.Rd).apply(null,arguments)},Qf=b._emscripten_bind_btMotionState___destroy___0=function(){return(Qf=b._emscripten_bind_btMotionState___destroy___0=b.asm.Sd).apply(null,arguments)},Rf=b._emscripten_bind_ConvexResultCallback_hasHit_0=function(){return(Rf=b._emscripten_bind_ConvexResultCallback_hasHit_0=b.asm.Td).apply(null,arguments)},Sf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterGroup_0=function(){return(Sf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterGroup_0= +b.asm.Ud).apply(null,arguments)},Tf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterGroup_1=function(){return(Tf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterGroup_1=b.asm.Vd).apply(null,arguments)},Uf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterMask_0=function(){return(Uf=b._emscripten_bind_ConvexResultCallback_get_m_collisionFilterMask_0=b.asm.Wd).apply(null,arguments)},Vf=b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterMask_1=function(){return(Vf= +b._emscripten_bind_ConvexResultCallback_set_m_collisionFilterMask_1=b.asm.Xd).apply(null,arguments)},Wf=b._emscripten_bind_ConvexResultCallback_get_m_closestHitFraction_0=function(){return(Wf=b._emscripten_bind_ConvexResultCallback_get_m_closestHitFraction_0=b.asm.Yd).apply(null,arguments)},Xf=b._emscripten_bind_ConvexResultCallback_set_m_closestHitFraction_1=function(){return(Xf=b._emscripten_bind_ConvexResultCallback_set_m_closestHitFraction_1=b.asm.Zd).apply(null,arguments)},Yf=b._emscripten_bind_ConvexResultCallback___destroy___0= +function(){return(Yf=b._emscripten_bind_ConvexResultCallback___destroy___0=b.asm._d).apply(null,arguments)},Zf=b._emscripten_bind_ContactResultCallback_addSingleResult_7=function(){return(Zf=b._emscripten_bind_ContactResultCallback_addSingleResult_7=b.asm.$d).apply(null,arguments)},$f=b._emscripten_bind_ContactResultCallback___destroy___0=function(){return($f=b._emscripten_bind_ContactResultCallback___destroy___0=b.asm.ae).apply(null,arguments)},ag=b._emscripten_bind_btSoftBodySolver___destroy___0= +function(){return(ag=b._emscripten_bind_btSoftBodySolver___destroy___0=b.asm.be).apply(null,arguments)},bg=b._emscripten_bind_RayResultCallback_hasHit_0=function(){return(bg=b._emscripten_bind_RayResultCallback_hasHit_0=b.asm.ce).apply(null,arguments)},cg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterGroup_0=function(){return(cg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterGroup_0=b.asm.de).apply(null,arguments)},dg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterGroup_1= +function(){return(dg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterGroup_1=b.asm.ee).apply(null,arguments)},eg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterMask_0=function(){return(eg=b._emscripten_bind_RayResultCallback_get_m_collisionFilterMask_0=b.asm.fe).apply(null,arguments)},fg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterMask_1=function(){return(fg=b._emscripten_bind_RayResultCallback_set_m_collisionFilterMask_1=b.asm.ge).apply(null,arguments)},gg=b._emscripten_bind_RayResultCallback_get_m_closestHitFraction_0= +function(){return(gg=b._emscripten_bind_RayResultCallback_get_m_closestHitFraction_0=b.asm.he).apply(null,arguments)},hg=b._emscripten_bind_RayResultCallback_set_m_closestHitFraction_1=function(){return(hg=b._emscripten_bind_RayResultCallback_set_m_closestHitFraction_1=b.asm.ie).apply(null,arguments)},ig=b._emscripten_bind_RayResultCallback_get_m_collisionObject_0=function(){return(ig=b._emscripten_bind_RayResultCallback_get_m_collisionObject_0=b.asm.je).apply(null,arguments)},jg=b._emscripten_bind_RayResultCallback_set_m_collisionObject_1= +function(){return(jg=b._emscripten_bind_RayResultCallback_set_m_collisionObject_1=b.asm.ke).apply(null,arguments)},kg=b._emscripten_bind_RayResultCallback___destroy___0=function(){return(kg=b._emscripten_bind_RayResultCallback___destroy___0=b.asm.le).apply(null,arguments)},lg=b._emscripten_bind_btMatrix3x3_setEulerZYX_3=function(){return(lg=b._emscripten_bind_btMatrix3x3_setEulerZYX_3=b.asm.me).apply(null,arguments)},mg=b._emscripten_bind_btMatrix3x3_getRotation_1=function(){return(mg=b._emscripten_bind_btMatrix3x3_getRotation_1= +b.asm.ne).apply(null,arguments)},ng=b._emscripten_bind_btMatrix3x3_getRow_1=function(){return(ng=b._emscripten_bind_btMatrix3x3_getRow_1=b.asm.oe).apply(null,arguments)},og=b._emscripten_bind_btMatrix3x3___destroy___0=function(){return(og=b._emscripten_bind_btMatrix3x3___destroy___0=b.asm.pe).apply(null,arguments)},pg=b._emscripten_bind_btScalarArray_size_0=function(){return(pg=b._emscripten_bind_btScalarArray_size_0=b.asm.qe).apply(null,arguments)},qg=b._emscripten_bind_btScalarArray_at_1=function(){return(qg= +b._emscripten_bind_btScalarArray_at_1=b.asm.re).apply(null,arguments)},rg=b._emscripten_bind_btScalarArray___destroy___0=function(){return(rg=b._emscripten_bind_btScalarArray___destroy___0=b.asm.se).apply(null,arguments)},sg=b._emscripten_bind_Material_get_m_kLST_0=function(){return(sg=b._emscripten_bind_Material_get_m_kLST_0=b.asm.te).apply(null,arguments)},tg=b._emscripten_bind_Material_set_m_kLST_1=function(){return(tg=b._emscripten_bind_Material_set_m_kLST_1=b.asm.ue).apply(null,arguments)},ug= +b._emscripten_bind_Material_get_m_kAST_0=function(){return(ug=b._emscripten_bind_Material_get_m_kAST_0=b.asm.ve).apply(null,arguments)},vg=b._emscripten_bind_Material_set_m_kAST_1=function(){return(vg=b._emscripten_bind_Material_set_m_kAST_1=b.asm.we).apply(null,arguments)},wg=b._emscripten_bind_Material_get_m_kVST_0=function(){return(wg=b._emscripten_bind_Material_get_m_kVST_0=b.asm.xe).apply(null,arguments)},xg=b._emscripten_bind_Material_set_m_kVST_1=function(){return(xg=b._emscripten_bind_Material_set_m_kVST_1= +b.asm.ye).apply(null,arguments)},yg=b._emscripten_bind_Material_get_m_flags_0=function(){return(yg=b._emscripten_bind_Material_get_m_flags_0=b.asm.ze).apply(null,arguments)},zg=b._emscripten_bind_Material_set_m_flags_1=function(){return(zg=b._emscripten_bind_Material_set_m_flags_1=b.asm.Ae).apply(null,arguments)},Ag=b._emscripten_bind_Material___destroy___0=function(){return(Ag=b._emscripten_bind_Material___destroy___0=b.asm.Be).apply(null,arguments)},Bg=b._emscripten_bind_btDispatcherInfo_get_m_timeStep_0= +function(){return(Bg=b._emscripten_bind_btDispatcherInfo_get_m_timeStep_0=b.asm.Ce).apply(null,arguments)},Cg=b._emscripten_bind_btDispatcherInfo_set_m_timeStep_1=function(){return(Cg=b._emscripten_bind_btDispatcherInfo_set_m_timeStep_1=b.asm.De).apply(null,arguments)},Dg=b._emscripten_bind_btDispatcherInfo_get_m_stepCount_0=function(){return(Dg=b._emscripten_bind_btDispatcherInfo_get_m_stepCount_0=b.asm.Ee).apply(null,arguments)},Eg=b._emscripten_bind_btDispatcherInfo_set_m_stepCount_1=function(){return(Eg= +b._emscripten_bind_btDispatcherInfo_set_m_stepCount_1=b.asm.Fe).apply(null,arguments)},Fg=b._emscripten_bind_btDispatcherInfo_get_m_dispatchFunc_0=function(){return(Fg=b._emscripten_bind_btDispatcherInfo_get_m_dispatchFunc_0=b.asm.Ge).apply(null,arguments)},Gg=b._emscripten_bind_btDispatcherInfo_set_m_dispatchFunc_1=function(){return(Gg=b._emscripten_bind_btDispatcherInfo_set_m_dispatchFunc_1=b.asm.He).apply(null,arguments)},Hg=b._emscripten_bind_btDispatcherInfo_get_m_timeOfImpact_0=function(){return(Hg= +b._emscripten_bind_btDispatcherInfo_get_m_timeOfImpact_0=b.asm.Ie).apply(null,arguments)},Ig=b._emscripten_bind_btDispatcherInfo_set_m_timeOfImpact_1=function(){return(Ig=b._emscripten_bind_btDispatcherInfo_set_m_timeOfImpact_1=b.asm.Je).apply(null,arguments)},Jg=b._emscripten_bind_btDispatcherInfo_get_m_useContinuous_0=function(){return(Jg=b._emscripten_bind_btDispatcherInfo_get_m_useContinuous_0=b.asm.Ke).apply(null,arguments)},Kg=b._emscripten_bind_btDispatcherInfo_set_m_useContinuous_1=function(){return(Kg= +b._emscripten_bind_btDispatcherInfo_set_m_useContinuous_1=b.asm.Le).apply(null,arguments)},Lg=b._emscripten_bind_btDispatcherInfo_get_m_enableSatConvex_0=function(){return(Lg=b._emscripten_bind_btDispatcherInfo_get_m_enableSatConvex_0=b.asm.Me).apply(null,arguments)},Mg=b._emscripten_bind_btDispatcherInfo_set_m_enableSatConvex_1=function(){return(Mg=b._emscripten_bind_btDispatcherInfo_set_m_enableSatConvex_1=b.asm.Ne).apply(null,arguments)},Ng=b._emscripten_bind_btDispatcherInfo_get_m_enableSPU_0= +function(){return(Ng=b._emscripten_bind_btDispatcherInfo_get_m_enableSPU_0=b.asm.Oe).apply(null,arguments)},Og=b._emscripten_bind_btDispatcherInfo_set_m_enableSPU_1=function(){return(Og=b._emscripten_bind_btDispatcherInfo_set_m_enableSPU_1=b.asm.Pe).apply(null,arguments)},Pg=b._emscripten_bind_btDispatcherInfo_get_m_useEpa_0=function(){return(Pg=b._emscripten_bind_btDispatcherInfo_get_m_useEpa_0=b.asm.Qe).apply(null,arguments)},Qg=b._emscripten_bind_btDispatcherInfo_set_m_useEpa_1=function(){return(Qg= +b._emscripten_bind_btDispatcherInfo_set_m_useEpa_1=b.asm.Re).apply(null,arguments)},Rg=b._emscripten_bind_btDispatcherInfo_get_m_allowedCcdPenetration_0=function(){return(Rg=b._emscripten_bind_btDispatcherInfo_get_m_allowedCcdPenetration_0=b.asm.Se).apply(null,arguments)},Sg=b._emscripten_bind_btDispatcherInfo_set_m_allowedCcdPenetration_1=function(){return(Sg=b._emscripten_bind_btDispatcherInfo_set_m_allowedCcdPenetration_1=b.asm.Te).apply(null,arguments)},Tg=b._emscripten_bind_btDispatcherInfo_get_m_useConvexConservativeDistanceUtil_0= +function(){return(Tg=b._emscripten_bind_btDispatcherInfo_get_m_useConvexConservativeDistanceUtil_0=b.asm.Ue).apply(null,arguments)},Ug=b._emscripten_bind_btDispatcherInfo_set_m_useConvexConservativeDistanceUtil_1=function(){return(Ug=b._emscripten_bind_btDispatcherInfo_set_m_useConvexConservativeDistanceUtil_1=b.asm.Ve).apply(null,arguments)},Vg=b._emscripten_bind_btDispatcherInfo_get_m_convexConservativeDistanceThreshold_0=function(){return(Vg=b._emscripten_bind_btDispatcherInfo_get_m_convexConservativeDistanceThreshold_0= +b.asm.We).apply(null,arguments)},Wg=b._emscripten_bind_btDispatcherInfo_set_m_convexConservativeDistanceThreshold_1=function(){return(Wg=b._emscripten_bind_btDispatcherInfo_set_m_convexConservativeDistanceThreshold_1=b.asm.Xe).apply(null,arguments)},Xg=b._emscripten_bind_btDispatcherInfo___destroy___0=function(){return(Xg=b._emscripten_bind_btDispatcherInfo___destroy___0=b.asm.Ye).apply(null,arguments)},Yg=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_chassisConnectionCS_0=function(){return(Yg= +b._emscripten_bind_btWheelInfoConstructionInfo_get_m_chassisConnectionCS_0=b.asm.Ze).apply(null,arguments)},Zg=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_chassisConnectionCS_1=function(){return(Zg=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_chassisConnectionCS_1=b.asm._e).apply(null,arguments)},$g=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelDirectionCS_0=function(){return($g=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelDirectionCS_0=b.asm.$e).apply(null, +arguments)},ah=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelDirectionCS_1=function(){return(ah=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelDirectionCS_1=b.asm.af).apply(null,arguments)},bh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelAxleCS_0=function(){return(bh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelAxleCS_0=b.asm.bf).apply(null,arguments)},ch=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelAxleCS_1=function(){return(ch=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelAxleCS_1= +b.asm.cf).apply(null,arguments)},dh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionRestLength_0=function(){return(dh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionRestLength_0=b.asm.df).apply(null,arguments)},eh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionRestLength_1=function(){return(eh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionRestLength_1=b.asm.ef).apply(null,arguments)},fh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionTravelCm_0= +function(){return(fh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionTravelCm_0=b.asm.ff).apply(null,arguments)},gh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionTravelCm_1=function(){return(gh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionTravelCm_1=b.asm.gf).apply(null,arguments)},hh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelRadius_0=function(){return(hh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelRadius_0=b.asm.hf).apply(null, +arguments)},ih=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelRadius_1=function(){return(ih=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelRadius_1=b.asm.jf).apply(null,arguments)},jh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionStiffness_0=function(){return(jh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_suspensionStiffness_0=b.asm.kf).apply(null,arguments)},kh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionStiffness_1=function(){return(kh= +b._emscripten_bind_btWheelInfoConstructionInfo_set_m_suspensionStiffness_1=b.asm.lf).apply(null,arguments)},lh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingCompression_0=function(){return(lh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingCompression_0=b.asm.mf).apply(null,arguments)},mh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingCompression_1=function(){return(mh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingCompression_1= +b.asm.nf).apply(null,arguments)},nh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingRelaxation_0=function(){return(nh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_wheelsDampingRelaxation_0=b.asm.of).apply(null,arguments)},oh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingRelaxation_1=function(){return(oh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_wheelsDampingRelaxation_1=b.asm.pf).apply(null,arguments)},ph=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_frictionSlip_0= +function(){return(ph=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_frictionSlip_0=b.asm.qf).apply(null,arguments)},qh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_frictionSlip_1=function(){return(qh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_frictionSlip_1=b.asm.rf).apply(null,arguments)},rh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionForce_0=function(){return(rh=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_maxSuspensionForce_0=b.asm.sf).apply(null, +arguments)},sh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionForce_1=function(){return(sh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_maxSuspensionForce_1=b.asm.tf).apply(null,arguments)},th=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_bIsFrontWheel_0=function(){return(th=b._emscripten_bind_btWheelInfoConstructionInfo_get_m_bIsFrontWheel_0=b.asm.uf).apply(null,arguments)},uh=b._emscripten_bind_btWheelInfoConstructionInfo_set_m_bIsFrontWheel_1=function(){return(uh= +b._emscripten_bind_btWheelInfoConstructionInfo_set_m_bIsFrontWheel_1=b.asm.vf).apply(null,arguments)},vh=b._emscripten_bind_btWheelInfoConstructionInfo___destroy___0=function(){return(vh=b._emscripten_bind_btWheelInfoConstructionInfo___destroy___0=b.asm.wf).apply(null,arguments)},wh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_1=function(){return(wh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_1=b.asm.xf).apply(null,arguments)},xh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_2= +function(){return(xh=b._emscripten_bind_btConvexTriangleMeshShape_btConvexTriangleMeshShape_2=b.asm.yf).apply(null,arguments)},yh=b._emscripten_bind_btConvexTriangleMeshShape_setLocalScaling_1=function(){return(yh=b._emscripten_bind_btConvexTriangleMeshShape_setLocalScaling_1=b.asm.zf).apply(null,arguments)},zh=b._emscripten_bind_btConvexTriangleMeshShape_getLocalScaling_0=function(){return(zh=b._emscripten_bind_btConvexTriangleMeshShape_getLocalScaling_0=b.asm.Af).apply(null,arguments)},Ah=b._emscripten_bind_btConvexTriangleMeshShape_calculateLocalInertia_2= +function(){return(Ah=b._emscripten_bind_btConvexTriangleMeshShape_calculateLocalInertia_2=b.asm.Bf).apply(null,arguments)},Bh=b._emscripten_bind_btConvexTriangleMeshShape_setMargin_1=function(){return(Bh=b._emscripten_bind_btConvexTriangleMeshShape_setMargin_1=b.asm.Cf).apply(null,arguments)},Ch=b._emscripten_bind_btConvexTriangleMeshShape_getMargin_0=function(){return(Ch=b._emscripten_bind_btConvexTriangleMeshShape_getMargin_0=b.asm.Df).apply(null,arguments)},Dh=b._emscripten_bind_btConvexTriangleMeshShape___destroy___0= +function(){return(Dh=b._emscripten_bind_btConvexTriangleMeshShape___destroy___0=b.asm.Ef).apply(null,arguments)},Eh=b._emscripten_bind_btBroadphaseInterface_getOverlappingPairCache_0=function(){return(Eh=b._emscripten_bind_btBroadphaseInterface_getOverlappingPairCache_0=b.asm.Ff).apply(null,arguments)},Fh=b._emscripten_bind_btBroadphaseInterface___destroy___0=function(){return(Fh=b._emscripten_bind_btBroadphaseInterface___destroy___0=b.asm.Gf).apply(null,arguments)},Gh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_3= +function(){return(Gh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_3=b.asm.Hf).apply(null,arguments)},Hh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_4=function(){return(Hh=b._emscripten_bind_btRigidBodyConstructionInfo_btRigidBodyConstructionInfo_4=b.asm.If).apply(null,arguments)},Ih=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearDamping_0=function(){return(Ih=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearDamping_0= +b.asm.Jf).apply(null,arguments)},Jh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearDamping_1=function(){return(Jh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearDamping_1=b.asm.Kf).apply(null,arguments)},Kh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularDamping_0=function(){return(Kh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularDamping_0=b.asm.Lf).apply(null,arguments)},Lh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularDamping_1=function(){return(Lh= +b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularDamping_1=b.asm.Mf).apply(null,arguments)},Mh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_friction_0=function(){return(Mh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_friction_0=b.asm.Nf).apply(null,arguments)},Nh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_friction_1=function(){return(Nh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_friction_1=b.asm.Of).apply(null,arguments)},Oh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_rollingFriction_0= +function(){return(Oh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_rollingFriction_0=b.asm.Pf).apply(null,arguments)},Ph=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_rollingFriction_1=function(){return(Ph=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_rollingFriction_1=b.asm.Qf).apply(null,arguments)},Qh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_restitution_0=function(){return(Qh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_restitution_0=b.asm.Rf).apply(null, +arguments)},Rh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_restitution_1=function(){return(Rh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_restitution_1=b.asm.Sf).apply(null,arguments)},Sh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearSleepingThreshold_0=function(){return(Sh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_linearSleepingThreshold_0=b.asm.Tf).apply(null,arguments)},Th=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearSleepingThreshold_1=function(){return(Th= +b._emscripten_bind_btRigidBodyConstructionInfo_set_m_linearSleepingThreshold_1=b.asm.Uf).apply(null,arguments)},Uh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularSleepingThreshold_0=function(){return(Uh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_angularSleepingThreshold_0=b.asm.Vf).apply(null,arguments)},Vh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularSleepingThreshold_1=function(){return(Vh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_angularSleepingThreshold_1= +b.asm.Wf).apply(null,arguments)},Wh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDamping_0=function(){return(Wh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDamping_0=b.asm.Xf).apply(null,arguments)},Xh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDamping_1=function(){return(Xh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDamping_1=b.asm.Yf).apply(null,arguments)},Yh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDampingFactor_0= +function(){return(Yh=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalDampingFactor_0=b.asm.Zf).apply(null,arguments)},Zh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDampingFactor_1=function(){return(Zh=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalDampingFactor_1=b.asm._f).apply(null,arguments)},$h=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalLinearDampingThresholdSqr_0=function(){return($h=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalLinearDampingThresholdSqr_0= +b.asm.$f).apply(null,arguments)},ai=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalLinearDampingThresholdSqr_1=function(){return(ai=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalLinearDampingThresholdSqr_1=b.asm.ag).apply(null,arguments)},bi=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingThresholdSqr_0=function(){return(bi=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingThresholdSqr_0=b.asm.bg).apply(null, +arguments)},ci=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingThresholdSqr_1=function(){return(ci=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingThresholdSqr_1=b.asm.cg).apply(null,arguments)},di=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingFactor_0=function(){return(di=b._emscripten_bind_btRigidBodyConstructionInfo_get_m_additionalAngularDampingFactor_0=b.asm.dg).apply(null,arguments)},ei=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingFactor_1= +function(){return(ei=b._emscripten_bind_btRigidBodyConstructionInfo_set_m_additionalAngularDampingFactor_1=b.asm.eg).apply(null,arguments)},fi=b._emscripten_bind_btRigidBodyConstructionInfo___destroy___0=function(){return(fi=b._emscripten_bind_btRigidBodyConstructionInfo___destroy___0=b.asm.fg).apply(null,arguments)},gi=b._emscripten_bind_btCollisionConfiguration___destroy___0=function(){return(gi=b._emscripten_bind_btCollisionConfiguration___destroy___0=b.asm.gg).apply(null,arguments)},hi=b._emscripten_bind_btPersistentManifold_btPersistentManifold_0= +function(){return(hi=b._emscripten_bind_btPersistentManifold_btPersistentManifold_0=b.asm.hg).apply(null,arguments)},ii=b._emscripten_bind_btPersistentManifold_getBody0_0=function(){return(ii=b._emscripten_bind_btPersistentManifold_getBody0_0=b.asm.ig).apply(null,arguments)},ji=b._emscripten_bind_btPersistentManifold_getBody1_0=function(){return(ji=b._emscripten_bind_btPersistentManifold_getBody1_0=b.asm.jg).apply(null,arguments)},ki=b._emscripten_bind_btPersistentManifold_getNumContacts_0=function(){return(ki= +b._emscripten_bind_btPersistentManifold_getNumContacts_0=b.asm.kg).apply(null,arguments)},li=b._emscripten_bind_btPersistentManifold_getContactPoint_1=function(){return(li=b._emscripten_bind_btPersistentManifold_getContactPoint_1=b.asm.lg).apply(null,arguments)},mi=b._emscripten_bind_btPersistentManifold___destroy___0=function(){return(mi=b._emscripten_bind_btPersistentManifold___destroy___0=b.asm.mg).apply(null,arguments)},ni=b._emscripten_bind_btCompoundShape_btCompoundShape_0=function(){return(ni= +b._emscripten_bind_btCompoundShape_btCompoundShape_0=b.asm.ng).apply(null,arguments)},oi=b._emscripten_bind_btCompoundShape_btCompoundShape_1=function(){return(oi=b._emscripten_bind_btCompoundShape_btCompoundShape_1=b.asm.og).apply(null,arguments)},pi=b._emscripten_bind_btCompoundShape_addChildShape_2=function(){return(pi=b._emscripten_bind_btCompoundShape_addChildShape_2=b.asm.pg).apply(null,arguments)},qi=b._emscripten_bind_btCompoundShape_removeChildShape_1=function(){return(qi=b._emscripten_bind_btCompoundShape_removeChildShape_1= +b.asm.qg).apply(null,arguments)},ri=b._emscripten_bind_btCompoundShape_removeChildShapeByIndex_1=function(){return(ri=b._emscripten_bind_btCompoundShape_removeChildShapeByIndex_1=b.asm.rg).apply(null,arguments)},si=b._emscripten_bind_btCompoundShape_getNumChildShapes_0=function(){return(si=b._emscripten_bind_btCompoundShape_getNumChildShapes_0=b.asm.sg).apply(null,arguments)},ti=b._emscripten_bind_btCompoundShape_getChildShape_1=function(){return(ti=b._emscripten_bind_btCompoundShape_getChildShape_1= +b.asm.tg).apply(null,arguments)},ui=b._emscripten_bind_btCompoundShape_updateChildTransform_2=function(){return(ui=b._emscripten_bind_btCompoundShape_updateChildTransform_2=b.asm.ug).apply(null,arguments)},vi=b._emscripten_bind_btCompoundShape_updateChildTransform_3=function(){return(vi=b._emscripten_bind_btCompoundShape_updateChildTransform_3=b.asm.vg).apply(null,arguments)},wi=b._emscripten_bind_btCompoundShape_setMargin_1=function(){return(wi=b._emscripten_bind_btCompoundShape_setMargin_1=b.asm.wg).apply(null, +arguments)},xi=b._emscripten_bind_btCompoundShape_getMargin_0=function(){return(xi=b._emscripten_bind_btCompoundShape_getMargin_0=b.asm.xg).apply(null,arguments)},yi=b._emscripten_bind_btCompoundShape_setLocalScaling_1=function(){return(yi=b._emscripten_bind_btCompoundShape_setLocalScaling_1=b.asm.yg).apply(null,arguments)},zi=b._emscripten_bind_btCompoundShape_getLocalScaling_0=function(){return(zi=b._emscripten_bind_btCompoundShape_getLocalScaling_0=b.asm.zg).apply(null,arguments)},Ai=b._emscripten_bind_btCompoundShape_calculateLocalInertia_2= +function(){return(Ai=b._emscripten_bind_btCompoundShape_calculateLocalInertia_2=b.asm.Ag).apply(null,arguments)},Bi=b._emscripten_bind_btCompoundShape___destroy___0=function(){return(Bi=b._emscripten_bind_btCompoundShape___destroy___0=b.asm.Bg).apply(null,arguments)},Ci=b._emscripten_bind_ClosestConvexResultCallback_ClosestConvexResultCallback_2=function(){return(Ci=b._emscripten_bind_ClosestConvexResultCallback_ClosestConvexResultCallback_2=b.asm.Cg).apply(null,arguments)},Di=b._emscripten_bind_ClosestConvexResultCallback_hasHit_0= +function(){return(Di=b._emscripten_bind_ClosestConvexResultCallback_hasHit_0=b.asm.Dg).apply(null,arguments)},Ei=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexFromWorld_0=function(){return(Ei=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexFromWorld_0=b.asm.Eg).apply(null,arguments)},Fi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexFromWorld_1=function(){return(Fi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexFromWorld_1=b.asm.Fg).apply(null,arguments)}, +Gi=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexToWorld_0=function(){return(Gi=b._emscripten_bind_ClosestConvexResultCallback_get_m_convexToWorld_0=b.asm.Gg).apply(null,arguments)},Hi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexToWorld_1=function(){return(Hi=b._emscripten_bind_ClosestConvexResultCallback_set_m_convexToWorld_1=b.asm.Hg).apply(null,arguments)},Ii=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitNormalWorld_0=function(){return(Ii=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitNormalWorld_0= +b.asm.Ig).apply(null,arguments)},Ji=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitNormalWorld_1=function(){return(Ji=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitNormalWorld_1=b.asm.Jg).apply(null,arguments)},Ki=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitPointWorld_0=function(){return(Ki=b._emscripten_bind_ClosestConvexResultCallback_get_m_hitPointWorld_0=b.asm.Kg).apply(null,arguments)},Li=b._emscripten_bind_ClosestConvexResultCallback_set_m_hitPointWorld_1=function(){return(Li= +b._emscripten_bind_ClosestConvexResultCallback_set_m_hitPointWorld_1=b.asm.Lg).apply(null,arguments)},Mi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterGroup_0=function(){return(Mi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterGroup_0=b.asm.Mg).apply(null,arguments)},Ni=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterGroup_1=function(){return(Ni=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterGroup_1=b.asm.Ng).apply(null, +arguments)},Oi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterMask_0=function(){return(Oi=b._emscripten_bind_ClosestConvexResultCallback_get_m_collisionFilterMask_0=b.asm.Og).apply(null,arguments)},Pi=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterMask_1=function(){return(Pi=b._emscripten_bind_ClosestConvexResultCallback_set_m_collisionFilterMask_1=b.asm.Pg).apply(null,arguments)},Qi=b._emscripten_bind_ClosestConvexResultCallback_get_m_closestHitFraction_0= +function(){return(Qi=b._emscripten_bind_ClosestConvexResultCallback_get_m_closestHitFraction_0=b.asm.Qg).apply(null,arguments)},Ri=b._emscripten_bind_ClosestConvexResultCallback_set_m_closestHitFraction_1=function(){return(Ri=b._emscripten_bind_ClosestConvexResultCallback_set_m_closestHitFraction_1=b.asm.Rg).apply(null,arguments)},Si=b._emscripten_bind_ClosestConvexResultCallback___destroy___0=function(){return(Si=b._emscripten_bind_ClosestConvexResultCallback___destroy___0=b.asm.Sg).apply(null,arguments)}, +Ti=b._emscripten_bind_AllHitsRayResultCallback_AllHitsRayResultCallback_2=function(){return(Ti=b._emscripten_bind_AllHitsRayResultCallback_AllHitsRayResultCallback_2=b.asm.Tg).apply(null,arguments)},Ui=b._emscripten_bind_AllHitsRayResultCallback_hasHit_0=function(){return(Ui=b._emscripten_bind_AllHitsRayResultCallback_hasHit_0=b.asm.Ug).apply(null,arguments)},Vi=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObjects_0=function(){return(Vi=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObjects_0= +b.asm.Vg).apply(null,arguments)},Wi=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObjects_1=function(){return(Wi=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObjects_1=b.asm.Wg).apply(null,arguments)},Xi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayFromWorld_0=function(){return(Xi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayFromWorld_0=b.asm.Xg).apply(null,arguments)},Yi=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayFromWorld_1=function(){return(Yi= +b._emscripten_bind_AllHitsRayResultCallback_set_m_rayFromWorld_1=b.asm.Yg).apply(null,arguments)},Zi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayToWorld_0=function(){return(Zi=b._emscripten_bind_AllHitsRayResultCallback_get_m_rayToWorld_0=b.asm.Zg).apply(null,arguments)},$i=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayToWorld_1=function(){return($i=b._emscripten_bind_AllHitsRayResultCallback_set_m_rayToWorld_1=b.asm._g).apply(null,arguments)},aj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitNormalWorld_0= +function(){return(aj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitNormalWorld_0=b.asm.$g).apply(null,arguments)},bj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitNormalWorld_1=function(){return(bj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitNormalWorld_1=b.asm.ah).apply(null,arguments)},cj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitPointWorld_0=function(){return(cj=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitPointWorld_0=b.asm.bh).apply(null,arguments)}, +dj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitPointWorld_1=function(){return(dj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitPointWorld_1=b.asm.ch).apply(null,arguments)},ej=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitFractions_0=function(){return(ej=b._emscripten_bind_AllHitsRayResultCallback_get_m_hitFractions_0=b.asm.dh).apply(null,arguments)},fj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitFractions_1=function(){return(fj=b._emscripten_bind_AllHitsRayResultCallback_set_m_hitFractions_1= +b.asm.eh).apply(null,arguments)},gj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterGroup_0=function(){return(gj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterGroup_0=b.asm.fh).apply(null,arguments)},hj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterGroup_1=function(){return(hj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterGroup_1=b.asm.gh).apply(null,arguments)},ij=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterMask_0= +function(){return(ij=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionFilterMask_0=b.asm.hh).apply(null,arguments)},jj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterMask_1=function(){return(jj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionFilterMask_1=b.asm.ih).apply(null,arguments)},kj=b._emscripten_bind_AllHitsRayResultCallback_get_m_closestHitFraction_0=function(){return(kj=b._emscripten_bind_AllHitsRayResultCallback_get_m_closestHitFraction_0=b.asm.jh).apply(null, +arguments)},lj=b._emscripten_bind_AllHitsRayResultCallback_set_m_closestHitFraction_1=function(){return(lj=b._emscripten_bind_AllHitsRayResultCallback_set_m_closestHitFraction_1=b.asm.kh).apply(null,arguments)},mj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObject_0=function(){return(mj=b._emscripten_bind_AllHitsRayResultCallback_get_m_collisionObject_0=b.asm.lh).apply(null,arguments)},nj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObject_1=function(){return(nj=b._emscripten_bind_AllHitsRayResultCallback_set_m_collisionObject_1= +b.asm.mh).apply(null,arguments)},oj=b._emscripten_bind_AllHitsRayResultCallback___destroy___0=function(){return(oj=b._emscripten_bind_AllHitsRayResultCallback___destroy___0=b.asm.nh).apply(null,arguments)},pj=b._emscripten_bind_tMaterialArray_size_0=function(){return(pj=b._emscripten_bind_tMaterialArray_size_0=b.asm.oh).apply(null,arguments)},qj=b._emscripten_bind_tMaterialArray_at_1=function(){return(qj=b._emscripten_bind_tMaterialArray_at_1=b.asm.ph).apply(null,arguments)},rj=b._emscripten_bind_tMaterialArray___destroy___0= +function(){return(rj=b._emscripten_bind_tMaterialArray___destroy___0=b.asm.qh).apply(null,arguments)},sj=b._emscripten_bind_btDefaultVehicleRaycaster_btDefaultVehicleRaycaster_1=function(){return(sj=b._emscripten_bind_btDefaultVehicleRaycaster_btDefaultVehicleRaycaster_1=b.asm.rh).apply(null,arguments)},tj=b._emscripten_bind_btDefaultVehicleRaycaster_castRay_3=function(){return(tj=b._emscripten_bind_btDefaultVehicleRaycaster_castRay_3=b.asm.sh).apply(null,arguments)},uj=b._emscripten_bind_btDefaultVehicleRaycaster___destroy___0= +function(){return(uj=b._emscripten_bind_btDefaultVehicleRaycaster___destroy___0=b.asm.th).apply(null,arguments)},vj=b._emscripten_bind_btEmptyShape_btEmptyShape_0=function(){return(vj=b._emscripten_bind_btEmptyShape_btEmptyShape_0=b.asm.uh).apply(null,arguments)},wj=b._emscripten_bind_btEmptyShape_setLocalScaling_1=function(){return(wj=b._emscripten_bind_btEmptyShape_setLocalScaling_1=b.asm.vh).apply(null,arguments)},xj=b._emscripten_bind_btEmptyShape_getLocalScaling_0=function(){return(xj=b._emscripten_bind_btEmptyShape_getLocalScaling_0= +b.asm.wh).apply(null,arguments)},yj=b._emscripten_bind_btEmptyShape_calculateLocalInertia_2=function(){return(yj=b._emscripten_bind_btEmptyShape_calculateLocalInertia_2=b.asm.xh).apply(null,arguments)},zj=b._emscripten_bind_btEmptyShape___destroy___0=function(){return(zj=b._emscripten_bind_btEmptyShape___destroy___0=b.asm.yh).apply(null,arguments)},Aj=b._emscripten_bind_btConstraintSetting_btConstraintSetting_0=function(){return(Aj=b._emscripten_bind_btConstraintSetting_btConstraintSetting_0=b.asm.zh).apply(null, +arguments)},Bj=b._emscripten_bind_btConstraintSetting_get_m_tau_0=function(){return(Bj=b._emscripten_bind_btConstraintSetting_get_m_tau_0=b.asm.Ah).apply(null,arguments)},Cj=b._emscripten_bind_btConstraintSetting_set_m_tau_1=function(){return(Cj=b._emscripten_bind_btConstraintSetting_set_m_tau_1=b.asm.Bh).apply(null,arguments)},Dj=b._emscripten_bind_btConstraintSetting_get_m_damping_0=function(){return(Dj=b._emscripten_bind_btConstraintSetting_get_m_damping_0=b.asm.Ch).apply(null,arguments)},Ej=b._emscripten_bind_btConstraintSetting_set_m_damping_1= +function(){return(Ej=b._emscripten_bind_btConstraintSetting_set_m_damping_1=b.asm.Dh).apply(null,arguments)},Fj=b._emscripten_bind_btConstraintSetting_get_m_impulseClamp_0=function(){return(Fj=b._emscripten_bind_btConstraintSetting_get_m_impulseClamp_0=b.asm.Eh).apply(null,arguments)},Gj=b._emscripten_bind_btConstraintSetting_set_m_impulseClamp_1=function(){return(Gj=b._emscripten_bind_btConstraintSetting_set_m_impulseClamp_1=b.asm.Fh).apply(null,arguments)},Hj=b._emscripten_bind_btConstraintSetting___destroy___0= +function(){return(Hj=b._emscripten_bind_btConstraintSetting___destroy___0=b.asm.Gh).apply(null,arguments)},Ij=b._emscripten_bind_LocalShapeInfo_get_m_shapePart_0=function(){return(Ij=b._emscripten_bind_LocalShapeInfo_get_m_shapePart_0=b.asm.Hh).apply(null,arguments)},Jj=b._emscripten_bind_LocalShapeInfo_set_m_shapePart_1=function(){return(Jj=b._emscripten_bind_LocalShapeInfo_set_m_shapePart_1=b.asm.Ih).apply(null,arguments)},Kj=b._emscripten_bind_LocalShapeInfo_get_m_triangleIndex_0=function(){return(Kj= +b._emscripten_bind_LocalShapeInfo_get_m_triangleIndex_0=b.asm.Jh).apply(null,arguments)},Lj=b._emscripten_bind_LocalShapeInfo_set_m_triangleIndex_1=function(){return(Lj=b._emscripten_bind_LocalShapeInfo_set_m_triangleIndex_1=b.asm.Kh).apply(null,arguments)},Mj=b._emscripten_bind_LocalShapeInfo___destroy___0=function(){return(Mj=b._emscripten_bind_LocalShapeInfo___destroy___0=b.asm.Lh).apply(null,arguments)},Nj=b._emscripten_bind_btRigidBody_btRigidBody_1=function(){return(Nj=b._emscripten_bind_btRigidBody_btRigidBody_1= +b.asm.Mh).apply(null,arguments)},Oj=b._emscripten_bind_btRigidBody_getCenterOfMassTransform_0=function(){return(Oj=b._emscripten_bind_btRigidBody_getCenterOfMassTransform_0=b.asm.Nh).apply(null,arguments)},Pj=b._emscripten_bind_btRigidBody_setCenterOfMassTransform_1=function(){return(Pj=b._emscripten_bind_btRigidBody_setCenterOfMassTransform_1=b.asm.Oh).apply(null,arguments)},Qj=b._emscripten_bind_btRigidBody_setSleepingThresholds_2=function(){return(Qj=b._emscripten_bind_btRigidBody_setSleepingThresholds_2= +b.asm.Ph).apply(null,arguments)},Rj=b._emscripten_bind_btRigidBody_getLinearDamping_0=function(){return(Rj=b._emscripten_bind_btRigidBody_getLinearDamping_0=b.asm.Qh).apply(null,arguments)},Sj=b._emscripten_bind_btRigidBody_getAngularDamping_0=function(){return(Sj=b._emscripten_bind_btRigidBody_getAngularDamping_0=b.asm.Rh).apply(null,arguments)},Tj=b._emscripten_bind_btRigidBody_setDamping_2=function(){return(Tj=b._emscripten_bind_btRigidBody_setDamping_2=b.asm.Sh).apply(null,arguments)},Uj=b._emscripten_bind_btRigidBody_setMassProps_2= +function(){return(Uj=b._emscripten_bind_btRigidBody_setMassProps_2=b.asm.Th).apply(null,arguments)},Vj=b._emscripten_bind_btRigidBody_getLinearFactor_0=function(){return(Vj=b._emscripten_bind_btRigidBody_getLinearFactor_0=b.asm.Uh).apply(null,arguments)},Wj=b._emscripten_bind_btRigidBody_setLinearFactor_1=function(){return(Wj=b._emscripten_bind_btRigidBody_setLinearFactor_1=b.asm.Vh).apply(null,arguments)},Xj=b._emscripten_bind_btRigidBody_applyTorque_1=function(){return(Xj=b._emscripten_bind_btRigidBody_applyTorque_1= +b.asm.Wh).apply(null,arguments)},Yj=b._emscripten_bind_btRigidBody_applyLocalTorque_1=function(){return(Yj=b._emscripten_bind_btRigidBody_applyLocalTorque_1=b.asm.Xh).apply(null,arguments)},Zj=b._emscripten_bind_btRigidBody_applyForce_2=function(){return(Zj=b._emscripten_bind_btRigidBody_applyForce_2=b.asm.Yh).apply(null,arguments)},ak=b._emscripten_bind_btRigidBody_applyCentralForce_1=function(){return(ak=b._emscripten_bind_btRigidBody_applyCentralForce_1=b.asm.Zh).apply(null,arguments)},bk=b._emscripten_bind_btRigidBody_applyCentralLocalForce_1= +function(){return(bk=b._emscripten_bind_btRigidBody_applyCentralLocalForce_1=b.asm._h).apply(null,arguments)},ck=b._emscripten_bind_btRigidBody_applyTorqueImpulse_1=function(){return(ck=b._emscripten_bind_btRigidBody_applyTorqueImpulse_1=b.asm.$h).apply(null,arguments)},dk=b._emscripten_bind_btRigidBody_applyImpulse_2=function(){return(dk=b._emscripten_bind_btRigidBody_applyImpulse_2=b.asm.ai).apply(null,arguments)},ek=b._emscripten_bind_btRigidBody_applyCentralImpulse_1=function(){return(ek=b._emscripten_bind_btRigidBody_applyCentralImpulse_1= +b.asm.bi).apply(null,arguments)},fk=b._emscripten_bind_btRigidBody_updateInertiaTensor_0=function(){return(fk=b._emscripten_bind_btRigidBody_updateInertiaTensor_0=b.asm.ci).apply(null,arguments)},gk=b._emscripten_bind_btRigidBody_getLinearVelocity_0=function(){return(gk=b._emscripten_bind_btRigidBody_getLinearVelocity_0=b.asm.di).apply(null,arguments)},hk=b._emscripten_bind_btRigidBody_getAngularVelocity_0=function(){return(hk=b._emscripten_bind_btRigidBody_getAngularVelocity_0=b.asm.ei).apply(null, +arguments)},ik=b._emscripten_bind_btRigidBody_setLinearVelocity_1=function(){return(ik=b._emscripten_bind_btRigidBody_setLinearVelocity_1=b.asm.fi).apply(null,arguments)},jk=b._emscripten_bind_btRigidBody_setAngularVelocity_1=function(){return(jk=b._emscripten_bind_btRigidBody_setAngularVelocity_1=b.asm.gi).apply(null,arguments)},kk=b._emscripten_bind_btRigidBody_getMotionState_0=function(){return(kk=b._emscripten_bind_btRigidBody_getMotionState_0=b.asm.hi).apply(null,arguments)},lk=b._emscripten_bind_btRigidBody_setMotionState_1= +function(){return(lk=b._emscripten_bind_btRigidBody_setMotionState_1=b.asm.ii).apply(null,arguments)},mk=b._emscripten_bind_btRigidBody_getAngularFactor_0=function(){return(mk=b._emscripten_bind_btRigidBody_getAngularFactor_0=b.asm.ji).apply(null,arguments)},nk=b._emscripten_bind_btRigidBody_setAngularFactor_1=function(){return(nk=b._emscripten_bind_btRigidBody_setAngularFactor_1=b.asm.ki).apply(null,arguments)},ok=b._emscripten_bind_btRigidBody_upcast_1=function(){return(ok=b._emscripten_bind_btRigidBody_upcast_1= +b.asm.li).apply(null,arguments)},pk=b._emscripten_bind_btRigidBody_getAabb_2=function(){return(pk=b._emscripten_bind_btRigidBody_getAabb_2=b.asm.mi).apply(null,arguments)},qk=b._emscripten_bind_btRigidBody_applyGravity_0=function(){return(qk=b._emscripten_bind_btRigidBody_applyGravity_0=b.asm.ni).apply(null,arguments)},rk=b._emscripten_bind_btRigidBody_getGravity_0=function(){return(rk=b._emscripten_bind_btRigidBody_getGravity_0=b.asm.oi).apply(null,arguments)},sk=b._emscripten_bind_btRigidBody_setGravity_1= +function(){return(sk=b._emscripten_bind_btRigidBody_setGravity_1=b.asm.pi).apply(null,arguments)},tk=b._emscripten_bind_btRigidBody_getBroadphaseProxy_0=function(){return(tk=b._emscripten_bind_btRigidBody_getBroadphaseProxy_0=b.asm.qi).apply(null,arguments)},uk=b._emscripten_bind_btRigidBody_clearForces_0=function(){return(uk=b._emscripten_bind_btRigidBody_clearForces_0=b.asm.ri).apply(null,arguments)},vk=b._emscripten_bind_btRigidBody_setAnisotropicFriction_2=function(){return(vk=b._emscripten_bind_btRigidBody_setAnisotropicFriction_2= +b.asm.si).apply(null,arguments)},wk=b._emscripten_bind_btRigidBody_getCollisionShape_0=function(){return(wk=b._emscripten_bind_btRigidBody_getCollisionShape_0=b.asm.ti).apply(null,arguments)},xk=b._emscripten_bind_btRigidBody_setContactProcessingThreshold_1=function(){return(xk=b._emscripten_bind_btRigidBody_setContactProcessingThreshold_1=b.asm.ui).apply(null,arguments)},yk=b._emscripten_bind_btRigidBody_setActivationState_1=function(){return(yk=b._emscripten_bind_btRigidBody_setActivationState_1= +b.asm.vi).apply(null,arguments)},zk=b._emscripten_bind_btRigidBody_forceActivationState_1=function(){return(zk=b._emscripten_bind_btRigidBody_forceActivationState_1=b.asm.wi).apply(null,arguments)},Ak=b._emscripten_bind_btRigidBody_activate_0=function(){return(Ak=b._emscripten_bind_btRigidBody_activate_0=b.asm.xi).apply(null,arguments)},Bk=b._emscripten_bind_btRigidBody_activate_1=function(){return(Bk=b._emscripten_bind_btRigidBody_activate_1=b.asm.yi).apply(null,arguments)},Ck=b._emscripten_bind_btRigidBody_isActive_0= +function(){return(Ck=b._emscripten_bind_btRigidBody_isActive_0=b.asm.zi).apply(null,arguments)},Dk=b._emscripten_bind_btRigidBody_isKinematicObject_0=function(){return(Dk=b._emscripten_bind_btRigidBody_isKinematicObject_0=b.asm.Ai).apply(null,arguments)},Ek=b._emscripten_bind_btRigidBody_isStaticObject_0=function(){return(Ek=b._emscripten_bind_btRigidBody_isStaticObject_0=b.asm.Bi).apply(null,arguments)},Fk=b._emscripten_bind_btRigidBody_isStaticOrKinematicObject_0=function(){return(Fk=b._emscripten_bind_btRigidBody_isStaticOrKinematicObject_0= +b.asm.Ci).apply(null,arguments)},Gk=b._emscripten_bind_btRigidBody_getRestitution_0=function(){return(Gk=b._emscripten_bind_btRigidBody_getRestitution_0=b.asm.Di).apply(null,arguments)},Hk=b._emscripten_bind_btRigidBody_getFriction_0=function(){return(Hk=b._emscripten_bind_btRigidBody_getFriction_0=b.asm.Ei).apply(null,arguments)},Ik=b._emscripten_bind_btRigidBody_getRollingFriction_0=function(){return(Ik=b._emscripten_bind_btRigidBody_getRollingFriction_0=b.asm.Fi).apply(null,arguments)},Jk=b._emscripten_bind_btRigidBody_setRestitution_1= +function(){return(Jk=b._emscripten_bind_btRigidBody_setRestitution_1=b.asm.Gi).apply(null,arguments)},Kk=b._emscripten_bind_btRigidBody_setFriction_1=function(){return(Kk=b._emscripten_bind_btRigidBody_setFriction_1=b.asm.Hi).apply(null,arguments)},Lk=b._emscripten_bind_btRigidBody_setRollingFriction_1=function(){return(Lk=b._emscripten_bind_btRigidBody_setRollingFriction_1=b.asm.Ii).apply(null,arguments)},Mk=b._emscripten_bind_btRigidBody_getWorldTransform_0=function(){return(Mk=b._emscripten_bind_btRigidBody_getWorldTransform_0= +b.asm.Ji).apply(null,arguments)},Nk=b._emscripten_bind_btRigidBody_getCollisionFlags_0=function(){return(Nk=b._emscripten_bind_btRigidBody_getCollisionFlags_0=b.asm.Ki).apply(null,arguments)},Ok=b._emscripten_bind_btRigidBody_setCollisionFlags_1=function(){return(Ok=b._emscripten_bind_btRigidBody_setCollisionFlags_1=b.asm.Li).apply(null,arguments)},Pk=b._emscripten_bind_btRigidBody_setWorldTransform_1=function(){return(Pk=b._emscripten_bind_btRigidBody_setWorldTransform_1=b.asm.Mi).apply(null,arguments)}, +Qk=b._emscripten_bind_btRigidBody_setCollisionShape_1=function(){return(Qk=b._emscripten_bind_btRigidBody_setCollisionShape_1=b.asm.Ni).apply(null,arguments)},Rk=b._emscripten_bind_btRigidBody_setCcdMotionThreshold_1=function(){return(Rk=b._emscripten_bind_btRigidBody_setCcdMotionThreshold_1=b.asm.Oi).apply(null,arguments)},Sk=b._emscripten_bind_btRigidBody_setCcdSweptSphereRadius_1=function(){return(Sk=b._emscripten_bind_btRigidBody_setCcdSweptSphereRadius_1=b.asm.Pi).apply(null,arguments)},Tk=b._emscripten_bind_btRigidBody_getUserIndex_0= +function(){return(Tk=b._emscripten_bind_btRigidBody_getUserIndex_0=b.asm.Qi).apply(null,arguments)},Uk=b._emscripten_bind_btRigidBody_setUserIndex_1=function(){return(Uk=b._emscripten_bind_btRigidBody_setUserIndex_1=b.asm.Ri).apply(null,arguments)},Vk=b._emscripten_bind_btRigidBody_getUserPointer_0=function(){return(Vk=b._emscripten_bind_btRigidBody_getUserPointer_0=b.asm.Si).apply(null,arguments)},Wk=b._emscripten_bind_btRigidBody_setUserPointer_1=function(){return(Wk=b._emscripten_bind_btRigidBody_setUserPointer_1= +b.asm.Ti).apply(null,arguments)},Xk=b._emscripten_bind_btRigidBody_getBroadphaseHandle_0=function(){return(Xk=b._emscripten_bind_btRigidBody_getBroadphaseHandle_0=b.asm.Ui).apply(null,arguments)},Yk=b._emscripten_bind_btRigidBody___destroy___0=function(){return(Yk=b._emscripten_bind_btRigidBody___destroy___0=b.asm.Vi).apply(null,arguments)},Zk=b._emscripten_bind_btIndexedMeshArray_size_0=function(){return(Zk=b._emscripten_bind_btIndexedMeshArray_size_0=b.asm.Wi).apply(null,arguments)},$k=b._emscripten_bind_btIndexedMeshArray_at_1= +function(){return($k=b._emscripten_bind_btIndexedMeshArray_at_1=b.asm.Xi).apply(null,arguments)},al=b._emscripten_bind_btIndexedMeshArray___destroy___0=function(){return(al=b._emscripten_bind_btIndexedMeshArray___destroy___0=b.asm.Yi).apply(null,arguments)},bl=b._emscripten_bind_btDbvtBroadphase_btDbvtBroadphase_0=function(){return(bl=b._emscripten_bind_btDbvtBroadphase_btDbvtBroadphase_0=b.asm.Zi).apply(null,arguments)},cl=b._emscripten_bind_btDbvtBroadphase___destroy___0=function(){return(cl=b._emscripten_bind_btDbvtBroadphase___destroy___0= +b.asm._i).apply(null,arguments)},dl=b._emscripten_bind_btHeightfieldTerrainShape_btHeightfieldTerrainShape_9=function(){return(dl=b._emscripten_bind_btHeightfieldTerrainShape_btHeightfieldTerrainShape_9=b.asm.$i).apply(null,arguments)},el=b._emscripten_bind_btHeightfieldTerrainShape_setMargin_1=function(){return(el=b._emscripten_bind_btHeightfieldTerrainShape_setMargin_1=b.asm.aj).apply(null,arguments)},fl=b._emscripten_bind_btHeightfieldTerrainShape_getMargin_0=function(){return(fl=b._emscripten_bind_btHeightfieldTerrainShape_getMargin_0= +b.asm.bj).apply(null,arguments)},gl=b._emscripten_bind_btHeightfieldTerrainShape_setLocalScaling_1=function(){return(gl=b._emscripten_bind_btHeightfieldTerrainShape_setLocalScaling_1=b.asm.cj).apply(null,arguments)},hl=b._emscripten_bind_btHeightfieldTerrainShape_getLocalScaling_0=function(){return(hl=b._emscripten_bind_btHeightfieldTerrainShape_getLocalScaling_0=b.asm.dj).apply(null,arguments)},il=b._emscripten_bind_btHeightfieldTerrainShape_calculateLocalInertia_2=function(){return(il=b._emscripten_bind_btHeightfieldTerrainShape_calculateLocalInertia_2= +b.asm.ej).apply(null,arguments)},jl=b._emscripten_bind_btHeightfieldTerrainShape___destroy___0=function(){return(jl=b._emscripten_bind_btHeightfieldTerrainShape___destroy___0=b.asm.fj).apply(null,arguments)},kl=b._emscripten_bind_btDefaultSoftBodySolver_btDefaultSoftBodySolver_0=function(){return(kl=b._emscripten_bind_btDefaultSoftBodySolver_btDefaultSoftBodySolver_0=b.asm.gj).apply(null,arguments)},ll=b._emscripten_bind_btDefaultSoftBodySolver___destroy___0=function(){return(ll=b._emscripten_bind_btDefaultSoftBodySolver___destroy___0= +b.asm.hj).apply(null,arguments)},ml=b._emscripten_bind_btCollisionDispatcher_btCollisionDispatcher_1=function(){return(ml=b._emscripten_bind_btCollisionDispatcher_btCollisionDispatcher_1=b.asm.ij).apply(null,arguments)},nl=b._emscripten_bind_btCollisionDispatcher_getNumManifolds_0=function(){return(nl=b._emscripten_bind_btCollisionDispatcher_getNumManifolds_0=b.asm.jj).apply(null,arguments)},ol=b._emscripten_bind_btCollisionDispatcher_getManifoldByIndexInternal_1=function(){return(ol=b._emscripten_bind_btCollisionDispatcher_getManifoldByIndexInternal_1= +b.asm.kj).apply(null,arguments)},pl=b._emscripten_bind_btCollisionDispatcher___destroy___0=function(){return(pl=b._emscripten_bind_btCollisionDispatcher___destroy___0=b.asm.lj).apply(null,arguments)},ql=b._emscripten_bind_btAxisSweep3_btAxisSweep3_2=function(){return(ql=b._emscripten_bind_btAxisSweep3_btAxisSweep3_2=b.asm.mj).apply(null,arguments)},rl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_3=function(){return(rl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_3=b.asm.nj).apply(null,arguments)}, +sl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_4=function(){return(sl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_4=b.asm.oj).apply(null,arguments)},tl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_5=function(){return(tl=b._emscripten_bind_btAxisSweep3_btAxisSweep3_5=b.asm.pj).apply(null,arguments)},ul=b._emscripten_bind_btAxisSweep3___destroy___0=function(){return(ul=b._emscripten_bind_btAxisSweep3___destroy___0=b.asm.qj).apply(null,arguments)},vl=b._emscripten_bind_VoidPtr___destroy___0=function(){return(vl= +b._emscripten_bind_VoidPtr___destroy___0=b.asm.rj).apply(null,arguments)},wl=b._emscripten_bind_btSoftBodyWorldInfo_btSoftBodyWorldInfo_0=function(){return(wl=b._emscripten_bind_btSoftBodyWorldInfo_btSoftBodyWorldInfo_0=b.asm.sj).apply(null,arguments)},xl=b._emscripten_bind_btSoftBodyWorldInfo_get_air_density_0=function(){return(xl=b._emscripten_bind_btSoftBodyWorldInfo_get_air_density_0=b.asm.tj).apply(null,arguments)},yl=b._emscripten_bind_btSoftBodyWorldInfo_set_air_density_1=function(){return(yl= +b._emscripten_bind_btSoftBodyWorldInfo_set_air_density_1=b.asm.uj).apply(null,arguments)},zl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_density_0=function(){return(zl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_density_0=b.asm.vj).apply(null,arguments)},Al=b._emscripten_bind_btSoftBodyWorldInfo_set_water_density_1=function(){return(Al=b._emscripten_bind_btSoftBodyWorldInfo_set_water_density_1=b.asm.wj).apply(null,arguments)},Bl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_offset_0= +function(){return(Bl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_offset_0=b.asm.xj).apply(null,arguments)},Cl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_offset_1=function(){return(Cl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_offset_1=b.asm.yj).apply(null,arguments)},Dl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_maxDisplacement_0=function(){return(Dl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_maxDisplacement_0=b.asm.zj).apply(null,arguments)},El=b._emscripten_bind_btSoftBodyWorldInfo_set_m_maxDisplacement_1= +function(){return(El=b._emscripten_bind_btSoftBodyWorldInfo_set_m_maxDisplacement_1=b.asm.Aj).apply(null,arguments)},Fl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_normal_0=function(){return(Fl=b._emscripten_bind_btSoftBodyWorldInfo_get_water_normal_0=b.asm.Bj).apply(null,arguments)},Gl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_normal_1=function(){return(Gl=b._emscripten_bind_btSoftBodyWorldInfo_set_water_normal_1=b.asm.Cj).apply(null,arguments)},Hl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_broadphase_0= +function(){return(Hl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_broadphase_0=b.asm.Dj).apply(null,arguments)},Il=b._emscripten_bind_btSoftBodyWorldInfo_set_m_broadphase_1=function(){return(Il=b._emscripten_bind_btSoftBodyWorldInfo_set_m_broadphase_1=b.asm.Ej).apply(null,arguments)},Jl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_dispatcher_0=function(){return(Jl=b._emscripten_bind_btSoftBodyWorldInfo_get_m_dispatcher_0=b.asm.Fj).apply(null,arguments)},Kl=b._emscripten_bind_btSoftBodyWorldInfo_set_m_dispatcher_1= +function(){return(Kl=b._emscripten_bind_btSoftBodyWorldInfo_set_m_dispatcher_1=b.asm.Gj).apply(null,arguments)},Ll=b._emscripten_bind_btSoftBodyWorldInfo_get_m_gravity_0=function(){return(Ll=b._emscripten_bind_btSoftBodyWorldInfo_get_m_gravity_0=b.asm.Hj).apply(null,arguments)},Ml=b._emscripten_bind_btSoftBodyWorldInfo_set_m_gravity_1=function(){return(Ml=b._emscripten_bind_btSoftBodyWorldInfo_set_m_gravity_1=b.asm.Ij).apply(null,arguments)},Nl=b._emscripten_bind_btSoftBodyWorldInfo___destroy___0= +function(){return(Nl=b._emscripten_bind_btSoftBodyWorldInfo___destroy___0=b.asm.Jj).apply(null,arguments)},Ol=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_2=function(){return(Ol=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_2=b.asm.Kj).apply(null,arguments)},Pl=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_4=function(){return(Pl=b._emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_4=b.asm.Lj).apply(null,arguments)},Ql=b._emscripten_bind_btConeTwistConstraint_setLimit_2= +function(){return(Ql=b._emscripten_bind_btConeTwistConstraint_setLimit_2=b.asm.Mj).apply(null,arguments)},Rl=b._emscripten_bind_btConeTwistConstraint_setAngularOnly_1=function(){return(Rl=b._emscripten_bind_btConeTwistConstraint_setAngularOnly_1=b.asm.Nj).apply(null,arguments)},Sl=b._emscripten_bind_btConeTwistConstraint_setDamping_1=function(){return(Sl=b._emscripten_bind_btConeTwistConstraint_setDamping_1=b.asm.Oj).apply(null,arguments)},Tl=b._emscripten_bind_btConeTwistConstraint_enableMotor_1= +function(){return(Tl=b._emscripten_bind_btConeTwistConstraint_enableMotor_1=b.asm.Pj).apply(null,arguments)},Ul=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulse_1=function(){return(Ul=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulse_1=b.asm.Qj).apply(null,arguments)},Vl=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulseNormalized_1=function(){return(Vl=b._emscripten_bind_btConeTwistConstraint_setMaxMotorImpulseNormalized_1=b.asm.Rj).apply(null,arguments)},Wl=b._emscripten_bind_btConeTwistConstraint_setMotorTarget_1= +function(){return(Wl=b._emscripten_bind_btConeTwistConstraint_setMotorTarget_1=b.asm.Sj).apply(null,arguments)},Xl=b._emscripten_bind_btConeTwistConstraint_setMotorTargetInConstraintSpace_1=function(){return(Xl=b._emscripten_bind_btConeTwistConstraint_setMotorTargetInConstraintSpace_1=b.asm.Tj).apply(null,arguments)},Yl=b._emscripten_bind_btConeTwistConstraint_enableFeedback_1=function(){return(Yl=b._emscripten_bind_btConeTwistConstraint_enableFeedback_1=b.asm.Uj).apply(null,arguments)},Zl=b._emscripten_bind_btConeTwistConstraint_getBreakingImpulseThreshold_0= +function(){return(Zl=b._emscripten_bind_btConeTwistConstraint_getBreakingImpulseThreshold_0=b.asm.Vj).apply(null,arguments)},$l=b._emscripten_bind_btConeTwistConstraint_setBreakingImpulseThreshold_1=function(){return($l=b._emscripten_bind_btConeTwistConstraint_setBreakingImpulseThreshold_1=b.asm.Wj).apply(null,arguments)},am=b._emscripten_bind_btConeTwistConstraint_getParam_2=function(){return(am=b._emscripten_bind_btConeTwistConstraint_getParam_2=b.asm.Xj).apply(null,arguments)},bm=b._emscripten_bind_btConeTwistConstraint_setParam_3= +function(){return(bm=b._emscripten_bind_btConeTwistConstraint_setParam_3=b.asm.Yj).apply(null,arguments)},cm=b._emscripten_bind_btConeTwistConstraint___destroy___0=function(){return(cm=b._emscripten_bind_btConeTwistConstraint___destroy___0=b.asm.Zj).apply(null,arguments)},dm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_2=function(){return(dm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_2=b.asm._j).apply(null,arguments)},em=b._emscripten_bind_btHingeConstraint_btHingeConstraint_3= +function(){return(em=b._emscripten_bind_btHingeConstraint_btHingeConstraint_3=b.asm.$j).apply(null,arguments)},fm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_4=function(){return(fm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_4=b.asm.ak).apply(null,arguments)},gm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_5=function(){return(gm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_5=b.asm.bk).apply(null,arguments)},hm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_6= +function(){return(hm=b._emscripten_bind_btHingeConstraint_btHingeConstraint_6=b.asm.ck).apply(null,arguments)},im=b._emscripten_bind_btHingeConstraint_btHingeConstraint_7=function(){return(im=b._emscripten_bind_btHingeConstraint_btHingeConstraint_7=b.asm.dk).apply(null,arguments)},jm=b._emscripten_bind_btHingeConstraint_setLimit_4=function(){return(jm=b._emscripten_bind_btHingeConstraint_setLimit_4=b.asm.ek).apply(null,arguments)},km=b._emscripten_bind_btHingeConstraint_setLimit_5=function(){return(km= +b._emscripten_bind_btHingeConstraint_setLimit_5=b.asm.fk).apply(null,arguments)},lm=b._emscripten_bind_btHingeConstraint_enableAngularMotor_3=function(){return(lm=b._emscripten_bind_btHingeConstraint_enableAngularMotor_3=b.asm.gk).apply(null,arguments)},mm=b._emscripten_bind_btHingeConstraint_setAngularOnly_1=function(){return(mm=b._emscripten_bind_btHingeConstraint_setAngularOnly_1=b.asm.hk).apply(null,arguments)},nm=b._emscripten_bind_btHingeConstraint_enableMotor_1=function(){return(nm=b._emscripten_bind_btHingeConstraint_enableMotor_1= +b.asm.ik).apply(null,arguments)},om=b._emscripten_bind_btHingeConstraint_setMaxMotorImpulse_1=function(){return(om=b._emscripten_bind_btHingeConstraint_setMaxMotorImpulse_1=b.asm.jk).apply(null,arguments)},pm=b._emscripten_bind_btHingeConstraint_setMotorTarget_2=function(){return(pm=b._emscripten_bind_btHingeConstraint_setMotorTarget_2=b.asm.kk).apply(null,arguments)},qm=b._emscripten_bind_btHingeConstraint_enableFeedback_1=function(){return(qm=b._emscripten_bind_btHingeConstraint_enableFeedback_1= +b.asm.lk).apply(null,arguments)},rm=b._emscripten_bind_btHingeConstraint_getBreakingImpulseThreshold_0=function(){return(rm=b._emscripten_bind_btHingeConstraint_getBreakingImpulseThreshold_0=b.asm.mk).apply(null,arguments)},sm=b._emscripten_bind_btHingeConstraint_setBreakingImpulseThreshold_1=function(){return(sm=b._emscripten_bind_btHingeConstraint_setBreakingImpulseThreshold_1=b.asm.nk).apply(null,arguments)},tm=b._emscripten_bind_btHingeConstraint_getParam_2=function(){return(tm=b._emscripten_bind_btHingeConstraint_getParam_2= +b.asm.ok).apply(null,arguments)},um=b._emscripten_bind_btHingeConstraint_setParam_3=function(){return(um=b._emscripten_bind_btHingeConstraint_setParam_3=b.asm.pk).apply(null,arguments)},wm=b._emscripten_bind_btHingeConstraint___destroy___0=function(){return(wm=b._emscripten_bind_btHingeConstraint___destroy___0=b.asm.qk).apply(null,arguments)},xm=b._emscripten_bind_btConeShapeZ_btConeShapeZ_2=function(){return(xm=b._emscripten_bind_btConeShapeZ_btConeShapeZ_2=b.asm.rk).apply(null,arguments)},ym=b._emscripten_bind_btConeShapeZ_setLocalScaling_1= +function(){return(ym=b._emscripten_bind_btConeShapeZ_setLocalScaling_1=b.asm.sk).apply(null,arguments)},zm=b._emscripten_bind_btConeShapeZ_getLocalScaling_0=function(){return(zm=b._emscripten_bind_btConeShapeZ_getLocalScaling_0=b.asm.tk).apply(null,arguments)},Am=b._emscripten_bind_btConeShapeZ_calculateLocalInertia_2=function(){return(Am=b._emscripten_bind_btConeShapeZ_calculateLocalInertia_2=b.asm.uk).apply(null,arguments)},Bm=b._emscripten_bind_btConeShapeZ___destroy___0=function(){return(Bm=b._emscripten_bind_btConeShapeZ___destroy___0= +b.asm.vk).apply(null,arguments)},Cm=b._emscripten_bind_btConeShapeX_btConeShapeX_2=function(){return(Cm=b._emscripten_bind_btConeShapeX_btConeShapeX_2=b.asm.wk).apply(null,arguments)},Dm=b._emscripten_bind_btConeShapeX_setLocalScaling_1=function(){return(Dm=b._emscripten_bind_btConeShapeX_setLocalScaling_1=b.asm.xk).apply(null,arguments)},Em=b._emscripten_bind_btConeShapeX_getLocalScaling_0=function(){return(Em=b._emscripten_bind_btConeShapeX_getLocalScaling_0=b.asm.yk).apply(null,arguments)},Fm= +b._emscripten_bind_btConeShapeX_calculateLocalInertia_2=function(){return(Fm=b._emscripten_bind_btConeShapeX_calculateLocalInertia_2=b.asm.zk).apply(null,arguments)},Gm=b._emscripten_bind_btConeShapeX___destroy___0=function(){return(Gm=b._emscripten_bind_btConeShapeX___destroy___0=b.asm.Ak).apply(null,arguments)},Hm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_0=function(){return(Hm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_0=b.asm.Bk).apply(null,arguments)},Im=b._emscripten_bind_btTriangleMesh_btTriangleMesh_1= +function(){return(Im=b._emscripten_bind_btTriangleMesh_btTriangleMesh_1=b.asm.Ck).apply(null,arguments)},Jm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_2=function(){return(Jm=b._emscripten_bind_btTriangleMesh_btTriangleMesh_2=b.asm.Dk).apply(null,arguments)},Km=b._emscripten_bind_btTriangleMesh_addTriangle_3=function(){return(Km=b._emscripten_bind_btTriangleMesh_addTriangle_3=b.asm.Ek).apply(null,arguments)},Lm=b._emscripten_bind_btTriangleMesh_addTriangle_4=function(){return(Lm=b._emscripten_bind_btTriangleMesh_addTriangle_4= +b.asm.Fk).apply(null,arguments)},Mm=b._emscripten_bind_btTriangleMesh_findOrAddVertex_2=function(){return(Mm=b._emscripten_bind_btTriangleMesh_findOrAddVertex_2=b.asm.Gk).apply(null,arguments)},Nm=b._emscripten_bind_btTriangleMesh_addIndex_1=function(){return(Nm=b._emscripten_bind_btTriangleMesh_addIndex_1=b.asm.Hk).apply(null,arguments)},Om=b._emscripten_bind_btTriangleMesh_getIndexedMeshArray_0=function(){return(Om=b._emscripten_bind_btTriangleMesh_getIndexedMeshArray_0=b.asm.Ik).apply(null,arguments)}, +Pm=b._emscripten_bind_btTriangleMesh_setScaling_1=function(){return(Pm=b._emscripten_bind_btTriangleMesh_setScaling_1=b.asm.Jk).apply(null,arguments)},Qm=b._emscripten_bind_btTriangleMesh___destroy___0=function(){return(Qm=b._emscripten_bind_btTriangleMesh___destroy___0=b.asm.Kk).apply(null,arguments)},Rm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_0=function(){return(Rm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_0=b.asm.Lk).apply(null,arguments)},Sm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_1= +function(){return(Sm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_1=b.asm.Mk).apply(null,arguments)},Tm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_2=function(){return(Tm=b._emscripten_bind_btConvexHullShape_btConvexHullShape_2=b.asm.Nk).apply(null,arguments)},Um=b._emscripten_bind_btConvexHullShape_addPoint_1=function(){return(Um=b._emscripten_bind_btConvexHullShape_addPoint_1=b.asm.Ok).apply(null,arguments)},Vm=b._emscripten_bind_btConvexHullShape_addPoint_2=function(){return(Vm= +b._emscripten_bind_btConvexHullShape_addPoint_2=b.asm.Pk).apply(null,arguments)},Wm=b._emscripten_bind_btConvexHullShape_setMargin_1=function(){return(Wm=b._emscripten_bind_btConvexHullShape_setMargin_1=b.asm.Qk).apply(null,arguments)},Xm=b._emscripten_bind_btConvexHullShape_getMargin_0=function(){return(Xm=b._emscripten_bind_btConvexHullShape_getMargin_0=b.asm.Rk).apply(null,arguments)},Ym=b._emscripten_bind_btConvexHullShape_getNumVertices_0=function(){return(Ym=b._emscripten_bind_btConvexHullShape_getNumVertices_0= +b.asm.Sk).apply(null,arguments)},Zm=b._emscripten_bind_btConvexHullShape_initializePolyhedralFeatures_1=function(){return(Zm=b._emscripten_bind_btConvexHullShape_initializePolyhedralFeatures_1=b.asm.Tk).apply(null,arguments)},$m=b._emscripten_bind_btConvexHullShape_recalcLocalAabb_0=function(){return($m=b._emscripten_bind_btConvexHullShape_recalcLocalAabb_0=b.asm.Uk).apply(null,arguments)},an=b._emscripten_bind_btConvexHullShape_getConvexPolyhedron_0=function(){return(an=b._emscripten_bind_btConvexHullShape_getConvexPolyhedron_0= +b.asm.Vk).apply(null,arguments)},bn=b._emscripten_bind_btConvexHullShape_setLocalScaling_1=function(){return(bn=b._emscripten_bind_btConvexHullShape_setLocalScaling_1=b.asm.Wk).apply(null,arguments)},cn=b._emscripten_bind_btConvexHullShape_getLocalScaling_0=function(){return(cn=b._emscripten_bind_btConvexHullShape_getLocalScaling_0=b.asm.Xk).apply(null,arguments)},dn=b._emscripten_bind_btConvexHullShape_calculateLocalInertia_2=function(){return(dn=b._emscripten_bind_btConvexHullShape_calculateLocalInertia_2= +b.asm.Yk).apply(null,arguments)},en=b._emscripten_bind_btConvexHullShape___destroy___0=function(){return(en=b._emscripten_bind_btConvexHullShape___destroy___0=b.asm.Zk).apply(null,arguments)},fn=b._emscripten_bind_btVehicleTuning_btVehicleTuning_0=function(){return(fn=b._emscripten_bind_btVehicleTuning_btVehicleTuning_0=b.asm._k).apply(null,arguments)},gn=b._emscripten_bind_btVehicleTuning_get_m_suspensionStiffness_0=function(){return(gn=b._emscripten_bind_btVehicleTuning_get_m_suspensionStiffness_0= +b.asm.$k).apply(null,arguments)},hn=b._emscripten_bind_btVehicleTuning_set_m_suspensionStiffness_1=function(){return(hn=b._emscripten_bind_btVehicleTuning_set_m_suspensionStiffness_1=b.asm.al).apply(null,arguments)},jn=b._emscripten_bind_btVehicleTuning_get_m_suspensionCompression_0=function(){return(jn=b._emscripten_bind_btVehicleTuning_get_m_suspensionCompression_0=b.asm.bl).apply(null,arguments)},kn=b._emscripten_bind_btVehicleTuning_set_m_suspensionCompression_1=function(){return(kn=b._emscripten_bind_btVehicleTuning_set_m_suspensionCompression_1= +b.asm.cl).apply(null,arguments)},ln=b._emscripten_bind_btVehicleTuning_get_m_suspensionDamping_0=function(){return(ln=b._emscripten_bind_btVehicleTuning_get_m_suspensionDamping_0=b.asm.dl).apply(null,arguments)},mn=b._emscripten_bind_btVehicleTuning_set_m_suspensionDamping_1=function(){return(mn=b._emscripten_bind_btVehicleTuning_set_m_suspensionDamping_1=b.asm.el).apply(null,arguments)},nn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionTravelCm_0=function(){return(nn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionTravelCm_0= +b.asm.fl).apply(null,arguments)},on=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionTravelCm_1=function(){return(on=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionTravelCm_1=b.asm.gl).apply(null,arguments)},pn=b._emscripten_bind_btVehicleTuning_get_m_frictionSlip_0=function(){return(pn=b._emscripten_bind_btVehicleTuning_get_m_frictionSlip_0=b.asm.hl).apply(null,arguments)},qn=b._emscripten_bind_btVehicleTuning_set_m_frictionSlip_1=function(){return(qn=b._emscripten_bind_btVehicleTuning_set_m_frictionSlip_1= +b.asm.il).apply(null,arguments)},rn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionForce_0=function(){return(rn=b._emscripten_bind_btVehicleTuning_get_m_maxSuspensionForce_0=b.asm.jl).apply(null,arguments)},sn=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionForce_1=function(){return(sn=b._emscripten_bind_btVehicleTuning_set_m_maxSuspensionForce_1=b.asm.kl).apply(null,arguments)},tn=b._emscripten_bind_btCollisionObjectWrapper_getWorldTransform_0=function(){return(tn=b._emscripten_bind_btCollisionObjectWrapper_getWorldTransform_0= +b.asm.ll).apply(null,arguments)},un=b._emscripten_bind_btCollisionObjectWrapper_getCollisionObject_0=function(){return(un=b._emscripten_bind_btCollisionObjectWrapper_getCollisionObject_0=b.asm.ml).apply(null,arguments)},vn=b._emscripten_bind_btCollisionObjectWrapper_getCollisionShape_0=function(){return(vn=b._emscripten_bind_btCollisionObjectWrapper_getCollisionShape_0=b.asm.nl).apply(null,arguments)},wn=b._emscripten_bind_btShapeHull_btShapeHull_1=function(){return(wn=b._emscripten_bind_btShapeHull_btShapeHull_1= +b.asm.ol).apply(null,arguments)},xn=b._emscripten_bind_btShapeHull_buildHull_1=function(){return(xn=b._emscripten_bind_btShapeHull_buildHull_1=b.asm.pl).apply(null,arguments)},yn=b._emscripten_bind_btShapeHull_numVertices_0=function(){return(yn=b._emscripten_bind_btShapeHull_numVertices_0=b.asm.ql).apply(null,arguments)},zn=b._emscripten_bind_btShapeHull_getVertexPointer_0=function(){return(zn=b._emscripten_bind_btShapeHull_getVertexPointer_0=b.asm.rl).apply(null,arguments)},An=b._emscripten_bind_btShapeHull___destroy___0= +function(){return(An=b._emscripten_bind_btShapeHull___destroy___0=b.asm.sl).apply(null,arguments)},Bn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_0=function(){return(Bn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_0=b.asm.tl).apply(null,arguments)},Cn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_1=function(){return(Cn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_1=b.asm.ul).apply(null,arguments)},Dn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_2= +function(){return(Dn=b._emscripten_bind_btDefaultMotionState_btDefaultMotionState_2=b.asm.vl).apply(null,arguments)},En=b._emscripten_bind_btDefaultMotionState_getWorldTransform_1=function(){return(En=b._emscripten_bind_btDefaultMotionState_getWorldTransform_1=b.asm.wl).apply(null,arguments)},Fn=b._emscripten_bind_btDefaultMotionState_setWorldTransform_1=function(){return(Fn=b._emscripten_bind_btDefaultMotionState_setWorldTransform_1=b.asm.xl).apply(null,arguments)},Gn=b._emscripten_bind_btDefaultMotionState_get_m_graphicsWorldTrans_0= +function(){return(Gn=b._emscripten_bind_btDefaultMotionState_get_m_graphicsWorldTrans_0=b.asm.yl).apply(null,arguments)},Hn=b._emscripten_bind_btDefaultMotionState_set_m_graphicsWorldTrans_1=function(){return(Hn=b._emscripten_bind_btDefaultMotionState_set_m_graphicsWorldTrans_1=b.asm.zl).apply(null,arguments)},In=b._emscripten_bind_btDefaultMotionState___destroy___0=function(){return(In=b._emscripten_bind_btDefaultMotionState___destroy___0=b.asm.Al).apply(null,arguments)},Jn=b._emscripten_bind_btWheelInfo_btWheelInfo_1= +function(){return(Jn=b._emscripten_bind_btWheelInfo_btWheelInfo_1=b.asm.Bl).apply(null,arguments)},Kn=b._emscripten_bind_btWheelInfo_getSuspensionRestLength_0=function(){return(Kn=b._emscripten_bind_btWheelInfo_getSuspensionRestLength_0=b.asm.Cl).apply(null,arguments)},Ln=b._emscripten_bind_btWheelInfo_updateWheel_2=function(){return(Ln=b._emscripten_bind_btWheelInfo_updateWheel_2=b.asm.Dl).apply(null,arguments)},Mn=b._emscripten_bind_btWheelInfo_get_m_suspensionStiffness_0=function(){return(Mn=b._emscripten_bind_btWheelInfo_get_m_suspensionStiffness_0= +b.asm.El).apply(null,arguments)},Nn=b._emscripten_bind_btWheelInfo_set_m_suspensionStiffness_1=function(){return(Nn=b._emscripten_bind_btWheelInfo_set_m_suspensionStiffness_1=b.asm.Fl).apply(null,arguments)},On=b._emscripten_bind_btWheelInfo_get_m_frictionSlip_0=function(){return(On=b._emscripten_bind_btWheelInfo_get_m_frictionSlip_0=b.asm.Gl).apply(null,arguments)},Pn=b._emscripten_bind_btWheelInfo_set_m_frictionSlip_1=function(){return(Pn=b._emscripten_bind_btWheelInfo_set_m_frictionSlip_1=b.asm.Hl).apply(null, +arguments)},Qn=b._emscripten_bind_btWheelInfo_get_m_engineForce_0=function(){return(Qn=b._emscripten_bind_btWheelInfo_get_m_engineForce_0=b.asm.Il).apply(null,arguments)},Rn=b._emscripten_bind_btWheelInfo_set_m_engineForce_1=function(){return(Rn=b._emscripten_bind_btWheelInfo_set_m_engineForce_1=b.asm.Jl).apply(null,arguments)},Sn=b._emscripten_bind_btWheelInfo_get_m_rollInfluence_0=function(){return(Sn=b._emscripten_bind_btWheelInfo_get_m_rollInfluence_0=b.asm.Kl).apply(null,arguments)},Tn=b._emscripten_bind_btWheelInfo_set_m_rollInfluence_1= +function(){return(Tn=b._emscripten_bind_btWheelInfo_set_m_rollInfluence_1=b.asm.Ll).apply(null,arguments)},Un=b._emscripten_bind_btWheelInfo_get_m_suspensionRestLength1_0=function(){return(Un=b._emscripten_bind_btWheelInfo_get_m_suspensionRestLength1_0=b.asm.Ml).apply(null,arguments)},Vn=b._emscripten_bind_btWheelInfo_set_m_suspensionRestLength1_1=function(){return(Vn=b._emscripten_bind_btWheelInfo_set_m_suspensionRestLength1_1=b.asm.Nl).apply(null,arguments)},Wn=b._emscripten_bind_btWheelInfo_get_m_wheelsRadius_0= +function(){return(Wn=b._emscripten_bind_btWheelInfo_get_m_wheelsRadius_0=b.asm.Ol).apply(null,arguments)},Xn=b._emscripten_bind_btWheelInfo_set_m_wheelsRadius_1=function(){return(Xn=b._emscripten_bind_btWheelInfo_set_m_wheelsRadius_1=b.asm.Pl).apply(null,arguments)},Yn=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingCompression_0=function(){return(Yn=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingCompression_0=b.asm.Ql).apply(null,arguments)},Zn=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingCompression_1= +function(){return(Zn=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingCompression_1=b.asm.Rl).apply(null,arguments)},$n=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingRelaxation_0=function(){return($n=b._emscripten_bind_btWheelInfo_get_m_wheelsDampingRelaxation_0=b.asm.Sl).apply(null,arguments)},ao=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingRelaxation_1=function(){return(ao=b._emscripten_bind_btWheelInfo_set_m_wheelsDampingRelaxation_1=b.asm.Tl).apply(null,arguments)},bo=b._emscripten_bind_btWheelInfo_get_m_steering_0= +function(){return(bo=b._emscripten_bind_btWheelInfo_get_m_steering_0=b.asm.Ul).apply(null,arguments)},co=b._emscripten_bind_btWheelInfo_set_m_steering_1=function(){return(co=b._emscripten_bind_btWheelInfo_set_m_steering_1=b.asm.Vl).apply(null,arguments)},eo=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionForce_0=function(){return(eo=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionForce_0=b.asm.Wl).apply(null,arguments)},fo=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionForce_1=function(){return(fo= +b._emscripten_bind_btWheelInfo_set_m_maxSuspensionForce_1=b.asm.Xl).apply(null,arguments)},go=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionTravelCm_0=function(){return(go=b._emscripten_bind_btWheelInfo_get_m_maxSuspensionTravelCm_0=b.asm.Yl).apply(null,arguments)},ho=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionTravelCm_1=function(){return(ho=b._emscripten_bind_btWheelInfo_set_m_maxSuspensionTravelCm_1=b.asm.Zl).apply(null,arguments)},io=b._emscripten_bind_btWheelInfo_get_m_wheelsSuspensionForce_0= +function(){return(io=b._emscripten_bind_btWheelInfo_get_m_wheelsSuspensionForce_0=b.asm._l).apply(null,arguments)},jo=b._emscripten_bind_btWheelInfo_set_m_wheelsSuspensionForce_1=function(){return(jo=b._emscripten_bind_btWheelInfo_set_m_wheelsSuspensionForce_1=b.asm.$l).apply(null,arguments)},ko=b._emscripten_bind_btWheelInfo_get_m_bIsFrontWheel_0=function(){return(ko=b._emscripten_bind_btWheelInfo_get_m_bIsFrontWheel_0=b.asm.am).apply(null,arguments)},lo=b._emscripten_bind_btWheelInfo_set_m_bIsFrontWheel_1= +function(){return(lo=b._emscripten_bind_btWheelInfo_set_m_bIsFrontWheel_1=b.asm.bm).apply(null,arguments)},mo=b._emscripten_bind_btWheelInfo_get_m_raycastInfo_0=function(){return(mo=b._emscripten_bind_btWheelInfo_get_m_raycastInfo_0=b.asm.cm).apply(null,arguments)},no=b._emscripten_bind_btWheelInfo_set_m_raycastInfo_1=function(){return(no=b._emscripten_bind_btWheelInfo_set_m_raycastInfo_1=b.asm.dm).apply(null,arguments)},oo=b._emscripten_bind_btWheelInfo_get_m_chassisConnectionPointCS_0=function(){return(oo= +b._emscripten_bind_btWheelInfo_get_m_chassisConnectionPointCS_0=b.asm.em).apply(null,arguments)},po=b._emscripten_bind_btWheelInfo_set_m_chassisConnectionPointCS_1=function(){return(po=b._emscripten_bind_btWheelInfo_set_m_chassisConnectionPointCS_1=b.asm.fm).apply(null,arguments)},qo=b._emscripten_bind_btWheelInfo_get_m_worldTransform_0=function(){return(qo=b._emscripten_bind_btWheelInfo_get_m_worldTransform_0=b.asm.gm).apply(null,arguments)},ro=b._emscripten_bind_btWheelInfo_set_m_worldTransform_1= +function(){return(ro=b._emscripten_bind_btWheelInfo_set_m_worldTransform_1=b.asm.hm).apply(null,arguments)},so=b._emscripten_bind_btWheelInfo_get_m_wheelDirectionCS_0=function(){return(so=b._emscripten_bind_btWheelInfo_get_m_wheelDirectionCS_0=b.asm.im).apply(null,arguments)},to=b._emscripten_bind_btWheelInfo_set_m_wheelDirectionCS_1=function(){return(to=b._emscripten_bind_btWheelInfo_set_m_wheelDirectionCS_1=b.asm.jm).apply(null,arguments)},uo=b._emscripten_bind_btWheelInfo_get_m_wheelAxleCS_0=function(){return(uo= +b._emscripten_bind_btWheelInfo_get_m_wheelAxleCS_0=b.asm.km).apply(null,arguments)},vo=b._emscripten_bind_btWheelInfo_set_m_wheelAxleCS_1=function(){return(vo=b._emscripten_bind_btWheelInfo_set_m_wheelAxleCS_1=b.asm.lm).apply(null,arguments)},wo=b._emscripten_bind_btWheelInfo_get_m_rotation_0=function(){return(wo=b._emscripten_bind_btWheelInfo_get_m_rotation_0=b.asm.mm).apply(null,arguments)},xo=b._emscripten_bind_btWheelInfo_set_m_rotation_1=function(){return(xo=b._emscripten_bind_btWheelInfo_set_m_rotation_1= +b.asm.nm).apply(null,arguments)},yo=b._emscripten_bind_btWheelInfo_get_m_deltaRotation_0=function(){return(yo=b._emscripten_bind_btWheelInfo_get_m_deltaRotation_0=b.asm.om).apply(null,arguments)},zo=b._emscripten_bind_btWheelInfo_set_m_deltaRotation_1=function(){return(zo=b._emscripten_bind_btWheelInfo_set_m_deltaRotation_1=b.asm.pm).apply(null,arguments)},Ao=b._emscripten_bind_btWheelInfo_get_m_brake_0=function(){return(Ao=b._emscripten_bind_btWheelInfo_get_m_brake_0=b.asm.qm).apply(null,arguments)}, +Bo=b._emscripten_bind_btWheelInfo_set_m_brake_1=function(){return(Bo=b._emscripten_bind_btWheelInfo_set_m_brake_1=b.asm.rm).apply(null,arguments)},Co=b._emscripten_bind_btWheelInfo_get_m_clippedInvContactDotSuspension_0=function(){return(Co=b._emscripten_bind_btWheelInfo_get_m_clippedInvContactDotSuspension_0=b.asm.sm).apply(null,arguments)},Do=b._emscripten_bind_btWheelInfo_set_m_clippedInvContactDotSuspension_1=function(){return(Do=b._emscripten_bind_btWheelInfo_set_m_clippedInvContactDotSuspension_1= +b.asm.tm).apply(null,arguments)},Eo=b._emscripten_bind_btWheelInfo_get_m_suspensionRelativeVelocity_0=function(){return(Eo=b._emscripten_bind_btWheelInfo_get_m_suspensionRelativeVelocity_0=b.asm.um).apply(null,arguments)},Fo=b._emscripten_bind_btWheelInfo_set_m_suspensionRelativeVelocity_1=function(){return(Fo=b._emscripten_bind_btWheelInfo_set_m_suspensionRelativeVelocity_1=b.asm.vm).apply(null,arguments)},Go=b._emscripten_bind_btWheelInfo_get_m_skidInfo_0=function(){return(Go=b._emscripten_bind_btWheelInfo_get_m_skidInfo_0= +b.asm.wm).apply(null,arguments)},Ho=b._emscripten_bind_btWheelInfo_set_m_skidInfo_1=function(){return(Ho=b._emscripten_bind_btWheelInfo_set_m_skidInfo_1=b.asm.xm).apply(null,arguments)},Io=b._emscripten_bind_btWheelInfo___destroy___0=function(){return(Io=b._emscripten_bind_btWheelInfo___destroy___0=b.asm.ym).apply(null,arguments)},Jo=b._emscripten_bind_btVector4_btVector4_0=function(){return(Jo=b._emscripten_bind_btVector4_btVector4_0=b.asm.zm).apply(null,arguments)},Ko=b._emscripten_bind_btVector4_btVector4_4= +function(){return(Ko=b._emscripten_bind_btVector4_btVector4_4=b.asm.Am).apply(null,arguments)},Lo=b._emscripten_bind_btVector4_w_0=function(){return(Lo=b._emscripten_bind_btVector4_w_0=b.asm.Bm).apply(null,arguments)},Mo=b._emscripten_bind_btVector4_setValue_4=function(){return(Mo=b._emscripten_bind_btVector4_setValue_4=b.asm.Cm).apply(null,arguments)},No=b._emscripten_bind_btVector4_length_0=function(){return(No=b._emscripten_bind_btVector4_length_0=b.asm.Dm).apply(null,arguments)},Oo=b._emscripten_bind_btVector4_x_0= +function(){return(Oo=b._emscripten_bind_btVector4_x_0=b.asm.Em).apply(null,arguments)},Po=b._emscripten_bind_btVector4_y_0=function(){return(Po=b._emscripten_bind_btVector4_y_0=b.asm.Fm).apply(null,arguments)},Qo=b._emscripten_bind_btVector4_z_0=function(){return(Qo=b._emscripten_bind_btVector4_z_0=b.asm.Gm).apply(null,arguments)},Ro=b._emscripten_bind_btVector4_setX_1=function(){return(Ro=b._emscripten_bind_btVector4_setX_1=b.asm.Hm).apply(null,arguments)},So=b._emscripten_bind_btVector4_setY_1= +function(){return(So=b._emscripten_bind_btVector4_setY_1=b.asm.Im).apply(null,arguments)},To=b._emscripten_bind_btVector4_setZ_1=function(){return(To=b._emscripten_bind_btVector4_setZ_1=b.asm.Jm).apply(null,arguments)},Uo=b._emscripten_bind_btVector4_normalize_0=function(){return(Uo=b._emscripten_bind_btVector4_normalize_0=b.asm.Km).apply(null,arguments)},Vo=b._emscripten_bind_btVector4_rotate_2=function(){return(Vo=b._emscripten_bind_btVector4_rotate_2=b.asm.Lm).apply(null,arguments)},Wo=b._emscripten_bind_btVector4_dot_1= +function(){return(Wo=b._emscripten_bind_btVector4_dot_1=b.asm.Mm).apply(null,arguments)},Xo=b._emscripten_bind_btVector4_op_mul_1=function(){return(Xo=b._emscripten_bind_btVector4_op_mul_1=b.asm.Nm).apply(null,arguments)},Yo=b._emscripten_bind_btVector4_op_add_1=function(){return(Yo=b._emscripten_bind_btVector4_op_add_1=b.asm.Om).apply(null,arguments)},Zo=b._emscripten_bind_btVector4_op_sub_1=function(){return(Zo=b._emscripten_bind_btVector4_op_sub_1=b.asm.Pm).apply(null,arguments)},$o=b._emscripten_bind_btVector4___destroy___0= +function(){return($o=b._emscripten_bind_btVector4___destroy___0=b.asm.Qm).apply(null,arguments)},ap=b._emscripten_bind_btDefaultCollisionConstructionInfo_btDefaultCollisionConstructionInfo_0=function(){return(ap=b._emscripten_bind_btDefaultCollisionConstructionInfo_btDefaultCollisionConstructionInfo_0=b.asm.Rm).apply(null,arguments)},bp=b._emscripten_bind_btDefaultCollisionConstructionInfo___destroy___0=function(){return(bp=b._emscripten_bind_btDefaultCollisionConstructionInfo___destroy___0=b.asm.Sm).apply(null, +arguments)},cp=b._emscripten_bind_Anchor_get_m_node_0=function(){return(cp=b._emscripten_bind_Anchor_get_m_node_0=b.asm.Tm).apply(null,arguments)},dp=b._emscripten_bind_Anchor_set_m_node_1=function(){return(dp=b._emscripten_bind_Anchor_set_m_node_1=b.asm.Um).apply(null,arguments)},ep=b._emscripten_bind_Anchor_get_m_local_0=function(){return(ep=b._emscripten_bind_Anchor_get_m_local_0=b.asm.Vm).apply(null,arguments)},fp=b._emscripten_bind_Anchor_set_m_local_1=function(){return(fp=b._emscripten_bind_Anchor_set_m_local_1= +b.asm.Wm).apply(null,arguments)},gp=b._emscripten_bind_Anchor_get_m_body_0=function(){return(gp=b._emscripten_bind_Anchor_get_m_body_0=b.asm.Xm).apply(null,arguments)},hp=b._emscripten_bind_Anchor_set_m_body_1=function(){return(hp=b._emscripten_bind_Anchor_set_m_body_1=b.asm.Ym).apply(null,arguments)},ip=b._emscripten_bind_Anchor_get_m_influence_0=function(){return(ip=b._emscripten_bind_Anchor_get_m_influence_0=b.asm.Zm).apply(null,arguments)},jp=b._emscripten_bind_Anchor_set_m_influence_1=function(){return(jp= +b._emscripten_bind_Anchor_set_m_influence_1=b.asm._m).apply(null,arguments)},kp=b._emscripten_bind_Anchor_get_m_c0_0=function(){return(kp=b._emscripten_bind_Anchor_get_m_c0_0=b.asm.$m).apply(null,arguments)},lp=b._emscripten_bind_Anchor_set_m_c0_1=function(){return(lp=b._emscripten_bind_Anchor_set_m_c0_1=b.asm.an).apply(null,arguments)},mp=b._emscripten_bind_Anchor_get_m_c1_0=function(){return(mp=b._emscripten_bind_Anchor_get_m_c1_0=b.asm.bn).apply(null,arguments)},np=b._emscripten_bind_Anchor_set_m_c1_1= +function(){return(np=b._emscripten_bind_Anchor_set_m_c1_1=b.asm.cn).apply(null,arguments)},op=b._emscripten_bind_Anchor_get_m_c2_0=function(){return(op=b._emscripten_bind_Anchor_get_m_c2_0=b.asm.dn).apply(null,arguments)},pp=b._emscripten_bind_Anchor_set_m_c2_1=function(){return(pp=b._emscripten_bind_Anchor_set_m_c2_1=b.asm.en).apply(null,arguments)},qp=b._emscripten_bind_Anchor___destroy___0=function(){return(qp=b._emscripten_bind_Anchor___destroy___0=b.asm.fn).apply(null,arguments)},rp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitPointInWorld_0= +function(){return(rp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitPointInWorld_0=b.asm.gn).apply(null,arguments)},sp=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitPointInWorld_1=function(){return(sp=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitPointInWorld_1=b.asm.hn).apply(null,arguments)},tp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitNormalInWorld_0=function(){return(tp=b._emscripten_bind_btVehicleRaycasterResult_get_m_hitNormalInWorld_0=b.asm.jn).apply(null,arguments)}, +up=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitNormalInWorld_1=function(){return(up=b._emscripten_bind_btVehicleRaycasterResult_set_m_hitNormalInWorld_1=b.asm.kn).apply(null,arguments)},vp=b._emscripten_bind_btVehicleRaycasterResult_get_m_distFraction_0=function(){return(vp=b._emscripten_bind_btVehicleRaycasterResult_get_m_distFraction_0=b.asm.ln).apply(null,arguments)},wp=b._emscripten_bind_btVehicleRaycasterResult_set_m_distFraction_1=function(){return(wp=b._emscripten_bind_btVehicleRaycasterResult_set_m_distFraction_1= +b.asm.mn).apply(null,arguments)},xp=b._emscripten_bind_btVehicleRaycasterResult___destroy___0=function(){return(xp=b._emscripten_bind_btVehicleRaycasterResult___destroy___0=b.asm.nn).apply(null,arguments)},yp=b._emscripten_bind_btVector3Array_size_0=function(){return(yp=b._emscripten_bind_btVector3Array_size_0=b.asm.on).apply(null,arguments)},zp=b._emscripten_bind_btVector3Array_at_1=function(){return(zp=b._emscripten_bind_btVector3Array_at_1=b.asm.pn).apply(null,arguments)},Ap=b._emscripten_bind_btVector3Array___destroy___0= +function(){return(Ap=b._emscripten_bind_btVector3Array___destroy___0=b.asm.qn).apply(null,arguments)},Bp=b._emscripten_bind_btConstraintSolver___destroy___0=function(){return(Bp=b._emscripten_bind_btConstraintSolver___destroy___0=b.asm.rn).apply(null,arguments)},Cp=b._emscripten_bind_btRaycastVehicle_btRaycastVehicle_3=function(){return(Cp=b._emscripten_bind_btRaycastVehicle_btRaycastVehicle_3=b.asm.sn).apply(null,arguments)},Dp=b._emscripten_bind_btRaycastVehicle_applyEngineForce_2=function(){return(Dp= +b._emscripten_bind_btRaycastVehicle_applyEngineForce_2=b.asm.tn).apply(null,arguments)},Ep=b._emscripten_bind_btRaycastVehicle_setSteeringValue_2=function(){return(Ep=b._emscripten_bind_btRaycastVehicle_setSteeringValue_2=b.asm.un).apply(null,arguments)},Fp=b._emscripten_bind_btRaycastVehicle_getWheelTransformWS_1=function(){return(Fp=b._emscripten_bind_btRaycastVehicle_getWheelTransformWS_1=b.asm.vn).apply(null,arguments)},Gp=b._emscripten_bind_btRaycastVehicle_updateWheelTransform_2=function(){return(Gp= +b._emscripten_bind_btRaycastVehicle_updateWheelTransform_2=b.asm.wn).apply(null,arguments)},Hp=b._emscripten_bind_btRaycastVehicle_addWheel_7=function(){return(Hp=b._emscripten_bind_btRaycastVehicle_addWheel_7=b.asm.xn).apply(null,arguments)},Ip=b._emscripten_bind_btRaycastVehicle_getNumWheels_0=function(){return(Ip=b._emscripten_bind_btRaycastVehicle_getNumWheels_0=b.asm.yn).apply(null,arguments)},Jp=b._emscripten_bind_btRaycastVehicle_getRigidBody_0=function(){return(Jp=b._emscripten_bind_btRaycastVehicle_getRigidBody_0= +b.asm.zn).apply(null,arguments)},Kp=b._emscripten_bind_btRaycastVehicle_getWheelInfo_1=function(){return(Kp=b._emscripten_bind_btRaycastVehicle_getWheelInfo_1=b.asm.An).apply(null,arguments)},Lp=b._emscripten_bind_btRaycastVehicle_setBrake_2=function(){return(Lp=b._emscripten_bind_btRaycastVehicle_setBrake_2=b.asm.Bn).apply(null,arguments)},Mp=b._emscripten_bind_btRaycastVehicle_setCoordinateSystem_3=function(){return(Mp=b._emscripten_bind_btRaycastVehicle_setCoordinateSystem_3=b.asm.Cn).apply(null, +arguments)},Np=b._emscripten_bind_btRaycastVehicle_getCurrentSpeedKmHour_0=function(){return(Np=b._emscripten_bind_btRaycastVehicle_getCurrentSpeedKmHour_0=b.asm.Dn).apply(null,arguments)},Op=b._emscripten_bind_btRaycastVehicle_getChassisWorldTransform_0=function(){return(Op=b._emscripten_bind_btRaycastVehicle_getChassisWorldTransform_0=b.asm.En).apply(null,arguments)},Pp=b._emscripten_bind_btRaycastVehicle_rayCast_1=function(){return(Pp=b._emscripten_bind_btRaycastVehicle_rayCast_1=b.asm.Fn).apply(null, +arguments)},Qp=b._emscripten_bind_btRaycastVehicle_updateVehicle_1=function(){return(Qp=b._emscripten_bind_btRaycastVehicle_updateVehicle_1=b.asm.Gn).apply(null,arguments)},Rp=b._emscripten_bind_btRaycastVehicle_resetSuspension_0=function(){return(Rp=b._emscripten_bind_btRaycastVehicle_resetSuspension_0=b.asm.Hn).apply(null,arguments)},Sp=b._emscripten_bind_btRaycastVehicle_getSteeringValue_1=function(){return(Sp=b._emscripten_bind_btRaycastVehicle_getSteeringValue_1=b.asm.In).apply(null,arguments)}, +Tp=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_1=function(){return(Tp=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_1=b.asm.Jn).apply(null,arguments)},Up=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_2=function(){return(Up=b._emscripten_bind_btRaycastVehicle_updateWheelTransformsWS_2=b.asm.Kn).apply(null,arguments)},Vp=b._emscripten_bind_btRaycastVehicle_setPitchControl_1=function(){return(Vp=b._emscripten_bind_btRaycastVehicle_setPitchControl_1=b.asm.Ln).apply(null, +arguments)},Wp=b._emscripten_bind_btRaycastVehicle_updateSuspension_1=function(){return(Wp=b._emscripten_bind_btRaycastVehicle_updateSuspension_1=b.asm.Mn).apply(null,arguments)},Xp=b._emscripten_bind_btRaycastVehicle_updateFriction_1=function(){return(Xp=b._emscripten_bind_btRaycastVehicle_updateFriction_1=b.asm.Nn).apply(null,arguments)},Yp=b._emscripten_bind_btRaycastVehicle_getRightAxis_0=function(){return(Yp=b._emscripten_bind_btRaycastVehicle_getRightAxis_0=b.asm.On).apply(null,arguments)}, +Zp=b._emscripten_bind_btRaycastVehicle_getUpAxis_0=function(){return(Zp=b._emscripten_bind_btRaycastVehicle_getUpAxis_0=b.asm.Pn).apply(null,arguments)},$p=b._emscripten_bind_btRaycastVehicle_getForwardAxis_0=function(){return($p=b._emscripten_bind_btRaycastVehicle_getForwardAxis_0=b.asm.Qn).apply(null,arguments)},aq=b._emscripten_bind_btRaycastVehicle_getForwardVector_0=function(){return(aq=b._emscripten_bind_btRaycastVehicle_getForwardVector_0=b.asm.Rn).apply(null,arguments)},bq=b._emscripten_bind_btRaycastVehicle_getUserConstraintType_0= +function(){return(bq=b._emscripten_bind_btRaycastVehicle_getUserConstraintType_0=b.asm.Sn).apply(null,arguments)},cq=b._emscripten_bind_btRaycastVehicle_setUserConstraintType_1=function(){return(cq=b._emscripten_bind_btRaycastVehicle_setUserConstraintType_1=b.asm.Tn).apply(null,arguments)},dq=b._emscripten_bind_btRaycastVehicle_setUserConstraintId_1=function(){return(dq=b._emscripten_bind_btRaycastVehicle_setUserConstraintId_1=b.asm.Un).apply(null,arguments)},eq=b._emscripten_bind_btRaycastVehicle_getUserConstraintId_0= +function(){return(eq=b._emscripten_bind_btRaycastVehicle_getUserConstraintId_0=b.asm.Vn).apply(null,arguments)},fq=b._emscripten_bind_btRaycastVehicle_updateAction_2=function(){return(fq=b._emscripten_bind_btRaycastVehicle_updateAction_2=b.asm.Wn).apply(null,arguments)},gq=b._emscripten_bind_btRaycastVehicle___destroy___0=function(){return(gq=b._emscripten_bind_btRaycastVehicle___destroy___0=b.asm.Xn).apply(null,arguments)},hq=b._emscripten_bind_btCylinderShapeX_btCylinderShapeX_1=function(){return(hq= +b._emscripten_bind_btCylinderShapeX_btCylinderShapeX_1=b.asm.Yn).apply(null,arguments)},iq=b._emscripten_bind_btCylinderShapeX_setMargin_1=function(){return(iq=b._emscripten_bind_btCylinderShapeX_setMargin_1=b.asm.Zn).apply(null,arguments)},jq=b._emscripten_bind_btCylinderShapeX_getMargin_0=function(){return(jq=b._emscripten_bind_btCylinderShapeX_getMargin_0=b.asm._n).apply(null,arguments)},kq=b._emscripten_bind_btCylinderShapeX_setLocalScaling_1=function(){return(kq=b._emscripten_bind_btCylinderShapeX_setLocalScaling_1= +b.asm.$n).apply(null,arguments)},lq=b._emscripten_bind_btCylinderShapeX_getLocalScaling_0=function(){return(lq=b._emscripten_bind_btCylinderShapeX_getLocalScaling_0=b.asm.ao).apply(null,arguments)},mq=b._emscripten_bind_btCylinderShapeX_calculateLocalInertia_2=function(){return(mq=b._emscripten_bind_btCylinderShapeX_calculateLocalInertia_2=b.asm.bo).apply(null,arguments)},nq=b._emscripten_bind_btCylinderShapeX___destroy___0=function(){return(nq=b._emscripten_bind_btCylinderShapeX___destroy___0=b.asm.co).apply(null, +arguments)},oq=b._emscripten_bind_btCylinderShapeZ_btCylinderShapeZ_1=function(){return(oq=b._emscripten_bind_btCylinderShapeZ_btCylinderShapeZ_1=b.asm.eo).apply(null,arguments)},pq=b._emscripten_bind_btCylinderShapeZ_setMargin_1=function(){return(pq=b._emscripten_bind_btCylinderShapeZ_setMargin_1=b.asm.fo).apply(null,arguments)},qq=b._emscripten_bind_btCylinderShapeZ_getMargin_0=function(){return(qq=b._emscripten_bind_btCylinderShapeZ_getMargin_0=b.asm.go).apply(null,arguments)},rq=b._emscripten_bind_btCylinderShapeZ_setLocalScaling_1= +function(){return(rq=b._emscripten_bind_btCylinderShapeZ_setLocalScaling_1=b.asm.ho).apply(null,arguments)},sq=b._emscripten_bind_btCylinderShapeZ_getLocalScaling_0=function(){return(sq=b._emscripten_bind_btCylinderShapeZ_getLocalScaling_0=b.asm.io).apply(null,arguments)},tq=b._emscripten_bind_btCylinderShapeZ_calculateLocalInertia_2=function(){return(tq=b._emscripten_bind_btCylinderShapeZ_calculateLocalInertia_2=b.asm.jo).apply(null,arguments)},uq=b._emscripten_bind_btCylinderShapeZ___destroy___0= +function(){return(uq=b._emscripten_bind_btCylinderShapeZ___destroy___0=b.asm.ko).apply(null,arguments)},vq=b._emscripten_bind_btConvexPolyhedron_get_m_vertices_0=function(){return(vq=b._emscripten_bind_btConvexPolyhedron_get_m_vertices_0=b.asm.lo).apply(null,arguments)},wq=b._emscripten_bind_btConvexPolyhedron_set_m_vertices_1=function(){return(wq=b._emscripten_bind_btConvexPolyhedron_set_m_vertices_1=b.asm.mo).apply(null,arguments)},xq=b._emscripten_bind_btConvexPolyhedron_get_m_faces_0=function(){return(xq= +b._emscripten_bind_btConvexPolyhedron_get_m_faces_0=b.asm.no).apply(null,arguments)},yq=b._emscripten_bind_btConvexPolyhedron_set_m_faces_1=function(){return(yq=b._emscripten_bind_btConvexPolyhedron_set_m_faces_1=b.asm.oo).apply(null,arguments)},zq=b._emscripten_bind_btConvexPolyhedron___destroy___0=function(){return(zq=b._emscripten_bind_btConvexPolyhedron___destroy___0=b.asm.po).apply(null,arguments)},Aq=b._emscripten_bind_btSequentialImpulseConstraintSolver_btSequentialImpulseConstraintSolver_0= +function(){return(Aq=b._emscripten_bind_btSequentialImpulseConstraintSolver_btSequentialImpulseConstraintSolver_0=b.asm.qo).apply(null,arguments)},Bq=b._emscripten_bind_btSequentialImpulseConstraintSolver___destroy___0=function(){return(Bq=b._emscripten_bind_btSequentialImpulseConstraintSolver___destroy___0=b.asm.ro).apply(null,arguments)},Cq=b._emscripten_bind_tAnchorArray_size_0=function(){return(Cq=b._emscripten_bind_tAnchorArray_size_0=b.asm.so).apply(null,arguments)},Dq=b._emscripten_bind_tAnchorArray_at_1= +function(){return(Dq=b._emscripten_bind_tAnchorArray_at_1=b.asm.to).apply(null,arguments)},Eq=b._emscripten_bind_tAnchorArray_clear_0=function(){return(Eq=b._emscripten_bind_tAnchorArray_clear_0=b.asm.uo).apply(null,arguments)},Fq=b._emscripten_bind_tAnchorArray_push_back_1=function(){return(Fq=b._emscripten_bind_tAnchorArray_push_back_1=b.asm.vo).apply(null,arguments)},Gq=b._emscripten_bind_tAnchorArray_pop_back_0=function(){return(Gq=b._emscripten_bind_tAnchorArray_pop_back_0=b.asm.wo).apply(null, +arguments)},Hq=b._emscripten_bind_tAnchorArray___destroy___0=function(){return(Hq=b._emscripten_bind_tAnchorArray___destroy___0=b.asm.xo).apply(null,arguments)},Iq=b._emscripten_bind_RaycastInfo_get_m_contactNormalWS_0=function(){return(Iq=b._emscripten_bind_RaycastInfo_get_m_contactNormalWS_0=b.asm.yo).apply(null,arguments)},Jq=b._emscripten_bind_RaycastInfo_set_m_contactNormalWS_1=function(){return(Jq=b._emscripten_bind_RaycastInfo_set_m_contactNormalWS_1=b.asm.zo).apply(null,arguments)},Kq=b._emscripten_bind_RaycastInfo_get_m_contactPointWS_0= +function(){return(Kq=b._emscripten_bind_RaycastInfo_get_m_contactPointWS_0=b.asm.Ao).apply(null,arguments)},Lq=b._emscripten_bind_RaycastInfo_set_m_contactPointWS_1=function(){return(Lq=b._emscripten_bind_RaycastInfo_set_m_contactPointWS_1=b.asm.Bo).apply(null,arguments)},Mq=b._emscripten_bind_RaycastInfo_get_m_suspensionLength_0=function(){return(Mq=b._emscripten_bind_RaycastInfo_get_m_suspensionLength_0=b.asm.Co).apply(null,arguments)},Nq=b._emscripten_bind_RaycastInfo_set_m_suspensionLength_1= +function(){return(Nq=b._emscripten_bind_RaycastInfo_set_m_suspensionLength_1=b.asm.Do).apply(null,arguments)},Oq=b._emscripten_bind_RaycastInfo_get_m_hardPointWS_0=function(){return(Oq=b._emscripten_bind_RaycastInfo_get_m_hardPointWS_0=b.asm.Eo).apply(null,arguments)},Pq=b._emscripten_bind_RaycastInfo_set_m_hardPointWS_1=function(){return(Pq=b._emscripten_bind_RaycastInfo_set_m_hardPointWS_1=b.asm.Fo).apply(null,arguments)},Qq=b._emscripten_bind_RaycastInfo_get_m_wheelDirectionWS_0=function(){return(Qq= +b._emscripten_bind_RaycastInfo_get_m_wheelDirectionWS_0=b.asm.Go).apply(null,arguments)},Rq=b._emscripten_bind_RaycastInfo_set_m_wheelDirectionWS_1=function(){return(Rq=b._emscripten_bind_RaycastInfo_set_m_wheelDirectionWS_1=b.asm.Ho).apply(null,arguments)},Sq=b._emscripten_bind_RaycastInfo_get_m_wheelAxleWS_0=function(){return(Sq=b._emscripten_bind_RaycastInfo_get_m_wheelAxleWS_0=b.asm.Io).apply(null,arguments)},Tq=b._emscripten_bind_RaycastInfo_set_m_wheelAxleWS_1=function(){return(Tq=b._emscripten_bind_RaycastInfo_set_m_wheelAxleWS_1= +b.asm.Jo).apply(null,arguments)},Uq=b._emscripten_bind_RaycastInfo_get_m_isInContact_0=function(){return(Uq=b._emscripten_bind_RaycastInfo_get_m_isInContact_0=b.asm.Ko).apply(null,arguments)},Vq=b._emscripten_bind_RaycastInfo_set_m_isInContact_1=function(){return(Vq=b._emscripten_bind_RaycastInfo_set_m_isInContact_1=b.asm.Lo).apply(null,arguments)},Wq=b._emscripten_bind_RaycastInfo_get_m_groundObject_0=function(){return(Wq=b._emscripten_bind_RaycastInfo_get_m_groundObject_0=b.asm.Mo).apply(null,arguments)}, +Xq=b._emscripten_bind_RaycastInfo_set_m_groundObject_1=function(){return(Xq=b._emscripten_bind_RaycastInfo_set_m_groundObject_1=b.asm.No).apply(null,arguments)},Yq=b._emscripten_bind_RaycastInfo___destroy___0=function(){return(Yq=b._emscripten_bind_RaycastInfo___destroy___0=b.asm.Oo).apply(null,arguments)},Zq=b._emscripten_bind_btMultiSphereShape_btMultiSphereShape_3=function(){return(Zq=b._emscripten_bind_btMultiSphereShape_btMultiSphereShape_3=b.asm.Po).apply(null,arguments)},$q=b._emscripten_bind_btMultiSphereShape_setLocalScaling_1= +function(){return($q=b._emscripten_bind_btMultiSphereShape_setLocalScaling_1=b.asm.Qo).apply(null,arguments)},ar=b._emscripten_bind_btMultiSphereShape_getLocalScaling_0=function(){return(ar=b._emscripten_bind_btMultiSphereShape_getLocalScaling_0=b.asm.Ro).apply(null,arguments)},br=b._emscripten_bind_btMultiSphereShape_calculateLocalInertia_2=function(){return(br=b._emscripten_bind_btMultiSphereShape_calculateLocalInertia_2=b.asm.So).apply(null,arguments)},cr=b._emscripten_bind_btMultiSphereShape___destroy___0= +function(){return(cr=b._emscripten_bind_btMultiSphereShape___destroy___0=b.asm.To).apply(null,arguments)},dr=b._emscripten_bind_btSoftBody_btSoftBody_4=function(){return(dr=b._emscripten_bind_btSoftBody_btSoftBody_4=b.asm.Uo).apply(null,arguments)},er=b._emscripten_bind_btSoftBody_checkLink_2=function(){return(er=b._emscripten_bind_btSoftBody_checkLink_2=b.asm.Vo).apply(null,arguments)},fr=b._emscripten_bind_btSoftBody_checkFace_3=function(){return(fr=b._emscripten_bind_btSoftBody_checkFace_3=b.asm.Wo).apply(null, +arguments)},gr=b._emscripten_bind_btSoftBody_appendMaterial_0=function(){return(gr=b._emscripten_bind_btSoftBody_appendMaterial_0=b.asm.Xo).apply(null,arguments)},hr=b._emscripten_bind_btSoftBody_appendNode_2=function(){return(hr=b._emscripten_bind_btSoftBody_appendNode_2=b.asm.Yo).apply(null,arguments)},ir=b._emscripten_bind_btSoftBody_appendLink_4=function(){return(ir=b._emscripten_bind_btSoftBody_appendLink_4=b.asm.Zo).apply(null,arguments)},jr=b._emscripten_bind_btSoftBody_appendFace_4=function(){return(jr= +b._emscripten_bind_btSoftBody_appendFace_4=b.asm._o).apply(null,arguments)},kr=b._emscripten_bind_btSoftBody_appendTetra_5=function(){return(kr=b._emscripten_bind_btSoftBody_appendTetra_5=b.asm.$o).apply(null,arguments)},lr=b._emscripten_bind_btSoftBody_appendAnchor_4=function(){return(lr=b._emscripten_bind_btSoftBody_appendAnchor_4=b.asm.ap).apply(null,arguments)},mr=b._emscripten_bind_btSoftBody_addForce_1=function(){return(mr=b._emscripten_bind_btSoftBody_addForce_1=b.asm.bp).apply(null,arguments)}, +nr=b._emscripten_bind_btSoftBody_addForce_2=function(){return(nr=b._emscripten_bind_btSoftBody_addForce_2=b.asm.cp).apply(null,arguments)},or=b._emscripten_bind_btSoftBody_addAeroForceToNode_2=function(){return(or=b._emscripten_bind_btSoftBody_addAeroForceToNode_2=b.asm.dp).apply(null,arguments)},pr=b._emscripten_bind_btSoftBody_getTotalMass_0=function(){return(pr=b._emscripten_bind_btSoftBody_getTotalMass_0=b.asm.ep).apply(null,arguments)},qr=b._emscripten_bind_btSoftBody_setTotalMass_2=function(){return(qr= +b._emscripten_bind_btSoftBody_setTotalMass_2=b.asm.fp).apply(null,arguments)},rr=b._emscripten_bind_btSoftBody_setMass_2=function(){return(rr=b._emscripten_bind_btSoftBody_setMass_2=b.asm.gp).apply(null,arguments)},sr=b._emscripten_bind_btSoftBody_transform_1=function(){return(sr=b._emscripten_bind_btSoftBody_transform_1=b.asm.hp).apply(null,arguments)},tr=b._emscripten_bind_btSoftBody_translate_1=function(){return(tr=b._emscripten_bind_btSoftBody_translate_1=b.asm.ip).apply(null,arguments)},ur=b._emscripten_bind_btSoftBody_rotate_1= +function(){return(ur=b._emscripten_bind_btSoftBody_rotate_1=b.asm.jp).apply(null,arguments)},vr=b._emscripten_bind_btSoftBody_scale_1=function(){return(vr=b._emscripten_bind_btSoftBody_scale_1=b.asm.kp).apply(null,arguments)},wr=b._emscripten_bind_btSoftBody_generateClusters_1=function(){return(wr=b._emscripten_bind_btSoftBody_generateClusters_1=b.asm.lp).apply(null,arguments)},xr=b._emscripten_bind_btSoftBody_generateClusters_2=function(){return(xr=b._emscripten_bind_btSoftBody_generateClusters_2= +b.asm.mp).apply(null,arguments)},yr=b._emscripten_bind_btSoftBody_generateBendingConstraints_2=function(){return(yr=b._emscripten_bind_btSoftBody_generateBendingConstraints_2=b.asm.np).apply(null,arguments)},zr=b._emscripten_bind_btSoftBody_upcast_1=function(){return(zr=b._emscripten_bind_btSoftBody_upcast_1=b.asm.op).apply(null,arguments)},Ar=b._emscripten_bind_btSoftBody_setAnisotropicFriction_2=function(){return(Ar=b._emscripten_bind_btSoftBody_setAnisotropicFriction_2=b.asm.pp).apply(null,arguments)}, +Br=b._emscripten_bind_btSoftBody_getCollisionShape_0=function(){return(Br=b._emscripten_bind_btSoftBody_getCollisionShape_0=b.asm.qp).apply(null,arguments)},Cr=b._emscripten_bind_btSoftBody_setContactProcessingThreshold_1=function(){return(Cr=b._emscripten_bind_btSoftBody_setContactProcessingThreshold_1=b.asm.rp).apply(null,arguments)},Dr=b._emscripten_bind_btSoftBody_setActivationState_1=function(){return(Dr=b._emscripten_bind_btSoftBody_setActivationState_1=b.asm.sp).apply(null,arguments)},Er=b._emscripten_bind_btSoftBody_forceActivationState_1= +function(){return(Er=b._emscripten_bind_btSoftBody_forceActivationState_1=b.asm.tp).apply(null,arguments)},Fr=b._emscripten_bind_btSoftBody_activate_0=function(){return(Fr=b._emscripten_bind_btSoftBody_activate_0=b.asm.up).apply(null,arguments)},Gr=b._emscripten_bind_btSoftBody_activate_1=function(){return(Gr=b._emscripten_bind_btSoftBody_activate_1=b.asm.vp).apply(null,arguments)},Hr=b._emscripten_bind_btSoftBody_isActive_0=function(){return(Hr=b._emscripten_bind_btSoftBody_isActive_0=b.asm.wp).apply(null, +arguments)},Ir=b._emscripten_bind_btSoftBody_isKinematicObject_0=function(){return(Ir=b._emscripten_bind_btSoftBody_isKinematicObject_0=b.asm.xp).apply(null,arguments)},Jr=b._emscripten_bind_btSoftBody_isStaticObject_0=function(){return(Jr=b._emscripten_bind_btSoftBody_isStaticObject_0=b.asm.yp).apply(null,arguments)},Kr=b._emscripten_bind_btSoftBody_isStaticOrKinematicObject_0=function(){return(Kr=b._emscripten_bind_btSoftBody_isStaticOrKinematicObject_0=b.asm.zp).apply(null,arguments)},Lr=b._emscripten_bind_btSoftBody_getRestitution_0= +function(){return(Lr=b._emscripten_bind_btSoftBody_getRestitution_0=b.asm.Ap).apply(null,arguments)},Mr=b._emscripten_bind_btSoftBody_getFriction_0=function(){return(Mr=b._emscripten_bind_btSoftBody_getFriction_0=b.asm.Bp).apply(null,arguments)},Nr=b._emscripten_bind_btSoftBody_getRollingFriction_0=function(){return(Nr=b._emscripten_bind_btSoftBody_getRollingFriction_0=b.asm.Cp).apply(null,arguments)},Or=b._emscripten_bind_btSoftBody_setRestitution_1=function(){return(Or=b._emscripten_bind_btSoftBody_setRestitution_1= +b.asm.Dp).apply(null,arguments)},Pr=b._emscripten_bind_btSoftBody_setFriction_1=function(){return(Pr=b._emscripten_bind_btSoftBody_setFriction_1=b.asm.Ep).apply(null,arguments)},Qr=b._emscripten_bind_btSoftBody_setRollingFriction_1=function(){return(Qr=b._emscripten_bind_btSoftBody_setRollingFriction_1=b.asm.Fp).apply(null,arguments)},Rr=b._emscripten_bind_btSoftBody_getWorldTransform_0=function(){return(Rr=b._emscripten_bind_btSoftBody_getWorldTransform_0=b.asm.Gp).apply(null,arguments)},Sr=b._emscripten_bind_btSoftBody_getCollisionFlags_0= +function(){return(Sr=b._emscripten_bind_btSoftBody_getCollisionFlags_0=b.asm.Hp).apply(null,arguments)},Tr=b._emscripten_bind_btSoftBody_setCollisionFlags_1=function(){return(Tr=b._emscripten_bind_btSoftBody_setCollisionFlags_1=b.asm.Ip).apply(null,arguments)},Ur=b._emscripten_bind_btSoftBody_setWorldTransform_1=function(){return(Ur=b._emscripten_bind_btSoftBody_setWorldTransform_1=b.asm.Jp).apply(null,arguments)},Vr=b._emscripten_bind_btSoftBody_setCollisionShape_1=function(){return(Vr=b._emscripten_bind_btSoftBody_setCollisionShape_1= +b.asm.Kp).apply(null,arguments)},Wr=b._emscripten_bind_btSoftBody_setCcdMotionThreshold_1=function(){return(Wr=b._emscripten_bind_btSoftBody_setCcdMotionThreshold_1=b.asm.Lp).apply(null,arguments)},Xr=b._emscripten_bind_btSoftBody_setCcdSweptSphereRadius_1=function(){return(Xr=b._emscripten_bind_btSoftBody_setCcdSweptSphereRadius_1=b.asm.Mp).apply(null,arguments)},Yr=b._emscripten_bind_btSoftBody_getUserIndex_0=function(){return(Yr=b._emscripten_bind_btSoftBody_getUserIndex_0=b.asm.Np).apply(null, +arguments)},Zr=b._emscripten_bind_btSoftBody_setUserIndex_1=function(){return(Zr=b._emscripten_bind_btSoftBody_setUserIndex_1=b.asm.Op).apply(null,arguments)},$r=b._emscripten_bind_btSoftBody_getUserPointer_0=function(){return($r=b._emscripten_bind_btSoftBody_getUserPointer_0=b.asm.Pp).apply(null,arguments)},as=b._emscripten_bind_btSoftBody_setUserPointer_1=function(){return(as=b._emscripten_bind_btSoftBody_setUserPointer_1=b.asm.Qp).apply(null,arguments)},bs=b._emscripten_bind_btSoftBody_getBroadphaseHandle_0= +function(){return(bs=b._emscripten_bind_btSoftBody_getBroadphaseHandle_0=b.asm.Rp).apply(null,arguments)},cs=b._emscripten_bind_btSoftBody_get_m_cfg_0=function(){return(cs=b._emscripten_bind_btSoftBody_get_m_cfg_0=b.asm.Sp).apply(null,arguments)},ds=b._emscripten_bind_btSoftBody_set_m_cfg_1=function(){return(ds=b._emscripten_bind_btSoftBody_set_m_cfg_1=b.asm.Tp).apply(null,arguments)},es=b._emscripten_bind_btSoftBody_get_m_nodes_0=function(){return(es=b._emscripten_bind_btSoftBody_get_m_nodes_0=b.asm.Up).apply(null, +arguments)},gs=b._emscripten_bind_btSoftBody_set_m_nodes_1=function(){return(gs=b._emscripten_bind_btSoftBody_set_m_nodes_1=b.asm.Vp).apply(null,arguments)},hs=b._emscripten_bind_btSoftBody_get_m_faces_0=function(){return(hs=b._emscripten_bind_btSoftBody_get_m_faces_0=b.asm.Wp).apply(null,arguments)},is=b._emscripten_bind_btSoftBody_set_m_faces_1=function(){return(is=b._emscripten_bind_btSoftBody_set_m_faces_1=b.asm.Xp).apply(null,arguments)},js=b._emscripten_bind_btSoftBody_get_m_materials_0=function(){return(js= +b._emscripten_bind_btSoftBody_get_m_materials_0=b.asm.Yp).apply(null,arguments)},ks=b._emscripten_bind_btSoftBody_set_m_materials_1=function(){return(ks=b._emscripten_bind_btSoftBody_set_m_materials_1=b.asm.Zp).apply(null,arguments)},ls=b._emscripten_bind_btSoftBody_get_m_anchors_0=function(){return(ls=b._emscripten_bind_btSoftBody_get_m_anchors_0=b.asm._p).apply(null,arguments)},ms=b._emscripten_bind_btSoftBody_set_m_anchors_1=function(){return(ms=b._emscripten_bind_btSoftBody_set_m_anchors_1=b.asm.$p).apply(null, +arguments)},ns=b._emscripten_bind_btSoftBody___destroy___0=function(){return(ns=b._emscripten_bind_btSoftBody___destroy___0=b.asm.aq).apply(null,arguments)},ps=b._emscripten_bind_btIntArray_size_0=function(){return(ps=b._emscripten_bind_btIntArray_size_0=b.asm.bq).apply(null,arguments)},qs=b._emscripten_bind_btIntArray_at_1=function(){return(qs=b._emscripten_bind_btIntArray_at_1=b.asm.cq).apply(null,arguments)},rs=b._emscripten_bind_btIntArray___destroy___0=function(){return(rs=b._emscripten_bind_btIntArray___destroy___0= +b.asm.dq).apply(null,arguments)},ss=b._emscripten_bind_Config_get_kVCF_0=function(){return(ss=b._emscripten_bind_Config_get_kVCF_0=b.asm.eq).apply(null,arguments)},ts=b._emscripten_bind_Config_set_kVCF_1=function(){return(ts=b._emscripten_bind_Config_set_kVCF_1=b.asm.fq).apply(null,arguments)},us=b._emscripten_bind_Config_get_kDP_0=function(){return(us=b._emscripten_bind_Config_get_kDP_0=b.asm.gq).apply(null,arguments)},vs=b._emscripten_bind_Config_set_kDP_1=function(){return(vs=b._emscripten_bind_Config_set_kDP_1= +b.asm.hq).apply(null,arguments)},xs=b._emscripten_bind_Config_get_kDG_0=function(){return(xs=b._emscripten_bind_Config_get_kDG_0=b.asm.iq).apply(null,arguments)},ys=b._emscripten_bind_Config_set_kDG_1=function(){return(ys=b._emscripten_bind_Config_set_kDG_1=b.asm.jq).apply(null,arguments)},zs=b._emscripten_bind_Config_get_kLF_0=function(){return(zs=b._emscripten_bind_Config_get_kLF_0=b.asm.kq).apply(null,arguments)},As=b._emscripten_bind_Config_set_kLF_1=function(){return(As=b._emscripten_bind_Config_set_kLF_1= +b.asm.lq).apply(null,arguments)},Bs=b._emscripten_bind_Config_get_kPR_0=function(){return(Bs=b._emscripten_bind_Config_get_kPR_0=b.asm.mq).apply(null,arguments)},Cs=b._emscripten_bind_Config_set_kPR_1=function(){return(Cs=b._emscripten_bind_Config_set_kPR_1=b.asm.nq).apply(null,arguments)},Ds=b._emscripten_bind_Config_get_kVC_0=function(){return(Ds=b._emscripten_bind_Config_get_kVC_0=b.asm.oq).apply(null,arguments)},Es=b._emscripten_bind_Config_set_kVC_1=function(){return(Es=b._emscripten_bind_Config_set_kVC_1= +b.asm.pq).apply(null,arguments)},Fs=b._emscripten_bind_Config_get_kDF_0=function(){return(Fs=b._emscripten_bind_Config_get_kDF_0=b.asm.qq).apply(null,arguments)},Gs=b._emscripten_bind_Config_set_kDF_1=function(){return(Gs=b._emscripten_bind_Config_set_kDF_1=b.asm.rq).apply(null,arguments)},Hs=b._emscripten_bind_Config_get_kMT_0=function(){return(Hs=b._emscripten_bind_Config_get_kMT_0=b.asm.sq).apply(null,arguments)},Is=b._emscripten_bind_Config_set_kMT_1=function(){return(Is=b._emscripten_bind_Config_set_kMT_1= +b.asm.tq).apply(null,arguments)},Js=b._emscripten_bind_Config_get_kCHR_0=function(){return(Js=b._emscripten_bind_Config_get_kCHR_0=b.asm.uq).apply(null,arguments)},Ks=b._emscripten_bind_Config_set_kCHR_1=function(){return(Ks=b._emscripten_bind_Config_set_kCHR_1=b.asm.vq).apply(null,arguments)},Ls=b._emscripten_bind_Config_get_kKHR_0=function(){return(Ls=b._emscripten_bind_Config_get_kKHR_0=b.asm.wq).apply(null,arguments)},Ms=b._emscripten_bind_Config_set_kKHR_1=function(){return(Ms=b._emscripten_bind_Config_set_kKHR_1= +b.asm.xq).apply(null,arguments)},Ns=b._emscripten_bind_Config_get_kSHR_0=function(){return(Ns=b._emscripten_bind_Config_get_kSHR_0=b.asm.yq).apply(null,arguments)},Os=b._emscripten_bind_Config_set_kSHR_1=function(){return(Os=b._emscripten_bind_Config_set_kSHR_1=b.asm.zq).apply(null,arguments)},Ps=b._emscripten_bind_Config_get_kAHR_0=function(){return(Ps=b._emscripten_bind_Config_get_kAHR_0=b.asm.Aq).apply(null,arguments)},Qs=b._emscripten_bind_Config_set_kAHR_1=function(){return(Qs=b._emscripten_bind_Config_set_kAHR_1= +b.asm.Bq).apply(null,arguments)},Rs=b._emscripten_bind_Config_get_kSRHR_CL_0=function(){return(Rs=b._emscripten_bind_Config_get_kSRHR_CL_0=b.asm.Cq).apply(null,arguments)},Ss=b._emscripten_bind_Config_set_kSRHR_CL_1=function(){return(Ss=b._emscripten_bind_Config_set_kSRHR_CL_1=b.asm.Dq).apply(null,arguments)},Ts=b._emscripten_bind_Config_get_kSKHR_CL_0=function(){return(Ts=b._emscripten_bind_Config_get_kSKHR_CL_0=b.asm.Eq).apply(null,arguments)},Us=b._emscripten_bind_Config_set_kSKHR_CL_1=function(){return(Us= +b._emscripten_bind_Config_set_kSKHR_CL_1=b.asm.Fq).apply(null,arguments)},Vs=b._emscripten_bind_Config_get_kSSHR_CL_0=function(){return(Vs=b._emscripten_bind_Config_get_kSSHR_CL_0=b.asm.Gq).apply(null,arguments)},Ws=b._emscripten_bind_Config_set_kSSHR_CL_1=function(){return(Ws=b._emscripten_bind_Config_set_kSSHR_CL_1=b.asm.Hq).apply(null,arguments)},Xs=b._emscripten_bind_Config_get_kSR_SPLT_CL_0=function(){return(Xs=b._emscripten_bind_Config_get_kSR_SPLT_CL_0=b.asm.Iq).apply(null,arguments)},Ys=b._emscripten_bind_Config_set_kSR_SPLT_CL_1= +function(){return(Ys=b._emscripten_bind_Config_set_kSR_SPLT_CL_1=b.asm.Jq).apply(null,arguments)},Zs=b._emscripten_bind_Config_get_kSK_SPLT_CL_0=function(){return(Zs=b._emscripten_bind_Config_get_kSK_SPLT_CL_0=b.asm.Kq).apply(null,arguments)},$s=b._emscripten_bind_Config_set_kSK_SPLT_CL_1=function(){return($s=b._emscripten_bind_Config_set_kSK_SPLT_CL_1=b.asm.Lq).apply(null,arguments)},at=b._emscripten_bind_Config_get_kSS_SPLT_CL_0=function(){return(at=b._emscripten_bind_Config_get_kSS_SPLT_CL_0=b.asm.Mq).apply(null, +arguments)},bt=b._emscripten_bind_Config_set_kSS_SPLT_CL_1=function(){return(bt=b._emscripten_bind_Config_set_kSS_SPLT_CL_1=b.asm.Nq).apply(null,arguments)},ct=b._emscripten_bind_Config_get_maxvolume_0=function(){return(ct=b._emscripten_bind_Config_get_maxvolume_0=b.asm.Oq).apply(null,arguments)},dt=b._emscripten_bind_Config_set_maxvolume_1=function(){return(dt=b._emscripten_bind_Config_set_maxvolume_1=b.asm.Pq).apply(null,arguments)},et=b._emscripten_bind_Config_get_timescale_0=function(){return(et= +b._emscripten_bind_Config_get_timescale_0=b.asm.Qq).apply(null,arguments)},ft=b._emscripten_bind_Config_set_timescale_1=function(){return(ft=b._emscripten_bind_Config_set_timescale_1=b.asm.Rq).apply(null,arguments)},gt=b._emscripten_bind_Config_get_viterations_0=function(){return(gt=b._emscripten_bind_Config_get_viterations_0=b.asm.Sq).apply(null,arguments)},ht=b._emscripten_bind_Config_set_viterations_1=function(){return(ht=b._emscripten_bind_Config_set_viterations_1=b.asm.Tq).apply(null,arguments)}, +it=b._emscripten_bind_Config_get_piterations_0=function(){return(it=b._emscripten_bind_Config_get_piterations_0=b.asm.Uq).apply(null,arguments)},jt=b._emscripten_bind_Config_set_piterations_1=function(){return(jt=b._emscripten_bind_Config_set_piterations_1=b.asm.Vq).apply(null,arguments)},kt=b._emscripten_bind_Config_get_diterations_0=function(){return(kt=b._emscripten_bind_Config_get_diterations_0=b.asm.Wq).apply(null,arguments)},lt=b._emscripten_bind_Config_set_diterations_1=function(){return(lt= +b._emscripten_bind_Config_set_diterations_1=b.asm.Xq).apply(null,arguments)},mt=b._emscripten_bind_Config_get_citerations_0=function(){return(mt=b._emscripten_bind_Config_get_citerations_0=b.asm.Yq).apply(null,arguments)},nt=b._emscripten_bind_Config_set_citerations_1=function(){return(nt=b._emscripten_bind_Config_set_citerations_1=b.asm.Zq).apply(null,arguments)},ot=b._emscripten_bind_Config_get_collisions_0=function(){return(ot=b._emscripten_bind_Config_get_collisions_0=b.asm._q).apply(null,arguments)}, +pt=b._emscripten_bind_Config_set_collisions_1=function(){return(pt=b._emscripten_bind_Config_set_collisions_1=b.asm.$q).apply(null,arguments)},qt=b._emscripten_bind_Config___destroy___0=function(){return(qt=b._emscripten_bind_Config___destroy___0=b.asm.ar).apply(null,arguments)},rt=b._emscripten_bind_Node_get_m_x_0=function(){return(rt=b._emscripten_bind_Node_get_m_x_0=b.asm.br).apply(null,arguments)},st=b._emscripten_bind_Node_set_m_x_1=function(){return(st=b._emscripten_bind_Node_set_m_x_1=b.asm.cr).apply(null, +arguments)},tt=b._emscripten_bind_Node_get_m_q_0=function(){return(tt=b._emscripten_bind_Node_get_m_q_0=b.asm.dr).apply(null,arguments)},ut=b._emscripten_bind_Node_set_m_q_1=function(){return(ut=b._emscripten_bind_Node_set_m_q_1=b.asm.er).apply(null,arguments)},vt=b._emscripten_bind_Node_get_m_v_0=function(){return(vt=b._emscripten_bind_Node_get_m_v_0=b.asm.fr).apply(null,arguments)},wt=b._emscripten_bind_Node_set_m_v_1=function(){return(wt=b._emscripten_bind_Node_set_m_v_1=b.asm.gr).apply(null,arguments)}, +xt=b._emscripten_bind_Node_get_m_f_0=function(){return(xt=b._emscripten_bind_Node_get_m_f_0=b.asm.hr).apply(null,arguments)},yt=b._emscripten_bind_Node_set_m_f_1=function(){return(yt=b._emscripten_bind_Node_set_m_f_1=b.asm.ir).apply(null,arguments)},zt=b._emscripten_bind_Node_get_m_n_0=function(){return(zt=b._emscripten_bind_Node_get_m_n_0=b.asm.jr).apply(null,arguments)},At=b._emscripten_bind_Node_set_m_n_1=function(){return(At=b._emscripten_bind_Node_set_m_n_1=b.asm.kr).apply(null,arguments)},Bt= +b._emscripten_bind_Node_get_m_im_0=function(){return(Bt=b._emscripten_bind_Node_get_m_im_0=b.asm.lr).apply(null,arguments)},Ct=b._emscripten_bind_Node_set_m_im_1=function(){return(Ct=b._emscripten_bind_Node_set_m_im_1=b.asm.mr).apply(null,arguments)},Dt=b._emscripten_bind_Node_get_m_area_0=function(){return(Dt=b._emscripten_bind_Node_get_m_area_0=b.asm.nr).apply(null,arguments)},Et=b._emscripten_bind_Node_set_m_area_1=function(){return(Et=b._emscripten_bind_Node_set_m_area_1=b.asm.or).apply(null, +arguments)},Ft=b._emscripten_bind_Node___destroy___0=function(){return(Ft=b._emscripten_bind_Node___destroy___0=b.asm.pr).apply(null,arguments)},Gt=b._emscripten_bind_btGhostPairCallback_btGhostPairCallback_0=function(){return(Gt=b._emscripten_bind_btGhostPairCallback_btGhostPairCallback_0=b.asm.qr).apply(null,arguments)},Ht=b._emscripten_bind_btGhostPairCallback___destroy___0=function(){return(Ht=b._emscripten_bind_btGhostPairCallback___destroy___0=b.asm.rr).apply(null,arguments)},It=b._emscripten_bind_btOverlappingPairCallback___destroy___0= +function(){return(It=b._emscripten_bind_btOverlappingPairCallback___destroy___0=b.asm.sr).apply(null,arguments)},Jt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_3=function(){return(Jt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_3=b.asm.tr).apply(null,arguments)},Kt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_4=function(){return(Kt=b._emscripten_bind_btKinematicCharacterController_btKinematicCharacterController_4= +b.asm.ur).apply(null,arguments)},Lt=b._emscripten_bind_btKinematicCharacterController_setUpAxis_1=function(){return(Lt=b._emscripten_bind_btKinematicCharacterController_setUpAxis_1=b.asm.vr).apply(null,arguments)},Mt=b._emscripten_bind_btKinematicCharacterController_setWalkDirection_1=function(){return(Mt=b._emscripten_bind_btKinematicCharacterController_setWalkDirection_1=b.asm.wr).apply(null,arguments)},Nt=b._emscripten_bind_btKinematicCharacterController_setVelocityForTimeInterval_2=function(){return(Nt= +b._emscripten_bind_btKinematicCharacterController_setVelocityForTimeInterval_2=b.asm.xr).apply(null,arguments)},Ot=b._emscripten_bind_btKinematicCharacterController_warp_1=function(){return(Ot=b._emscripten_bind_btKinematicCharacterController_warp_1=b.asm.yr).apply(null,arguments)},Pt=b._emscripten_bind_btKinematicCharacterController_preStep_1=function(){return(Pt=b._emscripten_bind_btKinematicCharacterController_preStep_1=b.asm.zr).apply(null,arguments)},Qt=b._emscripten_bind_btKinematicCharacterController_playerStep_2= +function(){return(Qt=b._emscripten_bind_btKinematicCharacterController_playerStep_2=b.asm.Ar).apply(null,arguments)},Rt=b._emscripten_bind_btKinematicCharacterController_setFallSpeed_1=function(){return(Rt=b._emscripten_bind_btKinematicCharacterController_setFallSpeed_1=b.asm.Br).apply(null,arguments)},St=b._emscripten_bind_btKinematicCharacterController_setJumpSpeed_1=function(){return(St=b._emscripten_bind_btKinematicCharacterController_setJumpSpeed_1=b.asm.Cr).apply(null,arguments)},Tt=b._emscripten_bind_btKinematicCharacterController_setMaxJumpHeight_1= +function(){return(Tt=b._emscripten_bind_btKinematicCharacterController_setMaxJumpHeight_1=b.asm.Dr).apply(null,arguments)},Ut=b._emscripten_bind_btKinematicCharacterController_canJump_0=function(){return(Ut=b._emscripten_bind_btKinematicCharacterController_canJump_0=b.asm.Er).apply(null,arguments)},Vt=b._emscripten_bind_btKinematicCharacterController_jump_0=function(){return(Vt=b._emscripten_bind_btKinematicCharacterController_jump_0=b.asm.Fr).apply(null,arguments)},Wt=b._emscripten_bind_btKinematicCharacterController_setGravity_1= +function(){return(Wt=b._emscripten_bind_btKinematicCharacterController_setGravity_1=b.asm.Gr).apply(null,arguments)},Xt=b._emscripten_bind_btKinematicCharacterController_getGravity_0=function(){return(Xt=b._emscripten_bind_btKinematicCharacterController_getGravity_0=b.asm.Hr).apply(null,arguments)},Yt=b._emscripten_bind_btKinematicCharacterController_setMaxSlope_1=function(){return(Yt=b._emscripten_bind_btKinematicCharacterController_setMaxSlope_1=b.asm.Ir).apply(null,arguments)},Zt=b._emscripten_bind_btKinematicCharacterController_getMaxSlope_0= +function(){return(Zt=b._emscripten_bind_btKinematicCharacterController_getMaxSlope_0=b.asm.Jr).apply(null,arguments)},$t=b._emscripten_bind_btKinematicCharacterController_getGhostObject_0=function(){return($t=b._emscripten_bind_btKinematicCharacterController_getGhostObject_0=b.asm.Kr).apply(null,arguments)},au=b._emscripten_bind_btKinematicCharacterController_setUseGhostSweepTest_1=function(){return(au=b._emscripten_bind_btKinematicCharacterController_setUseGhostSweepTest_1=b.asm.Lr).apply(null,arguments)}, +bu=b._emscripten_bind_btKinematicCharacterController_onGround_0=function(){return(bu=b._emscripten_bind_btKinematicCharacterController_onGround_0=b.asm.Mr).apply(null,arguments)},cu=b._emscripten_bind_btKinematicCharacterController_setUpInterpolate_1=function(){return(cu=b._emscripten_bind_btKinematicCharacterController_setUpInterpolate_1=b.asm.Nr).apply(null,arguments)},du=b._emscripten_bind_btKinematicCharacterController_updateAction_2=function(){return(du=b._emscripten_bind_btKinematicCharacterController_updateAction_2= +b.asm.Or).apply(null,arguments)},eu=b._emscripten_bind_btKinematicCharacterController___destroy___0=function(){return(eu=b._emscripten_bind_btKinematicCharacterController___destroy___0=b.asm.Pr).apply(null,arguments)},fu=b._emscripten_bind_btSoftBodyArray_size_0=function(){return(fu=b._emscripten_bind_btSoftBodyArray_size_0=b.asm.Qr).apply(null,arguments)},gu=b._emscripten_bind_btSoftBodyArray_at_1=function(){return(gu=b._emscripten_bind_btSoftBodyArray_at_1=b.asm.Rr).apply(null,arguments)},hu=b._emscripten_bind_btSoftBodyArray___destroy___0= +function(){return(hu=b._emscripten_bind_btSoftBodyArray___destroy___0=b.asm.Sr).apply(null,arguments)},iu=b._emscripten_bind_btFaceArray_size_0=function(){return(iu=b._emscripten_bind_btFaceArray_size_0=b.asm.Tr).apply(null,arguments)},ju=b._emscripten_bind_btFaceArray_at_1=function(){return(ju=b._emscripten_bind_btFaceArray_at_1=b.asm.Ur).apply(null,arguments)},ku=b._emscripten_bind_btFaceArray___destroy___0=function(){return(ku=b._emscripten_bind_btFaceArray___destroy___0=b.asm.Vr).apply(null,arguments)}, +lu=b._emscripten_bind_btStaticPlaneShape_btStaticPlaneShape_2=function(){return(lu=b._emscripten_bind_btStaticPlaneShape_btStaticPlaneShape_2=b.asm.Wr).apply(null,arguments)},mu=b._emscripten_bind_btStaticPlaneShape_setLocalScaling_1=function(){return(mu=b._emscripten_bind_btStaticPlaneShape_setLocalScaling_1=b.asm.Xr).apply(null,arguments)},nu=b._emscripten_bind_btStaticPlaneShape_getLocalScaling_0=function(){return(nu=b._emscripten_bind_btStaticPlaneShape_getLocalScaling_0=b.asm.Yr).apply(null, +arguments)},ou=b._emscripten_bind_btStaticPlaneShape_calculateLocalInertia_2=function(){return(ou=b._emscripten_bind_btStaticPlaneShape_calculateLocalInertia_2=b.asm.Zr).apply(null,arguments)},pu=b._emscripten_bind_btStaticPlaneShape___destroy___0=function(){return(pu=b._emscripten_bind_btStaticPlaneShape___destroy___0=b.asm._r).apply(null,arguments)},qu=b._emscripten_bind_btOverlappingPairCache_setInternalGhostPairCallback_1=function(){return(qu=b._emscripten_bind_btOverlappingPairCache_setInternalGhostPairCallback_1= +b.asm.$r).apply(null,arguments)},ru=b._emscripten_bind_btOverlappingPairCache_getNumOverlappingPairs_0=function(){return(ru=b._emscripten_bind_btOverlappingPairCache_getNumOverlappingPairs_0=b.asm.as).apply(null,arguments)},su=b._emscripten_bind_btOverlappingPairCache___destroy___0=function(){return(su=b._emscripten_bind_btOverlappingPairCache___destroy___0=b.asm.bs).apply(null,arguments)},tu=b._emscripten_bind_btIndexedMesh_get_m_numTriangles_0=function(){return(tu=b._emscripten_bind_btIndexedMesh_get_m_numTriangles_0= +b.asm.cs).apply(null,arguments)},uu=b._emscripten_bind_btIndexedMesh_set_m_numTriangles_1=function(){return(uu=b._emscripten_bind_btIndexedMesh_set_m_numTriangles_1=b.asm.ds).apply(null,arguments)},vu=b._emscripten_bind_btIndexedMesh___destroy___0=function(){return(vu=b._emscripten_bind_btIndexedMesh___destroy___0=b.asm.es).apply(null,arguments)},wu=b._emscripten_bind_btSoftRigidDynamicsWorld_btSoftRigidDynamicsWorld_5=function(){return(wu=b._emscripten_bind_btSoftRigidDynamicsWorld_btSoftRigidDynamicsWorld_5= +b.asm.fs).apply(null,arguments)},xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addSoftBody_3=function(){return(xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addSoftBody_3=b.asm.gs).apply(null,arguments)},yu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeSoftBody_1=function(){return(yu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeSoftBody_1=b.asm.hs).apply(null,arguments)},zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeCollisionObject_1=function(){return(zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeCollisionObject_1= +b.asm.is).apply(null,arguments)},Au=b._emscripten_bind_btSoftRigidDynamicsWorld_getWorldInfo_0=function(){return(Au=b._emscripten_bind_btSoftRigidDynamicsWorld_getWorldInfo_0=b.asm.js).apply(null,arguments)},Bu=b._emscripten_bind_btSoftRigidDynamicsWorld_getSoftBodyArray_0=function(){return(Bu=b._emscripten_bind_btSoftRigidDynamicsWorld_getSoftBodyArray_0=b.asm.ks).apply(null,arguments)},Cu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatcher_0=function(){return(Cu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatcher_0= +b.asm.ls).apply(null,arguments)},Du=b._emscripten_bind_btSoftRigidDynamicsWorld_rayTest_3=function(){return(Du=b._emscripten_bind_btSoftRigidDynamicsWorld_rayTest_3=b.asm.ms).apply(null,arguments)},Eu=b._emscripten_bind_btSoftRigidDynamicsWorld_getPairCache_0=function(){return(Eu=b._emscripten_bind_btSoftRigidDynamicsWorld_getPairCache_0=b.asm.ns).apply(null,arguments)},Fu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatchInfo_0=function(){return(Fu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDispatchInfo_0= +b.asm.os).apply(null,arguments)},Gu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_1=function(){return(Gu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_1=b.asm.ps).apply(null,arguments)},Hu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_2=function(){return(Hu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_2=b.asm.qs).apply(null,arguments)},Iu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_3=function(){return(Iu=b._emscripten_bind_btSoftRigidDynamicsWorld_addCollisionObject_3= +b.asm.rs).apply(null,arguments)},Ju=b._emscripten_bind_btSoftRigidDynamicsWorld_getBroadphase_0=function(){return(Ju=b._emscripten_bind_btSoftRigidDynamicsWorld_getBroadphase_0=b.asm.ss).apply(null,arguments)},Ku=b._emscripten_bind_btSoftRigidDynamicsWorld_convexSweepTest_5=function(){return(Ku=b._emscripten_bind_btSoftRigidDynamicsWorld_convexSweepTest_5=b.asm.ts).apply(null,arguments)},Lu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactPairTest_3=function(){return(Lu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactPairTest_3= +b.asm.us).apply(null,arguments)},Mu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactTest_2=function(){return(Mu=b._emscripten_bind_btSoftRigidDynamicsWorld_contactTest_2=b.asm.vs).apply(null,arguments)},Nu=b._emscripten_bind_btSoftRigidDynamicsWorld_updateSingleAabb_1=function(){return(Nu=b._emscripten_bind_btSoftRigidDynamicsWorld_updateSingleAabb_1=b.asm.ws).apply(null,arguments)},Ou=b._emscripten_bind_btSoftRigidDynamicsWorld_setDebugDrawer_1=function(){return(Ou=b._emscripten_bind_btSoftRigidDynamicsWorld_setDebugDrawer_1= +b.asm.xs).apply(null,arguments)},Pu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDebugDrawer_0=function(){return(Pu=b._emscripten_bind_btSoftRigidDynamicsWorld_getDebugDrawer_0=b.asm.ys).apply(null,arguments)},Qu=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawWorld_0=function(){return(Qu=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawWorld_0=b.asm.zs).apply(null,arguments)},Ru=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawObject_3=function(){return(Ru=b._emscripten_bind_btSoftRigidDynamicsWorld_debugDrawObject_3= +b.asm.As).apply(null,arguments)},Su=b._emscripten_bind_btSoftRigidDynamicsWorld_setGravity_1=function(){return(Su=b._emscripten_bind_btSoftRigidDynamicsWorld_setGravity_1=b.asm.Bs).apply(null,arguments)},Tu=b._emscripten_bind_btSoftRigidDynamicsWorld_getGravity_0=function(){return(Tu=b._emscripten_bind_btSoftRigidDynamicsWorld_getGravity_0=b.asm.Cs).apply(null,arguments)},Uu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_1=function(){return(Uu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_1= +b.asm.Ds).apply(null,arguments)},Vu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_3=function(){return(Vu=b._emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_3=b.asm.Es).apply(null,arguments)},Wu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeRigidBody_1=function(){return(Wu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeRigidBody_1=b.asm.Fs).apply(null,arguments)},Xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_1=function(){return(Xu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_1= +b.asm.Gs).apply(null,arguments)},Yu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_2=function(){return(Yu=b._emscripten_bind_btSoftRigidDynamicsWorld_addConstraint_2=b.asm.Hs).apply(null,arguments)},Zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeConstraint_1=function(){return(Zu=b._emscripten_bind_btSoftRigidDynamicsWorld_removeConstraint_1=b.asm.Is).apply(null,arguments)},$u=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_1=function(){return($u=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_1= +b.asm.Js).apply(null,arguments)},av=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_2=function(){return(av=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_2=b.asm.Ks).apply(null,arguments)},bv=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_3=function(){return(bv=b._emscripten_bind_btSoftRigidDynamicsWorld_stepSimulation_3=b.asm.Ls).apply(null,arguments)},cv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactAddedCallback_1=function(){return(cv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactAddedCallback_1= +b.asm.Ms).apply(null,arguments)},dv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactProcessedCallback_1=function(){return(dv=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactProcessedCallback_1=b.asm.Ns).apply(null,arguments)},ev=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactDestroyedCallback_1=function(){return(ev=b._emscripten_bind_btSoftRigidDynamicsWorld_setContactDestroyedCallback_1=b.asm.Os).apply(null,arguments)},fv=b._emscripten_bind_btSoftRigidDynamicsWorld_addAction_1= +function(){return(fv=b._emscripten_bind_btSoftRigidDynamicsWorld_addAction_1=b.asm.Ps).apply(null,arguments)},gv=b._emscripten_bind_btSoftRigidDynamicsWorld_removeAction_1=function(){return(gv=b._emscripten_bind_btSoftRigidDynamicsWorld_removeAction_1=b.asm.Qs).apply(null,arguments)},hv=b._emscripten_bind_btSoftRigidDynamicsWorld_getSolverInfo_0=function(){return(hv=b._emscripten_bind_btSoftRigidDynamicsWorld_getSolverInfo_0=b.asm.Rs).apply(null,arguments)},iv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_1= +function(){return(iv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_1=b.asm.Ss).apply(null,arguments)},jv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_2=function(){return(jv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_2=b.asm.Ts).apply(null,arguments)},kv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_3=function(){return(kv=b._emscripten_bind_btSoftRigidDynamicsWorld_setInternalTickCallback_3=b.asm.Us).apply(null, +arguments)},lv=b._emscripten_bind_btSoftRigidDynamicsWorld___destroy___0=function(){return(lv=b._emscripten_bind_btSoftRigidDynamicsWorld___destroy___0=b.asm.Vs).apply(null,arguments)},mv=b._emscripten_bind_btFixedConstraint_btFixedConstraint_4=function(){return(mv=b._emscripten_bind_btFixedConstraint_btFixedConstraint_4=b.asm.Ws).apply(null,arguments)},nv=b._emscripten_bind_btFixedConstraint_enableFeedback_1=function(){return(nv=b._emscripten_bind_btFixedConstraint_enableFeedback_1=b.asm.Xs).apply(null, +arguments)},ov=b._emscripten_bind_btFixedConstraint_getBreakingImpulseThreshold_0=function(){return(ov=b._emscripten_bind_btFixedConstraint_getBreakingImpulseThreshold_0=b.asm.Ys).apply(null,arguments)},pv=b._emscripten_bind_btFixedConstraint_setBreakingImpulseThreshold_1=function(){return(pv=b._emscripten_bind_btFixedConstraint_setBreakingImpulseThreshold_1=b.asm.Zs).apply(null,arguments)},qv=b._emscripten_bind_btFixedConstraint_getParam_2=function(){return(qv=b._emscripten_bind_btFixedConstraint_getParam_2= +b.asm._s).apply(null,arguments)},rv=b._emscripten_bind_btFixedConstraint_setParam_3=function(){return(rv=b._emscripten_bind_btFixedConstraint_setParam_3=b.asm.$s).apply(null,arguments)},sv=b._emscripten_bind_btFixedConstraint___destroy___0=function(){return(sv=b._emscripten_bind_btFixedConstraint___destroy___0=b.asm.at).apply(null,arguments)},tv=b._emscripten_bind_btTransform_btTransform_0=function(){return(tv=b._emscripten_bind_btTransform_btTransform_0=b.asm.bt).apply(null,arguments)},uv=b._emscripten_bind_btTransform_btTransform_2= +function(){return(uv=b._emscripten_bind_btTransform_btTransform_2=b.asm.ct).apply(null,arguments)},vv=b._emscripten_bind_btTransform_setIdentity_0=function(){return(vv=b._emscripten_bind_btTransform_setIdentity_0=b.asm.dt).apply(null,arguments)},wv=b._emscripten_bind_btTransform_setOrigin_1=function(){return(wv=b._emscripten_bind_btTransform_setOrigin_1=b.asm.et).apply(null,arguments)},xv=b._emscripten_bind_btTransform_setRotation_1=function(){return(xv=b._emscripten_bind_btTransform_setRotation_1= +b.asm.ft).apply(null,arguments)},yv=b._emscripten_bind_btTransform_getOrigin_0=function(){return(yv=b._emscripten_bind_btTransform_getOrigin_0=b.asm.gt).apply(null,arguments)},zv=b._emscripten_bind_btTransform_getRotation_0=function(){return(zv=b._emscripten_bind_btTransform_getRotation_0=b.asm.ht).apply(null,arguments)},Av=b._emscripten_bind_btTransform_getBasis_0=function(){return(Av=b._emscripten_bind_btTransform_getBasis_0=b.asm.it).apply(null,arguments)},Bv=b._emscripten_bind_btTransform_setFromOpenGLMatrix_1= +function(){return(Bv=b._emscripten_bind_btTransform_setFromOpenGLMatrix_1=b.asm.jt).apply(null,arguments)},Cv=b._emscripten_bind_btTransform_inverse_0=function(){return(Cv=b._emscripten_bind_btTransform_inverse_0=b.asm.kt).apply(null,arguments)},Dv=b._emscripten_bind_btTransform_op_mul_1=function(){return(Dv=b._emscripten_bind_btTransform_op_mul_1=b.asm.lt).apply(null,arguments)},Ev=b._emscripten_bind_btTransform___destroy___0=function(){return(Ev=b._emscripten_bind_btTransform___destroy___0=b.asm.mt).apply(null, +arguments)},Fv=b._emscripten_bind_ClosestRayResultCallback_ClosestRayResultCallback_2=function(){return(Fv=b._emscripten_bind_ClosestRayResultCallback_ClosestRayResultCallback_2=b.asm.nt).apply(null,arguments)},Gv=b._emscripten_bind_ClosestRayResultCallback_hasHit_0=function(){return(Gv=b._emscripten_bind_ClosestRayResultCallback_hasHit_0=b.asm.ot).apply(null,arguments)},Hv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayFromWorld_0=function(){return(Hv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayFromWorld_0= +b.asm.pt).apply(null,arguments)},Iv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayFromWorld_1=function(){return(Iv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayFromWorld_1=b.asm.qt).apply(null,arguments)},Jv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayToWorld_0=function(){return(Jv=b._emscripten_bind_ClosestRayResultCallback_get_m_rayToWorld_0=b.asm.rt).apply(null,arguments)},Kv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayToWorld_1=function(){return(Kv=b._emscripten_bind_ClosestRayResultCallback_set_m_rayToWorld_1= +b.asm.st).apply(null,arguments)},Lv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitNormalWorld_0=function(){return(Lv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitNormalWorld_0=b.asm.tt).apply(null,arguments)},Mv=b._emscripten_bind_ClosestRayResultCallback_set_m_hitNormalWorld_1=function(){return(Mv=b._emscripten_bind_ClosestRayResultCallback_set_m_hitNormalWorld_1=b.asm.ut).apply(null,arguments)},Nv=b._emscripten_bind_ClosestRayResultCallback_get_m_hitPointWorld_0=function(){return(Nv= +b._emscripten_bind_ClosestRayResultCallback_get_m_hitPointWorld_0=b.asm.vt).apply(null,arguments)},Ov=b._emscripten_bind_ClosestRayResultCallback_set_m_hitPointWorld_1=function(){return(Ov=b._emscripten_bind_ClosestRayResultCallback_set_m_hitPointWorld_1=b.asm.wt).apply(null,arguments)},Pv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterGroup_0=function(){return(Pv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterGroup_0=b.asm.xt).apply(null,arguments)},Qv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterGroup_1= +function(){return(Qv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterGroup_1=b.asm.yt).apply(null,arguments)},Rv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterMask_0=function(){return(Rv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionFilterMask_0=b.asm.zt).apply(null,arguments)},Sv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterMask_1=function(){return(Sv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionFilterMask_1=b.asm.At).apply(null, +arguments)},Tv=b._emscripten_bind_ClosestRayResultCallback_get_m_closestHitFraction_0=function(){return(Tv=b._emscripten_bind_ClosestRayResultCallback_get_m_closestHitFraction_0=b.asm.Bt).apply(null,arguments)},Uv=b._emscripten_bind_ClosestRayResultCallback_set_m_closestHitFraction_1=function(){return(Uv=b._emscripten_bind_ClosestRayResultCallback_set_m_closestHitFraction_1=b.asm.Ct).apply(null,arguments)},Vv=b._emscripten_bind_ClosestRayResultCallback_get_m_collisionObject_0=function(){return(Vv= +b._emscripten_bind_ClosestRayResultCallback_get_m_collisionObject_0=b.asm.Dt).apply(null,arguments)},Wv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionObject_1=function(){return(Wv=b._emscripten_bind_ClosestRayResultCallback_set_m_collisionObject_1=b.asm.Et).apply(null,arguments)},Xv=b._emscripten_bind_ClosestRayResultCallback___destroy___0=function(){return(Xv=b._emscripten_bind_ClosestRayResultCallback___destroy___0=b.asm.Ft).apply(null,arguments)},Yv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_0= +function(){return(Yv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_0=b.asm.Gt).apply(null,arguments)},Zv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_1=function(){return(Zv=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration_btSoftBodyRigidBodyCollisionConfiguration_1=b.asm.Ht).apply(null,arguments)},$v=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration___destroy___0= +function(){return($v=b._emscripten_bind_btSoftBodyRigidBodyCollisionConfiguration___destroy___0=b.asm.It).apply(null,arguments)},aw=b._emscripten_bind_ConcreteContactResultCallback_ConcreteContactResultCallback_0=function(){return(aw=b._emscripten_bind_ConcreteContactResultCallback_ConcreteContactResultCallback_0=b.asm.Jt).apply(null,arguments)},bw=b._emscripten_bind_ConcreteContactResultCallback_addSingleResult_7=function(){return(bw=b._emscripten_bind_ConcreteContactResultCallback_addSingleResult_7= +b.asm.Kt).apply(null,arguments)},cw=b._emscripten_bind_ConcreteContactResultCallback___destroy___0=function(){return(cw=b._emscripten_bind_ConcreteContactResultCallback___destroy___0=b.asm.Lt).apply(null,arguments)},dw=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_2=function(){return(dw=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_2=b.asm.Mt).apply(null,arguments)},ew=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_3=function(){return(ew=b._emscripten_bind_btBvhTriangleMeshShape_btBvhTriangleMeshShape_3= +b.asm.Nt).apply(null,arguments)},fw=b._emscripten_bind_btBvhTriangleMeshShape_setLocalScaling_1=function(){return(fw=b._emscripten_bind_btBvhTriangleMeshShape_setLocalScaling_1=b.asm.Ot).apply(null,arguments)},gw=b._emscripten_bind_btBvhTriangleMeshShape_getLocalScaling_0=function(){return(gw=b._emscripten_bind_btBvhTriangleMeshShape_getLocalScaling_0=b.asm.Pt).apply(null,arguments)},hw=b._emscripten_bind_btBvhTriangleMeshShape_calculateLocalInertia_2=function(){return(hw=b._emscripten_bind_btBvhTriangleMeshShape_calculateLocalInertia_2= +b.asm.Qt).apply(null,arguments)},iw=b._emscripten_bind_btBvhTriangleMeshShape___destroy___0=function(){return(iw=b._emscripten_bind_btBvhTriangleMeshShape___destroy___0=b.asm.Rt).apply(null,arguments)},jw=b._emscripten_bind_btConstCollisionObjectArray_size_0=function(){return(jw=b._emscripten_bind_btConstCollisionObjectArray_size_0=b.asm.St).apply(null,arguments)},kw=b._emscripten_bind_btConstCollisionObjectArray_at_1=function(){return(kw=b._emscripten_bind_btConstCollisionObjectArray_at_1=b.asm.Tt).apply(null, +arguments)},lw=b._emscripten_bind_btConstCollisionObjectArray___destroy___0=function(){return(lw=b._emscripten_bind_btConstCollisionObjectArray___destroy___0=b.asm.Ut).apply(null,arguments)},mw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_3=function(){return(mw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_3=b.asm.Vt).apply(null,arguments)},nw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_5=function(){return(nw=b._emscripten_bind_btSliderConstraint_btSliderConstraint_5= +b.asm.Wt).apply(null,arguments)},ow=b._emscripten_bind_btSliderConstraint_setLowerLinLimit_1=function(){return(ow=b._emscripten_bind_btSliderConstraint_setLowerLinLimit_1=b.asm.Xt).apply(null,arguments)},pw=b._emscripten_bind_btSliderConstraint_setUpperLinLimit_1=function(){return(pw=b._emscripten_bind_btSliderConstraint_setUpperLinLimit_1=b.asm.Yt).apply(null,arguments)},qw=b._emscripten_bind_btSliderConstraint_setLowerAngLimit_1=function(){return(qw=b._emscripten_bind_btSliderConstraint_setLowerAngLimit_1= +b.asm.Zt).apply(null,arguments)},rw=b._emscripten_bind_btSliderConstraint_setUpperAngLimit_1=function(){return(rw=b._emscripten_bind_btSliderConstraint_setUpperAngLimit_1=b.asm._t).apply(null,arguments)},sw=b._emscripten_bind_btSliderConstraint_enableFeedback_1=function(){return(sw=b._emscripten_bind_btSliderConstraint_enableFeedback_1=b.asm.$t).apply(null,arguments)},tw=b._emscripten_bind_btSliderConstraint_getBreakingImpulseThreshold_0=function(){return(tw=b._emscripten_bind_btSliderConstraint_getBreakingImpulseThreshold_0= +b.asm.au).apply(null,arguments)},uw=b._emscripten_bind_btSliderConstraint_setBreakingImpulseThreshold_1=function(){return(uw=b._emscripten_bind_btSliderConstraint_setBreakingImpulseThreshold_1=b.asm.bu).apply(null,arguments)},vw=b._emscripten_bind_btSliderConstraint_getParam_2=function(){return(vw=b._emscripten_bind_btSliderConstraint_getParam_2=b.asm.cu).apply(null,arguments)},ww=b._emscripten_bind_btSliderConstraint_setParam_3=function(){return(ww=b._emscripten_bind_btSliderConstraint_setParam_3= +b.asm.du).apply(null,arguments)},xw=b._emscripten_bind_btSliderConstraint___destroy___0=function(){return(xw=b._emscripten_bind_btSliderConstraint___destroy___0=b.asm.eu).apply(null,arguments)},yw=b._emscripten_bind_btPairCachingGhostObject_btPairCachingGhostObject_0=function(){return(yw=b._emscripten_bind_btPairCachingGhostObject_btPairCachingGhostObject_0=b.asm.fu).apply(null,arguments)},zw=b._emscripten_bind_btPairCachingGhostObject_setAnisotropicFriction_2=function(){return(zw=b._emscripten_bind_btPairCachingGhostObject_setAnisotropicFriction_2= +b.asm.gu).apply(null,arguments)},Aw=b._emscripten_bind_btPairCachingGhostObject_getCollisionShape_0=function(){return(Aw=b._emscripten_bind_btPairCachingGhostObject_getCollisionShape_0=b.asm.hu).apply(null,arguments)},Bw=b._emscripten_bind_btPairCachingGhostObject_setContactProcessingThreshold_1=function(){return(Bw=b._emscripten_bind_btPairCachingGhostObject_setContactProcessingThreshold_1=b.asm.iu).apply(null,arguments)},Cw=b._emscripten_bind_btPairCachingGhostObject_setActivationState_1=function(){return(Cw= +b._emscripten_bind_btPairCachingGhostObject_setActivationState_1=b.asm.ju).apply(null,arguments)},Dw=b._emscripten_bind_btPairCachingGhostObject_forceActivationState_1=function(){return(Dw=b._emscripten_bind_btPairCachingGhostObject_forceActivationState_1=b.asm.ku).apply(null,arguments)},Ew=b._emscripten_bind_btPairCachingGhostObject_activate_0=function(){return(Ew=b._emscripten_bind_btPairCachingGhostObject_activate_0=b.asm.lu).apply(null,arguments)},Fw=b._emscripten_bind_btPairCachingGhostObject_activate_1= +function(){return(Fw=b._emscripten_bind_btPairCachingGhostObject_activate_1=b.asm.mu).apply(null,arguments)},Gw=b._emscripten_bind_btPairCachingGhostObject_isActive_0=function(){return(Gw=b._emscripten_bind_btPairCachingGhostObject_isActive_0=b.asm.nu).apply(null,arguments)},Hw=b._emscripten_bind_btPairCachingGhostObject_isKinematicObject_0=function(){return(Hw=b._emscripten_bind_btPairCachingGhostObject_isKinematicObject_0=b.asm.ou).apply(null,arguments)},Iw=b._emscripten_bind_btPairCachingGhostObject_isStaticObject_0= +function(){return(Iw=b._emscripten_bind_btPairCachingGhostObject_isStaticObject_0=b.asm.pu).apply(null,arguments)},Jw=b._emscripten_bind_btPairCachingGhostObject_isStaticOrKinematicObject_0=function(){return(Jw=b._emscripten_bind_btPairCachingGhostObject_isStaticOrKinematicObject_0=b.asm.qu).apply(null,arguments)},Kw=b._emscripten_bind_btPairCachingGhostObject_getRestitution_0=function(){return(Kw=b._emscripten_bind_btPairCachingGhostObject_getRestitution_0=b.asm.ru).apply(null,arguments)},Lw=b._emscripten_bind_btPairCachingGhostObject_getFriction_0= +function(){return(Lw=b._emscripten_bind_btPairCachingGhostObject_getFriction_0=b.asm.su).apply(null,arguments)},Mw=b._emscripten_bind_btPairCachingGhostObject_getRollingFriction_0=function(){return(Mw=b._emscripten_bind_btPairCachingGhostObject_getRollingFriction_0=b.asm.tu).apply(null,arguments)},Nw=b._emscripten_bind_btPairCachingGhostObject_setRestitution_1=function(){return(Nw=b._emscripten_bind_btPairCachingGhostObject_setRestitution_1=b.asm.uu).apply(null,arguments)},Ow=b._emscripten_bind_btPairCachingGhostObject_setFriction_1= +function(){return(Ow=b._emscripten_bind_btPairCachingGhostObject_setFriction_1=b.asm.vu).apply(null,arguments)},Pw=b._emscripten_bind_btPairCachingGhostObject_setRollingFriction_1=function(){return(Pw=b._emscripten_bind_btPairCachingGhostObject_setRollingFriction_1=b.asm.wu).apply(null,arguments)},Qw=b._emscripten_bind_btPairCachingGhostObject_getWorldTransform_0=function(){return(Qw=b._emscripten_bind_btPairCachingGhostObject_getWorldTransform_0=b.asm.xu).apply(null,arguments)},Rw=b._emscripten_bind_btPairCachingGhostObject_getCollisionFlags_0= +function(){return(Rw=b._emscripten_bind_btPairCachingGhostObject_getCollisionFlags_0=b.asm.yu).apply(null,arguments)},Sw=b._emscripten_bind_btPairCachingGhostObject_setCollisionFlags_1=function(){return(Sw=b._emscripten_bind_btPairCachingGhostObject_setCollisionFlags_1=b.asm.zu).apply(null,arguments)},Tw=b._emscripten_bind_btPairCachingGhostObject_setWorldTransform_1=function(){return(Tw=b._emscripten_bind_btPairCachingGhostObject_setWorldTransform_1=b.asm.Au).apply(null,arguments)},Uw=b._emscripten_bind_btPairCachingGhostObject_setCollisionShape_1= +function(){return(Uw=b._emscripten_bind_btPairCachingGhostObject_setCollisionShape_1=b.asm.Bu).apply(null,arguments)},Vw=b._emscripten_bind_btPairCachingGhostObject_setCcdMotionThreshold_1=function(){return(Vw=b._emscripten_bind_btPairCachingGhostObject_setCcdMotionThreshold_1=b.asm.Cu).apply(null,arguments)},Ww=b._emscripten_bind_btPairCachingGhostObject_setCcdSweptSphereRadius_1=function(){return(Ww=b._emscripten_bind_btPairCachingGhostObject_setCcdSweptSphereRadius_1=b.asm.Du).apply(null,arguments)}, +Xw=b._emscripten_bind_btPairCachingGhostObject_getUserIndex_0=function(){return(Xw=b._emscripten_bind_btPairCachingGhostObject_getUserIndex_0=b.asm.Eu).apply(null,arguments)},Yw=b._emscripten_bind_btPairCachingGhostObject_setUserIndex_1=function(){return(Yw=b._emscripten_bind_btPairCachingGhostObject_setUserIndex_1=b.asm.Fu).apply(null,arguments)},Zw=b._emscripten_bind_btPairCachingGhostObject_getUserPointer_0=function(){return(Zw=b._emscripten_bind_btPairCachingGhostObject_getUserPointer_0=b.asm.Gu).apply(null, +arguments)},$w=b._emscripten_bind_btPairCachingGhostObject_setUserPointer_1=function(){return($w=b._emscripten_bind_btPairCachingGhostObject_setUserPointer_1=b.asm.Hu).apply(null,arguments)},ax=b._emscripten_bind_btPairCachingGhostObject_getBroadphaseHandle_0=function(){return(ax=b._emscripten_bind_btPairCachingGhostObject_getBroadphaseHandle_0=b.asm.Iu).apply(null,arguments)},bx=b._emscripten_bind_btPairCachingGhostObject_getNumOverlappingObjects_0=function(){return(bx=b._emscripten_bind_btPairCachingGhostObject_getNumOverlappingObjects_0= +b.asm.Ju).apply(null,arguments)},cx=b._emscripten_bind_btPairCachingGhostObject_getOverlappingObject_1=function(){return(cx=b._emscripten_bind_btPairCachingGhostObject_getOverlappingObject_1=b.asm.Ku).apply(null,arguments)},dx=b._emscripten_bind_btPairCachingGhostObject___destroy___0=function(){return(dx=b._emscripten_bind_btPairCachingGhostObject___destroy___0=b.asm.Lu).apply(null,arguments)},ex=b._emscripten_bind_btManifoldPoint_getPositionWorldOnA_0=function(){return(ex=b._emscripten_bind_btManifoldPoint_getPositionWorldOnA_0= +b.asm.Mu).apply(null,arguments)},fx=b._emscripten_bind_btManifoldPoint_getPositionWorldOnB_0=function(){return(fx=b._emscripten_bind_btManifoldPoint_getPositionWorldOnB_0=b.asm.Nu).apply(null,arguments)},gx=b._emscripten_bind_btManifoldPoint_getAppliedImpulse_0=function(){return(gx=b._emscripten_bind_btManifoldPoint_getAppliedImpulse_0=b.asm.Ou).apply(null,arguments)},hx=b._emscripten_bind_btManifoldPoint_getDistance_0=function(){return(hx=b._emscripten_bind_btManifoldPoint_getDistance_0=b.asm.Pu).apply(null, +arguments)},ix=b._emscripten_bind_btManifoldPoint_get_m_localPointA_0=function(){return(ix=b._emscripten_bind_btManifoldPoint_get_m_localPointA_0=b.asm.Qu).apply(null,arguments)},jx=b._emscripten_bind_btManifoldPoint_set_m_localPointA_1=function(){return(jx=b._emscripten_bind_btManifoldPoint_set_m_localPointA_1=b.asm.Ru).apply(null,arguments)},kx=b._emscripten_bind_btManifoldPoint_get_m_localPointB_0=function(){return(kx=b._emscripten_bind_btManifoldPoint_get_m_localPointB_0=b.asm.Su).apply(null, +arguments)},lx=b._emscripten_bind_btManifoldPoint_set_m_localPointB_1=function(){return(lx=b._emscripten_bind_btManifoldPoint_set_m_localPointB_1=b.asm.Tu).apply(null,arguments)},mx=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnB_0=function(){return(mx=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnB_0=b.asm.Uu).apply(null,arguments)},nx=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnB_1=function(){return(nx=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnB_1=b.asm.Vu).apply(null, +arguments)},ox=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnA_0=function(){return(ox=b._emscripten_bind_btManifoldPoint_get_m_positionWorldOnA_0=b.asm.Wu).apply(null,arguments)},px=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnA_1=function(){return(px=b._emscripten_bind_btManifoldPoint_set_m_positionWorldOnA_1=b.asm.Xu).apply(null,arguments)},qx=b._emscripten_bind_btManifoldPoint_get_m_normalWorldOnB_0=function(){return(qx=b._emscripten_bind_btManifoldPoint_get_m_normalWorldOnB_0= +b.asm.Yu).apply(null,arguments)},rx=b._emscripten_bind_btManifoldPoint_set_m_normalWorldOnB_1=function(){return(rx=b._emscripten_bind_btManifoldPoint_set_m_normalWorldOnB_1=b.asm.Zu).apply(null,arguments)},sx=b._emscripten_bind_btManifoldPoint_get_m_userPersistentData_0=function(){return(sx=b._emscripten_bind_btManifoldPoint_get_m_userPersistentData_0=b.asm._u).apply(null,arguments)},tx=b._emscripten_bind_btManifoldPoint_set_m_userPersistentData_1=function(){return(tx=b._emscripten_bind_btManifoldPoint_set_m_userPersistentData_1= +b.asm.$u).apply(null,arguments)},ux=b._emscripten_bind_btManifoldPoint___destroy___0=function(){return(ux=b._emscripten_bind_btManifoldPoint___destroy___0=b.asm.av).apply(null,arguments)},vx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_2=function(){return(vx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_2=b.asm.bv).apply(null,arguments)},wx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_4=function(){return(wx=b._emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_4= +b.asm.cv).apply(null,arguments)},xx=b._emscripten_bind_btPoint2PointConstraint_setPivotA_1=function(){return(xx=b._emscripten_bind_btPoint2PointConstraint_setPivotA_1=b.asm.dv).apply(null,arguments)},yx=b._emscripten_bind_btPoint2PointConstraint_setPivotB_1=function(){return(yx=b._emscripten_bind_btPoint2PointConstraint_setPivotB_1=b.asm.ev).apply(null,arguments)},zx=b._emscripten_bind_btPoint2PointConstraint_getPivotInA_0=function(){return(zx=b._emscripten_bind_btPoint2PointConstraint_getPivotInA_0= +b.asm.fv).apply(null,arguments)},Ax=b._emscripten_bind_btPoint2PointConstraint_getPivotInB_0=function(){return(Ax=b._emscripten_bind_btPoint2PointConstraint_getPivotInB_0=b.asm.gv).apply(null,arguments)},Bx=b._emscripten_bind_btPoint2PointConstraint_enableFeedback_1=function(){return(Bx=b._emscripten_bind_btPoint2PointConstraint_enableFeedback_1=b.asm.hv).apply(null,arguments)},Cx=b._emscripten_bind_btPoint2PointConstraint_getBreakingImpulseThreshold_0=function(){return(Cx=b._emscripten_bind_btPoint2PointConstraint_getBreakingImpulseThreshold_0= +b.asm.iv).apply(null,arguments)},Dx=b._emscripten_bind_btPoint2PointConstraint_setBreakingImpulseThreshold_1=function(){return(Dx=b._emscripten_bind_btPoint2PointConstraint_setBreakingImpulseThreshold_1=b.asm.jv).apply(null,arguments)},Ex=b._emscripten_bind_btPoint2PointConstraint_getParam_2=function(){return(Ex=b._emscripten_bind_btPoint2PointConstraint_getParam_2=b.asm.kv).apply(null,arguments)},Fx=b._emscripten_bind_btPoint2PointConstraint_setParam_3=function(){return(Fx=b._emscripten_bind_btPoint2PointConstraint_setParam_3= +b.asm.lv).apply(null,arguments)},Gx=b._emscripten_bind_btPoint2PointConstraint_get_m_setting_0=function(){return(Gx=b._emscripten_bind_btPoint2PointConstraint_get_m_setting_0=b.asm.mv).apply(null,arguments)},Hx=b._emscripten_bind_btPoint2PointConstraint_set_m_setting_1=function(){return(Hx=b._emscripten_bind_btPoint2PointConstraint_set_m_setting_1=b.asm.nv).apply(null,arguments)},Ix=b._emscripten_bind_btPoint2PointConstraint___destroy___0=function(){return(Ix=b._emscripten_bind_btPoint2PointConstraint___destroy___0= +b.asm.ov).apply(null,arguments)},Jx=b._emscripten_bind_btSoftBodyHelpers_btSoftBodyHelpers_0=function(){return(Jx=b._emscripten_bind_btSoftBodyHelpers_btSoftBodyHelpers_0=b.asm.pv).apply(null,arguments)},Kx=b._emscripten_bind_btSoftBodyHelpers_CreateRope_5=function(){return(Kx=b._emscripten_bind_btSoftBodyHelpers_CreateRope_5=b.asm.qv).apply(null,arguments)},Lx=b._emscripten_bind_btSoftBodyHelpers_CreatePatch_9=function(){return(Lx=b._emscripten_bind_btSoftBodyHelpers_CreatePatch_9=b.asm.rv).apply(null, +arguments)},Mx=b._emscripten_bind_btSoftBodyHelpers_CreatePatchUV_10=function(){return(Mx=b._emscripten_bind_btSoftBodyHelpers_CreatePatchUV_10=b.asm.sv).apply(null,arguments)},Nx=b._emscripten_bind_btSoftBodyHelpers_CreateEllipsoid_4=function(){return(Nx=b._emscripten_bind_btSoftBodyHelpers_CreateEllipsoid_4=b.asm.tv).apply(null,arguments)},Ox=b._emscripten_bind_btSoftBodyHelpers_CreateFromTriMesh_5=function(){return(Ox=b._emscripten_bind_btSoftBodyHelpers_CreateFromTriMesh_5=b.asm.uv).apply(null, +arguments)},Px=b._emscripten_bind_btSoftBodyHelpers_CreateFromConvexHull_4=function(){return(Px=b._emscripten_bind_btSoftBodyHelpers_CreateFromConvexHull_4=b.asm.vv).apply(null,arguments)},Qx=b._emscripten_bind_btSoftBodyHelpers___destroy___0=function(){return(Qx=b._emscripten_bind_btSoftBodyHelpers___destroy___0=b.asm.wv).apply(null,arguments)},Rx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterGroup_0=function(){return(Rx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterGroup_0= +b.asm.xv).apply(null,arguments)},Sx=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterGroup_1=function(){return(Sx=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterGroup_1=b.asm.yv).apply(null,arguments)},Tx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterMask_0=function(){return(Tx=b._emscripten_bind_btBroadphaseProxy_get_m_collisionFilterMask_0=b.asm.zv).apply(null,arguments)},Ux=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterMask_1=function(){return(Ux=b._emscripten_bind_btBroadphaseProxy_set_m_collisionFilterMask_1= +b.asm.Av).apply(null,arguments)},Vx=b._emscripten_bind_btBroadphaseProxy___destroy___0=function(){return(Vx=b._emscripten_bind_btBroadphaseProxy___destroy___0=b.asm.Bv).apply(null,arguments)},Wx=b._emscripten_bind_tNodeArray_size_0=function(){return(Wx=b._emscripten_bind_tNodeArray_size_0=b.asm.Cv).apply(null,arguments)},Xx=b._emscripten_bind_tNodeArray_at_1=function(){return(Xx=b._emscripten_bind_tNodeArray_at_1=b.asm.Dv).apply(null,arguments)},Yx=b._emscripten_bind_tNodeArray___destroy___0=function(){return(Yx= +b._emscripten_bind_tNodeArray___destroy___0=b.asm.Ev).apply(null,arguments)},Zx=b._emscripten_bind_btBoxShape_btBoxShape_1=function(){return(Zx=b._emscripten_bind_btBoxShape_btBoxShape_1=b.asm.Fv).apply(null,arguments)},$x=b._emscripten_bind_btBoxShape_setMargin_1=function(){return($x=b._emscripten_bind_btBoxShape_setMargin_1=b.asm.Gv).apply(null,arguments)},ay=b._emscripten_bind_btBoxShape_getMargin_0=function(){return(ay=b._emscripten_bind_btBoxShape_getMargin_0=b.asm.Hv).apply(null,arguments)}, +by=b._emscripten_bind_btBoxShape_setLocalScaling_1=function(){return(by=b._emscripten_bind_btBoxShape_setLocalScaling_1=b.asm.Iv).apply(null,arguments)},cy=b._emscripten_bind_btBoxShape_getLocalScaling_0=function(){return(cy=b._emscripten_bind_btBoxShape_getLocalScaling_0=b.asm.Jv).apply(null,arguments)},dy=b._emscripten_bind_btBoxShape_calculateLocalInertia_2=function(){return(dy=b._emscripten_bind_btBoxShape_calculateLocalInertia_2=b.asm.Kv).apply(null,arguments)},ey=b._emscripten_bind_btBoxShape___destroy___0= +function(){return(ey=b._emscripten_bind_btBoxShape___destroy___0=b.asm.Lv).apply(null,arguments)},fy=b._emscripten_bind_btFace_get_m_indices_0=function(){return(fy=b._emscripten_bind_btFace_get_m_indices_0=b.asm.Mv).apply(null,arguments)},gy=b._emscripten_bind_btFace_set_m_indices_1=function(){return(gy=b._emscripten_bind_btFace_set_m_indices_1=b.asm.Nv).apply(null,arguments)},hy=b._emscripten_bind_btFace_get_m_plane_1=function(){return(hy=b._emscripten_bind_btFace_get_m_plane_1=b.asm.Ov).apply(null, +arguments)},iy=b._emscripten_bind_btFace_set_m_plane_2=function(){return(iy=b._emscripten_bind_btFace_set_m_plane_2=b.asm.Pv).apply(null,arguments)},jy=b._emscripten_bind_btFace___destroy___0=function(){return(jy=b._emscripten_bind_btFace___destroy___0=b.asm.Qv).apply(null,arguments)},ky=b._emscripten_bind_DebugDrawer_DebugDrawer_0=function(){return(ky=b._emscripten_bind_DebugDrawer_DebugDrawer_0=b.asm.Rv).apply(null,arguments)},ly=b._emscripten_bind_DebugDrawer_drawLine_3=function(){return(ly=b._emscripten_bind_DebugDrawer_drawLine_3= +b.asm.Sv).apply(null,arguments)},my=b._emscripten_bind_DebugDrawer_drawContactPoint_5=function(){return(my=b._emscripten_bind_DebugDrawer_drawContactPoint_5=b.asm.Tv).apply(null,arguments)},ny=b._emscripten_bind_DebugDrawer_reportErrorWarning_1=function(){return(ny=b._emscripten_bind_DebugDrawer_reportErrorWarning_1=b.asm.Uv).apply(null,arguments)},oy=b._emscripten_bind_DebugDrawer_draw3dText_2=function(){return(oy=b._emscripten_bind_DebugDrawer_draw3dText_2=b.asm.Vv).apply(null,arguments)},py=b._emscripten_bind_DebugDrawer_setDebugMode_1= +function(){return(py=b._emscripten_bind_DebugDrawer_setDebugMode_1=b.asm.Wv).apply(null,arguments)},qy=b._emscripten_bind_DebugDrawer_getDebugMode_0=function(){return(qy=b._emscripten_bind_DebugDrawer_getDebugMode_0=b.asm.Xv).apply(null,arguments)},ry=b._emscripten_bind_DebugDrawer___destroy___0=function(){return(ry=b._emscripten_bind_DebugDrawer___destroy___0=b.asm.Yv).apply(null,arguments)},sy=b._emscripten_bind_btCapsuleShapeX_btCapsuleShapeX_2=function(){return(sy=b._emscripten_bind_btCapsuleShapeX_btCapsuleShapeX_2= +b.asm.Zv).apply(null,arguments)},ty=b._emscripten_bind_btCapsuleShapeX_setMargin_1=function(){return(ty=b._emscripten_bind_btCapsuleShapeX_setMargin_1=b.asm._v).apply(null,arguments)},uy=b._emscripten_bind_btCapsuleShapeX_getMargin_0=function(){return(uy=b._emscripten_bind_btCapsuleShapeX_getMargin_0=b.asm.$v).apply(null,arguments)},vy=b._emscripten_bind_btCapsuleShapeX_getUpAxis_0=function(){return(vy=b._emscripten_bind_btCapsuleShapeX_getUpAxis_0=b.asm.aw).apply(null,arguments)},wy=b._emscripten_bind_btCapsuleShapeX_getRadius_0= +function(){return(wy=b._emscripten_bind_btCapsuleShapeX_getRadius_0=b.asm.bw).apply(null,arguments)},xy=b._emscripten_bind_btCapsuleShapeX_getHalfHeight_0=function(){return(xy=b._emscripten_bind_btCapsuleShapeX_getHalfHeight_0=b.asm.cw).apply(null,arguments)},yy=b._emscripten_bind_btCapsuleShapeX_setLocalScaling_1=function(){return(yy=b._emscripten_bind_btCapsuleShapeX_setLocalScaling_1=b.asm.dw).apply(null,arguments)},zy=b._emscripten_bind_btCapsuleShapeX_getLocalScaling_0=function(){return(zy=b._emscripten_bind_btCapsuleShapeX_getLocalScaling_0= +b.asm.ew).apply(null,arguments)},Ay=b._emscripten_bind_btCapsuleShapeX_calculateLocalInertia_2=function(){return(Ay=b._emscripten_bind_btCapsuleShapeX_calculateLocalInertia_2=b.asm.fw).apply(null,arguments)},By=b._emscripten_bind_btCapsuleShapeX___destroy___0=function(){return(By=b._emscripten_bind_btCapsuleShapeX___destroy___0=b.asm.gw).apply(null,arguments)},Cy=b._emscripten_bind_btQuaternion_btQuaternion_4=function(){return(Cy=b._emscripten_bind_btQuaternion_btQuaternion_4=b.asm.hw).apply(null, +arguments)},Dy=b._emscripten_bind_btQuaternion_setValue_4=function(){return(Dy=b._emscripten_bind_btQuaternion_setValue_4=b.asm.iw).apply(null,arguments)},Ey=b._emscripten_bind_btQuaternion_setEulerZYX_3=function(){return(Ey=b._emscripten_bind_btQuaternion_setEulerZYX_3=b.asm.jw).apply(null,arguments)},Fy=b._emscripten_bind_btQuaternion_setRotation_2=function(){return(Fy=b._emscripten_bind_btQuaternion_setRotation_2=b.asm.kw).apply(null,arguments)},Gy=b._emscripten_bind_btQuaternion_normalize_0=function(){return(Gy= +b._emscripten_bind_btQuaternion_normalize_0=b.asm.lw).apply(null,arguments)},Hy=b._emscripten_bind_btQuaternion_length2_0=function(){return(Hy=b._emscripten_bind_btQuaternion_length2_0=b.asm.mw).apply(null,arguments)},Iy=b._emscripten_bind_btQuaternion_length_0=function(){return(Iy=b._emscripten_bind_btQuaternion_length_0=b.asm.nw).apply(null,arguments)},Jy=b._emscripten_bind_btQuaternion_dot_1=function(){return(Jy=b._emscripten_bind_btQuaternion_dot_1=b.asm.ow).apply(null,arguments)},Ky=b._emscripten_bind_btQuaternion_normalized_0= +function(){return(Ky=b._emscripten_bind_btQuaternion_normalized_0=b.asm.pw).apply(null,arguments)},Ly=b._emscripten_bind_btQuaternion_getAxis_0=function(){return(Ly=b._emscripten_bind_btQuaternion_getAxis_0=b.asm.qw).apply(null,arguments)},My=b._emscripten_bind_btQuaternion_inverse_0=function(){return(My=b._emscripten_bind_btQuaternion_inverse_0=b.asm.rw).apply(null,arguments)},Ny=b._emscripten_bind_btQuaternion_getAngle_0=function(){return(Ny=b._emscripten_bind_btQuaternion_getAngle_0=b.asm.sw).apply(null, +arguments)},Oy=b._emscripten_bind_btQuaternion_getAngleShortestPath_0=function(){return(Oy=b._emscripten_bind_btQuaternion_getAngleShortestPath_0=b.asm.tw).apply(null,arguments)},Py=b._emscripten_bind_btQuaternion_angle_1=function(){return(Py=b._emscripten_bind_btQuaternion_angle_1=b.asm.uw).apply(null,arguments)},Qy=b._emscripten_bind_btQuaternion_angleShortestPath_1=function(){return(Qy=b._emscripten_bind_btQuaternion_angleShortestPath_1=b.asm.vw).apply(null,arguments)},Ry=b._emscripten_bind_btQuaternion_op_add_1= +function(){return(Ry=b._emscripten_bind_btQuaternion_op_add_1=b.asm.ww).apply(null,arguments)},Sy=b._emscripten_bind_btQuaternion_op_sub_1=function(){return(Sy=b._emscripten_bind_btQuaternion_op_sub_1=b.asm.xw).apply(null,arguments)},Ty=b._emscripten_bind_btQuaternion_op_mul_1=function(){return(Ty=b._emscripten_bind_btQuaternion_op_mul_1=b.asm.yw).apply(null,arguments)},Uy=b._emscripten_bind_btQuaternion_op_mulq_1=function(){return(Uy=b._emscripten_bind_btQuaternion_op_mulq_1=b.asm.zw).apply(null, +arguments)},Vy=b._emscripten_bind_btQuaternion_op_div_1=function(){return(Vy=b._emscripten_bind_btQuaternion_op_div_1=b.asm.Aw).apply(null,arguments)},Wy=b._emscripten_bind_btQuaternion_x_0=function(){return(Wy=b._emscripten_bind_btQuaternion_x_0=b.asm.Bw).apply(null,arguments)},Xy=b._emscripten_bind_btQuaternion_y_0=function(){return(Xy=b._emscripten_bind_btQuaternion_y_0=b.asm.Cw).apply(null,arguments)},Yy=b._emscripten_bind_btQuaternion_z_0=function(){return(Yy=b._emscripten_bind_btQuaternion_z_0= +b.asm.Dw).apply(null,arguments)},Zy=b._emscripten_bind_btQuaternion_w_0=function(){return(Zy=b._emscripten_bind_btQuaternion_w_0=b.asm.Ew).apply(null,arguments)},$y=b._emscripten_bind_btQuaternion_setX_1=function(){return($y=b._emscripten_bind_btQuaternion_setX_1=b.asm.Fw).apply(null,arguments)},az=b._emscripten_bind_btQuaternion_setY_1=function(){return(az=b._emscripten_bind_btQuaternion_setY_1=b.asm.Gw).apply(null,arguments)},bz=b._emscripten_bind_btQuaternion_setZ_1=function(){return(bz=b._emscripten_bind_btQuaternion_setZ_1= +b.asm.Hw).apply(null,arguments)},cz=b._emscripten_bind_btQuaternion_setW_1=function(){return(cz=b._emscripten_bind_btQuaternion_setW_1=b.asm.Iw).apply(null,arguments)},dz=b._emscripten_bind_btQuaternion___destroy___0=function(){return(dz=b._emscripten_bind_btQuaternion___destroy___0=b.asm.Jw).apply(null,arguments)},ez=b._emscripten_bind_btCapsuleShapeZ_btCapsuleShapeZ_2=function(){return(ez=b._emscripten_bind_btCapsuleShapeZ_btCapsuleShapeZ_2=b.asm.Kw).apply(null,arguments)},fz=b._emscripten_bind_btCapsuleShapeZ_setMargin_1= +function(){return(fz=b._emscripten_bind_btCapsuleShapeZ_setMargin_1=b.asm.Lw).apply(null,arguments)},gz=b._emscripten_bind_btCapsuleShapeZ_getMargin_0=function(){return(gz=b._emscripten_bind_btCapsuleShapeZ_getMargin_0=b.asm.Mw).apply(null,arguments)},hz=b._emscripten_bind_btCapsuleShapeZ_getUpAxis_0=function(){return(hz=b._emscripten_bind_btCapsuleShapeZ_getUpAxis_0=b.asm.Nw).apply(null,arguments)},iz=b._emscripten_bind_btCapsuleShapeZ_getRadius_0=function(){return(iz=b._emscripten_bind_btCapsuleShapeZ_getRadius_0= +b.asm.Ow).apply(null,arguments)},jz=b._emscripten_bind_btCapsuleShapeZ_getHalfHeight_0=function(){return(jz=b._emscripten_bind_btCapsuleShapeZ_getHalfHeight_0=b.asm.Pw).apply(null,arguments)},kz=b._emscripten_bind_btCapsuleShapeZ_setLocalScaling_1=function(){return(kz=b._emscripten_bind_btCapsuleShapeZ_setLocalScaling_1=b.asm.Qw).apply(null,arguments)},lz=b._emscripten_bind_btCapsuleShapeZ_getLocalScaling_0=function(){return(lz=b._emscripten_bind_btCapsuleShapeZ_getLocalScaling_0=b.asm.Rw).apply(null, +arguments)},mz=b._emscripten_bind_btCapsuleShapeZ_calculateLocalInertia_2=function(){return(mz=b._emscripten_bind_btCapsuleShapeZ_calculateLocalInertia_2=b.asm.Sw).apply(null,arguments)},nz=b._emscripten_bind_btCapsuleShapeZ___destroy___0=function(){return(nz=b._emscripten_bind_btCapsuleShapeZ___destroy___0=b.asm.Tw).apply(null,arguments)},oz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulse_0=function(){return(oz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulse_0=b.asm.Uw).apply(null, +arguments)},pz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulse_1=function(){return(pz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulse_1=b.asm.Vw).apply(null,arguments)},qz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulsePenetrationThreshold_0=function(){return(qz=b._emscripten_bind_btContactSolverInfo_get_m_splitImpulsePenetrationThreshold_0=b.asm.Ww).apply(null,arguments)},rz=b._emscripten_bind_btContactSolverInfo_set_m_splitImpulsePenetrationThreshold_1=function(){return(rz= +b._emscripten_bind_btContactSolverInfo_set_m_splitImpulsePenetrationThreshold_1=b.asm.Xw).apply(null,arguments)},sz=b._emscripten_bind_btContactSolverInfo_get_m_numIterations_0=function(){return(sz=b._emscripten_bind_btContactSolverInfo_get_m_numIterations_0=b.asm.Yw).apply(null,arguments)},tz=b._emscripten_bind_btContactSolverInfo_set_m_numIterations_1=function(){return(tz=b._emscripten_bind_btContactSolverInfo_set_m_numIterations_1=b.asm.Zw).apply(null,arguments)},uz=b._emscripten_bind_btContactSolverInfo___destroy___0= +function(){return(uz=b._emscripten_bind_btContactSolverInfo___destroy___0=b.asm._w).apply(null,arguments)},vz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_3=function(){return(vz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_3=b.asm.$w).apply(null,arguments)},wz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_5=function(){return(wz=b._emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_5= +b.asm.ax).apply(null,arguments)},xz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableSpring_2=function(){return(xz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableSpring_2=b.asm.bx).apply(null,arguments)},yz=b._emscripten_bind_btGeneric6DofSpringConstraint_setStiffness_2=function(){return(yz=b._emscripten_bind_btGeneric6DofSpringConstraint_setStiffness_2=b.asm.cx).apply(null,arguments)},zz=b._emscripten_bind_btGeneric6DofSpringConstraint_setDamping_2=function(){return(zz=b._emscripten_bind_btGeneric6DofSpringConstraint_setDamping_2= +b.asm.dx).apply(null,arguments)},Az=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_0=function(){return(Az=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_0=b.asm.ex).apply(null,arguments)},Bz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_1=function(){return(Bz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_1=b.asm.fx).apply(null,arguments)},Cz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_2= +function(){return(Cz=b._emscripten_bind_btGeneric6DofSpringConstraint_setEquilibriumPoint_2=b.asm.gx).apply(null,arguments)},Dz=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearLowerLimit_1=function(){return(Dz=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearLowerLimit_1=b.asm.hx).apply(null,arguments)},Ez=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearUpperLimit_1=function(){return(Ez=b._emscripten_bind_btGeneric6DofSpringConstraint_setLinearUpperLimit_1=b.asm.ix).apply(null, +arguments)},Fz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularLowerLimit_1=function(){return(Fz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularLowerLimit_1=b.asm.jx).apply(null,arguments)},Gz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularUpperLimit_1=function(){return(Gz=b._emscripten_bind_btGeneric6DofSpringConstraint_setAngularUpperLimit_1=b.asm.kx).apply(null,arguments)},Hz=b._emscripten_bind_btGeneric6DofSpringConstraint_getFrameOffsetA_0=function(){return(Hz= +b._emscripten_bind_btGeneric6DofSpringConstraint_getFrameOffsetA_0=b.asm.lx).apply(null,arguments)},Iz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableFeedback_1=function(){return(Iz=b._emscripten_bind_btGeneric6DofSpringConstraint_enableFeedback_1=b.asm.mx).apply(null,arguments)},Jz=b._emscripten_bind_btGeneric6DofSpringConstraint_getBreakingImpulseThreshold_0=function(){return(Jz=b._emscripten_bind_btGeneric6DofSpringConstraint_getBreakingImpulseThreshold_0=b.asm.nx).apply(null,arguments)}, +Kz=b._emscripten_bind_btGeneric6DofSpringConstraint_setBreakingImpulseThreshold_1=function(){return(Kz=b._emscripten_bind_btGeneric6DofSpringConstraint_setBreakingImpulseThreshold_1=b.asm.ox).apply(null,arguments)},Lz=b._emscripten_bind_btGeneric6DofSpringConstraint_getParam_2=function(){return(Lz=b._emscripten_bind_btGeneric6DofSpringConstraint_getParam_2=b.asm.px).apply(null,arguments)},Mz=b._emscripten_bind_btGeneric6DofSpringConstraint_setParam_3=function(){return(Mz=b._emscripten_bind_btGeneric6DofSpringConstraint_setParam_3= +b.asm.qx).apply(null,arguments)},Nz=b._emscripten_bind_btGeneric6DofSpringConstraint___destroy___0=function(){return(Nz=b._emscripten_bind_btGeneric6DofSpringConstraint___destroy___0=b.asm.rx).apply(null,arguments)},Oz=b._emscripten_bind_btSphereShape_btSphereShape_1=function(){return(Oz=b._emscripten_bind_btSphereShape_btSphereShape_1=b.asm.sx).apply(null,arguments)},Pz=b._emscripten_bind_btSphereShape_setMargin_1=function(){return(Pz=b._emscripten_bind_btSphereShape_setMargin_1=b.asm.tx).apply(null, +arguments)},Qz=b._emscripten_bind_btSphereShape_getMargin_0=function(){return(Qz=b._emscripten_bind_btSphereShape_getMargin_0=b.asm.ux).apply(null,arguments)},Rz=b._emscripten_bind_btSphereShape_setLocalScaling_1=function(){return(Rz=b._emscripten_bind_btSphereShape_setLocalScaling_1=b.asm.vx).apply(null,arguments)},Sz=b._emscripten_bind_btSphereShape_getLocalScaling_0=function(){return(Sz=b._emscripten_bind_btSphereShape_getLocalScaling_0=b.asm.wx).apply(null,arguments)},Tz=b._emscripten_bind_btSphereShape_calculateLocalInertia_2= +function(){return(Tz=b._emscripten_bind_btSphereShape_calculateLocalInertia_2=b.asm.xx).apply(null,arguments)},Uz=b._emscripten_bind_btSphereShape___destroy___0=function(){return(Uz=b._emscripten_bind_btSphereShape___destroy___0=b.asm.yx).apply(null,arguments)},Vz=b._emscripten_bind_Face_get_m_n_1=function(){return(Vz=b._emscripten_bind_Face_get_m_n_1=b.asm.zx).apply(null,arguments)},Wz=b._emscripten_bind_Face_set_m_n_2=function(){return(Wz=b._emscripten_bind_Face_set_m_n_2=b.asm.Ax).apply(null,arguments)}, +Xz=b._emscripten_bind_Face_get_m_normal_0=function(){return(Xz=b._emscripten_bind_Face_get_m_normal_0=b.asm.Bx).apply(null,arguments)},Yz=b._emscripten_bind_Face_set_m_normal_1=function(){return(Yz=b._emscripten_bind_Face_set_m_normal_1=b.asm.Cx).apply(null,arguments)},Zz=b._emscripten_bind_Face_get_m_ra_0=function(){return(Zz=b._emscripten_bind_Face_get_m_ra_0=b.asm.Dx).apply(null,arguments)},$z=b._emscripten_bind_Face_set_m_ra_1=function(){return($z=b._emscripten_bind_Face_set_m_ra_1=b.asm.Ex).apply(null, +arguments)},aA=b._emscripten_bind_Face___destroy___0=function(){return(aA=b._emscripten_bind_Face___destroy___0=b.asm.Fx).apply(null,arguments)},bA=b._emscripten_bind_tFaceArray_size_0=function(){return(bA=b._emscripten_bind_tFaceArray_size_0=b.asm.Gx).apply(null,arguments)},cA=b._emscripten_bind_tFaceArray_at_1=function(){return(cA=b._emscripten_bind_tFaceArray_at_1=b.asm.Hx).apply(null,arguments)},dA=b._emscripten_bind_tFaceArray___destroy___0=function(){return(dA=b._emscripten_bind_tFaceArray___destroy___0= +b.asm.Ix).apply(null,arguments)},eA=b._emscripten_bind_LocalConvexResult_LocalConvexResult_5=function(){return(eA=b._emscripten_bind_LocalConvexResult_LocalConvexResult_5=b.asm.Jx).apply(null,arguments)},fA=b._emscripten_bind_LocalConvexResult_get_m_hitCollisionObject_0=function(){return(fA=b._emscripten_bind_LocalConvexResult_get_m_hitCollisionObject_0=b.asm.Kx).apply(null,arguments)},gA=b._emscripten_bind_LocalConvexResult_set_m_hitCollisionObject_1=function(){return(gA=b._emscripten_bind_LocalConvexResult_set_m_hitCollisionObject_1= +b.asm.Lx).apply(null,arguments)},hA=b._emscripten_bind_LocalConvexResult_get_m_localShapeInfo_0=function(){return(hA=b._emscripten_bind_LocalConvexResult_get_m_localShapeInfo_0=b.asm.Mx).apply(null,arguments)},iA=b._emscripten_bind_LocalConvexResult_set_m_localShapeInfo_1=function(){return(iA=b._emscripten_bind_LocalConvexResult_set_m_localShapeInfo_1=b.asm.Nx).apply(null,arguments)},jA=b._emscripten_bind_LocalConvexResult_get_m_hitNormalLocal_0=function(){return(jA=b._emscripten_bind_LocalConvexResult_get_m_hitNormalLocal_0= +b.asm.Ox).apply(null,arguments)},kA=b._emscripten_bind_LocalConvexResult_set_m_hitNormalLocal_1=function(){return(kA=b._emscripten_bind_LocalConvexResult_set_m_hitNormalLocal_1=b.asm.Px).apply(null,arguments)},lA=b._emscripten_bind_LocalConvexResult_get_m_hitPointLocal_0=function(){return(lA=b._emscripten_bind_LocalConvexResult_get_m_hitPointLocal_0=b.asm.Qx).apply(null,arguments)},mA=b._emscripten_bind_LocalConvexResult_set_m_hitPointLocal_1=function(){return(mA=b._emscripten_bind_LocalConvexResult_set_m_hitPointLocal_1= +b.asm.Rx).apply(null,arguments)},nA=b._emscripten_bind_LocalConvexResult_get_m_hitFraction_0=function(){return(nA=b._emscripten_bind_LocalConvexResult_get_m_hitFraction_0=b.asm.Sx).apply(null,arguments)},oA=b._emscripten_bind_LocalConvexResult_set_m_hitFraction_1=function(){return(oA=b._emscripten_bind_LocalConvexResult_set_m_hitFraction_1=b.asm.Tx).apply(null,arguments)},pA=b._emscripten_bind_LocalConvexResult___destroy___0=function(){return(pA=b._emscripten_bind_LocalConvexResult___destroy___0= +b.asm.Ux).apply(null,arguments)},qA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_ERP=function(){return(qA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_ERP=b.asm.Vx).apply(null,arguments)},rA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_ERP=function(){return(rA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_ERP=b.asm.Wx).apply(null,arguments)},sA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_CFM=function(){return(sA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_CFM= +b.asm.Xx).apply(null,arguments)},tA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_CFM=function(){return(tA=b._emscripten_enum_btConstraintParams_BT_CONSTRAINT_STOP_CFM=b.asm.Yx).apply(null,arguments)},uA=b._emscripten_enum_PHY_ScalarType_PHY_FLOAT=function(){return(uA=b._emscripten_enum_PHY_ScalarType_PHY_FLOAT=b.asm.Zx).apply(null,arguments)},vA=b._emscripten_enum_PHY_ScalarType_PHY_DOUBLE=function(){return(vA=b._emscripten_enum_PHY_ScalarType_PHY_DOUBLE=b.asm._x).apply(null,arguments)}, +wA=b._emscripten_enum_PHY_ScalarType_PHY_INTEGER=function(){return(wA=b._emscripten_enum_PHY_ScalarType_PHY_INTEGER=b.asm.$x).apply(null,arguments)},xA=b._emscripten_enum_PHY_ScalarType_PHY_SHORT=function(){return(xA=b._emscripten_enum_PHY_ScalarType_PHY_SHORT=b.asm.ay).apply(null,arguments)},yA=b._emscripten_enum_PHY_ScalarType_PHY_FIXEDPOINT88=function(){return(yA=b._emscripten_enum_PHY_ScalarType_PHY_FIXEDPOINT88=b.asm.by).apply(null,arguments)},zA=b._emscripten_enum_PHY_ScalarType_PHY_UCHAR=function(){return(zA= +b._emscripten_enum_PHY_ScalarType_PHY_UCHAR=b.asm.cy).apply(null,arguments)};b._malloc=function(){return(b._malloc=b.asm.dy).apply(null,arguments)};b._free=function(){return(b._free=b.asm.ey).apply(null,arguments)};b.dynCall_vi=function(){return(b.dynCall_vi=b.asm.fy).apply(null,arguments)};b.dynCall_v=function(){return(b.dynCall_v=b.asm.gy).apply(null,arguments)}; +b.UTF8ToString=function(a,c){if(a){var d=a+c;for(c=a;za[c]&&!(c>=d);)++c;if(16e?d+=String.fromCharCode(e):(e-=65536,d+=String.fromCharCode(55296|e>>10,56320|e&1023))}}else d+=String.fromCharCode(e)}a=d}}else a="";return a};var AA; +Oa=function BA(){AA||CA();AA||(Oa=BA)}; +function CA(){function a(){if(!AA&&(AA=!0,b.calledRun=!0,!va)){Ka=!0;Fa(Ha);Fa(Ia);ba(b);if(b.onRuntimeInitialized)b.onRuntimeInitialized();if(b.postRun)for("function"==typeof b.postRun&&(b.postRun=[b.postRun]);b.postRun.length;){var c=b.postRun.shift();Ja.unshift(c)}Fa(Ja)}}if(!(0=EA?(assert(0>>=0;switch(c.BYTES_PER_ELEMENT){case 2:d>>>=1;break;case 4:d>>>=2;break;case 8:d>>>=3}for(var e=0;e=e&&(e=65536+((e&1023)<<10)|a.charCodeAt(++d)&1023);127>=e?++c:c=2047>=e?c+2:65535>=e?c+3:c+4}c=Array(c+1);e=c.length;d=0;if(0=n){var F=a.charCodeAt(++g);n=65536+((n&1023)<<10)|F&1023}if(127>=n){if(d>=e)break;c[d++]=n}else{if(2047>=n){if(d+1>=e)break;c[d++]=192|n>>6}else{if(65535>=n){if(d+2>=e)break;c[d++]=224| +n>>12}else{if(d+3>=e)break;c[d++]=240|n>>18;c[d++]=128|n>>12&63}c[d++]=128|n>>6&63}c[d++]=128|n&63}}c[d]=0}a=JA(c,ya);KA(c,ya,a)}return a}function MA(a){if("object"===typeof a){var c=JA(a,Ba);KA(a,Ba,c);return c}return a}function NA(){throw"cannot construct a btCollisionWorld, no constructor in IDL";}NA.prototype=Object.create(f.prototype);NA.prototype.constructor=NA;NA.prototype.iy=NA;NA.jy={};b.btCollisionWorld=NA;NA.prototype.getDispatcher=function(){return k($a(this.hy),OA)}; +NA.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ab(e,a,c,d)};NA.prototype.getPairCache=function(){return k(bb(this.hy),PA)};NA.prototype.getDispatchInfo=function(){return k(cb(this.hy),l)}; +NA.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?db(e,a):void 0===d?eb(e,a,c):fb(e,a,c,d)};NA.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gb(c,a)};NA.prototype.getBroadphase=function(){return k(hb(this.hy),QA)}; +NA.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);ib(n,a,c,d,e,g)};NA.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);jb(e,a,c,d)}; +NA.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);kb(d,a,c)};NA.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lb(c,a)};NA.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mb(c,a)};NA.prototype.getDebugDrawer=function(){return k(nb(this.hy),RA)};NA.prototype.debugDrawWorld=function(){ob(this.hy)}; +NA.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);pb(e,a,c,d)};NA.prototype.__destroy__=function(){qb(this.hy)};function m(){throw"cannot construct a btCollisionShape, no constructor in IDL";}m.prototype=Object.create(f.prototype);m.prototype.constructor=m;m.prototype.iy=m;m.jy={};b.btCollisionShape=m; +m.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rb(c,a)};m.prototype.getLocalScaling=function(){return k(sb(this.hy),p)};m.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tb(d,a,c)};m.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ub(c,a)};m.prototype.getMargin=function(){return vb(this.hy)};m.prototype.__destroy__=function(){wb(this.hy)}; +function q(){throw"cannot construct a btCollisionObject, no constructor in IDL";}q.prototype=Object.create(f.prototype);q.prototype.constructor=q;q.prototype.iy=q;q.jy={};b.btCollisionObject=q;q.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);xb(d,a,c)};q.prototype.getCollisionShape=function(){return k(yb(this.hy),m)}; +q.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zb(c,a)};q.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ab(c,a)};q.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bb(c,a)};q.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Cb(c):Db(c,a)};q.prototype.isActive=function(){return!!Eb(this.hy)};q.prototype.isKinematicObject=function(){return!!Fb(this.hy)}; +q.prototype.isStaticObject=function(){return!!Gb(this.hy)};q.prototype.isStaticOrKinematicObject=function(){return!!Hb(this.hy)};q.prototype.getRestitution=function(){return Ib(this.hy)};q.prototype.getFriction=function(){return Jb(this.hy)};q.prototype.getRollingFriction=function(){return Kb(this.hy)};q.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lb(c,a)};q.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mb(c,a)}; +q.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nb(c,a)};q.prototype.getWorldTransform=function(){return k(Ob(this.hy),r)};q.prototype.getCollisionFlags=function(){return Pb(this.hy)};q.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qb(c,a)};q.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sb(c,a)}; +q.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tb(c,a)};q.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ub(c,a)};q.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vb(c,a)};q.prototype.getUserIndex=function(){return Wb(this.hy)};q.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xb(c,a)}; +q.prototype.getUserPointer=function(){return k(Yb(this.hy),SA)};q.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zb(c,a)};q.prototype.getBroadphaseHandle=function(){return k($b(this.hy),t)};q.prototype.__destroy__=function(){ac(this.hy)};function u(){throw"cannot construct a btDynamicsWorld, no constructor in IDL";}u.prototype=Object.create(NA.prototype);u.prototype.constructor=u;u.prototype.iy=u;u.jy={};b.btDynamicsWorld=u; +u.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bc(c,a)};u.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cc(c,a)};u.prototype.getSolverInfo=function(){return k(dc(this.hy),v)};u.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?ec(e,a):void 0===d?fc(e,a,c):hc(e,a,c,d)}; +u.prototype.getDispatcher=function(){return k(ic(this.hy),OA)};u.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);jc(e,a,c,d)};u.prototype.getPairCache=function(){return k(kc(this.hy),PA)};u.prototype.getDispatchInfo=function(){return k(lc(this.hy),l)}; +u.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?mc(e,a):void 0===d?nc(e,a,c):oc(e,a,c,d)};u.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pc(c,a)};u.prototype.getBroadphase=function(){return k(qc(this.hy),QA)}; +u.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);rc(n,a,c,d,e,g)};u.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);sc(e,a,c,d)}; +u.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tc(d,a,c)};u.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uc(c,a)};u.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vc(c,a)};u.prototype.getDebugDrawer=function(){return k(wc(this.hy),RA)};u.prototype.debugDrawWorld=function(){xc(this.hy)}; +u.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);yc(e,a,c,d)};u.prototype.__destroy__=function(){zc(this.hy)};function TA(){throw"cannot construct a btTypedConstraint, no constructor in IDL";}TA.prototype=Object.create(f.prototype);TA.prototype.constructor=TA;TA.prototype.iy=TA;TA.jy={};b.btTypedConstraint=TA; +TA.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ac(c,a)};TA.prototype.getBreakingImpulseThreshold=function(){return Bc(this.hy)};TA.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cc(c,a)};TA.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Dc(d,a,c)}; +TA.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ec(e,a,c,d)};TA.prototype.__destroy__=function(){Fc(this.hy)};function UA(){throw"cannot construct a btConcaveShape, no constructor in IDL";}UA.prototype=Object.create(m.prototype);UA.prototype.constructor=UA;UA.prototype.iy=UA;UA.jy={};b.btConcaveShape=UA; +UA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gc(c,a)};UA.prototype.getLocalScaling=function(){return k(Hc(this.hy),p)};UA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ic(d,a,c)};UA.prototype.__destroy__=function(){Jc(this.hy)};function VA(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Kc(a,c);h(VA)[this.hy]=this}VA.prototype=Object.create(m.prototype); +VA.prototype.constructor=VA;VA.prototype.iy=VA;VA.jy={};b.btCapsuleShape=VA;VA.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lc(c,a)};VA.prototype.getMargin=function(){return Mc(this.hy)};VA.prototype.getUpAxis=function(){return Nc(this.hy)};VA.prototype.getRadius=function(){return Oc(this.hy)};VA.prototype.getHalfHeight=function(){return Pc(this.hy)};VA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qc(c,a)}; +VA.prototype.getLocalScaling=function(){return k(Rc(this.hy),p)};VA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Sc(d,a,c)};VA.prototype.__destroy__=function(){Tc(this.hy)};function RA(){throw"cannot construct a btIDebugDraw, no constructor in IDL";}RA.prototype=Object.create(f.prototype);RA.prototype.constructor=RA;RA.prototype.iy=RA;RA.jy={};b.btIDebugDraw=RA; +RA.prototype.drawLine=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Uc(e,a,c,d)};RA.prototype.drawContactPoint=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);Vc(n,a,c,d,e,g)}; +RA.prototype.reportErrorWarning=function(a){var c=this.hy;IA();a=a&&"object"===typeof a?a.hy:LA(a);Wc(c,a)};RA.prototype.draw3dText=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c=c&&"object"===typeof c?c.hy:LA(c);Xc(d,a,c)};RA.prototype.setDebugMode=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yc(c,a)};RA.prototype.getDebugMode=function(){return Zc(this.hy)};RA.prototype.__destroy__=function(){$c(this.hy)}; +function WA(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?ad():bd(a);h(WA)[this.hy]=this}WA.prototype=Object.create(f.prototype);WA.prototype.constructor=WA;WA.prototype.iy=WA;WA.jy={};b.btDefaultCollisionConfiguration=WA;WA.prototype.__destroy__=function(){cd(this.hy)};function XA(){throw"cannot construct a btTriangleMeshShape, no constructor in IDL";}XA.prototype=Object.create(UA.prototype);XA.prototype.constructor=XA;XA.prototype.iy=XA;XA.jy={};b.btTriangleMeshShape=XA; +XA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dd(c,a)};XA.prototype.getLocalScaling=function(){return k(ed(this.hy),p)};XA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);fd(d,a,c)};XA.prototype.__destroy__=function(){gd(this.hy)};function w(){this.hy=hd();h(w)[this.hy]=this}w.prototype=Object.create(q.prototype);w.prototype.constructor=w;w.prototype.iy=w;w.jy={}; +b.btGhostObject=w;w.prototype.getNumOverlappingObjects=function(){return id(this.hy)};w.prototype.getOverlappingObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(jd(c,a),q)};w.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);kd(d,a,c)};w.prototype.getCollisionShape=function(){return k(ld(this.hy),m)}; +w.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);md(c,a)};w.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nd(c,a)};w.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);od(c,a)};w.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?pd(c):qd(c,a)};w.prototype.isActive=function(){return!!rd(this.hy)};w.prototype.isKinematicObject=function(){return!!sd(this.hy)}; +w.prototype.isStaticObject=function(){return!!td(this.hy)};w.prototype.isStaticOrKinematicObject=function(){return!!ud(this.hy)};w.prototype.getRestitution=function(){return vd(this.hy)};w.prototype.getFriction=function(){return wd(this.hy)};w.prototype.getRollingFriction=function(){return xd(this.hy)};w.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yd(c,a)};w.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zd(c,a)}; +w.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ad(c,a)};w.prototype.getWorldTransform=function(){return k(Bd(this.hy),r)};w.prototype.getCollisionFlags=function(){return Cd(this.hy)};w.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dd(c,a)};w.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ed(c,a)}; +w.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fd(c,a)};w.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gd(c,a)};w.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hd(c,a)};w.prototype.getUserIndex=function(){return Id(this.hy)};w.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jd(c,a)}; +w.prototype.getUserPointer=function(){return k(Kd(this.hy),SA)};w.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ld(c,a)};w.prototype.getBroadphaseHandle=function(){return k(Md(this.hy),t)};w.prototype.__destroy__=function(){Nd(this.hy)};function YA(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Od(a,c);h(YA)[this.hy]=this}YA.prototype=Object.create(m.prototype);YA.prototype.constructor=YA;YA.prototype.iy=YA;YA.jy={}; +b.btConeShape=YA;YA.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pd(c,a)};YA.prototype.getLocalScaling=function(){return k(Qd(this.hy),p)};YA.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Rd(d,a,c)};YA.prototype.__destroy__=function(){Sd(this.hy)};function ZA(){throw"cannot construct a btActionInterface, no constructor in IDL";}ZA.prototype=Object.create(f.prototype); +ZA.prototype.constructor=ZA;ZA.prototype.iy=ZA;ZA.jy={};b.btActionInterface=ZA;ZA.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Td(d,a,c)};ZA.prototype.__destroy__=function(){Ud(this.hy)}; +function p(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=void 0===a?Vd():void 0===c?_emscripten_bind_btVector3_btVector3_1(a):void 0===d?_emscripten_bind_btVector3_btVector3_2(a,c):Wd(a,c,d);h(p)[this.hy]=this}p.prototype=Object.create(f.prototype);p.prototype.constructor=p;p.prototype.iy=p;p.jy={};b.btVector3=p;p.prototype.length=p.prototype.length=function(){return Xd(this.hy)};p.prototype.x=p.prototype.x=function(){return Yd(this.hy)}; +p.prototype.y=p.prototype.y=function(){return Zd(this.hy)};p.prototype.z=p.prototype.z=function(){return $d(this.hy)};p.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ae(c,a)};p.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);be(c,a)};p.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ce(c,a)}; +p.prototype.setValue=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);de(e,a,c,d)};p.prototype.normalize=p.prototype.normalize=function(){ee(this.hy)};p.prototype.rotate=p.prototype.rotate=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return k(fe(d,a,c),p)};p.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return ge(c,a)}; +p.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(he(c,a),p)};p.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ie(c,a),p)};p.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(je(c,a),p)};p.prototype.__destroy__=function(){ke(this.hy)};function $A(){throw"cannot construct a btVehicleRaycaster, no constructor in IDL";}$A.prototype=Object.create(f.prototype);$A.prototype.constructor=$A; +$A.prototype.iy=$A;$A.jy={};b.btVehicleRaycaster=$A;$A.prototype.castRay=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);le(e,a,c,d)};$A.prototype.__destroy__=function(){me(this.hy)};function aB(){throw"cannot construct a btQuadWord, no constructor in IDL";}aB.prototype=Object.create(f.prototype);aB.prototype.constructor=aB;aB.prototype.iy=aB;aB.jy={};b.btQuadWord=aB;aB.prototype.x=aB.prototype.x=function(){return ne(this.hy)}; +aB.prototype.y=aB.prototype.y=function(){return oe(this.hy)};aB.prototype.z=aB.prototype.z=function(){return pe(this.hy)};aB.prototype.w=function(){return qe(this.hy)};aB.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);re(c,a)};aB.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);se(c,a)};aB.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);te(c,a)}; +aB.prototype.setW=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ue(c,a)};aB.prototype.__destroy__=function(){ve(this.hy)};function bB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=we(a);h(bB)[this.hy]=this}bB.prototype=Object.create(m.prototype);bB.prototype.constructor=bB;bB.prototype.iy=bB;bB.jy={};b.btCylinderShape=bB;bB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xe(c,a)};bB.prototype.getMargin=function(){return ye(this.hy)}; +bB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ze(c,a)};bB.prototype.getLocalScaling=function(){return k(Ae(this.hy),p)};bB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Be(d,a,c)};bB.prototype.__destroy__=function(){Ce(this.hy)}; +function x(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=De(a,c,d,e);h(x)[this.hy]=this}x.prototype=Object.create(u.prototype);x.prototype.constructor=x;x.prototype.iy=x;x.jy={};b.btDiscreteDynamicsWorld=x;x.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ee(c,a)};x.prototype.getGravity=function(){return k(Fe(this.hy),p)}; +x.prototype.addRigidBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Ge(e,a):void 0===d?_emscripten_bind_btDiscreteDynamicsWorld_addRigidBody_2(e,a,c):He(e,a,c,d)};x.prototype.removeRigidBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ie(c,a)}; +x.prototype.addConstraint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Je(d,a):Ke(d,a,c)};x.prototype.removeConstraint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Le(c,a)};x.prototype.stepSimulation=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return void 0===c?Me(e,a):void 0===d?Ne(e,a,c):Oe(e,a,c,d)}; +x.prototype.setContactAddedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pe(c,a)};x.prototype.setContactProcessedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qe(c,a)};x.prototype.setContactDestroyedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Re(c,a)};x.prototype.getDispatcher=function(){return k(Se(this.hy),OA)}; +x.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Te(e,a,c,d)};x.prototype.getPairCache=function(){return k(Ue(this.hy),PA)};x.prototype.getDispatchInfo=function(){return k(Ve(this.hy),l)};x.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?We(e,a):void 0===d?Xe(e,a,c):Ye(e,a,c,d)}; +x.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ze(c,a)};x.prototype.getBroadphase=function(){return k($e(this.hy),QA)};x.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);af(n,a,c,d,e,g)}; +x.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);bf(e,a,c,d)};x.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);cf(d,a,c)};x.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);df(c,a)};x.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ef(c,a)}; +x.prototype.getDebugDrawer=function(){return k(ff(this.hy),RA)};x.prototype.debugDrawWorld=function(){gf(this.hy)};x.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);hf(e,a,c,d)};x.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jf(c,a)};x.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kf(c,a)}; +x.prototype.getSolverInfo=function(){return k(lf(this.hy),v)};x.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?mf(e,a):void 0===d?nf(e,a,c):of(e,a,c,d)};x.prototype.__destroy__=function(){pf(this.hy)};function cB(){throw"cannot construct a btConvexShape, no constructor in IDL";}cB.prototype=Object.create(m.prototype);cB.prototype.constructor=cB;cB.prototype.iy=cB;cB.jy={}; +b.btConvexShape=cB;cB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qf(c,a)};cB.prototype.getLocalScaling=function(){return k(rf(this.hy),p)};cB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);sf(d,a,c)};cB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tf(c,a)};cB.prototype.getMargin=function(){return uf(this.hy)};cB.prototype.__destroy__=function(){vf(this.hy)}; +function OA(){throw"cannot construct a btDispatcher, no constructor in IDL";}OA.prototype=Object.create(f.prototype);OA.prototype.constructor=OA;OA.prototype.iy=OA;OA.jy={};b.btDispatcher=OA;OA.prototype.getNumManifolds=function(){return wf(this.hy)};OA.prototype.getManifoldByIndexInternal=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(xf(c,a),dB)};OA.prototype.__destroy__=function(){yf(this.hy)}; +function eB(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?zf(a,c,d):void 0===g?_emscripten_bind_btGeneric6DofConstraint_btGeneric6DofConstraint_4(a,c,d,e):Af(a,c,d,e,g);h(eB)[this.hy]=this}eB.prototype=Object.create(TA.prototype);eB.prototype.constructor=eB;eB.prototype.iy=eB;eB.jy={};b.btGeneric6DofConstraint=eB; +eB.prototype.setLinearLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bf(c,a)};eB.prototype.setLinearUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cf(c,a)};eB.prototype.setAngularLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Df(c,a)};eB.prototype.setAngularUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ef(c,a)};eB.prototype.getFrameOffsetA=function(){return k(Ff(this.hy),r)}; +eB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gf(c,a)};eB.prototype.getBreakingImpulseThreshold=function(){return Hf(this.hy)};eB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);If(c,a)};eB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Jf(d,a,c)}; +eB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Kf(e,a,c,d)};eB.prototype.__destroy__=function(){Lf(this.hy)};function fB(){throw"cannot construct a btStridingMeshInterface, no constructor in IDL";}fB.prototype=Object.create(f.prototype);fB.prototype.constructor=fB;fB.prototype.iy=fB;fB.jy={};b.btStridingMeshInterface=fB; +fB.prototype.setScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mf(c,a)};fB.prototype.__destroy__=function(){Nf(this.hy)};function gB(){throw"cannot construct a btMotionState, no constructor in IDL";}gB.prototype=Object.create(f.prototype);gB.prototype.constructor=gB;gB.prototype.iy=gB;gB.jy={};b.btMotionState=gB;gB.prototype.getWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Of(c,a)}; +gB.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pf(c,a)};gB.prototype.__destroy__=function(){Qf(this.hy)};function y(){throw"cannot construct a ConvexResultCallback, no constructor in IDL";}y.prototype=Object.create(f.prototype);y.prototype.constructor=y;y.prototype.iy=y;y.jy={};b.ConvexResultCallback=y;y.prototype.hasHit=function(){return!!Rf(this.hy)};y.prototype.get_m_collisionFilterGroup=y.prototype.ky=function(){return Sf(this.hy)}; +y.prototype.set_m_collisionFilterGroup=y.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tf(c,a)};Object.defineProperty(y.prototype,"m_collisionFilterGroup",{get:y.prototype.ky,set:y.prototype.my});y.prototype.get_m_collisionFilterMask=y.prototype.ly=function(){return Uf(this.hy)};y.prototype.set_m_collisionFilterMask=y.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vf(c,a)}; +Object.defineProperty(y.prototype,"m_collisionFilterMask",{get:y.prototype.ly,set:y.prototype.ny});y.prototype.get_m_closestHitFraction=y.prototype.oy=function(){return Wf(this.hy)};y.prototype.set_m_closestHitFraction=y.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xf(c,a)};Object.defineProperty(y.prototype,"m_closestHitFraction",{get:y.prototype.oy,set:y.prototype.py});y.prototype.__destroy__=function(){Yf(this.hy)}; +function hB(){throw"cannot construct a ContactResultCallback, no constructor in IDL";}hB.prototype=Object.create(f.prototype);hB.prototype.constructor=hB;hB.prototype.iy=hB;hB.jy={};b.ContactResultCallback=hB; +hB.prototype.addSingleResult=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return Zf(aa,a,c,d,e,g,n,F)};hB.prototype.__destroy__=function(){$f(this.hy)};function iB(){throw"cannot construct a btSoftBodySolver, no constructor in IDL";}iB.prototype=Object.create(f.prototype); +iB.prototype.constructor=iB;iB.prototype.iy=iB;iB.jy={};b.btSoftBodySolver=iB;iB.prototype.__destroy__=function(){ag(this.hy)};function z(){throw"cannot construct a RayResultCallback, no constructor in IDL";}z.prototype=Object.create(f.prototype);z.prototype.constructor=z;z.prototype.iy=z;z.jy={};b.RayResultCallback=z;z.prototype.hasHit=function(){return!!bg(this.hy)};z.prototype.get_m_collisionFilterGroup=z.prototype.ky=function(){return cg(this.hy)}; +z.prototype.set_m_collisionFilterGroup=z.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dg(c,a)};Object.defineProperty(z.prototype,"m_collisionFilterGroup",{get:z.prototype.ky,set:z.prototype.my});z.prototype.get_m_collisionFilterMask=z.prototype.ly=function(){return eg(this.hy)};z.prototype.set_m_collisionFilterMask=z.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fg(c,a)}; +Object.defineProperty(z.prototype,"m_collisionFilterMask",{get:z.prototype.ly,set:z.prototype.ny});z.prototype.get_m_closestHitFraction=z.prototype.oy=function(){return gg(this.hy)};z.prototype.set_m_closestHitFraction=z.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hg(c,a)};Object.defineProperty(z.prototype,"m_closestHitFraction",{get:z.prototype.oy,set:z.prototype.py});z.prototype.get_m_collisionObject=z.prototype.qy=function(){return k(ig(this.hy),q)}; +z.prototype.set_m_collisionObject=z.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jg(c,a)};Object.defineProperty(z.prototype,"m_collisionObject",{get:z.prototype.qy,set:z.prototype.xy});z.prototype.__destroy__=function(){kg(this.hy)};function jB(){throw"cannot construct a btMatrix3x3, no constructor in IDL";}jB.prototype=Object.create(f.prototype);jB.prototype.constructor=jB;jB.prototype.iy=jB;jB.jy={};b.btMatrix3x3=jB; +jB.prototype.setEulerZYX=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);lg(e,a,c,d)};jB.prototype.getRotation=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mg(c,a)};jB.prototype.getRow=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ng(c,a),p)};jB.prototype.__destroy__=function(){og(this.hy)};function kB(){throw"cannot construct a btScalarArray, no constructor in IDL";}kB.prototype=Object.create(f.prototype); +kB.prototype.constructor=kB;kB.prototype.iy=kB;kB.jy={};b.btScalarArray=kB;kB.prototype.size=kB.prototype.size=function(){return pg(this.hy)};kB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return qg(c,a)};kB.prototype.__destroy__=function(){rg(this.hy)};function A(){throw"cannot construct a Material, no constructor in IDL";}A.prototype=Object.create(f.prototype);A.prototype.constructor=A;A.prototype.iy=A;A.jy={};b.Material=A;A.prototype.get_m_kLST=A.prototype.vA=function(){return sg(this.hy)}; +A.prototype.set_m_kLST=A.prototype.bD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tg(c,a)};Object.defineProperty(A.prototype,"m_kLST",{get:A.prototype.vA,set:A.prototype.bD});A.prototype.get_m_kAST=A.prototype.uA=function(){return ug(this.hy)};A.prototype.set_m_kAST=A.prototype.aD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vg(c,a)};Object.defineProperty(A.prototype,"m_kAST",{get:A.prototype.uA,set:A.prototype.aD});A.prototype.get_m_kVST=A.prototype.wA=function(){return wg(this.hy)}; +A.prototype.set_m_kVST=A.prototype.cD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xg(c,a)};Object.defineProperty(A.prototype,"m_kVST",{get:A.prototype.wA,set:A.prototype.cD});A.prototype.get_m_flags=A.prototype.cA=function(){return yg(this.hy)};A.prototype.set_m_flags=A.prototype.JC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zg(c,a)};Object.defineProperty(A.prototype,"m_flags",{get:A.prototype.cA,set:A.prototype.JC});A.prototype.__destroy__=function(){Ag(this.hy)}; +function l(){throw"cannot construct a btDispatcherInfo, no constructor in IDL";}l.prototype=Object.create(f.prototype);l.prototype.constructor=l;l.prototype.iy=l;l.jy={};b.btDispatcherInfo=l;l.prototype.get_m_timeStep=l.prototype.jB=function(){return Bg(this.hy)};l.prototype.set_m_timeStep=l.prototype.QD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cg(c,a)};Object.defineProperty(l.prototype,"m_timeStep",{get:l.prototype.jB,set:l.prototype.QD}); +l.prototype.get_m_stepCount=l.prototype.aB=function(){return Dg(this.hy)};l.prototype.set_m_stepCount=l.prototype.HD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Eg(c,a)};Object.defineProperty(l.prototype,"m_stepCount",{get:l.prototype.aB,set:l.prototype.HD});l.prototype.get_m_dispatchFunc=l.prototype.Wz=function(){return Fg(this.hy)};l.prototype.set_m_dispatchFunc=l.prototype.CC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gg(c,a)}; +Object.defineProperty(l.prototype,"m_dispatchFunc",{get:l.prototype.Wz,set:l.prototype.CC});l.prototype.get_m_timeOfImpact=l.prototype.iB=function(){return Hg(this.hy)};l.prototype.set_m_timeOfImpact=l.prototype.PD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ig(c,a)};Object.defineProperty(l.prototype,"m_timeOfImpact",{get:l.prototype.iB,set:l.prototype.PD});l.prototype.get_m_useContinuous=l.prototype.lB=function(){return!!Jg(this.hy)}; +l.prototype.set_m_useContinuous=l.prototype.SD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kg(c,a)};Object.defineProperty(l.prototype,"m_useContinuous",{get:l.prototype.lB,set:l.prototype.SD});l.prototype.get_m_enableSatConvex=l.prototype.$z=function(){return!!Lg(this.hy)};l.prototype.set_m_enableSatConvex=l.prototype.GC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mg(c,a)};Object.defineProperty(l.prototype,"m_enableSatConvex",{get:l.prototype.$z,set:l.prototype.GC}); +l.prototype.get_m_enableSPU=l.prototype.Zz=function(){return!!Ng(this.hy)};l.prototype.set_m_enableSPU=l.prototype.FC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Og(c,a)};Object.defineProperty(l.prototype,"m_enableSPU",{get:l.prototype.Zz,set:l.prototype.FC});l.prototype.get_m_useEpa=l.prototype.nB=function(){return!!Pg(this.hy)};l.prototype.set_m_useEpa=l.prototype.UD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qg(c,a)}; +Object.defineProperty(l.prototype,"m_useEpa",{get:l.prototype.nB,set:l.prototype.UD});l.prototype.get_m_allowedCcdPenetration=l.prototype.zz=function(){return Rg(this.hy)};l.prototype.set_m_allowedCcdPenetration=l.prototype.fC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sg(c,a)};Object.defineProperty(l.prototype,"m_allowedCcdPenetration",{get:l.prototype.zz,set:l.prototype.fC});l.prototype.get_m_useConvexConservativeDistanceUtil=l.prototype.mB=function(){return!!Tg(this.hy)}; +l.prototype.set_m_useConvexConservativeDistanceUtil=l.prototype.TD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ug(c,a)};Object.defineProperty(l.prototype,"m_useConvexConservativeDistanceUtil",{get:l.prototype.mB,set:l.prototype.TD});l.prototype.get_m_convexConservativeDistanceThreshold=l.prototype.Rz=function(){return Vg(this.hy)};l.prototype.set_m_convexConservativeDistanceThreshold=l.prototype.xC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wg(c,a)}; +Object.defineProperty(l.prototype,"m_convexConservativeDistanceThreshold",{get:l.prototype.Rz,set:l.prototype.xC});l.prototype.__destroy__=function(){Xg(this.hy)};function B(){throw"cannot construct a btWheelInfoConstructionInfo, no constructor in IDL";}B.prototype=Object.create(f.prototype);B.prototype.constructor=B;B.prototype.iy=B;B.jy={};b.btWheelInfoConstructionInfo=B;B.prototype.get_m_chassisConnectionCS=B.prototype.Lz=function(){return k(Yg(this.hy),p)}; +B.prototype.set_m_chassisConnectionCS=B.prototype.rC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zg(c,a)};Object.defineProperty(B.prototype,"m_chassisConnectionCS",{get:B.prototype.Lz,set:B.prototype.rC});B.prototype.get_m_wheelDirectionCS=B.prototype.Ly=function(){return k($g(this.hy),p)};B.prototype.set_m_wheelDirectionCS=B.prototype.Uy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ah(c,a)};Object.defineProperty(B.prototype,"m_wheelDirectionCS",{get:B.prototype.Ly,set:B.prototype.Uy}); +B.prototype.get_m_wheelAxleCS=B.prototype.Ky=function(){return k(bh(this.hy),p)};B.prototype.set_m_wheelAxleCS=B.prototype.Ty=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ch(c,a)};Object.defineProperty(B.prototype,"m_wheelAxleCS",{get:B.prototype.Ky,set:B.prototype.Ty});B.prototype.get_m_suspensionRestLength=B.prototype.fB=function(){return dh(this.hy)};B.prototype.set_m_suspensionRestLength=B.prototype.MD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);eh(c,a)}; +Object.defineProperty(B.prototype,"m_suspensionRestLength",{get:B.prototype.fB,set:B.prototype.MD});B.prototype.get_m_maxSuspensionTravelCm=B.prototype.vy=function(){return fh(this.hy)};B.prototype.set_m_maxSuspensionTravelCm=B.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gh(c,a)};Object.defineProperty(B.prototype,"m_maxSuspensionTravelCm",{get:B.prototype.vy,set:B.prototype.Cy});B.prototype.get_m_wheelRadius=B.prototype.tB=function(){return hh(this.hy)}; +B.prototype.set_m_wheelRadius=B.prototype.$D=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ih(c,a)};Object.defineProperty(B.prototype,"m_wheelRadius",{get:B.prototype.tB,set:B.prototype.$D});B.prototype.get_m_suspensionStiffness=B.prototype.wy=function(){return jh(this.hy)};B.prototype.set_m_suspensionStiffness=B.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kh(c,a)};Object.defineProperty(B.prototype,"m_suspensionStiffness",{get:B.prototype.wy,set:B.prototype.Dy}); +B.prototype.get_m_wheelsDampingCompression=B.prototype.My=function(){return lh(this.hy)};B.prototype.set_m_wheelsDampingCompression=B.prototype.Vy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mh(c,a)};Object.defineProperty(B.prototype,"m_wheelsDampingCompression",{get:B.prototype.My,set:B.prototype.Vy});B.prototype.get_m_wheelsDampingRelaxation=B.prototype.Ny=function(){return nh(this.hy)}; +B.prototype.set_m_wheelsDampingRelaxation=B.prototype.Wy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);oh(c,a)};Object.defineProperty(B.prototype,"m_wheelsDampingRelaxation",{get:B.prototype.Ny,set:B.prototype.Wy});B.prototype.get_m_frictionSlip=B.prototype.ry=function(){return ph(this.hy)};B.prototype.set_m_frictionSlip=B.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qh(c,a)};Object.defineProperty(B.prototype,"m_frictionSlip",{get:B.prototype.ry,set:B.prototype.yy}); +B.prototype.get_m_maxSuspensionForce=B.prototype.uy=function(){return rh(this.hy)};B.prototype.set_m_maxSuspensionForce=B.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sh(c,a)};Object.defineProperty(B.prototype,"m_maxSuspensionForce",{get:B.prototype.uy,set:B.prototype.By});B.prototype.get_m_bIsFrontWheel=B.prototype.Fy=function(){return!!th(this.hy)};B.prototype.set_m_bIsFrontWheel=B.prototype.Oy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uh(c,a)}; +Object.defineProperty(B.prototype,"m_bIsFrontWheel",{get:B.prototype.Fy,set:B.prototype.Oy});B.prototype.__destroy__=function(){vh(this.hy)};function lB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===c?wh(a):xh(a,c);h(lB)[this.hy]=this}lB.prototype=Object.create(cB.prototype);lB.prototype.constructor=lB;lB.prototype.iy=lB;lB.jy={};b.btConvexTriangleMeshShape=lB;lB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yh(c,a)}; +lB.prototype.getLocalScaling=function(){return k(zh(this.hy),p)};lB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ah(d,a,c)};lB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bh(c,a)};lB.prototype.getMargin=function(){return Ch(this.hy)};lB.prototype.__destroy__=function(){Dh(this.hy)};function QA(){throw"cannot construct a btBroadphaseInterface, no constructor in IDL";}QA.prototype=Object.create(f.prototype); +QA.prototype.constructor=QA;QA.prototype.iy=QA;QA.jy={};b.btBroadphaseInterface=QA;QA.prototype.getOverlappingPairCache=function(){return k(Eh(this.hy),PA)};QA.prototype.__destroy__=function(){Fh(this.hy)};function C(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===e?Gh(a,c,d):Hh(a,c,d,e);h(C)[this.hy]=this}C.prototype=Object.create(f.prototype);C.prototype.constructor=C;C.prototype.iy=C; +C.jy={};b.btRigidBodyConstructionInfo=C;C.prototype.get_m_linearDamping=C.prototype.xA=function(){return Ih(this.hy)};C.prototype.set_m_linearDamping=C.prototype.dD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jh(c,a)};Object.defineProperty(C.prototype,"m_linearDamping",{get:C.prototype.xA,set:C.prototype.dD});C.prototype.get_m_angularDamping=C.prototype.Bz=function(){return Kh(this.hy)}; +C.prototype.set_m_angularDamping=C.prototype.hC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lh(c,a)};Object.defineProperty(C.prototype,"m_angularDamping",{get:C.prototype.Bz,set:C.prototype.hC});C.prototype.get_m_friction=C.prototype.dA=function(){return Mh(this.hy)};C.prototype.set_m_friction=C.prototype.KC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nh(c,a)};Object.defineProperty(C.prototype,"m_friction",{get:C.prototype.dA,set:C.prototype.KC}); +C.prototype.get_m_rollingFriction=C.prototype.TA=function(){return Oh(this.hy)};C.prototype.set_m_rollingFriction=C.prototype.zD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ph(c,a)};Object.defineProperty(C.prototype,"m_rollingFriction",{get:C.prototype.TA,set:C.prototype.zD});C.prototype.get_m_restitution=C.prototype.RA=function(){return Qh(this.hy)};C.prototype.set_m_restitution=C.prototype.xD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rh(c,a)}; +Object.defineProperty(C.prototype,"m_restitution",{get:C.prototype.RA,set:C.prototype.xD});C.prototype.get_m_linearSleepingThreshold=C.prototype.yA=function(){return Sh(this.hy)};C.prototype.set_m_linearSleepingThreshold=C.prototype.eD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Th(c,a)};Object.defineProperty(C.prototype,"m_linearSleepingThreshold",{get:C.prototype.yA,set:C.prototype.eD});C.prototype.get_m_angularSleepingThreshold=C.prototype.Cz=function(){return Uh(this.hy)}; +C.prototype.set_m_angularSleepingThreshold=C.prototype.iC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vh(c,a)};Object.defineProperty(C.prototype,"m_angularSleepingThreshold",{get:C.prototype.Cz,set:C.prototype.iC});C.prototype.get_m_additionalDamping=C.prototype.wz=function(){return!!Wh(this.hy)};C.prototype.set_m_additionalDamping=C.prototype.cC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xh(c,a)}; +Object.defineProperty(C.prototype,"m_additionalDamping",{get:C.prototype.wz,set:C.prototype.cC});C.prototype.get_m_additionalDampingFactor=C.prototype.xz=function(){return Yh(this.hy)};C.prototype.set_m_additionalDampingFactor=C.prototype.dC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zh(c,a)};Object.defineProperty(C.prototype,"m_additionalDampingFactor",{get:C.prototype.xz,set:C.prototype.dC});C.prototype.get_m_additionalLinearDampingThresholdSqr=C.prototype.yz=function(){return $h(this.hy)}; +C.prototype.set_m_additionalLinearDampingThresholdSqr=C.prototype.eC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ai(c,a)};Object.defineProperty(C.prototype,"m_additionalLinearDampingThresholdSqr",{get:C.prototype.yz,set:C.prototype.eC});C.prototype.get_m_additionalAngularDampingThresholdSqr=C.prototype.vz=function(){return bi(this.hy)};C.prototype.set_m_additionalAngularDampingThresholdSqr=C.prototype.bC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ci(c,a)}; +Object.defineProperty(C.prototype,"m_additionalAngularDampingThresholdSqr",{get:C.prototype.vz,set:C.prototype.bC});C.prototype.get_m_additionalAngularDampingFactor=C.prototype.uz=function(){return di(this.hy)};C.prototype.set_m_additionalAngularDampingFactor=C.prototype.aC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ei(c,a)};Object.defineProperty(C.prototype,"m_additionalAngularDampingFactor",{get:C.prototype.uz,set:C.prototype.aC});C.prototype.__destroy__=function(){fi(this.hy)}; +function mB(){throw"cannot construct a btCollisionConfiguration, no constructor in IDL";}mB.prototype=Object.create(f.prototype);mB.prototype.constructor=mB;mB.prototype.iy=mB;mB.jy={};b.btCollisionConfiguration=mB;mB.prototype.__destroy__=function(){gi(this.hy)};function dB(){this.hy=hi();h(dB)[this.hy]=this}dB.prototype=Object.create(f.prototype);dB.prototype.constructor=dB;dB.prototype.iy=dB;dB.jy={};b.btPersistentManifold=dB;dB.prototype.getBody0=function(){return k(ii(this.hy),q)}; +dB.prototype.getBody1=function(){return k(ji(this.hy),q)};dB.prototype.getNumContacts=function(){return ki(this.hy)};dB.prototype.getContactPoint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(li(c,a),D)};dB.prototype.__destroy__=function(){mi(this.hy)};function nB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?ni():oi(a);h(nB)[this.hy]=this}nB.prototype=Object.create(m.prototype);nB.prototype.constructor=nB;nB.prototype.iy=nB;nB.jy={};b.btCompoundShape=nB; +nB.prototype.addChildShape=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pi(d,a,c)};nB.prototype.removeChildShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qi(c,a)};nB.prototype.removeChildShapeByIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ri(c,a)};nB.prototype.getNumChildShapes=function(){return si(this.hy)};nB.prototype.getChildShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ti(c,a),m)}; +nB.prototype.updateChildTransform=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===d?ui(e,a,c):vi(e,a,c,d)};nB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wi(c,a)};nB.prototype.getMargin=function(){return xi(this.hy)};nB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yi(c,a)};nB.prototype.getLocalScaling=function(){return k(zi(this.hy),p)}; +nB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ai(d,a,c)};nB.prototype.__destroy__=function(){Bi(this.hy)};function E(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Ci(a,c);h(E)[this.hy]=this}E.prototype=Object.create(y.prototype);E.prototype.constructor=E;E.prototype.iy=E;E.jy={};b.ClosestConvexResultCallback=E;E.prototype.hasHit=function(){return!!Di(this.hy)}; +E.prototype.get_m_convexFromWorld=E.prototype.Sz=function(){return k(Ei(this.hy),p)};E.prototype.set_m_convexFromWorld=E.prototype.yC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fi(c,a)};Object.defineProperty(E.prototype,"m_convexFromWorld",{get:E.prototype.Sz,set:E.prototype.yC});E.prototype.get_m_convexToWorld=E.prototype.Tz=function(){return k(Gi(this.hy),p)};E.prototype.set_m_convexToWorld=E.prototype.zC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hi(c,a)}; +Object.defineProperty(E.prototype,"m_convexToWorld",{get:E.prototype.Tz,set:E.prototype.zC});E.prototype.get_m_hitNormalWorld=E.prototype.sy=function(){return k(Ii(this.hy),p)};E.prototype.set_m_hitNormalWorld=E.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ji(c,a)};Object.defineProperty(E.prototype,"m_hitNormalWorld",{get:E.prototype.sy,set:E.prototype.zy});E.prototype.get_m_hitPointWorld=E.prototype.ty=function(){return k(Ki(this.hy),p)}; +E.prototype.set_m_hitPointWorld=E.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Li(c,a)};Object.defineProperty(E.prototype,"m_hitPointWorld",{get:E.prototype.ty,set:E.prototype.Ay});E.prototype.get_m_collisionFilterGroup=E.prototype.ky=function(){return Mi(this.hy)};E.prototype.set_m_collisionFilterGroup=E.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ni(c,a)};Object.defineProperty(E.prototype,"m_collisionFilterGroup",{get:E.prototype.ky,set:E.prototype.my}); +E.prototype.get_m_collisionFilterMask=E.prototype.ly=function(){return Oi(this.hy)};E.prototype.set_m_collisionFilterMask=E.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pi(c,a)};Object.defineProperty(E.prototype,"m_collisionFilterMask",{get:E.prototype.ly,set:E.prototype.ny});E.prototype.get_m_closestHitFraction=E.prototype.oy=function(){return Qi(this.hy)}; +E.prototype.set_m_closestHitFraction=E.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ri(c,a)};Object.defineProperty(E.prototype,"m_closestHitFraction",{get:E.prototype.oy,set:E.prototype.py});E.prototype.__destroy__=function(){Si(this.hy)};function G(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Ti(a,c);h(G)[this.hy]=this}G.prototype=Object.create(z.prototype);G.prototype.constructor=G;G.prototype.iy=G;G.jy={};b.AllHitsRayResultCallback=G; +G.prototype.hasHit=function(){return!!Ui(this.hy)};G.prototype.get_m_collisionObjects=G.prototype.Oz=function(){return k(Vi(this.hy),oB)};G.prototype.set_m_collisionObjects=G.prototype.uC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wi(c,a)};Object.defineProperty(G.prototype,"m_collisionObjects",{get:G.prototype.Oz,set:G.prototype.uC});G.prototype.get_m_rayFromWorld=G.prototype.Iy=function(){return k(Xi(this.hy),p)}; +G.prototype.set_m_rayFromWorld=G.prototype.Ry=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yi(c,a)};Object.defineProperty(G.prototype,"m_rayFromWorld",{get:G.prototype.Iy,set:G.prototype.Ry});G.prototype.get_m_rayToWorld=G.prototype.Jy=function(){return k(Zi(this.hy),p)};G.prototype.set_m_rayToWorld=G.prototype.Sy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$i(c,a)};Object.defineProperty(G.prototype,"m_rayToWorld",{get:G.prototype.Jy,set:G.prototype.Sy}); +G.prototype.get_m_hitNormalWorld=G.prototype.sy=function(){return k(aj(this.hy),pB)};G.prototype.set_m_hitNormalWorld=G.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bj(c,a)};Object.defineProperty(G.prototype,"m_hitNormalWorld",{get:G.prototype.sy,set:G.prototype.zy});G.prototype.get_m_hitPointWorld=G.prototype.ty=function(){return k(cj(this.hy),pB)};G.prototype.set_m_hitPointWorld=G.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dj(c,a)}; +Object.defineProperty(G.prototype,"m_hitPointWorld",{get:G.prototype.ty,set:G.prototype.Ay});G.prototype.get_m_hitFractions=G.prototype.kA=function(){return k(ej(this.hy),kB)};G.prototype.set_m_hitFractions=G.prototype.RC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fj(c,a)};Object.defineProperty(G.prototype,"m_hitFractions",{get:G.prototype.kA,set:G.prototype.RC});G.prototype.get_m_collisionFilterGroup=G.prototype.ky=function(){return gj(this.hy)}; +G.prototype.set_m_collisionFilterGroup=G.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hj(c,a)};Object.defineProperty(G.prototype,"m_collisionFilterGroup",{get:G.prototype.ky,set:G.prototype.my});G.prototype.get_m_collisionFilterMask=G.prototype.ly=function(){return ij(this.hy)};G.prototype.set_m_collisionFilterMask=G.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jj(c,a)}; +Object.defineProperty(G.prototype,"m_collisionFilterMask",{get:G.prototype.ly,set:G.prototype.ny});G.prototype.get_m_closestHitFraction=G.prototype.oy=function(){return kj(this.hy)};G.prototype.set_m_closestHitFraction=G.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lj(c,a)};Object.defineProperty(G.prototype,"m_closestHitFraction",{get:G.prototype.oy,set:G.prototype.py});G.prototype.get_m_collisionObject=G.prototype.qy=function(){return k(mj(this.hy),q)}; +G.prototype.set_m_collisionObject=G.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nj(c,a)};Object.defineProperty(G.prototype,"m_collisionObject",{get:G.prototype.qy,set:G.prototype.xy});G.prototype.__destroy__=function(){oj(this.hy)};function qB(){throw"cannot construct a tMaterialArray, no constructor in IDL";}qB.prototype=Object.create(f.prototype);qB.prototype.constructor=qB;qB.prototype.iy=qB;qB.jy={};b.tMaterialArray=qB;qB.prototype.size=qB.prototype.size=function(){return pj(this.hy)}; +qB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(qj(c,a),A)};qB.prototype.__destroy__=function(){rj(this.hy)};function rB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=sj(a);h(rB)[this.hy]=this}rB.prototype=Object.create($A.prototype);rB.prototype.constructor=rB;rB.prototype.iy=rB;rB.jy={};b.btDefaultVehicleRaycaster=rB; +rB.prototype.castRay=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);tj(e,a,c,d)};rB.prototype.__destroy__=function(){uj(this.hy)};function sB(){this.hy=vj();h(sB)[this.hy]=this}sB.prototype=Object.create(UA.prototype);sB.prototype.constructor=sB;sB.prototype.iy=sB;sB.jy={};b.btEmptyShape=sB;sB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wj(c,a)}; +sB.prototype.getLocalScaling=function(){return k(xj(this.hy),p)};sB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);yj(d,a,c)};sB.prototype.__destroy__=function(){zj(this.hy)};function H(){this.hy=Aj();h(H)[this.hy]=this}H.prototype=Object.create(f.prototype);H.prototype.constructor=H;H.prototype.iy=H;H.jy={};b.btConstraintSetting=H;H.prototype.get_m_tau=H.prototype.hB=function(){return Bj(this.hy)}; +H.prototype.set_m_tau=H.prototype.OD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cj(c,a)};Object.defineProperty(H.prototype,"m_tau",{get:H.prototype.hB,set:H.prototype.OD});H.prototype.get_m_damping=H.prototype.Uz=function(){return Dj(this.hy)};H.prototype.set_m_damping=H.prototype.AC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ej(c,a)};Object.defineProperty(H.prototype,"m_damping",{get:H.prototype.Uz,set:H.prototype.AC}); +H.prototype.get_m_impulseClamp=H.prototype.qA=function(){return Fj(this.hy)};H.prototype.set_m_impulseClamp=H.prototype.XC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gj(c,a)};Object.defineProperty(H.prototype,"m_impulseClamp",{get:H.prototype.qA,set:H.prototype.XC});H.prototype.__destroy__=function(){Hj(this.hy)};function tB(){throw"cannot construct a LocalShapeInfo, no constructor in IDL";}tB.prototype=Object.create(f.prototype);tB.prototype.constructor=tB;tB.prototype.iy=tB; +tB.jy={};b.LocalShapeInfo=tB;tB.prototype.get_m_shapePart=tB.prototype.WA=function(){return Ij(this.hy)};tB.prototype.set_m_shapePart=tB.prototype.CD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jj(c,a)};Object.defineProperty(tB.prototype,"m_shapePart",{get:tB.prototype.WA,set:tB.prototype.CD});tB.prototype.get_m_triangleIndex=tB.prototype.kB=function(){return Kj(this.hy)}; +tB.prototype.set_m_triangleIndex=tB.prototype.RD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lj(c,a)};Object.defineProperty(tB.prototype,"m_triangleIndex",{get:tB.prototype.kB,set:tB.prototype.RD});tB.prototype.__destroy__=function(){Mj(this.hy)};function I(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Nj(a);h(I)[this.hy]=this}I.prototype=Object.create(q.prototype);I.prototype.constructor=I;I.prototype.iy=I;I.jy={};b.btRigidBody=I; +I.prototype.getCenterOfMassTransform=function(){return k(Oj(this.hy),r)};I.prototype.setCenterOfMassTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pj(c,a)};I.prototype.setSleepingThresholds=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Qj(d,a,c)};I.prototype.getLinearDamping=function(){return Rj(this.hy)};I.prototype.getAngularDamping=function(){return Sj(this.hy)}; +I.prototype.setDamping=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Tj(d,a,c)};I.prototype.setMassProps=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Uj(d,a,c)};I.prototype.getLinearFactor=function(){return k(Vj(this.hy),p)};I.prototype.setLinearFactor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wj(c,a)}; +I.prototype.applyTorque=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xj(c,a)};I.prototype.applyLocalTorque=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yj(c,a)};I.prototype.applyForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Zj(d,a,c)};I.prototype.applyCentralForce=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ak(c,a)}; +I.prototype.applyCentralLocalForce=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bk(c,a)};I.prototype.applyTorqueImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ck(c,a)};I.prototype.applyImpulse=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dk(d,a,c)};I.prototype.applyCentralImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ek(c,a)};I.prototype.updateInertiaTensor=function(){fk(this.hy)}; +I.prototype.getLinearVelocity=function(){return k(gk(this.hy),p)};I.prototype.getAngularVelocity=function(){return k(hk(this.hy),p)};I.prototype.setLinearVelocity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ik(c,a)};I.prototype.setAngularVelocity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jk(c,a)};I.prototype.getMotionState=function(){return k(kk(this.hy),gB)};I.prototype.setMotionState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lk(c,a)}; +I.prototype.getAngularFactor=function(){return k(mk(this.hy),p)};I.prototype.setAngularFactor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nk(c,a)};I.prototype.upcast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ok(c,a),I)};I.prototype.getAabb=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pk(d,a,c)};I.prototype.applyGravity=function(){qk(this.hy)};I.prototype.getGravity=function(){return k(rk(this.hy),p)}; +I.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sk(c,a)};I.prototype.getBroadphaseProxy=function(){return k(tk(this.hy),t)};I.prototype.clearForces=function(){uk(this.hy)};I.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);vk(d,a,c)};I.prototype.getCollisionShape=function(){return k(wk(this.hy),m)}; +I.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xk(c,a)};I.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yk(c,a)};I.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zk(c,a)};I.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Ak(c):Bk(c,a)};I.prototype.isActive=function(){return!!Ck(this.hy)};I.prototype.isKinematicObject=function(){return!!Dk(this.hy)}; +I.prototype.isStaticObject=function(){return!!Ek(this.hy)};I.prototype.isStaticOrKinematicObject=function(){return!!Fk(this.hy)};I.prototype.getRestitution=function(){return Gk(this.hy)};I.prototype.getFriction=function(){return Hk(this.hy)};I.prototype.getRollingFriction=function(){return Ik(this.hy)};I.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jk(c,a)};I.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kk(c,a)}; +I.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lk(c,a)};I.prototype.getWorldTransform=function(){return k(Mk(this.hy),r)};I.prototype.getCollisionFlags=function(){return Nk(this.hy)};I.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ok(c,a)};I.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pk(c,a)}; +I.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qk(c,a)};I.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rk(c,a)};I.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sk(c,a)};I.prototype.getUserIndex=function(){return Tk(this.hy)};I.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uk(c,a)}; +I.prototype.getUserPointer=function(){return k(Vk(this.hy),SA)};I.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wk(c,a)};I.prototype.getBroadphaseHandle=function(){return k(Xk(this.hy),t)};I.prototype.__destroy__=function(){Yk(this.hy)};function uB(){throw"cannot construct a btIndexedMeshArray, no constructor in IDL";}uB.prototype=Object.create(f.prototype);uB.prototype.constructor=uB;uB.prototype.iy=uB;uB.jy={};b.btIndexedMeshArray=uB; +uB.prototype.size=uB.prototype.size=function(){return Zk(this.hy)};uB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k($k(c,a),vB)};uB.prototype.__destroy__=function(){al(this.hy)};function wB(){this.hy=bl();h(wB)[this.hy]=this}wB.prototype=Object.create(f.prototype);wB.prototype.constructor=wB;wB.prototype.iy=wB;wB.jy={};b.btDbvtBroadphase=wB;wB.prototype.__destroy__=function(){cl(this.hy)}; +function xB(a,c,d,e,g,n,F,aa,ta){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);this.hy=dl(a,c,d,e,g,n,F,aa,ta);h(xB)[this.hy]=this}xB.prototype=Object.create(UA.prototype);xB.prototype.constructor=xB;xB.prototype.iy=xB;xB.jy={}; +b.btHeightfieldTerrainShape=xB;xB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);el(c,a)};xB.prototype.getMargin=function(){return fl(this.hy)};xB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gl(c,a)};xB.prototype.getLocalScaling=function(){return k(hl(this.hy),p)};xB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);il(d,a,c)}; +xB.prototype.__destroy__=function(){jl(this.hy)};function yB(){this.hy=kl();h(yB)[this.hy]=this}yB.prototype=Object.create(iB.prototype);yB.prototype.constructor=yB;yB.prototype.iy=yB;yB.jy={};b.btDefaultSoftBodySolver=yB;yB.prototype.__destroy__=function(){ll(this.hy)};function zB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=ml(a);h(zB)[this.hy]=this}zB.prototype=Object.create(OA.prototype);zB.prototype.constructor=zB;zB.prototype.iy=zB;zB.jy={};b.btCollisionDispatcher=zB; +zB.prototype.getNumManifolds=function(){return nl(this.hy)};zB.prototype.getManifoldByIndexInternal=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ol(c,a),dB)};zB.prototype.__destroy__=function(){pl(this.hy)}; +function AB(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===d?ql(a,c):void 0===e?rl(a,c,d):void 0===g?sl(a,c,d,e):tl(a,c,d,e,g);h(AB)[this.hy]=this}AB.prototype=Object.create(f.prototype);AB.prototype.constructor=AB;AB.prototype.iy=AB;AB.jy={};b.btAxisSweep3=AB;AB.prototype.__destroy__=function(){ul(this.hy)}; +function SA(){throw"cannot construct a VoidPtr, no constructor in IDL";}SA.prototype=Object.create(f.prototype);SA.prototype.constructor=SA;SA.prototype.iy=SA;SA.jy={};b.VoidPtr=SA;SA.prototype.__destroy__=function(){vl(this.hy)};function J(){this.hy=wl();h(J)[this.hy]=this}J.prototype=Object.create(f.prototype);J.prototype.constructor=J;J.prototype.iy=J;J.jy={};b.btSoftBodyWorldInfo=J;J.prototype.get_air_density=J.prototype.Yy=function(){return xl(this.hy)}; +J.prototype.set_air_density=J.prototype.FB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yl(c,a)};Object.defineProperty(J.prototype,"air_density",{get:J.prototype.Yy,set:J.prototype.FB});J.prototype.get_water_density=J.prototype.CB=function(){return zl(this.hy)};J.prototype.set_water_density=J.prototype.iE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Al(c,a)};Object.defineProperty(J.prototype,"water_density",{get:J.prototype.CB,set:J.prototype.iE}); +J.prototype.get_water_offset=J.prototype.EB=function(){return Bl(this.hy)};J.prototype.set_water_offset=J.prototype.kE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cl(c,a)};Object.defineProperty(J.prototype,"water_offset",{get:J.prototype.EB,set:J.prototype.kE});J.prototype.get_m_maxDisplacement=J.prototype.EA=function(){return Dl(this.hy)};J.prototype.set_m_maxDisplacement=J.prototype.kD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);El(c,a)}; +Object.defineProperty(J.prototype,"m_maxDisplacement",{get:J.prototype.EA,set:J.prototype.kD});J.prototype.get_water_normal=J.prototype.DB=function(){return k(Fl(this.hy),p)};J.prototype.set_water_normal=J.prototype.jE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gl(c,a)};Object.defineProperty(J.prototype,"water_normal",{get:J.prototype.DB,set:J.prototype.jE});J.prototype.get_m_broadphase=J.prototype.Gz=function(){return k(Hl(this.hy),QA)}; +J.prototype.set_m_broadphase=J.prototype.mC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Il(c,a)};Object.defineProperty(J.prototype,"m_broadphase",{get:J.prototype.Gz,set:J.prototype.mC});J.prototype.get_m_dispatcher=J.prototype.Xz=function(){return k(Jl(this.hy),OA)};J.prototype.set_m_dispatcher=J.prototype.DC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kl(c,a)};Object.defineProperty(J.prototype,"m_dispatcher",{get:J.prototype.Xz,set:J.prototype.DC}); +J.prototype.get_m_gravity=J.prototype.fA=function(){return k(Ll(this.hy),p)};J.prototype.set_m_gravity=J.prototype.MC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ml(c,a)};Object.defineProperty(J.prototype,"m_gravity",{get:J.prototype.fA,set:J.prototype.MC});J.prototype.__destroy__=function(){Nl(this.hy)}; +function BB(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===d?Ol(a,c):void 0===e?_emscripten_bind_btConeTwistConstraint_btConeTwistConstraint_3(a,c,d):Pl(a,c,d,e);h(BB)[this.hy]=this}BB.prototype=Object.create(TA.prototype);BB.prototype.constructor=BB;BB.prototype.iy=BB;BB.jy={};b.btConeTwistConstraint=BB; +BB.prototype.setLimit=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ql(d,a,c)};BB.prototype.setAngularOnly=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rl(c,a)};BB.prototype.setDamping=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sl(c,a)};BB.prototype.enableMotor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tl(c,a)}; +BB.prototype.setMaxMotorImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ul(c,a)};BB.prototype.setMaxMotorImpulseNormalized=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vl(c,a)};BB.prototype.setMotorTarget=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wl(c,a)};BB.prototype.setMotorTargetInConstraintSpace=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xl(c,a)}; +BB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yl(c,a)};BB.prototype.getBreakingImpulseThreshold=function(){return Zl(this.hy)};BB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$l(c,a)};BB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return am(d,a,c)}; +BB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);bm(e,a,c,d)};BB.prototype.__destroy__=function(){cm(this.hy)}; +function CB(a,c,d,e,g,n,F){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);this.hy=void 0===d?dm(a,c):void 0===e?em(a,c,d):void 0===g?fm(a,c,d,e):void 0===n?gm(a,c,d,e,g):void 0===F?hm(a,c,d,e,g,n):im(a,c,d,e,g,n,F);h(CB)[this.hy]=this}CB.prototype=Object.create(TA.prototype);CB.prototype.constructor=CB; +CB.prototype.iy=CB;CB.jy={};b.btHingeConstraint=CB;CB.prototype.setLimit=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);void 0===g?jm(n,a,c,d,e):km(n,a,c,d,e,g)};CB.prototype.enableAngularMotor=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);lm(e,a,c,d)}; +CB.prototype.setAngularOnly=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mm(c,a)};CB.prototype.enableMotor=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nm(c,a)};CB.prototype.setMaxMotorImpulse=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);om(c,a)};CB.prototype.setMotorTarget=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);pm(d,a,c)}; +CB.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qm(c,a)};CB.prototype.getBreakingImpulseThreshold=function(){return rm(this.hy)};CB.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sm(c,a)};CB.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return tm(d,a,c)}; +CB.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);um(e,a,c,d)};CB.prototype.__destroy__=function(){wm(this.hy)};function DB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=xm(a,c);h(DB)[this.hy]=this}DB.prototype=Object.create(YA.prototype);DB.prototype.constructor=DB;DB.prototype.iy=DB;DB.jy={};b.btConeShapeZ=DB; +DB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ym(c,a)};DB.prototype.getLocalScaling=function(){return k(zm(this.hy),p)};DB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Am(d,a,c)};DB.prototype.__destroy__=function(){Bm(this.hy)};function EB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Cm(a,c);h(EB)[this.hy]=this}EB.prototype=Object.create(YA.prototype); +EB.prototype.constructor=EB;EB.prototype.iy=EB;EB.jy={};b.btConeShapeX=EB;EB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dm(c,a)};EB.prototype.getLocalScaling=function(){return k(Em(this.hy),p)};EB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Fm(d,a,c)};EB.prototype.__destroy__=function(){Gm(this.hy)}; +function FB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Hm():void 0===c?Im(a):Jm(a,c);h(FB)[this.hy]=this}FB.prototype=Object.create(fB.prototype);FB.prototype.constructor=FB;FB.prototype.iy=FB;FB.jy={};b.btTriangleMesh=FB;FB.prototype.addTriangle=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);void 0===e?Km(g,a,c,d):Lm(g,a,c,d,e)}; +FB.prototype.findOrAddVertex=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Mm(d,a,c)};FB.prototype.addIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nm(c,a)};FB.prototype.getIndexedMeshArray=function(){return k(Om(this.hy),uB)};FB.prototype.setScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pm(c,a)};FB.prototype.__destroy__=function(){Qm(this.hy)}; +function GB(a,c){IA();"object"==typeof a&&(a=MA(a));c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Rm():void 0===c?Sm(a):Tm(a,c);h(GB)[this.hy]=this}GB.prototype=Object.create(m.prototype);GB.prototype.constructor=GB;GB.prototype.iy=GB;GB.jy={};b.btConvexHullShape=GB;GB.prototype.addPoint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Um(d,a):Vm(d,a,c)}; +GB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wm(c,a)};GB.prototype.getMargin=function(){return Xm(this.hy)};GB.prototype.getNumVertices=function(){return Ym(this.hy)};GB.prototype.initializePolyhedralFeatures=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return!!Zm(c,a)};GB.prototype.recalcLocalAabb=function(){$m(this.hy)};GB.prototype.getConvexPolyhedron=function(){return k(an(this.hy),HB)}; +GB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bn(c,a)};GB.prototype.getLocalScaling=function(){return k(cn(this.hy),p)};GB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dn(d,a,c)};GB.prototype.__destroy__=function(){en(this.hy)};function K(){this.hy=fn();h(K)[this.hy]=this}K.prototype=Object.create(f.prototype);K.prototype.constructor=K;K.prototype.iy=K;K.jy={}; +b.btVehicleTuning=K;K.prototype.get_m_suspensionStiffness=K.prototype.wy=function(){return gn(this.hy)};K.prototype.set_m_suspensionStiffness=K.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hn(c,a)};Object.defineProperty(K.prototype,"m_suspensionStiffness",{get:K.prototype.wy,set:K.prototype.Dy});K.prototype.get_m_suspensionCompression=K.prototype.bB=function(){return jn(this.hy)}; +K.prototype.set_m_suspensionCompression=K.prototype.ID=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kn(c,a)};Object.defineProperty(K.prototype,"m_suspensionCompression",{get:K.prototype.bB,set:K.prototype.ID});K.prototype.get_m_suspensionDamping=K.prototype.cB=function(){return ln(this.hy)};K.prototype.set_m_suspensionDamping=K.prototype.JD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mn(c,a)}; +Object.defineProperty(K.prototype,"m_suspensionDamping",{get:K.prototype.cB,set:K.prototype.JD});K.prototype.get_m_maxSuspensionTravelCm=K.prototype.vy=function(){return nn(this.hy)};K.prototype.set_m_maxSuspensionTravelCm=K.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);on(c,a)};Object.defineProperty(K.prototype,"m_maxSuspensionTravelCm",{get:K.prototype.vy,set:K.prototype.Cy});K.prototype.get_m_frictionSlip=K.prototype.ry=function(){return pn(this.hy)}; +K.prototype.set_m_frictionSlip=K.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qn(c,a)};Object.defineProperty(K.prototype,"m_frictionSlip",{get:K.prototype.ry,set:K.prototype.yy});K.prototype.get_m_maxSuspensionForce=K.prototype.uy=function(){return rn(this.hy)};K.prototype.set_m_maxSuspensionForce=K.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sn(c,a)};Object.defineProperty(K.prototype,"m_maxSuspensionForce",{get:K.prototype.uy,set:K.prototype.By}); +function IB(){throw"cannot construct a btCollisionObjectWrapper, no constructor in IDL";}IB.prototype=Object.create(f.prototype);IB.prototype.constructor=IB;IB.prototype.iy=IB;IB.jy={};b.btCollisionObjectWrapper=IB;IB.prototype.getWorldTransform=function(){return k(tn(this.hy),r)};IB.prototype.getCollisionObject=function(){return k(un(this.hy),q)};IB.prototype.getCollisionShape=function(){return k(vn(this.hy),m)};function JB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=wn(a);h(JB)[this.hy]=this} +JB.prototype=Object.create(f.prototype);JB.prototype.constructor=JB;JB.prototype.iy=JB;JB.jy={};b.btShapeHull=JB;JB.prototype.buildHull=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return!!xn(c,a)};JB.prototype.numVertices=function(){return yn(this.hy)};JB.prototype.getVertexPointer=function(){return k(zn(this.hy),p)};JB.prototype.__destroy__=function(){An(this.hy)}; +function KB(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?Bn():void 0===c?Cn(a):Dn(a,c);h(KB)[this.hy]=this}KB.prototype=Object.create(gB.prototype);KB.prototype.constructor=KB;KB.prototype.iy=KB;KB.jy={};b.btDefaultMotionState=KB;KB.prototype.getWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);En(c,a)};KB.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fn(c,a)}; +KB.prototype.get_m_graphicsWorldTrans=KB.prototype.eA=function(){return k(Gn(this.hy),r)};KB.prototype.set_m_graphicsWorldTrans=KB.prototype.LC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hn(c,a)};Object.defineProperty(KB.prototype,"m_graphicsWorldTrans",{get:KB.prototype.eA,set:KB.prototype.LC});KB.prototype.__destroy__=function(){In(this.hy)};function L(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Jn(a);h(L)[this.hy]=this}L.prototype=Object.create(f.prototype); +L.prototype.constructor=L;L.prototype.iy=L;L.jy={};b.btWheelInfo=L;L.prototype.getSuspensionRestLength=function(){return Kn(this.hy)};L.prototype.updateWheel=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ln(d,a,c)};L.prototype.get_m_suspensionStiffness=L.prototype.wy=function(){return Mn(this.hy)};L.prototype.set_m_suspensionStiffness=L.prototype.Dy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nn(c,a)}; +Object.defineProperty(L.prototype,"m_suspensionStiffness",{get:L.prototype.wy,set:L.prototype.Dy});L.prototype.get_m_frictionSlip=L.prototype.ry=function(){return On(this.hy)};L.prototype.set_m_frictionSlip=L.prototype.yy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pn(c,a)};Object.defineProperty(L.prototype,"m_frictionSlip",{get:L.prototype.ry,set:L.prototype.yy});L.prototype.get_m_engineForce=L.prototype.aA=function(){return Qn(this.hy)}; +L.prototype.set_m_engineForce=L.prototype.HC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rn(c,a)};Object.defineProperty(L.prototype,"m_engineForce",{get:L.prototype.aA,set:L.prototype.HC});L.prototype.get_m_rollInfluence=L.prototype.SA=function(){return Sn(this.hy)};L.prototype.set_m_rollInfluence=L.prototype.yD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tn(c,a)};Object.defineProperty(L.prototype,"m_rollInfluence",{get:L.prototype.SA,set:L.prototype.yD}); +L.prototype.get_m_suspensionRestLength1=L.prototype.gB=function(){return Un(this.hy)};L.prototype.set_m_suspensionRestLength1=L.prototype.ND=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vn(c,a)};Object.defineProperty(L.prototype,"m_suspensionRestLength1",{get:L.prototype.gB,set:L.prototype.ND});L.prototype.get_m_wheelsRadius=L.prototype.uB=function(){return Wn(this.hy)};L.prototype.set_m_wheelsRadius=L.prototype.aE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xn(c,a)}; +Object.defineProperty(L.prototype,"m_wheelsRadius",{get:L.prototype.uB,set:L.prototype.aE});L.prototype.get_m_wheelsDampingCompression=L.prototype.My=function(){return Yn(this.hy)};L.prototype.set_m_wheelsDampingCompression=L.prototype.Vy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zn(c,a)};Object.defineProperty(L.prototype,"m_wheelsDampingCompression",{get:L.prototype.My,set:L.prototype.Vy});L.prototype.get_m_wheelsDampingRelaxation=L.prototype.Ny=function(){return $n(this.hy)}; +L.prototype.set_m_wheelsDampingRelaxation=L.prototype.Wy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ao(c,a)};Object.defineProperty(L.prototype,"m_wheelsDampingRelaxation",{get:L.prototype.Ny,set:L.prototype.Wy});L.prototype.get_m_steering=L.prototype.$A=function(){return bo(this.hy)};L.prototype.set_m_steering=L.prototype.GD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);co(c,a)};Object.defineProperty(L.prototype,"m_steering",{get:L.prototype.$A,set:L.prototype.GD}); +L.prototype.get_m_maxSuspensionForce=L.prototype.uy=function(){return eo(this.hy)};L.prototype.set_m_maxSuspensionForce=L.prototype.By=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fo(c,a)};Object.defineProperty(L.prototype,"m_maxSuspensionForce",{get:L.prototype.uy,set:L.prototype.By});L.prototype.get_m_maxSuspensionTravelCm=L.prototype.vy=function(){return go(this.hy)}; +L.prototype.set_m_maxSuspensionTravelCm=L.prototype.Cy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ho(c,a)};Object.defineProperty(L.prototype,"m_maxSuspensionTravelCm",{get:L.prototype.vy,set:L.prototype.Cy});L.prototype.get_m_wheelsSuspensionForce=L.prototype.vB=function(){return io(this.hy)};L.prototype.set_m_wheelsSuspensionForce=L.prototype.bE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jo(c,a)}; +Object.defineProperty(L.prototype,"m_wheelsSuspensionForce",{get:L.prototype.vB,set:L.prototype.bE});L.prototype.get_m_bIsFrontWheel=L.prototype.Fy=function(){return!!ko(this.hy)};L.prototype.set_m_bIsFrontWheel=L.prototype.Oy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lo(c,a)};Object.defineProperty(L.prototype,"m_bIsFrontWheel",{get:L.prototype.Fy,set:L.prototype.Oy});L.prototype.get_m_raycastInfo=L.prototype.QA=function(){return k(mo(this.hy),M)}; +L.prototype.set_m_raycastInfo=L.prototype.wD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);no(c,a)};Object.defineProperty(L.prototype,"m_raycastInfo",{get:L.prototype.QA,set:L.prototype.wD});L.prototype.get_m_chassisConnectionPointCS=L.prototype.Mz=function(){return k(oo(this.hy),p)};L.prototype.set_m_chassisConnectionPointCS=L.prototype.sC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);po(c,a)}; +Object.defineProperty(L.prototype,"m_chassisConnectionPointCS",{get:L.prototype.Mz,set:L.prototype.sC});L.prototype.get_m_worldTransform=L.prototype.wB=function(){return k(qo(this.hy),r)};L.prototype.set_m_worldTransform=L.prototype.cE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ro(c,a)};Object.defineProperty(L.prototype,"m_worldTransform",{get:L.prototype.wB,set:L.prototype.cE});L.prototype.get_m_wheelDirectionCS=L.prototype.Ly=function(){return k(so(this.hy),p)}; +L.prototype.set_m_wheelDirectionCS=L.prototype.Uy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);to(c,a)};Object.defineProperty(L.prototype,"m_wheelDirectionCS",{get:L.prototype.Ly,set:L.prototype.Uy});L.prototype.get_m_wheelAxleCS=L.prototype.Ky=function(){return k(uo(this.hy),p)};L.prototype.set_m_wheelAxleCS=L.prototype.Ty=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vo(c,a)};Object.defineProperty(L.prototype,"m_wheelAxleCS",{get:L.prototype.Ky,set:L.prototype.Ty}); +L.prototype.get_m_rotation=L.prototype.UA=function(){return wo(this.hy)};L.prototype.set_m_rotation=L.prototype.AD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xo(c,a)};Object.defineProperty(L.prototype,"m_rotation",{get:L.prototype.UA,set:L.prototype.AD});L.prototype.get_m_deltaRotation=L.prototype.Vz=function(){return yo(this.hy)};L.prototype.set_m_deltaRotation=L.prototype.BC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zo(c,a)}; +Object.defineProperty(L.prototype,"m_deltaRotation",{get:L.prototype.Vz,set:L.prototype.BC});L.prototype.get_m_brake=L.prototype.Fz=function(){return Ao(this.hy)};L.prototype.set_m_brake=L.prototype.lC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bo(c,a)};Object.defineProperty(L.prototype,"m_brake",{get:L.prototype.Fz,set:L.prototype.lC});L.prototype.get_m_clippedInvContactDotSuspension=L.prototype.Nz=function(){return Co(this.hy)}; +L.prototype.set_m_clippedInvContactDotSuspension=L.prototype.tC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Do(c,a)};Object.defineProperty(L.prototype,"m_clippedInvContactDotSuspension",{get:L.prototype.Nz,set:L.prototype.tC});L.prototype.get_m_suspensionRelativeVelocity=L.prototype.eB=function(){return Eo(this.hy)};L.prototype.set_m_suspensionRelativeVelocity=L.prototype.LD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fo(c,a)}; +Object.defineProperty(L.prototype,"m_suspensionRelativeVelocity",{get:L.prototype.eB,set:L.prototype.LD});L.prototype.get_m_skidInfo=L.prototype.XA=function(){return Go(this.hy)};L.prototype.set_m_skidInfo=L.prototype.DD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ho(c,a)};Object.defineProperty(L.prototype,"m_skidInfo",{get:L.prototype.XA,set:L.prototype.DD});L.prototype.__destroy__=function(){Io(this.hy)}; +function N(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===a?Jo():void 0===c?_emscripten_bind_btVector4_btVector4_1(a):void 0===d?_emscripten_bind_btVector4_btVector4_2(a,c):void 0===e?_emscripten_bind_btVector4_btVector4_3(a,c,d):Ko(a,c,d,e);h(N)[this.hy]=this}N.prototype=Object.create(p.prototype);N.prototype.constructor=N;N.prototype.iy=N;N.jy={};b.btVector4=N;N.prototype.w=function(){return Lo(this.hy)}; +N.prototype.setValue=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);Mo(g,a,c,d,e)};N.prototype.length=N.prototype.length=function(){return No(this.hy)};N.prototype.x=N.prototype.x=function(){return Oo(this.hy)};N.prototype.y=N.prototype.y=function(){return Po(this.hy)};N.prototype.z=N.prototype.z=function(){return Qo(this.hy)}; +N.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ro(c,a)};N.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);So(c,a)};N.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);To(c,a)};N.prototype.normalize=N.prototype.normalize=function(){Uo(this.hy)};N.prototype.rotate=N.prototype.rotate=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return k(Vo(d,a,c),p)}; +N.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Wo(c,a)};N.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Xo(c,a),p)};N.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Yo(c,a),p)};N.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Zo(c,a),p)};N.prototype.__destroy__=function(){$o(this.hy)};function LB(){this.hy=ap();h(LB)[this.hy]=this}LB.prototype=Object.create(f.prototype); +LB.prototype.constructor=LB;LB.prototype.iy=LB;LB.jy={};b.btDefaultCollisionConstructionInfo=LB;LB.prototype.__destroy__=function(){bp(this.hy)};function O(){throw"cannot construct a Anchor, no constructor in IDL";}O.prototype=Object.create(f.prototype);O.prototype.constructor=O;O.prototype.iy=O;O.jy={};b.Anchor=O;O.prototype.get_m_node=O.prototype.FA=function(){return k(cp(this.hy),Node)};O.prototype.set_m_node=O.prototype.lD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dp(c,a)}; +Object.defineProperty(O.prototype,"m_node",{get:O.prototype.FA,set:O.prototype.lD});O.prototype.get_m_local=O.prototype.zA=function(){return k(ep(this.hy),p)};O.prototype.set_m_local=O.prototype.fD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fp(c,a)};Object.defineProperty(O.prototype,"m_local",{get:O.prototype.zA,set:O.prototype.fD});O.prototype.get_m_body=O.prototype.Ez=function(){return k(gp(this.hy),I)}; +O.prototype.set_m_body=O.prototype.kC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);hp(c,a)};Object.defineProperty(O.prototype,"m_body",{get:O.prototype.Ez,set:O.prototype.kC});O.prototype.get_m_influence=O.prototype.sA=function(){return ip(this.hy)};O.prototype.set_m_influence=O.prototype.ZC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jp(c,a)};Object.defineProperty(O.prototype,"m_influence",{get:O.prototype.sA,set:O.prototype.ZC}); +O.prototype.get_m_c0=O.prototype.Hz=function(){return k(kp(this.hy),jB)};O.prototype.set_m_c0=O.prototype.nC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lp(c,a)};Object.defineProperty(O.prototype,"m_c0",{get:O.prototype.Hz,set:O.prototype.nC});O.prototype.get_m_c1=O.prototype.Iz=function(){return k(mp(this.hy),p)};O.prototype.set_m_c1=O.prototype.oC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);np(c,a)};Object.defineProperty(O.prototype,"m_c1",{get:O.prototype.Iz,set:O.prototype.oC}); +O.prototype.get_m_c2=O.prototype.Jz=function(){return op(this.hy)};O.prototype.set_m_c2=O.prototype.pC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pp(c,a)};Object.defineProperty(O.prototype,"m_c2",{get:O.prototype.Jz,set:O.prototype.pC});O.prototype.__destroy__=function(){qp(this.hy)};function P(){throw"cannot construct a btVehicleRaycasterResult, no constructor in IDL";}P.prototype=Object.create(f.prototype);P.prototype.constructor=P;P.prototype.iy=P;P.jy={}; +b.btVehicleRaycasterResult=P;P.prototype.get_m_hitPointInWorld=P.prototype.nA=function(){return k(rp(this.hy),p)};P.prototype.set_m_hitPointInWorld=P.prototype.UC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sp(c,a)};Object.defineProperty(P.prototype,"m_hitPointInWorld",{get:P.prototype.nA,set:P.prototype.UC});P.prototype.get_m_hitNormalInWorld=P.prototype.lA=function(){return k(tp(this.hy),p)}; +P.prototype.set_m_hitNormalInWorld=P.prototype.SC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);up(c,a)};Object.defineProperty(P.prototype,"m_hitNormalInWorld",{get:P.prototype.lA,set:P.prototype.SC});P.prototype.get_m_distFraction=P.prototype.Yz=function(){return vp(this.hy)};P.prototype.set_m_distFraction=P.prototype.EC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wp(c,a)};Object.defineProperty(P.prototype,"m_distFraction",{get:P.prototype.Yz,set:P.prototype.EC}); +P.prototype.__destroy__=function(){xp(this.hy)};function pB(){throw"cannot construct a btVector3Array, no constructor in IDL";}pB.prototype=Object.create(f.prototype);pB.prototype.constructor=pB;pB.prototype.iy=pB;pB.jy={};b.btVector3Array=pB;pB.prototype.size=pB.prototype.size=function(){return yp(this.hy)};pB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(zp(c,a),p)};pB.prototype.__destroy__=function(){Ap(this.hy)}; +function MB(){throw"cannot construct a btConstraintSolver, no constructor in IDL";}MB.prototype=Object.create(f.prototype);MB.prototype.constructor=MB;MB.prototype.iy=MB;MB.jy={};b.btConstraintSolver=MB;MB.prototype.__destroy__=function(){Bp(this.hy)};function Q(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=Cp(a,c,d);h(Q)[this.hy]=this}Q.prototype=Object.create(ZA.prototype);Q.prototype.constructor=Q;Q.prototype.iy=Q;Q.jy={}; +b.btRaycastVehicle=Q;Q.prototype.applyEngineForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Dp(d,a,c)};Q.prototype.setSteeringValue=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ep(d,a,c)};Q.prototype.getWheelTransformWS=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Fp(c,a),r)}; +Q.prototype.updateWheelTransform=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Gp(d,a,c)};Q.prototype.addWheel=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return k(Hp(aa,a,c,d,e,g,n,F),L)};Q.prototype.getNumWheels=function(){return Ip(this.hy)}; +Q.prototype.getRigidBody=function(){return k(Jp(this.hy),I)};Q.prototype.getWheelInfo=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Kp(c,a),L)};Q.prototype.setBrake=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Lp(d,a,c)};Q.prototype.setCoordinateSystem=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Mp(e,a,c,d)};Q.prototype.getCurrentSpeedKmHour=function(){return Np(this.hy)}; +Q.prototype.getChassisWorldTransform=function(){return k(Op(this.hy),r)};Q.prototype.rayCast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Pp(c,a)};Q.prototype.updateVehicle=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qp(c,a)};Q.prototype.resetSuspension=function(){Rp(this.hy)};Q.prototype.getSteeringValue=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Sp(c,a)}; +Q.prototype.updateWheelTransformsWS=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Tp(d,a):Up(d,a,c)};Q.prototype.setPitchControl=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vp(c,a)};Q.prototype.updateSuspension=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wp(c,a)};Q.prototype.updateFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xp(c,a)};Q.prototype.getRightAxis=function(){return Yp(this.hy)}; +Q.prototype.getUpAxis=function(){return Zp(this.hy)};Q.prototype.getForwardAxis=function(){return $p(this.hy)};Q.prototype.getForwardVector=function(){return k(aq(this.hy),p)};Q.prototype.getUserConstraintType=function(){return bq(this.hy)};Q.prototype.setUserConstraintType=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cq(c,a)};Q.prototype.setUserConstraintId=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dq(c,a)};Q.prototype.getUserConstraintId=function(){return eq(this.hy)}; +Q.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);fq(d,a,c)};Q.prototype.__destroy__=function(){gq(this.hy)};function NB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=hq(a);h(NB)[this.hy]=this}NB.prototype=Object.create(bB.prototype);NB.prototype.constructor=NB;NB.prototype.iy=NB;NB.jy={};b.btCylinderShapeX=NB;NB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);iq(c,a)};NB.prototype.getMargin=function(){return jq(this.hy)}; +NB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kq(c,a)};NB.prototype.getLocalScaling=function(){return k(lq(this.hy),p)};NB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);mq(d,a,c)};NB.prototype.__destroy__=function(){nq(this.hy)};function OB(a){a&&"object"===typeof a&&(a=a.hy);this.hy=oq(a);h(OB)[this.hy]=this}OB.prototype=Object.create(bB.prototype);OB.prototype.constructor=OB; +OB.prototype.iy=OB;OB.jy={};b.btCylinderShapeZ=OB;OB.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pq(c,a)};OB.prototype.getMargin=function(){return qq(this.hy)};OB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rq(c,a)};OB.prototype.getLocalScaling=function(){return k(sq(this.hy),p)};OB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);tq(d,a,c)}; +OB.prototype.__destroy__=function(){uq(this.hy)};function HB(){throw"cannot construct a btConvexPolyhedron, no constructor in IDL";}HB.prototype=Object.create(f.prototype);HB.prototype.constructor=HB;HB.prototype.iy=HB;HB.jy={};b.btConvexPolyhedron=HB;HB.prototype.get_m_vertices=HB.prototype.qB=function(){return k(vq(this.hy),pB)};HB.prototype.set_m_vertices=HB.prototype.XD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wq(c,a)}; +Object.defineProperty(HB.prototype,"m_vertices",{get:HB.prototype.qB,set:HB.prototype.XD});HB.prototype.get_m_faces=HB.prototype.Gy=function(){return k(xq(this.hy),PB)};HB.prototype.set_m_faces=HB.prototype.Py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yq(c,a)};Object.defineProperty(HB.prototype,"m_faces",{get:HB.prototype.Gy,set:HB.prototype.Py});HB.prototype.__destroy__=function(){zq(this.hy)};function QB(){this.hy=Aq();h(QB)[this.hy]=this}QB.prototype=Object.create(f.prototype); +QB.prototype.constructor=QB;QB.prototype.iy=QB;QB.jy={};b.btSequentialImpulseConstraintSolver=QB;QB.prototype.__destroy__=function(){Bq(this.hy)};function RB(){throw"cannot construct a tAnchorArray, no constructor in IDL";}RB.prototype=Object.create(f.prototype);RB.prototype.constructor=RB;RB.prototype.iy=RB;RB.jy={};b.tAnchorArray=RB;RB.prototype.size=RB.prototype.size=function(){return Cq(this.hy)};RB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Dq(c,a),O)}; +RB.prototype.clear=RB.prototype.clear=function(){Eq(this.hy)};RB.prototype.push_back=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fq(c,a)};RB.prototype.pop_back=function(){Gq(this.hy)};RB.prototype.__destroy__=function(){Hq(this.hy)};function M(){throw"cannot construct a RaycastInfo, no constructor in IDL";}M.prototype=Object.create(f.prototype);M.prototype.constructor=M;M.prototype.iy=M;M.jy={};b.RaycastInfo=M; +M.prototype.get_m_contactNormalWS=M.prototype.Pz=function(){return k(Iq(this.hy),p)};M.prototype.set_m_contactNormalWS=M.prototype.vC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Jq(c,a)};Object.defineProperty(M.prototype,"m_contactNormalWS",{get:M.prototype.Pz,set:M.prototype.vC});M.prototype.get_m_contactPointWS=M.prototype.Qz=function(){return k(Kq(this.hy),p)};M.prototype.set_m_contactPointWS=M.prototype.wC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lq(c,a)}; +Object.defineProperty(M.prototype,"m_contactPointWS",{get:M.prototype.Qz,set:M.prototype.wC});M.prototype.get_m_suspensionLength=M.prototype.dB=function(){return Mq(this.hy)};M.prototype.set_m_suspensionLength=M.prototype.KD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nq(c,a)};Object.defineProperty(M.prototype,"m_suspensionLength",{get:M.prototype.dB,set:M.prototype.KD});M.prototype.get_m_hardPointWS=M.prototype.hA=function(){return k(Oq(this.hy),p)}; +M.prototype.set_m_hardPointWS=M.prototype.OC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pq(c,a)};Object.defineProperty(M.prototype,"m_hardPointWS",{get:M.prototype.hA,set:M.prototype.OC});M.prototype.get_m_wheelDirectionWS=M.prototype.sB=function(){return k(Qq(this.hy),p)};M.prototype.set_m_wheelDirectionWS=M.prototype.ZD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rq(c,a)};Object.defineProperty(M.prototype,"m_wheelDirectionWS",{get:M.prototype.sB,set:M.prototype.ZD}); +M.prototype.get_m_wheelAxleWS=M.prototype.rB=function(){return k(Sq(this.hy),p)};M.prototype.set_m_wheelAxleWS=M.prototype.YD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tq(c,a)};Object.defineProperty(M.prototype,"m_wheelAxleWS",{get:M.prototype.rB,set:M.prototype.YD});M.prototype.get_m_isInContact=M.prototype.tA=function(){return!!Uq(this.hy)};M.prototype.set_m_isInContact=M.prototype.$C=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vq(c,a)}; +Object.defineProperty(M.prototype,"m_isInContact",{get:M.prototype.tA,set:M.prototype.$C});M.prototype.get_m_groundObject=M.prototype.gA=function(){return Wq(this.hy)};M.prototype.set_m_groundObject=M.prototype.NC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xq(c,a)};Object.defineProperty(M.prototype,"m_groundObject",{get:M.prototype.gA,set:M.prototype.NC});M.prototype.__destroy__=function(){Yq(this.hy)}; +function SB(a,c,d){IA();a&&"object"===typeof a&&(a=a.hy);"object"==typeof c&&(c=MA(c));d&&"object"===typeof d&&(d=d.hy);this.hy=Zq(a,c,d);h(SB)[this.hy]=this}SB.prototype=Object.create(m.prototype);SB.prototype.constructor=SB;SB.prototype.iy=SB;SB.jy={};b.btMultiSphereShape=SB;SB.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$q(c,a)};SB.prototype.getLocalScaling=function(){return k(ar(this.hy),p)}; +SB.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);br(d,a,c)};SB.prototype.__destroy__=function(){cr(this.hy)};function R(a,c,d,e){IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);"object"==typeof e&&(e=MA(e));this.hy=dr(a,c,d,e);h(R)[this.hy]=this}R.prototype=Object.create(q.prototype);R.prototype.constructor=R;R.prototype.iy=R;R.jy={};b.btSoftBody=R; +R.prototype.checkLink=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return!!er(d,a,c)};R.prototype.checkFace=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return!!fr(e,a,c,d)};R.prototype.appendMaterial=function(){return k(gr(this.hy),A)};R.prototype.appendNode=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);hr(d,a,c)}; +R.prototype.appendLink=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);ir(g,a,c,d,e)};R.prototype.appendFace=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);jr(g,a,c,d,e)}; +R.prototype.appendTetra=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);kr(n,a,c,d,e,g)};R.prototype.appendAnchor=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);lr(g,a,c,d,e)}; +R.prototype.addForce=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?mr(d,a):nr(d,a,c)};R.prototype.addAeroForceToNode=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);or(d,a,c)};R.prototype.getTotalMass=function(){return pr(this.hy)};R.prototype.setTotalMass=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);qr(d,a,c)}; +R.prototype.setMass=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);rr(d,a,c)};R.prototype.transform=R.prototype.transform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sr(c,a)};R.prototype.translate=R.prototype.translate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tr(c,a)};R.prototype.rotate=R.prototype.rotate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ur(c,a)}; +R.prototype.scale=R.prototype.scale=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vr(c,a)};R.prototype.generateClusters=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return void 0===c?wr(d,a):xr(d,a,c)};R.prototype.generateBendingConstraints=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return yr(d,a,c)}; +R.prototype.upcast=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(zr(c,a),R)};R.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ar(d,a,c)};R.prototype.getCollisionShape=function(){return k(Br(this.hy),m)};R.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cr(c,a)}; +R.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dr(c,a)};R.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Er(c,a)};R.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Fr(c):Gr(c,a)};R.prototype.isActive=function(){return!!Hr(this.hy)};R.prototype.isKinematicObject=function(){return!!Ir(this.hy)};R.prototype.isStaticObject=function(){return!!Jr(this.hy)}; +R.prototype.isStaticOrKinematicObject=function(){return!!Kr(this.hy)};R.prototype.getRestitution=function(){return Lr(this.hy)};R.prototype.getFriction=function(){return Mr(this.hy)};R.prototype.getRollingFriction=function(){return Nr(this.hy)};R.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Or(c,a)};R.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pr(c,a)}; +R.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qr(c,a)};R.prototype.getWorldTransform=function(){return k(Rr(this.hy),r)};R.prototype.getCollisionFlags=function(){return Sr(this.hy)};R.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tr(c,a)};R.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ur(c,a)}; +R.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vr(c,a)};R.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wr(c,a)};R.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Xr(c,a)};R.prototype.getUserIndex=function(){return Yr(this.hy)};R.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zr(c,a)}; +R.prototype.getUserPointer=function(){return k($r(this.hy),SA)};R.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);as(c,a)};R.prototype.getBroadphaseHandle=function(){return k(bs(this.hy),t)};R.prototype.get_m_cfg=R.prototype.Kz=function(){return k(cs(this.hy),S)};R.prototype.set_m_cfg=R.prototype.qC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ds(c,a)};Object.defineProperty(R.prototype,"m_cfg",{get:R.prototype.Kz,set:R.prototype.qC}); +R.prototype.get_m_nodes=R.prototype.GA=function(){return k(es(this.hy),TB)};R.prototype.set_m_nodes=R.prototype.mD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gs(c,a)};Object.defineProperty(R.prototype,"m_nodes",{get:R.prototype.GA,set:R.prototype.mD});R.prototype.get_m_faces=R.prototype.Gy=function(){return k(hs(this.hy),UB)};R.prototype.set_m_faces=R.prototype.Py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);is(c,a)}; +Object.defineProperty(R.prototype,"m_faces",{get:R.prototype.Gy,set:R.prototype.Py});R.prototype.get_m_materials=R.prototype.DA=function(){return k(js(this.hy),qB)};R.prototype.set_m_materials=R.prototype.jD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ks(c,a)};Object.defineProperty(R.prototype,"m_materials",{get:R.prototype.DA,set:R.prototype.jD});R.prototype.get_m_anchors=R.prototype.Az=function(){return k(ls(this.hy),RB)}; +R.prototype.set_m_anchors=R.prototype.gC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ms(c,a)};Object.defineProperty(R.prototype,"m_anchors",{get:R.prototype.Az,set:R.prototype.gC});R.prototype.__destroy__=function(){ns(this.hy)};function VB(){throw"cannot construct a btIntArray, no constructor in IDL";}VB.prototype=Object.create(f.prototype);VB.prototype.constructor=VB;VB.prototype.iy=VB;VB.jy={};b.btIntArray=VB;VB.prototype.size=VB.prototype.size=function(){return ps(this.hy)}; +VB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return qs(c,a)};VB.prototype.__destroy__=function(){rs(this.hy)};function S(){throw"cannot construct a Config, no constructor in IDL";}S.prototype=Object.create(f.prototype);S.prototype.constructor=S;S.prototype.iy=S;S.jy={};b.Config=S;S.prototype.get_kVCF=S.prototype.sz=function(){return ss(this.hy)};S.prototype.set_kVCF=S.prototype.$B=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ts(c,a)}; +Object.defineProperty(S.prototype,"kVCF",{get:S.prototype.sz,set:S.prototype.$B});S.prototype.get_kDP=S.prototype.fz=function(){return us(this.hy)};S.prototype.set_kDP=S.prototype.NB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);vs(c,a)};Object.defineProperty(S.prototype,"kDP",{get:S.prototype.fz,set:S.prototype.NB});S.prototype.get_kDG=S.prototype.ez=function(){return xs(this.hy)};S.prototype.set_kDG=S.prototype.MB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ys(c,a)}; +Object.defineProperty(S.prototype,"kDG",{get:S.prototype.ez,set:S.prototype.MB});S.prototype.get_kLF=S.prototype.hz=function(){return zs(this.hy)};S.prototype.set_kLF=S.prototype.PB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);As(c,a)};Object.defineProperty(S.prototype,"kLF",{get:S.prototype.hz,set:S.prototype.PB});S.prototype.get_kPR=S.prototype.jz=function(){return Bs(this.hy)};S.prototype.set_kPR=S.prototype.RB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cs(c,a)}; +Object.defineProperty(S.prototype,"kPR",{get:S.prototype.jz,set:S.prototype.RB});S.prototype.get_kVC=S.prototype.rz=function(){return Ds(this.hy)};S.prototype.set_kVC=S.prototype.ZB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Es(c,a)};Object.defineProperty(S.prototype,"kVC",{get:S.prototype.rz,set:S.prototype.ZB});S.prototype.get_kDF=S.prototype.dz=function(){return Fs(this.hy)};S.prototype.set_kDF=S.prototype.LB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gs(c,a)}; +Object.defineProperty(S.prototype,"kDF",{get:S.prototype.dz,set:S.prototype.LB});S.prototype.get_kMT=S.prototype.iz=function(){return Hs(this.hy)};S.prototype.set_kMT=S.prototype.QB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Is(c,a)};Object.defineProperty(S.prototype,"kMT",{get:S.prototype.iz,set:S.prototype.QB});S.prototype.get_kCHR=S.prototype.cz=function(){return Js(this.hy)};S.prototype.set_kCHR=S.prototype.KB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ks(c,a)}; +Object.defineProperty(S.prototype,"kCHR",{get:S.prototype.cz,set:S.prototype.KB});S.prototype.get_kKHR=S.prototype.gz=function(){return Ls(this.hy)};S.prototype.set_kKHR=S.prototype.OB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ms(c,a)};Object.defineProperty(S.prototype,"kKHR",{get:S.prototype.gz,set:S.prototype.OB});S.prototype.get_kSHR=S.prototype.kz=function(){return Ns(this.hy)}; +S.prototype.set_kSHR=S.prototype.SB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Os(c,a)};Object.defineProperty(S.prototype,"kSHR",{get:S.prototype.kz,set:S.prototype.SB});S.prototype.get_kAHR=S.prototype.bz=function(){return Ps(this.hy)};S.prototype.set_kAHR=S.prototype.JB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qs(c,a)};Object.defineProperty(S.prototype,"kAHR",{get:S.prototype.bz,set:S.prototype.JB});S.prototype.get_kSRHR_CL=S.prototype.nz=function(){return Rs(this.hy)}; +S.prototype.set_kSRHR_CL=S.prototype.VB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ss(c,a)};Object.defineProperty(S.prototype,"kSRHR_CL",{get:S.prototype.nz,set:S.prototype.VB});S.prototype.get_kSKHR_CL=S.prototype.lz=function(){return Ts(this.hy)};S.prototype.set_kSKHR_CL=S.prototype.TB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Us(c,a)};Object.defineProperty(S.prototype,"kSKHR_CL",{get:S.prototype.lz,set:S.prototype.TB});S.prototype.get_kSSHR_CL=S.prototype.pz=function(){return Vs(this.hy)}; +S.prototype.set_kSSHR_CL=S.prototype.XB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ws(c,a)};Object.defineProperty(S.prototype,"kSSHR_CL",{get:S.prototype.pz,set:S.prototype.XB});S.prototype.get_kSR_SPLT_CL=S.prototype.oz=function(){return Xs(this.hy)};S.prototype.set_kSR_SPLT_CL=S.prototype.WB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ys(c,a)};Object.defineProperty(S.prototype,"kSR_SPLT_CL",{get:S.prototype.oz,set:S.prototype.WB}); +S.prototype.get_kSK_SPLT_CL=S.prototype.mz=function(){return Zs(this.hy)};S.prototype.set_kSK_SPLT_CL=S.prototype.UB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$s(c,a)};Object.defineProperty(S.prototype,"kSK_SPLT_CL",{get:S.prototype.mz,set:S.prototype.UB});S.prototype.get_kSS_SPLT_CL=S.prototype.qz=function(){return at(this.hy)};S.prototype.set_kSS_SPLT_CL=S.prototype.YB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bt(c,a)}; +Object.defineProperty(S.prototype,"kSS_SPLT_CL",{get:S.prototype.qz,set:S.prototype.YB});S.prototype.get_maxvolume=S.prototype.yB=function(){return ct(this.hy)};S.prototype.set_maxvolume=S.prototype.eE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dt(c,a)};Object.defineProperty(S.prototype,"maxvolume",{get:S.prototype.yB,set:S.prototype.eE});S.prototype.get_timescale=S.prototype.AB=function(){return et(this.hy)}; +S.prototype.set_timescale=S.prototype.gE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ft(c,a)};Object.defineProperty(S.prototype,"timescale",{get:S.prototype.AB,set:S.prototype.gE});S.prototype.get_viterations=S.prototype.BB=function(){return gt(this.hy)};S.prototype.set_viterations=S.prototype.hE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ht(c,a)};Object.defineProperty(S.prototype,"viterations",{get:S.prototype.BB,set:S.prototype.hE}); +S.prototype.get_piterations=S.prototype.zB=function(){return it(this.hy)};S.prototype.set_piterations=S.prototype.fE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jt(c,a)};Object.defineProperty(S.prototype,"piterations",{get:S.prototype.zB,set:S.prototype.fE});S.prototype.get_diterations=S.prototype.az=function(){return kt(this.hy)};S.prototype.set_diterations=S.prototype.IB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lt(c,a)}; +Object.defineProperty(S.prototype,"diterations",{get:S.prototype.az,set:S.prototype.IB});S.prototype.get_citerations=S.prototype.Zy=function(){return mt(this.hy)};S.prototype.set_citerations=S.prototype.GB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nt(c,a)};Object.defineProperty(S.prototype,"citerations",{get:S.prototype.Zy,set:S.prototype.GB});S.prototype.get_collisions=S.prototype.$y=function(){return ot(this.hy)}; +S.prototype.set_collisions=S.prototype.HB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pt(c,a)};Object.defineProperty(S.prototype,"collisions",{get:S.prototype.$y,set:S.prototype.HB});S.prototype.__destroy__=function(){qt(this.hy)};function Node(){throw"cannot construct a Node, no constructor in IDL";}Node.prototype=Object.create(f.prototype);Node.prototype.constructor=Node;Node.prototype.iy=Node;Node.jy={};b.Node=Node; +Node.prototype.get_m_x=Node.prototype.xB=function(){return k(rt(this.hy),p)};Node.prototype.set_m_x=Node.prototype.dE=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);st(c,a)};Object.defineProperty(Node.prototype,"m_x",{get:Node.prototype.xB,set:Node.prototype.dE});Node.prototype.get_m_q=Node.prototype.OA=function(){return k(tt(this.hy),p)};Node.prototype.set_m_q=Node.prototype.uD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ut(c,a)}; +Object.defineProperty(Node.prototype,"m_q",{get:Node.prototype.OA,set:Node.prototype.uD});Node.prototype.get_m_v=Node.prototype.pB=function(){return k(vt(this.hy),p)};Node.prototype.set_m_v=Node.prototype.WD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wt(c,a)};Object.defineProperty(Node.prototype,"m_v",{get:Node.prototype.pB,set:Node.prototype.WD});Node.prototype.get_m_f=Node.prototype.bA=function(){return k(xt(this.hy),p)}; +Node.prototype.set_m_f=Node.prototype.IC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yt(c,a)};Object.defineProperty(Node.prototype,"m_f",{get:Node.prototype.bA,set:Node.prototype.IC});Node.prototype.get_m_n=Node.prototype.Hy=function(){return k(zt(this.hy),p)};Node.prototype.set_m_n=Node.prototype.Qy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);At(c,a)};Object.defineProperty(Node.prototype,"m_n",{get:Node.prototype.Hy,set:Node.prototype.Qy}); +Node.prototype.get_m_im=Node.prototype.pA=function(){return Bt(this.hy)};Node.prototype.set_m_im=Node.prototype.WC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ct(c,a)};Object.defineProperty(Node.prototype,"m_im",{get:Node.prototype.pA,set:Node.prototype.WC});Node.prototype.get_m_area=Node.prototype.Dz=function(){return Dt(this.hy)};Node.prototype.set_m_area=Node.prototype.jC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Et(c,a)}; +Object.defineProperty(Node.prototype,"m_area",{get:Node.prototype.Dz,set:Node.prototype.jC});Node.prototype.__destroy__=function(){Ft(this.hy)};function WB(){this.hy=Gt();h(WB)[this.hy]=this}WB.prototype=Object.create(f.prototype);WB.prototype.constructor=WB;WB.prototype.iy=WB;WB.jy={};b.btGhostPairCallback=WB;WB.prototype.__destroy__=function(){Ht(this.hy)};function XB(){throw"cannot construct a btOverlappingPairCallback, no constructor in IDL";}XB.prototype=Object.create(f.prototype); +XB.prototype.constructor=XB;XB.prototype.iy=XB;XB.jy={};b.btOverlappingPairCallback=XB;XB.prototype.__destroy__=function(){It(this.hy)};function T(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===e?Jt(a,c,d):Kt(a,c,d,e);h(T)[this.hy]=this}T.prototype=Object.create(ZA.prototype);T.prototype.constructor=T;T.prototype.iy=T;T.jy={};b.btKinematicCharacterController=T; +T.prototype.setUpAxis=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Lt(c,a)};T.prototype.setWalkDirection=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mt(c,a)};T.prototype.setVelocityForTimeInterval=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Nt(d,a,c)};T.prototype.warp=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ot(c,a)};T.prototype.preStep=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pt(c,a)}; +T.prototype.playerStep=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Qt(d,a,c)};T.prototype.setFallSpeed=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rt(c,a)};T.prototype.setJumpSpeed=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);St(c,a)};T.prototype.setMaxJumpHeight=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tt(c,a)};T.prototype.canJump=function(){return!!Ut(this.hy)};T.prototype.jump=function(){Vt(this.hy)}; +T.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wt(c,a)};T.prototype.getGravity=function(){return Xt(this.hy)};T.prototype.setMaxSlope=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yt(c,a)};T.prototype.getMaxSlope=function(){return Zt(this.hy)};T.prototype.getGhostObject=function(){return k($t(this.hy),U)};T.prototype.setUseGhostSweepTest=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);au(c,a)};T.prototype.onGround=function(){return!!bu(this.hy)}; +T.prototype.setUpInterpolate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cu(c,a)};T.prototype.updateAction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);du(d,a,c)};T.prototype.__destroy__=function(){eu(this.hy)};function YB(){throw"cannot construct a btSoftBodyArray, no constructor in IDL";}YB.prototype=Object.create(f.prototype);YB.prototype.constructor=YB;YB.prototype.iy=YB;YB.jy={};b.btSoftBodyArray=YB; +YB.prototype.size=YB.prototype.size=function(){return fu(this.hy)};YB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(gu(c,a),R)};YB.prototype.__destroy__=function(){hu(this.hy)};function PB(){throw"cannot construct a btFaceArray, no constructor in IDL";}PB.prototype=Object.create(f.prototype);PB.prototype.constructor=PB;PB.prototype.iy=PB;PB.jy={};b.btFaceArray=PB;PB.prototype.size=PB.prototype.size=function(){return iu(this.hy)}; +PB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(ju(c,a),ZB)};PB.prototype.__destroy__=function(){ku(this.hy)};function $B(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=lu(a,c);h($B)[this.hy]=this}$B.prototype=Object.create(UA.prototype);$B.prototype.constructor=$B;$B.prototype.iy=$B;$B.jy={};b.btStaticPlaneShape=$B;$B.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mu(c,a)}; +$B.prototype.getLocalScaling=function(){return k(nu(this.hy),p)};$B.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);ou(d,a,c)};$B.prototype.__destroy__=function(){pu(this.hy)};function PA(){throw"cannot construct a btOverlappingPairCache, no constructor in IDL";}PA.prototype=Object.create(f.prototype);PA.prototype.constructor=PA;PA.prototype.iy=PA;PA.jy={};b.btOverlappingPairCache=PA; +PA.prototype.setInternalGhostPairCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qu(c,a)};PA.prototype.getNumOverlappingPairs=function(){return ru(this.hy)};PA.prototype.__destroy__=function(){su(this.hy)};function vB(){throw"cannot construct a btIndexedMesh, no constructor in IDL";}vB.prototype=Object.create(f.prototype);vB.prototype.constructor=vB;vB.prototype.iy=vB;vB.jy={};b.btIndexedMesh=vB;vB.prototype.get_m_numTriangles=vB.prototype.KA=function(){return tu(this.hy)}; +vB.prototype.set_m_numTriangles=vB.prototype.qD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uu(c,a)};Object.defineProperty(vB.prototype,"m_numTriangles",{get:vB.prototype.KA,set:vB.prototype.qD});vB.prototype.__destroy__=function(){vu(this.hy)};function V(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=wu(a,c,d,e,g);h(V)[this.hy]=this}V.prototype=Object.create(x.prototype); +V.prototype.constructor=V;V.prototype.iy=V;V.jy={};b.btSoftRigidDynamicsWorld=V;V.prototype.addSoftBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);xu(e,a,c,d)};V.prototype.removeSoftBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yu(c,a)};V.prototype.removeCollisionObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);zu(c,a)};V.prototype.getWorldInfo=function(){return k(Au(this.hy),J)}; +V.prototype.getSoftBodyArray=function(){return k(Bu(this.hy),YB)};V.prototype.getDispatcher=function(){return k(Cu(this.hy),OA)};V.prototype.rayTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Du(e,a,c,d)};V.prototype.getPairCache=function(){return k(Eu(this.hy),PA)};V.prototype.getDispatchInfo=function(){return k(Fu(this.hy),l)}; +V.prototype.addCollisionObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Gu(e,a):void 0===d?Hu(e,a,c):Iu(e,a,c,d)};V.prototype.getBroadphase=function(){return k(Ju(this.hy),QA)}; +V.prototype.convexSweepTest=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);Ku(n,a,c,d,e,g)};V.prototype.contactPairTest=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Lu(e,a,c,d)}; +V.prototype.contactTest=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Mu(d,a,c)};V.prototype.updateSingleAabb=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nu(c,a)};V.prototype.setDebugDrawer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ou(c,a)};V.prototype.getDebugDrawer=function(){return k(Pu(this.hy),RA)};V.prototype.debugDrawWorld=function(){Qu(this.hy)}; +V.prototype.debugDrawObject=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ru(e,a,c,d)};V.prototype.setGravity=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Su(c,a)};V.prototype.getGravity=function(){return k(Tu(this.hy),p)}; +V.prototype.addRigidBody=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?Uu(e,a):void 0===d?_emscripten_bind_btSoftRigidDynamicsWorld_addRigidBody_2(e,a,c):Vu(e,a,c,d)};V.prototype.removeRigidBody=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wu(c,a)}; +V.prototype.addConstraint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===c?Xu(d,a):Yu(d,a,c)};V.prototype.removeConstraint=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Zu(c,a)};V.prototype.stepSimulation=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);return void 0===c?$u(e,a):void 0===d?av(e,a,c):bv(e,a,c,d)}; +V.prototype.setContactAddedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cv(c,a)};V.prototype.setContactProcessedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);dv(c,a)};V.prototype.setContactDestroyedCallback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ev(c,a)};V.prototype.addAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fv(c,a)};V.prototype.removeAction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gv(c,a)}; +V.prototype.getSolverInfo=function(){return k(hv(this.hy),v)};V.prototype.setInternalTickCallback=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);void 0===c?iv(e,a):void 0===d?jv(e,a,c):kv(e,a,c,d)};V.prototype.__destroy__=function(){lv(this.hy)}; +function aC(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=mv(a,c,d,e);h(aC)[this.hy]=this}aC.prototype=Object.create(TA.prototype);aC.prototype.constructor=aC;aC.prototype.iy=aC;aC.jy={};b.btFixedConstraint=aC;aC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nv(c,a)};aC.prototype.getBreakingImpulseThreshold=function(){return ov(this.hy)}; +aC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pv(c,a)};aC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return qv(d,a,c)};aC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);rv(e,a,c,d)};aC.prototype.__destroy__=function(){sv(this.hy)}; +function r(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=void 0===a?tv():void 0===c?_emscripten_bind_btTransform_btTransform_1(a):uv(a,c);h(r)[this.hy]=this}r.prototype=Object.create(f.prototype);r.prototype.constructor=r;r.prototype.iy=r;r.jy={};b.btTransform=r;r.prototype.setIdentity=function(){vv(this.hy)};r.prototype.setOrigin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);wv(c,a)}; +r.prototype.setRotation=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xv(c,a)};r.prototype.getOrigin=function(){return k(yv(this.hy),p)};r.prototype.getRotation=function(){return k(zv(this.hy),W)};r.prototype.getBasis=function(){return k(Av(this.hy),jB)};r.prototype.setFromOpenGLMatrix=function(a){var c=this.hy;IA();"object"==typeof a&&(a=MA(a));Bv(c,a)};r.prototype.inverse=r.prototype.inverse=function(){return k(Cv(this.hy),r)}; +r.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Dv(c,a),r)};r.prototype.__destroy__=function(){Ev(this.hy)};function X(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=Fv(a,c);h(X)[this.hy]=this}X.prototype=Object.create(z.prototype);X.prototype.constructor=X;X.prototype.iy=X;X.jy={};b.ClosestRayResultCallback=X;X.prototype.hasHit=function(){return!!Gv(this.hy)}; +X.prototype.get_m_rayFromWorld=X.prototype.Iy=function(){return k(Hv(this.hy),p)};X.prototype.set_m_rayFromWorld=X.prototype.Ry=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Iv(c,a)};Object.defineProperty(X.prototype,"m_rayFromWorld",{get:X.prototype.Iy,set:X.prototype.Ry});X.prototype.get_m_rayToWorld=X.prototype.Jy=function(){return k(Jv(this.hy),p)};X.prototype.set_m_rayToWorld=X.prototype.Sy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kv(c,a)}; +Object.defineProperty(X.prototype,"m_rayToWorld",{get:X.prototype.Jy,set:X.prototype.Sy});X.prototype.get_m_hitNormalWorld=X.prototype.sy=function(){return k(Lv(this.hy),p)};X.prototype.set_m_hitNormalWorld=X.prototype.zy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Mv(c,a)};Object.defineProperty(X.prototype,"m_hitNormalWorld",{get:X.prototype.sy,set:X.prototype.zy});X.prototype.get_m_hitPointWorld=X.prototype.ty=function(){return k(Nv(this.hy),p)}; +X.prototype.set_m_hitPointWorld=X.prototype.Ay=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ov(c,a)};Object.defineProperty(X.prototype,"m_hitPointWorld",{get:X.prototype.ty,set:X.prototype.Ay});X.prototype.get_m_collisionFilterGroup=X.prototype.ky=function(){return Pv(this.hy)};X.prototype.set_m_collisionFilterGroup=X.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Qv(c,a)};Object.defineProperty(X.prototype,"m_collisionFilterGroup",{get:X.prototype.ky,set:X.prototype.my}); +X.prototype.get_m_collisionFilterMask=X.prototype.ly=function(){return Rv(this.hy)};X.prototype.set_m_collisionFilterMask=X.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sv(c,a)};Object.defineProperty(X.prototype,"m_collisionFilterMask",{get:X.prototype.ly,set:X.prototype.ny});X.prototype.get_m_closestHitFraction=X.prototype.oy=function(){return Tv(this.hy)}; +X.prototype.set_m_closestHitFraction=X.prototype.py=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uv(c,a)};Object.defineProperty(X.prototype,"m_closestHitFraction",{get:X.prototype.oy,set:X.prototype.py});X.prototype.get_m_collisionObject=X.prototype.qy=function(){return k(Vv(this.hy),q)};X.prototype.set_m_collisionObject=X.prototype.xy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Wv(c,a)};Object.defineProperty(X.prototype,"m_collisionObject",{get:X.prototype.qy,set:X.prototype.xy}); +X.prototype.__destroy__=function(){Xv(this.hy)};function bC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=void 0===a?Yv():Zv(a);h(bC)[this.hy]=this}bC.prototype=Object.create(WA.prototype);bC.prototype.constructor=bC;bC.prototype.iy=bC;bC.jy={};b.btSoftBodyRigidBodyCollisionConfiguration=bC;bC.prototype.__destroy__=function(){$v(this.hy)};function cC(){this.hy=aw();h(cC)[this.hy]=this}cC.prototype=Object.create(hB.prototype);cC.prototype.constructor=cC;cC.prototype.iy=cC;cC.jy={}; +b.ConcreteContactResultCallback=cC;cC.prototype.addSingleResult=function(a,c,d,e,g,n,F){var aa=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);return bw(aa,a,c,d,e,g,n,F)};cC.prototype.__destroy__=function(){cw(this.hy)}; +function dC(a,c,d){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);this.hy=void 0===d?dw(a,c):ew(a,c,d);h(dC)[this.hy]=this}dC.prototype=Object.create(XA.prototype);dC.prototype.constructor=dC;dC.prototype.iy=dC;dC.jy={};b.btBvhTriangleMeshShape=dC;dC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fw(c,a)};dC.prototype.getLocalScaling=function(){return k(gw(this.hy),p)}; +dC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);hw(d,a,c)};dC.prototype.__destroy__=function(){iw(this.hy)};function oB(){throw"cannot construct a btConstCollisionObjectArray, no constructor in IDL";}oB.prototype=Object.create(f.prototype);oB.prototype.constructor=oB;oB.prototype.iy=oB;oB.jy={};b.btConstCollisionObjectArray=oB;oB.prototype.size=oB.prototype.size=function(){return jw(this.hy)}; +oB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(kw(c,a),q)};oB.prototype.__destroy__=function(){lw(this.hy)};function eC(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?mw(a,c,d):void 0===g?_emscripten_bind_btSliderConstraint_btSliderConstraint_4(a,c,d,e):nw(a,c,d,e,g);h(eC)[this.hy]=this}eC.prototype=Object.create(TA.prototype); +eC.prototype.constructor=eC;eC.prototype.iy=eC;eC.jy={};b.btSliderConstraint=eC;eC.prototype.setLowerLinLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ow(c,a)};eC.prototype.setUpperLinLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pw(c,a)};eC.prototype.setLowerAngLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);qw(c,a)};eC.prototype.setUpperAngLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rw(c,a)}; +eC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);sw(c,a)};eC.prototype.getBreakingImpulseThreshold=function(){return tw(this.hy)};eC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);uw(c,a)};eC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return vw(d,a,c)}; +eC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ww(e,a,c,d)};eC.prototype.__destroy__=function(){xw(this.hy)};function U(){this.hy=yw();h(U)[this.hy]=this}U.prototype=Object.create(w.prototype);U.prototype.constructor=U;U.prototype.iy=U;U.jy={};b.btPairCachingGhostObject=U; +U.prototype.setAnisotropicFriction=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);zw(d,a,c)};U.prototype.getCollisionShape=function(){return k(Aw(this.hy),m)};U.prototype.setContactProcessingThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bw(c,a)};U.prototype.setActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Cw(c,a)}; +U.prototype.forceActivationState=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dw(c,a)};U.prototype.activate=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);void 0===a?Ew(c):Fw(c,a)};U.prototype.isActive=function(){return!!Gw(this.hy)};U.prototype.isKinematicObject=function(){return!!Hw(this.hy)};U.prototype.isStaticObject=function(){return!!Iw(this.hy)};U.prototype.isStaticOrKinematicObject=function(){return!!Jw(this.hy)};U.prototype.getRestitution=function(){return Kw(this.hy)}; +U.prototype.getFriction=function(){return Lw(this.hy)};U.prototype.getRollingFriction=function(){return Mw(this.hy)};U.prototype.setRestitution=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Nw(c,a)};U.prototype.setFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ow(c,a)};U.prototype.setRollingFriction=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pw(c,a)};U.prototype.getWorldTransform=function(){return k(Qw(this.hy),r)};U.prototype.getCollisionFlags=function(){return Rw(this.hy)}; +U.prototype.setCollisionFlags=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sw(c,a)};U.prototype.setWorldTransform=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Tw(c,a)};U.prototype.setCollisionShape=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Uw(c,a)};U.prototype.setCcdMotionThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Vw(c,a)};U.prototype.setCcdSweptSphereRadius=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ww(c,a)}; +U.prototype.getUserIndex=function(){return Xw(this.hy)};U.prototype.setUserIndex=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yw(c,a)};U.prototype.getUserPointer=function(){return k(Zw(this.hy),SA)};U.prototype.setUserPointer=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$w(c,a)};U.prototype.getBroadphaseHandle=function(){return k(ax(this.hy),t)};U.prototype.getNumOverlappingObjects=function(){return bx(this.hy)}; +U.prototype.getOverlappingObject=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(cx(c,a),q)};U.prototype.__destroy__=function(){dx(this.hy)};function D(){throw"cannot construct a btManifoldPoint, no constructor in IDL";}D.prototype=Object.create(f.prototype);D.prototype.constructor=D;D.prototype.iy=D;D.jy={};b.btManifoldPoint=D;D.prototype.getPositionWorldOnA=function(){return k(ex(this.hy),p)};D.prototype.getPositionWorldOnB=function(){return k(fx(this.hy),p)}; +D.prototype.getAppliedImpulse=function(){return gx(this.hy)};D.prototype.getDistance=function(){return hx(this.hy)};D.prototype.get_m_localPointA=D.prototype.AA=function(){return k(ix(this.hy),p)};D.prototype.set_m_localPointA=D.prototype.gD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);jx(c,a)};Object.defineProperty(D.prototype,"m_localPointA",{get:D.prototype.AA,set:D.prototype.gD});D.prototype.get_m_localPointB=D.prototype.BA=function(){return k(kx(this.hy),p)}; +D.prototype.set_m_localPointB=D.prototype.hD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);lx(c,a)};Object.defineProperty(D.prototype,"m_localPointB",{get:D.prototype.BA,set:D.prototype.hD});D.prototype.get_m_positionWorldOnB=D.prototype.NA=function(){return k(mx(this.hy),p)};D.prototype.set_m_positionWorldOnB=D.prototype.tD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);nx(c,a)};Object.defineProperty(D.prototype,"m_positionWorldOnB",{get:D.prototype.NA,set:D.prototype.tD}); +D.prototype.get_m_positionWorldOnA=D.prototype.MA=function(){return k(ox(this.hy),p)};D.prototype.set_m_positionWorldOnA=D.prototype.sD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);px(c,a)};Object.defineProperty(D.prototype,"m_positionWorldOnA",{get:D.prototype.MA,set:D.prototype.sD});D.prototype.get_m_normalWorldOnB=D.prototype.IA=function(){return k(qx(this.hy),p)};D.prototype.set_m_normalWorldOnB=D.prototype.oD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rx(c,a)}; +Object.defineProperty(D.prototype,"m_normalWorldOnB",{get:D.prototype.IA,set:D.prototype.oD});D.prototype.get_m_userPersistentData=D.prototype.oB=function(){return sx(this.hy)};D.prototype.set_m_userPersistentData=D.prototype.VD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tx(c,a)};Object.defineProperty(D.prototype,"m_userPersistentData",{get:D.prototype.oB,set:D.prototype.VD});D.prototype.__destroy__=function(){ux(this.hy)}; +function fC(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=void 0===d?vx(a,c):void 0===e?_emscripten_bind_btPoint2PointConstraint_btPoint2PointConstraint_3(a,c,d):wx(a,c,d,e);h(fC)[this.hy]=this}fC.prototype=Object.create(TA.prototype);fC.prototype.constructor=fC;fC.prototype.iy=fC;fC.jy={};b.btPoint2PointConstraint=fC; +fC.prototype.setPivotA=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);xx(c,a)};fC.prototype.setPivotB=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yx(c,a)};fC.prototype.getPivotInA=function(){return k(zx(this.hy),p)};fC.prototype.getPivotInB=function(){return k(Ax(this.hy),p)};fC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Bx(c,a)};fC.prototype.getBreakingImpulseThreshold=function(){return Cx(this.hy)}; +fC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dx(c,a)};fC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Ex(d,a,c)};fC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Fx(e,a,c,d)};fC.prototype.get_m_setting=fC.prototype.VA=function(){return k(Gx(this.hy),H)}; +fC.prototype.set_m_setting=fC.prototype.BD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Hx(c,a)};Object.defineProperty(fC.prototype,"m_setting",{get:fC.prototype.VA,set:fC.prototype.BD});fC.prototype.__destroy__=function(){Ix(this.hy)};function gC(){this.hy=Jx();h(gC)[this.hy]=this}gC.prototype=Object.create(f.prototype);gC.prototype.constructor=gC;gC.prototype.iy=gC;gC.jy={};b.btSoftBodyHelpers=gC; +gC.prototype.CreateRope=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);return k(Kx(n,a,c,d,e,g),R)}; +gC.prototype.CreatePatch=function(a,c,d,e,g,n,F,aa,ta){var Rb=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);return k(Lx(Rb,a,c,d,e,g,n,F,aa,ta),R)}; +gC.prototype.CreatePatchUV=function(a,c,d,e,g,n,F,aa,ta,Rb){var nC=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);n&&"object"===typeof n&&(n=n.hy);F&&"object"===typeof F&&(F=F.hy);aa&&"object"===typeof aa&&(aa=aa.hy);ta&&"object"===typeof ta&&(ta=ta.hy);"object"==typeof Rb&&(Rb=MA(Rb));return k(Mx(nC,a,c,d,e,g,n,F,aa,ta,Rb),R)}; +gC.prototype.CreateEllipsoid=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);return k(Nx(g,a,c,d,e),R)}; +gC.prototype.CreateFromTriMesh=function(a,c,d,e,g){var n=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);"object"==typeof c&&(c=MA(c));if("object"==typeof d&&"object"===typeof d){var F=JA(d,Aa);KA(d,Aa,F);d=F}e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);return k(Ox(n,a,c,d,e,g),R)}; +gC.prototype.CreateFromConvexHull=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);return k(Px(g,a,c,d,e),R)};gC.prototype.__destroy__=function(){Qx(this.hy)};function t(){throw"cannot construct a btBroadphaseProxy, no constructor in IDL";}t.prototype=Object.create(f.prototype);t.prototype.constructor=t;t.prototype.iy=t;t.jy={};b.btBroadphaseProxy=t; +t.prototype.get_m_collisionFilterGroup=t.prototype.ky=function(){return Rx(this.hy)};t.prototype.set_m_collisionFilterGroup=t.prototype.my=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Sx(c,a)};Object.defineProperty(t.prototype,"m_collisionFilterGroup",{get:t.prototype.ky,set:t.prototype.my});t.prototype.get_m_collisionFilterMask=t.prototype.ly=function(){return Tx(this.hy)}; +t.prototype.set_m_collisionFilterMask=t.prototype.ny=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ux(c,a)};Object.defineProperty(t.prototype,"m_collisionFilterMask",{get:t.prototype.ly,set:t.prototype.ny});t.prototype.__destroy__=function(){Vx(this.hy)};function TB(){throw"cannot construct a tNodeArray, no constructor in IDL";}TB.prototype=Object.create(f.prototype);TB.prototype.constructor=TB;TB.prototype.iy=TB;TB.jy={};b.tNodeArray=TB;TB.prototype.size=TB.prototype.size=function(){return Wx(this.hy)}; +TB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Xx(c,a),Node)};TB.prototype.__destroy__=function(){Yx(this.hy)};function hC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Zx(a);h(hC)[this.hy]=this}hC.prototype=Object.create(m.prototype);hC.prototype.constructor=hC;hC.prototype.iy=hC;hC.jy={};b.btBoxShape=hC;hC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$x(c,a)};hC.prototype.getMargin=function(){return ay(this.hy)}; +hC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);by(c,a)};hC.prototype.getLocalScaling=function(){return k(cy(this.hy),p)};hC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);dy(d,a,c)};hC.prototype.__destroy__=function(){ey(this.hy)};function ZB(){throw"cannot construct a btFace, no constructor in IDL";}ZB.prototype=Object.create(f.prototype);ZB.prototype.constructor=ZB; +ZB.prototype.iy=ZB;ZB.jy={};b.btFace=ZB;ZB.prototype.get_m_indices=ZB.prototype.rA=function(){return k(fy(this.hy),VB)};ZB.prototype.set_m_indices=ZB.prototype.YC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gy(c,a)};Object.defineProperty(ZB.prototype,"m_indices",{get:ZB.prototype.rA,set:ZB.prototype.YC});ZB.prototype.get_m_plane=ZB.prototype.LA=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return hy(c,a)}; +ZB.prototype.set_m_plane=ZB.prototype.rD=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);iy(d,a,c)};Object.defineProperty(ZB.prototype,"m_plane",{get:ZB.prototype.LA,set:ZB.prototype.rD});ZB.prototype.__destroy__=function(){jy(this.hy)};function iC(){this.hy=ky();h(iC)[this.hy]=this}iC.prototype=Object.create(RA.prototype);iC.prototype.constructor=iC;iC.prototype.iy=iC;iC.jy={};b.DebugDrawer=iC; +iC.prototype.drawLine=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);ly(e,a,c,d)};iC.prototype.drawContactPoint=function(a,c,d,e,g){var n=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);my(n,a,c,d,e,g)}; +iC.prototype.reportErrorWarning=function(a){var c=this.hy;IA();a=a&&"object"===typeof a?a.hy:LA(a);ny(c,a)};iC.prototype.draw3dText=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c=c&&"object"===typeof c?c.hy:LA(c);oy(d,a,c)};iC.prototype.setDebugMode=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);py(c,a)};iC.prototype.getDebugMode=function(){return qy(this.hy)};iC.prototype.__destroy__=function(){ry(this.hy)}; +function jC(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=sy(a,c);h(jC)[this.hy]=this}jC.prototype=Object.create(VA.prototype);jC.prototype.constructor=jC;jC.prototype.iy=jC;jC.jy={};b.btCapsuleShapeX=jC;jC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);ty(c,a)};jC.prototype.getMargin=function(){return uy(this.hy)};jC.prototype.getUpAxis=function(){return vy(this.hy)};jC.prototype.getRadius=function(){return wy(this.hy)}; +jC.prototype.getHalfHeight=function(){return xy(this.hy)};jC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);yy(c,a)};jC.prototype.getLocalScaling=function(){return k(zy(this.hy),p)};jC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Ay(d,a,c)};jC.prototype.__destroy__=function(){By(this.hy)}; +function W(a,c,d,e){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);this.hy=Cy(a,c,d,e);h(W)[this.hy]=this}W.prototype=Object.create(aB.prototype);W.prototype.constructor=W;W.prototype.iy=W;W.jy={};b.btQuaternion=W;W.prototype.setValue=function(a,c,d,e){var g=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);Dy(g,a,c,d,e)}; +W.prototype.setEulerZYX=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Ey(e,a,c,d)};W.prototype.setRotation=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Fy(d,a,c)};W.prototype.normalize=W.prototype.normalize=function(){Gy(this.hy)};W.prototype.length2=function(){return Hy(this.hy)};W.prototype.length=W.prototype.length=function(){return Iy(this.hy)}; +W.prototype.dot=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Jy(c,a)};W.prototype.normalized=function(){return k(Ky(this.hy),W)};W.prototype.getAxis=function(){return k(Ly(this.hy),p)};W.prototype.inverse=W.prototype.inverse=function(){return k(My(this.hy),W)};W.prototype.getAngle=function(){return Ny(this.hy)};W.prototype.getAngleShortestPath=function(){return Oy(this.hy)}; +W.prototype.angle=W.prototype.angle=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Py(c,a)};W.prototype.angleShortestPath=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return Qy(c,a)};W.prototype.op_add=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Ry(c,a),W)};W.prototype.op_sub=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Sy(c,a),W)}; +W.prototype.op_mul=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Ty(c,a),W)};W.prototype.op_mulq=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Uy(c,a),W)};W.prototype.op_div=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Vy(c,a),W)};W.prototype.x=W.prototype.x=function(){return Wy(this.hy)};W.prototype.y=W.prototype.y=function(){return Xy(this.hy)};W.prototype.z=W.prototype.z=function(){return Yy(this.hy)};W.prototype.w=function(){return Zy(this.hy)}; +W.prototype.setX=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$y(c,a)};W.prototype.setY=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);az(c,a)};W.prototype.setZ=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);bz(c,a)};W.prototype.setW=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);cz(c,a)};W.prototype.__destroy__=function(){dz(this.hy)}; +function kC(a,c){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);this.hy=ez(a,c);h(kC)[this.hy]=this}kC.prototype=Object.create(VA.prototype);kC.prototype.constructor=kC;kC.prototype.iy=kC;kC.jy={};b.btCapsuleShapeZ=kC;kC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);fz(c,a)};kC.prototype.getMargin=function(){return gz(this.hy)};kC.prototype.getUpAxis=function(){return hz(this.hy)};kC.prototype.getRadius=function(){return iz(this.hy)}; +kC.prototype.getHalfHeight=function(){return jz(this.hy)};kC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kz(c,a)};kC.prototype.getLocalScaling=function(){return k(lz(this.hy),p)};kC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);mz(d,a,c)};kC.prototype.__destroy__=function(){nz(this.hy)};function v(){throw"cannot construct a btContactSolverInfo, no constructor in IDL";} +v.prototype=Object.create(f.prototype);v.prototype.constructor=v;v.prototype.iy=v;v.jy={};b.btContactSolverInfo=v;v.prototype.get_m_splitImpulse=v.prototype.YA=function(){return!!oz(this.hy)};v.prototype.set_m_splitImpulse=v.prototype.ED=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);pz(c,a)};Object.defineProperty(v.prototype,"m_splitImpulse",{get:v.prototype.YA,set:v.prototype.ED});v.prototype.get_m_splitImpulsePenetrationThreshold=v.prototype.ZA=function(){return qz(this.hy)}; +v.prototype.set_m_splitImpulsePenetrationThreshold=v.prototype.FD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);rz(c,a)};Object.defineProperty(v.prototype,"m_splitImpulsePenetrationThreshold",{get:v.prototype.ZA,set:v.prototype.FD});v.prototype.get_m_numIterations=v.prototype.JA=function(){return sz(this.hy)};v.prototype.set_m_numIterations=v.prototype.pD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);tz(c,a)}; +Object.defineProperty(v.prototype,"m_numIterations",{get:v.prototype.JA,set:v.prototype.pD});v.prototype.__destroy__=function(){uz(this.hy)};function lC(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=void 0===e?vz(a,c,d):void 0===g?_emscripten_bind_btGeneric6DofSpringConstraint_btGeneric6DofSpringConstraint_4(a,c,d,e):wz(a,c,d,e,g);h(lC)[this.hy]=this} +lC.prototype=Object.create(eB.prototype);lC.prototype.constructor=lC;lC.prototype.iy=lC;lC.jy={};b.btGeneric6DofSpringConstraint=lC;lC.prototype.enableSpring=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);xz(d,a,c)};lC.prototype.setStiffness=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);yz(d,a,c)}; +lC.prototype.setDamping=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);zz(d,a,c)};lC.prototype.setEquilibriumPoint=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);void 0===a?Az(d):void 0===c?Bz(d,a):Cz(d,a,c)};lC.prototype.setLinearLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Dz(c,a)}; +lC.prototype.setLinearUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Ez(c,a)};lC.prototype.setAngularLowerLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Fz(c,a)};lC.prototype.setAngularUpperLimit=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Gz(c,a)};lC.prototype.getFrameOffsetA=function(){return k(Hz(this.hy),r)};lC.prototype.enableFeedback=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Iz(c,a)}; +lC.prototype.getBreakingImpulseThreshold=function(){return Jz(this.hy)};lC.prototype.setBreakingImpulseThreshold=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Kz(c,a)};lC.prototype.getParam=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);return Lz(d,a,c)};lC.prototype.setParam=function(a,c,d){var e=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);Mz(e,a,c,d)}; +lC.prototype.__destroy__=function(){Nz(this.hy)};function mC(a){a&&"object"===typeof a&&(a=a.hy);this.hy=Oz(a);h(mC)[this.hy]=this}mC.prototype=Object.create(m.prototype);mC.prototype.constructor=mC;mC.prototype.iy=mC;mC.jy={};b.btSphereShape=mC;mC.prototype.setMargin=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Pz(c,a)};mC.prototype.getMargin=function(){return Qz(this.hy)};mC.prototype.setLocalScaling=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Rz(c,a)}; +mC.prototype.getLocalScaling=function(){return k(Sz(this.hy),p)};mC.prototype.calculateLocalInertia=function(a,c){var d=this.hy;a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Tz(d,a,c)};mC.prototype.__destroy__=function(){Uz(this.hy)};function Y(){throw"cannot construct a Face, no constructor in IDL";}Y.prototype=Object.create(f.prototype);Y.prototype.constructor=Y;Y.prototype.iy=Y;Y.jy={};b.Face=Y; +Y.prototype.get_m_n=Y.prototype.Hy=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(Vz(c,a),Node)};Y.prototype.set_m_n=Y.prototype.Qy=function(a,c){var d=this.hy;IA();a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);Wz(d,a,c)};Object.defineProperty(Y.prototype,"m_n",{get:Y.prototype.Hy,set:Y.prototype.Qy});Y.prototype.get_m_normal=Y.prototype.HA=function(){return k(Xz(this.hy),p)}; +Y.prototype.set_m_normal=Y.prototype.nD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);Yz(c,a)};Object.defineProperty(Y.prototype,"m_normal",{get:Y.prototype.HA,set:Y.prototype.nD});Y.prototype.get_m_ra=Y.prototype.PA=function(){return Zz(this.hy)};Y.prototype.set_m_ra=Y.prototype.vD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);$z(c,a)};Object.defineProperty(Y.prototype,"m_ra",{get:Y.prototype.PA,set:Y.prototype.vD});Y.prototype.__destroy__=function(){aA(this.hy)}; +function UB(){throw"cannot construct a tFaceArray, no constructor in IDL";}UB.prototype=Object.create(f.prototype);UB.prototype.constructor=UB;UB.prototype.iy=UB;UB.jy={};b.tFaceArray=UB;UB.prototype.size=UB.prototype.size=function(){return bA(this.hy)};UB.prototype.at=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);return k(cA(c,a),Y)};UB.prototype.__destroy__=function(){dA(this.hy)}; +function Z(a,c,d,e,g){a&&"object"===typeof a&&(a=a.hy);c&&"object"===typeof c&&(c=c.hy);d&&"object"===typeof d&&(d=d.hy);e&&"object"===typeof e&&(e=e.hy);g&&"object"===typeof g&&(g=g.hy);this.hy=eA(a,c,d,e,g);h(Z)[this.hy]=this}Z.prototype=Object.create(f.prototype);Z.prototype.constructor=Z;Z.prototype.iy=Z;Z.jy={};b.LocalConvexResult=Z;Z.prototype.get_m_hitCollisionObject=Z.prototype.iA=function(){return k(fA(this.hy),q)}; +Z.prototype.set_m_hitCollisionObject=Z.prototype.PC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);gA(c,a)};Object.defineProperty(Z.prototype,"m_hitCollisionObject",{get:Z.prototype.iA,set:Z.prototype.PC});Z.prototype.get_m_localShapeInfo=Z.prototype.CA=function(){return k(hA(this.hy),tB)};Z.prototype.set_m_localShapeInfo=Z.prototype.iD=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);iA(c,a)};Object.defineProperty(Z.prototype,"m_localShapeInfo",{get:Z.prototype.CA,set:Z.prototype.iD}); +Z.prototype.get_m_hitNormalLocal=Z.prototype.mA=function(){return k(jA(this.hy),p)};Z.prototype.set_m_hitNormalLocal=Z.prototype.TC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);kA(c,a)};Object.defineProperty(Z.prototype,"m_hitNormalLocal",{get:Z.prototype.mA,set:Z.prototype.TC});Z.prototype.get_m_hitPointLocal=Z.prototype.oA=function(){return k(lA(this.hy),p)};Z.prototype.set_m_hitPointLocal=Z.prototype.VC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);mA(c,a)}; +Object.defineProperty(Z.prototype,"m_hitPointLocal",{get:Z.prototype.oA,set:Z.prototype.VC});Z.prototype.get_m_hitFraction=Z.prototype.jA=function(){return nA(this.hy)};Z.prototype.set_m_hitFraction=Z.prototype.QC=function(a){var c=this.hy;a&&"object"===typeof a&&(a=a.hy);oA(c,a)};Object.defineProperty(Z.prototype,"m_hitFraction",{get:Z.prototype.jA,set:Z.prototype.QC});Z.prototype.__destroy__=function(){pA(this.hy)}; +(function(){function a(){b.BT_CONSTRAINT_ERP=qA();b.BT_CONSTRAINT_STOP_ERP=rA();b.BT_CONSTRAINT_CFM=sA();b.BT_CONSTRAINT_STOP_CFM=tA();b.PHY_FLOAT=uA();b.PHY_DOUBLE=vA();b.PHY_INTEGER=wA();b.PHY_SHORT=xA();b.PHY_FIXEDPOINT88=yA();b.PHY_UCHAR=zA()}Ka?a():Ia.unshift(a)})();this.Ammo=b; + + + return Ammo.ready +} +); +})(); +if (typeof exports === 'object' && typeof module === 'object') + module.exports = Ammo; + else if (typeof define === 'function' && define['amd']) + define([], function() { return Ammo; }); + else if (typeof exports === 'object') + exports["Ammo"] = Ammo; + diff --git a/ui/viewer/vendor/three/addons/libs/ammo.wasm.wasm b/ui/viewer/vendor/three/addons/libs/ammo.wasm.wasm new file mode 100644 index 0000000..fb4eff2 Binary files /dev/null and b/ui/viewer/vendor/three/addons/libs/ammo.wasm.wasm differ diff --git a/ui/viewer/vendor/three/addons/libs/mmdparser.module.js b/ui/viewer/vendor/three/addons/libs/mmdparser.module.js new file mode 100644 index 0000000..5a587f1 --- /dev/null +++ b/ui/viewer/vendor/three/addons/libs/mmdparser.module.js @@ -0,0 +1,11530 @@ +/** + * @author Takahiro / https://github.com/takahirox + * + * Simple CharsetEncoder. + */ + +function CharsetEncoder() { +} + +/* + * Converts from Shift_JIS Uint8Array data to Unicode strings. + */ +CharsetEncoder.prototype.s2u = function(uint8Array) { + var t = this.s2uTable; + var str = ''; + var p = 0; + + while(p < uint8Array.length) { + var key = uint8Array[p++]; + + if(! ((key >= 0x00 && key <= 0x7e) || + (key >= 0xa1 && key <= 0xdf)) && + p < uint8Array.length) { + key = (key << 8) | uint8Array[p++]; + } + + if(t[key] === undefined) { + console.error('unknown char code ' + key + '.'); + return str; + } + + str += String.fromCharCode(t[key]); + } + + return str; +}; + +CharsetEncoder.prototype.s2uTable = { +0:0, +1:1, +2:2, +3:3, +4:4, +5:5, +6:6, +7:7, +8:8, +9:9, +10:10, +11:11, +12:12, +13:13, +14:14, +15:15, +16:16, +17:17, +18:18, +19:19, +20:20, +21:21, +22:22, +23:23, +24:24, +25:25, +26:26, +27:27, +28:28, +29:29, +30:30, +31:31, +32:32, +33:33, +34:34, +35:35, +36:36, +37:37, +38:38, +39:39, +40:40, +41:41, +42:42, +43:43, +44:44, +45:45, +46:46, +47:47, +48:48, +49:49, +50:50, +51:51, +52:52, +53:53, +54:54, +55:55, +56:56, +57:57, +58:58, +59:59, +60:60, +61:61, +62:62, +63:63, +64:64, +65:65, +66:66, +67:67, +68:68, +69:69, +70:70, +71:71, +72:72, +73:73, +74:74, +75:75, +76:76, +77:77, +78:78, +79:79, +80:80, +81:81, +82:82, +83:83, +84:84, +85:85, +86:86, +87:87, +88:88, +89:89, +90:90, +91:91, +92:92, +93:93, +94:94, +95:95, +96:96, +97:97, +98:98, +99:99, +100:100, +101:101, +102:102, +103:103, +104:104, +105:105, +106:106, +107:107, +108:108, +109:109, +110:110, +111:111, +112:112, +113:113, +114:114, +115:115, +116:116, +117:117, +118:118, +119:119, +120:120, +121:121, +122:122, +123:123, +124:124, +125:125, +126:126, +161:65377, +162:65378, +163:65379, +164:65380, +165:65381, +166:65382, +167:65383, +168:65384, +169:65385, +170:65386, +171:65387, +172:65388, +173:65389, +174:65390, +175:65391, +176:65392, +177:65393, +178:65394, +179:65395, +180:65396, +181:65397, +182:65398, +183:65399, +184:65400, +185:65401, +186:65402, +187:65403, +188:65404, +189:65405, +190:65406, +191:65407, +192:65408, +193:65409, +194:65410, +195:65411, +196:65412, +197:65413, +198:65414, +199:65415, +200:65416, +201:65417, +202:65418, +203:65419, +204:65420, +205:65421, +206:65422, +207:65423, +208:65424, +209:65425, +210:65426, +211:65427, +212:65428, +213:65429, +214:65430, +215:65431, +216:65432, +217:65433, +218:65434, +219:65435, +220:65436, +221:65437, +222:65438, +223:65439, +33088:12288, +33089:12289, +33090:12290, +33091:65292, +33092:65294, +33093:12539, +33094:65306, +33095:65307, +33096:65311, +33097:65281, +33098:12443, +33099:12444, +33100:180, +33101:65344, +33102:168, +33103:65342, +33104:65507, +33105:65343, +33106:12541, +33107:12542, +33108:12445, +33109:12446, +33110:12291, +33111:20189, +33112:12293, +33113:12294, +33114:12295, +33115:12540, +33116:8213, +33117:8208, +33118:65295, +33119:65340, +33120:65374, +33121:8741, +33122:65372, +33123:8230, +33124:8229, +33125:8216, +33126:8217, +33127:8220, +33128:8221, +33129:65288, +33130:65289, +33131:12308, +33132:12309, +33133:65339, +33134:65341, +33135:65371, +33136:65373, +33137:12296, +33138:12297, +33139:12298, +33140:12299, +33141:12300, +33142:12301, +33143:12302, +33144:12303, +33145:12304, +33146:12305, +33147:65291, +33148:65293, +33149:177, +33150:215, +33152:247, +33153:65309, +33154:8800, +33155:65308, +33156:65310, +33157:8806, +33158:8807, +33159:8734, +33160:8756, +33161:9794, +33162:9792, +33163:176, +33164:8242, +33165:8243, +33166:8451, +33167:65509, +33168:65284, +33169:65504, +33170:65505, +33171:65285, +33172:65283, +33173:65286, +33174:65290, +33175:65312, +33176:167, +33177:9734, +33178:9733, +33179:9675, +33180:9679, +33181:9678, +33182:9671, +33183:9670, +33184:9633, +33185:9632, +33186:9651, +33187:9650, +33188:9661, +33189:9660, +33190:8251, +33191:12306, +33192:8594, +33193:8592, +33194:8593, +33195:8595, +33196:12307, +33208:8712, +33209:8715, +33210:8838, +33211:8839, +33212:8834, +33213:8835, +33214:8746, +33215:8745, +33224:8743, +33225:8744, +33226:65506, +33227:8658, +33228:8660, +33229:8704, +33230:8707, +33242:8736, +33243:8869, +33244:8978, +33245:8706, +33246:8711, +33247:8801, +33248:8786, +33249:8810, +33250:8811, +33251:8730, +33252:8765, +33253:8733, +33254:8757, +33255:8747, +33256:8748, +33264:8491, +33265:8240, +33266:9839, +33267:9837, +33268:9834, +33269:8224, +33270:8225, +33271:182, +33276:9711, +33359:65296, +33360:65297, +33361:65298, +33362:65299, +33363:65300, +33364:65301, +33365:65302, +33366:65303, +33367:65304, +33368:65305, +33376:65313, +33377:65314, +33378:65315, +33379:65316, +33380:65317, +33381:65318, +33382:65319, +33383:65320, +33384:65321, +33385:65322, +33386:65323, +33387:65324, +33388:65325, +33389:65326, +33390:65327, +33391:65328, +33392:65329, +33393:65330, +33394:65331, +33395:65332, +33396:65333, +33397:65334, +33398:65335, +33399:65336, +33400:65337, +33401:65338, +33409:65345, +33410:65346, +33411:65347, +33412:65348, +33413:65349, +33414:65350, +33415:65351, +33416:65352, +33417:65353, +33418:65354, +33419:65355, +33420:65356, +33421:65357, +33422:65358, +33423:65359, +33424:65360, +33425:65361, +33426:65362, +33427:65363, +33428:65364, +33429:65365, +33430:65366, +33431:65367, +33432:65368, +33433:65369, +33434:65370, +33439:12353, +33440:12354, +33441:12355, +33442:12356, +33443:12357, +33444:12358, +33445:12359, +33446:12360, +33447:12361, +33448:12362, +33449:12363, +33450:12364, +33451:12365, +33452:12366, +33453:12367, +33454:12368, +33455:12369, +33456:12370, +33457:12371, +33458:12372, +33459:12373, +33460:12374, +33461:12375, +33462:12376, +33463:12377, +33464:12378, +33465:12379, +33466:12380, +33467:12381, +33468:12382, +33469:12383, +33470:12384, +33471:12385, +33472:12386, +33473:12387, +33474:12388, +33475:12389, +33476:12390, +33477:12391, +33478:12392, +33479:12393, +33480:12394, +33481:12395, +33482:12396, +33483:12397, +33484:12398, +33485:12399, +33486:12400, +33487:12401, +33488:12402, +33489:12403, +33490:12404, +33491:12405, +33492:12406, +33493:12407, +33494:12408, +33495:12409, +33496:12410, +33497:12411, +33498:12412, +33499:12413, +33500:12414, +33501:12415, +33502:12416, +33503:12417, +33504:12418, +33505:12419, +33506:12420, +33507:12421, +33508:12422, +33509:12423, +33510:12424, +33511:12425, +33512:12426, +33513:12427, +33514:12428, +33515:12429, +33516:12430, +33517:12431, +33518:12432, +33519:12433, +33520:12434, +33521:12435, +33600:12449, +33601:12450, +33602:12451, +33603:12452, +33604:12453, +33605:12454, +33606:12455, +33607:12456, +33608:12457, +33609:12458, +33610:12459, +33611:12460, +33612:12461, +33613:12462, +33614:12463, +33615:12464, +33616:12465, +33617:12466, +33618:12467, +33619:12468, +33620:12469, +33621:12470, +33622:12471, +33623:12472, +33624:12473, +33625:12474, +33626:12475, +33627:12476, +33628:12477, +33629:12478, +33630:12479, +33631:12480, +33632:12481, +33633:12482, +33634:12483, +33635:12484, +33636:12485, +33637:12486, +33638:12487, +33639:12488, +33640:12489, +33641:12490, +33642:12491, +33643:12492, +33644:12493, +33645:12494, +33646:12495, +33647:12496, +33648:12497, +33649:12498, +33650:12499, +33651:12500, +33652:12501, +33653:12502, +33654:12503, +33655:12504, +33656:12505, +33657:12506, +33658:12507, +33659:12508, +33660:12509, +33661:12510, +33662:12511, +33664:12512, +33665:12513, +33666:12514, +33667:12515, +33668:12516, +33669:12517, +33670:12518, +33671:12519, +33672:12520, +33673:12521, +33674:12522, +33675:12523, +33676:12524, +33677:12525, +33678:12526, +33679:12527, +33680:12528, +33681:12529, +33682:12530, +33683:12531, +33684:12532, +33685:12533, +33686:12534, +33695:913, +33696:914, +33697:915, +33698:916, +33699:917, +33700:918, +33701:919, +33702:920, +33703:921, +33704:922, +33705:923, +33706:924, +33707:925, +33708:926, +33709:927, +33710:928, +33711:929, +33712:931, +33713:932, +33714:933, +33715:934, +33716:935, +33717:936, +33718:937, +33727:945, +33728:946, +33729:947, +33730:948, +33731:949, +33732:950, +33733:951, +33734:952, +33735:953, +33736:954, +33737:955, +33738:956, +33739:957, +33740:958, +33741:959, +33742:960, +33743:961, +33744:963, +33745:964, +33746:965, +33747:966, +33748:967, +33749:968, +33750:969, +33856:1040, +33857:1041, +33858:1042, +33859:1043, +33860:1044, +33861:1045, +33862:1025, +33863:1046, +33864:1047, +33865:1048, +33866:1049, +33867:1050, +33868:1051, +33869:1052, +33870:1053, +33871:1054, +33872:1055, +33873:1056, +33874:1057, +33875:1058, +33876:1059, +33877:1060, +33878:1061, +33879:1062, +33880:1063, +33881:1064, +33882:1065, +33883:1066, +33884:1067, +33885:1068, +33886:1069, +33887:1070, +33888:1071, +33904:1072, +33905:1073, +33906:1074, +33907:1075, +33908:1076, +33909:1077, +33910:1105, +33911:1078, +33912:1079, +33913:1080, +33914:1081, +33915:1082, +33916:1083, +33917:1084, +33918:1085, +33920:1086, +33921:1087, +33922:1088, +33923:1089, +33924:1090, +33925:1091, +33926:1092, +33927:1093, +33928:1094, +33929:1095, +33930:1096, +33931:1097, +33932:1098, +33933:1099, +33934:1100, +33935:1101, +33936:1102, +33937:1103, +33951:9472, +33952:9474, +33953:9484, +33954:9488, +33955:9496, +33956:9492, +33957:9500, +33958:9516, +33959:9508, +33960:9524, +33961:9532, +33962:9473, +33963:9475, +33964:9487, +33965:9491, +33966:9499, +33967:9495, +33968:9507, +33969:9523, +33970:9515, +33971:9531, +33972:9547, +33973:9504, +33974:9519, +33975:9512, +33976:9527, +33977:9535, +33978:9501, +33979:9520, +33980:9509, +33981:9528, +33982:9538, +34624:9312, +34625:9313, +34626:9314, +34627:9315, +34628:9316, +34629:9317, +34630:9318, +34631:9319, +34632:9320, +34633:9321, +34634:9322, +34635:9323, +34636:9324, +34637:9325, +34638:9326, +34639:9327, +34640:9328, +34641:9329, +34642:9330, +34643:9331, +34644:8544, +34645:8545, +34646:8546, +34647:8547, +34648:8548, +34649:8549, +34650:8550, +34651:8551, +34652:8552, +34653:8553, +34655:13129, +34656:13076, +34657:13090, +34658:13133, +34659:13080, +34660:13095, +34661:13059, +34662:13110, +34663:13137, +34664:13143, +34665:13069, +34666:13094, +34667:13091, +34668:13099, +34669:13130, +34670:13115, +34671:13212, +34672:13213, +34673:13214, +34674:13198, +34675:13199, +34676:13252, +34677:13217, +34686:13179, +34688:12317, +34689:12319, +34690:8470, +34691:13261, +34692:8481, +34693:12964, +34694:12965, +34695:12966, +34696:12967, +34697:12968, +34698:12849, +34699:12850, +34700:12857, +34701:13182, +34702:13181, +34703:13180, +34704:8786, +34705:8801, +34706:8747, +34707:8750, +34708:8721, +34709:8730, +34710:8869, +34711:8736, +34712:8735, +34713:8895, +34714:8757, +34715:8745, +34716:8746, +34975:20124, +34976:21782, +34977:23043, +34978:38463, +34979:21696, +34980:24859, +34981:25384, +34982:23030, +34983:36898, +34984:33909, +34985:33564, +34986:31312, +34987:24746, +34988:25569, +34989:28197, +34990:26093, +34991:33894, +34992:33446, +34993:39925, +34994:26771, +34995:22311, +34996:26017, +34997:25201, +34998:23451, +34999:22992, +35000:34427, +35001:39156, +35002:32098, +35003:32190, +35004:39822, +35005:25110, +35006:31903, +35007:34999, +35008:23433, +35009:24245, +35010:25353, +35011:26263, +35012:26696, +35013:38343, +35014:38797, +35015:26447, +35016:20197, +35017:20234, +35018:20301, +35019:20381, +35020:20553, +35021:22258, +35022:22839, +35023:22996, +35024:23041, +35025:23561, +35026:24799, +35027:24847, +35028:24944, +35029:26131, +35030:26885, +35031:28858, +35032:30031, +35033:30064, +35034:31227, +35035:32173, +35036:32239, +35037:32963, +35038:33806, +35039:34915, +35040:35586, +35041:36949, +35042:36986, +35043:21307, +35044:20117, +35045:20133, +35046:22495, +35047:32946, +35048:37057, +35049:30959, +35050:19968, +35051:22769, +35052:28322, +35053:36920, +35054:31282, +35055:33576, +35056:33419, +35057:39983, +35058:20801, +35059:21360, +35060:21693, +35061:21729, +35062:22240, +35063:23035, +35064:24341, +35065:39154, +35066:28139, +35067:32996, +35068:34093, +35136:38498, +35137:38512, +35138:38560, +35139:38907, +35140:21515, +35141:21491, +35142:23431, +35143:28879, +35144:32701, +35145:36802, +35146:38632, +35147:21359, +35148:40284, +35149:31418, +35150:19985, +35151:30867, +35152:33276, +35153:28198, +35154:22040, +35155:21764, +35156:27421, +35157:34074, +35158:39995, +35159:23013, +35160:21417, +35161:28006, +35162:29916, +35163:38287, +35164:22082, +35165:20113, +35166:36939, +35167:38642, +35168:33615, +35169:39180, +35170:21473, +35171:21942, +35172:23344, +35173:24433, +35174:26144, +35175:26355, +35176:26628, +35177:27704, +35178:27891, +35179:27945, +35180:29787, +35181:30408, +35182:31310, +35183:38964, +35184:33521, +35185:34907, +35186:35424, +35187:37613, +35188:28082, +35189:30123, +35190:30410, +35191:39365, +35192:24742, +35193:35585, +35194:36234, +35195:38322, +35196:27022, +35197:21421, +35198:20870, +35200:22290, +35201:22576, +35202:22852, +35203:23476, +35204:24310, +35205:24616, +35206:25513, +35207:25588, +35208:27839, +35209:28436, +35210:28814, +35211:28948, +35212:29017, +35213:29141, +35214:29503, +35215:32257, +35216:33398, +35217:33489, +35218:34199, +35219:36960, +35220:37467, +35221:40219, +35222:22633, +35223:26044, +35224:27738, +35225:29989, +35226:20985, +35227:22830, +35228:22885, +35229:24448, +35230:24540, +35231:25276, +35232:26106, +35233:27178, +35234:27431, +35235:27572, +35236:29579, +35237:32705, +35238:35158, +35239:40236, +35240:40206, +35241:40644, +35242:23713, +35243:27798, +35244:33659, +35245:20740, +35246:23627, +35247:25014, +35248:33222, +35249:26742, +35250:29281, +35251:20057, +35252:20474, +35253:21368, +35254:24681, +35255:28201, +35256:31311, +35257:38899, +35258:19979, +35259:21270, +35260:20206, +35261:20309, +35262:20285, +35263:20385, +35264:20339, +35265:21152, +35266:21487, +35267:22025, +35268:22799, +35269:23233, +35270:23478, +35271:23521, +35272:31185, +35273:26247, +35274:26524, +35275:26550, +35276:27468, +35277:27827, +35278:28779, +35279:29634, +35280:31117, +35281:31166, +35282:31292, +35283:31623, +35284:33457, +35285:33499, +35286:33540, +35287:33655, +35288:33775, +35289:33747, +35290:34662, +35291:35506, +35292:22057, +35293:36008, +35294:36838, +35295:36942, +35296:38686, +35297:34442, +35298:20420, +35299:23784, +35300:25105, +35301:29273, +35302:30011, +35303:33253, +35304:33469, +35305:34558, +35306:36032, +35307:38597, +35308:39187, +35309:39381, +35310:20171, +35311:20250, +35312:35299, +35313:22238, +35314:22602, +35315:22730, +35316:24315, +35317:24555, +35318:24618, +35319:24724, +35320:24674, +35321:25040, +35322:25106, +35323:25296, +35324:25913, +35392:39745, +35393:26214, +35394:26800, +35395:28023, +35396:28784, +35397:30028, +35398:30342, +35399:32117, +35400:33445, +35401:34809, +35402:38283, +35403:38542, +35404:35997, +35405:20977, +35406:21182, +35407:22806, +35408:21683, +35409:23475, +35410:23830, +35411:24936, +35412:27010, +35413:28079, +35414:30861, +35415:33995, +35416:34903, +35417:35442, +35418:37799, +35419:39608, +35420:28012, +35421:39336, +35422:34521, +35423:22435, +35424:26623, +35425:34510, +35426:37390, +35427:21123, +35428:22151, +35429:21508, +35430:24275, +35431:25313, +35432:25785, +35433:26684, +35434:26680, +35435:27579, +35436:29554, +35437:30906, +35438:31339, +35439:35226, +35440:35282, +35441:36203, +35442:36611, +35443:37101, +35444:38307, +35445:38548, +35446:38761, +35447:23398, +35448:23731, +35449:27005, +35450:38989, +35451:38990, +35452:25499, +35453:31520, +35454:27179, +35456:27263, +35457:26806, +35458:39949, +35459:28511, +35460:21106, +35461:21917, +35462:24688, +35463:25324, +35464:27963, +35465:28167, +35466:28369, +35467:33883, +35468:35088, +35469:36676, +35470:19988, +35471:39993, +35472:21494, +35473:26907, +35474:27194, +35475:38788, +35476:26666, +35477:20828, +35478:31427, +35479:33970, +35480:37340, +35481:37772, +35482:22107, +35483:40232, +35484:26658, +35485:33541, +35486:33841, +35487:31909, +35488:21000, +35489:33477, +35490:29926, +35491:20094, +35492:20355, +35493:20896, +35494:23506, +35495:21002, +35496:21208, +35497:21223, +35498:24059, +35499:21914, +35500:22570, +35501:23014, +35502:23436, +35503:23448, +35504:23515, +35505:24178, +35506:24185, +35507:24739, +35508:24863, +35509:24931, +35510:25022, +35511:25563, +35512:25954, +35513:26577, +35514:26707, +35515:26874, +35516:27454, +35517:27475, +35518:27735, +35519:28450, +35520:28567, +35521:28485, +35522:29872, +35523:29976, +35524:30435, +35525:30475, +35526:31487, +35527:31649, +35528:31777, +35529:32233, +35530:32566, +35531:32752, +35532:32925, +35533:33382, +35534:33694, +35535:35251, +35536:35532, +35537:36011, +35538:36996, +35539:37969, +35540:38291, +35541:38289, +35542:38306, +35543:38501, +35544:38867, +35545:39208, +35546:33304, +35547:20024, +35548:21547, +35549:23736, +35550:24012, +35551:29609, +35552:30284, +35553:30524, +35554:23721, +35555:32747, +35556:36107, +35557:38593, +35558:38929, +35559:38996, +35560:39000, +35561:20225, +35562:20238, +35563:21361, +35564:21916, +35565:22120, +35566:22522, +35567:22855, +35568:23305, +35569:23492, +35570:23696, +35571:24076, +35572:24190, +35573:24524, +35574:25582, +35575:26426, +35576:26071, +35577:26082, +35578:26399, +35579:26827, +35580:26820, +35648:27231, +35649:24112, +35650:27589, +35651:27671, +35652:27773, +35653:30079, +35654:31048, +35655:23395, +35656:31232, +35657:32000, +35658:24509, +35659:35215, +35660:35352, +35661:36020, +35662:36215, +35663:36556, +35664:36637, +35665:39138, +35666:39438, +35667:39740, +35668:20096, +35669:20605, +35670:20736, +35671:22931, +35672:23452, +35673:25135, +35674:25216, +35675:25836, +35676:27450, +35677:29344, +35678:30097, +35679:31047, +35680:32681, +35681:34811, +35682:35516, +35683:35696, +35684:25516, +35685:33738, +35686:38816, +35687:21513, +35688:21507, +35689:21931, +35690:26708, +35691:27224, +35692:35440, +35693:30759, +35694:26485, +35695:40653, +35696:21364, +35697:23458, +35698:33050, +35699:34384, +35700:36870, +35701:19992, +35702:20037, +35703:20167, +35704:20241, +35705:21450, +35706:21560, +35707:23470, +35708:24339, +35709:24613, +35710:25937, +35712:26429, +35713:27714, +35714:27762, +35715:27875, +35716:28792, +35717:29699, +35718:31350, +35719:31406, +35720:31496, +35721:32026, +35722:31998, +35723:32102, +35724:26087, +35725:29275, +35726:21435, +35727:23621, +35728:24040, +35729:25298, +35730:25312, +35731:25369, +35732:28192, +35733:34394, +35734:35377, +35735:36317, +35736:37624, +35737:28417, +35738:31142, +35739:39770, +35740:20136, +35741:20139, +35742:20140, +35743:20379, +35744:20384, +35745:20689, +35746:20807, +35747:31478, +35748:20849, +35749:20982, +35750:21332, +35751:21281, +35752:21375, +35753:21483, +35754:21932, +35755:22659, +35756:23777, +35757:24375, +35758:24394, +35759:24623, +35760:24656, +35761:24685, +35762:25375, +35763:25945, +35764:27211, +35765:27841, +35766:29378, +35767:29421, +35768:30703, +35769:33016, +35770:33029, +35771:33288, +35772:34126, +35773:37111, +35774:37857, +35775:38911, +35776:39255, +35777:39514, +35778:20208, +35779:20957, +35780:23597, +35781:26241, +35782:26989, +35783:23616, +35784:26354, +35785:26997, +35786:29577, +35787:26704, +35788:31873, +35789:20677, +35790:21220, +35791:22343, +35792:24062, +35793:37670, +35794:26020, +35795:27427, +35796:27453, +35797:29748, +35798:31105, +35799:31165, +35800:31563, +35801:32202, +35802:33465, +35803:33740, +35804:34943, +35805:35167, +35806:35641, +35807:36817, +35808:37329, +35809:21535, +35810:37504, +35811:20061, +35812:20534, +35813:21477, +35814:21306, +35815:29399, +35816:29590, +35817:30697, +35818:33510, +35819:36527, +35820:39366, +35821:39368, +35822:39378, +35823:20855, +35824:24858, +35825:34398, +35826:21936, +35827:31354, +35828:20598, +35829:23507, +35830:36935, +35831:38533, +35832:20018, +35833:27355, +35834:37351, +35835:23633, +35836:23624, +35904:25496, +35905:31391, +35906:27795, +35907:38772, +35908:36705, +35909:31402, +35910:29066, +35911:38536, +35912:31874, +35913:26647, +35914:32368, +35915:26705, +35916:37740, +35917:21234, +35918:21531, +35919:34219, +35920:35347, +35921:32676, +35922:36557, +35923:37089, +35924:21350, +35925:34952, +35926:31041, +35927:20418, +35928:20670, +35929:21009, +35930:20804, +35931:21843, +35932:22317, +35933:29674, +35934:22411, +35935:22865, +35936:24418, +35937:24452, +35938:24693, +35939:24950, +35940:24935, +35941:25001, +35942:25522, +35943:25658, +35944:25964, +35945:26223, +35946:26690, +35947:28179, +35948:30054, +35949:31293, +35950:31995, +35951:32076, +35952:32153, +35953:32331, +35954:32619, +35955:33550, +35956:33610, +35957:34509, +35958:35336, +35959:35427, +35960:35686, +35961:36605, +35962:38938, +35963:40335, +35964:33464, +35965:36814, +35966:39912, +35968:21127, +35969:25119, +35970:25731, +35971:28608, +35972:38553, +35973:26689, +35974:20625, +35975:27424, +35976:27770, +35977:28500, +35978:31348, +35979:32080, +35980:34880, +35981:35363, +35982:26376, +35983:20214, +35984:20537, +35985:20518, +35986:20581, +35987:20860, +35988:21048, +35989:21091, +35990:21927, +35991:22287, +35992:22533, +35993:23244, +35994:24314, +35995:25010, +35996:25080, +35997:25331, +35998:25458, +35999:26908, +36000:27177, +36001:29309, +36002:29356, +36003:29486, +36004:30740, +36005:30831, +36006:32121, +36007:30476, +36008:32937, +36009:35211, +36010:35609, +36011:36066, +36012:36562, +36013:36963, +36014:37749, +36015:38522, +36016:38997, +36017:39443, +36018:40568, +36019:20803, +36020:21407, +36021:21427, +36022:24187, +36023:24358, +36024:28187, +36025:28304, +36026:29572, +36027:29694, +36028:32067, +36029:33335, +36030:35328, +36031:35578, +36032:38480, +36033:20046, +36034:20491, +36035:21476, +36036:21628, +36037:22266, +36038:22993, +36039:23396, +36040:24049, +36041:24235, +36042:24359, +36043:25144, +36044:25925, +36045:26543, +36046:28246, +36047:29392, +36048:31946, +36049:34996, +36050:32929, +36051:32993, +36052:33776, +36053:34382, +36054:35463, +36055:36328, +36056:37431, +36057:38599, +36058:39015, +36059:40723, +36060:20116, +36061:20114, +36062:20237, +36063:21320, +36064:21577, +36065:21566, +36066:23087, +36067:24460, +36068:24481, +36069:24735, +36070:26791, +36071:27278, +36072:29786, +36073:30849, +36074:35486, +36075:35492, +36076:35703, +36077:37264, +36078:20062, +36079:39881, +36080:20132, +36081:20348, +36082:20399, +36083:20505, +36084:20502, +36085:20809, +36086:20844, +36087:21151, +36088:21177, +36089:21246, +36090:21402, +36091:21475, +36092:21521, +36160:21518, +36161:21897, +36162:22353, +36163:22434, +36164:22909, +36165:23380, +36166:23389, +36167:23439, +36168:24037, +36169:24039, +36170:24055, +36171:24184, +36172:24195, +36173:24218, +36174:24247, +36175:24344, +36176:24658, +36177:24908, +36178:25239, +36179:25304, +36180:25511, +36181:25915, +36182:26114, +36183:26179, +36184:26356, +36185:26477, +36186:26657, +36187:26775, +36188:27083, +36189:27743, +36190:27946, +36191:28009, +36192:28207, +36193:28317, +36194:30002, +36195:30343, +36196:30828, +36197:31295, +36198:31968, +36199:32005, +36200:32024, +36201:32094, +36202:32177, +36203:32789, +36204:32771, +36205:32943, +36206:32945, +36207:33108, +36208:33167, +36209:33322, +36210:33618, +36211:34892, +36212:34913, +36213:35611, +36214:36002, +36215:36092, +36216:37066, +36217:37237, +36218:37489, +36219:30783, +36220:37628, +36221:38308, +36222:38477, +36224:38917, +36225:39321, +36226:39640, +36227:40251, +36228:21083, +36229:21163, +36230:21495, +36231:21512, +36232:22741, +36233:25335, +36234:28640, +36235:35946, +36236:36703, +36237:40633, +36238:20811, +36239:21051, +36240:21578, +36241:22269, +36242:31296, +36243:37239, +36244:40288, +36245:40658, +36246:29508, +36247:28425, +36248:33136, +36249:29969, +36250:24573, +36251:24794, +36252:39592, +36253:29403, +36254:36796, +36255:27492, +36256:38915, +36257:20170, +36258:22256, +36259:22372, +36260:22718, +36261:23130, +36262:24680, +36263:25031, +36264:26127, +36265:26118, +36266:26681, +36267:26801, +36268:28151, +36269:30165, +36270:32058, +36271:33390, +36272:39746, +36273:20123, +36274:20304, +36275:21449, +36276:21766, +36277:23919, +36278:24038, +36279:24046, +36280:26619, +36281:27801, +36282:29811, +36283:30722, +36284:35408, +36285:37782, +36286:35039, +36287:22352, +36288:24231, +36289:25387, +36290:20661, +36291:20652, +36292:20877, +36293:26368, +36294:21705, +36295:22622, +36296:22971, +36297:23472, +36298:24425, +36299:25165, +36300:25505, +36301:26685, +36302:27507, +36303:28168, +36304:28797, +36305:37319, +36306:29312, +36307:30741, +36308:30758, +36309:31085, +36310:25998, +36311:32048, +36312:33756, +36313:35009, +36314:36617, +36315:38555, +36316:21092, +36317:22312, +36318:26448, +36319:32618, +36320:36001, +36321:20916, +36322:22338, +36323:38442, +36324:22586, +36325:27018, +36326:32948, +36327:21682, +36328:23822, +36329:22524, +36330:30869, +36331:40442, +36332:20316, +36333:21066, +36334:21643, +36335:25662, +36336:26152, +36337:26388, +36338:26613, +36339:31364, +36340:31574, +36341:32034, +36342:37679, +36343:26716, +36344:39853, +36345:31545, +36346:21273, +36347:20874, +36348:21047, +36416:23519, +36417:25334, +36418:25774, +36419:25830, +36420:26413, +36421:27578, +36422:34217, +36423:38609, +36424:30352, +36425:39894, +36426:25420, +36427:37638, +36428:39851, +36429:30399, +36430:26194, +36431:19977, +36432:20632, +36433:21442, +36434:23665, +36435:24808, +36436:25746, +36437:25955, +36438:26719, +36439:29158, +36440:29642, +36441:29987, +36442:31639, +36443:32386, +36444:34453, +36445:35715, +36446:36059, +36447:37240, +36448:39184, +36449:26028, +36450:26283, +36451:27531, +36452:20181, +36453:20180, +36454:20282, +36455:20351, +36456:21050, +36457:21496, +36458:21490, +36459:21987, +36460:22235, +36461:22763, +36462:22987, +36463:22985, +36464:23039, +36465:23376, +36466:23629, +36467:24066, +36468:24107, +36469:24535, +36470:24605, +36471:25351, +36472:25903, +36473:23388, +36474:26031, +36475:26045, +36476:26088, +36477:26525, +36478:27490, +36480:27515, +36481:27663, +36482:29509, +36483:31049, +36484:31169, +36485:31992, +36486:32025, +36487:32043, +36488:32930, +36489:33026, +36490:33267, +36491:35222, +36492:35422, +36493:35433, +36494:35430, +36495:35468, +36496:35566, +36497:36039, +36498:36060, +36499:38604, +36500:39164, +36501:27503, +36502:20107, +36503:20284, +36504:20365, +36505:20816, +36506:23383, +36507:23546, +36508:24904, +36509:25345, +36510:26178, +36511:27425, +36512:28363, +36513:27835, +36514:29246, +36515:29885, +36516:30164, +36517:30913, +36518:31034, +36519:32780, +36520:32819, +36521:33258, +36522:33940, +36523:36766, +36524:27728, +36525:40575, +36526:24335, +36527:35672, +36528:40235, +36529:31482, +36530:36600, +36531:23437, +36532:38635, +36533:19971, +36534:21489, +36535:22519, +36536:22833, +36537:23241, +36538:23460, +36539:24713, +36540:28287, +36541:28422, +36542:30142, +36543:36074, +36544:23455, +36545:34048, +36546:31712, +36547:20594, +36548:26612, +36549:33437, +36550:23649, +36551:34122, +36552:32286, +36553:33294, +36554:20889, +36555:23556, +36556:25448, +36557:36198, +36558:26012, +36559:29038, +36560:31038, +36561:32023, +36562:32773, +36563:35613, +36564:36554, +36565:36974, +36566:34503, +36567:37034, +36568:20511, +36569:21242, +36570:23610, +36571:26451, +36572:28796, +36573:29237, +36574:37196, +36575:37320, +36576:37675, +36577:33509, +36578:23490, +36579:24369, +36580:24825, +36581:20027, +36582:21462, +36583:23432, +36584:25163, +36585:26417, +36586:27530, +36587:29417, +36588:29664, +36589:31278, +36590:33131, +36591:36259, +36592:37202, +36593:39318, +36594:20754, +36595:21463, +36596:21610, +36597:23551, +36598:25480, +36599:27193, +36600:32172, +36601:38656, +36602:22234, +36603:21454, +36604:21608, +36672:23447, +36673:23601, +36674:24030, +36675:20462, +36676:24833, +36677:25342, +36678:27954, +36679:31168, +36680:31179, +36681:32066, +36682:32333, +36683:32722, +36684:33261, +36685:33311, +36686:33936, +36687:34886, +36688:35186, +36689:35728, +36690:36468, +36691:36655, +36692:36913, +36693:37195, +36694:37228, +36695:38598, +36696:37276, +36697:20160, +36698:20303, +36699:20805, +36700:21313, +36701:24467, +36702:25102, +36703:26580, +36704:27713, +36705:28171, +36706:29539, +36707:32294, +36708:37325, +36709:37507, +36710:21460, +36711:22809, +36712:23487, +36713:28113, +36714:31069, +36715:32302, +36716:31899, +36717:22654, +36718:29087, +36719:20986, +36720:34899, +36721:36848, +36722:20426, +36723:23803, +36724:26149, +36725:30636, +36726:31459, +36727:33308, +36728:39423, +36729:20934, +36730:24490, +36731:26092, +36732:26991, +36733:27529, +36734:28147, +36736:28310, +36737:28516, +36738:30462, +36739:32020, +36740:24033, +36741:36981, +36742:37255, +36743:38918, +36744:20966, +36745:21021, +36746:25152, +36747:26257, +36748:26329, +36749:28186, +36750:24246, +36751:32210, +36752:32626, +36753:26360, +36754:34223, +36755:34295, +36756:35576, +36757:21161, +36758:21465, +36759:22899, +36760:24207, +36761:24464, +36762:24661, +36763:37604, +36764:38500, +36765:20663, +36766:20767, +36767:21213, +36768:21280, +36769:21319, +36770:21484, +36771:21736, +36772:21830, +36773:21809, +36774:22039, +36775:22888, +36776:22974, +36777:23100, +36778:23477, +36779:23558, +36780:23567, +36781:23569, +36782:23578, +36783:24196, +36784:24202, +36785:24288, +36786:24432, +36787:25215, +36788:25220, +36789:25307, +36790:25484, +36791:25463, +36792:26119, +36793:26124, +36794:26157, +36795:26230, +36796:26494, +36797:26786, +36798:27167, +36799:27189, +36800:27836, +36801:28040, +36802:28169, +36803:28248, +36804:28988, +36805:28966, +36806:29031, +36807:30151, +36808:30465, +36809:30813, +36810:30977, +36811:31077, +36812:31216, +36813:31456, +36814:31505, +36815:31911, +36816:32057, +36817:32918, +36818:33750, +36819:33931, +36820:34121, +36821:34909, +36822:35059, +36823:35359, +36824:35388, +36825:35412, +36826:35443, +36827:35937, +36828:36062, +36829:37284, +36830:37478, +36831:37758, +36832:37912, +36833:38556, +36834:38808, +36835:19978, +36836:19976, +36837:19998, +36838:20055, +36839:20887, +36840:21104, +36841:22478, +36842:22580, +36843:22732, +36844:23330, +36845:24120, +36846:24773, +36847:25854, +36848:26465, +36849:26454, +36850:27972, +36851:29366, +36852:30067, +36853:31331, +36854:33976, +36855:35698, +36856:37304, +36857:37664, +36858:22065, +36859:22516, +36860:39166, +36928:25325, +36929:26893, +36930:27542, +36931:29165, +36932:32340, +36933:32887, +36934:33394, +36935:35302, +36936:39135, +36937:34645, +36938:36785, +36939:23611, +36940:20280, +36941:20449, +36942:20405, +36943:21767, +36944:23072, +36945:23517, +36946:23529, +36947:24515, +36948:24910, +36949:25391, +36950:26032, +36951:26187, +36952:26862, +36953:27035, +36954:28024, +36955:28145, +36956:30003, +36957:30137, +36958:30495, +36959:31070, +36960:31206, +36961:32051, +36962:33251, +36963:33455, +36964:34218, +36965:35242, +36966:35386, +36967:36523, +36968:36763, +36969:36914, +36970:37341, +36971:38663, +36972:20154, +36973:20161, +36974:20995, +36975:22645, +36976:22764, +36977:23563, +36978:29978, +36979:23613, +36980:33102, +36981:35338, +36982:36805, +36983:38499, +36984:38765, +36985:31525, +36986:35535, +36987:38920, +36988:37218, +36989:22259, +36990:21416, +36992:36887, +36993:21561, +36994:22402, +36995:24101, +36996:25512, +36997:27700, +36998:28810, +36999:30561, +37000:31883, +37001:32736, +37002:34928, +37003:36930, +37004:37204, +37005:37648, +37006:37656, +37007:38543, +37008:29790, +37009:39620, +37010:23815, +37011:23913, +37012:25968, +37013:26530, +37014:36264, +37015:38619, +37016:25454, +37017:26441, +37018:26905, +37019:33733, +37020:38935, +37021:38592, +37022:35070, +37023:28548, +37024:25722, +37025:23544, +37026:19990, +37027:28716, +37028:30045, +37029:26159, +37030:20932, +37031:21046, +37032:21218, +37033:22995, +37034:24449, +37035:24615, +37036:25104, +37037:25919, +37038:25972, +37039:26143, +37040:26228, +37041:26866, +37042:26646, +37043:27491, +37044:28165, +37045:29298, +37046:29983, +37047:30427, +37048:31934, +37049:32854, +37050:22768, +37051:35069, +37052:35199, +37053:35488, +37054:35475, +37055:35531, +37056:36893, +37057:37266, +37058:38738, +37059:38745, +37060:25993, +37061:31246, +37062:33030, +37063:38587, +37064:24109, +37065:24796, +37066:25114, +37067:26021, +37068:26132, +37069:26512, +37070:30707, +37071:31309, +37072:31821, +37073:32318, +37074:33034, +37075:36012, +37076:36196, +37077:36321, +37078:36447, +37079:30889, +37080:20999, +37081:25305, +37082:25509, +37083:25666, +37084:25240, +37085:35373, +37086:31363, +37087:31680, +37088:35500, +37089:38634, +37090:32118, +37091:33292, +37092:34633, +37093:20185, +37094:20808, +37095:21315, +37096:21344, +37097:23459, +37098:23554, +37099:23574, +37100:24029, +37101:25126, +37102:25159, +37103:25776, +37104:26643, +37105:26676, +37106:27849, +37107:27973, +37108:27927, +37109:26579, +37110:28508, +37111:29006, +37112:29053, +37113:26059, +37114:31359, +37115:31661, +37116:32218, +37184:32330, +37185:32680, +37186:33146, +37187:33307, +37188:33337, +37189:34214, +37190:35438, +37191:36046, +37192:36341, +37193:36984, +37194:36983, +37195:37549, +37196:37521, +37197:38275, +37198:39854, +37199:21069, +37200:21892, +37201:28472, +37202:28982, +37203:20840, +37204:31109, +37205:32341, +37206:33203, +37207:31950, +37208:22092, +37209:22609, +37210:23720, +37211:25514, +37212:26366, +37213:26365, +37214:26970, +37215:29401, +37216:30095, +37217:30094, +37218:30990, +37219:31062, +37220:31199, +37221:31895, +37222:32032, +37223:32068, +37224:34311, +37225:35380, +37226:38459, +37227:36961, +37228:40736, +37229:20711, +37230:21109, +37231:21452, +37232:21474, +37233:20489, +37234:21930, +37235:22766, +37236:22863, +37237:29245, +37238:23435, +37239:23652, +37240:21277, +37241:24803, +37242:24819, +37243:25436, +37244:25475, +37245:25407, +37246:25531, +37248:25805, +37249:26089, +37250:26361, +37251:24035, +37252:27085, +37253:27133, +37254:28437, +37255:29157, +37256:20105, +37257:30185, +37258:30456, +37259:31379, +37260:31967, +37261:32207, +37262:32156, +37263:32865, +37264:33609, +37265:33624, +37266:33900, +37267:33980, +37268:34299, +37269:35013, +37270:36208, +37271:36865, +37272:36973, +37273:37783, +37274:38684, +37275:39442, +37276:20687, +37277:22679, +37278:24974, +37279:33235, +37280:34101, +37281:36104, +37282:36896, +37283:20419, +37284:20596, +37285:21063, +37286:21363, +37287:24687, +37288:25417, +37289:26463, +37290:28204, +37291:36275, +37292:36895, +37293:20439, +37294:23646, +37295:36042, +37296:26063, +37297:32154, +37298:21330, +37299:34966, +37300:20854, +37301:25539, +37302:23384, +37303:23403, +37304:23562, +37305:25613, +37306:26449, +37307:36956, +37308:20182, +37309:22810, +37310:22826, +37311:27760, +37312:35409, +37313:21822, +37314:22549, +37315:22949, +37316:24816, +37317:25171, +37318:26561, +37319:33333, +37320:26965, +37321:38464, +37322:39364, +37323:39464, +37324:20307, +37325:22534, +37326:23550, +37327:32784, +37328:23729, +37329:24111, +37330:24453, +37331:24608, +37332:24907, +37333:25140, +37334:26367, +37335:27888, +37336:28382, +37337:32974, +37338:33151, +37339:33492, +37340:34955, +37341:36024, +37342:36864, +37343:36910, +37344:38538, +37345:40667, +37346:39899, +37347:20195, +37348:21488, +37349:22823, +37350:31532, +37351:37261, +37352:38988, +37353:40441, +37354:28381, +37355:28711, +37356:21331, +37357:21828, +37358:23429, +37359:25176, +37360:25246, +37361:25299, +37362:27810, +37363:28655, +37364:29730, +37365:35351, +37366:37944, +37367:28609, +37368:35582, +37369:33592, +37370:20967, +37371:34552, +37372:21482, +37440:21481, +37441:20294, +37442:36948, +37443:36784, +37444:22890, +37445:33073, +37446:24061, +37447:31466, +37448:36799, +37449:26842, +37450:35895, +37451:29432, +37452:40008, +37453:27197, +37454:35504, +37455:20025, +37456:21336, +37457:22022, +37458:22374, +37459:25285, +37460:25506, +37461:26086, +37462:27470, +37463:28129, +37464:28251, +37465:28845, +37466:30701, +37467:31471, +37468:31658, +37469:32187, +37470:32829, +37471:32966, +37472:34507, +37473:35477, +37474:37723, +37475:22243, +37476:22727, +37477:24382, +37478:26029, +37479:26262, +37480:27264, +37481:27573, +37482:30007, +37483:35527, +37484:20516, +37485:30693, +37486:22320, +37487:24347, +37488:24677, +37489:26234, +37490:27744, +37491:30196, +37492:31258, +37493:32622, +37494:33268, +37495:34584, +37496:36933, +37497:39347, +37498:31689, +37499:30044, +37500:31481, +37501:31569, +37502:33988, +37504:36880, +37505:31209, +37506:31378, +37507:33590, +37508:23265, +37509:30528, +37510:20013, +37511:20210, +37512:23449, +37513:24544, +37514:25277, +37515:26172, +37516:26609, +37517:27880, +37518:34411, +37519:34935, +37520:35387, +37521:37198, +37522:37619, +37523:39376, +37524:27159, +37525:28710, +37526:29482, +37527:33511, +37528:33879, +37529:36015, +37530:19969, +37531:20806, +37532:20939, +37533:21899, +37534:23541, +37535:24086, +37536:24115, +37537:24193, +37538:24340, +37539:24373, +37540:24427, +37541:24500, +37542:25074, +37543:25361, +37544:26274, +37545:26397, +37546:28526, +37547:29266, +37548:30010, +37549:30522, +37550:32884, +37551:33081, +37552:33144, +37553:34678, +37554:35519, +37555:35548, +37556:36229, +37557:36339, +37558:37530, +37559:38263, +37560:38914, +37561:40165, +37562:21189, +37563:25431, +37564:30452, +37565:26389, +37566:27784, +37567:29645, +37568:36035, +37569:37806, +37570:38515, +37571:27941, +37572:22684, +37573:26894, +37574:27084, +37575:36861, +37576:37786, +37577:30171, +37578:36890, +37579:22618, +37580:26626, +37581:25524, +37582:27131, +37583:20291, +37584:28460, +37585:26584, +37586:36795, +37587:34086, +37588:32180, +37589:37716, +37590:26943, +37591:28528, +37592:22378, +37593:22775, +37594:23340, +37595:32044, +37596:29226, +37597:21514, +37598:37347, +37599:40372, +37600:20141, +37601:20302, +37602:20572, +37603:20597, +37604:21059, +37605:35998, +37606:21576, +37607:22564, +37608:23450, +37609:24093, +37610:24213, +37611:24237, +37612:24311, +37613:24351, +37614:24716, +37615:25269, +37616:25402, +37617:25552, +37618:26799, +37619:27712, +37620:30855, +37621:31118, +37622:31243, +37623:32224, +37624:33351, +37625:35330, +37626:35558, +37627:36420, +37628:36883, +37696:37048, +37697:37165, +37698:37336, +37699:40718, +37700:27877, +37701:25688, +37702:25826, +37703:25973, +37704:28404, +37705:30340, +37706:31515, +37707:36969, +37708:37841, +37709:28346, +37710:21746, +37711:24505, +37712:25764, +37713:36685, +37714:36845, +37715:37444, +37716:20856, +37717:22635, +37718:22825, +37719:23637, +37720:24215, +37721:28155, +37722:32399, +37723:29980, +37724:36028, +37725:36578, +37726:39003, +37727:28857, +37728:20253, +37729:27583, +37730:28593, +37731:30000, +37732:38651, +37733:20814, +37734:21520, +37735:22581, +37736:22615, +37737:22956, +37738:23648, +37739:24466, +37740:26007, +37741:26460, +37742:28193, +37743:30331, +37744:33759, +37745:36077, +37746:36884, +37747:37117, +37748:37709, +37749:30757, +37750:30778, +37751:21162, +37752:24230, +37753:22303, +37754:22900, +37755:24594, +37756:20498, +37757:20826, +37758:20908, +37760:20941, +37761:20992, +37762:21776, +37763:22612, +37764:22616, +37765:22871, +37766:23445, +37767:23798, +37768:23947, +37769:24764, +37770:25237, +37771:25645, +37772:26481, +37773:26691, +37774:26812, +37775:26847, +37776:30423, +37777:28120, +37778:28271, +37779:28059, +37780:28783, +37781:29128, +37782:24403, +37783:30168, +37784:31095, +37785:31561, +37786:31572, +37787:31570, +37788:31958, +37789:32113, +37790:21040, +37791:33891, +37792:34153, +37793:34276, +37794:35342, +37795:35588, +37796:35910, +37797:36367, +37798:36867, +37799:36879, +37800:37913, +37801:38518, +37802:38957, +37803:39472, +37804:38360, +37805:20685, +37806:21205, +37807:21516, +37808:22530, +37809:23566, +37810:24999, +37811:25758, +37812:27934, +37813:30643, +37814:31461, +37815:33012, +37816:33796, +37817:36947, +37818:37509, +37819:23776, +37820:40199, +37821:21311, +37822:24471, +37823:24499, +37824:28060, +37825:29305, +37826:30563, +37827:31167, +37828:31716, +37829:27602, +37830:29420, +37831:35501, +37832:26627, +37833:27233, +37834:20984, +37835:31361, +37836:26932, +37837:23626, +37838:40182, +37839:33515, +37840:23493, +37841:37193, +37842:28702, +37843:22136, +37844:23663, +37845:24775, +37846:25958, +37847:27788, +37848:35930, +37849:36929, +37850:38931, +37851:21585, +37852:26311, +37853:37389, +37854:22856, +37855:37027, +37856:20869, +37857:20045, +37858:20970, +37859:34201, +37860:35598, +37861:28760, +37862:25466, +37863:37707, +37864:26978, +37865:39348, +37866:32260, +37867:30071, +37868:21335, +37869:26976, +37870:36575, +37871:38627, +37872:27741, +37873:20108, +37874:23612, +37875:24336, +37876:36841, +37877:21250, +37878:36049, +37879:32905, +37880:34425, +37881:24319, +37882:26085, +37883:20083, +37884:20837, +37952:22914, +37953:23615, +37954:38894, +37955:20219, +37956:22922, +37957:24525, +37958:35469, +37959:28641, +37960:31152, +37961:31074, +37962:23527, +37963:33905, +37964:29483, +37965:29105, +37966:24180, +37967:24565, +37968:25467, +37969:25754, +37970:29123, +37971:31896, +37972:20035, +37973:24316, +37974:20043, +37975:22492, +37976:22178, +37977:24745, +37978:28611, +37979:32013, +37980:33021, +37981:33075, +37982:33215, +37983:36786, +37984:35223, +37985:34468, +37986:24052, +37987:25226, +37988:25773, +37989:35207, +37990:26487, +37991:27874, +37992:27966, +37993:29750, +37994:30772, +37995:23110, +37996:32629, +37997:33453, +37998:39340, +37999:20467, +38000:24259, +38001:25309, +38002:25490, +38003:25943, +38004:26479, +38005:30403, +38006:29260, +38007:32972, +38008:32954, +38009:36649, +38010:37197, +38011:20493, +38012:22521, +38013:23186, +38014:26757, +38016:26995, +38017:29028, +38018:29437, +38019:36023, +38020:22770, +38021:36064, +38022:38506, +38023:36889, +38024:34687, +38025:31204, +38026:30695, +38027:33833, +38028:20271, +38029:21093, +38030:21338, +38031:25293, +38032:26575, +38033:27850, +38034:30333, +38035:31636, +38036:31893, +38037:33334, +38038:34180, +38039:36843, +38040:26333, +38041:28448, +38042:29190, +38043:32283, +38044:33707, +38045:39361, +38046:40614, +38047:20989, +38048:31665, +38049:30834, +38050:31672, +38051:32903, +38052:31560, +38053:27368, +38054:24161, +38055:32908, +38056:30033, +38057:30048, +38058:20843, +38059:37474, +38060:28300, +38061:30330, +38062:37271, +38063:39658, +38064:20240, +38065:32624, +38066:25244, +38067:31567, +38068:38309, +38069:40169, +38070:22138, +38071:22617, +38072:34532, +38073:38588, +38074:20276, +38075:21028, +38076:21322, +38077:21453, +38078:21467, +38079:24070, +38080:25644, +38081:26001, +38082:26495, +38083:27710, +38084:27726, +38085:29256, +38086:29359, +38087:29677, +38088:30036, +38089:32321, +38090:33324, +38091:34281, +38092:36009, +38093:31684, +38094:37318, +38095:29033, +38096:38930, +38097:39151, +38098:25405, +38099:26217, +38100:30058, +38101:30436, +38102:30928, +38103:34115, +38104:34542, +38105:21290, +38106:21329, +38107:21542, +38108:22915, +38109:24199, +38110:24444, +38111:24754, +38112:25161, +38113:25209, +38114:25259, +38115:26000, +38116:27604, +38117:27852, +38118:30130, +38119:30382, +38120:30865, +38121:31192, +38122:32203, +38123:32631, +38124:32933, +38125:34987, +38126:35513, +38127:36027, +38128:36991, +38129:38750, +38130:39131, +38131:27147, +38132:31800, +38133:20633, +38134:23614, +38135:24494, +38136:26503, +38137:27608, +38138:29749, +38139:30473, +38140:32654, +38208:40763, +38209:26570, +38210:31255, +38211:21305, +38212:30091, +38213:39661, +38214:24422, +38215:33181, +38216:33777, +38217:32920, +38218:24380, +38219:24517, +38220:30050, +38221:31558, +38222:36924, +38223:26727, +38224:23019, +38225:23195, +38226:32016, +38227:30334, +38228:35628, +38229:20469, +38230:24426, +38231:27161, +38232:27703, +38233:28418, +38234:29922, +38235:31080, +38236:34920, +38237:35413, +38238:35961, +38239:24287, +38240:25551, +38241:30149, +38242:31186, +38243:33495, +38244:37672, +38245:37618, +38246:33948, +38247:34541, +38248:39981, +38249:21697, +38250:24428, +38251:25996, +38252:27996, +38253:28693, +38254:36007, +38255:36051, +38256:38971, +38257:25935, +38258:29942, +38259:19981, +38260:20184, +38261:22496, +38262:22827, +38263:23142, +38264:23500, +38265:20904, +38266:24067, +38267:24220, +38268:24598, +38269:25206, +38270:25975, +38272:26023, +38273:26222, +38274:28014, +38275:29238, +38276:31526, +38277:33104, +38278:33178, +38279:33433, +38280:35676, +38281:36000, +38282:36070, +38283:36212, +38284:38428, +38285:38468, +38286:20398, +38287:25771, +38288:27494, +38289:33310, +38290:33889, +38291:34154, +38292:37096, +38293:23553, +38294:26963, +38295:39080, +38296:33914, +38297:34135, +38298:20239, +38299:21103, +38300:24489, +38301:24133, +38302:26381, +38303:31119, +38304:33145, +38305:35079, +38306:35206, +38307:28149, +38308:24343, +38309:25173, +38310:27832, +38311:20175, +38312:29289, +38313:39826, +38314:20998, +38315:21563, +38316:22132, +38317:22707, +38318:24996, +38319:25198, +38320:28954, +38321:22894, +38322:31881, +38323:31966, +38324:32027, +38325:38640, +38326:25991, +38327:32862, +38328:19993, +38329:20341, +38330:20853, +38331:22592, +38332:24163, +38333:24179, +38334:24330, +38335:26564, +38336:20006, +38337:34109, +38338:38281, +38339:38491, +38340:31859, +38341:38913, +38342:20731, +38343:22721, +38344:30294, +38345:30887, +38346:21029, +38347:30629, +38348:34065, +38349:31622, +38350:20559, +38351:22793, +38352:29255, +38353:31687, +38354:32232, +38355:36794, +38356:36820, +38357:36941, +38358:20415, +38359:21193, +38360:23081, +38361:24321, +38362:38829, +38363:20445, +38364:33303, +38365:37610, +38366:22275, +38367:25429, +38368:27497, +38369:29995, +38370:35036, +38371:36628, +38372:31298, +38373:21215, +38374:22675, +38375:24917, +38376:25098, +38377:26286, +38378:27597, +38379:31807, +38380:33769, +38381:20515, +38382:20472, +38383:21253, +38384:21574, +38385:22577, +38386:22857, +38387:23453, +38388:23792, +38389:23791, +38390:23849, +38391:24214, +38392:25265, +38393:25447, +38394:25918, +38395:26041, +38396:26379, +38464:27861, +38465:27873, +38466:28921, +38467:30770, +38468:32299, +38469:32990, +38470:33459, +38471:33804, +38472:34028, +38473:34562, +38474:35090, +38475:35370, +38476:35914, +38477:37030, +38478:37586, +38479:39165, +38480:40179, +38481:40300, +38482:20047, +38483:20129, +38484:20621, +38485:21078, +38486:22346, +38487:22952, +38488:24125, +38489:24536, +38490:24537, +38491:25151, +38492:26292, +38493:26395, +38494:26576, +38495:26834, +38496:20882, +38497:32033, +38498:32938, +38499:33192, +38500:35584, +38501:35980, +38502:36031, +38503:37502, +38504:38450, +38505:21536, +38506:38956, +38507:21271, +38508:20693, +38509:21340, +38510:22696, +38511:25778, +38512:26420, +38513:29287, +38514:30566, +38515:31302, +38516:37350, +38517:21187, +38518:27809, +38519:27526, +38520:22528, +38521:24140, +38522:22868, +38523:26412, +38524:32763, +38525:20961, +38526:30406, +38528:25705, +38529:30952, +38530:39764, +38531:40635, +38532:22475, +38533:22969, +38534:26151, +38535:26522, +38536:27598, +38537:21737, +38538:27097, +38539:24149, +38540:33180, +38541:26517, +38542:39850, +38543:26622, +38544:40018, +38545:26717, +38546:20134, +38547:20451, +38548:21448, +38549:25273, +38550:26411, +38551:27819, +38552:36804, +38553:20397, +38554:32365, +38555:40639, +38556:19975, +38557:24930, +38558:28288, +38559:28459, +38560:34067, +38561:21619, +38562:26410, +38563:39749, +38564:24051, +38565:31637, +38566:23724, +38567:23494, +38568:34588, +38569:28234, +38570:34001, +38571:31252, +38572:33032, +38573:22937, +38574:31885, +38575:27665, +38576:30496, +38577:21209, +38578:22818, +38579:28961, +38580:29279, +38581:30683, +38582:38695, +38583:40289, +38584:26891, +38585:23167, +38586:23064, +38587:20901, +38588:21517, +38589:21629, +38590:26126, +38591:30431, +38592:36855, +38593:37528, +38594:40180, +38595:23018, +38596:29277, +38597:28357, +38598:20813, +38599:26825, +38600:32191, +38601:32236, +38602:38754, +38603:40634, +38604:25720, +38605:27169, +38606:33538, +38607:22916, +38608:23391, +38609:27611, +38610:29467, +38611:30450, +38612:32178, +38613:32791, +38614:33945, +38615:20786, +38616:26408, +38617:40665, +38618:30446, +38619:26466, +38620:21247, +38621:39173, +38622:23588, +38623:25147, +38624:31870, +38625:36016, +38626:21839, +38627:24758, +38628:32011, +38629:38272, +38630:21249, +38631:20063, +38632:20918, +38633:22812, +38634:29242, +38635:32822, +38636:37326, +38637:24357, +38638:30690, +38639:21380, +38640:24441, +38641:32004, +38642:34220, +38643:35379, +38644:36493, +38645:38742, +38646:26611, +38647:34222, +38648:37971, +38649:24841, +38650:24840, +38651:27833, +38652:30290, +38720:35565, +38721:36664, +38722:21807, +38723:20305, +38724:20778, +38725:21191, +38726:21451, +38727:23461, +38728:24189, +38729:24736, +38730:24962, +38731:25558, +38732:26377, +38733:26586, +38734:28263, +38735:28044, +38736:29494, +38737:29495, +38738:30001, +38739:31056, +38740:35029, +38741:35480, +38742:36938, +38743:37009, +38744:37109, +38745:38596, +38746:34701, +38747:22805, +38748:20104, +38749:20313, +38750:19982, +38751:35465, +38752:36671, +38753:38928, +38754:20653, +38755:24188, +38756:22934, +38757:23481, +38758:24248, +38759:25562, +38760:25594, +38761:25793, +38762:26332, +38763:26954, +38764:27096, +38765:27915, +38766:28342, +38767:29076, +38768:29992, +38769:31407, +38770:32650, +38771:32768, +38772:33865, +38773:33993, +38774:35201, +38775:35617, +38776:36362, +38777:36965, +38778:38525, +38779:39178, +38780:24958, +38781:25233, +38782:27442, +38784:27779, +38785:28020, +38786:32716, +38787:32764, +38788:28096, +38789:32645, +38790:34746, +38791:35064, +38792:26469, +38793:33713, +38794:38972, +38795:38647, +38796:27931, +38797:32097, +38798:33853, +38799:37226, +38800:20081, +38801:21365, +38802:23888, +38803:27396, +38804:28651, +38805:34253, +38806:34349, +38807:35239, +38808:21033, +38809:21519, +38810:23653, +38811:26446, +38812:26792, +38813:29702, +38814:29827, +38815:30178, +38816:35023, +38817:35041, +38818:37324, +38819:38626, +38820:38520, +38821:24459, +38822:29575, +38823:31435, +38824:33870, +38825:25504, +38826:30053, +38827:21129, +38828:27969, +38829:28316, +38830:29705, +38831:30041, +38832:30827, +38833:31890, +38834:38534, +38835:31452, +38836:40845, +38837:20406, +38838:24942, +38839:26053, +38840:34396, +38841:20102, +38842:20142, +38843:20698, +38844:20001, +38845:20940, +38846:23534, +38847:26009, +38848:26753, +38849:28092, +38850:29471, +38851:30274, +38852:30637, +38853:31260, +38854:31975, +38855:33391, +38856:35538, +38857:36988, +38858:37327, +38859:38517, +38860:38936, +38861:21147, +38862:32209, +38863:20523, +38864:21400, +38865:26519, +38866:28107, +38867:29136, +38868:29747, +38869:33256, +38870:36650, +38871:38563, +38872:40023, +38873:40607, +38874:29792, +38875:22593, +38876:28057, +38877:32047, +38878:39006, +38879:20196, +38880:20278, +38881:20363, +38882:20919, +38883:21169, +38884:23994, +38885:24604, +38886:29618, +38887:31036, +38888:33491, +38889:37428, +38890:38583, +38891:38646, +38892:38666, +38893:40599, +38894:40802, +38895:26278, +38896:27508, +38897:21015, +38898:21155, +38899:28872, +38900:35010, +38901:24265, +38902:24651, +38903:24976, +38904:28451, +38905:29001, +38906:31806, +38907:32244, +38908:32879, +38976:34030, +38977:36899, +38978:37676, +38979:21570, +38980:39791, +38981:27347, +38982:28809, +38983:36034, +38984:36335, +38985:38706, +38986:21172, +38987:23105, +38988:24266, +38989:24324, +38990:26391, +38991:27004, +38992:27028, +38993:28010, +38994:28431, +38995:29282, +38996:29436, +38997:31725, +38998:32769, +38999:32894, +39000:34635, +39001:37070, +39002:20845, +39003:40595, +39004:31108, +39005:32907, +39006:37682, +39007:35542, +39008:20525, +39009:21644, +39010:35441, +39011:27498, +39012:36036, +39013:33031, +39014:24785, +39015:26528, +39016:40434, +39017:20121, +39018:20120, +39019:39952, +39020:35435, +39021:34241, +39022:34152, +39023:26880, +39024:28286, +39025:30871, +39026:33109, +39071:24332, +39072:19984, +39073:19989, +39074:20010, +39075:20017, +39076:20022, +39077:20028, +39078:20031, +39079:20034, +39080:20054, +39081:20056, +39082:20098, +39083:20101, +39084:35947, +39085:20106, +39086:33298, +39087:24333, +39088:20110, +39089:20126, +39090:20127, +39091:20128, +39092:20130, +39093:20144, +39094:20147, +39095:20150, +39096:20174, +39097:20173, +39098:20164, +39099:20166, +39100:20162, +39101:20183, +39102:20190, +39103:20205, +39104:20191, +39105:20215, +39106:20233, +39107:20314, +39108:20272, +39109:20315, +39110:20317, +39111:20311, +39112:20295, +39113:20342, +39114:20360, +39115:20367, +39116:20376, +39117:20347, +39118:20329, +39119:20336, +39120:20369, +39121:20335, +39122:20358, +39123:20374, +39124:20760, +39125:20436, +39126:20447, +39127:20430, +39128:20440, +39129:20443, +39130:20433, +39131:20442, +39132:20432, +39133:20452, +39134:20453, +39135:20506, +39136:20520, +39137:20500, +39138:20522, +39139:20517, +39140:20485, +39141:20252, +39142:20470, +39143:20513, +39144:20521, +39145:20524, +39146:20478, +39147:20463, +39148:20497, +39149:20486, +39150:20547, +39151:20551, +39152:26371, +39153:20565, +39154:20560, +39155:20552, +39156:20570, +39157:20566, +39158:20588, +39159:20600, +39160:20608, +39161:20634, +39162:20613, +39163:20660, +39164:20658, +39232:20681, +39233:20682, +39234:20659, +39235:20674, +39236:20694, +39237:20702, +39238:20709, +39239:20717, +39240:20707, +39241:20718, +39242:20729, +39243:20725, +39244:20745, +39245:20737, +39246:20738, +39247:20758, +39248:20757, +39249:20756, +39250:20762, +39251:20769, +39252:20794, +39253:20791, +39254:20796, +39255:20795, +39256:20799, +39257:20800, +39258:20818, +39259:20812, +39260:20820, +39261:20834, +39262:31480, +39263:20841, +39264:20842, +39265:20846, +39266:20864, +39267:20866, +39268:22232, +39269:20876, +39270:20873, +39271:20879, +39272:20881, +39273:20883, +39274:20885, +39275:20886, +39276:20900, +39277:20902, +39278:20898, +39279:20905, +39280:20906, +39281:20907, +39282:20915, +39283:20913, +39284:20914, +39285:20912, +39286:20917, +39287:20925, +39288:20933, +39289:20937, +39290:20955, +39291:20960, +39292:34389, +39293:20969, +39294:20973, +39296:20976, +39297:20981, +39298:20990, +39299:20996, +39300:21003, +39301:21012, +39302:21006, +39303:21031, +39304:21034, +39305:21038, +39306:21043, +39307:21049, +39308:21071, +39309:21060, +39310:21067, +39311:21068, +39312:21086, +39313:21076, +39314:21098, +39315:21108, +39316:21097, +39317:21107, +39318:21119, +39319:21117, +39320:21133, +39321:21140, +39322:21138, +39323:21105, +39324:21128, +39325:21137, +39326:36776, +39327:36775, +39328:21164, +39329:21165, +39330:21180, +39331:21173, +39332:21185, +39333:21197, +39334:21207, +39335:21214, +39336:21219, +39337:21222, +39338:39149, +39339:21216, +39340:21235, +39341:21237, +39342:21240, +39343:21241, +39344:21254, +39345:21256, +39346:30008, +39347:21261, +39348:21264, +39349:21263, +39350:21269, +39351:21274, +39352:21283, +39353:21295, +39354:21297, +39355:21299, +39356:21304, +39357:21312, +39358:21318, +39359:21317, +39360:19991, +39361:21321, +39362:21325, +39363:20950, +39364:21342, +39365:21353, +39366:21358, +39367:22808, +39368:21371, +39369:21367, +39370:21378, +39371:21398, +39372:21408, +39373:21414, +39374:21413, +39375:21422, +39376:21424, +39377:21430, +39378:21443, +39379:31762, +39380:38617, +39381:21471, +39382:26364, +39383:29166, +39384:21486, +39385:21480, +39386:21485, +39387:21498, +39388:21505, +39389:21565, +39390:21568, +39391:21548, +39392:21549, +39393:21564, +39394:21550, +39395:21558, +39396:21545, +39397:21533, +39398:21582, +39399:21647, +39400:21621, +39401:21646, +39402:21599, +39403:21617, +39404:21623, +39405:21616, +39406:21650, +39407:21627, +39408:21632, +39409:21622, +39410:21636, +39411:21648, +39412:21638, +39413:21703, +39414:21666, +39415:21688, +39416:21669, +39417:21676, +39418:21700, +39419:21704, +39420:21672, +39488:21675, +39489:21698, +39490:21668, +39491:21694, +39492:21692, +39493:21720, +39494:21733, +39495:21734, +39496:21775, +39497:21780, +39498:21757, +39499:21742, +39500:21741, +39501:21754, +39502:21730, +39503:21817, +39504:21824, +39505:21859, +39506:21836, +39507:21806, +39508:21852, +39509:21829, +39510:21846, +39511:21847, +39512:21816, +39513:21811, +39514:21853, +39515:21913, +39516:21888, +39517:21679, +39518:21898, +39519:21919, +39520:21883, +39521:21886, +39522:21912, +39523:21918, +39524:21934, +39525:21884, +39526:21891, +39527:21929, +39528:21895, +39529:21928, +39530:21978, +39531:21957, +39532:21983, +39533:21956, +39534:21980, +39535:21988, +39536:21972, +39537:22036, +39538:22007, +39539:22038, +39540:22014, +39541:22013, +39542:22043, +39543:22009, +39544:22094, +39545:22096, +39546:29151, +39547:22068, +39548:22070, +39549:22066, +39550:22072, +39552:22123, +39553:22116, +39554:22063, +39555:22124, +39556:22122, +39557:22150, +39558:22144, +39559:22154, +39560:22176, +39561:22164, +39562:22159, +39563:22181, +39564:22190, +39565:22198, +39566:22196, +39567:22210, +39568:22204, +39569:22209, +39570:22211, +39571:22208, +39572:22216, +39573:22222, +39574:22225, +39575:22227, +39576:22231, +39577:22254, +39578:22265, +39579:22272, +39580:22271, +39581:22276, +39582:22281, +39583:22280, +39584:22283, +39585:22285, +39586:22291, +39587:22296, +39588:22294, +39589:21959, +39590:22300, +39591:22310, +39592:22327, +39593:22328, +39594:22350, +39595:22331, +39596:22336, +39597:22351, +39598:22377, +39599:22464, +39600:22408, +39601:22369, +39602:22399, +39603:22409, +39604:22419, +39605:22432, +39606:22451, +39607:22436, +39608:22442, +39609:22448, +39610:22467, +39611:22470, +39612:22484, +39613:22482, +39614:22483, +39615:22538, +39616:22486, +39617:22499, +39618:22539, +39619:22553, +39620:22557, +39621:22642, +39622:22561, +39623:22626, +39624:22603, +39625:22640, +39626:27584, +39627:22610, +39628:22589, +39629:22649, +39630:22661, +39631:22713, +39632:22687, +39633:22699, +39634:22714, +39635:22750, +39636:22715, +39637:22712, +39638:22702, +39639:22725, +39640:22739, +39641:22737, +39642:22743, +39643:22745, +39644:22744, +39645:22757, +39646:22748, +39647:22756, +39648:22751, +39649:22767, +39650:22778, +39651:22777, +39652:22779, +39653:22780, +39654:22781, +39655:22786, +39656:22794, +39657:22800, +39658:22811, +39659:26790, +39660:22821, +39661:22828, +39662:22829, +39663:22834, +39664:22840, +39665:22846, +39666:31442, +39667:22869, +39668:22864, +39669:22862, +39670:22874, +39671:22872, +39672:22882, +39673:22880, +39674:22887, +39675:22892, +39676:22889, +39744:22904, +39745:22913, +39746:22941, +39747:20318, +39748:20395, +39749:22947, +39750:22962, +39751:22982, +39752:23016, +39753:23004, +39754:22925, +39755:23001, +39756:23002, +39757:23077, +39758:23071, +39759:23057, +39760:23068, +39761:23049, +39762:23066, +39763:23104, +39764:23148, +39765:23113, +39766:23093, +39767:23094, +39768:23138, +39769:23146, +39770:23194, +39771:23228, +39772:23230, +39773:23243, +39774:23234, +39775:23229, +39776:23267, +39777:23255, +39778:23270, +39779:23273, +39780:23254, +39781:23290, +39782:23291, +39783:23308, +39784:23307, +39785:23318, +39786:23346, +39787:23248, +39788:23338, +39789:23350, +39790:23358, +39791:23363, +39792:23365, +39793:23360, +39794:23377, +39795:23381, +39796:23386, +39797:23387, +39798:23397, +39799:23401, +39800:23408, +39801:23411, +39802:23413, +39803:23416, +39804:25992, +39805:23418, +39806:23424, +39808:23427, +39809:23462, +39810:23480, +39811:23491, +39812:23495, +39813:23497, +39814:23508, +39815:23504, +39816:23524, +39817:23526, +39818:23522, +39819:23518, +39820:23525, +39821:23531, +39822:23536, +39823:23542, +39824:23539, +39825:23557, +39826:23559, +39827:23560, +39828:23565, +39829:23571, +39830:23584, +39831:23586, +39832:23592, +39833:23608, +39834:23609, +39835:23617, +39836:23622, +39837:23630, +39838:23635, +39839:23632, +39840:23631, +39841:23409, +39842:23660, +39843:23662, +39844:20066, +39845:23670, +39846:23673, +39847:23692, +39848:23697, +39849:23700, +39850:22939, +39851:23723, +39852:23739, +39853:23734, +39854:23740, +39855:23735, +39856:23749, +39857:23742, +39858:23751, +39859:23769, +39860:23785, +39861:23805, +39862:23802, +39863:23789, +39864:23948, +39865:23786, +39866:23819, +39867:23829, +39868:23831, +39869:23900, +39870:23839, +39871:23835, +39872:23825, +39873:23828, +39874:23842, +39875:23834, +39876:23833, +39877:23832, +39878:23884, +39879:23890, +39880:23886, +39881:23883, +39882:23916, +39883:23923, +39884:23926, +39885:23943, +39886:23940, +39887:23938, +39888:23970, +39889:23965, +39890:23980, +39891:23982, +39892:23997, +39893:23952, +39894:23991, +39895:23996, +39896:24009, +39897:24013, +39898:24019, +39899:24018, +39900:24022, +39901:24027, +39902:24043, +39903:24050, +39904:24053, +39905:24075, +39906:24090, +39907:24089, +39908:24081, +39909:24091, +39910:24118, +39911:24119, +39912:24132, +39913:24131, +39914:24128, +39915:24142, +39916:24151, +39917:24148, +39918:24159, +39919:24162, +39920:24164, +39921:24135, +39922:24181, +39923:24182, +39924:24186, +39925:40636, +39926:24191, +39927:24224, +39928:24257, +39929:24258, +39930:24264, +39931:24272, +39932:24271, +40000:24278, +40001:24291, +40002:24285, +40003:24282, +40004:24283, +40005:24290, +40006:24289, +40007:24296, +40008:24297, +40009:24300, +40010:24305, +40011:24307, +40012:24304, +40013:24308, +40014:24312, +40015:24318, +40016:24323, +40017:24329, +40018:24413, +40019:24412, +40020:24331, +40021:24337, +40022:24342, +40023:24361, +40024:24365, +40025:24376, +40026:24385, +40027:24392, +40028:24396, +40029:24398, +40030:24367, +40031:24401, +40032:24406, +40033:24407, +40034:24409, +40035:24417, +40036:24429, +40037:24435, +40038:24439, +40039:24451, +40040:24450, +40041:24447, +40042:24458, +40043:24456, +40044:24465, +40045:24455, +40046:24478, +40047:24473, +40048:24472, +40049:24480, +40050:24488, +40051:24493, +40052:24508, +40053:24534, +40054:24571, +40055:24548, +40056:24568, +40057:24561, +40058:24541, +40059:24755, +40060:24575, +40061:24609, +40062:24672, +40064:24601, +40065:24592, +40066:24617, +40067:24590, +40068:24625, +40069:24603, +40070:24597, +40071:24619, +40072:24614, +40073:24591, +40074:24634, +40075:24666, +40076:24641, +40077:24682, +40078:24695, +40079:24671, +40080:24650, +40081:24646, +40082:24653, +40083:24675, +40084:24643, +40085:24676, +40086:24642, +40087:24684, +40088:24683, +40089:24665, +40090:24705, +40091:24717, +40092:24807, +40093:24707, +40094:24730, +40095:24708, +40096:24731, +40097:24726, +40098:24727, +40099:24722, +40100:24743, +40101:24715, +40102:24801, +40103:24760, +40104:24800, +40105:24787, +40106:24756, +40107:24560, +40108:24765, +40109:24774, +40110:24757, +40111:24792, +40112:24909, +40113:24853, +40114:24838, +40115:24822, +40116:24823, +40117:24832, +40118:24820, +40119:24826, +40120:24835, +40121:24865, +40122:24827, +40123:24817, +40124:24845, +40125:24846, +40126:24903, +40127:24894, +40128:24872, +40129:24871, +40130:24906, +40131:24895, +40132:24892, +40133:24876, +40134:24884, +40135:24893, +40136:24898, +40137:24900, +40138:24947, +40139:24951, +40140:24920, +40141:24921, +40142:24922, +40143:24939, +40144:24948, +40145:24943, +40146:24933, +40147:24945, +40148:24927, +40149:24925, +40150:24915, +40151:24949, +40152:24985, +40153:24982, +40154:24967, +40155:25004, +40156:24980, +40157:24986, +40158:24970, +40159:24977, +40160:25003, +40161:25006, +40162:25036, +40163:25034, +40164:25033, +40165:25079, +40166:25032, +40167:25027, +40168:25030, +40169:25018, +40170:25035, +40171:32633, +40172:25037, +40173:25062, +40174:25059, +40175:25078, +40176:25082, +40177:25076, +40178:25087, +40179:25085, +40180:25084, +40181:25086, +40182:25088, +40183:25096, +40184:25097, +40185:25101, +40186:25100, +40187:25108, +40188:25115, +40256:25118, +40257:25121, +40258:25130, +40259:25134, +40260:25136, +40261:25138, +40262:25139, +40263:25153, +40264:25166, +40265:25182, +40266:25187, +40267:25179, +40268:25184, +40269:25192, +40270:25212, +40271:25218, +40272:25225, +40273:25214, +40274:25234, +40275:25235, +40276:25238, +40277:25300, +40278:25219, +40279:25236, +40280:25303, +40281:25297, +40282:25275, +40283:25295, +40284:25343, +40285:25286, +40286:25812, +40287:25288, +40288:25308, +40289:25292, +40290:25290, +40291:25282, +40292:25287, +40293:25243, +40294:25289, +40295:25356, +40296:25326, +40297:25329, +40298:25383, +40299:25346, +40300:25352, +40301:25327, +40302:25333, +40303:25424, +40304:25406, +40305:25421, +40306:25628, +40307:25423, +40308:25494, +40309:25486, +40310:25472, +40311:25515, +40312:25462, +40313:25507, +40314:25487, +40315:25481, +40316:25503, +40317:25525, +40318:25451, +40320:25449, +40321:25534, +40322:25577, +40323:25536, +40324:25542, +40325:25571, +40326:25545, +40327:25554, +40328:25590, +40329:25540, +40330:25622, +40331:25652, +40332:25606, +40333:25619, +40334:25638, +40335:25654, +40336:25885, +40337:25623, +40338:25640, +40339:25615, +40340:25703, +40341:25711, +40342:25718, +40343:25678, +40344:25898, +40345:25749, +40346:25747, +40347:25765, +40348:25769, +40349:25736, +40350:25788, +40351:25818, +40352:25810, +40353:25797, +40354:25799, +40355:25787, +40356:25816, +40357:25794, +40358:25841, +40359:25831, +40360:33289, +40361:25824, +40362:25825, +40363:25260, +40364:25827, +40365:25839, +40366:25900, +40367:25846, +40368:25844, +40369:25842, +40370:25850, +40371:25856, +40372:25853, +40373:25880, +40374:25884, +40375:25861, +40376:25892, +40377:25891, +40378:25899, +40379:25908, +40380:25909, +40381:25911, +40382:25910, +40383:25912, +40384:30027, +40385:25928, +40386:25942, +40387:25941, +40388:25933, +40389:25944, +40390:25950, +40391:25949, +40392:25970, +40393:25976, +40394:25986, +40395:25987, +40396:35722, +40397:26011, +40398:26015, +40399:26027, +40400:26039, +40401:26051, +40402:26054, +40403:26049, +40404:26052, +40405:26060, +40406:26066, +40407:26075, +40408:26073, +40409:26080, +40410:26081, +40411:26097, +40412:26482, +40413:26122, +40414:26115, +40415:26107, +40416:26483, +40417:26165, +40418:26166, +40419:26164, +40420:26140, +40421:26191, +40422:26180, +40423:26185, +40424:26177, +40425:26206, +40426:26205, +40427:26212, +40428:26215, +40429:26216, +40430:26207, +40431:26210, +40432:26224, +40433:26243, +40434:26248, +40435:26254, +40436:26249, +40437:26244, +40438:26264, +40439:26269, +40440:26305, +40441:26297, +40442:26313, +40443:26302, +40444:26300, +40512:26308, +40513:26296, +40514:26326, +40515:26330, +40516:26336, +40517:26175, +40518:26342, +40519:26345, +40520:26352, +40521:26357, +40522:26359, +40523:26383, +40524:26390, +40525:26398, +40526:26406, +40527:26407, +40528:38712, +40529:26414, +40530:26431, +40531:26422, +40532:26433, +40533:26424, +40534:26423, +40535:26438, +40536:26462, +40537:26464, +40538:26457, +40539:26467, +40540:26468, +40541:26505, +40542:26480, +40543:26537, +40544:26492, +40545:26474, +40546:26508, +40547:26507, +40548:26534, +40549:26529, +40550:26501, +40551:26551, +40552:26607, +40553:26548, +40554:26604, +40555:26547, +40556:26601, +40557:26552, +40558:26596, +40559:26590, +40560:26589, +40561:26594, +40562:26606, +40563:26553, +40564:26574, +40565:26566, +40566:26599, +40567:27292, +40568:26654, +40569:26694, +40570:26665, +40571:26688, +40572:26701, +40573:26674, +40574:26702, +40576:26803, +40577:26667, +40578:26713, +40579:26723, +40580:26743, +40581:26751, +40582:26783, +40583:26767, +40584:26797, +40585:26772, +40586:26781, +40587:26779, +40588:26755, +40589:27310, +40590:26809, +40591:26740, +40592:26805, +40593:26784, +40594:26810, +40595:26895, +40596:26765, +40597:26750, +40598:26881, +40599:26826, +40600:26888, +40601:26840, +40602:26914, +40603:26918, +40604:26849, +40605:26892, +40606:26829, +40607:26836, +40608:26855, +40609:26837, +40610:26934, +40611:26898, +40612:26884, +40613:26839, +40614:26851, +40615:26917, +40616:26873, +40617:26848, +40618:26863, +40619:26920, +40620:26922, +40621:26906, +40622:26915, +40623:26913, +40624:26822, +40625:27001, +40626:26999, +40627:26972, +40628:27000, +40629:26987, +40630:26964, +40631:27006, +40632:26990, +40633:26937, +40634:26996, +40635:26941, +40636:26969, +40637:26928, +40638:26977, +40639:26974, +40640:26973, +40641:27009, +40642:26986, +40643:27058, +40644:27054, +40645:27088, +40646:27071, +40647:27073, +40648:27091, +40649:27070, +40650:27086, +40651:23528, +40652:27082, +40653:27101, +40654:27067, +40655:27075, +40656:27047, +40657:27182, +40658:27025, +40659:27040, +40660:27036, +40661:27029, +40662:27060, +40663:27102, +40664:27112, +40665:27138, +40666:27163, +40667:27135, +40668:27402, +40669:27129, +40670:27122, +40671:27111, +40672:27141, +40673:27057, +40674:27166, +40675:27117, +40676:27156, +40677:27115, +40678:27146, +40679:27154, +40680:27329, +40681:27171, +40682:27155, +40683:27204, +40684:27148, +40685:27250, +40686:27190, +40687:27256, +40688:27207, +40689:27234, +40690:27225, +40691:27238, +40692:27208, +40693:27192, +40694:27170, +40695:27280, +40696:27277, +40697:27296, +40698:27268, +40699:27298, +40700:27299, +40768:27287, +40769:34327, +40770:27323, +40771:27331, +40772:27330, +40773:27320, +40774:27315, +40775:27308, +40776:27358, +40777:27345, +40778:27359, +40779:27306, +40780:27354, +40781:27370, +40782:27387, +40783:27397, +40784:34326, +40785:27386, +40786:27410, +40787:27414, +40788:39729, +40789:27423, +40790:27448, +40791:27447, +40792:30428, +40793:27449, +40794:39150, +40795:27463, +40796:27459, +40797:27465, +40798:27472, +40799:27481, +40800:27476, +40801:27483, +40802:27487, +40803:27489, +40804:27512, +40805:27513, +40806:27519, +40807:27520, +40808:27524, +40809:27523, +40810:27533, +40811:27544, +40812:27541, +40813:27550, +40814:27556, +40815:27562, +40816:27563, +40817:27567, +40818:27570, +40819:27569, +40820:27571, +40821:27575, +40822:27580, +40823:27590, +40824:27595, +40825:27603, +40826:27615, +40827:27628, +40828:27627, +40829:27635, +40830:27631, +40832:40638, +40833:27656, +40834:27667, +40835:27668, +40836:27675, +40837:27684, +40838:27683, +40839:27742, +40840:27733, +40841:27746, +40842:27754, +40843:27778, +40844:27789, +40845:27802, +40846:27777, +40847:27803, +40848:27774, +40849:27752, +40850:27763, +40851:27794, +40852:27792, +40853:27844, +40854:27889, +40855:27859, +40856:27837, +40857:27863, +40858:27845, +40859:27869, +40860:27822, +40861:27825, +40862:27838, +40863:27834, +40864:27867, +40865:27887, +40866:27865, +40867:27882, +40868:27935, +40869:34893, +40870:27958, +40871:27947, +40872:27965, +40873:27960, +40874:27929, +40875:27957, +40876:27955, +40877:27922, +40878:27916, +40879:28003, +40880:28051, +40881:28004, +40882:27994, +40883:28025, +40884:27993, +40885:28046, +40886:28053, +40887:28644, +40888:28037, +40889:28153, +40890:28181, +40891:28170, +40892:28085, +40893:28103, +40894:28134, +40895:28088, +40896:28102, +40897:28140, +40898:28126, +40899:28108, +40900:28136, +40901:28114, +40902:28101, +40903:28154, +40904:28121, +40905:28132, +40906:28117, +40907:28138, +40908:28142, +40909:28205, +40910:28270, +40911:28206, +40912:28185, +40913:28274, +40914:28255, +40915:28222, +40916:28195, +40917:28267, +40918:28203, +40919:28278, +40920:28237, +40921:28191, +40922:28227, +40923:28218, +40924:28238, +40925:28196, +40926:28415, +40927:28189, +40928:28216, +40929:28290, +40930:28330, +40931:28312, +40932:28361, +40933:28343, +40934:28371, +40935:28349, +40936:28335, +40937:28356, +40938:28338, +40939:28372, +40940:28373, +40941:28303, +40942:28325, +40943:28354, +40944:28319, +40945:28481, +40946:28433, +40947:28748, +40948:28396, +40949:28408, +40950:28414, +40951:28479, +40952:28402, +40953:28465, +40954:28399, +40955:28466, +40956:28364, +57408:28478, +57409:28435, +57410:28407, +57411:28550, +57412:28538, +57413:28536, +57414:28545, +57415:28544, +57416:28527, +57417:28507, +57418:28659, +57419:28525, +57420:28546, +57421:28540, +57422:28504, +57423:28558, +57424:28561, +57425:28610, +57426:28518, +57427:28595, +57428:28579, +57429:28577, +57430:28580, +57431:28601, +57432:28614, +57433:28586, +57434:28639, +57435:28629, +57436:28652, +57437:28628, +57438:28632, +57439:28657, +57440:28654, +57441:28635, +57442:28681, +57443:28683, +57444:28666, +57445:28689, +57446:28673, +57447:28687, +57448:28670, +57449:28699, +57450:28698, +57451:28532, +57452:28701, +57453:28696, +57454:28703, +57455:28720, +57456:28734, +57457:28722, +57458:28753, +57459:28771, +57460:28825, +57461:28818, +57462:28847, +57463:28913, +57464:28844, +57465:28856, +57466:28851, +57467:28846, +57468:28895, +57469:28875, +57470:28893, +57472:28889, +57473:28937, +57474:28925, +57475:28956, +57476:28953, +57477:29029, +57478:29013, +57479:29064, +57480:29030, +57481:29026, +57482:29004, +57483:29014, +57484:29036, +57485:29071, +57486:29179, +57487:29060, +57488:29077, +57489:29096, +57490:29100, +57491:29143, +57492:29113, +57493:29118, +57494:29138, +57495:29129, +57496:29140, +57497:29134, +57498:29152, +57499:29164, +57500:29159, +57501:29173, +57502:29180, +57503:29177, +57504:29183, +57505:29197, +57506:29200, +57507:29211, +57508:29224, +57509:29229, +57510:29228, +57511:29232, +57512:29234, +57513:29243, +57514:29244, +57515:29247, +57516:29248, +57517:29254, +57518:29259, +57519:29272, +57520:29300, +57521:29310, +57522:29314, +57523:29313, +57524:29319, +57525:29330, +57526:29334, +57527:29346, +57528:29351, +57529:29369, +57530:29362, +57531:29379, +57532:29382, +57533:29380, +57534:29390, +57535:29394, +57536:29410, +57537:29408, +57538:29409, +57539:29433, +57540:29431, +57541:20495, +57542:29463, +57543:29450, +57544:29468, +57545:29462, +57546:29469, +57547:29492, +57548:29487, +57549:29481, +57550:29477, +57551:29502, +57552:29518, +57553:29519, +57554:40664, +57555:29527, +57556:29546, +57557:29544, +57558:29552, +57559:29560, +57560:29557, +57561:29563, +57562:29562, +57563:29640, +57564:29619, +57565:29646, +57566:29627, +57567:29632, +57568:29669, +57569:29678, +57570:29662, +57571:29858, +57572:29701, +57573:29807, +57574:29733, +57575:29688, +57576:29746, +57577:29754, +57578:29781, +57579:29759, +57580:29791, +57581:29785, +57582:29761, +57583:29788, +57584:29801, +57585:29808, +57586:29795, +57587:29802, +57588:29814, +57589:29822, +57590:29835, +57591:29854, +57592:29863, +57593:29898, +57594:29903, +57595:29908, +57596:29681, +57664:29920, +57665:29923, +57666:29927, +57667:29929, +57668:29934, +57669:29938, +57670:29936, +57671:29937, +57672:29944, +57673:29943, +57674:29956, +57675:29955, +57676:29957, +57677:29964, +57678:29966, +57679:29965, +57680:29973, +57681:29971, +57682:29982, +57683:29990, +57684:29996, +57685:30012, +57686:30020, +57687:30029, +57688:30026, +57689:30025, +57690:30043, +57691:30022, +57692:30042, +57693:30057, +57694:30052, +57695:30055, +57696:30059, +57697:30061, +57698:30072, +57699:30070, +57700:30086, +57701:30087, +57702:30068, +57703:30090, +57704:30089, +57705:30082, +57706:30100, +57707:30106, +57708:30109, +57709:30117, +57710:30115, +57711:30146, +57712:30131, +57713:30147, +57714:30133, +57715:30141, +57716:30136, +57717:30140, +57718:30129, +57719:30157, +57720:30154, +57721:30162, +57722:30169, +57723:30179, +57724:30174, +57725:30206, +57726:30207, +57728:30204, +57729:30209, +57730:30192, +57731:30202, +57732:30194, +57733:30195, +57734:30219, +57735:30221, +57736:30217, +57737:30239, +57738:30247, +57739:30240, +57740:30241, +57741:30242, +57742:30244, +57743:30260, +57744:30256, +57745:30267, +57746:30279, +57747:30280, +57748:30278, +57749:30300, +57750:30296, +57751:30305, +57752:30306, +57753:30312, +57754:30313, +57755:30314, +57756:30311, +57757:30316, +57758:30320, +57759:30322, +57760:30326, +57761:30328, +57762:30332, +57763:30336, +57764:30339, +57765:30344, +57766:30347, +57767:30350, +57768:30358, +57769:30355, +57770:30361, +57771:30362, +57772:30384, +57773:30388, +57774:30392, +57775:30393, +57776:30394, +57777:30402, +57778:30413, +57779:30422, +57780:30418, +57781:30430, +57782:30433, +57783:30437, +57784:30439, +57785:30442, +57786:34351, +57787:30459, +57788:30472, +57789:30471, +57790:30468, +57791:30505, +57792:30500, +57793:30494, +57794:30501, +57795:30502, +57796:30491, +57797:30519, +57798:30520, +57799:30535, +57800:30554, +57801:30568, +57802:30571, +57803:30555, +57804:30565, +57805:30591, +57806:30590, +57807:30585, +57808:30606, +57809:30603, +57810:30609, +57811:30624, +57812:30622, +57813:30640, +57814:30646, +57815:30649, +57816:30655, +57817:30652, +57818:30653, +57819:30651, +57820:30663, +57821:30669, +57822:30679, +57823:30682, +57824:30684, +57825:30691, +57826:30702, +57827:30716, +57828:30732, +57829:30738, +57830:31014, +57831:30752, +57832:31018, +57833:30789, +57834:30862, +57835:30836, +57836:30854, +57837:30844, +57838:30874, +57839:30860, +57840:30883, +57841:30901, +57842:30890, +57843:30895, +57844:30929, +57845:30918, +57846:30923, +57847:30932, +57848:30910, +57849:30908, +57850:30917, +57851:30922, +57852:30956, +57920:30951, +57921:30938, +57922:30973, +57923:30964, +57924:30983, +57925:30994, +57926:30993, +57927:31001, +57928:31020, +57929:31019, +57930:31040, +57931:31072, +57932:31063, +57933:31071, +57934:31066, +57935:31061, +57936:31059, +57937:31098, +57938:31103, +57939:31114, +57940:31133, +57941:31143, +57942:40779, +57943:31146, +57944:31150, +57945:31155, +57946:31161, +57947:31162, +57948:31177, +57949:31189, +57950:31207, +57951:31212, +57952:31201, +57953:31203, +57954:31240, +57955:31245, +57956:31256, +57957:31257, +57958:31264, +57959:31263, +57960:31104, +57961:31281, +57962:31291, +57963:31294, +57964:31287, +57965:31299, +57966:31319, +57967:31305, +57968:31329, +57969:31330, +57970:31337, +57971:40861, +57972:31344, +57973:31353, +57974:31357, +57975:31368, +57976:31383, +57977:31381, +57978:31384, +57979:31382, +57980:31401, +57981:31432, +57982:31408, +57984:31414, +57985:31429, +57986:31428, +57987:31423, +57988:36995, +57989:31431, +57990:31434, +57991:31437, +57992:31439, +57993:31445, +57994:31443, +57995:31449, +57996:31450, +57997:31453, +57998:31457, +57999:31458, +58000:31462, +58001:31469, +58002:31472, +58003:31490, +58004:31503, +58005:31498, +58006:31494, +58007:31539, +58008:31512, +58009:31513, +58010:31518, +58011:31541, +58012:31528, +58013:31542, +58014:31568, +58015:31610, +58016:31492, +58017:31565, +58018:31499, +58019:31564, +58020:31557, +58021:31605, +58022:31589, +58023:31604, +58024:31591, +58025:31600, +58026:31601, +58027:31596, +58028:31598, +58029:31645, +58030:31640, +58031:31647, +58032:31629, +58033:31644, +58034:31642, +58035:31627, +58036:31634, +58037:31631, +58038:31581, +58039:31641, +58040:31691, +58041:31681, +58042:31692, +58043:31695, +58044:31668, +58045:31686, +58046:31709, +58047:31721, +58048:31761, +58049:31764, +58050:31718, +58051:31717, +58052:31840, +58053:31744, +58054:31751, +58055:31763, +58056:31731, +58057:31735, +58058:31767, +58059:31757, +58060:31734, +58061:31779, +58062:31783, +58063:31786, +58064:31775, +58065:31799, +58066:31787, +58067:31805, +58068:31820, +58069:31811, +58070:31828, +58071:31823, +58072:31808, +58073:31824, +58074:31832, +58075:31839, +58076:31844, +58077:31830, +58078:31845, +58079:31852, +58080:31861, +58081:31875, +58082:31888, +58083:31908, +58084:31917, +58085:31906, +58086:31915, +58087:31905, +58088:31912, +58089:31923, +58090:31922, +58091:31921, +58092:31918, +58093:31929, +58094:31933, +58095:31936, +58096:31941, +58097:31938, +58098:31960, +58099:31954, +58100:31964, +58101:31970, +58102:39739, +58103:31983, +58104:31986, +58105:31988, +58106:31990, +58107:31994, +58108:32006, +58176:32002, +58177:32028, +58178:32021, +58179:32010, +58180:32069, +58181:32075, +58182:32046, +58183:32050, +58184:32063, +58185:32053, +58186:32070, +58187:32115, +58188:32086, +58189:32078, +58190:32114, +58191:32104, +58192:32110, +58193:32079, +58194:32099, +58195:32147, +58196:32137, +58197:32091, +58198:32143, +58199:32125, +58200:32155, +58201:32186, +58202:32174, +58203:32163, +58204:32181, +58205:32199, +58206:32189, +58207:32171, +58208:32317, +58209:32162, +58210:32175, +58211:32220, +58212:32184, +58213:32159, +58214:32176, +58215:32216, +58216:32221, +58217:32228, +58218:32222, +58219:32251, +58220:32242, +58221:32225, +58222:32261, +58223:32266, +58224:32291, +58225:32289, +58226:32274, +58227:32305, +58228:32287, +58229:32265, +58230:32267, +58231:32290, +58232:32326, +58233:32358, +58234:32315, +58235:32309, +58236:32313, +58237:32323, +58238:32311, +58240:32306, +58241:32314, +58242:32359, +58243:32349, +58244:32342, +58245:32350, +58246:32345, +58247:32346, +58248:32377, +58249:32362, +58250:32361, +58251:32380, +58252:32379, +58253:32387, +58254:32213, +58255:32381, +58256:36782, +58257:32383, +58258:32392, +58259:32393, +58260:32396, +58261:32402, +58262:32400, +58263:32403, +58264:32404, +58265:32406, +58266:32398, +58267:32411, +58268:32412, +58269:32568, +58270:32570, +58271:32581, +58272:32588, +58273:32589, +58274:32590, +58275:32592, +58276:32593, +58277:32597, +58278:32596, +58279:32600, +58280:32607, +58281:32608, +58282:32616, +58283:32617, +58284:32615, +58285:32632, +58286:32642, +58287:32646, +58288:32643, +58289:32648, +58290:32647, +58291:32652, +58292:32660, +58293:32670, +58294:32669, +58295:32666, +58296:32675, +58297:32687, +58298:32690, +58299:32697, +58300:32686, +58301:32694, +58302:32696, +58303:35697, +58304:32709, +58305:32710, +58306:32714, +58307:32725, +58308:32724, +58309:32737, +58310:32742, +58311:32745, +58312:32755, +58313:32761, +58314:39132, +58315:32774, +58316:32772, +58317:32779, +58318:32786, +58319:32792, +58320:32793, +58321:32796, +58322:32801, +58323:32808, +58324:32831, +58325:32827, +58326:32842, +58327:32838, +58328:32850, +58329:32856, +58330:32858, +58331:32863, +58332:32866, +58333:32872, +58334:32883, +58335:32882, +58336:32880, +58337:32886, +58338:32889, +58339:32893, +58340:32895, +58341:32900, +58342:32902, +58343:32901, +58344:32923, +58345:32915, +58346:32922, +58347:32941, +58348:20880, +58349:32940, +58350:32987, +58351:32997, +58352:32985, +58353:32989, +58354:32964, +58355:32986, +58356:32982, +58357:33033, +58358:33007, +58359:33009, +58360:33051, +58361:33065, +58362:33059, +58363:33071, +58364:33099, +58432:38539, +58433:33094, +58434:33086, +58435:33107, +58436:33105, +58437:33020, +58438:33137, +58439:33134, +58440:33125, +58441:33126, +58442:33140, +58443:33155, +58444:33160, +58445:33162, +58446:33152, +58447:33154, +58448:33184, +58449:33173, +58450:33188, +58451:33187, +58452:33119, +58453:33171, +58454:33193, +58455:33200, +58456:33205, +58457:33214, +58458:33208, +58459:33213, +58460:33216, +58461:33218, +58462:33210, +58463:33225, +58464:33229, +58465:33233, +58466:33241, +58467:33240, +58468:33224, +58469:33242, +58470:33247, +58471:33248, +58472:33255, +58473:33274, +58474:33275, +58475:33278, +58476:33281, +58477:33282, +58478:33285, +58479:33287, +58480:33290, +58481:33293, +58482:33296, +58483:33302, +58484:33321, +58485:33323, +58486:33336, +58487:33331, +58488:33344, +58489:33369, +58490:33368, +58491:33373, +58492:33370, +58493:33375, +58494:33380, +58496:33378, +58497:33384, +58498:33386, +58499:33387, +58500:33326, +58501:33393, +58502:33399, +58503:33400, +58504:33406, +58505:33421, +58506:33426, +58507:33451, +58508:33439, +58509:33467, +58510:33452, +58511:33505, +58512:33507, +58513:33503, +58514:33490, +58515:33524, +58516:33523, +58517:33530, +58518:33683, +58519:33539, +58520:33531, +58521:33529, +58522:33502, +58523:33542, +58524:33500, +58525:33545, +58526:33497, +58527:33589, +58528:33588, +58529:33558, +58530:33586, +58531:33585, +58532:33600, +58533:33593, +58534:33616, +58535:33605, +58536:33583, +58537:33579, +58538:33559, +58539:33560, +58540:33669, +58541:33690, +58542:33706, +58543:33695, +58544:33698, +58545:33686, +58546:33571, +58547:33678, +58548:33671, +58549:33674, +58550:33660, +58551:33717, +58552:33651, +58553:33653, +58554:33696, +58555:33673, +58556:33704, +58557:33780, +58558:33811, +58559:33771, +58560:33742, +58561:33789, +58562:33795, +58563:33752, +58564:33803, +58565:33729, +58566:33783, +58567:33799, +58568:33760, +58569:33778, +58570:33805, +58571:33826, +58572:33824, +58573:33725, +58574:33848, +58575:34054, +58576:33787, +58577:33901, +58578:33834, +58579:33852, +58580:34138, +58581:33924, +58582:33911, +58583:33899, +58584:33965, +58585:33902, +58586:33922, +58587:33897, +58588:33862, +58589:33836, +58590:33903, +58591:33913, +58592:33845, +58593:33994, +58594:33890, +58595:33977, +58596:33983, +58597:33951, +58598:34009, +58599:33997, +58600:33979, +58601:34010, +58602:34000, +58603:33985, +58604:33990, +58605:34006, +58606:33953, +58607:34081, +58608:34047, +58609:34036, +58610:34071, +58611:34072, +58612:34092, +58613:34079, +58614:34069, +58615:34068, +58616:34044, +58617:34112, +58618:34147, +58619:34136, +58620:34120, +58688:34113, +58689:34306, +58690:34123, +58691:34133, +58692:34176, +58693:34212, +58694:34184, +58695:34193, +58696:34186, +58697:34216, +58698:34157, +58699:34196, +58700:34203, +58701:34282, +58702:34183, +58703:34204, +58704:34167, +58705:34174, +58706:34192, +58707:34249, +58708:34234, +58709:34255, +58710:34233, +58711:34256, +58712:34261, +58713:34269, +58714:34277, +58715:34268, +58716:34297, +58717:34314, +58718:34323, +58719:34315, +58720:34302, +58721:34298, +58722:34310, +58723:34338, +58724:34330, +58725:34352, +58726:34367, +58727:34381, +58728:20053, +58729:34388, +58730:34399, +58731:34407, +58732:34417, +58733:34451, +58734:34467, +58735:34473, +58736:34474, +58737:34443, +58738:34444, +58739:34486, +58740:34479, +58741:34500, +58742:34502, +58743:34480, +58744:34505, +58745:34851, +58746:34475, +58747:34516, +58748:34526, +58749:34537, +58750:34540, +58752:34527, +58753:34523, +58754:34543, +58755:34578, +58756:34566, +58757:34568, +58758:34560, +58759:34563, +58760:34555, +58761:34577, +58762:34569, +58763:34573, +58764:34553, +58765:34570, +58766:34612, +58767:34623, +58768:34615, +58769:34619, +58770:34597, +58771:34601, +58772:34586, +58773:34656, +58774:34655, +58775:34680, +58776:34636, +58777:34638, +58778:34676, +58779:34647, +58780:34664, +58781:34670, +58782:34649, +58783:34643, +58784:34659, +58785:34666, +58786:34821, +58787:34722, +58788:34719, +58789:34690, +58790:34735, +58791:34763, +58792:34749, +58793:34752, +58794:34768, +58795:38614, +58796:34731, +58797:34756, +58798:34739, +58799:34759, +58800:34758, +58801:34747, +58802:34799, +58803:34802, +58804:34784, +58805:34831, +58806:34829, +58807:34814, +58808:34806, +58809:34807, +58810:34830, +58811:34770, +58812:34833, +58813:34838, +58814:34837, +58815:34850, +58816:34849, +58817:34865, +58818:34870, +58819:34873, +58820:34855, +58821:34875, +58822:34884, +58823:34882, +58824:34898, +58825:34905, +58826:34910, +58827:34914, +58828:34923, +58829:34945, +58830:34942, +58831:34974, +58832:34933, +58833:34941, +58834:34997, +58835:34930, +58836:34946, +58837:34967, +58838:34962, +58839:34990, +58840:34969, +58841:34978, +58842:34957, +58843:34980, +58844:34992, +58845:35007, +58846:34993, +58847:35011, +58848:35012, +58849:35028, +58850:35032, +58851:35033, +58852:35037, +58853:35065, +58854:35074, +58855:35068, +58856:35060, +58857:35048, +58858:35058, +58859:35076, +58860:35084, +58861:35082, +58862:35091, +58863:35139, +58864:35102, +58865:35109, +58866:35114, +58867:35115, +58868:35137, +58869:35140, +58870:35131, +58871:35126, +58872:35128, +58873:35148, +58874:35101, +58875:35168, +58876:35166, +58944:35174, +58945:35172, +58946:35181, +58947:35178, +58948:35183, +58949:35188, +58950:35191, +58951:35198, +58952:35203, +58953:35208, +58954:35210, +58955:35219, +58956:35224, +58957:35233, +58958:35241, +58959:35238, +58960:35244, +58961:35247, +58962:35250, +58963:35258, +58964:35261, +58965:35263, +58966:35264, +58967:35290, +58968:35292, +58969:35293, +58970:35303, +58971:35316, +58972:35320, +58973:35331, +58974:35350, +58975:35344, +58976:35340, +58977:35355, +58978:35357, +58979:35365, +58980:35382, +58981:35393, +58982:35419, +58983:35410, +58984:35398, +58985:35400, +58986:35452, +58987:35437, +58988:35436, +58989:35426, +58990:35461, +58991:35458, +58992:35460, +58993:35496, +58994:35489, +58995:35473, +58996:35493, +58997:35494, +58998:35482, +58999:35491, +59000:35524, +59001:35533, +59002:35522, +59003:35546, +59004:35563, +59005:35571, +59006:35559, +59008:35556, +59009:35569, +59010:35604, +59011:35552, +59012:35554, +59013:35575, +59014:35550, +59015:35547, +59016:35596, +59017:35591, +59018:35610, +59019:35553, +59020:35606, +59021:35600, +59022:35607, +59023:35616, +59024:35635, +59025:38827, +59026:35622, +59027:35627, +59028:35646, +59029:35624, +59030:35649, +59031:35660, +59032:35663, +59033:35662, +59034:35657, +59035:35670, +59036:35675, +59037:35674, +59038:35691, +59039:35679, +59040:35692, +59041:35695, +59042:35700, +59043:35709, +59044:35712, +59045:35724, +59046:35726, +59047:35730, +59048:35731, +59049:35734, +59050:35737, +59051:35738, +59052:35898, +59053:35905, +59054:35903, +59055:35912, +59056:35916, +59057:35918, +59058:35920, +59059:35925, +59060:35938, +59061:35948, +59062:35960, +59063:35962, +59064:35970, +59065:35977, +59066:35973, +59067:35978, +59068:35981, +59069:35982, +59070:35988, +59071:35964, +59072:35992, +59073:25117, +59074:36013, +59075:36010, +59076:36029, +59077:36018, +59078:36019, +59079:36014, +59080:36022, +59081:36040, +59082:36033, +59083:36068, +59084:36067, +59085:36058, +59086:36093, +59087:36090, +59088:36091, +59089:36100, +59090:36101, +59091:36106, +59092:36103, +59093:36111, +59094:36109, +59095:36112, +59096:40782, +59097:36115, +59098:36045, +59099:36116, +59100:36118, +59101:36199, +59102:36205, +59103:36209, +59104:36211, +59105:36225, +59106:36249, +59107:36290, +59108:36286, +59109:36282, +59110:36303, +59111:36314, +59112:36310, +59113:36300, +59114:36315, +59115:36299, +59116:36330, +59117:36331, +59118:36319, +59119:36323, +59120:36348, +59121:36360, +59122:36361, +59123:36351, +59124:36381, +59125:36382, +59126:36368, +59127:36383, +59128:36418, +59129:36405, +59130:36400, +59131:36404, +59132:36426, +59200:36423, +59201:36425, +59202:36428, +59203:36432, +59204:36424, +59205:36441, +59206:36452, +59207:36448, +59208:36394, +59209:36451, +59210:36437, +59211:36470, +59212:36466, +59213:36476, +59214:36481, +59215:36487, +59216:36485, +59217:36484, +59218:36491, +59219:36490, +59220:36499, +59221:36497, +59222:36500, +59223:36505, +59224:36522, +59225:36513, +59226:36524, +59227:36528, +59228:36550, +59229:36529, +59230:36542, +59231:36549, +59232:36552, +59233:36555, +59234:36571, +59235:36579, +59236:36604, +59237:36603, +59238:36587, +59239:36606, +59240:36618, +59241:36613, +59242:36629, +59243:36626, +59244:36633, +59245:36627, +59246:36636, +59247:36639, +59248:36635, +59249:36620, +59250:36646, +59251:36659, +59252:36667, +59253:36665, +59254:36677, +59255:36674, +59256:36670, +59257:36684, +59258:36681, +59259:36678, +59260:36686, +59261:36695, +59262:36700, +59264:36706, +59265:36707, +59266:36708, +59267:36764, +59268:36767, +59269:36771, +59270:36781, +59271:36783, +59272:36791, +59273:36826, +59274:36837, +59275:36834, +59276:36842, +59277:36847, +59278:36999, +59279:36852, +59280:36869, +59281:36857, +59282:36858, +59283:36881, +59284:36885, +59285:36897, +59286:36877, +59287:36894, +59288:36886, +59289:36875, +59290:36903, +59291:36918, +59292:36917, +59293:36921, +59294:36856, +59295:36943, +59296:36944, +59297:36945, +59298:36946, +59299:36878, +59300:36937, +59301:36926, +59302:36950, +59303:36952, +59304:36958, +59305:36968, +59306:36975, +59307:36982, +59308:38568, +59309:36978, +59310:36994, +59311:36989, +59312:36993, +59313:36992, +59314:37002, +59315:37001, +59316:37007, +59317:37032, +59318:37039, +59319:37041, +59320:37045, +59321:37090, +59322:37092, +59323:25160, +59324:37083, +59325:37122, +59326:37138, +59327:37145, +59328:37170, +59329:37168, +59330:37194, +59331:37206, +59332:37208, +59333:37219, +59334:37221, +59335:37225, +59336:37235, +59337:37234, +59338:37259, +59339:37257, +59340:37250, +59341:37282, +59342:37291, +59343:37295, +59344:37290, +59345:37301, +59346:37300, +59347:37306, +59348:37312, +59349:37313, +59350:37321, +59351:37323, +59352:37328, +59353:37334, +59354:37343, +59355:37345, +59356:37339, +59357:37372, +59358:37365, +59359:37366, +59360:37406, +59361:37375, +59362:37396, +59363:37420, +59364:37397, +59365:37393, +59366:37470, +59367:37463, +59368:37445, +59369:37449, +59370:37476, +59371:37448, +59372:37525, +59373:37439, +59374:37451, +59375:37456, +59376:37532, +59377:37526, +59378:37523, +59379:37531, +59380:37466, +59381:37583, +59382:37561, +59383:37559, +59384:37609, +59385:37647, +59386:37626, +59387:37700, +59388:37678, +59456:37657, +59457:37666, +59458:37658, +59459:37667, +59460:37690, +59461:37685, +59462:37691, +59463:37724, +59464:37728, +59465:37756, +59466:37742, +59467:37718, +59468:37808, +59469:37804, +59470:37805, +59471:37780, +59472:37817, +59473:37846, +59474:37847, +59475:37864, +59476:37861, +59477:37848, +59478:37827, +59479:37853, +59480:37840, +59481:37832, +59482:37860, +59483:37914, +59484:37908, +59485:37907, +59486:37891, +59487:37895, +59488:37904, +59489:37942, +59490:37931, +59491:37941, +59492:37921, +59493:37946, +59494:37953, +59495:37970, +59496:37956, +59497:37979, +59498:37984, +59499:37986, +59500:37982, +59501:37994, +59502:37417, +59503:38000, +59504:38005, +59505:38007, +59506:38013, +59507:37978, +59508:38012, +59509:38014, +59510:38017, +59511:38015, +59512:38274, +59513:38279, +59514:38282, +59515:38292, +59516:38294, +59517:38296, +59518:38297, +59520:38304, +59521:38312, +59522:38311, +59523:38317, +59524:38332, +59525:38331, +59526:38329, +59527:38334, +59528:38346, +59529:28662, +59530:38339, +59531:38349, +59532:38348, +59533:38357, +59534:38356, +59535:38358, +59536:38364, +59537:38369, +59538:38373, +59539:38370, +59540:38433, +59541:38440, +59542:38446, +59543:38447, +59544:38466, +59545:38476, +59546:38479, +59547:38475, +59548:38519, +59549:38492, +59550:38494, +59551:38493, +59552:38495, +59553:38502, +59554:38514, +59555:38508, +59556:38541, +59557:38552, +59558:38549, +59559:38551, +59560:38570, +59561:38567, +59562:38577, +59563:38578, +59564:38576, +59565:38580, +59566:38582, +59567:38584, +59568:38585, +59569:38606, +59570:38603, +59571:38601, +59572:38605, +59573:35149, +59574:38620, +59575:38669, +59576:38613, +59577:38649, +59578:38660, +59579:38662, +59580:38664, +59581:38675, +59582:38670, +59583:38673, +59584:38671, +59585:38678, +59586:38681, +59587:38692, +59588:38698, +59589:38704, +59590:38713, +59591:38717, +59592:38718, +59593:38724, +59594:38726, +59595:38728, +59596:38722, +59597:38729, +59598:38748, +59599:38752, +59600:38756, +59601:38758, +59602:38760, +59603:21202, +59604:38763, +59605:38769, +59606:38777, +59607:38789, +59608:38780, +59609:38785, +59610:38778, +59611:38790, +59612:38795, +59613:38799, +59614:38800, +59615:38812, +59616:38824, +59617:38822, +59618:38819, +59619:38835, +59620:38836, +59621:38851, +59622:38854, +59623:38856, +59624:38859, +59625:38876, +59626:38893, +59627:40783, +59628:38898, +59629:31455, +59630:38902, +59631:38901, +59632:38927, +59633:38924, +59634:38968, +59635:38948, +59636:38945, +59637:38967, +59638:38973, +59639:38982, +59640:38991, +59641:38987, +59642:39019, +59643:39023, +59644:39024, +59712:39025, +59713:39028, +59714:39027, +59715:39082, +59716:39087, +59717:39089, +59718:39094, +59719:39108, +59720:39107, +59721:39110, +59722:39145, +59723:39147, +59724:39171, +59725:39177, +59726:39186, +59727:39188, +59728:39192, +59729:39201, +59730:39197, +59731:39198, +59732:39204, +59733:39200, +59734:39212, +59735:39214, +59736:39229, +59737:39230, +59738:39234, +59739:39241, +59740:39237, +59741:39248, +59742:39243, +59743:39249, +59744:39250, +59745:39244, +59746:39253, +59747:39319, +59748:39320, +59749:39333, +59750:39341, +59751:39342, +59752:39356, +59753:39391, +59754:39387, +59755:39389, +59756:39384, +59757:39377, +59758:39405, +59759:39406, +59760:39409, +59761:39410, +59762:39419, +59763:39416, +59764:39425, +59765:39439, +59766:39429, +59767:39394, +59768:39449, +59769:39467, +59770:39479, +59771:39493, +59772:39490, +59773:39488, +59774:39491, +59776:39486, +59777:39509, +59778:39501, +59779:39515, +59780:39511, +59781:39519, +59782:39522, +59783:39525, +59784:39524, +59785:39529, +59786:39531, +59787:39530, +59788:39597, +59789:39600, +59790:39612, +59791:39616, +59792:39631, +59793:39633, +59794:39635, +59795:39636, +59796:39646, +59797:39647, +59798:39650, +59799:39651, +59800:39654, +59801:39663, +59802:39659, +59803:39662, +59804:39668, +59805:39665, +59806:39671, +59807:39675, +59808:39686, +59809:39704, +59810:39706, +59811:39711, +59812:39714, +59813:39715, +59814:39717, +59815:39719, +59816:39720, +59817:39721, +59818:39722, +59819:39726, +59820:39727, +59821:39730, +59822:39748, +59823:39747, +59824:39759, +59825:39757, +59826:39758, +59827:39761, +59828:39768, +59829:39796, +59830:39827, +59831:39811, +59832:39825, +59833:39830, +59834:39831, +59835:39839, +59836:39840, +59837:39848, +59838:39860, +59839:39872, +59840:39882, +59841:39865, +59842:39878, +59843:39887, +59844:39889, +59845:39890, +59846:39907, +59847:39906, +59848:39908, +59849:39892, +59850:39905, +59851:39994, +59852:39922, +59853:39921, +59854:39920, +59855:39957, +59856:39956, +59857:39945, +59858:39955, +59859:39948, +59860:39942, +59861:39944, +59862:39954, +59863:39946, +59864:39940, +59865:39982, +59866:39963, +59867:39973, +59868:39972, +59869:39969, +59870:39984, +59871:40007, +59872:39986, +59873:40006, +59874:39998, +59875:40026, +59876:40032, +59877:40039, +59878:40054, +59879:40056, +59880:40167, +59881:40172, +59882:40176, +59883:40201, +59884:40200, +59885:40171, +59886:40195, +59887:40198, +59888:40234, +59889:40230, +59890:40367, +59891:40227, +59892:40223, +59893:40260, +59894:40213, +59895:40210, +59896:40257, +59897:40255, +59898:40254, +59899:40262, +59900:40264, +59968:40285, +59969:40286, +59970:40292, +59971:40273, +59972:40272, +59973:40281, +59974:40306, +59975:40329, +59976:40327, +59977:40363, +59978:40303, +59979:40314, +59980:40346, +59981:40356, +59982:40361, +59983:40370, +59984:40388, +59985:40385, +59986:40379, +59987:40376, +59988:40378, +59989:40390, +59990:40399, +59991:40386, +59992:40409, +59993:40403, +59994:40440, +59995:40422, +59996:40429, +59997:40431, +59998:40445, +59999:40474, +60000:40475, +60001:40478, +60002:40565, +60003:40569, +60004:40573, +60005:40577, +60006:40584, +60007:40587, +60008:40588, +60009:40594, +60010:40597, +60011:40593, +60012:40605, +60013:40613, +60014:40617, +60015:40632, +60016:40618, +60017:40621, +60018:38753, +60019:40652, +60020:40654, +60021:40655, +60022:40656, +60023:40660, +60024:40668, +60025:40670, +60026:40669, +60027:40672, +60028:40677, +60029:40680, +60030:40687, +60032:40692, +60033:40694, +60034:40695, +60035:40697, +60036:40699, +60037:40700, +60038:40701, +60039:40711, +60040:40712, +60041:30391, +60042:40725, +60043:40737, +60044:40748, +60045:40766, +60046:40778, +60047:40786, +60048:40788, +60049:40803, +60050:40799, +60051:40800, +60052:40801, +60053:40806, +60054:40807, +60055:40812, +60056:40810, +60057:40823, +60058:40818, +60059:40822, +60060:40853, +60061:40860, +60062:40864, +60063:22575, +60064:27079, +60065:36953, +60066:29796, +60067:20956, +60068:29081, +60736:32394, +60737:35100, +60738:37704, +60739:37512, +60740:34012, +60741:20425, +60742:28859, +60743:26161, +60744:26824, +60745:37625, +60746:26363, +60747:24389, +60748:20008, +60749:20193, +60750:20220, +60751:20224, +60752:20227, +60753:20281, +60754:20310, +60755:20370, +60756:20362, +60757:20378, +60758:20372, +60759:20429, +60760:20544, +60761:20514, +60762:20479, +60763:20510, +60764:20550, +60765:20592, +60766:20546, +60767:20628, +60768:20724, +60769:20696, +60770:20810, +60771:20836, +60772:20893, +60773:20926, +60774:20972, +60775:21013, +60776:21148, +60777:21158, +60778:21184, +60779:21211, +60780:21248, +60781:21255, +60782:21284, +60783:21362, +60784:21395, +60785:21426, +60786:21469, +60787:64014, +60788:21660, +60789:21642, +60790:21673, +60791:21759, +60792:21894, +60793:22361, +60794:22373, +60795:22444, +60796:22472, +60797:22471, +60798:64015, +60800:64016, +60801:22686, +60802:22706, +60803:22795, +60804:22867, +60805:22875, +60806:22877, +60807:22883, +60808:22948, +60809:22970, +60810:23382, +60811:23488, +60812:29999, +60813:23512, +60814:23532, +60815:23582, +60816:23718, +60817:23738, +60818:23797, +60819:23847, +60820:23891, +60821:64017, +60822:23874, +60823:23917, +60824:23992, +60825:23993, +60826:24016, +60827:24353, +60828:24372, +60829:24423, +60830:24503, +60831:24542, +60832:24669, +60833:24709, +60834:24714, +60835:24798, +60836:24789, +60837:24864, +60838:24818, +60839:24849, +60840:24887, +60841:24880, +60842:24984, +60843:25107, +60844:25254, +60845:25589, +60846:25696, +60847:25757, +60848:25806, +60849:25934, +60850:26112, +60851:26133, +60852:26171, +60853:26121, +60854:26158, +60855:26142, +60856:26148, +60857:26213, +60858:26199, +60859:26201, +60860:64018, +60861:26227, +60862:26265, +60863:26272, +60864:26290, +60865:26303, +60866:26362, +60867:26382, +60868:63785, +60869:26470, +60870:26555, +60871:26706, +60872:26560, +60873:26625, +60874:26692, +60875:26831, +60876:64019, +60877:26984, +60878:64020, +60879:27032, +60880:27106, +60881:27184, +60882:27243, +60883:27206, +60884:27251, +60885:27262, +60886:27362, +60887:27364, +60888:27606, +60889:27711, +60890:27740, +60891:27782, +60892:27759, +60893:27866, +60894:27908, +60895:28039, +60896:28015, +60897:28054, +60898:28076, +60899:28111, +60900:28152, +60901:28146, +60902:28156, +60903:28217, +60904:28252, +60905:28199, +60906:28220, +60907:28351, +60908:28552, +60909:28597, +60910:28661, +60911:28677, +60912:28679, +60913:28712, +60914:28805, +60915:28843, +60916:28943, +60917:28932, +60918:29020, +60919:28998, +60920:28999, +60921:64021, +60922:29121, +60923:29182, +60924:29361, +60992:29374, +60993:29476, +60994:64022, +60995:29559, +60996:29629, +60997:29641, +60998:29654, +60999:29667, +61000:29650, +61001:29703, +61002:29685, +61003:29734, +61004:29738, +61005:29737, +61006:29742, +61007:29794, +61008:29833, +61009:29855, +61010:29953, +61011:30063, +61012:30338, +61013:30364, +61014:30366, +61015:30363, +61016:30374, +61017:64023, +61018:30534, +61019:21167, +61020:30753, +61021:30798, +61022:30820, +61023:30842, +61024:31024, +61025:64024, +61026:64025, +61027:64026, +61028:31124, +61029:64027, +61030:31131, +61031:31441, +61032:31463, +61033:64028, +61034:31467, +61035:31646, +61036:64029, +61037:32072, +61038:32092, +61039:32183, +61040:32160, +61041:32214, +61042:32338, +61043:32583, +61044:32673, +61045:64030, +61046:33537, +61047:33634, +61048:33663, +61049:33735, +61050:33782, +61051:33864, +61052:33972, +61053:34131, +61054:34137, +61056:34155, +61057:64031, +61058:34224, +61059:64032, +61060:64033, +61061:34823, +61062:35061, +61063:35346, +61064:35383, +61065:35449, +61066:35495, +61067:35518, +61068:35551, +61069:64034, +61070:35574, +61071:35667, +61072:35711, +61073:36080, +61074:36084, +61075:36114, +61076:36214, +61077:64035, +61078:36559, +61079:64036, +61080:64037, +61081:36967, +61082:37086, +61083:64038, +61084:37141, +61085:37159, +61086:37338, +61087:37335, +61088:37342, +61089:37357, +61090:37358, +61091:37348, +61092:37349, +61093:37382, +61094:37392, +61095:37386, +61096:37434, +61097:37440, +61098:37436, +61099:37454, +61100:37465, +61101:37457, +61102:37433, +61103:37479, +61104:37543, +61105:37495, +61106:37496, +61107:37607, +61108:37591, +61109:37593, +61110:37584, +61111:64039, +61112:37589, +61113:37600, +61114:37587, +61115:37669, +61116:37665, +61117:37627, +61118:64040, +61119:37662, +61120:37631, +61121:37661, +61122:37634, +61123:37744, +61124:37719, +61125:37796, +61126:37830, +61127:37854, +61128:37880, +61129:37937, +61130:37957, +61131:37960, +61132:38290, +61133:63964, +61134:64041, +61135:38557, +61136:38575, +61137:38707, +61138:38715, +61139:38723, +61140:38733, +61141:38735, +61142:38737, +61143:38741, +61144:38999, +61145:39013, +61146:64042, +61147:64043, +61148:39207, +61149:64044, +61150:39326, +61151:39502, +61152:39641, +61153:39644, +61154:39797, +61155:39794, +61156:39823, +61157:39857, +61158:39867, +61159:39936, +61160:40304, +61161:40299, +61162:64045, +61163:40473, +61164:40657, +61167:8560, +61168:8561, +61169:8562, +61170:8563, +61171:8564, +61172:8565, +61173:8566, +61174:8567, +61175:8568, +61176:8569, +61177:65506, +61178:65508, +61179:65287, +61180:65282, +61504:57344, +61505:57345, +61506:57346, +61507:57347, +61508:57348, +61509:57349, +61510:57350, +61511:57351, +61512:57352, +61513:57353, +61514:57354, +61515:57355, +61516:57356, +61517:57357, +61518:57358, +61519:57359, +61520:57360, +61521:57361, +61522:57362, +61523:57363, +61524:57364, +61525:57365, +61526:57366, +61527:57367, +61528:57368, +61529:57369, +61530:57370, +61531:57371, +61532:57372, +61533:57373, +61534:57374, +61535:57375, +61536:57376, +61537:57377, +61538:57378, +61539:57379, +61540:57380, +61541:57381, +61542:57382, +61543:57383, +61544:57384, +61545:57385, +61546:57386, +61547:57387, +61548:57388, +61549:57389, +61550:57390, +61551:57391, +61552:57392, +61553:57393, +61554:57394, +61555:57395, +61556:57396, +61557:57397, +61558:57398, +61559:57399, +61560:57400, +61561:57401, +61562:57402, +61563:57403, +61564:57404, +61565:57405, +61566:57406, +61568:57407, +61569:57408, +61570:57409, +61571:57410, +61572:57411, +61573:57412, +61574:57413, +61575:57414, +61576:57415, +61577:57416, +61578:57417, +61579:57418, +61580:57419, +61581:57420, +61582:57421, +61583:57422, +61584:57423, +61585:57424, +61586:57425, +61587:57426, +61588:57427, +61589:57428, +61590:57429, +61591:57430, +61592:57431, +61593:57432, +61594:57433, +61595:57434, +61596:57435, +61597:57436, +61598:57437, +61599:57438, +61600:57439, +61601:57440, +61602:57441, +61603:57442, +61604:57443, +61605:57444, +61606:57445, +61607:57446, +61608:57447, +61609:57448, +61610:57449, +61611:57450, +61612:57451, +61613:57452, +61614:57453, +61615:57454, +61616:57455, +61617:57456, +61618:57457, +61619:57458, +61620:57459, +61621:57460, +61622:57461, +61623:57462, +61624:57463, +61625:57464, +61626:57465, +61627:57466, +61628:57467, +61629:57468, +61630:57469, +61631:57470, +61632:57471, +61633:57472, +61634:57473, +61635:57474, +61636:57475, +61637:57476, +61638:57477, +61639:57478, +61640:57479, +61641:57480, +61642:57481, +61643:57482, +61644:57483, +61645:57484, +61646:57485, +61647:57486, +61648:57487, +61649:57488, +61650:57489, +61651:57490, +61652:57491, +61653:57492, +61654:57493, +61655:57494, +61656:57495, +61657:57496, +61658:57497, +61659:57498, +61660:57499, +61661:57500, +61662:57501, +61663:57502, +61664:57503, +61665:57504, +61666:57505, +61667:57506, +61668:57507, +61669:57508, +61670:57509, +61671:57510, +61672:57511, +61673:57512, +61674:57513, +61675:57514, +61676:57515, +61677:57516, +61678:57517, +61679:57518, +61680:57519, +61681:57520, +61682:57521, +61683:57522, +61684:57523, +61685:57524, +61686:57525, +61687:57526, +61688:57527, +61689:57528, +61690:57529, +61691:57530, +61692:57531, +61760:57532, +61761:57533, +61762:57534, +61763:57535, +61764:57536, +61765:57537, +61766:57538, +61767:57539, +61768:57540, +61769:57541, +61770:57542, +61771:57543, +61772:57544, +61773:57545, +61774:57546, +61775:57547, +61776:57548, +61777:57549, +61778:57550, +61779:57551, +61780:57552, +61781:57553, +61782:57554, +61783:57555, +61784:57556, +61785:57557, +61786:57558, +61787:57559, +61788:57560, +61789:57561, +61790:57562, +61791:57563, +61792:57564, +61793:57565, +61794:57566, +61795:57567, +61796:57568, +61797:57569, +61798:57570, +61799:57571, +61800:57572, +61801:57573, +61802:57574, +61803:57575, +61804:57576, +61805:57577, +61806:57578, +61807:57579, +61808:57580, +61809:57581, +61810:57582, +61811:57583, +61812:57584, +61813:57585, +61814:57586, +61815:57587, +61816:57588, +61817:57589, +61818:57590, +61819:57591, +61820:57592, +61821:57593, +61822:57594, +61824:57595, +61825:57596, +61826:57597, +61827:57598, +61828:57599, +61829:57600, +61830:57601, +61831:57602, +61832:57603, +61833:57604, +61834:57605, +61835:57606, +61836:57607, +61837:57608, +61838:57609, +61839:57610, +61840:57611, +61841:57612, +61842:57613, +61843:57614, +61844:57615, +61845:57616, +61846:57617, +61847:57618, +61848:57619, +61849:57620, +61850:57621, +61851:57622, +61852:57623, +61853:57624, +61854:57625, +61855:57626, +61856:57627, +61857:57628, +61858:57629, +61859:57630, +61860:57631, +61861:57632, +61862:57633, +61863:57634, +61864:57635, +61865:57636, +61866:57637, +61867:57638, +61868:57639, +61869:57640, +61870:57641, +61871:57642, +61872:57643, +61873:57644, +61874:57645, +61875:57646, +61876:57647, +61877:57648, +61878:57649, +61879:57650, +61880:57651, +61881:57652, +61882:57653, +61883:57654, +61884:57655, +61885:57656, +61886:57657, +61887:57658, +61888:57659, +61889:57660, +61890:57661, +61891:57662, +61892:57663, +61893:57664, +61894:57665, +61895:57666, +61896:57667, +61897:57668, +61898:57669, +61899:57670, +61900:57671, +61901:57672, +61902:57673, +61903:57674, +61904:57675, +61905:57676, +61906:57677, +61907:57678, +61908:57679, +61909:57680, +61910:57681, +61911:57682, +61912:57683, +61913:57684, +61914:57685, +61915:57686, +61916:57687, +61917:57688, +61918:57689, +61919:57690, +61920:57691, +61921:57692, +61922:57693, +61923:57694, +61924:57695, +61925:57696, +61926:57697, +61927:57698, +61928:57699, +61929:57700, +61930:57701, +61931:57702, +61932:57703, +61933:57704, +61934:57705, +61935:57706, +61936:57707, +61937:57708, +61938:57709, +61939:57710, +61940:57711, +61941:57712, +61942:57713, +61943:57714, +61944:57715, +61945:57716, +61946:57717, +61947:57718, +61948:57719, +62016:57720, +62017:57721, +62018:57722, +62019:57723, +62020:57724, +62021:57725, +62022:57726, +62023:57727, +62024:57728, +62025:57729, +62026:57730, +62027:57731, +62028:57732, +62029:57733, +62030:57734, +62031:57735, +62032:57736, +62033:57737, +62034:57738, +62035:57739, +62036:57740, +62037:57741, +62038:57742, +62039:57743, +62040:57744, +62041:57745, +62042:57746, +62043:57747, +62044:57748, +62045:57749, +62046:57750, +62047:57751, +62048:57752, +62049:57753, +62050:57754, +62051:57755, +62052:57756, +62053:57757, +62054:57758, +62055:57759, +62056:57760, +62057:57761, +62058:57762, +62059:57763, +62060:57764, +62061:57765, +62062:57766, +62063:57767, +62064:57768, +62065:57769, +62066:57770, +62067:57771, +62068:57772, +62069:57773, +62070:57774, +62071:57775, +62072:57776, +62073:57777, +62074:57778, +62075:57779, +62076:57780, +62077:57781, +62078:57782, +62080:57783, +62081:57784, +62082:57785, +62083:57786, +62084:57787, +62085:57788, +62086:57789, +62087:57790, +62088:57791, +62089:57792, +62090:57793, +62091:57794, +62092:57795, +62093:57796, +62094:57797, +62095:57798, +62096:57799, +62097:57800, +62098:57801, +62099:57802, +62100:57803, +62101:57804, +62102:57805, +62103:57806, +62104:57807, +62105:57808, +62106:57809, +62107:57810, +62108:57811, +62109:57812, +62110:57813, +62111:57814, +62112:57815, +62113:57816, +62114:57817, +62115:57818, +62116:57819, +62117:57820, +62118:57821, +62119:57822, +62120:57823, +62121:57824, +62122:57825, +62123:57826, +62124:57827, +62125:57828, +62126:57829, +62127:57830, +62128:57831, +62129:57832, +62130:57833, +62131:57834, +62132:57835, +62133:57836, +62134:57837, +62135:57838, +62136:57839, +62137:57840, +62138:57841, +62139:57842, +62140:57843, +62141:57844, +62142:57845, +62143:57846, +62144:57847, +62145:57848, +62146:57849, +62147:57850, +62148:57851, +62149:57852, +62150:57853, +62151:57854, +62152:57855, +62153:57856, +62154:57857, +62155:57858, +62156:57859, +62157:57860, +62158:57861, +62159:57862, +62160:57863, +62161:57864, +62162:57865, +62163:57866, +62164:57867, +62165:57868, +62166:57869, +62167:57870, +62168:57871, +62169:57872, +62170:57873, +62171:57874, +62172:57875, +62173:57876, +62174:57877, +62175:57878, +62176:57879, +62177:57880, +62178:57881, +62179:57882, +62180:57883, +62181:57884, +62182:57885, +62183:57886, +62184:57887, +62185:57888, +62186:57889, +62187:57890, +62188:57891, +62189:57892, +62190:57893, +62191:57894, +62192:57895, +62193:57896, +62194:57897, +62195:57898, +62196:57899, +62197:57900, +62198:57901, +62199:57902, +62200:57903, +62201:57904, +62202:57905, +62203:57906, +62204:57907, +62272:57908, +62273:57909, +62274:57910, +62275:57911, +62276:57912, +62277:57913, +62278:57914, +62279:57915, +62280:57916, +62281:57917, +62282:57918, +62283:57919, +62284:57920, +62285:57921, +62286:57922, +62287:57923, +62288:57924, +62289:57925, +62290:57926, +62291:57927, +62292:57928, +62293:57929, +62294:57930, +62295:57931, +62296:57932, +62297:57933, +62298:57934, +62299:57935, +62300:57936, +62301:57937, +62302:57938, +62303:57939, +62304:57940, +62305:57941, +62306:57942, +62307:57943, +62308:57944, +62309:57945, +62310:57946, +62311:57947, +62312:57948, +62313:57949, +62314:57950, +62315:57951, +62316:57952, +62317:57953, +62318:57954, +62319:57955, +62320:57956, +62321:57957, +62322:57958, +62323:57959, +62324:57960, +62325:57961, +62326:57962, +62327:57963, +62328:57964, +62329:57965, +62330:57966, +62331:57967, +62332:57968, +62333:57969, +62334:57970, +62336:57971, +62337:57972, +62338:57973, +62339:57974, +62340:57975, +62341:57976, +62342:57977, +62343:57978, +62344:57979, +62345:57980, +62346:57981, +62347:57982, +62348:57983, +62349:57984, +62350:57985, +62351:57986, +62352:57987, +62353:57988, +62354:57989, +62355:57990, +62356:57991, +62357:57992, +62358:57993, +62359:57994, +62360:57995, +62361:57996, +62362:57997, +62363:57998, +62364:57999, +62365:58000, +62366:58001, +62367:58002, +62368:58003, +62369:58004, +62370:58005, +62371:58006, +62372:58007, +62373:58008, +62374:58009, +62375:58010, +62376:58011, +62377:58012, +62378:58013, +62379:58014, +62380:58015, +62381:58016, +62382:58017, +62383:58018, +62384:58019, +62385:58020, +62386:58021, +62387:58022, +62388:58023, +62389:58024, +62390:58025, +62391:58026, +62392:58027, +62393:58028, +62394:58029, +62395:58030, +62396:58031, +62397:58032, +62398:58033, +62399:58034, +62400:58035, +62401:58036, +62402:58037, +62403:58038, +62404:58039, +62405:58040, +62406:58041, +62407:58042, +62408:58043, +62409:58044, +62410:58045, +62411:58046, +62412:58047, +62413:58048, +62414:58049, +62415:58050, +62416:58051, +62417:58052, +62418:58053, +62419:58054, +62420:58055, +62421:58056, +62422:58057, +62423:58058, +62424:58059, +62425:58060, +62426:58061, +62427:58062, +62428:58063, +62429:58064, +62430:58065, +62431:58066, +62432:58067, +62433:58068, +62434:58069, +62435:58070, +62436:58071, +62437:58072, +62438:58073, +62439:58074, +62440:58075, +62441:58076, +62442:58077, +62443:58078, +62444:58079, +62445:58080, +62446:58081, +62447:58082, +62448:58083, +62449:58084, +62450:58085, +62451:58086, +62452:58087, +62453:58088, +62454:58089, +62455:58090, +62456:58091, +62457:58092, +62458:58093, +62459:58094, +62460:58095, +62528:58096, +62529:58097, +62530:58098, +62531:58099, +62532:58100, +62533:58101, +62534:58102, +62535:58103, +62536:58104, +62537:58105, +62538:58106, +62539:58107, +62540:58108, +62541:58109, +62542:58110, +62543:58111, +62544:58112, +62545:58113, +62546:58114, +62547:58115, +62548:58116, +62549:58117, +62550:58118, +62551:58119, +62552:58120, +62553:58121, +62554:58122, +62555:58123, +62556:58124, +62557:58125, +62558:58126, +62559:58127, +62560:58128, +62561:58129, +62562:58130, +62563:58131, +62564:58132, +62565:58133, +62566:58134, +62567:58135, +62568:58136, +62569:58137, +62570:58138, +62571:58139, +62572:58140, +62573:58141, +62574:58142, +62575:58143, +62576:58144, +62577:58145, +62578:58146, +62579:58147, +62580:58148, +62581:58149, +62582:58150, +62583:58151, +62584:58152, +62585:58153, +62586:58154, +62587:58155, +62588:58156, +62589:58157, +62590:58158, +62592:58159, +62593:58160, +62594:58161, +62595:58162, +62596:58163, +62597:58164, +62598:58165, +62599:58166, +62600:58167, +62601:58168, +62602:58169, +62603:58170, +62604:58171, +62605:58172, +62606:58173, +62607:58174, +62608:58175, +62609:58176, +62610:58177, +62611:58178, +62612:58179, +62613:58180, +62614:58181, +62615:58182, +62616:58183, +62617:58184, +62618:58185, +62619:58186, +62620:58187, +62621:58188, +62622:58189, +62623:58190, +62624:58191, +62625:58192, +62626:58193, +62627:58194, +62628:58195, +62629:58196, +62630:58197, +62631:58198, +62632:58199, +62633:58200, +62634:58201, +62635:58202, +62636:58203, +62637:58204, +62638:58205, +62639:58206, +62640:58207, +62641:58208, +62642:58209, +62643:58210, +62644:58211, +62645:58212, +62646:58213, +62647:58214, +62648:58215, +62649:58216, +62650:58217, +62651:58218, +62652:58219, +62653:58220, +62654:58221, +62655:58222, +62656:58223, +62657:58224, +62658:58225, +62659:58226, +62660:58227, +62661:58228, +62662:58229, +62663:58230, +62664:58231, +62665:58232, +62666:58233, +62667:58234, +62668:58235, +62669:58236, +62670:58237, +62671:58238, +62672:58239, +62673:58240, +62674:58241, +62675:58242, +62676:58243, +62677:58244, +62678:58245, +62679:58246, +62680:58247, +62681:58248, +62682:58249, +62683:58250, +62684:58251, +62685:58252, +62686:58253, +62687:58254, +62688:58255, +62689:58256, +62690:58257, +62691:58258, +62692:58259, +62693:58260, +62694:58261, +62695:58262, +62696:58263, +62697:58264, +62698:58265, +62699:58266, +62700:58267, +62701:58268, +62702:58269, +62703:58270, +62704:58271, +62705:58272, +62706:58273, +62707:58274, +62708:58275, +62709:58276, +62710:58277, +62711:58278, +62712:58279, +62713:58280, +62714:58281, +62715:58282, +62716:58283, +62784:58284, +62785:58285, +62786:58286, +62787:58287, +62788:58288, +62789:58289, +62790:58290, +62791:58291, +62792:58292, +62793:58293, +62794:58294, +62795:58295, +62796:58296, +62797:58297, +62798:58298, +62799:58299, +62800:58300, +62801:58301, +62802:58302, +62803:58303, +62804:58304, +62805:58305, +62806:58306, +62807:58307, +62808:58308, +62809:58309, +62810:58310, +62811:58311, +62812:58312, +62813:58313, +62814:58314, +62815:58315, +62816:58316, +62817:58317, +62818:58318, +62819:58319, +62820:58320, +62821:58321, +62822:58322, +62823:58323, +62824:58324, +62825:58325, +62826:58326, +62827:58327, +62828:58328, +62829:58329, +62830:58330, +62831:58331, +62832:58332, +62833:58333, +62834:58334, +62835:58335, +62836:58336, +62837:58337, +62838:58338, +62839:58339, +62840:58340, +62841:58341, +62842:58342, +62843:58343, +62844:58344, +62845:58345, +62846:58346, +62848:58347, +62849:58348, +62850:58349, +62851:58350, +62852:58351, +62853:58352, +62854:58353, +62855:58354, +62856:58355, +62857:58356, +62858:58357, +62859:58358, +62860:58359, +62861:58360, +62862:58361, +62863:58362, +62864:58363, +62865:58364, +62866:58365, +62867:58366, +62868:58367, +62869:58368, +62870:58369, +62871:58370, +62872:58371, +62873:58372, +62874:58373, +62875:58374, +62876:58375, +62877:58376, +62878:58377, +62879:58378, +62880:58379, +62881:58380, +62882:58381, +62883:58382, +62884:58383, +62885:58384, +62886:58385, +62887:58386, +62888:58387, +62889:58388, +62890:58389, +62891:58390, +62892:58391, +62893:58392, +62894:58393, +62895:58394, +62896:58395, +62897:58396, +62898:58397, +62899:58398, +62900:58399, +62901:58400, +62902:58401, +62903:58402, +62904:58403, +62905:58404, +62906:58405, +62907:58406, +62908:58407, +62909:58408, +62910:58409, +62911:58410, +62912:58411, +62913:58412, +62914:58413, +62915:58414, +62916:58415, +62917:58416, +62918:58417, +62919:58418, +62920:58419, +62921:58420, +62922:58421, +62923:58422, +62924:58423, +62925:58424, +62926:58425, +62927:58426, +62928:58427, +62929:58428, +62930:58429, +62931:58430, +62932:58431, +62933:58432, +62934:58433, +62935:58434, +62936:58435, +62937:58436, +62938:58437, +62939:58438, +62940:58439, +62941:58440, +62942:58441, +62943:58442, +62944:58443, +62945:58444, +62946:58445, +62947:58446, +62948:58447, +62949:58448, +62950:58449, +62951:58450, +62952:58451, +62953:58452, +62954:58453, +62955:58454, +62956:58455, +62957:58456, +62958:58457, +62959:58458, +62960:58459, +62961:58460, +62962:58461, +62963:58462, +62964:58463, +62965:58464, +62966:58465, +62967:58466, +62968:58467, +62969:58468, +62970:58469, +62971:58470, +62972:58471, +63040:58472, +63041:58473, +63042:58474, +63043:58475, +63044:58476, +63045:58477, +63046:58478, +63047:58479, +63048:58480, +63049:58481, +63050:58482, +63051:58483, +63052:58484, +63053:58485, +63054:58486, +63055:58487, +63056:58488, +63057:58489, +63058:58490, +63059:58491, +63060:58492, +63061:58493, +63062:58494, +63063:58495, +63064:58496, +63065:58497, +63066:58498, +63067:58499, +63068:58500, +63069:58501, +63070:58502, +63071:58503, +63072:58504, +63073:58505, +63074:58506, +63075:58507, +63076:58508, +63077:58509, +63078:58510, +63079:58511, +63080:58512, +63081:58513, +63082:58514, +63083:58515, +63084:58516, +63085:58517, +63086:58518, +63087:58519, +63088:58520, +63089:58521, +63090:58522, +63091:58523, +63092:58524, +63093:58525, +63094:58526, +63095:58527, +63096:58528, +63097:58529, +63098:58530, +63099:58531, +63100:58532, +63101:58533, +63102:58534, +63104:58535, +63105:58536, +63106:58537, +63107:58538, +63108:58539, +63109:58540, +63110:58541, +63111:58542, +63112:58543, +63113:58544, +63114:58545, +63115:58546, +63116:58547, +63117:58548, +63118:58549, +63119:58550, +63120:58551, +63121:58552, +63122:58553, +63123:58554, +63124:58555, +63125:58556, +63126:58557, +63127:58558, +63128:58559, +63129:58560, +63130:58561, +63131:58562, +63132:58563, +63133:58564, +63134:58565, +63135:58566, +63136:58567, +63137:58568, +63138:58569, +63139:58570, +63140:58571, +63141:58572, +63142:58573, +63143:58574, +63144:58575, +63145:58576, +63146:58577, +63147:58578, +63148:58579, +63149:58580, +63150:58581, +63151:58582, +63152:58583, +63153:58584, +63154:58585, +63155:58586, +63156:58587, +63157:58588, +63158:58589, +63159:58590, +63160:58591, +63161:58592, +63162:58593, +63163:58594, +63164:58595, +63165:58596, +63166:58597, +63167:58598, +63168:58599, +63169:58600, +63170:58601, +63171:58602, +63172:58603, +63173:58604, +63174:58605, +63175:58606, +63176:58607, +63177:58608, +63178:58609, +63179:58610, +63180:58611, +63181:58612, +63182:58613, +63183:58614, +63184:58615, +63185:58616, +63186:58617, +63187:58618, +63188:58619, +63189:58620, +63190:58621, +63191:58622, +63192:58623, +63193:58624, +63194:58625, +63195:58626, +63196:58627, +63197:58628, +63198:58629, +63199:58630, +63200:58631, +63201:58632, +63202:58633, +63203:58634, +63204:58635, +63205:58636, +63206:58637, +63207:58638, +63208:58639, +63209:58640, +63210:58641, +63211:58642, +63212:58643, +63213:58644, +63214:58645, +63215:58646, +63216:58647, +63217:58648, +63218:58649, +63219:58650, +63220:58651, +63221:58652, +63222:58653, +63223:58654, +63224:58655, +63225:58656, +63226:58657, +63227:58658, +63228:58659, +63296:58660, +63297:58661, +63298:58662, +63299:58663, +63300:58664, +63301:58665, +63302:58666, +63303:58667, +63304:58668, +63305:58669, +63306:58670, +63307:58671, +63308:58672, +63309:58673, +63310:58674, +63311:58675, +63312:58676, +63313:58677, +63314:58678, +63315:58679, +63316:58680, +63317:58681, +63318:58682, +63319:58683, +63320:58684, +63321:58685, +63322:58686, +63323:58687, +63324:58688, +63325:58689, +63326:58690, +63327:58691, +63328:58692, +63329:58693, +63330:58694, +63331:58695, +63332:58696, +63333:58697, +63334:58698, +63335:58699, +63336:58700, +63337:58701, +63338:58702, +63339:58703, +63340:58704, +63341:58705, +63342:58706, +63343:58707, +63344:58708, +63345:58709, +63346:58710, +63347:58711, +63348:58712, +63349:58713, +63350:58714, +63351:58715, +63352:58716, +63353:58717, +63354:58718, +63355:58719, +63356:58720, +63357:58721, +63358:58722, +63360:58723, +63361:58724, +63362:58725, +63363:58726, +63364:58727, +63365:58728, +63366:58729, +63367:58730, +63368:58731, +63369:58732, +63370:58733, +63371:58734, +63372:58735, +63373:58736, +63374:58737, +63375:58738, +63376:58739, +63377:58740, +63378:58741, +63379:58742, +63380:58743, +63381:58744, +63382:58745, +63383:58746, +63384:58747, +63385:58748, +63386:58749, +63387:58750, +63388:58751, +63389:58752, +63390:58753, +63391:58754, +63392:58755, +63393:58756, +63394:58757, +63395:58758, +63396:58759, +63397:58760, +63398:58761, +63399:58762, +63400:58763, +63401:58764, +63402:58765, +63403:58766, +63404:58767, +63405:58768, +63406:58769, +63407:58770, +63408:58771, +63409:58772, +63410:58773, +63411:58774, +63412:58775, +63413:58776, +63414:58777, +63415:58778, +63416:58779, +63417:58780, +63418:58781, +63419:58782, +63420:58783, +63421:58784, +63422:58785, +63423:58786, +63424:58787, +63425:58788, +63426:58789, +63427:58790, +63428:58791, +63429:58792, +63430:58793, +63431:58794, +63432:58795, +63433:58796, +63434:58797, +63435:58798, +63436:58799, +63437:58800, +63438:58801, +63439:58802, +63440:58803, +63441:58804, +63442:58805, +63443:58806, +63444:58807, +63445:58808, +63446:58809, +63447:58810, +63448:58811, +63449:58812, +63450:58813, +63451:58814, +63452:58815, +63453:58816, +63454:58817, +63455:58818, +63456:58819, +63457:58820, +63458:58821, +63459:58822, +63460:58823, +63461:58824, +63462:58825, +63463:58826, +63464:58827, +63465:58828, +63466:58829, +63467:58830, +63468:58831, +63469:58832, +63470:58833, +63471:58834, +63472:58835, +63473:58836, +63474:58837, +63475:58838, +63476:58839, +63477:58840, +63478:58841, +63479:58842, +63480:58843, +63481:58844, +63482:58845, +63483:58846, +63484:58847, +63552:58848, +63553:58849, +63554:58850, +63555:58851, +63556:58852, +63557:58853, +63558:58854, +63559:58855, +63560:58856, +63561:58857, +63562:58858, +63563:58859, +63564:58860, +63565:58861, +63566:58862, +63567:58863, +63568:58864, +63569:58865, +63570:58866, +63571:58867, +63572:58868, +63573:58869, +63574:58870, +63575:58871, +63576:58872, +63577:58873, +63578:58874, +63579:58875, +63580:58876, +63581:58877, +63582:58878, +63583:58879, +63584:58880, +63585:58881, +63586:58882, +63587:58883, +63588:58884, +63589:58885, +63590:58886, +63591:58887, +63592:58888, +63593:58889, +63594:58890, +63595:58891, +63596:58892, +63597:58893, +63598:58894, +63599:58895, +63600:58896, +63601:58897, +63602:58898, +63603:58899, +63604:58900, +63605:58901, +63606:58902, +63607:58903, +63608:58904, +63609:58905, +63610:58906, +63611:58907, +63612:58908, +63613:58909, +63614:58910, +63616:58911, +63617:58912, +63618:58913, +63619:58914, +63620:58915, +63621:58916, +63622:58917, +63623:58918, +63624:58919, +63625:58920, +63626:58921, +63627:58922, +63628:58923, +63629:58924, +63630:58925, +63631:58926, +63632:58927, +63633:58928, +63634:58929, +63635:58930, +63636:58931, +63637:58932, +63638:58933, +63639:58934, +63640:58935, +63641:58936, +63642:58937, +63643:58938, +63644:58939, +63645:58940, +63646:58941, +63647:58942, +63648:58943, +63649:58944, +63650:58945, +63651:58946, +63652:58947, +63653:58948, +63654:58949, +63655:58950, +63656:58951, +63657:58952, +63658:58953, +63659:58954, +63660:58955, +63661:58956, +63662:58957, +63663:58958, +63664:58959, +63665:58960, +63666:58961, +63667:58962, +63668:58963, +63669:58964, +63670:58965, +63671:58966, +63672:58967, +63673:58968, +63674:58969, +63675:58970, +63676:58971, +63677:58972, +63678:58973, +63679:58974, +63680:58975, +63681:58976, +63682:58977, +63683:58978, +63684:58979, +63685:58980, +63686:58981, +63687:58982, +63688:58983, +63689:58984, +63690:58985, +63691:58986, +63692:58987, +63693:58988, +63694:58989, +63695:58990, +63696:58991, +63697:58992, +63698:58993, +63699:58994, +63700:58995, +63701:58996, +63702:58997, +63703:58998, +63704:58999, +63705:59000, +63706:59001, +63707:59002, +63708:59003, +63709:59004, +63710:59005, +63711:59006, +63712:59007, +63713:59008, +63714:59009, +63715:59010, +63716:59011, +63717:59012, +63718:59013, +63719:59014, +63720:59015, +63721:59016, +63722:59017, +63723:59018, +63724:59019, +63725:59020, +63726:59021, +63727:59022, +63728:59023, +63729:59024, +63730:59025, +63731:59026, +63732:59027, +63733:59028, +63734:59029, +63735:59030, +63736:59031, +63737:59032, +63738:59033, +63739:59034, +63740:59035, +64064:8560, +64065:8561, +64066:8562, +64067:8563, +64068:8564, +64069:8565, +64070:8566, +64071:8567, +64072:8568, +64073:8569, +64074:8544, +64075:8545, +64076:8546, +64077:8547, +64078:8548, +64079:8549, +64080:8550, +64081:8551, +64082:8552, +64083:8553, +64084:65506, +64085:65508, +64086:65287, +64087:65282, +64088:12849, +64089:8470, +64090:8481, +64091:8757, +64092:32394, +64093:35100, +64094:37704, +64095:37512, +64096:34012, +64097:20425, +64098:28859, +64099:26161, +64100:26824, +64101:37625, +64102:26363, +64103:24389, +64104:20008, +64105:20193, +64106:20220, +64107:20224, +64108:20227, +64109:20281, +64110:20310, +64111:20370, +64112:20362, +64113:20378, +64114:20372, +64115:20429, +64116:20544, +64117:20514, +64118:20479, +64119:20510, +64120:20550, +64121:20592, +64122:20546, +64123:20628, +64124:20724, +64125:20696, +64126:20810, +64128:20836, +64129:20893, +64130:20926, +64131:20972, +64132:21013, +64133:21148, +64134:21158, +64135:21184, +64136:21211, +64137:21248, +64138:21255, +64139:21284, +64140:21362, +64141:21395, +64142:21426, +64143:21469, +64144:64014, +64145:21660, +64146:21642, +64147:21673, +64148:21759, +64149:21894, +64150:22361, +64151:22373, +64152:22444, +64153:22472, +64154:22471, +64155:64015, +64156:64016, +64157:22686, +64158:22706, +64159:22795, +64160:22867, +64161:22875, +64162:22877, +64163:22883, +64164:22948, +64165:22970, +64166:23382, +64167:23488, +64168:29999, +64169:23512, +64170:23532, +64171:23582, +64172:23718, +64173:23738, +64174:23797, +64175:23847, +64176:23891, +64177:64017, +64178:23874, +64179:23917, +64180:23992, +64181:23993, +64182:24016, +64183:24353, +64184:24372, +64185:24423, +64186:24503, +64187:24542, +64188:24669, +64189:24709, +64190:24714, +64191:24798, +64192:24789, +64193:24864, +64194:24818, +64195:24849, +64196:24887, +64197:24880, +64198:24984, +64199:25107, +64200:25254, +64201:25589, +64202:25696, +64203:25757, +64204:25806, +64205:25934, +64206:26112, +64207:26133, +64208:26171, +64209:26121, +64210:26158, +64211:26142, +64212:26148, +64213:26213, +64214:26199, +64215:26201, +64216:64018, +64217:26227, +64218:26265, +64219:26272, +64220:26290, +64221:26303, +64222:26362, +64223:26382, +64224:63785, +64225:26470, +64226:26555, +64227:26706, +64228:26560, +64229:26625, +64230:26692, +64231:26831, +64232:64019, +64233:26984, +64234:64020, +64235:27032, +64236:27106, +64237:27184, +64238:27243, +64239:27206, +64240:27251, +64241:27262, +64242:27362, +64243:27364, +64244:27606, +64245:27711, +64246:27740, +64247:27782, +64248:27759, +64249:27866, +64250:27908, +64251:28039, +64252:28015, +64320:28054, +64321:28076, +64322:28111, +64323:28152, +64324:28146, +64325:28156, +64326:28217, +64327:28252, +64328:28199, +64329:28220, +64330:28351, +64331:28552, +64332:28597, +64333:28661, +64334:28677, +64335:28679, +64336:28712, +64337:28805, +64338:28843, +64339:28943, +64340:28932, +64341:29020, +64342:28998, +64343:28999, +64344:64021, +64345:29121, +64346:29182, +64347:29361, +64348:29374, +64349:29476, +64350:64022, +64351:29559, +64352:29629, +64353:29641, +64354:29654, +64355:29667, +64356:29650, +64357:29703, +64358:29685, +64359:29734, +64360:29738, +64361:29737, +64362:29742, +64363:29794, +64364:29833, +64365:29855, +64366:29953, +64367:30063, +64368:30338, +64369:30364, +64370:30366, +64371:30363, +64372:30374, +64373:64023, +64374:30534, +64375:21167, +64376:30753, +64377:30798, +64378:30820, +64379:30842, +64380:31024, +64381:64024, +64382:64025, +64384:64026, +64385:31124, +64386:64027, +64387:31131, +64388:31441, +64389:31463, +64390:64028, +64391:31467, +64392:31646, +64393:64029, +64394:32072, +64395:32092, +64396:32183, +64397:32160, +64398:32214, +64399:32338, +64400:32583, +64401:32673, +64402:64030, +64403:33537, +64404:33634, +64405:33663, +64406:33735, +64407:33782, +64408:33864, +64409:33972, +64410:34131, +64411:34137, +64412:34155, +64413:64031, +64414:34224, +64415:64032, +64416:64033, +64417:34823, +64418:35061, +64419:35346, +64420:35383, +64421:35449, +64422:35495, +64423:35518, +64424:35551, +64425:64034, +64426:35574, +64427:35667, +64428:35711, +64429:36080, +64430:36084, +64431:36114, +64432:36214, +64433:64035, +64434:36559, +64435:64036, +64436:64037, +64437:36967, +64438:37086, +64439:64038, +64440:37141, +64441:37159, +64442:37338, +64443:37335, +64444:37342, +64445:37357, +64446:37358, +64447:37348, +64448:37349, +64449:37382, +64450:37392, +64451:37386, +64452:37434, +64453:37440, +64454:37436, +64455:37454, +64456:37465, +64457:37457, +64458:37433, +64459:37479, +64460:37543, +64461:37495, +64462:37496, +64463:37607, +64464:37591, +64465:37593, +64466:37584, +64467:64039, +64468:37589, +64469:37600, +64470:37587, +64471:37669, +64472:37665, +64473:37627, +64474:64040, +64475:37662, +64476:37631, +64477:37661, +64478:37634, +64479:37744, +64480:37719, +64481:37796, +64482:37830, +64483:37854, +64484:37880, +64485:37937, +64486:37957, +64487:37960, +64488:38290, +64489:63964, +64490:64041, +64491:38557, +64492:38575, +64493:38707, +64494:38715, +64495:38723, +64496:38733, +64497:38735, +64498:38737, +64499:38741, +64500:38999, +64501:39013, +64502:64042, +64503:64043, +64504:39207, +64505:64044, +64506:39326, +64507:39502, +64508:39641, +64576:39644, +64577:39797, +64578:39794, +64579:39823, +64580:39857, +64581:39867, +64582:39936, +64583:40304, +64584:40299, +64585:64045, +64586:40473, +64587:40657 +}; + +/** + * @author takahiro / https://github.com/takahirox + */ + +function DataViewEx ( buffer, littleEndian ) { + + this.dv = new DataView( buffer ); + this.offset = 0; + this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true; + this.encoder = new CharsetEncoder(); + +} + +DataViewEx.prototype = { + + constructor: DataViewEx, + + getInt8: function () { + + var value = this.dv.getInt8( this.offset ); + this.offset += 1; + return value; + + }, + + getInt8Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getInt8() ); + + } + + return a; + + }, + + getUint8: function () { + + var value = this.dv.getUint8( this.offset ); + this.offset += 1; + return value; + + }, + + getUint8Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getUint8() ); + + } + + return a; + + }, + + + getInt16: function () { + + var value = this.dv.getInt16( this.offset, this.littleEndian ); + this.offset += 2; + return value; + + }, + + getInt16Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getInt16() ); + + } + + return a; + + }, + + getUint16: function () { + + var value = this.dv.getUint16( this.offset, this.littleEndian ); + this.offset += 2; + return value; + + }, + + getUint16Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getUint16() ); + + } + + return a; + + }, + + getInt32: function () { + + var value = this.dv.getInt32( this.offset, this.littleEndian ); + this.offset += 4; + return value; + + }, + + getInt32Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getInt32() ); + + } + + return a; + + }, + + getUint32: function () { + + var value = this.dv.getUint32( this.offset, this.littleEndian ); + this.offset += 4; + return value; + + }, + + getUint32Array: function ( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getUint32() ); + + } + + return a; + + }, + + getFloat32: function () { + + var value = this.dv.getFloat32( this.offset, this.littleEndian ); + this.offset += 4; + return value; + + }, + + getFloat32Array: function( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getFloat32() ); + + } + + return a; + + }, + + getFloat64: function () { + + var value = this.dv.getFloat64( this.offset, this.littleEndian ); + this.offset += 8; + return value; + + }, + + getFloat64Array: function( size ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getFloat64() ); + + } + + return a; + + }, + + getIndex: function ( type, isUnsigned ) { + + switch ( type ) { + + case 1: + return ( isUnsigned === true ) ? this.getUint8() : this.getInt8(); + + case 2: + return ( isUnsigned === true ) ? this.getUint16() : this.getInt16(); + + case 4: + return this.getInt32(); // No Uint32 + + default: + throw 'unknown number type ' + type + ' exception.'; + + } + + }, + + getIndexArray: function ( type, size, isUnsigned ) { + + var a = []; + + for ( var i = 0; i < size; i++ ) { + + a.push( this.getIndex( type, isUnsigned ) ); + + } + + return a; + + }, + + getChars: function ( size ) { + + var str = ''; + + while ( size > 0 ) { + + var value = this.getUint8(); + size--; + + if ( value === 0 ) { + + break; + + } + + str += String.fromCharCode( value ); + + } + + while ( size > 0 ) { + + this.getUint8(); + size--; + + } + + return str; + + }, + + getSjisStringsAsUnicode: function ( size ) { + + var a = []; + + while ( size > 0 ) { + + var value = this.getUint8(); + size--; + + if ( value === 0 ) { + + break; + + } + + a.push( value ); + + } + + while ( size > 0 ) { + + this.getUint8(); + size--; + + } + + return this.encoder.s2u( new Uint8Array( a ) ); + + }, + + getUnicodeStrings: function ( size ) { + + var str = ''; + + while ( size > 0 ) { + + var value = this.getUint16(); + size -= 2; + + if ( value === 0 ) { + + break; + + } + + str += String.fromCharCode( value ); + + } + + while ( size > 0 ) { + + this.getUint8(); + size--; + + } + + return str; + + }, + + getTextBuffer: function () { + + var size = this.getUint32(); + return this.getUnicodeStrings( size ); + + } + +}; + +/** + * @author takahiro / https://github.com/takahirox + */ + +function DataCreationHelper () { +} + +DataCreationHelper.prototype = { + + constructor: DataCreationHelper, + + leftToRightVector3: function ( v ) { + + v[ 2 ] = -v[ 2 ]; + + }, + + leftToRightQuaternion: function ( q ) { + + q[ 0 ] = -q[ 0 ]; + q[ 1 ] = -q[ 1 ]; + + }, + + leftToRightEuler: function ( r ) { + + r[ 0 ] = -r[ 0 ]; + r[ 1 ] = -r[ 1 ]; + + }, + + leftToRightIndexOrder: function ( p ) { + + var tmp = p[ 2 ]; + p[ 2 ] = p[ 0 ]; + p[ 0 ] = tmp; + + }, + + leftToRightVector3Range: function ( v1, v2 ) { + + var tmp = -v2[ 2 ]; + v2[ 2 ] = -v1[ 2 ]; + v1[ 2 ] = tmp; + + }, + + leftToRightEulerRange: function ( r1, r2 ) { + + var tmp1 = -r2[ 0 ]; + var tmp2 = -r2[ 1 ]; + r2[ 0 ] = -r1[ 0 ]; + r2[ 1 ] = -r1[ 1 ]; + r1[ 0 ] = tmp1; + r1[ 1 ] = tmp2; + + } + +}; + +/** + * @author takahiro / https://github.com/takahirox + */ + +function Parser() { +} + +Parser.prototype.parsePmd = function ( buffer, leftToRight ) { + + var pmd = {}; + var dv = new DataViewEx( buffer ); + + pmd.metadata = {}; + pmd.metadata.format = 'pmd'; + pmd.metadata.coordinateSystem = 'left'; + + var parseHeader = function () { + + var metadata = pmd.metadata; + metadata.magic = dv.getChars( 3 ); + + if ( metadata.magic !== 'Pmd' ) { + + throw 'PMD file magic is not Pmd, but ' + metadata.magic; + + } + + metadata.version = dv.getFloat32(); + metadata.modelName = dv.getSjisStringsAsUnicode( 20 ); + metadata.comment = dv.getSjisStringsAsUnicode( 256 ); + + }; + + var parseVertices = function () { + + var parseVertex = function () { + + var p = {}; + p.position = dv.getFloat32Array( 3 ); + p.normal = dv.getFloat32Array( 3 ); + p.uv = dv.getFloat32Array( 2 ); + p.skinIndices = dv.getUint16Array( 2 ); + p.skinWeights = [ dv.getUint8() / 100 ]; + p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); + p.edgeFlag = dv.getUint8(); + return p; + + }; + + var metadata = pmd.metadata; + metadata.vertexCount = dv.getUint32(); + + pmd.vertices = []; + + for ( var i = 0; i < metadata.vertexCount; i++ ) { + + pmd.vertices.push( parseVertex() ); + + } + + }; + + var parseFaces = function () { + + var parseFace = function () { + + var p = {}; + p.indices = dv.getUint16Array( 3 ); + return p; + + }; + + var metadata = pmd.metadata; + metadata.faceCount = dv.getUint32() / 3; + + pmd.faces = []; + + for ( var i = 0; i < metadata.faceCount; i++ ) { + + pmd.faces.push( parseFace() ); + + } + + }; + + var parseMaterials = function () { + + var parseMaterial = function () { + + var p = {}; + p.diffuse = dv.getFloat32Array( 4 ); + p.shininess = dv.getFloat32(); + p.specular = dv.getFloat32Array( 3 ); + p.ambient = dv.getFloat32Array( 3 ); + p.toonIndex = dv.getInt8(); + p.edgeFlag = dv.getUint8(); + p.faceCount = dv.getUint32() / 3; + p.fileName = dv.getSjisStringsAsUnicode( 20 ); + return p; + + }; + + var metadata = pmd.metadata; + metadata.materialCount = dv.getUint32(); + + pmd.materials = []; + + for ( var i = 0; i < metadata.materialCount; i++ ) { + + pmd.materials.push( parseMaterial() ); + + } + + }; + + var parseBones = function () { + + var parseBone = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + p.parentIndex = dv.getInt16(); + p.tailIndex = dv.getInt16(); + p.type = dv.getUint8(); + p.ikIndex = dv.getInt16(); + p.position = dv.getFloat32Array( 3 ); + return p; + + }; + + var metadata = pmd.metadata; + metadata.boneCount = dv.getUint16(); + + pmd.bones = []; + + for ( var i = 0; i < metadata.boneCount; i++ ) { + + pmd.bones.push( parseBone() ); + + } + + }; + + var parseIks = function () { + + var parseIk = function () { + + var p = {}; + p.target = dv.getUint16(); + p.effector = dv.getUint16(); + p.linkCount = dv.getUint8(); + p.iteration = dv.getUint16(); + p.maxAngle = dv.getFloat32(); + + p.links = []; + for ( var i = 0; i < p.linkCount; i++ ) { + + var link = {}; + link.index = dv.getUint16(); + p.links.push( link ); + + } + + return p; + + }; + + var metadata = pmd.metadata; + metadata.ikCount = dv.getUint16(); + + pmd.iks = []; + + for ( var i = 0; i < metadata.ikCount; i++ ) { + + pmd.iks.push( parseIk() ); + + } + + }; + + var parseMorphs = function () { + + var parseMorph = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + p.elementCount = dv.getUint32(); + p.type = dv.getUint8(); + + p.elements = []; + for ( var i = 0; i < p.elementCount; i++ ) { + + p.elements.push( { + index: dv.getUint32(), + position: dv.getFloat32Array( 3 ) + } ) ; + + } + + return p; + + }; + + var metadata = pmd.metadata; + metadata.morphCount = dv.getUint16(); + + pmd.morphs = []; + + for ( var i = 0; i < metadata.morphCount; i++ ) { + + pmd.morphs.push( parseMorph() ); + + } + + + }; + + var parseMorphFrames = function () { + + var parseMorphFrame = function () { + + var p = {}; + p.index = dv.getUint16(); + return p; + + }; + + var metadata = pmd.metadata; + metadata.morphFrameCount = dv.getUint8(); + + pmd.morphFrames = []; + + for ( var i = 0; i < metadata.morphFrameCount; i++ ) { + + pmd.morphFrames.push( parseMorphFrame() ); + + } + + }; + + var parseBoneFrameNames = function () { + + var parseBoneFrameName = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 50 ); + return p; + + }; + + var metadata = pmd.metadata; + metadata.boneFrameNameCount = dv.getUint8(); + + pmd.boneFrameNames = []; + + for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { + + pmd.boneFrameNames.push( parseBoneFrameName() ); + + } + + }; + + var parseBoneFrames = function () { + + var parseBoneFrame = function () { + + var p = {}; + p.boneIndex = dv.getInt16(); + p.frameIndex = dv.getUint8(); + return p; + + }; + + var metadata = pmd.metadata; + metadata.boneFrameCount = dv.getUint32(); + + pmd.boneFrames = []; + + for ( var i = 0; i < metadata.boneFrameCount; i++ ) { + + pmd.boneFrames.push( parseBoneFrame() ); + + } + + }; + + var parseEnglishHeader = function () { + + var metadata = pmd.metadata; + metadata.englishCompatibility = dv.getUint8(); + + if ( metadata.englishCompatibility > 0 ) { + + metadata.englishModelName = dv.getSjisStringsAsUnicode( 20 ); + metadata.englishComment = dv.getSjisStringsAsUnicode( 256 ); + + } + + }; + + var parseEnglishBoneNames = function () { + + var parseEnglishBoneName = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + return p; + + }; + + var metadata = pmd.metadata; + + if ( metadata.englishCompatibility === 0 ) { + + return; + + } + + pmd.englishBoneNames = []; + + for ( var i = 0; i < metadata.boneCount; i++ ) { + + pmd.englishBoneNames.push( parseEnglishBoneName() ); + + } + + }; + + var parseEnglishMorphNames = function () { + + var parseEnglishMorphName = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + return p; + + }; + + var metadata = pmd.metadata; + + if ( metadata.englishCompatibility === 0 ) { + + return; + + } + + pmd.englishMorphNames = []; + + for ( var i = 0; i < metadata.morphCount - 1; i++ ) { + + pmd.englishMorphNames.push( parseEnglishMorphName() ); + + } + + }; + + var parseEnglishBoneFrameNames = function () { + + var parseEnglishBoneFrameName = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 50 ); + return p; + + }; + + var metadata = pmd.metadata; + + if ( metadata.englishCompatibility === 0 ) { + + return; + + } + + pmd.englishBoneFrameNames = []; + + for ( var i = 0; i < metadata.boneFrameNameCount; i++ ) { + + pmd.englishBoneFrameNames.push( parseEnglishBoneFrameName() ); + + } + + }; + + var parseToonTextures = function () { + + var parseToonTexture = function () { + + var p = {}; + p.fileName = dv.getSjisStringsAsUnicode( 100 ); + return p; + + }; + + pmd.toonTextures = []; + + for ( var i = 0; i < 10; i++ ) { + + pmd.toonTextures.push( parseToonTexture() ); + + } + + }; + + var parseRigidBodies = function () { + + var parseRigidBody = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + p.boneIndex = dv.getInt16(); + p.groupIndex = dv.getUint8(); + p.groupTarget = dv.getUint16(); + p.shapeType = dv.getUint8(); + p.width = dv.getFloat32(); + p.height = dv.getFloat32(); + p.depth = dv.getFloat32(); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 3 ); + p.weight = dv.getFloat32(); + p.positionDamping = dv.getFloat32(); + p.rotationDamping = dv.getFloat32(); + p.restitution = dv.getFloat32(); + p.friction = dv.getFloat32(); + p.type = dv.getUint8(); + return p; + + }; + + var metadata = pmd.metadata; + metadata.rigidBodyCount = dv.getUint32(); + + pmd.rigidBodies = []; + + for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { + + pmd.rigidBodies.push( parseRigidBody() ); + + } + + }; + + var parseConstraints = function () { + + var parseConstraint = function () { + + var p = {}; + p.name = dv.getSjisStringsAsUnicode( 20 ); + p.rigidBodyIndex1 = dv.getUint32(); + p.rigidBodyIndex2 = dv.getUint32(); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 3 ); + p.translationLimitation1 = dv.getFloat32Array( 3 ); + p.translationLimitation2 = dv.getFloat32Array( 3 ); + p.rotationLimitation1 = dv.getFloat32Array( 3 ); + p.rotationLimitation2 = dv.getFloat32Array( 3 ); + p.springPosition = dv.getFloat32Array( 3 ); + p.springRotation = dv.getFloat32Array( 3 ); + return p; + + }; + + var metadata = pmd.metadata; + metadata.constraintCount = dv.getUint32(); + + pmd.constraints = []; + + for ( var i = 0; i < metadata.constraintCount; i++ ) { + + pmd.constraints.push( parseConstraint() ); + + } + + }; + + parseHeader(); + parseVertices(); + parseFaces(); + parseMaterials(); + parseBones(); + parseIks(); + parseMorphs(); + parseMorphFrames(); + parseBoneFrameNames(); + parseBoneFrames(); + parseEnglishHeader(); + parseEnglishBoneNames(); + parseEnglishMorphNames(); + parseEnglishBoneFrameNames(); + parseToonTextures(); + parseRigidBodies(); + parseConstraints(); + + if ( leftToRight === true ) this.leftToRightModel( pmd ); + + // console.log( pmd ); // for console debug + + return pmd; + +}; + +Parser.prototype.parsePmx = function ( buffer, leftToRight ) { + + var pmx = {}; + var dv = new DataViewEx( buffer ); + + pmx.metadata = {}; + pmx.metadata.format = 'pmx'; + pmx.metadata.coordinateSystem = 'left'; + + var parseHeader = function () { + + var metadata = pmx.metadata; + metadata.magic = dv.getChars( 4 ); + + // Note: don't remove the last blank space. + if ( metadata.magic !== 'PMX ' ) { + + throw 'PMX file magic is not PMX , but ' + metadata.magic; + + } + + metadata.version = dv.getFloat32(); + + if ( metadata.version !== 2.0 && metadata.version !== 2.1 ) { + + throw 'PMX version ' + metadata.version + ' is not supported.'; + + } + + metadata.headerSize = dv.getUint8(); + metadata.encoding = dv.getUint8(); + metadata.additionalUvNum = dv.getUint8(); + metadata.vertexIndexSize = dv.getUint8(); + metadata.textureIndexSize = dv.getUint8(); + metadata.materialIndexSize = dv.getUint8(); + metadata.boneIndexSize = dv.getUint8(); + metadata.morphIndexSize = dv.getUint8(); + metadata.rigidBodyIndexSize = dv.getUint8(); + metadata.modelName = dv.getTextBuffer(); + metadata.englishModelName = dv.getTextBuffer(); + metadata.comment = dv.getTextBuffer(); + metadata.englishComment = dv.getTextBuffer(); + + }; + + var parseVertices = function () { + + var parseVertex = function () { + + var p = {}; + p.position = dv.getFloat32Array( 3 ); + p.normal = dv.getFloat32Array( 3 ); + p.uv = dv.getFloat32Array( 2 ); + + p.auvs = []; + + for ( var i = 0; i < pmx.metadata.additionalUvNum; i++ ) { + + p.auvs.push( dv.getFloat32Array( 4 ) ); + + } + + p.type = dv.getUint8(); + + var indexSize = metadata.boneIndexSize; + + if ( p.type === 0 ) { // BDEF1 + + p.skinIndices = dv.getIndexArray( indexSize, 1 ); + p.skinWeights = [ 1.0 ]; + + } else if ( p.type === 1 ) { // BDEF2 + + p.skinIndices = dv.getIndexArray( indexSize, 2 ); + p.skinWeights = dv.getFloat32Array( 1 ); + p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); + + } else if ( p.type === 2 ) { // BDEF4 + + p.skinIndices = dv.getIndexArray( indexSize, 4 ); + p.skinWeights = dv.getFloat32Array( 4 ); + + } else if ( p.type === 3 ) { // SDEF + + p.skinIndices = dv.getIndexArray( indexSize, 2 ); + p.skinWeights = dv.getFloat32Array( 1 ); + p.skinWeights.push( 1.0 - p.skinWeights[ 0 ] ); + + p.skinC = dv.getFloat32Array( 3 ); + p.skinR0 = dv.getFloat32Array( 3 ); + p.skinR1 = dv.getFloat32Array( 3 ); + + // SDEF is not supported yet and is handled as BDEF2 so far. + // TODO: SDEF support + p.type = 1; + + } else { + + throw 'unsupport bone type ' + p.type + ' exception.'; + + } + + p.edgeRatio = dv.getFloat32(); + return p; + + }; + + var metadata = pmx.metadata; + metadata.vertexCount = dv.getUint32(); + + pmx.vertices = []; + + for ( var i = 0; i < metadata.vertexCount; i++ ) { + + pmx.vertices.push( parseVertex() ); + + } + + }; + + var parseFaces = function () { + + var parseFace = function () { + + var p = {}; + p.indices = dv.getIndexArray( metadata.vertexIndexSize, 3, true ); + return p; + + }; + + var metadata = pmx.metadata; + metadata.faceCount = dv.getUint32() / 3; + + pmx.faces = []; + + for ( var i = 0; i < metadata.faceCount; i++ ) { + + pmx.faces.push( parseFace() ); + + } + + }; + + var parseTextures = function () { + + var parseTexture = function () { + + return dv.getTextBuffer(); + + }; + + var metadata = pmx.metadata; + metadata.textureCount = dv.getUint32(); + + pmx.textures = []; + + for ( var i = 0; i < metadata.textureCount; i++ ) { + + pmx.textures.push( parseTexture() ); + + } + + }; + + var parseMaterials = function () { + + var parseMaterial = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.diffuse = dv.getFloat32Array( 4 ); + p.specular = dv.getFloat32Array( 3 ); + p.shininess = dv.getFloat32(); + p.ambient = dv.getFloat32Array( 3 ); + p.flag = dv.getUint8(); + p.edgeColor = dv.getFloat32Array( 4 ); + p.edgeSize = dv.getFloat32(); + p.textureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); + p.envTextureIndex = dv.getIndex( pmx.metadata.textureIndexSize ); + p.envFlag = dv.getUint8(); + p.toonFlag = dv.getUint8(); + + if ( p.toonFlag === 0 ) { + + p.toonIndex = dv.getIndex( pmx.metadata.textureIndexSize ); + + } else if ( p.toonFlag === 1 ) { + + p.toonIndex = dv.getInt8(); + + } else { + + throw 'unknown toon flag ' + p.toonFlag + ' exception.'; + + } + + p.comment = dv.getTextBuffer(); + p.faceCount = dv.getUint32() / 3; + return p; + + }; + + var metadata = pmx.metadata; + metadata.materialCount = dv.getUint32(); + + pmx.materials = []; + + for ( var i = 0; i < metadata.materialCount; i++ ) { + + pmx.materials.push( parseMaterial() ); + + } + + }; + + var parseBones = function () { + + var parseBone = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.position = dv.getFloat32Array( 3 ); + p.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); + p.transformationClass = dv.getUint32(); + p.flag = dv.getUint16(); + + if ( p.flag & 0x1 ) { + + p.connectIndex = dv.getIndex( pmx.metadata.boneIndexSize ); + + } else { + + p.offsetPosition = dv.getFloat32Array( 3 ); + + } + + if ( p.flag & 0x100 || p.flag & 0x200 ) { + + // Note: I don't think Grant is an appropriate name + // but I found that some English translated MMD tools use this term + // so I've named it Grant so far. + // I'd rename to more appropriate name from Grant later. + var grant = {}; + + grant.isLocal = ( p.flag & 0x80 ) !== 0 ? true : false; + grant.affectRotation = ( p.flag & 0x100 ) !== 0 ? true : false; + grant.affectPosition = ( p.flag & 0x200 ) !== 0 ? true : false; + grant.parentIndex = dv.getIndex( pmx.metadata.boneIndexSize ); + grant.ratio = dv.getFloat32(); + + p.grant = grant; + + } + + if ( p.flag & 0x400 ) { + + p.fixAxis = dv.getFloat32Array( 3 ); + + } + + if ( p.flag & 0x800 ) { + + p.localXVector = dv.getFloat32Array( 3 ); + p.localZVector = dv.getFloat32Array( 3 ); + + } + + if ( p.flag & 0x2000 ) { + + p.key = dv.getUint32(); + + } + + if ( p.flag & 0x20 ) { + + var ik = {}; + + ik.effector = dv.getIndex( pmx.metadata.boneIndexSize ); + ik.target = null; + ik.iteration = dv.getUint32(); + ik.maxAngle = dv.getFloat32(); + ik.linkCount = dv.getUint32(); + ik.links = []; + + for ( var i = 0; i < ik.linkCount; i++ ) { + + var link = {}; + link.index = dv.getIndex( pmx.metadata.boneIndexSize ); + link.angleLimitation = dv.getUint8(); + + if ( link.angleLimitation === 1 ) { + + link.lowerLimitationAngle = dv.getFloat32Array( 3 ); + link.upperLimitationAngle = dv.getFloat32Array( 3 ); + + } + + ik.links.push( link ); + + } + + p.ik = ik; + } + + return p; + + }; + + var metadata = pmx.metadata; + metadata.boneCount = dv.getUint32(); + + pmx.bones = []; + + for ( var i = 0; i < metadata.boneCount; i++ ) { + + pmx.bones.push( parseBone() ); + + } + + }; + + var parseMorphs = function () { + + var parseMorph = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.panel = dv.getUint8(); + p.type = dv.getUint8(); + p.elementCount = dv.getUint32(); + p.elements = []; + + for ( var i = 0; i < p.elementCount; i++ ) { + + if ( p.type === 0 ) { // group morph + + var m = {}; + m.index = dv.getIndex( pmx.metadata.morphIndexSize ); + m.ratio = dv.getFloat32(); + p.elements.push( m ); + + } else if ( p.type === 1 ) { // vertex morph + + var m = {}; + m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); + m.position = dv.getFloat32Array( 3 ); + p.elements.push( m ); + + } else if ( p.type === 2 ) { // bone morph + + var m = {}; + m.index = dv.getIndex( pmx.metadata.boneIndexSize ); + m.position = dv.getFloat32Array( 3 ); + m.rotation = dv.getFloat32Array( 4 ); + p.elements.push( m ); + + } else if ( p.type === 3 ) { // uv morph + + var m = {}; + m.index = dv.getIndex( pmx.metadata.vertexIndexSize, true ); + m.uv = dv.getFloat32Array( 4 ); + p.elements.push( m ); + + } else if ( p.type === 4 ) { // additional uv1 + + // TODO: implement + + } else if ( p.type === 5 ) { // additional uv2 + + // TODO: implement + + } else if ( p.type === 6 ) { // additional uv3 + + // TODO: implement + + } else if ( p.type === 7 ) { // additional uv4 + + // TODO: implement + + } else if ( p.type === 8 ) { // material morph + + var m = {}; + m.index = dv.getIndex( pmx.metadata.materialIndexSize ); + m.type = dv.getUint8(); + m.diffuse = dv.getFloat32Array( 4 ); + m.specular = dv.getFloat32Array( 3 ); + m.shininess = dv.getFloat32(); + m.ambient = dv.getFloat32Array( 3 ); + m.edgeColor = dv.getFloat32Array( 4 ); + m.edgeSize = dv.getFloat32(); + m.textureColor = dv.getFloat32Array( 4 ); + m.sphereTextureColor = dv.getFloat32Array( 4 ); + m.toonColor = dv.getFloat32Array( 4 ); + p.elements.push( m ); + + } + + } + + return p; + + }; + + var metadata = pmx.metadata; + metadata.morphCount = dv.getUint32(); + + pmx.morphs = []; + + for ( var i = 0; i < metadata.morphCount; i++ ) { + + pmx.morphs.push( parseMorph() ); + + } + + }; + + var parseFrames = function () { + + var parseFrame = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.type = dv.getUint8(); + p.elementCount = dv.getUint32(); + p.elements = []; + + for ( var i = 0; i < p.elementCount; i++ ) { + + var e = {}; + e.target = dv.getUint8(); + e.index = ( e.target === 0 ) ? dv.getIndex( pmx.metadata.boneIndexSize ) : dv.getIndex( pmx.metadata.morphIndexSize ); + p.elements.push( e ); + + } + + return p; + + }; + + var metadata = pmx.metadata; + metadata.frameCount = dv.getUint32(); + + pmx.frames = []; + + for ( var i = 0; i < metadata.frameCount; i++ ) { + + pmx.frames.push( parseFrame() ); + + } + + }; + + var parseRigidBodies = function () { + + var parseRigidBody = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.boneIndex = dv.getIndex( pmx.metadata.boneIndexSize ); + p.groupIndex = dv.getUint8(); + p.groupTarget = dv.getUint16(); + p.shapeType = dv.getUint8(); + p.width = dv.getFloat32(); + p.height = dv.getFloat32(); + p.depth = dv.getFloat32(); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 3 ); + p.weight = dv.getFloat32(); + p.positionDamping = dv.getFloat32(); + p.rotationDamping = dv.getFloat32(); + p.restitution = dv.getFloat32(); + p.friction = dv.getFloat32(); + p.type = dv.getUint8(); + return p; + + }; + + var metadata = pmx.metadata; + metadata.rigidBodyCount = dv.getUint32(); + + pmx.rigidBodies = []; + + for ( var i = 0; i < metadata.rigidBodyCount; i++ ) { + + pmx.rigidBodies.push( parseRigidBody() ); + + } + + }; + + var parseConstraints = function () { + + var parseConstraint = function () { + + var p = {}; + p.name = dv.getTextBuffer(); + p.englishName = dv.getTextBuffer(); + p.type = dv.getUint8(); + p.rigidBodyIndex1 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); + p.rigidBodyIndex2 = dv.getIndex( pmx.metadata.rigidBodyIndexSize ); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 3 ); + p.translationLimitation1 = dv.getFloat32Array( 3 ); + p.translationLimitation2 = dv.getFloat32Array( 3 ); + p.rotationLimitation1 = dv.getFloat32Array( 3 ); + p.rotationLimitation2 = dv.getFloat32Array( 3 ); + p.springPosition = dv.getFloat32Array( 3 ); + p.springRotation = dv.getFloat32Array( 3 ); + return p; + + }; + + var metadata = pmx.metadata; + metadata.constraintCount = dv.getUint32(); + + pmx.constraints = []; + + for ( var i = 0; i < metadata.constraintCount; i++ ) { + + pmx.constraints.push( parseConstraint() ); + + } + + }; + + parseHeader(); + parseVertices(); + parseFaces(); + parseTextures(); + parseMaterials(); + parseBones(); + parseMorphs(); + parseFrames(); + parseRigidBodies(); + parseConstraints(); + + if ( leftToRight === true ) this.leftToRightModel( pmx ); + + // console.log( pmx ); // for console debug + + return pmx; + +}; + +Parser.prototype.parseVmd = function ( buffer, leftToRight ) { + + var vmd = {}; + var dv = new DataViewEx( buffer ); + + vmd.metadata = {}; + vmd.metadata.coordinateSystem = 'left'; + + var parseHeader = function () { + + var metadata = vmd.metadata; + metadata.magic = dv.getChars( 30 ); + + if ( metadata.magic !== 'Vocaloid Motion Data 0002' ) { + + throw 'VMD file magic is not Vocaloid Motion Data 0002, but ' + metadata.magic; + + } + + metadata.name = dv.getSjisStringsAsUnicode( 20 ); + + }; + + var parseMotions = function () { + + var parseMotion = function () { + + var p = {}; + p.boneName = dv.getSjisStringsAsUnicode( 15 ); + p.frameNum = dv.getUint32(); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 4 ); + p.interpolation = dv.getUint8Array( 64 ); + return p; + + }; + + var metadata = vmd.metadata; + metadata.motionCount = dv.getUint32(); + + vmd.motions = []; + for ( var i = 0; i < metadata.motionCount; i++ ) { + + vmd.motions.push( parseMotion() ); + + } + + }; + + var parseMorphs = function () { + + var parseMorph = function () { + + var p = {}; + p.morphName = dv.getSjisStringsAsUnicode( 15 ); + p.frameNum = dv.getUint32(); + p.weight = dv.getFloat32(); + return p; + + }; + + var metadata = vmd.metadata; + metadata.morphCount = dv.getUint32(); + + vmd.morphs = []; + for ( var i = 0; i < metadata.morphCount; i++ ) { + + vmd.morphs.push( parseMorph() ); + + } + + }; + + var parseCameras = function () { + + var parseCamera = function () { + + var p = {}; + p.frameNum = dv.getUint32(); + p.distance = dv.getFloat32(); + p.position = dv.getFloat32Array( 3 ); + p.rotation = dv.getFloat32Array( 3 ); + p.interpolation = dv.getUint8Array( 24 ); + p.fov = dv.getUint32(); + p.perspective = dv.getUint8(); + return p; + + }; + + var metadata = vmd.metadata; + metadata.cameraCount = dv.getUint32(); + + vmd.cameras = []; + for ( var i = 0; i < metadata.cameraCount; i++ ) { + + vmd.cameras.push( parseCamera() ); + + } + + }; + + parseHeader(); + parseMotions(); + parseMorphs(); + parseCameras(); + + if ( leftToRight === true ) this.leftToRightVmd( vmd ); + + // console.log( vmd ); // for console debug + + return vmd; + +}; + +Parser.prototype.parseVpd = function ( text, leftToRight ) { + + var vpd = {}; + + vpd.metadata = {}; + vpd.metadata.coordinateSystem = 'left'; + + vpd.bones = []; + + var commentPatternG = /\/\/\w*(\r|\n|\r\n)/g; + var newlinePattern = /\r|\n|\r\n/; + + var lines = text.replace( commentPatternG, '' ).split( newlinePattern ); + + function throwError () { + + throw 'the file seems not vpd file.'; + + } + + function checkMagic () { + + if ( lines[ 0 ] !== 'Vocaloid Pose Data file' ) { + + throwError(); + + } + + } + + function parseHeader () { + + if ( lines.length < 4 ) { + + throwError(); + + } + + vpd.metadata.parentFile = lines[ 2 ]; + vpd.metadata.boneCount = parseInt( lines[ 3 ] ); + + } + + function parseBones () { + + var boneHeaderPattern = /^\s*(Bone[0-9]+)\s*\{\s*(.*)$/; + var boneVectorPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; + var boneQuaternionPattern = /^\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*,\s*(-?[0-9]+\.[0-9]+)\s*;/; + var boneFooterPattern = /^\s*}/; + + var bones = vpd.bones; + var n = null; + var v = null; + var q = null; + + for ( var i = 4; i < lines.length; i++ ) { + + var line = lines[ i ]; + + var result; + + result = line.match( boneHeaderPattern ); + + if ( result !== null ) { + + if ( n !== null ) { + + throwError(); + + } + + n = result[ 2 ]; + + } + + result = line.match( boneVectorPattern ); + + if ( result !== null ) { + + if ( v !== null ) { + + throwError(); + + } + + v = [ + + parseFloat( result[ 1 ] ), + parseFloat( result[ 2 ] ), + parseFloat( result[ 3 ] ) + + ]; + + } + + result = line.match( boneQuaternionPattern ); + + if ( result !== null ) { + + if ( q !== null ) { + + throwError(); + + } + + q = [ + + parseFloat( result[ 1 ] ), + parseFloat( result[ 2 ] ), + parseFloat( result[ 3 ] ), + parseFloat( result[ 4 ] ) + + ]; + + + } + + result = line.match( boneFooterPattern ); + + if ( result !== null ) { + + if ( n === null || v === null || q === null ) { + + throwError(); + + } + + bones.push( { + + name: n, + translation: v, + quaternion: q + + } ); + + n = null; + v = null; + q = null; + + } + + } + + if ( n !== null || v !== null || q !== null ) { + + throwError(); + + } + + } + + checkMagic(); + parseHeader(); + parseBones(); + + if ( leftToRight === true ) this.leftToRightVpd( vpd ); + + // console.log( vpd ); // for console debug + + return vpd; + +}; + +Parser.prototype.mergeVmds = function ( vmds ) { + + var v = {}; + v.metadata = {}; + v.metadata.name = vmds[ 0 ].metadata.name; + v.metadata.coordinateSystem = vmds[ 0 ].metadata.coordinateSystem; + v.metadata.motionCount = 0; + v.metadata.morphCount = 0; + v.metadata.cameraCount = 0; + v.motions = []; + v.morphs = []; + v.cameras = []; + + for ( var i = 0; i < vmds.length; i++ ) { + + var v2 = vmds[ i ]; + + v.metadata.motionCount += v2.metadata.motionCount; + v.metadata.morphCount += v2.metadata.morphCount; + v.metadata.cameraCount += v2.metadata.cameraCount; + + for ( var j = 0; j < v2.metadata.motionCount; j++ ) { + + v.motions.push( v2.motions[ j ] ); + + } + + for ( var j = 0; j < v2.metadata.morphCount; j++ ) { + + v.morphs.push( v2.morphs[ j ] ); + + } + + for ( var j = 0; j < v2.metadata.cameraCount; j++ ) { + + v.cameras.push( v2.cameras[ j ] ); + + } + + } + + return v; + +}; + +Parser.prototype.leftToRightModel = function ( model ) { + + if ( model.metadata.coordinateSystem === 'right' ) { + + return; + + } + + model.metadata.coordinateSystem = 'right'; + + var helper = new DataCreationHelper(); + + for ( var i = 0; i < model.metadata.vertexCount; i++ ) { + + helper.leftToRightVector3( model.vertices[ i ].position ); + helper.leftToRightVector3( model.vertices[ i ].normal ); + + } + + for ( var i = 0; i < model.metadata.faceCount; i++ ) { + + helper.leftToRightIndexOrder( model.faces[ i ].indices ); + + } + + for ( var i = 0; i < model.metadata.boneCount; i++ ) { + + helper.leftToRightVector3( model.bones[ i ].position ); + + } + + // TODO: support other morph for PMX + for ( var i = 0; i < model.metadata.morphCount; i++ ) { + + var m = model.morphs[ i ]; + + if ( model.metadata.format === 'pmx' && m.type !== 1 ) { + + // TODO: implement + continue; + + } + + for ( var j = 0; j < m.elements.length; j++ ) { + + helper.leftToRightVector3( m.elements[ j ].position ); + + } + + } + + for ( var i = 0; i < model.metadata.rigidBodyCount; i++ ) { + + helper.leftToRightVector3( model.rigidBodies[ i ].position ); + helper.leftToRightEuler( model.rigidBodies[ i ].rotation ); + + } + + for ( var i = 0; i < model.metadata.constraintCount; i++ ) { + + helper.leftToRightVector3( model.constraints[ i ].position ); + helper.leftToRightEuler( model.constraints[ i ].rotation ); + helper.leftToRightVector3Range( model.constraints[ i ].translationLimitation1, model.constraints[ i ].translationLimitation2 ); + helper.leftToRightEulerRange( model.constraints[ i ].rotationLimitation1, model.constraints[ i ].rotationLimitation2 ); + + } + +}; + +Parser.prototype.leftToRightVmd = function ( vmd ) { + + if ( vmd.metadata.coordinateSystem === 'right' ) { + + return; + + } + + vmd.metadata.coordinateSystem = 'right'; + + var helper = new DataCreationHelper(); + + for ( var i = 0; i < vmd.metadata.motionCount; i++ ) { + + helper.leftToRightVector3( vmd.motions[ i ].position ); + helper.leftToRightQuaternion( vmd.motions[ i ].rotation ); + + } + + for ( var i = 0; i < vmd.metadata.cameraCount; i++ ) { + + helper.leftToRightVector3( vmd.cameras[ i ].position ); + helper.leftToRightEuler( vmd.cameras[ i ].rotation ); + + } + +}; + +Parser.prototype.leftToRightVpd = function ( vpd ) { + + if ( vpd.metadata.coordinateSystem === 'right' ) { + + return; + + } + + vpd.metadata.coordinateSystem = 'right'; + + var helper = new DataCreationHelper(); + + for ( var i = 0; i < vpd.bones.length; i++ ) { + + helper.leftToRightVector3( vpd.bones[ i ].translation ); + helper.leftToRightQuaternion( vpd.bones[ i ].quaternion ); + + } + +}; + +var MMDParser = { + CharsetEncoder: CharsetEncoder, + Parser: Parser +}; + +export { MMDParser, CharsetEncoder, Parser }; diff --git a/ui/viewer/vendor/three/addons/loaders/GLTFLoader.js b/ui/viewer/vendor/three/addons/loaders/GLTFLoader.js new file mode 100644 index 0000000..e39cbcb --- /dev/null +++ b/ui/viewer/vendor/three/addons/loaders/GLTFLoader.js @@ -0,0 +1,4725 @@ +import { + AnimationClip, + Bone, + Box3, + BufferAttribute, + BufferGeometry, + ClampToEdgeWrapping, + Color, + ColorManagement, + DirectionalLight, + DoubleSide, + FileLoader, + FrontSide, + Group, + ImageBitmapLoader, + InstancedMesh, + InterleavedBuffer, + InterleavedBufferAttribute, + Interpolant, + InterpolateDiscrete, + InterpolateLinear, + Line, + LineBasicMaterial, + LineLoop, + LineSegments, + LinearFilter, + LinearMipmapLinearFilter, + LinearMipmapNearestFilter, + LinearSRGBColorSpace, + Loader, + LoaderUtils, + Material, + MathUtils, + Matrix4, + Mesh, + MeshBasicMaterial, + MeshPhysicalMaterial, + MeshStandardMaterial, + MirroredRepeatWrapping, + NearestFilter, + NearestMipmapLinearFilter, + NearestMipmapNearestFilter, + NumberKeyframeTrack, + Object3D, + OrthographicCamera, + PerspectiveCamera, + PointLight, + Points, + PointsMaterial, + PropertyBinding, + Quaternion, + QuaternionKeyframeTrack, + RepeatWrapping, + Skeleton, + SkinnedMesh, + Sphere, + SpotLight, + Texture, + TextureLoader, + TriangleFanDrawMode, + TriangleStripDrawMode, + Vector2, + Vector3, + VectorKeyframeTrack, + SRGBColorSpace, + InstancedBufferAttribute +} from 'three'; +import { toTrianglesDrawMode } from '../utils/BufferGeometryUtils.js'; + +class GLTFLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + this.dracoLoader = null; + this.ktx2Loader = null; + this.meshoptDecoder = null; + + this.pluginCallbacks = []; + + this.register( function ( parser ) { + + return new GLTFMaterialsClearcoatExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsDispersionExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFTextureBasisUExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFTextureWebPExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFTextureAVIFExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsSheenExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsTransmissionExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsVolumeExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIorExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsEmissiveStrengthExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsSpecularExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsIridescenceExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsAnisotropyExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMaterialsBumpExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFLightsExtension( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMeshoptCompression( parser ); + + } ); + + this.register( function ( parser ) { + + return new GLTFMeshGpuInstancing( parser ); + + } ); + + } + + load( url, onLoad, onProgress, onError ) { + + const scope = this; + + let resourcePath; + + if ( this.resourcePath !== '' ) { + + resourcePath = this.resourcePath; + + } else if ( this.path !== '' ) { + + // If a base path is set, resources will be relative paths from that plus the relative path of the gltf file + // Example path = 'https://my-cnd-server.com/', url = 'assets/models/model.gltf' + // resourcePath = 'https://my-cnd-server.com/assets/models/' + // referenced resource 'model.bin' will be loaded from 'https://my-cnd-server.com/assets/models/model.bin' + // referenced resource '../textures/texture.png' will be loaded from 'https://my-cnd-server.com/assets/textures/texture.png' + const relativeUrl = LoaderUtils.extractUrlBase( url ); + resourcePath = LoaderUtils.resolveURL( relativeUrl, this.path ); + + } else { + + resourcePath = LoaderUtils.extractUrlBase( url ); + + } + + // Tells the LoadingManager to track an extra item, which resolves after + // the model is fully loaded. This means the count of items loaded will + // be incorrect, but ensures manager.onLoad() does not fire early. + this.manager.itemStart( url ); + + const _onError = function ( e ) { + + if ( onError ) { + + onError( e ); + + } else { + + console.error( e ); + + } + + scope.manager.itemError( url ); + scope.manager.itemEnd( url ); + + }; + + const loader = new FileLoader( this.manager ); + + loader.setPath( this.path ); + loader.setResponseType( 'arraybuffer' ); + loader.setRequestHeader( this.requestHeader ); + loader.setWithCredentials( this.withCredentials ); + + loader.load( url, function ( data ) { + + try { + + scope.parse( data, resourcePath, function ( gltf ) { + + onLoad( gltf ); + + scope.manager.itemEnd( url ); + + }, _onError ); + + } catch ( e ) { + + _onError( e ); + + } + + }, onProgress, _onError ); + + } + + setDRACOLoader( dracoLoader ) { + + this.dracoLoader = dracoLoader; + return this; + + } + + setKTX2Loader( ktx2Loader ) { + + this.ktx2Loader = ktx2Loader; + return this; + + } + + setMeshoptDecoder( meshoptDecoder ) { + + this.meshoptDecoder = meshoptDecoder; + return this; + + } + + register( callback ) { + + if ( this.pluginCallbacks.indexOf( callback ) === - 1 ) { + + this.pluginCallbacks.push( callback ); + + } + + return this; + + } + + unregister( callback ) { + + if ( this.pluginCallbacks.indexOf( callback ) !== - 1 ) { + + this.pluginCallbacks.splice( this.pluginCallbacks.indexOf( callback ), 1 ); + + } + + return this; + + } + + parse( data, path, onLoad, onError ) { + + let json; + const extensions = {}; + const plugins = {}; + const textDecoder = new TextDecoder(); + + if ( typeof data === 'string' ) { + + json = JSON.parse( data ); + + } else if ( data instanceof ArrayBuffer ) { + + const magic = textDecoder.decode( new Uint8Array( data, 0, 4 ) ); + + if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { + + try { + + extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); + + } catch ( error ) { + + if ( onError ) onError( error ); + return; + + } + + json = JSON.parse( extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content ); + + } else { + + json = JSON.parse( textDecoder.decode( data ) ); + + } + + } else { + + json = data; + + } + + if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { + + if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) ); + return; + + } + + const parser = new GLTFParser( json, { + + path: path || this.resourcePath || '', + crossOrigin: this.crossOrigin, + requestHeader: this.requestHeader, + manager: this.manager, + ktx2Loader: this.ktx2Loader, + meshoptDecoder: this.meshoptDecoder + + } ); + + parser.fileLoader.setRequestHeader( this.requestHeader ); + + for ( let i = 0; i < this.pluginCallbacks.length; i ++ ) { + + const plugin = this.pluginCallbacks[ i ]( parser ); + + if ( ! plugin.name ) console.error( 'THREE.GLTFLoader: Invalid plugin found: missing name' ); + + plugins[ plugin.name ] = plugin; + + // Workaround to avoid determining as unknown extension + // in addUnknownExtensionsToUserData(). + // Remove this workaround if we move all the existing + // extension handlers to plugin system + extensions[ plugin.name ] = true; + + } + + if ( json.extensionsUsed ) { + + for ( let i = 0; i < json.extensionsUsed.length; ++ i ) { + + const extensionName = json.extensionsUsed[ i ]; + const extensionsRequired = json.extensionsRequired || []; + + switch ( extensionName ) { + + case EXTENSIONS.KHR_MATERIALS_UNLIT: + extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); + break; + + case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: + extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); + break; + + case EXTENSIONS.KHR_TEXTURE_TRANSFORM: + extensions[ extensionName ] = new GLTFTextureTransformExtension(); + break; + + case EXTENSIONS.KHR_MESH_QUANTIZATION: + extensions[ extensionName ] = new GLTFMeshQuantizationExtension(); + break; + + default: + + if ( extensionsRequired.indexOf( extensionName ) >= 0 && plugins[ extensionName ] === undefined ) { + + console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); + + } + + } + + } + + } + + parser.setExtensions( extensions ); + parser.setPlugins( plugins ); + parser.parse( onLoad, onError ); + + } + + parseAsync( data, path ) { + + const scope = this; + + return new Promise( function ( resolve, reject ) { + + scope.parse( data, path, resolve, reject ); + + } ); + + } + +} + +/* GLTFREGISTRY */ + +function GLTFRegistry() { + + let objects = {}; + + return { + + get: function ( key ) { + + return objects[ key ]; + + }, + + add: function ( key, object ) { + + objects[ key ] = object; + + }, + + remove: function ( key ) { + + delete objects[ key ]; + + }, + + removeAll: function () { + + objects = {}; + + } + + }; + +} + +/*********************************/ +/********** EXTENSIONS ***********/ +/*********************************/ + +const EXTENSIONS = { + KHR_BINARY_GLTF: 'KHR_binary_glTF', + KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', + KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', + KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat', + KHR_MATERIALS_DISPERSION: 'KHR_materials_dispersion', + KHR_MATERIALS_IOR: 'KHR_materials_ior', + KHR_MATERIALS_SHEEN: 'KHR_materials_sheen', + KHR_MATERIALS_SPECULAR: 'KHR_materials_specular', + KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission', + KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence', + KHR_MATERIALS_ANISOTROPY: 'KHR_materials_anisotropy', + KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', + KHR_MATERIALS_VOLUME: 'KHR_materials_volume', + KHR_TEXTURE_BASISU: 'KHR_texture_basisu', + KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', + KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization', + KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength', + EXT_MATERIALS_BUMP: 'EXT_materials_bump', + EXT_TEXTURE_WEBP: 'EXT_texture_webp', + EXT_TEXTURE_AVIF: 'EXT_texture_avif', + EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression', + EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing' +}; + +/** + * Punctual Lights Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual + */ +class GLTFLightsExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; + + // Object3D instance caches + this.cache = { refs: {}, uses: {} }; + + } + + _markDefs() { + + const parser = this.parser; + const nodeDefs = this.parser.json.nodes || []; + + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + + const nodeDef = nodeDefs[ nodeIndex ]; + + if ( nodeDef.extensions + && nodeDef.extensions[ this.name ] + && nodeDef.extensions[ this.name ].light !== undefined ) { + + parser._addNodeRef( this.cache, nodeDef.extensions[ this.name ].light ); + + } + + } + + } + + _loadLight( lightIndex ) { + + const parser = this.parser; + const cacheKey = 'light:' + lightIndex; + let dependency = parser.cache.get( cacheKey ); + + if ( dependency ) return dependency; + + const json = parser.json; + const extensions = ( json.extensions && json.extensions[ this.name ] ) || {}; + const lightDefs = extensions.lights || []; + const lightDef = lightDefs[ lightIndex ]; + let lightNode; + + const color = new Color( 0xffffff ); + + if ( lightDef.color !== undefined ) color.setRGB( lightDef.color[ 0 ], lightDef.color[ 1 ], lightDef.color[ 2 ], LinearSRGBColorSpace ); + + const range = lightDef.range !== undefined ? lightDef.range : 0; + + switch ( lightDef.type ) { + + case 'directional': + lightNode = new DirectionalLight( color ); + lightNode.target.position.set( 0, 0, - 1 ); + lightNode.add( lightNode.target ); + break; + + case 'point': + lightNode = new PointLight( color ); + lightNode.distance = range; + break; + + case 'spot': + lightNode = new SpotLight( color ); + lightNode.distance = range; + // Handle spotlight properties. + lightDef.spot = lightDef.spot || {}; + lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; + lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; + lightNode.angle = lightDef.spot.outerConeAngle; + lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; + lightNode.target.position.set( 0, 0, - 1 ); + lightNode.add( lightNode.target ); + break; + + default: + throw new Error( 'THREE.GLTFLoader: Unexpected light type: ' + lightDef.type ); + + } + + // Some lights (e.g. spot) default to a position other than the origin. Reset the position + // here, because node-level parsing will only override position if explicitly specified. + lightNode.position.set( 0, 0, 0 ); + + lightNode.decay = 2; + + assignExtrasToUserData( lightNode, lightDef ); + + if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity; + + lightNode.name = parser.createUniqueName( lightDef.name || ( 'light_' + lightIndex ) ); + + dependency = Promise.resolve( lightNode ); + + parser.cache.add( cacheKey, dependency ); + + return dependency; + + } + + getDependency( type, index ) { + + if ( type !== 'light' ) return; + + return this._loadLight( index ); + + } + + createNodeAttachment( nodeIndex ) { + + const self = this; + const parser = this.parser; + const json = parser.json; + const nodeDef = json.nodes[ nodeIndex ]; + const lightDef = ( nodeDef.extensions && nodeDef.extensions[ this.name ] ) || {}; + const lightIndex = lightDef.light; + + if ( lightIndex === undefined ) return null; + + return this._loadLight( lightIndex ).then( function ( light ) { + + return parser._getNodeRef( self.cache, lightIndex, light ); + + } ); + + } + +} + +/** + * Unlit Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit + */ +class GLTFMaterialsUnlitExtension { + + constructor() { + + this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; + + } + + getMaterialType() { + + return MeshBasicMaterial; + + } + + extendParams( materialParams, materialDef, parser ) { + + const pending = []; + + materialParams.color = new Color( 1.0, 1.0, 1.0 ); + materialParams.opacity = 1.0; + + const metallicRoughness = materialDef.pbrMetallicRoughness; + + if ( metallicRoughness ) { + + if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { + + const array = metallicRoughness.baseColorFactor; + + materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace ); + materialParams.opacity = array[ 3 ]; + + } + + if ( metallicRoughness.baseColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) ); + + } + + } + + return Promise.all( pending ); + + } + +} + +/** + * Materials Emissive Strength Extension + * + * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md + */ +class GLTFMaterialsEmissiveStrengthExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const emissiveStrength = materialDef.extensions[ this.name ].emissiveStrength; + + if ( emissiveStrength !== undefined ) { + + materialParams.emissiveIntensity = emissiveStrength; + + } + + return Promise.resolve(); + + } + +} + +/** + * Clearcoat Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat + */ +class GLTFMaterialsClearcoatExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.clearcoatFactor !== undefined ) { + + materialParams.clearcoat = extension.clearcoatFactor; + + } + + if ( extension.clearcoatTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'clearcoatMap', extension.clearcoatTexture ) ); + + } + + if ( extension.clearcoatRoughnessFactor !== undefined ) { + + materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor; + + } + + if ( extension.clearcoatRoughnessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture ) ); + + } + + if ( extension.clearcoatNormalTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture ) ); + + if ( extension.clearcoatNormalTexture.scale !== undefined ) { + + const scale = extension.clearcoatNormalTexture.scale; + + materialParams.clearcoatNormalScale = new Vector2( scale, scale ); + + } + + } + + return Promise.all( pending ); + + } + +} + +/** + * Materials dispersion Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_dispersion + */ +class GLTFMaterialsDispersionExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_DISPERSION; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const extension = materialDef.extensions[ this.name ]; + + materialParams.dispersion = extension.dispersion !== undefined ? extension.dispersion : 0; + + return Promise.resolve(); + + } + +} + +/** + * Iridescence Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence + */ +class GLTFMaterialsIridescenceExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.iridescenceFactor !== undefined ) { + + materialParams.iridescence = extension.iridescenceFactor; + + } + + if ( extension.iridescenceTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceMap', extension.iridescenceTexture ) ); + + } + + if ( extension.iridescenceIor !== undefined ) { + + materialParams.iridescenceIOR = extension.iridescenceIor; + + } + + if ( materialParams.iridescenceThicknessRange === undefined ) { + + materialParams.iridescenceThicknessRange = [ 100, 400 ]; + + } + + if ( extension.iridescenceThicknessMinimum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 0 ] = extension.iridescenceThicknessMinimum; + + } + + if ( extension.iridescenceThicknessMaximum !== undefined ) { + + materialParams.iridescenceThicknessRange[ 1 ] = extension.iridescenceThicknessMaximum; + + } + + if ( extension.iridescenceThicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Sheen Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen + */ +class GLTFMaterialsSheenExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SHEEN; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + materialParams.sheenColor = new Color( 0, 0, 0 ); + materialParams.sheenRoughness = 0; + materialParams.sheen = 1; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.sheenColorFactor !== undefined ) { + + const colorFactor = extension.sheenColorFactor; + materialParams.sheenColor.setRGB( colorFactor[ 0 ], colorFactor[ 1 ], colorFactor[ 2 ], LinearSRGBColorSpace ); + + } + + if ( extension.sheenRoughnessFactor !== undefined ) { + + materialParams.sheenRoughness = extension.sheenRoughnessFactor; + + } + + if ( extension.sheenColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenColorMap', extension.sheenColorTexture, SRGBColorSpace ) ); + + } + + if ( extension.sheenRoughnessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Transmission Materials Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission + * Draft: https://github.com/KhronosGroup/glTF/pull/1698 + */ +class GLTFMaterialsTransmissionExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.transmissionFactor !== undefined ) { + + materialParams.transmission = extension.transmissionFactor; + + } + + if ( extension.transmissionTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'transmissionMap', extension.transmissionTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Materials Volume Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume + */ +class GLTFMaterialsVolumeExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_VOLUME; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0; + + if ( extension.thicknessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'thicknessMap', extension.thicknessTexture ) ); + + } + + materialParams.attenuationDistance = extension.attenuationDistance || Infinity; + + const colorArray = extension.attenuationColor || [ 1, 1, 1 ]; + materialParams.attenuationColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace ); + + return Promise.all( pending ); + + } + +} + +/** + * Materials ior Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior + */ +class GLTFMaterialsIorExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_IOR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const extension = materialDef.extensions[ this.name ]; + + materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5; + + return Promise.resolve(); + + } + +} + +/** + * Materials specular Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular + */ +class GLTFMaterialsSpecularExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0; + + if ( extension.specularTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularIntensityMap', extension.specularTexture ) ); + + } + + const colorArray = extension.specularColorFactor || [ 1, 1, 1 ]; + materialParams.specularColor = new Color().setRGB( colorArray[ 0 ], colorArray[ 1 ], colorArray[ 2 ], LinearSRGBColorSpace ); + + if ( extension.specularColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'specularColorMap', extension.specularColorTexture, SRGBColorSpace ) ); + + } + + return Promise.all( pending ); + + } + +} + + +/** + * Materials bump Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/EXT_materials_bump + */ +class GLTFMaterialsBumpExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.EXT_MATERIALS_BUMP; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + materialParams.bumpScale = extension.bumpFactor !== undefined ? extension.bumpFactor : 1.0; + + if ( extension.bumpTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'bumpMap', extension.bumpTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * Materials anisotropy Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_anisotropy + */ +class GLTFMaterialsAnisotropyExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_MATERIALS_ANISOTROPY; + + } + + getMaterialType( materialIndex ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) return null; + + return MeshPhysicalMaterial; + + } + + extendMaterialParams( materialIndex, materialParams ) { + + const parser = this.parser; + const materialDef = parser.json.materials[ materialIndex ]; + + if ( ! materialDef.extensions || ! materialDef.extensions[ this.name ] ) { + + return Promise.resolve(); + + } + + const pending = []; + + const extension = materialDef.extensions[ this.name ]; + + if ( extension.anisotropyStrength !== undefined ) { + + materialParams.anisotropy = extension.anisotropyStrength; + + } + + if ( extension.anisotropyRotation !== undefined ) { + + materialParams.anisotropyRotation = extension.anisotropyRotation; + + } + + if ( extension.anisotropyTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'anisotropyMap', extension.anisotropyTexture ) ); + + } + + return Promise.all( pending ); + + } + +} + +/** + * BasisU Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu + */ +class GLTFTextureBasisUExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.KHR_TEXTURE_BASISU; + + } + + loadTexture( textureIndex ) { + + const parser = this.parser; + const json = parser.json; + + const textureDef = json.textures[ textureIndex ]; + + if ( ! textureDef.extensions || ! textureDef.extensions[ this.name ] ) { + + return null; + + } + + const extension = textureDef.extensions[ this.name ]; + const loader = parser.options.ktx2Loader; + + if ( ! loader ) { + + if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) { + + throw new Error( 'THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures' ); + + } else { + + // Assumes that the extension is optional and that a fallback texture is present + return null; + + } + + } + + return parser.loadTextureImage( textureIndex, extension.source, loader ); + + } + +} + +/** + * WebP Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp + */ +class GLTFTextureWebPExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_WEBP; + this.isSupported = null; + + } + + loadTexture( textureIndex ) { + + const name = this.name; + const parser = this.parser; + const json = parser.json; + + const textureDef = json.textures[ textureIndex ]; + + if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) { + + return null; + + } + + const extension = textureDef.extensions[ name ]; + const source = json.images[ extension.source ]; + + let loader = parser.textureLoader; + if ( source.uri ) { + + const handler = parser.options.manager.getHandler( source.uri ); + if ( handler !== null ) loader = handler; + + } + + return this.detectSupport().then( function ( isSupported ) { + + if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader ); + + if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) { + + throw new Error( 'THREE.GLTFLoader: WebP required by asset but unsupported.' ); + + } + + // Fall back to PNG or JPEG. + return parser.loadTexture( textureIndex ); + + } ); + + } + + detectSupport() { + + if ( ! this.isSupported ) { + + this.isSupported = new Promise( function ( resolve ) { + + const image = new Image(); + + // Lossy test image. Support for lossy images doesn't guarantee support for all + // WebP images, unfortunately. + image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'; + + image.onload = image.onerror = function () { + + resolve( image.height === 1 ); + + }; + + } ); + + } + + return this.isSupported; + + } + +} + +/** + * AVIF Texture Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_avif + */ +class GLTFTextureAVIFExtension { + + constructor( parser ) { + + this.parser = parser; + this.name = EXTENSIONS.EXT_TEXTURE_AVIF; + this.isSupported = null; + + } + + loadTexture( textureIndex ) { + + const name = this.name; + const parser = this.parser; + const json = parser.json; + + const textureDef = json.textures[ textureIndex ]; + + if ( ! textureDef.extensions || ! textureDef.extensions[ name ] ) { + + return null; + + } + + const extension = textureDef.extensions[ name ]; + const source = json.images[ extension.source ]; + + let loader = parser.textureLoader; + if ( source.uri ) { + + const handler = parser.options.manager.getHandler( source.uri ); + if ( handler !== null ) loader = handler; + + } + + return this.detectSupport().then( function ( isSupported ) { + + if ( isSupported ) return parser.loadTextureImage( textureIndex, extension.source, loader ); + + if ( json.extensionsRequired && json.extensionsRequired.indexOf( name ) >= 0 ) { + + throw new Error( 'THREE.GLTFLoader: AVIF required by asset but unsupported.' ); + + } + + // Fall back to PNG or JPEG. + return parser.loadTexture( textureIndex ); + + } ); + + } + + detectSupport() { + + if ( ! this.isSupported ) { + + this.isSupported = new Promise( function ( resolve ) { + + const image = new Image(); + + // Lossy test image. + image.src = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI='; + image.onload = image.onerror = function () { + + resolve( image.height === 1 ); + + }; + + } ); + + } + + return this.isSupported; + + } + +} + +/** + * meshopt BufferView Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression + */ +class GLTFMeshoptCompression { + + constructor( parser ) { + + this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION; + this.parser = parser; + + } + + loadBufferView( index ) { + + const json = this.parser.json; + const bufferView = json.bufferViews[ index ]; + + if ( bufferView.extensions && bufferView.extensions[ this.name ] ) { + + const extensionDef = bufferView.extensions[ this.name ]; + + const buffer = this.parser.getDependency( 'buffer', extensionDef.buffer ); + const decoder = this.parser.options.meshoptDecoder; + + if ( ! decoder || ! decoder.supported ) { + + if ( json.extensionsRequired && json.extensionsRequired.indexOf( this.name ) >= 0 ) { + + throw new Error( 'THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files' ); + + } else { + + // Assumes that the extension is optional and that fallback buffer data is present + return null; + + } + + } + + return buffer.then( function ( res ) { + + const byteOffset = extensionDef.byteOffset || 0; + const byteLength = extensionDef.byteLength || 0; + + const count = extensionDef.count; + const stride = extensionDef.byteStride; + + const source = new Uint8Array( res, byteOffset, byteLength ); + + if ( decoder.decodeGltfBufferAsync ) { + + return decoder.decodeGltfBufferAsync( count, stride, source, extensionDef.mode, extensionDef.filter ).then( function ( res ) { + + return res.buffer; + + } ); + + } else { + + // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync + return decoder.ready.then( function () { + + const result = new ArrayBuffer( count * stride ); + decoder.decodeGltfBuffer( new Uint8Array( result ), count, stride, source, extensionDef.mode, extensionDef.filter ); + return result; + + } ); + + } + + } ); + + } else { + + return null; + + } + + } + +} + +/** + * GPU Instancing Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing + * + */ +class GLTFMeshGpuInstancing { + + constructor( parser ) { + + this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING; + this.parser = parser; + + } + + createNodeMesh( nodeIndex ) { + + const json = this.parser.json; + const nodeDef = json.nodes[ nodeIndex ]; + + if ( ! nodeDef.extensions || ! nodeDef.extensions[ this.name ] || + nodeDef.mesh === undefined ) { + + return null; + + } + + const meshDef = json.meshes[ nodeDef.mesh ]; + + // No Points or Lines + Instancing support yet + + for ( const primitive of meshDef.primitives ) { + + if ( primitive.mode !== WEBGL_CONSTANTS.TRIANGLES && + primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP && + primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN && + primitive.mode !== undefined ) { + + return null; + + } + + } + + const extensionDef = nodeDef.extensions[ this.name ]; + const attributesDef = extensionDef.attributes; + + // @TODO: Can we support InstancedMesh + SkinnedMesh? + + const pending = []; + const attributes = {}; + + for ( const key in attributesDef ) { + + pending.push( this.parser.getDependency( 'accessor', attributesDef[ key ] ).then( accessor => { + + attributes[ key ] = accessor; + return attributes[ key ]; + + } ) ); + + } + + if ( pending.length < 1 ) { + + return null; + + } + + pending.push( this.parser.createNodeMesh( nodeIndex ) ); + + return Promise.all( pending ).then( results => { + + const nodeObject = results.pop(); + const meshes = nodeObject.isGroup ? nodeObject.children : [ nodeObject ]; + const count = results[ 0 ].count; // All attribute counts should be same + const instancedMeshes = []; + + for ( const mesh of meshes ) { + + // Temporal variables + const m = new Matrix4(); + const p = new Vector3(); + const q = new Quaternion(); + const s = new Vector3( 1, 1, 1 ); + + const instancedMesh = new InstancedMesh( mesh.geometry, mesh.material, count ); + + for ( let i = 0; i < count; i ++ ) { + + if ( attributes.TRANSLATION ) { + + p.fromBufferAttribute( attributes.TRANSLATION, i ); + + } + + if ( attributes.ROTATION ) { + + q.fromBufferAttribute( attributes.ROTATION, i ); + + } + + if ( attributes.SCALE ) { + + s.fromBufferAttribute( attributes.SCALE, i ); + + } + + instancedMesh.setMatrixAt( i, m.compose( p, q, s ) ); + + } + + // Add instance attributes to the geometry, excluding TRS. + for ( const attributeName in attributes ) { + + if ( attributeName === '_COLOR_0' ) { + + const attr = attributes[ attributeName ]; + instancedMesh.instanceColor = new InstancedBufferAttribute( attr.array, attr.itemSize, attr.normalized ); + + } else if ( attributeName !== 'TRANSLATION' && + attributeName !== 'ROTATION' && + attributeName !== 'SCALE' ) { + + mesh.geometry.setAttribute( attributeName, attributes[ attributeName ] ); + + } + + } + + // Just in case + Object3D.prototype.copy.call( instancedMesh, mesh ); + + this.parser.assignFinalMaterial( instancedMesh ); + + instancedMeshes.push( instancedMesh ); + + } + + if ( nodeObject.isGroup ) { + + nodeObject.clear(); + + nodeObject.add( ... instancedMeshes ); + + return nodeObject; + + } + + return instancedMeshes[ 0 ]; + + } ); + + } + +} + +/* BINARY EXTENSION */ +const BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; +const BINARY_EXTENSION_HEADER_LENGTH = 12; +const BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; + +class GLTFBinaryExtension { + + constructor( data ) { + + this.name = EXTENSIONS.KHR_BINARY_GLTF; + this.content = null; + this.body = null; + + const headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); + const textDecoder = new TextDecoder(); + + this.header = { + magic: textDecoder.decode( new Uint8Array( data.slice( 0, 4 ) ) ), + version: headerView.getUint32( 4, true ), + length: headerView.getUint32( 8, true ) + }; + + if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) { + + throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' ); + + } else if ( this.header.version < 2.0 ) { + + throw new Error( 'THREE.GLTFLoader: Legacy binary file detected.' ); + + } + + const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH; + const chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); + let chunkIndex = 0; + + while ( chunkIndex < chunkContentsLength ) { + + const chunkLength = chunkView.getUint32( chunkIndex, true ); + chunkIndex += 4; + + const chunkType = chunkView.getUint32( chunkIndex, true ); + chunkIndex += 4; + + if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { + + const contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); + this.content = textDecoder.decode( contentArray ); + + } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { + + const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; + this.body = data.slice( byteOffset, byteOffset + chunkLength ); + + } + + // Clients must ignore chunks with unknown types. + + chunkIndex += chunkLength; + + } + + if ( this.content === null ) { + + throw new Error( 'THREE.GLTFLoader: JSON content not found.' ); + + } + + } + +} + +/** + * DRACO Mesh Compression Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression + */ +class GLTFDracoMeshCompressionExtension { + + constructor( json, dracoLoader ) { + + if ( ! dracoLoader ) { + + throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); + + } + + this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; + this.json = json; + this.dracoLoader = dracoLoader; + this.dracoLoader.preload(); + + } + + decodePrimitive( primitive, parser ) { + + const json = this.json; + const dracoLoader = this.dracoLoader; + const bufferViewIndex = primitive.extensions[ this.name ].bufferView; + const gltfAttributeMap = primitive.extensions[ this.name ].attributes; + const threeAttributeMap = {}; + const attributeNormalizedMap = {}; + const attributeTypeMap = {}; + + for ( const attributeName in gltfAttributeMap ) { + + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + + threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ]; + + } + + for ( const attributeName in primitive.attributes ) { + + const threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); + + if ( gltfAttributeMap[ attributeName ] !== undefined ) { + + const accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; + const componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + + attributeTypeMap[ threeAttributeName ] = componentType.name; + attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true; + + } + + } + + return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) { + + return new Promise( function ( resolve, reject ) { + + dracoLoader.decodeDracoFile( bufferView, function ( geometry ) { + + for ( const attributeName in geometry.attributes ) { + + const attribute = geometry.attributes[ attributeName ]; + const normalized = attributeNormalizedMap[ attributeName ]; + + if ( normalized !== undefined ) attribute.normalized = normalized; + + } + + resolve( geometry ); + + }, threeAttributeMap, attributeTypeMap, LinearSRGBColorSpace, reject ); + + } ); + + } ); + + } + +} + +/** + * Texture Transform Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform + */ +class GLTFTextureTransformExtension { + + constructor() { + + this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; + + } + + extendTexture( texture, transform ) { + + if ( ( transform.texCoord === undefined || transform.texCoord === texture.channel ) + && transform.offset === undefined + && transform.rotation === undefined + && transform.scale === undefined ) { + + // See https://github.com/mrdoob/three.js/issues/21819. + return texture; + + } + + texture = texture.clone(); + + if ( transform.texCoord !== undefined ) { + + texture.channel = transform.texCoord; + + } + + if ( transform.offset !== undefined ) { + + texture.offset.fromArray( transform.offset ); + + } + + if ( transform.rotation !== undefined ) { + + texture.rotation = transform.rotation; + + } + + if ( transform.scale !== undefined ) { + + texture.repeat.fromArray( transform.scale ); + + } + + texture.needsUpdate = true; + + return texture; + + } + +} + +/** + * Mesh Quantization Extension + * + * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization + */ +class GLTFMeshQuantizationExtension { + + constructor() { + + this.name = EXTENSIONS.KHR_MESH_QUANTIZATION; + + } + +} + +/*********************************/ +/********** INTERPOLATION ********/ +/*********************************/ + +// Spline Interpolation +// Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation +class GLTFCubicSplineInterpolant extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + } + + copySampleValue_( index ) { + + // Copies a sample value to the result buffer. See description of glTF + // CUBICSPLINE values layout in interpolate_() function below. + + const result = this.resultBuffer, + values = this.sampleValues, + valueSize = this.valueSize, + offset = index * valueSize * 3 + valueSize; + + for ( let i = 0; i !== valueSize; i ++ ) { + + result[ i ] = values[ offset + i ]; + + } + + return result; + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; + + const stride2 = stride * 2; + const stride3 = stride * 3; + + const td = t1 - t0; + + const p = ( t - t0 ) / td; + const pp = p * p; + const ppp = pp * p; + + const offset1 = i1 * stride3; + const offset0 = offset1 - stride3; + + const s2 = - 2 * ppp + 3 * pp; + const s3 = ppp - pp; + const s0 = 1 - s2; + const s1 = s3 - pp + p; + + // Layout of keyframe output values for CUBICSPLINE animations: + // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] + for ( let i = 0; i !== stride; i ++ ) { + + const p0 = values[ offset0 + i + stride ]; // splineVertex_k + const m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) + const p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 + const m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) + + result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; + + } + + return result; + + } + +} + +const _q = new Quaternion(); + +class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant { + + interpolate_( i1, t0, t, t1 ) { + + const result = super.interpolate_( i1, t0, t, t1 ); + + _q.fromArray( result ).normalize().toArray( result ); + + return result; + + } + +} + + +/*********************************/ +/********** INTERNALS ************/ +/*********************************/ + +/* CONSTANTS */ + +const WEBGL_CONSTANTS = { + FLOAT: 5126, + //FLOAT_MAT2: 35674, + FLOAT_MAT3: 35675, + FLOAT_MAT4: 35676, + FLOAT_VEC2: 35664, + FLOAT_VEC3: 35665, + FLOAT_VEC4: 35666, + LINEAR: 9729, + REPEAT: 10497, + SAMPLER_2D: 35678, + POINTS: 0, + LINES: 1, + LINE_LOOP: 2, + LINE_STRIP: 3, + TRIANGLES: 4, + TRIANGLE_STRIP: 5, + TRIANGLE_FAN: 6, + UNSIGNED_BYTE: 5121, + UNSIGNED_SHORT: 5123 +}; + +const WEBGL_COMPONENT_TYPES = { + 5120: Int8Array, + 5121: Uint8Array, + 5122: Int16Array, + 5123: Uint16Array, + 5125: Uint32Array, + 5126: Float32Array +}; + +const WEBGL_FILTERS = { + 9728: NearestFilter, + 9729: LinearFilter, + 9984: NearestMipmapNearestFilter, + 9985: LinearMipmapNearestFilter, + 9986: NearestMipmapLinearFilter, + 9987: LinearMipmapLinearFilter +}; + +const WEBGL_WRAPPINGS = { + 33071: ClampToEdgeWrapping, + 33648: MirroredRepeatWrapping, + 10497: RepeatWrapping +}; + +const WEBGL_TYPE_SIZES = { + 'SCALAR': 1, + 'VEC2': 2, + 'VEC3': 3, + 'VEC4': 4, + 'MAT2': 4, + 'MAT3': 9, + 'MAT4': 16 +}; + +const ATTRIBUTES = { + POSITION: 'position', + NORMAL: 'normal', + TANGENT: 'tangent', + TEXCOORD_0: 'uv', + TEXCOORD_1: 'uv1', + TEXCOORD_2: 'uv2', + TEXCOORD_3: 'uv3', + COLOR_0: 'color', + WEIGHTS_0: 'skinWeight', + JOINTS_0: 'skinIndex', +}; + +const PATH_PROPERTIES = { + scale: 'scale', + translation: 'position', + rotation: 'quaternion', + weights: 'morphTargetInfluences' +}; + +const INTERPOLATION = { + CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each + // keyframe track will be initialized with a default interpolation type, then modified. + LINEAR: InterpolateLinear, + STEP: InterpolateDiscrete +}; + +const ALPHA_MODES = { + OPAQUE: 'OPAQUE', + MASK: 'MASK', + BLEND: 'BLEND' +}; + +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material + */ +function createDefaultMaterial( cache ) { + + if ( cache[ 'DefaultMaterial' ] === undefined ) { + + cache[ 'DefaultMaterial' ] = new MeshStandardMaterial( { + color: 0xFFFFFF, + emissive: 0x000000, + metalness: 1, + roughness: 1, + transparent: false, + depthTest: true, + side: FrontSide + } ); + + } + + return cache[ 'DefaultMaterial' ]; + +} + +function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { + + // Add unknown glTF extensions to an object's userData. + + for ( const name in objectDef.extensions ) { + + if ( knownExtensions[ name ] === undefined ) { + + object.userData.gltfExtensions = object.userData.gltfExtensions || {}; + object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; + + } + + } + +} + +/** + * @param {Object3D|Material|BufferGeometry} object + * @param {GLTF.definition} gltfDef + */ +function assignExtrasToUserData( object, gltfDef ) { + + if ( gltfDef.extras !== undefined ) { + + if ( typeof gltfDef.extras === 'object' ) { + + Object.assign( object.userData, gltfDef.extras ); + + } else { + + console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); + + } + + } + +} + +/** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets + * + * @param {BufferGeometry} geometry + * @param {Array} targets + * @param {GLTFParser} parser + * @return {Promise} + */ +function addMorphTargets( geometry, targets, parser ) { + + let hasMorphPosition = false; + let hasMorphNormal = false; + let hasMorphColor = false; + + for ( let i = 0, il = targets.length; i < il; i ++ ) { + + const target = targets[ i ]; + + if ( target.POSITION !== undefined ) hasMorphPosition = true; + if ( target.NORMAL !== undefined ) hasMorphNormal = true; + if ( target.COLOR_0 !== undefined ) hasMorphColor = true; + + if ( hasMorphPosition && hasMorphNormal && hasMorphColor ) break; + + } + + if ( ! hasMorphPosition && ! hasMorphNormal && ! hasMorphColor ) return Promise.resolve( geometry ); + + const pendingPositionAccessors = []; + const pendingNormalAccessors = []; + const pendingColorAccessors = []; + + for ( let i = 0, il = targets.length; i < il; i ++ ) { + + const target = targets[ i ]; + + if ( hasMorphPosition ) { + + const pendingAccessor = target.POSITION !== undefined + ? parser.getDependency( 'accessor', target.POSITION ) + : geometry.attributes.position; + + pendingPositionAccessors.push( pendingAccessor ); + + } + + if ( hasMorphNormal ) { + + const pendingAccessor = target.NORMAL !== undefined + ? parser.getDependency( 'accessor', target.NORMAL ) + : geometry.attributes.normal; + + pendingNormalAccessors.push( pendingAccessor ); + + } + + if ( hasMorphColor ) { + + const pendingAccessor = target.COLOR_0 !== undefined + ? parser.getDependency( 'accessor', target.COLOR_0 ) + : geometry.attributes.color; + + pendingColorAccessors.push( pendingAccessor ); + + } + + } + + return Promise.all( [ + Promise.all( pendingPositionAccessors ), + Promise.all( pendingNormalAccessors ), + Promise.all( pendingColorAccessors ) + ] ).then( function ( accessors ) { + + const morphPositions = accessors[ 0 ]; + const morphNormals = accessors[ 1 ]; + const morphColors = accessors[ 2 ]; + + if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; + if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; + if ( hasMorphColor ) geometry.morphAttributes.color = morphColors; + geometry.morphTargetsRelative = true; + + return geometry; + + } ); + +} + +/** + * @param {Mesh} mesh + * @param {GLTF.Mesh} meshDef + */ +function updateMorphTargets( mesh, meshDef ) { + + mesh.updateMorphTargets(); + + if ( meshDef.weights !== undefined ) { + + for ( let i = 0, il = meshDef.weights.length; i < il; i ++ ) { + + mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; + + } + + } + + // .extras has user-defined data, so check that .extras.targetNames is an array. + if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { + + const targetNames = meshDef.extras.targetNames; + + if ( mesh.morphTargetInfluences.length === targetNames.length ) { + + mesh.morphTargetDictionary = {}; + + for ( let i = 0, il = targetNames.length; i < il; i ++ ) { + + mesh.morphTargetDictionary[ targetNames[ i ] ] = i; + + } + + } else { + + console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); + + } + + } + +} + +function createPrimitiveKey( primitiveDef ) { + + let geometryKey; + + const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; + + if ( dracoExtension ) { + + geometryKey = 'draco:' + dracoExtension.bufferView + + ':' + dracoExtension.indices + + ':' + createAttributesKey( dracoExtension.attributes ); + + } else { + + geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; + + } + + if ( primitiveDef.targets !== undefined ) { + + for ( let i = 0, il = primitiveDef.targets.length; i < il; i ++ ) { + + geometryKey += ':' + createAttributesKey( primitiveDef.targets[ i ] ); + + } + + } + + return geometryKey; + +} + +function createAttributesKey( attributes ) { + + let attributesKey = ''; + + const keys = Object.keys( attributes ).sort(); + + for ( let i = 0, il = keys.length; i < il; i ++ ) { + + attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; + + } + + return attributesKey; + +} + +function getNormalizedComponentScale( constructor ) { + + // Reference: + // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data + + switch ( constructor ) { + + case Int8Array: + return 1 / 127; + + case Uint8Array: + return 1 / 255; + + case Int16Array: + return 1 / 32767; + + case Uint16Array: + return 1 / 65535; + + default: + throw new Error( 'THREE.GLTFLoader: Unsupported normalized accessor component type.' ); + + } + +} + +function getImageURIMimeType( uri ) { + + if ( uri.search( /\.jpe?g($|\?)/i ) > 0 || uri.search( /^data\:image\/jpeg/ ) === 0 ) return 'image/jpeg'; + if ( uri.search( /\.webp($|\?)/i ) > 0 || uri.search( /^data\:image\/webp/ ) === 0 ) return 'image/webp'; + + return 'image/png'; + +} + +const _identityMatrix = new Matrix4(); + +/* GLTF PARSER */ + +class GLTFParser { + + constructor( json = {}, options = {} ) { + + this.json = json; + this.extensions = {}; + this.plugins = {}; + this.options = options; + + // loader object cache + this.cache = new GLTFRegistry(); + + // associations between Three.js objects and glTF elements + this.associations = new Map(); + + // BufferGeometry caching + this.primitiveCache = {}; + + // Node cache + this.nodeCache = {}; + + // Object3D instance caches + this.meshCache = { refs: {}, uses: {} }; + this.cameraCache = { refs: {}, uses: {} }; + this.lightCache = { refs: {}, uses: {} }; + + this.sourceCache = {}; + this.textureCache = {}; + + // Track node names, to ensure no duplicates + this.nodeNamesUsed = {}; + + // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the + // expensive work of uploading a texture to the GPU off the main thread. + + let isSafari = false; + let safariVersion = - 1; + let isFirefox = false; + let firefoxVersion = - 1; + + if ( typeof navigator !== 'undefined' ) { + + const userAgent = navigator.userAgent; + + isSafari = /^((?!chrome|android).)*safari/i.test( userAgent ) === true; + const safariMatch = userAgent.match( /Version\/(\d+)/ ); + safariVersion = isSafari && safariMatch ? parseInt( safariMatch[ 1 ], 10 ) : - 1; + + isFirefox = userAgent.indexOf( 'Firefox' ) > - 1; + firefoxVersion = isFirefox ? userAgent.match( /Firefox\/([0-9]+)\./ )[ 1 ] : - 1; + + } + + if ( typeof createImageBitmap === 'undefined' || ( isSafari && safariVersion < 17 ) || ( isFirefox && firefoxVersion < 98 ) ) { + + this.textureLoader = new TextureLoader( this.options.manager ); + + } else { + + this.textureLoader = new ImageBitmapLoader( this.options.manager ); + + } + + this.textureLoader.setCrossOrigin( this.options.crossOrigin ); + this.textureLoader.setRequestHeader( this.options.requestHeader ); + + this.fileLoader = new FileLoader( this.options.manager ); + this.fileLoader.setResponseType( 'arraybuffer' ); + + if ( this.options.crossOrigin === 'use-credentials' ) { + + this.fileLoader.setWithCredentials( true ); + + } + + } + + setExtensions( extensions ) { + + this.extensions = extensions; + + } + + setPlugins( plugins ) { + + this.plugins = plugins; + + } + + parse( onLoad, onError ) { + + const parser = this; + const json = this.json; + const extensions = this.extensions; + + // Clear the loader cache + this.cache.removeAll(); + this.nodeCache = {}; + + // Mark the special nodes/meshes in json for efficient parse + this._invokeAll( function ( ext ) { + + return ext._markDefs && ext._markDefs(); + + } ); + + Promise.all( this._invokeAll( function ( ext ) { + + return ext.beforeRoot && ext.beforeRoot(); + + } ) ).then( function () { + + return Promise.all( [ + + parser.getDependencies( 'scene' ), + parser.getDependencies( 'animation' ), + parser.getDependencies( 'camera' ), + + ] ); + + } ).then( function ( dependencies ) { + + const result = { + scene: dependencies[ 0 ][ json.scene || 0 ], + scenes: dependencies[ 0 ], + animations: dependencies[ 1 ], + cameras: dependencies[ 2 ], + asset: json.asset, + parser: parser, + userData: {} + }; + + addUnknownExtensionsToUserData( extensions, result, json ); + + assignExtrasToUserData( result, json ); + + return Promise.all( parser._invokeAll( function ( ext ) { + + return ext.afterRoot && ext.afterRoot( result ); + + } ) ).then( function () { + + for ( const scene of result.scenes ) { + + scene.updateMatrixWorld(); + + } + + onLoad( result ); + + } ); + + } ).catch( onError ); + + } + + /** + * Marks the special nodes/meshes in json for efficient parse. + */ + _markDefs() { + + const nodeDefs = this.json.nodes || []; + const skinDefs = this.json.skins || []; + const meshDefs = this.json.meshes || []; + + // Nothing in the node definition indicates whether it is a Bone or an + // Object3D. Use the skins' joint references to mark bones. + for ( let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { + + const joints = skinDefs[ skinIndex ].joints; + + for ( let i = 0, il = joints.length; i < il; i ++ ) { + + nodeDefs[ joints[ i ] ].isBone = true; + + } + + } + + // Iterate over all nodes, marking references to shared resources, + // as well as skeleton joints. + for ( let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { + + const nodeDef = nodeDefs[ nodeIndex ]; + + if ( nodeDef.mesh !== undefined ) { + + this._addNodeRef( this.meshCache, nodeDef.mesh ); + + // Nothing in the mesh definition indicates whether it is + // a SkinnedMesh or Mesh. Use the node's mesh reference + // to mark SkinnedMesh if node has skin. + if ( nodeDef.skin !== undefined ) { + + meshDefs[ nodeDef.mesh ].isSkinnedMesh = true; + + } + + } + + if ( nodeDef.camera !== undefined ) { + + this._addNodeRef( this.cameraCache, nodeDef.camera ); + + } + + } + + } + + /** + * Counts references to shared node / Object3D resources. These resources + * can be reused, or "instantiated", at multiple nodes in the scene + * hierarchy. Mesh, Camera, and Light instances are instantiated and must + * be marked. Non-scenegraph resources (like Materials, Geometries, and + * Textures) can be reused directly and are not marked here. + * + * Example: CesiumMilkTruck sample model reuses "Wheel" meshes. + */ + _addNodeRef( cache, index ) { + + if ( index === undefined ) return; + + if ( cache.refs[ index ] === undefined ) { + + cache.refs[ index ] = cache.uses[ index ] = 0; + + } + + cache.refs[ index ] ++; + + } + + /** Returns a reference to a shared resource, cloning it if necessary. */ + _getNodeRef( cache, index, object ) { + + if ( cache.refs[ index ] <= 1 ) return object; + + const ref = object.clone(); + + // Propagates mappings to the cloned object, prevents mappings on the + // original object from being lost. + const updateMappings = ( original, clone ) => { + + const mappings = this.associations.get( original ); + if ( mappings != null ) { + + this.associations.set( clone, mappings ); + + } + + for ( const [ i, child ] of original.children.entries() ) { + + updateMappings( child, clone.children[ i ] ); + + } + + }; + + updateMappings( object, ref ); + + ref.name += '_instance_' + ( cache.uses[ index ] ++ ); + + return ref; + + } + + _invokeOne( func ) { + + const extensions = Object.values( this.plugins ); + extensions.push( this ); + + for ( let i = 0; i < extensions.length; i ++ ) { + + const result = func( extensions[ i ] ); + + if ( result ) return result; + + } + + return null; + + } + + _invokeAll( func ) { + + const extensions = Object.values( this.plugins ); + extensions.unshift( this ); + + const pending = []; + + for ( let i = 0; i < extensions.length; i ++ ) { + + const result = func( extensions[ i ] ); + + if ( result ) pending.push( result ); + + } + + return pending; + + } + + /** + * Requests the specified dependency asynchronously, with caching. + * @param {string} type + * @param {number} index + * @return {Promise} + */ + getDependency( type, index ) { + + const cacheKey = type + ':' + index; + let dependency = this.cache.get( cacheKey ); + + if ( ! dependency ) { + + switch ( type ) { + + case 'scene': + dependency = this.loadScene( index ); + break; + + case 'node': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadNode && ext.loadNode( index ); + + } ); + break; + + case 'mesh': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadMesh && ext.loadMesh( index ); + + } ); + break; + + case 'accessor': + dependency = this.loadAccessor( index ); + break; + + case 'bufferView': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadBufferView && ext.loadBufferView( index ); + + } ); + break; + + case 'buffer': + dependency = this.loadBuffer( index ); + break; + + case 'material': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadMaterial && ext.loadMaterial( index ); + + } ); + break; + + case 'texture': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadTexture && ext.loadTexture( index ); + + } ); + break; + + case 'skin': + dependency = this.loadSkin( index ); + break; + + case 'animation': + dependency = this._invokeOne( function ( ext ) { + + return ext.loadAnimation && ext.loadAnimation( index ); + + } ); + break; + + case 'camera': + dependency = this.loadCamera( index ); + break; + + default: + dependency = this._invokeOne( function ( ext ) { + + return ext != this && ext.getDependency && ext.getDependency( type, index ); + + } ); + + if ( ! dependency ) { + + throw new Error( 'Unknown type: ' + type ); + + } + + break; + + } + + this.cache.add( cacheKey, dependency ); + + } + + return dependency; + + } + + /** + * Requests all dependencies of the specified type asynchronously, with caching. + * @param {string} type + * @return {Promise>} + */ + getDependencies( type ) { + + let dependencies = this.cache.get( type ); + + if ( ! dependencies ) { + + const parser = this; + const defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; + + dependencies = Promise.all( defs.map( function ( def, index ) { + + return parser.getDependency( type, index ); + + } ) ); + + this.cache.add( type, dependencies ); + + } + + return dependencies; + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views + * @param {number} bufferIndex + * @return {Promise} + */ + loadBuffer( bufferIndex ) { + + const bufferDef = this.json.buffers[ bufferIndex ]; + const loader = this.fileLoader; + + if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) { + + throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' ); + + } + + // If present, GLB container is required to be the first buffer. + if ( bufferDef.uri === undefined && bufferIndex === 0 ) { + + return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body ); + + } + + const options = this.options; + + return new Promise( function ( resolve, reject ) { + + loader.load( LoaderUtils.resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { + + reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) ); + + } ); + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views + * @param {number} bufferViewIndex + * @return {Promise} + */ + loadBufferView( bufferViewIndex ) { + + const bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; + + return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) { + + const byteLength = bufferViewDef.byteLength || 0; + const byteOffset = bufferViewDef.byteOffset || 0; + return buffer.slice( byteOffset, byteOffset + byteLength ); + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors + * @param {number} accessorIndex + * @return {Promise} + */ + loadAccessor( accessorIndex ) { + + const parser = this; + const json = this.json; + + const accessorDef = this.json.accessors[ accessorIndex ]; + + if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) { + + const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; + const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + const normalized = accessorDef.normalized === true; + + const array = new TypedArray( accessorDef.count * itemSize ); + return Promise.resolve( new BufferAttribute( array, itemSize, normalized ) ); + + } + + const pendingBufferViews = []; + + if ( accessorDef.bufferView !== undefined ) { + + pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) ); + + } else { + + pendingBufferViews.push( null ); + + } + + if ( accessorDef.sparse !== undefined ) { + + pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) ); + pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) ); + + } + + return Promise.all( pendingBufferViews ).then( function ( bufferViews ) { + + const bufferView = bufferViews[ 0 ]; + + const itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; + const TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; + + // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. + const elementBytes = TypedArray.BYTES_PER_ELEMENT; + const itemBytes = elementBytes * itemSize; + const byteOffset = accessorDef.byteOffset || 0; + const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; + const normalized = accessorDef.normalized === true; + let array, bufferAttribute; + + // The buffer is not interleaved if the stride is the item size in bytes. + if ( byteStride && byteStride !== itemBytes ) { + + // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer + // This makes sure that IBA.count reflects accessor.count properly + const ibSlice = Math.floor( byteOffset / byteStride ); + const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; + let ib = parser.cache.get( ibCacheKey ); + + if ( ! ib ) { + + array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes ); + + // Integer parameters to IB/IBA are in array elements, not bytes. + ib = new InterleavedBuffer( array, byteStride / elementBytes ); + + parser.cache.add( ibCacheKey, ib ); + + } + + bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized ); + + } else { + + if ( bufferView === null ) { + + array = new TypedArray( accessorDef.count * itemSize ); + + } else { + + array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize ); + + } + + bufferAttribute = new BufferAttribute( array, itemSize, normalized ); + + } + + // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors + if ( accessorDef.sparse !== undefined ) { + + const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; + const TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; + + const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; + const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; + + const sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); + const sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); + + if ( bufferView !== null ) { + + // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. + bufferAttribute = new BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized ); + + } + + // Ignore normalized since we copy from sparse + bufferAttribute.normalized = false; + + for ( let i = 0, il = sparseIndices.length; i < il; i ++ ) { + + const index = sparseIndices[ i ]; + + bufferAttribute.setX( index, sparseValues[ i * itemSize ] ); + if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] ); + if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] ); + if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] ); + if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' ); + + } + + bufferAttribute.normalized = normalized; + + } + + return bufferAttribute; + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures + * @param {number} textureIndex + * @return {Promise} + */ + loadTexture( textureIndex ) { + + const json = this.json; + const options = this.options; + const textureDef = json.textures[ textureIndex ]; + const sourceIndex = textureDef.source; + const sourceDef = json.images[ sourceIndex ]; + + let loader = this.textureLoader; + + if ( sourceDef.uri ) { + + const handler = options.manager.getHandler( sourceDef.uri ); + if ( handler !== null ) loader = handler; + + } + + return this.loadTextureImage( textureIndex, sourceIndex, loader ); + + } + + loadTextureImage( textureIndex, sourceIndex, loader ) { + + const parser = this; + const json = this.json; + + const textureDef = json.textures[ textureIndex ]; + const sourceDef = json.images[ sourceIndex ]; + + const cacheKey = ( sourceDef.uri || sourceDef.bufferView ) + ':' + textureDef.sampler; + + if ( this.textureCache[ cacheKey ] ) { + + // See https://github.com/mrdoob/three.js/issues/21559. + return this.textureCache[ cacheKey ]; + + } + + const promise = this.loadImageSource( sourceIndex, loader ).then( function ( texture ) { + + texture.flipY = false; + + texture.name = textureDef.name || sourceDef.name || ''; + + if ( texture.name === '' && typeof sourceDef.uri === 'string' && sourceDef.uri.startsWith( 'data:image/' ) === false ) { + + texture.name = sourceDef.uri; + + } + + const samplers = json.samplers || {}; + const sampler = samplers[ textureDef.sampler ] || {}; + + texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter; + texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter; + texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping; + texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping; + + parser.associations.set( texture, { textures: textureIndex } ); + + return texture; + + } ).catch( function () { + + return null; + + } ); + + this.textureCache[ cacheKey ] = promise; + + return promise; + + } + + loadImageSource( sourceIndex, loader ) { + + const parser = this; + const json = this.json; + const options = this.options; + + if ( this.sourceCache[ sourceIndex ] !== undefined ) { + + return this.sourceCache[ sourceIndex ].then( ( texture ) => texture.clone() ); + + } + + const sourceDef = json.images[ sourceIndex ]; + + const URL = self.URL || self.webkitURL; + + let sourceURI = sourceDef.uri || ''; + let isObjectURL = false; + + if ( sourceDef.bufferView !== undefined ) { + + // Load binary image data from bufferView, if provided. + + sourceURI = parser.getDependency( 'bufferView', sourceDef.bufferView ).then( function ( bufferView ) { + + isObjectURL = true; + const blob = new Blob( [ bufferView ], { type: sourceDef.mimeType } ); + sourceURI = URL.createObjectURL( blob ); + return sourceURI; + + } ); + + } else if ( sourceDef.uri === undefined ) { + + throw new Error( 'THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView' ); + + } + + const promise = Promise.resolve( sourceURI ).then( function ( sourceURI ) { + + return new Promise( function ( resolve, reject ) { + + let onLoad = resolve; + + if ( loader.isImageBitmapLoader === true ) { + + onLoad = function ( imageBitmap ) { + + const texture = new Texture( imageBitmap ); + texture.needsUpdate = true; + + resolve( texture ); + + }; + + } + + loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject ); + + } ); + + } ).then( function ( texture ) { + + // Clean up resources and configure Texture. + + if ( isObjectURL === true ) { + + URL.revokeObjectURL( sourceURI ); + + } + + assignExtrasToUserData( texture, sourceDef ); + + texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType( sourceDef.uri ); + + return texture; + + } ).catch( function ( error ) { + + console.error( 'THREE.GLTFLoader: Couldn\'t load texture', sourceURI ); + throw error; + + } ); + + this.sourceCache[ sourceIndex ] = promise; + return promise; + + } + + /** + * Asynchronously assigns a texture to the given material parameters. + * @param {Object} materialParams + * @param {string} mapName + * @param {Object} mapDef + * @return {Promise} + */ + assignTexture( materialParams, mapName, mapDef, colorSpace ) { + + const parser = this; + + return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) { + + if ( ! texture ) return null; + + if ( mapDef.texCoord !== undefined && mapDef.texCoord > 0 ) { + + texture = texture.clone(); + texture.channel = mapDef.texCoord; + + } + + if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { + + const transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; + + if ( transform ) { + + const gltfReference = parser.associations.get( texture ); + texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform ); + parser.associations.set( texture, gltfReference ); + + } + + } + + if ( colorSpace !== undefined ) { + + texture.colorSpace = colorSpace; + + } + + materialParams[ mapName ] = texture; + + return texture; + + } ); + + } + + /** + * Assigns final material to a Mesh, Line, or Points instance. The instance + * already has a material (generated from the glTF material options alone) + * but reuse of the same glTF material may require multiple threejs materials + * to accommodate different primitive types, defines, etc. New materials will + * be created if necessary, and reused from a cache. + * @param {Object3D} mesh Mesh, Line, or Points instance. + */ + assignFinalMaterial( mesh ) { + + const geometry = mesh.geometry; + let material = mesh.material; + + const useDerivativeTangents = geometry.attributes.tangent === undefined; + const useVertexColors = geometry.attributes.color !== undefined; + const useFlatShading = geometry.attributes.normal === undefined; + + if ( mesh.isPoints ) { + + const cacheKey = 'PointsMaterial:' + material.uuid; + + let pointsMaterial = this.cache.get( cacheKey ); + + if ( ! pointsMaterial ) { + + pointsMaterial = new PointsMaterial(); + Material.prototype.copy.call( pointsMaterial, material ); + pointsMaterial.color.copy( material.color ); + pointsMaterial.map = material.map; + pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px + + this.cache.add( cacheKey, pointsMaterial ); + + } + + material = pointsMaterial; + + } else if ( mesh.isLine ) { + + const cacheKey = 'LineBasicMaterial:' + material.uuid; + + let lineMaterial = this.cache.get( cacheKey ); + + if ( ! lineMaterial ) { + + lineMaterial = new LineBasicMaterial(); + Material.prototype.copy.call( lineMaterial, material ); + lineMaterial.color.copy( material.color ); + lineMaterial.map = material.map; + + this.cache.add( cacheKey, lineMaterial ); + + } + + material = lineMaterial; + + } + + // Clone the material if it will be modified + if ( useDerivativeTangents || useVertexColors || useFlatShading ) { + + let cacheKey = 'ClonedMaterial:' + material.uuid + ':'; + + if ( useDerivativeTangents ) cacheKey += 'derivative-tangents:'; + if ( useVertexColors ) cacheKey += 'vertex-colors:'; + if ( useFlatShading ) cacheKey += 'flat-shading:'; + + let cachedMaterial = this.cache.get( cacheKey ); + + if ( ! cachedMaterial ) { + + cachedMaterial = material.clone(); + + if ( useVertexColors ) cachedMaterial.vertexColors = true; + if ( useFlatShading ) cachedMaterial.flatShading = true; + + if ( useDerivativeTangents ) { + + // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995 + if ( cachedMaterial.normalScale ) cachedMaterial.normalScale.y *= - 1; + if ( cachedMaterial.clearcoatNormalScale ) cachedMaterial.clearcoatNormalScale.y *= - 1; + + } + + this.cache.add( cacheKey, cachedMaterial ); + + this.associations.set( cachedMaterial, this.associations.get( material ) ); + + } + + material = cachedMaterial; + + } + + mesh.material = material; + + } + + getMaterialType( /* materialIndex */ ) { + + return MeshStandardMaterial; + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials + * @param {number} materialIndex + * @return {Promise} + */ + loadMaterial( materialIndex ) { + + const parser = this; + const json = this.json; + const extensions = this.extensions; + const materialDef = json.materials[ materialIndex ]; + + let materialType; + const materialParams = {}; + const materialExtensions = materialDef.extensions || {}; + + const pending = []; + + if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) { + + const kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; + materialType = kmuExtension.getMaterialType(); + pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) ); + + } else { + + // Specification: + // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material + + const metallicRoughness = materialDef.pbrMetallicRoughness || {}; + + materialParams.color = new Color( 1.0, 1.0, 1.0 ); + materialParams.opacity = 1.0; + + if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { + + const array = metallicRoughness.baseColorFactor; + + materialParams.color.setRGB( array[ 0 ], array[ 1 ], array[ 2 ], LinearSRGBColorSpace ); + materialParams.opacity = array[ 3 ]; + + } + + if ( metallicRoughness.baseColorTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture, SRGBColorSpace ) ); + + } + + materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0; + materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0; + + if ( metallicRoughness.metallicRoughnessTexture !== undefined ) { + + pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) ); + pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) ); + + } + + materialType = this._invokeOne( function ( ext ) { + + return ext.getMaterialType && ext.getMaterialType( materialIndex ); + + } ); + + pending.push( Promise.all( this._invokeAll( function ( ext ) { + + return ext.extendMaterialParams && ext.extendMaterialParams( materialIndex, materialParams ); + + } ) ) ); + + } + + if ( materialDef.doubleSided === true ) { + + materialParams.side = DoubleSide; + + } + + const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; + + if ( alphaMode === ALPHA_MODES.BLEND ) { + + materialParams.transparent = true; + + // See: https://github.com/mrdoob/three.js/issues/17706 + materialParams.depthWrite = false; + + } else { + + materialParams.transparent = false; + + if ( alphaMode === ALPHA_MODES.MASK ) { + + materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; + + } + + } + + if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) { + + pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); + + materialParams.normalScale = new Vector2( 1, 1 ); + + if ( materialDef.normalTexture.scale !== undefined ) { + + const scale = materialDef.normalTexture.scale; + + materialParams.normalScale.set( scale, scale ); + + } + + } + + if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) { + + pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) ); + + if ( materialDef.occlusionTexture.strength !== undefined ) { + + materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; + + } + + } + + if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) { + + const emissiveFactor = materialDef.emissiveFactor; + materialParams.emissive = new Color().setRGB( emissiveFactor[ 0 ], emissiveFactor[ 1 ], emissiveFactor[ 2 ], LinearSRGBColorSpace ); + + } + + if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) { + + pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture, SRGBColorSpace ) ); + + } + + return Promise.all( pending ).then( function () { + + const material = new materialType( materialParams ); + + if ( materialDef.name ) material.name = materialDef.name; + + assignExtrasToUserData( material, materialDef ); + + parser.associations.set( material, { materials: materialIndex } ); + + if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef ); + + return material; + + } ); + + } + + /** When Object3D instances are targeted by animation, they need unique names. */ + createUniqueName( originalName ) { + + const sanitizedName = PropertyBinding.sanitizeNodeName( originalName || '' ); + + if ( sanitizedName in this.nodeNamesUsed ) { + + return sanitizedName + '_' + ( ++ this.nodeNamesUsed[ sanitizedName ] ); + + } else { + + this.nodeNamesUsed[ sanitizedName ] = 0; + + return sanitizedName; + + } + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry + * + * Creates BufferGeometries from primitives. + * + * @param {Array} primitives + * @return {Promise>} + */ + loadGeometries( primitives ) { + + const parser = this; + const extensions = this.extensions; + const cache = this.primitiveCache; + + function createDracoPrimitive( primitive ) { + + return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] + .decodePrimitive( primitive, parser ) + .then( function ( geometry ) { + + return addPrimitiveAttributes( geometry, primitive, parser ); + + } ); + + } + + const pending = []; + + for ( let i = 0, il = primitives.length; i < il; i ++ ) { + + const primitive = primitives[ i ]; + const cacheKey = createPrimitiveKey( primitive ); + + // See if we've already created this geometry + const cached = cache[ cacheKey ]; + + if ( cached ) { + + // Use the cached geometry if it exists + pending.push( cached.promise ); + + } else { + + let geometryPromise; + + if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) { + + // Use DRACO geometry if available + geometryPromise = createDracoPrimitive( primitive ); + + } else { + + // Otherwise create a new geometry + geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser ); + + } + + // Cache this geometry + cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise }; + + pending.push( geometryPromise ); + + } + + } + + return Promise.all( pending ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes + * @param {number} meshIndex + * @return {Promise} + */ + loadMesh( meshIndex ) { + + const parser = this; + const json = this.json; + const extensions = this.extensions; + + const meshDef = json.meshes[ meshIndex ]; + const primitives = meshDef.primitives; + + const pending = []; + + for ( let i = 0, il = primitives.length; i < il; i ++ ) { + + const material = primitives[ i ].material === undefined + ? createDefaultMaterial( this.cache ) + : this.getDependency( 'material', primitives[ i ].material ); + + pending.push( material ); + + } + + pending.push( parser.loadGeometries( primitives ) ); + + return Promise.all( pending ).then( function ( results ) { + + const materials = results.slice( 0, results.length - 1 ); + const geometries = results[ results.length - 1 ]; + + const meshes = []; + + for ( let i = 0, il = geometries.length; i < il; i ++ ) { + + const geometry = geometries[ i ]; + const primitive = primitives[ i ]; + + // 1. create Mesh + + let mesh; + + const material = materials[ i ]; + + if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || + primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || + primitive.mode === undefined ) { + + // .isSkinnedMesh isn't in glTF spec. See ._markDefs() + mesh = meshDef.isSkinnedMesh === true + ? new SkinnedMesh( geometry, material ) + : new Mesh( geometry, material ); + + if ( mesh.isSkinnedMesh === true ) { + + // normalize skin weights to fix malformed assets (see #15319) + mesh.normalizeSkinWeights(); + + } + + if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) { + + mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleStripDrawMode ); + + } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) { + + mesh.geometry = toTrianglesDrawMode( mesh.geometry, TriangleFanDrawMode ); + + } + + } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { + + mesh = new LineSegments( geometry, material ); + + } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) { + + mesh = new Line( geometry, material ); + + } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) { + + mesh = new LineLoop( geometry, material ); + + } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) { + + mesh = new Points( geometry, material ); + + } else { + + throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode ); + + } + + if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) { + + updateMorphTargets( mesh, meshDef ); + + } + + mesh.name = parser.createUniqueName( meshDef.name || ( 'mesh_' + meshIndex ) ); + + assignExtrasToUserData( mesh, meshDef ); + + if ( primitive.extensions ) addUnknownExtensionsToUserData( extensions, mesh, primitive ); + + parser.assignFinalMaterial( mesh ); + + meshes.push( mesh ); + + } + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + parser.associations.set( meshes[ i ], { + meshes: meshIndex, + primitives: i + } ); + + } + + if ( meshes.length === 1 ) { + + if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, meshes[ 0 ], meshDef ); + + return meshes[ 0 ]; + + } + + const group = new Group(); + + if ( meshDef.extensions ) addUnknownExtensionsToUserData( extensions, group, meshDef ); + + parser.associations.set( group, { meshes: meshIndex } ); + + for ( let i = 0, il = meshes.length; i < il; i ++ ) { + + group.add( meshes[ i ] ); + + } + + return group; + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras + * @param {number} cameraIndex + * @return {Promise} + */ + loadCamera( cameraIndex ) { + + let camera; + const cameraDef = this.json.cameras[ cameraIndex ]; + const params = cameraDef[ cameraDef.type ]; + + if ( ! params ) { + + console.warn( 'THREE.GLTFLoader: Missing camera parameters.' ); + return; + + } + + if ( cameraDef.type === 'perspective' ) { + + camera = new PerspectiveCamera( MathUtils.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 ); + + } else if ( cameraDef.type === 'orthographic' ) { + + camera = new OrthographicCamera( - params.xmag, params.xmag, params.ymag, - params.ymag, params.znear, params.zfar ); + + } + + if ( cameraDef.name ) camera.name = this.createUniqueName( cameraDef.name ); + + assignExtrasToUserData( camera, cameraDef ); + + return Promise.resolve( camera ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins + * @param {number} skinIndex + * @return {Promise} + */ + loadSkin( skinIndex ) { + + const skinDef = this.json.skins[ skinIndex ]; + + const pending = []; + + for ( let i = 0, il = skinDef.joints.length; i < il; i ++ ) { + + pending.push( this._loadNodeShallow( skinDef.joints[ i ] ) ); + + } + + if ( skinDef.inverseBindMatrices !== undefined ) { + + pending.push( this.getDependency( 'accessor', skinDef.inverseBindMatrices ) ); + + } else { + + pending.push( null ); + + } + + return Promise.all( pending ).then( function ( results ) { + + const inverseBindMatrices = results.pop(); + const jointNodes = results; + + // Note that bones (joint nodes) may or may not be in the + // scene graph at this time. + + const bones = []; + const boneInverses = []; + + for ( let i = 0, il = jointNodes.length; i < il; i ++ ) { + + const jointNode = jointNodes[ i ]; + + if ( jointNode ) { + + bones.push( jointNode ); + + const mat = new Matrix4(); + + if ( inverseBindMatrices !== null ) { + + mat.fromArray( inverseBindMatrices.array, i * 16 ); + + } + + boneInverses.push( mat ); + + } else { + + console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinDef.joints[ i ] ); + + } + + } + + return new Skeleton( bones, boneInverses ); + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations + * @param {number} animationIndex + * @return {Promise} + */ + loadAnimation( animationIndex ) { + + const json = this.json; + const parser = this; + + const animationDef = json.animations[ animationIndex ]; + const animationName = animationDef.name ? animationDef.name : 'animation_' + animationIndex; + + const pendingNodes = []; + const pendingInputAccessors = []; + const pendingOutputAccessors = []; + const pendingSamplers = []; + const pendingTargets = []; + + for ( let i = 0, il = animationDef.channels.length; i < il; i ++ ) { + + const channel = animationDef.channels[ i ]; + const sampler = animationDef.samplers[ channel.sampler ]; + const target = channel.target; + const name = target.node; + const input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; + const output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; + + if ( target.node === undefined ) continue; + + pendingNodes.push( this.getDependency( 'node', name ) ); + pendingInputAccessors.push( this.getDependency( 'accessor', input ) ); + pendingOutputAccessors.push( this.getDependency( 'accessor', output ) ); + pendingSamplers.push( sampler ); + pendingTargets.push( target ); + + } + + return Promise.all( [ + + Promise.all( pendingNodes ), + Promise.all( pendingInputAccessors ), + Promise.all( pendingOutputAccessors ), + Promise.all( pendingSamplers ), + Promise.all( pendingTargets ) + + ] ).then( function ( dependencies ) { + + const nodes = dependencies[ 0 ]; + const inputAccessors = dependencies[ 1 ]; + const outputAccessors = dependencies[ 2 ]; + const samplers = dependencies[ 3 ]; + const targets = dependencies[ 4 ]; + + const tracks = []; + + for ( let i = 0, il = nodes.length; i < il; i ++ ) { + + const node = nodes[ i ]; + const inputAccessor = inputAccessors[ i ]; + const outputAccessor = outputAccessors[ i ]; + const sampler = samplers[ i ]; + const target = targets[ i ]; + + if ( node === undefined ) continue; + + if ( node.updateMatrix ) { + + node.updateMatrix(); + + } + + const createdTracks = parser._createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ); + + if ( createdTracks ) { + + for ( let k = 0; k < createdTracks.length; k ++ ) { + + tracks.push( createdTracks[ k ] ); + + } + + } + + } + + return new AnimationClip( animationName, undefined, tracks ); + + } ); + + } + + createNodeMesh( nodeIndex ) { + + const json = this.json; + const parser = this; + const nodeDef = json.nodes[ nodeIndex ]; + + if ( nodeDef.mesh === undefined ) return null; + + return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { + + const node = parser._getNodeRef( parser.meshCache, nodeDef.mesh, mesh ); + + // if weights are provided on the node, override weights on the mesh. + if ( nodeDef.weights !== undefined ) { + + node.traverse( function ( o ) { + + if ( ! o.isMesh ) return; + + for ( let i = 0, il = nodeDef.weights.length; i < il; i ++ ) { + + o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; + + } + + } ); + + } + + return node; + + } ); + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy + * @param {number} nodeIndex + * @return {Promise} + */ + loadNode( nodeIndex ) { + + const json = this.json; + const parser = this; + + const nodeDef = json.nodes[ nodeIndex ]; + + const nodePending = parser._loadNodeShallow( nodeIndex ); + + const childPending = []; + const childrenDef = nodeDef.children || []; + + for ( let i = 0, il = childrenDef.length; i < il; i ++ ) { + + childPending.push( parser.getDependency( 'node', childrenDef[ i ] ) ); + + } + + const skeletonPending = nodeDef.skin === undefined + ? Promise.resolve( null ) + : parser.getDependency( 'skin', nodeDef.skin ); + + return Promise.all( [ + nodePending, + Promise.all( childPending ), + skeletonPending + ] ).then( function ( results ) { + + const node = results[ 0 ]; + const children = results[ 1 ]; + const skeleton = results[ 2 ]; + + if ( skeleton !== null ) { + + // This full traverse should be fine because + // child glTF nodes have not been added to this node yet. + node.traverse( function ( mesh ) { + + if ( ! mesh.isSkinnedMesh ) return; + + mesh.bind( skeleton, _identityMatrix ); + + } ); + + } + + for ( let i = 0, il = children.length; i < il; i ++ ) { + + node.add( children[ i ] ); + + } + + return node; + + } ); + + } + + // ._loadNodeShallow() parses a single node. + // skin and child nodes are created and added in .loadNode() (no '_' prefix). + _loadNodeShallow( nodeIndex ) { + + const json = this.json; + const extensions = this.extensions; + const parser = this; + + // This method is called from .loadNode() and .loadSkin(). + // Cache a node to avoid duplication. + + if ( this.nodeCache[ nodeIndex ] !== undefined ) { + + return this.nodeCache[ nodeIndex ]; + + } + + const nodeDef = json.nodes[ nodeIndex ]; + + // reserve node's name before its dependencies, so the root has the intended name. + const nodeName = nodeDef.name ? parser.createUniqueName( nodeDef.name ) : ''; + + const pending = []; + + const meshPromise = parser._invokeOne( function ( ext ) { + + return ext.createNodeMesh && ext.createNodeMesh( nodeIndex ); + + } ); + + if ( meshPromise ) { + + pending.push( meshPromise ); + + } + + if ( nodeDef.camera !== undefined ) { + + pending.push( parser.getDependency( 'camera', nodeDef.camera ).then( function ( camera ) { + + return parser._getNodeRef( parser.cameraCache, nodeDef.camera, camera ); + + } ) ); + + } + + parser._invokeAll( function ( ext ) { + + return ext.createNodeAttachment && ext.createNodeAttachment( nodeIndex ); + + } ).forEach( function ( promise ) { + + pending.push( promise ); + + } ); + + this.nodeCache[ nodeIndex ] = Promise.all( pending ).then( function ( objects ) { + + let node; + + // .isBone isn't in glTF spec. See ._markDefs + if ( nodeDef.isBone === true ) { + + node = new Bone(); + + } else if ( objects.length > 1 ) { + + node = new Group(); + + } else if ( objects.length === 1 ) { + + node = objects[ 0 ]; + + } else { + + node = new Object3D(); + + } + + if ( node !== objects[ 0 ] ) { + + for ( let i = 0, il = objects.length; i < il; i ++ ) { + + node.add( objects[ i ] ); + + } + + } + + if ( nodeDef.name ) { + + node.userData.name = nodeDef.name; + node.name = nodeName; + + } + + assignExtrasToUserData( node, nodeDef ); + + if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef ); + + if ( nodeDef.matrix !== undefined ) { + + const matrix = new Matrix4(); + matrix.fromArray( nodeDef.matrix ); + node.applyMatrix4( matrix ); + + } else { + + if ( nodeDef.translation !== undefined ) { + + node.position.fromArray( nodeDef.translation ); + + } + + if ( nodeDef.rotation !== undefined ) { + + node.quaternion.fromArray( nodeDef.rotation ); + + } + + if ( nodeDef.scale !== undefined ) { + + node.scale.fromArray( nodeDef.scale ); + + } + + } + + if ( ! parser.associations.has( node ) ) { + + parser.associations.set( node, {} ); + + } + + parser.associations.get( node ).nodes = nodeIndex; + + return node; + + } ); + + return this.nodeCache[ nodeIndex ]; + + } + + /** + * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes + * @param {number} sceneIndex + * @return {Promise} + */ + loadScene( sceneIndex ) { + + const extensions = this.extensions; + const sceneDef = this.json.scenes[ sceneIndex ]; + const parser = this; + + // Loader returns Group, not Scene. + // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172 + const scene = new Group(); + if ( sceneDef.name ) scene.name = parser.createUniqueName( sceneDef.name ); + + assignExtrasToUserData( scene, sceneDef ); + + if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); + + const nodeIds = sceneDef.nodes || []; + + const pending = []; + + for ( let i = 0, il = nodeIds.length; i < il; i ++ ) { + + pending.push( parser.getDependency( 'node', nodeIds[ i ] ) ); + + } + + return Promise.all( pending ).then( function ( nodes ) { + + for ( let i = 0, il = nodes.length; i < il; i ++ ) { + + scene.add( nodes[ i ] ); + + } + + // Removes dangling associations, associations that reference a node that + // didn't make it into the scene. + const reduceAssociations = ( node ) => { + + const reducedAssociations = new Map(); + + for ( const [ key, value ] of parser.associations ) { + + if ( key instanceof Material || key instanceof Texture ) { + + reducedAssociations.set( key, value ); + + } + + } + + node.traverse( ( node ) => { + + const mappings = parser.associations.get( node ); + + if ( mappings != null ) { + + reducedAssociations.set( node, mappings ); + + } + + } ); + + return reducedAssociations; + + }; + + parser.associations = reduceAssociations( scene ); + + return scene; + + } ); + + } + + _createAnimationTracks( node, inputAccessor, outputAccessor, sampler, target ) { + + const tracks = []; + + const targetName = node.name ? node.name : node.uuid; + const targetNames = []; + + if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { + + node.traverse( function ( object ) { + + if ( object.morphTargetInfluences ) { + + targetNames.push( object.name ? object.name : object.uuid ); + + } + + } ); + + } else { + + targetNames.push( targetName ); + + } + + let TypedKeyframeTrack; + + switch ( PATH_PROPERTIES[ target.path ] ) { + + case PATH_PROPERTIES.weights: + + TypedKeyframeTrack = NumberKeyframeTrack; + break; + + case PATH_PROPERTIES.rotation: + + TypedKeyframeTrack = QuaternionKeyframeTrack; + break; + + case PATH_PROPERTIES.position: + case PATH_PROPERTIES.scale: + + TypedKeyframeTrack = VectorKeyframeTrack; + break; + + default: + + switch ( outputAccessor.itemSize ) { + + case 1: + TypedKeyframeTrack = NumberKeyframeTrack; + break; + case 2: + case 3: + default: + TypedKeyframeTrack = VectorKeyframeTrack; + break; + + } + + break; + + } + + const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear; + + + const outputArray = this._getArrayFromAccessor( outputAccessor ); + + for ( let j = 0, jl = targetNames.length; j < jl; j ++ ) { + + const track = new TypedKeyframeTrack( + targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], + inputAccessor.array, + outputArray, + interpolation + ); + + // Override interpolation with custom factory method. + if ( sampler.interpolation === 'CUBICSPLINE' ) { + + this._createCubicSplineTrackInterpolant( track ); + + } + + tracks.push( track ); + + } + + return tracks; + + } + + _getArrayFromAccessor( accessor ) { + + let outputArray = accessor.array; + + if ( accessor.normalized ) { + + const scale = getNormalizedComponentScale( outputArray.constructor ); + const scaled = new Float32Array( outputArray.length ); + + for ( let j = 0, jl = outputArray.length; j < jl; j ++ ) { + + scaled[ j ] = outputArray[ j ] * scale; + + } + + outputArray = scaled; + + } + + return outputArray; + + } + + _createCubicSplineTrackInterpolant( track ) { + + track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) { + + // A CUBICSPLINE keyframe in glTF has three output values for each input value, + // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() + // must be divided by three to get the interpolant's sampleSize argument. + + const interpolantType = ( this instanceof QuaternionKeyframeTrack ) ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant; + + return new interpolantType( this.times, this.values, this.getValueSize() / 3, result ); + + }; + + // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants. + track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; + + } + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + */ +function computeBounds( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const box = new Box3(); + + if ( attributes.POSITION !== undefined ) { + + const accessor = parser.json.accessors[ attributes.POSITION ]; + + const min = accessor.min; + const max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + box.set( + new Vector3( min[ 0 ], min[ 1 ], min[ 2 ] ), + new Vector3( max[ 0 ], max[ 1 ], max[ 2 ] ) + ); + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + box.min.multiplyScalar( boxScale ); + box.max.multiplyScalar( boxScale ); + + } + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + return; + + } + + } else { + + return; + + } + + const targets = primitiveDef.targets; + + if ( targets !== undefined ) { + + const maxDisplacement = new Vector3(); + const vector = new Vector3(); + + for ( let i = 0, il = targets.length; i < il; i ++ ) { + + const target = targets[ i ]; + + if ( target.POSITION !== undefined ) { + + const accessor = parser.json.accessors[ target.POSITION ]; + const min = accessor.min; + const max = accessor.max; + + // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement. + + if ( min !== undefined && max !== undefined ) { + + // we need to get max of absolute components because target weight is [-1,1] + vector.setX( Math.max( Math.abs( min[ 0 ] ), Math.abs( max[ 0 ] ) ) ); + vector.setY( Math.max( Math.abs( min[ 1 ] ), Math.abs( max[ 1 ] ) ) ); + vector.setZ( Math.max( Math.abs( min[ 2 ] ), Math.abs( max[ 2 ] ) ) ); + + + if ( accessor.normalized ) { + + const boxScale = getNormalizedComponentScale( WEBGL_COMPONENT_TYPES[ accessor.componentType ] ); + vector.multiplyScalar( boxScale ); + + } + + // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative + // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets + // are used to implement key-frame animations and as such only two are active at a time - this results in very large + // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size. + maxDisplacement.max( vector ); + + } else { + + console.warn( 'THREE.GLTFLoader: Missing min/max properties for accessor POSITION.' ); + + } + + } + + } + + // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets. + box.expandByVector( maxDisplacement ); + + } + + geometry.boundingBox = box; + + const sphere = new Sphere(); + + box.getCenter( sphere.center ); + sphere.radius = box.min.distanceTo( box.max ) / 2; + + geometry.boundingSphere = sphere; + +} + +/** + * @param {BufferGeometry} geometry + * @param {GLTF.Primitive} primitiveDef + * @param {GLTFParser} parser + * @return {Promise} + */ +function addPrimitiveAttributes( geometry, primitiveDef, parser ) { + + const attributes = primitiveDef.attributes; + + const pending = []; + + function assignAttributeAccessor( accessorIndex, attributeName ) { + + return parser.getDependency( 'accessor', accessorIndex ) + .then( function ( accessor ) { + + geometry.setAttribute( attributeName, accessor ); + + } ); + + } + + for ( const gltfAttributeName in attributes ) { + + const threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); + + // Skip attributes already provided by e.g. Draco extension. + if ( threeAttributeName in geometry.attributes ) continue; + + pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); + + } + + if ( primitiveDef.indices !== undefined && ! geometry.index ) { + + const accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { + + geometry.setIndex( accessor ); + + } ); + + pending.push( accessor ); + + } + + if ( ColorManagement.workingColorSpace !== LinearSRGBColorSpace && 'COLOR_0' in attributes ) { + + console.warn( `THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${ColorManagement.workingColorSpace}" not supported.` ); + + } + + assignExtrasToUserData( geometry, primitiveDef ); + + computeBounds( geometry, primitiveDef, parser ); + + return Promise.all( pending ).then( function () { + + return primitiveDef.targets !== undefined + ? addMorphTargets( geometry, primitiveDef.targets, parser ) + : geometry; + + } ); + +} + +export { GLTFLoader }; diff --git a/ui/viewer/vendor/three/addons/loaders/MMDLoader.js b/ui/viewer/vendor/three/addons/loaders/MMDLoader.js new file mode 100644 index 0000000..b9f2f0c --- /dev/null +++ b/ui/viewer/vendor/three/addons/loaders/MMDLoader.js @@ -0,0 +1,2295 @@ +import { + AddOperation, + AnimationClip, + Bone, + BufferGeometry, + Color, + CustomBlending, + TangentSpaceNormalMap, + DoubleSide, + DstAlphaFactor, + Euler, + FileLoader, + Float32BufferAttribute, + FrontSide, + Interpolant, + Loader, + LoaderUtils, + UniformsUtils, + ShaderMaterial, + MultiplyOperation, + NearestFilter, + NumberKeyframeTrack, + OneMinusSrcAlphaFactor, + Quaternion, + QuaternionKeyframeTrack, + RepeatWrapping, + Skeleton, + SkinnedMesh, + SrcAlphaFactor, + SRGBColorSpace, + TextureLoader, + Uint16BufferAttribute, + Vector3, + VectorKeyframeTrack, + RGB_S3TC_DXT1_Format, + RGB_PVRTC_4BPPV1_Format, + RGB_PVRTC_2BPPV1_Format, + RGB_ETC1_Format, + RGB_ETC2_Format +} from 'three'; +import { MMDToonShader } from '../shaders/MMDToonShader.js'; +import { TGALoader } from '../loaders/TGALoader.js'; +import { MMDParser } from '../libs/mmdparser.module.js'; + +/** + * Dependencies + * - mmd-parser https://github.com/takahirox/mmd-parser + * - TGALoader + * - OutlineEffect + * + * MMDLoader creates Three.js Objects from MMD resources as + * PMD, PMX, VMD, and VPD files. + * + * PMD/PMX is a model data format, VMD is a motion data format + * VPD is a posing data format used in MMD(Miku Miku Dance). + * + * MMD official site + * - https://sites.google.com/view/evpvp/ + * + * PMD, VMD format (in Japanese) + * - http://blog.goo.ne.jp/torisu_tetosuki/e/209ad341d3ece2b1b4df24abf619d6e4 + * + * PMX format + * - https://gist.github.com/felixjones/f8a06bd48f9da9a4539f + * + * TODO + * - light motion in vmd support. + * - SDEF support. + * - uv/material/bone morphing support. + * - more precise grant skinning support. + * - shadow support. + */ + +/** + * @param {THREE.LoadingManager} manager + */ +class MMDLoader extends Loader { + + constructor( manager ) { + + super( manager ); + + this.loader = new FileLoader( this.manager ); + + this.parser = null; // lazy generation + this.meshBuilder = new MeshBuilder( this.manager ); + this.animationBuilder = new AnimationBuilder(); + + } + + /** + * @param {string} animationPath + * @return {MMDLoader} + */ + setAnimationPath( animationPath ) { + + this.animationPath = animationPath; + return this; + + } + + // Load MMD assets as Three.js Object + + /** + * Loads Model file (.pmd or .pmx) as a SkinnedMesh. + * + * @param {string} url - url to Model(.pmd or .pmx) file + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + load( url, onLoad, onProgress, onError ) { + + const builder = this.meshBuilder.setCrossOrigin( this.crossOrigin ); + + // resource path + + let resourcePath; + + if ( this.resourcePath !== '' ) { + + resourcePath = this.resourcePath; + + } else if ( this.path !== '' ) { + + resourcePath = this.path; + + } else { + + resourcePath = LoaderUtils.extractUrlBase( url ); + + } + + const parser = this._getParser(); + const extractModelExtension = this._extractModelExtension; + + this.loader + .setMimeType( undefined ) + .setPath( this.path ) + .setResponseType( 'arraybuffer' ) + .setRequestHeader( this.requestHeader ) + .setWithCredentials( this.withCredentials ) + .load( url, function ( buffer ) { + + try { + + const modelExtension = extractModelExtension( buffer ); + + if ( modelExtension !== 'pmd' && modelExtension !== 'pmx' ) { + + if ( onError ) onError( new Error( 'THREE.MMDLoader: Unknown model file extension .' + modelExtension + '.' ) ); + + return; + + } + + const data = modelExtension === 'pmd' ? parser.parsePmd( buffer, true ) : parser.parsePmx( buffer, true ); + + onLoad( builder.build( data, resourcePath, onProgress, onError ) ); + + } catch ( e ) { + + if ( onError ) onError( e ); + + } + + }, onProgress, onError ); + + } + + /** + * Loads Motion file(s) (.vmd) as a AnimationClip. + * If two or more files are specified, they'll be merged. + * + * @param {string|Array} url - url(s) to animation(.vmd) file(s) + * @param {SkinnedMesh|THREE.Camera} object - tracks will be fitting to this object + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadAnimation( url, object, onLoad, onProgress, onError ) { + + const builder = this.animationBuilder; + + this.loadVMD( url, function ( vmd ) { + + onLoad( object.isCamera + ? builder.buildCameraAnimation( vmd ) + : builder.build( vmd, object ) ); + + }, onProgress, onError ); + + } + + /** + * Loads mode file and motion file(s) as an object containing + * a SkinnedMesh and a AnimationClip. + * Tracks of AnimationClip are fitting to the model. + * + * @param {string} modelUrl - url to Model(.pmd or .pmx) file + * @param {string|Array{string}} vmdUrl - url(s) to animation(.vmd) file + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadWithAnimation( modelUrl, vmdUrl, onLoad, onProgress, onError ) { + + const scope = this; + + this.load( modelUrl, function ( mesh ) { + + scope.loadAnimation( vmdUrl, mesh, function ( animation ) { + + onLoad( { + mesh: mesh, + animation: animation + } ); + + }, onProgress, onError ); + + }, onProgress, onError ); + + } + + // Load MMD assets as Object data parsed by MMDParser + + /** + * Loads .pmd file as an Object. + * + * @param {string} url - url to .pmd file + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadPMD( url, onLoad, onProgress, onError ) { + + const parser = this._getParser(); + + this.loader + .setMimeType( undefined ) + .setPath( this.path ) + .setResponseType( 'arraybuffer' ) + .setRequestHeader( this.requestHeader ) + .setWithCredentials( this.withCredentials ) + .load( url, function ( buffer ) { + + try { + + onLoad( parser.parsePmd( buffer, true ) ); + + } catch ( e ) { + + if ( onError ) onError( e ); + + } + + }, onProgress, onError ); + + } + + /** + * Loads .pmx file as an Object. + * + * @param {string} url - url to .pmx file + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadPMX( url, onLoad, onProgress, onError ) { + + const parser = this._getParser(); + + this.loader + .setMimeType( undefined ) + .setPath( this.path ) + .setResponseType( 'arraybuffer' ) + .setRequestHeader( this.requestHeader ) + .setWithCredentials( this.withCredentials ) + .load( url, function ( buffer ) { + + try { + + onLoad( parser.parsePmx( buffer, true ) ); + + } catch ( e ) { + + if ( onError ) onError( e ); + + } + + }, onProgress, onError ); + + } + + /** + * Loads .vmd file as an Object. If two or more files are specified + * they'll be merged. + * + * @param {string|Array} url - url(s) to .vmd file(s) + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadVMD( url, onLoad, onProgress, onError ) { + + const urls = Array.isArray( url ) ? url : [ url ]; + + const vmds = []; + const vmdNum = urls.length; + + const parser = this._getParser(); + + this.loader + .setMimeType( undefined ) + .setPath( this.animationPath ) + .setResponseType( 'arraybuffer' ) + .setRequestHeader( this.requestHeader ) + .setWithCredentials( this.withCredentials ); + + for ( let i = 0, il = urls.length; i < il; i ++ ) { + + this.loader.load( urls[ i ], function ( buffer ) { + + try { + + vmds.push( parser.parseVmd( buffer, true ) ); + + if ( vmds.length === vmdNum ) onLoad( parser.mergeVmds( vmds ) ); + + } catch ( e ) { + + if ( onError ) onError( e ); + + } + + }, onProgress, onError ); + + } + + } + + /** + * Loads .vpd file as an Object. + * + * @param {string} url - url to .vpd file + * @param {boolean} isUnicode + * @param {function} onLoad + * @param {function} onProgress + * @param {function} onError + */ + loadVPD( url, isUnicode, onLoad, onProgress, onError ) { + + const parser = this._getParser(); + + this.loader + .setMimeType( isUnicode ? undefined : 'text/plain; charset=shift_jis' ) + .setPath( this.animationPath ) + .setResponseType( 'text' ) + .setRequestHeader( this.requestHeader ) + .setWithCredentials( this.withCredentials ) + .load( url, function ( text ) { + + try { + + onLoad( parser.parseVpd( text, true ) ); + + } catch ( e ) { + + if ( onError ) onError( e ); + + } + + }, onProgress, onError ); + + } + + // private methods + + _extractModelExtension( buffer ) { + + const decoder = new TextDecoder( 'utf-8' ); + const bytes = new Uint8Array( buffer, 0, 3 ); + return decoder.decode( bytes ).toLowerCase(); + + } + + _getParser() { + + if ( this.parser === null ) { + + this.parser = new MMDParser.Parser(); + + } + + return this.parser; + + } + +} + +// Utilities + +/* + * base64 encoded defalut toon textures toon00.bmp - toon10.bmp. + * We don't need to request external toon image files. + */ +const DEFAULT_TOON_TEXTURES = [ + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/bWiiMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh8aBHZBl14e8wAAAABJRU5ErkJggg==', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOUlEQVRYR+3WMREAMAwDsYY/yoDI7MLwIiP40+RJklfcCCBAgAABAgTqArfb/QMCCBAgQIAAgbbAB3z/e0F3js2cAAAAAElFTkSuQmCC', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAN0lEQVRYR+3WQREAMBACsZ5/B5ilMvgEBTt5cW37hjsBBAgQIECAwFwgyfYPCCBAgAABAgTWAh81dWyx0gFwKAAAAABJRU5ErkJggg==', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAOklEQVRYR+3WoREAMAwDsWb/UQtCy9wxTOQJ/oQ8SXKKGwEECBAgQIBAXeDt7f4BAQQIECBAgEBb4AOz8Hzx7WLY4wAAAABJRU5ErkJggg==', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABPUlEQVRYR+1XwW7CMAy1+f9fZOMysSEOEweEOPRNdm3HbdOyIhAcklPrOs/PLy9RygBALxzcCDQFmgJNgaZAU6Ap0BR4PwX8gsRMVLssMRH5HcpzJEaWL7EVg9F1IHRlyqQohgVr4FGUlUcMJSjcUlDw0zvjeun70cLWmneoyf7NgBTQSniBTQQSuJAZsOnnaczjIMb5hCiuHKxokCrJfVnrctyZL0PkJAJe1HMil4nxeyi3Ypfn1kX51jpPvo/JeCNC4PhVdHdJw2XjBR8brF8PEIhNVn12AgP7uHsTBguBn53MUZCqv7Lp07Pn5k1Ro+uWmUNn7D+M57rtk7aG0Vo73xyF/fbFf0bPJjDXngnGocDTdFhygZjwUQrMNrDcmZlQT50VJ/g/UwNyHpu778+yW+/ksOz/BFo54P4AsUXMfRq7XWsAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACMElEQVRYR+2Xv4pTQRTGf2dubhLdICiii2KnYKHVolhauKWPoGAnNr6BD6CvIVaihYuI2i1ia0BY0MZGRHQXjZj/mSPnnskfNWiWZUlzJ5k7M2cm833nO5Mziej2DWWJRUoCpQKlAntSQCqgw39/iUWAGmh37jrRnVsKlgpiqmkoGVABA7E57fvY+pJDdgKqF6HzFCSADkDq+F6AHABtQ+UMVE5D7zXod7fFNhTEckTbj5XQgHzNN+5tQvc5NG7C6BNkp6D3EmpXHDR+dQAjFLchW3VS9rlw3JBh+B7ys5Cf9z0GW1C/7P32AyBAOAz1q4jGliIH3YPuBnSfQX4OGreTIgEYQb/pBDtPnEQ4CivXYPAWBk13oHrB54yA9QuSn2H4AcKRpEILDt0BUzj+RLR1V5EqjD66NPRBVpLcQwjHoHYJOhsQv6U4mnzmrIXJCFr4LDwm/xBUoboG9XX4cc9VKdYoSA2yk5NQLJaKDUjTBoveG3Z2TElTxwjNK4M3LEZgUdDdruvcXzKBpStgp2NPiWi3ks9ZXxIoFVi+AvHLdc9TqtjL3/aYjpPlrzOcEnK62Szhimdd7xX232zFDTgtxezOu3WNMRLjiKgjtOhHVMd1loynVHvOgjuIIJMaELEqhJAV/RCSLbWTcfPFakFgFlALTRRvx+ok6Hlp/Q+v3fmx90bMyUzaEAhmM3KvHlXTL5DxnbGf/1M8RNNACLL5MNtPxP/mypJAqcDSFfgFhpYqWUzhTEAAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=', + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAL0lEQVRYR+3QQREAAAzCsOFfNJPBJ1XQS9r2hsUAAQIECBAgQIAAAQIECBAgsBZ4MUx/ofm2I/kAAAAASUVORK5CYII=' +]; + +const NON_ALPHA_CHANNEL_FORMATS = [ + RGB_S3TC_DXT1_Format, + RGB_PVRTC_4BPPV1_Format, + RGB_PVRTC_2BPPV1_Format, + RGB_ETC1_Format, + RGB_ETC2_Format +]; + +// Builders. They build Three.js object from Object data parsed by MMDParser. + +/** + * @param {THREE.LoadingManager} manager + */ +class MeshBuilder { + + constructor( manager ) { + + this.crossOrigin = 'anonymous'; + this.geometryBuilder = new GeometryBuilder(); + this.materialBuilder = new MaterialBuilder( manager ); + + } + + /** + * @param {string} crossOrigin + * @return {MeshBuilder} + */ + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + /** + * @param {Object} data - parsed PMD/PMX data + * @param {string} resourcePath + * @param {function} onProgress + * @param {function} onError + * @return {SkinnedMesh} + */ + build( data, resourcePath, onProgress, onError ) { + + const geometry = this.geometryBuilder.build( data ); + const material = this.materialBuilder + .setCrossOrigin( this.crossOrigin ) + .setResourcePath( resourcePath ) + .build( data, geometry, onProgress, onError ); + + const mesh = new SkinnedMesh( geometry, material ); + + const skeleton = new Skeleton( initBones( mesh ) ); + mesh.bind( skeleton ); + + // console.log( mesh ); // for console debug + + return mesh; + + } + +} + +// TODO: Try to remove this function + +function initBones( mesh ) { + + const geometry = mesh.geometry; + + const bones = []; + + if ( geometry && geometry.bones !== undefined ) { + + // first, create array of 'Bone' objects from geometry data + + for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) { + + const gbone = geometry.bones[ i ]; + + // create new 'Bone' object + + const bone = new Bone(); + bones.push( bone ); + + // apply values + + bone.name = gbone.name; + bone.position.fromArray( gbone.pos ); + bone.quaternion.fromArray( gbone.rotq ); + if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl ); + + } + + // second, create bone hierarchy + + for ( let i = 0, il = geometry.bones.length; i < il; i ++ ) { + + const gbone = geometry.bones[ i ]; + + if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) { + + // subsequent bones in the hierarchy + + bones[ gbone.parent ].add( bones[ i ] ); + + } else { + + // topmost bone, immediate child of the skinned mesh + + mesh.add( bones[ i ] ); + + } + + } + + } + + // now the bones are part of the scene graph and children of the skinned mesh. + // let's update the corresponding matrices + + mesh.updateMatrixWorld( true ); + + return bones; + +} + +// + +class GeometryBuilder { + + /** + * @param {Object} data - parsed PMD/PMX data + * @return {BufferGeometry} + */ + build( data ) { + + // for geometry + const positions = []; + const uvs = []; + const normals = []; + + const indices = []; + + const groups = []; + + const bones = []; + const skinIndices = []; + const skinWeights = []; + + const morphTargets = []; + const morphPositions = []; + + const iks = []; + const grants = []; + + const rigidBodies = []; + const constraints = []; + + // for work + let offset = 0; + const boneTypeTable = {}; + + // positions, normals, uvs, skinIndices, skinWeights + + for ( let i = 0; i < data.metadata.vertexCount; i ++ ) { + + const v = data.vertices[ i ]; + + for ( let j = 0, jl = v.position.length; j < jl; j ++ ) { + + positions.push( v.position[ j ] ); + + } + + for ( let j = 0, jl = v.normal.length; j < jl; j ++ ) { + + normals.push( v.normal[ j ] ); + + } + + for ( let j = 0, jl = v.uv.length; j < jl; j ++ ) { + + uvs.push( v.uv[ j ] ); + + } + + for ( let j = 0; j < 4; j ++ ) { + + skinIndices.push( v.skinIndices.length - 1 >= j ? v.skinIndices[ j ] : 0.0 ); + + } + + for ( let j = 0; j < 4; j ++ ) { + + skinWeights.push( v.skinWeights.length - 1 >= j ? v.skinWeights[ j ] : 0.0 ); + + } + + } + + // indices + + for ( let i = 0; i < data.metadata.faceCount; i ++ ) { + + const face = data.faces[ i ]; + + for ( let j = 0, jl = face.indices.length; j < jl; j ++ ) { + + indices.push( face.indices[ j ] ); + + } + + } + + // groups + + for ( let i = 0; i < data.metadata.materialCount; i ++ ) { + + const material = data.materials[ i ]; + + groups.push( { + offset: offset * 3, + count: material.faceCount * 3 + } ); + + offset += material.faceCount; + + } + + // bones + + for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) { + + const body = data.rigidBodies[ i ]; + let value = boneTypeTable[ body.boneIndex ]; + + // keeps greater number if already value is set without any special reasons + value = value === undefined ? body.type : Math.max( body.type, value ); + + boneTypeTable[ body.boneIndex ] = value; + + } + + for ( let i = 0; i < data.metadata.boneCount; i ++ ) { + + const boneData = data.bones[ i ]; + + const bone = { + index: i, + transformationClass: boneData.transformationClass, + parent: boneData.parentIndex, + name: boneData.name, + pos: boneData.position.slice( 0, 3 ), + rotq: [ 0, 0, 0, 1 ], + scl: [ 1, 1, 1 ], + rigidBodyType: boneTypeTable[ i ] !== undefined ? boneTypeTable[ i ] : - 1 + }; + + if ( bone.parent !== - 1 ) { + + bone.pos[ 0 ] -= data.bones[ bone.parent ].position[ 0 ]; + bone.pos[ 1 ] -= data.bones[ bone.parent ].position[ 1 ]; + bone.pos[ 2 ] -= data.bones[ bone.parent ].position[ 2 ]; + + } + + bones.push( bone ); + + } + + // iks + + // TODO: remove duplicated codes between PMD and PMX + if ( data.metadata.format === 'pmd' ) { + + for ( let i = 0; i < data.metadata.ikCount; i ++ ) { + + const ik = data.iks[ i ]; + + const param = { + target: ik.target, + effector: ik.effector, + iteration: ik.iteration, + maxAngle: ik.maxAngle * 4, + links: [] + }; + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = {}; + link.index = ik.links[ j ].index; + link.enabled = true; + + if ( data.bones[ link.index ].name.indexOf( 'ひざ' ) >= 0 ) { + + link.limitation = new Vector3( 1.0, 0.0, 0.0 ); + + } + + param.links.push( link ); + + } + + iks.push( param ); + + } + + } else { + + for ( let i = 0; i < data.metadata.boneCount; i ++ ) { + + const ik = data.bones[ i ].ik; + + if ( ik === undefined ) continue; + + const param = { + target: i, + effector: ik.effector, + iteration: ik.iteration, + maxAngle: ik.maxAngle, + links: [] + }; + + for ( let j = 0, jl = ik.links.length; j < jl; j ++ ) { + + const link = {}; + link.index = ik.links[ j ].index; + link.enabled = true; + + if ( ik.links[ j ].angleLimitation === 1 ) { + + // Revert if rotationMin/Max doesn't work well + // link.limitation = new Vector3( 1.0, 0.0, 0.0 ); + + const rotationMin = ik.links[ j ].lowerLimitationAngle; + const rotationMax = ik.links[ j ].upperLimitationAngle; + + // Convert Left to Right coordinate by myself because + // MMDParser doesn't convert. It's a MMDParser's bug + + const tmp1 = - rotationMax[ 0 ]; + const tmp2 = - rotationMax[ 1 ]; + rotationMax[ 0 ] = - rotationMin[ 0 ]; + rotationMax[ 1 ] = - rotationMin[ 1 ]; + rotationMin[ 0 ] = tmp1; + rotationMin[ 1 ] = tmp2; + + link.rotationMin = new Vector3().fromArray( rotationMin ); + link.rotationMax = new Vector3().fromArray( rotationMax ); + + } + + param.links.push( link ); + + } + + iks.push( param ); + + // Save the reference even from bone data for efficiently + // simulating PMX animation system + bones[ i ].ik = param; + + } + + } + + // grants + + if ( data.metadata.format === 'pmx' ) { + + // bone index -> grant entry map + const grantEntryMap = {}; + + for ( let i = 0; i < data.metadata.boneCount; i ++ ) { + + const boneData = data.bones[ i ]; + const grant = boneData.grant; + + if ( grant === undefined ) continue; + + const param = { + index: i, + parentIndex: grant.parentIndex, + ratio: grant.ratio, + isLocal: grant.isLocal, + affectRotation: grant.affectRotation, + affectPosition: grant.affectPosition, + transformationClass: boneData.transformationClass + }; + + grantEntryMap[ i ] = { parent: null, children: [], param: param, visited: false }; + + } + + const rootEntry = { parent: null, children: [], param: null, visited: false }; + + // Build a tree representing grant hierarchy + + for ( const boneIndex in grantEntryMap ) { + + const grantEntry = grantEntryMap[ boneIndex ]; + const parentGrantEntry = grantEntryMap[ grantEntry.parentIndex ] || rootEntry; + + grantEntry.parent = parentGrantEntry; + parentGrantEntry.children.push( grantEntry ); + + } + + // Sort grant parameters from parents to children because + // grant uses parent's transform that parent's grant is already applied + // so grant should be applied in order from parents to children + + function traverse( entry ) { + + if ( entry.param ) { + + grants.push( entry.param ); + + // Save the reference even from bone data for efficiently + // simulating PMX animation system + bones[ entry.param.index ].grant = entry.param; + + } + + entry.visited = true; + + for ( let i = 0, il = entry.children.length; i < il; i ++ ) { + + const child = entry.children[ i ]; + + // Cut off a loop if exists. (Is a grant loop invalid?) + if ( ! child.visited ) traverse( child ); + + } + + } + + traverse( rootEntry ); + + } + + // morph + + function updateAttributes( attribute, morph, ratio ) { + + for ( let i = 0; i < morph.elementCount; i ++ ) { + + const element = morph.elements[ i ]; + + let index; + + if ( data.metadata.format === 'pmd' ) { + + index = data.morphs[ 0 ].elements[ element.index ].index; + + } else { + + index = element.index; + + } + + attribute.array[ index * 3 + 0 ] += element.position[ 0 ] * ratio; + attribute.array[ index * 3 + 1 ] += element.position[ 1 ] * ratio; + attribute.array[ index * 3 + 2 ] += element.position[ 2 ] * ratio; + + } + + } + + for ( let i = 0; i < data.metadata.morphCount; i ++ ) { + + const morph = data.morphs[ i ]; + const params = { name: morph.name }; + + const attribute = new Float32BufferAttribute( data.metadata.vertexCount * 3, 3 ); + attribute.name = morph.name; + + for ( let j = 0; j < data.metadata.vertexCount * 3; j ++ ) { + + attribute.array[ j ] = positions[ j ]; + + } + + if ( data.metadata.format === 'pmd' ) { + + if ( i !== 0 ) { + + updateAttributes( attribute, morph, 1.0 ); + + } + + } else { + + if ( morph.type === 0 ) { // group + + for ( let j = 0; j < morph.elementCount; j ++ ) { + + const morph2 = data.morphs[ morph.elements[ j ].index ]; + const ratio = morph.elements[ j ].ratio; + + if ( morph2.type === 1 ) { + + updateAttributes( attribute, morph2, ratio ); + + } else { + + // TODO: implement + + } + + } + + } else if ( morph.type === 1 ) { // vertex + + updateAttributes( attribute, morph, 1.0 ); + + } else if ( morph.type === 2 ) { // bone + + // TODO: implement + + } else if ( morph.type === 3 ) { // uv + + // TODO: implement + + } else if ( morph.type === 4 ) { // additional uv1 + + // TODO: implement + + } else if ( morph.type === 5 ) { // additional uv2 + + // TODO: implement + + } else if ( morph.type === 6 ) { // additional uv3 + + // TODO: implement + + } else if ( morph.type === 7 ) { // additional uv4 + + // TODO: implement + + } else if ( morph.type === 8 ) { // material + + // TODO: implement + + } + + } + + morphTargets.push( params ); + morphPositions.push( attribute ); + + } + + // rigid bodies from rigidBodies field. + + for ( let i = 0; i < data.metadata.rigidBodyCount; i ++ ) { + + const rigidBody = data.rigidBodies[ i ]; + const params = {}; + + for ( const key in rigidBody ) { + + params[ key ] = rigidBody[ key ]; + + } + + /* + * RigidBody position parameter in PMX seems global position + * while the one in PMD seems offset from corresponding bone. + * So unify being offset. + */ + if ( data.metadata.format === 'pmx' ) { + + if ( params.boneIndex !== - 1 ) { + + const bone = data.bones[ params.boneIndex ]; + params.position[ 0 ] -= bone.position[ 0 ]; + params.position[ 1 ] -= bone.position[ 1 ]; + params.position[ 2 ] -= bone.position[ 2 ]; + + } + + } + + rigidBodies.push( params ); + + } + + // constraints from constraints field. + + for ( let i = 0; i < data.metadata.constraintCount; i ++ ) { + + const constraint = data.constraints[ i ]; + const params = {}; + + for ( const key in constraint ) { + + params[ key ] = constraint[ key ]; + + } + + const bodyA = rigidBodies[ params.rigidBodyIndex1 ]; + const bodyB = rigidBodies[ params.rigidBodyIndex2 ]; + + // Refer to http://www20.atpages.jp/katwat/wp/?p=4135 + if ( bodyA.type !== 0 && bodyB.type === 2 ) { + + if ( bodyA.boneIndex !== - 1 && bodyB.boneIndex !== - 1 && + data.bones[ bodyB.boneIndex ].parentIndex === bodyA.boneIndex ) { + + bodyB.type = 1; + + } + + } + + constraints.push( params ); + + } + + // build BufferGeometry. + + const geometry = new BufferGeometry(); + + geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) ); + geometry.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) ); + geometry.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) ); + geometry.setAttribute( 'skinIndex', new Uint16BufferAttribute( skinIndices, 4 ) ); + geometry.setAttribute( 'skinWeight', new Float32BufferAttribute( skinWeights, 4 ) ); + geometry.setIndex( indices ); + + for ( let i = 0, il = groups.length; i < il; i ++ ) { + + geometry.addGroup( groups[ i ].offset, groups[ i ].count, i ); + + } + + geometry.bones = bones; + + geometry.morphTargets = morphTargets; + geometry.morphAttributes.position = morphPositions; + geometry.morphTargetsRelative = false; + + geometry.userData.MMD = { + bones: bones, + iks: iks, + grants: grants, + rigidBodies: rigidBodies, + constraints: constraints, + format: data.metadata.format + }; + + geometry.computeBoundingSphere(); + + return geometry; + + } + +} + +// + +/** + * @param {THREE.LoadingManager} manager + */ +class MaterialBuilder { + + constructor( manager ) { + + this.manager = manager; + + this.textureLoader = new TextureLoader( this.manager ); + this.tgaLoader = null; // lazy generation + + this.crossOrigin = 'anonymous'; + this.resourcePath = undefined; + + } + + /** + * @param {string} crossOrigin + * @return {MaterialBuilder} + */ + setCrossOrigin( crossOrigin ) { + + this.crossOrigin = crossOrigin; + return this; + + } + + /** + * @param {string} resourcePath + * @return {MaterialBuilder} + */ + setResourcePath( resourcePath ) { + + this.resourcePath = resourcePath; + return this; + + } + + /** + * @param {Object} data - parsed PMD/PMX data + * @param {BufferGeometry} geometry - some properties are dependend on geometry + * @param {function} onProgress + * @param {function} onError + * @return {Array} + */ + build( data, geometry /*, onProgress, onError */ ) { + + const materials = []; + + const textures = {}; + + this.textureLoader.setCrossOrigin( this.crossOrigin ); + + // materials + + for ( let i = 0; i < data.metadata.materialCount; i ++ ) { + + const material = data.materials[ i ]; + + const params = { userData: { MMD: {} } }; + + if ( material.name !== undefined ) params.name = material.name; + + /* + * Color + * + * MMD MMDToonMaterial + * ambient - emissive * a + * (a = 1.0 without map texture or 0.2 with map texture) + * + * MMDToonMaterial doesn't have ambient. Set it to emissive instead. + * It'll be too bright if material has map texture so using coef 0.2. + */ + params.diffuse = new Color().setRGB( + material.diffuse[ 0 ], + material.diffuse[ 1 ], + material.diffuse[ 2 ], + SRGBColorSpace + ); + params.opacity = material.diffuse[ 3 ]; + params.specular = new Color().setRGB( ...material.specular, SRGBColorSpace ); + params.shininess = material.shininess; + params.emissive = new Color().setRGB( ...material.ambient, SRGBColorSpace ); + params.transparent = params.opacity !== 1.0; + + // + + params.fog = true; + + // blend + + params.blending = CustomBlending; + params.blendSrc = SrcAlphaFactor; + params.blendDst = OneMinusSrcAlphaFactor; + params.blendSrcAlpha = SrcAlphaFactor; + params.blendDstAlpha = DstAlphaFactor; + + // side + + if ( data.metadata.format === 'pmx' && ( material.flag & 0x1 ) === 1 ) { + + params.side = DoubleSide; + + } else { + + params.side = params.opacity === 1.0 ? FrontSide : DoubleSide; + + } + + if ( data.metadata.format === 'pmd' ) { + + // map, matcap + + if ( material.fileName ) { + + const fileName = material.fileName; + const fileNames = fileName.split( '*' ); + + // fileNames[ 0 ]: mapFileName + // fileNames[ 1 ]: matcapFileName( optional ) + + params.map = this._loadTexture( fileNames[ 0 ], textures ); + + if ( fileNames.length > 1 ) { + + const extension = fileNames[ 1 ].slice( - 4 ).toLowerCase(); + + params.matcap = this._loadTexture( + fileNames[ 1 ], + textures + ); + + params.matcapCombine = extension === '.sph' + ? MultiplyOperation + : AddOperation; + + } + + } + + // gradientMap + + const toonFileName = ( material.toonIndex === - 1 ) + ? 'toon00.bmp' + : data.toonTextures[ material.toonIndex ].fileName; + + params.gradientMap = this._loadTexture( + toonFileName, + textures, + { + isToonTexture: true, + isDefaultToonTexture: this._isDefaultToonTexture( toonFileName ) + } + ); + + // parameters for OutlineEffect + + params.userData.outlineParameters = { + thickness: material.edgeFlag === 1 ? 0.003 : 0.0, + color: [ 0, 0, 0 ], + alpha: 1.0, + visible: material.edgeFlag === 1 + }; + + } else { + + // map + + if ( material.textureIndex !== - 1 ) { + + params.map = this._loadTexture( data.textures[ material.textureIndex ], textures ); + + // Since PMX spec don't have standard to list map files except color map and env map, + // we need to save file name for further mapping, like matching normal map file names after model loaded. + // ref: https://gist.github.com/felixjones/f8a06bd48f9da9a4539f#texture + params.userData.MMD.mapFileName = data.textures[ material.textureIndex ]; + + } + + // matcap TODO: support m.envFlag === 3 + + if ( material.envTextureIndex !== - 1 && ( material.envFlag === 1 || material.envFlag == 2 ) ) { + + params.matcap = this._loadTexture( + data.textures[ material.envTextureIndex ], + textures + ); + + // Same as color map above, keep file name in userData for further usage. + params.userData.MMD.matcapFileName = data.textures[ material.envTextureIndex ]; + + params.matcapCombine = material.envFlag === 1 + ? MultiplyOperation + : AddOperation; + + } + + // gradientMap + + let toonFileName, isDefaultToon; + + if ( material.toonIndex === - 1 || material.toonFlag !== 0 ) { + + toonFileName = 'toon' + ( '0' + ( material.toonIndex + 1 ) ).slice( - 2 ) + '.bmp'; + isDefaultToon = true; + + } else { + + toonFileName = data.textures[ material.toonIndex ]; + isDefaultToon = false; + + } + + params.gradientMap = this._loadTexture( + toonFileName, + textures, + { + isToonTexture: true, + isDefaultToonTexture: isDefaultToon + } + ); + + // parameters for OutlineEffect + params.userData.outlineParameters = { + thickness: material.edgeSize / 300, // TODO: better calculation? + color: material.edgeColor.slice( 0, 3 ), + alpha: material.edgeColor[ 3 ], + visible: ( material.flag & 0x10 ) !== 0 && material.edgeSize > 0.0 + }; + + } + + if ( params.map !== undefined ) { + + if ( ! params.transparent ) { + + this._checkImageTransparency( params.map, geometry, i ); + + } + + params.emissive.multiplyScalar( 0.2 ); + + } + + materials.push( new MMDToonMaterial( params ) ); + + } + + if ( data.metadata.format === 'pmx' ) { + + // set transparent true if alpha morph is defined. + + function checkAlphaMorph( elements, materials ) { + + for ( let i = 0, il = elements.length; i < il; i ++ ) { + + const element = elements[ i ]; + + if ( element.index === - 1 ) continue; + + const material = materials[ element.index ]; + + if ( material.opacity !== element.diffuse[ 3 ] ) { + + material.transparent = true; + + } + + } + + } + + for ( let i = 0, il = data.morphs.length; i < il; i ++ ) { + + const morph = data.morphs[ i ]; + const elements = morph.elements; + + if ( morph.type === 0 ) { + + for ( let j = 0, jl = elements.length; j < jl; j ++ ) { + + const morph2 = data.morphs[ elements[ j ].index ]; + + if ( morph2.type !== 8 ) continue; + + checkAlphaMorph( morph2.elements, materials ); + + } + + } else if ( morph.type === 8 ) { + + checkAlphaMorph( elements, materials ); + + } + + } + + } + + return materials; + + } + + // private methods + + _getTGALoader() { + + if ( this.tgaLoader === null ) { + + if ( TGALoader === undefined ) { + + throw new Error( 'THREE.MMDLoader: Import TGALoader' ); + + } + + this.tgaLoader = new TGALoader( this.manager ); + + } + + return this.tgaLoader; + + } + + _isDefaultToonTexture( name ) { + + if ( name.length !== 10 ) return false; + + return /toon(10|0[0-9])\.bmp/.test( name ); + + } + + _loadTexture( filePath, textures, params, onProgress, onError ) { + + params = params || {}; + + const scope = this; + + let fullPath; + + if ( params.isDefaultToonTexture === true ) { + + let index; + + try { + + index = parseInt( filePath.match( /toon([0-9]{2})\.bmp$/ )[ 1 ] ); + + } catch ( e ) { + + console.warn( 'THREE.MMDLoader: ' + filePath + ' seems like a ' + + 'not right default texture path. Using toon00.bmp instead.' ); + + index = 0; + + } + + fullPath = DEFAULT_TOON_TEXTURES[ index ]; + + } else { + + fullPath = this.resourcePath + filePath; + + } + + if ( textures[ fullPath ] !== undefined ) return textures[ fullPath ]; + + let loader = this.manager.getHandler( fullPath ); + + if ( loader === null ) { + + loader = ( filePath.slice( - 4 ).toLowerCase() === '.tga' ) + ? this._getTGALoader() + : this.textureLoader; + + } + + const texture = loader.load( fullPath, function ( t ) { + + // MMD toon texture is Axis-Y oriented + // but Three.js gradient map is Axis-X oriented. + // So here replaces the toon texture image with the rotated one. + if ( params.isToonTexture === true ) { + + t.image = scope._getRotatedImage( t.image ); + + t.magFilter = NearestFilter; + t.minFilter = NearestFilter; + + } + + t.flipY = false; + t.wrapS = RepeatWrapping; + t.wrapT = RepeatWrapping; + t.colorSpace = SRGBColorSpace; + + for ( let i = 0; i < texture.readyCallbacks.length; i ++ ) { + + texture.readyCallbacks[ i ]( texture ); + + } + + delete texture.readyCallbacks; + + }, onProgress, onError ); + + texture.readyCallbacks = []; + + textures[ fullPath ] = texture; + + return texture; + + } + + _getRotatedImage( image ) { + + const canvas = document.createElement( 'canvas' ); + const context = canvas.getContext( '2d' ); + + const width = image.width; + const height = image.height; + + canvas.width = width; + canvas.height = height; + + context.clearRect( 0, 0, width, height ); + context.translate( width / 2.0, height / 2.0 ); + context.rotate( 0.5 * Math.PI ); // 90.0 * Math.PI / 180.0 + context.translate( - width / 2.0, - height / 2.0 ); + context.drawImage( image, 0, 0 ); + + return context.getImageData( 0, 0, width, height ); + + } + + // Check if the partial image area used by the texture is transparent. + _checkImageTransparency( map, geometry, groupIndex ) { + + map.readyCallbacks.push( function ( texture ) { + + // Is there any efficient ways? + function createImageData( image ) { + + const canvas = document.createElement( 'canvas' ); + canvas.width = image.width; + canvas.height = image.height; + + const context = canvas.getContext( '2d' ); + context.drawImage( image, 0, 0 ); + + return context.getImageData( 0, 0, canvas.width, canvas.height ); + + } + + function detectImageTransparency( image, uvs, indices ) { + + const width = image.width; + const height = image.height; + const data = image.data; + const threshold = 253; + + if ( data.length / ( width * height ) !== 4 ) return false; + + for ( let i = 0; i < indices.length; i += 3 ) { + + const centerUV = { x: 0.0, y: 0.0 }; + + for ( let j = 0; j < 3; j ++ ) { + + const index = indices[ i * 3 + j ]; + const uv = { x: uvs[ index * 2 + 0 ], y: uvs[ index * 2 + 1 ] }; + + if ( getAlphaByUv( image, uv ) < threshold ) return true; + + centerUV.x += uv.x; + centerUV.y += uv.y; + + } + + centerUV.x /= 3; + centerUV.y /= 3; + + if ( getAlphaByUv( image, centerUV ) < threshold ) return true; + + } + + return false; + + } + + /* + * This method expects + * texture.flipY = false + * texture.wrapS = RepeatWrapping + * texture.wrapT = RepeatWrapping + * TODO: more precise + */ + function getAlphaByUv( image, uv ) { + + const width = image.width; + const height = image.height; + + let x = Math.round( uv.x * width ) % width; + let y = Math.round( uv.y * height ) % height; + + if ( x < 0 ) x += width; + if ( y < 0 ) y += height; + + const index = y * width + x; + + return image.data[ index * 4 + 3 ]; + + } + + if ( texture.isCompressedTexture === true ) { + + if ( NON_ALPHA_CHANNEL_FORMATS.includes( texture.format ) ) { + + map.transparent = false; + + } else { + + // any other way to check transparency of CompressedTexture? + map.transparent = true; + + } + + return; + + } + + const imageData = texture.image.data !== undefined + ? texture.image + : createImageData( texture.image ); + + const group = geometry.groups[ groupIndex ]; + + if ( detectImageTransparency( + imageData, + geometry.attributes.uv.array, + geometry.index.array.slice( group.start, group.start + group.count ) ) ) { + + map.transparent = true; + + } + + } ); + + } + +} + +// + +class AnimationBuilder { + + /** + * @param {Object} vmd - parsed VMD data + * @param {SkinnedMesh} mesh - tracks will be fitting to mesh + * @return {AnimationClip} + */ + build( vmd, mesh ) { + + // combine skeletal and morph animations + + const tracks = this.buildSkeletalAnimation( vmd, mesh ).tracks; + const tracks2 = this.buildMorphAnimation( vmd, mesh ).tracks; + + for ( let i = 0, il = tracks2.length; i < il; i ++ ) { + + tracks.push( tracks2[ i ] ); + + } + + return new AnimationClip( '', - 1, tracks ); + + } + + /** + * @param {Object} vmd - parsed VMD data + * @param {SkinnedMesh} mesh - tracks will be fitting to mesh + * @return {AnimationClip} + */ + buildSkeletalAnimation( vmd, mesh ) { + + function pushInterpolation( array, interpolation, index ) { + + array.push( interpolation[ index + 0 ] / 127 ); // x1 + array.push( interpolation[ index + 8 ] / 127 ); // x2 + array.push( interpolation[ index + 4 ] / 127 ); // y1 + array.push( interpolation[ index + 12 ] / 127 ); // y2 + + } + + const tracks = []; + + const motions = {}; + const bones = mesh.skeleton.bones; + const boneNameDictionary = {}; + + for ( let i = 0, il = bones.length; i < il; i ++ ) { + + boneNameDictionary[ bones[ i ].name ] = true; + + } + + for ( let i = 0; i < vmd.metadata.motionCount; i ++ ) { + + const motion = vmd.motions[ i ]; + const boneName = motion.boneName; + + if ( boneNameDictionary[ boneName ] === undefined ) continue; + + motions[ boneName ] = motions[ boneName ] || []; + motions[ boneName ].push( motion ); + + } + + for ( const key in motions ) { + + const array = motions[ key ]; + + array.sort( function ( a, b ) { + + return a.frameNum - b.frameNum; + + } ); + + const times = []; + const positions = []; + const rotations = []; + const pInterpolations = []; + const rInterpolations = []; + + const basePosition = mesh.skeleton.getBoneByName( key ).position.toArray(); + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + const time = array[ i ].frameNum / 30; + const position = array[ i ].position; + const rotation = array[ i ].rotation; + const interpolation = array[ i ].interpolation; + + times.push( time ); + + for ( let j = 0; j < 3; j ++ ) positions.push( basePosition[ j ] + position[ j ] ); + for ( let j = 0; j < 4; j ++ ) rotations.push( rotation[ j ] ); + for ( let j = 0; j < 3; j ++ ) pushInterpolation( pInterpolations, interpolation, j ); + + pushInterpolation( rInterpolations, interpolation, 3 ); + + } + + const targetName = '.bones[' + key + ']'; + + tracks.push( this._createTrack( targetName + '.position', VectorKeyframeTrack, times, positions, pInterpolations ) ); + tracks.push( this._createTrack( targetName + '.quaternion', QuaternionKeyframeTrack, times, rotations, rInterpolations ) ); + + } + + return new AnimationClip( '', - 1, tracks ); + + } + + /** + * @param {Object} vmd - parsed VMD data + * @param {SkinnedMesh} mesh - tracks will be fitting to mesh + * @return {AnimationClip} + */ + buildMorphAnimation( vmd, mesh ) { + + const tracks = []; + + const morphs = {}; + const morphTargetDictionary = mesh.morphTargetDictionary; + + for ( let i = 0; i < vmd.metadata.morphCount; i ++ ) { + + const morph = vmd.morphs[ i ]; + const morphName = morph.morphName; + + if ( morphTargetDictionary[ morphName ] === undefined ) continue; + + morphs[ morphName ] = morphs[ morphName ] || []; + morphs[ morphName ].push( morph ); + + } + + for ( const key in morphs ) { + + const array = morphs[ key ]; + + array.sort( function ( a, b ) { + + return a.frameNum - b.frameNum; + + } ); + + const times = []; + const values = []; + + for ( let i = 0, il = array.length; i < il; i ++ ) { + + times.push( array[ i ].frameNum / 30 ); + values.push( array[ i ].weight ); + + } + + tracks.push( new NumberKeyframeTrack( '.morphTargetInfluences[' + morphTargetDictionary[ key ] + ']', times, values ) ); + + } + + return new AnimationClip( '', - 1, tracks ); + + } + + /** + * @param {Object} vmd - parsed VMD data + * @return {AnimationClip} + */ + buildCameraAnimation( vmd ) { + + function pushVector3( array, vec ) { + + array.push( vec.x ); + array.push( vec.y ); + array.push( vec.z ); + + } + + function pushQuaternion( array, q ) { + + array.push( q.x ); + array.push( q.y ); + array.push( q.z ); + array.push( q.w ); + + } + + function pushInterpolation( array, interpolation, index ) { + + array.push( interpolation[ index * 4 + 0 ] / 127 ); // x1 + array.push( interpolation[ index * 4 + 1 ] / 127 ); // x2 + array.push( interpolation[ index * 4 + 2 ] / 127 ); // y1 + array.push( interpolation[ index * 4 + 3 ] / 127 ); // y2 + + } + + const cameras = vmd.cameras === undefined ? [] : vmd.cameras.slice(); + + cameras.sort( function ( a, b ) { + + return a.frameNum - b.frameNum; + + } ); + + const times = []; + const centers = []; + const quaternions = []; + const positions = []; + const fovs = []; + + const cInterpolations = []; + const qInterpolations = []; + const pInterpolations = []; + const fInterpolations = []; + + const quaternion = new Quaternion(); + const euler = new Euler(); + const position = new Vector3(); + const center = new Vector3(); + + for ( let i = 0, il = cameras.length; i < il; i ++ ) { + + const motion = cameras[ i ]; + + const time = motion.frameNum / 30; + const pos = motion.position; + const rot = motion.rotation; + const distance = motion.distance; + const fov = motion.fov; + const interpolation = motion.interpolation; + + times.push( time ); + + position.set( 0, 0, - distance ); + center.set( pos[ 0 ], pos[ 1 ], pos[ 2 ] ); + + euler.set( - rot[ 0 ], - rot[ 1 ], - rot[ 2 ] ); + quaternion.setFromEuler( euler ); + + position.add( center ); + position.applyQuaternion( quaternion ); + + pushVector3( centers, center ); + pushQuaternion( quaternions, quaternion ); + pushVector3( positions, position ); + + fovs.push( fov ); + + for ( let j = 0; j < 3; j ++ ) { + + pushInterpolation( cInterpolations, interpolation, j ); + + } + + pushInterpolation( qInterpolations, interpolation, 3 ); + + // use the same parameter for x, y, z axis. + for ( let j = 0; j < 3; j ++ ) { + + pushInterpolation( pInterpolations, interpolation, 4 ); + + } + + pushInterpolation( fInterpolations, interpolation, 5 ); + + } + + const tracks = []; + + // I expect an object whose name 'target' exists under THREE.Camera + tracks.push( this._createTrack( 'target.position', VectorKeyframeTrack, times, centers, cInterpolations ) ); + + tracks.push( this._createTrack( '.quaternion', QuaternionKeyframeTrack, times, quaternions, qInterpolations ) ); + tracks.push( this._createTrack( '.position', VectorKeyframeTrack, times, positions, pInterpolations ) ); + tracks.push( this._createTrack( '.fov', NumberKeyframeTrack, times, fovs, fInterpolations ) ); + + return new AnimationClip( '', - 1, tracks ); + + } + + // private method + + _createTrack( node, typedKeyframeTrack, times, values, interpolations ) { + + /* + * optimizes here not to let KeyframeTrackPrototype optimize + * because KeyframeTrackPrototype optimizes times and values but + * doesn't optimize interpolations. + */ + if ( times.length > 2 ) { + + times = times.slice(); + values = values.slice(); + interpolations = interpolations.slice(); + + const stride = values.length / times.length; + const interpolateStride = interpolations.length / times.length; + + let index = 1; + + for ( let aheadIndex = 2, endIndex = times.length; aheadIndex < endIndex; aheadIndex ++ ) { + + for ( let i = 0; i < stride; i ++ ) { + + if ( values[ index * stride + i ] !== values[ ( index - 1 ) * stride + i ] || + values[ index * stride + i ] !== values[ aheadIndex * stride + i ] ) { + + index ++; + break; + + } + + } + + if ( aheadIndex > index ) { + + times[ index ] = times[ aheadIndex ]; + + for ( let i = 0; i < stride; i ++ ) { + + values[ index * stride + i ] = values[ aheadIndex * stride + i ]; + + } + + for ( let i = 0; i < interpolateStride; i ++ ) { + + interpolations[ index * interpolateStride + i ] = interpolations[ aheadIndex * interpolateStride + i ]; + + } + + } + + } + + times.length = index + 1; + values.length = ( index + 1 ) * stride; + interpolations.length = ( index + 1 ) * interpolateStride; + + } + + const track = new typedKeyframeTrack( node, times, values ); + + track.createInterpolant = function InterpolantFactoryMethodCubicBezier( result ) { + + return new CubicBezierInterpolation( this.times, this.values, this.getValueSize(), result, new Float32Array( interpolations ) ); + + }; + + return track; + + } + +} + +// interpolation + +class CubicBezierInterpolation extends Interpolant { + + constructor( parameterPositions, sampleValues, sampleSize, resultBuffer, params ) { + + super( parameterPositions, sampleValues, sampleSize, resultBuffer ); + + this.interpolationParams = params; + + } + + interpolate_( i1, t0, t, t1 ) { + + const result = this.resultBuffer; + const values = this.sampleValues; + const stride = this.valueSize; + const params = this.interpolationParams; + + const offset1 = i1 * stride; + const offset0 = offset1 - stride; + + // No interpolation if next key frame is in one frame in 30fps. + // This is from MMD animation spec. + // '1.5' is for precision loss. times are Float32 in Three.js Animation system. + const weight1 = ( ( t1 - t0 ) < 1 / 30 * 1.5 ) ? 0.0 : ( t - t0 ) / ( t1 - t0 ); + + if ( stride === 4 ) { // Quaternion + + const x1 = params[ i1 * 4 + 0 ]; + const x2 = params[ i1 * 4 + 1 ]; + const y1 = params[ i1 * 4 + 2 ]; + const y2 = params[ i1 * 4 + 3 ]; + + const ratio = this._calculate( x1, x2, y1, y2, weight1 ); + + Quaternion.slerpFlat( result, 0, values, offset0, values, offset1, ratio ); + + } else if ( stride === 3 ) { // Vector3 + + for ( let i = 0; i !== stride; ++ i ) { + + const x1 = params[ i1 * 12 + i * 4 + 0 ]; + const x2 = params[ i1 * 12 + i * 4 + 1 ]; + const y1 = params[ i1 * 12 + i * 4 + 2 ]; + const y2 = params[ i1 * 12 + i * 4 + 3 ]; + + const ratio = this._calculate( x1, x2, y1, y2, weight1 ); + + result[ i ] = values[ offset0 + i ] * ( 1 - ratio ) + values[ offset1 + i ] * ratio; + + } + + } else { // Number + + const x1 = params[ i1 * 4 + 0 ]; + const x2 = params[ i1 * 4 + 1 ]; + const y1 = params[ i1 * 4 + 2 ]; + const y2 = params[ i1 * 4 + 3 ]; + + const ratio = this._calculate( x1, x2, y1, y2, weight1 ); + + result[ 0 ] = values[ offset0 ] * ( 1 - ratio ) + values[ offset1 ] * ratio; + + } + + return result; + + } + + _calculate( x1, x2, y1, y2, x ) { + + /* + * Cubic Bezier curves + * https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B.C3.A9zier_curves + * + * B(t) = ( 1 - t ) ^ 3 * P0 + * + 3 * ( 1 - t ) ^ 2 * t * P1 + * + 3 * ( 1 - t ) * t^2 * P2 + * + t ^ 3 * P3 + * ( 0 <= t <= 1 ) + * + * MMD uses Cubic Bezier curves for bone and camera animation interpolation. + * http://d.hatena.ne.jp/edvakf/20111016/1318716097 + * + * x = ( 1 - t ) ^ 3 * x0 + * + 3 * ( 1 - t ) ^ 2 * t * x1 + * + 3 * ( 1 - t ) * t^2 * x2 + * + t ^ 3 * x3 + * y = ( 1 - t ) ^ 3 * y0 + * + 3 * ( 1 - t ) ^ 2 * t * y1 + * + 3 * ( 1 - t ) * t^2 * y2 + * + t ^ 3 * y3 + * ( x0 = 0, y0 = 0 ) + * ( x3 = 1, y3 = 1 ) + * ( 0 <= t, x1, x2, y1, y2 <= 1 ) + * + * Here solves this equation with Bisection method, + * https://en.wikipedia.org/wiki/Bisection_method + * gets t, and then calculate y. + * + * f(t) = 3 * ( 1 - t ) ^ 2 * t * x1 + * + 3 * ( 1 - t ) * t^2 * x2 + * + t ^ 3 - x = 0 + * + * (Another option: Newton's method + * https://en.wikipedia.org/wiki/Newton%27s_method) + */ + + let c = 0.5; + let t = c; + let s = 1.0 - t; + const loop = 15; + const eps = 1e-5; + const math = Math; + + let sst3, stt3, ttt; + + for ( let i = 0; i < loop; i ++ ) { + + sst3 = 3.0 * s * s * t; + stt3 = 3.0 * s * t * t; + ttt = t * t * t; + + const ft = ( sst3 * x1 ) + ( stt3 * x2 ) + ( ttt ) - x; + + if ( math.abs( ft ) < eps ) break; + + c /= 2.0; + + t += ( ft < 0 ) ? c : - c; + s = 1.0 - t; + + } + + return ( sst3 * y1 ) + ( stt3 * y2 ) + ttt; + + } + +} + +class MMDToonMaterial extends ShaderMaterial { + + constructor( parameters ) { + + super(); + + this.isMMDToonMaterial = true; + + this.type = 'MMDToonMaterial'; + + this._matcapCombine = AddOperation; + this.emissiveIntensity = 1.0; + this.normalMapType = TangentSpaceNormalMap; + + this.combine = MultiplyOperation; + + this.wireframeLinecap = 'round'; + this.wireframeLinejoin = 'round'; + + this.flatShading = false; + + this.lights = true; + + this.vertexShader = MMDToonShader.vertexShader; + this.fragmentShader = MMDToonShader.fragmentShader; + + this.defines = Object.assign( {}, MMDToonShader.defines ); + Object.defineProperty( this, 'matcapCombine', { + + get: function () { + + return this._matcapCombine; + + }, + + set: function ( value ) { + + this._matcapCombine = value; + + switch ( value ) { + + case MultiplyOperation: + this.defines.MATCAP_BLENDING_MULTIPLY = true; + delete this.defines.MATCAP_BLENDING_ADD; + break; + + default: + case AddOperation: + this.defines.MATCAP_BLENDING_ADD = true; + delete this.defines.MATCAP_BLENDING_MULTIPLY; + break; + + } + + }, + + } ); + + this.uniforms = UniformsUtils.clone( MMDToonShader.uniforms ); + + // merged from MeshToon/Phong/MatcapMaterial + const exposePropertyNames = [ + 'specular', + 'opacity', + 'diffuse', + + 'map', + 'matcap', + 'gradientMap', + + 'lightMap', + 'lightMapIntensity', + + 'aoMap', + 'aoMapIntensity', + + 'emissive', + 'emissiveMap', + + 'bumpMap', + 'bumpScale', + + 'normalMap', + 'normalScale', + + 'displacemantBias', + 'displacemantMap', + 'displacemantScale', + + 'specularMap', + + 'alphaMap', + + 'reflectivity', + 'refractionRatio', + ]; + for ( const propertyName of exposePropertyNames ) { + + Object.defineProperty( this, propertyName, { + + get: function () { + + return this.uniforms[ propertyName ].value; + + }, + + set: function ( value ) { + + this.uniforms[ propertyName ].value = value; + + }, + + } ); + + } + + // Special path for shininess to handle zero shininess properly + this._shininess = 30; + Object.defineProperty( this, 'shininess', { + + get: function () { + + return this._shininess; + + }, + + set: function ( value ) { + + this._shininess = value; + this.uniforms.shininess.value = Math.max( this._shininess, 1e-4 ); // To prevent pow( 0.0, 0.0 ) + + }, + + } ); + + Object.defineProperty( + this, + 'color', + Object.getOwnPropertyDescriptor( this, 'diffuse' ) + ); + + this.setValues( parameters ); + + } + + copy( source ) { + + super.copy( source ); + + this.matcapCombine = source.matcapCombine; + this.emissiveIntensity = source.emissiveIntensity; + this.normalMapType = source.normalMapType; + + this.combine = source.combine; + + this.wireframeLinecap = source.wireframeLinecap; + this.wireframeLinejoin = source.wireframeLinejoin; + + this.flatShading = source.flatShading; + + return this; + + } + +} + +export { MMDLoader }; diff --git a/ui/viewer/vendor/three/addons/loaders/TGALoader.js b/ui/viewer/vendor/three/addons/loaders/TGALoader.js new file mode 100644 index 0000000..deab157 --- /dev/null +++ b/ui/viewer/vendor/three/addons/loaders/TGALoader.js @@ -0,0 +1,517 @@ +import { + DataTextureLoader, + LinearMipmapLinearFilter +} from 'three'; + +class TGALoader extends DataTextureLoader { + + constructor( manager ) { + + super( manager ); + + } + + parse( buffer ) { + + // reference from vthibault, https://github.com/vthibault/roBrowser/blob/master/src/Loaders/Targa.js + + function tgaCheckHeader( header ) { + + switch ( header.image_type ) { + + // check indexed type + + case TGA_TYPE_INDEXED: + case TGA_TYPE_RLE_INDEXED: + if ( header.colormap_length > 256 || header.colormap_size !== 24 || header.colormap_type !== 1 ) { + + throw new Error( 'THREE.TGALoader: Invalid type colormap data for indexed type.' ); + + } + + break; + + // check colormap type + + case TGA_TYPE_RGB: + case TGA_TYPE_GREY: + case TGA_TYPE_RLE_RGB: + case TGA_TYPE_RLE_GREY: + if ( header.colormap_type ) { + + throw new Error( 'THREE.TGALoader: Invalid type colormap data for colormap type.' ); + + } + + break; + + // What the need of a file without data ? + + case TGA_TYPE_NO_DATA: + throw new Error( 'THREE.TGALoader: No data.' ); + + // Invalid type ? + + default: + throw new Error( 'THREE.TGALoader: Invalid type ' + header.image_type ); + + } + + // check image width and height + + if ( header.width <= 0 || header.height <= 0 ) { + + throw new Error( 'THREE.TGALoader: Invalid image size.' ); + + } + + // check image pixel size + + if ( header.pixel_size !== 8 && header.pixel_size !== 16 && + header.pixel_size !== 24 && header.pixel_size !== 32 ) { + + throw new Error( 'THREE.TGALoader: Invalid pixel size ' + header.pixel_size ); + + } + + } + + // parse tga image buffer + + function tgaParse( use_rle, use_pal, header, offset, data ) { + + let pixel_data, + palettes; + + const pixel_size = header.pixel_size >> 3; + const pixel_total = header.width * header.height * pixel_size; + + // read palettes + + if ( use_pal ) { + + palettes = data.subarray( offset, offset += header.colormap_length * ( header.colormap_size >> 3 ) ); + + } + + // read RLE + + if ( use_rle ) { + + pixel_data = new Uint8Array( pixel_total ); + + let c, count, i; + let shift = 0; + const pixels = new Uint8Array( pixel_size ); + + while ( shift < pixel_total ) { + + c = data[ offset ++ ]; + count = ( c & 0x7f ) + 1; + + // RLE pixels + + if ( c & 0x80 ) { + + // bind pixel tmp array + + for ( i = 0; i < pixel_size; ++ i ) { + + pixels[ i ] = data[ offset ++ ]; + + } + + // copy pixel array + + for ( i = 0; i < count; ++ i ) { + + pixel_data.set( pixels, shift + i * pixel_size ); + + } + + shift += pixel_size * count; + + } else { + + // raw pixels + + count *= pixel_size; + + for ( i = 0; i < count; ++ i ) { + + pixel_data[ shift + i ] = data[ offset ++ ]; + + } + + shift += count; + + } + + } + + } else { + + // raw pixels + + pixel_data = data.subarray( + offset, offset += ( use_pal ? header.width * header.height : pixel_total ) + ); + + } + + return { + pixel_data: pixel_data, + palettes: palettes + }; + + } + + function tgaGetImageData8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image, palettes ) { + + const colormap = palettes; + let color, i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i ++ ) { + + color = image[ i ]; + imageData[ ( x + width * y ) * 4 + 3 ] = 255; + imageData[ ( x + width * y ) * 4 + 2 ] = colormap[ ( color * 3 ) + 0 ]; + imageData[ ( x + width * y ) * 4 + 1 ] = colormap[ ( color * 3 ) + 1 ]; + imageData[ ( x + width * y ) * 4 + 0 ] = colormap[ ( color * 3 ) + 2 ]; + + } + + } + + return imageData; + + } + + function tgaGetImageData16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { + + let color, i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i += 2 ) { + + color = image[ i + 0 ] + ( image[ i + 1 ] << 8 ); + imageData[ ( x + width * y ) * 4 + 0 ] = ( color & 0x7C00 ) >> 7; + imageData[ ( x + width * y ) * 4 + 1 ] = ( color & 0x03E0 ) >> 2; + imageData[ ( x + width * y ) * 4 + 2 ] = ( color & 0x001F ) << 3; + imageData[ ( x + width * y ) * 4 + 3 ] = ( color & 0x8000 ) ? 0 : 255; + + } + + } + + return imageData; + + } + + function tgaGetImageData24bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { + + let i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i += 3 ) { + + imageData[ ( x + width * y ) * 4 + 3 ] = 255; + imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; + imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ]; + imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ]; + + } + + } + + return imageData; + + } + + function tgaGetImageData32bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { + + let i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i += 4 ) { + + imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; + imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 1 ]; + imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 2 ]; + imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 3 ]; + + } + + } + + return imageData; + + } + + function tgaGetImageDataGrey8bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { + + let color, i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i ++ ) { + + color = image[ i ]; + imageData[ ( x + width * y ) * 4 + 0 ] = color; + imageData[ ( x + width * y ) * 4 + 1 ] = color; + imageData[ ( x + width * y ) * 4 + 2 ] = color; + imageData[ ( x + width * y ) * 4 + 3 ] = 255; + + } + + } + + return imageData; + + } + + function tgaGetImageDataGrey16bits( imageData, y_start, y_step, y_end, x_start, x_step, x_end, image ) { + + let i = 0, x, y; + const width = header.width; + + for ( y = y_start; y !== y_end; y += y_step ) { + + for ( x = x_start; x !== x_end; x += x_step, i += 2 ) { + + imageData[ ( x + width * y ) * 4 + 0 ] = image[ i + 0 ]; + imageData[ ( x + width * y ) * 4 + 1 ] = image[ i + 0 ]; + imageData[ ( x + width * y ) * 4 + 2 ] = image[ i + 0 ]; + imageData[ ( x + width * y ) * 4 + 3 ] = image[ i + 1 ]; + + } + + } + + return imageData; + + } + + function getTgaRGBA( data, width, height, image, palette ) { + + let x_start, + y_start, + x_step, + y_step, + x_end, + y_end; + + switch ( ( header.flags & TGA_ORIGIN_MASK ) >> TGA_ORIGIN_SHIFT ) { + + default: + case TGA_ORIGIN_UL: + x_start = 0; + x_step = 1; + x_end = width; + y_start = 0; + y_step = 1; + y_end = height; + break; + + case TGA_ORIGIN_BL: + x_start = 0; + x_step = 1; + x_end = width; + y_start = height - 1; + y_step = - 1; + y_end = - 1; + break; + + case TGA_ORIGIN_UR: + x_start = width - 1; + x_step = - 1; + x_end = - 1; + y_start = 0; + y_step = 1; + y_end = height; + break; + + case TGA_ORIGIN_BR: + x_start = width - 1; + x_step = - 1; + x_end = - 1; + y_start = height - 1; + y_step = - 1; + y_end = - 1; + break; + + } + + if ( use_grey ) { + + switch ( header.pixel_size ) { + + case 8: + tgaGetImageDataGrey8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); + break; + + case 16: + tgaGetImageDataGrey16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); + break; + + default: + throw new Error( 'THREE.TGALoader: Format not supported.' ); + break; + + } + + } else { + + switch ( header.pixel_size ) { + + case 8: + tgaGetImageData8bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image, palette ); + break; + + case 16: + tgaGetImageData16bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); + break; + + case 24: + tgaGetImageData24bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); + break; + + case 32: + tgaGetImageData32bits( data, y_start, y_step, y_end, x_start, x_step, x_end, image ); + break; + + default: + throw new Error( 'THREE.TGALoader: Format not supported.' ); + break; + + } + + } + + // Load image data according to specific method + // let func = 'tgaGetImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits'; + // func(data, y_start, y_step, y_end, x_start, x_step, x_end, width, image, palette ); + return data; + + } + + // TGA constants + + const TGA_TYPE_NO_DATA = 0, + TGA_TYPE_INDEXED = 1, + TGA_TYPE_RGB = 2, + TGA_TYPE_GREY = 3, + TGA_TYPE_RLE_INDEXED = 9, + TGA_TYPE_RLE_RGB = 10, + TGA_TYPE_RLE_GREY = 11, + + TGA_ORIGIN_MASK = 0x30, + TGA_ORIGIN_SHIFT = 0x04, + TGA_ORIGIN_BL = 0x00, + TGA_ORIGIN_BR = 0x01, + TGA_ORIGIN_UL = 0x02, + TGA_ORIGIN_UR = 0x03; + + if ( buffer.length < 19 ) throw new Error( 'THREE.TGALoader: Not enough data to contain header.' ); + + let offset = 0; + + const content = new Uint8Array( buffer ), + header = { + id_length: content[ offset ++ ], + colormap_type: content[ offset ++ ], + image_type: content[ offset ++ ], + colormap_index: content[ offset ++ ] | content[ offset ++ ] << 8, + colormap_length: content[ offset ++ ] | content[ offset ++ ] << 8, + colormap_size: content[ offset ++ ], + origin: [ + content[ offset ++ ] | content[ offset ++ ] << 8, + content[ offset ++ ] | content[ offset ++ ] << 8 + ], + width: content[ offset ++ ] | content[ offset ++ ] << 8, + height: content[ offset ++ ] | content[ offset ++ ] << 8, + pixel_size: content[ offset ++ ], + flags: content[ offset ++ ] + }; + + // check tga if it is valid format + + tgaCheckHeader( header ); + + if ( header.id_length + offset > buffer.length ) { + + throw new Error( 'THREE.TGALoader: No data.' ); + + } + + // skip the needn't data + + offset += header.id_length; + + // get targa information about RLE compression and palette + + let use_rle = false, + use_pal = false, + use_grey = false; + + switch ( header.image_type ) { + + case TGA_TYPE_RLE_INDEXED: + use_rle = true; + use_pal = true; + break; + + case TGA_TYPE_INDEXED: + use_pal = true; + break; + + case TGA_TYPE_RLE_RGB: + use_rle = true; + break; + + case TGA_TYPE_RGB: + break; + + case TGA_TYPE_RLE_GREY: + use_rle = true; + use_grey = true; + break; + + case TGA_TYPE_GREY: + use_grey = true; + break; + + } + + // + + const imageData = new Uint8Array( header.width * header.height * 4 ); + const result = tgaParse( use_rle, use_pal, header, offset, content ); + getTgaRGBA( imageData, header.width, header.height, result.pixel_data, result.palettes ); + + return { + + data: imageData, + width: header.width, + height: header.height, + flipY: true, + generateMipmaps: true, + minFilter: LinearMipmapLinearFilter, + + }; + + } + +} + +export { TGALoader }; diff --git a/ui/viewer/vendor/three/addons/shaders/MMDToonShader.js b/ui/viewer/vendor/three/addons/shaders/MMDToonShader.js new file mode 100644 index 0000000..7f5ce4b --- /dev/null +++ b/ui/viewer/vendor/three/addons/shaders/MMDToonShader.js @@ -0,0 +1,134 @@ +/** + * MMD Toon Shader + * + * This shader is extended from MeshPhongMaterial, and merged algorithms with + * MeshToonMaterial and MeshMetcapMaterial. + * Ideas came from https://github.com/mrdoob/three.js/issues/19609 + * + * Combining steps: + * * Declare matcap uniform. + * * Add gradientmap_pars_fragment. + * * Use gradient irradiances instead of dotNL irradiance from MeshPhongMaterial. + * (Replace lights_phong_pars_fragment with lights_mmd_toon_pars_fragment) + * * Add mmd_toon_matcap_fragment. + */ + +import { UniformsUtils, ShaderLib } from 'three'; + +const lights_mmd_toon_pars_fragment = /* glsl */` +varying vec3 vViewPosition; + +struct BlinnPhongMaterial { + + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; + +}; + +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; + +} + +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + +} + +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong +`; + +const mmd_toon_matcap_fragment = /* glsl */` +#ifdef USE_MATCAP + + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; // 0.495 to remove artifacts caused by undersized matcap disks + vec4 matcapColor = texture2D( matcap, uv ); + + #ifdef MATCAP_BLENDING_MULTIPLY + + outgoingLight *= matcapColor.rgb; + + #elif defined( MATCAP_BLENDING_ADD ) + + outgoingLight += matcapColor.rgb; + + #endif + +#endif +`; + +const MMDToonShader = { + + name: 'MMDToonShader', + + defines: { + TOON: true, + MATCAP: true, + MATCAP_BLENDING_ADD: true, + }, + + uniforms: UniformsUtils.merge( [ + ShaderLib.toon.uniforms, + ShaderLib.phong.uniforms, + ShaderLib.matcap.uniforms, + ] ), + + vertexShader: + ShaderLib.phong.vertexShader + .replace( + '#include ', + '' + ) + .replace( + '#include ', + '' + ), + + fragmentShader: + ShaderLib.phong.fragmentShader + .replace( + '#include ', + ` + #ifdef USE_MATCAP + uniform sampler2D matcap; + #endif + + #include + ` + ) + .replace( + '#include ', + ` + #include + ` + ) + .replace( + '#include ', + '' + ) + .replace( + '#include ', + lights_mmd_toon_pars_fragment + ) + .replace( + '#include ', + ` + ${mmd_toon_matcap_fragment} + ` + ) + +}; + +export { MMDToonShader }; diff --git a/ui/viewer/vendor/three/addons/utils/BufferGeometryUtils.js b/ui/viewer/vendor/three/addons/utils/BufferGeometryUtils.js new file mode 100644 index 0000000..cc3e4ef --- /dev/null +++ b/ui/viewer/vendor/three/addons/utils/BufferGeometryUtils.js @@ -0,0 +1,1373 @@ +import { + BufferAttribute, + BufferGeometry, + Float32BufferAttribute, + InstancedBufferAttribute, + InterleavedBuffer, + InterleavedBufferAttribute, + TriangleFanDrawMode, + TriangleStripDrawMode, + TrianglesDrawMode, + Vector3, +} from 'three'; + +function computeMikkTSpaceTangents( geometry, MikkTSpace, negateSign = true ) { + + if ( ! MikkTSpace || ! MikkTSpace.isReady ) { + + throw new Error( 'BufferGeometryUtils: Initialized MikkTSpace library required.' ); + + } + + if ( ! geometry.hasAttribute( 'position' ) || ! geometry.hasAttribute( 'normal' ) || ! geometry.hasAttribute( 'uv' ) ) { + + throw new Error( 'BufferGeometryUtils: Tangents require "position", "normal", and "uv" attributes.' ); + + } + + function getAttributeArray( attribute ) { + + if ( attribute.normalized || attribute.isInterleavedBufferAttribute ) { + + const dstArray = new Float32Array( attribute.count * attribute.itemSize ); + + for ( let i = 0, j = 0; i < attribute.count; i ++ ) { + + dstArray[ j ++ ] = attribute.getX( i ); + dstArray[ j ++ ] = attribute.getY( i ); + + if ( attribute.itemSize > 2 ) { + + dstArray[ j ++ ] = attribute.getZ( i ); + + } + + } + + return dstArray; + + } + + if ( attribute.array instanceof Float32Array ) { + + return attribute.array; + + } + + return new Float32Array( attribute.array ); + + } + + // MikkTSpace algorithm requires non-indexed input. + + const _geometry = geometry.index ? geometry.toNonIndexed() : geometry; + + // Compute vertex tangents. + + const tangents = MikkTSpace.generateTangents( + + getAttributeArray( _geometry.attributes.position ), + getAttributeArray( _geometry.attributes.normal ), + getAttributeArray( _geometry.attributes.uv ) + + ); + + // Texture coordinate convention of glTF differs from the apparent + // default of the MikkTSpace library; .w component must be flipped. + + if ( negateSign ) { + + for ( let i = 3; i < tangents.length; i += 4 ) { + + tangents[ i ] *= - 1; + + } + + } + + // + + _geometry.setAttribute( 'tangent', new BufferAttribute( tangents, 4 ) ); + + if ( geometry !== _geometry ) { + + geometry.copy( _geometry ); + + } + + return geometry; + +} + +/** + * @param {Array} geometries + * @param {Boolean} useGroups + * @return {BufferGeometry} + */ +function mergeGeometries( geometries, useGroups = false ) { + + const isIndexed = geometries[ 0 ].index !== null; + + const attributesUsed = new Set( Object.keys( geometries[ 0 ].attributes ) ); + const morphAttributesUsed = new Set( Object.keys( geometries[ 0 ].morphAttributes ) ); + + const attributes = {}; + const morphAttributes = {}; + + const morphTargetsRelative = geometries[ 0 ].morphTargetsRelative; + + const mergedGeometry = new BufferGeometry(); + + let offset = 0; + + for ( let i = 0; i < geometries.length; ++ i ) { + + const geometry = geometries[ i ]; + let attributesCount = 0; + + // ensure that all geometries are indexed, or none + + if ( isIndexed !== ( geometry.index !== null ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them.' ); + return null; + + } + + // gather attributes, exit early if they're different + + for ( const name in geometry.attributes ) { + + if ( ! attributesUsed.has( name ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. All geometries must have compatible attributes; make sure "' + name + '" attribute exists among all geometries, or in none of them.' ); + return null; + + } + + if ( attributes[ name ] === undefined ) attributes[ name ] = []; + + attributes[ name ].push( geometry.attributes[ name ] ); + + attributesCount ++; + + } + + // ensure geometries have the same number of attributes + + if ( attributesCount !== attributesUsed.size ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. Make sure all geometries have the same number of attributes.' ); + return null; + + } + + // gather morph attributes, exit early if they're different + + if ( morphTargetsRelative !== geometry.morphTargetsRelative ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphTargetsRelative must be consistent throughout all geometries.' ); + return null; + + } + + for ( const name in geometry.morphAttributes ) { + + if ( ! morphAttributesUsed.has( name ) ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. .morphAttributes must be consistent throughout all geometries.' ); + return null; + + } + + if ( morphAttributes[ name ] === undefined ) morphAttributes[ name ] = []; + + morphAttributes[ name ].push( geometry.morphAttributes[ name ] ); + + } + + if ( useGroups ) { + + let count; + + if ( isIndexed ) { + + count = geometry.index.count; + + } else if ( geometry.attributes.position !== undefined ) { + + count = geometry.attributes.position.count; + + } else { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index ' + i + '. The geometry must have either an index or a position attribute' ); + return null; + + } + + mergedGeometry.addGroup( offset, count, i ); + + offset += count; + + } + + } + + // merge indices + + if ( isIndexed ) { + + let indexOffset = 0; + const mergedIndex = []; + + for ( let i = 0; i < geometries.length; ++ i ) { + + const index = geometries[ i ].index; + + for ( let j = 0; j < index.count; ++ j ) { + + mergedIndex.push( index.getX( j ) + indexOffset ); + + } + + indexOffset += geometries[ i ].attributes.position.count; + + } + + mergedGeometry.setIndex( mergedIndex ); + + } + + // merge attributes + + for ( const name in attributes ) { + + const mergedAttribute = mergeAttributes( attributes[ name ] ); + + if ( ! mergedAttribute ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' attribute.' ); + return null; + + } + + mergedGeometry.setAttribute( name, mergedAttribute ); + + } + + // merge morph attributes + + for ( const name in morphAttributes ) { + + const numMorphTargets = morphAttributes[ name ][ 0 ].length; + + if ( numMorphTargets === 0 ) break; + + mergedGeometry.morphAttributes = mergedGeometry.morphAttributes || {}; + mergedGeometry.morphAttributes[ name ] = []; + + for ( let i = 0; i < numMorphTargets; ++ i ) { + + const morphAttributesToMerge = []; + + for ( let j = 0; j < morphAttributes[ name ].length; ++ j ) { + + morphAttributesToMerge.push( morphAttributes[ name ][ j ][ i ] ); + + } + + const mergedMorphAttribute = mergeAttributes( morphAttributesToMerge ); + + if ( ! mergedMorphAttribute ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the ' + name + ' morphAttribute.' ); + return null; + + } + + mergedGeometry.morphAttributes[ name ].push( mergedMorphAttribute ); + + } + + } + + return mergedGeometry; + +} + +/** + * @param {Array} attributes + * @return {BufferAttribute} + */ +function mergeAttributes( attributes ) { + + let TypedArray; + let itemSize; + let normalized; + let gpuType = - 1; + let arrayLength = 0; + + for ( let i = 0; i < attributes.length; ++ i ) { + + const attribute = attributes[ i ]; + + if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; + if ( TypedArray !== attribute.array.constructor ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes.' ); + return null; + + } + + if ( itemSize === undefined ) itemSize = attribute.itemSize; + if ( itemSize !== attribute.itemSize ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes.' ); + return null; + + } + + if ( normalized === undefined ) normalized = attribute.normalized; + if ( normalized !== attribute.normalized ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes.' ); + return null; + + } + + if ( gpuType === - 1 ) gpuType = attribute.gpuType; + if ( gpuType !== attribute.gpuType ) { + + console.error( 'THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes.' ); + return null; + + } + + arrayLength += attribute.count * itemSize; + + } + + const array = new TypedArray( arrayLength ); + const result = new BufferAttribute( array, itemSize, normalized ); + let offset = 0; + + for ( let i = 0; i < attributes.length; ++ i ) { + + const attribute = attributes[ i ]; + if ( attribute.isInterleavedBufferAttribute ) { + + const tupleOffset = offset / itemSize; + for ( let j = 0, l = attribute.count; j < l; j ++ ) { + + for ( let c = 0; c < itemSize; c ++ ) { + + const value = attribute.getComponent( j, c ); + result.setComponent( j + tupleOffset, c, value ); + + } + + } + + } else { + + array.set( attribute.array, offset ); + + } + + offset += attribute.count * itemSize; + + } + + if ( gpuType !== undefined ) { + + result.gpuType = gpuType; + + } + + return result; + +} + +/** + * @param {BufferAttribute} + * @return {BufferAttribute} + */ +export function deepCloneAttribute( attribute ) { + + if ( attribute.isInstancedInterleavedBufferAttribute || attribute.isInterleavedBufferAttribute ) { + + return deinterleaveAttribute( attribute ); + + } + + if ( attribute.isInstancedBufferAttribute ) { + + return new InstancedBufferAttribute().copy( attribute ); + + } + + return new BufferAttribute().copy( attribute ); + +} + +/** + * @param {Array} attributes + * @return {Array} + */ +function interleaveAttributes( attributes ) { + + // Interleaves the provided attributes into an InterleavedBuffer and returns + // a set of InterleavedBufferAttributes for each attribute + let TypedArray; + let arrayLength = 0; + let stride = 0; + + // calculate the length and type of the interleavedBuffer + for ( let i = 0, l = attributes.length; i < l; ++ i ) { + + const attribute = attributes[ i ]; + + if ( TypedArray === undefined ) TypedArray = attribute.array.constructor; + if ( TypedArray !== attribute.array.constructor ) { + + console.error( 'AttributeBuffers of different types cannot be interleaved' ); + return null; + + } + + arrayLength += attribute.array.length; + stride += attribute.itemSize; + + } + + // Create the set of buffer attributes + const interleavedBuffer = new InterleavedBuffer( new TypedArray( arrayLength ), stride ); + let offset = 0; + const res = []; + const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; + const setters = [ 'setX', 'setY', 'setZ', 'setW' ]; + + for ( let j = 0, l = attributes.length; j < l; j ++ ) { + + const attribute = attributes[ j ]; + const itemSize = attribute.itemSize; + const count = attribute.count; + const iba = new InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, attribute.normalized ); + res.push( iba ); + + offset += itemSize; + + // Move the data for each attribute into the new interleavedBuffer + // at the appropriate offset + for ( let c = 0; c < count; c ++ ) { + + for ( let k = 0; k < itemSize; k ++ ) { + + iba[ setters[ k ] ]( c, attribute[ getters[ k ] ]( c ) ); + + } + + } + + } + + return res; + +} + +// returns a new, non-interleaved version of the provided attribute +export function deinterleaveAttribute( attribute ) { + + const cons = attribute.data.array.constructor; + const count = attribute.count; + const itemSize = attribute.itemSize; + const normalized = attribute.normalized; + + const array = new cons( count * itemSize ); + let newAttribute; + if ( attribute.isInstancedInterleavedBufferAttribute ) { + + newAttribute = new InstancedBufferAttribute( array, itemSize, normalized, attribute.meshPerAttribute ); + + } else { + + newAttribute = new BufferAttribute( array, itemSize, normalized ); + + } + + for ( let i = 0; i < count; i ++ ) { + + newAttribute.setX( i, attribute.getX( i ) ); + + if ( itemSize >= 2 ) { + + newAttribute.setY( i, attribute.getY( i ) ); + + } + + if ( itemSize >= 3 ) { + + newAttribute.setZ( i, attribute.getZ( i ) ); + + } + + if ( itemSize >= 4 ) { + + newAttribute.setW( i, attribute.getW( i ) ); + + } + + } + + return newAttribute; + +} + +// deinterleaves all attributes on the geometry +export function deinterleaveGeometry( geometry ) { + + const attributes = geometry.attributes; + const morphTargets = geometry.morphTargets; + const attrMap = new Map(); + + for ( const key in attributes ) { + + const attr = attributes[ key ]; + if ( attr.isInterleavedBufferAttribute ) { + + if ( ! attrMap.has( attr ) ) { + + attrMap.set( attr, deinterleaveAttribute( attr ) ); + + } + + attributes[ key ] = attrMap.get( attr ); + + } + + } + + for ( const key in morphTargets ) { + + const attr = morphTargets[ key ]; + if ( attr.isInterleavedBufferAttribute ) { + + if ( ! attrMap.has( attr ) ) { + + attrMap.set( attr, deinterleaveAttribute( attr ) ); + + } + + morphTargets[ key ] = attrMap.get( attr ); + + } + + } + +} + +/** + * @param {BufferGeometry} geometry + * @return {number} + */ +function estimateBytesUsed( geometry ) { + + // Return the estimated memory used by this geometry in bytes + // Calculate using itemSize, count, and BYTES_PER_ELEMENT to account + // for InterleavedBufferAttributes. + let mem = 0; + for ( const name in geometry.attributes ) { + + const attr = geometry.getAttribute( name ); + mem += attr.count * attr.itemSize * attr.array.BYTES_PER_ELEMENT; + + } + + const indices = geometry.getIndex(); + mem += indices ? indices.count * indices.itemSize * indices.array.BYTES_PER_ELEMENT : 0; + return mem; + +} + +/** + * @param {BufferGeometry} geometry + * @param {number} tolerance + * @return {BufferGeometry} + */ +function mergeVertices( geometry, tolerance = 1e-4 ) { + + tolerance = Math.max( tolerance, Number.EPSILON ); + + // Generate an index buffer if the geometry doesn't have one, or optimize it + // if it's already available. + const hashToIndex = {}; + const indices = geometry.getIndex(); + const positions = geometry.getAttribute( 'position' ); + const vertexCount = indices ? indices.count : positions.count; + + // next value for triangle indices + let nextIndex = 0; + + // attributes and new attribute arrays + const attributeNames = Object.keys( geometry.attributes ); + const tmpAttributes = {}; + const tmpMorphAttributes = {}; + const newIndices = []; + const getters = [ 'getX', 'getY', 'getZ', 'getW' ]; + const setters = [ 'setX', 'setY', 'setZ', 'setW' ]; + + // Initialize the arrays, allocating space conservatively. Extra + // space will be trimmed in the last step. + for ( let i = 0, l = attributeNames.length; i < l; i ++ ) { + + const name = attributeNames[ i ]; + const attr = geometry.attributes[ name ]; + + tmpAttributes[ name ] = new attr.constructor( + new attr.array.constructor( attr.count * attr.itemSize ), + attr.itemSize, + attr.normalized + ); + + const morphAttributes = geometry.morphAttributes[ name ]; + if ( morphAttributes ) { + + if ( ! tmpMorphAttributes[ name ] ) tmpMorphAttributes[ name ] = []; + morphAttributes.forEach( ( morphAttr, i ) => { + + const array = new morphAttr.array.constructor( morphAttr.count * morphAttr.itemSize ); + tmpMorphAttributes[ name ][ i ] = new morphAttr.constructor( array, morphAttr.itemSize, morphAttr.normalized ); + + } ); + + } + + } + + // convert the error tolerance to an amount of decimal places to truncate to + const halfTolerance = tolerance * 0.5; + const exponent = Math.log10( 1 / tolerance ); + const hashMultiplier = Math.pow( 10, exponent ); + const hashAdditive = halfTolerance * hashMultiplier; + for ( let i = 0; i < vertexCount; i ++ ) { + + const index = indices ? indices.getX( i ) : i; + + // Generate a hash for the vertex attributes at the current index 'i' + let hash = ''; + for ( let j = 0, l = attributeNames.length; j < l; j ++ ) { + + const name = attributeNames[ j ]; + const attribute = geometry.getAttribute( name ); + const itemSize = attribute.itemSize; + + for ( let k = 0; k < itemSize; k ++ ) { + + // double tilde truncates the decimal value + hash += `${ ~ ~ ( attribute[ getters[ k ] ]( index ) * hashMultiplier + hashAdditive ) },`; + + } + + } + + // Add another reference to the vertex if it's already + // used by another index + if ( hash in hashToIndex ) { + + newIndices.push( hashToIndex[ hash ] ); + + } else { + + // copy data to the new index in the temporary attributes + for ( let j = 0, l = attributeNames.length; j < l; j ++ ) { + + const name = attributeNames[ j ]; + const attribute = geometry.getAttribute( name ); + const morphAttributes = geometry.morphAttributes[ name ]; + const itemSize = attribute.itemSize; + const newArray = tmpAttributes[ name ]; + const newMorphArrays = tmpMorphAttributes[ name ]; + + for ( let k = 0; k < itemSize; k ++ ) { + + const getterFunc = getters[ k ]; + const setterFunc = setters[ k ]; + newArray[ setterFunc ]( nextIndex, attribute[ getterFunc ]( index ) ); + + if ( morphAttributes ) { + + for ( let m = 0, ml = morphAttributes.length; m < ml; m ++ ) { + + newMorphArrays[ m ][ setterFunc ]( nextIndex, morphAttributes[ m ][ getterFunc ]( index ) ); + + } + + } + + } + + } + + hashToIndex[ hash ] = nextIndex; + newIndices.push( nextIndex ); + nextIndex ++; + + } + + } + + // generate result BufferGeometry + const result = geometry.clone(); + for ( const name in geometry.attributes ) { + + const tmpAttribute = tmpAttributes[ name ]; + + result.setAttribute( name, new tmpAttribute.constructor( + tmpAttribute.array.slice( 0, nextIndex * tmpAttribute.itemSize ), + tmpAttribute.itemSize, + tmpAttribute.normalized, + ) ); + + if ( ! ( name in tmpMorphAttributes ) ) continue; + + for ( let j = 0; j < tmpMorphAttributes[ name ].length; j ++ ) { + + const tmpMorphAttribute = tmpMorphAttributes[ name ][ j ]; + + result.morphAttributes[ name ][ j ] = new tmpMorphAttribute.constructor( + tmpMorphAttribute.array.slice( 0, nextIndex * tmpMorphAttribute.itemSize ), + tmpMorphAttribute.itemSize, + tmpMorphAttribute.normalized, + ); + + } + + } + + // indices + + result.setIndex( newIndices ); + + return result; + +} + +/** + * @param {BufferGeometry} geometry + * @param {number} drawMode + * @return {BufferGeometry} + */ +function toTrianglesDrawMode( geometry, drawMode ) { + + if ( drawMode === TrianglesDrawMode ) { + + console.warn( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles.' ); + return geometry; + + } + + if ( drawMode === TriangleFanDrawMode || drawMode === TriangleStripDrawMode ) { + + let index = geometry.getIndex(); + + // generate index if not present + + if ( index === null ) { + + const indices = []; + + const position = geometry.getAttribute( 'position' ); + + if ( position !== undefined ) { + + for ( let i = 0; i < position.count; i ++ ) { + + indices.push( i ); + + } + + geometry.setIndex( indices ); + index = geometry.getIndex(); + + } else { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.' ); + return geometry; + + } + + } + + // + + const numberOfTriangles = index.count - 2; + const newIndices = []; + + if ( drawMode === TriangleFanDrawMode ) { + + // gl.TRIANGLE_FAN + + for ( let i = 1; i <= numberOfTriangles; i ++ ) { + + newIndices.push( index.getX( 0 ) ); + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + + } + + } else { + + // gl.TRIANGLE_STRIP + + for ( let i = 0; i < numberOfTriangles; i ++ ) { + + if ( i % 2 === 0 ) { + + newIndices.push( index.getX( i ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i + 2 ) ); + + } else { + + newIndices.push( index.getX( i + 2 ) ); + newIndices.push( index.getX( i + 1 ) ); + newIndices.push( index.getX( i ) ); + + } + + } + + } + + if ( ( newIndices.length / 3 ) !== numberOfTriangles ) { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.' ); + + } + + // build final geometry + + const newGeometry = geometry.clone(); + newGeometry.setIndex( newIndices ); + newGeometry.clearGroups(); + + return newGeometry; + + } else { + + console.error( 'THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:', drawMode ); + return geometry; + + } + +} + +/** + * Calculates the morphed attributes of a morphed/skinned BufferGeometry. + * Helpful for Raytracing or Decals. + * @param {Mesh | Line | Points} object An instance of Mesh, Line or Points. + * @return {Object} An Object with original position/normal attributes and morphed ones. + */ +function computeMorphedAttributes( object ) { + + const _vA = new Vector3(); + const _vB = new Vector3(); + const _vC = new Vector3(); + + const _tempA = new Vector3(); + const _tempB = new Vector3(); + const _tempC = new Vector3(); + + const _morphA = new Vector3(); + const _morphB = new Vector3(); + const _morphC = new Vector3(); + + function _calculateMorphedAttributeData( + object, + attribute, + morphAttribute, + morphTargetsRelative, + a, + b, + c, + modifiedAttributeArray + ) { + + _vA.fromBufferAttribute( attribute, a ); + _vB.fromBufferAttribute( attribute, b ); + _vC.fromBufferAttribute( attribute, c ); + + const morphInfluences = object.morphTargetInfluences; + + if ( morphAttribute && morphInfluences ) { + + _morphA.set( 0, 0, 0 ); + _morphB.set( 0, 0, 0 ); + _morphC.set( 0, 0, 0 ); + + for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) { + + const influence = morphInfluences[ i ]; + const morph = morphAttribute[ i ]; + + if ( influence === 0 ) continue; + + _tempA.fromBufferAttribute( morph, a ); + _tempB.fromBufferAttribute( morph, b ); + _tempC.fromBufferAttribute( morph, c ); + + if ( morphTargetsRelative ) { + + _morphA.addScaledVector( _tempA, influence ); + _morphB.addScaledVector( _tempB, influence ); + _morphC.addScaledVector( _tempC, influence ); + + } else { + + _morphA.addScaledVector( _tempA.sub( _vA ), influence ); + _morphB.addScaledVector( _tempB.sub( _vB ), influence ); + _morphC.addScaledVector( _tempC.sub( _vC ), influence ); + + } + + } + + _vA.add( _morphA ); + _vB.add( _morphB ); + _vC.add( _morphC ); + + } + + if ( object.isSkinnedMesh ) { + + object.applyBoneTransform( a, _vA ); + object.applyBoneTransform( b, _vB ); + object.applyBoneTransform( c, _vC ); + + } + + modifiedAttributeArray[ a * 3 + 0 ] = _vA.x; + modifiedAttributeArray[ a * 3 + 1 ] = _vA.y; + modifiedAttributeArray[ a * 3 + 2 ] = _vA.z; + modifiedAttributeArray[ b * 3 + 0 ] = _vB.x; + modifiedAttributeArray[ b * 3 + 1 ] = _vB.y; + modifiedAttributeArray[ b * 3 + 2 ] = _vB.z; + modifiedAttributeArray[ c * 3 + 0 ] = _vC.x; + modifiedAttributeArray[ c * 3 + 1 ] = _vC.y; + modifiedAttributeArray[ c * 3 + 2 ] = _vC.z; + + } + + const geometry = object.geometry; + const material = object.material; + + let a, b, c; + const index = geometry.index; + const positionAttribute = geometry.attributes.position; + const morphPosition = geometry.morphAttributes.position; + const morphTargetsRelative = geometry.morphTargetsRelative; + const normalAttribute = geometry.attributes.normal; + const morphNormal = geometry.morphAttributes.position; + + const groups = geometry.groups; + const drawRange = geometry.drawRange; + let i, j, il, jl; + let group; + let start, end; + + const modifiedPosition = new Float32Array( positionAttribute.count * positionAttribute.itemSize ); + const modifiedNormal = new Float32Array( normalAttribute.count * normalAttribute.itemSize ); + + if ( index !== null ) { + + // indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( i = 0, il = groups.length; i < il; i ++ ) { + + group = groups[ i ]; + + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + + for ( j = start, jl = end; j < jl; j += 3 ) { + + a = index.getX( j ); + b = index.getX( j + 1 ); + c = index.getX( j + 2 ); + + _calculateMorphedAttributeData( + object, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + start = Math.max( 0, drawRange.start ); + end = Math.min( index.count, ( drawRange.start + drawRange.count ) ); + + for ( i = start, il = end; i < il; i += 3 ) { + + a = index.getX( i ); + b = index.getX( i + 1 ); + c = index.getX( i + 2 ); + + _calculateMorphedAttributeData( + object, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + // non-indexed buffer geometry + + if ( Array.isArray( material ) ) { + + for ( i = 0, il = groups.length; i < il; i ++ ) { + + group = groups[ i ]; + + start = Math.max( group.start, drawRange.start ); + end = Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ); + + for ( j = start, jl = end; j < jl; j += 3 ) { + + a = j; + b = j + 1; + c = j + 2; + + _calculateMorphedAttributeData( + object, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } else { + + start = Math.max( 0, drawRange.start ); + end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) ); + + for ( i = start, il = end; i < il; i += 3 ) { + + a = i; + b = i + 1; + c = i + 2; + + _calculateMorphedAttributeData( + object, + positionAttribute, + morphPosition, + morphTargetsRelative, + a, b, c, + modifiedPosition + ); + + _calculateMorphedAttributeData( + object, + normalAttribute, + morphNormal, + morphTargetsRelative, + a, b, c, + modifiedNormal + ); + + } + + } + + } + + const morphedPositionAttribute = new Float32BufferAttribute( modifiedPosition, 3 ); + const morphedNormalAttribute = new Float32BufferAttribute( modifiedNormal, 3 ); + + return { + + positionAttribute: positionAttribute, + normalAttribute: normalAttribute, + morphedPositionAttribute: morphedPositionAttribute, + morphedNormalAttribute: morphedNormalAttribute + + }; + +} + +function mergeGroups( geometry ) { + + if ( geometry.groups.length === 0 ) { + + console.warn( 'THREE.BufferGeometryUtils.mergeGroups(): No groups are defined. Nothing to merge.' ); + return geometry; + + } + + let groups = geometry.groups; + + // sort groups by material index + + groups = groups.sort( ( a, b ) => { + + if ( a.materialIndex !== b.materialIndex ) return a.materialIndex - b.materialIndex; + + return a.start - b.start; + + } ); + + // create index for non-indexed geometries + + if ( geometry.getIndex() === null ) { + + const positionAttribute = geometry.getAttribute( 'position' ); + const indices = []; + + for ( let i = 0; i < positionAttribute.count; i += 3 ) { + + indices.push( i, i + 1, i + 2 ); + + } + + geometry.setIndex( indices ); + + } + + // sort index + + const index = geometry.getIndex(); + + const newIndices = []; + + for ( let i = 0; i < groups.length; i ++ ) { + + const group = groups[ i ]; + + const groupStart = group.start; + const groupLength = groupStart + group.count; + + for ( let j = groupStart; j < groupLength; j ++ ) { + + newIndices.push( index.getX( j ) ); + + } + + } + + geometry.dispose(); // Required to force buffer recreation + geometry.setIndex( newIndices ); + + // update groups indices + + let start = 0; + + for ( let i = 0; i < groups.length; i ++ ) { + + const group = groups[ i ]; + + group.start = start; + start += group.count; + + } + + // merge groups + + let currentGroup = groups[ 0 ]; + + geometry.groups = [ currentGroup ]; + + for ( let i = 1; i < groups.length; i ++ ) { + + const group = groups[ i ]; + + if ( currentGroup.materialIndex === group.materialIndex ) { + + currentGroup.count += group.count; + + } else { + + currentGroup = group; + geometry.groups.push( currentGroup ); + + } + + } + + return geometry; + +} + + +/** + * Modifies the supplied geometry if it is non-indexed, otherwise creates a new, + * non-indexed geometry. Returns the geometry with smooth normals everywhere except + * faces that meet at an angle greater than the crease angle. + * + * @param {BufferGeometry} geometry + * @param {number} [creaseAngle] + * @return {BufferGeometry} + */ +function toCreasedNormals( geometry, creaseAngle = Math.PI / 3 /* 60 degrees */ ) { + + const creaseDot = Math.cos( creaseAngle ); + const hashMultiplier = ( 1 + 1e-10 ) * 1e2; + + // reusable vectors + const verts = [ new Vector3(), new Vector3(), new Vector3() ]; + const tempVec1 = new Vector3(); + const tempVec2 = new Vector3(); + const tempNorm = new Vector3(); + const tempNorm2 = new Vector3(); + + // hashes a vector + function hashVertex( v ) { + + const x = ~ ~ ( v.x * hashMultiplier ); + const y = ~ ~ ( v.y * hashMultiplier ); + const z = ~ ~ ( v.z * hashMultiplier ); + return `${x},${y},${z}`; + + } + + // BufferGeometry.toNonIndexed() warns if the geometry is non-indexed + // and returns the original geometry + const resultGeometry = geometry.index ? geometry.toNonIndexed() : geometry; + const posAttr = resultGeometry.attributes.position; + const vertexMap = {}; + + // find all the normals shared by commonly located vertices + for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) { + + const i3 = 3 * i; + const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 ); + const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 ); + const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 ); + + tempVec1.subVectors( c, b ); + tempVec2.subVectors( a, b ); + + // add the normal to the map for all vertices + const normal = new Vector3().crossVectors( tempVec1, tempVec2 ).normalize(); + for ( let n = 0; n < 3; n ++ ) { + + const vert = verts[ n ]; + const hash = hashVertex( vert ); + if ( ! ( hash in vertexMap ) ) { + + vertexMap[ hash ] = []; + + } + + vertexMap[ hash ].push( normal ); + + } + + } + + // average normals from all vertices that share a common location if they are within the + // provided crease threshold + const normalArray = new Float32Array( posAttr.count * 3 ); + const normAttr = new BufferAttribute( normalArray, 3, false ); + for ( let i = 0, l = posAttr.count / 3; i < l; i ++ ) { + + // get the face normal for this vertex + const i3 = 3 * i; + const a = verts[ 0 ].fromBufferAttribute( posAttr, i3 + 0 ); + const b = verts[ 1 ].fromBufferAttribute( posAttr, i3 + 1 ); + const c = verts[ 2 ].fromBufferAttribute( posAttr, i3 + 2 ); + + tempVec1.subVectors( c, b ); + tempVec2.subVectors( a, b ); + + tempNorm.crossVectors( tempVec1, tempVec2 ).normalize(); + + // average all normals that meet the threshold and set the normal value + for ( let n = 0; n < 3; n ++ ) { + + const vert = verts[ n ]; + const hash = hashVertex( vert ); + const otherNormals = vertexMap[ hash ]; + tempNorm2.set( 0, 0, 0 ); + + for ( let k = 0, lk = otherNormals.length; k < lk; k ++ ) { + + const otherNorm = otherNormals[ k ]; + if ( tempNorm.dot( otherNorm ) > creaseDot ) { + + tempNorm2.add( otherNorm ); + + } + + } + + tempNorm2.normalize(); + normAttr.setXYZ( i3 + n, tempNorm2.x, tempNorm2.y, tempNorm2.z ); + + } + + } + + resultGeometry.setAttribute( 'normal', normAttr ); + return resultGeometry; + +} + +export { + computeMikkTSpaceTangents, + mergeGeometries, + mergeAttributes, + interleaveAttributes, + estimateBytesUsed, + mergeVertices, + toTrianglesDrawMode, + computeMorphedAttributes, + mergeGroups, + toCreasedNormals +}; diff --git a/ui/viewer/vendor/three/three.module.min.js b/ui/viewer/vendor/three/three.module.min.js new file mode 100644 index 0000000..424ef1c --- /dev/null +++ b/ui/viewer/vendor/three/three.module.min.js @@ -0,0 +1,6 @@ +/** + * @license + * Copyright 2010-2024 Three.js Authors + * SPDX-License-Identifier: MIT + */ +const t="169",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},n={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,s=2,a=3,o=0,l=1,c=2,h=3,u=0,d=1,p=2,m=0,f=1,g=2,v=3,_=4,x=5,y=100,M=101,S=102,b=103,w=104,T=200,E=201,A=202,R=203,C=204,P=205,I=206,L=207,U=208,N=209,D=210,O=211,F=212,B=213,z=214,k=0,V=1,H=2,G=3,W=4,X=5,j=6,q=7,Y=0,Z=1,J=2,K=0,$=1,Q=2,tt=3,et=4,nt=5,it=6,rt=7,st="attached",at="detached",ot=300,lt=301,ct=302,ht=303,ut=304,dt=306,pt=1e3,mt=1001,ft=1002,gt=1003,vt=1004,_t=1004,xt=1005,yt=1005,Mt=1006,St=1007,bt=1007,wt=1008,Tt=1008,Et=1009,At=1010,Rt=1011,Ct=1012,Pt=1013,It=1014,Lt=1015,Ut=1016,Nt=1017,Dt=1018,Ot=1020,Ft=35902,Bt=1021,zt=1022,kt=1023,Vt=1024,Ht=1025,Gt=1026,Wt=1027,Xt=1028,jt=1029,qt=1030,Yt=1031,Zt=1032,Jt=1033,Kt=33776,$t=33777,Qt=33778,te=33779,ee=35840,ne=35841,ie=35842,re=35843,se=36196,ae=37492,oe=37496,le=37808,ce=37809,he=37810,ue=37811,de=37812,pe=37813,me=37814,fe=37815,ge=37816,ve=37817,_e=37818,xe=37819,ye=37820,Me=37821,Se=36492,be=36494,we=36495,Te=36283,Ee=36284,Ae=36285,Re=36286,Ce=2200,Pe=2201,Ie=2202,Le=2300,Ue=2301,Ne=2302,De=2400,Oe=2401,Fe=2402,Be=2500,ze=2501,ke=0,Ve=1,He=2,Ge=3200,We=3201,Xe=3202,je=3203,qe=0,Ye=1,Ze="",Je="srgb",Ke="srgb-linear",$e="display-p3",Qe="display-p3-linear",tn="linear",en="srgb",nn="rec709",rn="p3",sn=0,an=7680,on=7681,ln=7682,cn=7683,hn=34055,un=34056,dn=5386,pn=512,mn=513,fn=514,gn=515,vn=516,_n=517,xn=518,yn=519,Mn=512,Sn=513,bn=514,wn=515,Tn=516,En=517,An=518,Rn=519,Cn=35044,Pn=35048,In=35040,Ln=35045,Un=35049,Nn=35041,Dn=35046,On=35050,Fn=35042,Bn="100",zn="300 es",kn=2e3,Vn=2001;class Hn{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e>8&255]+Gn[t>>16&255]+Gn[t>>24&255]+"-"+Gn[255&e]+Gn[e>>8&255]+"-"+Gn[e>>16&15|64]+Gn[e>>24&255]+"-"+Gn[63&n|128]+Gn[n>>8&255]+"-"+Gn[n>>16&255]+Gn[n>>24&255]+Gn[255&i]+Gn[i>>8&255]+Gn[i>>16&255]+Gn[i>>24&255]).toLowerCase()}function Yn(t,e,n){return Math.max(e,Math.min(n,t))}function Zn(t,e){return(t%e+e)%e}function Jn(t,e,n){return(1-n)*t+n*e}function Kn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function $n(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Qn={DEG2RAD:Xn,RAD2DEG:jn,generateUUID:qn,clamp:Yn,euclideanModulo:Zn,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:Jn,damp:function(t,e,n,i){return Jn(t,e,1-Math.exp(-n*i))},pingpong:function(t,e=1){return e-Math.abs(Zn(t,2*e)-e)},smoothstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*(3-2*t)},smootherstep:function(t,e,n){return t<=e?0:t>=n?1:(t=(t-e)/(n-e))*t*t*(t*(6*t-15)+10)},randInt:function(t,e){return t+Math.floor(Math.random()*(e-t+1))},randFloat:function(t,e){return t+Math.random()*(e-t)},randFloatSpread:function(t){return t*(.5-Math.random())},seededRandom:function(t){void 0!==t&&(Wn=t);let e=Wn+=1831565813;return e=Math.imul(e^e>>>15,1|e),e^=e+Math.imul(e^e>>>7,61|e),((e^e>>>14)>>>0)/4294967296},degToRad:function(t){return t*Xn},radToDeg:function(t){return t*jn},isPowerOfTwo:function(t){return 0==(t&t-1)&&0!==t},ceilPowerOfTwo:function(t){return Math.pow(2,Math.ceil(Math.log(t)/Math.LN2))},floorPowerOfTwo:function(t){return Math.pow(2,Math.floor(Math.log(t)/Math.LN2))},setQuaternionFromProperEuler:function(t,e,n,i,r){const s=Math.cos,a=Math.sin,o=s(n/2),l=a(n/2),c=s((e+i)/2),h=a((e+i)/2),u=s((e-i)/2),d=a((e-i)/2),p=s((i-e)/2),m=a((i-e)/2);switch(r){case"XYX":t.set(o*h,l*u,l*d,o*c);break;case"YZY":t.set(l*d,o*h,l*u,o*c);break;case"ZXZ":t.set(l*u,l*d,o*h,o*c);break;case"XZX":t.set(o*h,l*m,l*p,o*c);break;case"YXY":t.set(l*p,o*h,l*m,o*c);break;case"ZYZ":t.set(l*m,l*p,o*h,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:$n,denormalize:Kn};class ti{constructor(t=0,e=0){ti.prototype.isVector2=!0,this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,n=this.y,i=t.elements;return this.x=i[0]*e+i[3]*n+i[6],this.y=i[1]*e+i[4]*n+i[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Yn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y;return e*e+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const n=Math.cos(e),i=Math.sin(e),r=this.x-t.x,s=this.y-t.y;return this.x=r*n-s*i+t.x,this.y=r*i+s*n+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ei{constructor(t,e,n,i,r,s,a,o,l){ei.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l)}set(t,e,n,i,r,s,a,o,l){const c=this.elements;return c[0]=t,c[1]=i,c[2]=a,c[3]=e,c[4]=r,c[5]=o,c[6]=n,c[7]=s,c[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],this}extractBasis(t,e,n){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[3],o=n[6],l=n[1],c=n[4],h=n[7],u=n[2],d=n[5],p=n[8],m=i[0],f=i[3],g=i[6],v=i[1],_=i[4],x=i[7],y=i[2],M=i[5],S=i[8];return r[0]=s*m+a*v+o*y,r[3]=s*f+a*_+o*M,r[6]=s*g+a*x+o*S,r[1]=l*m+c*v+h*y,r[4]=l*f+c*_+h*M,r[7]=l*g+c*x+h*S,r[2]=u*m+d*v+p*y,r[5]=u*f+d*_+p*M,r[8]=u*g+d*x+p*S,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8];return e*s*c-e*a*l-n*r*c+n*a*o+i*r*l-i*s*o}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=c*s-a*l,u=a*o-c*r,d=l*r-s*o,p=e*h+n*u+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return t[0]=h*m,t[1]=(i*l-c*n)*m,t[2]=(a*n-i*s)*m,t[3]=u*m,t[4]=(c*e-i*o)*m,t[5]=(i*r-a*e)*m,t[6]=d*m,t[7]=(n*o-l*e)*m,t[8]=(s*e-n*r)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,n,i,r,s,a){const o=Math.cos(r),l=Math.sin(r);return this.set(n*o,n*l,-n*(o*s+l*a)+s+t,-i*l,i*o,-i*(-l*s+o*a)+a+e,0,0,1),this}scale(t,e){return this.premultiply(ni.makeScale(t,e)),this}rotate(t){return this.premultiply(ni.makeRotation(-t)),this}translate(t,e){return this.premultiply(ni.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,n,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<9;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<9;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t}clone(){return(new this.constructor).fromArray(this.elements)}}const ni=new ei;function ii(t){for(let e=t.length-1;e>=0;--e)if(t[e]>=65535)return!0;return!1}const ri={Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function si(t,e){return new ri[t](e)}function ai(t){return document.createElementNS("http://www.w3.org/1999/xhtml",t)}function oi(){const t=ai("canvas");return t.style.display="block",t}const li={};function ci(t){t in li||(li[t]=!0,console.warn(t))}const hi=(new ei).set(.8224621,.177538,0,.0331941,.9668058,0,.0170827,.0723974,.9105199),ui=(new ei).set(1.2249401,-.2249404,0,-.0420569,1.0420571,0,-.0196376,-.0786361,1.0982735),di={[Ke]:{transfer:tn,primaries:nn,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t,fromReference:t=>t},[Je]:{transfer:en,primaries:nn,luminanceCoefficients:[.2126,.7152,.0722],toReference:t=>t.convertSRGBToLinear(),fromReference:t=>t.convertLinearToSRGB()},[Qe]:{transfer:tn,primaries:rn,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.applyMatrix3(ui),fromReference:t=>t.applyMatrix3(hi)},[$e]:{transfer:en,primaries:rn,luminanceCoefficients:[.2289,.6917,.0793],toReference:t=>t.convertSRGBToLinear().applyMatrix3(ui),fromReference:t=>t.applyMatrix3(hi).convertLinearToSRGB()}},pi=new Set([Ke,Qe]),mi={enabled:!0,_workingColorSpace:Ke,get workingColorSpace(){return this._workingColorSpace},set workingColorSpace(t){if(!pi.has(t))throw new Error(`Unsupported working color space, "${t}".`);this._workingColorSpace=t},convert:function(t,e,n){if(!1===this.enabled||e===n||!e||!n)return t;const i=di[e].toReference;return(0,di[n].fromReference)(i(t))},fromWorkingColorSpace:function(t,e){return this.convert(t,this._workingColorSpace,e)},toWorkingColorSpace:function(t,e){return this.convert(t,e,this._workingColorSpace)},getPrimaries:function(t){return di[t].primaries},getTransfer:function(t){return t===Ze?tn:di[t].transfer},getLuminanceCoefficients:function(t,e=this._workingColorSpace){return t.fromArray(di[e].luminanceCoefficients)}};function fi(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function gi(t){return t<.0031308?12.92*t:1.055*Math.pow(t,.41666)-.055}let vi;class _i{static getDataURL(t){if(/^data:/i.test(t.src))return t.src;if("undefined"==typeof HTMLCanvasElement)return t.src;let e;if(t instanceof HTMLCanvasElement)e=t;else{void 0===vi&&(vi=ai("canvas")),vi.width=t.width,vi.height=t.height;const n=vi.getContext("2d");t instanceof ImageData?n.putImageData(t,0,0):n.drawImage(t,0,0,t.width,t.height),e=vi}return e.width>2048||e.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",t),e.toDataURL("image/jpeg",.6)):e.toDataURL("image/png")}static sRGBToLinear(t){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap){const e=ai("canvas");e.width=t.width,e.height=t.height;const n=e.getContext("2d");n.drawImage(t,0,0,t.width,t.height);const i=n.getImageData(0,0,t.width,t.height),r=i.data;for(let t=0;t0&&(n.userData=this.userData),e||(t.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==ot)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case pt:t.x=t.x-Math.floor(t.x);break;case mt:t.x=t.x<0?0:1;break;case ft:1===Math.abs(Math.floor(t.x)%2)?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x)}if(t.y<0||t.y>1)switch(this.wrapT){case pt:t.y=t.y-Math.floor(t.y);break;case mt:t.y=t.y<0?0:1;break;case ft:1===Math.abs(Math.floor(t.y)%2)?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y)}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){!0===t&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){!0===t&&this.pmremVersion++}}bi.DEFAULT_IMAGE=null,bi.DEFAULT_MAPPING=ot,bi.DEFAULT_ANISOTROPY=1;class wi{constructor(t=0,e=0,n=0,i=1){wi.prototype.isVector4=!0,this.x=t,this.y=e,this.z=n,this.w=i}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,n,i){return this.x=t,this.y=e,this.z=n,this.w=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=void 0!==t.w?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=this.w,s=t.elements;return this.x=s[0]*e+s[4]*n+s[8]*i+s[12]*r,this.y=s[1]*e+s[5]*n+s[9]*i+s[13]*r,this.z=s[2]*e+s[6]*n+s[10]*i+s[14]*r,this.w=s[3]*e+s[7]*n+s[11]*i+s[15]*r,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,n,i,r;const s=.01,a=.1,o=t.elements,l=o[0],c=o[4],h=o[8],u=o[1],d=o[5],p=o[9],m=o[2],f=o[6],g=o[10];if(Math.abs(c-u)o&&t>v?tv?o=0?1:-1,i=1-e*e;if(i>Number.EPSILON){const r=Math.sqrt(i),s=Math.atan2(r,e*n);t=Math.sin(t*s)/r,a=Math.sin(a*s)/r}const r=a*n;if(o=o*t+u*r,l=l*t+d*r,c=c*t+p*r,h=h*t+m*r,t===1-a){const t=1/Math.sqrt(o*o+l*l+c*c+h*h);o*=t,l*=t,c*=t,h*=t}}t[e]=o,t[e+1]=l,t[e+2]=c,t[e+3]=h}static multiplyQuaternionsFlat(t,e,n,i,r,s){const a=n[i],o=n[i+1],l=n[i+2],c=n[i+3],h=r[s],u=r[s+1],d=r[s+2],p=r[s+3];return t[e]=a*p+c*h+o*d-l*u,t[e+1]=o*p+c*u+l*h-a*d,t[e+2]=l*p+c*d+a*u-o*h,t[e+3]=c*p-a*h-o*u-l*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,n,i){return this._x=t,this._y=e,this._z=n,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const n=t._x,i=t._y,r=t._z,s=t._order,a=Math.cos,o=Math.sin,l=a(n/2),c=a(i/2),h=a(r/2),u=o(n/2),d=o(i/2),p=o(r/2);switch(s){case"XYZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"YXZ":this._x=u*c*h+l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"ZXY":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h-u*d*p;break;case"ZYX":this._x=u*c*h-l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h+u*d*p;break;case"YZX":this._x=u*c*h+l*d*p,this._y=l*d*h+u*c*p,this._z=l*c*p-u*d*h,this._w=l*c*h-u*d*p;break;case"XZY":this._x=u*c*h-l*d*p,this._y=l*d*h-u*c*p,this._z=l*c*p+u*d*h,this._w=l*c*h+u*d*p;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return!0===e&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const n=e/2,i=Math.sin(n);return this._x=t.x*i,this._y=t.y*i,this._z=t.z*i,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,n=e[0],i=e[4],r=e[8],s=e[1],a=e[5],o=e[9],l=e[2],c=e[6],h=e[10],u=n+a+h;if(u>0){const t=.5/Math.sqrt(u+1);this._w=.25/t,this._x=(c-o)*t,this._y=(r-l)*t,this._z=(s-i)*t}else if(n>a&&n>h){const t=2*Math.sqrt(1+n-a-h);this._w=(c-o)/t,this._x=.25*t,this._y=(i+s)/t,this._z=(r+l)/t}else if(a>h){const t=2*Math.sqrt(1+a-n-h);this._w=(r-l)/t,this._x=(i+s)/t,this._y=.25*t,this._z=(o+c)/t}else{const t=2*Math.sqrt(1+h-n-a);this._w=(s-i)/t,this._x=(r+l)/t,this._y=(o+c)/t,this._z=.25*t}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let n=t.dot(e)+1;return nMath.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=n):(this._x=0,this._y=-t.z,this._z=t.y,this._w=n)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=n),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(Yn(this.dot(t),-1,1)))}rotateTowards(t,e){const n=this.angleTo(t);if(0===n)return this;const i=Math.min(1,e/n);return this.slerp(t,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return 0===t?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const n=t._x,i=t._y,r=t._z,s=t._w,a=e._x,o=e._y,l=e._z,c=e._w;return this._x=n*c+s*a+i*l-r*o,this._y=i*c+s*o+r*a-n*l,this._z=r*c+s*l+n*o-i*a,this._w=s*c-n*a-i*o-r*l,this._onChangeCallback(),this}slerp(t,e){if(0===e)return this;if(1===e)return this.copy(t);const n=this._x,i=this._y,r=this._z,s=this._w;let a=s*t._w+n*t._x+i*t._y+r*t._z;if(a<0?(this._w=-t._w,this._x=-t._x,this._y=-t._y,this._z=-t._z,a=-a):this.copy(t),a>=1)return this._w=s,this._x=n,this._y=i,this._z=r,this;const o=1-a*a;if(o<=Number.EPSILON){const t=1-e;return this._w=t*s+e*this._w,this._x=t*n+e*this._x,this._y=t*i+e*this._y,this._z=t*r+e*this._z,this.normalize(),this}const l=Math.sqrt(o),c=Math.atan2(l,a),h=Math.sin((1-e)*c)/l,u=Math.sin(e*c)/l;return this._w=s*h+this._w*u,this._x=n*h+this._x*u,this._y=i*h+this._y*u,this._z=r*h+this._z*u,this._onChangeCallback(),this}slerpQuaternions(t,e,n){return this.copy(t).slerp(e,n)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),n=Math.random(),i=Math.sqrt(1-n),r=Math.sqrt(n);return this.set(i*Math.sin(t),i*Math.cos(t),r*Math.sin(e),r*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class Li{constructor(t=0,e=0,n=0){Li.prototype.isVector3=!0,this.x=t,this.y=e,this.z=n}set(t,e,n){return void 0===n&&(n=this.z),this.x=t,this.y=e,this.z=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(Ni.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(Ni.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[3]*n+r[6]*i,this.y=r[1]*e+r[4]*n+r[7]*i,this.z=r[2]*e+r[5]*n+r[8]*i,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,n=this.y,i=this.z,r=t.elements,s=1/(r[3]*e+r[7]*n+r[11]*i+r[15]);return this.x=(r[0]*e+r[4]*n+r[8]*i+r[12])*s,this.y=(r[1]*e+r[5]*n+r[9]*i+r[13])*s,this.z=(r[2]*e+r[6]*n+r[10]*i+r[14])*s,this}applyQuaternion(t){const e=this.x,n=this.y,i=this.z,r=t.x,s=t.y,a=t.z,o=t.w,l=2*(s*i-a*n),c=2*(a*e-r*i),h=2*(r*n-s*e);return this.x=e+o*l+s*h-a*c,this.y=n+o*c+a*l-r*h,this.z=i+o*h+r*c-s*l,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,n=this.y,i=this.z,r=t.elements;return this.x=r[0]*e+r[4]*n+r[8]*i,this.y=r[1]*e+r[5]*n+r[9]*i,this.z=r[2]*e+r[6]*n+r[10]*i,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=Math.max(t.x,Math.min(e.x,this.x)),this.y=Math.max(t.y,Math.min(e.y,this.y)),this.z=Math.max(t.z,Math.min(e.z,this.z)),this}clampScalar(t,e){return this.x=Math.max(t,Math.min(e,this.x)),this.y=Math.max(t,Math.min(e,this.y)),this.z=Math.max(t,Math.min(e,this.z)),this}clampLength(t,e){const n=this.length();return this.divideScalar(n||1).multiplyScalar(Math.max(t,Math.min(e,n)))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,n){return this.x=t.x+(e.x-t.x)*n,this.y=t.y+(e.y-t.y)*n,this.z=t.z+(e.z-t.z)*n,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const n=t.x,i=t.y,r=t.z,s=e.x,a=e.y,o=e.z;return this.x=i*o-r*a,this.y=r*s-n*o,this.z=n*a-i*s,this}projectOnVector(t){const e=t.lengthSq();if(0===e)return this.set(0,0,0);const n=t.dot(this)/e;return this.copy(t).multiplyScalar(n)}projectOnPlane(t){return Ui.copy(this).projectOnVector(t),this.sub(Ui)}reflect(t){return this.sub(Ui.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(0===e)return Math.PI/2;const n=this.dot(t)/e;return Math.acos(Yn(n,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,n=this.y-t.y,i=this.z-t.z;return e*e+n*n+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,n){const i=Math.sin(e)*t;return this.x=i*Math.sin(n),this.y=Math.cos(e)*t,this.z=i*Math.cos(n),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,n){return this.x=t*Math.sin(e),this.y=n,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),n=this.setFromMatrixColumn(t,1).length(),i=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=n,this.z=i,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,4*e)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,3*e)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=2*Math.random()-1,n=Math.sqrt(1-e*e);return this.x=n*Math.cos(t),this.y=e,this.z=n*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const Ui=new Li,Ni=new Ii;class Di{constructor(t=new Li(1/0,1/0,1/0),e=new Li(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,n=t.length;e=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,Fi),Fi.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,n;return t.normal.x>0?(e=t.normal.x*this.min.x,n=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,n=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,n+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,n+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,n+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,n+=t.normal.z*this.min.z),e<=-t.constant&&n>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(Xi),ji.subVectors(this.max,Xi),zi.subVectors(t.a,Xi),ki.subVectors(t.b,Xi),Vi.subVectors(t.c,Xi),Hi.subVectors(ki,zi),Gi.subVectors(Vi,ki),Wi.subVectors(zi,Vi);let e=[0,-Hi.z,Hi.y,0,-Gi.z,Gi.y,0,-Wi.z,Wi.y,Hi.z,0,-Hi.x,Gi.z,0,-Gi.x,Wi.z,0,-Wi.x,-Hi.y,Hi.x,0,-Gi.y,Gi.x,0,-Wi.y,Wi.x,0];return!!Zi(e,zi,ki,Vi,ji)&&(e=[1,0,0,0,1,0,0,0,1],!!Zi(e,zi,ki,Vi,ji)&&(qi.crossVectors(Hi,Gi),e=[qi.x,qi.y,qi.z],Zi(e,zi,ki,Vi,ji)))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,Fi).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=.5*this.getSize(Fi).length()),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()||(Oi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),Oi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),Oi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),Oi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),Oi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),Oi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),Oi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),Oi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(Oi)),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Oi=[new Li,new Li,new Li,new Li,new Li,new Li,new Li,new Li],Fi=new Li,Bi=new Di,zi=new Li,ki=new Li,Vi=new Li,Hi=new Li,Gi=new Li,Wi=new Li,Xi=new Li,ji=new Li,qi=new Li,Yi=new Li;function Zi(t,e,n,i,r){for(let s=0,a=t.length-3;s<=a;s+=3){Yi.fromArray(t,s);const a=r.x*Math.abs(Yi.x)+r.y*Math.abs(Yi.y)+r.z*Math.abs(Yi.z),o=e.dot(Yi),l=n.dot(Yi),c=i.dot(Yi);if(Math.max(-Math.max(o,l,c),Math.min(o,l,c))>a)return!1}return!0}const Ji=new Di,Ki=new Li,$i=new Li;class Qi{constructor(t=new Li,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const n=this.center;void 0!==e?n.copy(e):Ji.setFromPoints(t).getCenter(n);let i=0;for(let e=0,r=t.length;ethis.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;Ki.subVectors(t,this.center);const e=Ki.lengthSq();if(e>this.radius*this.radius){const t=Math.sqrt(e),n=.5*(t-this.radius);this.center.addScaledVector(Ki,n/t),this.radius+=n}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(!0===this.center.equals(t.center)?this.radius=Math.max(this.radius,t.radius):($i.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(Ki.copy(t.center).add($i)),this.expandByPoint(Ki.copy(t.center).sub($i))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return(new this.constructor).copy(this)}}const tr=new Li,er=new Li,nr=new Li,ir=new Li,rr=new Li,sr=new Li,ar=new Li;class or{constructor(t=new Li,e=new Li(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,tr)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const n=e.dot(this.direction);return n<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,n)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=tr.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(tr.copy(this.origin).addScaledVector(this.direction,e),tr.distanceToSquared(t))}distanceSqToSegment(t,e,n,i){er.copy(t).add(e).multiplyScalar(.5),nr.copy(e).sub(t).normalize(),ir.copy(this.origin).sub(er);const r=.5*t.distanceTo(e),s=-this.direction.dot(nr),a=ir.dot(this.direction),o=-ir.dot(nr),l=ir.lengthSq(),c=Math.abs(1-s*s);let h,u,d,p;if(c>0)if(h=s*o-a,u=s*a-o,p=r*c,h>=0)if(u>=-p)if(u<=p){const t=1/c;h*=t,u*=t,d=h*(h+s*u+2*a)+u*(s*h+u+2*o)+l}else u=r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u=-r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;else u<=-p?(h=Math.max(0,-(-s*r+a)),u=h>0?-r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l):u<=p?(h=0,u=Math.min(Math.max(-r,-o),r),d=u*(u+2*o)+l):(h=Math.max(0,-(s*r+a)),u=h>0?r:Math.min(Math.max(-r,-o),r),d=-h*h+u*(u+2*o)+l);else u=s>0?-r:r,h=Math.max(0,-(s*u+a)),d=-h*h+u*(u+2*o)+l;return n&&n.copy(this.origin).addScaledVector(this.direction,h),i&&i.copy(er).addScaledVector(nr,u),d}intersectSphere(t,e){tr.subVectors(t.center,this.origin);const n=tr.dot(this.direction),i=tr.dot(tr)-n*n,r=t.radius*t.radius;if(i>r)return null;const s=Math.sqrt(r-i),a=n-s,o=n+s;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(0===e)return 0===t.distanceToPoint(this.origin)?0:null;const n=-(this.origin.dot(t.normal)+t.constant)/e;return n>=0?n:null}intersectPlane(t,e){const n=this.distanceToPlane(t);return null===n?null:this.at(n,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);if(0===e)return!0;return t.normal.dot(this.direction)*e<0}intersectBox(t,e){let n,i,r,s,a,o;const l=1/this.direction.x,c=1/this.direction.y,h=1/this.direction.z,u=this.origin;return l>=0?(n=(t.min.x-u.x)*l,i=(t.max.x-u.x)*l):(n=(t.max.x-u.x)*l,i=(t.min.x-u.x)*l),c>=0?(r=(t.min.y-u.y)*c,s=(t.max.y-u.y)*c):(r=(t.max.y-u.y)*c,s=(t.min.y-u.y)*c),n>s||r>i?null:((r>n||isNaN(n))&&(n=r),(s=0?(a=(t.min.z-u.z)*h,o=(t.max.z-u.z)*h):(a=(t.max.z-u.z)*h,o=(t.min.z-u.z)*h),n>o||a>i?null:((a>n||n!=n)&&(n=a),(o=0?n:i,e)))}intersectsBox(t){return null!==this.intersectBox(t,tr)}intersectTriangle(t,e,n,i,r){rr.subVectors(e,t),sr.subVectors(n,t),ar.crossVectors(rr,sr);let s,a=this.direction.dot(ar);if(a>0){if(i)return null;s=1}else{if(!(a<0))return null;s=-1,a=-a}ir.subVectors(this.origin,t);const o=s*this.direction.dot(sr.crossVectors(ir,sr));if(o<0)return null;const l=s*this.direction.dot(rr.cross(ir));if(l<0)return null;if(o+l>a)return null;const c=-s*ir.dot(ar);return c<0?null:this.at(c/a,r)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class lr{constructor(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){lr.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==t&&this.set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f)}set(t,e,n,i,r,s,a,o,l,c,h,u,d,p,m,f){const g=this.elements;return g[0]=t,g[4]=e,g[8]=n,g[12]=i,g[1]=r,g[5]=s,g[9]=a,g[13]=o,g[2]=l,g[6]=c,g[10]=h,g[14]=u,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new lr).fromArray(this.elements)}copy(t){const e=this.elements,n=t.elements;return e[0]=n[0],e[1]=n[1],e[2]=n[2],e[3]=n[3],e[4]=n[4],e[5]=n[5],e[6]=n[6],e[7]=n[7],e[8]=n[8],e[9]=n[9],e[10]=n[10],e[11]=n[11],e[12]=n[12],e[13]=n[13],e[14]=n[14],e[15]=n[15],this}copyPosition(t){const e=this.elements,n=t.elements;return e[12]=n[12],e[13]=n[13],e[14]=n[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,n){return t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),n.setFromMatrixColumn(this,2),this}makeBasis(t,e,n){return this.set(t.x,e.x,n.x,0,t.y,e.y,n.y,0,t.z,e.z,n.z,0,0,0,0,1),this}extractRotation(t){const e=this.elements,n=t.elements,i=1/cr.setFromMatrixColumn(t,0).length(),r=1/cr.setFromMatrixColumn(t,1).length(),s=1/cr.setFromMatrixColumn(t,2).length();return e[0]=n[0]*i,e[1]=n[1]*i,e[2]=n[2]*i,e[3]=0,e[4]=n[4]*r,e[5]=n[5]*r,e[6]=n[6]*r,e[7]=0,e[8]=n[8]*s,e[9]=n[9]*s,e[10]=n[10]*s,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,n=t.x,i=t.y,r=t.z,s=Math.cos(n),a=Math.sin(n),o=Math.cos(i),l=Math.sin(i),c=Math.cos(r),h=Math.sin(r);if("XYZ"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=-o*h,e[8]=l,e[1]=n+i*l,e[5]=t-r*l,e[9]=-a*o,e[2]=r-t*l,e[6]=i+n*l,e[10]=s*o}else if("YXZ"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t+r*a,e[4]=i*a-n,e[8]=s*l,e[1]=s*h,e[5]=s*c,e[9]=-a,e[2]=n*a-i,e[6]=r+t*a,e[10]=s*o}else if("ZXY"===t.order){const t=o*c,n=o*h,i=l*c,r=l*h;e[0]=t-r*a,e[4]=-s*h,e[8]=i+n*a,e[1]=n+i*a,e[5]=s*c,e[9]=r-t*a,e[2]=-s*l,e[6]=a,e[10]=s*o}else if("ZYX"===t.order){const t=s*c,n=s*h,i=a*c,r=a*h;e[0]=o*c,e[4]=i*l-n,e[8]=t*l+r,e[1]=o*h,e[5]=r*l+t,e[9]=n*l-i,e[2]=-l,e[6]=a*o,e[10]=s*o}else if("YZX"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=r-t*h,e[8]=i*h+n,e[1]=h,e[5]=s*c,e[9]=-a*c,e[2]=-l*c,e[6]=n*h+i,e[10]=t-r*h}else if("XZY"===t.order){const t=s*o,n=s*l,i=a*o,r=a*l;e[0]=o*c,e[4]=-h,e[8]=l*c,e[1]=t*h+r,e[5]=s*c,e[9]=n*h-i,e[2]=i*h-n,e[6]=a*c,e[10]=r*h+t}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(ur,t,dr)}lookAt(t,e,n){const i=this.elements;return fr.subVectors(t,e),0===fr.lengthSq()&&(fr.z=1),fr.normalize(),pr.crossVectors(n,fr),0===pr.lengthSq()&&(1===Math.abs(n.z)?fr.x+=1e-4:fr.z+=1e-4,fr.normalize(),pr.crossVectors(n,fr)),pr.normalize(),mr.crossVectors(fr,pr),i[0]=pr.x,i[4]=mr.x,i[8]=fr.x,i[1]=pr.y,i[5]=mr.y,i[9]=fr.y,i[2]=pr.z,i[6]=mr.z,i[10]=fr.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const n=t.elements,i=e.elements,r=this.elements,s=n[0],a=n[4],o=n[8],l=n[12],c=n[1],h=n[5],u=n[9],d=n[13],p=n[2],m=n[6],f=n[10],g=n[14],v=n[3],_=n[7],x=n[11],y=n[15],M=i[0],S=i[4],b=i[8],w=i[12],T=i[1],E=i[5],A=i[9],R=i[13],C=i[2],P=i[6],I=i[10],L=i[14],U=i[3],N=i[7],D=i[11],O=i[15];return r[0]=s*M+a*T+o*C+l*U,r[4]=s*S+a*E+o*P+l*N,r[8]=s*b+a*A+o*I+l*D,r[12]=s*w+a*R+o*L+l*O,r[1]=c*M+h*T+u*C+d*U,r[5]=c*S+h*E+u*P+d*N,r[9]=c*b+h*A+u*I+d*D,r[13]=c*w+h*R+u*L+d*O,r[2]=p*M+m*T+f*C+g*U,r[6]=p*S+m*E+f*P+g*N,r[10]=p*b+m*A+f*I+g*D,r[14]=p*w+m*R+f*L+g*O,r[3]=v*M+_*T+x*C+y*U,r[7]=v*S+_*E+x*P+y*N,r[11]=v*b+_*A+x*I+y*D,r[15]=v*w+_*R+x*L+y*O,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],n=t[4],i=t[8],r=t[12],s=t[1],a=t[5],o=t[9],l=t[13],c=t[2],h=t[6],u=t[10],d=t[14];return t[3]*(+r*o*h-i*l*h-r*a*u+n*l*u+i*a*d-n*o*d)+t[7]*(+e*o*d-e*l*u+r*s*u-i*s*d+i*l*c-r*o*c)+t[11]*(+e*l*h-e*a*d-r*s*h+n*s*d+r*a*c-n*l*c)+t[15]*(-i*a*c-e*o*h+e*a*u+i*s*h-n*s*u+n*o*c)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,n){const i=this.elements;return t.isVector3?(i[12]=t.x,i[13]=t.y,i[14]=t.z):(i[12]=t,i[13]=e,i[14]=n),this}invert(){const t=this.elements,e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],l=t[7],c=t[8],h=t[9],u=t[10],d=t[11],p=t[12],m=t[13],f=t[14],g=t[15],v=h*f*l-m*u*l+m*o*d-a*f*d-h*o*g+a*u*g,_=p*u*l-c*f*l-p*o*d+s*f*d+c*o*g-s*u*g,x=c*m*l-p*h*l+p*a*d-s*m*d-c*a*g+s*h*g,y=p*h*o-c*m*o-p*a*u+s*m*u+c*a*f-s*h*f,M=e*v+n*_+i*x+r*y;if(0===M)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const S=1/M;return t[0]=v*S,t[1]=(m*u*r-h*f*r-m*i*d+n*f*d+h*i*g-n*u*g)*S,t[2]=(a*f*r-m*o*r+m*i*l-n*f*l-a*i*g+n*o*g)*S,t[3]=(h*o*r-a*u*r-h*i*l+n*u*l+a*i*d-n*o*d)*S,t[4]=_*S,t[5]=(c*f*r-p*u*r+p*i*d-e*f*d-c*i*g+e*u*g)*S,t[6]=(p*o*r-s*f*r-p*i*l+e*f*l+s*i*g-e*o*g)*S,t[7]=(s*u*r-c*o*r+c*i*l-e*u*l-s*i*d+e*o*d)*S,t[8]=x*S,t[9]=(p*h*r-c*m*r-p*n*d+e*m*d+c*n*g-e*h*g)*S,t[10]=(s*m*r-p*a*r+p*n*l-e*m*l-s*n*g+e*a*g)*S,t[11]=(c*a*r-s*h*r-c*n*l+e*h*l+s*n*d-e*a*d)*S,t[12]=y*S,t[13]=(c*m*i-p*h*i+p*n*u-e*m*u-c*n*f+e*h*f)*S,t[14]=(p*a*i-s*m*i-p*n*o+e*m*o+s*n*f-e*a*f)*S,t[15]=(s*h*i-c*a*i+c*n*o-e*h*o-s*n*u+e*a*u)*S,this}scale(t){const e=this.elements,n=t.x,i=t.y,r=t.z;return e[0]*=n,e[4]*=i,e[8]*=r,e[1]*=n,e[5]*=i,e[9]*=r,e[2]*=n,e[6]*=i,e[10]*=r,e[3]*=n,e[7]*=i,e[11]*=r,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],n=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],i=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,n,i))}makeTranslation(t,e,n){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,n,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),n=Math.sin(t);return this.set(1,0,0,0,0,e,-n,0,0,n,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,0,n,0,0,1,0,0,-n,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),n=Math.sin(t);return this.set(e,-n,0,0,n,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const n=Math.cos(e),i=Math.sin(e),r=1-n,s=t.x,a=t.y,o=t.z,l=r*s,c=r*a;return this.set(l*s+n,l*a-i*o,l*o+i*a,0,l*a+i*o,c*a+n,c*o-i*s,0,l*o-i*a,c*o+i*s,r*o*o+n,0,0,0,0,1),this}makeScale(t,e,n){return this.set(t,0,0,0,0,e,0,0,0,0,n,0,0,0,0,1),this}makeShear(t,e,n,i,r,s){return this.set(1,n,r,0,t,1,s,0,e,i,1,0,0,0,0,1),this}compose(t,e,n){const i=this.elements,r=e._x,s=e._y,a=e._z,o=e._w,l=r+r,c=s+s,h=a+a,u=r*l,d=r*c,p=r*h,m=s*c,f=s*h,g=a*h,v=o*l,_=o*c,x=o*h,y=n.x,M=n.y,S=n.z;return i[0]=(1-(m+g))*y,i[1]=(d+x)*y,i[2]=(p-_)*y,i[3]=0,i[4]=(d-x)*M,i[5]=(1-(u+g))*M,i[6]=(f+v)*M,i[7]=0,i[8]=(p+_)*S,i[9]=(f-v)*S,i[10]=(1-(u+m))*S,i[11]=0,i[12]=t.x,i[13]=t.y,i[14]=t.z,i[15]=1,this}decompose(t,e,n){const i=this.elements;let r=cr.set(i[0],i[1],i[2]).length();const s=cr.set(i[4],i[5],i[6]).length(),a=cr.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),t.x=i[12],t.y=i[13],t.z=i[14],hr.copy(this);const o=1/r,l=1/s,c=1/a;return hr.elements[0]*=o,hr.elements[1]*=o,hr.elements[2]*=o,hr.elements[4]*=l,hr.elements[5]*=l,hr.elements[6]*=l,hr.elements[8]*=c,hr.elements[9]*=c,hr.elements[10]*=c,e.setFromRotationMatrix(hr),n.x=r,n.y=s,n.z=a,this}makePerspective(t,e,n,i,r,s,a=2e3){const o=this.elements,l=2*r/(e-t),c=2*r/(n-i),h=(e+t)/(e-t),u=(n+i)/(n-i);let d,p;if(a===kn)d=-(s+r)/(s-r),p=-2*s*r/(s-r);else{if(a!==Vn)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);d=-s/(s-r),p=-s*r/(s-r)}return o[0]=l,o[4]=0,o[8]=h,o[12]=0,o[1]=0,o[5]=c,o[9]=u,o[13]=0,o[2]=0,o[6]=0,o[10]=d,o[14]=p,o[3]=0,o[7]=0,o[11]=-1,o[15]=0,this}makeOrthographic(t,e,n,i,r,s,a=2e3){const o=this.elements,l=1/(e-t),c=1/(n-i),h=1/(s-r),u=(e+t)*l,d=(n+i)*c;let p,m;if(a===kn)p=(s+r)*h,m=-2*h;else{if(a!==Vn)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);p=r*h,m=-1*h}return o[0]=2*l,o[4]=0,o[8]=0,o[12]=-u,o[1]=0,o[5]=2*c,o[9]=0,o[13]=-d,o[2]=0,o[6]=0,o[10]=m,o[14]=-p,o[3]=0,o[7]=0,o[11]=0,o[15]=1,this}equals(t){const e=this.elements,n=t.elements;for(let t=0;t<16;t++)if(e[t]!==n[t])return!1;return!0}fromArray(t,e=0){for(let n=0;n<16;n++)this.elements[n]=t[n+e];return this}toArray(t=[],e=0){const n=this.elements;return t[e]=n[0],t[e+1]=n[1],t[e+2]=n[2],t[e+3]=n[3],t[e+4]=n[4],t[e+5]=n[5],t[e+6]=n[6],t[e+7]=n[7],t[e+8]=n[8],t[e+9]=n[9],t[e+10]=n[10],t[e+11]=n[11],t[e+12]=n[12],t[e+13]=n[13],t[e+14]=n[14],t[e+15]=n[15],t}}const cr=new Li,hr=new lr,ur=new Li(0,0,0),dr=new Li(1,1,1),pr=new Li,mr=new Li,fr=new Li,gr=new lr,vr=new Ii;class _r{constructor(t=0,e=0,n=0,i=_r.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=n,this._order=i}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,n,i=this._order){return this._x=t,this._y=e,this._z=n,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,n=!0){const i=t.elements,r=i[0],s=i[4],a=i[8],o=i[1],l=i[5],c=i[9],h=i[2],u=i[6],d=i[10];switch(e){case"XYZ":this._y=Math.asin(Yn(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-c,d),this._z=Math.atan2(-s,r)):(this._x=Math.atan2(u,l),this._z=0);break;case"YXZ":this._x=Math.asin(-Yn(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,l)):(this._y=Math.atan2(-h,r),this._z=0);break;case"ZXY":this._x=Math.asin(Yn(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(-h,d),this._z=Math.atan2(-s,l)):(this._y=0,this._z=Math.atan2(o,r));break;case"ZYX":this._y=Math.asin(-Yn(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(u,d),this._z=Math.atan2(o,r)):(this._x=0,this._z=Math.atan2(-s,l));break;case"YZX":this._z=Math.asin(Yn(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-c,l),this._y=Math.atan2(-h,r)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-Yn(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(u,l),this._y=Math.atan2(a,r)):(this._x=Math.atan2(-c,d),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,!0===n&&this._onChangeCallback(),this}setFromQuaternion(t,e,n){return gr.makeRotationFromQuaternion(t),this.setFromRotationMatrix(gr,e,n)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return vr.setFromEuler(this),this.setFromQuaternion(vr,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],void 0!==t[3]&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}_r.DEFAULT_ORDER="XYZ";class xr{constructor(){this.mask=1}set(t){this.mask=(1<>>0}enable(t){this.mask|=1<1){for(let t=0;t1){for(let t=0;t0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.visibility=this._visibility,i.active=this._active,i.bounds=this._bounds.map((t=>({boxInitialized:t.boxInitialized,boxMin:t.box.min.toArray(),boxMax:t.box.max.toArray(),sphereInitialized:t.sphereInitialized,sphereRadius:t.sphere.radius,sphereCenter:t.sphere.center.toArray()}))),i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.geometryCount=this._geometryCount,i.matricesTexture=this._matricesTexture.toJSON(t),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(t)),null!==this.boundingSphere&&(i.boundingSphere={center:i.boundingSphere.center.toArray(),radius:i.boundingSphere.radius}),null!==this.boundingBox&&(i.boundingBox={min:i.boundingBox.min.toArray(),max:i.boundingBox.max.toArray()})),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(t.geometries,this.geometry);const e=this.geometry.parameters;if(void 0!==e&&void 0!==e.shapes){const n=e.shapes;if(Array.isArray(n))for(let e=0,i=n.length;e0){i.children=[];for(let e=0;e0){i.animations=[];for(let e=0;e0&&(n.geometries=e),i.length>0&&(n.materials=i),r.length>0&&(n.textures=r),a.length>0&&(n.images=a),o.length>0&&(n.shapes=o),l.length>0&&(n.skeletons=l),c.length>0&&(n.animations=c),h.length>0&&(n.nodes=h)}return n.object=i,n;function s(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}}clone(t){return(new this.constructor).copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),!0===e)for(let e=0;e0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(t,e,n,i,r){Or.subVectors(i,e),Fr.subVectors(n,e),Br.subVectors(t,e);const s=Or.dot(Or),a=Or.dot(Fr),o=Or.dot(Br),l=Fr.dot(Fr),c=Fr.dot(Br),h=s*l-a*a;if(0===h)return r.set(0,0,0),null;const u=1/h,d=(l*o-a*c)*u,p=(s*c-a*o)*u;return r.set(1-d-p,p,d)}static containsPoint(t,e,n,i){return null!==this.getBarycoord(t,e,n,i,zr)&&(zr.x>=0&&zr.y>=0&&zr.x+zr.y<=1)}static getInterpolation(t,e,n,i,r,s,a,o){return null===this.getBarycoord(t,e,n,i,zr)?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(r,zr.x),o.addScaledVector(s,zr.y),o.addScaledVector(a,zr.z),o)}static getInterpolatedAttribute(t,e,n,i,r,s){return jr.setScalar(0),qr.setScalar(0),Yr.setScalar(0),jr.fromBufferAttribute(t,e),qr.fromBufferAttribute(t,n),Yr.fromBufferAttribute(t,i),s.setScalar(0),s.addScaledVector(jr,r.x),s.addScaledVector(qr,r.y),s.addScaledVector(Yr,r.z),s}static isFrontFacing(t,e,n,i){return Or.subVectors(n,e),Fr.subVectors(t,e),Or.cross(Fr).dot(i)<0}set(t,e,n){return this.a.copy(t),this.b.copy(e),this.c.copy(n),this}setFromPointsAndIndices(t,e,n,i){return this.a.copy(t[e]),this.b.copy(t[n]),this.c.copy(t[i]),this}setFromAttributeAndIndices(t,e,n,i){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,n),this.c.fromBufferAttribute(t,i),this}clone(){return(new this.constructor).copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return Or.subVectors(this.c,this.b),Fr.subVectors(this.a,this.b),.5*Or.cross(Fr).length()}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return Zr.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return Zr.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,n,i,r){return Zr.getInterpolation(t,this.a,this.b,this.c,e,n,i,r)}containsPoint(t){return Zr.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return Zr.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const n=this.a,i=this.b,r=this.c;let s,a;kr.subVectors(i,n),Vr.subVectors(r,n),Gr.subVectors(t,n);const o=kr.dot(Gr),l=Vr.dot(Gr);if(o<=0&&l<=0)return e.copy(n);Wr.subVectors(t,i);const c=kr.dot(Wr),h=Vr.dot(Wr);if(c>=0&&h<=c)return e.copy(i);const u=o*h-c*l;if(u<=0&&o>=0&&c<=0)return s=o/(o-c),e.copy(n).addScaledVector(kr,s);Xr.subVectors(t,r);const d=kr.dot(Xr),p=Vr.dot(Xr);if(p>=0&&d<=p)return e.copy(r);const m=d*l-o*p;if(m<=0&&l>=0&&p<=0)return a=l/(l-p),e.copy(n).addScaledVector(Vr,a);const f=c*p-d*h;if(f<=0&&h-c>=0&&d-p>=0)return Hr.subVectors(r,i),a=(h-c)/(h-c+(d-p)),e.copy(i).addScaledVector(Hr,a);const g=1/(f+m+u);return s=m*g,a=u*g,e.copy(n).addScaledVector(kr,s).addScaledVector(Vr,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}const Jr={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Kr={h:0,s:0,l:0},$r={h:0,s:0,l:0};function Qr(t,e,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?t+6*(e-t)*n:n<.5?e:n<2/3?t+6*(e-t)*(2/3-n):t}class ts{constructor(t,e,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(t,e,n)}set(t,e,n){if(void 0===e&&void 0===n){const e=t;e&&e.isColor?this.copy(e):"number"==typeof e?this.setHex(e):"string"==typeof e&&this.setStyle(e)}else this.setRGB(t,e,n);return this}setScalar(t){return this.r=t,this.g=t,this.b=t,this}setHex(t,e=Je){return t=Math.floor(t),this.r=(t>>16&255)/255,this.g=(t>>8&255)/255,this.b=(255&t)/255,mi.toWorkingColorSpace(this,e),this}setRGB(t,e,n,i=mi.workingColorSpace){return this.r=t,this.g=e,this.b=n,mi.toWorkingColorSpace(this,i),this}setHSL(t,e,n,i=mi.workingColorSpace){if(t=Zn(t,1),e=Yn(e,0,1),n=Yn(n,0,1),0===e)this.r=this.g=this.b=n;else{const i=n<=.5?n*(1+e):n+e-n*e,r=2*n-i;this.r=Qr(r,i,t+1/3),this.g=Qr(r,i,t),this.b=Qr(r,i,t-1/3)}return mi.toWorkingColorSpace(this,i),this}setStyle(t,e=Je){function n(e){void 0!==e&&parseFloat(e)<1&&console.warn("THREE.Color: Alpha component of "+t+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(t)){let r;const s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,e);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,e);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return n(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,e);break;default:console.warn("THREE.Color: Unknown color model "+t)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(t)){const n=i[1],r=n.length;if(3===r)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,e);if(6===r)return this.setHex(parseInt(n,16),e);console.warn("THREE.Color: Invalid hex color "+t)}else if(t&&t.length>0)return this.setColorName(t,e);return this}setColorName(t,e=Je){const n=Jr[t.toLowerCase()];return void 0!==n?this.setHex(n,e):console.warn("THREE.Color: Unknown color "+t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(t){return this.r=t.r,this.g=t.g,this.b=t.b,this}copySRGBToLinear(t){return this.r=fi(t.r),this.g=fi(t.g),this.b=fi(t.b),this}copyLinearToSRGB(t){return this.r=gi(t.r),this.g=gi(t.g),this.b=gi(t.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(t=Je){return mi.fromWorkingColorSpace(es.copy(this),t),65536*Math.round(Yn(255*es.r,0,255))+256*Math.round(Yn(255*es.g,0,255))+Math.round(Yn(255*es.b,0,255))}getHexString(t=Je){return("000000"+this.getHex(t).toString(16)).slice(-6)}getHSL(t,e=mi.workingColorSpace){mi.fromWorkingColorSpace(es.copy(this),e);const n=es.r,i=es.g,r=es.b,s=Math.max(n,i,r),a=Math.min(n,i,r);let o,l;const c=(a+s)/2;if(a===s)o=0,l=0;else{const t=s-a;switch(l=c<=.5?t/(s+a):t/(2-s-a),s){case n:o=(i-r)/t+(i0!=t>0&&this.version++,this._alphaTest=t}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(t){if(void 0!==t)for(const e in t){const n=t[e];if(void 0===n){console.warn(`THREE.Material: parameter '${e}' has value of undefined.`);continue}const i=this[e];void 0!==i?i&&i.isColor?i.set(n):i&&i.isVector3&&n&&n.isVector3?i.copy(n):this[e]=n:console.warn(`THREE.Material: '${e}' is not a property of THREE.${this.type}.`)}}toJSON(t){const e=void 0===t||"string"==typeof t;e&&(t={textures:{},images:{}});const n={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};function i(t){const e=[];for(const n in t){const i=t[n];delete i.metadata,e.push(i)}return e}if(n.uuid=this.uuid,n.type=this.type,""!==this.name&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),void 0!==this.roughness&&(n.roughness=this.roughness),void 0!==this.metalness&&(n.metalness=this.metalness),void 0!==this.sheen&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(n.shininess=this.shininess),void 0!==this.clearcoat&&(n.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(t).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(t).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(t).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),void 0!==this.dispersion&&(n.dispersion=this.dispersion),void 0!==this.iridescence&&(n.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(n.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(t).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(t).uuid),void 0!==this.anisotropy&&(n.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(t).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(t).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(t).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(t).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(t).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(t).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(t).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(t).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(t).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(t).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(t).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(t).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(t).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(t).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(t).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(t).uuid,void 0!==this.combine&&(n.combine=this.combine)),void 0!==this.envMapRotation&&(n.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(n.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(n.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(t).uuid),void 0!==this.transmission&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(t).uuid),void 0!==this.thickness&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(t).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(n.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(n.size=this.size),null!==this.shadowSide&&(n.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(n.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(n.blending=this.blending),this.side!==u&&(n.side=this.side),!0===this.vertexColors&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),!0===this.transparent&&(n.transparent=!0),this.blendSrc!==C&&(n.blendSrc=this.blendSrc),this.blendDst!==P&&(n.blendDst=this.blendDst),this.blendEquation!==y&&(n.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(n.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(n.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(n.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(n.depthFunc=this.depthFunc),!1===this.depthTest&&(n.depthTest=this.depthTest),!1===this.depthWrite&&(n.depthWrite=this.depthWrite),!1===this.colorWrite&&(n.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(n.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(n.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(n.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==an&&(n.stencilFail=this.stencilFail),this.stencilZFail!==an&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==an&&(n.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(n.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(n.rotation=this.rotation),!0===this.polygonOffset&&(n.polygonOffset=!0),0!==this.polygonOffsetFactor&&(n.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(n.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(n.linewidth=this.linewidth),void 0!==this.dashSize&&(n.dashSize=this.dashSize),void 0!==this.gapSize&&(n.gapSize=this.gapSize),void 0!==this.scale&&(n.scale=this.scale),!0===this.dithering&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),!0===this.alphaHash&&(n.alphaHash=!0),!0===this.alphaToCoverage&&(n.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(n.premultipliedAlpha=!0),!0===this.forceSinglePass&&(n.forceSinglePass=!0),!0===this.wireframe&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(n.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(n.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(n.flatShading=!0),!1===this.visible&&(n.visible=!1),!1===this.toneMapped&&(n.toneMapped=!1),!1===this.fog&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData),e){const e=i(t.textures),r=i(t.images);e.length>0&&(n.textures=e),r.length>0&&(n.images=r)}return n}clone(){return(new this.constructor).copy(this)}copy(t){this.name=t.name,this.blending=t.blending,this.side=t.side,this.vertexColors=t.vertexColors,this.opacity=t.opacity,this.transparent=t.transparent,this.blendSrc=t.blendSrc,this.blendDst=t.blendDst,this.blendEquation=t.blendEquation,this.blendSrcAlpha=t.blendSrcAlpha,this.blendDstAlpha=t.blendDstAlpha,this.blendEquationAlpha=t.blendEquationAlpha,this.blendColor.copy(t.blendColor),this.blendAlpha=t.blendAlpha,this.depthFunc=t.depthFunc,this.depthTest=t.depthTest,this.depthWrite=t.depthWrite,this.stencilWriteMask=t.stencilWriteMask,this.stencilFunc=t.stencilFunc,this.stencilRef=t.stencilRef,this.stencilFuncMask=t.stencilFuncMask,this.stencilFail=t.stencilFail,this.stencilZFail=t.stencilZFail,this.stencilZPass=t.stencilZPass,this.stencilWrite=t.stencilWrite;const e=t.clippingPlanes;let n=null;if(null!==e){const t=e.length;n=new Array(t);for(let i=0;i!==t;++i)n[i]=e[i].clone()}return this.clippingPlanes=n,this.clipIntersection=t.clipIntersection,this.clipShadows=t.clipShadows,this.shadowSide=t.shadowSide,this.colorWrite=t.colorWrite,this.precision=t.precision,this.polygonOffset=t.polygonOffset,this.polygonOffsetFactor=t.polygonOffsetFactor,this.polygonOffsetUnits=t.polygonOffsetUnits,this.dithering=t.dithering,this.alphaTest=t.alphaTest,this.alphaHash=t.alphaHash,this.alphaToCoverage=t.alphaToCoverage,this.premultipliedAlpha=t.premultipliedAlpha,this.forceSinglePass=t.forceSinglePass,this.visible=t.visible,this.toneMapped=t.toneMapped,this.userData=JSON.parse(JSON.stringify(t.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(t){!0===t&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}}class rs extends is{constructor(t){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new ts(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}const ss=as();function as(){const t=new ArrayBuffer(4),e=new Float32Array(t),n=new Uint32Array(t),i=new Uint32Array(512),r=new Uint32Array(512);for(let t=0;t<256;++t){const e=t-127;e<-27?(i[t]=0,i[256|t]=32768,r[t]=24,r[256|t]=24):e<-14?(i[t]=1024>>-e-14,i[256|t]=1024>>-e-14|32768,r[t]=-e-1,r[256|t]=-e-1):e<=15?(i[t]=e+15<<10,i[256|t]=e+15<<10|32768,r[t]=13,r[256|t]=13):e<128?(i[t]=31744,i[256|t]=64512,r[t]=24,r[256|t]=24):(i[t]=31744,i[256|t]=64512,r[t]=13,r[256|t]=13)}const s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let t=1;t<1024;++t){let e=t<<13,n=0;for(;0==(8388608&e);)e<<=1,n-=8388608;e&=-8388609,n+=947912704,s[t]=e|n}for(let t=1024;t<2048;++t)s[t]=939524096+(t-1024<<13);for(let t=1;t<31;++t)a[t]=t<<23;a[31]=1199570944,a[32]=2147483648;for(let t=33;t<63;++t)a[t]=2147483648+(t-32<<23);a[63]=3347054592;for(let t=1;t<64;++t)32!==t&&(o[t]=1024);return{floatView:e,uint32View:n,baseTable:i,shiftTable:r,mantissaTable:s,exponentTable:a,offsetTable:o}}function os(t){Math.abs(t)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),t=Yn(t,-65504,65504),ss.floatView[0]=t;const e=ss.uint32View[0],n=e>>23&511;return ss.baseTable[n]+((8388607&e)>>ss.shiftTable[n])}function ls(t){const e=t>>10;return ss.uint32View[0]=ss.mantissaTable[ss.offsetTable[e]+(1023&t)]+ss.exponentTable[e],ss.floatView[0]}const cs={toHalfFloat:os,fromHalfFloat:ls},hs=new Li,us=new ti;class ds{constructor(t,e,n=!1){if(Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=t,this.itemSize=e,this.count=void 0!==t?t.length/e:0,this.normalized=n,this.usage=Cn,this.updateRanges=[],this.gpuType=Lt,this.version=0}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,n){t*=this.itemSize,n*=e.itemSize;for(let i=0,r=this.itemSize;i0&&(t.userData=this.userData),void 0!==this.parameters){const e=this.parameters;for(const n in e)void 0!==e[n]&&(t[n]=e[n]);return t}t.data={attributes:{}};const e=this.index;null!==e&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const n=this.attributes;for(const e in n){const i=n[e];t.data.attributes[e]=i.toJSON(t.data)}const i={};let r=!1;for(const e in this.morphAttributes){const n=this.morphAttributes[e],s=[];for(let e=0,i=n.length;e0&&(i[e]=s,r=!0)}r&&(t.data.morphAttributes=i,t.data.morphTargetsRelative=this.morphTargetsRelative);const s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));const a=this.boundingSphere;return null!==a&&(t.data.boundingSphere={center:a.center.toArray(),radius:a.radius}),t}clone(){return(new this.constructor).copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const n=t.index;null!==n&&this.setIndex(n.clone(e));const i=t.attributes;for(const t in i){const n=i[t];this.setAttribute(t,n.clone(e))}const r=t.morphAttributes;for(const t in r){const n=[],i=r[t];for(let t=0,r=i.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;t(t.far-t.near)**2)return}Ps.copy(r).invert(),Is.copy(t.ray).applyMatrix4(Ps),null!==n.boundingBox&&!1===Is.intersectsBox(n.boundingBox)||this._computeIntersections(t,e,Is)}}_computeIntersections(t,e,n){let i;const r=this.geometry,s=this.material,a=r.index,o=r.attributes.position,l=r.attributes.uv,c=r.attributes.uv1,h=r.attributes.normal,u=r.groups,d=r.drawRange;if(null!==a)if(Array.isArray(s))for(let r=0,o=u.length;rn.far?null:{distance:c,point:ks.clone(),object:t}}(t,e,n,i,Ns,Ds,Os,zs);if(h){const t=new Li;Zr.getBarycoord(zs,Ns,Ds,Os,t),r&&(h.uv=Zr.getInterpolatedAttribute(r,o,l,c,t,new ti)),s&&(h.uv1=Zr.getInterpolatedAttribute(s,o,l,c,t,new ti)),a&&(h.normal=Zr.getInterpolatedAttribute(a,o,l,c,t,new Li),h.normal.dot(i.direction)>0&&h.normal.multiplyScalar(-1));const e={a:o,b:l,c:c,normal:new Li,materialIndex:0};Zr.getNormal(Ns,Ds,Os,e.normal),h.face=e,h.barycoord=t}return h}class Gs extends Cs{constructor(t=1,e=1,n=1,i=1,r=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:e,depth:n,widthSegments:i,heightSegments:r,depthSegments:s};const a=this;i=Math.floor(i),r=Math.floor(r),s=Math.floor(s);const o=[],l=[],c=[],h=[];let u=0,d=0;function p(t,e,n,i,r,s,p,m,f,g,v){const _=s/f,x=p/g,y=s/2,M=p/2,S=m/2,b=f+1,w=g+1;let T=0,E=0;const A=new Li;for(let s=0;s0?1:-1,c.push(A.x,A.y,A.z),h.push(o/f),h.push(1-s/g),T+=1}}for(let t=0;t0&&(e.defines=this.defines),e.vertexShader=this.vertexShader,e.fragmentShader=this.fragmentShader,e.lights=this.lights,e.clipping=this.clipping;const n={};for(const t in this.extensions)!0===this.extensions[t]&&(n[t]=!0);return Object.keys(n).length>0&&(e.extensions=n),e}}class Zs extends Dr{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new lr,this.projectionMatrix=new lr,this.projectionMatrixInverse=new lr,this.coordinateSystem=kn}copy(t,e){return super.copy(t,e),this.matrixWorldInverse.copy(t.matrixWorldInverse),this.projectionMatrix.copy(t.projectionMatrix),this.projectionMatrixInverse.copy(t.projectionMatrixInverse),this.coordinateSystem=t.coordinateSystem,this}getWorldDirection(t){return super.getWorldDirection(t).negate()}updateMatrixWorld(t){super.updateMatrixWorld(t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(t,e){super.updateWorldMatrix(t,e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Js=new Li,Ks=new ti,$s=new ti;class Qs extends Zs{constructor(t=50,e=1,n=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=t,this.zoom=1,this.near=n,this.far=i,this.focus=10,this.aspect=e,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.fov=t.fov,this.zoom=t.zoom,this.near=t.near,this.far=t.far,this.focus=t.focus,this.aspect=t.aspect,this.view=null===t.view?null:Object.assign({},t.view),this.filmGauge=t.filmGauge,this.filmOffset=t.filmOffset,this}setFocalLength(t){const e=.5*this.getFilmHeight()/t;this.fov=2*jn*Math.atan(e),this.updateProjectionMatrix()}getFocalLength(){const t=Math.tan(.5*Xn*this.fov);return.5*this.getFilmHeight()/t}getEffectiveFOV(){return 2*jn*Math.atan(Math.tan(.5*Xn*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(t,e,n){Js.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),e.set(Js.x,Js.y).multiplyScalar(-t/Js.z),Js.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),n.set(Js.x,Js.y).multiplyScalar(-t/Js.z)}getViewSize(t,e){return this.getViewBounds(t,Ks,$s),e.subVectors($s,Ks)}setViewOffset(t,e,n,i,r,s){this.aspect=t/e,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=this.near;let e=t*Math.tan(.5*Xn*this.fov)/this.zoom,n=2*e,i=this.aspect*n,r=-.5*i;const s=this.view;if(null!==this.view&&this.view.enabled){const t=s.fullWidth,a=s.fullHeight;r+=s.offsetX*i/t,e-=s.offsetY*n/a,i*=s.width/t,n*=s.height/a}const a=this.filmOffset;0!==a&&(r+=t*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,e,e-n,t,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.fov=this.fov,e.object.zoom=this.zoom,e.object.near=this.near,e.object.far=this.far,e.object.focus=this.focus,e.object.aspect=this.aspect,null!==this.view&&(e.object.view=Object.assign({},this.view)),e.object.filmGauge=this.filmGauge,e.object.filmOffset=this.filmOffset,e}}const ta=-90;class ea extends Dr{constructor(t,e,n){super(),this.type="CubeCamera",this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Qs(ta,1,t,e);i.layers=this.layers,this.add(i);const r=new Qs(ta,1,t,e);r.layers=this.layers,this.add(r);const s=new Qs(ta,1,t,e);s.layers=this.layers,this.add(s);const a=new Qs(ta,1,t,e);a.layers=this.layers,this.add(a);const o=new Qs(ta,1,t,e);o.layers=this.layers,this.add(o);const l=new Qs(ta,1,t,e);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const t=this.coordinateSystem,e=this.children.concat(),[n,i,r,s,a,o]=e;for(const t of e)this.remove(t);if(t===kn)n.up.set(0,1,0),n.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else{if(t!==Vn)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+t);n.up.set(0,-1,0),n.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1)}for(const t of e)this.add(t),t.updateMatrixWorld()}update(t,e){null===this.parent&&this.updateMatrixWorld();const{renderTarget:n,activeMipmapLevel:i}=this;this.coordinateSystem!==t.coordinateSystem&&(this.coordinateSystem=t.coordinateSystem,this.updateCoordinateSystem());const[r,s,a,o,l,c]=this.children,h=t.getRenderTarget(),u=t.getActiveCubeFace(),d=t.getActiveMipmapLevel(),p=t.xr.enabled;t.xr.enabled=!1;const m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1,t.setRenderTarget(n,0,i),t.render(e,r),t.setRenderTarget(n,1,i),t.render(e,s),t.setRenderTarget(n,2,i),t.render(e,a),t.setRenderTarget(n,3,i),t.render(e,o),t.setRenderTarget(n,4,i),t.render(e,l),n.texture.generateMipmaps=m,t.setRenderTarget(n,5,i),t.render(e,c),t.setRenderTarget(h,u,d),t.xr.enabled=p,n.texture.needsPMREMUpdate=!0}}class na extends bi{constructor(t,e,n,i,r,s,a,o,l,c){super(t=void 0!==t?t:[],e=void 0!==e?e:lt,n,i,r,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(t){this.image=t}}class ia extends Ei{constructor(t=1,e={}){super(t,t,e),this.isWebGLCubeRenderTarget=!0;const n={width:t,height:t,depth:1},i=[n,n,n,n,n,n];this.texture=new na(i,e.mapping,e.wrapS,e.wrapT,e.magFilter,e.minFilter,e.format,e.type,e.anisotropy,e.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=void 0!==e.generateMipmaps&&e.generateMipmaps,this.texture.minFilter=void 0!==e.minFilter?e.minFilter:Mt}fromEquirectangularTexture(t,e){this.texture.type=e.type,this.texture.colorSpace=e.colorSpace,this.texture.generateMipmaps=e.generateMipmaps,this.texture.minFilter=e.minFilter,this.texture.magFilter=e.magFilter;const n={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include \n\t\t\t\t\t#include \n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include \n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Gs(5,5,5),r=new Ys({name:"CubemapFromEquirect",uniforms:Ws(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:d,blending:0});r.uniforms.tEquirect.value=e;const s=new Vs(i,r),a=e.minFilter;e.minFilter===wt&&(e.minFilter=Mt);return new ea(1,10,this).update(t,s),e.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(t,e,n,i){const r=t.getRenderTarget();for(let r=0;r<6;r++)t.setRenderTarget(this,r),t.clear(e,n,i);t.setRenderTarget(r)}}const ra=new Li,sa=new Li,aa=new ei;class oa{constructor(t=new Li(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,n,i){return this.normal.set(t,e,n),this.constant=i,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,n){const i=ra.subVectors(n,e).cross(sa.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(i,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e){const n=t.delta(ra),i=this.normal.dot(n);if(0===i)return 0===this.distanceToPoint(t.start)?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:e.copy(t.start).addScaledVector(n,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),n=this.distanceToPoint(t.end);return e<0&&n>0||n<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const n=e||aa.getNormalMatrix(t),i=this.coplanarPoint(ra).applyMatrix4(t),r=this.normal.applyMatrix3(n).normalize();return this.constant=-i.dot(r),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const la=new Qi,ca=new Li;class ha{constructor(t=new oa,e=new oa,n=new oa,i=new oa,r=new oa,s=new oa){this.planes=[t,e,n,i,r,s]}set(t,e,n,i,r,s){const a=this.planes;return a[0].copy(t),a[1].copy(e),a[2].copy(n),a[3].copy(i),a[4].copy(r),a[5].copy(s),this}copy(t){const e=this.planes;for(let n=0;n<6;n++)e[n].copy(t.planes[n]);return this}setFromProjectionMatrix(t,e=2e3){const n=this.planes,i=t.elements,r=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],h=i[6],u=i[7],d=i[8],p=i[9],m=i[10],f=i[11],g=i[12],v=i[13],_=i[14],x=i[15];if(n[0].setComponents(o-r,u-l,f-d,x-g).normalize(),n[1].setComponents(o+r,u+l,f+d,x+g).normalize(),n[2].setComponents(o+s,u+c,f+p,x+v).normalize(),n[3].setComponents(o-s,u-c,f-p,x-v).normalize(),n[4].setComponents(o-a,u-h,f-m,x-_).normalize(),e===kn)n[5].setComponents(o+a,u+h,f+m,x+_).normalize();else{if(e!==Vn)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+e);n[5].setComponents(a,h,m,_).normalize()}return this}intersectsObject(t){if(void 0!==t.boundingSphere)null===t.boundingSphere&&t.computeBoundingSphere(),la.copy(t.boundingSphere).applyMatrix4(t.matrixWorld);else{const e=t.geometry;null===e.boundingSphere&&e.computeBoundingSphere(),la.copy(e.boundingSphere).applyMatrix4(t.matrixWorld)}return this.intersectsSphere(la)}intersectsSprite(t){return la.center.set(0,0,0),la.radius=.7071067811865476,la.applyMatrix4(t.matrixWorld),this.intersectsSphere(la)}intersectsSphere(t){const e=this.planes,n=t.center,i=-t.radius;for(let t=0;t<6;t++){if(e[t].distanceToPoint(n)0?t.max.x:t.min.x,ca.y=i.normal.y>0?t.max.y:t.min.y,ca.z=i.normal.z>0?t.max.z:t.min.z,i.distanceToPoint(ca)<0)return!1}return!0}containsPoint(t){const e=this.planes;for(let n=0;n<6;n++)if(e[n].distanceToPoint(t)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}function ua(){let t=null,e=!1,n=null,i=null;function r(e,s){n(e,s),i=t.requestAnimationFrame(r)}return{start:function(){!0!==e&&null!==n&&(i=t.requestAnimationFrame(r),e=!0)},stop:function(){t.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(t){n=t},setContext:function(e){t=e}}}function da(t){const e=new WeakMap;return{get:function(t){return t.isInterleavedBufferAttribute&&(t=t.data),e.get(t)},remove:function(n){n.isInterleavedBufferAttribute&&(n=n.data);const i=e.get(n);i&&(t.deleteBuffer(i.buffer),e.delete(n))},update:function(n,i){if(n.isInterleavedBufferAttribute&&(n=n.data),n.isGLBufferAttribute){const t=e.get(n);return void((!t||t.versiont.start-e.start));let e=0;for(let t=1;t 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif",clipping_planes_pars_fragment:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif",clipping_planes_pars_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif",clipping_planes_vertex:"#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif",color_fragment:"#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif",color_pars_fragment:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif",color_pars_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif",color_vertex:"#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif",common:"#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated",cube_uv_reflection_fragment:"#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif",defaultnormal_vertex:"vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif",displacementmap_pars_vertex:"#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif",displacementmap_vertex:"#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif",emissivemap_fragment:"#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif",emissivemap_pars_fragment:"#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif",colorspace_fragment:"gl_FragColor = linearToOutputTexel( gl_FragColor );",colorspace_pars_fragment:"\nconst mat3 LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = mat3(\n\tvec3( 0.8224621, 0.177538, 0.0 ),\n\tvec3( 0.0331941, 0.9668058, 0.0 ),\n\tvec3( 0.0170827, 0.0723974, 0.9105199 )\n);\nconst mat3 LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.2249401, - 0.2249404, 0.0 ),\n\tvec3( - 0.0420569, 1.0420571, 0.0 ),\n\tvec3( - 0.0196376, - 0.0786361, 1.0982735 )\n);\nvec4 LinearSRGBToLinearDisplayP3( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_SRGB_TO_LINEAR_DISPLAY_P3, value.a );\n}\nvec4 LinearDisplayP3ToLinearSRGB( in vec4 value ) {\n\treturn vec4( value.rgb * LINEAR_DISPLAY_P3_TO_LINEAR_SRGB, value.a );\n}\nvec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}",envmap_fragment:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif",envmap_common_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif",envmap_pars_fragment:"#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif",envmap_pars_vertex:"#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif",envmap_physical_pars_fragment:"#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif",envmap_vertex:"#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif",fog_vertex:"#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif",fog_pars_vertex:"#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif",fog_fragment:"#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, vFogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif",fog_pars_fragment:"#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float vFogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif",gradientmap_pars_fragment:"#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn vec3( texture2D( gradientMap, coord ).r );\n\t#else\n\t\tvec2 fw = fwidth( coord ) * 0.5;\n\t\treturn mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );\n\t#endif\n}",lightmap_pars_fragment:"#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif",lights_lambert_fragment:"LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;",lights_lambert_pars_fragment:"varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert",lights_pars_begin:"uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif",lights_toon_fragment:"ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;",lights_toon_pars_fragment:"varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon",lights_phong_fragment:"BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;",lights_phong_pars_fragment:"varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong",lights_physical_fragment:"PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif",lights_physical_pars_fragment:"struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}",lights_fragment_begin:"\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif",lights_fragment_maps:"#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif",lights_fragment_end:"#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif",logdepthbuf_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif",logdepthbuf_pars_fragment:"#if defined( USE_LOGDEPTHBUF )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_pars_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif",logdepthbuf_vertex:"#ifdef USE_LOGDEPTHBUF\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif",map_fragment:"#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif",map_pars_fragment:"#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif",map_particle_fragment:"#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif",map_particle_pars_fragment:"#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif",metalnessmap_fragment:"float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif",metalnessmap_pars_fragment:"#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif",morphinstance_vertex:"#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif",morphcolor_vertex:"#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif",morphnormal_vertex:"#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",morphtarget_pars_vertex:"#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif",morphtarget_vertex:"#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif",normal_fragment_begin:"float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;",normal_fragment_maps:"#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif",normal_pars_fragment:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_pars_vertex:"#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif",normal_vertex:"#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif",normalmap_pars_fragment:"#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif",clearcoat_normal_fragment_begin:"#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif",clearcoat_normal_fragment_maps:"#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif",clearcoat_pars_fragment:"#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif",iridescence_pars_fragment:"#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif",opaque_fragment:"#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );",packing:"vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}",premultiplied_alpha_fragment:"#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif",project_vertex:"vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;",dithering_fragment:"#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif",dithering_pars_fragment:"#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif",roughnessmap_fragment:"float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif",roughnessmap_pars_fragment:"#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif",shadowmap_pars_fragment:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif",shadowmap_pars_vertex:"#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif",shadowmap_vertex:"#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif",shadowmask_pars_fragment:"float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}",skinbase_vertex:"#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif",skinning_pars_vertex:"#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif",skinning_vertex:"#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif",skinnormal_vertex:"#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif",specularmap_fragment:"float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif",specularmap_pars_fragment:"#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif",tonemapping_fragment:"#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif",tonemapping_pars_fragment:"#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }",transmission_fragment:"#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif",transmission_pars_fragment:"#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t\n\t\t#else\n\t\t\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif",uv_pars_fragment:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_pars_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif",uv_vertex:"#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif",worldpos_vertex:"#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif",background_vert:"varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}",background_frag:"uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",backgroundCube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",backgroundCube_frag:"#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include \n\t#include \n}",cube_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n\tgl_Position.z = gl_Position.w;\n}",cube_frag:"uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include \n\t#include \n}",depth_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvHighPrecisionZW = gl_Position.zw;\n}",depth_frag:"#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}",distanceRGBA_vert:"#define DISTANCE\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvWorldPosition = worldPosition.xyz;\n}",distanceRGBA_frag:"#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}",equirect_vert:"varying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include \n\t#include \n}",equirect_frag:"uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include \nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include \n\t#include \n}",linedashed_vert:"uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",linedashed_frag:"uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshbasic_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include \n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_vert:"#define LAMBERT\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshlambert_frag:"#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshmatcap_vert:"#define MATCAP\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n}",meshmatcap_frag:"#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshnormal_vert:"#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}",meshnormal_frag:"#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}",meshphong_vert:"#define PHONG\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphong_frag:"#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshphysical_vert:"#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}",meshphysical_frag:"#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include \n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",meshtoon_vert:"#define TOON\nvarying vec3 vViewPosition;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvViewPosition = - mvPosition.xyz;\n\t#include \n\t#include \n\t#include \n}",meshtoon_frag:"#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",points_vert:"uniform float size;\nuniform float scale;\n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include \n\t#include \n\t#include \n\t#include \n}",points_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_vert:"#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n}",shadow_frag:"uniform vec3 color;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include \n\t#include \n\t#include \n}",sprite_vert:"uniform float rotation;\nuniform vec2 center;\n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\t#include \n\tvec4 mvPosition = modelViewMatrix[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include \n\t#include \n\t#include \n}",sprite_frag:"uniform vec3 diffuse;\nuniform float opacity;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include \n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\toutgoingLight = diffuseColor.rgb;\n\t#include \n\t#include \n\t#include \n\t#include \n}"},fa={common:{diffuse:{value:new ts(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new ei},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new ei}},envmap:{envMap:{value:null},envMapRotation:{value:new ei},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new ei}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new ei}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new ei},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new ei},normalScale:{value:new ti(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new ei},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new ei}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new ei}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new ei}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new ts(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new ts(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0},uvTransform:{value:new ei}},sprite:{diffuse:{value:new ts(16777215)},opacity:{value:1},center:{value:new ti(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new ei},alphaMap:{value:null},alphaMapTransform:{value:new ei},alphaTest:{value:0}}},ga={basic:{uniforms:Xs([fa.common,fa.specularmap,fa.envmap,fa.aomap,fa.lightmap,fa.fog]),vertexShader:ma.meshbasic_vert,fragmentShader:ma.meshbasic_frag},lambert:{uniforms:Xs([fa.common,fa.specularmap,fa.envmap,fa.aomap,fa.lightmap,fa.emissivemap,fa.bumpmap,fa.normalmap,fa.displacementmap,fa.fog,fa.lights,{emissive:{value:new ts(0)}}]),vertexShader:ma.meshlambert_vert,fragmentShader:ma.meshlambert_frag},phong:{uniforms:Xs([fa.common,fa.specularmap,fa.envmap,fa.aomap,fa.lightmap,fa.emissivemap,fa.bumpmap,fa.normalmap,fa.displacementmap,fa.fog,fa.lights,{emissive:{value:new ts(0)},specular:{value:new ts(1118481)},shininess:{value:30}}]),vertexShader:ma.meshphong_vert,fragmentShader:ma.meshphong_frag},standard:{uniforms:Xs([fa.common,fa.envmap,fa.aomap,fa.lightmap,fa.emissivemap,fa.bumpmap,fa.normalmap,fa.displacementmap,fa.roughnessmap,fa.metalnessmap,fa.fog,fa.lights,{emissive:{value:new ts(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ma.meshphysical_vert,fragmentShader:ma.meshphysical_frag},toon:{uniforms:Xs([fa.common,fa.aomap,fa.lightmap,fa.emissivemap,fa.bumpmap,fa.normalmap,fa.displacementmap,fa.gradientmap,fa.fog,fa.lights,{emissive:{value:new ts(0)}}]),vertexShader:ma.meshtoon_vert,fragmentShader:ma.meshtoon_frag},matcap:{uniforms:Xs([fa.common,fa.bumpmap,fa.normalmap,fa.displacementmap,fa.fog,{matcap:{value:null}}]),vertexShader:ma.meshmatcap_vert,fragmentShader:ma.meshmatcap_frag},points:{uniforms:Xs([fa.points,fa.fog]),vertexShader:ma.points_vert,fragmentShader:ma.points_frag},dashed:{uniforms:Xs([fa.common,fa.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ma.linedashed_vert,fragmentShader:ma.linedashed_frag},depth:{uniforms:Xs([fa.common,fa.displacementmap]),vertexShader:ma.depth_vert,fragmentShader:ma.depth_frag},normal:{uniforms:Xs([fa.common,fa.bumpmap,fa.normalmap,fa.displacementmap,{opacity:{value:1}}]),vertexShader:ma.meshnormal_vert,fragmentShader:ma.meshnormal_frag},sprite:{uniforms:Xs([fa.sprite,fa.fog]),vertexShader:ma.sprite_vert,fragmentShader:ma.sprite_frag},background:{uniforms:{uvTransform:{value:new ei},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ma.background_vert,fragmentShader:ma.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new ei}},vertexShader:ma.backgroundCube_vert,fragmentShader:ma.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ma.cube_vert,fragmentShader:ma.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ma.equirect_vert,fragmentShader:ma.equirect_frag},distanceRGBA:{uniforms:Xs([fa.common,fa.displacementmap,{referencePosition:{value:new Li},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ma.distanceRGBA_vert,fragmentShader:ma.distanceRGBA_frag},shadow:{uniforms:Xs([fa.lights,fa.fog,{color:{value:new ts(0)},opacity:{value:1}}]),vertexShader:ma.shadow_vert,fragmentShader:ma.shadow_frag}};ga.physical={uniforms:Xs([ga.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new ei},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new ei},clearcoatNormalScale:{value:new ti(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new ei},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new ei},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new ei},sheen:{value:0},sheenColor:{value:new ts(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new ei},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new ei},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new ei},transmissionSamplerSize:{value:new ti},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new ei},attenuationDistance:{value:0},attenuationColor:{value:new ts(0)},specularColor:{value:new ts(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new ei},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new ei},anisotropyVector:{value:new ti},anisotropyMap:{value:null},anisotropyMapTransform:{value:new ei}}]),vertexShader:ma.meshphysical_vert,fragmentShader:ma.meshphysical_frag};const va={r:0,b:0,g:0},_a=new _r,xa=new lr;function ya(t,e,n,i,r,s,a){const o=new ts(0);let l,c,h=!0===s?0:1,p=null,m=0,f=null;function g(t){let i=!0===t.isScene?t.background:null;if(i&&i.isTexture){i=(t.backgroundBlurriness>0?n:e).get(i)}return i}function v(e,n){e.getRGB(va,js(t)),i.buffers.color.setClear(va.r,va.g,va.b,n,a)}return{getClearColor:function(){return o},setClearColor:function(t,e=1){o.set(t),h=e,v(o,h)},getClearAlpha:function(){return h},setClearAlpha:function(t){h=t,v(o,h)},render:function(e){let n=!1;const r=g(e);null===r?v(o,h):r&&r.isColor&&(v(r,1),n=!0);const s=t.xr.getEnvironmentBlendMode();"additive"===s?i.buffers.color.setClear(0,0,0,1,a):"alpha-blend"===s&&i.buffers.color.setClear(0,0,0,0,a),(t.autoClear||n)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),t.clear(t.autoClearColor,t.autoClearDepth,t.autoClearStencil))},addToRenderList:function(e,n){const i=g(n);i&&(i.isCubeTexture||i.mapping===dt)?(void 0===c&&(c=new Vs(new Gs(1,1,1),new Ys({name:"BackgroundCubeMaterial",uniforms:Ws(ga.backgroundCube.uniforms),vertexShader:ga.backgroundCube.vertexShader,fragmentShader:ga.backgroundCube.fragmentShader,side:d,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),c.geometry.deleteAttribute("uv"),c.onBeforeRender=function(t,e,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(c.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),r.update(c)),_a.copy(n.backgroundRotation),_a.x*=-1,_a.y*=-1,_a.z*=-1,i.isCubeTexture&&!1===i.isRenderTargetTexture&&(_a.y*=-1,_a.z*=-1),c.material.uniforms.envMap.value=i,c.material.uniforms.flipEnvMap.value=i.isCubeTexture&&!1===i.isRenderTargetTexture?-1:1,c.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.uniforms.backgroundRotation.value.setFromMatrix4(xa.makeRotationFromEuler(_a)),c.material.toneMapped=mi.getTransfer(i.colorSpace)!==en,p===i&&m===i.version&&f===t.toneMapping||(c.material.needsUpdate=!0,p=i,m=i.version,f=t.toneMapping),c.layers.enableAll(),e.unshift(c,c.geometry,c.material,0,0,null)):i&&i.isTexture&&(void 0===l&&(l=new Vs(new pa(2,2),new Ys({name:"BackgroundMaterial",uniforms:Ws(ga.background.uniforms),vertexShader:ga.background.vertexShader,fragmentShader:ga.background.fragmentShader,side:u,depthTest:!1,depthWrite:!1,fog:!1})),l.geometry.deleteAttribute("normal"),Object.defineProperty(l.material,"map",{get:function(){return this.uniforms.t2D.value}}),r.update(l)),l.material.uniforms.t2D.value=i,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.toneMapped=mi.getTransfer(i.colorSpace)!==en,!0===i.matrixAutoUpdate&&i.updateMatrix(),l.material.uniforms.uvTransform.value.copy(i.matrix),p===i&&m===i.version&&f===t.toneMapping||(l.material.needsUpdate=!0,p=i,m=i.version,f=t.toneMapping),l.layers.enableAll(),e.unshift(l,l.geometry,l.material,0,0,null))}}}function Ma(t,e){const n=t.getParameter(t.MAX_VERTEX_ATTRIBS),i={},r=c(null);let s=r,a=!1;function o(e){return t.bindVertexArray(e)}function l(e){return t.deleteVertexArray(e)}function c(t){const e=[],i=[],r=[];for(let t=0;t=0){const n=r[e];let i=a[e];if(void 0===i&&("instanceMatrix"===e&&t.instanceMatrix&&(i=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(i=t.instanceColor)),void 0===n)return!0;if(n.attribute!==i)return!0;if(i&&n.data!==i.data)return!0;o++}}return s.attributesNum!==o||s.index!==i}(n,f,l,g),v&&function(t,e,n,i){const r={},a=e.attributes;let o=0;const l=n.getAttributes();for(const e in l){if(l[e].location>=0){let n=a[e];void 0===n&&("instanceMatrix"===e&&t.instanceMatrix&&(n=t.instanceMatrix),"instanceColor"===e&&t.instanceColor&&(n=t.instanceColor));const i={};i.attribute=n,n&&n.data&&(i.data=n.data),r[e]=i,o++}}s.attributes=r,s.attributesNum=o,s.index=i}(n,f,l,g),null!==g&&e.update(g,t.ELEMENT_ARRAY_BUFFER),(v||a)&&(a=!1,function(n,i,r,s){h();const a=s.attributes,o=r.getAttributes(),l=i.defaultAttributeValues;for(const i in o){const r=o[i];if(r.location>=0){let o=a[i];if(void 0===o&&("instanceMatrix"===i&&n.instanceMatrix&&(o=n.instanceMatrix),"instanceColor"===i&&n.instanceColor&&(o=n.instanceColor)),void 0!==o){const i=o.normalized,a=o.itemSize,l=e.get(o);if(void 0===l)continue;const c=l.buffer,h=l.type,p=l.bytesPerElement,f=h===t.INT||h===t.UNSIGNED_INT||o.gpuType===Pt;if(o.isInterleavedBufferAttribute){const e=o.data,l=e.stride,g=o.offset;if(e.isInstancedInterleavedBuffer){for(let t=0;t0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT).precision>0)return"highp";e="mediump"}return"mediump"===e&&t.getShaderPrecisionFormat(t.VERTEX_SHADER,t.MEDIUM_FLOAT).precision>0&&t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let a=void 0!==n.precision?n.precision:"highp";const o=s(a);o!==a&&(console.warn("THREE.WebGLRenderer:",a,"not supported, using",o,"instead."),a=o);const l=!0===n.logarithmicDepthBuffer,c=!0===n.reverseDepthBuffer&&e.has("EXT_clip_control");if(!0===c){const t=e.get("EXT_clip_control");t.clipControlEXT(t.LOWER_LEFT_EXT,t.ZERO_TO_ONE_EXT)}const h=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),u=t.getParameter(t.MAX_VERTEX_TEXTURE_IMAGE_UNITS);return{isWebGL2:!0,getMaxAnisotropy:function(){if(void 0!==r)return r;if(!0===e.has("EXT_texture_filter_anisotropic")){const n=e.get("EXT_texture_filter_anisotropic");r=t.getParameter(n.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else r=0;return r},getMaxPrecision:s,textureFormatReadable:function(e){return e===kt||i.convert(e)===t.getParameter(t.IMPLEMENTATION_COLOR_READ_FORMAT)},textureTypeReadable:function(n){const r=n===Ut&&(e.has("EXT_color_buffer_half_float")||e.has("EXT_color_buffer_float"));return!(n!==Et&&i.convert(n)!==t.getParameter(t.IMPLEMENTATION_COLOR_READ_TYPE)&&n!==Lt&&!r)},precision:a,logarithmicDepthBuffer:l,reverseDepthBuffer:c,maxTextures:h,maxVertexTextures:u,maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxCubemapSize:t.getParameter(t.MAX_CUBE_MAP_TEXTURE_SIZE),maxAttributes:t.getParameter(t.MAX_VERTEX_ATTRIBS),maxVertexUniforms:t.getParameter(t.MAX_VERTEX_UNIFORM_VECTORS),maxVaryings:t.getParameter(t.MAX_VARYING_VECTORS),maxFragmentUniforms:t.getParameter(t.MAX_FRAGMENT_UNIFORM_VECTORS),vertexTextures:u>0,maxSamples:t.getParameter(t.MAX_SAMPLES)}}function wa(t){const e=this;let n=null,i=0,r=!1,s=!1;const a=new oa,o=new ei,l={value:null,needsUpdate:!1};function c(t,n,i,r){const s=null!==t?t.length:0;let c=null;if(0!==s){if(c=l.value,!0!==r||null===c){const e=i+4*s,r=n.matrixWorldInverse;o.getNormalMatrix(r),(null===c||c.length0);e.numPlanes=i,e.numIntersection=0}();else{const t=s?0:i,e=4*t;let r=m.clippingState||null;l.value=r,r=c(u,o,e,h);for(let t=0;t!==e;++t)r[t]=n[t];m.clippingState=r,this.numIntersection=d?this.numPlanes:0,this.numPlanes+=t}}}function Ta(t){let e=new WeakMap;function n(t,e){return e===ht?t.mapping=lt:e===ut&&(t.mapping=ct),t}function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping;if(s===ht||s===ut){if(e.has(r)){return n(e.get(r).texture,r.mapping)}{const s=r.image;if(s&&s.height>0){const a=new ia(s.height);return a.fromEquirectangularTexture(t,r),e.set(r,a),r.addEventListener("dispose",i),n(a.texture,r.mapping)}return null}}}return r},dispose:function(){e=new WeakMap}}}class Ea extends Zs{constructor(t=-1,e=1,n=1,i=-1,r=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=t,this.right=e,this.top=n,this.bottom=i,this.near=r,this.far=s,this.updateProjectionMatrix()}copy(t,e){return super.copy(t,e),this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.near=t.near,this.far=t.far,this.zoom=t.zoom,this.view=null===t.view?null:Object.assign({},t.view),this}setViewOffset(t,e,n,i,r,s){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=t,this.view.fullHeight=e,this.view.offsetX=n,this.view.offsetY=i,this.view.width=r,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const t=(this.right-this.left)/(2*this.zoom),e=(this.top-this.bottom)/(2*this.zoom),n=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=n-t,s=n+t,a=i+e,o=i-e;if(null!==this.view&&this.view.enabled){const t=(this.right-this.left)/this.view.fullWidth/this.zoom,e=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=t*this.view.offsetX,s=r+t*this.view.width,a-=e*this.view.offsetY,o=a-e*this.view.height}this.projectionMatrix.makeOrthographic(r,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(t){const e=super.toJSON(t);return e.object.zoom=this.zoom,e.object.left=this.left,e.object.right=this.right,e.object.top=this.top,e.object.bottom=this.bottom,e.object.near=this.near,e.object.far=this.far,null!==this.view&&(e.object.view=Object.assign({},this.view)),e}}const Aa=[.125,.215,.35,.446,.526,.582],Ra=20,Ca=new Ea,Pa=new ts;let Ia=null,La=0,Ua=0,Na=!1;const Da=(1+Math.sqrt(5))/2,Oa=1/Da,Fa=[new Li(-Da,Oa,0),new Li(Da,Oa,0),new Li(-Oa,0,Da),new Li(Oa,0,Da),new Li(0,Da,-Oa),new Li(0,Da,Oa),new Li(-1,1,-1),new Li(1,1,-1),new Li(-1,1,1),new Li(1,1,1)];class Ba{constructor(t){this._renderer=t,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(t,e=0,n=.1,i=100){Ia=this._renderer.getRenderTarget(),La=this._renderer.getActiveCubeFace(),Ua=this._renderer.getActiveMipmapLevel(),Na=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);const r=this._allocateTargets();return r.depthBuffer=!0,this._sceneToCubeUV(t,n,i,r),e>0&&this._blur(r,0,0,e),this._applyPMREM(r),this._cleanup(r),r}fromEquirectangular(t,e=null){return this._fromTexture(t,e)}fromCubemap(t,e=null){return this._fromTexture(t,e)}compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=Ha(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=Va(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose()}_setSize(t){this._lodMax=Math.floor(Math.log2(t)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let t=0;tt-4?o=Aa[a-t+4-1]:0===a&&(o=0),i.push(o);const l=1/(s-2),c=-l,h=1+l,u=[c,c,h,c,h,h,c,c,h,h,c,h],d=6,p=6,m=3,f=2,g=1,v=new Float32Array(m*p*d),_=new Float32Array(f*p*d),x=new Float32Array(g*p*d);for(let t=0;t2?0:-1,i=[e,n,0,e+2/3,n,0,e+2/3,n+1,0,e,n,0,e+2/3,n+1,0,e,n+1,0];v.set(i,m*p*t),_.set(u,f*p*t);const r=[t,t,t,t,t,t];x.set(r,g*p*t)}const y=new Cs;y.setAttribute("position",new ds(v,m)),y.setAttribute("uv",new ds(_,f)),y.setAttribute("faceIndex",new ds(x,g)),e.push(y),r>4&&r--}return{lodPlanes:e,sizeLods:n,sigmas:i}}(i)),this._blurMaterial=function(t,e,n){const i=new Float32Array(Ra),r=new Li(0,1,0),s=new Ys({name:"SphericalGaussianBlur",defines:{n:Ra,CUBEUV_TEXEL_WIDTH:1/e,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${t}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:r}},vertexShader:Ga(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include \n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1});return s}(i,t,e)}return i}_compileMaterial(t){const e=new Vs(this._lodPlanes[0],t);this._renderer.compile(e,Ca)}_sceneToCubeUV(t,e,n,i){const r=new Qs(90,1,e,n),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(Pa),o.toneMapping=K,o.autoClear=!1;const h=new rs({name:"PMREM.Background",side:d,depthWrite:!1,depthTest:!1}),u=new Vs(new Gs,h);let p=!1;const m=t.background;m?m.isColor&&(h.color.copy(m),t.background=null,p=!0):(h.color.copy(Pa),p=!0);for(let e=0;e<6;e++){const n=e%3;0===n?(r.up.set(0,s[e],0),r.lookAt(a[e],0,0)):1===n?(r.up.set(0,0,s[e]),r.lookAt(0,a[e],0)):(r.up.set(0,s[e],0),r.lookAt(0,0,a[e]));const l=this._cubeSize;ka(i,n*l,e>2?l:0,l,l),o.setRenderTarget(i),p&&o.render(u,r),o.render(t,r)}u.geometry.dispose(),u.material.dispose(),o.toneMapping=c,o.autoClear=l,t.background=m}_textureToCubeUV(t,e){const n=this._renderer,i=t.mapping===lt||t.mapping===ct;i?(null===this._cubemapMaterial&&(this._cubemapMaterial=Ha()),this._cubemapMaterial.uniforms.flipEnvMap.value=!1===t.isRenderTargetTexture?-1:1):null===this._equirectMaterial&&(this._equirectMaterial=Va());const r=i?this._cubemapMaterial:this._equirectMaterial,s=new Vs(this._lodPlanes[0],r);r.uniforms.envMap.value=t;const a=this._cubeSize;ka(e,0,0,3*a,2*a),n.setRenderTarget(e),n.render(s,Ca)}_applyPMREM(t){const e=this._renderer,n=e.autoClear;e.autoClear=!1;const i=this._lodPlanes.length;for(let e=1;eRa&&console.warn(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let t=0;tv-4?i-v+4:0),4*(this._cubeSize-_),3*_,2*_),o.setRenderTarget(e),o.render(c,Ca)}}function za(t,e,n){const i=new Ei(t,e,n);return i.texture.mapping=dt,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function ka(t,e,n,i,r){t.viewport.set(e,n,i,r),t.scissor.set(e,n,i,r)}function Va(){return new Ys({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Ga(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\n\t\t\t#include \n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tgl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ha(){return new Ys({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Ga(),fragmentShader:"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tuniform float flipEnvMap;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );\n\n\t\t\t}\n\t\t",blending:0,depthTest:!1,depthWrite:!1})}function Ga(){return"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t"}function Wa(t){let e=new WeakMap,n=null;function i(t){const n=t.target;n.removeEventListener("dispose",i);const r=e.get(n);void 0!==r&&(e.delete(n),r.dispose())}return{get:function(r){if(r&&r.isTexture){const s=r.mapping,a=s===ht||s===ut,o=s===lt||s===ct;if(a||o){let s=e.get(r);const l=void 0!==s?s.texture.pmremVersion:0;if(r.isRenderTargetTexture&&r.pmremVersion!==l)return null===n&&(n=new Ba(t)),s=a?n.fromEquirectangular(r,s):n.fromCubemap(r,s),s.texture.pmremVersion=r.pmremVersion,e.set(r,s),s.texture;if(void 0!==s)return s.texture;{const l=r.image;return a&&l&&l.height>0||o&&l&&function(t){let e=0;const n=6;for(let i=0;ie.maxTextureSize&&(y=Math.ceil(x/e.maxTextureSize),x=e.maxTextureSize);const M=new Float32Array(x*y*4*h),S=new Ai(M,x,y,h);S.type=Lt,S.needsUpdate=!0;const b=4*_;for(let T=0;T0)return t;const r=e*n;let s=io[r];if(void 0===s&&(s=new Float32Array(r),io[r]=s),0!==e){i.toArray(s,0);for(let i=1,r=0;i!==e;++i)r+=n,t[i].toArray(s,r)}return s}function co(t,e){if(t.length!==e.length)return!1;for(let n=0,i=t.length;n":" "} ${r}: ${n[t]}`)}return i.join("\n")}(t.getShaderSource(e),i)}return r}function ll(t,e){const n=function(t){const e=mi.getPrimaries(mi.workingColorSpace),n=mi.getPrimaries(t);let i;switch(e===n?i="":e===rn&&n===nn?i="LinearDisplayP3ToLinearSRGB":e===nn&&n===rn&&(i="LinearSRGBToLinearDisplayP3"),t){case Ke:case Qe:return[i,"LinearTransferOETF"];case Je:case $e:return[i,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space:",t),[i,"LinearTransferOETF"]}}(e);return`vec4 ${t}( vec4 value ) { return ${n[0]}( ${n[1]}( value ) ); }`}function cl(t,e){let n;switch(e){case $:n="Linear";break;case Q:n="Reinhard";break;case tt:n="Cineon";break;case et:n="ACESFilmic";break;case it:n="AgX";break;case rt:n="Neutral";break;case nt:n="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",e),n="Linear"}return"vec3 "+t+"( vec3 color ) { return "+n+"ToneMapping( color ); }"}const hl=new Li;function ul(){mi.getLuminanceCoefficients(hl);return["float luminance( const in vec3 rgb ) {",`\tconst vec3 weights = vec3( ${hl.x.toFixed(4)}, ${hl.y.toFixed(4)}, ${hl.z.toFixed(4)} );`,"\treturn dot( weights, rgb );","}"].join("\n")}function dl(t){return""!==t}function pl(t,e){const n=e.numSpotLightShadows+e.numSpotLightMaps-e.numSpotLightShadowsWithMaps;return t.replace(/NUM_DIR_LIGHTS/g,e.numDirLights).replace(/NUM_SPOT_LIGHTS/g,e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,n).replace(/NUM_RECT_AREA_LIGHTS/g,e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,e.numPointLights).replace(/NUM_HEMI_LIGHTS/g,e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,e.numPointLightShadows)}function ml(t,e){return t.replace(/NUM_CLIPPING_PLANES/g,e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,e.numClippingPlanes-e.numClipIntersection)}const fl=/^[ \t]*#include +<([\w\d./]+)>/gm;function gl(t){return t.replace(fl,_l)}const vl=new Map;function _l(t,e){let n=ma[e];if(void 0===n){const t=vl.get(e);if(void 0===t)throw new Error("Can not resolve #include <"+e+">");n=ma[t],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',e,t)}return gl(n)}const xl=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function yl(t){return t.replace(xl,Ml)}function Ml(t,e,n,i){let r="";for(let t=parseInt(e);t0&&(x+="\n"),y=["#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v].filter(dl).join("\n"),y.length>0&&(y+="\n")):(x=[Sl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",n.batching?"#define USE_BATCHING":"",n.batchingColor?"#define USE_BATCHING_COLOR":"",n.instancing?"#define USE_INSTANCING":"",n.instancingColor?"#define USE_INSTANCING_COLOR":"",n.instancingMorph?"#define USE_INSTANCING_MORPH":"",n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.map?"#define USE_MAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+p:"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.displacementMap?"#define USE_DISPLACEMENTMAP":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.mapUv?"#define MAP_UV "+n.mapUv:"",n.alphaMapUv?"#define ALPHAMAP_UV "+n.alphaMapUv:"",n.lightMapUv?"#define LIGHTMAP_UV "+n.lightMapUv:"",n.aoMapUv?"#define AOMAP_UV "+n.aoMapUv:"",n.emissiveMapUv?"#define EMISSIVEMAP_UV "+n.emissiveMapUv:"",n.bumpMapUv?"#define BUMPMAP_UV "+n.bumpMapUv:"",n.normalMapUv?"#define NORMALMAP_UV "+n.normalMapUv:"",n.displacementMapUv?"#define DISPLACEMENTMAP_UV "+n.displacementMapUv:"",n.metalnessMapUv?"#define METALNESSMAP_UV "+n.metalnessMapUv:"",n.roughnessMapUv?"#define ROUGHNESSMAP_UV "+n.roughnessMapUv:"",n.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+n.anisotropyMapUv:"",n.clearcoatMapUv?"#define CLEARCOATMAP_UV "+n.clearcoatMapUv:"",n.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+n.clearcoatNormalMapUv:"",n.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+n.clearcoatRoughnessMapUv:"",n.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+n.iridescenceMapUv:"",n.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+n.iridescenceThicknessMapUv:"",n.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+n.sheenColorMapUv:"",n.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+n.sheenRoughnessMapUv:"",n.specularMapUv?"#define SPECULARMAP_UV "+n.specularMapUv:"",n.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+n.specularColorMapUv:"",n.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+n.specularIntensityMapUv:"",n.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+n.transmissionMapUv:"",n.thicknessMapUv?"#define THICKNESSMAP_UV "+n.thicknessMapUv:"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.flatShading?"#define FLAT_SHADED":"",n.skinning?"#define USE_SKINNING":"",n.morphTargets?"#define USE_MORPHTARGETS":"",n.morphNormals&&!1===n.flatShading?"#define USE_MORPHNORMALS":"",n.morphColors?"#define USE_MORPHCOLORS":"",n.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+n.morphTextureStride:"",n.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+n.morphTargetsCount:"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+u:"",n.sizeAttenuation?"#define USE_SIZEATTENUATION":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","\tattribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","\tattribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","\tuniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","\tattribute vec2 uv1;","#endif","#ifdef USE_UV2","\tattribute vec2 uv2;","#endif","#ifdef USE_UV3","\tattribute vec2 uv3;","#endif","#ifdef USE_TANGENT","\tattribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","\tattribute vec4 color;","#elif defined( USE_COLOR )","\tattribute vec3 color;","#endif","#ifdef USE_SKINNING","\tattribute vec4 skinIndex;","\tattribute vec4 skinWeight;","#endif","\n"].filter(dl).join("\n"),y=[Sl(n),"#define SHADER_TYPE "+n.shaderType,"#define SHADER_NAME "+n.shaderName,v,n.useFog&&n.fog?"#define USE_FOG":"",n.useFog&&n.fogExp2?"#define FOG_EXP2":"",n.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",n.map?"#define USE_MAP":"",n.matcap?"#define USE_MATCAP":"",n.envMap?"#define USE_ENVMAP":"",n.envMap?"#define "+d:"",n.envMap?"#define "+p:"",n.envMap?"#define "+m:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",n.lightMap?"#define USE_LIGHTMAP":"",n.aoMap?"#define USE_AOMAP":"",n.bumpMap?"#define USE_BUMPMAP":"",n.normalMap?"#define USE_NORMALMAP":"",n.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",n.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",n.emissiveMap?"#define USE_EMISSIVEMAP":"",n.anisotropy?"#define USE_ANISOTROPY":"",n.anisotropyMap?"#define USE_ANISOTROPYMAP":"",n.clearcoat?"#define USE_CLEARCOAT":"",n.clearcoatMap?"#define USE_CLEARCOATMAP":"",n.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",n.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",n.dispersion?"#define USE_DISPERSION":"",n.iridescence?"#define USE_IRIDESCENCE":"",n.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",n.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",n.specularMap?"#define USE_SPECULARMAP":"",n.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",n.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",n.roughnessMap?"#define USE_ROUGHNESSMAP":"",n.metalnessMap?"#define USE_METALNESSMAP":"",n.alphaMap?"#define USE_ALPHAMAP":"",n.alphaTest?"#define USE_ALPHATEST":"",n.alphaHash?"#define USE_ALPHAHASH":"",n.sheen?"#define USE_SHEEN":"",n.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",n.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",n.transmission?"#define USE_TRANSMISSION":"",n.transmissionMap?"#define USE_TRANSMISSIONMAP":"",n.thicknessMap?"#define USE_THICKNESSMAP":"",n.vertexTangents&&!1===n.flatShading?"#define USE_TANGENT":"",n.vertexColors||n.instancingColor||n.batchingColor?"#define USE_COLOR":"",n.vertexAlphas?"#define USE_COLOR_ALPHA":"",n.vertexUv1s?"#define USE_UV1":"",n.vertexUv2s?"#define USE_UV2":"",n.vertexUv3s?"#define USE_UV3":"",n.pointsUvs?"#define USE_POINTS_UV":"",n.gradientMap?"#define USE_GRADIENTMAP":"",n.flatShading?"#define FLAT_SHADED":"",n.doubleSided?"#define DOUBLE_SIDED":"",n.flipSided?"#define FLIP_SIDED":"",n.shadowMapEnabled?"#define USE_SHADOWMAP":"",n.shadowMapEnabled?"#define "+u:"",n.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",n.numLightProbes>0?"#define USE_LIGHT_PROBES":"",n.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",n.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",n.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",n.toneMapping!==K?"#define TONE_MAPPING":"",n.toneMapping!==K?ma.tonemapping_pars_fragment:"",n.toneMapping!==K?cl("toneMapping",n.toneMapping):"",n.dithering?"#define DITHERING":"",n.opaque?"#define OPAQUE":"",ma.colorspace_pars_fragment,ll("linearToOutputTexel",n.outputColorSpace),ul(),n.useDepthPacking?"#define DEPTH_PACKING "+n.depthPacking:"","\n"].filter(dl).join("\n")),a=gl(a),a=pl(a,n),a=ml(a,n),o=gl(o),o=pl(o,n),o=ml(o,n),a=yl(a),o=yl(o),!0!==n.isRawShaderMaterial&&(M="#version 300 es\n",x=[g,"#define attribute in","#define varying out","#define texture2D texture"].join("\n")+"\n"+x,y=["#define varying in",n.glslVersion===zn?"":"layout(location = 0) out highp vec4 pc_fragColor;",n.glslVersion===zn?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join("\n")+"\n"+y);const S=M+x+a,b=M+y+o,w=rl(r,r.VERTEX_SHADER,S),T=rl(r,r.FRAGMENT_SHADER,b);function E(e){if(t.debug.checkShaderErrors){const n=r.getProgramInfoLog(_).trim(),i=r.getShaderInfoLog(w).trim(),s=r.getShaderInfoLog(T).trim();let a=!0,o=!0;if(!1===r.getProgramParameter(_,r.LINK_STATUS))if(a=!1,"function"==typeof t.debug.onShaderError)t.debug.onShaderError(r,_,w,T);else{const t=ol(r,w,"vertex"),i=ol(r,T,"fragment");console.error("THREE.WebGLProgram: Shader Error "+r.getError()+" - VALIDATE_STATUS "+r.getProgramParameter(_,r.VALIDATE_STATUS)+"\n\nMaterial Name: "+e.name+"\nMaterial Type: "+e.type+"\n\nProgram Info Log: "+n+"\n"+t+"\n"+i)}else""!==n?console.warn("THREE.WebGLProgram: Program Info Log:",n):""!==i&&""!==s||(o=!1);o&&(e.diagnostics={runnable:a,programLog:n,vertexShader:{log:i,prefix:x},fragmentShader:{log:s,prefix:y}})}r.deleteShader(w),r.deleteShader(T),A=new il(r,_),R=function(t,e){const n={},i=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES);for(let r=0;r0,Y=s.clearcoat>0,Z=s.dispersion>0,J=s.iridescence>0,$=s.sheen>0,Q=s.transmission>0,tt=q&&!!s.anisotropyMap,et=Y&&!!s.clearcoatMap,nt=Y&&!!s.clearcoatNormalMap,it=Y&&!!s.clearcoatRoughnessMap,rt=J&&!!s.iridescenceMap,st=J&&!!s.iridescenceThicknessMap,at=$&&!!s.sheenColorMap,ot=$&&!!s.sheenRoughnessMap,lt=!!s.specularMap,ct=!!s.specularColorMap,ht=!!s.specularIntensityMap,ut=Q&&!!s.transmissionMap,pt=Q&&!!s.thicknessMap,mt=!!s.gradientMap,ft=!!s.alphaMap,gt=s.alphaTest>0,vt=!!s.alphaHash,_t=!!s.extensions;let xt=K;s.toneMapped&&(null!==U&&!0!==U.isXRRenderTarget||(xt=t.toneMapping));const yt={shaderID:T,shaderType:s.type,shaderName:s.name,vertexShader:R,fragmentShader:C,defines:s.defines,customVertexShaderID:P,customFragmentShaderID:I,isRawShaderMaterial:!0===s.isRawShaderMaterial,glslVersion:s.glslVersion,precision:f,batching:D,batchingColor:D&&null!==x._colorsTexture,instancing:N,instancingColor:N&&null!==x.instanceColor,instancingMorph:N&&null!==x.morphTexture,supportsVertexTextures:m,outputColorSpace:null===U?t.outputColorSpace:!0===U.isXRRenderTarget?U.texture.colorSpace:Ke,alphaToCoverage:!!s.alphaToCoverage,map:O,matcap:F,envMap:B,envMapMode:B&&b.mapping,envMapCubeUVHeight:w,aoMap:z,lightMap:k,bumpMap:V,normalMap:H,displacementMap:m&&G,emissiveMap:W,normalMapObjectSpace:H&&1===s.normalMapType,normalMapTangentSpace:H&&0===s.normalMapType,metalnessMap:X,roughnessMap:j,anisotropy:q,anisotropyMap:tt,clearcoat:Y,clearcoatMap:et,clearcoatNormalMap:nt,clearcoatRoughnessMap:it,dispersion:Z,iridescence:J,iridescenceMap:rt,iridescenceThicknessMap:st,sheen:$,sheenColorMap:at,sheenRoughnessMap:ot,specularMap:lt,specularColorMap:ct,specularIntensityMap:ht,transmission:Q,transmissionMap:ut,thicknessMap:pt,gradientMap:mt,opaque:!1===s.transparent&&1===s.blending&&!1===s.alphaToCoverage,alphaMap:ft,alphaTest:gt,alphaHash:vt,combine:s.combine,mapUv:O&&v(s.map.channel),aoMapUv:z&&v(s.aoMap.channel),lightMapUv:k&&v(s.lightMap.channel),bumpMapUv:V&&v(s.bumpMap.channel),normalMapUv:H&&v(s.normalMap.channel),displacementMapUv:G&&v(s.displacementMap.channel),emissiveMapUv:W&&v(s.emissiveMap.channel),metalnessMapUv:X&&v(s.metalnessMap.channel),roughnessMapUv:j&&v(s.roughnessMap.channel),anisotropyMapUv:tt&&v(s.anisotropyMap.channel),clearcoatMapUv:et&&v(s.clearcoatMap.channel),clearcoatNormalMapUv:nt&&v(s.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:it&&v(s.clearcoatRoughnessMap.channel),iridescenceMapUv:rt&&v(s.iridescenceMap.channel),iridescenceThicknessMapUv:st&&v(s.iridescenceThicknessMap.channel),sheenColorMapUv:at&&v(s.sheenColorMap.channel),sheenRoughnessMapUv:ot&&v(s.sheenRoughnessMap.channel),specularMapUv:lt&&v(s.specularMap.channel),specularColorMapUv:ct&&v(s.specularColorMap.channel),specularIntensityMapUv:ht&&v(s.specularIntensityMap.channel),transmissionMapUv:ut&&v(s.transmissionMap.channel),thicknessMapUv:pt&&v(s.thicknessMap.channel),alphaMapUv:ft&&v(s.alphaMap.channel),vertexTangents:!!M.attributes.tangent&&(H||q),vertexColors:s.vertexColors,vertexAlphas:!0===s.vertexColors&&!!M.attributes.color&&4===M.attributes.color.itemSize,pointsUvs:!0===x.isPoints&&!!M.attributes.uv&&(O||ft),fog:!!y,useFog:!0===s.fog,fogExp2:!!y&&y.isFogExp2,flatShading:!0===s.flatShading,sizeAttenuation:!0===s.sizeAttenuation,logarithmicDepthBuffer:u,reverseDepthBuffer:p,skinning:!0===x.isSkinnedMesh,morphTargets:void 0!==M.morphAttributes.position,morphNormals:void 0!==M.morphAttributes.normal,morphColors:void 0!==M.morphAttributes.color,morphTargetsCount:A,morphTextureStride:L,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:s.dithering,shadowMapEnabled:t.shadowMap.enabled&&h.length>0,shadowMapType:t.shadowMap.type,toneMapping:xt,decodeVideoTexture:O&&!0===s.map.isVideoTexture&&mi.getTransfer(s.map.colorSpace)===en,premultipliedAlpha:s.premultipliedAlpha,doubleSided:2===s.side,flipSided:s.side===d,useDepthPacking:s.depthPacking>=0,depthPacking:s.depthPacking||0,index0AttributeName:s.index0AttributeName,extensionClipCullDistance:_t&&!0===s.extensions.clipCullDistance&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(_t&&!0===s.extensions.multiDraw||D)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:s.customProgramCacheKey()};return yt.vertexUv1s=c.has(1),yt.vertexUv2s=c.has(2),yt.vertexUv3s=c.has(3),c.clear(),yt},getProgramCacheKey:function(e){const n=[];if(e.shaderID?n.push(e.shaderID):(n.push(e.customVertexShaderID),n.push(e.customFragmentShaderID)),void 0!==e.defines)for(const t in e.defines)n.push(t),n.push(e.defines[t]);return!1===e.isRawShaderMaterial&&(!function(t,e){t.push(e.precision),t.push(e.outputColorSpace),t.push(e.envMapMode),t.push(e.envMapCubeUVHeight),t.push(e.mapUv),t.push(e.alphaMapUv),t.push(e.lightMapUv),t.push(e.aoMapUv),t.push(e.bumpMapUv),t.push(e.normalMapUv),t.push(e.displacementMapUv),t.push(e.emissiveMapUv),t.push(e.metalnessMapUv),t.push(e.roughnessMapUv),t.push(e.anisotropyMapUv),t.push(e.clearcoatMapUv),t.push(e.clearcoatNormalMapUv),t.push(e.clearcoatRoughnessMapUv),t.push(e.iridescenceMapUv),t.push(e.iridescenceThicknessMapUv),t.push(e.sheenColorMapUv),t.push(e.sheenRoughnessMapUv),t.push(e.specularMapUv),t.push(e.specularColorMapUv),t.push(e.specularIntensityMapUv),t.push(e.transmissionMapUv),t.push(e.thicknessMapUv),t.push(e.combine),t.push(e.fogExp2),t.push(e.sizeAttenuation),t.push(e.morphTargetsCount),t.push(e.morphAttributeCount),t.push(e.numDirLights),t.push(e.numPointLights),t.push(e.numSpotLights),t.push(e.numSpotLightMaps),t.push(e.numHemiLights),t.push(e.numRectAreaLights),t.push(e.numDirLightShadows),t.push(e.numPointLightShadows),t.push(e.numSpotLightShadows),t.push(e.numSpotLightShadowsWithMaps),t.push(e.numLightProbes),t.push(e.shadowMapType),t.push(e.toneMapping),t.push(e.numClippingPlanes),t.push(e.numClipIntersection),t.push(e.depthPacking)}(n,e),function(t,e){o.disableAll(),e.supportsVertexTextures&&o.enable(0);e.instancing&&o.enable(1);e.instancingColor&&o.enable(2);e.instancingMorph&&o.enable(3);e.matcap&&o.enable(4);e.envMap&&o.enable(5);e.normalMapObjectSpace&&o.enable(6);e.normalMapTangentSpace&&o.enable(7);e.clearcoat&&o.enable(8);e.iridescence&&o.enable(9);e.alphaTest&&o.enable(10);e.vertexColors&&o.enable(11);e.vertexAlphas&&o.enable(12);e.vertexUv1s&&o.enable(13);e.vertexUv2s&&o.enable(14);e.vertexUv3s&&o.enable(15);e.vertexTangents&&o.enable(16);e.anisotropy&&o.enable(17);e.alphaHash&&o.enable(18);e.batching&&o.enable(19);e.dispersion&&o.enable(20);e.batchingColor&&o.enable(21);t.push(o.mask),o.disableAll(),e.fog&&o.enable(0);e.useFog&&o.enable(1);e.flatShading&&o.enable(2);e.logarithmicDepthBuffer&&o.enable(3);e.reverseDepthBuffer&&o.enable(4);e.skinning&&o.enable(5);e.morphTargets&&o.enable(6);e.morphNormals&&o.enable(7);e.morphColors&&o.enable(8);e.premultipliedAlpha&&o.enable(9);e.shadowMapEnabled&&o.enable(10);e.doubleSided&&o.enable(11);e.flipSided&&o.enable(12);e.useDepthPacking&&o.enable(13);e.dithering&&o.enable(14);e.transmission&&o.enable(15);e.sheen&&o.enable(16);e.opaque&&o.enable(17);e.pointsUvs&&o.enable(18);e.decodeVideoTexture&&o.enable(19);e.alphaToCoverage&&o.enable(20);t.push(o.mask)}(n,e),n.push(t.outputColorSpace)),n.push(e.customProgramCacheKey),n.join()},getUniforms:function(t){const e=g[t.type];let n;if(e){const t=ga[e];n=qs.clone(t.uniforms)}else n=t.uniforms;return n},acquireProgram:function(e,n){let i;for(let t=0,e=h.length;t0?i.push(h):!0===a.transparent?r.push(h):n.push(h)},unshift:function(t,e,a,o,l,c){const h=s(t,e,a,o,l,c);a.transmission>0?i.unshift(h):!0===a.transparent?r.unshift(h):n.unshift(h)},finish:function(){for(let n=e,i=t.length;n1&&n.sort(t||Cl),i.length>1&&i.sort(e||Pl),r.length>1&&r.sort(e||Pl)}}}function Ll(){let t=new WeakMap;return{get:function(e,n){const i=t.get(e);let r;return void 0===i?(r=new Il,t.set(e,[r])):n>=i.length?(r=new Il,i.push(r)):r=i[n],r},dispose:function(){t=new WeakMap}}}function Ul(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":n={direction:new Li,color:new ts};break;case"SpotLight":n={position:new Li,direction:new Li,color:new ts,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":n={position:new Li,color:new ts,distance:0,decay:0};break;case"HemisphereLight":n={direction:new Li,skyColor:new ts,groundColor:new ts};break;case"RectAreaLight":n={color:new ts,position:new Li,halfWidth:new Li,halfHeight:new Li}}return t[e.id]=n,n}}}let Nl=0;function Dl(t,e){return(e.castShadow?2:0)-(t.castShadow?2:0)+(e.map?1:0)-(t.map?1:0)}function Ol(t){const e=new Ul,n=function(){const t={};return{get:function(e){if(void 0!==t[e.id])return t[e.id];let n;switch(e.type){case"DirectionalLight":case"SpotLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ti};break;case"PointLight":n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ti,shadowCameraNear:1,shadowCameraFar:1e3}}return t[e.id]=n,n}}}(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let t=0;t<9;t++)i.probe.push(new Li);const r=new Li,s=new lr,a=new lr;return{setup:function(r){let s=0,a=0,o=0;for(let t=0;t<9;t++)i.probe[t].set(0,0,0);let l=0,c=0,h=0,u=0,d=0,p=0,m=0,f=0,g=0,v=0,_=0;r.sort(Dl);for(let t=0,x=r.length;t0&&(!0===t.has("OES_texture_float_linear")?(i.rectAreaLTC1=fa.LTC_FLOAT_1,i.rectAreaLTC2=fa.LTC_FLOAT_2):(i.rectAreaLTC1=fa.LTC_HALF_1,i.rectAreaLTC2=fa.LTC_HALF_2)),i.ambient[0]=s,i.ambient[1]=a,i.ambient[2]=o;const x=i.hash;x.directionalLength===l&&x.pointLength===c&&x.spotLength===h&&x.rectAreaLength===u&&x.hemiLength===d&&x.numDirectionalShadows===p&&x.numPointShadows===m&&x.numSpotShadows===f&&x.numSpotMaps===g&&x.numLightProbes===_||(i.directional.length=l,i.spot.length=h,i.rectArea.length=u,i.point.length=c,i.hemi.length=d,i.directionalShadow.length=p,i.directionalShadowMap.length=p,i.pointShadow.length=m,i.pointShadowMap.length=m,i.spotShadow.length=f,i.spotShadowMap.length=f,i.directionalShadowMatrix.length=p,i.pointShadowMatrix.length=m,i.spotLightMatrix.length=f+g-v,i.spotLightMap.length=g,i.numSpotLightShadowsWithMaps=v,i.numLightProbes=_,x.directionalLength=l,x.pointLength=c,x.spotLength=h,x.rectAreaLength=u,x.hemiLength=d,x.numDirectionalShadows=p,x.numPointShadows=m,x.numSpotShadows=f,x.numSpotMaps=g,x.numLightProbes=_,i.version=Nl++)},setupView:function(t,e){let n=0,o=0,l=0,c=0,h=0;const u=e.matrixWorldInverse;for(let e=0,d=t.length;e=r.length?(s=new Fl(t),r.push(s)):s=r[i],s},dispose:function(){e=new WeakMap}}}class zl extends is{constructor(t){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=3200,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(t)}copy(t){return super.copy(t),this.depthPacking=t.depthPacking,this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this}}class kl extends is{constructor(t){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(t)}copy(t){return super.copy(t),this.map=t.map,this.alphaMap=t.alphaMap,this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this}}function Vl(t,e,n){let i=new ha;const r=new ti,s=new ti,a=new wi,o=new zl({depthPacking:3201}),c=new kl,p={},m=n.maxTextureSize,f={[u]:d,[d]:u,2:2},g=new Ys({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ti},radius:{value:4}},vertexShader:"void main() {\n\tgl_Position = vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include \nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}"}),v=g.clone();v.defines.HORIZONTAL_PASS=1;const _=new Cs;_.setAttribute("position",new ds(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const x=new Vs(_,g),y=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=l;let M=this.type;function S(n,i){const s=e.update(x);g.defines.VSM_SAMPLES!==n.blurSamples&&(g.defines.VSM_SAMPLES=n.blurSamples,v.defines.VSM_SAMPLES=n.blurSamples,g.needsUpdate=!0,v.needsUpdate=!0),null===n.mapPass&&(n.mapPass=new Ei(r.x,r.y)),g.uniforms.shadow_pass.value=n.map.texture,g.uniforms.resolution.value=n.mapSize,g.uniforms.radius.value=n.radius,t.setRenderTarget(n.mapPass),t.clear(),t.renderBufferDirect(i,null,s,g,x,null),v.uniforms.shadow_pass.value=n.mapPass.texture,v.uniforms.resolution.value=n.mapSize,v.uniforms.radius.value=n.radius,t.setRenderTarget(n.map),t.clear(),t.renderBufferDirect(i,null,s,v,x,null)}function b(e,n,i,r){let s=null;const a=!0===i.isPointLight?e.customDistanceMaterial:e.customDepthMaterial;if(void 0!==a)s=a;else if(s=!0===i.isPointLight?c:o,t.localClippingEnabled&&!0===n.clipShadows&&Array.isArray(n.clippingPlanes)&&0!==n.clippingPlanes.length||n.displacementMap&&0!==n.displacementScale||n.alphaMap&&n.alphaTest>0||n.map&&n.alphaTest>0){const t=s.uuid,e=n.uuid;let i=p[t];void 0===i&&(i={},p[t]=i);let r=i[e];void 0===r&&(r=s.clone(),i[e]=r,n.addEventListener("dispose",T)),s=r}if(s.visible=n.visible,s.wireframe=n.wireframe,s.side=r===h?null!==n.shadowSide?n.shadowSide:n.side:null!==n.shadowSide?n.shadowSide:f[n.side],s.alphaMap=n.alphaMap,s.alphaTest=n.alphaTest,s.map=n.map,s.clipShadows=n.clipShadows,s.clippingPlanes=n.clippingPlanes,s.clipIntersection=n.clipIntersection,s.displacementMap=n.displacementMap,s.displacementScale=n.displacementScale,s.displacementBias=n.displacementBias,s.wireframeLinewidth=n.wireframeLinewidth,s.linewidth=n.linewidth,!0===i.isPointLight&&!0===s.isMeshDistanceMaterial){t.properties.get(s).light=i}return s}function w(n,r,s,a,o){if(!1===n.visible)return;if(n.layers.test(r.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&o===h)&&(!n.frustumCulled||i.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,n.matrixWorld);const i=e.update(n),l=n.material;if(Array.isArray(l)){const e=i.groups;for(let c=0,h=e.length;cm||r.y>m)&&(r.x>m&&(s.x=Math.floor(m/g.x),r.x=s.x*g.x,u.mapSize.x=s.x),r.y>m&&(s.y=Math.floor(m/g.y),r.y=s.y*g.y,u.mapSize.y=s.y)),null===u.map||!0===p||!0===f){const t=this.type!==h?{minFilter:gt,magFilter:gt}:{};null!==u.map&&u.map.dispose(),u.map=new Ei(r.x,r.y,t),u.map.texture.name=c.name+".shadowMap",u.camera.updateProjectionMatrix()}t.setRenderTarget(u.map),t.clear();const v=u.getViewportCount();for(let t=0;t=1):-1!==N.indexOf("OpenGL ES")&&(U=parseFloat(/^OpenGL ES (\d)/.exec(N)[1]),L=U>=2);let D=null,O={};const F=t.getParameter(t.SCISSOR_BOX),B=t.getParameter(t.VIEWPORT),z=(new wi).fromArray(F),k=(new wi).fromArray(B);function V(e,n,i,r){const s=new Uint8Array(4),a=t.createTexture();t.bindTexture(e,a),t.texParameteri(e,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(e,t.TEXTURE_MAG_FILTER,t.NEAREST);for(let a=0;ae?(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2):(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0),t},cover:function(t,e){const n=t.image&&t.image.width?t.image.width/t.image.height:1;return n>e?(t.repeat.x=e/n,t.repeat.y=1,t.offset.x=(1-t.repeat.x)/2,t.offset.y=0):(t.repeat.x=1,t.repeat.y=n/e,t.offset.x=0,t.offset.y=(1-t.repeat.y)/2),t},fill:function(t){return t.repeat.x=1,t.repeat.y=1,t.offset.x=0,t.offset.y=0,t},getByteLength:Wl};function jl(t,e,n,i,r,s,a){const o=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),c=new ti,h=new WeakMap;let u;const d=new WeakMap;let p=!1;try{p="undefined"!=typeof OffscreenCanvas&&null!==new OffscreenCanvas(1,1).getContext("2d")}catch(t){}function m(t,e){return p?new OffscreenCanvas(t,e):ai("canvas")}function f(t,e,n){let i=1;const r=k(t);if((r.width>n||r.height>n)&&(i=n/Math.max(r.width,r.height)),i<1){if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof VideoFrame&&t instanceof VideoFrame){const n=Math.floor(i*r.width),s=Math.floor(i*r.height);void 0===u&&(u=m(n,s));const a=e?m(n,s):u;a.width=n,a.height=s;return a.getContext("2d").drawImage(t,0,0,n,s),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+r.width+"x"+r.height+") to ("+n+"x"+s+")."),a}return"data"in t&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+r.width+"x"+r.height+")."),t}return t}function g(t){return t.generateMipmaps&&t.minFilter!==gt&&t.minFilter!==Mt}function v(e){t.generateMipmap(e)}function _(n,i,r,s,a=!1){if(null!==n){if(void 0!==t[n])return t[n];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+n+"'")}let o=i;if(i===t.RED&&(r===t.FLOAT&&(o=t.R32F),r===t.HALF_FLOAT&&(o=t.R16F),r===t.UNSIGNED_BYTE&&(o=t.R8)),i===t.RED_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.R8UI),r===t.UNSIGNED_SHORT&&(o=t.R16UI),r===t.UNSIGNED_INT&&(o=t.R32UI),r===t.BYTE&&(o=t.R8I),r===t.SHORT&&(o=t.R16I),r===t.INT&&(o=t.R32I)),i===t.RG&&(r===t.FLOAT&&(o=t.RG32F),r===t.HALF_FLOAT&&(o=t.RG16F),r===t.UNSIGNED_BYTE&&(o=t.RG8)),i===t.RG_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RG8UI),r===t.UNSIGNED_SHORT&&(o=t.RG16UI),r===t.UNSIGNED_INT&&(o=t.RG32UI),r===t.BYTE&&(o=t.RG8I),r===t.SHORT&&(o=t.RG16I),r===t.INT&&(o=t.RG32I)),i===t.RGB_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGB8UI),r===t.UNSIGNED_SHORT&&(o=t.RGB16UI),r===t.UNSIGNED_INT&&(o=t.RGB32UI),r===t.BYTE&&(o=t.RGB8I),r===t.SHORT&&(o=t.RGB16I),r===t.INT&&(o=t.RGB32I)),i===t.RGBA_INTEGER&&(r===t.UNSIGNED_BYTE&&(o=t.RGBA8UI),r===t.UNSIGNED_SHORT&&(o=t.RGBA16UI),r===t.UNSIGNED_INT&&(o=t.RGBA32UI),r===t.BYTE&&(o=t.RGBA8I),r===t.SHORT&&(o=t.RGBA16I),r===t.INT&&(o=t.RGBA32I)),i===t.RGB&&r===t.UNSIGNED_INT_5_9_9_9_REV&&(o=t.RGB9_E5),i===t.RGBA){const e=a?tn:mi.getTransfer(s);r===t.FLOAT&&(o=t.RGBA32F),r===t.HALF_FLOAT&&(o=t.RGBA16F),r===t.UNSIGNED_BYTE&&(o=e===en?t.SRGB8_ALPHA8:t.RGBA8),r===t.UNSIGNED_SHORT_4_4_4_4&&(o=t.RGBA4),r===t.UNSIGNED_SHORT_5_5_5_1&&(o=t.RGB5_A1)}return o!==t.R16F&&o!==t.R32F&&o!==t.RG16F&&o!==t.RG32F&&o!==t.RGBA16F&&o!==t.RGBA32F||e.get("EXT_color_buffer_float"),o}function x(e,n){let i;return e?null===n||n===It||n===Ot?i=t.DEPTH24_STENCIL8:n===Lt?i=t.DEPTH32F_STENCIL8:n===Ct&&(i=t.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):null===n||n===It||n===Ot?i=t.DEPTH_COMPONENT24:n===Lt?i=t.DEPTH_COMPONENT32F:n===Ct&&(i=t.DEPTH_COMPONENT16),i}function y(t,e){return!0===g(t)||t.isFramebufferTexture&&t.minFilter!==gt&&t.minFilter!==Mt?Math.log2(Math.max(e.width,e.height))+1:void 0!==t.mipmaps&&t.mipmaps.length>0?t.mipmaps.length:t.isCompressedTexture&&Array.isArray(t.image)?e.mipmaps.length:1}function M(t){const e=t.target;e.removeEventListener("dispose",M),function(t){const e=i.get(t);if(void 0===e.__webglInit)return;const n=t.source,r=d.get(n);if(r){const i=r[e.__cacheKey];i.usedTimes--,0===i.usedTimes&&b(t),0===Object.keys(r).length&&d.delete(n)}i.remove(t)}(e),e.isVideoTexture&&h.delete(e)}function S(e){const n=e.target;n.removeEventListener("dispose",S),function(e){const n=i.get(e);e.depthTexture&&e.depthTexture.dispose();if(e.isWebGLCubeRenderTarget)for(let e=0;e<6;e++){if(Array.isArray(n.__webglFramebuffer[e]))for(let i=0;i0&&s.__version!==e.version){const t=e.image;if(null===t)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else{if(!1!==t.complete)return void I(s,e,r);console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete")}}n.bindTexture(t.TEXTURE_2D,s.__webglTexture,t.TEXTURE0+r)}const E={[pt]:t.REPEAT,[mt]:t.CLAMP_TO_EDGE,[ft]:t.MIRRORED_REPEAT},A={[gt]:t.NEAREST,[vt]:t.NEAREST_MIPMAP_NEAREST,[xt]:t.NEAREST_MIPMAP_LINEAR,[Mt]:t.LINEAR,[St]:t.LINEAR_MIPMAP_NEAREST,[wt]:t.LINEAR_MIPMAP_LINEAR},R={512:t.NEVER,519:t.ALWAYS,513:t.LESS,[wn]:t.LEQUAL,514:t.EQUAL,518:t.GEQUAL,516:t.GREATER,517:t.NOTEQUAL};function C(n,s){if(s.type!==Lt||!1!==e.has("OES_texture_float_linear")||s.magFilter!==Mt&&s.magFilter!==St&&s.magFilter!==xt&&s.magFilter!==wt&&s.minFilter!==Mt&&s.minFilter!==St&&s.minFilter!==xt&&s.minFilter!==wt||console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),t.texParameteri(n,t.TEXTURE_WRAP_S,E[s.wrapS]),t.texParameteri(n,t.TEXTURE_WRAP_T,E[s.wrapT]),n!==t.TEXTURE_3D&&n!==t.TEXTURE_2D_ARRAY||t.texParameteri(n,t.TEXTURE_WRAP_R,E[s.wrapR]),t.texParameteri(n,t.TEXTURE_MAG_FILTER,A[s.magFilter]),t.texParameteri(n,t.TEXTURE_MIN_FILTER,A[s.minFilter]),s.compareFunction&&(t.texParameteri(n,t.TEXTURE_COMPARE_MODE,t.COMPARE_REF_TO_TEXTURE),t.texParameteri(n,t.TEXTURE_COMPARE_FUNC,R[s.compareFunction])),!0===e.has("EXT_texture_filter_anisotropic")){if(s.magFilter===gt)return;if(s.minFilter!==xt&&s.minFilter!==wt)return;if(s.type===Lt&&!1===e.has("OES_texture_float_linear"))return;if(s.anisotropy>1||i.get(s).__currentAnisotropy){const a=e.get("EXT_texture_filter_anisotropic");t.texParameterf(n,a.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s.anisotropy,r.getMaxAnisotropy())),i.get(s).__currentAnisotropy=s.anisotropy}}}function P(e,n){let i=!1;void 0===e.__webglInit&&(e.__webglInit=!0,n.addEventListener("dispose",M));const r=n.source;let s=d.get(r);void 0===s&&(s={},d.set(r,s));const o=function(t){const e=[];return e.push(t.wrapS),e.push(t.wrapT),e.push(t.wrapR||0),e.push(t.magFilter),e.push(t.minFilter),e.push(t.anisotropy),e.push(t.internalFormat),e.push(t.format),e.push(t.type),e.push(t.generateMipmaps),e.push(t.premultiplyAlpha),e.push(t.flipY),e.push(t.unpackAlignment),e.push(t.colorSpace),e.join()}(n);if(o!==e.__cacheKey){void 0===s[o]&&(s[o]={texture:t.createTexture(),usedTimes:0},a.memory.textures++,i=!0),s[o].usedTimes++;const r=s[e.__cacheKey];void 0!==r&&(s[e.__cacheKey].usedTimes--,0===r.usedTimes&&b(n)),e.__cacheKey=o,e.__webglTexture=s[o].texture}return i}function I(e,a,o){let l=t.TEXTURE_2D;(a.isDataArrayTexture||a.isCompressedArrayTexture)&&(l=t.TEXTURE_2D_ARRAY),a.isData3DTexture&&(l=t.TEXTURE_3D);const c=P(e,a),h=a.source;n.bindTexture(l,e.__webglTexture,t.TEXTURE0+o);const u=i.get(h);if(h.version!==u.__version||!0===c){n.activeTexture(t.TEXTURE0+o);const e=mi.getPrimaries(mi.workingColorSpace),i=a.colorSpace===Ze?null:mi.getPrimaries(a.colorSpace),d=a.colorSpace===Ze||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,d);let p=f(a.image,!1,r.maxTextureSize);p=z(a,p);const m=s.convert(a.format,a.colorSpace),M=s.convert(a.type);let S,b=_(a.internalFormat,m,M,a.colorSpace,a.isVideoTexture);C(l,a);const w=a.mipmaps,T=!0!==a.isVideoTexture,E=void 0===u.__version||!0===c,A=h.dataReady,R=y(a,p);if(a.isDepthTexture)b=x(a.format===Wt,a.type),E&&(T?n.texStorage2D(t.TEXTURE_2D,1,b,p.width,p.height):n.texImage2D(t.TEXTURE_2D,0,b,p.width,p.height,0,m,M,null));else if(a.isDataTexture)if(w.length>0){T&&E&&n.texStorage2D(t.TEXTURE_2D,R,b,w[0].width,w[0].height);for(let e=0,i=w.length;e0){const i=Wl(S.width,S.height,a.format,a.type);for(const r of a.layerUpdates){const s=S.data.subarray(r*i/S.data.BYTES_PER_ELEMENT,(r+1)*i/S.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,r,S.width,S.height,1,m,s,0,0)}a.clearLayerUpdates()}else n.compressedTexSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,S.width,S.height,p.depth,m,S.data,0,0)}else n.compressedTexImage3D(t.TEXTURE_2D_ARRAY,e,b,S.width,S.height,p.depth,0,S.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else T?A&&n.texSubImage3D(t.TEXTURE_2D_ARRAY,e,0,0,0,S.width,S.height,p.depth,m,M,S.data):n.texImage3D(t.TEXTURE_2D_ARRAY,e,b,S.width,S.height,p.depth,0,m,M,S.data)}else{T&&E&&n.texStorage2D(t.TEXTURE_2D,R,b,w[0].width,w[0].height);for(let e=0,i=w.length;e0){const e=Wl(p.width,p.height,a.format,a.type);for(const i of a.layerUpdates){const r=p.data.subarray(i*e/p.data.BYTES_PER_ELEMENT,(i+1)*e/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,i,p.width,p.height,1,m,M,r)}a.clearLayerUpdates()}else n.texSubImage3D(t.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,M,p.data)}else n.texImage3D(t.TEXTURE_2D_ARRAY,0,b,p.width,p.height,p.depth,0,m,M,p.data);else if(a.isData3DTexture)T?(E&&n.texStorage3D(t.TEXTURE_3D,R,b,p.width,p.height,p.depth),A&&n.texSubImage3D(t.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,M,p.data)):n.texImage3D(t.TEXTURE_3D,0,b,p.width,p.height,p.depth,0,m,M,p.data);else if(a.isFramebufferTexture){if(E)if(T)n.texStorage2D(t.TEXTURE_2D,R,b,p.width,p.height);else{let e=p.width,i=p.height;for(let r=0;r>=1,i>>=1}}else if(w.length>0){if(T&&E){const e=k(w[0]);n.texStorage2D(t.TEXTURE_2D,R,b,e.width,e.height)}for(let e=0,i=w.length;e>h),i=Math.max(1,r.height>>h);c===t.TEXTURE_3D||c===t.TEXTURE_2D_ARRAY?n.texImage3D(c,h,p,e,i,r.depth,0,u,d,null):n.texImage2D(c,h,p,e,i,0,u,d,null)}n.bindFramebuffer(t.FRAMEBUFFER,e),B(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,0,F(r)):(c===t.TEXTURE_2D||c>=t.TEXTURE_CUBE_MAP_POSITIVE_X&&c<=t.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&t.framebufferTexture2D(t.FRAMEBUFFER,l,c,i.get(a).__webglTexture,h),n.bindFramebuffer(t.FRAMEBUFFER,null)}function U(e,n,i){if(t.bindRenderbuffer(t.RENDERBUFFER,e),n.depthBuffer){const r=n.depthTexture,s=r&&r.isDepthTexture?r.type:null,a=x(n.stencilBuffer,s),l=n.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,c=F(n);B(n)?o.renderbufferStorageMultisampleEXT(t.RENDERBUFFER,c,a,n.width,n.height):i?t.renderbufferStorageMultisample(t.RENDERBUFFER,c,a,n.width,n.height):t.renderbufferStorage(t.RENDERBUFFER,a,n.width,n.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,l,t.RENDERBUFFER,e)}else{const e=n.textures;for(let r=0;r{delete r.__boundDepthTexture,delete r.__depthDisposeCallback,t.removeEventListener("dispose",e)};t.addEventListener("dispose",e),r.__depthDisposeCallback=e}r.__boundDepthTexture=t}if(e.depthTexture&&!r.__autoAllocateDepthBuffer){if(s)throw new Error("target.depthTexture not supported in Cube render targets");!function(e,r){if(r&&r.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(n.bindFramebuffer(t.FRAMEBUFFER,e),!r.depthTexture||!r.depthTexture.isDepthTexture)throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");i.get(r.depthTexture).__webglTexture&&r.depthTexture.image.width===r.width&&r.depthTexture.image.height===r.height||(r.depthTexture.image.width=r.width,r.depthTexture.image.height=r.height,r.depthTexture.needsUpdate=!0),T(r.depthTexture,0);const s=i.get(r.depthTexture).__webglTexture,a=F(r);if(r.depthTexture.format===Gt)B(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_ATTACHMENT,t.TEXTURE_2D,s,0);else{if(r.depthTexture.format!==Wt)throw new Error("Unknown depthTexture format");B(r)?o.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0,a):t.framebufferTexture2D(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.TEXTURE_2D,s,0)}}(r.__webglFramebuffer,e)}else if(s){r.__webglDepthbuffer=[];for(let i=0;i<6;i++)if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer[i]),void 0===r.__webglDepthbuffer[i])r.__webglDepthbuffer[i]=t.createRenderbuffer(),U(r.__webglDepthbuffer[i],e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,s=r.__webglDepthbuffer[i];t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,s)}}else if(n.bindFramebuffer(t.FRAMEBUFFER,r.__webglFramebuffer),void 0===r.__webglDepthbuffer)r.__webglDepthbuffer=t.createRenderbuffer(),U(r.__webglDepthbuffer,e,!1);else{const n=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,i=r.__webglDepthbuffer;t.bindRenderbuffer(t.RENDERBUFFER,i),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,i)}n.bindFramebuffer(t.FRAMEBUFFER,null)}const D=[],O=[];function F(t){return Math.min(r.maxSamples,t.samples)}function B(t){const n=i.get(t);return t.samples>0&&!0===e.has("WEBGL_multisampled_render_to_texture")&&!1!==n.__useRenderToTexture}function z(t,e){const n=t.colorSpace,i=t.format,r=t.type;return!0===t.isCompressedTexture||!0===t.isVideoTexture||n!==Ke&&n!==Ze&&(mi.getTransfer(n)===en?i===kt&&r===Et||console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",n)),e}function k(t){return"undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement?(c.width=t.naturalWidth||t.width,c.height=t.naturalHeight||t.height):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?(c.width=t.displayWidth,c.height=t.displayHeight):(c.width=t.width,c.height=t.height),c}this.allocateTextureUnit=function(){const t=w;return t>=r.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+t+" texture units while this GPU supports only "+r.maxTextures),w+=1,t},this.resetTextureUnits=function(){w=0},this.setTexture2D=T,this.setTexture2DArray=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?I(s,e,r):n.bindTexture(t.TEXTURE_2D_ARRAY,s.__webglTexture,t.TEXTURE0+r)},this.setTexture3D=function(e,r){const s=i.get(e);e.version>0&&s.__version!==e.version?I(s,e,r):n.bindTexture(t.TEXTURE_3D,s.__webglTexture,t.TEXTURE0+r)},this.setTextureCube=function(e,a){const o=i.get(e);e.version>0&&o.__version!==e.version?function(e,a,o){if(6!==a.image.length)return;const l=P(e,a),c=a.source;n.bindTexture(t.TEXTURE_CUBE_MAP,e.__webglTexture,t.TEXTURE0+o);const h=i.get(c);if(c.version!==h.__version||!0===l){n.activeTexture(t.TEXTURE0+o);const e=mi.getPrimaries(mi.workingColorSpace),i=a.colorSpace===Ze?null:mi.getPrimaries(a.colorSpace),u=a.colorSpace===Ze||e===i?t.NONE:t.BROWSER_DEFAULT_WEBGL;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,a.flipY),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,a.premultiplyAlpha),t.pixelStorei(t.UNPACK_ALIGNMENT,a.unpackAlignment),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,u);const d=a.isCompressedTexture||a.image[0].isCompressedTexture,p=a.image[0]&&a.image[0].isDataTexture,m=[];for(let t=0;t<6;t++)m[t]=d||p?p?a.image[t].image:a.image[t]:f(a.image[t],!0,r.maxCubemapSize),m[t]=z(a,m[t]);const x=m[0],M=s.convert(a.format,a.colorSpace),S=s.convert(a.type),b=_(a.internalFormat,M,S,a.colorSpace),w=!0!==a.isVideoTexture,T=void 0===h.__version||!0===l,E=c.dataReady;let A,R=y(a,x);if(C(t.TEXTURE_CUBE_MAP,a),d){w&&T&&n.texStorage2D(t.TEXTURE_CUBE_MAP,R,b,x.width,x.height);for(let e=0;e<6;e++){A=m[e].mipmaps;for(let i=0;i0&&R++;const e=k(m[0]);n.texStorage2D(t.TEXTURE_CUBE_MAP,R,b,e.width,e.height)}for(let e=0;e<6;e++)if(p){w?E&&n.texSubImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,m[e].width,m[e].height,M,S,m[e].data):n.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,b,m[e].width,m[e].height,0,M,S,m[e].data);for(let i=0;i1;if(u||(void 0===l.__webglTexture&&(l.__webglTexture=t.createTexture()),l.__version=r.version,a.memory.textures++),h){o.__webglFramebuffer=[];for(let e=0;e<6;e++)if(r.mipmaps&&r.mipmaps.length>0){o.__webglFramebuffer[e]=[];for(let n=0;n0){o.__webglFramebuffer=[];for(let e=0;e0&&!1===B(e)){o.__webglMultisampledFramebuffer=t.createFramebuffer(),o.__webglColorRenderbuffer=[],n.bindFramebuffer(t.FRAMEBUFFER,o.__webglMultisampledFramebuffer);for(let n=0;n0)for(let i=0;i0)for(let n=0;n0)if(!1===B(e)){const r=e.textures,s=e.width,a=e.height;let o=t.COLOR_BUFFER_BIT;const c=e.stencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT,h=i.get(e),u=r.length>1;if(u)for(let e=0;eo+c?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:t.handedness,target:this})):!l.inputState.pinching&&a<=o-c&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:t.handedness,target:this}))}else null!==o&&t.gripSpace&&(r=e.getPose(t.gripSpace,n),null!==r&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1));null!==a&&(i=e.getPose(t.targetRaySpace,n),null===i&&null!==r&&(i=r),null!==i&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(Jl)))}return null!==a&&(a.visible=null!==i),null!==o&&(o.visible=null!==r),null!==l&&(l.visible=null!==s),this}_getHandJoint(t,e){if(void 0===t.joints[e.jointName]){const n=new Zl;n.matrixAutoUpdate=!1,n.visible=!1,t.joints[e.jointName]=n,t.add(n)}return t.joints[e.jointName]}}class $l{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(t,e,n){if(null===this.texture){const i=new bi;t.properties.get(i).__webglTexture=e.texture,e.depthNear==n.depthNear&&e.depthFar==n.depthFar||(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(t){if(null!==this.texture&&null===this.mesh){const e=t.cameras[0].viewport,n=new Ys({vertexShader:"\nvoid main() {\n\n\tgl_Position = vec4( position, 1.0 );\n\n}",fragmentShader:"\nuniform sampler2DArray depthColor;\nuniform float depthWidth;\nuniform float depthHeight;\n\nvoid main() {\n\n\tvec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );\n\n\tif ( coord.x >= 1.0 ) {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;\n\n\t} else {\n\n\t\tgl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;\n\n\t}\n\n}",uniforms:{depthColor:{value:this.texture},depthWidth:{value:e.z},depthHeight:{value:e.w}}});this.mesh=new Vs(new pa(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class Ql extends Hn{constructor(t,e){super();const n=this;let i=null,r=1,s=null,a="local-floor",o=1,l=null,c=null,h=null,u=null,d=null,p=null;const m=new $l,f=e.getContextAttributes();let g=null,v=null;const _=[],x=[],y=new ti;let M=null;const S=new Qs;S.layers.enable(1),S.viewport=new wi;const b=new Qs;b.layers.enable(2),b.viewport=new wi;const w=[S,b],T=new Yl;T.layers.enable(1),T.layers.enable(2);let E=null,A=null;function R(t){const e=x.indexOf(t.inputSource);if(-1===e)return;const n=_[e];void 0!==n&&(n.update(t.inputSource,t.frame,l||s),n.dispatchEvent({type:t.type,data:t.inputSource}))}function C(){i.removeEventListener("select",R),i.removeEventListener("selectstart",R),i.removeEventListener("selectend",R),i.removeEventListener("squeeze",R),i.removeEventListener("squeezestart",R),i.removeEventListener("squeezeend",R),i.removeEventListener("end",C),i.removeEventListener("inputsourceschange",P);for(let t=0;t<_.length;t++){const e=x[t];null!==e&&(x[t]=null,_[t].disconnect(e))}E=null,A=null,m.reset(),t.setRenderTarget(g),d=null,u=null,h=null,i=null,v=null,D.stop(),n.isPresenting=!1,t.setPixelRatio(M),t.setSize(y.width,y.height,!1),n.dispatchEvent({type:"sessionend"})}function P(t){for(let e=0;e=0&&(x[i]=null,_[i].disconnect(n))}for(let e=0;e=x.length){x.push(n),i=t;break}if(null===x[t]){x[t]=n,i=t;break}}if(-1===i)break}const r=_[i];r&&r.connect(n)}}this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(t){let e=_[t];return void 0===e&&(e=new Kl,_[t]=e),e.getTargetRaySpace()},this.getControllerGrip=function(t){let e=_[t];return void 0===e&&(e=new Kl,_[t]=e),e.getGripSpace()},this.getHand=function(t){let e=_[t];return void 0===e&&(e=new Kl,_[t]=e),e.getHandSpace()},this.setFramebufferScaleFactor=function(t){r=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(t){a=t,!0===n.isPresenting&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(t){l=t},this.getBaseLayer=function(){return null!==u?u:d},this.getBinding=function(){return h},this.getFrame=function(){return p},this.getSession=function(){return i},this.setSession=async function(c){if(i=c,null!==i){if(g=t.getRenderTarget(),i.addEventListener("select",R),i.addEventListener("selectstart",R),i.addEventListener("selectend",R),i.addEventListener("squeeze",R),i.addEventListener("squeezestart",R),i.addEventListener("squeezeend",R),i.addEventListener("end",C),i.addEventListener("inputsourceschange",P),!0!==f.xrCompatible&&await e.makeXRCompatible(),M=t.getPixelRatio(),t.getSize(y),void 0===i.renderState.layers){const n={antialias:f.antialias,alpha:!0,depth:f.depth,stencil:f.stencil,framebufferScaleFactor:r};d=new XRWebGLLayer(i,e,n),i.updateRenderState({baseLayer:d}),t.setPixelRatio(1),t.setSize(d.framebufferWidth,d.framebufferHeight,!1),v=new Ei(d.framebufferWidth,d.framebufferHeight,{format:kt,type:Et,colorSpace:t.outputColorSpace,stencilBuffer:f.stencil})}else{let n=null,s=null,a=null;f.depth&&(a=f.stencil?e.DEPTH24_STENCIL8:e.DEPTH_COMPONENT24,n=f.stencil?Wt:Gt,s=f.stencil?Ot:It);const o={colorFormat:e.RGBA8,depthFormat:a,scaleFactor:r};h=new XRWebGLBinding(i,e),u=h.createProjectionLayer(o),i.updateRenderState({layers:[u]}),t.setPixelRatio(1),t.setSize(u.textureWidth,u.textureHeight,!1),v=new Ei(u.textureWidth,u.textureHeight,{format:kt,type:Et,depthTexture:new Ka(u.textureWidth,u.textureHeight,s,void 0,void 0,void 0,void 0,void 0,void 0,n),stencilBuffer:f.stencil,colorSpace:t.outputColorSpace,samples:f.antialias?4:0,resolveDepthBuffer:!1===u.ignoreDepthValues})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),D.setContext(i),D.start(),n.isPresenting=!0,n.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(null!==i)return i.environmentBlendMode},this.getDepthTexture=function(){return m.getDepthTexture()};const I=new Li,L=new Li;function U(t,e){null===e?t.matrixWorld.copy(t.matrix):t.matrixWorld.multiplyMatrices(e.matrixWorld,t.matrix),t.matrixWorldInverse.copy(t.matrixWorld).invert()}this.updateCamera=function(t){if(null===i)return;let e=t.near,n=t.far;null!==m.texture&&(m.depthNear>0&&(e=m.depthNear),m.depthFar>0&&(n=m.depthFar)),T.near=b.near=S.near=e,T.far=b.far=S.far=n,E===T.near&&A===T.far||(i.updateRenderState({depthNear:T.near,depthFar:T.far}),E=T.near,A=T.far);const r=t.parent,s=T.cameras;U(T,r);for(let t=0;t0&&(t.alphaTest.value=i.alphaTest);const r=e.get(i),s=r.envMap,a=r.envMapRotation;s&&(t.envMap.value=s,tc.copy(a),tc.x*=-1,tc.y*=-1,tc.z*=-1,s.isCubeTexture&&!1===s.isRenderTargetTexture&&(tc.y*=-1,tc.z*=-1),t.envMapRotation.value.setFromMatrix4(ec.makeRotationFromEuler(tc)),t.flipEnvMap.value=s.isCubeTexture&&!1===s.isRenderTargetTexture?-1:1,t.reflectivity.value=i.reflectivity,t.ior.value=i.ior,t.refractionRatio.value=i.refractionRatio),i.lightMap&&(t.lightMap.value=i.lightMap,t.lightMapIntensity.value=i.lightMapIntensity,n(i.lightMap,t.lightMapTransform)),i.aoMap&&(t.aoMap.value=i.aoMap,t.aoMapIntensity.value=i.aoMapIntensity,n(i.aoMap,t.aoMapTransform))}return{refreshFogUniforms:function(e,n){n.color.getRGB(e.fogColor.value,js(t)),n.isFog?(e.fogNear.value=n.near,e.fogFar.value=n.far):n.isFogExp2&&(e.fogDensity.value=n.density)},refreshMaterialUniforms:function(t,r,s,a,o){r.isMeshBasicMaterial||r.isMeshLambertMaterial?i(t,r):r.isMeshToonMaterial?(i(t,r),function(t,e){e.gradientMap&&(t.gradientMap.value=e.gradientMap)}(t,r)):r.isMeshPhongMaterial?(i(t,r),function(t,e){t.specular.value.copy(e.specular),t.shininess.value=Math.max(e.shininess,1e-4)}(t,r)):r.isMeshStandardMaterial?(i(t,r),function(t,e){t.metalness.value=e.metalness,e.metalnessMap&&(t.metalnessMap.value=e.metalnessMap,n(e.metalnessMap,t.metalnessMapTransform));t.roughness.value=e.roughness,e.roughnessMap&&(t.roughnessMap.value=e.roughnessMap,n(e.roughnessMap,t.roughnessMapTransform));e.envMap&&(t.envMapIntensity.value=e.envMapIntensity)}(t,r),r.isMeshPhysicalMaterial&&function(t,e,i){t.ior.value=e.ior,e.sheen>0&&(t.sheenColor.value.copy(e.sheenColor).multiplyScalar(e.sheen),t.sheenRoughness.value=e.sheenRoughness,e.sheenColorMap&&(t.sheenColorMap.value=e.sheenColorMap,n(e.sheenColorMap,t.sheenColorMapTransform)),e.sheenRoughnessMap&&(t.sheenRoughnessMap.value=e.sheenRoughnessMap,n(e.sheenRoughnessMap,t.sheenRoughnessMapTransform)));e.clearcoat>0&&(t.clearcoat.value=e.clearcoat,t.clearcoatRoughness.value=e.clearcoatRoughness,e.clearcoatMap&&(t.clearcoatMap.value=e.clearcoatMap,n(e.clearcoatMap,t.clearcoatMapTransform)),e.clearcoatRoughnessMap&&(t.clearcoatRoughnessMap.value=e.clearcoatRoughnessMap,n(e.clearcoatRoughnessMap,t.clearcoatRoughnessMapTransform)),e.clearcoatNormalMap&&(t.clearcoatNormalMap.value=e.clearcoatNormalMap,n(e.clearcoatNormalMap,t.clearcoatNormalMapTransform),t.clearcoatNormalScale.value.copy(e.clearcoatNormalScale),e.side===d&&t.clearcoatNormalScale.value.negate()));e.dispersion>0&&(t.dispersion.value=e.dispersion);e.iridescence>0&&(t.iridescence.value=e.iridescence,t.iridescenceIOR.value=e.iridescenceIOR,t.iridescenceThicknessMinimum.value=e.iridescenceThicknessRange[0],t.iridescenceThicknessMaximum.value=e.iridescenceThicknessRange[1],e.iridescenceMap&&(t.iridescenceMap.value=e.iridescenceMap,n(e.iridescenceMap,t.iridescenceMapTransform)),e.iridescenceThicknessMap&&(t.iridescenceThicknessMap.value=e.iridescenceThicknessMap,n(e.iridescenceThicknessMap,t.iridescenceThicknessMapTransform)));e.transmission>0&&(t.transmission.value=e.transmission,t.transmissionSamplerMap.value=i.texture,t.transmissionSamplerSize.value.set(i.width,i.height),e.transmissionMap&&(t.transmissionMap.value=e.transmissionMap,n(e.transmissionMap,t.transmissionMapTransform)),t.thickness.value=e.thickness,e.thicknessMap&&(t.thicknessMap.value=e.thicknessMap,n(e.thicknessMap,t.thicknessMapTransform)),t.attenuationDistance.value=e.attenuationDistance,t.attenuationColor.value.copy(e.attenuationColor));e.anisotropy>0&&(t.anisotropyVector.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation)),e.anisotropyMap&&(t.anisotropyMap.value=e.anisotropyMap,n(e.anisotropyMap,t.anisotropyMapTransform)));t.specularIntensity.value=e.specularIntensity,t.specularColor.value.copy(e.specularColor),e.specularColorMap&&(t.specularColorMap.value=e.specularColorMap,n(e.specularColorMap,t.specularColorMapTransform));e.specularIntensityMap&&(t.specularIntensityMap.value=e.specularIntensityMap,n(e.specularIntensityMap,t.specularIntensityMapTransform))}(t,r,o)):r.isMeshMatcapMaterial?(i(t,r),function(t,e){e.matcap&&(t.matcap.value=e.matcap)}(t,r)):r.isMeshDepthMaterial?i(t,r):r.isMeshDistanceMaterial?(i(t,r),function(t,n){const i=e.get(n).light;t.referencePosition.value.setFromMatrixPosition(i.matrixWorld),t.nearDistance.value=i.shadow.camera.near,t.farDistance.value=i.shadow.camera.far}(t,r)):r.isMeshNormalMaterial?i(t,r):r.isLineBasicMaterial?(function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform))}(t,r),r.isLineDashedMaterial&&function(t,e){t.dashSize.value=e.dashSize,t.totalSize.value=e.dashSize+e.gapSize,t.scale.value=e.scale}(t,r)):r.isPointsMaterial?function(t,e,i,r){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.size.value=e.size*i,t.scale.value=.5*r,e.map&&(t.map.value=e.map,n(e.map,t.uvTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r,s,a):r.isSpriteMaterial?function(t,e){t.diffuse.value.copy(e.color),t.opacity.value=e.opacity,t.rotation.value=e.rotation,e.map&&(t.map.value=e.map,n(e.map,t.mapTransform));e.alphaMap&&(t.alphaMap.value=e.alphaMap,n(e.alphaMap,t.alphaMapTransform));e.alphaTest>0&&(t.alphaTest.value=e.alphaTest)}(t,r):r.isShadowMaterial?(t.color.value.copy(r.color),t.opacity.value=r.opacity):r.isShaderMaterial&&(r.uniformsNeedUpdate=!1)}}}function ic(t,e,n,i){let r={},s={},a=[];const o=t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS);function l(t,e,n,i){const r=t.value,s=e+"_"+n;if(void 0===i[s])return i[s]="number"==typeof r||"boolean"==typeof r?r:r.clone(),!0;{const t=i[s];if("number"==typeof r||"boolean"==typeof r){if(t!==r)return i[s]=r,!0}else if(!1===t.equals(r))return t.copy(r),!0}return!1}function c(t){const e={boundary:0,storage:0};return"number"==typeof t||"boolean"==typeof t?(e.boundary=4,e.storage=4):t.isVector2?(e.boundary=8,e.storage=8):t.isVector3||t.isColor?(e.boundary=16,e.storage=12):t.isVector4?(e.boundary=16,e.storage=16):t.isMatrix3?(e.boundary=48,e.storage=48):t.isMatrix4?(e.boundary=64,e.storage=64):t.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",t),e}function h(e){const n=e.target;n.removeEventListener("dispose",h);const i=a.indexOf(n.__bindingPointIndex);a.splice(i,1),t.deleteBuffer(r[n.id]),delete r[n.id],delete s[n.id]}return{bind:function(t,e){const n=e.program;i.uniformBlockBinding(t,n)},update:function(n,u){let d=r[n.id];void 0===d&&(!function(t){const e=t.uniforms;let n=0;const i=16;for(let t=0,r=e.length;t0&&(n+=i-r);t.__size=n,t.__cache={}}(n),d=function(e){const n=function(){for(let t=0;t0),u=!!n.morphAttributes.position,d=!!n.morphAttributes.normal,p=!!n.morphAttributes.color;let m=K;i.toneMapped&&(null!==T&&!0!==T.isXRRenderTarget||(m=M.toneMapping));const f=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,g=void 0!==f?f.length:0,v=nt.get(i),x=_.state.lights;if(!0===H&&(!0===G||t!==A)){const e=t===A&&i.id===E;pt.setState(i,t,e)}let y=!1;i.version===v.__version?v.needsLights&&v.lightsStateVersion!==x.state.version||v.outputColorSpace!==o||r.isBatchedMesh&&!1===v.batching?y=!0:r.isBatchedMesh||!0!==v.batching?r.isBatchedMesh&&!0===v.batchingColor&&null===r.colorTexture||r.isBatchedMesh&&!1===v.batchingColor&&null!==r.colorTexture||r.isInstancedMesh&&!1===v.instancing?y=!0:r.isInstancedMesh||!0!==v.instancing?r.isSkinnedMesh&&!1===v.skinning?y=!0:r.isSkinnedMesh||!0!==v.skinning?r.isInstancedMesh&&!0===v.instancingColor&&null===r.instanceColor||r.isInstancedMesh&&!1===v.instancingColor&&null!==r.instanceColor||r.isInstancedMesh&&!0===v.instancingMorph&&null===r.morphTexture||r.isInstancedMesh&&!1===v.instancingMorph&&null!==r.morphTexture||v.envMap!==l||!0===i.fog&&v.fog!==s?y=!0:void 0===v.numClippingPlanes||v.numClippingPlanes===pt.numPlanes&&v.numIntersection===pt.numIntersection?(v.vertexAlphas!==c||v.vertexTangents!==h||v.morphTargets!==u||v.morphNormals!==d||v.morphColors!==p||v.toneMapping!==m||v.morphTargetsCount!==g)&&(y=!0):y=!0:y=!0:y=!0:y=!0:(y=!0,v.__version=i.version);let S=v.currentProgram;!0===y&&(S=Kt(i,e,r));let b=!1,w=!1,R=!1;const C=S.getUniforms(),P=v.uniforms;tt.useProgram(S.program)&&(b=!0,w=!0,R=!0);i.id!==E&&(E=i.id,w=!0);if(b||A!==t){Q.reverseDepthBuffer?(W.copy(t.projectionMatrix),function(t){const e=t.elements;e[2]=.5*e[2]+.5*e[3],e[6]=.5*e[6]+.5*e[7],e[10]=.5*e[10]+.5*e[11],e[14]=.5*e[14]+.5*e[15]}(W),function(t){const e=t.elements;-1===e[11]?(e[10]=-e[10]-1,e[14]=-e[14]):(e[10]=-e[10],e[14]=1-e[14])}(W),C.setValue(St,"projectionMatrix",W)):C.setValue(St,"projectionMatrix",t.projectionMatrix),C.setValue(St,"viewMatrix",t.matrixWorldInverse);const e=C.map.cameraPosition;void 0!==e&&e.setValue(St,j.setFromMatrixPosition(t.matrixWorld)),Q.logarithmicDepthBuffer&&C.setValue(St,"logDepthBufFC",2/(Math.log(t.far+1)/Math.LN2)),(i.isMeshPhongMaterial||i.isMeshToonMaterial||i.isMeshLambertMaterial||i.isMeshBasicMaterial||i.isMeshStandardMaterial||i.isShaderMaterial)&&C.setValue(St,"isOrthographic",!0===t.isOrthographicCamera),A!==t&&(A=t,w=!0,R=!0)}if(r.isSkinnedMesh){C.setOptional(St,r,"bindMatrix"),C.setOptional(St,r,"bindMatrixInverse");const t=r.skeleton;t&&(null===t.boneTexture&&t.computeBoneTexture(),C.setValue(St,"boneTexture",t.boneTexture,it))}r.isBatchedMesh&&(C.setOptional(St,r,"batchingTexture"),C.setValue(St,"batchingTexture",r._matricesTexture,it),C.setOptional(St,r,"batchingIdTexture"),C.setValue(St,"batchingIdTexture",r._indirectTexture,it),C.setOptional(St,r,"batchingColorTexture"),null!==r._colorsTexture&&C.setValue(St,"batchingColorTexture",r._colorsTexture,it));const I=n.morphAttributes;void 0===I.position&&void 0===I.normal&&void 0===I.color||gt.update(r,n,S);(w||v.receiveShadow!==r.receiveShadow)&&(v.receiveShadow=r.receiveShadow,C.setValue(St,"receiveShadow",r.receiveShadow));i.isMeshGouraudMaterial&&null!==i.envMap&&(P.envMap.value=l,P.flipEnvMap.value=l.isCubeTexture&&!1===l.isRenderTargetTexture?-1:1);i.isMeshStandardMaterial&&null===i.envMap&&null!==e.environment&&(P.envMapIntensity.value=e.environmentIntensity);w&&(C.setValue(St,"toneMappingExposure",M.toneMappingExposure),v.needsLights&&(U=R,(L=P).ambientLightColor.needsUpdate=U,L.lightProbe.needsUpdate=U,L.directionalLights.needsUpdate=U,L.directionalLightShadows.needsUpdate=U,L.pointLights.needsUpdate=U,L.pointLightShadows.needsUpdate=U,L.spotLights.needsUpdate=U,L.spotLightShadows.needsUpdate=U,L.rectAreaLights.needsUpdate=U,L.hemisphereLights.needsUpdate=U),s&&!0===i.fog&&ht.refreshFogUniforms(P,s),ht.refreshMaterialUniforms(P,i,D,N,_.state.transmissionRenderTarget[t.id]),il.upload(St,$t(v),P,it));var L,U;i.isShaderMaterial&&!0===i.uniformsNeedUpdate&&(il.upload(St,$t(v),P,it),i.uniformsNeedUpdate=!1);i.isSpriteMaterial&&C.setValue(St,"center",r.center);if(C.setValue(St,"modelViewMatrix",r.modelViewMatrix),C.setValue(St,"normalMatrix",r.normalMatrix),C.setValue(St,"modelMatrix",r.matrixWorld),i.isShaderMaterial||i.isRawShaderMaterial){const t=i.uniformsGroups;for(let e=0,n=t.length;e{function n(){i.forEach((function(t){nt.get(t).currentProgram.isReady()&&i.delete(t)})),0!==i.size?setTimeout(n,10):e(t)}null!==$.get("KHR_parallel_shader_compile")?n():setTimeout(n,10)}))};let zt=null;function kt(){Ht.stop()}function Vt(){Ht.start()}const Ht=new ua;function Gt(t,e,n,i){if(!1===t.visible)return;if(t.layers.test(e.layers))if(t.isGroup)n=t.renderOrder;else if(t.isLOD)!0===t.autoUpdate&&t.update(e);else if(t.isLight)_.pushLight(t),t.castShadow&&_.pushShadow(t);else if(t.isSprite){if(!t.frustumCulled||V.intersectsSprite(t)){i&&q.setFromMatrixPosition(t.matrixWorld).applyMatrix4(X);const e=lt.update(t),r=t.material;r.visible&&v.push(t,e,r,n,q.z,null)}}else if((t.isMesh||t.isLine||t.isPoints)&&(!t.frustumCulled||V.intersectsObject(t))){const e=lt.update(t),r=t.material;if(i&&(void 0!==t.boundingSphere?(null===t.boundingSphere&&t.computeBoundingSphere(),q.copy(t.boundingSphere.center)):(null===e.boundingSphere&&e.computeBoundingSphere(),q.copy(e.boundingSphere.center)),q.applyMatrix4(t.matrixWorld).applyMatrix4(X)),Array.isArray(r)){const i=e.groups;for(let s=0,a=i.length;s0&&qt(r,e,n),s.length>0&&qt(s,e,n),a.length>0&&qt(a,e,n),tt.buffers.depth.setTest(!0),tt.buffers.depth.setMask(!0),tt.buffers.color.setMask(!0),tt.setPolygonOffset(!1)}function Xt(t,e,n,i){if(null!==(!0===n.isScene?n.overrideMaterial:null))return;void 0===_.state.transmissionRenderTarget[i.id]&&(_.state.transmissionRenderTarget[i.id]=new Ei(1,1,{generateMipmaps:!0,type:$.has("EXT_color_buffer_half_float")||$.has("EXT_color_buffer_float")?Ut:Et,minFilter:wt,samples:4,stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:mi.workingColorSpace}));const r=_.state.transmissionRenderTarget[i.id],a=i.viewport||R;r.setSize(a.z,a.w);const o=M.getRenderTarget();M.setRenderTarget(r),M.getClearColor(I),L=M.getClearAlpha(),L<1&&M.setClearColor(16777215,.5),M.clear(),Z&&ft.render(n);const l=M.toneMapping;M.toneMapping=K;const c=i.viewport;if(void 0!==i.viewport&&(i.viewport=void 0),_.setupLightsView(i),!0===H&&pt.setGlobalState(M.clippingPlanes,i),qt(t,n,i),it.updateMultisampleRenderTarget(r),it.updateRenderTargetMipmap(r),!1===$.has("WEBGL_multisampled_render_to_texture")){let t=!1;for(let r=0,s=e.length;r0)for(let e=0,s=n.length;e0&&Xt(i,r,t,e),Z&&ft.render(t),Wt(v,t,e);null!==T&&(it.updateMultisampleRenderTarget(T),it.updateRenderTargetMipmap(T)),!0===t.isScene&&t.onAfterRender(M,t,e),yt.resetDefaultState(),E=-1,A=null,y.pop(),y.length>0?(_=y[y.length-1],!0===H&&pt.setGlobalState(M.clippingPlanes,_.state.camera)):_=null,x.pop(),v=x.length>0?x[x.length-1]:null},this.getActiveCubeFace=function(){return b},this.getActiveMipmapLevel=function(){return w},this.getRenderTarget=function(){return T},this.setRenderTargetTextures=function(t,e,n){nt.get(t.texture).__webglTexture=e,nt.get(t.depthTexture).__webglTexture=n;const i=nt.get(t);i.__hasExternalTextures=!0,i.__autoAllocateDepthBuffer=void 0===n,i.__autoAllocateDepthBuffer||!0===$.has("WEBGL_multisampled_render_to_texture")&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),i.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(t,e){const n=nt.get(t);n.__webglFramebuffer=e,n.__useDefaultFramebuffer=void 0===e},this.setRenderTarget=function(t,e=0,n=0){T=t,b=e,w=n;let i=!0,r=null,s=!1,a=!1;if(t){const o=nt.get(t);if(void 0!==o.__useDefaultFramebuffer)tt.bindFramebuffer(St.FRAMEBUFFER,null),i=!1;else if(void 0===o.__webglFramebuffer)it.setupRenderTarget(t);else if(o.__hasExternalTextures)it.rebindTextures(t,nt.get(t.texture).__webglTexture,nt.get(t.depthTexture).__webglTexture);else if(t.depthBuffer){const e=t.depthTexture;if(o.__boundDepthTexture!==e){if(null!==e&&nt.has(e)&&(t.width!==e.image.width||t.height!==e.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");it.setupDepthRenderbuffer(t)}}const l=t.texture;(l.isData3DTexture||l.isDataArrayTexture||l.isCompressedArrayTexture)&&(a=!0);const c=nt.get(t).__webglFramebuffer;t.isWebGLCubeRenderTarget?(r=Array.isArray(c[e])?c[e][n]:c[e],s=!0):r=t.samples>0&&!1===it.useMultisampledRTT(t)?nt.get(t).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,R.copy(t.viewport),C.copy(t.scissor),P=t.scissorTest}else R.copy(B).multiplyScalar(D).floor(),C.copy(z).multiplyScalar(D).floor(),P=k;if(tt.bindFramebuffer(St.FRAMEBUFFER,r)&&i&&tt.drawBuffers(t,r),tt.viewport(R),tt.scissor(C),tt.setScissorTest(P),s){const i=nt.get(t.texture);St.framebufferTexture2D(St.FRAMEBUFFER,St.COLOR_ATTACHMENT0,St.TEXTURE_CUBE_MAP_POSITIVE_X+e,i.__webglTexture,n)}else if(a){const i=nt.get(t.texture),r=e||0;St.framebufferTextureLayer(St.FRAMEBUFFER,St.COLOR_ATTACHMENT0,i.__webglTexture,n||0,r)}E=-1},this.readRenderTargetPixels=function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=nt.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){tt.bindFramebuffer(St.FRAMEBUFFER,o);try{const a=t.texture,o=a.format,l=a.type;if(!Q.textureFormatReadable(o))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(l))return void console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r&&St.readPixels(e,n,i,r,xt.convert(o),xt.convert(l),s)}finally{const t=null!==T?nt.get(T).__webglFramebuffer:null;tt.bindFramebuffer(St.FRAMEBUFFER,t)}}},this.readRenderTargetPixelsAsync=async function(t,e,n,i,r,s,a){if(!t||!t.isWebGLRenderTarget)throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let o=nt.get(t).__webglFramebuffer;if(t.isWebGLCubeRenderTarget&&void 0!==a&&(o=o[a]),o){const a=t.texture,l=a.format,c=a.type;if(!Q.textureFormatReadable(l))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Q.textureTypeReadable(c))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(e>=0&&e<=t.width-i&&n>=0&&n<=t.height-r){tt.bindFramebuffer(St.FRAMEBUFFER,o);const t=St.createBuffer();St.bindBuffer(St.PIXEL_PACK_BUFFER,t),St.bufferData(St.PIXEL_PACK_BUFFER,s.byteLength,St.STREAM_READ),St.readPixels(e,n,i,r,xt.convert(l),xt.convert(c),0);const a=null!==T?nt.get(T).__webglFramebuffer:null;tt.bindFramebuffer(St.FRAMEBUFFER,a);const h=St.fenceSync(St.SYNC_GPU_COMMANDS_COMPLETE,0);return St.flush(),await function(t,e,n){return new Promise((function(i,r){setTimeout((function s(){switch(t.clientWaitSync(e,t.SYNC_FLUSH_COMMANDS_BIT,0)){case t.WAIT_FAILED:r();break;case t.TIMEOUT_EXPIRED:setTimeout(s,n);break;default:i()}}),n)}))}(St,h,4),St.bindBuffer(St.PIXEL_PACK_BUFFER,t),St.getBufferSubData(St.PIXEL_PACK_BUFFER,0,s),St.deleteBuffer(t),St.deleteSync(h),s}throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(t,e=null,n=0){!0!==t.isTexture&&(ci("WebGLRenderer: copyFramebufferToTexture function signature has changed."),e=arguments[0]||null,t=arguments[1]);const i=Math.pow(2,-n),r=Math.floor(t.image.width*i),s=Math.floor(t.image.height*i),a=null!==e?e.x:0,o=null!==e?e.y:0;it.setTexture2D(t,0),St.copyTexSubImage2D(St.TEXTURE_2D,n,0,0,a,o,r,s),tt.unbindTexture()},this.copyTextureToTexture=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h;!0!==t.isTexture&&(ci("WebGLRenderer: copyTextureToTexture function signature has changed."),i=arguments[0]||null,t=arguments[1],e=arguments[2],r=arguments[3]||0,n=null),null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.min.x,l=n.min.y):(s=t.image.width,a=t.image.height,o=0,l=0),null!==i?(c=i.x,h=i.y):(c=0,h=0);const u=xt.convert(e.format),d=xt.convert(e.type);it.setTexture2D(e,0),St.pixelStorei(St.UNPACK_FLIP_Y_WEBGL,e.flipY),St.pixelStorei(St.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),St.pixelStorei(St.UNPACK_ALIGNMENT,e.unpackAlignment);const p=St.getParameter(St.UNPACK_ROW_LENGTH),m=St.getParameter(St.UNPACK_IMAGE_HEIGHT),f=St.getParameter(St.UNPACK_SKIP_PIXELS),g=St.getParameter(St.UNPACK_SKIP_ROWS),v=St.getParameter(St.UNPACK_SKIP_IMAGES),_=t.isCompressedTexture?t.mipmaps[r]:t.image;St.pixelStorei(St.UNPACK_ROW_LENGTH,_.width),St.pixelStorei(St.UNPACK_IMAGE_HEIGHT,_.height),St.pixelStorei(St.UNPACK_SKIP_PIXELS,o),St.pixelStorei(St.UNPACK_SKIP_ROWS,l),t.isDataTexture?St.texSubImage2D(St.TEXTURE_2D,r,c,h,s,a,u,d,_.data):t.isCompressedTexture?St.compressedTexSubImage2D(St.TEXTURE_2D,r,c,h,_.width,_.height,u,_.data):St.texSubImage2D(St.TEXTURE_2D,r,c,h,s,a,u,d,_),St.pixelStorei(St.UNPACK_ROW_LENGTH,p),St.pixelStorei(St.UNPACK_IMAGE_HEIGHT,m),St.pixelStorei(St.UNPACK_SKIP_PIXELS,f),St.pixelStorei(St.UNPACK_SKIP_ROWS,g),St.pixelStorei(St.UNPACK_SKIP_IMAGES,v),0===r&&e.generateMipmaps&&St.generateMipmap(St.TEXTURE_2D),tt.unbindTexture()},this.copyTextureToTexture3D=function(t,e,n=null,i=null,r=0){let s,a,o,l,c,h,u,d,p;!0!==t.isTexture&&(ci("WebGLRenderer: copyTextureToTexture3D function signature has changed."),n=arguments[0]||null,i=arguments[1]||null,t=arguments[2],e=arguments[3],r=arguments[4]||0);const m=t.isCompressedTexture?t.mipmaps[r]:t.image;null!==n?(s=n.max.x-n.min.x,a=n.max.y-n.min.y,o=n.max.z-n.min.z,l=n.min.x,c=n.min.y,h=n.min.z):(s=m.width,a=m.height,o=m.depth,l=0,c=0,h=0),null!==i?(u=i.x,d=i.y,p=i.z):(u=0,d=0,p=0);const f=xt.convert(e.format),g=xt.convert(e.type);let v;if(e.isData3DTexture)it.setTexture3D(e,0),v=St.TEXTURE_3D;else{if(!e.isDataArrayTexture&&!e.isCompressedArrayTexture)return void console.warn("THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.");it.setTexture2DArray(e,0),v=St.TEXTURE_2D_ARRAY}St.pixelStorei(St.UNPACK_FLIP_Y_WEBGL,e.flipY),St.pixelStorei(St.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.premultiplyAlpha),St.pixelStorei(St.UNPACK_ALIGNMENT,e.unpackAlignment);const _=St.getParameter(St.UNPACK_ROW_LENGTH),x=St.getParameter(St.UNPACK_IMAGE_HEIGHT),y=St.getParameter(St.UNPACK_SKIP_PIXELS),M=St.getParameter(St.UNPACK_SKIP_ROWS),S=St.getParameter(St.UNPACK_SKIP_IMAGES);St.pixelStorei(St.UNPACK_ROW_LENGTH,m.width),St.pixelStorei(St.UNPACK_IMAGE_HEIGHT,m.height),St.pixelStorei(St.UNPACK_SKIP_PIXELS,l),St.pixelStorei(St.UNPACK_SKIP_ROWS,c),St.pixelStorei(St.UNPACK_SKIP_IMAGES,h),t.isDataTexture||t.isData3DTexture?St.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m.data):e.isCompressedArrayTexture?St.compressedTexSubImage3D(v,r,u,d,p,s,a,o,f,m.data):St.texSubImage3D(v,r,u,d,p,s,a,o,f,g,m),St.pixelStorei(St.UNPACK_ROW_LENGTH,_),St.pixelStorei(St.UNPACK_IMAGE_HEIGHT,x),St.pixelStorei(St.UNPACK_SKIP_PIXELS,y),St.pixelStorei(St.UNPACK_SKIP_ROWS,M),St.pixelStorei(St.UNPACK_SKIP_IMAGES,S),0===r&&e.generateMipmaps&&St.generateMipmap(v),tt.unbindTexture()},this.initRenderTarget=function(t){void 0===nt.get(t).__webglFramebuffer&&it.setupRenderTarget(t)},this.initTexture=function(t){t.isCubeTexture?it.setTextureCube(t,0):t.isData3DTexture?it.setTexture3D(t,0):t.isDataArrayTexture||t.isCompressedArrayTexture?it.setTexture2DArray(t,0):it.setTexture2D(t,0),tt.unbindTexture()},this.resetState=function(){b=0,w=0,T=null,tt.reset(),yt.reset()},"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return kn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(t){this._outputColorSpace=t;const e=this.getContext();e.drawingBufferColorSpace=t===$e?"display-p3":"srgb",e.unpackColorSpace=mi.workingColorSpace===Qe?"display-p3":"srgb"}}class sc{constructor(t,e=25e-5){this.isFogExp2=!0,this.name="",this.color=new ts(t),this.density=e}clone(){return new sc(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}}class ac{constructor(t,e=1,n=1e3){this.isFog=!0,this.name="",this.color=new ts(t),this.near=e,this.far=n}clone(){return new ac(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}}class oc extends Dr{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new _r,this.environmentIntensity=1,this.environmentRotation=new _r,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(t,e){return super.copy(t,e),null!==t.background&&(this.background=t.background.clone()),null!==t.environment&&(this.environment=t.environment.clone()),null!==t.fog&&(this.fog=t.fog.clone()),this.backgroundBlurriness=t.backgroundBlurriness,this.backgroundIntensity=t.backgroundIntensity,this.backgroundRotation.copy(t.backgroundRotation),this.environmentIntensity=t.environmentIntensity,this.environmentRotation.copy(t.environmentRotation),null!==t.overrideMaterial&&(this.overrideMaterial=t.overrideMaterial.clone()),this.matrixAutoUpdate=t.matrixAutoUpdate,this}toJSON(t){const e=super.toJSON(t);return null!==this.fog&&(e.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(e.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(e.object.backgroundIntensity=this.backgroundIntensity),e.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(e.object.environmentIntensity=this.environmentIntensity),e.object.environmentRotation=this.environmentRotation.toArray(),e}}class lc{constructor(t,e){this.isInterleavedBuffer=!0,this.array=t,this.stride=e,this.count=void 0!==t?t.length/e:0,this.usage=Cn,this.updateRanges=[],this.version=0,this.uuid=qn()}onUploadCallback(){}set needsUpdate(t){!0===t&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.array=new t.array.constructor(t.array),this.count=t.count,this.stride=t.stride,this.usage=t.usage,this}copyAt(t,e,n){t*=this.stride,n*=e.stride;for(let i=0,r=this.stride;it.far||e.push({distance:o,point:pc.clone(),uv:Zr.getInterpolation(pc,xc,yc,Mc,Sc,bc,wc,new ti),face:null,object:this})}copy(t,e){return super.copy(t,e),void 0!==t.center&&this.center.copy(t.center),this.material=t.material,this}}function Ec(t,e,n,i,r,s){gc.subVectors(t,n).addScalar(.5).multiply(i),void 0!==r?(vc.x=s*gc.x-r*gc.y,vc.y=r*gc.x+s*gc.y):vc.copy(gc),t.copy(e),t.x+=vc.x,t.y+=vc.y,t.applyMatrix4(_c)}const Ac=new Li,Rc=new Li;class Cc extends Dr{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(t){super.copy(t,!1);const e=t.levels;for(let t=0,n=e.length;t0){let n,i;for(n=1,i=e.length;n0){Ac.setFromMatrixPosition(this.matrixWorld);const n=t.ray.origin.distanceTo(Ac);this.getObjectForDistance(n).raycast(t,e)}}update(t){const e=this.levels;if(e.length>1){Ac.setFromMatrixPosition(t.matrixWorld),Rc.setFromMatrixPosition(this.matrixWorld);const n=Ac.distanceTo(Rc)/t.zoom;let i,r;for(e[0].object.visible=!0,i=1,r=e.length;i=t))break;e[i-1].object.visible=!1,e[i].object.visible=!0}for(this._currentLevel=i-1;i=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});const s=i[this.index];r.push(s),this.index++,s.start=t.start,s.count=t.count,s.z=e,s.index=n}reset(){this.list.length=0,this.index=0}}const ih=new lr,rh=new lr,sh=new lr,ah=new ts(1,1,1),oh=new lr,lh=new ha,ch=new Di,hh=new Qi,uh=new Li,dh=new Li,ph=new Li,mh=new nh,fh=new Vs,gh=[];function vh(t,e,n=0){const i=e.itemSize;if(t.isInterleavedBufferAttribute||t.array.constructor!==e.array.constructor){const r=t.count;for(let s=0;s65535?new Uint32Array(i):new Uint16Array(i);e.setIndex(new ds(t,1))}this._geometryInitialized=!0}}_validateGeometry(t){const e=this.geometry;if(Boolean(t.getIndex())!==Boolean(e.getIndex()))throw new Error('BatchedMesh: All geometries must consistently have "index".');for(const n in e.attributes){if(!t.hasAttribute(n))throw new Error(`BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);const i=t.getAttribute(n),r=e.getAttribute(n);if(i.itemSize!==r.itemSize||i.normalized!==r.normalized)throw new Error("BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}setCustomSort(t){return this.customSort=t,this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new Di);const t=this.boundingBox,e=this._drawInfo;t.makeEmpty();for(let n=0,i=e.length;n=this.maxInstanceCount&&0===this._availableInstanceIds.length)throw new Error("BatchedMesh: Maximum item count reached.");const e={visible:!0,active:!0,geometryIndex:t};let n=null;this._availableInstanceIds.length>0?(n=this._availableInstanceIds.pop(),this._drawInfo[n]=e):(n=this._drawInfo.length,this._drawInfo.push(e));const i=this._matricesTexture,r=i.image.data;sh.toArray(r,16*n),i.needsUpdate=!0;const s=this._colorsTexture;return s&&(ah.toArray(s.image.data,4*n),s.needsUpdate=!0),n}addGeometry(t,e=-1,n=-1){if(this._initializeGeometry(t),this._validateGeometry(t),this._drawInfo.length>=this._maxInstanceCount)throw new Error("BatchedMesh: Maximum item count reached.");const i={vertexStart:-1,vertexCount:-1,indexStart:-1,indexCount:-1};let r=null;const s=this._reservedRanges,a=this._drawRanges,o=this._bounds;0!==this._geometryCount&&(r=s[s.length-1]),i.vertexCount=-1===e?t.getAttribute("position").count:e,i.vertexStart=null===r?0:r.vertexStart+r.vertexCount;const l=t.getIndex(),c=null!==l;if(c&&(i.indexCount=-1===n?l.count:n,i.indexStart=null===r?0:r.indexStart+r.indexCount),-1!==i.indexStart&&i.indexStart+i.indexCount>this._maxIndexCount||i.vertexStart+i.vertexCount>this._maxVertexCount)throw new Error("BatchedMesh: Reserved space request exceeds the maximum buffer size.");const h=this._geometryCount;return this._geometryCount++,s.push(i),a.push({start:c?i.indexStart:i.vertexStart,count:-1}),o.push({boxInitialized:!1,box:new Di,sphereInitialized:!1,sphere:new Qi}),this.setGeometryAt(h,t),h}setGeometryAt(t,e){if(t>=this._geometryCount)throw new Error("BatchedMesh: Maximum geometry count reached.");this._validateGeometry(e);const n=this.geometry,i=null!==n.getIndex(),r=n.getIndex(),s=e.getIndex(),a=this._reservedRanges[t];if(i&&s.count>a.indexCount||e.attributes.position.count>a.vertexCount)throw new Error("BatchedMesh: Reserved space not large enough for provided geometry.");const o=a.vertexStart,l=a.vertexCount;for(const t in n.attributes){const i=e.getAttribute(t),r=n.getAttribute(t);vh(i,r,o);const s=i.itemSize;for(let t=i.count,e=l;t=e.length||!1===e[t].active||(e[t].active=!1,this._availableInstanceIds.push(t),this._visibilityChanged=!0),this}getBoundingBoxAt(t,e){if(t>=this._geometryCount)return null;const n=this._bounds[t],i=n.box,r=this.geometry;if(!1===n.boxInitialized){i.makeEmpty();const e=r.index,s=r.attributes.position,a=this._drawRanges[t];for(let t=a.start,n=a.start+a.count;t=this._geometryCount)return null;const n=this._bounds[t],i=n.sphere,r=this.geometry;if(!1===n.sphereInitialized){i.makeEmpty(),this.getBoundingBoxAt(t,ch),ch.getCenter(i.center);const e=r.index,s=r.attributes.position,a=this._drawRanges[t];let o=0;for(let t=a.start,n=a.start+a.count;t=n.length||!1===n[t].active||(e.toArray(r,16*t),i.needsUpdate=!0),this}getMatrixAt(t,e){const n=this._drawInfo,i=this._matricesTexture.image.data;return t>=n.length||!1===n[t].active?null:e.fromArray(i,16*t)}setColorAt(t,e){null===this._colorsTexture&&this._initColorsTexture();const n=this._colorsTexture,i=this._colorsTexture.image.data,r=this._drawInfo;return t>=r.length||!1===r[t].active||(e.toArray(i,4*t),n.needsUpdate=!0),this}getColorAt(t,e){const n=this._colorsTexture.image.data,i=this._drawInfo;return t>=i.length||!1===i[t].active?null:e.fromArray(n,4*t)}setVisibleAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||n[t].visible===e||(n[t].visible=e,this._visibilityChanged=!0),this}getVisibleAt(t){const e=this._drawInfo;return!(t>=e.length||!1===e[t].active)&&e[t].visible}setGeometryIdAt(t,e){const n=this._drawInfo;return t>=n.length||!1===n[t].active||e<0||e>=this._geometryCount?null:(n[t].geometryIndex=e,this)}getGeometryIdAt(t){const e=this._drawInfo;return t>=e.length||!1===e[t].active?-1:e[t].geometryIndex}getGeometryRangeAt(t,e={}){if(t<0||t>=this._geometryCount)return null;const n=this._drawRanges[t];return e.start=n.start,e.count=n.count,e}raycast(t,e){const n=this._drawInfo,i=this._drawRanges,r=this.matrixWorld,s=this.geometry;fh.material=this.material,fh.geometry.index=s.index,fh.geometry.attributes=s.attributes,null===fh.geometry.boundingBox&&(fh.geometry.boundingBox=new Di),null===fh.geometry.boundingSphere&&(fh.geometry.boundingSphere=new Qi);for(let s=0,a=n.length;s({...t}))),this._reservedRanges=t._reservedRanges.map((t=>({...t}))),this._drawInfo=t._drawInfo.map((t=>({...t}))),this._bounds=t._bounds.map((t=>({boxInitialized:t.boxInitialized,box:t.box.clone(),sphereInitialized:t.sphereInitialized,sphere:t.sphere.clone()}))),this._maxInstanceCount=t._maxInstanceCount,this._maxVertexCount=t._maxVertexCount,this._maxIndexCount=t._maxIndexCount,this._geometryInitialized=t._geometryInitialized,this._geometryCount=t._geometryCount,this._multiDrawCounts=t._multiDrawCounts.slice(),this._multiDrawStarts=t._multiDrawStarts.slice(),this._matricesTexture=t._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),null!==this._colorsTexture&&(this._colorsTexture=t._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,null!==this._colorsTexture&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(t,e,n,i,r){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;const s=i.getIndex(),a=null===s?1:s.array.BYTES_PER_ELEMENT,o=this._drawInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,h=this._drawRanges,u=this.perObjectFrustumCulled,d=this._indirectTexture,p=d.image.data;u&&(oh.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),lh.setFromProjectionMatrix(oh,t.coordinateSystem));let m=0;if(this.sortObjects){rh.copy(this.matrixWorld).invert(),uh.setFromMatrixPosition(n.matrixWorld).applyMatrix4(rh),dh.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(rh);for(let t=0,e=o.length;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;ti)return;Th.applyMatrix4(t.matrixWorld);const o=e.ray.origin.distanceTo(Th);return oe.far?void 0:{distance:o,point:Eh.clone().applyMatrix4(t.matrixWorld),index:r,face:null,faceIndex:null,barycoord:null,object:t}}const Ch=new Li,Ph=new Li;class Ih extends Ah{constructor(t,e){super(t,e),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const t=this.geometry;if(null===t.index){const e=t.attributes.position,n=[];for(let t=0,i=e.count;t0){const n=t[e[0]];if(void 0!==n){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let t=0,e=n.length;tr.far)return;s.push({distance:l,distanceToRay:Math.sqrt(o),point:n,index:e,face:null,faceIndex:null,barycoord:null,object:a})}}class kh extends bi{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isVideoTexture=!0,this.minFilter=void 0!==s?s:Mt,this.magFilter=void 0!==r?r:Mt,this.generateMipmaps=!1;const c=this;"requestVideoFrameCallback"in t&&t.requestVideoFrameCallback((function e(){c.needsUpdate=!0,t.requestVideoFrameCallback(e)}))}clone(){return new this.constructor(this.image).copy(this)}update(){const t=this.image;!1==="requestVideoFrameCallback"in t&&t.readyState>=t.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}}class Vh extends bi{constructor(t,e){super({width:t,height:e}),this.isFramebufferTexture=!0,this.magFilter=gt,this.minFilter=gt,this.generateMipmaps=!1,this.needsUpdate=!0}}class Hh extends bi{constructor(t,e,n,i,r,s,a,o,l,c,h,u){super(null,s,a,o,l,c,i,r,h,u),this.isCompressedTexture=!0,this.image={width:e,height:n},this.mipmaps=t,this.flipY=!1,this.generateMipmaps=!1}}class Gh extends Hh{constructor(t,e,n,i,r,s){super(t,e,n,r,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=mt,this.layerUpdates=new Set}addLayerUpdate(t){this.layerUpdates.add(t)}clearLayerUpdates(){this.layerUpdates.clear()}}class Wh extends Hh{constructor(t,e,n){super(void 0,t[0].width,t[0].height,e,n,lt),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=t}}class Xh extends bi{constructor(t,e,n,i,r,s,a,o,l){super(t,e,n,i,r,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}}class jh{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(t,e){const n=this.getUtoTmapping(t);return this.getPoint(n,e)}getPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPoint(n/t));return e}getSpacedPoints(t=5){const e=[];for(let n=0;n<=t;n++)e.push(this.getPointAt(n/t));return e}getLength(){const t=this.getLengths();return t[t.length-1]}getLengths(t=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===t+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;const e=[];let n,i=this.getPoint(0),r=0;e.push(0);for(let s=1;s<=t;s++)n=this.getPoint(s/t),r+=n.distanceTo(i),e.push(r),i=n;return this.cacheArcLengths=e,e}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(t,e){const n=this.getLengths();let i=0;const r=n.length;let s;s=e||t*n[r-1];let a,o=0,l=r-1;for(;o<=l;)if(i=Math.floor(o+(l-o)/2),a=n[i]-s,a<0)o=i+1;else{if(!(a>0)){l=i;break}l=i-1}if(i=l,n[i]===s)return i/(r-1);const c=n[i];return(i+(s-c)/(n[i+1]-c))/(r-1)}getTangent(t,e){const n=1e-4;let i=t-n,r=t+n;i<0&&(i=0),r>1&&(r=1);const s=this.getPoint(i),a=this.getPoint(r),o=e||(s.isVector2?new ti:new Li);return o.copy(a).sub(s).normalize(),o}getTangentAt(t,e){const n=this.getUtoTmapping(t);return this.getTangent(n,e)}computeFrenetFrames(t,e){const n=new Li,i=[],r=[],s=[],a=new Li,o=new lr;for(let e=0;e<=t;e++){const n=e/t;i[e]=this.getTangentAt(n,new Li)}r[0]=new Li,s[0]=new Li;let l=Number.MAX_VALUE;const c=Math.abs(i[0].x),h=Math.abs(i[0].y),u=Math.abs(i[0].z);c<=l&&(l=c,n.set(1,0,0)),h<=l&&(l=h,n.set(0,1,0)),u<=l&&n.set(0,0,1),a.crossVectors(i[0],n).normalize(),r[0].crossVectors(i[0],a),s[0].crossVectors(i[0],r[0]);for(let e=1;e<=t;e++){if(r[e]=r[e-1].clone(),s[e]=s[e-1].clone(),a.crossVectors(i[e-1],i[e]),a.length()>Number.EPSILON){a.normalize();const t=Math.acos(Yn(i[e-1].dot(i[e]),-1,1));r[e].applyMatrix4(o.makeRotationAxis(a,t))}s[e].crossVectors(i[e],r[e])}if(!0===e){let e=Math.acos(Yn(r[0].dot(r[t]),-1,1));e/=t,i[0].dot(a.crossVectors(r[0],r[t]))>0&&(e=-e);for(let n=1;n<=t;n++)r[n].applyMatrix4(o.makeRotationAxis(i[n],e*n)),s[n].crossVectors(i[n],r[n])}return{tangents:i,normals:r,binormals:s}}clone(){return(new this.constructor).copy(this)}copy(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}toJSON(){const t={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return t.arcLengthDivisions=this.arcLengthDivisions,t.type=this.type,t}fromJSON(t){return this.arcLengthDivisions=t.arcLengthDivisions,this}}class qh extends jh{constructor(t=0,e=0,n=1,i=1,r=0,s=2*Math.PI,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=t,this.aY=e,this.xRadius=n,this.yRadius=i,this.aStartAngle=r,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(t,e=new ti){const n=e,i=2*Math.PI;let r=this.aEndAngle-this.aStartAngle;const s=Math.abs(r)i;)r-=i;r0?0:(Math.floor(Math.abs(l)/r)+1)*r:0===c&&l===r-1&&(l=r-2,c=1),this.closed||l>0?a=i[(l-1)%r]:(Jh.subVectors(i[0],i[1]).add(i[0]),a=Jh);const h=i[l%r],u=i[(l+1)%r];if(this.closed||l+2i.length-2?i.length-1:s+1],h=i[s>i.length-3?i.length-1:s+2];return n.set(eu(a,o.x,l.x,c.x,h.x),eu(a,o.y,l.y,c.y,h.y)),n}copy(t){super.copy(t),this.points=[];for(let e=0,n=t.points.length;e=n){const t=i[r]-n,s=this.curves[r],a=s.getLength(),o=0===a?0:1-t/a;return s.getPointAt(o,e)}r++}return null}getLength(){const t=this.getCurveLengths();return t[t.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;const t=[];let e=0;for(let n=0,i=this.curves.length;n1&&!e[e.length-1].equals(e[0])&&e.push(e[0]),e}copy(t){super.copy(t),this.curves=[];for(let e=0,n=t.curves.length;e0){const t=l.getPoint(0);t.equals(this.currentPoint)||this.lineTo(t.x,t.y)}this.curves.push(l);const c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(t){return super.copy(t),this.currentPoint.copy(t.currentPoint),this}toJSON(){const t=super.toJSON();return t.currentPoint=this.currentPoint.toArray(),t}fromJSON(t){return super.fromJSON(t),this.currentPoint.fromArray(t.currentPoint),this}}class mu extends Cs{constructor(t=[new ti(0,-.5),new ti(.5,0),new ti(0,.5)],e=12,n=0,i=2*Math.PI){super(),this.type="LatheGeometry",this.parameters={points:t,segments:e,phiStart:n,phiLength:i},e=Math.floor(e),i=Yn(i,0,2*Math.PI);const r=[],s=[],a=[],o=[],l=[],c=1/e,h=new Li,u=new ti,d=new Li,p=new Li,m=new Li;let f=0,g=0;for(let e=0;e<=t.length-1;e++)switch(e){case 0:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,m.copy(d),d.normalize(),o.push(d.x,d.y,d.z);break;case t.length-1:o.push(m.x,m.y,m.z);break;default:f=t[e+1].x-t[e].x,g=t[e+1].y-t[e].y,d.x=1*g,d.y=-f,d.z=0*g,p.copy(d),d.x+=m.x,d.y+=m.y,d.z+=m.z,d.normalize(),o.push(d.x,d.y,d.z),m.copy(p)}for(let r=0;r<=e;r++){const d=n+r*c*i,p=Math.sin(d),m=Math.cos(d);for(let n=0;n<=t.length-1;n++){h.x=t[n].x*p,h.y=t[n].y,h.z=t[n].x*m,s.push(h.x,h.y,h.z),u.x=r/e,u.y=n/(t.length-1),a.push(u.x,u.y);const i=o[3*n+0]*p,c=o[3*n+1],d=o[3*n+0]*m;l.push(i,c,d)}}for(let n=0;n0&&(c.push(r,s,o),_+=3),e>0&&(c.push(s,a,o),_+=3)}l.addGroup(g,_,0),g+=_}(),!1===s&&(t>0&&v(!0),e>0&&v(!1)),this.setIndex(c),this.setAttribute("position",new Ms(h,3)),this.setAttribute("normal",new Ms(u,3)),this.setAttribute("uv",new Ms(d,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new vu(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class _u extends vu{constructor(t=1,e=1,n=32,i=1,r=!1,s=0,a=2*Math.PI){super(0,t,e,n,i,r,s,a),this.type="ConeGeometry",this.parameters={radius:t,height:e,radialSegments:n,heightSegments:i,openEnded:r,thetaStart:s,thetaLength:a}}static fromJSON(t){return new _u(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}}class xu extends Cs{constructor(t=[],e=[],n=1,i=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:e,radius:n,detail:i};const r=[],s=[];function a(t,e,n,i){const r=i+1,s=[];for(let i=0;i<=r;i++){s[i]=[];const a=t.clone().lerp(n,i/r),o=e.clone().lerp(n,i/r),l=r-i;for(let t=0;t<=l;t++)s[i][t]=0===t&&i===r?a:a.clone().lerp(o,t/l)}for(let t=0;t.9&&a<.1&&(e<.2&&(s[t+0]+=1),n<.2&&(s[t+2]+=1),i<.2&&(s[t+4]+=1))}}()}(),this.setAttribute("position",new Ms(r,3)),this.setAttribute("normal",new Ms(r.slice(),3)),this.setAttribute("uv",new Ms(s,2)),0===i?this.computeVertexNormals():this.normalizeNormals()}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new xu(t.vertices,t.indices,t.radius,t.details)}}class yu extends xu{constructor(t=1,e=0){const n=(1+Math.sqrt(5))/2,i=1/n;super([-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-i,-n,0,-i,n,0,i,-n,0,i,n,-i,-n,0,-i,n,0,i,-n,0,i,n,0,-n,0,-i,n,0,-i,-n,0,i,n,0,i],[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9],t,e),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:e}}static fromJSON(t){return new yu(t.radius,t.detail)}}const Mu=new Li,Su=new Li,bu=new Li,wu=new Zr;class Tu extends Cs{constructor(t=null,e=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:t,thresholdAngle:e},null!==t){const n=4,i=Math.pow(10,n),r=Math.cos(Xn*e),s=t.getIndex(),a=t.getAttribute("position"),o=s?s.count:a.count,l=[0,0,0],c=["a","b","c"],h=new Array(3),u={},d=[];for(let t=0;t80*n){o=c=t[0],l=h=t[1];for(let e=n;ec&&(c=u),d>h&&(h=d);p=Math.max(c-o,h-l),p=0!==p?32767/p:0}return Pu(s,a,n,o,l,p,0),a};function Ru(t,e,n,i,r){let s,a;if(r===function(t,e,n,i){let r=0;for(let s=e,a=n-i;s0)for(s=e;s=e;s-=i)a=Zu(s,t[s],t[s+1],a);return a&&Gu(a,a.next)&&(Ju(a),a=a.next),a}function Cu(t,e){if(!t)return t;e||(e=t);let n,i=t;do{if(n=!1,i.steiner||!Gu(i,i.next)&&0!==Hu(i.prev,i,i.next))i=i.next;else{if(Ju(i),i=e=i.prev,i===i.next)break;n=!0}}while(n||i!==e);return e}function Pu(t,e,n,i,r,s,a){if(!t)return;!a&&s&&function(t,e,n,i){let r=t;do{0===r.z&&(r.z=Bu(r.x,r.y,e,n,i)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){let e,n,i,r,s,a,o,l,c=1;do{for(n=t,t=null,s=null,a=0;n;){for(a++,i=n,o=0,e=0;e0||l>0&&i;)0!==o&&(0===l||!i||n.z<=i.z)?(r=n,n=n.nextZ,o--):(r=i,i=i.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;n=i}s.nextZ=null,c*=2}while(a>1)}(r)}(t,i,r,s);let o,l,c=t;for(;t.prev!==t.next;)if(o=t.prev,l=t.next,s?Lu(t,i,r,s):Iu(t))e.push(o.i/n|0),e.push(t.i/n|0),e.push(l.i/n|0),Ju(t),t=l.next,c=l.next;else if((t=l)===c){a?1===a?Pu(t=Uu(Cu(t),e,n),e,n,i,r,s,2):2===a&&Nu(t,e,n,i,r,s):Pu(Cu(t),e,n,i,r,s,1);break}}function Iu(t){const e=t.prev,n=t,i=t.next;if(Hu(e,n,i)>=0)return!1;const r=e.x,s=n.x,a=i.x,o=e.y,l=n.y,c=i.y,h=rs?r>a?r:a:s>a?s:a,p=o>l?o>c?o:c:l>c?l:c;let m=i.next;for(;m!==e;){if(m.x>=h&&m.x<=d&&m.y>=u&&m.y<=p&&ku(r,o,s,l,a,c,m.x,m.y)&&Hu(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Lu(t,e,n,i){const r=t.prev,s=t,a=t.next;if(Hu(r,s,a)>=0)return!1;const o=r.x,l=s.x,c=a.x,h=r.y,u=s.y,d=a.y,p=ol?o>c?o:c:l>c?l:c,g=h>u?h>d?h:d:u>d?u:d,v=Bu(p,m,e,n,i),_=Bu(f,g,e,n,i);let x=t.prevZ,y=t.nextZ;for(;x&&x.z>=v&&y&&y.z<=_;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&ku(o,h,l,u,c,d,x.x,x.y)&&Hu(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&ku(o,h,l,u,c,d,y.x,y.y)&&Hu(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;x&&x.z>=v;){if(x.x>=p&&x.x<=f&&x.y>=m&&x.y<=g&&x!==r&&x!==a&&ku(o,h,l,u,c,d,x.x,x.y)&&Hu(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;y&&y.z<=_;){if(y.x>=p&&y.x<=f&&y.y>=m&&y.y<=g&&y!==r&&y!==a&&ku(o,h,l,u,c,d,y.x,y.y)&&Hu(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Uu(t,e,n){let i=t;do{const r=i.prev,s=i.next.next;!Gu(r,s)&&Wu(r,i,i.next,s)&&qu(r,s)&&qu(s,r)&&(e.push(r.i/n|0),e.push(i.i/n|0),e.push(s.i/n|0),Ju(i),Ju(i.next),i=t=s),i=i.next}while(i!==t);return Cu(i)}function Nu(t,e,n,i,r,s){let a=t;do{let t=a.next.next;for(;t!==a.prev;){if(a.i!==t.i&&Vu(a,t)){let o=Yu(a,t);return a=Cu(a,a.next),o=Cu(o,o.next),Pu(a,e,n,i,r,s,0),void Pu(o,e,n,i,r,s,0)}t=t.next}a=a.next}while(a!==t)}function Du(t,e){return t.x-e.x}function Ou(t,e){const n=function(t,e){let n,i=e,r=-1/0;const s=t.x,a=t.y;do{if(a<=i.y&&a>=i.next.y&&i.next.y!==i.y){const t=i.x+(a-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(t<=s&&t>r&&(r=t,n=i.x=i.x&&i.x>=l&&s!==i.x&&ku(an.x||i.x===n.x&&Fu(n,i)))&&(n=i,u=h)),i=i.next}while(i!==o);return n}(t,e);if(!n)return e;const i=Yu(n,t);return Cu(i,i.next),Cu(n,n.next)}function Fu(t,e){return Hu(t.prev,t,e.prev)<0&&Hu(e.next,t,t.next)<0}function Bu(t,e,n,i,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-n)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function zu(t){let e=t,n=t;do{(e.x=(t-a)*(s-o)&&(t-a)*(i-o)>=(n-a)*(e-o)&&(n-a)*(s-o)>=(r-a)*(i-o)}function Vu(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){let n=t;do{if(n.i!==t.i&&n.next.i!==t.i&&n.i!==e.i&&n.next.i!==e.i&&Wu(n,n.next,t,e))return!0;n=n.next}while(n!==t);return!1}(t,e)&&(qu(t,e)&&qu(e,t)&&function(t,e){let n=t,i=!1;const r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{n.y>s!=n.next.y>s&&n.next.y!==n.y&&r<(n.next.x-n.x)*(s-n.y)/(n.next.y-n.y)+n.x&&(i=!i),n=n.next}while(n!==t);return i}(t,e)&&(Hu(t.prev,t,e.prev)||Hu(t,e.prev,e))||Gu(t,e)&&Hu(t.prev,t,t.next)>0&&Hu(e.prev,e,e.next)>0)}function Hu(t,e,n){return(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y)}function Gu(t,e){return t.x===e.x&&t.y===e.y}function Wu(t,e,n,i){const r=ju(Hu(t,e,n)),s=ju(Hu(t,e,i)),a=ju(Hu(n,i,t)),o=ju(Hu(n,i,e));return r!==s&&a!==o||(!(0!==r||!Xu(t,n,e))||(!(0!==s||!Xu(t,i,e))||(!(0!==a||!Xu(n,t,i))||!(0!==o||!Xu(n,e,i)))))}function Xu(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function ju(t){return t>0?1:t<0?-1:0}function qu(t,e){return Hu(t.prev,t,t.next)<0?Hu(t,e,t.next)>=0&&Hu(t,t.prev,e)>=0:Hu(t,e,t.prev)<0||Hu(t,t.next,e)<0}function Yu(t,e){const n=new Ku(t.i,t.x,t.y),i=new Ku(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,n.next=r,r.prev=n,i.next=n,n.prev=i,s.next=i,i.prev=s,i}function Zu(t,e,n,i){const r=new Ku(t,e,n);return i?(r.next=i.next,r.prev=i,i.next.prev=r,i.next=r):(r.prev=r,r.next=r),r}function Ju(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function Ku(t,e,n){this.i=t,this.x=e,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}class $u{static area(t){const e=t.length;let n=0;for(let i=e-1,r=0;r2&&t[e-1].equals(t[0])&&t.pop()}function td(t,e){for(let n=0;nNumber.EPSILON){const u=Math.sqrt(h),d=Math.sqrt(l*l+c*c),p=e.x-o/u,m=e.y+a/u,f=((n.x-c/d-p)*c-(n.y+l/d-m)*l)/(a*c-o*l);i=p+a*f-t.x,r=m+o*f-t.y;const g=i*i+r*r;if(g<=2)return new ti(i,r);s=Math.sqrt(g/2)}else{let t=!1;a>Number.EPSILON?l>Number.EPSILON&&(t=!0):a<-Number.EPSILON?l<-Number.EPSILON&&(t=!0):Math.sign(o)===Math.sign(c)&&(t=!0),t?(i=-o,r=a,s=Math.sqrt(h)):(i=a,r=o,s=Math.sqrt(h/2))}return new ti(i/s,r/s)}const I=[];for(let t=0,e=E.length,n=e-1,i=t+1;t=0;t--){const e=t/p,n=h*Math.cos(e*Math.PI/2),i=u*Math.sin(e*Math.PI/2)+d;for(let t=0,e=E.length;t=0;){const i=n;let r=n-1;r<0&&(r=t.length-1);for(let t=0,n=o+2*p;t0)&&d.push(e,r,l),(t!==n-1||o0!=t>0&&this.version++,this._anisotropy=t}get clearcoat(){return this._clearcoat}set clearcoat(t){this._clearcoat>0!=t>0&&this.version++,this._clearcoat=t}get iridescence(){return this._iridescence}set iridescence(t){this._iridescence>0!=t>0&&this.version++,this._iridescence=t}get dispersion(){return this._dispersion}set dispersion(t){this._dispersion>0!=t>0&&this.version++,this._dispersion=t}get sheen(){return this._sheen}set sheen(t){this._sheen>0!=t>0&&this.version++,this._sheen=t}get transmission(){return this._transmission}set transmission(t){this._transmission>0!=t>0&&this.version++,this._transmission=t}copy(t){return super.copy(t),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=t.anisotropy,this.anisotropyRotation=t.anisotropyRotation,this.anisotropyMap=t.anisotropyMap,this.clearcoat=t.clearcoat,this.clearcoatMap=t.clearcoatMap,this.clearcoatRoughness=t.clearcoatRoughness,this.clearcoatRoughnessMap=t.clearcoatRoughnessMap,this.clearcoatNormalMap=t.clearcoatNormalMap,this.clearcoatNormalScale.copy(t.clearcoatNormalScale),this.dispersion=t.dispersion,this.ior=t.ior,this.iridescence=t.iridescence,this.iridescenceMap=t.iridescenceMap,this.iridescenceIOR=t.iridescenceIOR,this.iridescenceThicknessRange=[...t.iridescenceThicknessRange],this.iridescenceThicknessMap=t.iridescenceThicknessMap,this.sheen=t.sheen,this.sheenColor.copy(t.sheenColor),this.sheenColorMap=t.sheenColorMap,this.sheenRoughness=t.sheenRoughness,this.sheenRoughnessMap=t.sheenRoughnessMap,this.transmission=t.transmission,this.transmissionMap=t.transmissionMap,this.thickness=t.thickness,this.thicknessMap=t.thicknessMap,this.attenuationDistance=t.attenuationDistance,this.attenuationColor.copy(t.attenuationColor),this.specularIntensity=t.specularIntensity,this.specularIntensityMap=t.specularIntensityMap,this.specularColor.copy(t.specularColor),this.specularColorMap=t.specularColorMap,this}}class xd extends is{constructor(t){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new ts(16777215),this.specular=new ts(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ts(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ti(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.specular.copy(t.specular),this.shininess=t.shininess,this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class yd extends is{constructor(t){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new ts(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ts(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ti(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.gradientMap=t.gradientMap,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.fog=t.fog,this}}class Md extends is{constructor(t){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ti(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(t)}copy(t){return super.copy(t),this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.flatShading=t.flatShading,this}}class Sd extends is{constructor(t){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new ts(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new ts(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ti(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new _r,this.combine=Y,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.color.copy(t.color),this.map=t.map,this.lightMap=t.lightMap,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive.copy(t.emissive),this.emissiveMap=t.emissiveMap,this.emissiveIntensity=t.emissiveIntensity,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.envMapRotation.copy(t.envMapRotation),this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.wireframe=t.wireframe,this.wireframeLinewidth=t.wireframeLinewidth,this.wireframeLinecap=t.wireframeLinecap,this.wireframeLinejoin=t.wireframeLinejoin,this.flatShading=t.flatShading,this.fog=t.fog,this}}class bd extends is{constructor(t){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new ts(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ti(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(t)}copy(t){return super.copy(t),this.defines={MATCAP:""},this.color.copy(t.color),this.matcap=t.matcap,this.map=t.map,this.bumpMap=t.bumpMap,this.bumpScale=t.bumpScale,this.normalMap=t.normalMap,this.normalMapType=t.normalMapType,this.normalScale.copy(t.normalScale),this.displacementMap=t.displacementMap,this.displacementScale=t.displacementScale,this.displacementBias=t.displacementBias,this.alphaMap=t.alphaMap,this.flatShading=t.flatShading,this.fog=t.fog,this}}class wd extends xh{constructor(t){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(t)}copy(t){return super.copy(t),this.scale=t.scale,this.dashSize=t.dashSize,this.gapSize=t.gapSize,this}}function Td(t,e,n){return!t||!n&&t.constructor===e?t:"number"==typeof e.BYTES_PER_ELEMENT?new e(t):Array.prototype.slice.call(t)}function Ed(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function Ad(t){const e=t.length,n=new Array(e);for(let t=0;t!==e;++t)n[t]=t;return n.sort((function(e,n){return t[e]-t[n]})),n}function Rd(t,e,n){const i=t.length,r=new t.constructor(i);for(let s=0,a=0;a!==i;++s){const i=n[s]*e;for(let n=0;n!==e;++n)r[a++]=t[i+n]}return r}function Cd(t,e,n,i){let r=1,s=t[0];for(;void 0!==s&&void 0===s[i];)s=t[r++];if(void 0===s)return;let a=s[i];if(void 0!==a)if(Array.isArray(a))do{a=s[i],void 0!==a&&(e.push(s.time),n.push.apply(n,a)),s=t[r++]}while(void 0!==s);else if(void 0!==a.toArray)do{a=s[i],void 0!==a&&(e.push(s.time),a.toArray(n,n.length)),s=t[r++]}while(void 0!==s);else do{a=s[i],void 0!==a&&(e.push(s.time),n.push(a)),s=t[r++]}while(void 0!==s)}const Pd={convertArray:Td,isTypedArray:Ed,getKeyframeOrder:Ad,sortedArray:Rd,flattenJSON:Cd,subclip:function(t,e,n,i,r=30){const s=t.clone();s.name=e;const a=[];for(let t=0;t=i)){l.push(e.times[t]);for(let n=0;ns.tracks[t].times[0]&&(o=s.tracks[t].times[0]);for(let t=0;t=i.times[u]){const t=u*l+o,e=t+l-o;d=i.values.slice(t,e)}else{const t=i.createInterpolant(),e=o,n=l-o;t.evaluate(s),d=t.resultBuffer.slice(e,n)}if("quaternion"===r){(new Ii).fromArray(d).normalize().conjugate().toArray(d)}const p=a.times.length;for(let t=0;t=r)break t;{const a=e[1];t=r)break e}s=n,n=0}}for(;n>>1;te;)--s;if(++s,0!==r||s!==i){r>=s&&(s=Math.max(s,1),r=s-1);const t=this.getValueSize();this.times=n.slice(r,s),this.values=this.values.slice(r*t,s*t)}return this}validate(){let t=!0;const e=this.getValueSize();e-Math.floor(e)!=0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),t=!1);const n=this.times,i=this.values,r=n.length;0===r&&(console.error("THREE.KeyframeTrack: Track is empty.",this),t=!1);let s=null;for(let e=0;e!==r;e++){const i=n[e];if("number"==typeof i&&isNaN(i)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,e,i),t=!1;break}if(null!==s&&s>i){console.error("THREE.KeyframeTrack: Out of order keys.",this,e,i,s),t=!1;break}s=i}if(void 0!==i&&Ed(i))for(let e=0,n=i.length;e!==n;++e){const n=i[e];if(isNaN(n)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,e,n),t=!1;break}}return t}optimize(){const t=this.times.slice(),e=this.values.slice(),n=this.getValueSize(),i=this.getInterpolation()===Ne,r=t.length-1;let s=1;for(let a=1;a0){t[s]=t[r];for(let t=r*n,i=s*n,a=0;a!==n;++a)e[i+a]=e[t+a];++s}return s!==t.length?(this.times=t.slice(0,s),this.values=e.slice(0,s*n)):(this.times=t,this.values=e),this}clone(){const t=this.times.slice(),e=this.values.slice(),n=new(0,this.constructor)(this.name,t,e);return n.createInterpolant=this.createInterpolant,n}}Dd.prototype.TimeBufferType=Float32Array,Dd.prototype.ValueBufferType=Float32Array,Dd.prototype.DefaultInterpolation=Ue;class Od extends Dd{constructor(t,e,n){super(t,e,n)}}Od.prototype.ValueTypeName="bool",Od.prototype.ValueBufferType=Array,Od.prototype.DefaultInterpolation=Le,Od.prototype.InterpolantFactoryMethodLinear=void 0,Od.prototype.InterpolantFactoryMethodSmooth=void 0;class Fd extends Dd{}Fd.prototype.ValueTypeName="color";class Bd extends Dd{}Bd.prototype.ValueTypeName="number";class zd extends Id{constructor(t,e,n,i){super(t,e,n,i)}interpolate_(t,e,n,i){const r=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(n-e)/(i-e);let l=t*a;for(let t=l+a;l!==t;l+=4)Ii.slerpFlat(r,0,s,l-a,s,l,o);return r}}class kd extends Dd{InterpolantFactoryMethodLinear(t){return new zd(this.times,this.values,this.getValueSize(),t)}}kd.prototype.ValueTypeName="quaternion",kd.prototype.InterpolantFactoryMethodSmooth=void 0;class Vd extends Dd{constructor(t,e,n){super(t,e,n)}}Vd.prototype.ValueTypeName="string",Vd.prototype.ValueBufferType=Array,Vd.prototype.DefaultInterpolation=Le,Vd.prototype.InterpolantFactoryMethodLinear=void 0,Vd.prototype.InterpolantFactoryMethodSmooth=void 0;class Hd extends Dd{}Hd.prototype.ValueTypeName="vector";class Gd{constructor(t="",e=-1,n=[],i=2500){this.name=t,this.tracks=n,this.duration=e,this.blendMode=i,this.uuid=qn(),this.duration<0&&this.resetDuration()}static parse(t){const e=[],n=t.tracks,i=1/(t.fps||1);for(let t=0,r=n.length;t!==r;++t)e.push(Wd(n[t]).scale(i));const r=new this(t.name,t.duration,e,t.blendMode);return r.uuid=t.uuid,r}static toJSON(t){const e=[],n=t.tracks,i={name:t.name,duration:t.duration,tracks:e,uuid:t.uuid,blendMode:t.blendMode};for(let t=0,i=n.length;t!==i;++t)e.push(Dd.toJSON(n[t]));return i}static CreateFromMorphTargetSequence(t,e,n,i){const r=e.length,s=[];for(let t=0;t1){const t=s[1];let e=i[t];e||(i[t]=e=[]),e.push(n)}}const s=[];for(const t in i)s.push(this.CreateFromMorphTargetSequence(t,i[t],e,n));return s}static parseAnimation(t,e){if(!t)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;const n=function(t,e,n,i,r){if(0!==n.length){const s=[],a=[];Cd(n,s,a,i),0!==s.length&&r.push(new t(e,s,a))}},i=[],r=t.name||"default",s=t.fps||30,a=t.blendMode;let o=t.length||-1;const l=t.hierarchy||[];for(let t=0;t{e&&e(r),this.manager.itemEnd(t)}),0),r;if(void 0!==Zd[t])return void Zd[t].push({onLoad:e,onProgress:n,onError:i});Zd[t]=[],Zd[t].push({onLoad:e,onProgress:n,onError:i});const s=new Request(t,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then((e=>{if(200===e.status||0===e.status){if(0===e.status&&console.warn("THREE.FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===e.body||void 0===e.body.getReader)return e;const n=Zd[t],i=e.body.getReader(),r=e.headers.get("X-File-Size")||e.headers.get("Content-Length"),s=r?parseInt(r):0,a=0!==s;let o=0;const l=new ReadableStream({start(t){!function e(){i.read().then((({done:i,value:r})=>{if(i)t.close();else{o+=r.byteLength;const i=new ProgressEvent("progress",{lengthComputable:a,loaded:o,total:s});for(let t=0,e=n.length;t{t.error(e)}))}()}});return new Response(l)}throw new Jd(`fetch for "${e.url}" responded with ${e.status}: ${e.statusText}`,e)})).then((t=>{switch(o){case"arraybuffer":return t.arrayBuffer();case"blob":return t.blob();case"document":return t.text().then((t=>(new DOMParser).parseFromString(t,a)));case"json":return t.json();default:if(void 0===a)return t.text();{const e=/charset="?([^;"\s]*)"?/i.exec(a),n=e&&e[1]?e[1].toLowerCase():void 0,i=new TextDecoder(n);return t.arrayBuffer().then((t=>i.decode(t)))}}})).then((e=>{Xd.add(t,e);const n=Zd[t];delete Zd[t];for(let t=0,i=n.length;t{const n=Zd[t];if(void 0===n)throw this.manager.itemError(t),e;delete Zd[t];for(let t=0,i=n.length;t{this.manager.itemEnd(t)})),this.manager.itemStart(t)}setResponseType(t){return this.responseType=t,this}setMimeType(t){return this.mimeType=t,this}}class $d extends Yd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new Kd(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(n){try{e(r.parse(JSON.parse(n)))}catch(e){i?i(e):console.error(e),r.manager.itemError(t)}}),n,i)}parse(t){const e=[];for(let n=0;n0:i.vertexColors=t.vertexColors),void 0!==t.uniforms)for(const e in t.uniforms){const r=t.uniforms[e];switch(i.uniforms[e]={},r.type){case"t":i.uniforms[e].value=n(r.value);break;case"c":i.uniforms[e].value=(new ts).setHex(r.value);break;case"v2":i.uniforms[e].value=(new ti).fromArray(r.value);break;case"v3":i.uniforms[e].value=(new Li).fromArray(r.value);break;case"v4":i.uniforms[e].value=(new wi).fromArray(r.value);break;case"m3":i.uniforms[e].value=(new ei).fromArray(r.value);break;case"m4":i.uniforms[e].value=(new lr).fromArray(r.value);break;default:i.uniforms[e].value=r.value}}if(void 0!==t.defines&&(i.defines=t.defines),void 0!==t.vertexShader&&(i.vertexShader=t.vertexShader),void 0!==t.fragmentShader&&(i.fragmentShader=t.fragmentShader),void 0!==t.glslVersion&&(i.glslVersion=t.glslVersion),void 0!==t.extensions)for(const e in t.extensions)i.extensions[e]=t.extensions[e];if(void 0!==t.lights&&(i.lights=t.lights),void 0!==t.clipping&&(i.clipping=t.clipping),void 0!==t.size&&(i.size=t.size),void 0!==t.sizeAttenuation&&(i.sizeAttenuation=t.sizeAttenuation),void 0!==t.map&&(i.map=n(t.map)),void 0!==t.matcap&&(i.matcap=n(t.matcap)),void 0!==t.alphaMap&&(i.alphaMap=n(t.alphaMap)),void 0!==t.bumpMap&&(i.bumpMap=n(t.bumpMap)),void 0!==t.bumpScale&&(i.bumpScale=t.bumpScale),void 0!==t.normalMap&&(i.normalMap=n(t.normalMap)),void 0!==t.normalMapType&&(i.normalMapType=t.normalMapType),void 0!==t.normalScale){let e=t.normalScale;!1===Array.isArray(e)&&(e=[e,e]),i.normalScale=(new ti).fromArray(e)}return void 0!==t.displacementMap&&(i.displacementMap=n(t.displacementMap)),void 0!==t.displacementScale&&(i.displacementScale=t.displacementScale),void 0!==t.displacementBias&&(i.displacementBias=t.displacementBias),void 0!==t.roughnessMap&&(i.roughnessMap=n(t.roughnessMap)),void 0!==t.metalnessMap&&(i.metalnessMap=n(t.metalnessMap)),void 0!==t.emissiveMap&&(i.emissiveMap=n(t.emissiveMap)),void 0!==t.emissiveIntensity&&(i.emissiveIntensity=t.emissiveIntensity),void 0!==t.specularMap&&(i.specularMap=n(t.specularMap)),void 0!==t.specularIntensityMap&&(i.specularIntensityMap=n(t.specularIntensityMap)),void 0!==t.specularColorMap&&(i.specularColorMap=n(t.specularColorMap)),void 0!==t.envMap&&(i.envMap=n(t.envMap)),void 0!==t.envMapRotation&&i.envMapRotation.fromArray(t.envMapRotation),void 0!==t.envMapIntensity&&(i.envMapIntensity=t.envMapIntensity),void 0!==t.reflectivity&&(i.reflectivity=t.reflectivity),void 0!==t.refractionRatio&&(i.refractionRatio=t.refractionRatio),void 0!==t.lightMap&&(i.lightMap=n(t.lightMap)),void 0!==t.lightMapIntensity&&(i.lightMapIntensity=t.lightMapIntensity),void 0!==t.aoMap&&(i.aoMap=n(t.aoMap)),void 0!==t.aoMapIntensity&&(i.aoMapIntensity=t.aoMapIntensity),void 0!==t.gradientMap&&(i.gradientMap=n(t.gradientMap)),void 0!==t.clearcoatMap&&(i.clearcoatMap=n(t.clearcoatMap)),void 0!==t.clearcoatRoughnessMap&&(i.clearcoatRoughnessMap=n(t.clearcoatRoughnessMap)),void 0!==t.clearcoatNormalMap&&(i.clearcoatNormalMap=n(t.clearcoatNormalMap)),void 0!==t.clearcoatNormalScale&&(i.clearcoatNormalScale=(new ti).fromArray(t.clearcoatNormalScale)),void 0!==t.iridescenceMap&&(i.iridescenceMap=n(t.iridescenceMap)),void 0!==t.iridescenceThicknessMap&&(i.iridescenceThicknessMap=n(t.iridescenceThicknessMap)),void 0!==t.transmissionMap&&(i.transmissionMap=n(t.transmissionMap)),void 0!==t.thicknessMap&&(i.thicknessMap=n(t.thicknessMap)),void 0!==t.anisotropyMap&&(i.anisotropyMap=n(t.anisotropyMap)),void 0!==t.sheenColorMap&&(i.sheenColorMap=n(t.sheenColorMap)),void 0!==t.sheenRoughnessMap&&(i.sheenRoughnessMap=n(t.sheenRoughnessMap)),i}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return bp.createMaterialFromType(t)}static createMaterialFromType(t){return new{ShadowMaterial:fd,SpriteMaterial:uc,RawShaderMaterial:gd,ShaderMaterial:Ys,PointsMaterial:Uh,MeshPhysicalMaterial:_d,MeshStandardMaterial:vd,MeshPhongMaterial:xd,MeshToonMaterial:yd,MeshNormalMaterial:Md,MeshLambertMaterial:Sd,MeshDepthMaterial:zl,MeshDistanceMaterial:kl,MeshBasicMaterial:rs,MeshMatcapMaterial:bd,LineDashedMaterial:wd,LineBasicMaterial:xh,Material:is}[t]}}class wp{static decodeText(t){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),"undefined"!=typeof TextDecoder)return(new TextDecoder).decode(t);let e="";for(let n=0,i=t.length;n0){const n=new jd(e);r=new tp(n),r.setCrossOrigin(this.crossOrigin);for(let e=0,n=t.length;e0){i=new tp(this.manager),i.setCrossOrigin(this.crossOrigin);for(let e=0,i=t.length;e{const e=new Di;e.min.fromArray(t.boxMin),e.max.fromArray(t.boxMax);const n=new Qi;return n.radius=t.sphereRadius,n.center.fromArray(t.sphereCenter),{boxInitialized:t.boxInitialized,box:e,sphereInitialized:t.sphereInitialized,sphere:n}})),s._maxInstanceCount=t.maxInstanceCount,s._maxVertexCount=t.maxVertexCount,s._maxIndexCount=t.maxIndexCount,s._geometryInitialized=t.geometryInitialized,s._geometryCount=t.geometryCount,s._matricesTexture=h(t.matricesTexture.uuid),void 0!==t.colorsTexture&&(s._colorsTexture=h(t.colorsTexture.uuid));break;case"LOD":s=new Cc;break;case"Line":s=new Ah(l(t.geometry),c(t.material));break;case"LineLoop":s=new Lh(l(t.geometry),c(t.material));break;case"LineSegments":s=new Ih(l(t.geometry),c(t.material));break;case"PointCloud":case"Points":s=new Bh(l(t.geometry),c(t.material));break;case"Sprite":s=new Tc(c(t.material));break;case"Group":s=new Zl;break;case"Bone":s=new kc;break;default:s=new Dr}if(s.uuid=t.uuid,void 0!==t.name&&(s.name=t.name),void 0!==t.matrix?(s.matrix.fromArray(t.matrix),void 0!==t.matrixAutoUpdate&&(s.matrixAutoUpdate=t.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(void 0!==t.position&&s.position.fromArray(t.position),void 0!==t.rotation&&s.rotation.fromArray(t.rotation),void 0!==t.quaternion&&s.quaternion.fromArray(t.quaternion),void 0!==t.scale&&s.scale.fromArray(t.scale)),void 0!==t.up&&s.up.fromArray(t.up),void 0!==t.castShadow&&(s.castShadow=t.castShadow),void 0!==t.receiveShadow&&(s.receiveShadow=t.receiveShadow),t.shadow&&(void 0!==t.shadow.intensity&&(s.shadow.intensity=t.shadow.intensity),void 0!==t.shadow.bias&&(s.shadow.bias=t.shadow.bias),void 0!==t.shadow.normalBias&&(s.shadow.normalBias=t.shadow.normalBias),void 0!==t.shadow.radius&&(s.shadow.radius=t.shadow.radius),void 0!==t.shadow.mapSize&&s.shadow.mapSize.fromArray(t.shadow.mapSize),void 0!==t.shadow.camera&&(s.shadow.camera=this.parseObject(t.shadow.camera))),void 0!==t.visible&&(s.visible=t.visible),void 0!==t.frustumCulled&&(s.frustumCulled=t.frustumCulled),void 0!==t.renderOrder&&(s.renderOrder=t.renderOrder),void 0!==t.userData&&(s.userData=t.userData),void 0!==t.layers&&(s.layers.mask=t.layers),void 0!==t.children){const a=t.children;for(let t=0;t{e&&e(n),r.manager.itemEnd(t)})).catch((t=>{i&&i(t)})):(setTimeout((function(){e&&e(s),r.manager.itemEnd(t)}),0),s);const a={};a.credentials="anonymous"===this.crossOrigin?"same-origin":"include",a.headers=this.requestHeader;const o=fetch(t,a).then((function(t){return t.blob()})).then((function(t){return createImageBitmap(t,Object.assign(r.options,{colorSpaceConversion:"none"}))})).then((function(n){return Xd.add(t,n),e&&e(n),r.manager.itemEnd(t),n})).catch((function(e){i&&i(e),Xd.remove(t),r.manager.itemError(t),r.manager.itemEnd(t)}));Xd.add(t,o),r.manager.itemStart(t)}}let Lp;class Up{static getContext(){return void 0===Lp&&(Lp=new(window.AudioContext||window.webkitAudioContext)),Lp}static setContext(t){Lp=t}}class Np extends Yd{constructor(t){super(t)}load(t,e,n,i){const r=this,s=new Kd(this.manager);function a(e){i?i(e):console.error(e),r.manager.itemError(t)}s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(t,(function(t){try{const n=t.slice(0);Up.getContext().decodeAudioData(n,(function(t){e(t)})).catch(a)}catch(t){a(t)}}),n,i)}}const Dp=new lr,Op=new lr,Fp=new lr;class Bp{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new Qs,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Qs,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(t){const e=this._cache;if(e.focus!==t.focus||e.fov!==t.fov||e.aspect!==t.aspect*this.aspect||e.near!==t.near||e.far!==t.far||e.zoom!==t.zoom||e.eyeSep!==this.eyeSep){e.focus=t.focus,e.fov=t.fov,e.aspect=t.aspect*this.aspect,e.near=t.near,e.far=t.far,e.zoom=t.zoom,e.eyeSep=this.eyeSep,Fp.copy(t.projectionMatrix);const n=e.eyeSep/2,i=n*e.near/e.focus,r=e.near*Math.tan(Xn*e.fov*.5)/e.zoom;let s,a;Op.elements[12]=-n,Dp.elements[12]=n,s=-r*e.aspect+i,a=r*e.aspect+i,Fp.elements[0]=2*e.near/(a-s),Fp.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(Fp),s=-r*e.aspect-i,a=r*e.aspect-i,Fp.elements[0]=2*e.near/(a-s),Fp.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(Fp)}this.cameraL.matrixWorld.copy(t.matrixWorld).multiply(Op),this.cameraR.matrixWorld.copy(t.matrixWorld).multiply(Dp)}}class zp{constructor(t=!0){this.autoStart=t,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=kp(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let t=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){const e=kp();t=(e-this.oldTime)/1e3,this.oldTime=e,this.elapsedTime+=t}return t}}function kp(){return performance.now()}const Vp=new Li,Hp=new Ii,Gp=new Li,Wp=new Li;class Xp extends Dr{constructor(){super(),this.type="AudioListener",this.context=Up.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new zp}getInput(){return this.gain}removeFilter(){return null!==this.filter&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(t){return null!==this.filter?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=t,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(t){return this.gain.gain.setTargetAtTime(t,this.context.currentTime,.01),this}updateMatrixWorld(t){super.updateMatrixWorld(t);const e=this.context.listener,n=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(Vp,Hp,Gp),Wp.set(0,0,-1).applyQuaternion(Hp),e.positionX){const t=this.context.currentTime+this.timeDelta;e.positionX.linearRampToValueAtTime(Vp.x,t),e.positionY.linearRampToValueAtTime(Vp.y,t),e.positionZ.linearRampToValueAtTime(Vp.z,t),e.forwardX.linearRampToValueAtTime(Wp.x,t),e.forwardY.linearRampToValueAtTime(Wp.y,t),e.forwardZ.linearRampToValueAtTime(Wp.z,t),e.upX.linearRampToValueAtTime(n.x,t),e.upY.linearRampToValueAtTime(n.y,t),e.upZ.linearRampToValueAtTime(n.z,t)}else e.setPosition(Vp.x,Vp.y,Vp.z),e.setOrientation(Wp.x,Wp.y,Wp.z,n.x,n.y,n.z)}}class jp extends Dr{constructor(t){super(),this.type="Audio",this.listener=t,this.context=t.context,this.gain=this.context.createGain(),this.gain.connect(t.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(t){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=t,this.connect(),this}setMediaElementSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(t),this.connect(),this}setMediaStreamSource(t){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(t),this.connect(),this}setBuffer(t){return this.buffer=t,this.sourceType="buffer",this.autoplay&&this.play(),this}play(t=0){if(!0===this.isPlaying)return void console.warn("THREE.Audio: Audio is already playing.");if(!1===this.hasPlaybackControl)return void console.warn("THREE.Audio: this Audio has no playback control.");this._startedAt=this.context.currentTime+t;const e=this.context.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,e.loopStart=this.loopStart,e.loopEnd=this.loopEnd,e.onended=this.onEnded.bind(this),e.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=e,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(!1!==this.hasPlaybackControl)return!0===this.isPlaying&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,!0===this.loop&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this;console.warn("THREE.Audio: this Audio has no playback control.")}stop(t=0){if(!1!==this.hasPlaybackControl)return this._progress=0,null!==this.source&&(this.source.stop(this.context.currentTime+t),this.source.onended=null),this.isPlaying=!1,this;console.warn("THREE.Audio: this Audio has no playback control.")}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let t=1,e=this.filters.length;t0){this.source.disconnect(this.filters[0]);for(let t=1,e=this.filters.length;t0&&this._mixBufferRegionAdditive(n,i,this._addIndex*e,1,e);for(let t=e,r=e+e;t!==r;++t)if(n[t]!==n[t+e]){a.setValue(n,i);break}}saveOriginalState(){const t=this.binding,e=this.buffer,n=this.valueSize,i=n*this._origIndex;t.getValue(e,i);for(let t=n,r=i;t!==r;++t)e[t]=e[i+t%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){const t=3*this.valueSize;this.binding.setValue(this.buffer,t)}_setAdditiveIdentityNumeric(){const t=this._addIndex*this.valueSize,e=t+this.valueSize;for(let n=t;n=.5)for(let i=0;i!==r;++i)t[e+i]=t[n+i]}_slerp(t,e,n,i){Ii.slerpFlat(t,e,t,e,t,n,i)}_slerpAdditive(t,e,n,i,r){const s=this._workIndex*r;Ii.multiplyQuaternionsFlat(t,s,t,e,t,n),Ii.slerpFlat(t,e,t,e,t,s,i)}_lerp(t,e,n,i,r){const s=1-i;for(let a=0;a!==r;++a){const r=e+a;t[r]=t[r]*s+t[n+a]*i}}_lerpAdditive(t,e,n,i,r){for(let s=0;s!==r;++s){const r=e+s;t[r]=t[r]+t[n+s]*i}}}const tm="\\[\\]\\.:\\/",em=new RegExp("["+tm+"]","g"),nm="[^"+tm+"]",im="[^"+tm.replace("\\.","")+"]",rm=new RegExp("^"+/((?:WC+[\/:])*)/.source.replace("WC",nm)+/(WCOD+)?/.source.replace("WCOD",im)+/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",nm)+/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",nm)+"$"),sm=["material","materials","bones","map"];class am{constructor(t,e,n){this.path=e,this.parsedPath=n||am.parseTrackName(e),this.node=am.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,e,n){return t&&t.isAnimationObjectGroup?new am.Composite(t,e,n):new am(t,e,n)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(em,"")}static parseTrackName(t){const e=rm.exec(t);if(null===e)throw new Error("PropertyBinding: Cannot parse trackName: "+t);const n={nodeName:e[2],objectName:e[3],objectIndex:e[4],propertyName:e[5],propertyIndex:e[6]},i=n.nodeName&&n.nodeName.lastIndexOf(".");if(void 0!==i&&-1!==i){const t=n.nodeName.substring(i+1);-1!==sm.indexOf(t)&&(n.nodeName=n.nodeName.substring(0,i),n.objectName=t)}if(null===n.propertyName||0===n.propertyName.length)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return n}static findNode(t,e){if(void 0===e||""===e||"."===e||-1===e||e===t.name||e===t.uuid)return t;if(t.skeleton){const n=t.skeleton.getBoneByName(e);if(void 0!==n)return n}if(t.children){const n=function(t){for(let i=0;i=r){const s=r++,c=t[s];e[c.uuid]=l,t[l]=c,e[o]=s,t[s]=a;for(let t=0,e=i;t!==e;++t){const e=n[t],i=e[s],r=e[l];e[l]=i,e[s]=r}}}this.nCachedObjects_=r}uncache(){const t=this._objects,e=this._indicesByUUID,n=this._bindings,i=n.length;let r=this.nCachedObjects_,s=t.length;for(let a=0,o=arguments.length;a!==o;++a){const o=arguments[a].uuid,l=e[o];if(void 0!==l)if(delete e[o],l0&&(e[a.uuid]=l),t[l]=a,t.pop();for(let t=0,e=i;t!==e;++t){const e=n[t];e[l]=e[r],e.pop()}}}this.nCachedObjects_=r}subscribe_(t,e){const n=this._bindingsIndicesByPath;let i=n[t];const r=this._bindings;if(void 0!==i)return r[i];const s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,h=new Array(l);i=r.length,n[t]=i,s.push(t),a.push(e),r.push(h);for(let n=c,i=o.length;n!==i;++n){const i=o[n];h[n]=new am(i,t,e)}return h}unsubscribe_(t){const e=this._bindingsIndicesByPath,n=e[t];if(void 0!==n){const i=this._paths,r=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a];e[t[a]]=n,s[n]=o,s.pop(),r[n]=r[a],r.pop(),i[n]=i[a],i.pop()}}}class lm{constructor(t,e,n=null,i=e.blendMode){this._mixer=t,this._clip=e,this._localRoot=n,this.blendMode=i;const r=e.tracks,s=r.length,a=new Array(s),o={endingStart:De,endingEnd:De};for(let t=0;t!==s;++t){const e=r[t].createInterpolant(null);a[t]=e,e.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=2201,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&0!==this.timeScale&&null===this._startTime&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(t){return this._startTime=t,this}setLoop(t,e){return this.loop=t,this.repetitions=e,this}setEffectiveWeight(t){return this.weight=t,this._effectiveWeight=this.enabled?t:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(t){return this._scheduleFading(t,0,1)}fadeOut(t){return this._scheduleFading(t,1,0)}crossFadeFrom(t,e,n){if(t.fadeOut(e),this.fadeIn(e),n){const n=this._clip.duration,i=t._clip.duration,r=i/n,s=n/i;t.warp(1,r,e),this.warp(s,1,e)}return this}crossFadeTo(t,e,n){return t.crossFadeFrom(this,e,n)}stopFading(){const t=this._weightInterpolant;return null!==t&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}setEffectiveTimeScale(t){return this.timeScale=t,this._effectiveTimeScale=this.paused?0:t,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(t){return this.timeScale=this._clip.duration/t,this.stopWarping()}syncWith(t){return this.time=t.time,this.timeScale=t.timeScale,this.stopWarping()}halt(t){return this.warp(this._effectiveTimeScale,0,t)}warp(t,e,n){const i=this._mixer,r=i.time,s=this.timeScale;let a=this._timeScaleInterpolant;null===a&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);const o=a.parameterPositions,l=a.sampleValues;return o[0]=r,o[1]=r+n,l[0]=t/s,l[1]=e/s,this}stopWarping(){const t=this._timeScaleInterpolant;return null!==t&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(t)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(t,e,n,i){if(!this.enabled)return void this._updateWeight(t);const r=this._startTime;if(null!==r){const i=(t-r)*n;i<0||0===n?e=0:(this._startTime=null,e=n*i)}e*=this._updateTimeScale(t);const s=this._updateTime(e),a=this._updateWeight(t);if(a>0){const t=this._interpolants,e=this._propertyBindings;if(this.blendMode===ze)for(let n=0,i=t.length;n!==i;++n)t[n].evaluate(s),e[n].accumulateAdditive(a);else for(let n=0,r=t.length;n!==r;++n)t[n].evaluate(s),e[n].accumulate(i,a)}}_updateWeight(t){let e=0;if(this.enabled){e=this.weight;const n=this._weightInterpolant;if(null!==n){const i=n.evaluate(t)[0];e*=i,t>n.parameterPositions[1]&&(this.stopFading(),0===i&&(this.enabled=!1))}}return this._effectiveWeight=e,e}_updateTimeScale(t){let e=0;if(!this.paused){e=this.timeScale;const n=this._timeScaleInterpolant;if(null!==n){e*=n.evaluate(t)[0],t>n.parameterPositions[1]&&(this.stopWarping(),0===e?this.paused=!0:this.timeScale=e)}}return this._effectiveTimeScale=e,e}_updateTime(t){const e=this._clip.duration,n=this.loop;let i=this.time+t,r=this._loopCount;const s=2202===n;if(0===t)return-1===r?i:s&&1==(1&r)?e-i:i;if(2200===n){-1===r&&(this._loopCount=0,this._setEndings(!0,!0,!1));t:{if(i>=e)i=e;else{if(!(i<0)){this.time=i;break t}i=0}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t<0?-1:1})}}else{if(-1===r&&(t>=0?(r=0,this._setEndings(!0,0===this.repetitions,s)):this._setEndings(0===this.repetitions,!0,s)),i>=e||i<0){const n=Math.floor(i/e);i-=e*n,r+=Math.abs(n);const a=this.repetitions-r;if(a<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=t>0?e:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:t>0?1:-1});else{if(1===a){const e=t<0;this._setEndings(e,!e,s)}else this._setEndings(!1,!1,s);this._loopCount=r,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:n})}}else this.time=i;if(s&&1==(1&r))return e-i}return i}_setEndings(t,e,n){const i=this._interpolantSettings;n?(i.endingStart=Oe,i.endingEnd=Oe):(i.endingStart=t?this.zeroSlopeAtStart?Oe:De:Fe,i.endingEnd=e?this.zeroSlopeAtEnd?Oe:De:Fe)}_scheduleFading(t,e,n){const i=this._mixer,r=i.time;let s=this._weightInterpolant;null===s&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);const a=s.parameterPositions,o=s.sampleValues;return a[0]=r,o[0]=e,a[1]=r+t,o[1]=n,this}}const cm=new Float32Array(1);class hm extends Hn{constructor(t){super(),this._root=t,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(t,e){const n=t._localRoot||this._root,i=t._clip.tracks,r=i.length,s=t._propertyBindings,a=t._interpolants,o=n.uuid,l=this._bindingsByRootAndName;let c=l[o];void 0===c&&(c={},l[o]=c);for(let t=0;t!==r;++t){const r=i[t],l=r.name;let h=c[l];if(void 0!==h)++h.referenceCount,s[t]=h;else{if(h=s[t],void 0!==h){null===h._cacheIndex&&(++h.referenceCount,this._addInactiveBinding(h,o,l));continue}const i=e&&e._propertyBindings[t].binding.parsedPath;h=new Qp(am.create(n,l,i),r.ValueTypeName,r.getValueSize()),++h.referenceCount,this._addInactiveBinding(h,o,l),s[t]=h}a[t].resultBuffer=h.buffer}}_activateAction(t){if(!this._isActiveAction(t)){if(null===t._cacheIndex){const e=(t._localRoot||this._root).uuid,n=t._clip.uuid,i=this._actionsByClip[n];this._bindAction(t,i&&i.knownActions[0]),this._addInactiveAction(t,n,e)}const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==n.useCount++&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(t)}}_deactivateAction(t){if(this._isActiveAction(t)){const e=t._propertyBindings;for(let t=0,n=e.length;t!==n;++t){const n=e[t];0==--n.useCount&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(t)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;const t=this;this.stats={actions:{get total(){return t._actions.length},get inUse(){return t._nActiveActions}},bindings:{get total(){return t._bindings.length},get inUse(){return t._nActiveBindings}},controlInterpolants:{get total(){return t._controlInterpolants.length},get inUse(){return t._nActiveControlInterpolants}}}}_isActiveAction(t){const e=t._cacheIndex;return null!==e&&e=0;--e)t[e].stop();return this}update(t){t*=this.timeScale;const e=this._actions,n=this._nActiveActions,i=this.time+=t,r=Math.sign(t),s=this._accuIndex^=1;for(let a=0;a!==n;++a){e[a]._update(i,t,r,s)}const a=this._bindings,o=this._nActiveBindings;for(let t=0;t!==o;++t)a[t].apply(s);return this}setTime(t){this.time=0;for(let t=0;t=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,bm).distanceTo(t)}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}}const Tm=new Li,Em=new Li;class Am{constructor(t=new Li,e=new Li){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Tm.subVectors(t,this.start),Em.subVectors(this.end,this.start);const n=Em.dot(Em);let i=Em.dot(Tm)/n;return e&&(i=Yn(i,0,1)),i}closestPointToPoint(t,e,n){const i=this.closestPointToPointParameter(t,e);return this.delta(n).multiplyScalar(i).add(this.start)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return(new this.constructor).copy(this)}}const Rm=new Li;class Cm extends Dr{constructor(t,e){super(),this.light=t,this.matrixAutoUpdate=!1,this.color=e,this.type="SpotLightHelper";const n=new Cs,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let t=0,e=1,n=32;t1)for(let n=0;n.99999)this.quaternion.set(0,0,0,1);else if(t.y<-.99999)this.quaternion.set(1,0,0,0);else{tf.set(t.z,0,-t.x).normalize();const e=Math.acos(t.y);this.quaternion.setFromAxisAngle(tf,e)}}setLength(t,e=.2*t,n=.2*e){this.line.scale.set(1,Math.max(1e-4,t-e),1),this.line.updateMatrix(),this.cone.scale.set(n,e,n),this.cone.position.y=t,this.cone.updateMatrix()}setColor(t){this.line.material.color.set(t),this.cone.material.color.set(t)}copy(t){return super.copy(t,!1),this.line.copy(t.line),this.cone.copy(t.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}}class sf extends Ih{constructor(t=1){const e=[0,0,0,t,0,0,0,0,0,0,t,0,0,0,0,0,0,t],n=new Cs;n.setAttribute("position",new Ms(e,3)),n.setAttribute("color",new Ms([1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],3));super(n,new xh({vertexColors:!0,toneMapped:!1})),this.type="AxesHelper"}setColors(t,e,n){const i=new ts,r=this.geometry.attributes.color.array;return i.set(t),i.toArray(r,0),i.toArray(r,3),i.set(e),i.toArray(r,6),i.toArray(r,9),i.set(n),i.toArray(r,12),i.toArray(r,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}}class af{constructor(){this.type="ShapePath",this.color=new ts,this.subPaths=[],this.currentPath=null}moveTo(t,e){return this.currentPath=new pu,this.subPaths.push(this.currentPath),this.currentPath.moveTo(t,e),this}lineTo(t,e){return this.currentPath.lineTo(t,e),this}quadraticCurveTo(t,e,n,i){return this.currentPath.quadraticCurveTo(t,e,n,i),this}bezierCurveTo(t,e,n,i,r,s){return this.currentPath.bezierCurveTo(t,e,n,i,r,s),this}splineThru(t){return this.currentPath.splineThru(t),this}toShapes(t){function e(t,e){const n=e.length;let i=!1;for(let r=n-1,s=0;sNumber.EPSILON){if(l<0&&(n=e[s],o=-o,a=e[r],l=-l),t.ya.y)continue;if(t.y===n.y){if(t.x===n.x)return!0}else{const e=l*(t.x-n.x)-o*(t.y-n.y);if(0===e)return!0;if(e<0)continue;i=!i}}else{if(t.y!==n.y)continue;if(a.x<=t.x&&t.x<=n.x||n.x<=t.x&&t.x<=a.x)return!0}}return i}const n=$u.isClockWise,i=this.subPaths;if(0===i.length)return[];let r,s,a;const o=[];if(1===i.length)return s=i[0],a=new Eu,a.curves=s.curves,o.push(a),o;let l=!n(i[0].getPoints());l=t?!l:l;const c=[],h=[];let u,d,p=[],m=0;h[m]=void 0,p[m]=[];for(let e=0,a=i.length;e1){let t=!1,n=0;for(let t=0,e=h.length;t0&&!1===t&&(p=c)}for(let t=0,e=h.length;t { + const s = document.createElement('script'); + s.src = new URL('./vendor/three/addons/libs/ammo.wasm.js', import.meta.url).href; + s.onload = () => window.Ammo().then((lib) => { window.Ammo = lib; resolve(); }, reject); + s.onerror = () => reject(new Error('ammo.js failed to load')); + document.head.append(s); + }); + } + return ammoReady; +} + +// VRM humanoid motion targets → standard MMD bone names (the motions are written for normalized VRM bones, +// which like MMD bones have no rest rotation, face +Z and have the character's left at +X) +const MMD_BONES = { + hips: ['センター', '下半身'], spine: ['上半身'], leftUpperLeg: ['左足'], rightUpperLeg: ['右足'], + leftLowerLeg: ['左ひざ'], rightLowerLeg: ['右ひざ'], leftUpperArm: ['左腕'], rightUpperArm: ['右腕'], + leftLowerArm: ['左ひじ'], rightLowerArm: ['右ひじ'], head: ['頭'], chest: ['上半身2', '上半身'], +}; + +// standard MMD bones: the PMX counterpart of humanoid bones in the skeleton overlay +const MMD_STANDARD = new Set(['センター', '下半身', '上半身', '上半身2', '上半身3', '首', '頭', '両目', '左目', '右目', + ...['肩', '腕', 'ひじ', '手首', '足', 'ひざ', '足首', 'つま先', '足先EX', + '親指0', '親指1', '親指2', '人指1', '人指2', '人指3', '中指1', '中指2', '中指3', + '薬指1', '薬指2', '薬指3', '小指1', '小指2', '小指3'].flatMap((n) => ['左' + n, '右' + n])]); + +// skeleton overlay colours by bone role (see Viewer.bones) +export const BONE_COLORS = { humanoid: '#ffb020', weighted: '#4fc3f7', spring: '#ff6fb5', control: '#b0b8c4', unused: '#ff4040' }; + +// English bone names (PMX converted from FBX / psk / xps keeps them) — the same rules as +// convert/vrmconv/humanoid.py _en_bone, reduced to the bones the preview motions drive. +const EN_LIMB = { arm: 'UpperArm', upperarm: 'UpperArm', shoulder: 'UpperArm', forearm: 'LowerArm', lowerarm: 'LowerArm', + elbow: 'LowerArm', upleg: 'UpperLeg', upperleg: 'UpperLeg', thigh: 'UpperLeg', hip: 'UpperLeg', + leg: 'LowerLeg', lowerleg: 'LowerLeg', calf: 'LowerLeg', shin: 'LowerLeg', knee: 'LowerLeg' }; +const EN_PREFIX = /^(?:character\d*|chr|bip0*1|jbipc|jbip|j|def|org|mch|armature|skeleton|rig|cc_base|valvebiped_bip01)(?=[a-z])/; +function enBone(name) { + const s = (name || '').split(':').pop().toLowerCase(); + const m = s.replace(/[. ]/g, '_').match(/(?:^|[^a-z])(l|r)(?:[^a-z]|$)|left|right/); + const side = m ? ((m[1] || m[0]).replace(/[_. ]/g, '').startsWith('l') ? 'left' : 'right') : null; + let base = s.replace(/left|right/g, '').replace(/(?:^|[_. ])[lr](?=[_. ]|$)/g, '_').replace(/[^a-z0-9]/g, ''); + base = base.replace(EN_PREFIX, ''); + if (!side) return { hips: 'hips', hip: 'hips', pelvis: 'hips', spine: 'spine', spine0: 'spine', spine1: 'chest', + chest: 'chest', head: 'head' }[base] || null; + return EN_LIMB[base] ? side + EN_LIMB[base] : null; +} + +// Same pose model as tools/qa/harness/motions.mjs (normalized humanoid bones, radians, 60 fps). +const smooth = (x) => x * x * (3 - 2 * x); +function gait(f, freq, thigh, knee, bob, armSwing) { + const ph = f / 60 * Math.PI * 2 * freq, s = Math.sin(ph); + return { bob: -bob * Math.cos(2 * ph), yaw: 0.08 * s, roll: 0.04 * Math.sin(2 * ph), spineYaw: -0.1 * s, + lLeg: -thigh * s, rLeg: thigh * s, + lKnee: 0.1 + knee * Math.max(0, Math.sin(ph + 0.9)), rKnee: 0.1 + knee * Math.max(0, Math.sin(ph + 0.9 + Math.PI)), + armDown: 0.7, armSwingL: armSwing * s, armSwingR: -armSwing * s }; +} +// relaxed hand for the preview (degrees per segment, proximal → distal; thumb: metacarpal → distal) +const RELAX = { Thumb: [12, 10, 8], Index: [10, 15, 10], Middle: [12, 18, 12], Ring: [15, 20, 13], Little: [18, 22, 15] }; +const THUMB_IN = 25; // the thumb's first segment also turns in toward the index finger (rest: 45° out) + +export const MOTIONS = { + tpose: () => ({}), + idle: (f) => ({ armDown: 0.7, yaw: Math.sin(f / 60 * Math.PI * 2 * 0.25) * 0.05, bob: Math.sin(f / 60 * Math.PI * 2 * 0.3) * 0.004 }), + walk: (f) => gait(f, 0.9, 0.45, 0.9, 0.025, 0.35), + run: (f) => gait(f, 1.4, 0.8, 1.6, 0.05, 0.7), + legRaise: (f) => { const c = f % 240, k = c < 40 ? smooth(c / 40) : c < 100 ? 1 : c < 140 ? smooth(1 - (c - 100) / 40) : 0; + return { armDown: 0.7, lLeg: -1.2 * k, lKnee: 1.0 * k }; }, + turn: (f) => ({ armDown: 0.7, yaw: Math.sin(f / 60 * Math.PI * 2 * 0.6) * 0.8 }), +}; + +export class Viewer { + // loop: false → no render loop of its own (offscreen use: load, frame, snapshot); pixelRatio overrides the screen's + constructor(container, { background = '#8a8f98', loop = true, pixelRatio = null } = {}) { + this.container = container; + this.vrm = null; + this.mmd = null; // { mesh, helper, grant, bones, rest, armRest } + this.name = ''; + this.info = null; + this.height = 1.6; this.headY = 1.45; this.chestY = 1.2; + this.motion = 'idle'; this.t = 0; this.acc = 0; this.speed = 1; this.paused = false; + this.springOn = true; this.springManager = null; + this.light = { az: 35, el: 40, intensity: 1.4, ambient: 0.6, shadow: true }; + this.onLoad = null; + + const r = this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); + r.setPixelRatio(pixelRatio || Math.min(2, window.devicePixelRatio || 1)); + r.shadowMap.enabled = true; + r.shadowMap.type = THREE.PCFSoftShadowMap; + r.domElement.style.display = 'block'; + r.domElement.style.width = '100%'; + r.domElement.style.height = '100%'; + container.prepend(r.domElement); + + this.scene = new THREE.Scene(); + this.scene.background = new THREE.Color(background); + this.camera = new THREE.PerspectiveCamera(30, 1, 0.02, 100); + this.camera.position.set(0, 1.2, 4); + this.controls = new OrbitControls(this.camera, r.domElement); + this.controls.target.set(0, 0.9, 0); + this.controls.enableDamping = true; + this.controls.zoomToCursor = true; // the wheel zooms toward the point under the pointer + this.controls.minDistance = 0.03; + // double-click: that point of the model (or the bone under the pointer) becomes the orbit centre; + // on the empty background it goes back to the last framing (resetView) + r.domElement.addEventListener('dblclick', (e) => { + const p = this.pointAt(e.clientX, e.clientY); + if (p) this.focusOn(p); + else this.resetView(); + }); + + this.ambient = new THREE.AmbientLight(0xffffff, 0.6); + this.sun = new THREE.DirectionalLight(0xffffff, 1.4); + this.sun.castShadow = true; + this.sun.shadow.mapSize.set(2048, 2048); + this.sun.shadow.bias = -0.0003; + this.sun.shadow.normalBias = 0.003; + this.scene.add(this.ambient, this.sun, this.sun.target); + this.floor = new THREE.Mesh(new THREE.CircleGeometry(1.2, 48), new THREE.ShadowMaterial({ opacity: 0.25 })); + this.floor.rotation.x = -Math.PI / 2; + this.floor.receiveShadow = true; + this.scene.add(this.floor); + + this.loader = new GLTFLoader(); + this.loader.register((p) => new VRMLoaderPlugin(p)); + + new ResizeObserver(() => this.resize()).observe(container); + this.resize(); + this._fitShadow(); + this.clock = new THREE.Clock(); + const tick = () => { requestAnimationFrame(tick); this._tick(); }; + if (loop) tick(); + } + + resize() { + const w = Math.max(1, this.container.clientWidth), h = Math.max(1, this.container.clientHeight); + this.renderer.setSize(w, h, false); + this.camera.aspect = w / h; + this.camera.updateProjectionMatrix(); + } + + get loaded() { return !!(this.vrm || this.mmd); } + get kind() { return this.vrm ? 'vrm' : this.mmd ? 'pmx' : null; } + + // ------------------------------------------------------------ loading -- + async loadUrl(url, name) { + if (/\.pmx$/i.test(name || '') || /\.pmx(\?|$)/i.test(url)) return this.loadPmx(url, name); + const r = await fetch(url); + if (!r.ok) throw new Error('HTTP ' + r.status); + return this.loadBuffer(await r.arrayBuffer(), name || url.split('/').pop()); + } + + async loadBuffer(buf, name) { + const gltf = await this.loader.parseAsync(buf, ''); + const v = gltf.userData.vrm; + if (!v) throw new Error('not a VRM file'); + this._setModel(gltf, v, name); + return this.info; + } + + clear() { + if (this.vrm) { this.scene.remove(this.vrm.scene); VRMUtils.deepDispose(this.vrm.scene); } + if (this.mmd) { + const { mesh, helper } = this.mmd; + this.scene.remove(mesh); + try { helper.remove(mesh); } catch (e) { /* physics already gone */ } + mesh.geometry.dispose(); + for (const m of [].concat(mesh.material)) { + for (const k of ['map', 'matcap', 'gradientMap']) if (m[k]) m[k].dispose(); + m.dispose(); + } + } + this.vrm = null; this.mmd = null; this.info = null; this.springManager = null; this.name = ''; this.gltf = null; + this._jointsByNode = null; this._removedJoints = new Set(); + if (this._boneGfx) this.setBonesVisible(false, true); + this.highlightChain(null); + this._byNode = null; + this._boneList = null; this._bonePos = null; this.boneHover = -1; + } + + _setModel(gltf, v, name) { + this.clear(); + VRMUtils.removeUnnecessaryVertices(gltf.scene); + VRMUtils.combineSkeletons(gltf.scene); + if (v.meta && v.meta.metaVersion === '0') VRMUtils.rotateVRM0(v); + v.scene.traverse((o) => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; o.frustumCulled = false; } }); + this.scene.add(v.scene); + this.vrm = v; this.name = name; this.gltf = gltf; + this.springManager = v.springBoneManager || null; + if (!this.springOn) v.springBoneManager = undefined; + v.humanoid.resetNormalizedPose(); + v.update(0); + const box = new THREE.Box3().setFromObject(v.scene); + this.height = Math.max(0.3, box.max.y - box.min.y); + // 道具之类又宽又扁的模型:取景距离按最大边长算,不然镜头会怼到模型里 + const sz = box.getSize(new THREE.Vector3()); + this.extent = Math.max(this.height, sz.x, sz.z); + this.centerY = (box.min.y + box.max.y) / 2; + const head = v.humanoid.getNormalizedBoneNode('head'); + const chest = v.humanoid.getNormalizedBoneNode('chest') || v.humanoid.getNormalizedBoneNode('spine'); + const p = new THREE.Vector3(); + this.headY = head ? head.getWorldPosition(p).y + 0.06 * this.height / 1.6 : this.height * 0.9; + this.chestY = chest ? chest.getWorldPosition(p).y : this.height * 0.7; + this._fitShadow(); + this.t = 0; + this._applyMotion(0); + if (this.springManager) this.springManager.reset(); + this.info = this._info(gltf, v); + if (this.showBones) this.setBonesVisible(true); + if (this.onLoad) this.onLoad(this.info); + } + + // ---------------------------------------------------------------- PMX -- + async loadPmx(url, name) { + let physicsOk = true; + try { await loadAmmo(); } catch (e) { physicsOk = false; console.warn(e); } + const mesh = await new Promise((res, rej) => new MMDLoader().load(url, res, undefined, rej)); + this.clear(); + mesh.castShadow = true; mesh.receiveShadow = true; mesh.frustumCulled = false; + this.scene.add(mesh); + const mmd = mesh.geometry.userData.MMD || {}; + const helper = new MMDAnimationHelper(); + let physics = physicsOk && (mmd.rigidBodies || []).length > 0; + try { helper.add(mesh, { physics }); } catch (e) { console.warn(e); physics = false; helper.add(mesh, { physics: false }); } + if (!this.springOn) helper.enable('physics', false); + const bones = {}; + for (const b of mesh.skeleton.bones) if (!(b.name in bones)) bones[b.name] = b; + const en = {}; // English fallback: slot → bone (first match wins; clavicle+shoulder → shoulder is the arm) + for (const b of mesh.skeleton.bones) { + const k = enBone(b.name); + if (!k) continue; + if (/UpperArm$/.test(k) && /clavicle/i.test(b.name)) continue; + if (/UpperArm$/.test(k) && /shoulder/i.test(b.name) && mesh.skeleton.bones.some((o) => enBone(o.name) === k && !/shoulder|clavicle/i.test(o.name))) continue; + if (!(k in en)) en[k] = b; + } + const pick = (k) => (MMD_BONES[k] || []).map((n) => bones[n]).find(Boolean) || en[k] || null; + const rest = mesh.skeleton.bones.map((b) => [b.position.clone(), b.quaternion.clone()]); + // how far the arms already hang down in the model's rest pose (MMD models are usually in A-pose) + const armRest = {}; + for (const [arm, elbow, side] of [['leftUpperArm', 'leftLowerArm', 1], ['rightUpperArm', 'rightLowerArm', -1]]) { + const a = pick(arm), e = pick(elbow); + if (a && e) { + const pa = a.getWorldPosition(new THREE.Vector3()), pe = e.getWorldPosition(new THREE.Vector3()); + armRest[arm] = Math.atan2(pa.y - pe.y, Math.abs(pe.x - pa.x) || 1e-6); + } + } + this.mmd = { mesh, helper, grant: helper.createGrantSolver(mesh), bones, pick, rest, armRest, physics }; + this.name = name || url.split('/').pop(); + const box = new THREE.Box3().setFromObject(mesh); + this.height = Math.max(0.3, box.max.y - box.min.y); + const sz = box.getSize(new THREE.Vector3()); + this.extent = Math.max(this.height, sz.x, sz.z); + this.centerY = (box.min.y + box.max.y) / 2; + const p = new THREE.Vector3(), head = pick('head'), chest = pick('chest'); + this.headY = head ? head.getWorldPosition(p).y + 0.06 * this.height / 1.6 : this.height * 0.9; + this.chestY = chest ? chest.getWorldPosition(p).y : this.height * 0.7; + this._fitShadow(); + this.t = 0; + this._applyMotionPmx(0); + this.info = { + name: this.name, spec: 'PMX', height: this.height, humanBones: Object.keys(MMD_BONES).filter((k) => pick(k)).length, + triangles: Math.round((mesh.geometry.index ? mesh.geometry.index.count : mesh.geometry.attributes.position.count) / 3), + materials: [].concat(mesh.material).length, + textures: new Set([].concat(mesh.material).map((m) => m.map && m.map.uuid).filter(Boolean)).size, + springs: 0, joints: 0, colliders: 0, + rigidBodies: (mmd.rigidBodies || []).length, constraints: (mmd.constraints || []).length, physics, + expressions: Object.keys(mesh.morphTargetDictionary || {}).map((n) => ({ name: n, preset: false })), + }; + this.info.bones = this.boneStats(); + if (this.showBones) this.setBonesVisible(true); + if (this.onLoad) this.onLoad(this.info); + return this.info; + } + + _applyMotionPmx(f) { + const { mesh, pick, rest, armRest } = this.mmd; + mesh.skeleton.bones.forEach((b, i) => { b.position.copy(rest[i][0]); b.quaternion.copy(rest[i][1]); }); + const p = MOTIONS[this.motion](f); + const set = (k, x, y, z) => { const b = pick(k); if (b) b.quaternion.setFromEuler(new THREE.Euler(x, y, z)); }; + set('hips', 0, p.yaw || 0, p.roll || 0); + set('spine', 0, p.spineYaw || 0, 0); + mesh.position.y = (p.bob || 0) * this.height / 1.6; + set('leftUpperLeg', p.lLeg || 0, 0, 0); set('rightUpperLeg', p.rLeg || 0, 0, 0); + set('leftLowerLeg', p.lKnee || 0, 0, 0); set('rightLowerLeg', p.rKnee || 0, 0, 0); + // VRM motions lower the arm from T-pose by `a`; the PMX arm already hangs down by armRest + const a = 1.22 * Math.min(1, (p.armDown || 0) / 0.7); + set('leftUpperArm', p.armSwingL || 0, 0, -(a - (armRest.leftUpperArm || 0))); + set('rightUpperArm', p.armSwingR || 0, 0, a - (armRest.rightUpperArm || 0)); + set('leftLowerArm', 0, p.armSwingL ? -0.3 : 0, 0); set('rightLowerArm', 0, p.armSwingR ? 0.3 : 0, 0); + mesh.updateMatrixWorld(true); + this.mmd.grant.update(); // 付与 bones (足D etc. carry the leg skinning in most MMD models) + // again after the grant: MMD physics reads bone.matrixWorld, and the leg rigid bodies usually hang + // on 足D / ひざD — without this they stay in the rest pose and skirts never meet the legs + mesh.updateMatrixWorld(true); + } + + _info(gltf, v) { + const json = gltf.parser.json; + let tris = 0; + for (const m of json.meshes || []) for (const pr of m.primitives) { + const a = json.accessors[pr.indices != null ? pr.indices : pr.attributes.POSITION]; + tris += a.count / 3; + } + const sb = json.extensions && json.extensions.VRMC_springBone; + const sa = json.extensions && json.extensions.VRM && json.extensions.VRM.secondaryAnimation; + const em = v.expressionManager; + const presets = new Set(em ? Object.values(em.presetExpressionMap || {}).map((e) => e.expressionName) : []); + return { + name: (v.meta && (v.meta.name || v.meta.title)) || this.name, + spec: v.meta && v.meta.metaVersion === '0' ? '0.x' : '1.0', + height: this.height, + humanBones: Object.keys(v.humanoid.humanBones).length, + triangles: Math.round(tris), + materials: (json.materials || []).length, + textures: (json.images || []).length, + springs: sb ? sb.springs.length : (sa ? sa.boneGroups.length : 0), + joints: sb ? sb.springs.reduce((a, s) => a + s.joints.length, 0) : (sa ? sa.boneGroups.reduce((a, g) => a + g.bones.length, 0) : 0), + colliders: sb ? (sb.colliders || []).length : 0, + expressions: em ? em.expressions.map((e) => ({ name: e.expressionName, preset: presets.has(e.expressionName) })) + .sort((a, b) => (b.preset - a.preset)) : [], + bones: this.boneStats(), + }; + } + + // ------------------------------------------------------------- camera -- + frame(kind) { + this.frameKind = kind; + const H = this.height, c = this.chestY, h = this.headY, E = this.extent || H, cy = this.centerY ?? H * 0.52; + const presets = { + body: [[0, cy + E * 0.03, E * 2.4], [0, cy, 0]], + upper: [[0, c + 0.05, H * 1.1], [0, c + 0.03, 0]], + face: [[0, h, H * 0.42], [0, h - 0.01, 0]], + back: [[0, cy + E * 0.08, -E * 2.2], [0, cy + E * 0.03, 0]], + }; + const [pos, tgt] = presets[kind] || presets.body; + this._focus = null; + this.camera.position.set(...pos); this.controls.target.set(...tgt); this.controls.update(); + } + + // the point of the model under the pointer (client coordinates): a bone of the skeleton overlay when one is + // within a few pixels, else the first surface hit (skinned and morphed as shown). null when nothing is there + pointAt(x, y) { + if (!this.loaded) return null; + const b = this._boneGfx ? this.boneAt(x, y, 8) : null; + if (b) return this._bonePos[b.index].clone(); + const r = this.renderer.domElement.getBoundingClientRect(); + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((x - r.left) / r.width * 2 - 1, -(y - r.top) / r.height * 2 + 1), this.camera); + const hit = ray.intersectObject(this.vrm ? this.vrm.scene : this.mmd.mesh, true).find((h) => h.object.isMesh); + return hit ? hit.point.clone() : null; + } + + // back to the last framing preset (frame), undoing orbit / pan / zoom / double-click focus + resetView() { if (this.loaded) this.frame(this.frameKind || 'body'); } + + // move the orbit centre to p (world), keeping the viewing direction and distance; eased over ~0.3 s + focusOn(p) { + this._focus = { from: this.controls.target.clone(), to: p.clone(), t: 0 }; + } + + // the orbit centre onto a SpringBone chain (its joint nodes), a little closer when far away + focusChain(nodes) { + const byNode = this.vrm ? this._nodes() : null; + if (!byNode || !nodes || !nodes.length) return; + this.scene.updateMatrixWorld(); + const c = new THREE.Vector3(), p = new THREE.Vector3(), box = new THREE.Box3(); + let n = 0; + for (const i of nodes) { + const o = byNode.get(i); + if (!o) continue; + p.setFromMatrixPosition(o.matrixWorld); c.add(p); box.expandByPoint(p); n++; + } + if (!n) return; + c.divideScalar(n); + const size = Math.max(0.15, box.getSize(p).length()); + const off = this.camera.position.clone().sub(this.controls.target); + if (off.length() > size * 3) this.camera.position.copy(this.controls.target).add(off.setLength(size * 3)); + this.focusOn(c); + } + + _stepFocus(dt) { + const f = this._focus; + f.t = Math.min(1, f.t + dt / 0.3); + const k = 1 - Math.pow(1 - f.t, 3); + const tgt = f.from.clone().lerp(f.to, k), d = tgt.clone().sub(this.controls.target); + this.controls.target.add(d); + this.camera.position.add(d); + if (f.t >= 1) this._focus = null; + } + + // ------------------------------------------------------------- lights -- + setLight(opts) { + Object.assign(this.light, opts); + const L = this.light, H = this.height; + const az = THREE.MathUtils.degToRad(L.az), el = THREE.MathUtils.degToRad(L.el); + const d = H * 2.5, cy = H * 0.55; + this.sun.position.set(Math.sin(az) * Math.cos(el) * d, cy + Math.sin(el) * d, Math.cos(az) * Math.cos(el) * d); + this.sun.target.position.set(0, cy, 0); + this.sun.intensity = L.intensity; + this.ambient.intensity = L.ambient; + this.sun.castShadow = !!L.shadow; + } + + _fitShadow() { + const c = this.sun.shadow.camera, r = this.height * 0.75; + c.left = -r; c.right = r; c.top = r; c.bottom = -r; c.near = 0.1; c.far = this.height * 6; + c.updateProjectionMatrix(); + this.floor.scale.setScalar(this.height / 1.6); + this.sun.shadow.bias = -0.0003; + this.sun.shadow.normalBias = 0.003 * this.height / 1.6; + this.setLight({}); + } + + setBackground(color) { this.scene.background = new THREE.Color(color); } + + // ------------------------------------------------------------ motion -- + setMotion(m) { if (MOTIONS[m]) { this.motion = m; this.t = 0; } } + setSpeed(s) { this.speed = s; } + setPaused(p) { this.paused = p; } + setSpring(on) { + this.springOn = on; + if (this.mmd) { + this.mmd.helper.enable('physics', on); + if (on && this.mmd.physics) this.mmd.helper.objects.get(this.mmd.mesh).physics.reset(); + return; + } + if (!this.vrm) return; + this.vrm.springBoneManager = on ? this.springManager : undefined; + if (on && this.springManager) this.springManager.reset(); + } + resetPhysics() { + if (this.springManager) this.springManager.reset(); + if (this.mmd && this.mmd.physics) this.mmd.helper.objects.get(this.mmd.mesh).physics.reset(); + } + + // glTF node index → SpringBone joint (three-vrm keeps no spring/chain grouping, the file does) + _joints() { + if (this._jointsByNode || !this.springManager || !this.gltf) return this._jointsByNode || new Map(); + const m = new Map(), assoc = this.gltf.parser.associations; + for (const j of this.springManager.joints) { + const a = assoc.get(j.bone); + if (a && a.nodes != null) m.set(a.nodes, j); + } + return (this._jointsByNode = m); + } + + setSpringParams(list) { + const m = this._joints(), mgr = this.springManager; + if (!mgr) return; + let readded = false; + for (const p of list) { + const j = m.get(p.node); + if (!j) continue; + Object.assign(j.settings, { stiffness: p.stiffness, gravityPower: p.gravityPower, dragForce: p.dragForce }); + if (p.enabled === false && !this._removedJoints.has(j)) { mgr.deleteJoint(j); this._removedJoints.add(j); } + else if (p.enabled !== false && this._removedJoints.has(j)) { mgr.addJoint(j); this._removedJoints.delete(j); readded = true; } + } + if (readded) mgr.reset(); + } + + _applyMotion(f) { + const v = this.vrm; + if (!v) return; + const p = MOTIONS[this.motion](f), n = (b) => v.humanoid.getNormalizedBoneNode(b); + // three-vrm 里 VRM 0.x 的 normalized 骨(rotateVRM0 之后)X、Z 轴转向和 1.0 相反: + // 不取反的话 0.x 模型放下手臂时手臂往上抬、腿往后摆 + const s = v.meta && v.meta.metaVersion === '0' ? -1 : 1; + const set = (b, x, y, z) => { const o = n(b); if (o) o.rotation.set(x * s, y, z * s); }; + set('hips', 0, p.yaw || 0, p.roll || 0); + set('spine', 0, p.spineYaw || 0, 0); + v.scene.position.y = (p.bob || 0) * this.height / 1.6; + set('leftUpperLeg', p.lLeg || 0, 0, 0); set('rightUpperLeg', p.rLeg || 0, 0, 0); + set('leftLowerLeg', p.lKnee || 0, 0, 0); set('rightLowerLeg', p.rKnee || 0, 0, 0); + const a = 1.22 * Math.min(1, (p.armDown || 0) / 0.7); + set('leftUpperArm', p.armSwingL || 0, 0, -a); set('rightUpperArm', p.armSwingR || 0, 0, a); + set('leftLowerArm', 0, p.armSwingL ? -0.3 : 0, 0); set('rightLowerArm', 0, p.armSwingR ? 0.3 : 0, 0); + this._relaxHands(n, s, a / 1.22); + } + + // Relaxed hands (preview only): the VRM rest pose has straight fingers and the thumb out at 45°, so with the + // arms down the hands would look stiff. Each segment bends toward the palm (−Y at rest) by RELAX degrees × k + // (k follows the arms: 0 in T-pose). Axis = rest direction × down; s flips X/Z for VRM 0.x like set() above + _relaxHands(n, s, k) { + const down = new THREE.Vector3(0, -1, 0), ax = new THREE.Vector3(), q = new THREE.Quaternion(), qi = new THREE.Quaternion(); + for (const [side, sx] of [['left', 1], ['right', -1]]) { + qi.setFromAxisAngle(new THREE.Vector3(0, sx, 0), THREE.MathUtils.degToRad(THUMB_IN * k)); + for (const [f, degs] of Object.entries(RELAX)) { + const dir = f === 'Thumb' ? new THREE.Vector3(sx, 0, 1).normalize() : new THREE.Vector3(sx, 0, 0); + ax.crossVectors(dir, down).normalize(); + ax.set(ax.x * s, ax.y, ax.z * s); + (f === 'Thumb' ? ['Metacarpal', 'Proximal', 'Distal'] : ['Proximal', 'Intermediate', 'Distal']).forEach((seg, i) => { + const o = n(side + f + seg); + if (!o) return; + q.setFromAxisAngle(ax, THREE.MathUtils.degToRad(degs[i] * k)); + o.quaternion.copy(f === 'Thumb' && i === 0 ? qi.clone().multiply(q) : q); + }); + } + } + } + + // -------------------------------------------------------- expressions -- + setExpression(name, value) { + if (this.vrm && this.vrm.expressionManager) this.vrm.expressionManager.setValue(name, value); + if (this.mmd) { + const m = this.mmd.mesh, i = (m.morphTargetDictionary || {})[name]; + if (i !== undefined) m.morphTargetInfluences[i] = value; + } + } + resetExpressions() { + if (this.vrm && this.vrm.expressionManager) this.vrm.expressionManager.resetValues(); + if (this.mmd && this.mmd.mesh.morphTargetInfluences) this.mmd.mesh.morphTargetInfluences.fill(0); + } + + // eye gaze preview: yaw / pitch in degrees as VRM lookAt takes them (±90 = the far end of the range). + // ranges = { h, down, up } overrides the max eye angles (the tune panel previews manual values); + // null restores the model's own. setLook(null) hands the eyes back to the normal update. + setLook(yaw, pitch, ranges) { + const la = this.vrm && this.vrm.lookAt, ap = la && la.applier; + if (!ap || !ap.applyYawPitch || !ap.rangeMapHorizontalInner) return false; + const maps = { h: ['rangeMapHorizontalInner', 'rangeMapHorizontalOuter'], down: ['rangeMapVerticalDown'], up: ['rangeMapVerticalUp'] }; + if (!ap._origScale) ap._origScale = Object.fromEntries(Object.values(maps).flat().map((k) => [k, ap[k].outputScale])); + for (const [k, names] of Object.entries(maps)) { + for (const n of names) ap[n].outputScale = ranges && ranges[k] != null ? ranges[k] : ap._origScale[n]; + } + if (yaw === null) { la.autoUpdate = true; ap.applyYawPitch(0, 0); return true; } + la.autoUpdate = false; + ap.applyYawPitch(yaw, pitch); + return true; + } + + // ------------------------------------------------------------- bones -- + // Every bone of the loaded model and its role: + // humanoid humanoid bone (PMX: a standard MMD bone) + // weighted moves vertices + // spring SpringBone joint / collider (PMX: a bone driven by a physics rigid body) + // control moves nothing itself, but bones below it do (PMX: IK bones too) + // unused none of the above: an empty node + // → [{ obj, name, parent (index or -1), kind }], cached per model + bones() { + if (this._boneList) return this._boneList; + let objs = [], kind = new Map(), mark = (o, k) => { if (o && !kind.has(o)) kind.set(o, k); }; + const skinned = []; + if (this.vrm) { + const json = this.gltf.parser.json, byNode = this._nodes(), ext = json.extensions || {}; + const roots = new Set((json.scenes || [])[json.scene || 0]?.nodes || []); + (json.nodes || []).forEach((n, i) => { if (n.mesh == null && !roots.has(i) && byNode.get(i)) objs.push(byNode.get(i)); }); + const node = (i) => byNode.get(i); + const hb = ext.VRMC_vrm ? Object.values(ext.VRMC_vrm.humanoid.humanBones).map((b) => b.node) + : ext.VRM ? ext.VRM.humanoid.humanBones.map((b) => b.node) : []; + hb.forEach((i) => mark(node(i), 'humanoid')); + const sb = ext.VRMC_springBone, sa = ext.VRM && ext.VRM.secondaryAnimation; + if (sb) { + for (const s of sb.springs || []) for (const j of s.joints) mark(node(j.node), 'spring'); + for (const c of sb.colliders || []) mark(node(c.node), 'spring'); + } + if (sa) { + for (const g of sa.boneGroups || []) for (const r of g.bones || []) node(r)?.traverse((o) => mark(o, 'spring')); + for (const g of sa.colliderGroups || []) mark(node(g.node), 'spring'); + } + this.vrm.scene.traverse((o) => { if (o.isSkinnedMesh) skinned.push(o); }); + } else if (this.mmd) { + const { mesh } = this.mmd, mmd = mesh.geometry.userData.MMD || {}, B = mesh.skeleton.bones; + objs = B.slice(); + B.forEach((b) => { if (MMD_STANDARD.has(b.name)) mark(b, 'humanoid'); }); + for (const r of mmd.rigidBodies || []) if (r.type !== 0 && r.boneIndex >= 0) mark(B[r.boneIndex], 'spring'); + for (const ik of mmd.iks || []) mark(B[ik.target], 'ik'); + skinned.push(mesh); + } + for (const m of skinned) { + const si = m.geometry.attributes.skinIndex, sw = m.geometry.attributes.skinWeight, bs = m.skeleton.bones; + if (!si || !sw) continue; + const hit = new Uint8Array(bs.length); + for (let k = 0; k < sw.array.length; k++) if (sw.array[k] > 0) hit[si.array[k]] = 1; + hit.forEach((h, i) => { if (h) mark(bs[i], 'weighted'); }); + } + const index = new Map(objs.map((o, i) => [o, i])); + const list = objs.map((o) => { + let p = o.parent; + while (p && !index.has(p)) p = p.parent; + return { obj: o, name: o.name, parent: p ? index.get(p) : -1, kind: kind.get(o) === 'ik' ? 'control' : kind.get(o) || null }; + }); + // control: no role of its own, but something below has one + for (const b of list) { + if (!b.kind || b.kind === 'control') continue; + for (let p = b.parent; p >= 0 && !list[p].kind; p = list[p].parent) list[p].kind = 'control'; + } + for (const b of list) b.kind = b.kind || 'unused'; + return (this._boneList = list); + } + + // glTF node index → Object3D + _nodes() { + if (this._byNode) return this._byNode; + const m = new Map(); + for (const [o, a] of this.gltf.parser.associations) if (o.isObject3D && a && a.nodes != null && !m.has(a.nodes)) m.set(a.nodes, o); + return (this._byNode = m); + } + + // one SpringBone chain (VRM 1.0), picked by its joint nodes: the chain, each joint's hit radius and the + // colliders it collides with, drawn over the model and following it. null clears it. + highlightChain(nodes) { + if (this._chainGfx) { + this.scene.remove(this._chainGfx); + this._chainGfx.traverse((o) => { o.geometry?.dispose(); o.material?.dispose(); }); + this._chainGfx = null; + } + const sb = this.vrm && this.gltf.parser.json.extensions?.VRMC_springBone; + if (!nodes || !nodes.length || !sb) return; + const spring = (sb.springs || []).find((sp) => sp.joints[0] && sp.joints[0].node === nodes[0]); + if (!spring) return; + const byNode = this._nodes(), over = { depthTest: false, depthWrite: false, transparent: true }; + const g = new THREE.Group(), items = []; + // a ball = three great circles (a full wireframe sphere hides the model under dozens of colliders) + const ring = []; + for (let k = 0; k < 3; k++) { + for (let i = 0; i < 32; i++) { + for (const a of [i / 32 * Math.PI * 2, (i + 1) / 32 * Math.PI * 2]) { + const c = Math.cos(a), s = Math.sin(a); + ring.push(k === 0 ? [c, s, 0] : k === 1 ? [c, 0, s] : [0, c, s]); + } + } + } + const ringGeo = new THREE.BufferGeometry().setFromPoints(ring.map((q) => new THREE.Vector3(...q))); + const sphere = (color, opacity) => new THREE.LineSegments(ringGeo, new THREE.LineBasicMaterial({ ...over, color, opacity })); + // the chain: a line through the joints and a sphere of hitRadius on each + const js = spring.joints.map((j) => ({ obj: byNode.get(j.node), r: j.hitRadius || 0 })).filter((j) => j.obj); + const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(js.map(() => new THREE.Vector3())), + new THREE.LineBasicMaterial({ ...over, color: 0xffe14d })); + g.add(line); + for (const j of js) { + const m = sphere(0xffe14d, 0.9); + g.add(m); + items.push({ mesh: m, obj: j.obj, offset: new THREE.Vector3(), r: Math.max(j.r, 0.004) }); + } + // its colliders: sphere = one ball; capsule = balls at both ends joined by lines + const ids = new Set((spring.colliderGroups || []).flatMap((gi) => (sb.colliderGroups || [])[gi]?.colliders || [])); + const caps = []; + for (const ci of ids) { + const c = sb.colliders[ci], obj = byNode.get(c.node); + if (!obj) continue; + const sh = c.shape.sphere || c.shape.capsule; + const off = new THREE.Vector3(...(sh.offset || [0, 0, 0])); + const a = sphere(0x40e0ff, 0.5); g.add(a); + items.push({ mesh: a, obj, offset: off, r: sh.radius }); + if (c.shape.capsule) { + const tail = new THREE.Vector3(...(sh.tail || [0, 0, 0])); + const b = sphere(0x40e0ff, 0.5); g.add(b); + items.push({ mesh: b, obj, offset: tail, r: sh.radius }); + const l = new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints(Array.from({ length: 8 }, () => new THREE.Vector3())), + new THREE.LineBasicMaterial({ ...over, color: 0x40e0ff, opacity: 0.6 })); + g.add(l); + caps.push({ line: l, a: items[items.length - 2], b: items[items.length - 1] }); + } + } + g.children.forEach((o) => { o.renderOrder = 1000; o.frustumCulled = false; }); + this._chainGfx = g; + this._chain = { line, joints: js, items, caps }; + this.scene.add(g); + this._updateChain(); + } + + _updateChain() { + const { line, joints, items, caps } = this._chain, p = new THREE.Vector3(); + const lp = line.geometry.attributes.position; + joints.forEach((j, i) => { p.setFromMatrixPosition(j.obj.matrixWorld); lp.setXYZ(i, p.x, p.y, p.z); }); + lp.needsUpdate = true; + for (const it of items) { + it.mesh.position.copy(it.offset).applyMatrix4(it.obj.matrixWorld); + it.mesh.scale.setScalar(it.r); + } + // capsule sides: four lines between the end balls, offset by the radius across the axis + const d = new THREE.Vector3(), u = new THREE.Vector3(), v = new THREE.Vector3(); + for (const c of caps) { + const A = c.a.mesh.position, B = c.b.mesh.position, r = c.a.r, cp = c.line.geometry.attributes.position; + d.subVectors(B, A).normalize(); + u.set(Math.abs(d.y) < 0.9 ? 0 : 1, Math.abs(d.y) < 0.9 ? 1 : 0, 0).cross(d).normalize(); + v.crossVectors(d, u); + [u, v, u.clone().negate(), v.clone().negate()].forEach((w, k) => { + cp.setXYZ(k * 2, A.x + w.x * r, A.y + w.y * r, A.z + w.z * r); + cp.setXYZ(k * 2 + 1, B.x + w.x * r, B.y + w.y * r, B.z + w.z * r); + }); + cp.needsUpdate = true; + } + } + + // bone counts by role (the info panel) + boneStats() { + const s = { total: 0, humanoid: 0, weighted: 0, spring: 0, control: 0, unused: 0 }; + for (const b of this.bones()) { s.total++; s[b.kind]++; } + return s; + } + + // skeleton overlay: a line to the parent and a dot per bone, coloured by role, drawn over the model + setBonesVisible(on, keep = false) { + if (!keep) this.showBones = on; + if (this._boneGfx) { this.scene.remove(this._boneGfx); this._boneGfx.traverse((o) => { o.geometry?.dispose(); o.material?.dispose(); }); this._boneGfx = null; } + if (!on || !this.loaded) return; + const list = this.bones(), n = list.length; + const col = (k) => new THREE.Color(BONE_COLORS[k]); + const lines = new THREE.BufferGeometry(), dots = new THREE.BufferGeometry(); + const lc = new Float32Array(n * 6), dc = new Float32Array(n * 3); + list.forEach((b, i) => { + const c = col(b.kind); + c.toArray(dc, i * 3); c.toArray(lc, i * 6); c.toArray(lc, i * 6 + 3); + }); + lines.setAttribute('position', new THREE.BufferAttribute(new Float32Array(n * 6), 3)); + lines.setAttribute('color', new THREE.BufferAttribute(lc, 3)); + dots.setAttribute('position', new THREE.BufferAttribute(new Float32Array(n * 3), 3)); + dots.setAttribute('color', new THREE.BufferAttribute(dc, 3)); + const over = { depthTest: false, depthWrite: false, transparent: true, vertexColors: true }; + const g = new THREE.Group(); + g.add(new THREE.LineSegments(lines, new THREE.LineBasicMaterial({ ...over, opacity: 0.85 }))); + g.add(new THREE.Points(dots, new THREE.PointsMaterial({ ...over, size: 5, sizeAttenuation: false }))); + const hl = new THREE.BufferGeometry(); + hl.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3), 3)); + const hp = new THREE.Points(hl, new THREE.PointsMaterial({ depthTest: false, transparent: true, size: 11, sizeAttenuation: false, color: 0xffffff })); + hp.visible = false; + g.add(hp); + g.children.forEach((o) => { o.renderOrder = 999; o.frustumCulled = false; }); + this._boneGfx = g; + this.scene.add(g); + this._updateBones(); + } + + _updateBones() { + const g = this._boneGfx; + if (!g) return; + const list = this.bones(), [ls, ds, hp] = g.children; + const lp = ls.geometry.attributes.position, dp = ds.geometry.attributes.position, v = new THREE.Vector3(); + this._bonePos = this._bonePos || list.map(() => new THREE.Vector3()); + list.forEach((b, i) => this._bonePos[i].setFromMatrixPosition(b.obj.matrixWorld)); + list.forEach((b, i) => { + const p = this._bonePos[i], q = b.parent >= 0 ? this._bonePos[b.parent] : p; + dp.setXYZ(i, p.x, p.y, p.z); + lp.setXYZ(i * 2, p.x, p.y, p.z); lp.setXYZ(i * 2 + 1, q.x, q.y, q.z); + }); + lp.needsUpdate = dp.needsUpdate = true; + hp.visible = this.boneHover != null && this.boneHover >= 0; + if (hp.visible) { v.copy(this._bonePos[this.boneHover]); hp.geometry.attributes.position.setXYZ(0, v.x, v.y, v.z); hp.geometry.attributes.position.needsUpdate = true; } + } + + // bone under the pointer (client coordinates), within `px` pixels → { index, name, kind, parent } or null; + // highlights it in the overlay + boneAt(x, y, px = 10) { + if (!this._boneGfx || !this._bonePos) return null; + const r = this.renderer.domElement.getBoundingClientRect(), v = new THREE.Vector3(); + let best = -1, bd = px * px, bz = Infinity; + this._bonePos.forEach((p, i) => { + v.copy(p).project(this.camera); + if (v.z > 1) return; + const dx = (v.x + 1) / 2 * r.width + r.left - x, dy = (1 - v.y) / 2 * r.height + r.top - y, d = dx * dx + dy * dy; + if (d < bd - 1e-6 || (Math.abs(d - bd) < 1e-6 && v.z < bz)) { best = i; bd = d; bz = v.z; } + }); + this.boneHover = best; + if (best < 0) return null; + const list = this.bones(), b = list[best]; + return { index: best, name: b.name, kind: b.kind, parent: b.parent >= 0 ? list[b.parent].name : null }; + } + + snapshot() { this.renderer.render(this.scene, this.camera); return this.renderer.domElement.toDataURL('image/png'); } + + // centre square of the current view, scaled to size×size (VRM thumbnails are square) + snapshotSquare(size = 1024) { + const gfx = [this._boneGfx, this._chainGfx].filter(Boolean); // a thumbnail never shows the overlays + gfx.forEach((o) => { o.visible = false; }); + this.renderer.render(this.scene, this.camera); + gfx.forEach((o) => { o.visible = true; }); + const src = this.renderer.domElement, s = Math.min(src.width, src.height); + const c = document.createElement('canvas'); c.width = c.height = size; + c.getContext('2d').drawImage(src, (src.width - s) / 2, (src.height - s) / 2, s, s, 0, 0, size, size); + return c.toDataURL('image/png'); + } + + // --------------------------------------------------------------- loop -- + _tick() { + const dt = Math.min(0.1, this.clock.getDelta()); + if (this.vrm && !this.paused) { + // motion advances on a 60 Hz grid (like the QA harness); physics steps with real time + this.acc += dt * this.speed * 60; + const steps = Math.floor(this.acc); + this.acc -= steps; + this.t += steps; + this._applyMotion(this.t); + this.vrm.update(dt * this.speed); + } else if (this.mmd && !this.paused) { + this.acc += dt * this.speed * 60; + const steps = Math.floor(this.acc); + this.acc -= steps; + this.t += steps; + this._applyMotionPmx(this.t); + this.mmd.helper.update(dt * this.speed); // MMD physics only (no animation clip → no IK) + } + if (this._focus) this._stepFocus(dt); + this.controls.update(); + if (this._boneGfx || this._chainGfx) this.scene.updateMatrixWorld(); + if (this._boneGfx) this._updateBones(); + if (this._chainGfx) this._updateChain(); + this.renderer.render(this.scene, this.camera); + } +} diff --git a/ui/web/app.css b/ui/web/app.css new file mode 100644 index 0000000..5a20455 --- /dev/null +++ b/ui/web/app.css @@ -0,0 +1,231 @@ +:root { + --left-w: 440px; --side-w: 300px; --side-wide-w: 380px; + --bg: #f3f4f7; --card: #ffffff; --text: #1d2026; --muted: #6b7380; --line: #e3e6eb; --hover: #f2f4f8; + --accent: #3a6ee8; --accent-soft: #e9f0fd; --ok: #1f9d55; --warn: #c27c0e; --err: #d64545; + --viewport: #8a8f98; --shadow: 0 1px 2px rgba(16, 24, 40, .06), 0 1px 3px rgba(16, 24, 40, .08); +} +@media (prefers-color-scheme: dark) { + :root { --bg: #15171b; --card: #1e2126; --text: #e6e8eb; --muted: #98a1ad; --line: #2e3238; --hover: #262a30; + --accent: #7aa2ff; --accent-soft: #24324f; --ok: #45c47a; --warn: #e2a33a; --err: #f07272; --viewport: #3a3d43; + --shadow: none; } +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +html, body { margin: 0; height: 100%; background: var(--bg); color: var(--text); + font: 13px/1.45 "Microsoft YaHei UI", "PingFang SC", "Noto Sans CJK SC", "Segoe UI", system-ui, sans-serif; } +body { display: flex; flex-direction: column; overflow: hidden; } +button { font: inherit; color: inherit; } +h2 { font-size: 13px; margin: 0; font-weight: 600; } +h3 { font-size: 12px; margin: 14px 0 4px; color: var(--muted); font-weight: 600; } + +/* top bar */ +.topbar { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; + background: var(--card); border-bottom: 1px solid var(--line); flex: none; } +.brand { font-weight: 700; font-size: 14px; letter-spacing: .02em; } +.logo { color: var(--accent); } +.enh { font-size: 11px; font-weight: 600; color: var(--accent); background: var(--accent-soft); border-radius: 4px; padding: 1px 5px; margin-left: 4px; vertical-align: 1px; } +.ver { font-weight: 400; font-size: 12px; color: var(--muted); margin-left: 4px; } + +.layout { flex: 1; display: flex; min-height: 0; } +.mode-note { flex: none; padding: 6px 16px; font-size: 12px; background: var(--accent-soft); color: var(--text, inherit); + border-bottom: 1px solid var(--line); } +.mode-note b { color: var(--warn); } +.mode-note a { color: var(--accent); } +/* left column: settings scroll, the run bar stays at the bottom */ +.left { width: var(--left-w); flex: none; display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--line); } +.left-scroll { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; gap: 10px; padding: 12px; } +.right { flex: 1; display: flex; flex-direction: column; min-width: 0; } + +/* cards */ +.card { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; box-shadow: var(--shadow); } +.card-head { display: flex; align-items: center; justify-content: space-between; gap: 6px 8px; margin-bottom: 8px; flex-wrap: wrap; } +.card-head h2 { white-space: nowrap; } +.card-head .actions { display: flex; gap: 6px; } +.log-card .card-head { margin-bottom: 0; } + +/* buttons */ +.btn { background: var(--card); border: 1px solid var(--line); border-radius: 7px; padding: 4px 10px; cursor: pointer; white-space: nowrap; } +.btn:hover { background: var(--hover); } +.btn.ghost { border-color: transparent; color: var(--muted); } +.btn.small { padding: 2px 8px; font-size: 12px; } +.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; font-weight: 600; padding: 7px 16px; } +.btn.primary:disabled { opacity: .5; cursor: default; } +.link { background: none; border: none; cursor: pointer; padding: 0; font-weight: 600; } +.icon { background: none; border: none; cursor: pointer; color: var(--muted); padding: 2px 5px; border-radius: 5px; font-size: 12px; } +.icon:hover { background: var(--hover); color: var(--text); } + +.seg { display: inline-flex; border: 1px solid var(--line); border-radius: 7px; overflow: hidden; flex-wrap: wrap; } +.seg button { border: none; background: transparent; padding: 4px 10px; cursor: pointer; } +.seg button + button { border-left: 1px solid var(--line); } +.seg button.on { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +.seg.small button { padding: 2px 8px; font-size: 12px; } +.tabs { display: inline-flex; gap: 2px; } +.tabs button { border: none; background: none; padding: 3px 9px; border-radius: 6px; cursor: pointer; color: var(--muted); white-space: nowrap; } +.tabs button.on { background: var(--accent-soft); color: var(--accent); font-weight: 600; } + +/* form */ +.field { display: flex; align-items: center; gap: 8px; margin: 7px 0; } +.field > label { width: 92px; flex: none; color: var(--muted); } +.field input[type=range] { flex: 1; min-width: 0; accent-color: var(--accent); } +.field output { width: 34px; text-align: right; color: var(--muted); font-variant-numeric: tabular-nums; } +.seg.nowrap { flex-wrap: nowrap; flex: none; } +.input.jobs-num { flex: none; width: 64px; } +.input.jobs-num:disabled { color: var(--muted); } +.switch { display: flex; align-items: center; gap: 7px; margin: 6px 0; cursor: pointer; } +.switch input { accent-color: var(--accent); width: 15px; height: 15px; margin: 0; } +.switch.sub, .field.sub { margin-left: 22px; } +.switch.small { margin: 0; font-size: 12px; } +.hint { color: var(--muted); font-size: 12px; margin: -4px 0 4px 22px; } +.grid2 { display: grid; grid-template-columns: 1fr 1fr; column-gap: 8px; } +.folder-row .path { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); + border: 1px dashed var(--line); border-radius: 6px; padding: 3px 8px; } +.input { flex: 1; min-width: 0; background: var(--card); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 3px 8px; font: inherit; } + +/* files */ +.drop { border: 1.5px dashed var(--line); border-radius: 8px; padding: 18px 10px; text-align: center; color: var(--muted); cursor: pointer; } +.drop.compact { padding: 6px; font-size: 12px; } +.drop.over, body.dragging .drop { border-color: var(--accent); background: var(--accent-soft); color: var(--accent); } +.file-list { list-style: none; margin: 8px 0 0; padding: 0; max-height: 300px; overflow-y: auto; } +.file-list:empty::before { content: attr(data-empty); display: block; color: var(--muted); text-align: center; padding: 6px; font-size: 12px; } +.file { border-radius: 7px; padding: 6px 6px 6px 8px; } +.file:hover { background: var(--hover); } +.file.current { background: var(--accent-soft); } +.file .row1 { display: flex; align-items: center; gap: 6px; } +.file .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.kind { font-size: 10px; text-transform: uppercase; color: var(--muted); border: 1px solid var(--line); border-radius: 4px; padding: 0 4px; } +.chip { font-size: 11px; border-radius: 10px; padding: 0 7px; background: var(--hover); color: var(--muted); white-space: nowrap; } +.chip.running { background: var(--accent-soft); color: var(--accent); } +.chip.done { color: var(--ok); } +.chip.error { color: var(--err); } +.file .outs { margin: 3px 0 0 4px; font-size: 12px; color: var(--muted); display: flex; flex-wrap: wrap; gap: 2px 10px; } +.file .outs a { color: var(--accent); cursor: pointer; text-decoration: none; } +.file .err { color: var(--err); font-size: 12px; margin: 2px 0 0 4px; word-break: break-all; } +.file .note { color: var(--muted); font-size: 12px; margin: 2px 0 0 4px; } + +/* run bar */ +.runbar { flex: none; display: grid; grid-template-columns: auto 1fr auto; /* start or stop · status · open output */ align-items: center; gap: 6px 10px; padding: 10px 12px; + background: var(--card); border-top: 1px solid var(--line); } +.progress { grid-column: 1 / -1; height: 4px; background: var(--line); border-radius: 2px; overflow: hidden; } +.progress div { height: 100%; width: 0; background: var(--accent); transition: width .3s; } +.status { color: var(--muted); font-size: 12px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.badge { background: var(--err); color: #fff; border-radius: 8px; padding: 0 6px; font-size: 11px; font-weight: 600; } +.caret { display: inline-block; transition: transform .15s; } +.log-card.open .caret { transform: rotate(90deg); } +.log { margin: 8px 0 0; max-height: 260px; overflow: auto; font: 11.5px/1.5 Consolas, "Cascadia Mono", monospace; white-space: pre-wrap; word-break: break-all; } +.log .ok { color: var(--ok); } .log .warn { color: var(--warn); } .log .err { color: var(--err); } +.log .head { font-weight: 700; } .log .info { color: var(--muted); } +.log .file-mark { color: var(--accent); margin-top: 2px; } + +/* preview */ +.pv-toolbar { display: flex; align-items: center; gap: 8px; padding: 7px 12px; background: var(--card); border-bottom: 1px solid var(--line); flex-wrap: wrap; } +.pv-title { font-weight: 600; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.spacer { flex: 1; } +.btn.on { background: var(--accent-soft); border-color: var(--accent-soft); color: var(--accent); font-weight: 600; } +.stage { flex: 1; display: flex; min-height: 0; } +.pv { flex: 1; position: relative; background: var(--viewport); min-height: 0; min-width: 0; } +.pv canvas { position: absolute; inset: 0; } +.pv-empty, .pv-busy { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; gap: 10px; + color: #fff; text-shadow: 0 1px 3px #0008; pointer-events: none; font-size: 14px; } +.pv-busy { background: #0003; } +/* skeleton overlay: legend (bone roles with counts) and the hovered bone */ +.pv-legend { position: absolute; left: 10px; bottom: 10px; padding: 6px 10px; border-radius: 6px; background: #000a; color: #fff; + font-size: 12px; line-height: 1.7; pointer-events: none; } +.pv-legend i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; vertical-align: 0; } +.pv-legend b { font-weight: 600; margin-left: 6px; } +.pv-tip { position: absolute; padding: 4px 8px; border-radius: 4px; background: #000c; color: #fff; font-size: 12px; + line-height: 1.5; pointer-events: none; white-space: nowrap; transform: translate(12px, 12px); } +.pv-tip .k { opacity: 0.75; } +.pv-hint { position: absolute; right: 10px; bottom: 8px; color: #fff; opacity: 0.6; font-size: 11px; + text-shadow: 0 1px 2px #0009; pointer-events: none; } +/* tune panel: chain rows with keep-shown / focus buttons */ +.chain-head { display: flex; align-items: center; gap: 2px; } +.chain-head .switch { flex: 1; min-width: 0; } +.ibtn { flex: none; width: 24px; height: 22px; padding: 0; border: 1px solid transparent; border-radius: 4px; + background: none; color: var(--muted); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; } +.ibtn:hover { background: var(--accent-soft); color: var(--accent); } +.ibtn.on { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); } +.ibtn svg { width: 15px; height: 15px; } +.chain.pinned { box-shadow: inset 3px 0 0 var(--accent); padding-left: 4px; } +.spinner { width: 18px; height: 18px; border: 2px solid #fff6; border-top-color: #fff; border-radius: 50%; animation: spin 1s linear infinite; } +@keyframes spin { to { transform: rotate(360deg); } } +/* side column next to the preview (one panel at a time) */ +.side { width: var(--side-w); flex: none; display: flex; flex-direction: column; min-height: 0; background: var(--card); + border-left: 1px solid var(--line); } +.side.wide { width: var(--side-wide-w); } +/* drag handles between the columns (double-click resets) */ +.splitter { width: 6px; margin: 0 -3px; flex: none; cursor: col-resize; position: relative; z-index: 5; } +.splitter::after { content: ""; position: absolute; top: 0; bottom: 0; left: 2px; width: 2px; background: transparent; transition: background .15s; } +.splitter:hover::after, .splitter.dragging::after { background: var(--accent); } +body.resizing { cursor: col-resize; user-select: none; } +body.resizing .pv canvas { pointer-events: none; } +/* narrow windows (the app allows 1000 px): give the preview more of the width */ +@media (max-width: 1200px) { + :root { --left-w: 360px; --side-w: 260px; --side-wide-w: 330px; } + .pv-title { max-width: 140px; } +} +.panel { flex: 1; min-height: 0; display: flex; flex-direction: column; padding: 10px 12px; overflow-y: auto; } +.panel .field > label { width: 64px; } +.expr-list { overflow-y: auto; flex: 1; min-height: 0; } +.expr-list .field > label { width: 110px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.swatches { display: flex; gap: 6px; margin: 6px 0 2px; } +.swatches button { width: 22px; height: 22px; border-radius: 50%; border: 1px solid var(--line); cursor: pointer; padding: 0; } +.swatches button.on { outline: 2px solid var(--accent); outline-offset: 1px; } +.info { display: grid; grid-template-columns: auto 1fr; gap: 3px 12px; margin: 2px 0; font-size: 12px; } +.info dt { color: var(--muted); } .info dd { margin: 0; font-variant-numeric: tabular-nums; } + +.toast { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); background: #000c; color: #fff; padding: 6px 14px; + border-radius: 8px; font-size: 12px; opacity: 0; transition: opacity .3s; pointer-events: none; max-width: 80vw; } +.toast.show { opacity: 1; } + +/* metadata tab / texture hint */ +.hint.flush { margin-left: 0; } +.dim { opacity: .45; } +.hint.warn { color: var(--warn); } +.tab-body[data-panel=meta] .field > label { width: 80px; } +.tab-body[data-panel=main] .field > label { width: 72px; } +/* settings: Advanced fold, per-format sections, options that only apply to one target */ +details.adv { border-top: 1px solid var(--line); border-bottom: none; margin-top: 10px; padding-bottom: 0; } +details.adv > summary { font-weight: 600; color: var(--text); } +details.adv h3:first-of-type { margin-top: 6px; } +.settings-card.pmx .vrm-only, .settings-card:not(.pmx) .pmx-only, .settings-card.pmx .pmx-hidden { display: none; } +.fmt h3 { margin-top: 10px; } +#metaReset { margin-top: 10px; } + +/* tune panel */ +#tunePanel { overflow: hidden; } +.tune-body { overflow-y: auto; flex: 1; min-height: 0; margin: 0 -4px; padding: 0 4px; } +details.sec { border-bottom: 1px solid var(--line); padding: 2px 0 6px; } +details.sec details.sec { border: none; padding: 0; } +details.sec > summary { list-style: none; cursor: pointer; display: flex; align-items: center; gap: 6px; margin: 8px 0 4px; + font-size: 12px; font-weight: 600; color: var(--muted); } +details.sec > summary::-webkit-details-marker { display: none; } +details.sec > summary::before { content: "▸"; display: inline-block; transition: transform .15s; } +details.sec[open] > summary::before { transform: rotate(90deg); } +details.sec > summary:hover { color: var(--text); } +.tune-body .field > label { width: 96px; color: var(--text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.tune-body select { flex: 1; min-width: 0; background: var(--card); color: var(--text); border: 1px solid var(--line); border-radius: 6px; padding: 2px 4px; font: inherit; } +.tune-body select.changed, .tune-body input.changed { border-color: var(--accent); } +.tune-body .field.preset > label { width: 60px; } +.tune-body .field.preset { gap: 6px; } +.tune-body .field.preset.missing select { color: var(--muted); font-style: italic; } +.tune-body input.strength { flex: none; width: 56px; } +.tune-body output.strength { width: 36px; } +.tune-body input.strength.changed { accent-color: var(--accent); filter: saturate(1.6); } +.tune-msg { color: var(--muted); padding: 12px 2px; } +.thumb-row { display: flex; align-items: center; gap: 8px; } +.thumb-row img, .thumb-row .noimg { width: 64px; height: 64px; border-radius: 6px; border: 1px solid var(--line); object-fit: cover; flex: none; + display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 11px; } +.thumb-row .col { display: flex; flex-direction: column; gap: 4px; } +.chain { border-top: 1px solid var(--line); padding: 4px 0; } +.chain .switch { margin: 2px 0; } +.chain .switch span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chain .field { margin: 2px 0 2px 22px; } +.chain .field > label { width: 40px; color: var(--muted); } +.chain.off .field { display: none; } +.chain-list { margin-top: 4px; } +.tune-foot { display: flex; align-items: center; gap: 6px; padding-top: 8px; border-top: 1px solid var(--line); margin-top: 6px; } +.tune-foot .muted { flex: 1; color: var(--muted); font-size: 12px; } +.chip.tuned { background: var(--accent-soft); color: var(--accent); } +.mini { background: none; border: 1px solid var(--line); border-radius: 5px; cursor: pointer; padding: 0 5px; font-size: 11px; color: var(--muted); } +.mini:hover { color: var(--text); background: var(--hover); } +.tune-foot .btn.primary { padding: 2px 10px; font-weight: 600; } diff --git a/ui/web/app.js b/ui/web/app.js new file mode 100644 index 0000000..aee86d5 --- /dev/null +++ b/ui/web/app.js @@ -0,0 +1,95 @@ +// VRMify Enhanced UI entry. Talks to ui/server.py over HTTP (same API in the pywebview window and a browser). +// core.js shared state, i18n, api +// files.js file list options.js conversion settings +// run.js run bar + log preview.js 3D preview, toolbar, side column +// tune.js tune panel (per-model adjustments written into the VRM) +// layout.js drag handles for the column widths +import { $, S, api, errText, esc, pick, t, toast } from './core.js'; +import { renderFiles } from './files.js'; +import { applyOptsToForm, renderOutFolder, syncDependents } from './options.js'; +import { appendLog, relocalizeLog, renderStatus } from './run.js'; +import { applyLayout } from './layout.js'; +import { fillPreviewPanels, loadModel, previewFile, showBusy, viewer } from './preview.js'; +import { T, loadTune, renderTune } from './tune.js'; +import { queueThumb, setOnThumb } from './thumbs.js'; + +function applyLang() { + document.documentElement.lang = S.lang === 'en' ? 'en' : 'zh-CN'; + document.querySelectorAll('[data-i18n]').forEach((e) => { e.textContent = t(e.dataset.i18n); }); + document.querySelectorAll('[data-i18n-ph]').forEach((e) => { e.placeholder = t(e.dataset.i18nPh); }); + document.querySelectorAll('[data-i18n-title]').forEach((e) => { e.title = t(e.dataset.i18nTitle); }); + document.querySelectorAll('[data-lang]').forEach((b) => b.classList.toggle('on', b.dataset.lang === S.lang)); + $('fileList').dataset.empty = t('empty'); + renderModeNote(); + renderStatus(); renderOutFolder(); syncDependents(); relocalizeLog(); + fillPreviewPanels(viewer.info); + if (!$('tunePanel').hidden) renderTune(); +} +// why the app runs in the browser instead of its own window (ui/app.py), with what still works there +function renderModeNote() { + const n = S.modeNote, box = $('modeNote'); + box.hidden = S.native || !n; + if (box.hidden) return; + const link = n.kind === 'no_webview2' + ? ` ${esc(t('getWebView2'))}` : ''; + box.innerHTML = `${esc(t('browserMode'))} ${esc(pick(n.zh, n.en))}${link} ${esc(t('browserModeHint', { log: n.log }))}`; +} + +document.querySelectorAll('[data-lang]').forEach((b) => b.addEventListener('click', () => { + S.lang = b.dataset.lang; applyLang(); api('/api/options', { lang: S.lang }); +})); + +async function loadState() { + const st = await api('/api/state'); + Object.assign(S, { files: st.files, opts: st.opts, lang: st.lang, busy: st.busy, seq: st.seq, native: st.native, + features: st.features || {}, appOut: st.app_out || '', ui: st.ui || {}, modeNote: st.mode_note || null }); + applyLayout(); + $('ver').textContent = st.version ? 'v' + st.version : ''; + applyOptsToForm(); + applyLang(); +} + +function handleEvent(ev) { + if (ev.type === 'log') appendLog(ev.msg, ev.tag, ev.file, ev.en); + else if (ev.type === 'file') { + const i = S.files.findIndex((f) => f.id === ev.file.id); + const was = i >= 0 ? S.files[i].status : null; + if (i >= 0) S.files[i] = ev.file; else S.files.push(ev.file); + renderFiles(); + // a file just finished converting → open it in the preview: the first one of each run (unless the Tune + // panel has unsaved changes for the model on screen), and the one already on screen (show the real output) + if (ev.file.status === 'done' && was === 'running') queueThumb(ev.file); + if (ev.file.status === 'done' && was !== 'done' && ev.file.outputs.some((o) => o.url || o.previewable)) { + const first = !S.autoOpened && !(T.dirty && T.fid === S.current && ev.file.id !== S.current); + if (first) S.autoOpened = true; + if (first || ev.file.id === S.current) previewFile(ev.file.id); + } + } else if (ev.type === 'files') loadState(); + else if (ev.type === 'busy') { + S.busy = ev.busy; + if (ev.busy) S.autoOpened = false; + else { S.progress = null; S.result = { done: ev.done, failed: ev.failed, skipped: ev.skipped || 0 }; } + renderStatus(); + } else if (ev.type === 'progress') { S.progress = ev; renderStatus(); } + else if (ev.type === 'preview_busy') { if (ev.file === S.current) showBusy(t('pvMaking')); } + else if (ev.type === 'preview') { + if (ev.file !== S.current) return; + if (ev.error) { showBusy(null); toast(t('pvFailed', { err: errText(ev.error, ev.error_en) })); } else { loadModel(ev.url, ev.name); loadTune(); } + } +} + +// an automatic thumbnail was written: refresh the Tune panel when it shows that file (and has nothing unsaved) +setOnThumb((id) => { if (T.fid === id && !$('tunePanel').hidden && !T.dirty) loadTune(); }); + +async function pollEvents() { + for (;;) { + try { + const r = await api('/api/events?after=' + S.seq); + for (const ev of r.events) { S.seq = Math.max(S.seq, ev.seq); handleEvent(ev); } + } catch (e) { await new Promise((res) => setTimeout(res, 1500)); } + } +} + +await loadState(); +pollEvents(); +window.__app = { S, T, viewer, previewFile }; diff --git a/ui/web/core.js b/ui/web/core.js new file mode 100644 index 0000000..1d66fa3 --- /dev/null +++ b/ui/web/core.js @@ -0,0 +1,43 @@ +// Shared state and helpers for the UI modules (files / options / run / preview / tune). +import { STRINGS } from './i18n.js'; + +export const $ = (id) => document.getElementById(id); + +// App state mirrored from ui/server.py (/api/state + events), plus UI-only bits. +export const S = { + files: [], opts: {}, lang: 'zh_CN', busy: false, seq: 0, native: false, features: {}, appOut: '', + current: null, // file id shown in the preview + logErrors: 0, progress: null, result: null, + autoOpened: false, // first file of a run already opened in the preview + autoTune: false, // open the tune panel by itself once the model on screen can be tuned + ui: {}, // column widths from settings.json (layout.js) +}; + +export function t(key, args) { + let s = (STRINGS[S.lang] || STRINGS.zh_CN)[key] ?? key; + for (const [k, v] of Object.entries(args || {})) s = s.replaceAll('{' + k + '}', v); + return s; +} +export const presetLabel = (p) => ((STRINGS[S.lang] || STRINGS.zh_CN).preset || {})[p] || p; + +// Text from the server comes in Chinese, with an English version next to it when there is one +// (log lines, conversion errors: convert/logtext.py) +export const pick = (zh, en) => (S.lang === 'en' && en) || zh; +// an error from the server: a few fixed codes have their own strings, the rest come as zh + English version +const ERR = { 'no such file': 'errNoFile', 'not previewable': 'errNoPreview', 'file not found': 'errNotFound' }; +export const errText = (e, en) => (ERR[e] ? t(ERR[e]) : pick(e, en)); + +export async function api(path, body) { + const r = await fetch(path, body === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }); + return r.json(); +} + +export function toast(s) { + const e = $('toast'); + e.textContent = s; e.classList.add('show'); + clearTimeout(toast._t); toast._t = setTimeout(() => e.classList.remove('show'), 3000); +} + +export const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); +export const clone = (o) => JSON.parse(JSON.stringify(o || {})); +export const num = (v, d) => (typeof v === 'number' && isFinite(v) ? v : d); diff --git a/ui/web/files.js b/ui/web/files.js new file mode 100644 index 0000000..3243516 --- /dev/null +++ b/ui/web/files.js @@ -0,0 +1,137 @@ +// File list: add / remove, per-file status and outputs, drag & drop. +import { $, S, api, esc, pick, t, toast } from './core.js'; +import { loadModel, previewFile } from './preview.js'; +import { T, leaveTune, loadTune } from './tune.js'; + +const fmtSize = (n) => n > 1048576 ? (n / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(n / 1024)) + ' KB'; + +export function renderFiles() { + const ul = $('fileList'); + ul.innerHTML = ''; + for (const f of S.files) { + const li = document.createElement('li'); + li.className = 'file' + (f.id === S.current ? ' current' : ''); + const btn = (act, icon, key) => ``; + li.innerHTML = `
${f.kind} + ${esc(f.name)} + ${f.tuned ? `✎` : ''}${t('st_' + f.status)} + ${btn('preview', '👁', 'preview')}${btn('reveal', '📂', 'reveal')}${btn('remove', '✕', 'remove')}
`; + if (f.outputs.length) { + const d = document.createElement('div'); d.className = 'outs'; + d.innerHTML = t('outputs') + ':' + f.outputs.map((o, k) => `${esc(o.name)}`).join(''); + li.append(d); + } + if (f.error) { const d = document.createElement('div'); d.className = 'err'; d.textContent = pick(f.error, f.error_en); li.append(d); } + if (f.status === 'skipped') { const d = document.createElement('div'); d.className = 'note'; d.textContent = t('skippedNote'); li.append(d); } + li.addEventListener('click', (e) => { + const act = e.target.dataset.act, out = e.target.dataset.out; + if (act === 'remove') api('/api/remove', { ids: [f.id] }); + else if (act === 'reveal') api('/api/open', { path: f.outputs.length ? f.outputs[f.outputs.length - 1].path : f.path }); + else if (out !== undefined) { + const o = f.outputs[+out]; + if (!leaveTune(f.id)) return; + if (o.url) { S.current = f.id; renderFiles(); loadModel(o.url, o.name); if (!T.dirty) loadTune(); } + else if (o.previewable) previewFile(f.id, +out); + else api('/api/open', { path: o.path }); + } else previewFile(f.id); + }); + ul.append(li); + } + $('drop').classList.toggle('compact', S.files.length > 0); + $('drop').firstElementChild.textContent = t(S.files.length ? 'dropHintShort' : 'dropHint'); + const conv = S.files.filter((f) => f.kind !== 'vrm' && f.status !== 'running'); + const todo = conv.filter((f) => f.status === 'pending' || f.status === 'error').length; + const n = todo || conv.length; // nothing left to convert → the button converts everything again + $('startLabel').textContent = t(todo || !n ? 'start' : 'restart'); + $('startCount').textContent = n ? `(${n})` : ''; + $('start').disabled = S.busy || !n; +} + +// In the pywebview window files come with their paths: the native dialog (/api/pick) and the backend's own drop +// handler (ui/app.py). A plain browser never shows the page a path, so there the files are uploaded to the local +// program instead (into a temp folder, folders keep their structure so a PMX still finds its textures) and added +// from there (/api/upload, /api/upload/done). +const pickFiles = () => (S.native ? api('/api/pick', { folder: false }) : $('upFiles').click()); +$('addFiles').onclick = pickFiles; +$('drop').onclick = pickFiles; +$('addFolder').onclick = () => (S.native ? api('/api/pick', { folder: true }) : $('upFolder').click()); +$('clearFiles').onclick = () => api('/api/clear', {}); + +// a group = what ends up in one upload folder: one dropped / picked folder, or all loose files of one drop / pick +// (together, so a PMX dropped with its textures finds them). key: same content → same folder on every upload. +async function groupKey(files) { + const s = files.map((x) => `${x.rel}|${x.file.size}|${x.file.lastModified}`).sort().join('\n'); + const h = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(s)); + return [...new Uint8Array(h)].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +async function upload(groups) { + groups = groups.filter((g) => g.files.length); + const total = groups.reduce((n, g) => n + g.files.length, 0); + if (!total) return; + let done = 0, failed = 0; + const items = []; + for (const g of groups) { + const key = await groupKey(g.files); + for (const x of g.files) { + toast(t('uploading', { i: ++done, n: total, name: x.file.name })); + try { + const r = await (await fetch(`/api/upload?key=${encodeURIComponent(key)}&path=${encodeURIComponent(x.rel)}`, + { method: 'POST', body: x.file })).json(); + if (r.error) failed++; + } catch (e) { failed++; } + } + items.push({ key, roots: g.roots }); + } + const r = await api('/api/upload/done', { items }); + toast(failed ? t('uploadFailed', { n: failed }) : t('uploaded', { n: (r.added || []).length })); +} + +// files from : loose files are one group; with webkitdirectory each file carries its folder path +function fromInput(list) { + const loose = { roots: [], files: [] }, dirs = {}; + for (const file of list) { + const rel = file.webkitRelativePath || file.name, top = rel.split('/')[0]; + if (rel === file.name) { loose.files.push({ file, rel }); loose.roots.push(file.name); continue; } + (dirs[top] ||= { roots: [top], files: [] }).files.push({ file, rel }); + } + return [loose, ...Object.values(dirs)]; +} +for (const id of ['upFiles', 'upFolder']) { + $(id).addEventListener('change', (e) => { const g = fromInput(e.target.files); e.target.value = ''; upload(g); }); +} + +// dropped items: folders are walked with the entries API (readEntries returns at most 100 at a time) +const entryFile = (en) => new Promise((res, rej) => en.file(res, rej)); +async function walk(entry, prefix, out) { + if (entry.isFile) { out.push({ file: await entryFile(entry), rel: prefix + entry.name }); return; } + const reader = entry.createReader(); + for (;;) { + const batch = await new Promise((res, rej) => reader.readEntries(res, rej)); + if (!batch.length) break; + for (const en of batch) await walk(en, prefix + entry.name + '/', out); + } +} +async function fromDrop(dt) { + // entries have to be taken while the drop event is running; reading them can wait + const got = [...(dt.items || [])].filter((it) => it.kind === 'file') + .map((it) => ({ entry: it.webkitGetAsEntry ? it.webkitGetAsEntry() : null, file: it.getAsFile() })); + const loose = { roots: [], files: [] }, groups = [loose]; + for (const { entry, file } of got) { + if (entry && entry.isDirectory) { + const g = { roots: [entry.name], files: [] }; + await walk(entry, '', g.files); + groups.push(g); + } else if (file) { loose.files.push({ file, rel: file.name }); loose.roots.push(file.name); } + } + return groups; +} + +let dragDepth = 0; +window.addEventListener('dragenter', (e) => { e.preventDefault(); dragDepth++; document.body.classList.add('dragging'); }); +window.addEventListener('dragleave', () => { if (--dragDepth <= 0) { dragDepth = 0; document.body.classList.remove('dragging'); } }); +window.addEventListener('dragover', (e) => e.preventDefault()); +window.addEventListener('drop', (e) => { + e.preventDefault(); dragDepth = 0; document.body.classList.remove('dragging'); + if (!S.native && e.dataTransfer) fromDrop(e.dataTransfer).then(upload); +}); diff --git a/ui/web/i18n.js b/ui/web/i18n.js new file mode 100644 index 0000000..9a0ab9a --- /dev/null +++ b/ui/web/i18n.js @@ -0,0 +1,200 @@ +// UI strings: Simplified Chinese and English. Keys used via t(key) and data-i18n attributes. +export const STRINGS = { + zh_CN: { + files: '文件', addFiles: '添加文件', addFolder: '添加文件夹', clear: '清空', + dropHint: '把 PMX / VRM / 压缩包(zip / 7z / rar)/ FBX / unitypackage / uemodel / psk / xps 拖到这里', + dropHintShort: '拖入更多文件', uploading: '正在读入 {i} / {n}:{name}', uploaded: '已加入 {n} 个文件', uploadFailed: '有 {n} 个文件读入失败', + browserMode: '浏览器模式:', getWebView2: '下载 WebView2', browserModeHint: '拖入和添加文件照常可用(文件会先复制一份)。详细信息:{log}', + empty: '尚未添加文件', + st_pending: '待转换', st_running: '转换中', st_done: '完成', st_error: '失败', st_preview: '仅预览', st_skipped: '已跳过', + skippedNote: '未识别到人物模型(道具或仅含服装),已按「只转换人物」跳过,详见日志', + preview: '预览', reveal: '打开所在位置', remove: '移除', outputs: '输出', + settings: '转换设置', tabInput: '其它格式', + spec: 'VRM 版本', spec0x: '0.x', + spring: '物理(头发、裙摆摆动)', + springSkirt: '裙摆物理', autoSpring: '无物理的模型按骨骼名自动添加', stiffness: '整体硬度', morphs: '表情', comboExpr: '情绪表情组合眉、眼、嘴', gaze: '补充视线表情', extraExpr: '补充高光消失、吐舌表情', + outline: '描边(按 PMX 轮廓线)', tposeOpt: '转为 T 姿势(重摆骨架)', + tposeHint: '默认关闭,原样保留模型的静止姿势。勾选后才会把 A-pose 手臂抬成 VRM 规范的 T-pose。', + doubleSided: '所有材质双面', + targetPmx: '只转 PMX', + avatarOnly: '只转换人物', + avatarOnlyHint: '跳过模型包中常附带的道具(剑、椅子等)以及仅含服装 / 配件的模型。', + fbx: 'FBX / unitypackage', fbxAlpha: '贴图透明通道', alphaAuto: '自动判定', alphaKeep: '保留', alphaStrip: '全部去除', + autoFacing: '自动判定朝向', face180: '额外旋转 180°', fbxMorphs: '导出表情', + ue: 'uemodel', ueAlpha: '去除贴图透明通道', ueAlign: '对齐参考', clearRef: '清除', noRef: '(不对齐)', + ueAlignHint: '部件分开导出时(头部、身体、服装各为一个 uemodel),选择同一个整身模型作为参考,部件将按其骨架对齐。', + ueWeakRef: '该模型的骨架跨度仅约 {cm} cm,更像部件而非整身模型;用作参考可能导致模型整体下沉', + psk: 'psk / pskx', xps: 'xps', jpBones: '骨骼名改为 MMD 日文名', ik: '补充 IK 骨', inMorphs: '导出表情', + inAlpha: '去除贴图透明通道', hideUnused: '归类 unused 骨', xpsDouble: '材质双面', xpsEdge: '轮廓线', + outLocation: '保存到', outApp: '程序目录', outBeside: '源文件旁', outFolder: '指定文件夹', choose: '选择…', + noFolder: '(未选择)', subfolder: '每个文件的结果保存到单独的子文件夹', + jobs: '并行数', jobsAuto: '自动', jobsManual: '手动', jobsNumTip: '同时转换的文件数(1–64)', + jobsHint: '同时转换几个文件。「自动」为 CPU 物理核心数减一(最多 8),可用内存不足时再减少;转换在后台以较低优先级运行,不影响其它程序。通常无需修改。', + start: '开始转换', restart: '重新转换', stop: '停止', idle: '就绪', converting: '正在转换 {i}/{n}:{name}', + finished: '完成 {done} 个,失败 {failed} 个', finishedSkip: '完成 {done} 个,跳过 {skipped} 个,失败 {failed} 个', + nothing: '没有可转换的文件', + log: '日志', clearLog: '清空日志', + pvEmpty: '在左侧点击「预览」查看模型', pvMaking: '正在生成预览(快速转换)…', pvLoading: '加载中…', + pvFailed: '预览失败:{err}', + errNoFile: '文件已不在列表中', errNoPreview: '这个输出无法预览', errNotFound: '找不到文件', + body: '全身', upper: '上半身', face: '脸部', back: '背面', + tpose: 'T 姿势', idleM: '待机', walk: '走路', run: '跑步', legRaise: '抬腿', turn: '转身', + autoThumb: '转换后自动生成缩略图', + autoThumbHint: '在预览器中截取脸部写入 VRM,每次转换后更新。在「调整」中手动设置过缩略图的模型不受影响;压缩包里有多个模型时分别生成。', + thumbAuto: '自动生成', + pvHint: '左键旋转 · 右键平移 · 滚轮缩放 · 双击设为旋转中心 · R 恢复视角', pinChain: '常驻显示这条链', focusChain: '镜头对准这条链', + pvBones: '骨骼', bHumanoid: 'humanoid 骨骼', bHumanoidPmx: '标准骨骼', bWeighted: '带权重', bSpring: '物理', + bControl: '控制 / 中间骨骼', bUnused: '无效骨骼', bParent: '父骨骼:{p}', bRoot: '(根)', iBones: '骨骼', iBonesV: '{n}(无效 {u})', + physics: '物理', light: '灯光', expressions: '表情', shot: '截图', saved: '已保存:{path}', + lightAz: '水平角度', lightEl: '高度', lightI: '主光', ambient: '环境光', shadow: '投影', reset: '重置', + filter: '筛选…', info: '信息', + tabMain: '转换', convertTo: '转换成', targetHint_vrm1: '推荐。Unity(UniVRM)、VSeeFace 和大多数游戏均支持。', + targetHint_vrm0: '仅在软件不支持 VRM 1.0 时使用。物理按 0.x 的格式近似换算,效果比 1.0 略粗。', targetHint_pmx: 'FBX、unitypackage 等格式仅转换为 MMD 使用的 PMX;已添加的 PMX 文件不做处理。', + fileSize: '文件大小', sizeOrig: '原样', sizeMid: '适中', sizeSmall: '最小', sizeHint_orig: '保留原始贴图,画质最佳,文件最大。', + sizeHint_mid: '贴图最大 2048,不透明贴图存为 JPEG。文件通常可缩小一半以上,画质差异不明显。', sizeHint_small: '贴图最大 1024,不透明贴图存为 JPEG。文件最小,近距离观看略显模糊。', + sizeCustom: '自定义:贴图最大 {max},不透明贴图存为 {fmt}(可在「高级设置」中修改)。', advanced: '高级设置', advPhysics: '物理', advExpr: '表情', + advLook: '显示修正', advBones: '骨骼', collapseBones: '精简控制骨', advRun: '输出与转换', autoSpringHint: 'FBX 等格式的模型通常不含物理,将根据头发、裙摆、袖子等骨骼名自动添加。', + comboExprHint: '开心、生气等预设像 VRoid 一样整张脸联动;关闭后每个预设只对应一个表情。', + collapseBonesHint: '去掉没有权重的中间骨(全ての親、センター、グルーブ、腰、肩P 等),层级与 VRoid 一致(Root > Hips)。IK、末端骨等不起作用的骨始终会去掉。', + extraExprHint: '添加自定义表情 hideHighlight(关掉眼睛高光)和 tongue(吐舌)。优先使用模型自带的对应表情;没有关闭高光的表情时,按材质名找到眼睛高光并生成。', + gazeHint: '有眼骨时补充 lookUp / lookDown / lookLeft / lookRight,供直接播放这些表情的程序使用。', + doubleSidedHint: '模型出现破洞,或薄片头发、裙摆从背面不可见时开启。', subfolderHint: '文件夹命名为「名称_日期_序号」,重新转换不会覆盖已有结果。', + fbxAlphaHint: '游戏贴图的透明通道常存放其他数据,可能导致模型变透明。「自动判定」逐张判断;整块出现半透明时选择「全部去除」,蕾丝、发梢边缘变硬时选择「保留」。', + inputVrmHint: '骨骼命名、IK 等仅影响 PMX 的选项,在「转换成」中选择「只转 PMX」后显示。', metaTerms: '使用许可', + metaModHint: '「修改」针对修改后的模型,「允许且可再分发」表示修改后的版本也可发布;上方的「允许再分发」针对原样分享。', metaReset: '将许可恢复为默认(最严格)', openOut: '打开输出位置', + texTitle: '贴图', texMax: '最大边长', texOrig: '原样', texJpeg: '不透明贴图存为 JPEG', + texNoMip: '贴图不生成 mipmap(消除 UV 接缝白边)', + texNoMipHint: '贴图 UV 岛之间没留边距时,mipmap 会把岛外的白底混进边缘,形成白边。开启后只按原图分辨率采样,白边基本消失;远景会有轻微锯齿。', + noPillow: '缩小贴图和存为 JPEG 需要安装 Pillow(pip install pillow)。', + tabMeta: 'VRM 信息', metaHint: '写入 VRM 的作者和使用许可,设置一次即可用于之后转换的所有模型。名称默认为模型文件名,可在预览的「调整」中修改。转换他人的模型时,请按原作者的使用规约填写。', + metaAuthor: '作者', metaVersion: '模型版本', metaContact: '联系方式', metaCopyright: '版权', metaLicense: '许可 URL', + metaAvatar: '使用权限', permEveryone: '所有人', permLicensed: '获得授权者', permAuthor: '仅作者', + metaCommercial: '商用', comNone: '不可商用', comPersonal: '个人可商用', comCorp: '企业可商用', + metaMod: '修改', modNo: '禁止', modYes: '允许', modRedist: '允许且可再分发', + metaCredit: '署名', creditYes: '需要', creditNo: '不需要', metaRedist: '允许再分发(原样分享文件)', + tune: '调整', tuneNotReady: '预览生成后即可调整(或先转换该模型)', + tuneNotReadyPmx: '当前预览的是原始 PMX,转换为 VRM 后才能调整', + tuneAutoSaved: '已保存对 {name} 的调整', tuneNoFile: '请在左侧选择一个模型', + tuneNotEditable: '仅支持调整由本程序转换的模型', tuneTitle: '名称', tuneThumb: '缩略图', thumbFromView: '使用当前画面', + thumbHint: '请先在上方选择取景(例如「脸部」)', thumbRemove: '移除', thumbNone: '无', + tuneMeta: '名称和缩略图', tuneExpr: '预设表情', exprNone: '(不设)', exprMissing: '(模型中没有,可手动指定)', tryExpr: '试看', tunePhysics: '物理', + exprStrength: '强度(拖动时试看)', exprHint: '右侧滑块为强度:形态键权重按比例缩放,单个权重最高 100%,因此超过 100% 仅对组合表情(权重未满)有效。', + tuneLook: '视线范围', lookH: '左右', lookDown: '向下', lookUp: '向上', lookReset: '恢复自动', + lookHint: '眼睛看向最边缘时的转动角度(根据眼球结构自动计算)。修改会同时作用于 VRM 视线(如看向镜头)和转换时补充的 lookLeft 等视线表情。点击箭头可试看。', + lookTry: '试看:看向该方向的最大角度', + allChains: '整体', chains: '各条链({n})', stiffMul: '硬度', dragMul: '阻尼', gravAdd: '重力', + tuneSave: '保存并写入', tuneReset: '全部还原', tuneDirty: '有未保存的改动(转换或切换文件时会自动保存)', tuneClean: '将写入输出的 VRM,之后转换时自动应用', + tuneSaved: '已写入 {n} 个文件', tuneSavedNone: '已保存,下次转换时应用', thumbSaved: '缩略图已更新', + tuned: '已调整', dragResize: '拖动调整宽度,双击恢复默认', + iFormat: '格式', iHeight: '身高', iMmdUnit: ' MMD 单位', iTris: '三角面', iMats: '材质', iTex: '贴图', iMorphs: '表情', + iPhysics: '物理', iRigid: '{r} 刚体 / {j} 关节', iOff: '(未启用)', iHumanoid: 'humanoid 骨', iExpr: '表情', + iChains: '{n} 条 / {j} 关节', iColliders: '碰撞体', + preset: { happy: '开心', angry: '生气', sad: '悲伤', relaxed: '放松', surprised: '惊讶', neutral: '自然', + aa: '口型 あ', ih: '口型 い', ou: '口型 う', ee: '口型 え', oh: '口型 お', blink: '眨眼', blinkLeft: '闭左眼', blinkRight: '闭右眼', + joy: '开心', sorrow: '悲伤', fun: '愉快', a: '口型 あ', i: '口型 い', u: '口型 う', e: '口型 え', o: '口型 お', + blink_l: '闭左眼', blink_r: '闭右眼' }, + }, + en: { + files: 'Files', addFiles: 'Add files', addFolder: 'Add folder', clear: 'Clear', + dropHint: 'Drop PMX / VRM / archives (zip / 7z / rar) / FBX / unitypackage / uemodel / psk / xps here', + dropHintShort: 'Drop more files', uploading: 'Reading {i} / {n}: {name}', uploaded: 'Added {n} file(s)', uploadFailed: '{n} file(s) could not be read', + browserMode: 'Browser mode:', getWebView2: 'Get WebView2', browserModeHint: 'Dropping and adding files still work (the files are copied first). Details: {log}', + empty: 'No files yet', + st_pending: 'Pending', st_running: 'Converting', st_done: 'Done', st_error: 'Failed', st_preview: 'Preview only', st_skipped: 'Skipped', + skippedNote: 'No character model found (a prop or clothing only); skipped by \"Characters only\". See the log for details', + preview: 'Preview', reveal: 'Show in folder', remove: 'Remove', outputs: 'Output', + settings: 'Settings', tabInput: 'Other formats', + spec: 'VRM version', spec0x: '0.x', + spring: 'Physics (hair and skirt sway)', + springSkirt: 'Skirt physics', autoSpring: 'Add physics by bone name to models without it', stiffness: 'Stiffness', morphs: 'Expressions', comboExpr: 'Combine brow, eye and mouth in emotion presets', gaze: 'Add gaze expressions', extraExpr: 'Add highlight-off and tongue expressions', + outline: 'Outline (from PMX edges)', tposeOpt: 'Convert to T-pose (re-poses the skeleton)', + tposeHint: 'Off by default: the model keeps its original rest pose. Enable only if you want the arms raised to the VRM-spec T-pose.', + doubleSided: 'All materials double-sided', + targetPmx: 'PMX only', + avatarOnly: 'Characters only', + avatarOnlyHint: 'Skips props (swords, chairs, etc.) and clothing- or accessory-only models often bundled in model packs.', + fbx: 'FBX / unitypackage', fbxAlpha: 'Texture alpha', alphaAuto: 'Auto', alphaKeep: 'Keep', alphaStrip: 'Strip', + autoFacing: 'Auto-detect facing', face180: 'Extra 180° turn', fbxMorphs: 'Export morphs', + ue: 'uemodel', ueAlpha: 'Strip texture alpha', ueAlign: 'Align to', clearRef: 'Clear', noRef: '(no alignment)', + ueAlignHint: 'For parts exported separately (head, body and outfit as separate uemodels), select the same full-body model as reference to align them to its skeleton.', + ueWeakRef: 'This skeleton spans only about {cm} cm and looks like a part rather than a full body; using it as reference may sink the model', + psk: 'psk / pskx', xps: 'xps', jpBones: 'MMD Japanese bone names', ik: 'Add IK bones', inMorphs: 'Export morphs', + inAlpha: 'Strip texture alpha', hideUnused: 'Group unused bones', xpsDouble: 'Double-sided', xpsEdge: 'Outline', + outLocation: 'Save to', outApp: 'App folder', outBeside: 'Next to source', outFolder: 'Folder', choose: 'Choose…', + noFolder: '(none)', subfolder: 'Put each file\'s results in its own subfolder', + jobs: 'Parallel jobs', jobsAuto: 'Auto', jobsManual: 'Manual', jobsNumTip: 'Files converted at the same time (1–64)', + jobsHint: 'How many files are converted at the same time. Auto is the number of physical CPU cores minus one (at most 8), fewer when free memory is short; conversions run in the background at a lower priority so other programs stay responsive. Rarely needs changing.', + start: 'Start conversion', restart: 'Convert again', stop: 'Stop', idle: 'Ready', converting: 'Converting {i}/{n}: {name}', + finished: '{done} done, {failed} failed', finishedSkip: '{done} done, {skipped} skipped, {failed} failed', + nothing: 'Nothing to convert', + log: 'Log', clearLog: 'Clear log', + pvEmpty: 'Click "Preview" on the left to view a model', pvMaking: 'Generating preview (quick conversion)…', + pvLoading: 'Loading…', pvFailed: 'Preview failed: {err}', + errNoFile: 'The file is no longer in the list', errNoPreview: "This output can't be previewed", errNotFound: 'File not found', + body: 'Body', upper: 'Upper', face: 'Face', back: 'Back', + tpose: 'T-pose', idleM: 'Idle', walk: 'Walk', run: 'Run', legRaise: 'Leg raise', turn: 'Turn', + autoThumb: 'Generate a thumbnail after converting', + autoThumbHint: 'Captures the face in the previewer and writes it into the VRM, refreshed on every conversion. Models with a thumbnail set by hand in Tune are left alone; each model in an archive gets its own.', + thumbAuto: 'generated', + pvHint: 'Left drag: rotate · Right drag: pan · Wheel: zoom · Double-click: orbit around that point · R: reset view', pinChain: 'Keep this chain shown', focusChain: 'Point the camera at this chain', + pvBones: 'Bones', bHumanoid: 'Humanoid', bHumanoidPmx: 'Standard', bWeighted: 'Weighted', bSpring: 'Physics', + bControl: 'Control / intermediate', bUnused: 'Unused', bParent: 'Parent: {p}', bRoot: '(root)', iBones: 'Bones', iBonesV: '{n} ({u} unused)', + physics: 'Physics', light: 'Light', expressions: 'Expressions', shot: 'Snapshot', saved: 'Saved: {path}', + lightAz: 'Azimuth', lightEl: 'Elevation', lightI: 'Key light', ambient: 'Ambient', shadow: 'Shadows', reset: 'Reset', + filter: 'Filter…', info: 'Info', + tabMain: 'Convert', convertTo: 'Convert to', + targetHint_vrm1: 'Recommended. Supported by Unity (UniVRM), VSeeFace and most games.', + targetHint_vrm0: 'Use only for apps that cannot read VRM 1.0. Physics is approximated in the 0.x format, a little coarser than in 1.0.', + targetHint_pmx: 'FBX, unitypackage and other formats are converted to PMX for MMD only; added PMX files are not processed.', + fileSize: 'File size', sizeOrig: 'Original', sizeMid: 'Medium', sizeSmall: 'Smallest', + sizeHint_orig: 'Original textures: best quality, largest file.', + sizeHint_mid: 'Textures up to 2048, opaque textures as JPEG. Files are usually less than half the size with no noticeable quality loss.', + sizeHint_small: 'Textures up to 1024, opaque textures as JPEG. Smallest file; slightly blurry up close.', + sizeCustom: 'Custom: textures up to {max}, opaque textures as {fmt} (change under Advanced).', advanced: 'Advanced', + advPhysics: 'Physics', advExpr: 'Expressions', advLook: 'Display fixes', advBones: 'Skeleton', collapseBones: 'Remove control bones', + advRun: 'Output and conversion', + autoSpringHint: 'Models from FBX and similar formats usually have no physics; chains are added for hair, skirts, sleeves, etc. by bone name.', + comboExprHint: 'Presets such as happy and angry move the whole face, as in VRoid. When off, each preset uses a single morph.', + collapseBonesHint: 'Removes unweighted intermediate bones (全ての親, センター, グルーブ, 腰, 肩P, etc.) so the hierarchy matches VRoid (Root > Hips). IK, tip and other unused bones are always removed.', + extraExprHint: 'Adds custom expressions hideHighlight (eye highlights off) and tongue. Uses matching morphs from the model when present; without a highlight-off morph, one is generated from the eye highlight materials.', + gazeHint: 'With eye bones, adds lookUp / lookDown / lookLeft / lookRight for apps that play these expressions directly.', + doubleSidedHint: 'Turn on if the model has holes, or thin hair or skirts disappear when seen from behind.', + subfolderHint: 'Named \"name_date_n\"; converting again does not overwrite earlier results.', + fbxAlphaHint: 'Game textures often store other data in the alpha channel, which can make the model transparent. Auto decides per texture; choose Strip if whole parts become translucent, or Keep if lace or hair tips get hard edges.', + inputVrmHint: 'Options that only affect PMX (bone names, IK, etc.) appear when \"Convert to\" is set to PMX only.', + metaTerms: 'License', + metaModHint: 'Modification applies to edited versions: \"+ Redistribute\" allows publishing them. \"Allow redistribution\" above applies to sharing the file as is.', + metaReset: 'Reset license to defaults (most restrictive)', openOut: 'Show output', + texTitle: 'Textures', texMax: 'Max size', texOrig: 'Original', texJpeg: 'Store opaque textures as JPEG', + texNoMip: 'Disable texture mipmaps (fixes white UV seams)', + texNoMipHint: 'When UV islands have no gutter, mipmaps average the blank background into island edges and produce white seams. This samples the full-resolution texture instead; distant views may show slight aliasing.', + noPillow: 'Resizing textures and saving JPEG require Pillow (pip install pillow).', + tabMeta: 'Metadata', metaHint: 'Author and usage license written into the VRM; set once and used for every model you convert. The name defaults to the model file name and can be changed per model under Tune. When converting someone else\'s model, follow the original author\'s terms.', + metaAuthor: 'Author', metaVersion: 'Model version', metaContact: 'Contact', metaCopyright: 'Copyright', metaLicense: 'License URL', + metaAvatar: 'Who may use', permEveryone: 'Everyone', permLicensed: 'Licensed', permAuthor: 'Author only', + metaCommercial: 'Commercial', comNone: 'No', comPersonal: 'Personal', comCorp: 'Corporate', + metaMod: 'Modification', modNo: 'Prohibited', modYes: 'Allowed', modRedist: '+ Redistribute', + metaCredit: 'Credit', creditYes: 'Required', creditNo: 'Not required', metaRedist: 'Allow redistribution (sharing the file as is)', + tune: 'Tune', tuneNotReady: 'Tuning is available once the preview is ready (or after converting the model)', + tuneNotReadyPmx: 'This preview shows the original PMX; convert it to VRM to tune it', + tuneAutoSaved: 'Saved the tuning of {name}', tuneNoFile: 'Select a model on the left', + tuneNotEditable: 'Only models converted by this program can be tuned', tuneTitle: 'Name', tuneThumb: 'Thumbnail', thumbFromView: 'Use current view', + thumbHint: 'Choose the framing above first (e.g. Face)', thumbRemove: 'Remove', thumbNone: 'None', + tuneMeta: 'Name and thumbnail', tuneExpr: 'Preset expressions', exprNone: '(none)', exprMissing: '(not in the model; select one manually)', tryExpr: 'Try', tunePhysics: 'Physics', + exprStrength: 'Strength (previewed while dragging)', exprHint: 'The slider on the right sets strength: morph weights are scaled, each capped at 100%, so values above 100% only affect combined expressions (whose weights are below full).', + tuneLook: 'Gaze range', lookH: 'Left/right', lookDown: 'Down', lookUp: 'Up', lookReset: 'Back to auto', + lookHint: 'How far the eyes turn at the edge of their range (computed from the eye shape). Applies to both VRM look-at (e.g. looking at the camera) and the lookLeft etc. expressions added during conversion. Click an arrow to preview.', + lookTry: 'Preview: full range in this direction', + allChains: 'All', chains: 'Chains ({n})', stiffMul: 'Stiffness', dragMul: 'Drag', gravAdd: 'Gravity', + tuneSave: 'Save & write', tuneReset: 'Reset all', tuneDirty: 'Unsaved changes (saved by themselves when you convert or switch files)', tuneClean: 'Will be written into the output VRM and applied to later conversions', + tuneSaved: 'Written to {n} file(s)', tuneSavedNone: 'Saved; applied on the next conversion', thumbSaved: 'Thumbnail updated', + tuned: 'Tuned', dragResize: 'Drag to resize, double-click to reset', + iFormat: 'Format', iHeight: 'Height', iMmdUnit: ' MMD units', iTris: 'Triangles', iMats: 'Materials', iTex: 'Textures', iMorphs: 'Morphs', + iPhysics: 'Physics', iRigid: '{r} rigid bodies / {j} joints', iOff: ' (off)', iHumanoid: 'Humanoid bones', iExpr: 'Expressions', + iChains: '{n} chains / {j} joints', iColliders: 'Colliders', + preset: { happy: 'Happy', angry: 'Angry', sad: 'Sad', relaxed: 'Relaxed', surprised: 'Surprised', neutral: 'Neutral', + aa: 'Mouth A', ih: 'Mouth I', ou: 'Mouth U', ee: 'Mouth E', oh: 'Mouth O', blink: 'Blink', blinkLeft: 'Blink left', blinkRight: 'Blink right', + joy: 'Joy', sorrow: 'Sorrow', fun: 'Fun', a: 'Mouth A', i: 'Mouth I', u: 'Mouth U', e: 'Mouth E', o: 'Mouth O', + blink_l: 'Blink left', blink_r: 'Blink right' }, + }, +}; diff --git a/ui/web/icon.png b/ui/web/icon.png new file mode 100644 index 0000000..c92fe72 Binary files /dev/null and b/ui/web/icon.png differ diff --git a/ui/web/index.html b/ui/web/index.html new file mode 100644 index 0000000..39dba1f --- /dev/null +++ b/ui/web/index.html @@ -0,0 +1,307 @@ + + + + + +VRMify 增强版 · VRMify Enhanced + + + + + +
+
VRMify 增强版
+
+ +
+
+ + +
+ + + +
+
+
+
+ + +
+
+ + + +
+ + + + + + + + +
+
+
+
+ + + + +
+ + + +
+
+
+
+ + + diff --git a/ui/web/layout.js b/ui/web/layout.js new file mode 100644 index 0000000..a2862d4 --- /dev/null +++ b/ui/web/layout.js @@ -0,0 +1,44 @@ +// Drag handles to resize the left column and the side column (panels). Widths are saved in settings.json +// (the pywebview window doesn't keep browser storage between launches); double-click a handle to reset. +import { $, S, api } from './core.js'; + +const root = document.documentElement.style; +const VARS = { left: '--left-w', side: '--side-w', sideWide: '--side-wide-w' }; +const MIN_PREVIEW = 240; // the preview never gets narrower than this while dragging + +export function applyLayout() { + for (const [k, v] of Object.entries(VARS)) { + if (S.ui[k]) root.setProperty(v, S.ui[k] + 'px'); else root.removeProperty(v); + } +} + +const sideKey = () => ($('side').classList.contains('wide') ? 'sideWide' : 'side'); +const width = (el) => el.getBoundingClientRect().width; + +function drag(handle, key, measure) { + handle.addEventListener('pointerdown', (e) => { + e.preventDefault(); + handle.setPointerCapture(e.pointerId); + handle.classList.add('dragging'); document.body.classList.add('resizing'); + const k = key(), x0 = e.clientX, w0 = measure.width(), room = measure.room(); + const move = (ev) => { + const w = Math.round(Math.max(measure.min, Math.min(w0 + (ev.clientX - x0) * measure.dir, w0 + room - MIN_PREVIEW))); + S.ui[k] = w; root.setProperty(VARS[k], w + 'px'); + }; + const up = () => { + handle.removeEventListener('pointermove', move); handle.removeEventListener('pointerup', up); + handle.classList.remove('dragging'); document.body.classList.remove('resizing'); + api('/api/options', { ui: { [k]: S.ui[k] } }); + }; + handle.addEventListener('pointermove', move); handle.addEventListener('pointerup', up); + }); + handle.addEventListener('dblclick', () => { + const k = key(); + delete S.ui[k]; root.removeProperty(VARS[k]); + api('/api/options', { ui: { [k]: null } }); + }); +} + +// left column: dragging right widens it; the side column: dragging left widens it +drag($('splitLeft'), () => 'left', { dir: 1, min: 300, width: () => width(document.querySelector('.left')), room: () => width($('pv')) }); +drag($('splitSide'), sideKey, { dir: -1, min: 220, width: () => width($('side')), room: () => width($('pv')) }); diff --git a/ui/web/options.js b/ui/web/options.js new file mode 100644 index 0000000..384cb85 --- /dev/null +++ b/ui/web/options.js @@ -0,0 +1,155 @@ +// Conversion settings: form ↔ S.opts (saved to settings.json through /api/options), tabs. +// The first tab shows what most conversions need; finer options sit in the "Advanced" fold. +import { $, S, api, t, toast } from './core.js'; + +export const getOpt = (path) => path.split('.').reduce((o, k) => (o ? o[k] : undefined), S.opts); +function setOpt(path, v) { + const ks = path.split('.'); let o = S.opts; + for (const k of ks.slice(0, -1)) o = o[k] = o[k] || {}; + o[ks[ks.length - 1]] = v; +} + +// "Convert to" combines two stored options: target (vrm / pmx) and vrm.spec (1.0 / 0.x) +const targetValue = () => (getOpt('target') === 'pmx' ? 'pmx' : getOpt('vrm.spec') === '0.x' ? 'vrm0' : 'vrm1'); +// "File size" presets over the two texture options; anything else shows as custom (set under Advanced) +const SIZES = { orig: [0, false], mid: [2048, true], small: [1024, true] }; +const sizeValue = () => Object.keys(SIZES).find((k) => SIZES[k][0] === +getOpt('vrm.tex_max') && SIZES[k][1] === !!getOpt('vrm.tex_jpeg')); + +const markSeg = (seg, v) => seg.querySelectorAll('button').forEach((b) => { + const on = b.dataset.v === v; + b.classList.toggle('on', on); b.setAttribute('aria-pressed', on); +}); + +export function applyOptsToForm() { + document.querySelectorAll('[data-opt]').forEach((el) => { + const v = getOpt(el.dataset.opt); + if (el.classList.contains('seg')) markSeg(el, String(v)); + else if (el.type === 'checkbox') el.checked = !!v; + else if (el.type === 'text') { if (document.activeElement !== el) el.value = v ?? ''; } + else if (el.type === 'range') { + el.value = v; + const o = document.querySelector(`output[data-for="${el.dataset.opt}"]`); + if (o) o.textContent = (+v).toFixed(1); + } + }); + markSeg($('targetSeg'), targetValue()); + markSeg($('sizeSeg'), sizeValue()); + // parallel jobs: Auto (the box shows how many that is here, greyed) or Manual (the box is the number) + const jobs = Math.max(0, Math.round(+getOpt('jobs') || 0)); + markSeg($('jobsSeg'), jobs ? 'manual' : 'auto'); + $('jobsNum').disabled = !jobs; + if (document.activeElement !== $('jobsNum')) $('jobsNum').value = jobs || S.features.auto_jobs || ''; + syncDependents(); +} + +// greys out (and disables) options that don't apply with the current choices +const dim = (el, off) => { el.disabled = off; el.closest('.switch, .field').classList.toggle('dim', off); }; +export function syncDependents() { + const target = targetValue(), spring = getOpt('vrm.spring'); + document.querySelector('.settings-card').classList.toggle('pmx', target === 'pmx'); + $('targetHint').textContent = t('targetHint_' + target); + document.querySelectorAll('[data-opt="vrm.spring"], [data-opt="vrm.spring_skirt"], [data-opt="vrm.auto_spring"], [data-opt="vrm.spring_stiffness"]') + .forEach((el) => dim(el, el.dataset.opt !== 'vrm.spring' && !spring)); + document.querySelectorAll('[data-opt="vrm.gaze"], [data-opt="vrm.combo_expr"], [data-opt="vrm.extra_expr"]').forEach((el) => dim(el, !getOpt('vrm.morphs'))); + $('chooseOut').disabled = getOpt('output.mode') !== 'folder'; + // texture slimming needs Pillow on the Python side + const pil = S.features.pillow !== false; + for (const seg of [$('sizeSeg'), document.querySelector('[data-opt="vrm.tex_max"]')]) { + seg.querySelectorAll('button').forEach((b) => { b.disabled = !pil && b.dataset.v !== 'orig' && b.dataset.v !== '0'; }); + } + dim(document.querySelector('[data-opt="vrm.tex_jpeg"]'), !pil); + const size = sizeValue(); + $('texHint').textContent = !pil ? t('noPillow') : size ? t('sizeHint_' + size) + : t('sizeCustom', { max: +getOpt('vrm.tex_max') || t('texOrig'), fmt: getOpt('vrm.tex_jpeg') ? 'JPEG' : 'PNG' }); + $('texHint').classList.toggle('warn', !pil); + renderUeRef(); + renderOutFolder(); +} + + +function renderUeRef() { + const f = getOpt('uemodel.align_ref'); + $('ueRef').textContent = f ? f.split(/[\\/]/).pop() : t('noRef'); + $('ueRef').title = f || ''; + $('ueRefClear').disabled = !f; +} +export function renderOutFolder() { + const mode = getOpt('output.mode'), f = mode === 'app' ? S.appOut : getOpt('output.folder'); + $('outFolder').textContent = mode === 'beside' ? t('outBeside') : (f || t('noFolder')); + $('outFolder').title = f || ''; + $('outFolder').classList.toggle('dim', mode === 'beside'); +} + +let saveTimer = null; +function saveOpts() { clearTimeout(saveTimer); saveTimer = setTimeout(flushOpts, 250); } +// sends a pending change now (starting a conversion right after changing a setting must use the new value) +export async function flushOpts() { + if (saveTimer === null) return; + clearTimeout(saveTimer); saveTimer = null; + await api('/api/options', { opts: S.opts }); +} +const changed = () => { applyOptsToForm(); saveOpts(); }; + +document.querySelectorAll('[data-opt]').forEach((el) => { + if (el.classList.contains('seg')) { + el.addEventListener('click', (e) => { + const b = e.target.closest('button'); if (!b) return; + setOpt(el.dataset.opt, b.dataset.v); changed(); + }); + } else { + el.addEventListener('input', () => { + setOpt(el.dataset.opt, el.type === 'checkbox' ? el.checked : el.type === 'text' ? el.value.trim() : +el.value); + changed(); + }); + } +}); +$('jobsSeg').addEventListener('click', (e) => { + const v = e.target.closest('button')?.dataset.v; if (!v) return; + const manual = v === 'manual'; + if (manual === !!(+getOpt('jobs'))) return; + setOpt('jobs', manual ? Math.max(1, +$('jobsNum').value || S.features.auto_jobs || 1) : 0); + changed(); + if (manual) $('jobsNum').focus(); +}); +$('jobsNum').addEventListener('change', (e) => { + const n = Math.round(+e.target.value); + if (n >= 1) setOpt('jobs', Math.min(64, n)); + changed(); + e.target.value = +getOpt('jobs') || S.features.auto_jobs || ''; // an invalid entry shows the stored number again +}); +$('targetSeg').addEventListener('click', (e) => { + const v = e.target.closest('button')?.dataset.v; if (!v) return; + setOpt('target', v === 'pmx' ? 'pmx' : 'vrm'); + if (v !== 'pmx') setOpt('vrm.spec', v === 'vrm0' ? '0.x' : '1.0'); + changed(); +}); +$('sizeSeg').addEventListener('click', (e) => { + const v = e.target.closest('button')?.dataset.v; if (!v || !SIZES[v]) return; + setOpt('vrm.tex_max', String(SIZES[v][0])); setOpt('vrm.tex_jpeg', SIZES[v][1]); + changed(); +}); +// license terms back to the conservative defaults (author / contact fields stay) +const META_DEFAULTS = { avatar_permission: 'everyone', commercial_usage: 'personalNonProfit', credit_notation: 'required', + allow_redistribution: false, modification: 'prohibited' }; +$('metaReset').onclick = () => { for (const [k, v] of Object.entries(META_DEFAULTS)) setOpt('meta.' + k, v); changed(); }; + +$('ueRefPick').onclick = async () => { + const r = await api('/api/pick_ue_ref', {}); + if (!r.path) return; + setOpt('uemodel.align_ref', r.path); renderUeRef(); saveOpts(); + if (r.warn) toast(t('ueWeakRef', { cm: r.warn })); +}; +$('ueRefClear').onclick = () => { setOpt('uemodel.align_ref', ''); renderUeRef(); saveOpts(); }; +$('chooseOut').onclick = async () => { + const r = await api('/api/pick_output', {}); + if (r.folder) { setOpt('output.folder', r.folder); renderOutFolder(); saveOpts(); } +}; +document.querySelectorAll('[data-tab]').forEach((b) => b.addEventListener('click', () => { + document.querySelectorAll('[data-tab]').forEach((x) => x.classList.toggle('on', x === b)); + document.querySelectorAll('[data-panel]').forEach((p) => { p.hidden = p.dataset.panel !== b.dataset.tab; }); +})); +// the Advanced fold remembers whether it was open (per browser profile; harmless if storage is unavailable) +try { $('advanced').open = localStorage.getItem('advancedOpen') === '1'; } catch (e) { /* no storage */ } +$('advanced').addEventListener('toggle', () => { + try { localStorage.setItem('advancedOpen', $('advanced').open ? '1' : '0'); } catch (e) { /* no storage */ } +}); diff --git a/ui/web/preview.js b/ui/web/preview.js new file mode 100644 index 0000000..9c76d90 --- /dev/null +++ b/ui/web/preview.js @@ -0,0 +1,155 @@ +// 3D preview (viewer-core.js), its toolbar and the side column (light / expressions / tune / info). +import { BONE_COLORS, Viewer } from '/viewer/viewer-core.js'; +import { $, S, api, errText, esc, t, toast } from './core.js'; +import { renderFiles } from './files.js'; +import { flushOpts } from './options.js'; +import { T, leaveTune, loadTune, springParams } from './tune.js'; + +export const viewer = new Viewer($('pv')); +export let modelUrl = null; + +viewer.onLoad = (info) => { + fillPreviewPanels(info); + fillLegend(); + // reload after saving tune edits keeps the camera + if (S.keepView) { viewer.camera.position.copy(S.keepView.pos); viewer.controls.target.copy(S.keepView.tgt); viewer.controls.update(); S.keepView = null; } + else viewer.frame(document.querySelector('[data-frame].on').dataset.frame); + if (T.fid === S.current && T.info && T.info.ready && T.dirty) viewer.setSpringParams(springParams()); +}; + +export function showBusy(text) { $('pvBusy').hidden = !text; $('pvBusyText').textContent = text || ''; } + +export async function previewFile(id, output) { + if (!leaveTune(id)) return; + S.current = id; renderFiles(); + // the tune panel opens with the preview once there is something to tune (a converted / preview VRM), + // unless another panel (light / expressions / info) is open + S.autoTune = !openPanel(); + loadTune(); + await flushOpts(); + const r = await api('/api/preview', output === undefined ? { id } : { id, output }); + if (r.url) loadModel(r.url, r.name); + else if (r.pending) showBusy(t('pvMaking')); + else if (r.error) toast(errText(r.error, r.error_en)); +} + +export async function loadModel(url, name, keepView) { + showBusy(t('pvLoading')); + S.keepView = keepView && viewer.loaded ? { pos: viewer.camera.position.clone(), tgt: viewer.controls.target.clone() } : null; + try { + await viewer.loadUrl(url, name); + modelUrl = url; + $('pvEmpty').hidden = true; + $('pvHint').hidden = false; + $('pvTitle').textContent = name; + if (!T.dirty) loadTune(); // the Tune panel shows the model on screen (an archive can hold several) + } catch (e) { toast(t('pvFailed', { err: e.message })); } + showBusy(null); +} + +// ---- side column: one panel at a time; the preview narrows instead of being covered +const PANELS = { lightPanel: 'lightBtn', exprPanel: 'exprBtn', tunePanel: 'tuneBtn', infoPanel: 'infoBtn' }; +export const openPanel = () => Object.keys(PANELS).find((p) => !$(p).hidden) || null; +export function showPanel(id) { + for (const [p, btn] of Object.entries(PANELS)) { + $(p).hidden = p !== id; + $(btn).classList.toggle('on', p === id); + $(btn).setAttribute('aria-pressed', p === id); + } + $('side').hidden = !id; + if (id !== 'tunePanel') viewer.highlightChain(null); + $('splitSide').hidden = !id; + $('side').classList.toggle('wide', id === 'tunePanel'); +} +for (const [p, btn] of Object.entries(PANELS)) { + $(btn).onclick = () => { + S.autoTune = false; + const open = $(p).hidden; + showPanel(open ? p : null); + if (open && p === 'tunePanel') loadTune(); + }; +} + +// ---- info + expression panels +export function fillPreviewPanels(info) { + if (!info) return; + const rows = info.spec === 'PMX' + ? [[t('iFormat'), 'PMX'], [t('iHeight'), info.height.toFixed(1) + t('iMmdUnit')], [t('iTris'), info.triangles.toLocaleString()], + [t('iMats'), info.materials], [t('iTex'), info.textures], [t('iMorphs'), info.expressions.length], + [t('iPhysics'), info.rigidBodies ? t('iRigid', { r: info.rigidBodies, j: info.constraints }) + (info.physics ? '' : t('iOff')) : '—']] + : [['VRM', info.spec], [t('iHeight'), info.height.toFixed(2) + ' m'], [t('iHumanoid'), info.humanBones], + [t('iTris'), info.triangles.toLocaleString()], [t('iMats'), info.materials], [t('iTex'), info.textures], + [t('iExpr'), info.expressions.length], ['SpringBone', info.springs ? t('iChains', { n: info.springs, j: info.joints }) : '—'], + [t('iColliders'), info.colliders]]; + if (info.bones) rows.splice(info.spec === 'PMX' ? 1 : 2, 0, [t('iBones'), t('iBonesV', { n: info.bones.total, u: info.bones.unused })]); + $('infoList').innerHTML = rows.map(([k, v]) => `
${esc(k)}
${esc(v)}
`).join(''); + const box = $('exprList'); box.innerHTML = ''; + for (const e of info.expressions) { + const row = document.createElement('div'); row.className = 'field'; row.dataset.name = e.name.toLowerCase(); + row.innerHTML = ``; + row.querySelector('input').addEventListener('input', (ev) => viewer.setExpression(e.name, +ev.target.value)); + box.append(row); + } + filterExpr(); +} +function filterExpr() { + const q = $('exprFilter').value.trim().toLowerCase(); + for (const r of $('exprList').children) r.style.display = !q || r.dataset.name.includes(q) ? '' : 'none'; +} +$('exprFilter').addEventListener('input', filterExpr); +$('exprReset').onclick = () => { viewer.resetExpressions(); $('exprList').querySelectorAll('input').forEach((i) => { i.value = 0; }); }; + +// ---- toolbar +const segClick = (id, attr, fn) => $(id).addEventListener('click', (e) => { + const b = e.target.closest('button'); if (!b) return; + $(id).querySelectorAll('button').forEach((x) => { x.classList.toggle('on', x === b); x.setAttribute('aria-pressed', x === b); }); + fn(b.getAttribute(attr)); +}); +segClick('frameSeg', 'data-frame', (k) => viewer.frame(k)); +// R / Home: back to the selected framing (not while typing in a field) +document.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey || e.target.closest('input, textarea, select, [contenteditable]')) return; + if (e.key === 'r' || e.key === 'R' || e.key === 'Home') { viewer.resetView(); e.preventDefault(); } +}); +segClick('motionSeg', 'data-motion', (m) => viewer.setMotion(m)); +segClick('bgSeg', 'data-bg', (c) => viewer.setBackground(c)); +$('pvSpring').addEventListener('change', () => viewer.setSpring($('pvSpring').checked)); + +// ---- skeleton overlay: bones coloured by role, legend with counts, name + parent of the bone under the pointer +const BONE_KINDS = ['humanoid', 'weighted', 'spring', 'control', 'unused']; +const kindLabel = (k) => t({ humanoid: viewer.kind === 'pmx' ? 'bHumanoidPmx' : 'bHumanoid', weighted: 'bWeighted', + spring: 'bSpring', control: 'bControl', unused: 'bUnused' }[k]); +function fillLegend() { + const on = $('pvBones').checked && viewer.loaded; + $('pvLegend').hidden = !on; + $('pvTip').hidden = true; + if (!on) return; + const s = viewer.boneStats(); + $('pvLegend').innerHTML = BONE_KINDS.filter((k) => s[k]).map((k) => + `
${esc(kindLabel(k))}${s[k]}
`).join(''); +} +$('pvBones').addEventListener('change', () => { viewer.setBonesVisible($('pvBones').checked); fillLegend(); }); +$('pv').addEventListener('pointermove', (e) => { + if (!$('pvBones').checked || e.buttons) { $('pvTip').hidden = true; viewer.boneHover = -1; return; } + const b = viewer.boneAt(e.clientX, e.clientY), tip = $('pvTip'); + tip.hidden = !b; + if (!b) return; + const r = $('pv').getBoundingClientRect(); + tip.innerHTML = `
${esc(b.name)}
${esc(kindLabel(b.kind))} · ${esc(t('bParent', { p: b.parent || t('bRoot') }))}
`; + tip.style.left = (e.clientX - r.left) + 'px'; tip.style.top = (e.clientY - r.top) + 'px'; +}); +$('pv').addEventListener('pointerleave', () => { $('pvTip').hidden = true; viewer.boneHover = -1; }); + +function updateLight() { + viewer.setLight({ az: +$('lAz').value, el: +$('lEl').value, intensity: +$('lI').value, ambient: +$('lAmb').value, shadow: $('lShadow').checked }); + $('lAzV').textContent = $('lAz').value + '°'; $('lElV').textContent = $('lEl').value + '°'; + $('lIV').textContent = (+$('lI').value).toFixed(1); $('lAmbV').textContent = (+$('lAmb').value).toFixed(2); +} +['lAz', 'lEl', 'lI', 'lAmb', 'lShadow'].forEach((id) => $(id).addEventListener('input', updateLight)); +updateLight(); + +$('shotBtn').onclick = async () => { + if (!viewer.loaded) return; + const r = await api('/api/snapshot', { name: (viewer.name || 'vrm').replace(/\.[^.]+$/, ''), data: viewer.snapshot(), model: modelUrl }); + if (r.path) toast(t('saved', { path: r.path })); +}; diff --git a/ui/web/run.js b/ui/web/run.js new file mode 100644 index 0000000..a4ae168 --- /dev/null +++ b/ui/web/run.js @@ -0,0 +1,63 @@ +// Run bar (start / stop / progress) and the log. +import { $, S, api, pick, t, toast } from './core.js'; +import { renderFiles } from './files.js'; +import { flushOpts } from './options.js'; +import { T, saveTune } from './tune.js'; + +$('start').onclick = async () => { + await flushOpts(); + if (T.dirty && T.fid) await saveTune(T.edits); // unsaved tune edits go into this conversion + const r = await api('/api/convert', {}); + if (!r.started) toast(t('nothing')); + S.result = null; S.logErrors = 0; renderBadge(); +}; +$('stop').onclick = () => api('/api/stop', {}); +// after a run: show where the results went (the newest output, selected in the file manager) +const lastOutput = () => [...S.files].reverse().flatMap((f) => f.outputs.slice(-1))[0]; +$('openOut').onclick = () => { const o = lastOutput(); if (o) api('/api/open', { path: o.path }); }; + +export function renderStatus() { + $('start').hidden = S.busy; $('stop').hidden = !S.busy; + let s = t('idle'), pct = 0; + if (S.busy && S.progress) { + s = t('converting', { i: S.progress.index + 1, n: S.progress.total, name: S.progress.name }); + pct = S.progress.index / S.progress.total * 100; + } else if (S.result) { s = t(S.result.skipped ? 'finishedSkip' : 'finished', S.result); pct = 100; } + $('status').textContent = s; + $('openOut').hidden = S.busy || !lastOutput(); + $('progressFill').style.width = pct + '%'; + renderFiles(); +} + +let lastFile = null; +// fid: the file this line belongs to. When several files convert at once their lines interleave, so a short +// "· name" line marks each switch (a file's own first line "→ name" already says it) +// en: the English version of the line (null when there is none); both are kept so a language switch can redo the log +export function appendLog(msg, tag, fid, en) { + const log = $('log'); + if (fid && fid !== lastFile && !msg.startsWith('→')) { + const f = S.files.find((x) => x.id === fid); + if (f) { const h = document.createElement('div'); h.className = 'file-mark'; h.textContent = '· ' + f.name; log.append(h); } + } + lastFile = fid || lastFile; + const line = document.createElement('div'); + if (tag) line.className = tag; + line.dataset.zh = msg; + if (en) line.dataset.en = en; + line.textContent = pick(msg, en); + log.append(line); + while (log.childElementCount > 3000) log.firstElementChild.remove(); + log.scrollTop = log.scrollHeight; + if (tag === 'err') { S.logErrors++; renderBadge(); } +} +// after a language switch +export function relocalizeLog() { + for (const line of $('log').children) if (line.dataset.zh !== undefined) line.textContent = pick(line.dataset.zh, line.dataset.en); +} +function renderBadge() { $('logBadge').hidden = !S.logErrors; $('logBadge').textContent = S.logErrors; } +$('logToggle').onclick = () => { + const open = $('log').hidden; + $('log').hidden = !open; $('logCard').classList.toggle('open', open); + $('logToggle').setAttribute('aria-expanded', open); +}; +$('clearLog').onclick = () => { $('log').innerHTML = ''; S.logErrors = 0; renderBadge(); }; diff --git a/ui/web/thumbs.js b/ui/web/thumbs.js new file mode 100644 index 0000000..b97788f --- /dev/null +++ b/ui/web/thumbs.js @@ -0,0 +1,54 @@ +// Automatic VRM thumbnails: when a file finishes converting, each of its VRMs is loaded into a hidden viewer, +// framed on the face and saved as that model's thumbnail (the same as the Tune panel's "use current view"). +// Option vrm.auto_thumb; the server keeps a thumbnail the user set by hand (see /api/tune/thumb auto). +import { Viewer } from '/viewer/viewer-core.js'; +import { api } from './core.js'; +import { getOpt } from './options.js'; +import { viewer } from './preview.js'; +import { modelOf } from './tune.js'; + +let tv = null, running = false; +const queue = []; +export let onThumb = null; // (file id) → called after a thumbnail was written +export function setOnThumb(fn) { onThumb = fn; } + +function thumbViewer() { + if (!tv) { + const box = document.createElement('div'); + box.style.cssText = 'position:fixed;left:-20000px;top:0;width:1024px;height:1024px;pointer-events:none'; + box.setAttribute('aria-hidden', 'true'); + document.body.append(box); + tv = new Viewer(box, { loop: false, pixelRatio: 1 }); + } + return tv; +} + +// a file entry that just went from running to done: one thumbnail for each of its VRMs (an archive can hold several) +export function queueThumb(entry) { + if (!getOpt('vrm.auto_thumb')) return; + for (const o of (entry.outputs || []).filter((x) => x.url)) { + const model = modelOf(o.name); + if (!queue.some((q) => q.id === entry.id && q.model === model)) queue.push({ id: entry.id, url: o.url, name: o.name, model }); + } + if (queue.length && !running) run(); +} + +async function run() { + running = true; + while (queue.length) { + const job = queue.shift(); + try { + const v = thumbViewer(); + v.setBackground(viewer.scene.background); + v.setLight({ ...viewer.light }); + await v.loadUrl(job.url, job.name); + if (v.vrm) v.vrm.update(0); + v.frame('face'); + const data = v.snapshotSquare(1024); + v.clear(); + const r = await api('/api/tune/thumb', { id: job.id, data, auto: true, model: job.model }); + if (r.ok && onThumb) onThumb(job.id); + } catch (e) { console.warn('auto thumbnail failed', job.name, e); } + } + running = false; +} diff --git a/ui/web/tune.js b/ui/web/tune.js new file mode 100644 index 0000000..5a5b91e --- /dev/null +++ b/ui/web/tune.js @@ -0,0 +1,280 @@ +// Tune panel: per-model adjustments written into the converted VRM (convert/vrm_edit.py) — name, thumbnail, +// which expression drives each VRM preset and how strong, gaze range, SpringBone multipliers. +// Physics changes preview live; everything else is written on "Save" — or by itself before converting and when +// switching to another file, so edits aren't lost when "Save" is forgotten. +import { $, S, api, clone, errText, esc, num, presetLabel, t, toast } from './core.js'; +import { loadModel, modelUrl, showPanel, viewer } from './preview.js'; + +export const T = { + fid: null, info: null, edits: {}, dirty: false, + open: { meta: true, expr: true, look: true, physics: true, chains: false }, // collapsible sections (kept across models) +}; + +// three-vrm loads VRM 0.x presets under their 1.0 names +const V0_TO_V1 = { a: 'aa', i: 'ih', u: 'ou', e: 'ee', o: 'oh', joy: 'happy', sorrow: 'sad', fun: 'relaxed', blink_l: 'blinkLeft', blink_r: 'blinkRight' }; + +// which model of the file a VRM / preview URL or file name is (vrm_edit.model_key): thumbnails are kept per model +export const modelOf = (s) => (s ? decodeURIComponent(s.split('?')[0].split('/').pop()).replace(/\.[^.]+$/, '') : null); + +// switching to another file: save the unsaved tune edits of the one on screen (in the background; that file's +// VRM isn't on screen any more). Edits are per file, so other outputs of the same file keep them unsaved. +export function leaveTune(id) { + if (!T.dirty || !T.fid || T.fid === id) return true; + const fid = T.fid, edits = clone(T.edits), f = S.files.find((x) => x.id === fid); + T.dirty = false; + api('/api/tune/save', { id: fid, edits }).then((r) => + toast(r.error ? errText(r.error, r.error_en) : t('tuneAutoSaved', { name: f ? f.name : '' }))); + return true; +} + +export async function loadTune() { + if ($('tunePanel').hidden && !S.autoTune) return; + const fid = S.current; + if (!fid) { T.fid = null; T.info = null; renderTune(); return; } + const r = await api('/api/tune', { id: fid, model: modelOf(modelUrl) }); + if (fid !== S.current) return; + T.fid = fid; T.info = r; T.edits = clone(r.edits); delete T.edits.thumbnail; delete T.edits.thumbnail_auto; delete T.edits.thumbnails; + T.dirty = false; + if (S.autoTune && r.ready && $('tunePanel').hidden) { showPanel('tunePanel'); S.autoTune = false; } + if (!$('tunePanel').hidden) renderTune(); +} + +function assigned(p, edits) { + const e = (edits || T.edits).expressions || {}; + return p in e ? e[p] : (T.info.assign[p] || ''); +} + +// name of a source expression in the currently loaded (saved) model, for the "Try" button +function exprNameInModel(sid) { + const saved = clone(T.info.edits); + const is1 = T.info.spec === '1.0'; + for (const p of T.info.presets) if (assigned(p, saved) === sid) return is1 ? p : (V0_TO_V1[p] || p); + return sid.startsWith('@') ? 'orig_' + sid.slice(1) : sid; +} + +export function springParams() { + const sp = T.edits.spring || {}, gs = num(sp.stiffness, 1), gd = num(sp.drag, 1), gg = num(sp.gravity, 0), ch = sp.chains || {}; + const out = []; + for (const c of T.info.springs || []) { + const e = ch[c.key] || {}, cs = num(e.stiffness, 1), cg = num(e.gravity, 0); + for (const j of c.joints) { + out.push({ node: j.node, enabled: !e.off, stiffness: Math.max(0, j.stiffness * gs * cs), + gravityPower: Math.max(0, j.gravityPower + gg + cg), dragForce: Math.min(1, Math.max(0, j.dragForce * gd)) }); + } + } + return out; +} + +function markDirty() { + T.dirty = true; + $('tuneState').textContent = t('tuneDirty'); + $('tuneSave').disabled = false; +} + +function slider(label, val, min, max, step, onInput, fmt) { + const d = document.createElement('div'); d.className = 'field'; + d.innerHTML = `${fmt(val)}`; + const inp = d.querySelector('input'), o = d.querySelector('output'); + inp.addEventListener('input', () => { o.textContent = fmt(inp.value); onInput(+inp.value); }); + return d; +} +const fmtMul = (v) => '×' + (+v).toFixed(2), fmtAdd = (v) => '+' + (+v).toFixed(2), fmtDeg = (v) => (+v).toFixed(1) + '°'; +const hint = (text) => { const d = document.createElement('div'); d.className = 'hint flush'; d.textContent = text; return d; }; + +// a collapsible section; its open / closed state is remembered in T.open +function section(parent, key, title) { + const d = document.createElement('details'); d.className = 'sec'; d.open = T.open[key]; + d.addEventListener('toggle', () => { T.open[key] = d.open; }); + const s = document.createElement('summary'); s.textContent = title; + d.append(s); parent.append(d); + return d; +} + +export function renderTune() { + const body = $('tuneBody'); + const keep = T.renderedFid === T.fid ? body.scrollTop : 0; // re-render (reset / thumbnail …) stays in place + T.renderedFid = T.fid; + requestAnimationFrame(() => { body.scrollTop = keep; }); + body.innerHTML = ''; + const msg = (text) => { body.innerHTML = `
${esc(text)}
`; $('tuneFoot').hidden = true; }; + if (!T.info || T.fid !== S.current) return msg(t('tuneNoFile')); + if (T.info.error) return msg(errText(T.info.error, T.info.error_en)); + if (T.info.editable === false) return msg(t('tuneNotEditable')); + if (!T.info.ready) { + const f = S.files.find((x) => x.id === T.fid); + return msg(t(f && f.kind === 'pmx' ? 'tuneNotReadyPmx' : 'tuneNotReady')); + } + $('tuneFoot').hidden = false; + $('tuneState').textContent = T.dirty ? t('tuneDirty') : t('tuneClean'); + $('tuneSave').disabled = !T.dirty; + renderMeta(section(body, 'meta', t('tuneMeta'))); + renderExpr(section(body, 'expr', t('tuneExpr'))); + if (T.info.look) renderLook(section(body, 'look', t('tuneLook'))); + if ((T.info.springs || []).length) renderPhysics(section(body, 'physics', t('tunePhysics'))); +} + +// ---- name + thumbnail (the thumbnail is saved right away: it is a picture of the current view) +function renderMeta(sec) { + const nf = document.createElement('div'); nf.className = 'field'; + nf.innerHTML = ``; + nf.querySelector('input').addEventListener('input', (e) => { T.edits.title = e.target.value.trim(); markDirty(); }); + const tr = document.createElement('div'); tr.className = 'thumb-row'; + tr.innerHTML = (T.info.thumbnail ? `` : `
${t('thumbNone')}
`) + + `
` + + (T.info.thumbnail ? `` : '') + + (T.info.thumbnail && T.info.thumbnail_auto ? `${t('thumbAuto')}` : '') + + `
${t('thumbHint')}
`; + tr.addEventListener('click', async (e) => { + const a = e.target.dataset.a; + if (!a || !viewer.loaded) return; + const r = await api('/api/tune/thumb', { id: T.fid, data: a === 'shot' ? viewer.snapshotSquare(1024) : '', model: modelOf(modelUrl) }); + if (r.error) return toast(errText(r.error, r.error_en)); + T.info.thumbnail = r.thumbnail || null; + T.info.thumbnail_auto = false; // set by hand now: never replaced automatically + toast(t('thumbSaved')); + renderTune(); + }); + sec.append(nf, tr); +} + +// ---- which expression drives each preset, and how strong +function renderExpr(sec) { + sec.append(hint(t('exprHint'))); + const tryExpr = (sid, w) => { + if (!sid) return; + viewer.resetExpressions(); viewer.setExpression(exprNameInModel(sid), w); + clearTimeout(renderTune.tryTimer); renderTune.tryTimer = setTimeout(() => viewer.resetExpressions(), 1500); + }; + const choices = T.info.expressions.map((x) => ``).join(''); + // gaze presets are driven by the gaze range below, not picked here + for (const p of (T.info.presets || []).filter((x) => !/^look/i.test(x))) { + const base = T.info.assign[p] || ''; + const none = ``; + const d = document.createElement('div'); d.className = 'field preset'; + const k = num((T.edits.intensity || {})[p], 1); + d.innerHTML = `` + + `` + + `${Math.round(k * 100)}%`; + const sel = d.querySelector('select'), rng = d.querySelector('input'), out = d.querySelector('output'); + const sync = () => { + sel.classList.toggle('changed', sel.value !== base); + sel.title = sel.selectedOptions[0] ? sel.selectedOptions[0].textContent : ''; // combos are long: full text on hover + d.classList.toggle('missing', !sel.value); + rng.classList.toggle('changed', +rng.value !== 1); + }; + sel.value = assigned(p); + sync(); + rng.addEventListener('input', () => { + const v = +rng.value; + out.textContent = Math.round(v * 100) + '%'; + T.edits.intensity = T.edits.intensity || {}; + if (v === 1) delete T.edits.intensity[p]; else T.edits.intensity[p] = v; + sync(); tryExpr(sel.value, v); markDirty(); + }); + sel.addEventListener('change', () => { + T.edits.expressions = T.edits.expressions || {}; + if (sel.value === base) delete T.edits.expressions[p]; else T.edits.expressions[p] = sel.value; + sync(); markDirty(); + }); + d.querySelector('button').addEventListener('click', () => tryExpr(sel.value, +rng.value)); + sec.append(d); + } +} + +// ---- gaze range (VRM look-at max angles; also re-weights the added gaze expressions) +function renderLook(sec) { + sec.append(hint(t('lookHint'))); + const cur = () => Object.assign({}, T.info.look, T.edits.lookAt || {}); + // yaw / pitch for each preview arrow, as seen on screen from the front (VRM look-at input: + // +yaw = the model's own left = screen right; ±90 = full range) + const peek = (dir) => { + const [yaw, pitch] = { left: [-90, 0], right: [90, 0], up: [0, 90], down: [0, -90] }[dir]; + viewer.setLook(yaw, pitch, cur()); + clearTimeout(renderTune.lookTimer); renderTune.lookTimer = setTimeout(() => viewer.setLook(null), 1500); + }; + const set = (key, v) => { T.edits.lookAt = Object.assign(cur(), { [key]: v }); markDirty(); }; + sec.append(slider(t('lookH'), cur().h, 0, 40, 0.5, (v) => { set('h', v); peek('left'); }, fmtDeg), + slider(t('lookDown'), cur().down, 0, 30, 0.5, (v) => { set('down', v); peek('down'); }, fmtDeg), + slider(t('lookUp'), cur().up, 0, 30, 0.5, (v) => { set('up', v); peek('up'); }, fmtDeg)); + const row = document.createElement('div'); row.className = 'field'; + row.innerHTML = `` + ['left', 'right', 'up', 'down'].map((d) => + ``).join(' ') + + (T.edits.lookAt ? ` ` : ''); + row.addEventListener('click', (e) => { + const d = e.target.dataset.d; + if (!d) return; + if (d === 'reset') { delete T.edits.lookAt; markDirty(); renderTune(); return; } + peek(d); + }); + sec.append(row); +} + +// ---- physics (VRM 1.0 SpringBone / 0.x spring groups): overall multipliers, then each chain (collapsed by default) +// the chain kept shown in the preview (pin button), per file; hovering another chain shows that one meanwhile +let pinned = null; // { fid, key, nodes } +const pinnedNodes = () => (pinned && pinned.fid === T.fid ? pinned.nodes : null); +const ICON_EYE = ''; +const ICON_AIM = ''; + +function renderPhysics(sec) { + if (pinned && (pinned.fid !== T.fid || !T.info.springs.some((c) => c.key === pinned.key))) pinned = null; + viewer.highlightChain(pinnedNodes()); + const sp = T.edits.spring = T.edits.spring || {}; + sp.chains = sp.chains || {}; + const live = () => { viewer.setSpringParams(springParams()); markDirty(); }; + sec.append(hint(t('allChains')), + slider(t('stiffMul'), num(sp.stiffness, 1), 0.2, 3, 0.05, (v) => { sp.stiffness = v; live(); }, fmtMul), + slider(t('dragMul'), num(sp.drag, 1), 0.2, 2, 0.05, (v) => { sp.drag = v; live(); }, fmtMul), + slider(t('gravAdd'), num(sp.gravity, 0), 0, 1, 0.02, (v) => { sp.gravity = v; live(); }, fmtAdd)); + const chains = section(sec, 'chains', t('chains', { n: T.info.springs.length })); + const flt = document.createElement('div'); flt.className = 'field'; + flt.innerHTML = ``; + const list = document.createElement('div'); list.className = 'chain-list'; + chains.append(flt, list); + for (const c of T.info.springs) { + const e = sp.chains[c.key] || {}; + const get = () => (sp.chains[c.key] = sp.chains[c.key] || {}); + const row = document.createElement('div'); row.className = 'chain' + (e.off ? ' off' : ''); row.dataset.name = c.name.toLowerCase(); + const nodes = c.joints.map((j) => j.node); + row.classList.toggle('pinned', !!pinned && pinned.fid === T.fid && pinned.key === c.key); + const head = document.createElement('div'); head.className = 'chain-head'; + const pin = document.createElement('button'); pin.className = 'ibtn' + (row.classList.contains('pinned') ? ' on' : ''); + pin.innerHTML = ICON_EYE; pin.title = t('pinChain'); pin.setAttribute('aria-label', t('pinChain')); + pin.onclick = () => { + const on = !row.classList.contains('pinned'); + list.querySelectorAll('.chain.pinned').forEach((r) => { r.classList.remove('pinned'); r.querySelector('.ibtn').classList.remove('on'); }); + pinned = on ? { fid: T.fid, key: c.key, nodes } : null; + row.classList.toggle('pinned', on); pin.classList.toggle('on', on); + viewer.highlightChain(on ? nodes : null); + }; + const aim = document.createElement('button'); aim.className = 'ibtn'; + aim.innerHTML = ICON_AIM; aim.title = t('focusChain'); aim.setAttribute('aria-label', t('focusChain')); + aim.onclick = () => viewer.focusChain(nodes); + const sw = document.createElement('label'); sw.className = 'switch'; + sw.innerHTML = `${esc(c.name)} · ${c.joints.length}`; + sw.querySelector('input').addEventListener('change', (ev) => { get().off = !ev.target.checked; row.classList.toggle('off', !ev.target.checked); live(); }); + head.append(sw, pin, aim); + row.append(head, + slider(t('stiffMul'), num(e.stiffness, 1), 0.2, 3, 0.05, (v) => { get().stiffness = v; live(); }, fmtMul), + slider(t('gravAdd'), num(e.gravity, 0), 0, 1, 0.02, (v) => { get().gravity = v; live(); }, fmtAdd)); + // hovering a chain shows it in the preview (joints, hit radius, its colliders) + row.addEventListener('pointerenter', () => viewer.highlightChain(nodes)); + row.addEventListener('pointerleave', () => viewer.highlightChain(pinnedNodes())); + list.append(row); + } + flt.querySelector('input').addEventListener('input', (ev) => { + const q = ev.target.value.trim().toLowerCase(); + for (const r of list.children) r.style.display = !q || r.dataset.name.includes(q) ? '' : 'none'; + }); +} + +export async function saveTune(edits) { + const r = await api('/api/tune/save', { id: T.fid, edits }); + if (r.error) return toast(errText(r.error, r.error_en)); + toast(r.applied ? t('tuneSaved', { n: r.applied }) : t('tuneSavedNone')); + T.dirty = false; + if (modelUrl && r.applied) await loadModel(modelUrl, viewer.name, true); + await loadTune(); +} +$('tuneSave').onclick = () => saveTune(T.edits); +$('tuneReset').onclick = () => { T.edits = {}; saveTune({}); };