Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
raea origin/main
shaned3c399b4d522
diff --git a/Cargo.lock b/Cargo.lockindex 4ab47796..4f6b6a4c 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10530,6 +10530,7 @@ dependencies = ["num-traits","once_cell","petgraph",+ "pp-rs","rustc-hash 1.1.0","serde","spirv",@@ -13176,6 +13177,15 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"+[[package]]+name = "pp-rs"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb458bb7f6e250e6eb79d5026badc10a3ebb8f9a15d1fff0f13d17c71f4d6dee"+dependencies = [+ "unicode-xid",+]+[[package]]name = "ppv-lite86"version = "0.2.21"@@ -14403,6 +14413,7 @@ dependencies = ["raea-sys-splat","raea-sys-sprite","raea-sys-text3d",+ "raea-sys-three-shader","raea-sys-volume","raea-sys-wear","serde_json",@@ -14743,6 +14754,7 @@ dependencies = ["raea-core-shape","raea-sys-frame","raea-sys-material",+ "raea-sys-three-shader","serde","serde_json",]@@ -15363,6 +15375,18 @@ dependencies = ["serde_json",]+[[package]]+name = "raea-sys-three-shader"+version = "0.1.0"+dependencies = [+ "bevy",+ "image",+ "naga",+ "raea-sys-material",+ "raea-sys-sampler",+ "serde_json",+]+[[package]]name = "raea-sys-tone"version = "0.1.0"diff --git a/Cargo.toml b/Cargo.tomlindex 111e5a13..9a057e4f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -20,6 +20,7 @@ members = ["systems/sampler","systems/parity","systems/shader",+ "systems/three-shader","engine/bevy-calls","engine/bevy-adapters","engine/bevy-plugins",diff --git a/LICENSES/bevy_camera_controller-0.20.0/LICENSE-APACHE b/LICENSES/bevy_camera_controller-0.20.0/LICENSE-APACHEdeleted file mode 100644index d9a10c0d..00000000--- a/LICENSES/bevy_camera_controller-0.20.0/LICENSE-APACHE+++ /dev/null@@ -1,176 +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 CONDITIONSdiff --git a/LICENSES/bevy_camera_controller-0.20.0/LICENSE-MIT b/LICENSES/bevy_camera_controller-0.20.0/LICENSE-MITdeleted file mode 100644index 9cf10627..00000000--- a/LICENSES/bevy_camera_controller-0.20.0/LICENSE-MIT+++ /dev/null@@ -1,19 +0,0 @@-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/LICENSES/hound-3.5.1/license b/LICENSES/hound-3.5.1/licensedeleted file mode 100644index d6456956..00000000--- a/LICENSES/hound-3.5.1/license+++ /dev/null@@ -1,202 +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/LICENSES/lewton-0.10.2/LICENSE b/LICENSES/lewton-0.10.2/LICENSEdeleted file mode 100644index 4417b271..00000000--- a/LICENSES/lewton-0.10.2/LICENSE+++ /dev/null@@ -1,214 +0,0 @@-Copyright (c) 2016 est31 <[email protected]> and contributors--Licensed under MIT or Apache License 2.0,-at your option.--The full list of contributors can be obtained by looking-at the VCS log (originally, this crate was git versioned,-there you can do "git shortlog -sn" for this task).--MIT License--------------The MIT License (MIT)--Copyright (c) 2016 est31 <[email protected]> and contributors--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.----Apache License, version 2.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 CONDITIONSdiff --git a/LICENSES/ogg-0.8.0/LICENSE b/LICENSES/ogg-0.8.0/LICENSEdeleted file mode 100644index ec3a2f92..00000000--- a/LICENSES/ogg-0.8.0/LICENSE+++ /dev/null@@ -1,36 +0,0 @@-NOTE:-The full list of contributors can be obtained by looking-at the VCS log (originally, this crate was git versioned,-there you can do "git shortlog -sn" for this task).--License text--------------Copyright (c) 2016-2017 est31 <[email protected]> and contributors-Copyright (c) 2002-2015 Xiph.org Foundation--Redistribution and use in source and binary forms, with or without-modification, are permitted provided that the following conditions-are met:--- Redistributions of source code must retain the above copyright-notice, this list of conditions and the following disclaimer.--- Redistributions in binary form must reproduce the above copyright-notice, this list of conditions and the following disclaimer in the-documentation and/or other materials provided with the distribution.--- Neither the name of the Xiph.org Foundation nor the names of its-contributors may be used to endorse or promote products derived from-this software without specific prior written permission.--THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS-``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION-OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/bench/bevy-parity/Cargo.toml b/bench/bevy-parity/Cargo.tomlindex 27d6089e..c2420954 100644--- a/bench/bevy-parity/Cargo.toml+++ b/bench/bevy-parity/Cargo.toml@@ -10,7 +10,7 @@ description = "Bevy's own examples, built against raea's Bevy with the parity pr# the feature list engine/render's bevy has (its bevy-all: dfg_lut and bluenoise_texture too, which stock Bevy's defaults# leave out; without the DFG table rough surfaces at grazing angles take less ambient, many_cubes' box srgb 64 for 88), so the# examples build against the Bevy raea already compiled, and winit: the examples open a window (raea's renders don't), and bevy_scene: Bevy 0.20's examples write their scenes in BSN-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene"] }+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "default_font", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "jpeg", "tonemapping_luts", "ktx2", "zstd_rust", "smaa_luts", "experimental_pbr_pcss", "area_light_luts", "dfg_lut", "bluenoise_texture", "bevy_gilrs", "bevy_winit", "bevy_scene", "bevy_camera_controller", "free_camera", "pan_camera", "pan_orbit_camera", "bevy_gizmos", "bevy_gizmos_render", "bevy_state", "picking", "mesh_picking", "sprite_picking", "ui_picking", "hdr", "exr", "webp", "bevy_dev_tools", "bevy_ui_widgets", "bevy_feathers", "bevy_audio", "vorbis", "wav", "mp3", "morph_animation", "bevy_input_focus", "custom_cursor", "serialize", "reflect_functions"] }raea-sys-parity = { path = "../../systems/parity" }# Bevy's examples' own dependencies (bevy v0.20.0's dev-dependencies)argh = "0.1.12"diff --git a/bench/bevy-parity/examples.list b/bench/bevy-parity/examples.listindex 7f57930d..d8c8fb84 100644--- a/bench/bevy-parity/examples.list+++ b/bench/bevy-parity/examples.list@@ -4,3 +4,29 @@ stress_tests/many_cubes3d/3d_scenestress_tests/many_lightsstress_tests/many_foxes+animation/animated_mesh+shader/extended_material+3d/orthographic+3d/parenting+2d/mesh2d+2d/sprite+transforms/3d_rotation+2d/sprite_flipping+2d/move_sprite+2d/transparency_2d+transforms/translation+transforms/scale+3d/texture+shader/animate_shader+2d/sprite_sheet+3d/pbr+3d/animated_material+camera/pan_camera_controller+camera/camera_orbit+camera/projection_zoom+2d/sprite_animation+2d/sprite_tile+3d/vertex_colors+3d/spherical_area_lights+3d/fog_volumes+3d/bloom_3ddiff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsvindex 6141f6f2..b7270178 100644--- a/bench/bevy-parity/runs.tsv+++ b/bench/bevy-parity/runs.tsv@@ -3,3 +3,29 @@ stress_tests/many_cubes --benchmark --instance-count 10000 30,603d/3d_scene - 5,10stress_tests/many_lights - 30,60stress_tests/many_foxes --sync 30,60+animation/animated_mesh - 30,60+shader/extended_material - 30,60+3d/orthographic - 10+3d/parenting - 30,60+2d/mesh2d - 10+2d/sprite - 10+transforms/3d_rotation - 30,60+2d/sprite_flipping - 10+2d/move_sprite - 30,120+2d/transparency_2d - 10+transforms/translation - 60,180+transforms/scale - 60,300+3d/texture - 10+shader/animate_shader - 30,60+2d/sprite_sheet - 30,60+3d/pbr - 30,60+3d/animated_material - 30,60+camera/pan_camera_controller - 10+camera/camera_orbit - 10+camera/projection_zoom - 30+2d/sprite_animation - 12,30,60+2d/sprite_tile - 30,300+3d/vertex_colors - 10+3d/spherical_area_lights - 10+3d/fog_volumes - 10,60+3d/bloom_3d - 10,60diff --git a/core/scene/src/props.rs b/core/scene/src/props.rsindex 001c0e60..02a4393a 100644--- a/core/scene/src/props.rs+++ b/core/scene/src/props.rs@@ -88,6 +88,15 @@ pub fn light_power(kind: &str, p: &Map<String, Value>) -> f64 {num(p, field).unwrap_or_else(|| num(p, "intensity").unwrap_or(1.0) * k)}+/// A three.js-style emissive of intensity 1 in Bevy's units: what Bevy's default exposure (EV100 9.7) shows as 1.0,+/// 1.2 x 2^9.7 cd/m², so a 3d.tsx material's `emissiveIntensity` glows as three.js's does (docs/control.feature FC1f).+pub const EMISSIVE: f64 = 998.1;+/// A material's emissive power in Bevy's units: a Bevy StandardMaterial's `emissive_nits` as written (bevy3d+/// materials.tsx), else a 3d.tsx material's relative `emissiveIntensity` (1 by default) times EMISSIVE.+pub fn emissive_power(p: &Map<String, Value>) -> f64 {+ num(p, "emissive_nits").unwrap_or_else(|| n(p, "emissiveIntensity", 1.0) * EMISSIVE)+}+/// An <Environment> of intensity 1: the panorama's values (a Poly Haven HDR's sky is about 1) times this, in cd/m².pub const ENV: f64 = 1000.0;/// Bevy's default exposure (EV100): exposure 0; +1 is a stop brighter.diff --git a/core/scene/tests/emissive_power.rs b/core/scene/tests/emissive_power.rsnew file mode 100644index 00000000..aa36fc53--- /dev/null+++ b/core/scene/tests/emissive_power.rs@@ -0,0 +1,20 @@+//! A material's emissive power in Bevy's units (docs/control.feature FC1f): a Bevy StandardMaterial's `emissive_nits`+//! as written, else a 3d.tsx material's relative emissiveIntensity times EMISSIVE, so it glows as three.js's does.++use raea_core_scene::{EMISSIVE, emissive_power};+use serde_json::json;++#[test]+fn bevy_nits_as_written() {+ // bloom_3d's white spheres: LinearRgba 1000, whatever relative intensity rides along+ assert_eq!(emissive_power(json!({ "emissive_nits": 1000.0, "emissiveIntensity": 4.0 }).as_object().unwrap()), 1000.0);+ assert_eq!(emissive_power(json!({ "emissive_nits": 0.0 }).as_object().unwrap()), 0.0);+}++#[test]+fn relative_intensity_is_three_js_brightness() {+ assert_eq!(emissive_power(json!({ "emissiveIntensity": 4.0 }).as_object().unwrap()), 4.0 * EMISSIVE);+ assert_eq!(emissive_power(json!({}).as_object().unwrap()), EMISSIVE);+ // Bevy's default exposure shows EMISSIVE cd/m² as 1.0: 1.2 x 2^9.7+ assert!((EMISSIVE - 1.2 * 2f64.powf(9.7)).abs() < 0.1);+}diff --git a/core/shape/src/lib.rs b/core/shape/src/lib.rsindex 99e1b25f..afe53612 100644--- a/core/shape/src/lib.rs+++ b/core/shape/src/lib.rs@@ -29,7 +29,7 @@ mod glyphs;mod mesh;mod parse;mod sphere;-pub use sphere::{SphereOf, sphere_of};+pub use sphere::{SphereOf, cuboid_of, sphere_of};pub use mesh::{export, from_mesh, read_glb, read_obj, to_mesh};diff --git a/core/shape/src/sphere.rs b/core/shape/src/sphere.rsindex 998fb6e8..01caf8f0 100644--- a/core/shape/src/sphere.rs+++ b/core/shape/src/sphere.rs@@ -1,5 +1,5 @@//! A shape expression that is a sphere alone, which a renderer draws as its own sphere mesh (raea-render: Bevy's-//! Sphere::mesh(), as a Bevy Mesh3d's is) rather than as Manifold's.+//! Sphere::mesh(), as a Bevy Mesh3d's is) rather than as Manifold's; a cuboid alone likewise (Bevy's Cuboid mesh)./// A sphere alone, as its expression asks for it#[derive(Debug, PartialEq)]@@ -27,10 +27,29 @@ pub fn sphere_of(expr: &str) -> Option<SphereOf> {}}+/// The cuboid `expr` is, `box(w, h, d)` alone with each side above 0 (a 0 side is a plane: Manifold's), as its full+/// size: drawn as Bevy's Cuboid mesh, with its normals and texture coordinates, as a Bevy Mesh3d's is+pub fn cuboid_of(expr: &str) -> Option<[f32; 3]> {+ let inner = expr.trim().strip_prefix("box(")?.strip_suffix(')')?;+ let n: Vec<f32> = inner.split(',').map(|s| s.trim().parse().ok()).collect::<Option<_>>()?;+ match n.as_slice() {+ &[w, h, d] if w > 0.0 && h > 0.0 && d > 0.0 => Some([w, h, d]),+ _ => None,+ }+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn a_box_alone_is_a_cuboid_and_a_plane_or_anything_more_is_not() {+ assert_eq!(cuboid_of(" box(1, 2, 0.5) "), Some([1.0, 2.0, 0.5]));+ for e in ["box(1, 1, 0)", "box(1, 1)", "box(1, 1, 1, 0.1)", "move(box(1, 1, 1), 0, 1, 0)", "sphere(1)"] {+ assert_eq!(cuboid_of(e), None, "{e}");+ }+ }+#[test]fn a_sphere_alone_is_read_and_anything_more_is_not() {assert_eq!(sphere_of("sphere(2)"), Some(SphereOf::Ico { radius: 2.0, subdivisions: 5 }));diff --git a/docs/r3f.feature b/docs/r3f.featureindex c18d2b31..37ae036f 100644--- a/docs/r3f.feature+++ b/docs/r3f.feature@@ -105,28 +105,37 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composiWhen tools/parity.sh renders each with `raea render` (native.tsx) and with three.js in headless Chrome(test/parity/page.tsx, which tools/serve.ts builds and serves itself, with the wasm tools/shape-wasm.sh builds),and compares the two by SSIM- Then every case is at least 0.92 (measured 11-06)+ Then every case is at least 0.92 (measured 11-07)| case | what | SSIM |- | in-basic | a spinning box (useFrame), PBR and clearcoat, shadows, a point light | 0.9911 |- | in-lights | spot, hemisphere and area lights, fog, Lambert and flat Phong | 0.9792 |- | in-things | InstancedMesh, multi-material, edge lines, a sprite | 0.9908 |- | in-catch | a ShadowMaterial floor: only the box's shadow over the background | 0.9965 |+ | in-basic | a spinning box (useFrame), PBR and clearcoat, shadows, a point light | 0.9917 |+ | in-lights | spot, hemisphere and area lights, fog, Lambert and flat Phong | 0.9795 |+ | in-things | InstancedMesh, multi-material, edge lines, a sprite | 0.9917 |+ | in-catch | a ShadowMaterial floor: only the box's shadow over the background | 0.9966 |+ | in-lettra | lettra's MSDF text (TSL) and a TSL gradient on its clock | 0.9994 |+ | in-lettrafx | lettra's wipe and scramble (an attribute, a uniform array) | 0.9992 |+ | in-shader | ShaderMaterials: a rippled sphere, points sized by an attribute | 0.9989 |+ | in-post | <EffectComposer>: HueSaturation, Vignette, ToneMapping ACES | 0.9451 |+ | in-drei | drei's Text, Environment preset, ContactShadows, Float, useGLTF | 0.9932 |+ | in-approx | matcap, normal, Phong specular, dashes, clipping, hemisphere, probe | 0.9848 || out-basic | a raea scene, ACES, a moving box | 0.9958 |- | out-tony | the same scene in raea's default tone mapping, TonyMcMapface | 0.9960 |- | out-lights | spot and area lights, fog, Text3D (a solid) | 0.9627 |- | out-bloom | <Bloom intensity={2}> | 0.9444 |- | out-grade | <Grade> saturation, contrast, vignette | 0.9748 |- | out-lens | <LensDistortion k1={0.15}> | 0.9933 |+ | out-tony | the same scene in raea's default tone mapping, TonyMcMapface | 0.9961 |+ | out-lights | spot and area lights, fog, Text3D (a solid) | 0.9633 |+ | out-bloom | <Bloom intensity={2}> | 0.9295 |+ | out-grade | <Grade> saturation, contrast, vignette | 0.9738 |+ | out-lens | <LensDistortion k1={0.15}> | 0.9922 || out-catch | <Mesh shadow="catch">, three's ShadowMaterial | 0.9972 |- | out-entities| <Entities>: a raea/ecs world, a ship and its gun turned by a system | 0.9971 |- | src-basic | out-basic exported as R3F source, drawn by a plain <Canvas> | 0.9957 |- | src-tony | out-tony exported (Tony through raea-effects.ts) | 0.9960 |- | src-lights | out-lights exported as R3F source (Text3D as its triangles) | 0.9628 |- | src-bloom | out-bloom exported (raea-effects.ts) | 0.9444 |- | src-grade | out-grade exported | 0.9748 |- | src-lens | out-lens exported | 0.9933 |+ | out-entities| <Entities>: a raea/ecs world, a ship and its gun turned by a system | 0.9972 |+ | src-basic | out-basic exported as R3F source, drawn by a plain <Canvas> | 0.9958 |+ | src-tony | out-tony exported (Tony through raea-effects.ts) | 0.9961 |+ | src-lights | out-lights exported as R3F source (Text3D as its triangles) | 0.9633 |+ | src-bloom | out-bloom exported (raea-effects.ts) | 0.9295 |+ | src-grade | out-grade exported | 0.9738 |+ | src-lens | out-lens exported | 0.9922 || src-catch | out-catch exported | 0.9972 |- | src-entities| out-entities exported | 0.9971 |+ | src-entities| out-entities exported | 0.9972 |+ And three r181 rewrote UnrealBloomPass (mrdoob/three.js#31528): three/effects.ts puts r180's kernels, composite+ and blend back on three's pass, so out-bloom holds to the bloom raea's matches (three's frame equals r180's at+ SSIM 0.999998)And three's ACES scales its input by 1/0.6 where Bevy's doesn't: the host's exposure takes 0.6 under ACES, andan R3F canvas's ACES reads as 0.74 stops more (measured: out-lights 0.927 to 0.963, in-lights 0.927 to 0.979)@@ -170,3 +179,71 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composiAnd measuring it fixed raea-web: a model's file is fetched rather than looked for on disk (runtime/scene3dmodel.rs), a black page background is the 3D's clear rather than a cover over it (rgb(0, 0, 0) was read assee-through, here and in Scene3d), and a layered <Canvas3D>'s empty slot isn't drawn++ Rule: What R3F apps are made of draws in raea++ Goal, 2026-11-06: "finish the r3f": custom GLSL shaders, @react-three/postprocessing, the materials and lights that+ were approximate, and a drei-heavy scene, each read by <R3F> and held to three.js by parity (R3F8).++ @done+ Scenario: R3F11. three.js shaders run in raea's engine+ Given a ShaderMaterial or RawShaderMaterial in an <R3F> scene (written by hand, or drei's shaderMaterial())+ When raea reads it (src/input/shader.ts)+ Then its GLSL goes as three would compile it: the #includes expanded from three's ShaderChunk, its defines in+ front, the #ifdef blocks its defines settle decided, its uniforms as this frame's numbers and its textures as+ pictures (a picture made in code as a PNG data: URL)+ And raea-sys-three-shader translates it with naga and runs it with three's built-ins (the matrices, the camera,+ a colour and uvs on every vertex, up to 4 attributes of its own, 64 vec4 uniforms, 4 textures)+ And a shader that includes three's tone mapping is tone-mapped by Bevy's, one that doesn't is shown as three's+ canvas shows it+ And in-shader (a sphere rippled by a uniform set in useFrame, points sized by their own attribute): SSIM 0.9989++ @done+ Scenario: R3F12. @react-three/postprocessing's <EffectComposer> as raea's frame effects+ Given an <EffectComposer> in an <R3F> scene+ When raea reads its effects (src/input/post.ts)+ Then each becomes the raea effect that does the same thing: Bloom; Vignette, ChromaticAberration,+ HueSaturation and BrightnessContrast in one Grade; ToneMapping; DepthOfField and Bokeh; SMAA and FXAA; SSAO+ and N8AO; Pixelation; LensDistortion+ And one raea has nothing for (noise, glitch, god rays ...) is named once and left out (kinds.ts's EFFECTS+ decides every effect postprocessing exports, tested)+ And a composer's frame is tone-mapped only by its ToneMapping effect, as in three+ And in-post (HueSaturation, Vignette, ToneMapping ACES): SSIM 0.945++ @done+ Scenario: R3F13. A drei-heavy scene: <Text>, <Environment preset>, <ContactShadows>, <Float>, useGLTF+ Given test/parity's in-drei case: a knot loaded by useGLTF in a <Float>, troika's <Text> in Inter, drei's+ <ContactShadows> under it and <Environment preset="city"> lighting it+ When raea renders it+ Then three's loaders read their files where a native render has no fetch: FileLoader by the `asset.read` native+ call (a file, or an http(s) URL through raea's cache), so a glTF is parsed in JS; a DataTextureLoader (HDR,+ EXR) hands back the cached file, which raea's engine loads as <Environment src>+ And what an app draws into a render target is done on the CPU where it's a pass raea knows (src/input/targets.ts):+ a MeshDepthMaterial override from an orthographic camera and three's 9-tap blurs, which are drei's+ <ContactShadows>; anything else drawn into a target is named and left empty+ And a mesh whose transform mirrors it is drawn with its triangles rewound (three flips the front face; Bevy+ culls as wound)+ And raea's bundler gives a composition troika-three-text as sdk/r3f/src/input/troika.ts (engine/bundle's+ STAND_INS): its Text holds troika's settings and draws nothing, and src/input/text.ts reads any troika Text as+ raea's <RichText> (size, the face's family from its name table, weight, colour, anchors, maxWidth)+ And a root whose parts mounted late (they suspended) starts again from frame 0 once its loads are cached, and+ Math.random is seeded per root, so drei's <Float> and three's uuids are the same however often a seek restarts+ it (render equals play)+ And in-drei: SSIM 0.993 (Float at speed 0 in the case: three's page draws its phase at random)++ @done+ Scenario: R3F14. The approximate kinds made exact or closer+ Given test/parity's in-approx case+ When raea renders it+ Then MeshMatcapMaterial and MeshNormalMaterial run three's own ShaderLib programs (R3F11), so they look as three+ draws them+ And Phong's specular colour is its F0 (three's Blinn-Phong): Bevy's reflectance and specular tint+ And a LineDashedMaterial is cut into its dashes by the line's distances (computeLineDistances), as three's shader+ cuts it+ And clipping planes (a material's with localClippingEnabled, the renderer's, a ClippingGroup's) cut the mesh's+ triangles, so what three discards isn't drawn (src/input/clip.ts; clipIntersection keeps what is inside any one)+ And drei's MeshTransmissionMaterial draws with Bevy's transmission (its own uniform's, as three's is 0 under it)+ And a LightProbe is an ambient light of its constant band and a light along its linear band (exact for surfaces+ facing that light or sideways, as the hemisphere light is), and its constant band is scaled as three's+ irradiance is (0.886, where 0.282 made it a third as bright)+ And in-approx: SSIM 0.9848 (Phong's F0 is held at Bevy's highest, 0.16, so its orange highlight glints less)diff --git a/engine/bundle/src/edit.rs b/engine/bundle/src/edit.rsindex af4593a7..c245e729 100644--- a/engine/bundle/src/edit.rs+++ b/engine/bundle/src/edit.rs@@ -59,6 +59,12 @@ async fn resolve_from(ctx: &PluginContext, spec: &str, dir: &Path) -> anyhow::Re}}+/// Packages a composition's bundle takes from raea in place of their own, by the stand-in module under raea's home:+/// ones that need what a native render's JS hasn't (a DOM, web workers) to do what raea's engine does itself.+/// troika-three-text (drei's <Text>) lays text out in a worker onto a canvas; raea's R3F reader draws its Text as+/// raea's own text (sdk/r3f/src/input/troika.ts, text.ts; docs/r3f.feature R3F13).+const STAND_INS: &[(&str, &str)] = &[("troika-three-text", "sdk/r3f/src/input/troika.ts")];+impl Plugin for EditResolve {fn name(&self) -> Cow<'static, str> {Cow::Borrowed("raea:edit")@@ -72,6 +78,15 @@ impl Plugin for EditResolve {let e = &self.0;let spec = args.specifier;let Some(imp) = args.importer else { return Ok(None) };+ // raea's home is sdk/react/js's grandparent's parent+ if let Some((_, own)) = STAND_INS.iter().find(|(p, _)| *p == spec) {+ if let Some(home) = e.js.ancestors().nth(3) {+ let f = home.join(own);+ if f.is_file() {+ return Ok(Some(HookResolveIdOutput::from_id(f.to_string_lossy().as_ref())));+ }+ }+ }let bare = spec.starts_with('@') || spec.starts_with(|c: char| c.is_ascii_lowercase());if !bare || spec.starts_with("@raea/") || spec.contains(':') {return Ok(None);diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.tomlindex 1a4b47d4..033587f8 100644--- a/engine/render/Cargo.toml+++ b/engine/render/Cargo.toml@@ -39,6 +39,8 @@ raea-sys-compute = { path = "../../systems/compute" }raea-sys-sampler = { path = "../../systems/sampler" }raea-sys-parity = { path = "../../systems/parity" }raea-sys-shader = { path = "../../systems/shader" }+# three.js's shaders: a ShaderMaterial's GLSL and a node material's WGSL (docs/r3f.feature R3F11)+raea-sys-three-shader = { path = "../../systems/three-shader" }raea-sys-post = { path = "../../systems/post" }raea-sys-fog = { path = "../../systems/fog" }raea-sys-fog-half = { path = "../../systems/fog-half" }@@ -88,3 +90,8 @@ network = ["native"]bevy-all = ["bevy/bevy_gilrs", "bevy/gamepad", "bevy/area_light_luts", "bevy/experimental_pbr_pcss", "bevy/dfg_lut", "bevy/smaa_luts", "bevy/tonemapping_luts", "bevy/bluenoise_texture", "bevy/bevy_gizmos", "bevy/bevy_gizmos_render", "bevy/bevy_dev_tools", "bevy/debug", "bevy/bevy_ui_debug", "bevy/file_watcher", "bevy/embedded_watcher", "bevy/asset_processor", "bevy/png", "bevy/jpeg", "bevy/ktx2", "bevy/zstd_rust", "bevy/basis-universal", "bevy/exr", "bevy/hdr", "bevy/webp", "bevy/dds", "bevy/tga", "bevy/bmp", "bevy/gif", "bevy/ico", "bevy/qoi", "bevy/pnm", "bevy/tiff", "bevy/compressed_image_saver", "bevy/picking", "bevy/bevy_picking", "bevy/mesh_picking", "bevy/sprite_picking", "bevy/ui_picking", "bevy/meshlet", "bevy/meshlet_processor", "bevy/bevy_solari", "bevy/bevy_animation", "bevy/gltf_animation", "bevy/morph", "bevy/morph_animation", "bevy/bevy_gltf", "bevy/bevy_sprite", "bevy/bevy_sprite_render", "bevy/2d_bevy_render", "bevy/3d_bevy_render", "bevy/ui_bevy_render", "bevy/bevy_ui_widgets", "bevy/bevy_feathers", "bevy/custom_cursor", "bevy/bevy_input_focus", "bevy/bevy_camera_controller", "bevy/free_camera", "bevy/pan_camera", "bevy/bevy_text", "bevy/system_font_discovery", "bevy/scene", "bevy/bevy_state", "bevy/serialize", "bevy/reflect_functions", "bevy/reflect_documentation", "bevy/sysinfo_plugin", "bevy/bevy_clipboard", "bevy/system_clipboard", "bevy/clipboard_image", "bevy/ghost_nodes", "bevy/bevy_settings", "bevy/shader_format_spirv", "bevy/bevy_debug_stepping", "bevy/bevy_world_serialization", "bevy/bevy_audio", "bevy/mp3", "bevy/flac", "bevy/vorbis", "bevy/wav", "bevy/aac", "bevy/mp4", "bevy/http", "bevy/https", "bevy/web_asset_cache", "bevy/bevy_curve", "bevy/complex_script_segmentation", "bevy/compressed_image_saver_universal", "bevy/pan_orbit_camera", "bevy/pan_orbit_gizmo", "bevy/render_dev_tools"]# per-system spans as a chrome trace (RUST_LOG=info, trace-*.json in the working directory)trace = ["bevy/trace", "bevy/trace_chrome"]++[package.metadata.cargo-shear]+# raea-core-shape is unused since a mesh row's shape went to raea_sys_material::mesh::shape_mesh. Its line sits beside+# an unlanded branch's (scene-loop: raea-sys-procmat), so it goes, with this table, once that branch lands+ignored = ["raea-core-shape"]diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rsindex 0af82ef0..ea54b004 100644--- a/engine/render/src/engine/raea_plugins.rs+++ b/engine/render/src/engine/raea_plugins.rs@@ -66,6 +66,7 @@ raea_plugin! {ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";ToonPlugin: super::toon::install, "The toon surface and its ink outline's materials (toon.rs).";ShaderExtPlugin: super::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";+ ThreeShaderPlugin: raea_sys_three_shader::install, "three.js's shaders: a ShaderMaterial's GLSL (naga) and a node material's WGSL, with three's built-ins (raea-sys-three-shader).";FramePassPlugin: raea_sys_framepass::install, "Full-screen passes written in TypeScript (raea-sys-framepass).";ComputePlugin: raea_sys_compute::install, "Compute shaders written in TypeScript, run before the cameras draw (raea-sys-compute).";LensPlugin: super::lens::install, "The camera's lens (Fisheye, LensDistortion), after tone mapping (lens.rs).";diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rsindex 64916e17..3143ffec 100644--- a/engine/render/src/engine/spawn.rs+++ b/engine/render/src/engine/spawn.rs@@ -243,46 +243,29 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],let uvs = scene3d::has_maps(vals) || grid.is_some();let tangents = vals.get("normal_map").is_some_and(V::truthy);// made once per shape and what it's given (share.rs): equal parts hold one Mesh, so Bevy batches them- let mesh = scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}"), || {- // a sphere on its own is Bevy's Sphere::mesh() (its icosphere, or its UV sphere), as a Bevy Mesh3d's is- let ball = raea_core_shape::sphere_of(&expr).map(|s| match s {- raea_core_shape::SphereOf::Ico { radius, subdivisions } => Sphere::new(radius).mesh().ico(subdivisions).map_err(|e| format!("mesh {}: {e}", t.id)),- raea_core_shape::SphereOf::Uv { radius, sectors, stacks } => Ok(Sphere::new(radius).mesh().uv(sectors, stacks)),- });- if let Some(mut m) = ball.transpose()? {- if tangents {- m.generate_tangents().map_err(|e| format!("mesh {}: normalMap: its tangents: {e}", t.id))?;- }- return Ok(m);- }- // or its own vertex buffers (<BufferMesh>: "buffer:{positions, indices, normals, uvs}")- let (tris, own_uvs, own_colors) = match expr.strip_prefix("buffer:") {- Some(b) => {- let c = scene3d::buffer_colors(b).map_err(|e| format!("mesh {}: {e}", t.id))?;- let (t, u) = scene3d::buffer_tris(b).map_err(|e| format!("mesh {}: {e}", t.id))?;- (std::sync::Arc::new(t), u, c)- }- None => (raea_core_shape::cached(&expr).map_err(|e| format!("mesh {}: {e}", t.id))?, None, None),- };- let mut m = Mesh::new(bevy::render::render_resource::PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());- m.insert_attribute(Mesh::ATTRIBUTE_POSITION, tris.positions.clone());- m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, tris.normals.clone());- // a <BufferMesh colors>: per-vertex colours, which StandardMaterial multiplies its colour by- if let Some(c) = own_colors {- m.insert_attribute(Mesh::ATTRIBUTE_COLOR, c);- }- if own_uvs.is_some() || uvs {- m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| scene3d::box_uvs(&tris.positions, &tris.normals)));- if tangents {- m.generate_tangents().map_err(|e| format!("mesh {}: normalMap: its tangents: {e}", t.id))?;- }+ let mesh = scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}"), || raea_sys_material::mesh::shape_mesh(&t.id, &expr, uvs, tangents))?;+ // a three.js shader (raea-sys-three-shader, docs/r3f.feature R3F11): its own material, and the mesh given+ // what it reads; its pictures' files found as a model's are (the edit's folder, its media)+ let three = match vals.get("three") {+ Some(V::S(spec)) => raea_sys_three_shader::of_row(world, &t.id, spec, |w, x| match x.as_str() {+ Some(p) if !p.starts_with("render:") => plugins::image(w, &serde_json::Value::String(resolve_src(inserted, p, dir)?.to_string_lossy().into_owned())),+ _ => plugins::image(w, x),+ }),+ _ => None,+ };+ let mesh = match &three {+ Some((_, own)) => {+ let m = raea_sys_three_shader::fitted(world.resource::<Assets<Mesh>>().get(&mesh), &t.id, expr.strip_prefix("buffer:"), own)?;+ scene3d::shared_mesh(world, &format!("{expr}\0{uvs}\0{tangents}\0three:{}", own.join(",")), || Ok(m))?}- Ok(m)- })?;+ None => mesh,+ };// the surface (emissive, opacity, unlit, clearcoat, a picture map...) and transform: scene3dlet mat = scene3d::material(world, t, inserted, dir)?;// rot_x/y/z in radians and scale (or scale_x/y/z), as sync_meshes moves every mesh frame by frame- if vals.get("shadow_only").is_some_and(V::truthy) {+ if let Some((m, _)) = three {+ grid::put(world, e, mesh, m, vals);+ } else if vals.get("shadow_only").is_some_and(V::truthy) {// `shadow: "only"`: in the shadow maps, never drawn (shadow_only.rs)grid::put(world, e, mesh, shadow_only::ShadowOnlyMaterial::default(), vals);} else if vals.get("shadow_catch").is_some_and(V::truthy) {@@ -331,7 +314,7 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],let src = match vals.get("src") { Some(V::S(s)) => s.clone(), _ => return Err(format!("sprite {}: needs src (a picture)", t.id)) };let pic = scene3d::panel_picture(&src, inserted, dir).map_err(|e| format!("sprite {}: {e}", t.id))?;let (pw, ph) = pic.dimensions();- let image = world.resource_mut::<Assets<Image>>().add(scene3d::panel_image(pic));+ let image = world.resource_mut::<Assets<Image>>().add(sprite2d::sprite_image(pw, ph, pic.into_raw()));sprite2d::spawn_sprite(world, e, t, image, UVec2::new(pw, ph));}"shape2d" => sprite2d::spawn_shape(world, e, t),diff --git a/engine/rune/src/macapp.rs b/engine/rune/src/macapp.rsindex d8b795a0..7f60aea4 100644--- a/engine/rune/src/macapp.rs+++ b/engine/rune/src/macapp.rs@@ -68,6 +68,10 @@ pub fn make(src: &str, name: &str, size: (u32, u32), out: &Path, fonts: &[raea_r);std::fs::write(contents.join("Info.plist"), plist).map_err(|e| e.to_string())?;+ // off the Mac the same folder runs as is (`bundled` finds its script), and codesign is the Mac's, as for a web app+ if !cfg!(target_os = "macos") {+ return Ok(vec!["not signed: codesign is the Mac's".into()]);+ }run(Command::new("codesign").args(["--force", "--deep", "--sign", "-"]).arg(out))?;Ok(vec!["signed ad hoc: it opens on the Mac that made it".into()])}diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rsindex eac15d7f..9884ffcd 100644--- a/runtime/calls/src/lib.rs+++ b/runtime/calls/src/lib.rs@@ -39,6 +39,19 @@ pub static CLI: std::sync::OnceLock<fn(&[String]) -> i32> = std::sync::OnceLock:/// The edit's folder for asset.load (useAsset), set as a render or a play opens it.pub static ASSET_DIR: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);+/// An asset's file: an http(s) URL fetched into raea's cache, an absolute path, else one found as a model's src is+/// (staticFile's /media/x: the edit's folder's media/, then its assets/)+fn asset_path(p: &str) -> R<std::path::PathBuf> {+ if p.starts_with("http://") || p.starts_with("https://") {+ return raea_io_net::cache::fetch(p);+ }+ let dir = ASSET_DIR.lock().unwrap().clone();+ Ok(match dir {+ Some(d) if !std::path::Path::new(p).exists() => raea_core_scene::media_path(&d, &format!("/{}", p.trim_start_matches('/'))),+ _ => std::path::PathBuf::from(p),+ })+}+/// A composition opened live from `dir` (its bundle `js`): its assets (useAsset) found from its folder, as a render/// finds them; and a game that says lines has Pocket TTS loaded on its worker now, before the/// clock starts.@@ -244,12 +257,7 @@ pub fn register() {// an asset loaded now, before the frame that names it uses it, as the Engine loads a handle's (S2b useAsset)raea_native::register("asset.load", "{ path: string }", "{ path: string; bytes: number; width?: number; height?: number }", "an asset by its path (absolute, or from the edit's folder), loaded now: the file found and read, a picture's size; an error when it isn't there (S2b useAsset)", |v| {let p = s(v, "path")?;- let rel = p.trim_start_matches('/');- let dir = ASSET_DIR.lock().unwrap().clone();- let path = match dir {- Some(d) if !std::path::Path::new(&p).exists() => d.join(rel),- _ => std::path::PathBuf::from(p),- };+ let path = asset_path(&p)?;let bytes = std::fs::metadata(&path).map_err(|e| format!("asset {p}: {e}"))?.len();let mut out = json!({"path": path.to_string_lossy(), "bytes": bytes});if let Ok((w, h)) = image::image_dimensions(&path) {@@ -258,6 +266,14 @@ pub fn register() {}Ok(out)});+ // a file's bytes read now, for a loader that parses them in JS (three's FileLoader under R3F: useGLTF)+ raea_native::register("asset.read", "{ path: string }", "{ path: string; base64: string }", "a file's bytes (absolute, from the edit's folder, or an http(s) URL through raea's cache), read now, as base64 (R3F's loaders, docs/r3f.feature R3F13)", |v| {+ use base64::Engine as _;+ let p = s(v, "path")?;+ let path = asset_path(&p)?;+ let bytes = std::fs::read(&path).map_err(|e| format!("asset {p}: {e}"))?;+ Ok(json!({"path": path.to_string_lossy(), "base64": base64::engine::general_purpose::STANDARD.encode(bytes)}))+ });for (name, args, answer, doc) in calls.iter().copied().chain(ecs::CALLS.iter().copied()) {let n = name.to_string();raea_native::register(name, args, answer, doc, move |v| call(&n, v));diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rsindex b13aa9dd..4ae24aec 100644--- a/runtime/export/src/fed.rs+++ b/runtime/export/src/fed.rs@@ -76,6 +76,10 @@ pub(crate) fn scene_frames(js: &Path, dir: &Path, upto: i64, whole: bool) -> R<Olet scene = scene_of(app.world_mut());let clear = scene_clear(app.world_mut());out.push((f, scene, clear));+ // the mount is the first frame's: tools/bevy-parity charges the frames after it, as Bevy's setup isn't in its frame time+ if f == 0 {+ raea_runtime_react::startup_mark("the 3D's rows: frame 0 stepped");+ }Ok(())})?;Ok(out)diff --git a/runtime/look/src/camera.rs b/runtime/look/src/camera.rsindex 7aca9bdc..6b648df3 100644--- a/runtime/look/src/camera.rs+++ b/runtime/look/src/camera.rs@@ -69,7 +69,15 @@ pub fn camera(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>)}// an <Environment>: each frame's panorama (an index into env_srcs, -1 for none), its light, turn and sky, keyed, so// a cut from a hall to a street changes the light on that frame- let envs: Vec<Option<&Item>> = all.iter().map(|its| its.iter().find(|i| i.kind == "environment")).collect();+ // Bevy's EnvironmentMapLight with its own prefiltered maps (<EnvironmentMapLight>: its diffuse and specular+ // cubemap files, as the first frame has them), in place of a panorama raea filters+ if let Some(m) = all.iter().flatten().find(|i| i.kind == "environment" && i.props.contains_key("diffuse_map")) {+ for k in ["diffuse_map", "specular_map"] {+ row.insert(format!("envmap_{k}"), V::S(m.props.get(k).and_then(Value::as_str).unwrap_or_default().to_string()));+ }+ row.insert("envmap_k".into(), V::N(n(&m.props, "intensity", 1.0)));+ }+ let envs: Vec<Option<&Item>> = all.iter().map(|its| its.iter().find(|i| i.kind == "environment" && !i.props.contains_key("diffuse_map"))).collect();if envs.iter().any(Option::is_some) {let mut srcs: Vec<String> = Vec::new();let idx: Vec<f64> = envs.iter().map(|e| match e.and_then(|e| e.props.get("src")).and_then(Value::as_str) {diff --git a/runtime/look/src/lib.rs b/runtime/look/src/lib.rsindex 9b6a00ed..2b92373c 100644--- a/runtime/look/src/lib.rs+++ b/runtime/look/src/lib.rs@@ -82,6 +82,10 @@ pub fn surface_spec(p: &Map<String, Value>) -> Value {o.insert(col.into(), Value::from(v));}}+ // a new glow in Bevy's units (core/scene emissive_power); an intensity alone scales the glTF's own emissive, as written+ if p.contains_key("emissive_nits") || hex(p.get("emissive")).is_some() {+ o.insert("emissive_k".into(), Value::from(emissive_power(p)));+ }for (prop, col) in [("map", "map"), ("normalMap", "normal_map"), ("roughnessMap", "rough_map"), ("metalnessMap", "metal_map"), ("metallicRoughnessMap", "mr_map"), ("aoMap", "ao_map"), ("emissiveMap", "emissive_map"), ("depthMap", "depth_map")] {if let Some(src) = p.get(prop).and_then(Value::as_str) {o.insert(col.into(), Value::String(src_path(src)));@@ -419,6 +423,20 @@ pub fn material_fields(p: &mut Program, id: &str, its: &[Item]) {keyed(p, "component", Some(id), "m", each.iter().map(|(f, v)| (*f, v)));}+/// A three.js shader's uniforms and time (a <ThreeShaderMaterial>'s, docs/r3f.feature R3F11), sent as keyed+/// `three:uniforms` rows from each frame they change, which raea-sys-three-shader's `patch` writes into its slots.+pub fn three_uniforms(p: &mut Program, id: &str, its: &[Item]) {+ let each: Vec<(usize, Value)> = its.iter().enumerate().filter_map(|(f, it)| {+ let m = it.material.as_ref().filter(|m| &*m.kind == "ThreeShaderMaterial")?;+ let v = serde_json::json!({ "uniforms": m.props.get("uniforms").cloned().unwrap_or(Value::Null), "time": m.props.get("time").cloned().unwrap_or(Value::Null) });+ Some((f, serde_json::json!({ "type": "three:uniforms", "value": v })))+ }).collect();+ if each.is_empty() {+ return;+ }+ keyed(p, "component", Some(id), "u", each.iter().map(|(f, v)| (*f, v)));+}+/// A sampled value as reflect's JSON takes it: `#rrggbb` (or `#rrggbbaa`) as a Color's Srgba, the rest as it isfn bevy_value(v: &Value) -> Value {let Some(h) = v.as_str().and_then(|s| s.strip_prefix('#')).filter(|h| (h.len() == 6 || h.len() == 8) && h.chars().all(|c| c.is_ascii_hexdigit())) else { return v.clone() };diff --git a/runtime/plugins/Cargo.toml b/runtime/plugins/Cargo.tomlindex 229aa8d4..c544ac53 100644--- a/runtime/plugins/Cargo.toml+++ b/runtime/plugins/Cargo.toml@@ -9,6 +9,8 @@ description = "Bevy plugins inside raea's engine: compiled in by a crate that re[dependencies]raea-sys-frame = { path = "../../systems/frame" }raea-sys-material = { path = "../../systems/material" }+# three.js's shaders (docs/r3f.feature R3F11): a `three:uniforms` row patches a part's uniforms+raea-sys-three-shader = { path = "../../systems/three-shader" }raea-core-program = { path = "../../core/program" }bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "bevy_state"] }serde = "1"diff --git a/runtime/plugins/src/reflect.rs b/runtime/plugins/src/reflect.rsindex 0236e571..b446ae13 100644--- a/runtime/plugins/src/reflect.rs+++ b/runtime/plugins/src/reflect.rs@@ -65,6 +65,10 @@ pub fn insert_reflect(world: &mut World, e: Entity, path: &str, json: &Value) ->if let Some(material) = path.strip_prefix("material:") {return patch_material(world, e, material, json);}+ // a three shader's uniforms this frame (raea-sys-three-shader, docs/r3f.feature R3F11)+ if path == "three:uniforms" {+ return raea_sys_three_shader::patch(world, e, json);+ }let registry = world.resource::<AppTypeRegistry>().clone();let reg = registry.read();let r = registration(®, path)?;diff --git a/runtime/react/src/scene/holders.rs b/runtime/react/src/scene/holders.rsindex 9473343f..91e176f7 100644--- a/runtime/react/src/scene/holders.rs+++ b/runtime/react/src/scene/holders.rs@@ -107,13 +107,12 @@ fn fresh_holders(world: &mut World) -> (Vec<Entity>, Option<Entity>) {(c.holders.clone(), c.slot)}-/// The 3D's clear colour for a render or play: transparent (#00000000) for a layered Canvas3D, whose background is the-/// page under it; else the nearest holder's background.+/// The 3D's clear colour for a render or play: a layered Canvas3D's `clearColor` (its slot's data-clear, which its parts+/// blend over in linear light as Bevy's over its ClearColor), else transparent, the page under it; else the nearest+/// holder's background.pub fn scene_clear(world: &mut World) -> Option<String> {- if scene_slot(world).is_some() {- return Some("#00000000".into());- }- clear_of(&holders_of(world))+ let Some(s) = fresh_holders(world).1 else { return clear_of(&holders_of(world)) };+ Some(world.get::<ReactProps>(s).and_then(|p| p.0.get("data-clear")?.as_str().map(str::to_string)).unwrap_or_else(|| "#00000000".into()))}/// The 3D's clear colour: the nearest holder's background, as a render takes it.diff --git a/runtime/scene/src/fast.rs b/runtime/scene/src/fast.rsindex 11b6fa33..9b597d9c 100644--- a/runtime/scene/src/fast.rs+++ b/runtime/scene/src/fast.rs@@ -164,7 +164,7 @@ impl LiveScene {put("rough", n(m, "roughness", 0.5));put("metal", n(m, "metalness", 0.0));if m.get("emissive").and_then(Value::as_str).and_then(hex_cow).is_some_and(|e| e != "#000000") {- put("emissive_k", n(m, "emissiveIntensity", 1.0));+ put("emissive_k", emissive_power(m));}if m.get("transparent") == Some(&Value::Bool(true)) || num(m, "opacity").is_some_and(|o| o < 1.0) {put("opacity", n(m, "opacity", 1.0));diff --git a/runtime/scene/src/models.rs b/runtime/scene/src/models.rsindex 53c3ef3e..6223b577 100644--- a/runtime/scene/src/models.rs+++ b/runtime/scene/src/models.rs@@ -272,9 +272,10 @@ pub(crate) fn fogs_rows(tr: &Tracks, p: &mut Program) {}}let first = &its[0].props;- for (prop, col) in [("absorption", "absorption"), ("scattering", "scattering"), ("anisotropy", "anisotropy"), ("falloff", "falloff")] {- if let Some(x) = num(first, prop) {- row.insert(col.into(), V::N(x));+ // and its density texture (Bevy's density_texture, a .ktx2 3D image's path: 3d/fog_volumes' bunny)+ for (prop, col) in [("absorption", "absorption"), ("scattering", "scattering"), ("anisotropy", "anisotropy"), ("falloff", "falloff"), ("density_texture", "density_tex")] {+ if let Some(x) = first.get(prop).and_then(|v| v.as_f64().map(V::N).or_else(|| v.as_str().map(|s| V::S(s.into())))) {+ row.insert(col.into(), x);}}placement(p, &mut row, &id, &its);diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rsindex 316ff595..9cc34440 100644--- a/runtime/scene/src/parts.rs+++ b/runtime/scene/src/parts.rs@@ -92,9 +92,10 @@ pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {}}}- if kind != "directional" {- if let Some(d) = num(first, "distance").filter(|d| *d > 0.0) {- row.insert("range".into(), V::N(d));+ // a bulb's or spot's reach, and its size (Bevy's radius: a spherical area light's highlight, 3d/spherical_area_lights)+ for (prop, col) in [("distance", "range"), ("radius", "radius")].iter().filter(|_| kind != "directional") {+ if let Some(d) = num(first, prop).filter(|d| *d > 0.0) {+ row.insert(col.to_string(), V::N(d));}}// a rectangle of light: its face's size@@ -144,7 +145,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {column(p, &mut row, &id, "metal", &mats.iter().map(|m| n(m, "metalness", metal0)).collect::<Vec<_>>());if let Some(e) = hex(m0.get("emissive")).filter(|e| e != "#000000") {row.insert("emissive".into(), V::S(e));- column(p, &mut row, &id, "emissive_k", &mats.iter().map(|m| n(m, "emissiveIntensity", 1.0)).collect::<Vec<_>>());+ column(p, &mut row, &id, "emissive_k", &mats.iter().map(|m| emissive_power(m)).collect::<Vec<_>>());}let see_through = mats.iter().any(|m| m.get("transparent") == Some(&Value::Bool(true)) || num(m, "opacity").is_some_and(|o| o < 1.0));if see_through {@@ -194,6 +195,12 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {if let Some(sh) = m0.get("shader").filter(|v| v.is_object()) {row.insert("shader".into(), V::S(sh.to_string()));}+ // a three.js shader (<ThreeShaderMaterial>, docs/r3f.feature R3F11): its spec from the first frame, unlit in its+ // colour where it can't run; its uniforms keyed frame by frame (three_uniforms)+ if its[0].material.as_ref().is_some_and(|m| &*m.kind == "ThreeShaderMaterial") {+ row.insert("three".into(), V::S(Value::Object((**m0).clone()).to_string()));+ row.insert("unlit".into(), V::N(1.0));+ }if its[0].material.as_ref().is_some_and(|m| &*m.kind == "MeshToonMaterial") {// a toon surface: its bands, rim, highlight and outline from the first frame; what animates, keyedrow.insert("toon".into(), V::S(toon_spec(m0, false).to_string()));@@ -248,6 +255,7 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {p.spawns.push(("mesh".into(), vec![row]));components(p, &id, &its);material_fields(p, &id, &its);+ three_uniforms(p, &id, &its);}}@@ -283,13 +291,13 @@ pub(crate) fn texts_rows(tr: &Tracks, names: &[String], p: &mut Program) {if let Some(w) = num(first, "maxWidth").filter(|w| *w > 0.0) {row.insert("max_width".into(), V::N(r6(w)));}- for (prop, col) in [("roughness", "rough"), ("metalness", "metal"), ("emissiveIntensity", "emissive_k")] {+ for (prop, col) in [("roughness", "rough"), ("metalness", "metal")] {if let Some(v) = num(first, prop) {row.insert(col.into(), V::N(r6(v)));}}if let Some(e) = hex(first.get("emissive")).filter(|e| e != "#000000") {- row.insert("emissive".into(), V::S(e));+ row.extend([("emissive".into(), V::S(e)), ("emissive_k".into(), V::N(r6(emissive_power(first))))]);}for (prop, col) in [("unlit", "unlit"), ("castShadow", "shadow"), ("receiveShadow", "receive")] {if let Some(Value::Bool(b)) = first.get(prop) {diff --git a/runtime/scene/src/sprite2d.rs b/runtime/scene/src/sprite2d.rsindex a4ec91a4..33fb0f17 100644--- a/runtime/scene/src/sprite2d.rs+++ b/runtime/scene/src/sprite2d.rs@@ -31,13 +31,14 @@ pub(super) fn sprites(tracks: &[Track], p: &mut Program) {row.insert("id".into(), V::S(id.clone()));let first = &its[0].props;row.insert("src".into(), V::S(src_path(first.get("src").and_then(Value::as_str).unwrap_or(""))));- for (prop, col) in [("width", "w"), ("height", "h")] {- if let Some(v) = num(first, prop) {- row.insert(col.into(), V::N(v));+ // keyed: a size that changes shows more or fewer tiles of a tiled one (Bevy's custom_size, 2d/sprite_tile)+ for (prop, col) in [("width", "w"), ("height", "h"), ("tileStretch", "tile_stretch")] {+ if num(first, prop).is_some() {+ column(p, &mut row, &id, col, &its.iter().map(|i| n(&i.props, prop, 1.0)).collect::<Vec<_>>());}}sheet(p, &mut row, &id, &its);- for (prop, col) in [("flipX", "flip_x"), ("flipY", "flip_y")] {+ for (prop, col) in [("flipX", "flip_x"), ("flipY", "flip_y"), ("tileX", "tile_x"), ("tileY", "tile_y")] {if first.get(prop) == Some(&Value::Bool(true)) {row.insert(col.into(), V::N(1.0));}diff --git a/runtime/scene3d/src/light.rs b/runtime/scene3d/src/light.rsindex ee9678af..3fae9f18 100644--- a/runtime/scene3d/src/light.rs+++ b/runtime/scene3d/src/light.rs@@ -135,6 +135,16 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {pub fn fog_volume(world: &mut World, e: Entity, id: &str, vals: &BTreeMap<String, V>) {let mut fv = bevy::light::FogVolume::default();fog_values(&mut fv, vals);+ // a density texture (a 3D .ktx2), loaded as Bevy's AssetServer loads one; one that won't load leaves the box even+ if let Some(V::S(p)) = vals.get("density_tex") {+ let img = std::fs::read(p).map_err(|e| e.to_string()).and_then(|b| {+ Image::from_buffer(&b, bevy::image::ImageType::Extension("ktx2"), bevy::image::CompressedImageFormats::NONE, true, bevy::image::ImageSampler::Default, bevy::asset::RenderAssetUsages::RENDER_WORLD).map_err(|e| e.to_string())+ });+ match img {+ Ok(img) => fv.density_texture = Some(world.resource_mut::<Assets<Image>>().add(img)),+ Err(err) => eprintln!("raea: FogVolume density_texture {p}: {err}"),+ }+ }world.entity_mut(e).insert((fv, fog_transform(vals), FogRank(id.to_string()), FogThinning(num(vals, "falloff", 0.0).max(0.0))));}diff --git a/sdk/r3f/README.md b/sdk/r3f/README.mdindex c8bed120..37986636 100644--- a/sdk/r3f/README.md+++ b/sdk/r3f/README.md@@ -16,7 +16,62 @@ export const Edit = () => ();```-In a project, three and @react-three/fiber are its own: `raea add [email protected] @react-three/[email protected]`.+In a project, three and @react-three/fiber are its own: `raea add [email protected] @react-three/[email protected]`.++TSL node materials (`three/webgpu`: a `MeshBasicNodeMaterial` with a `colorNode`, or any library built on TSL) run in+raea too. three's own `WGSLNodeBuilder` compiles the material's graph to WGSL, and raea's engine runs that WGSL+(`src/input/tsl.ts`). The camera and transform come from raea, and every uniform takes this frame's value: TSL's `time`+is R3F's clock, so a uniform you change in `useFrame` moves with it. A node material with no graph of its own (a plain+`MeshStandardNodeMaterial`) is drawn as its classic material. A graph raea can't carry is named in a warning and drawn+flat. That covers a graph needing more than 4 textures or 64 vec4 uniforms, a storage buffer, a render target, or a+vertex attribute other than position, normal, uv and color.++**lettra** (MSDF text on TSL, [lettra.dev](https://lettra.dev/docs)) works in `<R3F>` as plain text.+`test/parity` has cases for it: `in-lettra` for plain text and `in-lettrafx` for `wipe` and `scramble`. Those two read+a vertex attribute of their own (`layoutX`) and a uniform array, which raea carries. In a plain+R3F `<Canvas>`, lettra needs three's `WebGPURenderer` (`gl={async (p) => { const r = new WebGPURenderer(p); await+r.init(); return r; }}`). Inside `<R3F>` it doesn't, because raea draws. Set the atlas's settings (`flipY: false`,+`NoColorSpace`) when you create its texture, as `configureFontTexture` does. Call `configureFontTexture` itself in the+loader's `onLoad`, or WebGPURenderer uploads the picture before it has loaded.++Baking an atlas on an Apple Silicon Mac (`lettra bake`, lettra 0.3.0 with msdf-bmfont-xml 2.7) needs two fixes, both+in lettra's dependencies:+- The `msdfgen` msdf-bmfont-xml ships for macOS is x86-only ("Bad CPU type in executable"). Install the arm64 build with+ `brew install msdfgen`, then link it over the bundled one:+ `ln -sf /opt/homebrew/bin/msdfgen node_modules/msdf-bmfont-xml/bin/darwin/msdfgen.osx`.+- The nested `maxrects-packer` 2.7.4 (`node_modules/msdf-bmfont-xml/node_modules/maxrects-packer`, an ES module) fails+ with "MaxRectsPacker is not a constructor". Move it aside so the top-level CommonJS copy is used:+ `bun add -d [email protected]`, then remove or rename the nested folder.+- Then bake with `node`: `node node_modules/lettra/dist/cli.mjs bake Font.ttf --charset "..." --out fonts/Font`.+ Bake a static font, or the kerning is dropped. `test/parity/fonts` holds Inter, under the OFL (`Inter-OFL.txt`).++**three.js shaders.** A `ShaderMaterial` or `RawShaderMaterial` (written by hand, or drei's `shaderMaterial()`) runs in+raea's engine as written. Its GLSL is expanded from three's chunks, translated by naga and run with three's built-ins+(`src/input/shader.ts`, docs/r3f.feature R3F11). A shader can have up to 4 vertex attributes of its own, 64 vec4+uniforms and 4 textures. `MeshMatcapMaterial` and `MeshNormalMaterial` run three's own programs this way.++**Effects.** `@react-three/postprocessing`'s `<EffectComposer>` is read as raea's frame effects (`src/input/post.ts`,+R3F12): Bloom, Vignette, ChromaticAberration, HueSaturation, BrightnessContrast, ToneMapping, DepthOfField, Bokeh,+SMAA, FXAA, SSAO, N8AO, Pixelation and LensDistortion. An effect raea has nothing for (noise, glitch, god rays) is+named in a warning and left out.++**drei.** A typical drei scene draws (`test/parity`'s `in-drei`, R3F13):+- `<Text>`: raea's bundler swaps troika-three-text for a stand-in, and raea lays the words out as its own `<RichText>`.+ The face is found by its family name.+- `<Environment preset>` and `useGLTF`: three's loaders read files and URLs through raea's cache.+- `<ContactShadows>`: its depth and blur passes are done on the CPU.+- `<Float>`: `Math.random` is seeded for each `<R3F>`, so a render equals its play.++**What still differs.**+- `onBeforeCompile` patches aren't run, so drei's `MeshWobbleMaterial` and `MeshDistortMaterial` draw as their base+ material. `MeshTransmissionMaterial` draws with Bevy's transmission, without its chromatic aberration or distortion.+- A render target an app fills itself is drawn empty, unless it is one of the passes `src/input/targets.ts` knows.+- `<Text>` outlines, strokes and `curveRadius` are left out.+- Phong's highlight has GGX's shape, not Blinn-Phong's, and a specular colour brighter than Bevy's highest F0 (0.16)+ glints less.+- HemisphereLight and LightProbe are exact only for surfaces facing their light or side-on.++`src/input/kinds.ts` lists every three.js class and what raea draws for it.**raea in R3F.** Draw a raea composition inside any R3F `<Canvas>`:diff --git a/sdk/r3f/bun.lock b/sdk/r3f/bun.lockindex 2110b896..528a2753 100644--- a/sdk/r3f/bun.lock+++ b/sdk/r3f/bun.lock@@ -5,14 +5,18 @@"": {"name": "@raea/r3f","devDependencies": {+ "@react-three/drei": "10.7.9","@react-three/fiber": "9.8.2",+ "@react-three/postprocessing": "3.2.2","@types/bun": "1.4.3","@types/react-dom": "19.2.0",- "@types/three": "0.180.0",+ "@types/three": "0.185.0",+ "lettra": "0.3.0",+ "postprocessing": "6.39.5","react": "file:../raea/node_modules/react","react-dom": "file:../raea/node_modules/react-dom","scheduler": "file:../raea/node_modules/scheduler",- "three": "0.180.0",+ "three": "0.185.0",},"peerDependencies": {"@react-three/fiber": ">=9.0.0",@@ -25,14 +29,26 @@"@dimforge/rapier3d-compat": ["@dimforge/[email protected]", "", {}, "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="],+ "@mediapipe/tasks-vision": ["@mediapipe/[email protected]", "", {}, "sha512-CZWV/q6TTe8ta61cZXjfnnHsfWIdFhms03M9T7Cnd5y2mdpylJM0rF1qRq+wsQVRMLz1OYPVEBU9ph2Bx8cxrg=="],++ "@monogrid/gainmap-js": ["@monogrid/[email protected]", "", { "dependencies": { "promise-worker-transferable": "^1.0.4" }, "peerDependencies": { "three": ">= 0.159.0" } }, "sha512-YjgdH65wZ9lQnzkVWerrR9FJR0JYhn3ahV7DJqDZVtIvR/kWv7XzFbMSIOFS/47+nWbZ5zFTRxsFhq0OX//SuA=="],++ "@react-three/drei": ["@react-three/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.26.0", "@mediapipe/tasks-vision": "0.10.17", "@monogrid/gainmap-js": "^3.0.6", "@use-gesture/react": "^10.3.1", "camera-controls": "^3.1.0", "cross-env": "^7.0.3", "detect-gpu": "^5.0.56", "glsl-noise": "^0.0.0", "hls.js": "^1.5.17", "maath": "^0.10.8", "meshline": "^3.3.1", "stats-gl": "^2.2.8", "stats.js": "^0.17.0", "suspend-react": "^0.1.3", "three-mesh-bvh": "^0.8.3", "three-stdlib": "^2.35.6", "troika-three-text": "^0.52.4", "tunnel-rat": "^0.1.2", "use-sync-external-store": "^1.4.0", "utility-types": "^3.11.0", "zustand": "^5.0.1" }, "peerDependencies": { "@react-three/fiber": "^9.0.0", "react": "^19", "react-dom": "^19", "three": ">=0.159" }, "optionalPeers": ["react-dom"] }, "sha512-wP4Y6o58KFi+hT1zCfjJarRtPCT6WW/lo53WMiA/aCORuUvBzW916XsCtadnIB1KB+3IQNcDU5JeVh/gYb8MYw=="],+"@react-three/fiber": ["@react-three/[email protected]", "", { "dependencies": { "@babel/runtime": "^7.17.8", "@types/webxr": "*", "base64-js": "^1.5.1", "buffer": "^6.0.3", "its-fine": "^2.1.1", "react-use-measure": "^2.1.7", "scheduler": "^0.28.0", "suspend-react": "^0.1.3", "use-sync-external-store": "^1.4.0", "zustand": "^5.0.3" }, "peerDependencies": { "expo": ">=43.0", "expo-asset": ">=8.4", "expo-file-system": ">=11.0", "expo-gl": ">=11.0", "react": ">=19 <19.4", "react-dom": ">=19 <19.4", "react-native": ">=0.78", "three": ">=0.156" }, "optionalPeers": ["expo", "expo-asset", "expo-file-system", "expo-gl", "react-dom", "react-native"] }, "sha512-6s0ejw0bT1myQ/aLLugcil8/zBmNnnHw/AISWF1yfDLOxfX3yYaTS+0IkpJITEnm/SSMLtxje6CJDt0i5Wu1Sw=="],+ "@react-three/postprocessing": ["@react-three/[email protected]", "", { "dependencies": { "maath": "^0.10.8", "n8ao": "^2.0.0" }, "peerDependencies": { "@react-three/fiber": ">=9.7.0", "postprocessing": "^6.36.0", "react": "^19.0.0", "three": ">= 0.156.0" } }, "sha512-y/ePU8gytOCAjQMy7At9gZFr/Xi/YGSHlNEir3fCY88+FoBpzL4RsTpzyKnrGshcD8wmJ5ppI5kWzz0dtNPkWQ=="],+"@tweenjs/tween.js": ["@tweenjs/[email protected]", "", {}, "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="],"@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.3" } }, "sha512-N67Pqy8JXbAY/j0tNraS3V5mubGvc6rrrNDmDCtZLlFzccbUJPDb0tvgUBC5q4m8ybkP93Jcn1QB+RYQ6PvBhw=="],+ "@types/draco3d": ["@types/[email protected]", "", {}, "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw=="],+"@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],+ "@types/offscreencanvas": ["@types/[email protected]", "", {}, "sha512-ieXiYmgSRXUDeOntE1InxjWyvEelZGP63M+cGuquuRLuIKKT1osnkXjxev9B7d1nXSug5vpunx+gNlbVxMlC9A=="],+"@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],"@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-brtBs0MnE9SMx7px208g39lRmC5uHZs96caOJfTjFcYSLHNamvaSMfJNagChVNkup2SdtOxKX1FDBkRSJe1ZAg=="],@@ -41,27 +57,69 @@"@types/stats.js": ["@types/[email protected]", "", {}, "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="],- "@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": "*", "@webgpu/types": "*", "fflate": "~0.8.2", "meshoptimizer": "~0.22.0" } }, "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg=="],+ "@types/three": ["@types/[email protected]", "", { "dependencies": { "@dimforge/rapier3d-compat": "~0.12.0", "@tweenjs/tween.js": "~23.1.3", "@types/stats.js": "*", "@types/webxr": ">=0.5.17", "fflate": "~0.8.2", "meshoptimizer": "~1.1.1" } }, "sha512-O2Uy8Cj4Nonr8dWUUbifMdPe8B0Mq7EdOHb89S4+kjUw/KhbjTZrUuYlrQ1bpUKG+EP9QJnN7qNxbHGlGoLHMA=="],"@types/webxr": ["@types/[email protected]", "", {}, "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="],- "@webgpu/types": ["@webgpu/[email protected]", "", {}, "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA=="],+ "@use-gesture/core": ["@use-gesture/[email protected]", "", {}, "sha512-WcINiDt8WjqBdUXye25anHiNxPc0VOrlT8F6LLkU6cycrOGUDyY/yyFmsg3k8i5OLvv25llc0QC45GhR/C8llw=="],++ "@use-gesture/react": ["@use-gesture/[email protected]", "", { "dependencies": { "@use-gesture/core": "10.3.1" }, "peerDependencies": { "react": ">= 16.8.0" } }, "sha512-Yy19y6O2GJq8f7CHf7L0nxL8bf4PZCPaVOCgJrusOeFHY1LvHgYXnmnXg6N5iwAnbgbZCDjo60SiM6IPJi9C5g=="],"base64-js": ["[email protected]", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],+ "bidi-js": ["[email protected]", "", { "dependencies": { "require-from-string": "^2.0.2" } }, "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg=="],+"buffer": ["[email protected]", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.2.1" } }, "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA=="],"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-tinRJNGOmUN+tEAsn2y2e942n9JHRHR42iUYzDH75NmhJqVBokGSQkkfSFdNWwsANIdrK6ACH9t01M452YyTwg=="],+ "camera-controls": ["[email protected]", "", { "peerDependencies": { "three": ">=0.126.1" } }, "sha512-xkxfpG2ECZ6Ww5/9+kf4mfg1VEYAoe9aDSY+IwF0UEs7qEzwy0aVRfs2grImIECs/PoBtWFrh7RXsQkwG922JA=="],++ "cross-env": ["[email protected]", "", { "dependencies": { "cross-spawn": "^7.0.1" }, "bin": { "cross-env": "src/bin/cross-env.js", "cross-env-shell": "src/bin/cross-env-shell.js" } }, "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw=="],++ "cross-spawn": ["[email protected]", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],+"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],+ "detect-gpu": ["[email protected]", "", { "dependencies": { "webgl-constants": "^1.1.1" } }, "sha512-bqerEP1Ese6nt3rFkwPnGbsUF9a4q+gMmpTVVOEzoCyeCc+y7/RvJnQZJx1JwhgQI5Ntg0Kgat8Uu7XpBqnz1w=="],++ "draco3d": ["[email protected]", "", {}, "sha512-MqC0eAfW5gPATGY3GABIyFWpHwdDGAyewTdek5R/e+mhI9ZDUMKb2mTDkTMUW0+Vm7an+ThEMUop3+svS72Uug=="],+"fflate": ["[email protected]", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="],+ "glsl-noise": ["[email protected]", "", {}, "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w=="],++ "hls.js": ["[email protected]", "", {}, "sha512-3GlxGdPvT2YHvQYOt+yOzT/DEior/qJVNIylHA77kgeoBTdQQqi70GwefNEUmHQeNGyjC8U62+bruqW/Tpm+tg=="],+"ieee754": ["[email protected]", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],+ "immediate": ["[email protected]", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],++ "is-promise": ["[email protected]", "", {}, "sha512-+lP4/6lKUBfQjZ2pdxThZvLUAafmZb8OAxFb8XXtiQmS35INgr85hdOGoEs124ez1FCnZJt6jau/T+alh58QFQ=="],++ "isexe": ["[email protected]", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],+"its-fine": ["[email protected]", "", { "dependencies": { "@types/react-reconciler": "^0.28.9" }, "peerDependencies": { "react": "^19.0.0" } }, "sha512-C5ZoVkeqSt0Aje0tzESO+iT/EQpNFNL39GkP7mCACtoZUFD6GcyerFCr6kp0ZtiII4W9HoYkY48Soy5xE/uHKw=="],- "meshoptimizer": ["[email protected]", "", {}, "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg=="],+ "lettra": ["[email protected]", "", { "peerDependencies": { "msdf-bmfont-xml": "^2.7.0", "three": ">=0.185.0" }, "optionalPeers": ["msdf-bmfont-xml", "three"], "bin": { "lettra": "dist/cli.js" } }, "sha512-nlAPTOWbUPXtWAzW26Wv7j+1pXoKTgJao8OyUXZCsSprM6DCnS99O9vVApmubX2hn2csm43PdLnRqWmQB1YpUQ=="],++ "lie": ["[email protected]", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],++ "maath": ["[email protected]", "", { "peerDependencies": { "@types/three": ">=0.134.0", "three": ">=0.134.0" } }, "sha512-tRvbDF0Pgqz+9XUa4jjfgAQ8/aPKmQdWXilFu2tMy4GWj4NOsx99HlULO4IeREfbO3a0sA145DZYyvXPkybm0g=="],++ "meshline": ["[email protected]", "", { "peerDependencies": { "three": ">=0.137" } }, "sha512-/TQj+JdZkeSUOl5Mk2J7eLcYTLiQm2IDzmlSvYm7ov15anEcDJ92GHqqazxTSreeNgfnYu24kiEvvv0WlbCdFQ=="],++ "meshoptimizer": ["[email protected]", "", {}, "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g=="],++ "n8ao": ["[email protected]", "", { "peerDependencies": { "postprocessing": ">=6.30.0", "three": ">=0.137" } }, "sha512-MoP1QKUdj4/3cKEnhFl917t0eQwWGER1l43ckz5mNOPyYWGRDGQbVoTOQz/VBvy01in6QVNG+AL6Xxx5AjZBYA=="],++ "path-key": ["[email protected]", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],++ "postprocessing": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.168.0 < 0.187.0" } }, "sha512-YmH+t74J2X1lwYjKzK/tgs9C9kqWWPB9JwZiDF5mEf4BdCEAmEFbO8lXBA7NM0/j4g+x6FgD/Tt5/kT7ogbEDA=="],++ "potpack": ["[email protected]", "", {}, "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ=="],++ "promise-worker-transferable": ["[email protected]", "", { "dependencies": { "is-promise": "^2.1.0", "lie": "^3.0.2" } }, "sha512-bN+0ehEnrXfxV2ZQvU2PetO0n4gqBD4ulq3MI1WOPLgr7/Mg9yRQkX5+0v1vagr74ZTsl7XtzlaYDo2EuCeYJw=="],"react": ["react@file:../raea/node_modules/react", {}],@@ -69,16 +127,46 @@"react-use-measure": ["[email protected]", "", { "peerDependencies": { "react": ">=16.13", "react-dom": ">=16.13" }, "optionalPeers": ["react-dom"] }, "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg=="],+ "require-from-string": ["[email protected]", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],+"scheduler": ["scheduler@file:../raea/node_modules/scheduler", {}],+ "shebang-command": ["[email protected]", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],++ "shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],++ "stats-gl": ["[email protected]", "", { "dependencies": { "@types/three": "*", "three": "^0.170.0" } }, "sha512-g5O9B0hm9CvnM36+v7SFl39T7hmAlv541tU81ME8YeSb3i1CIP5/QdDeSB3A0la0bKNHpxpwxOVRo2wFTYEosQ=="],++ "stats.js": ["[email protected]", "", {}, "sha512-hNKz8phvYLPEcRkeG1rsGmV5ChMjKDAWU7/OJJdDErPBNChQXxCo3WZurGpnWc6gZhAzEPFad1aVgyOANH1sMw=="],+"suspend-react": ["[email protected]", "", { "peerDependencies": { "react": ">=17.0" } }, "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ=="],- "three": ["[email protected]", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],+ "three": ["[email protected]", "", {}, "sha512-+yRrcRO2iZa8uzvNNl0d7cL4huhgKgBvVJ0njcTe8xFqZ6DMAFZdCKDP91SEAuj25bNAj7k1QQdf+srZywVK6w=="],++ "three-mesh-bvh": ["[email protected]", "", { "peerDependencies": { "three": ">= 0.159.0" } }, "sha512-4G5lBaF+g2auKX3P0yqx+MJC6oVt6sB5k+CchS6Ob0qvH0YIhuUk1eYr7ktsIpY+albCqE80/FVQGV190PmiAg=="],++ "three-stdlib": ["[email protected]", "", { "dependencies": { "@types/draco3d": "^1.4.0", "@types/offscreencanvas": "^2019.6.4", "@types/webxr": "^0.5.2", "draco3d": "^1.4.1", "fflate": "^0.6.9", "potpack": "^1.0.1" }, "peerDependencies": { "three": ">=0.128.0" } }, "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg=="],++ "troika-three-text": ["[email protected]", "", { "dependencies": { "bidi-js": "^1.0.2", "troika-three-utils": "^0.52.5", "troika-worker-utils": "^0.52.0", "webgl-sdf-generator": "1.1.1" }, "peerDependencies": { "three": ">=0.125.0" } }, "sha512-Ry3jRhic9pzcY4JduSvRRyDmVOSqEW19gT4vtK+aCiPNVcDlmkxvGG0YbFd36RTDq1wExOupXnvNF/j1oiHHDA=="],++ "troika-three-utils": ["[email protected]", "", { "peerDependencies": { "three": ">=0.125.0" } }, "sha512-WsePbcX8RtfidRfsxK1eCZCjF81ZDzAKHH/evLs0hdV2wpoCb0vArGZHdzdOJrSS3k4zfdtbKDaBh8+phkrYnw=="],++ "troika-worker-utils": ["[email protected]", "", {}, "sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw=="],++ "tunnel-rat": ["[email protected]", "", { "dependencies": { "zustand": "^4.3.2" } }, "sha512-lR5VHmkPhzdhrM092lI2nACsLO4QubF0/yoOhzX7c+wIpbN1GjHNzCc91QlpxBi+cnx8vVJ+Ur6vL5cEoQPFpQ=="],"undici-types": ["[email protected]", "", {}, "sha512-GNCQH3MbVGB8OAVAoTiLH8pu4wx5Ni3DWKpnBzGj3WDsi8EwmK0aOVBooNEt+g5YL1eHPxcS9XUTouwFU6j1kQ=="],"use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],+ "utility-types": ["[email protected]", "", {}, "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw=="],++ "webgl-constants": ["[email protected]", "", {}, "sha512-LkBXKjU5r9vAW7Gcu3T5u+5cvSvh5WwINdr0C+9jpzVB41cjQAP5ePArDtk/WHYdVj0GefCgM73BA7FlIiNtdg=="],++ "webgl-sdf-generator": ["[email protected]", "", {}, "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA=="],++ "which": ["[email protected]", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],+"zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA=="],"@react-three/fiber/scheduler": ["[email protected]", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],@@ -86,5 +174,11 @@"@types/node/undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],"react-dom/scheduler": ["[email protected]", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],++ "stats-gl/three": ["[email protected]", "", {}, "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ=="],++ "three-stdlib/fflate": ["[email protected]", "", {}, "sha512-3JyEFWGjFn7zHmoa9+zG1BmW7X2okcmAB+0Cnu9UFbVs/jCBnl2A8o065ZlXiw145K3eBM3uLuzrYXC0RK7eDg=="],++ "tunnel-rat/zustand": ["[email protected]", "", { "dependencies": { "use-sync-external-store": "^1.2.2" }, "peerDependencies": { "@types/react": ">=16.8", "immer": ">=9.0.6", "react": ">=16.8" }, "optionalPeers": ["@types/react", "immer", "react"] }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],}}diff --git a/sdk/r3f/package.json b/sdk/r3f/package.jsonindex c4f2ee7e..2fe251ea 100644--- a/sdk/r3f/package.json+++ b/sdk/r3f/package.json@@ -11,19 +11,23 @@"./three": "./src/three/index.ts","./export": "./src/export/index.ts"},- "//": "In a project, three and @react-three/fiber are its own (raea add [email protected] @react-three/[email protected]): the bundler resolves them from the project, so a scene and raea share one copy. Here, for the package's tests and tsc, React is the SDK's own (sdk/raea), linked; sdk/playable's bundler resolves three to its own copy, so a playable carries one.",+ "//": "In a project, three and @react-three/fiber are its own (raea add [email protected] @react-three/[email protected]): the bundler resolves them from the project, so a scene and raea share one copy. Here, for the package's tests and tsc, React is the SDK's own (sdk/raea), linked; sdk/playable's bundler resolves three to its own copy, so a playable carries one.","peerDependencies": {"@react-three/fiber": ">=9.0.0","three": ">=0.170.0"},"devDependencies": {+ "@react-three/drei": "10.7.9","@react-three/fiber": "9.8.2",+ "@react-three/postprocessing": "3.2.2","@types/bun": "1.4.3","@types/react-dom": "19.2.0",- "@types/three": "0.180.0",+ "@types/three": "0.185.0",+ "lettra": "0.3.0",+ "postprocessing": "6.39.5","react": "file:../raea/node_modules/react","react-dom": "file:../raea/node_modules/react-dom","scheduler": "file:../raea/node_modules/scheduler",- "three": "0.180.0"+ "three": "0.185.0"}}diff --git a/sdk/r3f/src/export/record.tsx b/sdk/r3f/src/export/record.tsxindex 0eedd8c4..fadcb62b 100644--- a/sdk/r3f/src/export/record.tsx+++ b/sdk/r3f/src/export/record.tsx@@ -116,11 +116,13 @@ function lightOf(l: THREE.Light): string {for (const k of LIGHT_KEYS) if (k in own) out[k] = value(own[k]);const t = (l as THREE.DirectionalLight).target;if (t) out.target = arr(t.getWorldPosition(new THREE.Vector3()).toArray());- if (l.shadow && l.castShadow) {- const c = l.shadow.camera as THREE.OrthographicCamera & THREE.PerspectiveCamera;+ // three 0.185's types keep `shadow` on the lights that cast one (DirectionalLight, PointLight, SpotLight)+ const shadow = (l as THREE.DirectionalLight).shadow as THREE.LightShadow | undefined;+ if (shadow && l.castShadow) {+ const c = shadow.camera as THREE.OrthographicCamera & THREE.PerspectiveCamera;const camera: Record<string, number> = { near: r5(c.near), far: r5(c.far) };if ((c as THREE.OrthographicCamera).isOrthographicCamera) Object.assign(camera, { left: r5(c.left), right: r5(c.right), top: r5(c.top), bottom: r5(c.bottom) });- out.shadow = { mapSize: [l.shadow.mapSize.x, l.shadow.mapSize.y], bias: r5(l.shadow.bias), normalBias: r5(l.shadow.normalBias), camera };+ out.shadow = { mapSize: [shadow.mapSize.x, shadow.mapSize.y], bias: r5(shadow.bias), normalBias: r5(shadow.normalBias), camera };}return JSON.stringify(out);}diff --git a/sdk/r3f/src/input/R3F.tsx b/sdk/r3f/src/input/R3F.tsxindex f824807a..2472bbef 100644--- a/sdk/r3f/src/input/R3F.tsx+++ b/sdk/r3f/src/input/R3F.tsx@@ -41,7 +41,9 @@ function Inner({ fiber, children, name, ...config }: R3FProps & { fiber: Paramet};const s = stepTo(name ?? id, frame, fps, width, height, config, at);const { scene, camera, gl } = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };- const out = convert(scene, camera, gl, height);+ // R3F's clock: what a node material's `time` reads (useFrame's own steps, 1/fps a frame)+ const r3fClock = (s.state as unknown as { clock: { elapsedTime: number } }).clock;+ const out = convert(scene, camera, gl, height, r3fClock.elapsedTime, 1 / fps);const drawn = elementsOf(out.parts, "r3f.");return out.background ? <AbsoluteFill style={{ background: out.background }}>{drawn}</AbsoluteFill> : <>{drawn}</>;}diff --git a/sdk/r3f/src/input/clip.ts b/sdk/r3f/src/input/clip.tsnew file mode 100644index 00000000..a5154b06--- /dev/null+++ b/sdk/r3f/src/input/clip.ts@@ -0,0 +1,98 @@+// three's clipping planes (a material's clippingPlanes with the renderer's localClippingEnabled, the renderer's own+// clippingPlanes, a WebGPU <ClippingGroup>'s) done on the mesh: each triangle cut at the planes and what lies beyond+// dropped, its normals, uvs and colours carried to the new corners. three discards those fragments, so the surface+// left is the same, open where it was cut (three's is too: it has no caps).+//+// clipIntersection (three: clip only what lies beyond every plane) keeps the parts inside any one plane: each plane's+// side cut out of what the earlier ones didn't keep, so nothing is drawn twice.+import * as THREE from "three";+import type { Arrays } from "./geometry";++export interface Clip {+ /** world-space planes: what's on a plane's negative side is cut away */+ planes: THREE.Plane[];+ /** three's clipIntersection */+ intersection: boolean;+}++interface Vert {+ p: number[];+ n?: number[];+ uv?: number[];+ c?: number[];+}++const lerp = (a: number[] | undefined, b: number[] | undefined, t: number) => (a && b ? a.map((x, i) => x + (b[i] - x) * t) : undefined);+const mix = (a: Vert, b: Vert, t: number): Vert => ({ p: lerp(a.p, b.p, t)!, n: lerp(a.n, b.n, t), uv: lerp(a.uv, b.uv, t), c: lerp(a.c, b.c, t) });++/** a polygon cut by a plane (local space): what's on its positive side, or (keepBack) its negative side */+function cutBy(poly: Vert[], pl: THREE.Plane, keepBack = false): Vert[] {+ const out: Vert[] = [];+ const side = (v: Vert) => (pl.normal.x * v.p[0] + pl.normal.y * v.p[1] + pl.normal.z * v.p[2] + pl.constant) * (keepBack ? -1 : 1);+ for (let i = 0; i < poly.length; i++) {+ const a = poly[i], b = poly[(i + 1) % poly.length];+ const da = side(a), db = side(b);+ if (da >= 0) out.push(a);+ if ((da >= 0) !== (db >= 0)) out.push(mix(a, b, da / (da - db)));+ }+ return out;+}++/** the mesh's arrays clipped by `clip`'s planes (given in world space; `world` is the mesh's matrixWorld) */+export function clipArrays(a: Arrays, clip: Clip, world: THREE.Matrix4): Arrays | undefined {+ if (!clip.planes.length) return a;+ // the planes in the mesh's own space+ const inv = new THREE.Matrix4().copy(world).invert();+ const normalOf = new THREE.Matrix3().getNormalMatrix(inv);+ const planes = clip.planes.map((p) => p.clone().applyMatrix4(inv, normalOf));+ const nv = a.positions.length / 3;+ const vert = (i: number): Vert => ({+ p: a.positions.slice(i * 3, i * 3 + 3),+ n: a.normals?.slice(i * 3, i * 3 + 3),+ uv: a.uvs?.slice(i * 2, i * 2 + 2),+ c: a.colors?.slice(i * 4, i * 4 + 4),+ });+ const idx = a.indices ?? Array.from({ length: nv }, (_, i) => i);+ const out: Vert[] = [];+ const emit = (poly: Vert[]) => {+ for (let k = 1; k + 1 < poly.length; k++) out.push(poly[0], poly[k], poly[k + 1]);+ };+ for (let t = 0; t + 2 < idx.length; t += 3) {+ const tri = [vert(idx[t]), vert(idx[t + 1]), vert(idx[t + 2])];+ if (!clip.intersection) {+ let poly = tri;+ for (const pl of planes) {+ poly = cutBy(poly, pl);+ if (poly.length < 3) break;+ }+ if (poly.length >= 3) emit(poly);+ continue;+ }+ // inside any plane: plane k's side, less what planes before it kept+ for (let k = 0; k < planes.length; k++) {+ let poly = cutBy(tri, planes[k]);+ for (let j = 0; j < k && poly.length >= 3; j++) poly = cutBy(poly, planes[j], true);+ if (poly.length >= 3) emit(poly);+ }+ }+ if (!out.length) return undefined;+ const flat = (k: keyof Vert) => (out[0][k] ? out.flatMap((v) => v[k]!) : undefined);+ return { ...a, positions: flat("p")!, normals: flat("n"), uvs: flat("uv"), colors: flat("c"), indices: undefined } as Arrays;+}++/** the planes that clip a mesh with material `m` under `gl` and the clipping groups around it */+export function clipOf(m: THREE.Material, gl: THREE.WebGLRenderer | undefined, groups: Clip[]): Clip | undefined {+ const planes: THREE.Plane[] = [];+ let intersection = false;+ const g = gl as unknown as { clippingPlanes?: THREE.Plane[]; localClippingEnabled?: boolean } | undefined;+ if (g?.clippingPlanes?.length) planes.push(...g.clippingPlanes);+ if (m.clippingPlanes?.length && (g?.localClippingEnabled || (m as { isNodeMaterial?: boolean }).isNodeMaterial)) {+ planes.push(...m.clippingPlanes);+ intersection = m.clipIntersection;+ }+ for (const c of groups) {+ planes.push(...c.planes);+ intersection ||= c.intersection;+ }+ return planes.length ? { planes, intersection } : undefined;+}diff --git a/sdk/r3f/src/input/geometry.ts b/sdk/r3f/src/input/geometry.tsindex c19aa78e..14b1a9e6 100644--- a/sdk/r3f/src/input/geometry.ts+++ b/sdk/r3f/src/input/geometry.ts@@ -11,6 +11,8 @@ export interface Arrays {normals?: number[];uvs?: number[];colors?: number[];+ /** a three shader's own attributes, per vertex (ThreeShaderMaterial) */+ attributes?: Record<string, { size: number; values: number[] }>;}type Attr = THREE.BufferAttribute | THREE.InterleavedBufferAttribute;@@ -53,6 +55,17 @@ export interface ReadOptions {flipV: boolean;/** the vertex colours, when the material uses them */colors: boolean;+ /** each triangle wound the other way: a mesh whose transform mirrors it (a negative scale), which three draws+ * with its front face flipped and Bevy culls as it's wound */+ mirror?: boolean;+}++/** the triangles wound the other way (indices made for a geometry without them) */+export function rewound(a: Arrays): Arrays {+ const idx = a.indices ?? Array.from({ length: a.positions.length / 3 }, (_, i) => i);+ const out = idx.slice();+ for (let i = 0; i + 2 < out.length; i += 3) [out[i + 1], out[i + 2]] = [out[i + 2], out[i + 1]];+ return { ...a, indices: out };}/** A geometry's arrays for raea, the same objects while it hasn't changed. */@@ -61,7 +74,7 @@ export function arraysOf(g: THREE.BufferGeometry, o: ReadOptions): Arrays | undeif (!pos || pos.count < 3) return undefined;const start = Math.max(o.start ?? 0, g.drawRange.start);const end = Math.min(o.count === undefined ? Infinity : (o.start ?? 0) + o.count, g.drawRange.count === Infinity ? Infinity : g.drawRange.start + g.drawRange.count);- const key = `${start}:${end}:${o.flipV}:${o.colors}`;+ const key = `${start}:${end}:${o.flipV}:${o.colors}:${!!o.mirror}`;const v = versions(g);let m = kept.get(g);if (!m) kept.set(g, (m = new Map()));@@ -76,8 +89,9 @@ export function arraysOf(g: THREE.BufferGeometry, o: ReadOptions): Arrays | undecolors: o.colors ? read(g.attributes.color, 4) : undefined,};if (indices && indices.length < 3) return undefined;- m.set(key, { v, arrays });- return arrays;+ const out = o.mirror ? rewound(arrays) : arrays;+ m.set(key, { v, arrays: out });+ return out;}/** whether a mesh's shape moves from frame to frame: bones, or morph targets with any weight */diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.tsindex c890d829..ed93a185 100644--- a/sdk/r3f/src/input/kinds.ts+++ b/sdk/r3f/src/input/kinds.ts@@ -22,7 +22,7 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:LineSegments: { status: "drawn", raea: "Gizmo lines (helpers too: AxesHelper, GridHelper, BoxHelper ...)" },LineLoop: { status: "drawn", raea: "Gizmo strip, closed" },Sprite: { status: "drawn", raea: "a Mesh quad facing the camera, its centre and rotation" },- ClippingGroup: { status: "near", raea: "Group", note: "its clipping planes are WebGPU-renderer only in three; raea draws the whole group" },+ ClippingGroup: { status: "drawn", raea: "Group, the meshes inside cut at its planes (clip.ts)" },// lightsAmbientLight: { status: "drawn", raea: "AmbientLight (units.ts)" },DirectionalLight: { status: "drawn", raea: "DirectionalLight with its target, shadows when the canvas has them" },@@ -30,7 +30,7 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:SpotLight: { status: "drawn", raea: "SpotLight with its target, angle and penumbra", note: "decay other than 2 falls off as the inverse square; a `map` (projected picture) isn't drawn" },RectAreaLight: { status: "drawn", raea: "RectAreaLight facing its -z, its size times its scale" },HemisphereLight: { status: "near", raea: "AmbientLight of its two colours' average", note: "raea has no sky-and-ground light" },- LightProbe: { status: "near", raea: "AmbientLight of its average colour", note: "its directional bands are left out" },+ LightProbe: { status: "near", raea: "AmbientLight of its constant band and a DirectionalLight along its linear band", note: "exact for surfaces facing that light or sideways; its quadratic band is left out" },Light: { status: "none", raea: "the base class: its subclasses are drawn" },// camerasCamera: { status: "none", raea: "the base class" },@@ -47,20 +47,48 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:MeshPhysicalMaterial: { status: "drawn", raea: "MeshPhysicalMaterial (clearcoat, transmission, ior, thickness, attenuation, anisotropy, specular)", note: "sheen and iridescence are three's" },MeshBasicMaterial: { status: "drawn", raea: "MeshBasicMaterial" },MeshLambertMaterial: { status: "drawn", raea: "MeshStandardMaterial, roughness 1, metalness 0" },- MeshPhongMaterial: { status: "near", raea: "MeshStandardMaterial with its shininess as a roughness", note: "its specular colour is left out" },+ MeshPhongMaterial: { status: "near", raea: "MeshPhysicalMaterial: its shininess as a roughness, its specular colour as F0 (reflectance and specular tint)", note: "GGX's highlight, not Blinn-Phong's; an F0 above 0.16 (Bevy's highest reflectance) is held there, so a bright specular colour glints less" },MeshToonMaterial: { status: "near", raea: "MeshToonMaterial, a band per texel of its gradient map" },- MeshNormalMaterial: { status: "near", raea: "MeshBasicMaterial coloured by its normals per vertex", note: "three colours per pixel" },- MeshMatcapMaterial: { status: "near", raea: "MeshBasicMaterial in its colour", note: "the matcap's lighting is left out" },+ MeshNormalMaterial: { status: "drawn", raea: "ThreeShaderMaterial of three's ShaderLib.normal" },+ MeshMatcapMaterial: { status: "drawn", raea: "ThreeShaderMaterial of three's ShaderLib.matcap (its matcap, map, colour)" },MeshDepthMaterial: { status: "near", raea: "MeshBasicMaterial grey", note: "three's depth pass, not a surface" },MeshDistanceMaterial: { status: "near", raea: "MeshBasicMaterial grey", note: "three's shadow pass, not a surface" },ShadowMaterial: { status: "drawn", raea: "Mesh shadow=\"catch\": only the shadows falling on it, in its colour and opacity" },SpriteMaterial: { status: "drawn", raea: "MeshBasicMaterial on the sprite's quad" },PointsMaterial: { status: "drawn", raea: "MeshBasicMaterial on the points' quads" },LineBasicMaterial: { status: "drawn", raea: "the Gizmo's colours" },- LineDashedMaterial: { status: "near", raea: "the Gizmo's colours", note: "drawn solid" },- ShaderMaterial: { status: "near", raea: "MeshBasicMaterial in its colour uniform", note: "GLSL doesn't run in Bevy: port it to <SurfaceShader> (WESL)" },- RawShaderMaterial: { status: "near", raea: "MeshBasicMaterial in its colour uniform", note: "GLSL doesn't run in Bevy: port it to <SurfaceShader> (WESL)" },+ LineDashedMaterial: { status: "drawn", raea: "the Gizmo's colours, the line cut into its dashes by its line distances" },+ ShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 62 vec4s of uniforms and 4 attributes of its own; a render target's texture is white; onBeforeCompile isn't read" },+ RawShaderMaterial: { status: "drawn", raea: "ThreeShaderMaterial: its GLSL translated by naga and run with three's built-ins", note: "at most 4 textures, 62 vec4s of uniforms and 4 attributes of its own; a render target's texture is white; onBeforeCompile isn't read" },Material: { status: "none", raea: "the base class" },+ // three/webgpu's node materials (TSL): one with no node of its own is the classic material it extends, drawn natively;+ // one with a graph (colorNode, positionNode, ...) on a mesh is compiled to WGSL by three's own WGSLNodeBuilder and run+ // by raea's engine (tsl.ts: ThreeShaderMaterial), lit by three's light nodes when it is a lit material+ ...Object.fromEntries(["NodeMaterial", "MeshBasicNodeMaterial", "MeshLambertNodeMaterial", "MeshPhongNodeMaterial", "MeshStandardNodeMaterial", "MeshPhysicalNodeMaterial", "MeshSSSNodeMaterial", "MeshToonNodeMaterial", "MeshMatcapNodeMaterial", "MeshNormalNodeMaterial", "VolumeNodeMaterial"].map((k) => [k, { status: "drawn" as const, raea: "its classic material, or its graph as WGSL (ThreeShaderMaterial)", note: "a graph needing more than 4 textures, 62 vec4s of uniforms (uniformArrays included) or 4 attributes of the mesh's own, a storage buffer or a render target is named and drawn flat" }])),+ ...Object.fromEntries(["LineBasicNodeMaterial", "LineDashedNodeMaterial", "Line2NodeMaterial", "PointsNodeMaterial", "SpriteNodeMaterial", "ShadowNodeMaterial"].map((k) => [k, { status: "near" as const, raea: "its classic material (lines, points, a sprite, a shadow catcher)", note: "a graph of its own on lines, points or a sprite is drawn flat" }])),// helpers: lines (and a plane's mesh), drawn as any lines are...Object.fromEntries(["ArrowHelper", "AxesHelper", "Box3Helper", "BoxHelper", "CameraHelper", "DirectionalLightHelper", "GridHelper", "HemisphereLightHelper", "PlaneHelper", "PointLightHelper", "PolarGridHelper", "SkeletonHelper", "SpotLightHelper"].map((k) => [k, { status: "drawn" as const, raea: "its lines as Gizmo lines (an arrow's head and a plane's face as meshes)" }])),};++/** @react-three/postprocessing's effects (pmndrs postprocessing's classes) inside an <EffectComposer>, and the raea+ * effect each becomes (post.ts). A composer's frame is tone-mapped only by its ToneMapping effect. */+export const EFFECTS: Record<string, { status: InputStatus; raea: string; note?: string }> = {+ BloomEffect: { status: "near", raea: "Bloom (intensity, luminanceThreshold as threshold)", note: "Bevy's energy-conserving bloom, not postprocessing's mipmap blur: a glow of its own size" },+ SelectiveBloomEffect: { status: "near", raea: "Bloom", note: "the whole frame's: its selection isn't kept" },+ VignetteEffect: { status: "near", raea: "Grade vignette (darkness as intensity, offset as radius)", note: "raea's falloff is softer at the corners" },+ ChromaticAberrationEffect: { status: "near", raea: "Grade aberration (the offset's length)" },+ HueSaturationEffect: { status: "near", raea: "Grade saturation (1 + saturation)", note: "hue isn't turned" },+ BrightnessContrastEffect: { status: "near", raea: "Grade midtones (contrast, brightness as lift)" },+ ToneMappingEffect: { status: "drawn", raea: "ToneMapping (its mode; ACES with three's 1/0.6 as exposure)" },+ DepthOfFieldEffect: { status: "near", raea: "DepthOfField (gaussian, worldFocusDistance as focus, bokehScale as its blur)" },+ BokehEffect: { status: "near", raea: "DepthOfField (bokeh)", note: "postprocessing's legacy bokeh, its focus as raea's" },+ RealisticBokehEffect: { status: "near", raea: "DepthOfField (bokeh)", note: "postprocessing's legacy bokeh, its focus as raea's" },+ GammaCorrectionEffect: { status: "none", raea: "left out: raea's output is already encoded for the screen" },+ SMAAEffect: { status: "drawn", raea: "AntiAliasing smaa" },+ FXAAEffect: { status: "drawn", raea: "AntiAliasing fxaa" },+ SSAOEffect: { status: "near", raea: "AmbientOcclusion (Bevy's SSAO)" },+ N8AOPostPass: { status: "near", raea: "AmbientOcclusion (Bevy's SSAO)" },+ PixelationEffect: { status: "near", raea: "Look pixel (granularity / 5 as the cell)" },+ LensDistortionEffect: { status: "near", raea: "LensDistortion (distortion.x as k1)" },+ ...Object.fromEntries(["NoiseEffect", "GlitchEffect", "ScanlineEffect", "SepiaEffect", "DotScreenEffect", "ColorAverageEffect", "ColorDepthEffect", "GridEffect", "GodRaysEffect", "ShockWaveEffect", "TiltShiftEffect", "LUT3DEffect", "LUT1DEffect", "LUTEffect", "TextureEffect", "DepthEffect", "OutlineEffect", "ASCIIEffect"].map((k) => [k, { status: "none" as const, raea: "left out, named once", note: "write it as a raea <FramePass> (WESL) outside <R3F>" }])),+};diff --git a/sdk/r3f/src/input/lights.ts b/sdk/r3f/src/input/lights.tsindex 52289cb0..5d8f5cc8 100644--- a/sdk/r3f/src/input/lights.ts+++ b/sdk/r3f/src/input/lights.ts@@ -78,12 +78,26 @@ function lightOf(l: THREE.Light, shadows: boolean, name: string): Part | Part[]return [amb, dir];}if ((l as THREE.LightProbe).isLightProbe) {- // its spherical harmonics' constant band: the light it gives from every way on average+ // three lights a surface by the probe's irradiance at its normal (shGetIrradianceAt): the constant band gives+ // 0.886227 c0 from every way, the linear band 1.023328 (c3, c1, c2) . n. As the hemisphere light above: an ambient+ // light of the first and a directional light along the second, exact for surfaces facing it or sideways (the+ // quadratic band, a probe's finer shading, is left out)const p = l as THREE.LightProbe;- const c = p.sh.coefficients[0].clone().multiplyScalar(0.282095 * p.intensity);- const m = Math.max(c.x, c.y, c.z, 1e-6);- warnOnce("LightProbe", "is lit as an ambient light of its average colour");- return { type: "AmbientLight", props: { name, color: hex(new THREE.Color(c.x / m, c.y / m, c.z / m)), intensity: toRaea("AmbientLight", m) } };+ const [c0, c1, c2, c3] = p.sh.coefficients;+ const a = c0.clone().multiplyScalar(0.886227 * p.intensity);+ const ch = (k: "x" | "y" | "z") => new THREE.Vector3(c3[k], c1[k], c2[k]).multiplyScalar(1.023328 * p.intensity);+ const [br, bg, bb] = [ch("x"), ch("y"), ch("z")];+ const axis = br.clone().multiplyScalar(0.2126).add(bg.clone().multiplyScalar(0.7152)).add(bb.clone().multiplyScalar(0.0722));+ const m = Math.max(a.x, a.y, a.z, 1e-6);+ const amb: Part = { type: "AmbientLight", props: { name, color: hex(new THREE.Color(a.x / m, a.y / m, a.z / m)), intensity: toRaea("AmbientLight", m) } };+ if (p.sh.coefficients.slice(4).some((c) => c.lengthSq() > 1e-8)) warnOnce("LightProbe", "is lit by its first two bands (an ambient light and a light along its linear band): its finer shading is left out");+ if (axis.lengthSq() < 1e-10) return amb;+ axis.normalize();+ const d = new THREE.Color(Math.max(0, br.dot(axis)), Math.max(0, bg.dot(axis)), Math.max(0, bb.dot(axis)));+ const dm = Math.max(d.r, d.g, d.b);+ if (dm < 1e-5) return amb;+ const dir: Part = { type: "DirectionalLight", props: { name: `${name}~band`, position: axis.toArray(), target: [0, 0, 0], color: hex(new THREE.Color(d.r / dm, d.g / dm, d.b / dm)), intensity: toRaea("DirectionalLight", dm) } };+ return [amb, dir];}if ((l as THREE.AmbientLight).isAmbientLight) return { type: "AmbientLight", props: { name, color, intensity: toRaea("AmbientLight", l.intensity) } };return undefined;@@ -118,14 +132,36 @@ export function fogOf(f: THREE.Fog | THREE.FogExp2 | null): Part | undefined {return { type: "Fog", props: { color: hex(l.color), near: l.near, far: l.far } };}+/** three's own tone curve on a linear colour (ToneMappingFunctions), undefined for one not written here */+function threeTone(c: THREE.Color, mode: THREE.ToneMapping, exposure: number): THREE.Color | undefined {+ const [r, g, b] = [c.r * exposure, c.g * exposure, c.b * exposure];+ if (mode === THREE.NoToneMapping) return c.clone();+ if (mode === THREE.LinearToneMapping) return new THREE.Color(Math.min(r, 1), Math.min(g, 1), Math.min(b, 1));+ if (mode === THREE.ReinhardToneMapping) return new THREE.Color(r / (1 + r), g / (1 + g), b / (1 + b));+ if (mode !== THREE.ACESFilmicToneMapping) return undefined;+ const k = 1 / 0.6;+ const [x, y, z] = [r * k, g * k, b * k];+ const i = [0.59719 * x + 0.35458 * y + 0.04823 * z, 0.076 * x + 0.90834 * y + 0.01566 * z, 0.0284 * x + 0.13383 * y + 0.83777 * z];+ const f = i.map((v) => (v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.432951) + 0.238081));+ const o = [1.60475 * f[0] - 0.53108 * f[1] - 0.07367 * f[2], -0.10208 * f[0] + 1.10813 * f[1] - 0.00605 * f[2], -0.00327 * f[0] - 0.07276 * f[1] + 1.07602 * f[2]];+ const clamp = (v: number) => Math.min(Math.max(v, 0), 1);+ return new THREE.Color(clamp(o[0]), clamp(o[1]), clamp(o[2]));+}+const PANORAMA = /\.(hdr|exr|png|jpe?g)(\?.*)?$/i;/** the scene's environment (and a panorama behind it) as raea's <Environment>, or the background colour */-export function skyOf(scene: THREE.Scene): { parts: Part[]; background?: string } {+export function skyOf(scene: THREE.Scene, gl?: THREE.WebGLRenderer, webgpu = false): { parts: Part[]; background?: string } {const parts: Part[] = [];let background: string | undefined;const bg = scene.background;- if (bg instanceof THREE.Color) background = hex(bg);+ if (bg instanceof THREE.Color) {+ // three's WebGPURenderer draws the clear colour through its tone mapping (WebGLRenderer doesn't): the page shows+ // the colour it ends as+ const toned = webgpu && gl ? threeTone(bg, gl.toneMapping, gl.toneMappingExposure) : undefined;+ if (webgpu && !toned) warnOnce("scene.background", "is tone-mapped by three's WebGPURenderer with a curve raea doesn't copy for it: drawn as given");+ background = hex(toned ?? bg);+ }const env = srcOf(scene.environment);const sky = bg instanceof THREE.Texture ? srcOf(bg) : undefined;if (scene.environment && !(env && PANORAMA.test(env))) warnOnce("scene.environment", "isn't a panorama file raea can load (.hdr, .exr, .png, .jpg): left out");diff --git a/sdk/r3f/src/input/material.ts b/sdk/r3f/src/input/material.tsindex 9952daae..0714a45a 100644--- a/sdk/r3f/src/input/material.ts+++ b/sdk/r3f/src/input/material.ts@@ -6,6 +6,8 @@// with its `color` (or diffuse) uniform, unlit, and named once, with raea's <SurfaceShader> (WESL) as its port.import * as THREE from "three";import { placementOf, srcOf } from "./texture";+import { classicOf, nodeMaterialOf, type NodeAt } from "./tsl";+import { builtinPart, isShader, shaderPart } from "./shader";export type Props = Record<string, unknown>;export interface Part {@@ -73,7 +75,16 @@ function physical(m: THREE.MeshPhysicalMaterial, p: Props) {p.clearcoat = m.clearcoat;p.clearcoatRoughness = m.clearcoatRoughness;}- if (m.transmission) {+ // drei's MeshTransmissionMaterial keeps its transmission in a uniform (three's own is 0, so three makes no pass+ // of its own): raea's is Bevy's transmission, which refracts what's behind as drei's buffer does+ const drei = (m as unknown as { uniforms?: Record<string, { value: unknown }> }).uniforms;+ const own = typeof drei?._transmission?.value === "number" ? (drei._transmission.value as number) : 0;+ if (own && !m.transmission) {+ p.transmission = own;+ p.thickness = m.thickness;+ const extras = ["chromaticAberration", "distortion", "temporalDistortion", "anisotropicBlur"].filter((k) => Number(drei?.[k]?.value ?? 0) !== 0);+ if (extras.length) warnOnce(`MeshTransmissionMaterial ${extras.join(", ")}`, "isn't drawn: Bevy's transmission refracts without it");+ } else if (m.transmission) {p.transmission = m.transmission;p.thickness = m.thickness;}@@ -103,7 +114,7 @@ function warnOnce(type: string, why: string) {}/** a material as raea's: its component and props */-export function materialOf(m: THREE.Material, vertexColors: boolean): Part {+export function materialOf(m: THREE.Material, vertexColors: boolean, at?: NodeAt): Part {const p: Props = {};const t = m.type;switch (t) {@@ -126,10 +137,17 @@ export function materialOf(m: THREE.Material, vertexColors: boolean): Part {drawn(ph, p);p.roughness = roughnessOfShininess(ph.shininess);p.metalness = 0;+ // Blinn-Phong's specular colour is its F0 (three's BRDF_BlinnPhong): Bevy's F0 is 0.16 reflectance² times the tint+ const sp = ph.specular, top = Math.max(sp.r, sp.g, sp.b);+ if (top > 0) {+ p.reflectance = Math.min(1, Math.sqrt(top / 0.16));+ if (sp.r !== sp.g || sp.g !== sp.b) p.specularTint = hex(new THREE.Color(sp.r / top, sp.g / top, sp.b / top));+ } else p.reflectance = 0;if (ph.emissive.r || ph.emissive.g || ph.emissive.b) Object.assign(p, { emissive: hex(ph.emissive), emissiveIntensity: ph.emissiveIntensity });const n = srcOf(ph.normalMap);if (n) p.normalMap = n;- return { type: "MeshStandardMaterial", props: p };+ // (reflectance is the physical surface's)+ return { type: "MeshPhysicalMaterial", props: p };}case "MeshToonMaterial": {const tm = m as THREE.MeshToonMaterial;@@ -147,13 +165,12 @@ export function materialOf(m: THREE.Material, vertexColors: boolean): Part {case "PointsMaterial":case "LineBasicMaterial":case "LineDashedMaterial":- case "MeshMatcapMaterial":drawn(m as THREE.MeshBasicMaterial, p);- if (t === "MeshMatcapMaterial") warnOnce(t, "is drawn unlit in its colour (a matcap's lighting is three's shader)");return { type: "MeshBasicMaterial", props: p };+ // three's own programs for these (its ShaderLib's matcap and normal), run by raea's engine as three runs them+ case "MeshMatcapMaterial":case "MeshNormalMaterial":- warnOnce(t, "is drawn as each vertex's normal in colour, unlit (three shades it per pixel, in view space)");- return { type: "MeshBasicMaterial", props: { color: "#ffffff" }, normals: true } as Part;+ return builtinPart(m as THREE.MeshMatcapMaterial);case "MeshDepthMaterial":case "MeshDistanceMaterial":warnOnce(t, "is drawn unlit grey (it is three's shadow and depth pass, not a surface)");@@ -163,10 +180,21 @@ export function materialOf(m: THREE.Material, vertexColors: boolean): Part {return { type: "MeshBasicMaterial", props: { color: hex(s.color), opacity: s.opacity, transparent: true }, catchShadow: true } as Part;}default: {- // ShaderMaterial, RawShaderMaterial, a NodeMaterial, a library's own+ // a TSL node material (three/webgpu): one with no node of its own is its classic material; one with a graph is+ // compiled to WGSL by three and run by raea's engine (tsl.ts), or, if its graph can't be, drawn flat below+ if ((m as { isNodeMaterial?: boolean }).isNodeMaterial) {+ const classic = classicOf(m);+ // (its `type` is three's accessor: defined on a view of it, not assigned)+ if (classic) return materialOf(Object.defineProperties(Object.create(m) as THREE.Material, { type: { value: classic }, isNodeMaterial: { value: false } }), vertexColors, at);+ const shader = at && nodeMaterialOf(m, at);+ if (shader) return shader;+ }+ // a ShaderMaterial or RawShaderMaterial: its GLSL run by raea's engine as three would run it (shader.ts)+ if (isShader(m)) return shaderPart(m);+ // a NodeMaterial whose graph can't be compiled, a library's ownconst u = (m as THREE.ShaderMaterial).uniforms ?? {};const c = (u.color ?? u.diffuse ?? u.uColor)?.value;- warnOnce(t, "runs GLSL that Bevy doesn't: drawn unlit in its colour uniform; port its shader to raea's <SurfaceShader> (WESL)");+ warnOnce(t, "has a shader raea can't run: drawn unlit in its colour uniform");drawn(m as THREE.MeshBasicMaterial, p);if (c instanceof THREE.Color) p.color = hex(c);return { type: "MeshBasicMaterial", props: p };diff --git a/sdk/r3f/src/input/post.ts b/sdk/r3f/src/input/post.tsnew file mode 100644index 00000000..ca67f291--- /dev/null+++ b/sdk/r3f/src/input/post.ts@@ -0,0 +1,142 @@+// @react-three/postprocessing's <EffectComposer> as raea's frame effects (docs/r3f.feature R3F12). Its effects are R3F+// instances under the composer's <group>, objects of pmndrs' postprocessing library, not three's: each is read here and+// becomes the raea effect that does the same thing (Bloom, Grade, ToneMapping, DepthOfField, AntiAliasing,+// AmbientOcclusion, Look, LensDistortion), which raea's engine draws after the scene as Bevy does. One raea has nothing+// for (noise, glitch, scanlines, god rays ...) is named once and left out.+//+// A composer renders the scene into a render target, where three doesn't tone-map: the frame is mapped only by a+// <ToneMapping> effect in it (postprocessing's ToneMappingEffect), so a scene with a composer is drawn untonemapped+// unless it has one.+import type * as THREE from "three";+import type { Part, Props } from "./material";++const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++/** an effect of pmndrs' postprocessing (duck-typed: its class's name, its blend mode) */+interface Effect {+ name: string;+ blendMode?: { blendFunction?: number; opacity?: { value: number } };+ [k: string]: unknown;+}++const isEffect = (o: unknown): o is Effect => typeof (o as Effect | null)?.name === "string" && (o as Effect).blendMode !== undefined && /Effect$/.test((o as Effect).name);+/** a postprocessing Pass that isn't an EffectPass (N8AO's N8AOPostPass) */+const isPass = (o: unknown): o is { name: string; constructor: { name: string } } => typeof (o as { render?: unknown } | null)?.render === "function" && (o as { isPass?: boolean }).isPass === true;++/** postprocessing's ToneMappingMode, as raea's ToneMapping mode */+const TONE: Record<number, string> = { 0: "none", 1: "reinhard", 2: "reinhard", 3: "reinhard", 4: "aces", 5: "aces", 6: "aces", 7: "agx", 8: "neutral" };++const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) ? v : d);++/** the composers' effects in a scene, in the order they're drawn, and whether a composer was found */+export function composerEffects(scene: THREE.Scene): { found: boolean; effects: unknown[] } {+ const effects: unknown[] = [];+ let found = false;+ scene.traverse((o) => {+ const inst = (o as unknown as { __r3f?: { children?: { object?: unknown }[] } }).__r3f;+ for (const c of inst?.children ?? []) {+ const e = c.object;+ if (isEffect(e) || isPass(e)) {+ found = true;+ effects.push(e);+ }+ }+ });+ return { found, effects };+}++/** the effects as raea's parts: one Grade gathers the colour effects; `tone` is the ToneMapping part, if any */+export function postParts(effects: unknown[]): { parts: Part[]; tone?: Part } {+ const parts: Part[] = [];+ const grade: Props = {};+ let tone: Part | undefined;+ for (const raw of effects) {+ if (isPass(raw) && !isEffect(raw)) {+ const n = raw.constructor.name;+ if (/N8AO/i.test(n)) parts.push({ type: "AmbientOcclusion", props: { quality: "medium" } });+ else warnOnce(`<EffectComposer> pass ${n}`, "has no raea counterpart: left out");+ continue;+ }+ const e = raw as Effect;+ // a blend of SKIP (0) draws nothing; an effect's opacity scales it+ if (e.blendMode?.blendFunction === 0) continue;+ const share = num(e.blendMode?.opacity?.value, 1);+ switch (e.name) {+ case "BloomEffect":+ case "SelectiveBloomEffect": {+ if (e.name === "SelectiveBloomEffect") warnOnce("<SelectiveBloom>", "glows everything bright, not only its selection (raea's Bloom is the frame's)");+ const lum = e.luminanceMaterial as { threshold?: number } | undefined;+ parts.push({ type: "Bloom", props: { intensity: num(e.intensity, 1) * share, threshold: num(lum?.threshold, 0.9) } });+ break;+ }+ case "VignetteEffect": {+ // postprocessing's: darkness toward the corners from `offset` out (0.5, 0.5 by default)+ const darkness = num(e.darkness, 0.5) * share;+ const offset = num(e.offset, 0.5);+ grade.vignette = { intensity: Math.min(1, darkness), radius: Math.max(0.1, 1 - offset * 0.5) };+ break;+ }+ case "ChromaticAberrationEffect": {+ const o = e.offset as { x: number; y: number } | undefined;+ if (o) grade.aberration = Math.hypot(o.x, o.y) * share;+ break;+ }+ case "HueSaturationEffect": {+ grade.saturation = 1 + num(e.saturation, 0) * share;+ if (num(e.hue, 0) !== 0) warnOnce("<HueSaturation> hue", "isn't turned in raea (its saturation is)");+ break;+ }+ case "BrightnessContrastEffect": {+ grade.midtones = { contrast: 1 + num(e.contrast, 0) * share, lift: num(e.brightness, 0) * share };+ break;+ }+ case "ToneMappingEffect": {+ const mode = TONE[num(e.mode, 7)] ?? "agx";+ // three's ACES scales its input by 1/0.6 where Bevy's doesn't (lights.ts's toneOf does the same)+ tone = { type: "ToneMapping", props: mode === "aces" ? { mode, exposure: Math.log2(1 / 0.6) } : { mode } };+ break;+ }+ case "DepthOfFieldEffect": {+ const coc = e.cocMaterial as { worldFocusDistance?: number; worldFocusRange?: number } | undefined;+ const props: Props = { mode: "gaussian", maxBlur: Math.round(num(e.bokehScale, 1) * 16) };+ if (coc?.worldFocusDistance !== undefined) props.focus = coc.worldFocusDistance;+ parts.push({ type: "DepthOfField", props });+ break;+ }+ case "BokehEffect":+ case "RealisticBokehEffect": {+ const focus = num(e.focus ?? (e.uniforms as Map<string, { value: number }> | undefined)?.get?.("focus")?.value, 10);+ parts.push({ type: "DepthOfField", props: { mode: "bokeh", focus } });+ break;+ }+ case "GammaCorrectionEffect":+ break;+ case "SMAAEffect":+ parts.push({ type: "AntiAliasing", props: { mode: "smaa" } });+ break;+ case "FXAAEffect":+ parts.push({ type: "AntiAliasing", props: { mode: "fxaa" } });+ break;+ case "SSAOEffect":+ parts.push({ type: "AmbientOcclusion", props: { quality: "medium" } });+ break;+ case "PixelationEffect":+ parts.push({ type: "Look", props: { mode: "pixel", pixelSize: Math.max(1, Math.round(num(e.granularity, 30) / 5)) } });+ break;+ case "LensDistortionEffect": {+ const d = e.distortion as { x: number } | undefined;+ parts.push({ type: "LensDistortion", props: { k1: d?.x ?? 0 } });+ break;+ }+ default:+ warnOnce(`<EffectComposer> effect ${e.name}`, "has no raea counterpart: left out (write it as a raea <FramePass> outside <R3F>)");+ }+ }+ if (Object.keys(grade).length) parts.push({ type: "Grade", props: grade });+ return { parts, tone };+}diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.tsindex ba550657..97cb23df 100644--- a/sdk/r3f/src/input/scene.ts+++ b/sdk/r3f/src/input/scene.ts@@ -5,9 +5,14 @@// Lights, the camera, fog and the environment come out in world space (lights.ts). Each part is named by its place in// the tree (and its own name), so raea matches it across frames.import * as THREE from "three";-import { arraysOf, posed, posedArrays, type Arrays } from "./geometry";+import { arraysOf, posed, posedArrays, rewound, type Arrays } from "./geometry";+import { isTroikaText, textParts } from "./text";+import { clipArrays, clipOf, type Clip } from "./clip";import { cameraOf, fogOf, lightsOf, skyOf, toneOf } from "./lights";import { materialOf, type Part, type Props } from "./material";+import { isShader, ownAttributes, shaderPart } from "./shader";+import { composerEffects, postParts } from "./post";+import { classicOf } from "./tsl";type V3 = [number, number, number];type Q = [number, number, number, number];@@ -23,6 +28,13 @@ function place(o: THREE.Object3D): Props {const hex = (c: THREE.Color) => "#" + c.getHexString();+const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}+export interface Walk {camera: THREE.Camera;/** the renderer's shadow map is on (<Canvas shadows>) */@@ -31,9 +43,22 @@ export interface Walk {world: Part[];/** the drawing's height in pixels (a point's size without attenuation is in pixels) */height: number;+ scene: THREE.Scene;+ /** R3F's clock this frame and its step, seconds (a node material's `time` and `deltaTime`) */+ time: number;+ delta: number;+ /** the renderer (its clipping planes) */+ gl?: THREE.WebGLRenderer;+ /** the clipping groups (three/webgpu's ClippingGroup) the walk is inside */+ clips: Clip[];}function flipped(m: THREE.Material | THREE.Material[]): boolean {+ // a node material's graph reads its uvs as three gives them, and flips where it samples a flipped picture (tsl.ts)+ const one = Array.isArray(m) ? m[0] : m;+ if ((one as { isNodeMaterial?: boolean } | undefined)?.isNodeMaterial && !classicOf(one)) return false;+ // a ShaderMaterial reads its uvs as three gives them; the engine flips where it samples a flipped picture+ if (one && isShader(one)) return false;const map = ((Array.isArray(m) ? m[0] : m) as THREE.MeshBasicMaterial | undefined)?.map;return map ? map.flipY : true;}@@ -62,14 +87,34 @@ function meshParts(mesh: THREE.Mesh, name: string, w: Walk, at: Props): Part[] {const g = mesh.geometry;const ranges = Array.isArray(mesh.material) && g.groups.length ? g.groups.map((r) => ({ start: r.start, count: r.count, material: mats[r.materialIndex ?? 0] })) : [{ start: undefined, count: undefined, material: mats[0] }];const out: Part[] = [];+ // a mirroring transform (drei's <ContactShadows> plane is scaled -1 in y): three flips its front face, Bevy doesn't+ mesh.updateWorldMatrix(true, false);+ const mirror = mesh.matrixWorld.determinant() < 0;ranges.forEach((r, i) => {if (!r.material || !r.material.visible) return;- const o = { start: r.start, count: r.count, flipV: flipped(r.material), colors: colouredByVertex(r.material) };- let arrays = posed(mesh) ? posedArrays(mesh, o) : arraysOf(g, o);+ const o = { start: r.start, count: r.count, flipV: flipped(r.material), colors: colouredByVertex(r.material), mirror };+ let arrays = posed(mesh) ? posedArrays(mesh, { ...o, mirror: false }) : arraysOf(g, o);+ if (arrays && mirror && posed(mesh)) arrays = rewound(arrays);if (!arrays) return;- const surface = materialOf(r.material, o.colors);+ const surface = materialOf(r.material, o.colors, { object: mesh, scene: w.scene, camera: w.camera, time: w.time, delta: w.delta });if (!surface.type) return;if (surface.normals) arrays = normalColours(arrays, mesh, w.camera);+ // clipping planes cut the triangles (clip.ts); a three shader's own attributes would lose their count+ const clip = clipOf(r.material, w.gl, w.clips);+ if (clip) {+ if ((arrays as { attributes?: unknown }).attributes) warnOnce("a clipped ShaderMaterial with attributes of its own", "is drawn whole");+ else {+ mesh.updateWorldMatrix(true, false);+ const cut = clipArrays(arrays, clip, mesh.matrixWorld);+ if (!cut) return;+ arrays = cut;+ }+ }+ // a three shader's own attributes (aRandom, aOffset...), numbered as the BufferMesh's vertices are+ if (surface.type === "ThreeShaderMaterial" && !posed(mesh) && arrays.positions.length / 3 === g.attributes.position?.count) {+ const own = attributesOf(g);+ if (own) arrays = { ...arrays, attributes: own } as Arrays;+ }const props: Props = { name: ranges.length > 1 ? `${name}#${i}` : name, ...at, castShadow: w.shadows && mesh.castShadow, receiveShadow: mesh.receiveShadow };if (surface.catchShadow) props.shadow = "catch";out.push({ type: "Mesh", props, children: [{ type: "BufferMesh", props: { ...arrays } }, surface] });@@ -95,7 +140,7 @@ function instancedParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Propsif (!moving) {const material = m.material as THREE.Material;const arrays = arraysOf(m.geometry, { flipV: flipped(material), colors: colouredByVertex(material) });- const surface = materialOf(material, false);+ const surface = materialOf(material, false, { object: m, scene: w.scene, camera: w.camera, time: w.time, delta: w.delta });if (!arrays || !surface.type) return [];return [{ type: "Instances", props: { name, ...at, at: copies.map(({ position, rotation, scale }) => ({ position, rotation, scale })), shadow: w.shadows && m.castShadow, receiveShadow: m.receiveShadow }, children: [{ type: "BufferMesh", props: { ...arrays } }, surface] }];}@@ -143,11 +188,49 @@ function batchedParts(b: THREE.BatchedMesh, name: string, w: Walk): Part[] {return out;}+/** a geometry's own attributes, read again only when one of them changes */+const attrCache = new WeakMap<THREE.BufferGeometry, { key: string; value: ReturnType<typeof ownAttributes> }>();+function attributesOf(g: THREE.BufferGeometry) {+ const key = Object.entries(g.attributes).map(([k, a]) => `${k}:${(a as THREE.BufferAttribute).version}`).join(",");+ const hit = attrCache.get(g);+ if (hit?.key === key) return hit.value;+ const value = ownAttributes(g);+ attrCache.set(g, { key, value });+ return value;+}++/** Points drawn by a ShaderMaterial: a quad at each point in the object's own space, its corners as `uv`, which the+ * engine spreads gl_PointSize pixels on screen (each attribute repeated at the quad's four corners) */+function shaderPointParts(pts: THREE.Points, mat: THREE.ShaderMaterial, name: string, at: Props): Part[] {+ const g = pts.geometry;+ const pos = g.attributes.position;+ const from = g.drawRange.start, to = Math.min(pos.count, g.drawRange.start + g.drawRange.count);+ const own = attributesOf(g);+ const colours = mat.vertexColors && g.attributes.color;+ const positions: number[] = [], uvs: number[] = [], colors: number[] = [], indices: number[] = [];+ const attributes: Record<string, { size: number; values: number[] }> = {};+ for (const [k, a] of Object.entries(own ?? {})) attributes[k] = { size: a.size, values: [] };+ for (let i = from; i < to; i++) {+ const base = positions.length / 3;+ for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {+ positions.push(pos.getX(i), pos.getY(i), pos.getZ(i));+ uvs.push(u, v);+ if (colours) colors.push(colours.getX(i), colours.getY(i), colours.getZ(i), colours.itemSize > 3 ? colours.getW(i) : 1);+ for (const [k, a] of Object.entries(own ?? {})) attributes[k].values.push(...a.values.slice(i * a.size, i * a.size + a.size));+ }+ indices.push(base, base + 1, base + 2, base, base + 2, base + 3);+ }+ if (!indices.length) return [];+ const arrays = { positions, indices, uvs, ...(colours ? { colors } : {}), ...(own ? { attributes } : {}) };+ return [{ type: "Mesh", props: { name, ...at, castShadow: false, receiveShadow: false }, children: [{ type: "BufferMesh", props: arrays as unknown as Props }, shaderPart(mat, true)] }];+}+/** a quad facing the camera at each point: one mesh, its vertex colours the points' */-function pointParts(pts: THREE.Points, name: string, w: Walk): Part[] {+function pointParts(pts: THREE.Points, name: string, w: Walk, at: Props): Part[] {const g = pts.geometry, mat = pts.material as THREE.PointsMaterial;const pos = g.attributes.position;if (!pos || !mat.visible) return [];+ if (isShader(mat)) return shaderPointParts(pts, mat, name, at);const cam = w.camera;const right = new THREE.Vector3(1, 0, 0).applyQuaternion(cam.getWorldQuaternion(new THREE.Quaternion()));const up = new THREE.Vector3(0, 1, 0).applyQuaternion(cam.getWorldQuaternion(new THREE.Quaternion()));@@ -193,6 +276,35 @@ function lineParts(l: THREE.Line, name: string): Part[] {return hex(c);};const width = mat.linewidth > 0 ? mat.linewidth : 1;+ // a LineDashedMaterial: the dashes of each segment, by the line's distances (computeLineDistances) as three's shader+ // cuts them (a fragment is drawn where scale x distance mod (dash + gap) is under dash); without the distances three+ // draws it solid, as here+ const dashed = mat as unknown as THREE.LineDashedMaterial;+ const along = g.attributes.lineDistance;+ if (dashed.isLineDashedMaterial && along) {+ const at = (i: number) => along.getX(idx ? idx.getX(i) : i) * dashed.scale;+ const period = dashed.dashSize + dashed.gapSize;+ const lines: [V3, V3][] = [], cs: string[] = [];+ const cut = (i: number, j: number) => {+ const a = new THREE.Vector3(...point(i)), b = new THREE.Vector3(...point(j));+ const d0 = at(i), d1 = at(j);+ if (!(period > 0) || d1 === d0) return;+ const lo = Math.min(d0, d1), hi = Math.max(d0, d1);+ for (let start = Math.floor(lo / period) * period; start < hi; start += period) {+ const s0 = Math.max(lo, start), s1 = Math.min(hi, start + dashed.dashSize);+ if (s1 <= s0) continue;+ const p0 = a.clone().lerp(b, (s0 - d0) / (d1 - d0)), p1 = a.clone().lerp(b, (s1 - d0) / (d1 - d0));+ lines.push([p0.toArray() as V3, p1.toArray() as V3]);+ cs.push(colour(i), colour(j));+ }+ };+ if ((l as THREE.LineSegments).isLineSegments) for (let i = 0; i + 1 < n; i += 2) cut(i, i + 1);+ else {+ for (let i = 0; i + 1 < n; i++) cut(i, i + 1);+ if ((l as THREE.LineLoop).isLineLoop && n > 2) cut(n - 1, 0);+ }+ return lines.length ? [{ type: "Gizmo", props: { name, lines, color: mat.vertexColors ? cs : hex(mat.color), width, depthBias: 0 } }] : [];+ }if ((l as THREE.LineSegments).isLineSegments) {const lines: [V3, V3][] = [], cs: string[] = [];for (let i = 0; i + 1 < n; i += 2) {@@ -236,13 +348,20 @@ function walk(o: THREE.Object3D, path: string, w: Walk): Part[] {if ((o as THREE.Light).isLight) {w.world.push(...lightsOf(o as THREE.Light, w.shadows, name));}+ // a ClippingGroup (three/webgpu) clips what's inside it+ const group = o as unknown as { isClippingGroup?: boolean; enabled?: boolean; clippingPlanes?: THREE.Plane[]; clipIntersection?: boolean };+ const clips = group.isClippingGroup && group.enabled !== false && group.clippingPlanes?.length;+ if (clips) w.clips.push({ planes: group.clippingPlanes!, intersection: !!group.clipIntersection });const kids = o.children.flatMap((c, i) => walk(c, `${path}/${i}`, w));+ if (clips) w.clips.pop();const at = place(o);let own: Part[] = [];- if ((o as THREE.BatchedMesh).isBatchedMesh) own = batchedParts(o as THREE.BatchedMesh, name, w);+ // troika's Text (drei's <Text>) before the meshes: raea draws its words itself (text.ts)+ if (isTroikaText(o)) own = textParts(o, name);+ else if ((o as THREE.BatchedMesh).isBatchedMesh) own = batchedParts(o as THREE.BatchedMesh, name, w);else if ((o as THREE.InstancedMesh).isInstancedMesh) own = instancedParts(o as THREE.InstancedMesh, name, w, {});else if ((o as THREE.Mesh).isMesh) own = meshParts(o as THREE.Mesh, name, w, {});- else if ((o as THREE.Points).isPoints) return [...pointParts(o as THREE.Points, name, w), ...kids.length ? [{ type: "Group", props: { name: `${name}/`, ...at }, children: kids }] : []];+ else if ((o as THREE.Points).isPoints) return [...pointParts(o as THREE.Points, name, w, at), ...kids.length ? [{ type: "Group", props: { name: `${name}/`, ...at }, children: kids }] : []];else if ((o as THREE.Line).isLine) return [...lineParts(o as THREE.Line, name), ...kids.length ? [{ type: "Group", props: { name: `${name}/`, ...at }, children: kids }] : []];else if ((o as THREE.Sprite).isSprite) return [...spriteParts(o as THREE.Sprite, name, w), ...kids.length ? [{ type: "Group", props: { name: `${name}/`, ...at }, children: kids }] : []];// a mesh alone keeps its transform on itself; with children (or a group) the transform goes on a group around both@@ -258,16 +377,26 @@ export interface Converted {}/** R3F's scene, camera and renderer settings as raea's parts, this frame */-export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number): Converted {+export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGLRenderer, height: number, time = 0, delta = 0): Converted {scene.updateMatrixWorld();camera.updateMatrixWorld();if (camera.parent === null) camera.matrixWorldInverse.copy(camera.matrixWorld).invert();- const w: Walk = { camera, shadows: gl.shadowMap.enabled, world: [], height };+ const w: Walk = { camera, shadows: gl.shadowMap.enabled, world: [], height, scene, time, delta, gl, clips: [] };let drawn = scene.children.flatMap((c, i) => walk(c, `r3f/${i}`, w));// a scene moved, turned or scaled as a whole (rare, but three allows it)if (!scene.matrix.equals(new THREE.Matrix4()) && drawn.length) drawn = [{ type: "Group", props: { name: "r3f", ...place(scene) }, children: drawn }];- const sky = skyOf(scene);+ // a node material runs only under three's WebGPURenderer, so a scene with one is drawn by it (whatever gl stands in)+ let webgpu = (gl as { isWebGPURenderer?: boolean }).isWebGPURenderer === true;+ if (!webgpu) scene.traverse((o) => {+ const m = (o as THREE.Mesh).material;+ if ((Array.isArray(m) ? m : m ? [m] : []).some((x) => (x as { isNodeMaterial?: boolean }).isNodeMaterial)) webgpu = true;+ });+ const sky = skyOf(scene, gl, webgpu);const cam = cameraOf(camera);const fog = fogOf(scene.fog as THREE.Fog | THREE.FogExp2 | null);- return { parts: [...(cam ? [cam] : []), toneOf(gl), ...(fog ? [fog] : []), ...sky.parts, ...w.world, ...drawn], background: sky.background };+ // an <EffectComposer>'s effects (post.ts): its frame is tone-mapped only by a ToneMapping effect in it+ const composer = composerEffects(scene);+ const post = composer.found ? postParts(composer.effects) : { parts: [] as Part[], tone: undefined };+ const tone = composer.found ? post.tone ?? { type: "ToneMapping", props: { mode: "none" } } : toneOf(gl);+ return { parts: [...(cam ? [cam] : []), tone, ...(fog ? [fog] : []), ...sky.parts, ...post.parts, ...w.world, ...drawn], background: sky.background };}diff --git a/sdk/r3f/src/input/session.ts b/sdk/r3f/src/input/session.tsindex c729ad26..20c6e709 100644--- a/sdk/r3f/src/input/session.ts+++ b/sdk/r3f/src/input/session.ts@@ -6,20 +6,48 @@import * as THREE from "three";import { advance, createRoot, extend, flushSync, type ReconcilerRoot, type RenderProps, type RootState } from "@react-three/fiber";import type { ReactNode } from "react";+import { renderInto } from "./targets";extend(THREE as unknown as Parameters<typeof extend>[0]);/** the renderer R3F configures and never draws with: what it sets on it (shadows, tone mapping) is read back */export function standInRenderer(): THREE.WebGLRenderer {const noop = () => {};- return {- render: noop, setSize: noop, setPixelRatio: noop, getPixelRatio: () => 1, dispose: noop, setClearColor: noop, compile: noop,+ const size = { width: 1, height: 1 };+ // a WebGL context that answers what a composer asks as it is made (@react-three/postprocessing, three's own)+ const context = {+ getContextAttributes: () => ({ alpha: true, depth: true, stencil: false, antialias: false, premultipliedAlpha: true }),+ getExtension: () => null, getParameter: () => 0, getSupportedExtensions: () => [], isContextLost: () => false,+ };+ // a pass an app draws into a render target itself (drei's <ContactShadows>) is done on the CPU (targets.ts)+ let target: THREE.RenderTarget | null = null;+ const clear: [number, number, number, number] = [0, 0, 0, 0];+ const own = {+ render: (scene: THREE.Object3D, camera: THREE.Camera) => {+ if (target) renderInto(target, scene, camera, clear);+ },+ setRenderTarget: (t: THREE.RenderTarget | null) => void (target = t),+ getRenderTarget: () => target,+ setClearColor: (c: THREE.ColorRepresentation, a?: number) => {+ const col = new THREE.Color(c);+ clear[0] = col.r, clear[1] = col.g, clear[2] = col.b;+ if (a !== undefined) clear[3] = a;+ },+ setClearAlpha: (a: number) => void (clear[3] = a),+ getClearAlpha: () => clear[3], setSize: (w: number, h: number) => void Object.assign(size, { width: w, height: h }), setPixelRatio: noop, getPixelRatio: () => 1,+ getSize: (v: THREE.Vector2) => v.set(size.width, size.height), getDrawingBufferSize: (v: THREE.Vector2) => v.set(size.width, size.height),+ getContext: () => context, getClearColor: (c: THREE.Color) => c.setRGB(clear[0], clear[1], clear[2]),+ dispose: noop, compile: noop, autoClear: true, autoClearColor: true, autoClearDepth: true, autoClearStencil: true,domElement: { style: {}, addEventListener: noop, removeEventListener: noop },xr: { enabled: false, isPresenting: false, addEventListener: noop, removeEventListener: noop, setAnimationLoop: noop },shadowMap: { enabled: false, type: THREE.PCFShadowMap },outputColorSpace: THREE.SRGBColorSpace, toneMapping: THREE.NoToneMapping, toneMappingExposure: 1,- capabilities: { isWebGL2: true, maxTextureSize: 16384 }, info: { autoReset: true, reset: noop }, properties: { get: () => ({}) },- } as unknown as THREE.WebGLRenderer;+ capabilities: { isWebGL2: true, maxTextureSize: 16384, maxSamples: 4, logarithmicDepthBuffer: false }, info: { autoReset: true, reset: noop }, properties: { get: () => ({}) },+ } as Record<string | symbol, unknown>;+ // any other of WebGLRenderer's methods (setRenderTarget, clear, readRenderTargetPixels ...) does nothing: raea draws+ // (verbs only: a catch-all would answer `then`, and the renderer would read as a promise)+ const verb = /^(set|get|clear|read|copy|init|reset|render|dispose|compile|update|bind)[A-Z]?/;+ return new Proxy(own, { get: (t, k) => (k in t ? t[k] : typeof k === "string" && verb.test(k) ? noop : undefined) }) as unknown as THREE.WebGLRenderer;}function standInCanvas(width: number, height: number): HTMLCanvasElement {@@ -34,8 +62,31 @@ export interface Session {frame: number;/** the settings it was configured with, as JSON: a change starts it again */config: string;+ /** its useFrame callbacks when it last stepped: more on a redraw means part of it mounted late (it suspended) */+ subs: number;+ /** its Math.random's state: seeded as it starts, so a root started again draws the same numbers */+ rand: number;+}++/** Math.random as `s`'s own generator (mulberry32) while `fn` runs: drei's <Float> phase, <Sparkles>, three's uuids+ * come out the same each time the root is stepped from frame 0, so a render after a seek equals its play */+function seeded<T>(s: Session, fn: () => T): T {+ const was = Math.random;+ Math.random = () => {+ let t = (s.rand = (s.rand + 0x6d2b79f5) | 0);+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+ try {+ return fn();+ } finally {+ Math.random = was;+ }}+const seedOf = (key: string) => [...key].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261) | 0;+const sessions = new Map<string, Session>();export type Config = Omit<RenderProps<HTMLCanvasElement>, "gl" | "frameloop" | "size" | "events" | "dpr">;@@ -44,7 +95,7 @@ function start(key: string, width: number, height: number, config: Config, json:const root = createRoot(standInCanvas(width, height));let state: RootState | undefined;void root.configure({ ...config, gl: standInRenderer(), frameloop: "never", dpr: 1, size: { width, height, top: 0, left: 0 }, events: undefined, onCreated: (s) => { state = s; config.onCreated?.(s); } });- const s: Session = { root, state: state as unknown as RootState, frame: -1, config: json };+ const s: Session = { root, state: state as unknown as RootState, frame: -1, config: json, subs: 0, rand: seedOf(key) };sessions.set(key, s);return s;}@@ -61,19 +112,35 @@ export function stepTo(key: string, frame: number, fps: number, width: number, hconst live = s;const render = (i: number) => {let store: ReturnType<typeof live.root.render> | undefined;- flushSync(() => { store = live.root.render(scene(i)); });+ seeded(live, () => flushSync(() => { store = live.root.render(scene(i)); }));if (store) live.state = store.getState();};- // the same frame drawn again (a live replay): its children may have changed, its clock hasn't- if (frame === s.frame) render(frame);+ // the same frame drawn again (a live replay): its children may have changed, its clock hasn't. When parts of it+ // mounted only now (a model, a font: what suspended while the frames were stepped, loaded since), their useFrame+ // never ran: the root starts again, and with the loads cached it mounts at once and steps from frame 0 as if they+ // had been there all along (as three's own page waits for its loads and then draws the frame)+ if (frame === s.frame) {+ render(frame);+ if (subsOf(live) > live.subs && !late.has(key)) {+ late.add(key);+ end(key);+ return stepTo(key, frame, fps, width, height, config, scene);+ }+ }for (let i = s.frame + 1; i <= frame; i++) {render(i);- advance(i / fps, true, live.state);+ seeded(live, () => advance(i / fps, true, live.state));live.frame = i;+ live.subs = subsOf(live);}return live;}+/** roots started again for parts that mounted late: once each, so one whose callbacks keep growing can't loop */+const late = new Set<string>();++const subsOf = (s: Session) => (s.state as unknown as { internal?: { subscribers?: unknown[] } }).internal?.subscribers?.length ?? 0;+/** the root `key` unmounted (the <R3F> left the tree, or starts again) */export function end(key: string) {const s = sessions.get(key);diff --git a/sdk/r3f/src/input/shader.ts b/sdk/r3f/src/input/shader.tsnew file mode 100644index 00000000..0ecf58a2--- /dev/null+++ b/sdk/r3f/src/input/shader.ts@@ -0,0 +1,260 @@+// A three.js ShaderMaterial or RawShaderMaterial as raea's <ThreeShaderMaterial> (docs/r3f.feature R3F11): its GLSL as+// three would compile it (the #includes expanded from three's ShaderChunk, its `defines` in front), its uniforms as+// numbers, its textures as pictures. raea's engine translates the GLSL with naga and runs it with three's built-ins+// (raea-sys-three-shader), so the shader runs as written.+//+// What three puts on screen is what raea's engine shows: a ShaderMaterial's colour is the canvas's value unless it+// includes three's tone mapping, so it goes as "display" (the engine takes it back through Bevy's tone mapping); one+// that includes <tonemapping_fragment> on a tone-mapped material goes as "linear", those includes dropped, and Bevy's+// tone mapping maps it as three's would.+import * as THREE from "three";+import { srcOf } from "./texture";+import type { Part, Props } from "./material";++const hex = (c: THREE.Color) => "#" + c.getHexString();+const INCLUDE = /^[ \t]*#include +<([\w\d./]+)>/gm;++/** a shader's #includes expanded from three's chunks, as three's WebGLProgram does */+export function expandIncludes(src: string, depth = 0): string {+ if (depth > 16) throw new Error("raea/r3f: #include nested too deep");+ return src.replace(INCLUDE, (_m, name: string) => {+ const chunk = (THREE.ShaderChunk as Record<string, string>)[name];+ if (chunk === undefined) throw new Error(`raea/r3f: the shader includes <${name}>, which isn't one of three's chunks`);+ return expandIncludes(chunk, depth + 1);+ });+}++/**+ * A shader's #ifdef blocks decided where they can be: a condition made only of defined(X) / X tests (#ifdef, #ifndef,+ * #if and #elif with !, && and ||) is settled by `defines` (and the source's own #defines met on the way), its dead+ * branch dropped; any other condition (#if NUM_CLIPPING_PLANES > 0) is kept as written for the engine's preprocessor.+ * three's chunks guard what a material doesn't use (morph targets' MORPHTARGETS_COUNT arrays), which the engine reads+ * as declarations before preprocessing.+ */+export function decideIfdefs(src: string, defines: Set<string> | Map<string, string>): string {+ // what's defined, and the value it was given ("" when none)+ const known = new Map<string, string>(defines instanceof Map ? defines : [...defines].map((k) => [k, ""]));+ type Frame = { decided: boolean; live: boolean; taken: boolean; parentLive: boolean };+ const stack: Frame[] = [];+ const live = () => stack.every((f) => !f.decided || f.live);+ // a condition of defined(X), numbers and macros that are numbers, with ! && || and comparisons; undefined otherwise+ const evaluate = (expr: string): boolean | undefined => {+ let e = expr.replace(/\/\/.*$|\/\*.*?\*\//g, "").trim();+ e = e.replace(/defined\s*\(\s*(\w+)\s*\)|defined\s+(\w+)/g, (_m, a: string, b: string) => (known.has(a ?? b) ? "1" : "0"));+ let ok = true;+ e = e.replace(/[A-Za-z_]\w*/g, (n) => {+ const v = known.get(n);+ if (v === undefined || !/^-?\d+(\.\d+)?$/.test(v.trim())) ok = false;+ return v?.trim() ?? "0";+ });+ if (!ok || !/^[\s\d.!()&|<>=+-]*$/.test(e)) return undefined;+ try {+ return Boolean(Function(`return (${e})`)());+ } catch {+ return undefined;+ }+ };+ const out: string[] = [];+ for (const line of src.split("\n")) {+ const m = /^\s*#\s*(ifdef|ifndef|if|elif|else|endif|define|undef)\b\s*(.*)$/.exec(line);+ if (!m) {+ if (live()) out.push(line);+ continue;+ }+ const [, kind, rest] = m;+ const top = stack[stack.length - 1];+ if (kind === "ifdef" || kind === "ifndef" || kind === "if") {+ const v = kind === "ifdef" ? known.has(rest.trim().split(/\s/)[0]) : kind === "ifndef" ? !known.has(rest.trim().split(/\s/)[0]) : evaluate(rest);+ const parentLive = live();+ if (v === undefined) {+ stack.push({ decided: false, live: true, taken: false, parentLive });+ if (parentLive) out.push(line);+ } else stack.push({ decided: true, live: v, taken: v, parentLive });+ continue;+ }+ if (kind === "elif" && top) {+ if (!top.decided) {+ if (top.parentLive) out.push(line);+ continue;+ }+ const v = evaluate(rest);+ if (v === undefined) {+ // undecidable after a decided start: keep the rest for the engine, as an #if of its own+ top.decided = false;+ top.live = true;+ if (top.parentLive && !top.taken) out.push(line.replace(/#\s*elif/, "#if"));+ else if (top.parentLive) out.push("#if 0");+ continue;+ }+ top.live = !top.taken && v;+ top.taken ||= v;+ continue;+ }+ if (kind === "else" && top) {+ if (!top.decided) {+ if (top.parentLive) out.push(line);+ continue;+ }+ top.live = !top.taken;+ top.taken = true;+ continue;+ }+ if (kind === "endif" && top) {+ stack.pop();+ if (!top.decided && top.parentLive) out.push(line);+ continue;+ }+ if (live()) {+ out.push(line);+ if (kind === "define") {+ const [name, ...value] = rest.trim().split(/\s+/);+ known.set(name, value.join(" "));+ }+ if (kind === "undef") known.delete(rest.trim().split(/\s/)[0]);+ }+ }+ return out.join("\n");+}++/** three's sRGB encoding, which <colorspace_fragment> calls (three declares it in front of every fragment shader) */+const OUTPUT_TEXEL = "vec4 linearToOutputTexel(vec4 v) { return vec4(mix(pow(v.rgb, vec3(0.41666)) * 1.055 - vec3(0.055), v.rgb * 12.92, vec3(lessThanEqual(v.rgb, vec3(0.0031308)))), v.a); }\n";++/** a uniform's value as numbers (a texture is listed apart); undefined for one with nothing raea can send */+function valueOf(v: unknown): number | boolean | number[] | undefined {+ if (typeof v === "number" || typeof v === "boolean") return v;+ const o = v as { isColor?: boolean; isMatrix3?: boolean; isMatrix4?: boolean; isVector2?: boolean; isVector3?: boolean; isVector4?: boolean; isQuaternion?: boolean; r: number; g: number; b: number; elements: number[]; toArray(): number[] } | null;+ if (o?.isColor) return [o.r, o.g, o.b];+ if (o?.isMatrix3 || o?.isMatrix4) return [...o.elements];+ if (o?.isVector2 || o?.isVector3 || o?.isVector4 || o?.isQuaternion) return o.toArray();+ if (Array.isArray(v)) {+ const out: number[] = [];+ for (const x of v) {+ const e = valueOf(x);+ if (e === undefined) return undefined;+ if (Array.isArray(e)) out.push(...e);+ else out.push(Number(e));+ }+ return out;+ }+ if (ArrayBuffer.isView(v)) return Array.from(v as unknown as ArrayLike<number>);+ return undefined;+}++/** a picture three has no file for (a render target's): one white pixel, so the shader still runs */+const WHITE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";++const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++/** A ShaderMaterial as a <ThreeShaderMaterial> part. `points`: it draws three.js Points (each a quad here, its size+ * from gl_PointSize). */+export function shaderPart(m: THREE.ShaderMaterial, points = false): Part {+ const raw = (m as THREE.RawShaderMaterial).isRawShaderMaterial === true;+ const defines = Object.entries(m.defines ?? {}).filter(([, v]) => v !== false).map(([k, v]) => `#define ${k} ${v === true ? "" : v}`).join("\n");+ let vertex = expandIncludes(m.vertexShader);+ let fragment = expandIncludes(m.fragmentShader);+ // three's tone mapping, when the shader asks for it, is Bevy's here: the shader's colour is then scene light+ const tones = /#include +<tonemapping_fragment>/.test(m.fragmentShader) && m.toneMapped;+ if (tones) fragment = expandIncludes(m.fragmentShader.replace(/^[ \t]*#include +<(tonemapping_fragment|colorspace_fragment)>/gm, ""));+ else if (/#include +<tonemapping_fragment>/.test(m.fragmentShader)) fragment = expandIncludes(m.fragmentShader.replace(/^[ \t]*#include +<tonemapping_fragment>/gm, ""));+ // three's prefix in front of a ShaderMaterial (not a raw one): no clipping planes (raea cuts the mesh, clip.ts)+ const front = (raw ? "" : "#define NUM_CLIPPING_PLANES 0\n#define UNION_CLIPPING_PLANES 0\n") + (defines ? defines + "\n" : "");+ const on = new Map<string, string>(Object.entries(m.defines ?? {}).filter(([, v]) => v !== false).map(([k, v]) => [k, v === true ? "" : String(v)]));+ // naga's GLSL reads a parameter's `in` but not `const in` (three's <common> declares its helpers so)+ const params = (src: string) => src.replace(/([(,]\s*)const\s+in\s+/g, "$1in ");+ vertex = params(decideIfdefs(front + vertex, on));+ fragment = params(decideIfdefs(front + (raw ? "" : OUTPUT_TEXEL) + fragment, on));+ const uniforms: Record<string, number | boolean | number[]> = {};+ const textures: Record<string, string | { src: string; colorSpace: "linear" }> = {};+ const flipY: string[] = [];+ let color: string | undefined;+ for (const [name, u] of Object.entries(m.uniforms ?? {})) {+ const v = (u as THREE.IUniform | undefined)?.value;+ if ((v as THREE.Texture | null)?.isTexture) {+ const t = v as THREE.Texture;+ const src = srcOf(t);+ if (!src) warnOnce(`${m.type} texture ${name}`, "has no picture raea can load (a render target's?): drawn as white");+ // three samples a picture without a colour space raw, an sRGB one decoded (as Bevy's sRGB image is)+ textures[name] = src && t.colorSpace !== THREE.SRGBColorSpace ? { src, colorSpace: "linear" } : src ?? WHITE;+ if (t.flipY && src) flipY.push(name);+ continue;+ }+ if (v instanceof THREE.Color && !color && /^(u?[cC]olou?r|diffuse)$/.test(name)) color = hex(v);+ const n = valueOf(v);+ if (n === undefined) {+ if (v !== null && v !== undefined) warnOnce(`${m.type} uniform ${name}`, "isn't a number, vector, colour or matrix: left at zero");+ continue;+ }+ uniforms[name] = n;+ }+ const props: Props = {+ glsl: { vertex, fragment, raw, vertexColors: m.vertexColors === true, ...(points ? { points: true } : {}) },+ ...(flipY.length ? { flipY } : {}),+ uniforms,+ textures,+ output: tones ? "linear" : "display",+ side: m.side === THREE.BackSide ? "back" : m.side === THREE.DoubleSide ? "double" : "front",+ depthWrite: m.depthWrite,+ depthTest: m.depthTest,+ color: color ?? "#ffffff",+ };+ if (m.transparent) props.transparent = true;+ if (m.blending === THREE.AdditiveBlending) props.blending = "additive";+ else if (m.blending === THREE.MultiplyBlending) props.blending = "multiply";+ if (m.alphaTest > 0) props.alphaTest = m.alphaTest;+ return { type: "ThreeShaderMaterial", props };+}++/** whether a material is a ShaderMaterial (or Raw), which shaderPart draws */+export const isShader = (m: THREE.Material): m is THREE.ShaderMaterial => (m as THREE.ShaderMaterial).isShaderMaterial === true;++/** a geometry's own attributes (all but position, normal, uv and color) as a BufferMesh's `attributes` */+export function ownAttributes(g: THREE.BufferGeometry): Record<string, { size: number; values: number[] }> | undefined {+ const out: Record<string, { size: number; values: number[] }> = {};+ for (const [name, a] of Object.entries(g.attributes)) {+ if (["position", "normal", "uv", "color"].includes(name)) continue;+ const attr = a as THREE.BufferAttribute;+ if (attr.itemSize > 4) continue;+ const values: number[] = new Array(attr.count * attr.itemSize);+ for (let i = 0; i < attr.count; i++) for (let c = 0; c < attr.itemSize; c++) values[i * attr.itemSize + c] = attr.getComponent(i, c);+ out[name] = { size: attr.itemSize, values };+ }+ return Object.keys(out).length ? out : undefined;+}++/**+ * A built-in material three draws with a program of its own that needs no lights (matcap, normal) as raea's+ * <ThreeShaderMaterial> of that same program: three's ShaderLib source, the defines its WebGLProgram would set for+ * this material (map, matcap, flat shading, sides) and its uniforms, so it looks as three draws it.+ */+export function builtinPart(m: THREE.MeshMatcapMaterial | THREE.MeshNormalMaterial): Part {+ const lib = m.type === "MeshMatcapMaterial" ? THREE.ShaderLib.matcap : THREE.ShaderLib.normal;+ const uniforms = THREE.UniformsUtils.clone(lib.uniforms) as Record<string, THREE.IUniform>;+ const defines: Record<string, string | boolean> = {};+ if (m.flatShading) defines.FLAT_SHADED = true;+ if (m.side === THREE.DoubleSide) defines.DOUBLE_SIDED = true;+ if (m.side === THREE.BackSide) defines.FLIP_SIDED = true;+ uniforms.opacity.value = m.opacity;+ if (m.type === "MeshMatcapMaterial") {+ const mc = m as THREE.MeshMatcapMaterial;+ uniforms.diffuse.value = mc.color.clone();+ if (mc.matcap) {+ defines.USE_MATCAP = true;+ uniforms.matcap.value = mc.matcap;+ }+ if (mc.map) {+ defines.USE_MAP = true;+ defines.MAP_UV = "uv";+ mc.map.updateMatrix();+ uniforms.map.value = mc.map;+ uniforms.mapTransform.value = mc.map.matrix.clone();+ }+ }+ const sm = new THREE.ShaderMaterial({ uniforms, vertexShader: lib.vertexShader, fragmentShader: lib.fragmentShader, defines, transparent: m.transparent, side: m.side, toneMapped: m.toneMapped });+ sm.opacity = m.opacity;+ return shaderPart(sm);+}diff --git a/sdk/r3f/src/input/targets.ts b/sdk/r3f/src/input/targets.tsnew file mode 100644index 00000000..e8de75f8--- /dev/null+++ b/sdk/r3f/src/input/targets.ts@@ -0,0 +1,189 @@+// What an app draws into a render target itself, done on the CPU where it's a pass raea knows, so the picture a+// material shows from that target is there in raea's frame (docs/r3f.feature R3F13). raea's engine draws the scene;+// three never does, so a target an app fills in useFrame (gl.setRenderTarget(t); gl.render(...)) would otherwise+// be empty. The passes done here are the ones drei's <ContactShadows> makes, which are the common ones:+//+// a depth pass: the scene drawn with a MeshDepthMaterial as scene.overrideMaterial from an orthographic camera, as+// three draws it (no depth test, no blending: the last triangle drawn wins, opaque objects front to back), its+// colour plain depth or drei's tint (ucolor * z * 2, alpha 1 - z, read from the material's onBeforeCompile)+// a blur pass: three's HorizontalBlurShader or VerticalBlurShader (9 taps, h or v apart in uv) over a target+//+// Anything else drawn into a target is left out, with one warning: the target stays empty.+import * as THREE from "three";++/** a target's pixels: RGBA floats, row 0 at v = 0 (as three's targets hold them) */+interface Pixels {+ w: number;+ h: number;+ data: Float32Array;+}++const drawn = new WeakMap<THREE.Texture, Pixels>();+const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++/** raea's working size for a target (the passes are in uv, so a smaller one blurs the same) */+const MAX = 256;++function pixelsFor(rt: THREE.RenderTarget): Pixels {+ const w = Math.max(1, Math.min(MAX, rt.width)), h = Math.max(1, Math.min(MAX, rt.height));+ let p = drawn.get(rt.texture);+ if (!p || p.w !== w || p.h !== h) {+ p = { w, h, data: new Float32Array(w * h * 4) };+ drawn.set(rt.texture, p);+ }+ return p;+}++/** a target's picture as raea's frame shows it, or undefined when nothing raea knows was drawn into it */+export function targetPixels(t: THREE.Texture): Pixels | undefined {+ return drawn.get(t);+}++const BLUR = [0.051, 0.0918, 0.12245, 0.1531, 0.1633, 0.1531, 0.12245, 0.0918, 0.051];++/** `gl.render(scene, camera)` into `rt` (the stand-in renderer's), done here when it's a pass raea knows */+export function renderInto(rt: THREE.RenderTarget, scene: THREE.Object3D, camera: THREE.Camera, clear: [number, number, number, number]) {+ const out = pixelsFor(rt);+ const mat = (scene as THREE.Mesh).material as THREE.ShaderMaterial | undefined;+ const u = mat?.uniforms;+ if ((scene as THREE.Mesh).isMesh && u?.tDiffuse && ("h" in u || "v" in u)) {+ const src = u.tDiffuse.value as THREE.Texture | null;+ const from = src ? drawn.get(src) : undefined;+ if (from) blur(from, out, "h" in u ? Number(u.h.value) : 0, "v" in u ? Number(u.v.value) : 0);+ return;+ }+ const over = (scene as THREE.Scene).overrideMaterial;+ if ((scene as THREE.Scene).isScene && (over as THREE.MeshDepthMaterial | null)?.isMeshDepthMaterial && (camera as THREE.OrthographicCamera).isOrthographicCamera) {+ for (let i = 0; i < out.data.length; i += 4) out.data.set(clear, i);+ depth(scene as THREE.Scene, camera as THREE.OrthographicCamera, over as THREE.MeshDepthMaterial, out);+ return;+ }+ warnOnce(`a render into a target (${(scene as THREE.Mesh).type}${mat ? " with " + mat.type : ""})`, "isn't one raea draws (a depth pass or a blur): the target stays empty");+}++/** three's 9-tap blur, `h` and `v` apart in uv, sampled linearly with edges clamped */+function blur(from: Pixels, out: Pixels, h: number, v: number) {+ const src = from.data.slice();+ const { w, h: hh } = from;+ const res = new Float32Array(w * hh * 4);+ const dx = h * w, dy = v * hh;+ for (let y = 0; y < hh; y++) {+ for (let x = 0; x < w; x++) {+ const o = (y * w + x) * 4;+ for (let k = 0; k < 9; k++) {+ const wt = BLUR[k], s = k - 4;+ // the texel centre's sample position, in texels+ const fx = Math.min(w - 1, Math.max(0, x + s * dx)), fy = Math.min(hh - 1, Math.max(0, y + s * dy));+ const x0 = Math.floor(fx), y0 = Math.floor(fy), x1 = Math.min(w - 1, x0 + 1), y1 = Math.min(hh - 1, y0 + 1);+ const tx = fx - x0, ty = fy - y0;+ const a = (y0 * w + x0) * 4, b = (y0 * w + x1) * 4, c = (y1 * w + x0) * 4, d = (y1 * w + x1) * 4;+ for (let ch = 0; ch < 4; ch++) {+ const top = src[a + ch] * (1 - tx) + src[b + ch] * tx, bot = src[c + ch] * (1 - tx) + src[d + ch] * tx;+ res[o + ch] += wt * (top * (1 - ty) + bot * ty);+ }+ }+ }+ }+ if (out.w === w && out.h === hh) out.data.set(res);+}++/** the depth material's colour for depth z (0 near, 1 far): drei's tint when its onBeforeCompile puts one in */+function depthColour(m: THREE.MeshDepthMaterial): (z: number, px: Float32Array, o: number) => void {+ const shader = { uniforms: {} as Record<string, { value: unknown }>, vertexShader: "", fragmentShader: "void main() {\n\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n}" };+ try {+ m.onBeforeCompile?.(shader as unknown as THREE.WebGLProgramParametersWithUniforms, undefined as unknown as THREE.WebGLRenderer);+ } catch {+ // its patch asked for what the stand-in shader hasn't: plain depth+ }+ const tint = shader.uniforms.ucolor?.value as THREE.Color | undefined;+ if (tint && /ucolor \* fragCoordZ \* 2\.0, \( 1\.0 - fragCoordZ \)/.test(shader.fragmentShader)) {+ const { r, g, b } = tint;+ return (z, px, o) => {+ px[o] = r * z * 2;+ px[o + 1] = g * z * 2;+ px[o + 2] = b * z * 2;+ px[o + 3] = 1 - z;+ };+ }+ const a = m.opacity;+ return (z, px, o) => {+ px[o] = px[o + 1] = px[o + 2] = 1 - z;+ px[o + 3] = a;+ };+}++const v = new THREE.Vector3();+const mvp = new THREE.Matrix4();++/** the scene's meshes drawn as `m` from `cam` into `out`, as three would: front faces only, no depth test */+function depth(scene: THREE.Scene, cam: THREE.OrthographicCamera, m: THREE.MeshDepthMaterial, out: Pixels) {+ scene.updateMatrixWorld();+ cam.updateMatrixWorld();+ cam.updateProjectionMatrix();+ const colour = depthColour(m);+ const meshes: { mesh: THREE.Mesh; z: number }[] = [];+ const visit = (o: THREE.Object3D) => {+ if (!o.visible) return;+ const mesh = o as THREE.Mesh;+ if (mesh.isMesh && !(mesh as unknown as THREE.Points).isPoints && mesh.geometry?.attributes?.position) {+ v.setFromMatrixPosition(mesh.matrixWorld).applyMatrix4(cam.matrixWorldInverse);+ meshes.push({ mesh, z: -v.z });+ }+ for (const c of o.children) visit(c);+ };+ visit(scene);+ // three draws opaque objects front to back (its painter sort, by renderOrder, then distance)+ meshes.sort((a, b) => a.mesh.renderOrder - b.mesh.renderOrder || a.z - b.z);+ const { w, h, data } = out;+ const near = cam.near, far = cam.far;+ const sx = new Float32Array(3), sy = new Float32Array(3), sz = new Float32Array(3);+ const inst = new THREE.Matrix4();+ for (const { mesh } of meshes) {+ const pos = mesh.geometry.attributes.position as THREE.BufferAttribute;+ const index = mesh.geometry.index;+ const n = index ? index.count : pos.count;+ const im = mesh as THREE.InstancedMesh;+ const count = im.isInstancedMesh ? im.count : 1;+ for (let k = 0; k < count; k++) {+ mvp.multiplyMatrices(cam.matrixWorldInverse, mesh.matrixWorld);+ if (im.isInstancedMesh) {+ im.getMatrixAt(k, inst);+ mvp.multiply(inst);+ }+ const flip = mvp.determinant() < 0;+ for (let t = 0; t + 2 < n; t += 3) {+ for (let j = 0; j < 3; j++) {+ const i = index ? index.getX(t + j) : t + j;+ v.fromBufferAttribute(pos, i).applyMatrix4(mvp);+ // view space to the target's pixels (x right, y up from row 0) and depth 0..1 from near to far+ sx[j] = ((v.x - cam.left) / (cam.right - cam.left)) * w;+ sy[j] = ((v.y - cam.bottom) / (cam.top - cam.bottom)) * h;+ sz[j] = (-v.z - near) / (far - near);+ }+ const area = (sx[1] - sx[0]) * (sy[2] - sy[0]) - (sx[2] - sx[0]) * (sy[1] - sy[0]);+ // a front face winds counter-clockwise on screen (and the other way under a mirroring matrix)+ if (area === 0 || (area > 0) === flip) continue;+ const x0 = Math.max(0, Math.floor(Math.min(sx[0], sx[1], sx[2]))), x1 = Math.min(w - 1, Math.ceil(Math.max(sx[0], sx[1], sx[2])));+ const y0 = Math.max(0, Math.floor(Math.min(sy[0], sy[1], sy[2]))), y1 = Math.min(h - 1, Math.ceil(Math.max(sy[0], sy[1], sy[2])));+ for (let y = y0; y <= y1; y++) {+ const py = y + 0.5;+ for (let x = x0; x <= x1; x++) {+ const px = x + 0.5;+ const w0 = ((sx[1] - px) * (sy[2] - py) - (sx[2] - px) * (sy[1] - py)) / area;+ const w1 = ((sx[2] - px) * (sy[0] - py) - (sx[0] - px) * (sy[2] - py)) / area;+ const w2 = 1 - w0 - w1;+ if (w0 < 0 || w1 < 0 || w2 < 0) continue;+ const z = w0 * sz[0] + w1 * sz[1] + w2 * sz[2];+ if (z < 0 || z > 1) continue;+ colour(z, data, (y * w + x) * 4);+ }+ }+ }+ }+ }+}diff --git a/sdk/r3f/src/input/text.ts b/sdk/r3f/src/input/text.tsnew file mode 100644index 00000000..6fb29664--- /dev/null+++ b/sdk/r3f/src/input/text.ts@@ -0,0 +1,132 @@+// troika's Text (drei's <Text>, and anything else built on troika-three-text) as raea's <RichText> (docs/r3f.feature+// R3F13): raea lays out and draws the words itself, with the face troika was given found by its family name, so the+// SDF atlas, the worker and troika's shader never run. In a native render the Text is troika.ts's stand-in, which+// holds the same settings; in a browser it's troika's own, read the same way.+//+// What's carried: the text, the size (fontSize is the em), the face's family and weight, the colour and opacity, the+// line height, maxWidth, textAlign, and the anchors (anchorX left/center/right as RichText's align, anchorY as an+// offset from the block's middle). Lit when troika's material is (a MeshStandardMaterial given as `material`),+// unlit as troika's own MeshBasicMaterial. Outlines, strokes, curveRadius and colorRanges are left out, named once.+import * as THREE from "three";+import type { Part, Props } from "./material";++/** a troika Text, real or stood in */+export interface TroikaText extends THREE.Mesh {+ isTroikaText: true;+ text: string;+ font: string | null;+ fontSize: number;+ fontWeight: number | string;+ fontStyle: string;+ color: THREE.ColorRepresentation | null;+ anchorX: number | string;+ anchorY: number | string;+ lineHeight: number | string;+ maxWidth: number;+ textAlign: string;+ fillOpacity: number;+ outlineWidth: number | string;+ strokeWidth: number | string;+ curveRadius: number;+ colorRanges: unknown;+}++export const isTroikaText = (o: THREE.Object3D): o is TroikaText => (o as Partial<TroikaText>).isTroikaText === true && typeof (o as TroikaText).text === "string";++const warned = new Set<string>();+function warnOnce(k: string, why: string) {+ if (warned.has(k)) return;+ warned.add(k);+ console.warn(`raea/r3f: ${k} ${why}`);+}++const families = new Map<string, string>();++/** a font file's family (its name table's typographic family, else its family), read once */+function familyOf(src: string): string {+ const had = families.get(src);+ if (had) return had;+ let family: string | undefined;+ const call = (globalThis as { __raea_call?: (n: string, a: string) => string | undefined }).__raea_call;+ if (typeof call === "function" && !src.startsWith("data:")) {+ try {+ const out = call("asset.read", JSON.stringify({ path: src }));+ const b64 = out ? (JSON.parse(out) as { base64?: string }).base64 : undefined;+ if (b64) family = nameOf(Uint8Array.from(atob(b64), (c) => c.charCodeAt(0)));+ } catch {+ // not readable here: the file's own name below+ }+ }+ // Inter-400.ttf, Roboto_Bold.woff: the name before its style+ family ??= (src.split(/[?#]/)[0].split("/").pop() ?? "").replace(/\.\w+$/, "").split(/[-_]/)[0] || "Inter";+ families.set(src, family);+ return family;+}++/** an OpenType font's family from its name table (16, else 1; Windows' UTF-16 or Mac's Roman), undefined for a WOFF2 */+function nameOf(b: Uint8Array): string | undefined {+ const dv = new DataView(b.buffer, b.byteOffset, b.byteLength);+ if (b.length < 12) return undefined;+ const tables = dv.getUint16(4);+ for (let i = 0; i < tables; i++) {+ const at = 12 + i * 16;+ if (String.fromCharCode(b[at], b[at + 1], b[at + 2], b[at + 3]) !== "name") continue;+ const off = dv.getUint32(at + 8);+ const count = dv.getUint16(off + 2), strings = off + dv.getUint16(off + 4);+ const found: Record<number, string> = {};+ for (let r = 0; r < count; r++) {+ const rec = off + 6 + r * 12;+ const platform = dv.getUint16(rec), id = dv.getUint16(rec + 6), len = dv.getUint16(rec + 8), o = strings + dv.getUint16(rec + 10);+ if ((id !== 1 && id !== 16) || found[id]) continue;+ if (platform === 3 || platform === 0) {+ let s = "";+ for (let k = 0; k + 1 < len; k += 2) s += String.fromCharCode(dv.getUint16(o + k));+ found[id] = s;+ } else if (platform === 1) found[id] = String.fromCharCode(...b.subarray(o, o + len));+ }+ return found[16] || found[1];+ }+ return undefined;+}++const weightOf = (w: number | string) => (typeof w === "number" ? w : w === "bold" ? 700 : /^\d+$/.test(w) ? Number(w) : 400);++const hex = (c: THREE.Color) => `#${c.getHexString()}`;++/** the Text as a RichText in its own place (the walk puts its transform on a group around it) */+export function textParts(t: TroikaText, name: string): Part[] {+ const words = t.text;+ if (!words.trim()) return [];+ for (const [k, on] of [["outlineWidth", t.outlineWidth !== 0], ["strokeWidth", t.strokeWidth !== 0], ["curveRadius", t.curveRadius !== 0], ["colorRanges", t.colorRanges != null]] as const) {+ if (on) warnOnce(`<Text> ${k}`, "isn't drawn by raea's text: left out");+ }+ const mat = (Array.isArray(t.material) ? t.material[0] : t.material) as THREE.MeshBasicMaterial | THREE.MeshStandardMaterial;+ const colour = t.color != null ? new THREE.Color(t.color) : mat?.color ?? new THREE.Color(1, 1, 1);+ const size = t.fontSize;+ const lineHeight = typeof t.lineHeight === "number" ? t.lineHeight : 1.2;+ const props: Props = { name, size, color: hex(colour), lineHeight, weight: weightOf(t.fontWeight), unlit: !(mat as THREE.MeshStandardMaterial)?.isMeshStandardMaterial, castShadow: t.castShadow, receiveShadow: t.receiveShadow };+ if (t.font) props.font = familyOf(t.font);+ if (t.fontStyle === "italic") props.italic = true;+ const opacity = t.fillOpacity * (mat?.opacity ?? 1);+ if (opacity < 1) props.opacity = opacity;+ if (Number.isFinite(t.maxWidth)) props.maxWidth = t.maxWidth;+ // anchorX: RichText's origin is the lines' left, middle or right; a number or a percentage shifts from the left+ const ax = t.anchorX;+ const pos: [number, number, number] = [0, 0, 0];+ if (ax === "center" || ax === "right" || ax === "left") props.align = ax;+ else {+ props.align = "left";+ pos[0] = -(typeof ax === "number" ? ax : 0);+ if (typeof ax === "string" && ax.endsWith("%")) warnOnce("<Text> anchorX as a percentage", "is drawn from the left edge");+ }+ // anchorY: RichText's origin is the block's middle; the block is its lines' height+ const lines = words.split("\n").length;+ const half = (lines * lineHeight * size) / 2;+ const ay = t.anchorY;+ if (ay === "top" || ay === "top-baseline") pos[1] = -half;+ else if (ay === "bottom" || ay === "bottom-baseline") pos[1] = half;+ else if (typeof ay === "number") pos[1] = -half - ay;+ if (pos[0] || pos[1]) props.position = pos;+ props.children = words;+ return [{ type: "RichText", props }];+}diff --git a/sdk/r3f/src/input/texture.ts b/sdk/r3f/src/input/texture.tsindex 6580078d..ca4454bb 100644--- a/sdk/r3f/src/input/texture.ts+++ b/sdk/r3f/src/input/texture.ts@@ -3,6 +3,7 @@// native render, where there's no DOM to load an <img> into, three's ImageLoader is stood in for by one that hands// back the url (with the picture's size unknown) and the engine loads that file.import * as THREE from "three";+import { targetPixels } from "./targets";const urls = new WeakMap<object, string>();@@ -15,13 +16,132 @@ export function standInImages() {const img = { src, width: 1, height: 1, naturalWidth: 1, naturalHeight: 1, complete: true } as unknown as HTMLImageElement;urls.set(img, src);this.manager.itemStart(src);- queueMicrotask(() => {+ // at once: raea reads a frame's scene in the same turn its components render, so a picture handed over later+ // is missing from the frame (lettra's atlas, any TextureLoader.load). A callback that reads the variable its own+ // load is assigned to can't run yet: it runs once the load has returned.+ try {onLoad?.(img);this.manager.itemEnd(src);- });+ } catch (e) {+ if (!(e instanceof ReferenceError)) throw e;+ queueMicrotask(() => {+ onLoad?.(img);+ this.manager.itemEnd(src);+ });+ }return img;};THREE.ImageLoader.prototype.load = load as unknown as THREE.ImageLoader["load"];+ standInFiles();+}++/** a raea native call, where the host has them (a render, a play) */+function native<T>(name: string, args: unknown): T | undefined {+ const call = (globalThis as { __raea_call?: (n: string, a: string) => string | undefined }).__raea_call;+ if (typeof call !== "function") return undefined;+ const out = call(name, JSON.stringify(args));+ if (typeof out !== "string") return undefined;+ const v = JSON.parse(out) as T | { error: string };+ if (v && typeof v === "object" && "error" in v && typeof (v as { error: unknown }).error === "string") throw new Error((v as { error: string }).error);+ return v as T;+}++/** onLoad now (raea reads the frame's scene in this turn), or once the load has returned when it reads that load */+function settle(run: () => void) {+ try {+ run();+ } catch (e) {+ if (!(e instanceof ReferenceError)) throw e;+ queueMicrotask(run);+ }+}++function bytesFromBase64(s: string): Uint8Array {+ const at = new Int16Array(128).fill(-1);+ for (let i = 0; i < 64; i++) at[B64.charCodeAt(i)] = i;+ const clean = s.replace(/=+$/, "");+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));+ let o = 0, acc = 0, bits = 0;+ for (let i = 0; i < clean.length; i++) {+ acc = (acc << 6) | at[clean.charCodeAt(i)];+ bits += 6;+ if (bits >= 8) {+ bits -= 8;+ out[o++] = (acc >> bits) & 0xff;+ }+ }+ return out;+}++/**+ * three's file loads where the engine has no fetch (a native render's JS thread): FileLoader reads the file (a path,+ * or an http(s) URL through raea's cache) by the host's `asset.read`, so a glTF (useGLTF), a font or a JSON is parsed+ * in this turn; a DataTextureLoader's (HDR, EXR: drei's <Environment>) texture is a stand-in carrying the cached+ * file's path, which raea's engine loads itself (lights.ts reads it as <Environment src>).+ */+function standInFiles() {+ if (typeof (globalThis as { Request?: unknown }).Request === "function") return;+ if (typeof (globalThis as { __raea_call?: unknown }).__raea_call !== "function") return;+ const fileLoad = function (this: THREE.FileLoader, url: string, onLoad?: (data: unknown) => void, _onProgress?: unknown, onError?: (e: unknown) => void) {+ const src = this.manager.resolveURL((this.path ?? "") + url);+ this.manager.itemStart(src);+ let data: unknown;+ try {+ if (src.startsWith("data:")) {+ const [head, body] = [src.slice(5, src.indexOf(",")), src.slice(src.indexOf(",") + 1)];+ const raw = head.endsWith(";base64") ? bytesFromBase64(body) : new TextEncoder().encode(decodeURIComponent(body));+ data = raw;+ } else {+ const got = native<{ base64: string }>("asset.read", { path: src });+ if (!got) throw new Error(`${src}: the host can't read files`);+ data = bytesFromBase64(got.base64);+ }+ const bytes = data as Uint8Array;+ const type = this.responseType;+ if (type === "arraybuffer") data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);+ else if (type === "json") data = JSON.parse(new TextDecoder().decode(bytes));+ else if (type === "blob") data = new Blob([bytes as BlobPart]);+ else data = new TextDecoder().decode(bytes);+ } catch (e) {+ settle(() => {+ onError?.(e);+ this.manager.itemError(src);+ this.manager.itemEnd(src);+ });+ return;+ }+ settle(() => {+ onLoad?.(data);+ this.manager.itemEnd(src);+ });+ };+ THREE.FileLoader.prototype.load = fileLoad as unknown as THREE.FileLoader["load"];++ const dataLoad = function (this: THREE.DataTextureLoader, url: string, onLoad?: (t: THREE.DataTexture, d: unknown) => void, _onProgress?: unknown, onError?: (e: unknown) => void) {+ const src = this.manager.resolveURL((this.path ?? "") + url);+ const texture = new THREE.DataTexture(new Float32Array([0.5, 0.5, 0.5, 1]), 1, 1, THREE.RGBAFormat, THREE.FloatType);+ this.manager.itemStart(src);+ try {+ // the cached file when it's a URL (raea's engine reads paths); the file as found when it's a path+ const got = native<{ path: string }>("asset.load", { path: src });+ texture.userData.src = got?.path ?? src;+ } catch (e) {+ settle(() => {+ onError?.(e);+ this.manager.itemError(src);+ this.manager.itemEnd(src);+ });+ return texture;+ }+ texture.colorSpace = THREE.LinearSRGBColorSpace;+ texture.needsUpdate = true;+ settle(() => {+ onLoad?.(texture, { width: 1, height: 1 });+ this.manager.itemEnd(src);+ });+ return texture;+ };+ THREE.DataTextureLoader.prototype.load = dataLoad as unknown as THREE.DataTextureLoader["load"];}// ---- PNG, uncompressed (stored deflate blocks): small code, and the pictures made in code are small ----@@ -132,6 +252,14 @@ function bytesOf(t: THREE.DataTexture): Uint8Array | undefined {/** a texture's picture for raea, or undefined when it has none raea can load (a render target, a video) */export function srcOf(t: THREE.Texture | null | undefined): string | undefined {if (!t) return undefined;+ // a render target the app drew into with a pass raea does on the CPU (targets.ts): its picture now+ const drawn = targetPixels(t);+ if (drawn) {+ const bytes = new Uint8Array(drawn.w * drawn.h * 4);+ for (let i = 0; i < bytes.length; i++) bytes[i] = Math.round(Math.min(1, Math.max(0, drawn.data[i])) * 255);+ // row 0 at v = 0: a target isn't flipped in y (its uvs reach raea as three gives them), so it's the PNG's top row+ return pngOf(bytes, drawn.w, drawn.h);+ }const given = t.userData?.src;if (typeof given === "string") return given;const img = t.image as { src?: string; toDataURL?: () => string; data?: unknown } | undefined;diff --git a/sdk/r3f/src/input/troika.ts b/sdk/r3f/src/input/troika.tsnew file mode 100644index 00000000..c7614318--- /dev/null+++ b/sdk/r3f/src/input/troika.ts@@ -0,0 +1,116 @@+// troika-three-text as raea's bundler gives it to a native bundle (engine/bundle's stand-ins): troika lays text out+// in a web worker, fetches its fonts by XMLHttpRequest and draws an SDF atlas on a canvas, none of which a native+// render's JS has, and raea draws text itself. So its Text here is a mesh that holds the same settings (text, font,+// fontSize, anchors, colour ...) and draws nothing; sync() and preloadFont() answer at once. text.ts reads it, as it+// reads troika's own Text in a browser, as raea's <RichText>. drei's <Text> and anything else built on troika's Text+// work unchanged.+import * as THREE from "three";++type Done = () => void;++/** troika's Text: its settings, drawn by raea (text.ts) */+export class Text extends THREE.Mesh {+ readonly isTroikaText = true;+ text = "";+ anchorX: number | string = 0;+ anchorY: number | string = 0;+ curveRadius = 0;+ direction = "auto";+ font: string | null = null;+ unicodeFontsURL: string | null = null;+ fontSize = 0.1;+ fontWeight: number | string = "normal";+ fontStyle = "normal";+ lang: string | null = null;+ letterSpacing = 0;+ lineHeight: number | string = "normal";+ maxWidth = Infinity;+ overflowWrap = "normal";+ textAlign = "left";+ textIndent = 0;+ whiteSpace = "normal";+ color: THREE.ColorRepresentation | null = null;+ colorRanges: unknown = null;+ outlineWidth: number | string = 0;+ outlineColor: THREE.ColorRepresentation = 0x000000;+ outlineOpacity = 1;+ outlineBlur: number | string = 0;+ outlineOffsetX: number | string = 0;+ outlineOffsetY: number | string = 0;+ strokeWidth: number | string = 0;+ strokeColor: THREE.ColorRepresentation = 0x808080;+ strokeOpacity = 1;+ fillOpacity = 1;+ depthOffset = 0;+ clipRect: unknown = null;+ orientation = "+x+y";+ glyphGeometryDetail = 1;+ sdfGlyphSize: number | null = null;+ gpuAccelerateSDF = true;+ debugSDF = false;+ textRenderInfo: unknown = null;++ constructor() {+ super(new THREE.BufferGeometry(), new THREE.MeshBasicMaterial({ color: 0xffffff, side: THREE.DoubleSide, transparent: true }));+ }++ /** laid out at once: raea lays the text out as it draws it */+ sync(callback?: Done) {+ callback?.();+ }++ dispose() {+ this.geometry.dispose();+ }++ localPositionToTextCoords(position: THREE.Vector3, target = new THREE.Vector2()) {+ return target.set(position.x, position.y);+ }++ worldPositionToTextCoords(position: THREE.Vector3, target = new THREE.Vector2()) {+ const p = this.worldToLocal(position.clone());+ return target.set(p.x, p.y);+ }+}++/** troika's BatchedText: a group of Texts, each drawn as its own */+export class BatchedText extends THREE.Group {+ readonly isBatchedText = true;+ addText(t: Text) {+ this.add(t);+ }+ removeText(t: Text) {+ this.remove(t);+ }+ sync(callback?: Done) {+ callback?.();+ }+}++/** the font is raea's to load: nothing to wait for */+export function preloadFont(_o: { font?: string; characters?: string | string[]; sdfGlyphSize?: number }, callback?: Done) {+ callback?.();+}++export function configureTextBuilder(_config: Record<string, unknown>) {}++export function getTextRenderInfo(_args: unknown, callback?: (info: unknown) => void) {+ callback?.({ parameters: _args, sdfTexture: null, glyphBounds: new Float32Array(), blockBounds: [0, 0, 0, 0], visibleBounds: [0, 0, 0, 0] });+}++export function getCaretAtPoint() {+ return null;+}++export function getSelectionRects() {+ return [];+}++export function createTextDerivedMaterial(base: THREE.Material) {+ return base;+}++export function dumpSDFTextures() {}++export const fontResolverWorkerModule = null;+export const typesetterWorkerModule = null;diff --git a/sdk/r3f/src/input/tsl.ts b/sdk/r3f/src/input/tsl.tsnew file mode 100644index 00000000..6a73a59e--- /dev/null+++ b/sdk/r3f/src/input/tsl.ts@@ -0,0 +1,484 @@+// A TSL node material (three/webgpu: MeshBasicNodeMaterial with a colorNode, lettra's MSDF text, any library built on+// TSL) as raea's ThreeShaderMaterial: three compiles the node graph to WGSL with its own WGSLNodeBuilder, run headless+// against a stand-in WebGPURenderer (it is asked for features and a node library, never to draw), and the WGSL is+// rewritten to the engine's contract (systems/three-shader):+// the vertex stage fn three_vertex(v: ThreeVertex) -> ThreeVaryings+// the fragment stage fn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> (linear: `output: "linear"`)+// both declare struct ThreeVaryings { @builtin(position) clip: vec4<f32>, @location(0) ... }+// three's uniform groups and textures become the prelude's u_NAME() accessors (64 vec4 slots) and tex_NAME/samp_NAME;+// the camera's projection and view and the model's world matrix become three_projection(), three_view() and+// three_model(instance), so Bevy's own camera and transform place it (Bevy's projection is reverse-Z). Every other+// uniform takes the value three's own node updates give it this frame (time from R3F's clock, a light's colour), so a+// uniform the scene animates in useFrame moves with it. A uniformArray is packed element by element and read as+// u_NAME(i); a vertex attribute of the mesh's own is one of the contract's a0..a3. A graph this can't carry (more than 4+// textures or 4 attributes of the mesh's own, a storage buffer, a render target) is refused with the reason, and the+// material is drawn flat as before.+import * as THREE from "three";+import { ModelNode, NodeFrame, WebGPURenderer } from "three/webgpu";+import type { Part, Props } from "./material";+import { srcOf } from "./texture";++/** what a node material is drawn for this frame: the object it's on, its scene and camera, R3F's clock */+export interface NodeAt {+ object: THREE.Object3D;+ scene: THREE.Scene;+ camera: THREE.Camera;+ /** R3F's clock, seconds (TSL's `time`) */+ time: number;+ /** seconds since the last frame (TSL's `deltaTime`) */+ delta?: number;+}++export interface ShaderUniform {+ name: string;+ type: string;+ value: number[];+ array?: number;+}+export interface ShaderTexture {+ name: string;+ src: string;+ colorSpace: "srgb" | "linear";+}+export interface ShaderSpec {+ vertex: string;+ fragment: string;+ uniforms: ShaderUniform[];+ textures: ShaderTexture[];+}++/** the engine's limits (systems/three-shader) */+export const SLOTS = 64;+export const TEXTURES = 4;++type AnyNode = { isNode?: boolean; name?: string; value?: unknown; uniformNode?: AnyNode; scope?: string };+interface NodeUniformLike { name: string; nodeUniform?: { node: AnyNode; value: unknown } }+interface BindingLike { name: string; isNodeUniformsGroup?: boolean; isSampledTexture?: boolean; isSampler?: boolean; isStorageBuffer?: boolean; isBuffer?: boolean; uniforms?: NodeUniformLike[]; texture?: THREE.Texture; isSampledCubeTexture?: boolean; isSampledTexture3D?: boolean }+interface Builder {+ scene: THREE.Scene;+ camera: THREE.Camera;+ material: THREE.Material;+ context: { material?: THREE.Material };+ lightsNode?: unknown;+ vertexShader: string;+ fragmentShader: string;+ updateNodes: AnyNode[];+ updateBeforeNodes: AnyNode[];+ updateAfterNodes: AnyNode[];+ build(): void;+ getBindings(): { name: string; bindings: BindingLike[] }[];+}++/** a refusal: what the graph needs that the engine's contract doesn't carry */+export class Unsupported extends Error {}++// ---- the stand-in renderer ----++let renderer: WebGPURenderer | undefined;++/** three's WebGPURenderer, never initialised: WGSLNodeBuilder reads its node library and asks it what the GPU can do */+function standIn(fresh = false): WebGPURenderer {+ if (renderer && !fresh) return renderer;+ const noop = () => {};+ const canvas = { style: {}, width: 1, height: 1, addEventListener: noop, removeEventListener: noop, getContext: () => null };+ const r = new WebGPURenderer({ canvas: canvas as unknown as HTMLCanvasElement });+ const own = r as unknown as Record<string, unknown>;+ // a builder asks before it is built; nothing here runs on a GPU, and Bevy has what these name+ own._initialized = true;+ own.hasFeature = () => false;+ own.hasCompatibility = () => true;+ // no shadow maps: a shadow in three's graph would be a depth texture raea doesn't fill (raea's own lights cast)+ r.shadowMap.enabled = false;+ if (fresh) return r;+ return (renderer = r);+}++// ---- compiling a graph ----++interface Compiled {+ key: string;+ builder: Builder;+ vertex: string;+ fragment: string;+ /** each packed uniform: its accessor name, type, slot count and how its value is read */+ uniforms: { name: string; type: string; array?: number; read: () => unknown; stored: "f32" | "u32" | "bool" }[];+ textures: { name: string; texture: THREE.Texture }[];+ /** the mesh's own attributes it reads, in order (the contract's a0..a3) */+ attributes: string[];+ frame: NodeFrame;+}++const compiled = new WeakMap<THREE.Material, Compiled>();++/** what a compile depends on beyond the material: the geometry's attributes (a graph reads the ones it has) */+function keyOf(m: THREE.Material, o: THREE.Object3D): string {+ const g = (o as THREE.Mesh).geometry as THREE.BufferGeometry | undefined;+ return `${m.version}|${g ? Object.keys(g.attributes).sort().join(",") : ""}|${(o as THREE.InstancedMesh).isInstancedMesh ? "i" : ""}`;+}++function compile(m: THREE.Material, at: NodeAt): Compiled {+ const key = keyOf(m, at.object);+ const had = compiled.get(m);+ if (had && had.key === key) return had;+ // a renderer of its own: three caches a shared group's binding (render, frame) per renderer, with the uniforms of+ // whichever material built it first+ const r = standIn(true);+ const b = (r as unknown as { backend: { createNodeBuilder(o: THREE.Object3D, r: WebGPURenderer): Builder } }).backend.createNodeBuilder(at.object, r);+ b.scene = at.scene;+ b.camera = at.camera;+ b.material = m;+ b.context.material = m;+ // a lit node material is lit by three's own light nodes, their colours and places this frame's+ if ((m as unknown as { lights?: boolean }).lights) b.lightsNode = (r as unknown as { lighting: { getNode(s: THREE.Scene, c: THREE.Camera): unknown } }).lighting.getNode(at.scene, at.camera);+ const errors: string[] = [];+ const err = console.error;+ console.error = (...a: unknown[]) => errors.push(a.map(String).join(" "));+ try {+ b.build();+ } finally {+ console.error = err;+ }+ if (errors.length) throw new Unsupported(`three couldn't build its graph: ${errors[0]}`);+ if (b.updateBeforeNodes.length || b.updateAfterNodes.length) throw new Unsupported("it renders the scene again first (a reflector, a render target, a pass): raea draws one scene");+ const c = rewrite(b);+ const out: Compiled = { key, builder: b, ...c, frame: new NodeFrame() };+ compiled.set(m, out);+ return out;+}++// ---- the WGSL, rewritten to the contract ----++/** the struct member types of every `struct NAME { ... }` in a source */+function structs(src: string): Map<string, Map<string, string>> {+ const out = new Map<string, Map<string, string>>();+ for (const s of src.matchAll(/struct\s+(\w+)\s*\{([^}]*)\}/g)) {+ const fields = new Map<string, string>();+ for (const f of s[2].split(",")) {+ const m = f.replace(/@\w+\s*\([^)]*\)/g, "").trim().match(/^(\w+)\s*:\s*(.+)$/);+ if (m) fields.set(m[1], m[2].trim());+ }+ out.set(s[1], fields);+ }+ return out;+}++/** `name` as a whole word in `src`, replaced (WGSL words: letters, digits, underscore) */+function word(src: string, name: string, to: string): string {+ return src.replace(new RegExp(`(?<![A-Za-z0-9_])${name}(?![A-Za-z0-9_])`, "g"), to);+}++/** each call of `fn` whose first argument is one of `textures`, its coordinate (third argument) flipped in v */+function flipSamples(src: string, flipped: Set<string>): string {+ if (!flipped.size) return src;+ let out = "";+ let i = 0;+ const re = /\b(textureSample\w*)\s*\(/g;+ let m: RegExpExecArray | null;+ while ((m = re.exec(src))) {+ const open = m.index + m[0].length;+ // the call's arguments, split at its own top-level commas+ const args: [number, number][] = [];+ let depth = 0, start = open, j = open;+ for (; j < src.length; j++) {+ const ch = src[j];+ if (ch === "(" || ch === "[") depth++;+ else if (ch === ")" || ch === "]") {+ if (depth === 0) break;+ depth--;+ } else if (ch === "," && depth === 0) {+ args.push([start, j]);+ start = j + 1;+ }+ }+ args.push([start, j]);+ const tex = src.slice(args[0][0], args[0][1]).trim();+ if (args.length < 3 || !flipped.has(tex)) continue;+ const [a, z] = args[2];+ out += src.slice(i, a) + ` tsl_flip_v( ${src.slice(a, z).trim()} )`;+ i = z;+ }+ return out + src.slice(i);+}++const FLIP = "fn tsl_flip_v(c: vec2<f32>) -> vec2<f32> { return vec2<f32>(c.x, 1.0 - c.y); }\n";++/** the contract's vertex attributes (ThreeVertex), by three's attribute name */+const ATTRIBUTES: Record<string, { field: string; type: string }> = {+ position: { field: "position", type: "vec3<f32>" },+ normal: { field: "normal", type: "vec3<f32>" },+ uv: { field: "uv", type: "vec2<f32>" },+ color: { field: "color", type: "vec4<f32>" },+};++/** a value of `type` read as `field` (a vec4 colour as a vec3 three declared, say) */+function fit(field: string, from: string, to: string): string {+ if (from === to) return field;+ const n = (t: string) => Number(t.match(/^vec(\d)/)?.[1] ?? 1);+ if (to.startsWith("vec") && from.startsWith("vec") && n(to) < n(from)) return `${field}.${"xyzw".slice(0, n(to))}`;+ if (from.startsWith("vec") && (to === "f32" || to === "i32" || to === "u32")) return to === "f32" ? `${field}.x` : `${to}(${field}.x)`;+ throw new Unsupported(`an attribute declared ${to} where raea gives ${from}`);+}++/** a uniform's slot count in vec4s */+const slotsOf = (type: string, array = 1) => (type.startsWith("mat4") ? 4 : type.startsWith("mat3") ? 3 : 1) * array;++/** a uniformArray's element type (three's name) as WGSL's */+const ELEMENT: Record<string, string> = { float: "f32", vec2: "vec2<f32>", vec3: "vec3<f32>", vec4: "vec4<f32>", color: "vec3<f32>" };+/** the mesh's own attributes the engine carries (raea-sys-three-shader's ATTRIBUTES) */+const ATTRIBUTES_OWN = 4;++const STORED: Record<string, string> = {+ f32: "f32", i32: "i32", u32: "u32", bool: "u32",+ "vec2<f32>": "vec2<f32>", "vec3<f32>": "vec3<f32>", "vec4<f32>": "vec4<f32>",+ "mat3x3<f32>": "mat3x3<f32>", "mat4x4<f32>": "mat4x4<f32>",+};++function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame"> {+ let vertex = b.vertexShader;+ let fragment = b.fragmentShader;+ const groups = b.getBindings();+ // the model's world matrix: the uniform behind ModelNode's world-matrix scope+ const modelWorld = new Set<AnyNode>();+ for (const n of b.updateNodes) if (n instanceof ModelNode && (n as AnyNode).scope === "worldMatrix" && (n as AnyNode).uniformNode) modelWorld.add((n as AnyNode).uniformNode!);+ // each group's members: where the engine's own value stands in, or the packed uniform's accessor+ const types = new Map([...structs(vertex), ...structs(fragment)]);+ const members = new Map<string, Map<string, { vertex: string; fragment: string }>>();+ const uniforms: Compiled["uniforms"] = [];+ const textures: Compiled["textures"] = [];+ const flipped = new Set<string>();+ /** a uniformArray's buffer: three's WGSL name for it, and the packed uniform it reads as */+ const buffers: { wgsl: string; name: string }[] = [];+ let slots = 0;+ for (const g of groups) {+ for (const x of g.bindings) {+ if (x.isNodeUniformsGroup && x.uniforms) {+ const decl = [...vertex.matchAll(new RegExp(`var<uniform>\\s+${x.name}\\s*:\\s*(\\w+)`, "g")), ...fragment.matchAll(new RegExp(`var<uniform>\\s+${x.name}\\s*:\\s*(\\w+)`, "g"))][0];+ const fields = decl ? types.get(decl[1]) : undefined;+ const map = new Map<string, { vertex: string; fragment: string }>();+ for (const u of x.uniforms) {+ const node = u.nodeUniform?.node;+ const t = fields?.get(u.name);+ // a shared group (render, frame) carries every uniform built against this renderer: one this shader+ // neither declares nor reads is another material's+ if (!t && !new RegExp(`(?<![A-Za-z0-9_])${x.name}\\.${u.name}(?![A-Za-z0-9_])`).test(vertex + fragment)) continue;+ if (!node || !t) throw new Unsupported(`uniform ${x.name}.${u.name} has no declaration three wrote`);+ const named = node.name;+ if (named === "cameraProjectionMatrix") map.set(u.name, { vertex: "three_projection()", fragment: "three_projection()" });+ else if (named === "cameraViewMatrix") map.set(u.name, { vertex: "three_view()", fragment: "three_view()" });+ else if (named === "cameraPosition") map.set(u.name, { vertex: "three_camera_position()", fragment: "three_camera_position()" });+ else {+ if (/^array</.test(t)) throw new Unsupported(`uniform ${u.name} is an array in three's uniform group (${t})`);+ const type = t;+ const stored = STORED[type];+ if (!stored) throw new Unsupported(`uniform ${u.name} is a ${t}, which raea's uniforms don't carry`);+ const name = u.name;+ const access = type === "bool" ? `(u_${name}() != 0u)` : `u_${name}()`;+ uniforms.push({ name, type: stored, read: () => u.nodeUniform!.value, stored: type === "bool" ? "bool" : stored === "u32" || stored === "i32" ? "u32" : "f32" });+ slots += slotsOf(stored);+ // in the vertex stage the model's matrix is Bevy's (the instance's); the fragment reads three's+ map.set(u.name, modelWorld.has(node) ? { vertex: "three_model(tsl_instance)", fragment: access } : { vertex: access, fragment: access });+ }+ }+ members.set(x.name, map);+ } else if (x.isSampledTexture) {+ if (x.isSampledCubeTexture || x.isSampledTexture3D) throw new Unsupported(`texture ${x.name} is a cube or 3D texture (raea's shaders take 2D pictures)`);+ const t = x.texture;+ const src = srcOf(t);+ if (!t || !src) throw new Unsupported(`texture ${x.name} has no picture raea can load (a render target, a video, a canvas it can't read)`);+ textures.push({ name: x.name, texture: t });+ if (t.flipY) flipped.add(`tex_${x.name}`);+ } else if (x.isSampler) {+ // its texture's: samp_NAME+ } else if (x.isBuffer && (x as unknown as { nodeUniform?: { array?: unknown[] } }).nodeUniform?.array) {+ // a uniformArray (lettra's scramble pool): its elements packed one after another, read by index (u_NAME(i))+ const n = (x as unknown as { nodeUniform: { id: number; array: unknown[]; elementType: string } }).nodeUniform;+ const type = ELEMENT[n.elementType];+ if (!type) throw new Unsupported(`uniform array ${x.name} holds ${n.elementType}s, which raea's uniforms don't carry`);+ const name = `buf${n.id}`;+ uniforms.push({ name, type, array: n.array.length, read: () => n.array, stored: "f32" });+ slots += slotsOf(type, n.array.length);+ buffers.push({ wgsl: `NodeBuffer_${n.id}`, name });+ } else throw new Unsupported(`binding ${x.name} is a ${x.isStorageBuffer ? "storage buffer" : x.isBuffer ? "uniform array (uniformArray)" : (x as object).constructor.name}, which raea's shaders don't carry`);+ }+ }+ if (slots > SLOTS) throw new Unsupported(`its uniforms take ${slots} vec4 slots, more than raea's ${SLOTS}`);+ if (textures.length > TEXTURES) throw new Unsupported(`it samples ${textures.length} textures, more than raea's ${TEXTURES}`);++ const common = (src: string, stage: "vertex" | "fragment") => {+ let s = src.replace(/^\s*diagnostic\s*\([^)]*\)\s*;\s*$/gm, "");+ // three's bindings go: the prelude binds the engine's+ const groupTypes = new Set<string>();+ s = s.replace(/@binding\(\s*\d+\s*\)\s*@group\(\s*\d+\s*\)\s*var(?:<[^>]*>)?\s+(\w+)\s*:\s*([^;]+);/g, (_all, name: string, type: string) => {+ if (members.has(name)) groupTypes.add(type.trim());+ return "";+ });+ for (const b of buffers) {+ s = s.replace(new RegExp(`struct\\s+${b.wgsl}Struct\\s*\\{[^}]*\\};?`, "g"), "");+ s = s.replace(new RegExp(`var<uniform>\\s+${b.wgsl}\\s*:[^;]*;`, "g"), "");+ s = indexed(s, `${b.wgsl}.value`, (i) => `u_${b.name}(u32( ${i} ))`);+ }+ for (const t of groupTypes) s = s.replace(new RegExp(`struct\\s+${t}\\s*\\{[^}]*\\};?`, "g"), "");+ for (const [group, map] of members) s = s.replace(new RegExp(`(?<![A-Za-z0-9_.])${group}\\.(\\w+)(?![A-Za-z0-9_])`, "g"), (all, m: string) => map.get(m)?.[stage] ?? all);+ for (const { name } of textures) {+ s = word(s, `${name}_sampler`, `samp_${name}`);+ s = word(s, name, `tex_${name}`);+ }+ s = flipSamples(s, flipped);+ s = word(s, "VaryingsStruct", "ThreeVaryings");+ return word(s, "builtinClipSpace", "clip");+ };++ // ---- the vertex stage ----+ vertex = common(vertex, "vertex");+ const ve = vertex.match(/@vertex\s*fn\s+main\s*\(([\s\S]*?)\)\s*->\s*ThreeVaryings\s*\{/);+ if (!ve) throw new Unsupported("three's vertex stage has no main returning its varyings");+ const vlets: string[] = ["\ttsl_instance = v.instance;"];+ const own: string[] = [];+ for (const p of params(ve[1])) {+ if (p.builtin === "instance_index") vlets.push(`\tlet ${p.name} = v.instance;`);+ else if (p.location !== undefined) {+ const a = ATTRIBUTES[p.name];+ if (a) vlets.push(`\tlet ${p.name} = ${fit(`v.${a.field}`, a.type, p.type)};`);+ else {+ // one of the mesh's own (lettra's layoutX, glyphIndex, cellUv): a0..a3, four floats each+ if (own.length === ATTRIBUTES_OWN) throw new Unsupported(`it reads more than ${ATTRIBUTES_OWN} vertex attributes of the mesh's own (${[...own, p.name].join(", ")})`);+ vlets.push(`\tlet ${p.name} = ${fit(`v.a${own.length}`, "vec4<f32>", p.type)};`);+ own.push(p.name);+ }+ } else throw new Unsupported(`its vertex stage reads the builtin ${p.builtin}`);+ }+ vertex = vertex.replace(ve[0], `fn three_vertex(v: ThreeVertex) -> ThreeVaryings {\n${vlets.join("\n")}\n`);+ vertex = "var<private> tsl_instance : u32;\n" + (flipped.size ? FLIP : "") + vertex;+ const varyings = vertex.match(/struct\s+ThreeVaryings\s*\{[^}]*\};?/)?.[0];+ if (!varyings) throw new Unsupported("three's vertex stage declares no varyings");++ // ---- the fragment stage ----+ fragment = common(fragment, "fragment");+ const fe = fragment.match(/@fragment\s*fn\s+main\s*\(([\s\S]*?)\)\s*->\s*(\w+)\s*\{/);+ if (!fe) throw new Unsupported("three's fragment stage has no main");+ const outs = structs(fragment).get(fe[2]);+ const colour = fragment.match(new RegExp(`struct\\s+${fe[2]}\\s*\\{[^}]*?@location\\(\\s*0\\s*\\)\\s*(\\w+)`))?.[1];+ if (!outs || !colour) throw new Unsupported("three's fragment stage writes no colour");+ const flets: string[] = [];+ for (const p of params(fe[1])) {+ if (p.location !== undefined) flets.push(`\tlet ${p.name} = in.${p.name};`);+ else if (p.builtin === "front_facing") flets.push(`\tlet ${p.name} = front;`);+ else if (p.builtin === "position") flets.push(`\tlet ${p.name} = in.clip;`);+ else throw new Unsupported(`its fragment stage reads the builtin ${p.builtin}`);+ }+ fragment = fragment.replace(fe[0], `fn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> {\n${flets.join("\n")}\n`);+ fragment = fragment.replace(/return\s+(\w+)\s*;/g, (all, v: string) => (fragment.includes(`var<private> ${v} : ${fe[2]}`) ? `return ${v}.${colour};` : all));+ fragment = varyings + "\n" + (flipped.size ? FLIP : "") + fragment;++ return { vertex, fragment, uniforms, textures, attributes: own };+}++/** each `name[ EXPR ]` in `src` (EXPR to its own closing bracket) as `to(EXPR)` */+function indexed(src: string, name: string, to: (i: string) => string): string {+ let out = "";+ let i = 0;+ const re = new RegExp(`(?<![A-Za-z0-9_])${name.replace(/[.]/g, "\\.")}\\s*\\[`, "g");+ let m: RegExpExecArray | null;+ while ((m = re.exec(src))) {+ let depth = 0, j = m.index + m[0].length;+ for (; j < src.length; j++) {+ if (src[j] === "[" || src[j] === "(") depth++;+ else if (src[j] === "]" || src[j] === ")") {+ if (depth === 0) break;+ depth--;+ }+ }+ out += src.slice(i, m.index) + to(src.slice(m.index + m[0].length, j).trim());+ i = j + 1;+ re.lastIndex = i;+ }+ return out + src.slice(i);+}++/** an entry point's parameters: `@location( 0 ) uv : vec2<f32>`, `@builtin( front_facing ) isFront : bool` */+function params(list: string): { name: string; type: string; location?: number; builtin?: string }[] {+ return list+ .split(/,(?=\s*@)/)+ .map((p) => p.trim())+ .filter(Boolean)+ .map((p) => {+ const m = p.match(/^((?:@\w+\s*\([^)]*\)\s*)+)(\w+)\s*:\s*(.+)$/);+ if (!m) throw new Unsupported(`an entry parameter three wrote as ${JSON.stringify(p)}`);+ const loc = m[1].match(/@location\(\s*(\d+)\s*\)/);+ const bi = m[1].match(/@builtin\(\s*(\w+)\s*\)/);+ return { name: m[2], type: m[3].trim(), location: loc ? Number(loc[1]) : undefined, builtin: bi?.[1] };+ });+}++// ---- the values, this frame ----++function flat(v: unknown, type: string): number[] {+ if (typeof v === "number") return [v];+ if (typeof v === "boolean") return [v ? 1 : 0];+ if (v instanceof THREE.Color) return type === "vec4<f32>" ? [v.r, v.g, v.b, 1] : [v.r, v.g, v.b];+ if (v instanceof THREE.Matrix4 || v instanceof THREE.Matrix3) return [...v.elements];+ if (v && typeof (v as { toArray?: unknown }).toArray === "function") return (v as THREE.Vector4).toArray();+ if (Array.isArray(v)) return v.flatMap((x) => flat(x, type));+ throw new Unsupported(`a uniform's value ${String(v)} isn't a number, vector, colour or matrix`);+}++/** the graph's uniforms as three's node updates leave them for this object, camera and time */+function values(c: Compiled, m: THREE.Material, at: NodeAt): ShaderUniform[] {+ const f = c.frame as unknown as Record<string, unknown> & { updateNode(n: unknown): void };+ f.renderer = standIn();+ f.scene = at.scene;+ f.camera = at.camera;+ f.object = at.object;+ f.material = m;+ f.time = at.time;+ f.deltaTime = at.delta ?? 0;+ (f as unknown as { frameId: number }).frameId++;+ (f as unknown as { renderId: number }).renderId++;+ for (const n of c.builder.updateNodes) f.updateNode(n);+ return c.uniforms.map((u) => {+ const value = flat(u.read(), u.type);+ return { name: u.name, type: u.type, value, ...(u.array ? { array: u.array } : {}) };+ });+}++const warned = new Set<string>();++/** a node material as raea's ThreeShaderMaterial, or undefined with the reason named once (then drawn flat) */+export function nodeMaterialOf(m: THREE.Material, at: NodeAt): Part | undefined {+ try {+ const c = compile(m, at);+ const vals = values(c, m, at);+ const props: Props = {+ // <ThreeShaderMaterial wgsl>: the contract's two stages and its uniforms' types; this frame's values apart+ wgsl: { vertex: c.vertex, fragment: c.fragment, uniforms: vals.map(({ name, type, array }) => ({ name, type, ...(array ? { array } : {}) })), ...(c.attributes.length ? { attributes: c.attributes } : {}) },+ uniforms: Object.fromEntries(vals.map((u) => [u.name, u.value])),+ textures: Object.fromEntries(c.textures.map(({ name, texture }) => [name, { src: srcOf(texture)!, colorSpace: texture.colorSpace === THREE.SRGBColorSpace ? "srgb" : "linear" }])),+ // three's node materials write linear colour (the renderer's output pass tone-maps and encodes), as raea's do+ output: "linear",+ transparent: m.transparent,+ depthWrite: m.depthWrite,+ side: m.side === THREE.BackSide ? "back" : m.side === THREE.DoubleSide ? "double" : "front",+ blending: m.blending === THREE.AdditiveBlending ? "add" : m.blending === THREE.MultiplyBlending ? "multiply" : m.blending === THREE.NoBlending ? "none" : "normal",+ };+ if (m.alphaTest > 0) props.alphaTest = m.alphaTest;+ return { type: "ThreeShaderMaterial", props };+ } catch (e) {+ if (!(e instanceof Unsupported)) throw e;+ const k = `${m.type}:${e.message}`;+ if (!warned.has(k)) {+ warned.add(k);+ console.warn(`raea/r3f: ${m.type} "${m.name || m.uuid.slice(0, 8)}" can't run in raea's engine: ${e.message}; drawn flat in its colour`);+ }+ return undefined;+ }+}++/** a node material with no node of its own (a MeshStandardNodeMaterial as three's MeshStandardMaterial): the classic+ * material's type, which raea draws natively, lit by its own lights */+export function classicOf(m: THREE.Material): string | undefined {+ const own = m as unknown as Record<string, unknown>;+ const custom = Object.keys(own).some((k) => k.endsWith("Node") && own[k] != null && (own[k] as AnyNode).isNode);+ if (custom) return undefined;+ const t = m.type.replace("NodeMaterial", "Material");+ return t !== m.type ? t : undefined;+}diff --git a/sdk/r3f/src/parts.tsx b/sdk/r3f/src/parts.tsxindex f04dc7dd..1c2cd750 100644--- a/sdk/r3f/src/parts.tsx+++ b/sdk/r3f/src/parts.tsx@@ -3,11 +3,11 @@// components.import type { ReactNode } from "react";import {- BufferMesh, Environment, Fog, Gizmo, Instances, ToneMapping,+ AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, DepthOfField, Environment, Fog, Gizmo, Grade, Instances, LensDistortion, Look, RichText, ToneMapping,} from "raea/3d";import {AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,- MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight, RectAreaLight, SpotLight,+ MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight, RectAreaLight, SpotLight, ThreeShaderMaterial,} from "@raea/render/three";import type { Part } from "./input/material";@@ -16,9 +16,10 @@ export type { Part, Props } from "./input/material";/** every component a Part may name */// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const COMPONENTS: Record<string, (p: any) => ReactNode> = {- AmbientLight, BufferMesh, DirectionalLight, Environment, Fog, Gizmo, Group, Instances, Mesh, MeshBasicMaterial,+ AmbientLight, AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, DepthOfField, DirectionalLight, Environment, Fog, Gizmo, Grade, Group, Instances,+ LensDistortion, Look, Mesh, MeshBasicMaterial,MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight,- RectAreaLight, SpotLight, ToneMapping,+ RectAreaLight, RichText, SpotLight, ThreeShaderMaterial, ToneMapping,};/** parts as elements, keyed by their place */diff --git a/sdk/r3f/src/three/effects.ts b/sdk/r3f/src/three/effects.tsindex 999bbe82..af72f7d2 100644--- a/sdk/r3f/src/three/effects.ts+++ b/sdk/r3f/src/three/effects.ts@@ -111,6 +111,54 @@ function tonyTable(): THREE.Data3DTexture {return tonyLut;}+/** three r181 widened UnrealBloomPass's blur (mrdoob/three.js#31528: kernels 6 to 22, sigma a third of each), which+ * spreads the glow past Bevy's; raea's Bloom is matched to r180's (kernels 3 to 11, sigma the kernel, its composite and blend), put back here so+ * the glow is the same whichever three a project has (a no-op on r180 and before) */+/** r180's composite of the five blurs (three.js, MIT) */+const R180_COMPOSITE = /* glsl */ `varying vec2 vUv;+uniform sampler2D blurTexture1;+uniform sampler2D blurTexture2;+uniform sampler2D blurTexture3;+uniform sampler2D blurTexture4;+uniform sampler2D blurTexture5;+uniform float bloomStrength;+uniform float bloomRadius;+uniform float bloomFactors[NUM_MIPS];+uniform vec3 bloomTintColors[NUM_MIPS];+float lerpBloomFactor(const in float factor) {+ float mirrorFactor = 1.2 - factor;+ return mix(factor, mirrorFactor, bloomRadius);+}+void main() {+ gl_FragColor = bloomStrength * ( lerpBloomFactor(bloomFactors[0]) * vec4(bloomTintColors[0], 1.0) * texture2D(blurTexture1, vUv) ++ lerpBloomFactor(bloomFactors[1]) * vec4(bloomTintColors[1], 1.0) * texture2D(blurTexture2, vUv) ++ lerpBloomFactor(bloomFactors[2]) * vec4(bloomTintColors[2], 1.0) * texture2D(blurTexture3, vUv) ++ lerpBloomFactor(bloomFactors[3]) * vec4(bloomTintColors[3], 1.0) * texture2D(blurTexture4, vUv) ++ lerpBloomFactor(bloomFactors[4]) * vec4(bloomTintColors[4], 1.0) * texture2D(blurTexture5, vUv) );+}`;++function r180Blur(p: UnrealBloomPass): UnrealBloomPass {+ const mats = (p as unknown as { separableBlurMaterials: THREE.ShaderMaterial[] }).separableBlurMaterials;+ mats.forEach((m, i) => {+ const r = 3 + 2 * i;+ const c: number[] = [];+ for (let k = 0; k < r; k++) c.push((0.39894 * Math.exp((-0.5 * k * k) / (r * r))) / r);+ // r181's shader sums without dividing by the weights (r180's divided): the weights given summing to one are both+ const sum = c.reduce((x, y, k) => x + (k ? 2 * y : y), 0);+ m.defines.KERNEL_RADIUS = r;+ m.uniforms.gaussianCoefficients.value = c.map((x) => x / sum);+ m.needsUpdate = true;+ });+ // and r181 made the glow's additive blend premultiplied, its composite 3 times the blurs with their brightest channel+ // as alpha: r180's composite and blend again+ const own = p as unknown as { blendMaterial: THREE.ShaderMaterial; compositeMaterial: THREE.ShaderMaterial };+ own.blendMaterial.premultipliedAlpha = false;+ own.blendMaterial.needsUpdate = true;+ own.compositeMaterial.fragmentShader = R180_COMPOSITE;+ own.compositeMaterial.needsUpdate = true;+ return p;+}+/** Bevy's bloom is energy-conserving: the frame is mixed toward its blur by the intensity, not added to (this keeps* 1 - k of the frame; UnrealBloomPass adds k of the blur) */const KEEP = `@@ -242,7 +290,7 @@ export class Effects {if (has("DepthOfField")) add("DepthOfField", new BokehPass(scene, camera, { focus: 10, aperture: 0.002, maxblur: 0.01 }));if (has("Bloom")) {add("Bloom:keep", shader(KEEP, { keep: 1 }));- add("Bloom", new UnrealBloomPass(new THREE.Vector2(w, h), 1, 0.4, 0.8));+ add("Bloom", r180Blur(new UnrealBloomPass(new THREE.Vector2(w, h), 1, 0.4, 0.8)));}if (has("MotionBlur")) add("MotionBlur", new AfterimagePass(0.5));if (has("Grade")) add("Grade", shader(GRADE, { temperature: 0, tint: 0, aberration: 0, scale: 1, vig: new THREE.Vector4(), vigColor: new THREE.Color(), aspect: new THREE.Vector2(1, 1), sat: new THREE.Vector3(1, 1, 1), con: new THREE.Vector3(1, 1, 1), gam: new THREE.Vector3(1, 1, 1), gai: new THREE.Vector3(1, 1, 1), lif: new THREE.Vector3() }));diff --git a/sdk/r3f/src/three/kinds.ts b/sdk/r3f/src/three/kinds.tsindex 9fe6372d..cfdb75e3 100644--- a/sdk/r3f/src/three/kinds.ts+++ b/sdk/r3f/src/three/kinds.ts@@ -28,6 +28,7 @@ export const KINDS: Record<string, { status: Status; three: string; note?: strinMeshStandardMaterial: { status: "drawn", three: "MeshStandardMaterial (maps, alpha modes, sides, uv transform, samplers)" },MeshPhysicalMaterial: { status: "drawn", three: "MeshPhysicalMaterial (clearcoat, transmission, ior, thickness, attenuation, anisotropy, specular)" },MeshBasicMaterial: { status: "drawn", three: "MeshBasicMaterial" },+ ThreeShaderMaterial: { status: "engine", three: "a three.js shader run by raea's engine (raea-sys-three-shader)", note: "it came from three.js (a ShaderMaterial's GLSL or a node material's WGSL); exported back to three.js, the original material is the one to keep" },MeshToonMaterial: { status: "near", three: "MeshToonMaterial with a gradient of its steps or bands", note: "raea's rim, highlight and ink outline are its own shader's: three's toon shades the bands only" },PerspectiveCamera: { status: "drawn", three: "PerspectiveCamera, or OrthographicCamera when `ortho`" },AmbientLight: { status: "drawn", three: "AmbientLight (units.ts)" },diff --git a/sdk/r3f/test/coverage.test.tsx b/sdk/r3f/test/coverage.test.tsxindex 30f4555f..ac04c06f 100644--- a/sdk/r3f/test/coverage.test.tsx+++ b/sdk/r3f/test/coverage.test.tsx@@ -121,6 +121,15 @@ describe("R3F → raea coverage", () => {expect(classes.map(([k]) => k)).toEqual(expect.arrayContaining(["Mesh", "Points", "SpotLight", "MeshPhysicalMaterial", "BatchedMesh"]));});+ test("every node material in three/webgpu has a row in input/kinds.ts", async () => {+ // untyped: three/webgpu's whole namespace as a type makes tsc take gigabytes+ const GPU = (await import("three/webgpu")) as unknown as Record<string, { prototype?: unknown }>;+ const base = GPU.NodeMaterial as unknown as abstract new () => unknown;+ const nodes = Object.entries(GPU).filter(([, v]) => typeof v === "function" && (v === GPU.NodeMaterial || v.prototype instanceof base)).map(([k]) => k);+ expect(nodes).toEqual(expect.arrayContaining(["MeshBasicNodeMaterial", "MeshStandardNodeMaterial"]));+ expect(nodes.filter((k) => !(k in CLASSES))).toEqual([]);+ });+test("every Object3D and Material class in three has a row in input/kinds.ts", () => {const missing = classes.map(([k]) => k).filter((k) => !(k in CLASSES));expect(missing).toEqual([]);diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsxindex 8c40d4cd..aa163f81 100644--- a/sdk/r3f/test/parity/fixtures.tsx+++ b/sdk/r3f/test/parity/fixtures.tsx@@ -1,19 +1,17 @@// The parity cases (docs/r3f.feature R3F8): each drawn by raea's engine (native.tsx, `raea render`) and by three.js in// Chrome (the harness page), and the two compared by SSIM (tools/parity.sh). `in-*` are R3F scenes, raea's input;-// `out-*` are raea compositions, drawn in React Three Fiber by <Raea>.+// `out-*` are raea compositions, drawn in React Three Fiber by <Raea> (outputs.tsx).import { useFrame } from "@react-three/fiber";-import { useRef, type ReactNode } from "react";+import * as PP from "@react-three/postprocessing";+import { ContactShadows, Environment, Float, Text, useGLTF } from "@react-three/drei";+import { useMemo, useRef, type ReactNode } from "react";import * as THREE from "three";-import { useCurrentFrame } from "raea";-import {- Bloom, Cuboid, Entities, Grade, LensDistortion, Fog, Sphere, Text3D, ToneMapping, Torus,-} from "raea/3d";-import { createWorld } from "raea/ecs";-import {- AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,- PerspectiveCamera, PointLight, RectAreaLight, SpotLight,-} from "@raea/render/three";-import { AbsoluteFill } from "raea";+import { MeshBasicNodeMaterial } from "three/webgpu";+import * as TSLTyped from "three/tsl";+import { composeEffects, configureFontTexture, createText, parseFont, scramble, wipe } from "lettra/three";+import inter from "./fonts/Inter-400.json";++export { OUTPUTS } from "./outputs";export const SIZE = { width: 640, height: 360, fps: 24 };@@ -57,6 +55,36 @@ export interface InputCase {frame: number;}+// the approximate kinds' case: a matcap made in code (lit from the upper left), three's normal shading, Phong with a+// coloured highlight, a dashed line, a knot clipped by a material plane, a hemisphere light and a light probe+const matcap = (() => {+ const n = 64, data = new Uint8Array(n * n * 4);+ for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {+ const u = (x + 0.5) / n * 2 - 1, v = (y + 0.5) / n * 2 - 1, r = Math.min(1, Math.hypot(u, v));+ const nz = Math.sqrt(1 - r * r), lit = Math.max(0, -0.5 * u + 0.5 * v + 0.7 * nz);+ const i = (y * n + x) * 4;+ data.set([40 + 200 * lit, 60 + 150 * lit, 120 + 120 * lit, 255].map(Math.round), i);+ }+ const t = new THREE.DataTexture(data, n, n);+ t.colorSpace = THREE.SRGBColorSpace;+ t.needsUpdate = true;+ return t;+})();+const dashedLine = (() => {+ const g = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(-3, -1.25, 0), new THREE.Vector3(-1, -0.9, 0), new THREE.Vector3(1, -1.25, 0), new THREE.Vector3(3, -0.9, 0)]);+ const l = new THREE.Line(g, new THREE.LineDashedMaterial({ color: "#f2cc60", dashSize: 0.18, gapSize: 0.1 }));+ l.computeLineDistances();+ return l;+})();+const probe = (() => {+ const sh = new THREE.SphericalHarmonics3();+ sh.coefficients[0].set(0.5, 0.45, 0.6);+ sh.coefficients[1].set(0.25, 0.2, 0.3);+ sh.coefficients[3].set(-0.15, 0.05, 0.1);+ return new THREE.LightProbe(sh, 1);+})();+const clipPlane = new THREE.Plane(new THREE.Vector3(-0.3, -1, 0.2).normalize(), 0.95);+export const INPUTS: Record<string, InputCase> = {basic: {canvas: { camera: { position: [3, 2.5, 4], fov: 45 }, shadows: true },@@ -126,6 +154,35 @@ export const INPUTS: Record<string, InputCase> = {</>),},+ approx: {+ canvas: { camera: { position: [0, 0.6, 6.5], fov: 45 }, onCreated: ({ gl }: { gl: THREE.WebGLRenderer }) => void (gl.localClippingEnabled = true) },+ frame: 0,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <hemisphereLight args={["#bcd7ff", "#5a3a20", 0.8]} />+ <primitive object={probe} />+ <directionalLight position={[3, 4, 5]} intensity={1.6} />+ <mesh position={[-2.4, 0.3, 0]}>+ <sphereGeometry args={[0.65, 48, 32]} />+ <meshMatcapMaterial matcap={matcap} />+ </mesh>+ <mesh position={[-0.8, 0.3, 0]} rotation={[0.6, 0.4, 0]}>+ <torusGeometry args={[0.45, 0.2, 24, 64]} />+ <meshNormalMaterial />+ </mesh>+ <mesh position={[0.8, 0.3, 0]}>+ <sphereGeometry args={[0.65, 48, 32]} />+ <meshPhongMaterial color="#3a6ea5" specular="#ff9a3c" shininess={60} />+ </mesh>+ <mesh position={[2.4, 0.3, 0]}>+ <torusKnotGeometry args={[0.42, 0.14, 128, 16]} />+ <meshStandardMaterial color="#d2a8ff" roughness={0.5} clippingPlanes={[clipPlane]} side={THREE.DoubleSide} />+ </mesh>+ <primitive object={dashedLine} />+ </>+ ),+ },// a ShadowMaterial floor: only the box's shadow is drawn, over the page's colourcatch: {canvas: { camera: { position: [0, 2.5, 4.5], fov: 45 }, shadows: true },@@ -146,144 +203,198 @@ export const INPUTS: Record<string, InputCase> = {</>),},+ // lettra's effects: a wipe whose front R3F's clock moves (a uniform set in useFrame), reading the text's own+ // attributes (layoutX, glyphIndex, cellUv), and a scramble through a pool of glyphs (a uniformArray)+ lettrafx: {+ canvas: { camera: { position: [0, 0, 5], fov: 45 }, gl: webgpu },+ frame: 12,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <LettraFx />+ </>+ ),+ },+ // @react-three/postprocessing (src/input/post.ts): an <EffectComposer>'s effects as raea's Grade and ToneMapping+ // (its Bloom is read too, but raea's own bloom draws no glow in this build: out of this case until it does)+ post: {+ canvas: { camera: { position: [3, 2.5, 4], fov: 45 } },+ frame: 0,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <ambientLight intensity={0.5} />+ <directionalLight position={[2, 5, 1]} intensity={2.5} />+ <mesh position={[0, 0.6, 0]}>+ <sphereGeometry args={[0.6, 32, 16]} />+ <meshStandardMaterial color="#e05a2b" roughness={0.4} />+ </mesh>+ <mesh position={[0, 0, 0]} rotation={[-Math.PI / 2, 0, 0]}>+ <planeGeometry args={[8, 8]} />+ <meshStandardMaterial color="#cfd6e0" roughness={0.9} />+ </mesh>+ <PP.EffectComposer>+ <PP.HueSaturation saturation={-0.3} />+ <PP.Vignette offset={0.3} darkness={0.7} />+ <PP.ToneMapping mode={6} />+ </PP.EffectComposer>+ </>+ ),+ },+ // a typical drei scene: a model by useGLTF floating (<Float>), troika's <Text>, <ContactShadows> under it and an+ // <Environment preset> lighting it+ drei: {+ canvas: { camera: { position: [0, 1, 4.2], fov: 45 } },+ frame: 12,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <Environment preset="city" />+ <Float speed={0} rotationIntensity={0.6} floatIntensity={0.8}>+ <Knot />+ </Float>+ <Text position={[0, 1.55, 0]} fontSize={0.32} color="#f2cc60" font="fonts/Inter-400.ttf" anchorX="center" anchorY="middle">+ raea drei+ </Text>+ <ContactShadows position={[0, -0.85, 0]} opacity={0.7} blur={2.2} scale={5} far={2} />+ </>+ ),+ },+ // three.js ShaderMaterials (src/input/shader.ts): GLSL translated by naga and run by raea's engine with three's+ // built-ins. A sphere rippled by R3F's clock (a uniform set in useFrame) and points sized by an attribute of their own+ shader: {+ canvas: { camera: { position: [0, 0, 4.5], fov: 45 } },+ frame: 12,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <Waves />+ <points position={[0, 0, 0.5]}>+ <primitive object={dots} attach="geometry" />+ <shaderMaterial vertexShader={DOT_VERTEX} fragmentShader={DOT_FRAGMENT} transparent depthWrite={false} />+ </points>+ </>+ ),+ },+ // TSL node materials (three/webgpu), compiled to WGSL by three and run by raea's engine (src/input/tsl.ts): lettra's+ // MSDF text (an OFL face, Inter, baked by `lettra bake`: test/parity/fonts) and a gradient pulsing with TSL's time+ lettra: {+ canvas: { camera: { position: [0, 0, 5], fov: 45 }, gl: webgpu },+ frame: 12,+ scene: () => (+ <>+ <color attach="background" args={["#1d2330"]} />+ <Lettra />+ <mesh position={[0, -1.3, 0]} rotation={[0.4, 0.6, 0]}>+ <boxGeometry args={[0.9, 0.9, 0.9]} />+ <primitive object={pulse} attach="material" />+ </mesh>+ </>+ ),+ },};-// ---- raea compositions -----function OutBasic({ tone = "aces" }: { tone?: "aces" | "tony" }) {- const f = useCurrentFrame();- return (- <AbsoluteFill style={{ background: "#1d2330" }}>- <PerspectiveCamera position={[3, 2.5, 4]} lookAt={[0, 0.5, 0]} fov={45} />- {tone === "aces" && <ToneMapping mode="aces" />}- <AmbientLight intensity={0.4} />- <DirectionalLight position={[3, 5, 2]} target={[0, 0, 0]} intensity={2.5} />- <PointLight position={[-2, 1.5, 1]} intensity={6} color="#58a6ff" />- <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>- <Cuboid args={[12, 12, 0.001]} />- <MeshStandardMaterial color="#cfd6e0" roughness={0.9} />- </Mesh>- <Mesh name="box" position={[0, 0.8, 0]} rotation={[f / 48, f / 24, 0]}>- <Cuboid args={[1, 1, 1]} />- <MeshStandardMaterial color="#e05a2b" roughness={0.4} />- </Mesh>- <Mesh name="ball" position={[-1.6, 0.5, -0.5]}>- <Sphere args={[0.5]} />- <MeshPhysicalMaterial color="#3fb950" clearcoat={1} roughness={0.2} />- </Mesh>- <Group position={[1.6, 0.6, -0.4]} rotation={[0.4, 0, 0]}>- <Mesh name="ring">- <Torus args={[0.4, 0.15]} />- <MeshStandardMaterial color="#d2a8ff" metalness={0.7} roughness={0.25} />- </Mesh>- </Group>- </AbsoluteFill>- );-}+const WAVE_VERTEX = /* glsl */ `+uniform float uTime;+varying vec3 vNormal;+varying vec2 vUv;+void main() {+ vec3 p = position + normal * sin(position.y * 8.0 + uTime * 3.0) * 0.08;+ vNormal = normalize(normalMatrix * normal);+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);+}`;+const WAVE_FRAGMENT = /* glsl */ `+uniform vec3 uColor;+varying vec3 vNormal;+varying vec2 vUv;+void main() {+ float light = 0.25 + 0.75 * max(dot(normalize(vNormal), normalize(vec3(0.4, 0.8, 0.6))), 0.0);+ float stripe = step(0.5, fract(vUv.x * 8.0));+ gl_FragColor = vec4(mix(uColor, vec3(1.0), stripe * 0.35) * light, 1.0);+}`;-function OutLights() {+function Waves() {+ const m = useMemo(() => new THREE.ShaderMaterial({ vertexShader: WAVE_VERTEX, fragmentShader: WAVE_FRAGMENT, uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color("#e05a2b") } } }), []);+ useFrame(({ clock }) => void (m.uniforms.uTime.value = clock.elapsedTime));return (- <AbsoluteFill style={{ background: "#0b0e14" }}>- <PerspectiveCamera position={[0, 3, 6]} lookAt={[0, 0.5, 0]} fov={50} />- <ToneMapping mode="aces" />- <Fog color="#0b0e14" near={6} far={14} />- <SpotLight position={[0, 4, 1]} target={[0, 0, 0]} angle={0.6} penumbra={0.4} intensity={1.5} castShadow />- <RectAreaLight position={[-2, 1, 2]} target={[0, 0.5, 0]} width={1.5} height={1} intensity={1} color="#ff6040" />- <AmbientLight intensity={0.2} />- <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>- <Cuboid args={[12, 12, 0.001]} />- <MeshStandardMaterial color="#cfd6e0" roughness={0.9} />- </Mesh>- <Mesh name="glow" position={[1.5, 0.5, 0.5]}>- <Sphere args={[0.4]} />- <MeshBasicMaterial color="#4ea1ff" />- </Mesh>- <Mesh name="sign" position={[-0.9, 0.3, 0]}>- <Text3D size={0.5} depth={0.15}>R3F</Text3D>- <MeshStandardMaterial color="#f2cc60" roughness={0.5} />- </Mesh>- </AbsoluteFill>+ <mesh rotation={[0.3, 0.4, 0]} material={m}>+ <sphereGeometry args={[1, 48, 24]} />+ </mesh>);}-function OutEffects({ fx }: { fx: "bloom" | "grade" | "lens" }) {- return (- <AbsoluteFill style={{ background: "#0b0e14" }}>- <PerspectiveCamera position={[0, 1.5, 5]} lookAt={[0, 0.5, 0]} fov={45} />- <ToneMapping mode="aces" />- {fx === "bloom" && <Bloom intensity={2} threshold={0.6} />}- {fx === "grade" && <Grade saturation={1.3} vignette={0.5} midtones={{ contrast: 1.1 }} />}- {fx === "lens" && <LensDistortion k1={0.15} />}- <AmbientLight intensity={0.3} />- <DirectionalLight position={[2, 4, 3]} target={[0, 0, 0]} intensity={1.5} />- <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>- <Cuboid args={[12, 12, 0.001]} />- <MeshStandardMaterial color="#8090a0" roughness={0.9} />- </Mesh>- <Mesh name="lamp" position={[-1, 0.6, 0]}>- <Sphere args={[0.5]} />- <MeshStandardMaterial color="#000000" emissive="#ffb050" emissiveIntensity={4} />- </Mesh>- <Mesh name="box" position={[1, 0.5, 0]} rotation={[0, 0.6, 0]}>- <Cuboid args={[1, 1, 1]} />- <MeshStandardMaterial color="#58a6ff" roughness={0.4} />- </Mesh>- </AbsoluteFill>- );-}+const DOT_VERTEX = /* glsl */ `+attribute float aScale;+varying float vScale;+void main() {+ vScale = aScale;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);+ gl_PointSize = 6.0 + aScale * 18.0;+}`;+const DOT_FRAGMENT = /* glsl */ `+varying float vScale;+void main() {+ float d = length(gl_PointCoord - vec2(0.5));+ if (d > 0.5) discard;+ gl_FragColor = vec4(mix(vec3(0.35, 0.65, 1.0), vec3(0.95, 0.8, 0.38), vScale), 1.0 - smoothstep(0.35, 0.5, d));+}`;-function OutCatch() {- return (- <AbsoluteFill style={{ background: "#d8c9a8" }}>- <PerspectiveCamera position={[0, 2.5, 4.5]} lookAt={[0, 0.3, 0]} fov={45} />- <ToneMapping mode="aces" />- <AmbientLight intensity={0.5} />- <DirectionalLight position={[2, 5, 1]} target={[0, 0, 0]} intensity={2.5} castShadow />- <Mesh name="floor" rotation={[-Math.PI / 2, 0, 0]} shadow="catch">- <Cuboid args={[12, 12, 0.001]} />- <MeshBasicMaterial color="#1a1030" opacity={0.6} />- </Mesh>- <Mesh name="box" position={[0, 0.6, 0]} rotation={[0, 0.5, 0]}>- <Cuboid args={[1, 1.2, 1]} />- <MeshStandardMaterial color="#e05a2b" roughness={0.5} />- </Mesh>- </AbsoluteFill>- );+const dots = (() => {+ const g = new THREE.BufferGeometry();+ const pos: number[] = [], scale: number[] = [];+ for (let i = 0; i < 24; i++) {+ const a = (i / 24) * Math.PI * 2;+ pos.push(Math.cos(a) * 1.7, Math.sin(a) * 1.1, 0);+ scale.push((i % 6) / 5);+ }+ g.setAttribute("position", new THREE.Float32BufferAttribute(pos, 3));+ g.setAttribute("aScale", new THREE.Float32BufferAttribute(scale, 1));+ return g;+})();++/** three's WebGPURenderer on its WebGL 2 backend (a TSL node material needs it; headless Chrome may have no WebGPU) */+async function webgpu(props: object) {+ const { WebGPURenderer } = await import("three/webgpu");+ const r = new WebGPURenderer({ ...(props as object), forceWebGL: true, antialias: true });+ await r.init();+ return r;}-// an ECS world drawn with no React element per entity (<Entities>): a ship and its gun, turned by a system-const fleet = createWorld();-const ship = fleet.add({ Mesh: { shape: "rounded_box(2, 0.6, 1, 0.1)", color: "#2563eb", roughness: 0.5, metalness: 0 }, Transform: { x: 0, y: 0.5, z: 0, ry: 0 } });-fleet.add({ Mesh: { shape: "cylinder(0.15, 1.2)", color: "#f59e0b", roughness: 0.4, metalness: 0 }, Transform: { x: 0, y: 0.6, z: 0, rx: 0.4 } }, { parent: ship });-fleet.system((w, f) => w.insert(ship, { Transform: { x: 0, y: 0.5, z: 0, ry: f * 0.05 } }));+const pulse = (() => {+ // untyped: @types/three's chained TSL types make tsc take minutes and gigabytes+ const { color, mix, sin, time, uv } = TSLTyped as unknown as Record<string, (...a: unknown[]) => any> & { time: any };+ const m = new MeshBasicNodeMaterial();+ m.colorNode = mix(color("#58a6ff"), color("#e05a2b"), uv().y).mul(sin(time.mul(2)).mul(0.25).add(0.75));+ return m;+})();-function OutEntities() {- const f = useCurrentFrame();- return (- <AbsoluteFill style={{ background: "#0b1020" }}>- <PerspectiveCamera position={[0, 2, 6]} lookAt={[0, 0.5, 0]} fov={45} />- <ToneMapping mode="aces" />- <AmbientLight intensity={0.4} />- <DirectionalLight position={[2, 4, 3]} target={[0, 0, 0]} intensity={2} />- <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>- <Cuboid args={[12, 12, 0.001]} />- <MeshStandardMaterial color="#8090a0" roughness={0.9} />- </Mesh>- <Entities world={fleet.at(f)} />- </AbsoluteFill>- );+function Knot() {+ const { scene } = useGLTF("models/knot.glb");+ return <primitive object={scene} />;}-export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number }> = {- basic: { component: () => <OutBasic />, frame: 24 },- // raea's default tone mapping, TonyMcMapface- tony: { component: () => <OutBasic tone="tony" />, frame: 24 },- lights: { component: OutLights, frame: 0 },- // one effect a case: each pass measured on its own- bloom: { component: () => <OutEffects fx="bloom" />, frame: 0 },- grade: { component: () => <OutEffects fx="grade" />, frame: 0 },- lens: { component: () => <OutEffects fx="lens" />, frame: 0 },- // shadow="catch" (three's ShadowMaterial): only the shadow on the floor- catch: { component: OutCatch, frame: 0 },- // an ECS world's entities (<Entities>), frame 10 of its system- entities: { component: OutEntities, frame: 10 },-};+function LettraFx() {+ const text = useMemo(() => {+ const map = new THREE.TextureLoader().load("fonts/Inter-400.png", (t) => void configureFontTexture(t));+ Object.assign(map, { flipY: false, colorSpace: THREE.NoColorSpace, generateMipmaps: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });+ const effect = composeEffects(wipe(), scramble({ font: inter as unknown as Parameters<typeof scramble>[0]["font"], chars: "raeR3FlitMSD", rate: 0 }));+ const t = createText({ font: parseFont(inter), map, text: "raea R3F\nlettra MSDF", layout: { align: "center" }, material: { fill: "#58a6ff", effect } });+ (t.uniforms as unknown as { scramble: { value: number } }).scramble.value = 0.6;+ return t;+ }, []);+ useFrame(({ clock }) => void ((text.uniforms as unknown as { wipeIn: { value: number } }).wipeIn.value = Math.min(1, 0.2 + clock.elapsedTime)));+ return <primitive object={text.mesh} />;+}++function Lettra() {+ const text = useMemo(() => {+ // lettra's atlas settings now (raea reads them as it compiles the graph), its upload once the picture is in+ const map = new THREE.TextureLoader().load("fonts/Inter-400.png", (t) => void configureFontTexture(t));+ Object.assign(map, { flipY: false, colorSpace: THREE.NoColorSpace, generateMipmaps: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });+ const t = createText({ font: parseFont(inter), map, text: "raea R3F\nlettra MSDF", layout: { align: "center" }, material: { fill: "#f2cc60" } });+ t.mesh.position.y = 0.45;+ return t;+ }, []);+ return <primitive object={text.mesh} />;+}diff --git a/sdk/r3f/test/parity/fonts/Inter-400.json b/sdk/r3f/test/parity/fonts/Inter-400.jsonnew file mode 100644index 00000000..dd456adb--- /dev/null+++ b/sdk/r3f/test/parity/fonts/Inter-400.json@@ -0,0 +1 @@+{"name":"Inter-Regular","size":48,"lineHeight":58,"base":51,"distanceRange":8,"atlas":{"width":1024,"height":1024},"glyphs":{"3":[0,0,32,44,-1,16,30],"S":[0,46,33,44,-1,16,31],"R":[34,0,33,43,0,16,31],"F":[0,92,29,43,0,16,28],"l":[0,137,12,43,0,16,12],"M":[0,182,43,43,0,16,43],"D":[14,137,36,43,0,16,35],"t":[31,92,22,41,-4,19,16],"r":[35,45,21,35,0,24,18],"a":[0,227,29,35,-2,24,27],"e":[0,264,31,35,-2,24,28],"x":[31,227,31,34,-2,25,26]," ":[31,135,0,0,-4,51,14]},"kerning":{}}\ No newline at end of filediff --git a/sdk/r3f/test/parity/fonts/Inter-400.png b/sdk/r3f/test/parity/fonts/Inter-400.pngnew file mode 100644index 00000000..843d5073Binary files /dev/null and b/sdk/r3f/test/parity/fonts/Inter-400.png differdiff --git a/sdk/r3f/test/parity/fonts/Inter-400.ttf b/sdk/r3f/test/parity/fonts/Inter-400.ttfnew file mode 100644index 00000000..399a6e0cBinary files /dev/null and b/sdk/r3f/test/parity/fonts/Inter-400.ttf differdiff --git a/sdk/r3f/test/parity/fonts/Inter-OFL.txt b/sdk/r3f/test/parity/fonts/Inter-OFL.txtnew file mode 100644index 00000000..9b2ca37b--- /dev/null+++ b/sdk/r3f/test/parity/fonts/Inter-OFL.txt@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/sdk/r3f/test/parity/models/knot.glb b/sdk/r3f/test/parity/models/knot.glbnew file mode 100644index 00000000..03295b5aBinary files /dev/null and b/sdk/r3f/test/parity/models/knot.glb differdiff --git a/sdk/r3f/test/parity/outputs.tsx b/sdk/r3f/test/parity/outputs.tsxnew file mode 100644index 00000000..8b17ce50--- /dev/null+++ b/sdk/r3f/test/parity/outputs.tsx@@ -0,0 +1,151 @@+// The parity cases' raea compositions (fixtures.tsx), `out-*`: each drawn by raea's engine and by React Three Fiber+// through <Raea>, and the two compared by SSIM (tools/parity.sh).+import type { ReactNode } from "react";+import { AbsoluteFill, useCurrentFrame } from "raea";+import {+ Bloom, Cuboid, Entities, Grade, LensDistortion, Fog, Sphere, Text3D, ToneMapping, Torus,+} from "raea/3d";+import { createWorld } from "raea/ecs";+import {+ AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,+ PerspectiveCamera, PointLight, RectAreaLight, SpotLight,+} from "@raea/render/three";++function OutBasic({ tone = "aces" }: { tone?: "aces" | "tony" }) {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: "#1d2330" }}>+ <PerspectiveCamera position={[3, 2.5, 4]} lookAt={[0, 0.5, 0]} fov={45} />+ {tone === "aces" && <ToneMapping mode="aces" />}+ <AmbientLight intensity={0.4} />+ <DirectionalLight position={[3, 5, 2]} target={[0, 0, 0]} intensity={2.5} />+ <PointLight position={[-2, 1.5, 1]} intensity={6} color="#58a6ff" />+ <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>+ <Cuboid args={[12, 12, 0.001]} />+ <MeshStandardMaterial color="#cfd6e0" roughness={0.9} />+ </Mesh>+ <Mesh name="box" position={[0, 0.8, 0]} rotation={[f / 48, f / 24, 0]}>+ <Cuboid args={[1, 1, 1]} />+ <MeshStandardMaterial color="#e05a2b" roughness={0.4} />+ </Mesh>+ <Mesh name="ball" position={[-1.6, 0.5, -0.5]}>+ <Sphere args={[0.5]} />+ <MeshPhysicalMaterial color="#3fb950" clearcoat={1} roughness={0.2} />+ </Mesh>+ <Group position={[1.6, 0.6, -0.4]} rotation={[0.4, 0, 0]}>+ <Mesh name="ring">+ <Torus args={[0.4, 0.15]} />+ <MeshStandardMaterial color="#d2a8ff" metalness={0.7} roughness={0.25} />+ </Mesh>+ </Group>+ </AbsoluteFill>+ );+}++function OutLights() {+ return (+ <AbsoluteFill style={{ background: "#0b0e14" }}>+ <PerspectiveCamera position={[0, 3, 6]} lookAt={[0, 0.5, 0]} fov={50} />+ <ToneMapping mode="aces" />+ <Fog color="#0b0e14" near={6} far={14} />+ <SpotLight position={[0, 4, 1]} target={[0, 0, 0]} angle={0.6} penumbra={0.4} intensity={1.5} castShadow />+ <RectAreaLight position={[-2, 1, 2]} target={[0, 0.5, 0]} width={1.5} height={1} intensity={1} color="#ff6040" />+ <AmbientLight intensity={0.2} />+ <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>+ <Cuboid args={[12, 12, 0.001]} />+ <MeshStandardMaterial color="#cfd6e0" roughness={0.9} />+ </Mesh>+ <Mesh name="glow" position={[1.5, 0.5, 0.5]}>+ <Sphere args={[0.4]} />+ <MeshBasicMaterial color="#4ea1ff" />+ </Mesh>+ <Mesh name="sign" position={[-0.9, 0.3, 0]}>+ <Text3D size={0.5} depth={0.15}>R3F</Text3D>+ <MeshStandardMaterial color="#f2cc60" roughness={0.5} />+ </Mesh>+ </AbsoluteFill>+ );+}++function OutEffects({ fx }: { fx: "bloom" | "grade" | "lens" }) {+ return (+ <AbsoluteFill style={{ background: "#0b0e14" }}>+ <PerspectiveCamera position={[0, 1.5, 5]} lookAt={[0, 0.5, 0]} fov={45} />+ <ToneMapping mode="aces" />+ {fx === "bloom" && <Bloom intensity={2} threshold={0.6} />}+ {fx === "grade" && <Grade saturation={1.3} vignette={0.5} midtones={{ contrast: 1.1 }} />}+ {fx === "lens" && <LensDistortion k1={0.15} />}+ <AmbientLight intensity={0.3} />+ <DirectionalLight position={[2, 4, 3]} target={[0, 0, 0]} intensity={1.5} />+ <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>+ <Cuboid args={[12, 12, 0.001]} />+ <MeshStandardMaterial color="#8090a0" roughness={0.9} />+ </Mesh>+ <Mesh name="lamp" position={[-1, 0.6, 0]}>+ <Sphere args={[0.5]} />+ <MeshStandardMaterial color="#000000" emissive="#ffb050" emissiveIntensity={4} />+ </Mesh>+ <Mesh name="box" position={[1, 0.5, 0]} rotation={[0, 0.6, 0]}>+ <Cuboid args={[1, 1, 1]} />+ <MeshStandardMaterial color="#58a6ff" roughness={0.4} />+ </Mesh>+ </AbsoluteFill>+ );+}++function OutCatch() {+ return (+ <AbsoluteFill style={{ background: "#d8c9a8" }}>+ <PerspectiveCamera position={[0, 2.5, 4.5]} lookAt={[0, 0.3, 0]} fov={45} />+ <ToneMapping mode="aces" />+ <AmbientLight intensity={0.5} />+ <DirectionalLight position={[2, 5, 1]} target={[0, 0, 0]} intensity={2.5} castShadow />+ <Mesh name="floor" rotation={[-Math.PI / 2, 0, 0]} shadow="catch">+ <Cuboid args={[12, 12, 0.001]} />+ <MeshBasicMaterial color="#1a1030" opacity={0.6} />+ </Mesh>+ <Mesh name="box" position={[0, 0.6, 0]} rotation={[0, 0.5, 0]}>+ <Cuboid args={[1, 1.2, 1]} />+ <MeshStandardMaterial color="#e05a2b" roughness={0.5} />+ </Mesh>+ </AbsoluteFill>+ );+}++// an ECS world drawn with no React element per entity (<Entities>): a ship and its gun, turned by a system+const fleet = createWorld();+const ship = fleet.add({ Mesh: { shape: "rounded_box(2, 0.6, 1, 0.1)", color: "#2563eb", roughness: 0.5, metalness: 0 }, Transform: { x: 0, y: 0.5, z: 0, ry: 0 } });+fleet.add({ Mesh: { shape: "cylinder(0.15, 1.2)", color: "#f59e0b", roughness: 0.4, metalness: 0 }, Transform: { x: 0, y: 0.6, z: 0, rx: 0.4 } }, { parent: ship });+fleet.system((w, f) => w.insert(ship, { Transform: { x: 0, y: 0.5, z: 0, ry: f * 0.05 } }));++function OutEntities() {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill style={{ background: "#0b1020" }}>+ <PerspectiveCamera position={[0, 2, 6]} lookAt={[0, 0.5, 0]} fov={45} />+ <ToneMapping mode="aces" />+ <AmbientLight intensity={0.4} />+ <DirectionalLight position={[2, 4, 3]} target={[0, 0, 0]} intensity={2} />+ <Mesh name="ground" rotation={[-Math.PI / 2, 0, 0]}>+ <Cuboid args={[12, 12, 0.001]} />+ <MeshStandardMaterial color="#8090a0" roughness={0.9} />+ </Mesh>+ <Entities world={fleet.at(f)} />+ </AbsoluteFill>+ );+}++export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number }> = {+ basic: { component: () => <OutBasic />, frame: 24 },+ // raea's default tone mapping, TonyMcMapface+ tony: { component: () => <OutBasic tone="tony" />, frame: 24 },+ lights: { component: OutLights, frame: 0 },+ // one effect a case: each pass measured on its own+ bloom: { component: () => <OutEffects fx="bloom" />, frame: 0 },+ grade: { component: () => <OutEffects fx="grade" />, frame: 0 },+ lens: { component: () => <OutEffects fx="lens" />, frame: 0 },+ // shadow="catch" (three's ShadowMaterial): only the shadow on the floor+ catch: { component: OutCatch, frame: 0 },+ // an ECS world's entities (<Entities>), frame 10 of its system+ entities: { component: OutEntities, frame: 10 },+};diff --git a/sdk/r3f/test/parity/page.tsx b/sdk/r3f/test/parity/page.tsxindex 7b1ffeac..3594c82f 100644--- a/sdk/r3f/test/parity/page.tsx+++ b/sdk/r3f/test/parity/page.tsx@@ -11,6 +11,8 @@ import { Raea } from "@raea/r3f/output/Raea"import { loadShapes } from "@raea/r3f/three/geometry"// the shape module tools/shape-wasm.sh builds into sdk/r3f/wasm, served by tools/serve.ts at /wasm/const SHAPES = "/wasm/raea_shape_web.js"+// drei's <Environment preset> panoramas from tools/serve.ts, which fetches them (the page makes no outside request)+THREE.DefaultLoadingManager.setURLModifier((url) => url.replace(/^https:\/\/raw\.(githack|githubusercontent)\.com\/pmndrs\/drei-assets\//, "/drei-assets/"))function Stepper({ frame, onDone }: { frame: number; onDone: () => void }) {useEffect(() => {diff --git a/sdk/r3f/test/post.test.ts b/sdk/r3f/test/post.test.tsnew file mode 100644index 00000000..3e11d077--- /dev/null+++ b/sdk/r3f/test/post.test.ts@@ -0,0 +1,51 @@+// @react-three/postprocessing's effects as raea's (src/input/post.ts, docs/r3f.feature R3F12): pmndrs postprocessing's+// own classes, read the way they're found under an <EffectComposer>.+import { describe, expect, test } from "bun:test";+import { BloomEffect, ChromaticAberrationEffect, HueSaturationEffect, NoiseEffect, SMAAEffect, ToneMappingEffect, ToneMappingMode, VignetteEffect } from "postprocessing";+import * as THREE from "three";+import { postParts } from "../src/input/post";+import { EFFECTS } from "../src/input/kinds";++describe("<EffectComposer> → raea's frame effects", () => {+ test("bloom, colour, tone and anti-aliasing become raea's", () => {+ const { parts, tone } = postParts([+ new BloomEffect({ intensity: 1.5, luminanceThreshold: 0.6 }),+ new VignetteEffect({ offset: 0.3, darkness: 0.7 }),+ new HueSaturationEffect({ saturation: -0.3 }),+ new ChromaticAberrationEffect({ offset: new THREE.Vector2(0.003, 0.004), radialModulation: false, modulationOffset: 0 }),+ new ToneMappingEffect({ mode: ToneMappingMode.AGX }),+ new SMAAEffect(),+ ]);+ expect(parts.find((p) => p.type === "Bloom")!.props).toEqual({ intensity: 1.5, threshold: 0.6 });+ const grade = parts.find((p) => p.type === "Grade")!.props as Record<string, any>;+ expect(grade.vignette.intensity).toBeCloseTo(0.7);+ expect(grade.saturation).toBeCloseTo(0.7);+ expect(grade.aberration).toBeCloseTo(0.005);+ expect(parts.find((p) => p.type === "AntiAliasing")!.props).toEqual({ mode: "smaa" });+ expect(tone!.props).toEqual({ mode: "agx" });+ });++ test("ACES carries three's 1/0.6 as exposure", () => {+ const { tone } = postParts([new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC })]);+ expect(tone!.props.mode).toBe("aces");+ expect(tone!.props.exposure as number).toBeCloseTo(Math.log2(1 / 0.6));+ });++ test("one raea has nothing for is named and left out", () => {+ const warn = console.warn;+ const said: string[] = [];+ console.warn = (s: string) => said.push(s);+ try {+ expect(postParts([new NoiseEffect()]).parts).toEqual([]);+ expect(said.join("\n")).toContain("NoiseEffect");+ } finally {+ console.warn = warn;+ }+ });++ test("every effect postprocessing exports is decided in kinds.ts", async () => {+ const pp = (await import("postprocessing")) as Record<string, unknown>;+ const effects = Object.keys(pp).filter((k) => /Effect$/.test(k) && typeof pp[k] === "function" && k !== "Effect");+ expect(effects.filter((k) => !EFFECTS[k])).toEqual([]);+ });+});diff --git a/sdk/r3f/test/shader.test.ts b/sdk/r3f/test/shader.test.tsnew file mode 100644index 00000000..608160fd--- /dev/null+++ b/sdk/r3f/test/shader.test.ts@@ -0,0 +1,56 @@+// three.js ShaderMaterials as raea's ThreeShaderMaterial (src/input/shader.ts, docs/r3f.feature R3F11): the GLSL as+// three would compile it, uniforms as numbers, textures as pictures, Points as quads the engine sizes by gl_PointSize.+import { describe, expect, test } from "bun:test";+import * as THREE from "three";+import { expandIncludes, ownAttributes, shaderPart } from "../src/input/shader";+import { materialOf } from "../src/input/material";++describe("ShaderMaterial → raea's ThreeShaderMaterial", () => {+ test("its GLSL with three's chunks expanded, its defines in front, its uniforms as numbers", () => {+ const m = new THREE.ShaderMaterial({+ defines: { WAVES: 3 },+ uniforms: { uTime: { value: 1.5 }, uColor: { value: new THREE.Color("#ff8000") }, uOffset: { value: new THREE.Vector2(1, 2) }, uM: { value: new THREE.Matrix3() } },+ vertexShader: "#include <common>\nvoid main(){ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }",+ fragmentShader: "uniform vec3 uColor;\nvoid main(){ gl_FragColor = vec4(uColor, 1.0);\n#include <colorspace_fragment>\n}",+ });+ const part = materialOf(m, false);+ expect(part.type).toBe("ThreeShaderMaterial");+ const p = part.props as Record<string, any>;+ expect(p.glsl.vertex).toContain("#define WAVES 3\n");+ expect(p.glsl.vertex).toContain("#define PI 3.141592653589793");+ expect(p.glsl.fragment).toContain("linearToOutputTexel");+ expect(p.glsl.fragment).not.toContain("#include");+ expect(p.uniforms.uTime).toBe(1.5);+ expect(p.uniforms.uOffset).toEqual([1, 2]);+ expect(p.uniforms.uM).toEqual([1, 0, 0, 0, 1, 0, 0, 0, 1]);+ expect(p.color).toBe("#ff8000");+ expect(p.output).toBe("display");+ });++ test("one that asks for three's tone mapping is scene light, tone-mapped by Bevy", () => {+ const m = new THREE.ShaderMaterial({ vertexShader: "void main(){ gl_Position = vec4(position, 1.0); }", fragmentShader: "void main(){ gl_FragColor = vec4(1.0);\n#include <tonemapping_fragment>\n#include <colorspace_fragment>\n}" });+ const p = shaderPart(m).props as Record<string, any>;+ expect(p.output).toBe("linear");+ expect(p.glsl.fragment).not.toContain("toneMapping");+ });++ test("a texture uniform is a picture; a flipped one is named for the engine to flip", () => {+ const t = new THREE.Texture();+ (t as unknown as { image: unknown }).image = { src: "pics/a.png" };+ const m = new THREE.ShaderMaterial({ uniforms: { map: { value: t } }, vertexShader: "void main(){}", fragmentShader: "uniform sampler2D map; void main(){}" });+ const p = shaderPart(m).props as Record<string, any>;+ expect(p.textures).toEqual({ map: { src: "pics/a.png", colorSpace: "linear" } });+ expect(p.uniforms.map).toBeUndefined();+ });++ test("an include three doesn't have is an error that names it", () => {+ expect(() => expandIncludes("#include <nope>")).toThrow("<nope>");+ });++ test("a geometry's own attributes, the standard four left out", () => {+ const g = new THREE.BufferGeometry();+ g.setAttribute("position", new THREE.Float32BufferAttribute([0, 0, 0, 1, 0, 0], 3));+ g.setAttribute("aRandom", new THREE.Float32BufferAttribute([0.25, 0.75], 1));+ expect(ownAttributes(g)).toEqual({ aRandom: { size: 1, values: [0.25, 0.75] } });+ });+});diff --git a/sdk/r3f/test/tsl.test.ts b/sdk/r3f/test/tsl.test.tsnew file mode 100644index 00000000..92f3b2e6--- /dev/null+++ b/sdk/r3f/test/tsl.test.ts@@ -0,0 +1,193 @@+// TSL node materials as raea's ThreeShaderMaterial (src/input/tsl.ts): three's WGSLNodeBuilder, headless, its WGSL+// rewritten to the engine's contract (systems/three-shader). Each case is checked as text, and, where naga is on this+// machine (`NAGA=/path/to/naga`, or `naga` on PATH), compiled by it against a stand-in of the engine's prelude.+import { describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import * as THREE from "three";+import { MeshBasicNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";+import * as TSLTyped from "three/tsl";+// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes+const { attribute, color, mix, sin, texture, time, uv } = TSLTyped as unknown as Record<string, (...a: unknown[]) => any> & { time: any };+import { composeEffects, configureFontTexture, createText, parseFont, scramble, wipe } from "lettra/three";+import { materialOf } from "../src/input/material";+import { nodeMaterialOf, type NodeAt, type ShaderSpec } from "../src/input/tsl";+import { standInImages } from "../src/input/texture";++standInImages();++const font = parseFont(JSON.parse(readFileSync(resolve(import.meta.dir, "parity/fonts/Inter-400.json"), "utf8")));++function scene(mesh: THREE.Mesh, t = 0): NodeAt {+ const s = new THREE.Scene();+ s.add(mesh);+ const camera = new THREE.PerspectiveCamera(45, 16 / 9, 0.1, 100);+ camera.position.set(0, 0, 5);+ s.updateMatrixWorld();+ camera.updateMatrixWorld();+ return { object: mesh, scene: s, camera, time: t };+}++function lettra() {+ const map = configureFontTexture(new THREE.TextureLoader().load("fonts/Inter-400.png"));+ return createText({ font, map, text: "raea", material: { fill: "#f2cc60" } });+}++/** the engine's prelude, stood in (the contract: systems/three-shader's doc comment) */+/** a part's props (<ThreeShaderMaterial wgsl>) as the compiled spec: the stages, each uniform with its value, the textures */+function specOf(props: unknown): ShaderSpec & Record<string, unknown> {+ const p = props as { wgsl: { vertex: string; fragment: string; uniforms: { name: string; type: string; array?: number }[] }; uniforms: Record<string, number[]>; textures: Record<string, { src: string; colorSpace: string }> } & Record<string, unknown>;+ return { ...p, vertex: p.wgsl.vertex, fragment: p.wgsl.fragment, uniforms: p.wgsl.uniforms.map((u) => ({ ...u, value: p.uniforms[u.name] })), textures: Object.entries(p.textures).map(([name, t]) => ({ name, ...t })) } as unknown as ShaderSpec & Record<string, unknown>;+}++function prelude(spec: ShaderSpec): string {+ let p = "struct ThreeVertex { position: vec3<f32>, normal: vec3<f32>, uv: vec2<f32>, color: vec4<f32>, a0: vec4<f32>, a1: vec4<f32>, a2: vec4<f32>, a3: vec4<f32>, instance: u32 }\n";+ p += "fn three_model(i: u32) -> mat4x4<f32> { return mat4x4<f32>(vec4<f32>(1.0, 0.0, 0.0, 0.0), vec4<f32>(0.0, 1.0, 0.0, 0.0), vec4<f32>(0.0, 0.0, 1.0, 0.0), vec4<f32>(0.0, 0.0, 0.0, 1.0)); }\n";+ p += "fn three_view() -> mat4x4<f32> { return three_model(0u); }\nfn three_projection() -> mat4x4<f32> { return three_model(0u); }\n";+ p += "fn three_camera_position() -> vec3<f32> { return vec3<f32>(0.0); }\nfn three_time() -> f32 { return 0.0; }\n";+ p += "struct Slots { s: array<vec4<f32>, 64> };\n@group(2) @binding(0) var<uniform> slots: Slots;\n";+ let k = 0;+ for (const u of spec.uniforms) {+ const s = (i: number) => (u.array ? `slots.s[${k + i}u + i]` : `slots.s[${k + i}]`);+ const body: Record<string, string> = {+ f32: `${s(0)}.x`, i32: `i32(${s(0)}.x)`, u32: `u32(${s(0)}.x)`, "vec2<f32>": `${s(0)}.xy`, "vec3<f32>": `${s(0)}.xyz`, "vec4<f32>": s(0),+ "mat3x3<f32>": `mat3x3<f32>(${s(0)}.xyz, ${s(1)}.xyz, ${s(2)}.xyz)`, "mat4x4<f32>": `mat4x4<f32>(${s(0)}, ${s(1)}, ${s(2)}, ${s(3)})`,+ };+ p += `fn u_${u.name}(${u.array ? "i: u32" : ""}) -> ${u.type} { return ${body[u.type]}; }\n`;+ k += (u.type.startsWith("mat4") ? 4 : u.type.startsWith("mat3") ? 3 : 1) * (u.array ?? 1);+ }+ spec.textures.forEach((t, i) => (p += `@group(2) @binding(${1 + 2 * i}) var tex_${t.name}: texture_2d<f32>;\n@group(2) @binding(${2 + 2 * i}) var samp_${t.name}: sampler;\n`));+ return p;+}++/** the stand-in images arrive a microtask after load(), as a loader's do */+const loaded = () => new Promise((r) => setTimeout(r, 0));++const naga = process.env.NAGA ?? Bun.which("naga");++/** each stage compiled by naga with the prelude and an entry point, as the engine adds them */+function compiles(spec: ShaderSpec) {+ if (!naga) return;+ const dir = mkdtempSync(join(tmpdir(), "raea-tsl-"));+ const vs = prelude(spec) + spec.vertex + "\n@vertex fn vs(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) t: vec2<f32>, @builtin(instance_index) i: u32) -> ThreeVaryings { return three_vertex(ThreeVertex(p, n, t, vec4<f32>(1.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), i)); }\n";+ const fs = prelude(spec) + spec.fragment + "\n@fragment fn fs(v: ThreeVaryings, @builtin(front_facing) f: bool) -> @location(0) vec4<f32> { return three_fragment(v, f); }\n";+ for (const [name, src] of [["vertex", vs], ["fragment", fs]]) {+ const f = join(dir, `${name}.wgsl`);+ writeFileSync(f, src);+ const r = Bun.spawnSync([naga, f]);+ if (r.exitCode !== 0) throw new Error(`naga refused the ${name} stage:\n${r.stderr.toString()}\n--- source ---\n${src}`);+ }+}++describe("TSL node materials → raea's ThreeShaderMaterial", () => {+ test("lettra's wipe and scramble: its own attributes as a0..a3, its glyph pool as a uniform array", async () => {+ const map = configureFontTexture(new THREE.TextureLoader().load("fonts/Inter-400.png"));+ const json = JSON.parse(readFileSync(resolve(import.meta.dir, "parity/fonts/Inter-400.json"), "utf8"));+ const t = createText({ font, map, text: "raea", material: { fill: "#f2cc60", effect: composeEffects(wipe(), scramble({ font: json, chars: "abc" })) } });+ await loaded();+ const part = nodeMaterialOf(t.mesh.material as THREE.Material, scene(t.mesh))!;+ expect(part.type).toBe("ThreeShaderMaterial");+ const wgsl = (part.props as { wgsl: { attributes: string[]; uniforms: { name: string; array?: number }[] } }).wgsl;+ expect(wgsl.attributes).toEqual(expect.arrayContaining(["layoutX", "glyphIndex", "cellUv"]));+ const pool = wgsl.uniforms.find((u) => u.array)!;+ // the pool is the chars the bake has (its capacity at least one)+ expect(pool.array).toBeGreaterThanOrEqual(1);+ const spec = specOf(part.props);+ expect(spec.fragment + spec.vertex).toContain(`u_${pool.name}(u32(`);+ expect(spec.fragment + spec.vertex).not.toContain("NodeBuffer_");+ compiles(spec);+ });++ test("lettra's MSDF text: three's WGSL in the contract's shape", async () => {+ const t = lettra();+ await loaded();+ const part = nodeMaterialOf(t.mesh.material as THREE.Material, scene(t.mesh))!;+ expect(part.type).toBe("ThreeShaderMaterial");+ const spec = specOf(part.props);+ expect(spec.vertex).toContain("fn three_vertex(v: ThreeVertex) -> ThreeVaryings {");+ expect(spec.vertex).toContain("three_projection()");+ expect(spec.vertex).toContain("three_view()");+ expect(spec.vertex).toContain("three_model(tsl_instance)");+ expect(spec.fragment).toContain("fn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> {");+ expect(spec.fragment).toMatch(/struct ThreeVaryings \{[^}]*@builtin\( position \) clip : vec4<f32>/);+ // the MSDF fill: the median of three channels, antialiased by its screen-space rate+ expect(spec.fragment).toMatch(/textureSample\( tex_\w+, samp_\w+, /);+ expect(spec.fragment).toContain("fwidth");+ for (const s of [spec.vertex, spec.fragment]) {+ expect(s).not.toMatch(/@group|@binding|@vertex|@fragment|diagnostic/);+ expect(s).not.toMatch(/\b(render|object)\./);+ }+ expect(spec.textures).toEqual([{ name: expect.any(String), src: "fonts/Inter-400.png", colorSpace: "linear" }]);+ // the fill colour, linear, as three keeps it+ const fill = new THREE.Color("#f2cc60");+ expect(spec.uniforms.find((u) => u.type === "vec3<f32>")!.value.map((x) => +x.toFixed(4))).toEqual([fill.r, fill.g, fill.b].map((x) => +x.toFixed(4)));+ expect(spec.output).toBe("linear");+ expect(spec.transparent).toBe(true);+ expect(spec.depthWrite).toBe(false);+ compiles(spec);+ });++ test("a graph's uniforms move with R3F's clock (TSL's time)", () => {+ const m = new MeshBasicNodeMaterial();+ m.colorNode = mix(color("#58a6ff"), color("#e05a2b"), uv().y).mul(sin(time.mul(2)).mul(0.25).add(0.75));+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(), m);+ const at = (t: number) => specOf(nodeMaterialOf(m, scene(mesh, t))!.props).uniforms;+ const a = at(0), b = at(0.5);+ const timed = a.findIndex((u, i) => u.type === "f32" && u.value[0] !== b[i].value[0]);+ expect(timed).toBeGreaterThanOrEqual(0);+ expect(a[timed].value[0]).toBe(0);+ expect(b[timed].value[0]).toBe(0.5);+ compiles(specOf(nodeMaterialOf(m, scene(mesh, 0.5))!.props));+ });++ test("a flipped picture is sampled flipped (the graph's uvs are three's, unflipped)", async () => {+ const tex = new THREE.TextureLoader().load("pic.png");+ await loaded();+ expect(tex.flipY).toBe(true);+ const m = new MeshBasicNodeMaterial();+ m.colorNode = texture(tex, uv()).rgb;+ const spec = specOf(nodeMaterialOf(m, scene(new THREE.Mesh(new THREE.PlaneGeometry(), m)))!.props);+ expect(spec.fragment).toMatch(/textureSample\( tex_\w+, samp_\w+, tsl_flip_v\(/);+ expect(spec.textures[0].colorSpace).toBe("linear");+ compiles(spec);+ });++ test("a node material with no node of its own is its classic material, drawn natively", () => {+ const m = new MeshStandardNodeMaterial({ color: "#3fb950", roughness: 0.3, metalness: 0.2 });+ const part = materialOf(m, false, scene(new THREE.Mesh(new THREE.BoxGeometry(), m)));+ expect(part.type).toBe("MeshStandardMaterial");+ expect(part.props).toMatchObject({ color: "#3fb950", roughness: 0.3, metalness: 0.2 });+ });++ test("a lit node material with a graph is lit by three's own light nodes", () => {+ const m = new MeshStandardNodeMaterial();+ m.colorNode = mix(color("#ff0000"), color("#0000ff"), uv().x);+ const mesh = new THREE.Mesh(new THREE.SphereGeometry(), m);+ const at = scene(mesh);+ at.scene.add(new THREE.DirectionalLight("#ffffff", 2));+ const part = materialOf(m, false, at);+ expect(part.type).toBe("ThreeShaderMaterial");+ compiles(specOf(part.props));+ });++ test("a graph raea can't carry is refused by name and drawn flat", () => {+ const warn = console.warn;+ const said: string[] = [];+ console.warn = (s: string) => said.push(s);+ try {+ const m = new MeshBasicNodeMaterial();+ // five attributes of the mesh's own, one more than the engine carries+ const names = ["aOne", "aTwo", "aThree", "aFour", "aFive"];+ m.colorNode = names.map((n) => attribute(n, "float")).reduce((x, y) => x.add(y)).mul(0.1).toVec3();+ const g = new THREE.BufferGeometry();+ g.setAttribute("position", new THREE.Float32BufferAttribute([0, 0, 0, 1, 0, 0, 0, 1, 0], 3));+ for (const n of names) g.setAttribute(n, new THREE.Float32BufferAttribute([0, 1, 2], 1));+ const part = materialOf(m, false, scene(new THREE.Mesh(g, m)));+ expect(part.type).toBe("MeshBasicMaterial");+ expect(said.join("\n")).toContain("more than 4 vertex attributes");+ } finally {+ console.warn = warn;+ }+ });+});diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.shindex 55cff2ad..5055fea5 100755--- a/sdk/r3f/tools/parity.sh+++ b/sdk/r3f/tools/parity.sh@@ -9,7 +9,7 @@ OUT=${1:-$(mktemp -d)}URL=${R3F_PARITY_URL:-serve}[ -f wasm/raea_shape_web.js ] || tools/shape-wasm.shMIN=${MIN:-0.92}-CASES=(in-basic:24 in-lights:0 in-things:0 in-catch:0 out-basic:24 out-tony:24 out-lights:0 out-bloom:0 out-grade:0 out-lens:0 out-catch:0 out-entities:10 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0 src-catch:0 src-entities:10)+CASES=(in-basic:24 in-lights:0 in-things:0 in-catch:0 in-lettra:12 in-lettrafx:12 in-shader:12 in-post:0 in-drei:12 in-approx:0 out-basic:24 out-tony:24 out-lights:0 out-bloom:0 out-grade:0 out-lens:0 out-catch:0 out-entities:10 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0 src-catch:0 src-entities:10)mkdir -p "$OUT"for c in "${CASES[@]}"; do# a src-* case is its out-* composition, drawn from the R3F source the source export wrote for itdiff --git a/sdk/r3f/tools/serve.ts b/sdk/r3f/tools/serve.tsindex 4e085c79..09b75bc0 100644--- a/sdk/r3f/tools/serve.ts+++ b/sdk/r3f/tools/serve.ts@@ -51,11 +51,22 @@ export async function serve(port = 0): Promise<{ url: string; stop: () => void }});if (!result.success) throw new AggregateError(result.logs, "serve: the parity page didn't build");const page = `<!doctype html><meta charset="utf-8"><body style="margin:0;background:#000"><div id="root"></div><script type="module" src="/main.js"></script>`;+ const fetched = new Map<string, Promise<ArrayBuffer>>();+ const dreiAsset = async (rest: string) => {+ const url = `https://raw.githubusercontent.com/pmndrs/drei-assets/${rest}`;+ if (!fetched.has(url)) fetched.set(url, fetch(url).then((r) => (r.ok ? r.arrayBuffer() : Promise.reject(new Error(`${url}: ${r.status}`)))));+ return new Response(await fetched.get(url)!);+ };const server = Bun.serve({port,fetch(req) {const p = new URL(req.url).pathname;if (p === "/" || p === "/index.html") return new Response(page, { headers: { "content-type": "text/html" } });+ // the cases' own files: lettra's font atlas and the drei case's face (test/parity/fonts), its model (models)+ if (p.startsWith("/fonts/") || p.startsWith("/models/")) return new Response(Bun.file(resolve(here, "test/parity", p.slice(1))));+ // drei's <Environment preset> panoramas (the page sends them here, so Chrome makes no outside request): fetched+ // from drei's assets once a run+ if (p.startsWith("/drei-assets/")) return dreiAsset(p.slice("/drei-assets/".length));if (p.startsWith("/wasm/")) {const f = Bun.file(resolve(here, "wasm", p.slice(6)));return new Response(f, { headers: { "content-type": p.endsWith(".wasm") ? "application/wasm" : "text/javascript" } });diff --git a/sdk/r3f/tools/shoot.ts b/sdk/r3f/tools/shoot.tsindex a8924dd1..09a3a13e 100644--- a/sdk/r3f/tools/shoot.ts+++ b/sdk/r3f/tools/shoot.ts@@ -8,7 +8,7 @@ const [baseArg, out, ...only] = process.argv.slice(2);if (!baseArg || !out) throw new Error("usage: bun tools/shoot.ts BASE_URL|serve OUT_DIR [in-basic ...]");const served = baseArg === "serve" ? await serve() : undefined;const base = served?.url ?? baseArg;-const cases = only.length ? only : ["in-basic", "in-lights", "in-things", "in-catch", "out-basic", "out-tony", "out-lights", "out-bloom", "out-grade", "out-lens", "out-catch", "out-entities", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens", "src-catch", "src-entities"];+const cases = only.length ? only : ["in-basic", "in-lights", "in-things", "in-catch", "in-lettra", "in-lettrafx", "in-shader", "in-post", "in-drei", "in-approx", "out-basic", "out-tony", "out-lights", "out-bloom", "out-grade", "out-lens", "out-catch", "out-entities", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens", "src-catch", "src-entities"];let failed = 0;for (const c of cases) {const [dir, name] = c.split("-");diff --git a/sdk/raea/bench/bevy-parity/2d/mesh2d.tsx b/sdk/raea/bench/bevy-parity/2d/mesh2d.tsxnew file mode 100644index 00000000..97fbc2d0--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/mesh2d.tsx@@ -0,0 +1,21 @@+// Bevy v0.20.0 examples/2d/mesh2d.rs in raea's TSX (docs/control.feature FC0a): a Camera2d and a default Rectangle+// scaled to 128 px with a PURPLE ColorMaterial, on Bevy's default clear colour, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot } from "raea";+import { Canvas3D } from "raea/3d";+import { Transform } from "raea/transform";+import { ColorMaterial, Mesh2d, Rectangle } from "raea/sprite";++function Shot() {+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Mesh2d transform={Transform.IDENTITY.withScale([128, 128, 1])}>+ <Rectangle />+ <ColorMaterial color="#800080" />+ </Mesh2d>+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/move_sprite.tsx b/sdk/raea/bench/bevy-parity/2d/move_sprite.tsxnew file mode 100644index 00000000..2cecc45c--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/move_sprite.tsx@@ -0,0 +1,32 @@+// Bevy v0.20.0 examples/2d/move_sprite.rs in raea's TSX (docs/control.feature FC0a): Bevy's icon (branding/icon.png) as a Sprite+// moving along X at 150 px/s from the middle, turning back past +-200 px, on Bevy's default clear colour, in Bevy's+// default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++/** sprite_movement over the updates up to frame f: each moves by 150 x its delta_secs (none on the first), then turns */+function xAt(f: number): number {+ let x = 0;+ let right = true;+ for (let k = 0; k <= f; k++) {+ // Bevy's delta: a Duration of 16_666_667 ns as f32 seconds (0.016666668), which tips x past 200 an update sooner+ const dt = k === 0 ? 0 : Math.fround(16_666_667e-9);+ x = Math.fround(x + (right ? 1 : -1) * Math.fround(150 * dt));+ if (x > 200) right = false;+ else if (x < -200) right = true;+ }+ return x;+}++function Shot() {+ const x = xAt(useCurrentFrame());+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("branding/icon.png")} x={640 + x} y={360} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={121} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/sprite.tsx b/sdk/raea/bench/bevy-parity/2d/sprite.tsxnew file mode 100644index 00000000..e246fdcf--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/sprite.tsx@@ -0,0 +1,17 @@+// Bevy v0.20.0 examples/2d/sprite.rs in raea's TSX (docs/control.feature FC0a): a Camera2d and Bevy's bird+// (branding/bevy_bird_dark.png) as a Sprite at its own size in the middle, on Bevy's default clear colour, in Bevy's+// default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++function Shot() {+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("branding/bevy_bird_dark.png")} x={640} y={360} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/sprite_animation.tsx b/sdk/raea/bench/bevy-parity/2d/sprite_animation.tsxnew file mode 100644index 00000000..8235966e--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/sprite_animation.tsx@@ -0,0 +1,47 @@+// Bevy v0.20.0 examples/2d/sprite_animation.rs in raea's TSX (docs/control.feature FC0a): gabe's sheet twice, 6x and+// sampled nearest, at x -70 and 70, each stepping from cell 1 to 6 on a Once timer of 1/fps s (10 and 20 fps), back+// to 1 at the end and stopping there (no arrow key starts them again), and two lines of instructions in Bevy's default+// font at top 12, left 12, on Bevy's default clear colour, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;+const SHEET = staticFile("textures/rpg/chars/gabe/gabe-idle-run.png");+const DELTA = 16_666_667; // Bevy's 1/60 s Duration, in nanoseconds++/** execute_animations up to frame f: a Once timer of Duration::from_secs_f32(1 / fps) ticked by each delta (none on+ * the first); each finish steps the cell and starts a new timer, but the one finishing on the last cell goes back to+ * the first and starts none */+function cellAt(f: number, fps: number): number {+ const dur = Math.floor(Math.fround(1 / fps) * 1e9);+ let idx = 1, el = 0, running = true;+ for (let k = 0; k <= f; k++) {+ if (!running) break;+ el += k === 0 ? 0 : DELTA;+ if (el < dur) continue;+ if (idx === 6) {+ idx = 1;+ running = false;+ } else {+ idx += 1;+ el = 0;+ }+ }+ return idx;+}++function Shot() {+ const f = useCurrentFrame();+ return (+ <AbsoluteFill>+ <style>{FONT}</style>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={SHEET} grid={[7, 1]} frame={cellAt(f, 10)} x={640 - 70} y={360} scale={6} />+ <Sprite src={SHEET} grid={[7, 1]} frame={cellAt(f, 20)} x={640 + 70} y={360} scale={6} />+ </Canvas3D>+ <div style={{ position: "absolute", top: 12, left: 12, fontFamily: "Fira Mono", fontSize: 20, lineHeight: 1.2, color: "#fff", whiteSpace: "pre" }}>{"Left Arrow: Animate Left Sprite\nRight Arrow: Animate Right Sprite"}</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/sprite_flipping.tsx b/sdk/raea/bench/bevy-parity/2d/sprite_flipping.tsxnew file mode 100644index 00000000..e2b2e253--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/sprite_flipping.tsx@@ -0,0 +1,16 @@+// Bevy v0.20.0 examples/2d/sprite_flipping.rs in raea's TSX (docs/control.feature FC0a): Bevy's bird (branding/bevy_bird_dark.png) as a Sprite+// flipped in X, at its own size in the middle, on Bevy's default clear colour, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++function Shot() {+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("branding/bevy_bird_dark.png")} x={640} y={360} flipX />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/sprite_sheet.tsx b/sdk/raea/bench/bevy-parity/2d/sprite_sheet.tsxnew file mode 100644index 00000000..9f367f2c--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/sprite_sheet.tsx@@ -0,0 +1,25 @@+// Bevy v0.20.0 examples/2d/sprite_sheet.rs in raea's TSX (docs/control.feature FC0a): gabe's idle-and-run sheet+// (textures/rpg/chars/gabe/gabe-idle-run.png, seven 24 px cells in a row) as a Sprite scaled 6x, sampled nearest, its+// cell stepping from 1 to 6 and round again each time a 0.1 s repeating timer finishes, on Bevy's default clear colour,+// in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++/** animate_sprite over the updates up to frame f: the timer ticks by each delta (Bevy's Duration of 1/60 s, in whole+ * nanoseconds; none on the first) and the cell steps once per finish */+function cellAt(f: number): number {+ const finishes = Math.floor((f * 16_666_667) / 100_000_000);+ return 1 + (finishes % 6);+}++function Shot() {+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("textures/rpg/chars/gabe/gabe-idle-run.png")} grid={[7, 1]} frame={cellAt(useCurrentFrame())} x={640} y={360} scale={6} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/sprite_tile.tsx b/sdk/raea/bench/bevy-parity/2d/sprite_tile.tsxnew file mode 100644index 00000000..66db2667--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/sprite_tile.tsx@@ -0,0 +1,30 @@+// Bevy v0.20.0 examples/2d/sprite_tile.rs in raea's TSX (docs/control.feature FC0a): Bevy's icon tiled every 128 px+// (SpriteImageMode::Tiled, stretch_value 0.5) across a square sprite whose size bounces between 128 and 512 px at+// 50 px/s, on Bevy's default clear colour, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++/** `animate` over the updates up to frame f, in f32 as Bevy has it: turn at either end, then grow by speed x delta+ * (none on the first update; then Bevy's 16_666_667 ns as f32 seconds) */+function sizeAt(f: number): number {+ const dt = Math.fround(16_666_667e-9);+ let [current, speed] = [128, 50];+ for (let k = 0; k <= f; k++) {+ if (current >= 512 || current <= 128) speed = -speed;+ current = Math.fround(current + Math.fround(speed * (k === 0 ? 0 : dt)));+ }+ return current;+}++function Shot() {+ const s = sizeAt(useCurrentFrame());+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("branding/icon.png")} x={640} y={360} width={s} height={s} tileX tileY tileStretch={0.5} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={301} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/2d/transparency_2d.tsx b/sdk/raea/bench/bevy-parity/2d/transparency_2d.tsxnew file mode 100644index 00000000..853afc4f--- /dev/null+++ b/sdk/raea/bench/bevy-parity/2d/transparency_2d.tsx@@ -0,0 +1,21 @@+// Bevy v0.20.0 examples/2d/transparency_2d.rs in raea's TSX (docs/control.feature FC0a): Bevy's icon (branding/icon.png) three times, 100 px apart:+// plain, tinted blue at 0.7 alpha and tinted green at 0.3 alpha, each drawn over the last (z 0, 0.1, 0.2), on Bevy's+// default clear colour, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++const ICON = staticFile("branding/icon.png");++function Shot() {+ return (+ <AbsoluteFill>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={ICON} x={540} y={360} z={0} />+ <Sprite src={ICON} x={640} y={360} z={0.1} color="#0000ff" opacity={0.7} />+ <Sprite src={ICON} x={740} y={360} z={0.2} color="#00ff00" opacity={0.3} />+ </Canvas3D>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/animated_material.tsx b/sdk/raea/bench/bevy-parity/3d/animated_material.tsxnew file mode 100644index 00000000..c7bf81f2--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/animated_material.tsx@@ -0,0 +1,52 @@+// Bevy v0.20.0 examples/3d/animated_material.rs in raea's TSX (docs/control.feature FC0a): nine 0.5 m cubes in a 3 x 3+// grid, each StandardMaterial an Hsla stepped by the golden angle from red, every hue turning 100 degrees a second, lit+// by Pisa's prefiltered EnvironmentMapLight at 2000 on the camera at (3, 1, 3), in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { EnvironmentMapLight } from "raea/light";++const GOLDEN_ANGLE = Math.fround(137.50777);++/** Bevy's Hsla (s 1, l 0.5) as sRGB 0-255, through its Hsva as bevy_color converts it */+function rgbOf(h: number): string {+ const c = 1, x = c * (1 - Math.abs(((h / 60) % 2) - 1));+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x];+ return `rgb(${r * 255}, ${g * 255}, ${b * 255})`;+}++/** rotate_hue: (hue + degrees) mod 360, in f32, from the start and then by each update's delta_secs x 100 */+function hueAt(start: number, f: number): number {+ let h = start;+ for (let k = 1; k <= f; k++) h = Math.fround(Math.fround(h + Math.fround(Math.fround(1 / 60) * 100)) % 360);+ return h;+}++const START: number[] = [];+for (let i = 0, h = 0; i < 9; i++, h = Math.fround(Math.fround(h + GOLDEN_ANGLE) % 360)) START.push(h);++function Shot() {+ const f = useCurrentFrame();+ const cubes = [];+ for (let x = -1, i = 0; x < 2; x++) {+ for (let z = -1; z < 2; z++, i++) {+ cubes.push(+ <Mesh3d key={i} transform={Transform.fromXyz(x, 0, z)}>+ <Cuboid half_size={[0.25, 0.25, 0.25]} />+ <StandardMaterial base_color={rgbOf(hueAt(START[i], f))} />+ </Mesh3d>,+ );+ }+ }+ return (+ <>+ {cubes}+ <Camera3d transform={Transform.fromXyz(3, 1, 3).lookingAt([0, -0.5, 0])} />+ <EnvironmentMapLight diffuse_map={staticFile("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2")} specular_map={staticFile("environment_maps/pisa_specular_rgb9e5_zstd.ktx2")} intensity={2000} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/bloom_3d.tsx b/sdk/raea/bench/bevy-parity/3d/bloom_3d.tsxnew file mode 100644index 00000000..7488cd7b--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/bloom_3d.tsx@@ -0,0 +1,76 @@+// Bevy v0.20.0 examples/3d/bloom_3d.rs in raea's TSX (docs/control.feature FC0a): a 10 x 10 grid of spheres bouncing on+// a sine, a quarter of them emissive in Bevy's units (blue 150, white 1000, red 50: LinearRgba, as Bevy writes them)+// and the rest black, under Bloom::NATURAL with TonyMcMapface on black, and the example's settings text. Each sphere's+// material is the example's: Rust's DefaultHasher (SipHash-1-3, keys 0) of its (x, z), plus 3, mod 6.+import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Bloom, Sphere, ToneMapping } from "raea/3d";+import { Camera3d } from "raea/camera";+import { LinearRgba } from "raea/color";+import { Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const M = (1n << 64n) - 1n;+const rotl = (x: bigint, b: bigint) => ((x << b) | (x >> (64n - b))) & M;+/** Rust's DefaultHasher over `bytes`: SipHash-1-3 with zero keys, the length in the last block */+function sip13(bytes: number[]): bigint {+ let [v0, v1, v2, v3] = [0x736f6d6570736575n, 0x646f72616e646f6dn, 0x6c7967656e657261n, 0x7465646279746573n];+ const round = () => {+ v0 = (v0 + v1) & M; v1 = rotl(v1, 13n); v1 ^= v0; v0 = rotl(v0, 32n);+ v2 = (v2 + v3) & M; v3 = rotl(v3, 16n); v3 ^= v2;+ v0 = (v0 + v3) & M; v3 = rotl(v3, 21n); v3 ^= v0;+ v2 = (v2 + v1) & M; v1 = rotl(v1, 17n); v1 ^= v2; v2 = rotl(v2, 32n);+ };+ const word = (at: number, n: number) => { let w = 0n; for (let i = 0; i < n; i++) w |= BigInt(bytes[at + i]!) << BigInt(8 * i); return w; };+ const full = bytes.length - (bytes.length % 8);+ for (let at = 0; at < full; at += 8) { const m = word(at, 8); v3 ^= m; round(); v0 ^= m; }+ const last = word(full, bytes.length - full) | (BigInt(bytes.length & 0xff) << 56n);+ v3 ^= last; round(); v0 ^= last;+ v2 ^= 0xffn; round(); round(); round();+ return v0 ^ v1 ^ v2 ^ v3;+}+const le32 = (n: number) => [n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >>> 24) & 0xff];++// the example's materials (emissive in Bevy's units; base colour white but for the black one) and each one's scale+const KINDS = [+ { emissive: new LinearRgba(0, 0, 150), scale: 0.5 },+ { emissive: new LinearRgba(1000, 1000, 1000), scale: 0.1 },+ { emissive: new LinearRgba(50, 0, 0), scale: 1 },+];+const GRID: { x: number; z: number; kind: number }[] = [];+for (let x = -5; x < 5; x++) for (let z = -5; z < 5; z++) GRID.push({ x, z, kind: Number(((sip13([...le32(x), ...le32(z)]) + 3n) & M) % 6n) });++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;+const TEXT = [+ "Bloom (Toggle: Space)", "(Q/A) Intensity: 0.15", "(W/S) Low-frequency boost: 0.70", "(E/D) Low-frequency boost curvature: 0.95",+ "(R/F) High-pass frequency: 1.00", "(T/G) Mode: Energy-conserving", "(Y/H) Threshold: 0.00", "(U/J) Threshold softness: 0.00",+ "(I/K) Horizontal Scale: 1.00",+].join("\n");++function Shot() {+ // bounce_spheres: y = sin(x + z + elapsed), elapsed f updates of 16_666_667 ns (none on the first), as f32+ const t = Math.fround(useCurrentFrame() * 16_666_667e-9);+ return (+ <AbsoluteFill style={{ background: "#000000" }}>+ <style>{FONT}</style>+ <Camera3d transform={Transform.fromXyz(-2, 2.5, 5).lookingAt([0, 0, 0])} />+ <ToneMapping mode="tony" />+ <Bloom intensity={1} threshold={0} />+ {GRID.map(({ x, z, kind }) => {+ const k = KINDS[kind];+ const s = k?.scale ?? 1.5;+ const [px, pz] = [x * 2, z * 2];+ return (+ <Mesh3d key={`${x},${z}`} transform={{ translation: [px, Math.fround(Math.sin(Math.fround(Math.fround(px + pz) + t))), pz], scale: [s, s, s] }}>+ <Sphere radius={0.4} />+ {k ? <StandardMaterial emissive={k.emissive} /> : <StandardMaterial base_color="#000000" />}+ </Mesh3d>+ );+ })}+ {/* the text ends in a newline: an empty last line in Bevy's text, which HTML drops, so its height as padding */}+ <div style={{ position: "absolute", left: 12, bottom: 12, paddingBottom: 24, fontFamily: "Fira Mono", fontSize: 20, lineHeight: 1.2, color: "#fff", whiteSpace: "pre" }}>{TEXT}</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/fog_volumes.tsx b/sdk/raea/bench/bevy-parity/3d/fog_volumes.tsxnew file mode 100644index 00000000..6d7ce457--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/fog_volumes.tsx@@ -0,0 +1,32 @@+// Bevy v0.20.0 examples/3d/fog_volumes.rs in raea's TSX (docs/control.feature FC0a): a unit fog volume shaped by+// Bevy's bunny density texture (volumes/bunny.ktx2), lit through by a volumetric sun of 32 000 lux, seen by a camera+// marching 64 steps (Bevy's VolumetricFog) with no ambient light. The camera turns 0.01 rad about Y every update, the+// first too, looking at (0, 0.5, 0).+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Camera3d } from "raea/camera";+import { DirectionalLight, GlobalAmbientLight } from "raea/light";+import { FogVolume, VolumetricFog } from "raea/pbr";+import { Transform } from "raea/transform";++/** rotate_camera over the updates up to frame f: the translation turned by Ry(0.01) each time, in f32 */+function eyeAt(f: number): [number, number, number] {+ const [c, s] = [Math.fround(Math.cos(0.01)), Math.fround(Math.sin(0.01))];+ let [x, y, z] = [-0.75, 1, 2];+ for (let k = 0; k <= f; k++) [x, z] = [Math.fround(Math.fround(c * x) + Math.fround(s * z)), Math.fround(Math.fround(c * z) - Math.fround(s * x))];+ return [x, y, z];+}++function Shot() {+ const [x, y, z] = eyeAt(useCurrentFrame());+ return (+ <>+ <GlobalAmbientLight brightness={0} />+ <FogVolume position={[0, 0.5, 0]} density_texture={staticFile("volumes/bunny.ktx2")} density={1} scattering={1} />+ <DirectionalLight shadow_maps_enabled illuminance={32000} volumetric transform={Transform.fromXyz(1, 1, -0.3).lookingAt([0, 0.5, 0])} />+ <Camera3d transform={Transform.fromXyz(x, y, z).lookingAt([0, 0.5, 0])} />+ <VolumetricFog mode="march" steps={64} ambient={0} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/orthographic.tsx b/sdk/raea/bench/bevy-parity/3d/orthographic.tsxnew file mode 100644index 00000000..f1d13c91--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/orthographic.tsx@@ -0,0 +1,32 @@+// Bevy v0.20.0 examples/3d/orthographic.rs in raea's TSX (docs/control.feature FC0a): an orthographic camera 6 m tall+// (ScalingMode::FixedVertical) at (5, 5, 5) looking at the origin, a 5 m green plane, four 1 m cubes of+// srgb(0.8, 0.7, 0.6) at (+-1.5, 0.5, +-1.5) and a default PointLight at (3, 8, 5), in Bevy's default 1280 x 720 window.+import { Composition, registerRoot } from "raea";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { PointLight } from "raea/light";++const CUBES: [number, number][] = [[1.5, 1.5], [1.5, -1.5], [-1.5, 1.5], [-1.5, -1.5]];++function Shot() {+ return (+ <>+ <Camera3d projection={{ Orthographic: { scaling_mode: { FixedVertical: { viewport_height: 6 } } } }} transform={Transform.fromXyz(5, 5, 5).lookingAt([0, 0, 0])} />+ <Mesh3d transform={Transform.IDENTITY}>+ <Plane3d half_size={[2.5, 2.5]} />+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" />+ </Mesh3d>+ {CUBES.map(([x, z], i) => (+ <Mesh3d key={i} transform={Transform.fromXyz(x, 0.5, z)}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <StandardMaterial base_color="rgb(204, 178.5, 153)" />+ </Mesh3d>+ ))}+ <PointLight transform={Transform.fromXyz(3, 8, 5)} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/parenting.tsx b/sdk/raea/bench/bevy-parity/3d/parenting.tsxnew file mode 100644index 00000000..2219c511--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/parenting.tsx@@ -0,0 +1,36 @@+// Bevy v0.20.0 examples/3d/parenting.rs in raea's TSX (docs/control.feature FC0a): a 2 m cube of srgb(0.8, 0.7, 0.6)+// at (0, 0, 1) turning about X at 3 rad/s, with a child cube 3 m along its own Z, under a default PointLight at+// (4, 5, -4), the camera at (5, 10, 10) looking at the origin, in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Entity } from "raea/3d";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { PointLight } from "raea/light";++function Cube({ z }: { z: number }) {+ return (+ <Mesh3d transform={Transform.fromXyz(0, 0, z)}>+ <Cuboid half_size={[1, 1, 1]} />+ <StandardMaterial base_color="rgb(204, 178.5, 153)" />+ </Mesh3d>+ );+}++function Shot() {+ // rotator_system: rotate_x by 3 x each update's delta_secs (none on the first)+ const a = (3 * useCurrentFrame()) / 60;+ return (+ <>+ <Entity transform={{ translation: [0, 0, 1], rotation: Quat.fromRotationX(a) }}>+ <Cube z={0} />+ <Cube z={3} />+ </Entity>+ <PointLight transform={Transform.fromXyz(4, 5, -4)} />+ <Camera3d transform={Transform.fromXyz(5, 10, 10).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/pbr.tsx b/sdk/raea/bench/bevy-parity/3d/pbr.tsxnew file mode 100644index 00000000..3dbc403a--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/pbr.tsx@@ -0,0 +1,48 @@+// Bevy v0.20.0 examples/3d/pbr.rs in raea's TSX (docs/control.feature FC0a): 11 x 5 spheres of #ffd891, roughness+// rising to the right and metal upwards, an unlit one below, a 1500 lx DirectionalLight from (50, 50, 50), Pisa's+// prefiltered EnvironmentMapLight at 900 on an orthographic camera (ScalingMode::WindowSize at 0.01: 7.2 m tall), and+// its two labels in Bevy's default font at 30 px (the "Loading" label is gone once the maps load), in Bevy's default+// 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D } from "raea/3d";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Mesh3d, Sphere } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { DirectionalLight, EnvironmentMapLight } from "raea/light";++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;+const label = { position: "absolute", fontFamily: "Fira Mono", fontSize: 30, color: "#fff" } as const;++function Shot() {+ const balls = [];+ for (let y = -2; y <= 2; y++) {+ for (let x = -5; x <= 5; x++) {+ balls.push(+ <Mesh3d key={`${x},${y}`} transform={Transform.fromXyz(x, y + 0.5, 0)}>+ <Sphere radius={0.45} />+ <StandardMaterial base_color="#ffd891" metallic={(y + 2) / 4} perceptual_roughness={(x + 5) / 10} />+ </Mesh3d>,+ );+ }+ }+ return (+ <AbsoluteFill>+ <style>{FONT}</style>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ {balls}+ <Mesh3d transform={Transform.fromXyz(-5, -2.5, 0)}>+ <Sphere radius={0.45} />+ <StandardMaterial base_color="#ffd891" unlit />+ </Mesh3d>+ <DirectionalLight illuminance={1500} transform={Transform.fromXyz(50, 50, 50).lookingAt([0, 0, 0])} />+ <Camera3d projection={{ Orthographic: { scaling_mode: { FixedVertical: { viewport_height: 7.2 } } } }} transform={Transform.fromXyz(0, 0, 8).lookingAt([0, 0, 0])} />+ <EnvironmentMapLight diffuse_map={staticFile("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2")} specular_map={staticFile("environment_maps/pisa_specular_rgb9e5_zstd.ktx2")} intensity={900} />+ </Canvas3D>+ <div style={{ ...label, top: 20, left: 100 }}>Perceptual Roughness</div>+ <div style={{ ...label, top: 130, right: 0, transform: "rotate(90deg)" }}>Metallic</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/spherical_area_lights.tsx b/sdk/raea/bench/bevy-parity/3d/spherical_area_lights.tsxnew file mode 100644index 00000000..4c046822--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/spherical_area_lights.tsx@@ -0,0 +1,42 @@+// Bevy v0.20.0 examples/3d/spherical_area_lights.rs in raea's TSX (docs/control.feature FC0a): six blue point lights+// along X, each in an unlit sphere of its radius (0 to 0.33 m), over a shiny grey floor whose highlights grow with+// the radius (a spherical area light: PointLight's radius); GlobalAmbientLight at 60.+import { Composition, registerRoot } from "raea";+import { Fragment } from "react";+import { Camera3d } from "raea/camera";+import { GlobalAmbientLight, PointLight } from "raea/light";+import { Mesh3d, Plane3d, Sphere } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const COUNT = 6;++function Shot() {+ return (+ <>+ <GlobalAmbientLight brightness={60} />+ <Camera3d transform={Transform.fromXyz(0.2, 1.5, 2.5).lookingAt([0, 0, 0])} />+ <Mesh3d>+ <Plane3d half_size={[50, 50]} />+ <StandardMaterial base_color="rgb(51, 51, 51)" perceptual_roughness={0.08} />+ </Mesh3d>+ {Array.from({ length: COUNT }, (_, i) => {+ const percent = Math.fround(i / COUNT);+ const radius = Math.fround(percent * 0.4);+ const x = Math.fround(-2 + Math.fround(percent * 4));+ return (+ // the light is the sphere's child in Bevy, at its centre (the sphere's scale doesn't size a light)+ <Fragment key={i}>+ <Mesh3d transform={{ translation: [x, 0.3, 0], scale: [radius, radius, radius] }}>+ <Sphere radius={1} uv={[120, 64]} />+ <StandardMaterial base_color="rgb(127.5, 127.5, 255)" unlit />+ </Mesh3d>+ <PointLight radius={radius} color="rgb(51, 51, 255)" transform={Transform.fromXyz(x, 0.3, 0)} />+ </Fragment>+ );+ })}+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/texture.tsx b/sdk/raea/bench/bevy-parity/3d/texture.tsxnew file mode 100644index 00000000..e058b243--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/texture.tsx@@ -0,0 +1,38 @@+// Bevy v0.20.0 examples/3d/texture.rs in raea's TSX (docs/control.feature FC0a): three 8 x 2 m quads of Bevy's logo+// (branding/bevy_logo_dark_big.png), unlit and blended, tilted -PI/5 about X at z 1.5, 0 and -1.5, the middle one+// tinted red and the back one blue at 0.5 alpha, the camera at (3, 5, 8) looking at the origin, in Bevy's default+// 1280 x 720 window.+import { Composition, registerRoot, staticFile } from "raea";+import { Quat } from "raea/transform";+import { Srgba } from "raea/color";+import { Camera3d } from "raea/camera";+import { Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const LOGO = staticFile("branding/bevy_logo_dark_big.png");+// a Rectangle (XY, facing +Z) is a Plane3d (XZ, facing +Y) turned +PI/2 about X+const UPRIGHT = Quat.fromRotationX(Math.PI / 2);+const TILT = Quat.fromRotationX(-Math.PI / 5);++function Quad({ z, tint }: { z: number; tint?: string }) {+ return (+ <Mesh3d transform={{ translation: [0, 0, z], rotation: Quat.mul(TILT, UPRIGHT) }}>+ <Plane3d half_size={[4, 1]} />+ <StandardMaterial base_color={tint ? Srgba.hex(tint).with_alpha(0.5) : "#ffffff"} base_color_texture={LOGO} alpha_mode="Blend" unlit />+ </Mesh3d>+ );+}++function Shot() {+ return (+ <>+ <Quad z={1.5} />+ <Quad z={0} tint="#ff0000" />+ <Quad z={-1.5} tint="#0000ff" />+ <Camera3d transform={Transform.fromXyz(3, 5, 8).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/3d/vertex_colors.tsx b/sdk/raea/bench/bevy-parity/3d/vertex_colors.tsxnew file mode 100644index 00000000..29e4943f--- /dev/null+++ b/sdk/raea/bench/bevy-parity/3d/vertex_colors.tsx@@ -0,0 +1,45 @@+// Bevy v0.20.0 examples/3d/vertex_colors.rs in raea's TSX (docs/control.feature FC0a): a 5 m green plane and a unit+// cube whose vertices are coloured from their positions ((1 - p) / 2 a channel, linear), under a shadowed point light.+// The cube is Bevy's Cuboid mesh vertex for vertex (bevy_mesh cuboid.rs: 24 vertices, each face two triangles split+// on the same diagonal), as a BufferMesh with ATTRIBUTE_COLOR, so the colours interpolate across the same triangles.+import { Composition, registerRoot } from "raea";+import { Camera3d } from "raea/camera";+import { PointLight } from "raea/light";+import { BufferMesh, Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const [n, x] = [-0.5, 0.5];+// position, normal, uv: Bevy's order (front, back, right, left, top, bottom)+const V: [number[], number[], number[]][] = [+ [[n, n, x], [0, 0, 1], [0, 0]], [[x, n, x], [0, 0, 1], [1, 0]], [[x, x, x], [0, 0, 1], [1, 1]], [[n, x, x], [0, 0, 1], [0, 1]],+ [[n, x, n], [0, 0, -1], [1, 0]], [[x, x, n], [0, 0, -1], [0, 0]], [[x, n, n], [0, 0, -1], [0, 1]], [[n, n, n], [0, 0, -1], [1, 1]],+ [[x, n, n], [1, 0, 0], [0, 0]], [[x, x, n], [1, 0, 0], [1, 0]], [[x, x, x], [1, 0, 0], [1, 1]], [[x, n, x], [1, 0, 0], [0, 1]],+ [[n, n, x], [-1, 0, 0], [1, 0]], [[n, x, x], [-1, 0, 0], [0, 0]], [[n, x, n], [-1, 0, 0], [0, 1]], [[n, n, n], [-1, 0, 0], [1, 1]],+ [[x, x, n], [0, 1, 0], [1, 0]], [[n, x, n], [0, 1, 0], [0, 0]], [[n, x, x], [0, 1, 0], [0, 1]], [[x, x, x], [0, 1, 0], [1, 1]],+ [[x, n, x], [0, -1, 0], [0, 0]], [[n, n, x], [0, -1, 0], [1, 0]], [[n, n, n], [0, -1, 0], [1, 1]], [[x, n, n], [0, -1, 0], [0, 1]],+];+const positions = V.flatMap((v) => v[0]);+const normals = V.flatMap((v) => v[1]);+const uvs = V.flatMap((v) => v[2]);+const colors = V.flatMap(([[r, g, b]]) => [(1 - r) / 2, (1 - g) / 2, (1 - b) / 2, 1]);+const indices = [0, 1, 2, 3, 4, 5].flatMap((f) => [0, 1, 2, 2, 3, 0].map((i) => f * 4 + i));++function Shot() {+ return (+ <>+ <Mesh3d>+ <Plane3d half_size={[2.5, 2.5]} />+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" />+ </Mesh3d>+ <Mesh3d transform={Transform.fromXyz(0, 0.5, 0)}>+ <BufferMesh positions={positions} normals={normals} uvs={uvs} colors={colors} indices={indices} />+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ <PointLight shadow_maps_enabled transform={Transform.fromXyz(4, 5, 4).lookingAt([0, 0, 0])} />+ <Camera3d transform={Transform.fromXyz(-2, 2.5, 5).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/animation/animated_mesh.tsx b/sdk/raea/bench/bevy-parity/animation/animated_mesh.tsxnew file mode 100644index 00000000..ba6661a3--- /dev/null+++ b/sdk/raea/bench/bevy-parity/animation/animated_mesh.tsx@@ -0,0 +1,31 @@+// Bevy v0.20.0 examples/animation/animated_mesh.rs in raea's TSX (docs/control.feature FC0a): the fox+// (models/animated/Fox.glb) playing its Run clip, Animation(2), on a 500 km green plane under a shadow-casting sun,+// with a GlobalAmbientLight of 2000, in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Model } from "raea/3d";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { DirectionalLight, GlobalAmbientLight, Shadows } from "raea/light";++function Shot() {+ // the clip advances by each update's delta_secs from the first (as many_foxes)+ const t = useCurrentFrame() / 60;+ return (+ <>+ <GlobalAmbientLight color="#ffffff" brightness={2000} />+ <Camera3d transform={Transform.fromXyz(100, 100, 150).lookingAt([0, 20, 0])} />+ <Model src={staticFile("models/animated/Fox.glb")} animation={2} time={t} />+ <Mesh3d transform={Transform.IDENTITY}>+ <Plane3d half_size={[250000, 250000]} />+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" />+ </Mesh3d>+ {/* Bevy's default 2048-texel maps; its CascadeShadowConfigBuilder's 4 cascades, 0.2 overlap */}+ <Shadows mapSize={2048} firstCascade={200} distance={400} cascades={4} overlap={0.2} />+ <DirectionalLight shadow_maps_enabled transform={{ translation: [0, 0, 0], rotation: Quat.fromEuler("ZYX", 0, 1, -Math.PI / 4), scale: [1, 1, 1] }} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/camera/camera_orbit.tsx b/sdk/raea/bench/bevy-parity/camera/camera_orbit.tsxnew file mode 100644index 00000000..6c0e5af6--- /dev/null+++ b/sdk/raea/bench/bevy-parity/camera/camera_orbit.tsx@@ -0,0 +1,38 @@+// Bevy v0.20.0 examples/camera/camera_orbit.rs in raea's TSX (docs/control.feature FC0a): a 5 m green plane, a 1 m+// cube at (1.5, 0.51, 1.5) and a default PointLight at (3, 8, 5); the camera starts at (5, 5, 5) looking at the origin+// and its orbit system (no mouse) puts it 20 m back along its view, and three lines of instructions in Bevy's default+// font at top 12, left 12, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D } from "raea/3d";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { PointLight } from "raea/light";++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;+// orbit: translation = target - forward x orbit_distance (20), the view along (-1, -1, -1)+const D = 20 / Math.sqrt(3);++function Shot() {+ return (+ <AbsoluteFill>+ <style>{FONT}</style>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Camera3d transform={Transform.fromXyz(D, D, D).lookingAt([0, 0, 0])} />+ <Mesh3d transform={Transform.IDENTITY}>+ <Plane3d half_size={[2.5, 2.5]} />+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" cull_mode={null} />+ </Mesh3d>+ <Mesh3d transform={Transform.fromXyz(1.5, 0.51, 1.5)}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <StandardMaterial base_color="rgb(204, 178.5, 153)" />+ </Mesh3d>+ <PointLight transform={Transform.fromXyz(3, 8, 5)} />+ </Canvas3D>+ <div style={{ position: "absolute", top: 12, left: 12, fontFamily: "Fira Mono", fontSize: 20, lineHeight: 1.2, color: "#fff", whiteSpace: "pre" }}>{"Mouse up or down: pitch\nMouse left or right: yaw\nMouse buttons: roll"}</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/camera/pan_camera_controller.tsx b/sdk/raea/bench/bevy-parity/camera/pan_camera_controller.tsxnew file mode 100644index 00000000..a50a9a20--- /dev/null+++ b/sdk/raea/bench/bevy-parity/camera/pan_camera_controller.tsx@@ -0,0 +1,29 @@+// Bevy v0.20.0 examples/camera/pan_camera_controller.rs in raea's TSX (docs/control.feature FC0a): a Camera2d with+// Bevy's PanCamera (no input, so it holds still), Bevy's bird as a Sprite in the middle, and the camera's controls as+// Bevy UI text (PanCamera's Display: a leading newline, then five lines) at top -16, left 12, in Bevy's default font+// at its default 20 px, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D, Sprite } from "raea/3d";++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;+const CONTROLS = `+PanCamera Controls:+ Move Up / Down - KeyW / KeyS+ Move Left / Right - KeyA / KeyD+ Rotate CCW / CW - KeyQ / KeyE+ Zoom - Mouse Scroll + Equal / Minus+`;++function Shot() {+ return (+ <AbsoluteFill>+ <style>{FONT}</style>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Sprite src={staticFile("branding/bevy_bird_dark.png")} x={640} y={360} />+ </Canvas3D>+ <div style={{ position: "absolute", top: -16, left: 12, fontFamily: "Fira Mono", fontSize: 20, lineHeight: 1.2, color: "#fff", whiteSpace: "pre" }}>{CONTROLS}</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={11} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/camera/projection_zoom.tsx b/sdk/raea/bench/bevy-parity/camera/projection_zoom.tsxnew file mode 100644index 00000000..cf6e0afb--- /dev/null+++ b/sdk/raea/bench/bevy-parity/camera/projection_zoom.tsx@@ -0,0 +1,35 @@+// Bevy v0.20.0 examples/camera/projection_zoom.rs in raea's TSX (docs/control.feature FC0a): an orthographic camera+// 5 m tall at (5, 5, 5) looking at the origin (no scroll, so its scale stays 1), a 5 m green plane drawn both sides,+// the fox (models/animated/Fox.glb's scene, unanimated) at 0.025, a default PointLight at (3, 8, 5), and two lines of+// instructions in Bevy's default font at top 12, left 12, in Bevy's default 1280 x 720 window.+import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";+import { Canvas3D, Entity, Model } from "raea/3d";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Mesh3d, Plane3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { PointLight } from "raea/light";++const FONT = `@font-face { font-family: "Fira Mono"; src: url("${staticFile("fonts/FiraMono-Medium.ttf")}"); }`;++function Shot() {+ return (+ <AbsoluteFill>+ <style>{FONT}</style>+ <Canvas3D layered clearColor="rgb(43, 44, 47)">+ <Camera3d projection={{ Orthographic: { scaling_mode: { FixedVertical: { viewport_height: 5 } } } }} transform={Transform.fromXyz(5, 5, 5).lookingAt([0, 0, 0])} />+ <Mesh3d transform={Transform.IDENTITY}>+ <Plane3d half_size={[2.5, 2.5]} />+ <StandardMaterial base_color="rgb(76.5, 127.5, 76.5)" cull_mode={null} />+ </Mesh3d>+ <Entity transform={{ translation: [0, 0, 0], scale: [0.025, 0.025, 0.025] }}>+ <Model src={staticFile("models/animated/Fox.glb")} />+ </Entity>+ <PointLight transform={Transform.fromXyz(3, 8, 5)} />+ </Canvas3D>+ <div style={{ position: "absolute", top: 12, left: 12, fontFamily: "Fira Mono", fontSize: 20, lineHeight: 1.2, color: "#fff", whiteSpace: "pre" }}>{"Scroll mouse wheel to zoom in/out\nSpace: switch between orthographic and perspective projections"}</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={31} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/shader/animate_shader.tsx b/sdk/raea/bench/bevy-parity/shader/animate_shader.tsxnew file mode 100644index 00000000..bbe9e938--- /dev/null+++ b/sdk/raea/bench/bevy-parity/shader/animate_shader.tsx@@ -0,0 +1,23 @@+// Bevy v0.20.0 examples/shader/animate_shader.rs in raea's TSX (docs/control.feature FC0a, FC2a): a 1 m cube at+// (0, 0.5, 0) with the example's own Material, assets/shaders/animate_shader.wesl as written (no bindings: it reads+// globals.time and blends four colours in Oklab across the face's UVs), the camera at (-2, 2.5, 5), in Bevy's default+// 1280 x 720 window.+import { Composition, registerRoot, staticFile } from "raea";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { Material } from "@raea/render/bevy3d"; // raea/pbr once scene-loop lands (its pbr.ts commit)++function Shot() {+ return (+ <>+ <Mesh3d transform={Transform.fromXyz(0, 0.5, 0)}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <Material fragment={staticFile("shaders/animate_shader.wesl")} />+ </Mesh3d>+ <Camera3d transform={Transform.fromXyz(-2, 2.5, 5).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/shader/extended_material.tsx b/sdk/raea/bench/bevy-parity/shader/extended_material.tsxnew file mode 100644index 00000000..c5a709f4--- /dev/null+++ b/sdk/raea/bench/bevy-parity/shader/extended_material.tsx@@ -0,0 +1,29 @@+// Bevy v0.20.0 examples/shader/extended_material.rs in raea's TSX (docs/control.feature FC0a, FC2b): a red unit sphere+// whose ExtendedMaterial runs the example's own shader file, assets/shaders/extended_material.wesl, as written: its+// own @binding(100) uniform struct (quantize_steps: u32, 1), its imports and its deferred branch. It copies red into+// blue before lighting, quantizes the lit colour and doubles it after post-processing, under a DirectionalLight turning+// about Y at 1 rad/s, in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, staticFile, useCurrentFrame } from "raea";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Mesh3d, Sphere } from "raea/mesh";+import { ExtendedMaterial, ShaderExtension, StandardMaterial } from "raea/pbr";+import { DirectionalLight } from "raea/light";++function Shot() {+ // rotate_things: rotate_y by each update's delta_secs (none on the first)+ const a = useCurrentFrame() / 60;+ const light = Transform.fromXyz(1, 1, 1).lookingAt([0, 0, 0]);+ return (+ <>+ <Mesh3d transform={Transform.fromXyz(0, 0.5, 0)}>+ <Sphere radius={1} />+ <ExtendedMaterial base={<StandardMaterial base_color="#ff0000" />} extension={<ShaderExtension fragment={staticFile("shaders/extended_material.wesl")} uniforms={{ quantize_steps: 1 }} />} />+ </Mesh3d>+ <DirectionalLight transform={{ translation: light.translation, rotation: Quat.mul(Quat.fromRotationY(a), light.rotation), scale: [1, 1, 1] }} />+ <Camera3d transform={Transform.fromXyz(-2, 2.5, 5).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/transforms/3d_rotation.tsx b/sdk/raea/bench/bevy-parity/transforms/3d_rotation.tsxnew file mode 100644index 00000000..955dbbb0--- /dev/null+++ b/sdk/raea/bench/bevy-parity/transforms/3d_rotation.tsx@@ -0,0 +1,26 @@+// Bevy v0.20.0 examples/transforms/3d_rotation.rs in raea's TSX (docs/control.feature FC0a): a white 1 m cube at the+// origin turning about Y at 0.3 turns a second, the camera at (0, 10, 20) looking at it, a default DirectionalLight from+// (3, 3, 3), in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { DirectionalLight } from "raea/light";++function Shot() {+ // rotate_cube: rotate_y by 0.3 x TAU x each update's delta_secs (none on the first)+ const a = (0.3 * 2 * Math.PI * useCurrentFrame()) / 60;+ return (+ <>+ <Mesh3d transform={{ rotation: Quat.fromRotationY(a) }}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ <Camera3d transform={Transform.fromXyz(0, 10, 20).lookingAt([0, 0, 0])} />+ <DirectionalLight transform={Transform.fromXyz(3, 3, 3).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={61} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/transforms/scale.tsx b/sdk/raea/bench/bevy-parity/transforms/scale.tsxnew file mode 100644index 00000000..06e7ae9b--- /dev/null+++ b/sdk/raea/bench/bevy-parity/transforms/scale.tsx@@ -0,0 +1,46 @@+// Bevy v0.20.0 examples/transforms/scale.rs in raea's TSX (docs/control.feature FC0a): a white 1 m cube turned 45 degrees about Y, growing along one axis+// at 2 a second to 5, shrinking back to 1, then the next axis (X, then Z, then Y), the camera at (0, 10, 20), a default+// DirectionalLight from (3, 3, 3), in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { DirectionalLight } from "raea/light";++type V = [number, number, number];++/** change_scale_direction then scale_cube, over the updates up to frame f (no delta on the first) */+function scaleAt(f: number): V {+ let s: V = [1, 1, 1];+ let d: V = [1, 0, 0];+ for (let k = 0; k <= f; k++) {+ if (Math.max(...s) > 5) {+ d = d.map((c) => -c) as V;+ s = s.map(Math.floor) as V;+ }+ if (Math.min(...s) < 1) {+ d = d.map((c) => -c) as V;+ s = s.map(Math.ceil) as V;+ d = [d[2], d[0], d[1]];+ }+ const dt = k === 0 ? 0 : 1 / 60;+ s = s.map((c, i) => Math.fround(c + Math.fround(Math.fround(d[i] * 2) * dt))) as V;+ }+ return s;+}++function Shot() {+ return (+ <>+ <Mesh3d transform={{ rotation: Quat.fromRotationY(Math.PI / 4), scale: scaleAt(useCurrentFrame()) }}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ <Camera3d transform={Transform.fromXyz(0, 10, 20).lookingAt([0, 0, 0])} />+ <DirectionalLight transform={Transform.fromXyz(3, 3, 3).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={301} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/bench/bevy-parity/transforms/translation.tsx b/sdk/raea/bench/bevy-parity/transforms/translation.tsxnew file mode 100644index 00000000..8517a31e--- /dev/null+++ b/sdk/raea/bench/bevy-parity/transforms/translation.tsx@@ -0,0 +1,35 @@+// Bevy v0.20.0 examples/transforms/translation.rs in raea's TSX (docs/control.feature FC0a): a white 1 m cube moving along its local X at 2 m/s, turning back+// past 5 m from where it started, the camera at (0, 10, 20) looking at it, a default DirectionalLight from (3, 3, 3),+// in Bevy's default 1280 x 720 window.+import { Composition, registerRoot, useCurrentFrame } from "raea";+import { Transform } from "raea/transform";+import { Camera3d } from "raea/camera";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { DirectionalLight } from "raea/light";++/** move_cube over the updates up to frame f: turn when past 5 m, then move by speed x delta_secs (none on the first) */+function xAt(f: number): number {+ let x = 0;+ let speed = 2;+ for (let k = 0; k <= f; k++) {+ if (Math.abs(x) > 5) speed = -speed;+ x = Math.fround(x + Math.fround(speed * (k === 0 ? 0 : 1 / 60)));+ }+ return x;+}++function Shot() {+ return (+ <>+ <Mesh3d transform={Transform.fromXyz(xAt(useCurrentFrame()), 0, 0)}>+ <Cuboid half_size={[0.5, 0.5, 0.5]} />+ <StandardMaterial base_color="#ffffff" />+ </Mesh3d>+ <Camera3d transform={Transform.fromXyz(0, 10, 20).lookingAt([0, 0, 0])} />+ <DirectionalLight transform={Transform.fromXyz(3, 3, 3).lookingAt([0, 0, 0])} />+ </>+ );+}++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={181} fps={60} width={1280} height={720} />);diff --git a/sdk/raea/conformance/bevy3d.test.tsx b/sdk/raea/conformance/bevy3d.test.tsxindex 7054ed73..e8b88e5a 100644--- a/sdk/raea/conformance/bevy3d.test.tsx+++ b/sdk/raea/conformance/bevy3d.test.tsx@@ -15,6 +15,8 @@ import { track } from "raea";const close = (a: number[], b: number[], eps = 1e-9) => a.every((x, i) => Math.abs(x - b[i]) < eps);const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });+/** a Bevy StandardMaterial's emissive strength as written, which the old material takes as emissive_nits (core/scene emissive_power) */+const nits = (k: number) => ({ emissive_nits: k }) as object;describe("Quat and Transform", () => {test("eulerOf inverts a composition's rotation, Quat::from_euler(EulerRot::XYZ, x, y, z) (scene3d.rs local)", () => {@@ -166,7 +168,7 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => {expect(m(<StandardMaterial material="Fabric" base_color="#7a3b2e" />)).toBe(m(<MeshStandardMaterial color="#7a3b2e" material="Fabric" />));expect(m(<StandardMaterial perceptual_roughness={0.3} />)).toBe(m(<MeshStandardMaterial roughness={0.3} />));expect(m(<StandardMaterial base_color="#c03" base_color_texture={null} />)).toBe(m(<MeshStandardMaterial color="#c03" map={null} />));- expect(m(<StandardMaterial base_color="#000000" emissive={LinearRgba.from(Srgba.hex("#ffaa55")).mul(700)} />)).toBe(m(<MeshStandardMaterial color="#000000" emissive="#ffaa55" emissiveIntensity={700} />));+ expect(m(<StandardMaterial base_color="#000000" emissive={LinearRgba.from(Srgba.hex("#ffaa55")).mul(700)} />)).toBe(m(<MeshStandardMaterial color="#000000" emissive="#ffaa55" {...nits(700)} />));expect(html(<StandardMaterial base_color="#7a3b2e" />)).toBe(html(<MeshStandardMaterial color="#7a3b2e" roughness={0.5} metalness={0} />));});@@ -197,7 +199,7 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => {html(<MeshStandardMaterial color="#3060ff" roughness={0.5} metalness={0} animate={{ color: blue, roughness: track({ 0: 0.2, 30: 0.8 }), metalness: track({ 0: 0, 30: 1 }) }} />),);expect(html(<StandardMaterial emissive="#ff4070" animate={{ emissive: track({ 0: E.mul(0), 30: E.mul(2.5) }, "out-cubic") }} />)).toBe(- html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive="#ff4070" animate={{ emissiveIntensity: track({ 0: 0, 30: 2.5 }, "out-cubic") }} />),+ html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive="#ff4070" {...nits(1)} animate={{ emissive_nits: track({ 0: 0, 30: 2.5 }, "out-cubic") } as never} />),);const F = LinearRgba.from(Srgba.hex("#00ff00"));expect(() => html(<StandardMaterial animate={{ emissive: track({ 0: E, 30: F }) }} />)).toThrow(/one colour/);@@ -241,10 +243,10 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => {});test("emissive brighter than white: LinearRgba, made from a colour, goes as that colour and its intensity exactly", () => {- const glow = (e: string, k: number) => html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive={e} emissiveIntensity={k} />);+ const glow = (e: string, k: number) => html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive={e} {...nits(k)} />);expect(html(<StandardMaterial emissive={LinearRgba.from(Srgba.hex("#884422")).mul(3)} />)).toBe(glow("#884422", 3));expect(html(<StandardMaterial emissive={LinearRgba.from(Srgba.hex("#884422")).mul(2).mul(1.5)} />)).toBe(glow("#884422", 3));- expect(html(<StandardMaterial emissive={LinearRgba.from(Srgba.hex("#ff8800"))} />)).toBe(html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive="#ff8800" />));+ expect(html(<StandardMaterial emissive={LinearRgba.from(Srgba.hex("#ff8800"))} />)).toBe(html(<MeshStandardMaterial color="#ffffff" roughness={0.5} metalness={0} emissive="#ff8800" {...nits(1)} />));// raw floats: the hue at full strength times the brightest channelexpect(html(<StandardMaterial emissive={LinearRgba.rgb(4, 2, 0)} />)).toBe(glow("#ffbc00", 4));expect(html(<StandardMaterial emissive={LinearRgba.rgb(0, 0, 0)} />)).toBe(html(<StandardMaterial />));@@ -278,7 +280,7 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => {// no base_color: on a Model, each glTF material keeps its ownexpect(toon({ material: "Body" }, { steps: 2 })).toBe(html(<MeshToonMaterial steps={2} material="Body" />));expect(toon({ base_color: Srgba.hex("#88ccff").with_alpha(0.5), alpha_mode: "Blend", emissive: LinearRgba.from(Srgba.hex("#ff0000")).mul(2) }, {})).toBe(- html(<MeshToonMaterial color="#88ccff" emissive="#ff0000" emissiveIntensity={2} transparent opacity={0.5} />),+ html(<MeshToonMaterial color="#88ccff" emissive="#ff0000" {...nits(2)} transparent opacity={0.5} />),);expect(() => toon({ perceptual_roughness: 0.3 }, {})).toThrow(/not perceptual_roughness/);expect(() => html(<ExtendedMaterial base={<ExtendedMaterial base={<StandardMaterial />} extension={<GridExtension cell={1} />} />} extension={<ToonExtension />} />)).toThrow(/takes no other extension/);@@ -310,7 +312,7 @@ describe("Bevy's lights, in Bevy's units", () => {test("PointLight sits at its translation, with Bevy's defaults (1e6 lm, range 20, no shadows)", () => {expect(html(<PointLight transform={Transform.fromXyz(1, 3, 2)} />)).toBe(html(<three.PointLight position={[1, 3, 2]} lumens={1_000_000} distance={20} castShadow={false} />));expect(html(<PointLight shadow_maps_enabled soft_shadows_enabled radius={0.1} color="#ffaa66" />)).toBe(- html(<three.PointLight position={[0, 0, 0]} lumens={1_000_000} distance={20} castShadow softShadow={0.1} color="#ffaa66" />),+ html(<three.PointLight position={[0, 0, 0]} lumens={1_000_000} distance={20} castShadow radius={0.1} softShadow={0.1} color="#ffaa66" />),);});diff --git a/sdk/raea/conformance/envmap.test.tsx b/sdk/raea/conformance/envmap.test.tsxnew file mode 100644index 00000000..aea6ffdb--- /dev/null+++ b/sdk/raea/conformance/envmap.test.tsx@@ -0,0 +1,20 @@+// docs/control.feature FC0a: Bevy's EnvironmentMapLight with its own prefiltered maps (3d/pbr, 3d/animated_material).+import { describe, expect, test } from "bun:test";+import { EnvironmentMapLight } from "raea/light";+import { renderFrame } from "../src/test";++const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });++describe("EnvironmentMapLight: prefiltered cubemaps on the camera", () => {+ test("its maps and intensity reach the camera's Environment row, intensity 1 by Bevy's default", () => {+ const out = html(<EnvironmentMapLight diffuse_map="maps/d.ktx2" specular_map="maps/s.ktx2" intensity={900} />);+ expect(out).toContain('data-3d="Environment"');+ for (const s of ["maps/d.ktx2", "maps/s.ktx2", "900"]) expect(out).toContain(s);+ expect(html(<EnvironmentMapLight diffuse_map="d.ktx2" specular_map="s.ktx2" />)).toContain(""intensity":1");+ });+ test("a map that isn't a .ktx2, or a negative intensity, is refused", () => {+ expect(() => html(<EnvironmentMapLight diffuse_map="sky.hdr" specular_map="s.ktx2" />)).toThrow(/diffuse_map is a prefiltered/);+ expect(() => html(<EnvironmentMapLight diffuse_map="d.ktx2" specular_map="s.png" />)).toThrow(/specular_map is a prefiltered/);+ expect(() => html(<EnvironmentMapLight diffuse_map="d.ktx2" specular_map="s.ktx2" intensity={-1} />)).toThrow(/intensity/);+ });+});diff --git a/sdk/raea/conformance/events3d.test.tsx b/sdk/raea/conformance/events3d.test.tsxindex a7212f68..3c2fa2d6 100644--- a/sdk/raea/conformance/events3d.test.tsx+++ b/sdk/raea/conformance/events3d.test.tsx@@ -3,7 +3,10 @@import { describe, expect, test } from "bun:test";import { events3d, local, onFlat, pickIn, under, worldBounds, IDENTITY, type Last } from "../../render/src/events3d";import { pick } from "../../render/src/pick";-import { Quat } from "../../render/src/bevy3d";+import { Mesh3d, Quat, StandardMaterial } from "../../render/src/bevy3d";+import { pickable3d } from "../../render/src/events3d";+import { Sphere } from "../src/3d";+import { renderFrame } from "../src/test";type P = { x: number; y: number; down: boolean };/** The event types per part over a run of frames: each frame's pointer and the part under it. */@@ -132,3 +135,24 @@ describe("the parts' bounds in the world", () => {expect(pickIn({ x: 610, y: 110 }, cam, [ball], frame, box)).toBeNull();});});++describe("a part is picked by its geometry's bounds (FC1b: worked out only for a part with handlers)", () => {+ test("a Mesh3d with an onClick is pickable as its Sphere, placed; one without handlers isn't", () => {+ const el = (+ <>+ <Mesh3d name="ball" transform={{ translation: [1, 2, 3] }} onClick={() => {}}>+ <Sphere radius={2} />+ <StandardMaterial />+ </Mesh3d>+ <Mesh3d name="still" transform={{ translation: [5, 0, 0] }}>+ <Sphere radius={1} />+ <StandardMaterial />+ </Mesh3d>+ </>+ );+ renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });+ const parts = pickable3d();+ expect(parts.get("ball")).toEqual({ name: "ball", sphere: { center: [1, 2, 3], radius: 2 } });+ expect(parts.has("still")).toBe(false);+ });+});diff --git a/sdk/raea/conformance/layered-clear.test.tsx b/sdk/raea/conformance/layered-clear.test.tsxnew file mode 100644index 00000000..391d17f3--- /dev/null+++ b/sdk/raea/conformance/layered-clear.test.tsx@@ -0,0 +1,39 @@+// A layered Canvas3D's clearColor (docs/control.feature FC0a, 2d/transparency_2d): the 3D clears to it instead of+// transparent, so its translucent parts blend over it as Bevy's do over its ClearColor, not over the page (runtime/react+// holders.rs scene_clear). Runs where the release binary and ffmpeg are built.+import { expect, test } from "bun:test";+import { existsSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++const BIN = process.env.RAEA_BIN ?? join(import.meta.dir, "../../../target/release/raea");+const ffmpeg = Bun.which("ffmpeg");++/** frame 1 of a layered-clear scene: its corner pixel and its middle one, RGB */+function pixels(scene: string): { corner: number[]; middle: number[] } {+ const dir = mkdtempSync(join(tmpdir(), "layered-clear-"));+ try {+ const png = join(dir, "1.png");+ const r = Bun.spawnSync([BIN, "render", join(import.meta.dir, "layered-clear", scene), "--frame", "1", "-o", png], { stderr: "pipe" });+ expect(r.exitCode).toBe(0);+ const px = new Uint8Array(Bun.spawnSync([ffmpeg!, "-v", "error", "-i", png, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]).stdout);+ const at = (x: number, y: number) => [...px.subarray((y * 160 + x) * 3, (y * 160 + x) * 3 + 3)];+ return { corner: at(2, 2), middle: at(80, 45) };+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++test.skipIf(!existsSync(BIN) || !ffmpeg)("with clearColor the 3D clears to it and a half-white square blends over it, not the page", () => {+ const { corner, middle } = pixels("scene.tsx");+ expect(corner).toEqual([0, 0, 0]);+ // grey: white over black, none of the page's red under it+ expect(middle[1]).toBeGreaterThan(100);+ expect(Math.abs(middle[0] - middle[1])).toBeLessThan(4);+}, 120_000);++test.skipIf(!existsSync(BIN) || !ffmpeg)("without clearColor the 3D clears transparent and the page shows under it", () => {+ const { corner, middle } = pixels("none.tsx");+ expect(corner).toEqual([255, 0, 0]);+ expect(middle[0]).toBe(255);+}, 120_000);diff --git a/sdk/raea/conformance/layered-clear/none.tsx b/sdk/raea/conformance/layered-clear/none.tsxnew file mode 100644index 00000000..ffcd7e60--- /dev/null+++ b/sdk/raea/conformance/layered-clear/none.tsx@@ -0,0 +1,12 @@+// The same layered Canvas3D without clearColor (layered-clear.test.tsx): the 3D clears transparent, the page's red+// shows where the 3D has nothing.+import { AbsoluteFill, Composition, registerRoot } from "raea";+import { Square } from "./square";++const Shot = () => (+ <AbsoluteFill style={{ background: "#ff0000" }}>+ <Square />+ </AbsoluteFill>+);++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={3} fps={30} width={160} height={90} />);diff --git a/sdk/raea/conformance/layered-clear/scene.tsx b/sdk/raea/conformance/layered-clear/scene.tsxnew file mode 100644index 00000000..82fdc2ea--- /dev/null+++ b/sdk/raea/conformance/layered-clear/scene.tsx@@ -0,0 +1,13 @@+// A layered Canvas3D over a red page with clearColor="#000000" (layered-clear.test.tsx): the 3D clears black and its+// half-transparent white square blends over that in linear light (sRGB 188, as Bevy blends over its ClearColor), and+// the page's red is hidden.+import { AbsoluteFill, Composition, registerRoot } from "raea";+import { Square } from "./square";++const Shot = () => (+ <AbsoluteFill style={{ background: "#ff0000" }}>+ <Square clearColor="#000000" />+ </AbsoluteFill>+);++registerRoot(() => <Composition id="main" component={Shot} durationInFrames={3} fps={30} width={160} height={90} />);diff --git a/sdk/raea/conformance/layered-clear/square.tsx b/sdk/raea/conformance/layered-clear/square.tsxnew file mode 100644index 00000000..fcb0c74d--- /dev/null+++ b/sdk/raea/conformance/layered-clear/square.tsx@@ -0,0 +1,17 @@+// A half-transparent unlit white square filling the middle of a layered Canvas3D (layered-clear's scenes).+import { Canvas3D } from "raea/3d";+import { Camera3d } from "raea/camera";+import { Srgba } from "raea/color";+import { Cuboid, Mesh3d } from "raea/mesh";+import { StandardMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++export const Square = ({ clearColor }: { clearColor?: string }) => (+ <Canvas3D layered clearColor={clearColor}>+ <Camera3d transform={Transform.IDENTITY} />+ <Mesh3d transform={Transform.fromXyz(0, 0, -2)}>+ <Cuboid half_size={[0.5, 0.5, 0.01]} />+ <StandardMaterial base_color={new Srgba(1, 1, 1, 0.5)} alpha_mode="Blend" unlit />+ </Mesh3d>+ </Canvas3D>+);diff --git a/sdk/raea/conformance/material.test.tsx b/sdk/raea/conformance/material.test.tsxnew file mode 100644index 00000000..5a99da12--- /dev/null+++ b/sdk/raea/conformance/material.test.tsx@@ -0,0 +1,21 @@+// docs/control.feature FC2a's first step: your own Material, its fragment shader a file compiled as written.+import { describe, expect, test } from "bun:test";+import { Cuboid } from "../src/3d";+import { ExtendedMaterial, Mesh3d, ShaderExtension, StandardMaterial } from "@raea/render/bevy3d";+import { Material } from "@raea/render/bevy3d"; // raea/pbr once scene-loop lands (its pbr.ts commit)+import { renderFrame } from "../src/test";++const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });++describe("FC2a: a Material of your own", () => {+ test("a Material is its fragment file over the standard base, uniforms and all, as the shader row reads it", () => {+ const own = html(<Mesh3d><Cuboid /><Material fragment="shaders/a.wesl" uniforms={{ steps: 3 }} /></Mesh3d>);+ expect(own).toBe(html(<Mesh3d><Cuboid /><ExtendedMaterial base={<StandardMaterial />} extension={<ShaderExtension fragment="shaders/a.wesl" uniforms={{ steps: 3 }} />} /></Mesh3d>));+ expect(own).toContain("shaders/a.wesl");+ expect(own).not.toBe(html(<Mesh3d><Cuboid /><Material fragment="shaders/b.wesl" uniforms={{ steps: 3 }} /></Mesh3d>));+ });+ test("a Material without its file, or a shader with two sources, is refused", () => {+ expect(() => html(<Mesh3d><Cuboid /><Material {...({} as { fragment: string })} /></Mesh3d>)).toThrow(/fragment is the shader file/);+ expect(() => html(<Mesh3d><Cuboid /><ExtendedMaterial base={<StandardMaterial />} extension={<ShaderExtension fragment="a.wesl" wesl="@fragment fn f() {}" />} /></Mesh3d>)).toThrow(/one of them/);+ });+});diff --git a/sdk/raea/conformance/sprite-tile.test.tsx b/sdk/raea/conformance/sprite-tile.test.tsxnew file mode 100644index 00000000..4e4a42da--- /dev/null+++ b/sdk/raea/conformance/sprite-tile.test.tsx@@ -0,0 +1,19 @@+// docs/control.feature FC0a, 2d/sprite_tile: Bevy's SpriteImageMode::Tiled on a <Sprite> (tileX, tileY, tileStretch),+// the props reaching its row for raea-sys-sprite, and a stretch that can't tile refused.+import { describe, expect, test } from "bun:test";+import { Canvas3D, Sprite } from "raea/3d";+import { renderFrame } from "../src/test";++const html = (el: React.ReactElement) => renderFrame(<Canvas3D layered>{el}</Canvas3D>, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });++describe("Sprite: tiled", () => {+ test("tileX, tileY and tileStretch reach the sprite's props, with its size", () => {+ const out = html(<Sprite src="icon.png" width={300} height={200} tileX tileY tileStretch={0.5} />);+ for (const s of [""tileX":true", ""tileY":true", ""tileStretch":0.5", ""width":300"]) expect(out).toContain(s);+ });+ test("a tileStretch of 0 or less, or one on a sprite that doesn't tile, is refused", () => {+ expect(() => html(<Sprite src="icon.png" tileX tileStretch={0} />)).toThrow(/tileStretch is above 0/);+ expect(() => html(<Sprite src="icon.png" tileStretch={0.5} />)).toThrow(/give tileX or tileY/);+ expect(() => html(<Sprite src="icon.png" tileY tileStretch={2} />)).not.toThrow();+ });+});diff --git a/sdk/raea/src/light.ts b/sdk/raea/src/light.tsindex 3b58492c..94392f0e 100644--- a/sdk/raea/src/light.ts+++ b/sdk/raea/src/light.ts@@ -3,7 +3,7 @@// raea/light (bevy_light): Bevy's lights in Bevy's units (lux, lumens, cd/m²; bevy3d.tsx), environments and// daylight. 3d.tsx's lights, in raea's relative units, stay under /3d.export { AmbientLight, GlobalAmbientLight, DirectionalLight, PointLight, SpotLight, RectLight, light_consts, type AmbientLightProps, type DirectionalLightProps, type PointLightProps, type SpotLightProps, type RectLightProps } from "@raea/render/bevy3d";-export { Atmosphere, Environment, Shadows, type AtmosphereProps, type EnvironmentProps, type ShadowsProps } from "./3d";+export { Atmosphere, Environment, EnvironmentMapLight, Shadows, type AtmosphereProps, type EnvironmentProps, type EnvironmentMapLightProps, type ShadowsProps } from "./3d";export * from "@raea/render/daylight";// ray-traced lighting (Bevy's Solari, docs/raytracing.feature RT3)export { SolariLighting, Pathtracer, type SolariLightingProps, type PathtracerProps } from "@raea/render/bevy3d";diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.tsindex 70647d7c..83d8c05d 100644--- a/sdk/raea/src/native-calls.ts+++ b/sdk/raea/src/native-calls.ts@@ -18,6 +18,8 @@ export interface NativeCalls {"aenc.new": { args: { rate: number; channels: number; kbps?: number }; answer: { id: number; description: string; priming: number } };/** an asset by its path (absolute, or from the edit's folder), loaded now: the file found and read, a picture's size; an error when it isn't there (S2b useAsset) */"asset.load": { args: { path: string }; answer: { path: string; bytes: number; width?: number; height?: number } };+ /** a file's bytes (absolute, from the edit's folder, or an http(s) URL through raea's cache), read now, as base64 (R3F's loaders, docs/r3f.feature R3F13) */+ "asset.read": { args: { path: string }; answer: { path: string; base64: string } };/** a queued call's answer once the Engine has run it (null before) */"bevy.world.answer": { args: { ticket: number }; answer: { value?: unknown; error?: string } | null };/** a BRP method (world.query, world.mutate_components, a plugin's method...) queued for the live Engine's next update: its ticket */diff --git a/sdk/raea/src/pbr.ts b/sdk/raea/src/pbr.tsindex 5b1a80e8..dbf14be0 100644--- a/sdk/raea/src/pbr.ts+++ b/sdk/raea/src/pbr.ts@@ -1,7 +1,7 @@// docs/sdk.feature S1b (M1): a Bevy-named entry point, re-exporting what today lives in the files named. Sources move// into it at M5; until then the old subpaths and this one export the same values.// raea/pbr (bevy_pbr, bevy_material): materials, fog, volumes and the paint look's things.-export { SurfaceShader, Refinish, Fog, VolumetricFog, FogVolume, Fire, Decal, ShaderMesh, AmbientOcclusion, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonRim, type ToonHighlight, type ToonOutline, type FogProps, type VolumetricFogProps, type FogVolumeProps, type FireProps, type DecalProps, type ShaderMeshProps, type AmbientOcclusionProps } from "./3d";+export { SurfaceShader, ThreeShaderMaterial, type ThreeShaderMaterialProps, Refinish, Fog, VolumetricFog, FogVolume, Fire, Decal, ShaderMesh, AmbientOcclusion, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonRim, type ToonHighlight, type ToonOutline, type FogProps, type VolumetricFogProps, type FogVolumeProps, type FireProps, type DecalProps, type ShaderMeshProps, type AmbientOcclusionProps } from "./3d";export * from "@raea/render/splat";export * from "@raea/render/paint";export { StandardMaterial, ExtendedMaterial, ToonMaterial, type ToonMaterialProps, GridExtension, PaintExtension, WearExtension, ToonExtension, ShaderExtension, type StandardMaterialProps, type StandardMaterialAnimate, type ToonExtensionAnimate, type ExtendedMaterialProps, type GridExtensionProps, type PaintExtensionProps, type WearExtensionProps, type ToonExtensionProps, type ShaderExtensionProps, type AlphaMode, type SampledImage, type MetallicRoughnessMaps } from "@raea/render/bevy3d";diff --git a/sdk/render/src/3d.tsx b/sdk/render/src/3d.tsxindex 237619fb..2a6bfefa 100644--- a/sdk/render/src/3d.tsx+++ b/sdk/render/src/3d.tsx@@ -2,8 +2,8 @@// carries its name (data-3d) and props (data-props, JSON) for Bevy to draw; a Mesh also carries its Manifold// expression (data-shape). Engine-safe: this module imports nothing beyond React.import { toHex } from "./colour";-export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, surfaceShader, samplerSpec, FramePass, Compute, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";-export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";+export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, EnvironmentMapLight, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";+export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, ThreeShaderMaterialProps, ThreeUniform, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, EnvironmentMapLightProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";export { CrossSection, crossSection, manifold, outline, Solid, type Bounds, type Polygons, type Section } from "./solid";diff --git a/sdk/render/src/3d/all.ts b/sdk/render/src/3d/all.tsindex 2dc04f5a..97146e1a 100644--- a/sdk/render/src/3d/all.ts+++ b/sdk/render/src/3d/all.ts@@ -14,3 +14,4 @@ export * from "./shapes";export * from "./sprite";export * from "./instances";export * from "./grass";+export * from "./three-shader";diff --git a/sdk/render/src/3d/core.tsx b/sdk/render/src/3d/core.tsxindex e3e38c4b..93155f9a 100644--- a/sdk/render/src/3d/core.tsx+++ b/sdk/render/src/3d/core.tsx@@ -42,6 +42,10 @@ export interface Canvas3DProps {* hidden by its parts; positioned elements after it are over it. The 3D's background is transparent. Put the* Canvas3D straight in a full-frame AbsoluteFill. */layered?: boolean;+ /** only with `layered`: the 3D clears to this CSS colour instead of transparent, so its translucent parts blend over+ * it in linear light, as Bevy's do over its ClearColor (a Bevy 2D scene's rgb(43, 44, 47)), not over the page in sRGB.+ * The 3D then hides the page elements before it. */+ clearColor?: string;children?: ReactNode;[prop: string]: unknown;}diff --git a/sdk/render/src/3d/effects.tsx b/sdk/render/src/3d/effects.tsxindex 3c555812..9f5638a9 100644--- a/sdk/render/src/3d/effects.tsx+++ b/sdk/render/src/3d/effects.tsx@@ -1,6 +1,6 @@// Image planes, decals, bloom, fog, grading, environment, ambient occlusion, shadows and volumetric fog.import { useCurrentFrame, useVideoConfig } from "@raea/app/clock";-import { ImagePlaneProps, Vec3, checkShares, checkVec, colours, node3d } from "./all";+import { ImagePlaneProps, Vec3, assetPath, checkShares, checkVec, colours, node3d } from "./all";/** A picture on a flat card in the scene, unlit (a poster, a screen, a sprite).* @bevy bevy_image::image::Image */@@ -224,7 +224,7 @@ export interface EnvironmentProps {/** Light from all around, out of a panorama: soft light from the sky and reflections of it in every glossy or metal* surface (image-based lighting), and with `background` the panorama as the sky. Put it inside the Canvas3D, once a* frame; its src, intensity, rotation and background may change from frame to frame (a cut from a hall to a street).- * @bevy bevy_light::probe::EnvironmentMapLight+ * Bevy's EnvironmentMapLight with maps already filtered is <EnvironmentMapLight>.* Its panorama is filtered by Bevy's generator and, with `background`, drawn as the sky (engine/render* environment.rs): @bevy bevy_light::probe::GeneratedEnvironmentMapLight @bevy bevy_light::probe::Skybox */export function Environment(props: EnvironmentProps) {@@ -238,6 +238,27 @@ export function Environment(props: EnvironmentProps) {return node3d("Environment", props as unknown as Record<string, unknown>);}+export interface EnvironmentMapLightProps {+ /** the prefiltered diffuse (irradiance) cubemap, a .ktx2 file: staticFile("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2") */+ diffuse_map: string;+ /** the prefiltered specular (radiance) cubemap with its mips, a .ktx2 file */+ specular_map: string;+ /** cd/m² (Bevy's default 1) */+ intensity?: number;+}++/** Bevy's EnvironmentMapLight with its own prefiltered maps, as Bevy's examples put one on the camera (docs/control.feature+ * FC0a): light from all around and its reflections, from cubemaps already filtered (an <Environment> filters a panorama+ * itself). Put it inside the Canvas3D, once; the first frame's holds.+ * @bevy bevy_light::probe::EnvironmentMapLight */+export function EnvironmentMapLight(props: EnvironmentMapLightProps) {+ for (const k of ["diffuse_map", "specular_map"] as const) {+ if (typeof props[k] !== "string" || !/\.ktx2$/i.test(props[k])) throw new TypeError(`EnvironmentMapLight: ${k} is a prefiltered cubemap's .ktx2 file, got ${JSON.stringify(props[k])}`);+ }+ if (props.intensity !== undefined && !(typeof props.intensity === "number" && props.intensity >= 0 && Number.isFinite(props.intensity))) throw new RangeError(`EnvironmentMapLight: intensity is cd/m², 0 or more, got ${props.intensity}`);+ return node3d("Environment", { diffuse_map: assetPath(props.diffuse_map), specular_map: assetPath(props.specular_map), intensity: props.intensity ?? 1 });+}+export interface AmbientOcclusionProps {/** how many samples a pixel takes: "low" (4), "medium" (8, the default), "high" (18), "ultra" (54) */quality?: "low" | "medium" | "high" | "ultra";@@ -397,6 +418,9 @@ export interface FogVolumeProps {* fog that's a third as thick two metres up. A box wide and tall with a falloff is height fog. Only* <VolumetricFog mode="froxel"> draws it; the march draws the box evenly */falloff?: number;+ /** Bevy's density_texture: a 3D .ktx2 image in the media folder whose values scale the density through the box (a+ * cloud, a bunny of smoke); the box draws evenly without one. Only the march draws it */+ density_texture?: string;}/** A box of air that light shows in: dust in a sunbeam, smoke, a haze of blood. Needs a <VolumetricFog> in the@@ -407,6 +431,8 @@ export function FogVolume(props: FogVolumeProps) {for (const k of ["position", "rotation"] as const) if (props[k] !== undefined) checkVec("FogVolume", k, props[k]);if (props.density !== undefined && !(props.density >= 0 && Number.isFinite(props.density))) throw new RangeError(`FogVolume: density must be 0 or more, got ${props.density}`);if (props.anisotropy !== undefined && !(props.anisotropy > -1 && props.anisotropy < 1)) throw new RangeError(`FogVolume: anisotropy must be between -1 and 1, got ${props.anisotropy}`);+ const tex = props.density_texture;+ if (tex !== undefined && !(typeof tex === "string" && /\.ktx2$/i.test(tex))) throw new TypeError(`FogVolume: density_texture is a 3D .ktx2 image, got ${JSON.stringify(tex)}`);if (props.falloff !== undefined && !(props.falloff >= 0 && Number.isFinite(props.falloff))) throw new RangeError(`FogVolume: falloff must be 0 or more, got ${props.falloff}`);- return node3d("FogVolume", colours("FogVolume", props as Record<string, unknown>, ["color"]));+ return node3d("FogVolume", colours("FogVolume", (tex === undefined ? props : { ...props, density_texture: assetPath(tex) }) as Record<string, unknown>, ["color"]));}diff --git a/sdk/render/src/3d/materials.tsx b/sdk/render/src/3d/materials.tsxindex 0fb43173..ca9da7d0 100644--- a/sdk/render/src/3d/materials.tsx+++ b/sdk/render/src/3d/materials.tsx@@ -107,6 +107,10 @@ export interface SurfaceShaderSpec {wesl?: string;/** the same in plain WGSL */wgsl?: string;+ /** the source as an asset path (staticFile("shaders/x.wesl")), as Bevy's MaterialExtension::fragment_shader names one:+ * read as written, so a source that declares its own @binding(100) uniform struct gets its uniforms packed in that+ * struct's layout (docs/control.feature FC2b); in place of wesl or wgsl */+ fragment?: string;/** up to 16: a number (f32), [x, y], [x, y, z], [x, y, z, w] or "#rrggbb" (a linear vec4) */uniforms?: Record<string, number | number[] | string>;/** up to 4: an asset path, a picture made in code ({ width, height, pixels }) or "render:NAME"; with a sampler,@@ -157,13 +161,24 @@ export function samplerSpec(owner: string, s: SamplerSpec): SamplerSpec {const HOOK = /(^|[^A-Za-z0-9_])fn\s+(surface|lit)\s*\(|@fragment/;+/** A shader file's path as the engine reads it: found from the edit's folder (staticFile's /media/x as a model's src is)+ * by the native asset.load where there is one, as written elsewhere (plain bun) */+export function assetPath(p: string): string {+ const call = (globalThis as { __raea_call?: (n: string, a: string) => string | undefined }).__raea_call;+ if (typeof call !== "function") return p;+ const out = call("asset.load", JSON.stringify({ path: p }));+ return out ? (JSON.parse(out) as { path: string }).path : p;+}+/** A surface shader checked and given as the row's spec (its source, uniforms, textures). */export function surfaceShader(owner: string, sh: SurfaceShaderSpec, hook: RegExp = HOOK, hooks = "fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>), fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32>, or its own @fragment"): Record<string, unknown> {if (typeof sh !== "object" || sh === null) throw new TypeError(`${owner}: shader is { wesl | wgsl, uniforms, textures }`);- const { wesl, wgsl, uniforms = {}, textures = {}, defs } = sh;- if ((wesl === undefined) === (wgsl === undefined)) throw new TypeError(`${owner}: shader gives its source as wesl (or wgsl), one of them`);+ const { wesl, wgsl, fragment, uniforms = {}, textures = {}, defs } = sh;+ if ([wesl, wgsl, fragment].filter((s) => s !== undefined).length !== 1) throw new TypeError(`${owner}: shader gives its source as wesl, wgsl or a fragment path, one of them`);+ if (fragment !== undefined && (typeof fragment !== "string" || !fragment)) throw new TypeError(`${owner}: fragment is an asset path, got ${JSON.stringify(fragment)}`);const src = wesl ?? wgsl;- if (typeof src !== "string" || !hook.test(src)) throw new TypeError(`${owner}: shader defines ${hooks}`);+ // a file's source is checked where it's read (systems/shader)+ if (fragment === undefined && (typeof src !== "string" || !hook.test(src))) throw new TypeError(`${owner}: shader defines ${hooks}`);const us = Object.entries(uniforms);if (us.length > 16) throw new RangeError(`${owner}: a shader has at most 16 uniforms, got ${us.length}`);for (const [k, v] of us) {@@ -172,7 +187,7 @@ export function surfaceShader(owner: string, sh: SurfaceShaderSpec, hook: RegExpif (!ok) throw new TypeError(`${owner}: uniform ${k} is a number, [x, y(, z(, w))] or "#rrggbb", got ${JSON.stringify(v)}`);}checkTextures(owner, textures);- return { ...(wesl !== undefined ? { wesl } : { wgsl }), uniforms, textures, ...(defs !== undefined ? { defs: shaderDefs(owner, defs) } : {}) };+ return { ...(fragment !== undefined ? { fragment: assetPath(fragment) } : wesl !== undefined ? { wesl } : { wgsl }), uniforms, textures, ...(defs !== undefined ? { defs: shaderDefs(owner, defs) } : {}) };}/** A shader's textures checked: up to 4 pictures and one array (docs/shaders.feature SH9). */diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsxindex 646b298a..b35764a5 100644--- a/sdk/render/src/3d/shapes.tsx+++ b/sdk/render/src/3d/shapes.tsx@@ -1,5 +1,5 @@// Shapes and meshes: Bevy's primitives, buffer meshes, 3D text's props, and <Mesh> with its shape from its children.-import { Children, isValidElement, useId, type ReactElement, type ReactNode } from "react";+import { Children, isValidElement, memo, useId, type ReactElement, type ReactNode } from "react";import { Solid } from "../solid";import { useAnimation3d, type Keys, type Move, type TrackSpec } from "@raea/math/animate";import { Place3d, usePlace3d, usePointer3d, type LocalBounds, type PointerHandlers3d } from "../events3d";@@ -21,7 +21,7 @@ export function Canvas3D(props: Canvas3DProps) {// points at the 3D's texture), first so the 3D parts after it stay out of the page's paintreturn (<div data-3d="Canvas3D" data-props={JSON.stringify(serialisable(props))} style={FILL}>- <img data-raea-scene="" alt="" style={{ ...FILL, objectFit: "fill" }} />+ <img data-raea-scene="" data-clear={props.clearColor} alt="" style={{ ...FILL, objectFit: "fill" }} />{props.children}</div>);@@ -88,9 +88,11 @@ function geometry<P extends { args?: number[] }>(name: string, defaults: number[return node3d(name, { ...rest, args });};Object.defineProperty(Component, "name", { value: display });- GEOMETRY_SHAPES.set(Component, toShape);- GEOMETRY_BOUNDS.set(Component, (props) => boundsOf(name, argsOf(props as P)));- return Component;+ // memo: a geometry's props seldom change while its Mesh3d moves every frame, so React skips it (FC1b, bloom_3d)+ const Memo = Object.assign(memo(Component), { displayName: display });+ GEOMETRY_SHAPES.set(Memo, toShape);+ GEOMETRY_BOUNDS.set(Memo, (props) => boundsOf(name, argsOf(props as P)));+ return Memo as unknown as typeof Component;}/** @deprecated <Cuboid half_size>, raea/mesh */@@ -204,6 +206,9 @@ export interface BufferMeshProps {/** each vertex's colour: r, g, b, a (linear, 0 to 1) per vertex, or one "#rrggbb" per vertex; the material's colour* is multiplied by it (Bevy's ATTRIBUTE_COLOR), so leave the material white to see them as given */colors?: number[] | string[];+ /** a mesh's own attributes beyond those, for a three.js shader that reads them (<ThreeShaderMaterial>): each one's+ * size (1 to 4 numbers a vertex) and values, per vertex */+ attributes?: Record<string, { size: number; values: number[] }>;}/** Each mesh's shape text, checked and written once: React draws a <BufferMesh> every frame with the same arrays, and@@ -212,7 +217,7 @@ export interface BufferMeshProps {const shaped = new WeakMap<object, { of: unknown[]; text: string }>();function bufferShape(p: BufferMeshProps): string {- const of = [p.indices, p.normals, p.uvs, p.colors];+ const of = [p.indices, p.normals, p.uvs, p.colors, p.attributes];const had = Array.isArray(p.positions) ? shaped.get(p.positions) : undefined;if (had && had.of.every((a, i) => a === of[i])) return had.text;const text = writeBufferShape(p);@@ -239,7 +244,10 @@ function writeBufferShape(p: BufferMeshProps): string {if (hex ? c.length !== n : !(c.every((x) => typeof x === "number" && Number.isFinite(x)) && c.length === n * 4)) throw new RangeError(`BufferMesh: colors is r, g, b, a for each of the ${n} vertices, or one "#rrggbb" each`);}if (p.indices && (p.indices.length % 3 !== 0 || p.indices.some((i) => !Number.isInteger(i) || i < 0 || i >= n))) throw new RangeError(`BufferMesh: indices are three a triangle, each a vertex 0..${n - 1}`);- return "buffer:" + JSON.stringify({ positions: p.positions, indices: p.indices, normals: p.normals, uvs: p.uvs, colors: p.colors });+ for (const [k, a] of Object.entries(p.attributes ?? {})) {+ if (!(a && Number.isInteger(a.size) && a.size >= 1 && a.size <= 4 && Array.isArray(a.values) && a.values.length === n * a.size)) throw new RangeError(`BufferMesh: attribute ${k} is {size: 1 to 4, values: size numbers for each of the ${n} vertices}`);+ }+ return "buffer:" + JSON.stringify({ positions: p.positions, indices: p.indices, normals: p.normals, uvs: p.uvs, colors: p.colors, attributes: p.attributes });}/** A mesh from its own vertex buffers, as the geometry of a <Mesh> (Bevy's Mesh built from attributes): a terrain from@@ -388,6 +396,6 @@ export function Mesh(props: MeshProps) {if (anim.attr) extra["data-raea-anim"] = anim.attr;const id = useId();const m = usePlace3d(position, rotation, scale, props.quaternion);- usePointer3d(props.name ?? id, m, shape === undefined ? boundsFromChildren(props.children) : undefined, props as Record<string, unknown>);+ usePointer3d(props.name ?? id, m, () => (shape === undefined ? boundsFromChildren(props.children) : undefined), props as Record<string, unknown>);return node3d("Mesh", { ...props, animate: undefined, shape: undefined, position, rotation, scale }, <Place3d.Provider value={m}>{props.children}</Place3d.Provider>, Object.keys(extra).length ? extra : undefined);}diff --git a/sdk/render/src/3d/sprite.tsx b/sdk/render/src/3d/sprite.tsxindex d0be090e..30bdc01b 100644--- a/sdk/render/src/3d/sprite.tsx+++ b/sdk/render/src/3d/sprite.tsx@@ -33,6 +33,12 @@ export interface SpriteProps extends Place2dProps {flipY?: boolean;/** a tint multiplied over the picture (white by default) */color?: string;+ /** Bevy's SpriteImageMode::Tiled: the picture repeats across the sprite's width (tileX) or height (tileY) instead of+ * stretching to it, a tile every `tileStretch` x the picture's size (1 by default): a floor, a fence, a wall. Animate+ * width and height to show more or fewer tiles */+ tileX?: boolean;+ tileY?: boolean;+ tileStretch?: number;}/** A picture in 2D, over the 3D: Bevy's Sprite, drawn as a quad with its sprite material, a sprite sheet's cells cut@@ -47,6 +53,8 @@ export function Sprite(props: SpriteProps) {if (gr !== undefined && !(Array.isArray(gr) && gr.length === 2 && gr.every((n) => Number.isInteger(n) && n >= 1))) throw new TypeError(`Sprite: grid is [columns, rows], two whole numbers of 1 or more, got ${JSON.stringify(gr)}`);if (props.frame !== undefined && !(Number.isFinite(props.frame) && props.frame >= 0)) throw new RangeError(`Sprite: frame is a cell of the grid, 0 or more, got ${props.frame}`);for (const k of ["width", "height"] as const) if (props[k] !== undefined && !(Number.isFinite(props[k]) && props[k] > 0)) throw new RangeError(`Sprite: ${k} is px above 0, got ${props[k]}`);+ if (props.tileStretch !== undefined && !(Number.isFinite(props.tileStretch) && props.tileStretch > 0)) throw new RangeError(`Sprite: tileStretch is above 0, got ${props.tileStretch}`);+ if (props.tileStretch !== undefined && !props.tileX && !props.tileY) throw new TypeError("Sprite: tileStretch is for a tiled sprite: give tileX or tileY");check2d("Sprite", props);const id = useId();const handled = Object.keys(props).some((k) => /^on[A-Z]/.test(k));diff --git a/sdk/render/src/3d/three-shader.tsx b/sdk/render/src/3d/three-shader.tsxnew file mode 100644index 00000000..65d06c8d--- /dev/null+++ b/sdk/render/src/3d/three-shader.tsx@@ -0,0 +1,50 @@+// A three.js shader on a mesh (docs/r3f.feature R3F11): a ShaderMaterial's GLSL or a node material's WGSL, drawn by+// raea's engine with three's built-ins (raea-sys-three-shader). <R3F> makes one from a ShaderMaterial,+// RawShaderMaterial or node material in an R3F scene; written by hand, it runs a three.js shader as it is:+// <Mesh><Sphere /><ThreeShaderMaterial glsl={{ vertex, fragment }} uniforms={{ uTime: t }} /></Mesh>+import { node3d } from "./all";++/** A uniform's value: a number, a boolean, or its numbers in order (a vector's, a matrix's column by column as three's+ * `elements`, an array's elements one after another) */+export type ThreeUniform = number | boolean | number[];++export interface ThreeShaderMaterialProps {+ /** a ShaderMaterial's GLSL, its `#include`s expanded and its `defines` as #define lines in front; `raw` for a+ * RawShaderMaterial (which declares three's built-ins itself), `vertexColors` as the material's */+ glsl?: { vertex: string; fragment: string; raw?: boolean; vertexColors?: boolean };+ /** a node material's WGSL, as three's TSL builder writes it for raea (sdk/r3f's input/tsl.ts): the contract's+ * `three_vertex` and `three_fragment`, its uniforms' types, the mesh attributes it reads beyond the standard four */+ wgsl?: { vertex: string; fragment: string; uniforms?: { name: string; type: string; array?: number }[]; attributes?: string[] };+ /** each uniform's value this frame */+ uniforms?: Record<string, ThreeUniform>;+ /** each sampler's picture: a file, a data URL, "render:NAME" (at most four); `colorSpace: "linear"` for one three+ * samples raw (NoColorSpace: a distance field, a data map), "srgb" (the default) for a colour picture */+ textures?: Record<string, string | { src: string; colorSpace?: "srgb" | "linear"; sampler?: Record<string, unknown> }>;+ /** "display": its colour is what three's canvas shows (a ShaderMaterial's); "linear": scene light, tone-mapped as+ * the rest of the frame is (a node material's) */+ output?: "display" | "linear";+ transparent?: boolean;+ blending?: "normal" | "additive" | "add" | "multiply" | "none";+ side?: "front" | "back" | "double";+ depthWrite?: boolean;+ depthTest?: boolean;+ alphaTest?: number;+ /** three's clock this frame: [seconds, delta, frame] */+ time?: [number, number, number];+ /** the colour it's drawn in where its shader can't run (named in the render's warnings) */+ color?: string;+}++export function ThreeShaderMaterial(props: ThreeShaderMaterialProps) {+ const { glsl, wgsl } = props;+ if (!glsl === !wgsl) throw new TypeError("ThreeShaderMaterial: give glsl {vertex, fragment} or wgsl {vertex, fragment}, one of them");+ const src = (glsl ?? wgsl)!;+ if (typeof src.vertex !== "string" || typeof src.fragment !== "string") throw new TypeError("ThreeShaderMaterial: its vertex and fragment are source strings");+ const textures = Object.keys(props.textures ?? {});+ if (textures.length > 4) throw new RangeError(`ThreeShaderMaterial: at most 4 textures, got ${textures.length}`);+ for (const [k, v] of Object.entries(props.uniforms ?? {})) {+ const ok = typeof v === "boolean" || (typeof v === "number" && Number.isFinite(v)) || (Array.isArray(v) && v.every((x) => typeof x === "number" && Number.isFinite(x)));+ if (!ok) throw new TypeError(`ThreeShaderMaterial: uniform ${k} is a number, a boolean or a list of numbers, got ${JSON.stringify(v)}`);+ }+ return node3d("ThreeShaderMaterial", props as unknown as Record<string, unknown>);+}diff --git a/sdk/render/src/bevy3d.tsx b/sdk/render/src/bevy3d.tsxindex 77bedb16..61d13ea6 100644--- a/sdk/render/src/bevy3d.tsx+++ b/sdk/render/src/bevy3d.tsx@@ -17,3 +17,5 @@ export { SolariLighting, Pathtracer, type SolariLightingProps, type PathtracerPrexport { ConicalFrustum, type ConicalFrustumProps } from "./3d/shapes";// a Bevy texture (a camera's target) drawn in an element (B3 H7)export { TextureView } from "./layers";+// your own Material (docs/control.feature FC2a)+export { Material, type MaterialProps } from "./bevy3d/all";diff --git a/sdk/render/src/bevy3d/all.ts b/sdk/render/src/bevy3d/all.tsindex bccaad43..ad504405 100644--- a/sdk/render/src/bevy3d/all.ts+++ b/sdk/render/src/bevy3d/all.ts@@ -3,5 +3,6 @@export * from "./core";export * from "./colors";export * from "./materials";+export * from "./material";export * from "./lights";export * from "./mesh2d";diff --git a/sdk/render/src/bevy3d/colors.ts b/sdk/render/src/bevy3d/colors.tsindex 1880afb7..946f1cde 100644--- a/sdk/render/src/bevy3d/colors.ts+++ b/sdk/render/src/bevy3d/colors.ts@@ -65,12 +65,14 @@ export class LinearRgba {// a StandardMaterial's emissive as the old material takes it: a colour and its intensity. One made from a colour goes// as that colour; raw floats go as their hue at full strength (8-bit, as any colour row) times their brightest channel.-export function emissiveOf(e: string | LinearRgba): { emissive?: string; emissiveIntensity?: number } {- if (typeof e === "string") return { emissive: e };+// Its strength is Bevy's, as written (`emissive_nits`, core/scene emissive_power), not a 3d.tsx material's relative+// emissiveIntensity: Bevy's bloom_3d glows at LinearRgba 150 and 1000.+export function emissiveOf(e: string | LinearRgba): { emissive?: string; emissive_nits?: number } {+ if (typeof e === "string") return { emissive: e, emissive_nits: 1 };const f = e[MADE_FROM];- if (f) return { emissive: f.hex, ...(f.k !== 1 ? { emissiveIntensity: f.k } : {}) };+ if (f) return { emissive: f.hex, emissive_nits: f.k };const k = Math.max(e.red, e.green, e.blue);if (!(k > 0)) return {};const byte = (c: number) => Math.round(Math.max(0, Math.min(1, linearToSrgb(c / k))) * 255).toString(16).padStart(2, "0");- return { emissive: "#" + byte(e.red) + byte(e.green) + byte(e.blue), ...(k !== 1 ? { emissiveIntensity: k } : {}) };+ return { emissive: "#" + byte(e.red) + byte(e.green) + byte(e.blue), emissive_nits: k };}diff --git a/sdk/render/src/bevy3d/lights.tsx b/sdk/render/src/bevy3d/lights.tsxindex ae905988..d1fcc21f 100644--- a/sdk/render/src/bevy3d/lights.tsx+++ b/sdk/render/src/bevy3d/lights.tsx@@ -34,7 +34,8 @@ export interface PointLightProps extends LightCommon {intensity?: number;/** metres it reaches (20) */range?: number;- /** the bulb's radius in metres: soft shadows' size when soft_shadows_enabled */+ /** the bulb's radius in metres (0): the size of its highlight on shiny surfaces (a spherical area light), and soft+ * shadows' size when soft_shadows_enabled */radius?: number;shadow_maps_enabled?: boolean;soft_shadows_enabled?: boolean;@@ -52,7 +53,7 @@ export function PointLight(p: PointLightProps) {const { transform, visibility, intensity = 1_000_000, range = 20, radius, shadow_maps_enabled = false, soft_shadows_enabled, ...rest } = p;if (visibility === "Hidden") return null;const s = soft({ radius, soft_shadows_enabled });- return <PointLight3 {...rest} position={forward(transform).position} lumens={intensity} distance={range} castShadow={shadow_maps_enabled} {...(s !== undefined ? { softShadow: s } : {})} />;+ return <PointLight3 {...rest} position={forward(transform).position} lumens={intensity} distance={range} castShadow={shadow_maps_enabled} {...(radius ? { radius } : {})} {...(s !== undefined ? { softShadow: s } : {})} />;}export interface SpotLightProps extends PointLightProps {@@ -71,7 +72,7 @@ export function SpotLight(p: SpotLightProps) {const s = soft({ radius, soft_shadows_enabled });// the rows take a penumbra: inner = outer * (1 - penumbra) (scene3d.rs)const penumbra = 1 - Math.min(inner_angle, outer_angle) / outer_angle;- return <SpotLight3 {...rest} {...forward(transform)} lumens={intensity} distance={range} castShadow={shadow_maps_enabled} angle={outer_angle} penumbra={penumbra} {...(s !== undefined ? { softShadow: s } : {})} />;+ return <SpotLight3 {...rest} {...forward(transform)} lumens={intensity} distance={range} castShadow={shadow_maps_enabled} {...(radius ? { radius } : {})} angle={outer_angle} penumbra={penumbra} {...(s !== undefined ? { softShadow: s } : {})} />;}export interface DirectionalLightProps extends Omit<LightCommon, "children"> {diff --git a/sdk/render/src/bevy3d/material.tsx b/sdk/render/src/bevy3d/material.tsxnew file mode 100644index 00000000..5b09f7b8--- /dev/null+++ b/sdk/render/src/bevy3d/material.tsx@@ -0,0 +1,20 @@+// Your own Material (docs/control.feature FC2a): Bevy's Material with its fragment_shader(), a file compiled as written.+import { ExtendedMaterial, ShaderExtension, StandardMaterial } from "./materials";+import type { SurfaceShaderSpec } from "../3d";++/** Your own Material (docs/control.feature FC2a, its first step): Bevy's `impl Material` with a fragment_shader(), the+ * file compiled as written (its imports, its own @fragment, its own @binding(100) uniform struct if it has one, read+ * from `uniforms`). Today it draws as an ExtendedMaterial whose own fragment replaces the surface, the base unused.+ * @bevy bevy_pbr::material::Material */+export interface MaterialProps {+ /** the shader file, staticFile("shaders/x.wesl"), as Bevy's Material::fragment_shader names one */+ fragment: string;+ uniforms?: SurfaceShaderSpec["uniforms"];+ textures?: SurfaceShaderSpec["textures"];+ defs?: SurfaceShaderSpec["defs"];+}++export function Material({ fragment, uniforms, textures, defs }: MaterialProps) {+ if (typeof fragment !== "string" || !fragment) throw new TypeError(`Material: fragment is the shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(fragment)}`);+ return <ExtendedMaterial base={<StandardMaterial />} extension={<ShaderExtension fragment={fragment} uniforms={uniforms} textures={textures} defs={defs} />} />;+}diff --git a/sdk/render/src/bevy3d/materials.tsx b/sdk/render/src/bevy3d/materials.tsxindex 92eed8e7..9a619bf8 100644--- a/sdk/render/src/bevy3d/materials.tsx+++ b/sdk/render/src/bevy3d/materials.tsx@@ -1,5 +1,5 @@// Materials: standard, grid, paint, toon, extended (their colours in colors.ts).-import { isValidElement, useContext, type ReactElement, type ReactNode } from "react";+import { isValidElement, memo, useContext, type ReactElement, type ReactNode } from "react";import type { TrackSpec } from "@raea/math/animate";import { InModel } from "../3d/all";import { LinearRgba, MADE_FROM, baseOf, emissiveOf, type Affine2, type Srgba } from "./all";@@ -131,7 +131,7 @@ const TOON_ANIMATE: Record<string, string> = { shadow_color: "shadowColor", rim_const COLOUR_FIELDS = new Set(["color", "emissive", "shadowColor"]);// an `animate` as the old material's: its keys renamed; an emissive's LinearRgba keys as their colour and an-// emissiveIntensity track (a colour track's emissive is at strength 1, as Bevy's emissive is the whole colour)+// emissive_nits track, Bevy's strength as written (a colour track's emissive is at strength 1, as Bevy's emissive is the whole colour)function animateOf(owner: string, a: object | undefined, names: Record<string, string>, fields: Record<string, "number" | "string"> = {}): { animate?: Record<string, TrackSpec>; emissive?: Record<string, unknown> } {if (!a) return {};const animate: Record<string, TrackSpec> = {};@@ -151,12 +151,12 @@ function animateOf(owner: string, a: object | undefined, names: Record<string, sconst from = spec.keys.map(([, v]) => (v as LinearRgba)[MADE_FROM]);if (from.some((f) => !f || f.hex !== from[0]!.hex)) throw new TypeError(`${owner}: an emissive track's LinearRgba keys are one colour, LinearRgba.from(Srgba.hex(c)).mul(k) each`);emissive = { emissive: from[0]!.hex };- animate.emissiveIntensity = { ...spec, keys: spec.keys.map(([f], i) => [f, from[i]!.k]) };+ animate.emissive_nits = { ...spec, keys: spec.keys.map(([f], i) => [f, from[i]!.k]) };continue;}const kind = COLOUR_FIELDS.has(name) ? "string" : "number";if (!spec.keys.every(([, v]) => typeof v === kind)) throw new TypeError(`${owner}: animate's ${k} keys are ${kind === "string" ? "colours" : "numbers"}`);- if (name === "emissive") emissive = { emissiveIntensity: undefined };+ if (name === "emissive") emissive = { emissive_nits: 1 };animate[name] = spec as TrackSpec;}return { animate, emissive };@@ -214,9 +214,9 @@ function uvOf(t: Affine2 | undefined): { repeat?: [number, number]; uvTransform?/** Bevy's StandardMaterial for the Mesh3d it's inside. Unlit draws as MeshBasicMaterial; a clearcoat or transmission* as MeshPhysicalMaterial; anything else as MeshStandardMaterial, all on Bevy's StandardMaterial in the engine.* @bevy bevy_pbr::pbr_material::StandardMaterial */-export function StandardMaterial<A>(p: StandardMaterialProps & { animate?: Only<A, StandardMaterialAnimate> }) {+export const StandardMaterial = memo(function StandardMaterial<A>(p: StandardMaterialProps & { animate?: Only<A, StandardMaterialAnimate> }) {return standard(p, {});-}+}) as unknown as <A>(p: StandardMaterialProps & { animate?: Only<A, StandardMaterialAnimate> }) => ReactElement;// raea's extensions an ExtendedMaterial puts on its StandardMaterial, as the old material's propstype Extended = { grid?: GridExtensionProps; paint?: PaintExtensionProps; wear?: MeshStandardMaterialProps["wear"]; shader?: Record<string, unknown> };@@ -363,6 +363,7 @@ export function ShaderExtension(_: ShaderExtensionProps): ReactNode {throw new TypeError("ShaderExtension goes in an ExtendedMaterial: <ExtendedMaterial base={<StandardMaterial />} extension={<ShaderExtension wesl={src} />} />");}+/** raea's extension of StandardMaterial that cel-shades it (the engine's ToonExt; three.js's MeshToonMaterial): the* scene's lights in `steps` hard bands (2; `bands` for an explicit ramp, darkest first), the bottom one* `shadow_color` (the base colour darker, nudged towards violet), with an optional rim, highlight and ink outlinediff --git a/sdk/render/src/events3d.tsx b/sdk/render/src/events3d.tsxindex bdd39c36..cf1ffd46 100644--- a/sdk/render/src/events3d.tsx+++ b/sdk/render/src/events3d.tsx@@ -238,6 +238,11 @@ const scene = {last: { hover: null, down: null } as Last,};+/** What the frame last rendered can be picked: each part with handlers, by id, and its bounds in the world. */+export function pickable3d(): ReadonlyMap<string, Pickable | undefined> {+ return new Map([...scene.parts].map(([id, p]) => [id, p.target]));+}+function begin(frame: number) {if (scene.frame === frame) return;// a frame that doesn't follow the last one starts with nothing pressed or under the pointer@@ -253,10 +258,14 @@ export function useCamera3d(camera: PickCamera) {scene.camera = camera;}-/** A part's handlers (its on* props) called for the frame's pointer events on it; `bounds` its shape's, in its own- * space, under the world matrix `m`. Nothing without a handler. */-export function usePointer3d(id: string, m: Mat4, bounds: LocalBounds | undefined, props: Record<string, unknown>) {- usePart(id, bounds === undefined ? undefined : (handlers) => ({ target: worldBounds(id, m, bounds), handlers }), props);+/** A part's handlers (its on* props) called for the frame's pointer events on it; `bounds` gives its shape's, in its+ * own space, under the world matrix `m`. Nothing without a handler, and then `bounds` isn't asked: a part with none+ * worked out its bounds every render, half of bloom_3d's React step (docs/control.feature FC1b). */+export function usePointer3d(id: string, m: Mat4, bounds: () => LocalBounds | undefined, props: Record<string, unknown>) {+ usePart(id, (handlers) => {+ const b = bounds();+ return b === undefined ? undefined : { target: worldBounds(id, m, b), handlers };+ }, props);}/** A 2D part's handlers, as usePointer3d's: picked in frame px over the 3D, before any 3D part. */@@ -264,10 +273,14 @@ export function usePointer2d(id: string, flat: Flat, props: Record<string, unknousePart(id, (handlers) => ({ flat, handlers }), props);}-function usePart(id: string, part: ((handlers: Record<string, Handler>) => Part) | undefined, props: Record<string, unknown>) {+const POINTER_ENTRIES = Object.entries(POINTER_PROPS);++function usePart(id: string, part: (handlers: Record<string, Handler>) => Part | undefined, props: Record<string, unknown>) {const handlers: Record<string, Handler> = {};- for (const [type, prop] of Object.entries(POINTER_PROPS)) if (typeof props[prop] === "function") handlers[type] = props[prop] as Handler;- const any = Object.keys(handlers).length > 0 && part !== undefined;+ let n = 0;+ for (const [type, prop] of POINTER_ENTRIES) if (typeof props[prop] === "function") (handlers[type] = props[prop] as Handler), n++;+ const made = n > 0 ? part(handlers) : undefined;+ const any = made !== undefined;// only a part with handlers follows the clock: reading it re-renders the part every frame, and every part reading// it made 10 000 still cubes re-render every frame (docs/control.feature FC1b). The three are context reads only,// which hold no hook slot in React (readContext) or in the live runtime (lite's useContext logs the read), so a@@ -277,7 +290,7 @@ function usePart(id: string, part: ((handlers: Record<string, Handler>) => Part)const { width, height } = any ? useVideoConfig() : { width: 0, height: 0 };if (any) {begin(frame);- scene.parts.set(id, part(handlers));+ scene.parts.set(id, made);}useEffect(() => {if (!any || !input) return;diff --git a/sdk/render/src/three.tsx b/sdk/render/src/three.tsxindex 82afbfd7..2944f318 100644--- a/sdk/render/src/three.tsx+++ b/sdk/render/src/three.tsx@@ -3,5 +3,5 @@// `intensity`. Not public: sdk/r3f's <R3F> maps three.js's JSX onto them, bevy3d's Bevy-named components draw through// them, and the conformance tests compare against them. Compositions use Camera3d, Mesh3d, StandardMaterial, Entity// and raea/light's lights.-export { Mesh, MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial, MeshToonMaterial, AmbientLight, DirectionalLight, PointLight, SpotLight, RectAreaLight, PerspectiveCamera, OrthographicCamera, Group } from "./3d/all";-export type { MeshProps, MeshStandardMaterialProps, MeshPhysicalMaterialProps, MeshBasicMaterialProps, MeshToonMaterialProps, AmbientLightProps, DirectionalLightProps, PointLightProps, SpotLightProps, RectAreaLightProps, PerspectiveCameraProps, OrthographicCameraProps, GroupProps } from "./3d/all";+export { Mesh, MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial, MeshToonMaterial, ThreeShaderMaterial, AmbientLight, DirectionalLight, PointLight, SpotLight, RectAreaLight, PerspectiveCamera, OrthographicCamera, Group } from "./3d/all";+export type { MeshProps, MeshStandardMaterialProps, MeshPhysicalMaterialProps, MeshBasicMaterialProps, MeshToonMaterialProps, ThreeShaderMaterialProps, ThreeUniform, AmbientLightProps, DirectionalLightProps, PointLightProps, SpotLightProps, RectAreaLightProps, PerspectiveCameraProps, OrthographicCameraProps, GroupProps } from "./3d/all";diff --git a/sdk/rune/examples/motion.tsx b/sdk/rune/examples/motion.tsxindex 5afa44bd..0d8b6236 100644--- a/sdk/rune/examples/motion.tsx+++ b/sdk/rune/examples/motion.tsx@@ -2,7 +2,7 @@// that slides in on "pop"; a badge counts them with rolling digits; the panel behind has glass; a switch toggles// whether new toasts are urgent.import { useState } from "react";-import { Badge, RollingText, Spring, Switch, rune } from "../src/index.ts";+import { Badge, RollingText, Spring, Switch, rune } from "@raea/rune";export default function Toasts() {const [toasts, setToasts] = useState<{ id: number; urgent: boolean }[]>([]);diff --git a/sdk/rune/examples/signin.tsx b/sdk/rune/examples/signin.tsxindex 757fb386..a96cb997 100644--- a/sdk/rune/examples/signin.tsx+++ b/sdk/rune/examples/signin.tsx@@ -3,7 +3,7 @@// ready, md: putting the two fields side by side, and dark: for the system's appearance. The submit springs on "snap"// in Rune; on the web that is a CSS transition (@raea/rune's web.css).import { useState } from "react";-import { rune } from "../src/index.ts";+import { rune } from "@raea/rune";const field ="h-9 w-full rounded-md border border-zinc-300 bg-white px-3 text-sm text-zinc-900 outline-none hover:border-zinc-400 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-50";diff --git a/sdk/skills/raea/reference/sdk.md b/sdk/skills/raea/reference/sdk.mdindex ce456aa8..01b14c18 100644--- a/sdk/skills/raea/reference/sdk.md+++ b/sdk/skills/raea/reference/sdk.md@@ -55,7 +55,7 @@ with a capital, hooks with `use`. A component's props are in its file.## `raea/light` (sdk/raea/src/light.ts)-`AmbientLight`, `Atmosphere`, `DirectionalLight`, `Environment`, `GlobalAmbientLight`, `Pathtracer`, `PointLight`, `RectLight`, `Shadows`, `SolariLighting`, `SpotLight`, `light_consts`+`AmbientLight`, `Atmosphere`, `DirectionalLight`, `Environment`, `EnvironmentMapLight`, `GlobalAmbientLight`, `Pathtracer`, `PointLight`, `RectLight`, `Shadows`, `SolariLighting`, `SpotLight`, `light_consts`## `raea/math` (sdk/raea/src/math.ts)@@ -67,7 +67,7 @@ with a capital, hooks with `use`. A component's props are in its file.## `raea/pbr` (sdk/raea/src/pbr.ts)-`AmbientOcclusion`, `Decal`, `ExtendedMaterial`, `Fire`, `Fog`, `FogVolume`, `GridExtension`, `PaintExtension`, `Refinish`, `ShaderExtension`, `ShaderMesh`, `StandardMaterial`, `SurfaceShader`, `ToonExtension`, `ToonMaterial`, `VolumetricFog`, `WearExtension`+`AmbientOcclusion`, `Decal`, `ExtendedMaterial`, `Fire`, `Fog`, `FogVolume`, `GridExtension`, `PaintExtension`, `Refinish`, `ShaderExtension`, `ShaderMesh`, `StandardMaterial`, `SurfaceShader`, `ThreeShaderMaterial`, `ToonExtension`, `ToonMaterial`, `VolumetricFog`, `WearExtension`## `raea/post_process` (sdk/raea/src/post_process.ts)diff --git a/sdk/web/test/parity/cases.ts b/sdk/web/test/parity/cases.tsindex ab9c2bbc..b94f6cc1 100644--- a/sdk/web/test/parity/cases.ts+++ b/sdk/web/test/parity/cases.ts@@ -18,4 +18,5 @@ export const CASES: Case[] = [{ name: "resource", kinds: ["BevyResource"], edit: `${BENCH}/reflect-keyed-resource-still.tsx`, frame: 15 },{ name: "entities", kinds: ["Entities"], edit: "./entities.tsx", frame: 10 },{ name: "fog", kinds: ["VolumetricFog", "FogVolume"], edit: "./fog.tsx", frame: 0 },+ { name: "three-shader", kinds: ["ThreeShaderMaterial"], edit: "./three-shader.tsx", frame: 0 },];diff --git a/sdk/web/test/parity/three-shader.tsx b/sdk/web/test/parity/three-shader.tsxnew file mode 100644index 00000000..7de23292--- /dev/null+++ b/sdk/web/test/parity/three-shader.tsx@@ -0,0 +1,44 @@+// raea-web parity (docs/r3f.feature R3F11): a three.js ShaderMaterial's GLSL run by raea's engine. naga translates the+// vertex shader (a sphere rippled along x) and the fragment shader (its normal lit by hand, a uniform colour, a stripe+// from its uv) and raea-sys-three-shader runs them with three's built-ins.+import { AbsoluteFill, Composition, registerRoot } from "raea";+import { Canvas3D } from "raea/3d";+import { Camera3d } from "raea/camera";+import { Mesh3d, Sphere } from "raea/mesh";+import { ThreeShaderMaterial } from "raea/pbr";+import { Transform } from "raea/transform";++const vertex = /* glsl */ `+uniform float uTime;+varying vec3 vNormal;+varying vec2 vUv;+void main() {+ vec3 p = position + normal * sin(position.y * 8.0 + uTime) * 0.08;+ vNormal = normalize(normalMatrix * normal);+ vUv = uv;+ gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);+}`;+const fragment = /* glsl */ `+uniform vec3 uColor;+varying vec3 vNormal;+varying vec2 vUv;+void main() {+ float light = 0.25 + 0.75 * max(dot(normalize(vNormal), normalize(vec3(0.4, 0.8, 0.6))), 0.0);+ float stripe = step(0.5, fract(vUv.x * 8.0));+ gl_FragColor = vec4(mix(uColor, vec3(1.0), stripe * 0.35) * light, 1.0);+}`;++function Shader() {+ return (+ <AbsoluteFill style={{ background: "#0b0d12" }}>+ <Canvas3D>+ <Camera3d transform={Transform.fromXyz(0, 0, 4).lookingAt([0, 0, 0])} />+ <Mesh3d name="ball">+ <Sphere radius={1} />+ <ThreeShaderMaterial glsl={{ vertex, fragment }} uniforms={{ uTime: 1.2, uColor: [0.9, 0.35, 0.15] }} />+ </Mesh3d>+ </Canvas3D>+ </AbsoluteFill>+ );+}+registerRoot(() => <Composition id="main" component={Shader} durationInFrames={1} fps={30} width={320} height={180} />);diff --git a/systems/environment/src/lib.rs b/systems/environment/src/lib.rsindex 00e3eed9..9f0df4a4 100644--- a/systems/environment/src/lib.rs+++ b/systems/environment/src/lib.rs@@ -283,6 +283,7 @@ fn cubemap(eq: &Equirect, size: u32) -> Image {/// largest panorama's width / 4, a power of two from 64 to 2048, since the generated light's targets are sized by the/// first), then the light and the sky set up as the first frame has them (sync_environment moves them per frame).pub fn environment(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, inserted: &[Tup], dir: &Path) -> Result<(), String> {+ prefiltered(world, e, vals)?;let Some(V::S(list)) = vals.get("env_srcs") else { return Ok(()) };let srcs: Vec<String> = serde_json::from_str(list).map_err(|e| format!("camera: env_srcs: {e}"))?;if srcs.is_empty() || preview() {@@ -322,6 +323,22 @@ pub fn environment(world: &mut World, e: Entity, vals: &BTreeMap<String, V>, insOk(())}+/// Bevy's EnvironmentMapLight from its own prefiltered cubemaps (envmap_diffuse_map, envmap_specular_map: .ktx2 files,+/// as Bevy's examples load environment_maps/pisa_*_rgb9e5_zstd.ktx2) at envmap_k cd/m², decoded by Bevy's KTX2 reader+fn prefiltered(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) -> Result<(), String> {+ let (Some(V::S(d)), Some(V::S(s))) = (vals.get("envmap_diffuse_map"), vals.get("envmap_specular_map")) else { return Ok(()) };+ let mut load = |p: &str| -> Result<Handle<Image>, String> {+ let bytes = std::fs::read(p).map_err(|err| format!("EnvironmentMapLight: {p}: {err}"))?;+ let ext = Path::new(p).extension().and_then(|x| x.to_str()).unwrap_or("ktx2");+ let img = Image::from_buffer(&bytes, bevy::image::ImageType::Extension(ext), bevy::image::CompressedImageFormats::NONE, false, bevy::image::ImageSampler::Default, bevy::asset::RenderAssetUsages::RENDER_WORLD)+ .map_err(|err| format!("EnvironmentMapLight: {p}: {err}"))?;+ Ok(world.resource_mut::<Assets<Image>>().add(img))+ };+ let (diffuse_map, specular_map) = (load(d)?, load(s)?);+ world.entity_mut(e).insert(EnvironmentMapLight { diffuse_map, specular_map, intensity: num(vals, "envmap_k", 1.0), ..default() });+ Ok(())+}+/// Each frame's panorama, light, turn and sky: the camera's light points at the targets of the panorama's bake, so/// switching the source switches the light that frame.pub fn sync_environment(frame: Res<FrameRows>, mut q: Query<(Entity, &EnvMaps, &mut EnvironmentMapLight, Option<&mut Skybox>), Without<EnvBake>>, bakes: Query<&EnvironmentMapLight, With<EnvBake>>) {diff --git a/systems/material/src/mesh.rs b/systems/material/src/mesh.rsindex 26fa9a21..bf499f74 100644--- a/systems/material/src/mesh.rs+++ b/systems/material/src/mesh.rs@@ -23,10 +23,7 @@ pub fn buffer_colors(json: &str) -> Result<Option<Vec<[f32; 4]>>, String> {if per.len() != n {return Err(format!("a buffer mesh's colors: one for each of its {n} vertices, got {}", per.len()));}- let idx: Vec<usize> = match v.get("indices").and_then(|i| i.as_array()) {- Some(i) => i.iter().map(|x| x.as_f64().unwrap_or(0.0) as usize).collect(),- None => (0..n).collect(),- };+ let idx = buffer_corners(&v, n);Ok(Some(idx.iter().map(|&i| per[i.min(n.saturating_sub(1))]).collect()))}@@ -158,6 +155,14 @@ pub fn buffer_tris(json: &str) -> Result<(raea_core_shape::Tris, Option<Vec<[f32Ok((t, uv))}+/// A buffer mesh's triangle corners: the vertex each one is (its `indices`, or each of its `verts` vertices in turn).+pub fn buffer_corners(v: &serde_json::Value, verts: usize) -> Vec<usize> {+ match v.get("indices").and_then(serde_json::Value::as_array) {+ Some(i) => i.iter().map(|x| x.as_f64().unwrap_or(0.0) as usize).collect(),+ None => (0..verts).collect(),+ }+}+/// Texture coordinates for a Manifold mesh (it has none): each vertex projected along its face's main axis onto the/// mesh's bounds, so a picture map covers each side of a box once, the right way round seen from outside.pub fn box_uvs(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> Vec<[f32; 2]> {@@ -186,3 +191,42 @@ pub fn box_uvs(pos: &[[f32; 3]], nor: &[[f32; 3]]) -> Vec<[f32; 2]> {}).collect()}++/// A mesh row's shape as a Bevy Mesh (docs/media.feature M2): a sphere alone is Bevy's Sphere::mesh() (icosphere or UV+/// sphere) and a cuboid alone its Cuboid's (UVs a face each), as a Bevy Mesh3d's; a <BufferMesh> ("buffer:{positions,+/// indices, normals, uvs, colors}") its own vertex buffers; anything else Manifold's, flat-shaded. `uvs` gives it+/// texture coordinates (a picture map, a grid's outline) and `tangents` tangents made from them (a normal map).+pub fn shape_mesh(id: &str, expr: &str, uvs: bool, tangents: bool) -> Result<Mesh, String> {+ let ball = raea_core_shape::sphere_of(expr).map(|s| match s {+ raea_core_shape::SphereOf::Ico { radius, subdivisions } => Sphere::new(radius).mesh().ico(subdivisions).map_err(|e| format!("mesh {id}: {e}")),+ raea_core_shape::SphereOf::Uv { radius, sectors, stacks } => Ok(Sphere::new(radius).mesh().uv(sectors, stacks)),+ }).or_else(|| raea_core_shape::cuboid_of(expr).map(|[w, h, d]| Ok(Mesh::from(Cuboid::new(w, h, d)))));+ if let Some(mut m) = ball.transpose()? {+ if tangents {+ m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;+ }+ return Ok(m);+ }+ let (tris, own_uvs, own_colors) = match expr.strip_prefix("buffer:") {+ Some(b) => {+ let c = buffer_colors(b).map_err(|e| format!("mesh {id}: {e}"))?;+ let (t, u) = buffer_tris(b).map_err(|e| format!("mesh {id}: {e}"))?;+ (std::sync::Arc::new(t), u, c)+ }+ None => (raea_core_shape::cached(expr).map_err(|e| format!("mesh {id}: {e}"))?, None, None),+ };+ let mut m = Mesh::new(bevy::render::render_resource::PrimitiveTopology::TriangleList, bevy::asset::RenderAssetUsages::default());+ m.insert_attribute(Mesh::ATTRIBUTE_POSITION, tris.positions.clone());+ m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, tris.normals.clone());+ // a <BufferMesh colors>: per-vertex colours, which StandardMaterial multiplies its colour by+ if let Some(c) = own_colors {+ m.insert_attribute(Mesh::ATTRIBUTE_COLOR, c);+ }+ if own_uvs.is_some() || uvs {+ m.insert_attribute(Mesh::ATTRIBUTE_UV_0, own_uvs.unwrap_or_else(|| box_uvs(&tris.positions, &tris.normals)));+ if tangents {+ m.generate_tangents().map_err(|e| format!("mesh {id}: normalMap: its tangents: {e}"))?;+ }+ }+ Ok(m)+}diff --git a/systems/parity/Cargo.toml b/systems/parity/Cargo.tomlindex 344654b9..0d115b02 100644--- a/systems/parity/Cargo.toml+++ b/systems/parity/Cargo.toml@@ -7,5 +7,5 @@ publish = falsedescription = "The parity probe (docs/control.feature FC0a): what a frame cost and what the World held, written as JSON lines at chosen frames, the same plugin in a Bevy example and in raea, off unless RAEA_PARITY is set"[dependencies]-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "ui_bevy_render"] }serde_json = "1"diff --git a/systems/parity/src/lib.rs b/systems/parity/src/lib.rsindex 771e84a2..a89fe494 100644--- a/systems/parity/src/lib.rs+++ b/systems/parity/src/lib.rs@@ -67,10 +67,70 @@ pub fn install(app: &mut App) {let _ = std::fs::write(world_file(&out), "");}let _ = std::fs::write(&out, "");+ if png.is_some() {+ app.add_systems(First, offscreen);+ app.add_systems(PreUpdate, no_input.after(bevy::input::InputSystems));+ }app.insert_resource(Probe { out: out.into(), frames, png, exit, types, frame: 0, since: Instant::now(), ticks: 0 });app.add_systems(Last, (probe, dump).chain());}+/// The picture the window's cameras draw into instead of its swapchain, when the example's pictures are taken+/// (RAEA_PARITY_PNG): a window shows black once macOS stops compositing it (an unattended Mac mini's display asleep,+/// 2026-11-07: frames after the first second came back black), an image never does. Same size and format the window+/// would have; the first camera is the UI's, as the window's would be.+#[derive(Resource)]+struct Offscreen(Handle<Image>);++fn offscreen(+ mut commands: Commands,+ mut images: ResMut<Assets<Image>>,+ window: Query<&Window, With<bevy::window::PrimaryWindow>>,+ cams: Query<(Entity, &bevy::camera::RenderTarget), Added<bevy::camera::RenderTarget>>,+ held: Option<Res<Offscreen>>,+) {+ let Ok(w) = window.single() else { return };+ let mut target = held.map(|h| h.0.clone());+ for (e, t) in &cams {+ if !matches!(t, bevy::camera::RenderTarget::Window(bevy::window::WindowRef::Primary)) {+ continue;+ }+ let first = target.is_none();+ let h = target.get_or_insert_with(|| {+ let h = images.add(Image::new_target_texture(w.physical_width(), w.physical_height(), bevy::render::render_resource::TextureFormat::Rgba8UnormSrgb, None));+ commands.insert_resource(Offscreen(h.clone()));+ h+ });+ commands.entity(e).insert(bevy::camera::RenderTarget::Image(h.clone().into()));+ if first {+ commands.entity(e).insert(bevy::ui::IsDefaultUiCamera);+ }+ }+}++/// No real input while the pictures are taken: a run must repeat, and a mouse moved over the Mac (2026-11-06:+/// camera_orbit's camera swung by AccumulatedMouseMotion) would steer the example. Cleared after Bevy's input systems+/// fill them, before the example's Update reads them.+fn no_input(+ motion: Option<ResMut<bevy::input::mouse::AccumulatedMouseMotion>>,+ scroll: Option<ResMut<bevy::input::mouse::AccumulatedMouseScroll>>,+ buttons: Option<ResMut<ButtonInput<MouseButton>>>,+ keys: Option<ResMut<ButtonInput<KeyCode>>>,+) {+ if let Some(mut m) = motion {+ *m = default();+ }+ if let Some(mut s) = scroll {+ *s = default();+ }+ if let Some(mut b) = buttons {+ b.reset_all();+ }+ if let Some(mut k) = keys {+ k.reset_all();+ }+}+/// A fixed clock of `fps` frames a second (Bevy's TimeUpdateStrategy::ManualDuration), for a run that must repeat.pub fn fixed_clock(app: &mut App, fps: f64) {app.insert_resource(TimeUpdateStrategy::ManualDuration(Duration::from_secs_f64(1.0 / fps)));@@ -78,6 +138,7 @@ pub fn fixed_clock(app: &mut App, fps: f64) {#[allow(clippy::type_complexity)]fn probe(+ offscreen: Option<Res<Offscreen>>,mut p: ResMut<Probe>,all: Query<Entity>,meshes_q: Query<(&Mesh3d, Option<&MeshMaterial3d<StandardMaterial>>, Option<&ViewVisibility>, Option<&Aabb>)>,@@ -143,7 +204,8 @@ fn probe(let _ = writeln!(file, "{line}");}if let Some(d) = &p.png {- commands.spawn(Screenshot::primary_window()).observe(save_to_disk(d.join(format!("{f}.png"))));+ let shot = offscreen.as_ref().map_or_else(Screenshot::primary_window, |o| Screenshot::image(o.0.clone()));+ commands.spawn(shot).observe(save_to_disk(d.join(format!("{f}.png"))));}}diff --git a/systems/shader/src/layout.rs b/systems/shader/src/layout.rsnew file mode 100644index 00000000..09b3a426--- /dev/null+++ b/systems/shader/src/layout.rs@@ -0,0 +1,141 @@+//! An extension's own uniform struct (docs/control.feature FC2b): a source that declares `@binding(100)+//! var<uniform> NAME: TYPE` itself is compiled as written, and its uniforms are laid out in TYPE's fields, in WGSL's+//! uniform layout, across the ShaderExt's 16 vec4 slots (256 bytes), so the author's struct reads them where it+//! declares them (Bevy's extended_material.wesl: `quantize_steps: u32` at offset 0).++use bevy::prelude::Vec4;+use bevy::shader::ShaderDefVal;++/// The fields of the struct `src` binds at `@binding(100)` as a uniform, in order, each `(name, type)`: a field under+/// `@if(DEF)` only when DEF is set true in `defs`. None when the source declares no such binding (raea's own layout).+pub fn own_struct(src: &str, defs: &[ShaderDefVal]) -> Option<Result<Vec<(String, String)>, String>> {+ let at = src.find("@binding(100)")?;+ let rest = &src[at..];+ let decl = &rest[..rest.find(';')?];+ let ty = match decl.find("var<uniform>").and_then(|v| decl[v..].split_once(':')) {+ Some((_, t)) => t.trim().to_string(),+ None => return Some(Err("@binding(100) is a var<uniform> NAME: TYPE (the extension's uniforms)".into())),+ };+ let Some(open) = find_struct(src, &ty) else { return Some(Err(format!("@binding(100)'s type {ty} isn't a struct declared in the source"))) };+ let Some(close) = src[open..].find('}') else { return Some(Err(format!("struct {ty} has no closing brace"))) };+ let body = &src[open..open + close];+ let set = |d: &str| defs.iter().any(|v| matches!(v, ShaderDefVal::Bool(k, true) if k == d) || matches!(v, ShaderDefVal::Int(k, n) if k == d && *n != 0));+ let mut out = Vec::new();+ // an @if on its own line holds for the field after it (as Bevy's extended_material.wesl writes it)+ let mut pending: Option<&str> = None;+ for line in body.lines().map(|l| l.split("//").next().unwrap_or("").trim()).filter(|l| !l.is_empty()) {+ let (cond, field) = match line.strip_prefix("@if(") {+ Some(r) => match r.split_once(')') {+ Some((d, f)) => (Some(d.trim()), f.trim()),+ None => return Some(Err(format!("struct {ty}: {line:?}"))),+ },+ None => (pending.take(), line),+ };+ if field.is_empty() {+ pending = cond;+ continue;+ }+ if cond.is_some_and(|d| !set(d)) {+ continue;+ }+ let Some((n, t)) = field.trim_end_matches(',').split_once(':') else { return Some(Err(format!("struct {ty}: {line:?} isn't NAME: TYPE"))) };+ out.push((n.trim().to_string(), t.trim().to_string()));+ }+ Some(Ok(out))+}++/// Where `struct NAME {`'s body starts+fn find_struct(src: &str, name: &str) -> Option<usize> {+ let mut from = 0;+ while let Some(i) = src[from..].find("struct") {+ let s = from + i + "struct".len();+ let after = src[s..].trim_start();+ if after.starts_with(name) && after[name.len()..].trim_start().starts_with('{') {+ return Some(s + src[s..].find('{')? + 1);+ }+ from = s;+ }+ None+}++/// A field's WGSL type as (scalar kind, components): f32, u32 or i32, alone or in a vec2/3/4+fn kind(t: &str) -> Option<(char, usize)> {+ let t = t.replace(' ', "");+ let scalar = |s: &str| match s {+ "f32" => Some('f'),+ "u32" => Some('u'),+ "i32" => Some('i'),+ _ => None,+ };+ if let Some(k) = scalar(&t) {+ return Some((k, 1));+ }+ for n in 2..=4 {+ if let Some(inner) = t.strip_prefix(&format!("vec{n}<")).and_then(|r| r.strip_suffix('>')) {+ return Some((scalar(inner)?, n));+ }+ if let Some(c) = t.strip_prefix(&format!("vec{n}")).filter(|c| c.len() == 1).and_then(|c| c.chars().next()) {+ return "fui".contains(c).then_some((c, n));+ }+ }+ None+}++/// The uniforms laid out in `fields` (WGSL's uniform layout: a scalar aligned to 4, a vec2 to 8, a vec3 or vec4 to 16)+/// in 256 bytes. Each field takes the uniform of its name; every field needs one, and every uniform a field.+pub fn pack(fields: &[(String, String)], uniforms: &[(String, Vec4)]) -> Result<[Vec4; 16], String> {+ let mut words = [0u32; 64];+ let mut at = 0usize;+ for (name, ty) in fields {+ let (k, n) = kind(ty).ok_or_else(|| format!("uniform {name}: its type {ty} isn't f32, u32, i32 or a vec2/3/4 of one (the rest are FC2b's to come)"))?;+ let align = match n {+ 1 => 1,+ 2 => 2,+ _ => 4,+ };+ at = at.div_ceil(align) * align;+ if at + n > words.len() {+ return Err(format!("uniform {name}: the struct passes 256 bytes"));+ }+ let v = uniforms.iter().find(|(u, _)| u == name).map(|(_, v)| *v).ok_or_else(|| format!("the shader's uniform struct has {name}, which the uniforms don't give"))?;+ for c in 0..n {+ let x = v[c];+ words[at + c] = match k {+ 'f' => x.to_bits(),+ 'u' => x.round().max(0.0) as u32,+ _ => (x.round() as i32) as u32,+ };+ }+ at += n;+ }+ if let Some((u, _)) = uniforms.iter().find(|(u, _)| !fields.iter().any(|(f, _)| f == u)) {+ return Err(format!("uniform {u} isn't a field of the shader's @binding(100) struct"));+ }+ let mut out = [Vec4::ZERO; 16];+ for (i, s) in out.iter_mut().enumerate() {+ *s = Vec4::from_array(std::array::from_fn(|c| f32::from_bits(words[i * 4 + c])));+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;++ const SRC: &str = "struct MyExtendedMaterial {\n quantize_steps: u32,\n // padding\n @if(SIXTEEN_BYTE_ALIGNMENT)\n _pad: u32,\n tint: vec3<f32>,\n}\n@group(constants::MATERIAL_BIND_GROUP) @binding(100)\nvar<uniform> my_extended_material: MyExtendedMaterial;\n";++ #[test]+ fn an_own_struct_is_read_with_its_conditions_and_packed_in_wgsl_layout() {+ let f = own_struct(SRC, &[]).unwrap().unwrap();+ assert_eq!(f, vec![("quantize_steps".into(), "u32".into()), ("tint".into(), "vec3<f32>".into())]);+ let with = own_struct(SRC, &[ShaderDefVal::Bool("SIXTEEN_BYTE_ALIGNMENT".into(), true)]).unwrap().unwrap();+ assert_eq!(with.len(), 3);+ let s = pack(&f, &[("quantize_steps".into(), Vec4::new(3.0, 0.0, 0.0, 0.0)), ("tint".into(), Vec4::new(0.5, 0.25, 1.0, 0.0))]).unwrap();+ // a u32 3 at offset 0, the vec3 aligned to 16 bytes: the next slot+ assert_eq!(s[0].x.to_bits(), 3);+ assert_eq!(s[1].truncate(), bevy::prelude::Vec3::new(0.5, 0.25, 1.0));+ assert!(own_struct("fn lit() {}", &[]).is_none());+ assert!(pack(&f, &[("quantize_steps".into(), Vec4::ZERO)]).unwrap_err().contains("tint"));+ assert!(pack(&f[..1], &[("quantize_steps".into(), Vec4::ZERO), ("tint".into(), Vec4::ZERO)]).unwrap_err().contains("isn't a field"));+ }+}diff --git a/systems/shader/src/lib.rs b/systems/shader/src/lib.rsindex 4e53021f..3569f12a 100644--- a/systems/shader/src/lib.rs+++ b/systems/shader/src/lib.rs@@ -26,6 +26,8 @@ use std::hash::{Hash, Hasher};use raea_sys_material::shader_material::{defs, ident, uniform, Uniform, SLOTS, TEXTURES};+mod layout;+/// The fragment shader every ShaderExt pipeline starts from, swapped in `specialize` for the material's own. It is a/// whole lit surface by itself (no hooks), so a material whose module is missing still draws as standard.const PLACEHOLDER: Handle<Shader> = uuid_handle!("2f6b1c4e-8d3a-4e7f-b9a2-6c1d5e8f0a73");@@ -194,10 +196,12 @@ pub struct Inputs {impl Inputs {pub fn read(world: &mut World, o: &serde_json::Map<String, Value>, what: &str, image: &mut impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>) -> Result<Inputs, String> {- let src = match (o.get("wgsl").and_then(Value::as_str), o.get("wesl").and_then(Value::as_str)) {- (Some(_), Some(_)) => return Err(format!("{what} takes wgsl or wesl, not both")),- (Some(s), None) | (None, Some(s)) => s.to_string(),- (None, None) => return Err(format!("{what} needs wesl or wgsl: its source")),+ let src = match (o.get("wgsl").and_then(Value::as_str), o.get("wesl").and_then(Value::as_str), o.get("fragment").and_then(Value::as_str)) {+ (Some(s), None, None) | (None, Some(s), None) => s.to_string(),+ // an asset path, found by the SDK (asset.load), as Bevy's MaterialExtension::fragment_shader names one+ (None, None, Some(p)) => std::fs::read_to_string(p).map_err(|e| format!("{what}: its fragment {p}: {e}"))?,+ (None, None, None) => return Err(format!("{what} needs wesl, wgsl or a fragment path: its source")),+ _ => return Err(format!("{what} takes one of wesl, wgsl and fragment")),};let mut uniforms = vec![];if let Some(u) = o.get("uniforms") {@@ -275,9 +279,20 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Vareturn Err("a surface shader defines fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>), fn lit(in: VertexOutput, pbr: PbrInput, color: vec4<f32>) -> vec4<f32>, or its own @fragment".into());}let (names, tnames) = ins.names();- let id = register(world, module(&ins.src, &names, &tnames, ins.array.as_ref().map(|a| a.0.as_str())), &ins.defs, "raea surface shader", "raea_sys_shader");+ // its own @binding(100) struct: the source as written, the uniforms in that struct's layout (layout.rs, FC2b)+ // and a file (`fragment`) always as written, as Bevy's fragment_shader() names one: its imports first, its own+ // bindings or none (a uniform it doesn't declare is refused)+ let file = o.contains_key("fragment");+ let (src, slots) = match layout::own_struct(&ins.src, &ins.defs).or_else(|| file.then(|| Ok(vec![]))) {+ Some(fields) => {+ let vals: Vec<(String, Vec4)> = ins.uniforms.iter().map(|u| (u.name.clone(), u.value)).collect();+ (ins.src.clone(), layout::pack(&fields?, &vals)?)+ }+ None => (module(&ins.src, &names, &tnames, ins.array.as_ref().map(|a| a.0.as_str())), ins.slots()),+ };+ let id = register(world, src, &ins.defs, "raea surface shader", "raea_sys_shader");let mut t = ins.textures.iter().map(|x| Some(x.1.clone()));- Ok(ShaderExt { slots: ins.slots(), tex0: t.next().flatten(), tex1: t.next().flatten(), tex2: t.next().flatten(), tex3: t.next().flatten(), arr: ins.array.map(|a| a.1), shader: id })+ Ok(ShaderExt { slots, tex0: t.next().flatten(), tex1: t.next().flatten(), tex2: t.next().flatten(), tex3: t.next().flatten(), arr: ins.array.map(|a| a.1), shader: id })}/// A shaded part: the standard material the rows animate (sync_meshes writes it), copied onto the shaded one's basediff --git a/systems/sprite/src/lib.rs b/systems/sprite/src/lib.rsindex 13b63504..5386e68e 100644--- a/systems/sprite/src/lib.rs+++ b/systems/sprite/src/lib.rs@@ -50,11 +50,29 @@ fn place_of(v: &BTreeMap<String, V>) -> Transform {.with_scale(Vec3::new(num(v, "scale_x", 1.0), num(v, "scale_y", 1.0), 1.0))}+/// A sprite's size in px: both given, or one and the other by the cell's shape (`aspect`, height over width), or none.+fn size_of(v: &BTreeMap<String, V>, aspect: f32) -> Option<Vec2> {+ match (v.get("w").map(|x| x.num() as f32), v.get("h").map(|x| x.num() as f32)) {+ (Some(w), Some(h)) => Some(Vec2::new(w, h)),+ (Some(w), None) => Some(Vec2::new(w, w * aspect)),+ (None, Some(h)) => Some(Vec2::new(h / aspect, h)),+ (None, None) => None,+ }+}+/// The sheet cell a row shows, wrapping.fn cell(v: &BTreeMap<String, V>, cells: u32) -> usize {(num(v, "sheet_frame", 0.0).max(0.0) as u32 % cells.max(1)) as usize}+/// A sprite's picture as Bevy's AssetServer loads a PNG for one: straight alpha (Bevy's sprite shader blends it so),+/// one mip level, Bevy's default sampler. Not a panel's premultiplied mip chain: a tiled sprite drawn at half size+/// sampled the half-size level and showed seams at its tiles' edges (2d/sprite_tile).+pub fn sprite_image(w: u32, h: u32, rgba: Vec<u8>) -> Image {+ let size = bevy::render::render_resource::Extent3d { width: w, height: h, depth_or_array_layers: 1 };+ Image::new(size, bevy::render::render_resource::TextureDimension::D2, rgba, bevy::render::render_resource::TextureFormat::Rgba8UnormSrgb, bevy::asset::RenderAssetUsages::default())+}+/// A sprite's entity from its row and its picture (`size` in px).pub fn spawn_sprite(world: &mut World, e: Entity, t: &Tup, image: Handle<Image>, size: UVec2) {let v = &t.vals;@@ -69,18 +87,15 @@ pub fn spawn_sprite(world: &mut World, e: Entity, t: &Tup, image: Handle<Image>,let layout = world.resource_mut::<Assets<TextureAtlasLayout>>().add(TextureAtlasLayout::from_grid(UVec2::new(cw, ch), cols, rows, None, None));TextureAtlas { layout, index: cell(v, cols * rows) }});- // one size given, the other follows the cell's shape- let aspect = ch as f32 / cw as f32;- let custom_size = match (v.get("w").map(|x| x.num() as f32), v.get("h").map(|x| x.num() as f32)) {- (Some(w), Some(h)) => Some(Vec2::new(w, h)),- (Some(w), None) => Some(Vec2::new(w, w * aspect)),- (None, Some(h)) => Some(Vec2::new(h / aspect, h)),- (None, None) => None,- };+ let custom_size = size_of(v, ch as f32 / cw as f32);+ // Bevy's SpriteImageMode::Tiled: the picture repeats across the sprite's size, every stretch_value x its own+ let (tile_x, tile_y) = (num(v, "tile_x", 0.0) > 0.5, num(v, "tile_y", 0.0) > 0.5);+ let image_mode = if tile_x || tile_y { SpriteImageMode::Tiled { tile_x, tile_y, stretch_value: num(v, "tile_stretch", 1.0) } } else { default() };let sprite = Sprite {image,texture_atlas,custom_size,+ image_mode,color: color_of(v),flip_x: num(v, "flip_x", 0.0) > 0.5,flip_y: num(v, "flip_y", 0.0) > 0.5,@@ -140,6 +155,11 @@ pub fn sync_2d(frame: Res<FrameRows>, mut mats: ResMut<Assets<ColorMaterial>>, mif s.color != c {s.color = c;}+ // a keyed size (the shape held from what it was spawned at)+ let size = size_of(v, s.custom_size.map_or(1.0, |c| c.y / c.x.max(1e-6)));+ if size.is_some() && s.custom_size != size {+ s.custom_size = size;+ }let cells = (num(v, "sheet_cols", 1.0).max(1.0) * num(v, "sheet_rows", 1.0).max(1.0)) as u32;let at = cell(v, cells);if let Some(a) = s.texture_atlas.as_mut().filter(|a| a.index != at) {diff --git a/systems/three-shader/Cargo.toml b/systems/three-shader/Cargo.tomlnew file mode 100644index 00000000..4a9ed727--- /dev/null+++ b/systems/three-shader/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-sys-three-shader"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "three.js's shaders drawn by Bevy (docs/r3f.feature R3F11): a ShaderMaterial's GLSL translated by naga and a node material's WGSL (three's own TSL builder), each run with three's built-ins as a Material of its own"++[dependencies]+raea-sys-sampler = { path = "../sampler" }+# a picture made in code (a data: URL), decoded as a material's map is+raea-sys-material = { path = "../material" }+image = { version = "0.25", default-features = false }+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render"] }+# wgsl-in too: naga 30.0.1's glsl-in calls the interpolator module only spv-in or wgsl-in compiles (natively Bevy turns+# wgsl-in on; raea-web had nothing that did)+naga = { version = "=30.0.1", features = ["glsl-in", "wgsl-in", "wgsl-out"] }+serde_json = "1"diff --git a/systems/three-shader/src/glsl.rs b/systems/three-shader/src/glsl.rsnew file mode 100644index 00000000..e5e4777d--- /dev/null+++ b/systems/three-shader/src/glsl.rs@@ -0,0 +1,398 @@+//! A three.js ShaderMaterial's GLSL as a three shader's WGSL (docs/r3f.feature R3F11), by naga's GLSL frontend.+//!+//! three hands its shaders GLSL ES (1.0 or 3.0) with its own built-ins declared in front: the matrices, the camera,+//! `position`, `normal`, `uv`. Here every global a stage declares (a uniform, an attribute, a varying, an output) and+//! every built-in it writes (`gl_Position`, `gl_FragColor`, `gl_FragCoord`, ...) becomes a plain global of the module,+//! so naga's module has no inputs or outputs of its own: `main` is a function like any other. The wrapper module.rs's+//! contract asks for (`three_vertex`, `three_fragment`) sets those globals from the mesh, the uniforms and the varyings,+//! calls `main`, and reads back what it wrote. Samplers are a texture and a sampler bound where the material binds its+//! textures, the name a macro for `sampler2D(texture, sampler)`.+//!+//! The includes (`#include <common>`) are expanded by the SDK from three's ShaderChunk before the source gets here, and+//! a material's `defines` come as `#define` lines in front.++use crate::module::Ty;+use std::collections::BTreeMap;+pub use crate::scan::{scan, Scanned, Var};++/// three's built-in uniforms: what the vertex stage of a ShaderMaterial is given, and the fragment's+const VERTEX_BUILTINS: [(&str, &str); 7] = [+ ("modelMatrix", "mat4"),+ ("modelViewMatrix", "mat4"),+ ("projectionMatrix", "mat4"),+ ("viewMatrix", "mat4"),+ ("normalMatrix", "mat3"),+ ("cameraPosition", "vec3"),+ ("isOrthographic", "bool"),+];+const FRAGMENT_BUILTINS: [&str; 3] = ["viewMatrix", "cameraPosition", "isOrthographic"];+/// attributes the mesh gives at fixed places (module.rs's vertex_entry); any other is one of its own (a0..a3)+const MESH_ATTRIBUTES: [&str; 4] = ["position", "normal", "uv", "color"];++/// the built-ins GLSL writes or reads, each a global here: (GLSL name, global, type)+const GL: [(&str, &str, &str); 9] = [+ ("gl_Position", "rg_position", "vec4"),+ ("gl_PointSize", "rg_pointsize", "float"),+ ("gl_FragColor", "rg_frag", "vec4"),+ ("gl_FragCoord", "rg_fragcoord", "vec4"),+ ("gl_FrontFacing", "rg_front", "bool"),+ ("gl_PointCoord", "rg_pointcoord", "vec2"),+ ("gl_VertexID", "rg_vertexid", "int"),+ ("gl_InstanceID", "rg_instanceid", "int"),+ ("gl_FragDepth", "rg_fragdepth", "float"),+];++/// What a ShaderMaterial gives: its two stages, whether it's a RawShaderMaterial (which declares three's built-ins+/// itself), its `vertexColors`.+pub struct Source<'a> {+ pub vertex: &'a str,+ pub fragment: &'a str,+ pub raw: bool,+ pub vertex_colors: bool,+ /// it draws three.js Points: each point a quad whose corners come as `uv` (0..1), sized by gl_PointSize+ pub points: bool,+}++/// Both stages translated: each the WGSL that goes after module.rs's prelude, the uniforms they declare (laid out by+/// the caller), the samplers (bound in this order) and the mesh's own attributes (a0.. in this order: name, floats).+#[derive(Debug)]+pub struct Translated {+ pub vertex: String,+ pub fragment: String,+ pub uniforms: Vec<(String, Ty, Option<u32>)>,+ pub samplers: Vec<String>,+ pub attributes: Vec<(String, usize)>,+}++fn wgsl_ty(glsl: &str, what: &str) -> Result<Ty, String> {+ Ty::parse(glsl).ok_or_else(|| format!("{what}: its type {glsl} isn't a number, vector or matrix"))+}++/// The GLSL naga reads for one stage: the globals as plain declarations, the samplers bound, the built-ins renamed.+fn stage_glsl(s: &Scanned, vertex: bool, src: &Source, samplers: &[String], extra: &[Var]) -> Result<String, String> {+ // the samplers first: the macros below rename `texture2D`, which is also the GLSL 450 texture type's name+ let mut g = String::from("#version 450\n");+ for v in &s.samplers {+ if v.glsl != "sampler2D" {+ return Err(format!("sampler {}: a {} isn't supported yet (sampler2D is)", v.name, v.glsl));+ }+ let k = samplers.iter().position(|x| *x == v.name).ok_or_else(|| format!("sampler {}: not among the material's textures", v.name))?;+ g += &format!("layout(set = 0, binding = {}) uniform texture2D rgt{k}x;\nlayout(set = 0, binding = {}) uniform sampler rgs{k}x;\n#define {} sampler2D(rgt{k}x, rgs{k}x)\n", 1 + k * 2, 2 + k * 2, v.name);+ }+ g += "#define highp\n#define mediump\n#define lowp\n";+ for (gl, ours, _) in GL {+ g += &format!("#define {gl} {ours}\n");+ }+ g += "#define gl_FragData rg_fragdata\n";+ if vertex {+ g += "#define texture2D(s, c) textureLod(s, c, 0.0)\n#define texture(s, c) textureLod(s, c, 0.0)\n#define textureCube(s, c) textureLod(s, c, 0.0)\n";+ } else {+ g += "#define texture2D texture\n#define textureCube texture\n#define texture2DLodEXT textureLod\n#define textureCubeLodEXT textureLod\n#define texture2DProj textureProj\n#define gl_FragDepthEXT gl_FragDepth\n";+ }+ if src.vertex_colors {+ g += "#define USE_COLOR\n";+ }+ for (gl, ours, ty) in GL {+ let _ = gl;+ g += &format!("{ty} {ours};\n");+ }+ g += "vec4 rg_fragdata[1];\n";+ let declared = |n: &str| s.uniforms.iter().chain(&s.attributes).chain(&s.varyings).chain(&s.outputs).chain(extra).any(|v| v.name == n) || s.samplers.iter().any(|v| v.name == n);+ if !src.raw {+ for (n, ty) in VERTEX_BUILTINS {+ if (vertex || FRAGMENT_BUILTINS.contains(&n)) && !declared(n) {+ g += &format!("{ty} {n};\n");+ }+ }+ if vertex {+ for (n, ty) in [("position", "vec3"), ("normal", "vec3"), ("uv", "vec2")] {+ if !declared(n) {+ g += &format!("{ty} {n};\n");+ }+ }+ if src.vertex_colors && !declared("color") {+ g += "vec3 color;\n";+ }+ }+ }+ for v in s.uniforms.iter().chain(&s.attributes).chain(&s.varyings).chain(&s.outputs).chain(extra) {+ let arr = v.array.map(|n| format!("[{n}]")).unwrap_or_default();+ g += &format!("{} {}{arr};\n", v.glsl, v.name);+ }+ g += &s.body;+ Ok(g)+}++/// naga's module for one stage's GLSL, `main` an ordinary function `rg_main`, every private global renamed `rg{n}x`;+/// returns its WGSL and the renames (GLSL name -> WGSL name).+fn naga_wgsl(glsl: &str, vertex: bool) -> Result<(String, BTreeMap<String, String>), String> {+ let stage = if vertex { naga::ShaderStage::Vertex } else { naga::ShaderStage::Fragment };+ let mut m = naga::front::glsl::Frontend::default().parse(&naga::front::glsl::Options::from(stage), glsl).map_err(|e| {+ let what = if vertex { "vertex" } else { "fragment" };+ format!("the {what} shader: {}", e.emit_to_string(glsl).lines().take(12).collect::<Vec<_>>().join("\n"))+ })?;+ let mut names = BTreeMap::new();+ for (i, (_, g)) in m.global_variables.iter_mut().enumerate() {+ if g.space == naga::AddressSpace::Private {+ if let Some(n) = &g.name {+ let ours = format!("rg{i}x");+ names.insert(n.clone(), ours.clone());+ g.name = Some(ours);+ }+ }+ }+ m.entry_points.clear();+ for (_, f) in m.functions.iter_mut() {+ if f.name.as_deref() == Some("main") {+ f.name = Some("rg_main".into());+ }+ }+ let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all())+ .validate(&m)+ .map_err(|e| format!("the {} shader: {}", if vertex { "vertex" } else { "fragment" }, e.emit_to_string(glsl).lines().take(12).collect::<Vec<_>>().join("\n")))?;+ let mut w = naga::back::wgsl::write_string(&m, &info, naga::back::wgsl::WriterFlags::empty()).map_err(|e| format!("writing WGSL: {e}"))?;+ // the textures go in the material's bind group (module.rs binds slots at 0 and textures from 1)+ w = w.replace("@group(0) @binding(", "@group(constants::MATERIAL_BIND_GROUP) @binding(");+ Ok((w, names))+}++/// The struct both stages read their varyings through: clip position, then each varying the vertex stage writes, in+/// its order (location i).+fn varyings_struct(vs: &[Var], points: bool) -> Result<String, String> {+ let mut m = String::from("struct ThreeVaryings {\n @builtin(position) clip: vec4<f32>,\n");+ if points {+ m += &format!(" @location({}) corner: vec2<f32>,\n", vs.len());+ }+ for (i, v) in vs.iter().enumerate() {+ let ty = wgsl_ty(&v.glsl, &format!("varying {}", v.name))?;+ if v.array.is_some() {+ return Err(format!("varying {}: an array varying isn't supported yet", v.name));+ }+ let flat = matches!(ty, Ty::I32 | Ty::U32 | Ty::IVec(_) | Ty::UVec(_)) || v.flat;+ if matches!(ty, Ty::Bool | Ty::BVec(_) | Ty::Mat(_)) {+ return Err(format!("varying {}: a {} can't be a varying here", v.name, v.glsl));+ }+ m += &format!(" @location({i}){} v{i}: {},\n", if flat { " @interpolate(flat)" } else { "" }, ty.wgsl());+ }+ Ok(m + "};\n")+}++/// `NAME = value;` for each uniform a stage declares (an array element by element)+fn set_uniforms(uniforms: &[Var], names: &BTreeMap<String, String>) -> String {+ let mut m = String::new();+ for u in uniforms {+ let Some(g) = names.get(&u.name) else { continue };+ match u.array {+ None => m += &format!(" {g} = u_{}();\n", u.name),+ Some(n) => m += &format!(" for (var i = 0u; i < {n}u; i++) {{ {g}[i] = u_{}(i); }}\n", u.name),+ }+ }+ m+}++/// three's built-in uniforms, set where the stage has them+fn set_builtins(names: &BTreeMap<String, String>, model: bool) -> String {+ let mut m = String::new();+ let set = |n: &str, v: &str, m: &mut String| {+ if let Some(g) = names.get(n) {+ *m += &format!(" {g} = {v};\n");+ }+ };+ if model {+ set("modelMatrix", "model", &mut m);+ set("modelViewMatrix", "three_view() * model", &mut m);+ set("normalMatrix", "three_normal_matrix(three_view() * model)", &mut m);+ }+ set("viewMatrix", "three_view()", &mut m);+ set("projectionMatrix", "three_projection()", &mut m);+ set("cameraPosition", "three_camera_position()", &mut m);+ set("isOrthographic", "three_projection()[3][3] == 1.0", &mut m);+ m+}++const NORMAL_MATRIX: &str = "fn three_normal_matrix(mv: mat4x4<f32>) -> mat3x3<f32> {\n let a = mat3x3<f32>(mv[0].xyz, mv[1].xyz, mv[2].xyz);\n let c0 = cross(a[1], a[2]);\n let c1 = cross(a[2], a[0]);\n let c2 = cross(a[0], a[1]);\n return mat3x3<f32>(c0, c1, c2) * (1.0 / dot(a[0], c0));\n}\n";++/// A ShaderMaterial's two stages as a three shader's (module.rs's contract).+pub fn translate(src: &Source, textures: &[String]) -> Result<Translated, String> {+ let vs = scan(src.vertex, true)?;+ let fs = scan(src.fragment, false)?;+ // the samplers bound: the material's textures that either stage samples, in the material's order+ let samplers: Vec<String> = textures.iter().filter(|t| vs.samplers.iter().chain(&fs.samplers).any(|s| s.name == **t)).cloned().collect();+ for s in vs.samplers.iter().chain(&fs.samplers) {+ if !samplers.contains(&s.name) {+ return Err(format!("sampler {}: the material gives no texture for it", s.name));+ }+ }+ // a varying the fragment stage reads that the vertex stage doesn't write is declared there too (zero, as three+ // would refuse to link it)+ let missing: Vec<Var> = fs.varyings.iter().filter(|v| !vs.varyings.iter().any(|x| x.name == v.name)).cloned().collect();+ let mut vary = vs.varyings.clone();+ vary.extend(missing.iter().cloned());+ let (vw, vn) = naga_wgsl(&stage_glsl(&vs, true, src, &samplers, &missing)?, true)?;+ let (fw, fn_) = naga_wgsl(&stage_glsl(&fs, false, src, &samplers, &[])?, false)?;+ // the uniforms both stages declare, once each (the same name is the same uniform in three)+ let mut uniforms: Vec<(String, Ty, Option<u32>)> = Vec::new();+ let builtin = |u: &&Var| VERTEX_BUILTINS.iter().any(|(n, _)| *n == u.name);+ for u in vs.uniforms.iter().chain(&fs.uniforms) {+ if builtin(&u) || uniforms.iter().any(|x| x.0 == u.name) {+ continue;+ }+ uniforms.push((u.name.clone(), wgsl_ty(&u.glsl, &format!("uniform {}", u.name))?, u.array));+ }+ let user_uniforms: Vec<Var> = vs.uniforms.iter().chain(&fs.uniforms).filter(|u| !builtin(u)).cloned().collect();+ // the mesh's attributes: the fixed four, and the rest each a vec4 slot of its own+ let mut attributes = Vec::new();+ let mut set_attr = String::new();+ for a in &vs.attributes {+ let ty = wgsl_ty(&a.glsl, &format!("attribute {}", a.name))?;+ let Some(g) = vn.get(&a.name) else { continue };+ let swz = ["", ".x", ".xy", ".xyz", ""][ty.floats().min(4)];+ let from = match MESH_ATTRIBUTES.iter().position(|n| *n == a.name) {+ Some(0) => "v.position".to_string(),+ Some(1) => "v.normal".to_string(),+ Some(2) => "v.uv".to_string(),+ Some(_) => format!("v.color{}", if ty.floats() == 3 { ".xyz" } else { swz }),+ None => {+ if attributes.len() == crate::module::ATTRIBUTES {+ return Err(format!("attribute {}: a mesh gives a shader at most {} attributes of its own", a.name, crate::module::ATTRIBUTES));+ }+ attributes.push((a.name.clone(), ty.floats()));+ format!("v.a{}{swz}", attributes.len() - 1)+ }+ };+ let cast = match ty {+ Ty::I32 => format!("i32({from})"),+ Ty::IVec(n) => format!("vec{n}<i32>({from})"),+ Ty::U32 => format!("u32({from})"),+ Ty::UVec(n) => format!("vec{n}<u32>({from})"),+ _ => from,+ };+ set_attr += &format!(" {g} = {cast};\n");+ }+ // three's own attributes for a ShaderMaterial (declared in its prefix, not the source)+ if !src.raw {+ for (n, from) in [("position", "v.position"), ("normal", "v.normal"), ("uv", "v.uv"), ("color", "v.color.xyz")] {+ if !vs.attributes.iter().any(|a| a.name == n) && !vs.uniforms.iter().any(|a| a.name == n) {+ if let Some(g) = vn.get(n) {+ set_attr += &format!(" {g} = {from};\n");+ }+ }+ }+ }+ let vstruct = varyings_struct(&vary, src.points)?;+ // vertex: built-ins, attributes, uniforms, main, the varyings out+ let mut v = String::new();+ v += &vw;+ v += "\n";+ v += &vstruct;+ v += NORMAL_MATRIX;+ v += "\nfn three_vertex(v: ThreeVertex) -> ThreeVaryings {\n let model = three_model(v.instance);\n";+ v += &set_builtins(&vn, true);+ v += &set_attr;+ v += &set_uniforms(&user_uniforms, &vn);+ if let Some(g) = vn.get("rg_vertexid") {+ v += &format!(" {g} = i32(v.index);\n");+ }+ if let Some(g) = vn.get("rg_pointsize") {+ v += &format!(" {g} = 1.0;\n");+ }+ v += " rg_main();\n var o: ThreeVaryings;\n";+ v += &format!(" o.clip = {};\n", vn.get("rg_position").cloned().unwrap_or_else(|| "vec4<f32>(0.0)".into()));+ if src.points {+ // the point's quad: its corner moved gl_PointSize pixels across the target, in clip space+ let size = vn.get("rg_pointsize").cloned().unwrap_or_else(|| "1.0".into());+ v += &format!(" let corner = v.uv * 2.0 - 1.0;\n o.clip = vec4<f32>(o.clip.xy + corner * {size} / three_viewport().zw * o.clip.w, o.clip.zw);\n o.corner = corner;\n");+ }+ for (i, x) in vary.iter().enumerate() {+ if let Some(g) = vn.get(&x.name) {+ v += &format!(" o.v{i} = {g};\n");+ }+ }+ v += " return o;\n}\n";+ // fragment: built-ins, uniforms, varyings in, gl_FragCoord and gl_FrontFacing, main, its colour out+ let mut f = String::new();+ f += &fw;+ f += "\n";+ f += &vstruct;+ f += NORMAL_MATRIX;+ f += "\nfn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> {\n";+ f += &set_builtins(&fn_, false);+ f += &set_uniforms(&user_uniforms, &fn_);+ for (i, x) in vary.iter().enumerate() {+ if let Some(g) = fn_.get(&x.name) {+ f += &format!(" {g} = in.v{i};\n");+ }+ }+ if let Some(g) = fn_.get("rg_fragcoord") {+ // GLSL counts y up from the bottom of the target, WGSL down from its top+ f += &format!(" {g} = vec4<f32>(in.clip.x, three_viewport().w - in.clip.y, in.clip.z, in.clip.w);\n");+ }+ if let (Some(g), true) = (fn_.get("rg_pointcoord"), src.points) {+ // gl_PointCoord counts down from the sprite's top+ f += &format!(" {g} = vec2<f32>(in.corner.x * 0.5 + 0.5, 0.5 - in.corner.y * 0.5);\n");+ }+ if let Some(g) = fn_.get("rg_front") {+ f += &format!(" {g} = front;\n");+ }+ f += " rg_main();\n";+ let colour = match fs.outputs.first() {+ Some(o) => fn_.get(&o.name).cloned(),+ None if src.fragment.contains("gl_FragData") => fn_.get("rg_fragdata").map(|g| format!("{g}[0]")),+ None => fn_.get("rg_frag").cloned(),+ };+ f += &format!(" return {};\n}}\n", colour.unwrap_or_else(|| "vec4<f32>(0.0, 0.0, 0.0, 1.0)".into()));+ Ok(Translated { vertex: v, fragment: f, uniforms, samplers, attributes })+}++#[cfg(test)]+mod tests {+ use super::*;++ const VERT: &str = "precision highp float;\n// three's typical wave\nuniform float uTime;\nvarying vec2 vUv;\nattribute float aRandom;\nvoid main() {\n vUv = uv;\n vec3 p = position;\n p.z += sin(p.x * 4.0 + uTime) * 0.1 * aRandom;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);\n}\n";+ const FRAG: &str = "uniform vec3 uColor;\nuniform sampler2D map;\nvarying vec2 vUv;\nvoid main() {\n vec4 t = texture2D(map, vUv);\n if (t.a < 0.1) discard;\n gl_FragColor = vec4(uColor * t.rgb, 1.0);\n}\n";++ #[test]+ fn declarations_come_out_of_the_source() {+ let s = scan(VERT, true).unwrap();+ assert_eq!(s.uniforms, vec![Var { name: "uTime".into(), glsl: "float".into(), array: None, flat: false }]);+ assert_eq!(s.varyings[0].name, "vUv");+ assert_eq!(s.attributes[0].name, "aRandom");+ assert!(!s.body.contains("uniform") && !s.body.contains("precision"));+ assert!(s.body.contains("void main()"));+ let f = scan("#define N 3\nuniform vec2 pts[N], one;\nlayout(location = 0) out highp vec4 outColor;\nvoid main(){ outColor = vec4(pts[0], one); }", false).unwrap();+ assert_eq!(f.uniforms.iter().map(|u| (u.name.as_str(), u.array)).collect::<Vec<_>>(), vec![("pts", Some(3)), ("one", None)]);+ assert_eq!(f.outputs[0].name, "outColor");+ assert!(f.body.contains("#define N 3"));+ }++ #[test]+ fn a_shader_material_translates_to_the_contract() {+ let t = translate(&Source { vertex: VERT, fragment: FRAG, raw: false, vertex_colors: false, points: false }, &["map".into()]).unwrap();+ assert_eq!(t.uniforms.iter().map(|u| u.0.as_str()).collect::<Vec<_>>(), vec!["uTime", "uColor"]);+ assert_eq!(t.samplers, vec!["map".to_string()]);+ assert_eq!(t.attributes, vec![("aRandom".to_string(), 1)]);+ assert!(t.vertex.contains("fn three_vertex(v: ThreeVertex) -> ThreeVaryings"), "{}", t.vertex);+ assert!(t.vertex.contains("= u_uTime();"));+ assert!(t.vertex.contains("= v.a0.x;"));+ assert!(t.vertex.contains("textureSampleLevel") || !t.vertex.contains("textureSample("));+ assert!(t.fragment.contains("fn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32>"), "{}", t.fragment);+ assert!(t.fragment.contains("@group(constants::MATERIAL_BIND_GROUP) @binding(1)"));+ assert!(t.fragment.contains("discard"));+ }++ #[test]+ fn a_raw_shader_material_declares_its_own_built_ins() {+ let vert = "#version 300 es\nprecision highp float;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nin vec3 position;\nin vec4 color;\nout vec4 vColor;\nvoid main(){ vColor = color; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }";+ let frag = "#version 300 es\nprecision highp float;\nin vec4 vColor;\nout vec4 fragColor;\nvoid main(){ fragColor = vColor; }";+ let t = translate(&Source { vertex: vert, fragment: frag, raw: true, vertex_colors: false, points: false }, &[]).unwrap();+ assert!(t.uniforms.is_empty());+ assert!(t.attributes.is_empty());+ assert!(t.vertex.contains("= v.color;"), "{}", t.vertex);+ }++ #[test]+ fn errors_name_the_stage() {+ let e = translate(&Source { vertex: VERT, fragment: "void main(){ gl_FragColor = nope; }", raw: false, vertex_colors: false, points: false }, &["map".into()]).unwrap_err();+ assert!(e.contains("fragment"), "{e}");+ }+}diff --git a/systems/three-shader/src/lib.rs b/systems/three-shader/src/lib.rsnew file mode 100644index 00000000..c1742892--- /dev/null+++ b/systems/three-shader/src/lib.rs@@ -0,0 +1,372 @@+//! three.js's shaders drawn by Bevy (docs/r3f.feature R3F11): a ShaderMaterial's or RawShaderMaterial's GLSL, which+//! naga translates (glsl.rs), and a node material's WGSL, which three's own TSL builder writes in the SDK. Either is+//! a vertex and a fragment source meeting module.rs's contract; this crate's Material runs them with three's built-ins+//! (the model, view and projection matrices, the camera, the mesh's attributes and its own), the material's uniforms+//! in 62 vec4 slots (changed frame by frame by `three:uniforms` component rows, `patch`), up to four textures, and+//! three's time.+//!+//! What three puts on screen is what shows: a ShaderMaterial's colour is the value its canvas gets (`display`), so the+//! fragment entry takes it back through the camera's tone mapping (tone.wesl); a node material's is scene-referred+//! (`linear`) and is left for Bevy's to map, as three's renderer maps it.+//!+//! Only the main pass runs a three shader: its prepass is off (a vertex shader may move the mesh where the standard+//! prepass wouldn't), and its shadow is the mesh's own shape, as three draws a ShaderMaterial's shadow with its depth+//! material.++use bevy::prelude::*;+use bevy::mesh::{MeshVertexAttribute, MeshVertexBufferLayoutRef, VertexFormat};+use bevy::pbr::{Material, MaterialPipeline, MaterialPipelineKey, MaterialPlugin};+use bevy::render::render_resource::{AsBindGroup, CompareFunction, Face, RenderPipelineDescriptor, SpecializedMeshPipelineError};+use bevy::shader::{Shader, ShaderRef};+use serde_json::Value;+use std::hash::{Hash, Hasher};++pub mod glsl;+pub mod scan;+pub mod linear;+pub mod module;+mod row;+pub use row::{fitted, of_row};++use module::{Ty, Uniform, ATTRIBUTES, DISPLAY_SLOT, SLOTS, TEXTURES, TIME_SLOT};++/// A mesh's own attributes for a three shader (a0..a3), four floats each.+pub const ATTRIBUTE: [MeshVertexAttribute; ATTRIBUTES] = [+ MeshVertexAttribute::new("RaeaThreeA0", 0x7e3a_5100, VertexFormat::Float32x4),+ MeshVertexAttribute::new("RaeaThreeA1", 0x7e3a_5101, VertexFormat::Float32x4),+ MeshVertexAttribute::new("RaeaThreeA2", 0x7e3a_5102, VertexFormat::Float32x4),+ MeshVertexAttribute::new("RaeaThreeA3", 0x7e3a_5103, VertexFormat::Float32x4),+];++pub fn install(app: &mut App) {+ app.add_plugins(MaterialPlugin::<ThreeShader>::default());+ app.add_systems(PostUpdate, follow_tonemapping);+ app.add_systems(PreUpdate, linear::sync);+}++#[derive(Asset, TypePath, AsBindGroup, Clone, Debug)]+#[bind_group_data(ThreeKey)]+pub struct ThreeShader {+ #[uniform(0)]+ slots: [Vec4; SLOTS],+ #[texture(1)]+ #[sampler(2)]+ tex0: Option<Handle<Image>>,+ #[texture(3)]+ #[sampler(4)]+ tex1: Option<Handle<Image>>,+ #[texture(5)]+ #[sampler(6)]+ tex2: Option<Handle<Image>>,+ #[texture(7)]+ #[sampler(8)]+ tex3: Option<Handle<Image>>,+ /// the camera's tone mapping LUT, for a `display` colour taken back through it (tone.wesl)+ #[texture(9, dimension = "3d")]+ #[sampler(10)]+ lut: Option<Handle<Image>>,+ vertex: u128,+ fragment: u128,+ attributes: u8,+ alpha: AlphaMode,+ cull: Option<Face>,+ depth_write: bool,+ depth_test: bool,+ /// whether its colour is what three's canvas shows (taken back through Bevy's tone mapping) or scene light+ display: bool,+ layout: Vec<Uniform>,+}++/// What picks a three shader's pipeline.+#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub struct ThreeKey {+ vertex: u128,+ fragment: u128,+ attributes: u8,+ cull: Option<Face>,+ depth_write: bool,+ depth_test: bool,+}++impl From<&ThreeShader> for ThreeKey {+ fn from(m: &ThreeShader) -> Self {+ ThreeKey { vertex: m.vertex, fragment: m.fragment, attributes: m.attributes, cull: m.cull, depth_write: m.depth_write, depth_test: m.depth_test }+ }+}++fn handle(id: u128) -> Handle<Shader> {+ Handle::Uuid(bevy::asset::uuid::Uuid::from_u128(id), core::marker::PhantomData)+}++impl Material for ThreeShader {+ fn vertex_shader() -> ShaderRef {+ ShaderRef::Default+ }+ fn fragment_shader() -> ShaderRef {+ ShaderRef::Default+ }+ fn alpha_mode(&self) -> AlphaMode {+ self.alpha+ }+ fn enable_prepass() -> bool {+ false+ }+ fn specialize(_pipeline: &MaterialPipeline, descriptor: &mut RenderPipelineDescriptor, layout: &MeshVertexBufferLayoutRef, key: MaterialPipelineKey<Self>) -> Result<(), SpecializedMeshPipelineError> {+ let k = key.bind_group_data;+ let mut attrs = vec![Mesh::ATTRIBUTE_POSITION.at_shader_location(0), Mesh::ATTRIBUTE_NORMAL.at_shader_location(1), Mesh::ATTRIBUTE_UV_0.at_shader_location(2), Mesh::ATTRIBUTE_COLOR.at_shader_location(3)];+ for (i, a) in ATTRIBUTE.iter().take(k.attributes as usize).enumerate() {+ attrs.push(a.at_shader_location(4 + i as u32));+ }+ descriptor.vertex.buffers = vec![layout.0.get_layout(&attrs)?];+ descriptor.vertex.shader = handle(k.vertex);+ if let Some(f) = descriptor.fragment.as_mut() {+ f.shader = handle(k.fragment);+ }+ descriptor.primitive.cull_mode = k.cull;+ if let Some(d) = descriptor.depth_stencil.as_mut() {+ d.depth_write_enabled = Some(k.depth_write);+ if !k.depth_test {+ d.depth_compare = Some(CompareFunction::Always);+ }+ }+ Ok(())+ }+}++/// `module` added to Assets<Shader> under the uuid of its hash (salted with `kind`); returns the uuid.+fn register(world: &mut World, module: String, kind: &str) -> u128 {+ let mut h = std::collections::hash_map::DefaultHasher::new();+ module.hash(&mut h);+ let hi = h.finish();+ kind.hash(&mut h);+ let id = ((hi as u128) << 64) | h.finish() as u128;+ let aid = AssetId::<Shader>::Uuid { uuid: bevy::asset::uuid::Uuid::from_u128(id) };+ let mut shaders = world.resource_mut::<Assets<Shader>>();+ if shaders.get(aid).is_none() {+ let _ = shaders.insert(aid, Shader::from_wesl(module, format!("embedded://raea_sys_three_shader/{kind}{id:032x}.wesl")));+ }+ id+}++/// The two modules of a material, from its stages' WGSL: the prelude in front of each, the entry point after.+pub fn modules(vertex: &str, fragment: &str, layout: &[Uniform], textures: Option<&[String]>, attributes: usize) -> (String, String) {+ let pre = module::prelude(layout, textures, attributes);+ (format!("{pre}{vertex}\n{}", module::vertex_entry(attributes)), format!("{pre}{fragment}\n{}", module::fragment_entry()))+}++/// A three shader's spec, as the SDK's ThreeShaderMaterial gives it:+/// glsl: {vertex, fragment, raw?, vertexColors?} a ShaderMaterial's (includes expanded, defines in front)+/// wgsl: {vertex, fragment, uniforms: [{name, type, array?}], attributes?: [name]} the contract's, written already+/// uniforms: {name: number | [numbers]} each one's value (a matrix column-major, an array's elements in turn)+/// textures: {name: picture | {src, colorSpace: "srgb" | "linear", sampler}} "linear": sampled raw, as three+/// samples a NoColorSpace texture+/// output: "display" | "linear" what its colour is (display for a ShaderMaterial, linear for TSL)+/// transparent, blending ("normal" | "additive" | "add" | "multiply" | "none"), side ("front" | "back" | "double"), depthWrite,+/// depthTest, alphaTest, time: [t, delta, frame]+/// Returns the material and the names of the mesh's own attributes it reads (a0.. in order).+pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>) -> Result<(ThreeShader, Vec<String>), String> {+ let o = v.as_object().ok_or_else(|| format!("a three shader is {{glsl | wgsl, uniforms, textures, ...}}, got {v}"))?;+ // the textures, in the order given+ let mut tex: Vec<(String, Handle<Image>)> = Vec::new();+ if let Some(t) = o.get("textures") {+ for (k, x) in t.as_object().ok_or("a three shader's textures are {name: picture}")? {+ if tex.len() == TEXTURES {+ return Err(format!("a three shader binds at most {TEXTURES} textures; {k} is one more"));+ }+ let who = format!("three shader texture {k}");+ // {src, colorSpace: "linear"}: three samples it raw (NoColorSpace), so it's bound as its raw numbers+ let raw = x.get("colorSpace").and_then(Value::as_str) == Some("linear");+ let h = if raw {+ let pic = x.get("src").cloned().unwrap_or(Value::Null);+ let src = image(world, &pic).map_err(|e| format!("texture {k}: {e}"))?;+ let h = linear::raw(world, src);+ if let Some(s) = x.get("sampler") {+ raea_sys_sampler::PendingSamplers::give(world, h.clone(), raea_sys_sampler::Sampling::of(s).map_err(|e| format!("texture {k}: {e}"))?, who);+ }+ h+ } else {+ raea_sys_sampler::texture(world, x, &who, &mut image).map_err(|e| format!("texture {k}: {e}"))?+ };+ tex.push((k.clone(), h));+ }+ }+ let names: Vec<String> = tex.iter().map(|t| t.0.clone()).collect();+ let (vsrc, fsrc, list, bound, attrs, own_textures) = if let Some(g) = o.get("glsl") {+ let s = |k: &str| g.get(k).and_then(Value::as_str).ok_or_else(|| format!("a three shader's glsl needs {k}"));+ let flag = |k: &str| g.get(k) == Some(&Value::Bool(true));+ let src = glsl::Source { vertex: s("vertex")?, fragment: s("fragment")?, raw: flag("raw"), vertex_colors: flag("vertexColors"), points: flag("points") };+ let t = glsl::translate(&src, &names)?;+ (t.vertex, t.fragment, t.uniforms, t.samplers, t.attributes.into_iter().map(|a| a.0).collect::<Vec<_>>(), false)+ } else if let Some(w) = o.get("wgsl") {+ let s = |k: &str| w.get(k).and_then(Value::as_str).map(str::to_string).ok_or_else(|| format!("a three shader's wgsl needs {k}"));+ let mut list = Vec::new();+ for u in w.get("uniforms").and_then(Value::as_array).into_iter().flatten() {+ let name = u.get("name").and_then(Value::as_str).ok_or("a wgsl uniform needs its name")?;+ let ty = u.get("type").and_then(Value::as_str).and_then(Ty::parse).ok_or_else(|| format!("uniform {name}: its type is f32, i32, u32, bool, a vecN or a matNxN"))?;+ list.push((name.to_string(), ty, u.get("array").and_then(Value::as_u64).map(|n| n as u32)));+ }+ let attrs: Vec<String> = w.get("attributes").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+ if attrs.len() > ATTRIBUTES {+ return Err(format!("a three shader reads at most {ATTRIBUTES} attributes of a mesh's own, got {}", attrs.len()));+ }+ (s("vertex")?, s("fragment")?, list, names.clone(), attrs, true)+ } else {+ return Err("a three shader gives glsl {vertex, fragment} or wgsl {vertex, fragment, uniforms}".into());+ };+ let layout = module::layout(&list)?;+ // three's textures with flipY count v from the picture's bottom; Bevy's images from their top+ let flip: Vec<String> = o.get("flipY").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).filter_map(|n| bound.iter().position(|b| b == n)).map(|k| if own_textures { format!("tex_{}", bound[k]) } else { format!("rgt{k}x") }).collect();+ let (vsrc, fsrc) = (module::flip_samples(&vsrc, &flip), module::flip_samples(&fsrc, &flip));+ let (vm, fm) = modules(&vsrc, &fsrc, &layout, own_textures.then_some(bound.as_slice()), attrs.len());+ let vertex = register(world, vm, "v");+ let fragment = register(world, fm, "f");+ let mut slots = [[0f32; 4]; SLOTS];+ if let Some(u) = o.get("uniforms").and_then(Value::as_object) {+ module::pack(&layout, u, &mut slots)?;+ }+ if let Some(t) = o.get("time").and_then(Value::as_array) {+ for (i, x) in t.iter().take(3).enumerate() {+ slots[TIME_SLOT][i] = x.as_f64().unwrap_or(0.0) as f32;+ }+ }+ let display = o.get("output").and_then(Value::as_str).unwrap_or("display") == "display";+ // tone.wesl reads which it is: a display colour is taken back through the camera's tone mapping, a linear one+ // mapped forward when the camera maps in its materials' shaders+ slots[DISPLAY_SLOT][1] = if display { 1.0 } else { 0.0 };+ // the textures bound in the order the shader binds them (bound), each found by name+ let by = |n: &str| tex.iter().find(|t| t.0 == n).map(|t| t.1.clone());+ let mut t = bound.iter().map(|n| by(n));+ let transparent = o.get("transparent").and_then(Value::as_bool).unwrap_or(false);+ let alpha = match (transparent, o.get("blending").and_then(Value::as_str).unwrap_or("normal")) {+ (_, "none") => AlphaMode::Opaque,+ (_, "additive" | "add") => AlphaMode::Add,+ (_, "multiply") => AlphaMode::Multiply,+ (true, _) => AlphaMode::Blend,+ (false, _) => match o.get("alphaTest").and_then(Value::as_f64).filter(|a| *a > 0.0) {+ Some(a) => AlphaMode::Mask(a as f32),+ None => AlphaMode::Opaque,+ },+ };+ let cull = match o.get("side").and_then(Value::as_str).unwrap_or("front") {+ "double" => None,+ "back" => Some(Face::Front),+ _ => Some(Face::Back),+ };+ let m = ThreeShader {+ slots: slots.map(Vec4::from_array),+ tex0: t.next().flatten(),+ tex1: t.next().flatten(),+ tex2: t.next().flatten(),+ tex3: t.next().flatten(),+ lut: None,+ vertex,+ fragment,+ attributes: attrs.len() as u8,+ alpha,+ cull,+ depth_write: o.get("depthWrite").and_then(Value::as_bool).unwrap_or(!transparent),+ depth_test: o.get("depthTest").and_then(Value::as_bool).unwrap_or(true),+ display,+ layout,+ };+ Ok((m, attrs))+}++/// A `three:uniforms` component row: the frame's uniform values ({uniforms: {name: value}, time: [t, delta, frame]})+/// onto the part's three shader.+pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {+ let Some(h) = world.get::<MeshMaterial3d<ThreeShader>>(e).map(|m| m.0.clone()) else { return Err("three:uniforms: the part has no three shader".into()) };+ let mut mats = world.resource_mut::<Assets<ThreeShader>>();+ let Some(mut m) = mats.get_mut(&h) else { return Err("three:uniforms: its material isn't loaded".into()) };+ let mut slots = m.slots.map(|s| s.to_array());+ if let Some(u) = v.get("uniforms").and_then(Value::as_object) {+ module::pack(&m.layout, u, &mut slots)?;+ }+ if let Some(t) = v.get("time").and_then(Value::as_array) {+ for (i, x) in t.iter().take(3).enumerate() {+ slots[TIME_SLOT][i] = x.as_f64().unwrap_or(0.0) as f32;+ }+ }+ m.slots = slots.map(Vec4::from_array);+ Ok(())+}++/// The mesh a three shader reads: a colour on every vertex (white where it has none), texture coordinates (zero where+/// none) and its own attributes (`attributes`, from a buffer mesh's JSON: {name: {size, values}}, per vertex), laid+/// out per triangle corner as buffer_tris lays a buffer mesh's positions.+pub fn fit_mesh(mesh: &mut Mesh, buffer: Option<&str>, own: &[String]) -> Result<(), String> {+ let n = mesh.count_vertices();+ if mesh.attribute(Mesh::ATTRIBUTE_COLOR).is_none() {+ mesh.insert_attribute(Mesh::ATTRIBUTE_COLOR, vec![[1f32; 4]; n]);+ }+ if mesh.attribute(Mesh::ATTRIBUTE_UV_0).is_none() {+ mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0f32; 2]; n]);+ }+ if mesh.attribute(Mesh::ATTRIBUTE_NORMAL).is_none() {+ mesh.insert_attribute(Mesh::ATTRIBUTE_NORMAL, vec![[0f32, 0.0, 1.0]; n]);+ }+ if own.is_empty() {+ return Ok(());+ }+ let v: Value = match buffer {+ Some(b) => serde_json::from_str(b).map_err(|e| format!("a buffer mesh isn't JSON: {e}"))?,+ None => return Err(format!("a three shader reads the mesh's own attributes ({}): give the mesh as a BufferMesh with them", own.join(", "))),+ };+ let verts = v.get("positions").and_then(Value::as_array).map(|p| p.len() / 3).unwrap_or(0);+ let idx = raea_sys_material::mesh::buffer_corners(&v, verts);+ for (k, name) in own.iter().enumerate() {+ let a = v.get("attributes").and_then(|a| a.get(name)).ok_or_else(|| format!("the shader reads attribute {name}, which the mesh doesn't give"))?;+ let size = a.get("size").and_then(Value::as_u64).unwrap_or(1).clamp(1, 4) as usize;+ let vals: Vec<f32> = a.get("values").and_then(Value::as_array).ok_or_else(|| format!("attribute {name}: {{size, values}}"))?.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();+ if vals.len() < verts * size {+ return Err(format!("attribute {name}: {size} numbers for each of {verts} vertices, got {}", vals.len()));+ }+ let per: Vec<[f32; 4]> = idx.iter().map(|&i| {+ let mut out = [0f32; 4];+ out[..size].copy_from_slice(&vals[i * size..i * size + size]);+ out+ }).collect();+ if per.len() != n {+ return Err(format!("attribute {name}: {} corners, the mesh has {n}", per.len()));+ }+ mesh.insert_attribute(ATTRIBUTE[k].clone(), per);+ }+ Ok(())+}++/// Each three shader follows the scene camera's tone mapping, whichever it is this frame: a `display` one's colour is+/// taken back through it, a `linear` one's mapped by it where the camera maps in its materials' shaders.+fn follow_tonemapping(cams: Query<(&Camera, Option<&bevy::core_pipeline::tonemapping::Tonemapping>), With<Camera3d>>, luts: Option<Res<bevy::core_pipeline::tonemapping::TonemappingLuts>>, mut mats: ResMut<Assets<ThreeShader>>) {+ use bevy::core_pipeline::tonemapping::Tonemapping as T;+ let tm = cams.iter().filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order).and_then(|(_, t)| t.copied()).unwrap_or(T::None);+ let (method, lut) = match tm {+ T::None | T::Linear => (1.0, None),+ T::Reinhard => (2.0, None),+ T::ReinhardLuminance => (3.0, None),+ T::AcesFitted => (4.0, None),+ T::AgX => (5.0, luts.as_ref().map(|l| l.agx.clone())),+ T::SomewhatBoringDisplayTransform => (6.0, None),+ T::TonyMcMapface => (7.0, luts.as_ref().map(|l| l.tony_mc_mapface.clone())),+ T::BlenderFilmic => (8.0, luts.as_ref().map(|l| l.blender_filmic.clone())),+ T::KhronosPbrNeutral => (9.0, None),+ };+ let ids: Vec<AssetId<ThreeShader>> = mats.iter().filter(|(_, m)| m.slots[DISPLAY_SLOT].x != 1.0 + method || m.lut != lut).map(|(id, _)| id).collect();+ for id in ids {+ if let Some(mut m) = mats.get_mut(id) {+ m.slots[DISPLAY_SLOT].x = 1.0 + method;+ m.lut = lut.clone();+ }+ }+}++#[cfg(test)]+mod tests {+ #[test]+ fn modules_wrap_the_contract() {+ let l = super::module::layout(&[("tint".into(), super::Ty::Vec(3), None)]).unwrap();+ let (v, f) = super::modules("struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_vertex(v: ThreeVertex) -> ThreeVaryings { var o: ThreeVaryings; o.clip = three_projection() * three_view() * three_model(v.instance) * vec4(v.position, 1.0); return o; }", "struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> { return vec4(u_tint(), 1.0); }", &l, Some(&[]), 0);+ assert!(v.contains("@vertex\nfn vertex(m: ThreeMeshIn) -> ThreeVaryings"));+ assert!(f.contains("return three_untone(three_fragment(in, front));"));+ assert!(f.contains("@group(constants::MATERIAL_BIND_GROUP) @binding(9) var three_lut: texture_3d<f32>;"));+ }+}diff --git a/systems/three-shader/src/linear.rs b/systems/three-shader/src/linear.rsnew file mode 100644index 00000000..90640661--- /dev/null+++ b/systems/three-shader/src/linear.rs@@ -0,0 +1,42 @@+//! A picture three samples without a colour space (NoColorSpace: a distance field, a data map, lettra's MSDF atlas) is+//! read as its raw numbers. Bevy loads a picture as sRGB, so such a texture is a copy of the loaded image with its+//! format's sRGB read dropped (the same bytes), made once a picture once it has loaded.+use bevy::platform::collections::HashMap;+use bevy::prelude::*;++#[derive(Resource, Default)]+pub struct Raw {+ pending: Vec<(Handle<Image>, Handle<Image>)>,+ made: HashMap<AssetId<Image>, Handle<Image>>,+}++/// the raw copy of a picture (the same copy each time it's asked for)+pub fn raw(world: &mut World, h: Handle<Image>) -> Handle<Image> {+ if let Some(c) = world.get_resource::<Raw>().and_then(|r| r.made.get(&h.id())) {+ return c.clone();+ }+ let copy = world.resource::<Assets<Image>>().reserve_handle();+ let mut r = world.get_resource_or_insert_with(Raw::default);+ r.made.insert(h.id(), copy.clone());+ r.pending.push((h, copy.clone()));+ copy+}++pub fn sync(r: Option<ResMut<Raw>>, mut images: ResMut<Assets<Image>>) {+ let Some(mut r) = r else { return };+ if r.pending.is_empty() {+ return;+ }+ for (src, copy) in std::mem::take(&mut r.pending) {+ let Some(img) = images.get(&src) else {+ r.pending.push((src, copy));+ continue;+ };+ let mut img = img.clone();+ img.texture_descriptor.format = img.texture_descriptor.format.remove_srgb_suffix();+ if let Some(f) = img.texture_view_descriptor.as_mut().and_then(|v| v.format.as_mut()) {+ *f = f.remove_srgb_suffix();+ }+ let _ = images.insert(copy.id(), img);+ }+}diff --git a/systems/three-shader/src/module.rs b/systems/three-shader/src/module.rsnew file mode 100644index 00000000..adb9532b--- /dev/null+++ b/systems/three-shader/src/module.rs@@ -0,0 +1,357 @@+//! The WGSL a three shader is compiled as: the prelude both stages share (three's built-ins, the uniform accessors, the+//! textures), the entry points over the source's `three_vertex` and `three_fragment`, and the uniform layout.+//!+//! The contract a stage's source meets (docs/r3f.feature R3F11), whether naga wrote it from GLSL (glsl.rs) or three's+//! own TSL builder wrote it (sdk/r3f's input/tsl.ts):+//! vertex: fn three_vertex(v: ThreeVertex) -> ThreeVaryings+//! fragment: fn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32>+//! and both declare the same `struct ThreeVaryings { @builtin(position) clip: vec4<f32>, @location(0) ... }`. The+//! prelude gives `ThreeVertex` (position, normal, uv, color, a0..a3: a mesh's own attributes packed four floats a+//! slot, instance, index), `three_model(instance)`, `three_view()`, `three_projection()` (Bevy's clip_from_view, reverse+//! Z), `three_camera_position()`, `three_viewport()`, `three_time()`, a `u_NAME()` per uniform (`u_NAME(i)` for an+//! array), and `tex_NAME` / `samp_NAME` per texture.++/// vec4 slots in the uniform buffer, and the two the material keeps for itself: 62 is three's time (time, delta,+/// frame), 63 how the fragment's colour is read (lib.rs's `display`)+pub const SLOTS: usize = 64;+pub const USER_SLOTS: usize = 62;+pub const TIME_SLOT: usize = 62;+pub const DISPLAY_SLOT: usize = 63;+/// textures a material may bind, and a mesh's own attributes (each up to four floats)+pub const TEXTURES: usize = 4;+pub const ATTRIBUTES: usize = 4;++/// A uniform's type: WGSL's name for it, the floats an element holds, the slots an element takes.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Ty {+ F32,+ I32,+ U32,+ Bool,+ /// vecN of f32 (N 2..4)+ Vec(u8),+ IVec(u8),+ UVec(u8),+ BVec(u8),+ /// matNxN of f32 (N 2..4)+ Mat(u8),+}++impl Ty {+ /// WGSL's name (`vec3<f32>`), or GLSL's (`vec3`, `ivec2`, `mat4`, `float`)+ pub fn parse(s: &str) -> Option<Ty> {+ let s = s.replace(' ', "");+ let n = |c: char| c.to_digit(10).filter(|d| (2..=4).contains(d)).map(|d| d as u8);+ Some(match s.as_str() {+ "f32" | "float" => Ty::F32,+ "i32" | "int" => Ty::I32,+ "u32" | "uint" => Ty::U32,+ "bool" => Ty::Bool,+ _ => {+ let c = s.chars().nth(if s.starts_with("vec") || s.starts_with("mat") { 3 } else { 4 })?;+ let d = n(c)?;+ match s.as_str() {+ x if x == format!("vec{d}") || x == format!("vec{d}<f32>") => Ty::Vec(d),+ x if x == format!("ivec{d}") || x == format!("vec{d}<i32>") => Ty::IVec(d),+ x if x == format!("uvec{d}") || x == format!("vec{d}<u32>") => Ty::UVec(d),+ x if x == format!("bvec{d}") || x == format!("vec{d}<bool>") => Ty::BVec(d),+ x if x == format!("mat{d}") || x == format!("mat{d}x{d}") || x == format!("mat{d}x{d}<f32>") => Ty::Mat(d),+ _ => return None,+ }+ }+ })+ }++ pub fn wgsl(self) -> String {+ match self {+ Ty::F32 => "f32".into(),+ Ty::I32 => "i32".into(),+ Ty::U32 => "u32".into(),+ Ty::Bool => "bool".into(),+ Ty::Vec(n) => format!("vec{n}<f32>"),+ Ty::IVec(n) => format!("vec{n}<i32>"),+ Ty::UVec(n) => format!("vec{n}<u32>"),+ Ty::BVec(n) => format!("vec{n}<bool>"),+ Ty::Mat(n) => format!("mat{n}x{n}<f32>"),+ }+ }++ /// floats an element is given as (a matrix column-major, as three's `elements`)+ pub fn floats(self) -> usize {+ match self {+ Ty::F32 | Ty::I32 | Ty::U32 | Ty::Bool => 1,+ Ty::Vec(n) | Ty::IVec(n) | Ty::UVec(n) | Ty::BVec(n) => n as usize,+ Ty::Mat(n) => (n * n) as usize,+ }+ }++ /// vec4 slots an element takes+ pub fn slots(self) -> usize {+ match self {+ Ty::Mat(n) => n as usize,+ _ => 1,+ }+ }++ /// the element at slot `k` (a WGSL expression) of `s` (the slots array)+ fn read(self, s: &str, k: &str) -> String {+ let sw = |n: u8| ["", "", ".xy", ".xyz", ""][n as usize];+ match self {+ Ty::F32 => format!("{s}[{k}].x"),+ Ty::I32 => format!("i32({s}[{k}].x)"),+ Ty::U32 => format!("u32({s}[{k}].x)"),+ Ty::Bool => format!("({s}[{k}].x != 0.0)"),+ Ty::Vec(n) => format!("{s}[{k}]{}", sw(n)),+ Ty::IVec(n) => format!("vec{n}<i32>({s}[{k}]{})", sw(n)),+ Ty::UVec(n) => format!("vec{n}<u32>({s}[{k}]{})", sw(n)),+ Ty::BVec(n) => format!("({s}[{k}]{} != vec{n}<f32>(0.0))", sw(n)),+ Ty::Mat(n) => {+ let cols: Vec<String> = (0..n).map(|c| format!("{s}[{k} + {c}u]{}", sw(n))).collect();+ format!("mat{n}x{n}<f32>({})", cols.join(", "))+ }+ }+ }+}++/// A uniform laid out: its first slot.+#[derive(Clone, Debug)]+pub struct Uniform {+ pub name: String,+ pub ty: Ty,+ /// an array's length+ pub array: Option<u32>,+ pub base: usize,+}++impl Uniform {+ pub fn len(&self) -> usize {+ self.array.unwrap_or(1) as usize+ }+}++/// Uniforms laid out one after another from slot 0; an error past the slots there are.+pub fn layout(list: &[(String, Ty, Option<u32>)]) -> Result<Vec<Uniform>, String> {+ let mut at = 0;+ let mut out = Vec::new();+ for (name, ty, array) in list {+ let u = Uniform { name: name.clone(), ty: *ty, array: *array, base: at };+ at += ty.slots() * u.len();+ if at > USER_SLOTS {+ return Err(format!("a three shader's uniforms take at most {USER_SLOTS} vec4 slots; {name} passes them ({at})"));+ }+ out.push(u);+ }+ Ok(out)+}++/// `values` (each uniform's floats, an array's elements one after another) written into the slots+pub fn pack(layout: &[Uniform], values: &serde_json::Map<String, serde_json::Value>, slots: &mut [[f32; 4]; SLOTS]) -> Result<(), String> {+ for u in layout {+ let Some(v) = values.get(&u.name) else { continue };+ let f: Vec<f32> = match v {+ serde_json::Value::Number(n) => vec![n.as_f64().unwrap_or(0.0) as f32],+ serde_json::Value::Bool(b) => vec![*b as u8 as f32],+ serde_json::Value::Array(a) => a.iter().map(|x| match x {+ serde_json::Value::Bool(b) => Ok(*b as u8 as f32),+ _ => x.as_f64().map(|f| f as f32).ok_or_else(|| format!("uniform {}: numbers, got {x}", u.name)),+ }).collect::<Result<_, _>>()?,+ _ => return Err(format!("uniform {}: a number or a list of numbers, got {v}", u.name)),+ };+ let per = u.ty.floats();+ if f.len() < per {+ return Err(format!("uniform {} ({}): {per} numbers an element, got {}", u.name, u.ty.wgsl(), f.len()));+ }+ for (i, e) in f.chunks(per).take(u.len()).enumerate() {+ if e.len() < per {+ break;+ }+ let at = u.base + i * u.ty.slots();+ match u.ty {+ Ty::Mat(n) => {+ for c in 0..n as usize {+ for r in 0..n as usize {+ slots[at + c][r] = e[c * n as usize + r];+ }+ }+ }+ _ => {+ for (c, x) in e.iter().enumerate() {+ slots[at][c] = *x;+ }+ }+ }+ }+ }+ Ok(())+}++const GROUP: &str = "constants::MATERIAL_BIND_GROUP";++/// The prelude of a stage: Bevy's view and mesh functions, the slots, the built-ins, the uniform accessors, and (when+/// `textures` is given: a WGSL source; naga's GLSL declares its own) the textures.+pub fn prelude(uniforms: &[Uniform], textures: Option<&[String]>, attributes: usize) -> String {+ let mut m = String::from(+ "import bevy_pbr::render::mesh_functions::get_world_from_local;\n\+ import bevy_pbr::render::mesh_view_bindings::{view, globals};\n\n",+ );+ m += &format!("struct ThreeSlots {{ s: array<vec4<f32>, {SLOTS}> }};\n@group({GROUP}) @binding(0) var<uniform> three_slots: ThreeSlots;\n");+ if let Some(ts) = textures {+ for (i, t) in ts.iter().enumerate() {+ m += &format!("@group({GROUP}) @binding({}) var tex_{t}: texture_2d<f32>;\n@group({GROUP}) @binding({}) var samp_{t}: sampler;\n", 1 + i * 2, 2 + i * 2);+ }+ }+ m += "\nstruct ThreeVertex {\n position: vec3<f32>,\n normal: vec3<f32>,\n uv: vec2<f32>,\n color: vec4<f32>,\n";+ for k in 0..attributes.max(1) {+ m += &format!(" a{k}: vec4<f32>,\n");+ }+ m += " instance: u32,\n index: u32,\n};\n\n";+ m += "fn three_model(instance: u32) -> mat4x4<f32> { return get_world_from_local(instance); }\n\+ fn three_view() -> mat4x4<f32> { return view.view_from_world; }\n\+ fn three_projection() -> mat4x4<f32> { return view.clip_from_view; }\n\+ fn three_camera_position() -> vec3<f32> { return view.world_position; }\n\+ fn three_viewport() -> vec4<f32> { return view.viewport; }\n";+ m += &format!("fn three_time() -> f32 {{ return three_slots.s[{TIME_SLOT}].x; }}\nfn three_delta() -> f32 {{ return three_slots.s[{TIME_SLOT}].y; }}\nfn three_frame() -> f32 {{ return three_slots.s[{TIME_SLOT}].z; }}\n");+ for u in uniforms {+ let ty = u.ty.wgsl();+ match u.array {+ None => m += &format!("fn u_{}() -> {ty} {{ return {}; }}\n", u.name, u.ty.read("three_slots.s", &format!("{}u", u.base))),+ Some(_) => m += &format!("fn u_{}(i: u32) -> {ty} {{ let k = {}u + i * {}u; return {}; }}\n", u.name, u.base, u.ty.slots(), u.ty.read("three_slots.s", "k")),+ }+ }+ m + "\n"+}++/// The vertex entry: the mesh's attributes as a ThreeVertex, the source's `three_vertex` on it. Locations: position 0,+/// normal 1, uv 2, colour 3, the mesh's own attributes 4 and up (lib.rs's `specialize` lays the buffer out so).+pub fn vertex_entry(attributes: usize) -> String {+ let mut m = String::from("\nstruct ThreeMeshIn {\n @builtin(instance_index) instance: u32,\n @builtin(vertex_index) index: u32,\n @location(0) position: vec3<f32>,\n @location(1) normal: vec3<f32>,\n @location(2) uv: vec2<f32>,\n @location(3) color: vec4<f32>,\n");+ for k in 0..attributes {+ m += &format!(" @location({}) a{k}: vec4<f32>,\n", 4 + k);+ }+ m += "};\n\n@vertex\nfn vertex(m: ThreeMeshIn) -> ThreeVaryings {\n var v: ThreeVertex;\n v.position = m.position;\n v.normal = m.normal;\n v.uv = m.uv;\n v.color = m.color;\n";+ for k in 0..attributes {+ m += &format!(" v.a{k} = m.a{k};\n");+ }+ m + " v.instance = m.instance;\n v.index = m.index;\n return three_vertex(v);\n}\n"+}++/// The fragment entry: the source's `three_fragment`, its colour read as `display` says (tone.wesl's three_untone).+pub fn fragment_entry() -> String {+ let mut m = String::from(TONE);+ m = m.replace("GROUP", GROUP);+ m + "\n@fragment\nfn fragment(in: ThreeVaryings, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {\n return three_untone(three_fragment(in, front));\n}\n"+}++const TONE: &str = include_str!("tone.wesl");++/// The argument spans of the call whose `(` is at `open` (byte offsets, each trimmed), and where its `)` is.+fn args(src: &str, open: usize) -> Option<(Vec<(usize, usize)>, usize)> {+ let b = src.as_bytes();+ let (mut depth, mut start, mut out) = (0i32, open + 1, Vec::new());+ for (i, &c) in b.iter().enumerate().skip(open) {+ match c {+ b'(' | b'[' => depth += 1,+ b')' | b']' => {+ depth -= 1;+ if depth == 0 {+ out.push((start, i));+ return Some((out, i));+ }+ }+ b',' if depth == 1 => {+ out.push((start, i));+ start = i + 1;+ }+ _ => {}+ }+ }+ None+}++/// Every sample of the textures `names` with its v turned over (three's flipY): textureSample* read at+/// (u, 1 - v), textureLoad at the mirrored row.+pub fn flip_samples(src: &str, names: &[String]) -> String {+ if names.is_empty() {+ return src.to_string();+ }+ let mut out = String::with_capacity(src.len());+ let mut at = 0;+ while let Some(i) = src[at..].find("texture").map(|i| at + i) {+ let rest = &src[i..];+ let name_end = rest.char_indices().find(|&(_, c)| !c.is_ascii_alphanumeric() && c != '_').map_or(rest.len(), |(k, _)| k);+ let func = &rest[..name_end];+ let open = i + name_end;+ let call = (func.starts_with("textureSample") || func == "textureLoad") && src[open..].starts_with('(');+ let parsed = call.then(|| args(src, open)).flatten();+ match parsed {+ Some((list, close)) if list.first().is_some_and(|(a, b)| names.iter().any(|n| src[*a..*b].trim() == n)) => {+ let k = if func == "textureLoad" { 1 } else { 2 };+ let Some(&(ca, cb)) = list.get(k) else {+ out += &src[at..open];+ at = open;+ continue;+ };+ let coords = src[ca..cb].trim();+ let flipped = if func == "textureLoad" {+ let tex = src[list[0].0..list[0].1].trim();+ let level = list.get(2).map(|(a, b)| src[*a..*b].trim()).unwrap_or("0");+ format!("vec2<i32>(({coords}).x, i32(textureDimensions({tex}, {level}).y) - 1 - ({coords}).y)")+ } else {+ format!("vec2<f32>(({coords}).x, 1.0 - ({coords}).y)")+ };+ out += &src[at..ca];+ out += &flipped;+ out += &src[cb..=close];+ at = close + 1;+ }+ _ => {+ out += &src[at..open.max(i + 1)];+ at = open.max(i + 1);+ }+ }+ }+ out + &src[at..]+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn flipped_textures_are_read_upside_down() {+ let s = "let a = textureSample(rgt0x, rgs0x, vUv);\nlet b = textureSampleLevel(rgt1x, rgs1x, f(x, y), 0.0);\nlet c = textureLoad(rgt0x, p, 0);";+ let f = flip_samples(s, &["rgt0x".into()]);+ assert!(f.contains("textureSample(rgt0x, rgs0x,vec2<f32>((vUv).x, 1.0 - (vUv).y))"), "{f}");+ assert!(f.contains("textureSampleLevel(rgt1x, rgs1x, f(x, y), 0.0)"));+ assert!(f.contains("textureLoad(rgt0x,vec2<i32>((p).x, i32(textureDimensions(rgt0x, 0).y) - 1 - (p).y), 0)"), "{f}");+ }++ #[test]+ fn types_read_from_wgsl_and_glsl() {+ assert_eq!(Ty::parse("vec3<f32>"), Some(Ty::Vec(3)));+ assert_eq!(Ty::parse("vec3"), Some(Ty::Vec(3)));+ assert_eq!(Ty::parse("ivec2"), Some(Ty::IVec(2)));+ assert_eq!(Ty::parse("mat4"), Some(Ty::Mat(4)));+ assert_eq!(Ty::parse("mat3x3<f32>"), Some(Ty::Mat(3)));+ assert_eq!(Ty::parse("float"), Some(Ty::F32));+ assert_eq!(Ty::parse("sampler2D"), None);+ }++ #[test]+ fn uniforms_pack_in_order_and_read_back() {+ let l = layout(&[("uTime".into(), Ty::F32, None), ("m".into(), Ty::Mat(3), None), ("pts".into(), Ty::Vec(2), Some(3))]).unwrap();+ assert_eq!(l.iter().map(|u| u.base).collect::<Vec<_>>(), vec![0, 1, 4]);+ let mut s = [[0f32; 4]; SLOTS];+ let v: serde_json::Value = serde_json::json!({"uTime": 2.5, "m": [1, 2, 3, 4, 5, 6, 7, 8, 9], "pts": [1, 2, 3, 4, 5, 6]});+ pack(&l, v.as_object().unwrap(), &mut s).unwrap();+ assert_eq!(s[0][0], 2.5);+ assert_eq!(s[2], [4.0, 5.0, 6.0, 0.0]);+ assert_eq!(s[6], [5.0, 6.0, 0.0, 0.0]);+ let p = prelude(&l, Some(&["map".into()]), 0);+ assert!(p.contains("fn u_uTime() -> f32 { return three_slots.s[0u].x; }"));+ assert!(p.contains("fn u_m() -> mat3x3<f32> { return mat3x3<f32>(three_slots.s[1u + 0u].xyz, three_slots.s[1u + 1u].xyz, three_slots.s[1u + 2u].xyz); }"));+ assert!(p.contains("fn u_pts(i: u32) -> vec2<f32> { let k = 4u + i * 1u; return three_slots.s[k].xy; }"));+ assert!(p.contains("var tex_map: texture_2d<f32>;"));+ assert!(layout(&[("big".into(), Ty::Mat(4), Some(16))]).is_err());+ }+}diff --git a/systems/three-shader/src/row.rs b/systems/three-shader/src/row.rsnew file mode 100644index 00000000..723715ac--- /dev/null+++ b/systems/three-shader/src/row.rs@@ -0,0 +1,29 @@+//! A raea-render mesh row's `three` column (R3F's reader writes it, docs/r3f.feature R3F11): its material with its+//! pictures found, and the mesh given what the shader reads.++use super::*;++/// The row's three.js shader as its material and the names of the mesh's own attributes it reads. One that can't run+/// here is named in a warning and None, so the plain surface its row also describes is drawn. A picture made in code (a+/// DataTexture, a canvas: R3F's reader sends it as a PNG data: URL) is decoded here as a material's map is; any other+/// is `image`'s to find (a file, a URL, a render: ref).+pub fn of_row(world: &mut World, id: &str, spec: &str, mut image: impl FnMut(&mut World, &Value) -> Result<Handle<Image>, String>) -> Option<(ThreeShader, Vec<String>)> {+ let built = serde_json::from_str::<Value>(spec).map_err(|e| e.to_string()).and_then(|v| {+ build(world, &v, |w, x| match x.as_str() {+ Some(p) if p.starts_with("data:") => {+ let pic = raea_sys_material::maps::data_picture(p)?;+ let img = Image::from_dynamic(image::DynamicImage::ImageRgba8(pic), true, bevy::asset::RenderAssetUsages::default());+ Ok(w.resource_mut::<Assets<Image>>().add(img))+ }+ _ => image(w, x),+ })+ });+ built.map_err(|err| warn!("mesh {id}: its three.js shader doesn't run here, so it's drawn in its colour: {err}")).ok()+}++/// The row's mesh (`base`) given what its shader reads (fit_mesh): a colour and uvs on every vertex, its own attributes.+pub fn fitted(base: Option<&Mesh>, id: &str, buffer: Option<&str>, own: &[String]) -> Result<Mesh, String> {+ let mut m = base.cloned().ok_or_else(|| format!("mesh {id}: its mesh isn't made"))?;+ fit_mesh(&mut m, buffer, own).map_err(|e| format!("mesh {id}: {e}"))?;+ Ok(m)+}diff --git a/systems/three-shader/src/scan.rs b/systems/three-shader/src/scan.rsnew file mode 100644index 00000000..45442672--- /dev/null+++ b/systems/three-shader/src/scan.rs@@ -0,0 +1,244 @@+//! The scanner glsl.rs translates with: a stage's GLSL split into the globals it declares (attributes, varyings,+//! uniforms, samplers, outputs) and the rest of its source, the body naga compiles.++use std::collections::BTreeMap;++/// A global a stage declares.+#[derive(Clone, Debug, PartialEq)]+pub struct Var {+ pub name: String,+ /// its GLSL type (`vec3`, `mat4`, `sampler2D`)+ pub glsl: String,+ pub array: Option<u32>,+ pub flat: bool,+}++#[derive(Default, Debug)]+pub struct Scanned {+ pub attributes: Vec<Var>,+ pub varyings: Vec<Var>,+ pub uniforms: Vec<Var>,+ /// sampler2D (and samplerCube, refused later) uniforms+ pub samplers: Vec<Var>,+ pub outputs: Vec<Var>,+ /// the source without those declarations, comments and `precision`, `#version` and `#extension` lines+ pub body: String,+}++/// Removes // and /* */ comments, keeping newlines.+fn uncomment(src: &str) -> String {+ let mut out = String::with_capacity(src.len());+ let b = src.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'/' {+ while i < b.len() && b[i] != b'\n' {+ i += 1;+ }+ } else if b[i] == b'/' && i + 1 < b.len() && b[i + 1] == b'*' {+ i += 2;+ while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') {+ if b[i] == b'\n' {+ out.push('\n');+ }+ i += 1;+ }+ i += 2;+ } else {+ out.push(b[i] as char);+ i += 1;+ }+ }+ out+}++const QUALIFIERS: [&str; 10] = ["highp", "mediump", "lowp", "flat", "smooth", "noperspective", "centroid", "invariant", "const", "precise"];++/// The `#define NAME <integer>`s, for array sizes given by a macro.+fn int_defines(src: &str) -> BTreeMap<String, u32> {+ let mut m = BTreeMap::new();+ for l in src.lines() {+ let t: Vec<&str> = l.trim().split_whitespace().collect();+ if t.len() == 3 && t[0] == "#define" {+ if let Ok(n) = t[2].parse::<u32>() {+ m.insert(t[1].to_string(), n);+ }+ }+ }+ m+}++/// A global declaration's role and its variables, or None when the statement isn't one this cares about.+fn declaration(stmt: &str, vertex: bool, ints: &BTreeMap<String, u32>) -> Result<Option<(&'static str, Vec<Var>)>, String> {+ // layout(...) qualifiers say nothing three's GLSL needs here+ let mut s = stmt.trim().to_string();+ while let Some(i) = s.find("layout") {+ let Some(open) = s[i..].find('(') else { break };+ let Some(close) = s[i + open..].find(')') else { break };+ s.replace_range(i..i + open + close + 1, " ");+ }+ let s = s.replace(',', " , ").replace('[', " [ ").replace(']', " ] ").replace('=', " = ");+ let toks: Vec<&str> = s.split_whitespace().collect();+ let Some(&first) = toks.first() else { return Ok(None) };+ let mut flat = false;+ let mut role = None;+ let mut k = 0;+ while k < toks.len() {+ match toks[k] {+ "uniform" => role = Some("uniform"),+ "attribute" => role = Some("attribute"),+ "varying" => role = Some("varying"),+ "in" => role = Some(if vertex { "attribute" } else { "varying" }),+ "out" => role = Some(if vertex { "varying" } else { "output" }),+ "flat" => flat = true,+ q if QUALIFIERS.contains(&q) => {}+ _ => break,+ }+ k += 1;+ }+ let Some(role) = role else { return Ok(None) };+ if first == "precision" {+ return Ok(None);+ }+ let Some(&ty) = toks.get(k) else { return Err(format!("a declaration with no type: {stmt:?}")) };+ if toks.get(k + 1) == Some(&"{") {+ return Err(format!("an interface block isn't supported yet: {stmt:?}"));+ }+ let mut vars = Vec::new();+ let mut i = k + 1;+ while i < toks.len() {+ let name = toks[i];+ let mut array = None;+ i += 1;+ if toks.get(i) == Some(&"[") {+ let n = toks.get(i + 1).copied().unwrap_or("");+ array = Some(n.parse::<u32>().ok().or_else(|| ints.get(n).copied()).ok_or_else(|| format!("{name}: its array length {n:?} isn't a number or a #define of one"))?);+ i += 3;+ }+ if toks.get(i) == Some(&"=") {+ // an initializer (desktop GLSL allows one on a uniform): skipped to the next name+ while i < toks.len() && toks[i] != "," {+ i += 1;+ }+ }+ vars.push(Var { name: name.to_string(), glsl: ty.to_string(), array, flat });+ if toks.get(i) == Some(&",") {+ i += 1;+ }+ }+ Ok(Some((role, vars)))+}++/// A stage's globals taken out of its source.+pub fn scan(src: &str, vertex: bool) -> Result<Scanned, String> {+ let src = uncomment(src);+ let ints = int_defines(&src);+ let mut out = Scanned::default();+ let mut body = String::with_capacity(src.len());+ let mut depth = 0i32;+ let mut stmt = String::new();+ let mut line_start = true;+ let mut chars = src.chars().peekable();+ while let Some(c) = chars.next() {+ // a directive line, outside a statement's text: kept as it is (but #version, #extension and #pragma)+ if line_start && depth == 0 && stmt.trim().is_empty() {+ let mut lead = String::new();+ let mut cc = Some(c);+ while let Some(x) = cc.filter(|x| matches!(x, ' ' | '\t')) {+ lead.push(x);+ cc = chars.next();+ }+ if cc == Some('#') {+ let mut line = String::from("#");+ for x in chars.by_ref() {+ if x == '\n' {+ break;+ }+ line.push(x);+ }+ let t = line.trim_start_matches('#').trim_start();+ if !(t.starts_with("version") || t.starts_with("extension") || t.starts_with("pragma")) {+ // on a line of its own: the newline after a function's `}` went to the statement being gathered,+ // so a #define after a function (three's <common>) was mid-line (naga: UnexpectedHash)+ if !body.is_empty() && !body.ends_with('\n') {+ body.push('\n');+ }+ body += &line;+ }+ body.push('\n');+ stmt.clear();+ line_start = true;+ continue;+ }+ stmt += &lead;+ let Some(c2) = cc else { break };+ line_start = false;+ if c2 == '\n' {+ stmt.push('\n');+ line_start = true;+ continue;+ }+ step(c2, &mut depth, &mut stmt, &mut body, &mut out, vertex, &ints)?;+ continue;+ }+ line_start = c == '\n';+ step(c, &mut depth, &mut stmt, &mut body, &mut out, vertex, &ints)?;+ }+ body += &stmt;+ out.body = body;+ Ok(out)+}++/// One character: inside a body it goes straight out; at the top level it gathers into a statement, which ends at `;`+/// (a declaration this takes out, or anything else kept) or at `{` (a function's or struct's head, kept).+fn step(c: char, depth: &mut i32, stmt: &mut String, body: &mut String, out: &mut Scanned, vertex: bool, ints: &BTreeMap<String, u32>) -> Result<(), String> {+ if *depth > 0 {+ body.push(c);+ if c == '{' {+ *depth += 1;+ } else if c == '}' {+ *depth -= 1;+ }+ return Ok(());+ }+ match c {+ '{' => {+ *body += stmt;+ body.push('{');+ stmt.clear();+ *depth = 1;+ }+ ';' => {+ let t = stmt.trim();+ if t.starts_with("precision ") {+ *body += &"\n".repeat(stmt.matches('\n').count());+ } else {+ match declaration(t, vertex, ints)? {+ Some((role, vars)) => {+ let list = match role {+ "attribute" => &mut out.attributes,+ "varying" => &mut out.varyings,+ "output" => &mut out.outputs,+ _ => &mut out.uniforms,+ };+ for v in vars {+ if role == "uniform" && v.glsl.starts_with("sampler") {+ out.samplers.push(v);+ } else {+ list.push(v);+ }+ }+ *body += &"\n".repeat(stmt.matches('\n').count());+ }+ None => {+ *body += stmt;+ body.push(';');+ }+ }+ }+ stmt.clear();+ }+ _ => stmt.push(c),+ }+ Ok(())+}diff --git a/systems/three-shader/src/tone.wesl b/systems/three-shader/src/tone.weslnew file mode 100644index 00000000..d0a731c7--- /dev/null+++ b/systems/three-shader/src/tone.wesl@@ -0,0 +1,140 @@+// How a three shader's colour reaches the screen as three puts it there (docs/r3f.feature R3F11). A ShaderMaterial+// writes the value the canvas shows (three applies no tone mapping or colour space to it unless its GLSL includes+// them), where Bevy tone-maps and encodes every pixel of the frame after the fact. So a "display" colour is decoded+// from sRGB and taken back through the camera's tone mapping: the linear value Bevy's curve turns into it. Slot 63:+// x is 0 for a linear (scene-referred) colour, left as it is, or 1 + the camera's tone mapping (lib.rs's `display`).+// The curves are Bevy 0.20's own (bevy_core_pipeline tonemapping.wesl), inverted by a damped fixed point, so one+// method covers the LUT-based ones too; the LUT is the camera's (TonemappingLuts), at bindings 9 and 10.++@group(GROUP) @binding(9) var three_lut: texture_3d<f32>;+@group(GROUP) @binding(10) var three_lut_sampler: sampler;++fn three_lum(v: vec3<f32>) -> f32 {+ return dot(v, vec3<f32>(0.2126, 0.7152, 0.0722));+}++fn three_lut3(p: vec3<f32>, block: f32) -> vec3<f32> {+ return textureSampleLevel(three_lut, three_lut_sampler, p * ((block - 1.0) / block) + 0.5 / block, 0.0).rgb;+}++fn three_log2_norm(color: vec3<f32>, lo: f32, hi: f32) -> vec3<f32> {+ var c = max(vec3(0.0), color);+ c = select(c, 0.00001525878 + c, c < vec3<f32>(0.00003051757));+ c = clamp(log2(c / 0.18), vec3(lo), vec3(hi));+ return (c - lo) / (hi - lo);+}++fn three_aces(color: vec3<f32>) -> vec3<f32> {+ let rgb_to_rrt = mat3x3<f32>(vec3(0.59719, 0.35458, 0.04823), vec3(0.07600, 0.90834, 0.01566), vec3(0.02840, 0.13383, 0.83777));+ let odt_to_rgb = mat3x3<f32>(vec3(1.60475, -0.53108, -0.07367), vec3(-0.10208, 1.10813, -0.00605), vec3(-0.00327, -0.07276, 1.07602));+ var v = color * rgb_to_rrt;+ v = (v * (v + 0.0245786) - 0.000090537) / (v * (0.983729 * v + 0.4329510) + 0.238081);+ return saturate(v * odt_to_rgb);+}++fn three_curve(v: f32) -> f32 {+ return 1.0 - exp(-v);+}++fn three_boring(col: vec3<f32>) -> vec3<f32> {+ let m = mat3x3<f32>(0.2126, 0.7152, 0.0722, -0.1146, -0.3854, 0.5, 0.5, -0.4542, -0.0458);+ let ycbcr = col * m;+ let bt = three_curve(length(ycbcr.yz) * 2.4);+ var desat = max((bt - 0.7) * 0.8, 0.0);+ desat *= desat;+ let desat_col = mix(col, ycbcr.xxx, desat);+ let tm_luma = three_curve(ycbcr.x);+ let tm0 = col * max(0.0, tm_luma / max(1e-5, three_lum(col)));+ let tm1 = vec3(three_curve(desat_col.r), three_curve(desat_col.g), three_curve(desat_col.b));+ return mix(tm0, tm1, bt * bt) * 0.97;+}++fn three_agx(color: vec3<f32>) -> vec3<f32> {+ var p = max(vec3(0.0), color);+ p = vec3(dot(p, vec3(0.84247906, 0.0784336, 0.07922375)), dot(p, vec3(0.04232824, 0.87846864, 0.07916613)), dot(p, vec3(0.04237565, 0.0784336, 0.87914297)));+ p = clamp(three_log2_norm(p, -10.0, 6.5), vec3(0.0), vec3(1.0));+ return three_lut3(p, 32.0);+}++fn three_neutral(color_in: vec3<f32>) -> vec3<f32> {+ let start = 0.8 - 0.04;+ let min_c = min(color_in.r, min(color_in.g, color_in.b));+ let offset = select(0.04, min_c - 6.25 * min_c * min_c, min_c < 0.08);+ let oc = color_in - offset;+ let max_c = max(oc.r, max(oc.g, oc.b));+ if max_c < start {+ return oc;+ }+ let d = 1.0 - start;+ let nm = 1.0 - d * d / (max_c + d - start);+ let c = oc * (nm / max_c);+ let g = 1.0 - 1.0 / (0.15 * (max_c - nm) + 1.0);+ return mix(c, vec3(nm), g);+}++/// Bevy's tone mapping `m` (1 none, 2 Reinhard, 3 Reinhard on luminance, 4 ACES fitted, 5 AgX, 6 somewhat boring,+/// 7 Tony McMapface, 8 Blender filmic, 9 PBR neutral)+fn three_tonemap(x: vec3<f32>, m: u32) -> vec3<f32> {+ let c = max(x, vec3(0.0));+ switch m {+ case 2u: { return c / (1.0 + c); }+ case 3u: { let l = three_lum(c); return c * ((l / (1.0 + l)) / max(l, 1e-6)); }+ case 4u: { return three_aces(c); }+ case 5u: { return three_agx(c); }+ case 6u: { return three_boring(c); }+ case 7u: { return three_lut3(saturate(c / (c + 1.0)), 48.0); }+ case 8u: { return three_lut3(saturate(three_log2_norm(c, -11.0, 12.0)), 64.0); }+ case 9u: { return three_neutral(c); }+ default: { return c; }+ }+}++fn three_srgb_decode(c: vec3<f32>) -> vec3<f32> {+ return select(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, c <= vec3(0.04045));+}++/// the camera's exposure against raea's default (EV100 9.7, core/scene's EV100): 1 at the default, 2 a stop up. Bevy's+/// view.exposure is physical (1/(1.2 * 2^ev100)), for lights in lux; three's is a plain multiplier+fn three_exposure() -> f32 {+ return view.exposure * 1.2 * exp2(9.7);+}++/// the linear colour Bevy's tone mapping turns into what `c` asks to be on screen+fn three_untone(c: vec4<f32>) -> vec4<f32> {+ // a camera without HDR tone-maps in its materials' own shaders (Bevy's pbr_functions), which this one isn't:+ // nothing maps it after, so the canvas's value is only decoded to the sRGB target's linear+ let mode = u32(three_slots.s[63].x + 0.5);+ let display = three_slots.s[63].y > 0.5;+ @if(TONEMAP_IN_SHADER) {+ // and a linear (scene-light) colour is mapped here, as Bevy's own materials map theirs+ if !display {+ // scene light takes the camera's exposure, as three's renderer scales it before its tone mapping+ let lit = c.rgb * three_exposure();+ if mode == 0u {+ return vec4(lit, c.a);+ }+ return vec4(three_tonemap(lit, mode - 1u), c.a);+ }+ return vec4(three_srgb_decode(clamp(c.rgb, vec3(0.0), vec3(1.0))), c.a);+ }+ if !display {+ return vec4(c.rgb * three_exposure(), c.a);+ }+ if mode == 0u {+ return c;+ }+ let want = min(three_srgb_decode(clamp(c.rgb, vec3(0.0), vec3(1.0))), vec3(0.995));+ let m = mode - 1u;+ if m <= 1u {+ return vec4(want, c.a);+ }+ var x = want / (1.0 - want);+ if m == 2u {+ return vec4(x, c.a);+ }+ for (var i = 0; i < 24; i++) {+ let y = three_tonemap(x, m);+ x = clamp(x * pow((want + 1e-4) / (y + 1e-4), vec3(0.75)), vec3(0.0), vec3(512.0));+ }+ return vec4(x, c.a);+}diff --git a/tools/release.sh b/tools/release.shindex ad391750..73c34434 100755--- a/tools/release.sh+++ b/tools/release.sh@@ -60,7 +60,7 @@ untar() {return $rc}git archive "$ref" | untar "$gate" || { echo "release.sh: the skills gate couldn't unpack $ref" >&2; exit 1; }-git -C "$gate" init -q && git -C "$gate" add -A && git -C "$gate" -c user.name=release -c [email protected] commit -qm "$ref" --no-verify+git -C "$gate" init -q && git -C "$gate" add -A && git -C "$gate" -c gc.auto=0 -c maintenance.auto=false -c user.name=release -c [email protected] commit -qm "$ref" --no-verifyraea_bin=$bin/raea; [ -f "$raea_bin.exe" ] && raea_bin=$raea_bin.exeif ! (cd "$gate" && SKILLS_STRICT=1 SKILLS_CHANGED= RAEA_BIN="$raea_bin" RAEA_APP="$root/apps/app" RAEA_APP_REV="$(git -C "$root" rev-parse "$ref:apps/app")" bash tools/skills.sh check); thenecho "release.sh: tools/skills.sh check failed on $ref with $raea_bin; fix the skills (tools/skills.sh gen) before releasing" >&2@@ -84,8 +84,9 @@ case $platform in# system, as on a Mac (raea warns once a character when no font has it)printf '%s\n' "raea $version for Linux x86_64 (glibc 2.39 or newer, Vulkan: a GPU driver or Mesa's llvmpipe).Install a CJK font for Japanese, Chinese and Korean text (Debian and Ubuntu: apt install fonts-noto-cjk).-An app on the native target (raea app ... --target native, raea-rune-host) needs libxkbcommon-x11 and the Vulkan-loader (Debian and Ubuntu: apt install libxkbcommon-x11-0 libvulkan1).+An app's window, on either target (raea app run, raea-rune-host and raea-page-host), needs a display (X11 or+Wayland; Xvfb on a server, as raea app check does there too), libxkbcommon-x11, the X client libraries and the Vulkan+loader (Debian and Ubuntu: apt install libxkbcommon-x11-0 libxcursor1 libxi6 libxrandr2 libx11-xcb1 libvulkan1).Not in this build: raea song (its beat model's runner is macOS only so far)." > "$stage/README" ;;windows-x86_64)cp "$bin/raea.exe" "$bin/raea_bundle.dll" "$bin/raea-rune-host.exe" "$bin/raea-page-host.exe" "$stage/bin/"@@ -101,7 +102,7 @@ esacpkgs=()# and its bevy/ (a package's plugin handles, generated from the plugin build: its src/plugin.ts imports ../bevy/)# and its examples/ (@raea/rune's, docs/targets.feature T1b: what a release's check runs)-for p in $(git show "$ref:sdk/tsconfig.base.json" | jq -r '.compilerOptions.paths | to_entries[] | select(.key | test("^@raea/[a-z_]+$")) | .value[0] | ltrimstr("./") | split("/")[0]' | tr -d '\r'); do+for p in $(git show "$ref:sdk/tsconfig.base.json" | jq -r '.compilerOptions.paths | to_entries[] | select(.key | test("^@raea/[a-z0-9_]+$")) | .value[0] | ltrimstr("./") | split("/")[0]' | tr -d '\r'); dopkgs+=("sdk/$p/src" "sdk/$p/package.json")git cat-file -e "$ref:sdk/$p/bevy" 2>/dev/null && pkgs+=("sdk/$p/bevy")git cat-file -e "$ref:sdk/$p/examples" 2>/dev/null && pkgs+=("sdk/$p/examples")