diff --git a/.cargo/config.toml b/.cargo/config.toml new file mode 100644 index 0000000..2404f21 --- /dev/null +++ b/.cargo/config.toml @@ -0,0 +1,6 @@ +# You may be asking, "wait, why is this here and not in the pacakge directories?" +# As of January 2025, [per-package targets](https://github.com/rust-lang/cargo/issues/9406) hasn't hit stable Rust. Once that hits, we can move this back into the package directories. +# Issue for our tracking: https://github.com/CesiumGS/cesium-wasm-utils/issues/2 + +[build] +target = "wasm32-unknown-unknown" diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7377d37 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,8 @@ +version: 2 +updates: +- package-ecosystem: cargo + directory: "/" + schedule: + interval: daily + time: "08:00" + open-pull-requests-limit: 10 diff --git a/.github/workflows/wasm-splats-ci.yml b/.github/workflows/wasm-splats-ci.yml new file mode 100644 index 0000000..358f09c --- /dev/null +++ b/.github/workflows/wasm-splats-ci.yml @@ -0,0 +1,55 @@ +name: wasm-splats CI +on: + push: + paths: + - 'wasm-splats/**' + - '.github/workflows/wasm-splats-ci.yml' + +jobs: + test_and_lint: + name: Testing and Linting + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + lfs: true + + - name: Install latest stable with wasm32-unknown-unknown + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: rustfmt, clippy + + - name: Install wasm-pack + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + + - name: Run rustfmt + run: cargo fmt --all -- --check + + - name: Run clippy + run: cargo clippy --all-targets --all-features -- -Dwarnings + + - name: Run wasm-splats tests + run: wasm-pack test --headless --chrome --firefox + working-directory: ./wasm-splats + + pack: + name: Packaging for npm + runs-on: ubuntu-latest + needs: [ test_and_lint ] + steps: + - uses: actions/checkout@v2 + + - name: Install latest stable with wasm32-unknown-unknown + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: stable + targets: wasm32-unknown-unknown + components: rustfmt, clippy + + - name: Install wasm-pack + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + + - name: Build wasm-splats + run: wasm-pack build ./wasm-splats --release --target web --scope cesium diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f6e165d --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +# Rust +/target +**/*.rs.bk +Cargo.lock +bin/ +pkg/ +wasm-pack.log + +# Rust Rover +.idea/ \ No newline at end of file diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 0000000..5264ecd --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,7 @@ +# Change Log + +## @cesium/wasm-splats + +### 0.1.0-alpha.1 + +- Initial release of the `wasm-splats` package. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..b4657de --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +One of Cesium's strengths is our community. Our contributors and users are pushing the 3D geospatial field to amazing new levels. We rely on an open, friendly, inclusive environment to facilitate this. As such, we follow the [Contributor Covenant](https://www.contributor-covenant.org/)'s [Code of Conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct/) to ensure a harassment-free experience in the Cesium community. Any unacceptable behavior can be confidentially sent to the core team at hello@cesium.com. + +This applies to the main Cesium repo, forum, twitter, and all channels, including all repos in the [CesiumGS](https://github.com/CesiumGS) GitHub organization. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0ecc556 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,79 @@ +# Contribution Guide + +Thanks for contributing to Cesium WASM Utilities. You rock! Are you + +- [submitting an issue](#submitting-an-issue), +- [getting started contributing](#getting-started-contributing), or +- [opening a pull request](#opening-a-pull-request)? + +To ensure an inclusive community, contributors and users in the Cesium community should follow the [code of conduct](./CODE_OF_CONDUCT.md). + +## Submitting an Issue + +If you have a question, do not submit an issue; instead, search the [Cesium community forum](https://community.cesium.com/). The forum is very active and there are years of informative archives, often with answers from the core Cesium team. If you do not find an answer to your question, start a new thread, and you'll likely get a quick response. + +If you think you've found a bug in Cesium WASM Utilities, first search the [issues](https://github.com/CesiumGS/cesium-wasm-utils/issues). If an issue already exists, please add a comment expressing your interest and any additional information. This helps us prioritize issues. + +If a related issue does not exist, submit a new one. Please be concise and include as much of the following information as is relevant: + +- Minimum amount of sample code (and data) shared through [Sandcastle](https://sandcastle.cesium.com). +- Screenshot or animated .gif if appropriate (try [LICEcap](http://www.cockos.com/licecap/)). For example, see [#3153](https://github.com/CesiumGS/cesium/issues/3153) in CesiumJS. Screenshots are particularly useful for exceptions and rendering artifacts. If it is a rendering artifact, also include the output of [webglreport.com](http://webglreport.com/). +- Link to the thread if this was discussed on the Cesium forum or elsewhere. For example, see [#3045](https://github.com/CesiumGS/cesium/issues/3045) in CesiumJS. +- Your operating system and version, browser and version, and video card. Are they all up-to-date? Is the issue specific to one of them? +- The version of CesiumJS. Did this work in a previous version? +- Ideas for how to fix or workaround the issue. Also mention if you are willing to help fix it. If so, the Cesium team can often provide guidance and the issue may get fixed more quickly with your help. + +## Getting Started Contributing + +Everyone is welcome to contribute to Cesium WASM Utilities! + +In addition to contributing core Cesium WASM Utilities code, we appreciate many types of contributions: + +- Being active on the [Cesium community forum](https://community.cesium.com/) by answering questions and providing input on Cesium's direction. +- Showcasing your Cesium apps on [Cesium blog](https://cesium.com/blog/categories/userstories/). Contact us at hello@cesium.com. +- Writing tutorials, creating examples, and improving the reference documentation. +- Submitting issues as [described above](#submitting-an-issue). +- Triaging issues. Browse the [issues](https://github.com/CesiumGS/cesium-wasm-utils/issues) and comment on issues that are no longer reproducible or on issues which you have additional information. +- Creating ecosystem projects for [glTF](https://github.com/KhronosGroup/glTF/issues/456), [CZML](https://github.com/CesiumGS/cesium/wiki/CZML-Guide), and [3D Tiles](https://github.com/CesiumGS/3d-tiles). + +See the [README](README.md) for how to build and run on your system. + +Always feel free to introduce yourself on the [Cesium community forum](https://community.cesium.com/) to brainstorm ideas and ask for guidance. + +## Opening a Pull Request + +We love pull requests. We strive to promptly review them, provide feedback, and merge. Interest in Cesium is at an all-time high so the core team is busy. Following the tips in this guide will help your pull request get merged quickly. + +> If you plan to make a major change, please start a new thread on the [Cesium community forum](https://community.cesium.com/) first. Pull requests for small features and bug fixes can generally just be opened without discussion on the forum. + +### Contributor License Agreement (CLA) + +Before we can review a pull request, we require a signed Contributor License Agreement. There is a CLA for: + +- [individuals](https://docs.google.com/forms/d/e/1FAIpQLScU-yvQdcdjCFHkNXwdNeEXx5Qhu45QXuWX_uF5qiLGFSEwlA/viewform) and +- [corporations](https://docs.google.com/forms/d/e/1FAIpQLSeYEaWlBl1tQEiegfHMuqnH9VxyfgXGyIw13C2sN7Fj3J3GVA/viewform). + +This only needs to be completed once, and enables contributions to all of the projects under the [CesiumGS](https://github.com/CesiumGS) organization, including Cesium WASM Utilities. The CLA ensures you retain copyright to your contributions, and provides us the right to use, modify, and redistribute your contributions using the [Apache 2.0 License](LICENSE.md). + +If you have any questions, feel free to reach out to [hello@cesium.com](mailto:hello@cesium)! + +### Pull Request Guidelines + +Our code is our lifeblood so maintaining Cesium WASM Utilities' high code quality is important to us. + +- Review the [Contributor Guide](./CONTRIBUTING.md). In addition to Cesium WASM Utilities specific topics, they contain a lot of general software development best practices. +- For an overview of our workflow see [GitHub pull request workflows](https://cesium.com/blog/2013/10/08/github-pull-request-workflows/). +- Pull request tips + - If your pull request fixes an existing issue, include a link to the issue in the description (like this: "Fixes [#1](https://github.com/CesiumGS/cesium/issues/1)"). Likewise, if your pull request fixes an issue reported on the Cesium forum, include a link to the thread. + - If your pull request needs additional work, include a [task list](https://github.com/blog/1375%0A-task-lists-in-gfm-issues-pulls-comments). + - Once you are done making new commits to address feedback, add a comment to the pull request such as `"this is ready"` since GitHub doesn't notify us about commits. +- Code and tests + - Follow the [Rust Style Guide](https://doc.rust-lang.org/nightly/style-guide/) and verify that your code passes [rustfmt](https://github.com/rust-lang/rustfmt). + - Verify that your code passes [clippy](https://doc.rust-lang.org/clippy/index.html). + - Verify that all tests pass, and write new tests with excellent code coverage for new code. + - Update the [CHANGES.md](CHANGES.md) file with a summary of your changes. + - If you added third-party libraries, including new version of existing libraries, update [LICENSE.md](LICENSE.md). Mention it in [CHANGES.md](CHANGES.md). If you plan to add a third-party library, start a [GitHub issue](https://github.com/CesiumGS/cesium-wasm-utils/issues/new) discussing it first. + +### Code of Conduct + +To ensure an inclusive community, contributors and users in the Cesium community should follow the [code of conduct](./CODE_OF_CONDUCT.md). diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b212c9b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,12 @@ +[workspace] +resolver = "2" +members = [ + "wasm-splats" +] + +# Profiles must be set at the root level of the `Cargo.toml` file. +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = 3 +lto = true +codegen-units = 1 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d648ea6 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,203 @@ +Copyright 2011-2025 CesiumJS Contributors + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2011-2025 CesiumJS Contributors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c173314 --- /dev/null +++ b/README.md @@ -0,0 +1,92 @@ +# cesium-wasm-utils + +![Cesium](https://github.com/CesiumGS/cesium/wiki/logos/Cesium_Logo_Color.jpg) + +CesiumJS is a JavaScript library for creating 3D globes and 2D maps in a web browser without a plugin. It uses WebGL for +hardware-accelerated graphics, and is cross-platform, cross-browser, and tuned for dynamic-data visualization. + +Built on open formats, CesiumJS is designed for robust interoperability and scaling for massive datasets. + +The `cesium-wasm-utils` mono-repository contains utilities for CesiumJS written in WebAssembly (Wasm) for +performance-critical tasks. + +**NOTE**: This repository is only required for development of these WebAssembly packages. If you are a CesiumJS user or +contributor, you do not need to clone this repository. Instead, follow the instructions in +the [CesiumJS README](https://github.com/CesiumGS/cesium/blob/main/README.md). + +## Packages in this Repository + +- [wasm-splats](wasm-splats/README.md): High-performance algorithms used in the rendering of Gaussian Splats in + CesiumJS. + +# Get Started + +These instructions assume that you already +have [CesiumJS](https://github.com/CesiumGS/cesium/blob/main/README.md#rocket-get-started) configured on your system. + +## Prerequisites + +- [Node.js](https://nodejs.org/en/download/) v22 or later. +- [Rust](https://www.rust-lang.org/tools/install) v1.55 or later. +- [wasm-pack](https://rustwasm.github.io/wasm-pack/installer/) v0.13 or later. + +### Installation recommendations + +#### Node.js + +##### Windows + +On Windows, we recommend using [chocolatey](https://chocolatey.org/) to install Node.js. + +```sh +choco install nodejs +``` + +##### Linux and macOS + +On Linux and macOS, we recommend using [nvm](https://github.com/nvm-sh/nvm) to install Node.js. + +See the [nvm README](https://github.com/nvm-sh/nvm/blob/master/README.md) for installation instructions. + +#### Rust + +On all platforms, we recommend using [rustup](https://rustup.rs/) to install Rust. + +See the [rust website](https://www.rust-lang.org/tools/install) for installation instructions. + +#### wasm-pack + +On all platforms, we recommend using the wasm-pack installer to install wasm-pack. + +See the [wasm-pack website](https://rustwasm.github.io/wasm-pack/installer/) for installation instructions. + +## Get the Code + +### You have commit access to `cesium-wasm-utils` + +Clone the repository: + +```sh +git clone git@github.com:CesiumGS/cesium-wasm-utils.git +``` + +### You do not have commit access to `cesium-wasm-utils` + +You need to fork `cesium-wasm-utils`: + +1. Fork the repository on GitHub. +2. Clone your fork, e.g., `git clone git@github.com:yourusername/cesium.git`. +3. Make changes in a branch, e.g., `git checkout -b my-feature`. + +## Generate Documentation and Open in Browser + +To generate the documentation for all packages in the workspace and open in your default browser, run: + +```sh +cargo doc --no-deps --document-private-items --open +``` + +## Further Instructions + +For further instructions on building and running the packages in this repository, see the README in each package +directory. diff --git a/wasm-splats/.gitattributes b/wasm-splats/.gitattributes new file mode 100644 index 0000000..6d7e777 --- /dev/null +++ b/wasm-splats/.gitattributes @@ -0,0 +1 @@ +tests/common/data/** filter=lfs diff=lfs merge=lfs -text diff --git a/wasm-splats/.gitignore b/wasm-splats/.gitignore new file mode 100644 index 0000000..4e30131 --- /dev/null +++ b/wasm-splats/.gitignore @@ -0,0 +1,6 @@ +/target +**/*.rs.bk +Cargo.lock +bin/ +pkg/ +wasm-pack.log diff --git a/wasm-splats/Cargo.toml b/wasm-splats/Cargo.toml new file mode 100644 index 0000000..d3d439b --- /dev/null +++ b/wasm-splats/Cargo.toml @@ -0,0 +1,38 @@ +[package] +name = "wasm-splats" +version = "0.1.0-alpha.1" +authors = ["Cesium GS, Inc. "] +edition = "2021" +homepage = "https://cesium.com/cesiumjs/" +repository = "https://github.com/CesiumGS/cesium-wasm-utils" +description = "Contains high-performance algorithms used in the rendering of Gaussian Splats in CesiumJS." +license = "Apache-2.0" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +default = ["console_error_panic_hook"] + +[dependencies] +wasm-bindgen = "0.2.99" +js-sys = "0.3.76" +web-sys = { version = "0.3.76", features = ["console"] } + +# The `console_error_panic_hook` crate provides better debugging of panics by +# logging them with `console.error`. This is great for development, but requires +# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for +# code size when deploying. +console_error_panic_hook = { version = "0.1.7", optional = true } + +[dev-dependencies] +wasm-bindgen-test = "0.3" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" + +# Typically we wouldn't include profiles in a workspace project like this, but `wasm-pack` doesn't support workspaces yet. +[profile.release] +# Tell `rustc` to optimize for small code size. +opt-level = 3 +lto = true +codegen-units = 1 diff --git a/wasm-splats/README.md b/wasm-splats/README.md new file mode 100644 index 0000000..4205fc1 --- /dev/null +++ b/wasm-splats/README.md @@ -0,0 +1,31 @@ +# wasm-splats + +[![wasm-splats CI](https://github.com/CesiumGS/cesium-wasm-utils/actions/workflows/wasm-splats-ci.yml/badge.svg)](https://github.com/CesiumGS/cesium-wasm-utils/actions/workflows/wasm-splats-ci.yml) +[![npm](https://img.shields.io/npm/v/@cesium/wasm-splats)](https://www.npmjs.com/package/@cesium/wasm-splats) + +The `wasm-splats` package contains high-performance algorithms used in the rendering of Gaussian Splats in CesiumJS. + +## Getting Started + +Follow the instructions in the [cesium-wasm-utils README](./README.md) to clone the repository and install +prerequisites. + +### Building + +To build the package, run: + +```sh +wasm-pack build --release --target web --scope cesium +``` + +This will output a `pkg` directory containing the compiled WebAssembly module and JavaScript bindings. + +### Testing + +To run the unit and integration tests, run: + +```sh +wasm-pack test --headless --chrome --firefox +``` + +In macOS, you can also add `--safari` to run the tests in Safari. diff --git a/wasm-splats/src/lib.rs b/wasm-splats/src/lib.rs new file mode 100644 index 0000000..d5a0472 --- /dev/null +++ b/wasm-splats/src/lib.rs @@ -0,0 +1,35 @@ +//! Library containing high-performance functions for the Gaussian Splats rendering process within CesiumJS. + +pub mod models; +pub mod radix; +pub mod texture_gen; + +use crate::models::TextureData; +use js_sys::{Float32Array, Uint32Array, Uint8Array}; +use wasm_bindgen::prelude::*; + +/// Generate a splat texture from the given attributes. +/// +/// Wraps the [`texture_gen::generate_texture_from_attrs`] function for access from JavaScript. +#[wasm_bindgen] +pub fn generate_splat_texture( + positions: &Float32Array, + scales: &Float32Array, + rotations: &Float32Array, + colors: &Uint8Array, + count: usize, +) -> Result { + texture_gen::generate_texture_from_attrs(positions, scales, rotations, colors, count) +} + +/// Sorts the Gaussian Splats by depth using a radix sort. +/// +/// Wraps the [`radix::radix_sort_gaussians_indexes`] function for access from JavaScript. +#[wasm_bindgen] +pub fn radix_sort_gaussians_indexes( + positions: &Float32Array, + model_view: &Float32Array, + count: usize, +) -> Result { + radix::radix_sort_gaussians_indexes(positions, model_view, count) +} diff --git a/wasm-splats/src/models.rs b/wasm-splats/src/models.rs new file mode 100644 index 0000000..8a8eed3 --- /dev/null +++ b/wasm-splats/src/models.rs @@ -0,0 +1,44 @@ +//! Module encapsulating the data models exposed through WebAssembly. + +use wasm_bindgen::prelude::wasm_bindgen; + +/// A structure representing texture data. This is used to pass the texture data from generation in [`texture_gen`] to the JavaScript side. +#[wasm_bindgen] +pub struct TextureData { + /// The texture data. + data: Vec, + /// Width of the texture in pixels. + width: u32, + /// Height of the texture in pixels. + height: u32, +} + +#[wasm_bindgen] +impl TextureData { + /// Getter for the underlying texture data. Always returns a copy. + #[wasm_bindgen(getter)] + pub fn data(&self) -> Vec { + self.data.clone() + } + + /// Getter for the width of the texture in pixels. + #[wasm_bindgen(getter)] + pub fn width(&self) -> u32 { + self.width + } + + /// Getter for the height of the texture in pixels. + #[wasm_bindgen(getter)] + pub fn height(&self) -> u32 { + self.height + } + + /// Creates a new texture data object with the underlying data, width, and height. + pub fn new(data: Vec, width: u32, height: u32) -> Self { + TextureData { + data, + width, + height, + } + } +} diff --git a/wasm-splats/src/radix.rs b/wasm-splats/src/radix.rs new file mode 100644 index 0000000..b6d373f --- /dev/null +++ b/wasm-splats/src/radix.rs @@ -0,0 +1,77 @@ +//! Radix sort implementation for sorting Gaussian Splats. + +use js_sys::{Float32Array, Uint32Array}; +use wasm_bindgen::prelude::*; + +/// Sorts the Gaussian Splats by depth using a radix sort. +pub fn radix_sort_gaussians_indexes( + positions: &Float32Array, + model_view: &Float32Array, + count: usize, +) -> Result { + if positions.length() as usize != count * 3 { + return Err(JsValue::from_str("Invalid positions length")); + } + if model_view.length() != 16 { + return Err(JsValue::from_str("Invalid model_view length")); + } + + let positions_vec = positions.to_vec(); + let model_view_vec = model_view.to_vec(); + let mut depth_values = vec![0i32; count]; + let mut max_depth = f32::NEG_INFINITY; + let mut min_depth = f32::INFINITY; + + for i in 0..count { + let depth = positions_vec[i * 3] * model_view_vec[2] + + positions_vec[i * 3 + 1] * model_view_vec[6] + + positions_vec[i * 3 + 2] * model_view_vec[10]; + + let depth_int = (depth * 4096.0) as i32; + depth_values[i] = depth_int; + max_depth = max_depth.max(depth_int as f32); + min_depth = min_depth.min(depth_int as f32); + } + + let depth_offset = (-min_depth) as i32; + for depth in depth_values.iter_mut() { + *depth += depth_offset; + } + + let mut indices: Vec = (0..count as u32).collect(); + let mut temp_depths = vec![0i32; count]; + let mut temp_indices = vec![0u32; count]; + + for shift in (0..32).step_by(8) { + let mut counts = [0u32; 256]; + + for &depth in depth_values.iter() { + let byte = ((depth >> shift) & 0xFF) as usize; + counts[byte] += 1; + } + + let mut total = 0; + for count in counts.iter_mut() { + let current = *count; + *count = total; + total += current; + } + + for i in 0..count { + let byte = ((depth_values[i] >> shift) & 0xFF) as usize; + let pos = counts[byte] as usize; + counts[byte] += 1; + + temp_depths[pos] = depth_values[i]; + temp_indices[pos] = indices[i]; + } + + depth_values.copy_from_slice(&temp_depths); + indices.copy_from_slice(&temp_indices); + } + + let indices_array = Uint32Array::new_with_length(count as u32); + indices_array.copy_from(&indices); + + Ok(indices_array) +} diff --git a/wasm-splats/src/texture_gen.rs b/wasm-splats/src/texture_gen.rs new file mode 100644 index 0000000..a508458 --- /dev/null +++ b/wasm-splats/src/texture_gen.rs @@ -0,0 +1,137 @@ +//! Generates textures for use within the Gaussian Splat shaders in CesiumJS. + +use crate::models::TextureData; +use js_sys::{Float32Array, Uint8Array}; +use wasm_bindgen::prelude::*; + +/// Converts a 32-bit float to a 16-bit integer. +fn float_to_half(f: f32) -> i16 { + //Algorithm from ILM + //https://github.com/mitsuba-renderer/openexr/blob/master/IlmBase/Half/half.cpp + let f_int = f.to_bits() as i32; + let sign = (f_int >> 16) & 0x00008000; + let mut exp = ((f_int >> 23) & 0x000000ff) - (127 - 15); + let mut frac = f_int & 0x007fffff; + + if exp <= 0 { + if exp < -10 { + return sign as i16; + } + + frac |= 0x00800000; + + let t = 14 - exp; + let a = (1 << (t - 1)) - 1; + let b = (frac >> t) & 1; + + frac = (frac + a + b) >> t; + return (sign | frac) as i16; + } else if exp == 0xff - (127 - 15) { + if frac == 0 { + return (sign | 0x7c00) as i16; + } else { + frac >>= 13; + return (sign | 0x7c00 | frac | ((frac == 0) as i32)) as i16; + } + } + + frac = frac + 0x00000fff + ((frac >> 13) & 1); + + if frac & 0x00800000 != 0 { + frac = 0; + exp += 1; + } + + if exp > 30 { + //the original algo sets cpu overflow here + return (sign | 0x7c00) as i16; + } + (sign | (exp << 10) | (frac >> 13)) as i16 +} + +/// Generates a texture from the given attributes. +pub fn generate_texture_from_attrs( + positions: &Float32Array, + scales: &Float32Array, + rots: &Float32Array, + colors: &Uint8Array, + count: usize, +) -> Result { + let tex_width = 2048; + let tex_height = ((2 * count) as f32 / tex_width as f32).ceil() as u32; + let mut tex_data = vec![0u32; (tex_width * tex_height * 4) as usize]; + + let tex_data_c = unsafe { + std::slice::from_raw_parts_mut(tex_data.as_mut_ptr() as *mut u8, tex_data.len() * 4) + }; + + let tex_data_f = unsafe { + std::slice::from_raw_parts_mut(tex_data.as_mut_ptr() as *mut f32, tex_data.len()) + }; + + let rotv: Vec = rots.to_vec(); + let posv: Vec = positions.to_vec(); + let clrv: Vec = colors.to_vec(); + let sclv: Vec = scales.to_vec(); + + for i in 0..count { + tex_data_f[8 * i] = posv[3 * i]; + tex_data_f[8 * i + 1] = posv[3 * i + 1]; + tex_data_f[8 * i + 2] = posv[3 * i + 2]; + + //u8 offsets + tex_data_c[4 * (8 * i + 7)] = clrv[4 * i]; + tex_data_c[4 * (8 * i + 7) + 1] = clrv[4 * i + 1]; + tex_data_c[4 * (8 * i + 7) + 2] = clrv[4 * i + 2]; + tex_data_c[4 * (8 * i + 7) + 3] = clrv[4 * i + 3]; + + let r = rotv[4 * i + 3]; + let x = rotv[4 * i]; + let y = rotv[4 * i + 1]; + let z = rotv[4 * i + 2]; + let r_matrix = [ + 1.0 - 2.0 * (y * y + z * z), + 2.0 * (x * y + r * z), + 2.0 * (x * z - r * y), + 2.0 * (x * y - r * z), + 1.0 - 2.0 * (x * x + z * z), + 2.0 * (y * z + r * x), + 2.0 * (x * z + r * y), + 2.0 * (y * z - r * x), + 1.0 - 2.0 * (x * x + y * y), + ]; + + // S * R multiplication + let s0 = 3 * i; + let s1 = 3 * i + 1; + let s2 = 3 * i + 2; + + let m = [ + r_matrix[0] * sclv[s0], + r_matrix[1] * sclv[s0], + r_matrix[2] * sclv[s0], + r_matrix[3] * sclv[s1], + r_matrix[4] * sclv[s1], + r_matrix[5] * sclv[s1], + r_matrix[6] * sclv[s2], + r_matrix[7] * sclv[s2], + r_matrix[8] * sclv[s2], + ]; + let sigma = [ + m[0] * m[0] + m[3] * m[3] + m[6] * m[6], + m[0] * m[1] + m[3] * m[4] + m[6] * m[7], + m[0] * m[2] + m[3] * m[5] + m[6] * m[8], + m[1] * m[1] + m[4] * m[4] + m[7] * m[7], + m[1] * m[2] + m[4] * m[5] + m[7] * m[8], + m[2] * m[2] + m[5] * m[5] + m[8] * m[8], + ]; + tex_data[8 * i + 4] = (float_to_half(4.0 * sigma[0]) as u32 & 0xFFFF) + | ((float_to_half(4.0 * sigma[1]) as u32 & 0xFFFF) << 16); + tex_data[8 * i + 5] = (float_to_half(4.0 * sigma[2]) as u32 & 0xFFFF) + | ((float_to_half(4.0 * sigma[3]) as u32 & 0xFFFF) << 16); + tex_data[8 * i + 6] = (float_to_half(4.0 * sigma[4]) as u32 & 0xFFFF) + | ((float_to_half(4.0 * sigma[5]) as u32 & 0xFFFF) << 16); + } + + Ok(TextureData::new(tex_data, tex_width, tex_height)) +} diff --git a/wasm-splats/tests/common/data/generate-splat-tex-attrs-input-data.json b/wasm-splats/tests/common/data/generate-splat-tex-attrs-input-data.json new file mode 100644 index 0000000..b0046d8 --- /dev/null +++ b/wasm-splats/tests/common/data/generate-splat-tex-attrs-input-data.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82746fdfd8f87b9973bebaa55576c77d08485dcd824e9888ee2d97935d17ece1 +size 17729892 diff --git a/wasm-splats/tests/common/data/generate-splat-tex-attrs-output-data.json b/wasm-splats/tests/common/data/generate-splat-tex-attrs-output-data.json new file mode 100644 index 0000000..7d446e6 --- /dev/null +++ b/wasm-splats/tests/common/data/generate-splat-tex-attrs-output-data.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c8c06b792a3ae8e9ade2aa38b2104b33fb241093d515e6fd9feaf85621c0539 +size 6502585 diff --git a/wasm-splats/tests/common/data/radix-sort-input-data.json b/wasm-splats/tests/common/data/radix-sort-input-data.json new file mode 100644 index 0000000..221ad06 --- /dev/null +++ b/wasm-splats/tests/common/data/radix-sort-input-data.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8fd57e5615311bb76803ed0f7688d17cbac986bcaa98f58ce088334cbb73212e +size 5304026 diff --git a/wasm-splats/tests/common/data/radix-sort-output-data.json b/wasm-splats/tests/common/data/radix-sort-output-data.json new file mode 100644 index 0000000..2e99a41 --- /dev/null +++ b/wasm-splats/tests/common/data/radix-sort-output-data.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d61cd49a41f8dcec0a277a837e8d3e1967f1b36a038f5e8943257a347a3dfb7f +size 793805 diff --git a/wasm-splats/tests/common/data_reader.rs b/wasm-splats/tests/common/data_reader.rs new file mode 100644 index 0000000..232ee76 --- /dev/null +++ b/wasm-splats/tests/common/data_reader.rs @@ -0,0 +1,42 @@ +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +pub struct GenerateSplatTxtAttrsTestInput { + pub positions: Vec, + pub scales: Vec, + pub rotations: Vec, + pub colors: Vec, + pub count: usize, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct GenerateSplatTxtAttrsTestOutput { + pub texture_data: Vec, + pub width: u32, + pub height: u32, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct RadixSortTestInput { + pub position: Vec, + pub model_view: Vec, + pub idx_count: usize, + pub sort_type: String, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct RadixSortTestOutput { + pub sorted_idx: Vec, +} + +pub fn read_string_data(data: &str) -> Result> +where + T: for<'de> Deserialize<'de>, +{ + let u: T = serde_json::from_str(data)?; + + Ok(u) +} diff --git a/wasm-splats/tests/common/mod.rs b/wasm-splats/tests/common/mod.rs new file mode 100644 index 0000000..0c1e2f6 --- /dev/null +++ b/wasm-splats/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub mod data_reader; +pub mod test_data; +pub mod test_utils; diff --git a/wasm-splats/tests/common/test_data.rs b/wasm-splats/tests/common/test_data.rs new file mode 100644 index 0000000..4c5ac6b --- /dev/null +++ b/wasm-splats/tests/common/test_data.rs @@ -0,0 +1,131 @@ +use crate::common::data_reader::*; +use js_sys::{Float32Array, Uint8Array}; +use wasm_bindgen::JsValue; + +pub struct GenerateSplatTextureTestData { + in_positions: Float32Array, + in_scales: Float32Array, + in_rotations: Float32Array, + in_colors: Uint8Array, + in_count: usize, + out_texture_data: Vec, + out_width: u32, + out_height: u32, +} + +impl GenerateSplatTextureTestData { + pub fn new() -> Result { + let input_data: GenerateSplatTxtAttrsTestInput = read_string_data(include_str!( + "./data/generate-splat-tex-attrs-input-data.json" + )) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + let output_data: GenerateSplatTxtAttrsTestOutput = read_string_data(include_str!( + "./data/generate-splat-tex-attrs-output-data.json" + )) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + + let positions = Float32Array::new_with_length(input_data.positions.len() as u32); + positions.copy_from(&input_data.positions); + + let scales = Float32Array::new_with_length(input_data.scales.len() as u32); + scales.copy_from(&input_data.scales); + + let rotations = Float32Array::new_with_length(input_data.rotations.len() as u32); + rotations.copy_from(&input_data.rotations); + + let colors = Uint8Array::new_with_length(input_data.colors.len() as u32); + colors.copy_from(&input_data.colors); + + Ok(Self { + in_positions: positions, + in_scales: scales, + in_rotations: rotations, + in_colors: colors, + in_count: input_data.count, + out_texture_data: output_data.texture_data, + out_width: output_data.width, + out_height: output_data.height, + }) + } + + pub fn get_positions(&self) -> Float32Array { + self.in_positions.clone() + } + + pub fn get_scales(&self) -> Float32Array { + self.in_scales.clone() + } + + pub fn get_rotations(&self) -> Float32Array { + self.in_rotations.clone() + } + + pub fn get_colors(&self) -> Uint8Array { + self.in_colors.clone() + } + + pub fn get_count(&self) -> usize { + self.in_count + } + + pub fn get_texture_data(&self) -> Vec { + self.out_texture_data.clone() + } + + pub fn get_width(&self) -> u32 { + self.out_width + } + + pub fn get_height(&self) -> u32 { + self.out_height + } +} + +pub struct SortGaussianIndexesTestData { + in_positions: Float32Array, + in_model_view: Float32Array, + in_count: usize, + out_sorted_idx: Vec, +} + +impl SortGaussianIndexesTestData { + pub fn new() -> Result { + let input_data: RadixSortTestInput = + read_string_data(include_str!("./data/radix-sort-input-data.json")) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + let output_data: RadixSortTestOutput = + read_string_data(include_str!("./data/radix-sort-output-data.json")) + .map_err(|e| JsValue::from_str(&e.to_string()))?; + + let positions = Float32Array::new_with_length(input_data.position.len() as u32); + positions.copy_from(&input_data.position); + + let model_view = Float32Array::new_with_length(input_data.model_view.len() as u32); + model_view.copy_from(&input_data.model_view); + + let sorted_idx = output_data.sorted_idx; + + Ok(Self { + in_positions: positions, + in_model_view: model_view, + in_count: input_data.idx_count, + out_sorted_idx: sorted_idx, + }) + } + + pub fn get_positions(&self) -> Float32Array { + self.in_positions.clone() + } + + pub fn get_model_view(&self) -> Float32Array { + self.in_model_view.clone() + } + + pub fn get_count(&self) -> usize { + self.in_count + } + + pub fn get_sorted_idx(&self) -> Vec { + self.out_sorted_idx.clone() + } +} diff --git a/wasm-splats/tests/common/test_utils.rs b/wasm-splats/tests/common/test_utils.rs new file mode 100644 index 0000000..7ff5c62 --- /dev/null +++ b/wasm-splats/tests/common/test_utils.rs @@ -0,0 +1,14 @@ +use js_sys::Uint32Array; + +pub fn check_uint32array( + array: &Uint32Array, + expected: &[u32], +) -> Result<(), Box> { + let len = array.length(); + let mut actual = vec![0; len as usize]; + array.copy_to(&mut actual); + + assert_eq!(actual, expected); + + Ok(()) +} diff --git a/wasm-splats/tests/web.rs b/wasm-splats/tests/web.rs new file mode 100644 index 0000000..83a15fd --- /dev/null +++ b/wasm-splats/tests/web.rs @@ -0,0 +1,46 @@ +//! Test suite for the Web and headless browsers. + +#![cfg(target_arch = "wasm32")] +mod common; + +extern crate wasm_bindgen_test; +use crate::common::test_utils::check_uint32array; +use common::test_data; +use wasm_bindgen_test::*; +use wasm_splats::radix::radix_sort_gaussians_indexes; +use wasm_splats::texture_gen::generate_texture_from_attrs; + +wasm_bindgen_test_configure!(run_in_browser); + +#[wasm_bindgen_test] +fn test_generate_splat_texture_from_attrs() { + let test_data = test_data::GenerateSplatTextureTestData::new().unwrap(); + let positions = test_data.get_positions(); + let scales = test_data.get_scales(); + let rotations = test_data.get_rotations(); + let colors = test_data.get_colors(); + let count = test_data.get_count(); + let texture_data = test_data.get_texture_data(); + let width = test_data.get_width(); + let height = test_data.get_height(); + + let result = + generate_texture_from_attrs(&positions, &scales, &rotations, &colors, count).unwrap(); + + assert_eq!(result.data(), texture_data); + assert_eq!(result.width(), width); + assert_eq!(result.height(), height); +} + +#[wasm_bindgen_test] +fn test_radix_sort_gaussians_indexes() { + let test_data = test_data::SortGaussianIndexesTestData::new().unwrap(); + let positions = test_data.get_positions(); + let model_view = test_data.get_model_view(); + let count = test_data.get_count(); + let sorted_idx = test_data.get_sorted_idx(); + + let result = radix_sort_gaussians_indexes(&positions, &model_view, count).unwrap(); + + check_uint32array(&result, sorted_idx.as_ref()).unwrap(); +}