raea origin/main

This commit is contained in:
shane committed 2026-11-07 01:29:24 -08:00
1 parent bd1ccec7f9
commit d3c399b4d5
144 files changed
+6559 -1020

No files matched your search

Generated
+24
View File
@@ -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"
+1
View File
@@ -20,6 +20,7 @@ members = [
"systems/sampler",
"systems/parity",
"systems/shader",
"systems/three-shader",
"engine/bevy-calls",
"engine/bevy-adapters",
"engine/bevy-plugins",
@@ -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 CONDITIONS
@@ -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.
-202
View File
@@ -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.
-214
View File
@@ -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 CONDITIONS
-36
View File
@@ -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.
+1 -1
View File
@@ -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"
+26
View File
@@ -4,3 +4,29 @@ stress_tests/many_cubes
3d/3d_scene
stress_tests/many_lights
stress_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_3d
+26
View File
@@ -3,3 +3,29 @@ stress_tests/many_cubes --benchmark --instance-count 10000 30,60
3d/3d_scene - 5,10
stress_tests/many_lights - 30,60
stress_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,60
1 # path example arguments (- for none) frames probed (docs/control.feature FC0a; tools/bevy-parity)
3 3d/3d_scene - 5,10
4 stress_tests/many_lights - 30,60
5 stress_tests/many_foxes --sync 30,60
6 animation/animated_mesh - 30,60
7 shader/extended_material - 30,60
8 3d/orthographic - 10
9 3d/parenting - 30,60
10 2d/mesh2d - 10
11 2d/sprite - 10
12 transforms/3d_rotation - 30,60
13 2d/sprite_flipping - 10
14 2d/move_sprite - 30,120
15 2d/transparency_2d - 10
16 transforms/translation - 60,180
17 transforms/scale - 60,300
18 3d/texture - 10
19 shader/animate_shader - 30,60
20 2d/sprite_sheet - 30,60
21 3d/pbr - 30,60
22 3d/animated_material - 30,60
23 camera/pan_camera_controller - 10
24 camera/camera_orbit - 10
25 camera/projection_zoom - 30
26 2d/sprite_animation - 12,30,60
27 2d/sprite_tile - 30,300
28 3d/vertex_colors - 10
29 3d/spherical_area_lights - 10
30 3d/fog_volumes - 10,60
31 3d/bloom_3d - 10,60
+9
View File
@@ -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.
+20
View File
@@ -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);
}
+1 -1
View File
@@ -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};
+20 -1
View File
@@ -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 }));
+95 -18
View File
@@ -105,28 +105,37 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
When 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, and
an 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 composi
And measuring it fixed raea-web: a model's file is fetched rather than looked for on disk (runtime/scene3d
model.rs), a black page background is the 3D's clear rather than a cover over it (rgb(0, 0, 0) was read as
see-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)
+15
View File
@@ -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);
+7
View File
@@ -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"]
+1
View File
@@ -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).";
+20 -37
View File
@@ -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);
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))?
}
// 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))?;
}
}
Ok(m)
})?;
None => mesh,
};
// the surface (emissive, opacity, unlit, clearcoat, a picture map...) and transform: scene3d
let 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),
+4
View File
@@ -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()])
}
+22 -6
View File
@@ -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));
+4
View File
@@ -76,6 +76,10 @@ pub(crate) fn scene_frames(js: &Path, dir: &Path, upto: i64, whole: bool) -> R<O
let 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)
+9 -1
View File
@@ -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) {
+18
View File
@@ -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 is
fn 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() };
+2
View File
@@ -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"
+4
View File
@@ -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(&reg, path)?;
+5 -6
View File
@@ -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.
+1 -1
View File
@@ -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));
+4 -3
View File
@@ -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);
+14 -6
View File
@@ -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, keyed
row.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) {
+5 -4
View File
@@ -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));
}
+10
View File
@@ -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))));
}
+56 -1
View File
@@ -16,7 +16,62 @@ export const Edit = () => (
);
```
In a project, three and @react-three/fiber are its own: `raea add [email protected]0.0 @react-three/[email protected]`.
In a project, three and @react-three/fiber are its own: `raea add [email protected]5.0 @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>`:
+100 -6
View File
@@ -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]0.0", "", { "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]5.0", "", { "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": ["m[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]0.0", "", {}, "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="],
"three": ["[email protected]5.0", "", {}, "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=="],
}
}
+7 -3
View File
@@ -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]0.0 @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]5.0 @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"
}
}
+5 -3
View File
@@ -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);
}
+3 -1
View File
@@ -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}</>;
}
+98
View File
@@ -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;
}
+17 -3
View File
@@ -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 | unde
if (!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 | unde
colors: 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 */
+36 -8
View File
@@ -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)" },
// lights
AmbientLight: { 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" },
// cameras
Camera: { 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>" }])),
};
+43 -7
View File
@@ -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");
+37 -9
View File
@@ -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 own
const 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 };
+142
View File
@@ -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 };
}
+141 -12
View File
@@ -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: Props
if (!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 };
}
+76 -9
View File
@@ -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, h
const 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);
+260
View File
@@ -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);
}
+189
View File
@@ -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);
}
}
}
}
}
}
+132
View File
@@ -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 }];
}
+130 -2
View File
@@ -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;
+116
View File
@@ -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;
+484
View File
@@ -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;
}
+5 -4
View File
@@ -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-any
export 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 */
+49 -1
View File
@@ -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() }));
+1
View File
@@ -28,6 +28,7 @@ export const KINDS: Record<string, { status: Status; three: string; note?: strin
MeshStandardMaterial: { 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)" },
+9
View File
@@ -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([]);
+251 -140
View File
@@ -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 colour
catch: {
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();
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 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: "#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>
<mesh rotation={[0.3, 0.4, 0]} material={m}>
<sphereGeometry args={[1, 48, 24]} />
</mesh>
);
}
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>
);
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));
}`;
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;
}
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 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 Knot() {
const { scene } = useGLTF("models/knot.glb");
return <primitive object={scene} />;
}
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>
);
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} />;
}
// 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>
);
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} />;
}
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 },
};
+1
View File
@@ -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":{}}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.
+92
View File
@@ -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.
Binary file not shown.
+151
View File
@@ -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 },
};
+2
View File
@@ -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(() => {
+51
View File
@@ -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([]);
});
});
+56
View File
@@ -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] } });
});
});
+193
View File
@@ -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;
}
});
});
+1 -1
View File
@@ -9,7 +9,7 @@ OUT=${1:-$(mktemp -d)}
URL=${R3F_PARITY_URL:-serve}
[ -f wasm/raea_shape_web.js ] || tools/shape-wasm.sh
MIN=${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 it
+11
View File
@@ -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" } });
+1 -1
View File
@@ -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("-");
+21
View File
@@ -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} />);
@@ -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} />);
+17
View File
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
+48
View File
@@ -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} />);
@@ -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} />);
+38
View File
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
@@ -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} />);
+8 -6
View File
@@ -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 channel
expect(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 own
expect(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" />),
);
});
+20
View File
@@ -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("&quot;intensity&quot;: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/);
});
});
+25 -1
View File
@@ -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);
});
});
@@ -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);
@@ -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} />);
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff. Show more