Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

raea 2e9eda9fa

shinyobjectz88ccb8284d12
diff --git a/Cargo.lock b/Cargo.lock
index 2b164980..4ab47796 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14387,6 +14387,7 @@ dependencies = [
"raea-sys-fog-half",
"raea-sys-frame",
"raea-sys-framepass",
+ "raea-sys-grass",
"raea-sys-grid",
"raea-sys-look",
"raea-sys-matchmove",
@@ -14427,6 +14428,7 @@ dependencies = [
"raea-core-wire",
"raea-io-net-calls",
"raea-io-os",
+ "raea-rune-look",
"raea-rune-media",
"raea-rune-page",
"raea-runtime-bundle-lib",
@@ -14436,6 +14438,15 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-rune-look"
+version = "0.1.0"
+dependencies = [
+ "raea-rune-page",
+ "rune",
+ "serde_json",
+]
+
[[package]]
name = "raea-rune-media"
version = "0.1.0"
@@ -15060,6 +15071,16 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-sys-grass"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+ "raea-core-program",
+ "raea-sys-frame",
+ "serde_json",
+]
+
[[package]]
name = "raea-sys-grid"
version = "0.1.0"
@@ -15396,6 +15417,21 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-web"
+version = "0.1.0"
+dependencies = [
+ "bevy",
+ "console_error_panic_hook",
+ "raea-core-scene",
+ "raea-render",
+ "raea-runtime-scene",
+ "raw-window-handle",
+ "serde_json",
+ "wasm-bindgen",
+ "web-sys",
+]
+
[[package]]
name = "rand"
version = "0.8.8"
@@ -15652,6 +15688,9 @@ name = "raw-window-handle"
version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+dependencies = [
+ "wasm-bindgen",
+]
[[package]]
name = "raw-window-metal"
diff --git a/Cargo.toml b/Cargo.toml
index b5f9fc20..111e5a13 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -37,6 +37,7 @@ members = [
"engine/rune",
"engine/rune/page",
"engine/rune/media",
+ "engine/rune/look",
"engine/rune/style",
"engine/page/stage",
"engine/page/window",
@@ -96,6 +97,7 @@ members = [
"systems/fog",
"systems/fog-half",
"systems/volume",
+ "systems/grass",
"systems/fonts",
"systems/image",
"runtime/twins",
@@ -109,6 +111,7 @@ members = [
"engine/render",
"engine/render/raytrace",
"engine/seedling",
+ "engine/web",
"runtime/react",
"bench/bridge",
"bench/bevy-parity",
@@ -191,6 +194,21 @@ strip = "symbols"
# the symbols the stripped player lacks, kept beside it as raea-game.dSYM (never shipped; export-game files it under
# ~/Library/Caches/raea/dsym by UUID for atos against panic.txt and crash.txt)
debug = "line-tables-only"
+# raea-web's wasm (engine/web, docs/web-export.md): what a browser downloads. opt-level s, fat LTO, one codegen unit,
+# no symbols (wasm32 has no unwinding: panics abort). Measured 11-06 on meadow-low in Chrome on the M5 Mac, brotli'd
+# after wasm-opt: z 7.2 MB but frames 6x slower than 3's (1326 ms against 219, the clouds then simulated: z gives up the
+# inlining the ECS's systems need); 3 9.0 MB; s 7.9 MB (with the Bevy features raea-render's `native` holds) at 17 ms a
+# frame, as 3, once the clouds are cards and the frame is the GPU's
+[profile.web]
+inherits = "release"
+incremental = false
+debug = false
+opt-level = "s"
+lto = "fat"
+codegen-units = 1
+panic = "abort"
+strip = "symbols"
+
# crates the player only runs while it loads (image, SVG and audio decoders, the MP4 demuxer, CSG), built for size;
# frame work keeps opt-level 3 (opt-level s for the whole player cost +20-22% frame work: lightspeed R7)
[profile.game.package.zune-jpeg]
diff --git a/LICENSES/bevy_feathers-0.20.0/LICENSE-APACHE b/LICENSES/bevy_feathers-0.20.0/LICENSE-APACHE
deleted file mode 100644
index d9a10c0d..00000000
--- a/LICENSES/bevy_feathers-0.20.0/LICENSE-APACHE
+++ /dev/null
@@ -1,176 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
diff --git a/LICENSES/bevy_feathers-0.20.0/LICENSE-MIT b/LICENSES/bevy_feathers-0.20.0/LICENSE-MIT
deleted file mode 100644
index 9cf10627..00000000
--- a/LICENSES/bevy_feathers-0.20.0/LICENSE-MIT
+++ /dev/null
@@ -1,19 +0,0 @@
-MIT License
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/apps/targets/src/lib.rs b/apps/targets/src/lib.rs
index 2fea0dfc..447ae854 100644
--- a/apps/targets/src/lib.rs
+++ b/apps/targets/src/lib.rs
@@ -7,6 +7,7 @@ pub mod config;
pub mod literal;
pub mod macapp;
pub mod native;
+pub mod portable;
pub mod sign;
pub mod steps;
pub mod verbs;
diff --git a/apps/targets/src/native.rs b/apps/targets/src/native.rs
index 29df82ae..8f292365 100644
--- a/apps/targets/src/native.rs
+++ b/apps/targets/src/native.rs
@@ -42,8 +42,11 @@ pub fn args(a: &Ask) -> Vec<String> {
pub fn run(a: &Ask) -> Result<String, String> {
host(&args(a))?;
- if a.verb != Verb::Bundle {
- return Ok(String::new());
+ match a.verb {
+ Verb::Run => return Ok(String::new()),
+ // the portability report (T4a): anything the host didn't draw or answer fails the check
+ Verb::Check => return crate::portable::verdict(&crate::portable::report(&a.png)?, &a.png),
+ Verb::Bundle => {}
}
// the host makes the .app (signed ad hoc); raea signs it as the developer asks, as it does a web app (T1d)
let out = a.out.clone().unwrap_or_else(|| PathBuf::from(format!("{}.app", crate::verbs::stem(&a.app))));
diff --git a/apps/targets/src/portable.rs b/apps/targets/src/portable.rs
new file mode 100644
index 00000000..73af9ac6
--- /dev/null
+++ b/apps/targets/src/portable.rs
@@ -0,0 +1,41 @@
+//! `raea app check`'s portability report (docs/targets.feature T4a): what the native host couldn't draw or answer,
+//! read from the files raea-rune-host writes beside its frames: unmapped.json (each prop or value with the path of the
+//! first element it was seen on, and why) and unanswered.json (each call the app made that the host refused, why, and
+//! how many times). On the native target any line fails the check; on a web app the native host runs too, and its
+//! report says what native wouldn't draw, without failing.
+
+use std::path::Path;
+
+use serde_json::Value;
+
+/// One line per unmapped prop and per unanswered call, as the host found them in `dir`.
+pub fn report(dir: &Path) -> Result<Vec<String>, String> {
+ let read = |name: &str| -> Result<Vec<Value>, String> {
+ let p = dir.join(name);
+ let text = std::fs::read_to_string(&p).map_err(|e| format!("{}: {e}", p.display()))?;
+ serde_json::from_str(&text).map_err(|e| format!("{}: {e}", p.display()))
+ };
+ let s = |v: &Value, k: &str| v[k].as_str().unwrap_or("").to_string();
+ let mut lines: Vec<String> = read("unmapped.json")?.iter().map(|u| format!("unmapped {}: {} at {} ({})", s(u, "prop"), s(u, "value"), s(u, "path"), s(u, "why"))).collect();
+ for c in read("unanswered.json")? {
+ let n = c["times"].as_u64().unwrap_or(1);
+ lines.push(format!("unanswered {} ({}), {n} time{}", s(&c, "call"), s(&c, "why"), if n == 1 { "" } else { "s" }));
+ }
+ Ok(lines)
+}
+
+/// The native check's verdict on `lines`: ok when there are none, else an error naming each.
+pub fn verdict(lines: &[String], dir: &Path) -> Result<String, String> {
+ if lines.is_empty() {
+ return Ok(String::new());
+ }
+ Err(format!("not portable to native: {} thing{} the Rune host didn't draw or answer (unmapped.json, unanswered.json in {}):\n {}", lines.len(), if lines.len() == 1 { "" } else { "s" }, dir.display(), lines.join("\n ")))
+}
+
+/// A web app's note: what the native target wouldn't draw, or that it would draw everything.
+pub fn note(lines: &[String]) -> String {
+ if lines.is_empty() {
+ return "native: the Rune host draws and answers all of it".into();
+ }
+ format!("native wouldn't draw or answer {} thing{} (the web check still passes):\n {}", lines.len(), if lines.len() == 1 { "" } else { "s" }, lines.join("\n "))
+}
diff --git a/apps/targets/src/verbs.rs b/apps/targets/src/verbs.rs
index 28779db1..b515836e 100644
--- a/apps/targets/src/verbs.rs
+++ b/apps/targets/src/verbs.rs
@@ -3,7 +3,8 @@
//!
//! run a window of its own: Blitz on Bevy for web (raea-page-host's window build), Rune for native
//! check headless (R4b): the mount and each step of `--script` written as PNGs to `--png DIR`, with tree.json (each
-//! frame's elements by data-testid) and unmapped.json (what the target didn't draw)
+//! frame's elements by data-testid), and the portability report (portable.rs, T4a): on native it fails on any
+//! unmapped prop or unanswered call, naming each; on web it says what native wouldn't draw
//! bundle a Mac app, `-o App.app` (the file's name when left out)
//!
//! `raea rune ARGS` is `raea app ARGS --target native`, and its older spellings (`rune --headless APP`) still reach
@@ -16,7 +17,7 @@ use crate::{AppConfig, Target};
pub const USAGE: &str = "usage: raea app run APP.tsx [--target web|native] [--size WxH]\n raea app check APP.tsx [--target web|native] [--script steps.json] [--png DIR] [--size WxH] [--settle N]\n raea app bundle APP.tsx [--target web|native] [-o App.app] [--size WxH] [--identity NAME] [--notarize PROFILE]\n raea rune ... (raea app ... --target native)";
/// What a verb was asked for, after the target is known
-#[derive(Debug)]
+#[derive(Clone, Debug)]
pub struct Ask {
pub verb: Verb,
pub app: PathBuf,
diff --git a/apps/targets/src/web.rs b/apps/targets/src/web.rs
index a27832ad..2633fcb1 100644
--- a/apps/targets/src/web.rs
+++ b/apps/targets/src/web.rs
@@ -46,7 +46,21 @@ pub fn run(a: &Ask) -> Result<String, String> {
let _ = std::fs::remove_dir_all(&dir);
st.success().then(String::new).ok_or(format!("{HOST} exited with {st}"))
}
- Verb::Check => crate::webcheck::check(a),
+ Verb::Check => {
+ let said = crate::webcheck::check(a)?;
+ Ok([said, native_note(a)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join("\n"))
+ }
Verb::Bundle => crate::macapp::web(a),
}
}
+
+/// What the native target wouldn't draw (T4a): the app through raea-rune-host headless too, with the same steps, into
+/// `--png`'s native/. Said, never failed on: a web app is checked against web. A host that can't run says why.
+fn native_note(a: &Ask) -> String {
+ let dir = a.png.join("native");
+ let native = Ask { png: dir.clone(), ..a.clone() };
+ match crate::native::host(&crate::native::args(&native)).and_then(|_| crate::portable::report(&dir)) {
+ Ok(lines) => crate::portable::note(&lines),
+ Err(e) => format!("native: the Rune host couldn't run it headless ({e}), so what native wouldn't draw isn't known"),
+ }
+}
diff --git a/apps/targets/tests/portable.rs b/apps/targets/tests/portable.rs
new file mode 100644
index 00000000..9fed1984
--- /dev/null
+++ b/apps/targets/tests/portable.rs
@@ -0,0 +1,40 @@
+//! T4a: the check's portability report, from the files raea-rune-host writes beside its frames.
+
+use raea_app_targets::portable::{note, report, verdict};
+
+fn dir(unmapped: &str, unanswered: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("raea-t4a-{}-{}", std::process::id(), unmapped.len() * 31 + unanswered.len()));
+ std::fs::create_dir_all(&d).unwrap();
+ std::fs::write(d.join("unmapped.json"), unmapped).unwrap();
+ std::fs::write(d.join("unanswered.json"), unanswered).unwrap();
+ d
+}
+
+#[test]
+fn each_unmapped_prop_and_unanswered_call_is_named() {
+ let d = dir(
+ r#"[{"prop": "transform", "value": "skewX(10deg)", "path": "/div[0]/span[0]", "why": "no skew"}]"#,
+ r#"[{"call": "files.open", "why": "the Rune host has no files.open", "times": 2}]"#,
+ );
+ let lines = report(&d).unwrap();
+ assert_eq!(lines, ["unmapped transform: skewX(10deg) at /div[0]/span[0] (no skew)", "unanswered files.open (the Rune host has no files.open), 2 times"]);
+ // native fails on them, naming each; web only says them
+ let e = verdict(&lines, &d).unwrap_err();
+ assert!(e.starts_with("not portable to native: 2 things") && e.contains("/div[0]/span[0]") && e.contains("files.open"), "{e}");
+ assert!(note(&lines).contains("the web check still passes"));
+}
+
+#[test]
+fn nothing_unmapped_passes() {
+ let d = dir("[]", "[]");
+ let lines = report(&d).unwrap();
+ assert_eq!(verdict(&lines, &d), Ok(String::new()));
+ assert_eq!(note(&lines), "native: the Rune host draws and answers all of it");
+}
+
+#[test]
+fn a_run_with_no_report_is_an_error_not_a_pass() {
+ let d = std::env::temp_dir().join(format!("raea-t4a-none-{}", std::process::id()));
+ std::fs::create_dir_all(&d).unwrap();
+ assert!(report(&d).is_err());
+}
diff --git a/core/program/src/timeline.rs b/core/program/src/timeline.rs
index a36eb0d7..2d72e585 100644
--- a/core/program/src/timeline.rs
+++ b/core/program/src/timeline.rs
@@ -58,8 +58,16 @@ impl Timeline {
}
}
-/// f(0..n) on every core, in order.
+/// f(0..n) on every core, in order. A browser build (wasm32) has one thread and can't spawn more: in turn there.
fn parallel<T: Send>(n: usize, f: impl Fn(usize) -> Result<T, String> + Sync) -> Result<Vec<T>, String> {
+ #[cfg(target_arch = "wasm32")]
+ return (0..n).map(f).collect();
+ #[cfg(not(target_arch = "wasm32"))]
+ parallel_threads(n, f)
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn parallel_threads<T: Send>(n: usize, f: impl Fn(usize) -> Result<T, String> + Sync) -> Result<Vec<T>, String> {
let cores = std::thread::available_parallelism().map(|c| c.get()).unwrap_or(4).min(n.max(1));
let chunk = n.div_ceil(cores.max(1)).max(1);
let parts: Vec<Result<Vec<T>, String>> = std::thread::scope(|s| {
diff --git a/docs/r3f.feature b/docs/r3f.feature
index 14c658e4..8b52255b 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -23,8 +23,8 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
@done
Scenario: R3F2. What is read from three.js
Then input/kinds.ts has a row for every Object3D and Material class three exports (62 in three 0.180):
- 41 drawn, 12 near (a note says what differs), 9 with nothing to draw (a bone, a camera that isn't drawn with,
- a sound, a base class, ShadowMaterial)
+ 42 drawn, 12 near (a note says what differs), 8 with nothing to draw (a bone, a camera that isn't drawn with,
+ a sound, a base class)
And meshes keep their triangles, normals, uvs (v flipped: Bevy counts from the top), vertex colours, geometry
groups (a mesh a material); skinned and morphed meshes are posed on the CPU each frame; an InstancedMesh is
Instances while its copies hold still; Points, Lines, Sprites and three's helpers are drawn
@@ -51,6 +51,10 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
And three/kinds.ts has a row for every kind raea's SDK renders (58): 26 drawn, 11 near, 4 settings, 9 effects
and 8 that are Bevy's own (a WESL shader or frame pass, a compute pass, a Bevy component or resource, an ECS
world read from the engine's tables, volumetric fog and fog volumes)
+ And the 8 that are Bevy's own aren't three.js's to draw: WESL and WGSL run on Bevy's renderer, components,
+ resources and ECS worlds are Bevy's data, and the fogs are raymarched through Bevy's shadow maps and depth. A
+ page that needs them uses raea-web, raea's engine itself in the browser on WebGPU (docs/web-export.md, which
+ says what stays native); Scene3d names each one it leaves out (a warning, and its row)
And a Model with `at` is a copy of the model at each placement, as raea's engine draws it
And raea's default tone mapping, TonyMcMapface, is drawn with Bevy's own LUT (sdk/playable's tony.bin) in a
pass in place of three's output pass; ACES, AgX, Reinhard and none are three's own
@@ -78,8 +82,9 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
composer doesn't draw
And it walks three's exports and fails on an Object3D or Material class missing from input/kinds.ts
And `bun test` in sdk/r3f runs these with the input, round-trip and source-export tests (26 tests)
- And the one class read with nothing drawn on purpose is ShadowMaterial: raea has no shadow-catching surface (a
- surface that shows only the shadows on it) to read it into, which is the engine's gap, not the reader's
+ And a ShadowMaterial is raea's <Mesh shadow="catch">: a surface that shows only the shadows falling on it, in
+ its material's colour and opacity (systems/material shadow_catch.rs in the engine, three's ShadowMaterial in
+ Scene3d)
@done
Scenario: R3F8. Each way held to the other renderer
@@ -93,18 +98,21 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
| 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 |
| 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-catch | <Mesh shadow="catch">, three's ShadowMaterial | 0.9972 |
| 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 |
+ | src-catch | out-catch exported | 0.9972 |
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)
diff --git a/docs/sdk-coverage.md b/docs/sdk-coverage.md
index 4f36366a..c9428957 100644
--- a/docs/sdk-coverage.md
+++ b/docs/sdk-coverage.md
@@ -22,10 +22,10 @@ reaches it yet).
| css | longhand | 241 | 0 | 0 | 51 | 13 | 0 | 1 | 0 | 306 |
| css | shorthand | 59 | 0 | 0 | 12 | 0 | 0 | 0 | 0 | 71 |
| element | html | 113 | 0 | 0 | 0 | 0 | 0 | 18 | 0 | 131 |
-| plugin | declared | 0 | 0 | 49 | 0 | 0 | 24 | 0 | 0 | 73 |
-| **all** | | **468** | **1027** | **49** | **63** | **13** | **24** | **22** | **0** | **1666** |
+| plugin | declared | 0 | 0 | 53 | 0 | 0 | 21 | 0 | 3 | 77 |
+| **all** | | **468** | **1027** | **53** | **63** | **13** | **21** | **22** | **3** | **1670** |
-Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in tools/agents/check) keeps it from dropping.
+Reached (tiers 1-3): **1548**. The ratchet (`tools/sdk-coverage --check`, in tools/agents/check) keeps it from dropping.
## Bevy types (the plugin build's TypeRegistry)
@@ -243,7 +243,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_audio::audio::PlaybackSettings` | component | 2 | bevy.PlaybackSettings (raea/plugins/bevy) |
| `bevy_audio::audio::SpatialListener` | component | 2 | bevy.SpatialListener (raea/plugins/bevy) |
| `bevy_audio::volume::GlobalVolume` | resource | 2 | bevy.GlobalVolume (raea/plugins/bevy) |
-| `bevy_camera::camera::Camera` | component | 1 | PerspectiveCamera (sdk/render/src/3d/lights.tsx) |
+| `bevy_camera::camera::Camera` | component | 1 | Camera3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_camera::camera::CameraMainTextureUsages` | component | 2 | bevy.CameraMainTextureUsages (raea/plugins/bevy) |
| `bevy_camera::camera::Exposure` | component | 1 | ToneMapping (sdk/render/src/3d/effects.tsx) |
| `bevy_camera::camera::MainPassResolutionOverride` | component | 2 | bevy.MainPassResolutionOverride (raea/plugins/bevy) |
@@ -252,7 +252,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_camera::camera::ShadowLodOrigin` | component | 2 | bevy.ShadowLodOrigin (raea/plugins/bevy) |
| `bevy_camera::clear_color::ClearColor` | resource | 2 | bevy.ClearColor (raea/plugins/bevy) |
| `bevy_camera::components::Camera2d` | component | 2 | bevy.Camera2d (raea/plugins/bevy) |
-| `bevy_camera::components::Camera3d` | component | 1 | OrthographicCamera (sdk/render/src/3d/model.tsx), PerspectiveCamera (sdk/render/src/3d/lights.tsx) |
+| `bevy_camera::components::Camera3d` | component | 1 | Camera3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_camera::components::CompositingSpace` | component | 2 | bevy.CompositingSpace (raea/plugins/bevy) |
| `bevy_camera::components::Hdr` | component | 2 | bevy.Hdr (raea/plugins/bevy) |
| `bevy_camera::primitives::Aabb` | component | 2 | bevy.Aabb (raea/plugins/bevy) |
@@ -260,7 +260,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_camera::primitives::CubemapFrusta` | component | 2 | bevy.CubemapFrusta (raea/plugins/bevy) |
| `bevy_camera::primitives::Frustum` | component | 2 | bevy.Frustum (raea/plugins/bevy) |
| `bevy_camera::primitives::Sphere` | component | 2 | bevy.Sphere (raea/plugins/bevy) |
-| `bevy_camera::projection::Projection` | component | 1 | OrthographicCamera (sdk/render/src/3d/model.tsx), PerspectiveCamera (sdk/render/src/3d/lights.tsx) |
+| `bevy_camera::projection::Projection` | component | 1 | Camera3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_camera::visibility::CascadesVisibleEntities` | component | 2 | bevy.CascadesVisibleEntities (raea/plugins/bevy) |
| `bevy_camera::visibility::CubemapVisibleEntities` | component | 2 | bevy.CubemapVisibleEntities (raea/plugins/bevy) |
| `bevy_camera::visibility::DynamicSkinnedMeshBounds` | component | 2 | bevy.DynamicSkinnedMeshBounds (raea/plugins/bevy) |
@@ -272,7 +272,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_camera::visibility::VisibleEntities` | component | 2 | bevy.VisibleEntities (raea/plugins/bevy) |
| `bevy_camera::visibility::VisibleMeshEntities` | component | 2 | bevy.VisibleMeshEntities (raea/plugins/bevy) |
| `bevy_camera::visibility::range::VisibilityRange` | component | 2 | raea/bevy-own |
-| `bevy_camera::visibility::render_layers::RenderLayers` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx) |
+| `bevy_camera::visibility::render_layers::RenderLayers` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_core_pipeline::prepass::DeferredPrepass` | component | 2 | bevy.DeferredPrepass (raea/plugins/bevy) |
| `bevy_core_pipeline::prepass::DeferredPrepassDoubleBuffer` | component | 2 | bevy.DeferredPrepassDoubleBuffer (raea/plugins/bevy) |
| `bevy_core_pipeline::prepass::DepthPrepass` | component | 2 | bevy.DepthPrepass (raea/plugins/bevy) |
@@ -568,21 +568,21 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_input_focus::gained_and_lost::FocusLost` | event | 2 | bevy.FocusLost (raea/plugins/bevy) |
| `bevy_input_focus::tab_navigation::TabGroup` | component | 2 | bevy.TabGroup (raea/plugins/bevy) |
| `bevy_input_focus::tab_navigation::TabIndex` | component | 2 | bevy.TabIndex (raea/plugins/bevy) |
-| `bevy_light::NotShadowCaster` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx) |
-| `bevy_light::NotShadowReceiver` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx) |
+| `bevy_light::NotShadowCaster` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) |
+| `bevy_light::NotShadowReceiver` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_light::ShadowFilteringMethod` | component | 1 | Shadows (sdk/render/src/3d/effects.tsx) |
| `bevy_light::TransmittedShadowReceiver` | component | 2 | raea/bevy-own |
-| `bevy_light::ambient_light::AmbientLight` | component | 1 | AmbientLight (sdk/render/src/3d/lights.tsx) |
+| `bevy_light::ambient_light::AmbientLight` | component | 1 | AmbientLight (sdk/render/src/bevy3d/lights.tsx) |
| `bevy_light::ambient_light::GlobalAmbientLight` | resource | 2 | bevy.GlobalAmbientLight (raea/plugins/bevy) |
| `bevy_light::cascade::CascadeShadowConfig` | component | 1 | Shadows (sdk/render/src/3d/effects.tsx) |
| `bevy_light::cascade::Cascades` | component | 2 | bevy.Cascades (raea/plugins/bevy) |
| `bevy_light::cluster::ClusterConfig` | component | 2 | raea/bevy-own |
| `bevy_light::cluster::ClusteredDecal` | component | 2 | bevy.ClusteredDecal (raea/plugins/bevy) |
-| `bevy_light::directional_light::DirectionalLight` | component | 1 | DirectionalLight (sdk/render/src/3d/lights.tsx) |
+| `bevy_light::directional_light::DirectionalLight` | component | 1 | DirectionalLight (sdk/render/src/bevy3d/lights.tsx) |
| `bevy_light::directional_light::DirectionalLightShadowMap` | resource | 1 | Shadows (sdk/render/src/3d/effects.tsx) |
| `bevy_light::directional_light::DirectionalLightTexture` | component | 2 | bevy.DirectionalLightTexture (raea/plugins/bevy) |
| `bevy_light::gizmos::ShowLightGizmo` | component | 2 | bevy.ShowLightGizmo (raea/plugins/bevy) |
-| `bevy_light::point_light::PointLight` | component | 1 | PointLight (sdk/render/src/3d/lights.tsx) |
+| `bevy_light::point_light::PointLight` | component | 1 | PointLight (sdk/render/src/bevy3d/lights.tsx) |
| `bevy_light::point_light::PointLightShadowMap` | resource | 1 | Shadows (sdk/render/src/3d/effects.tsx) |
| `bevy_light::point_light::PointLightTexture` | component | 2 | bevy.PointLightTexture (raea/plugins/bevy) |
| `bevy_light::probe::EnvironmentMapLight` | component | 1 | Environment (sdk/render/src/3d/effects.tsx) |
@@ -591,8 +591,8 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_light::probe::LightProbe` | component | 2 | bevy.LightProbe (raea/plugins/bevy) |
| `bevy_light::probe::ParallaxCorrection` | component | 2 | bevy.ParallaxCorrection (raea/plugins/bevy) |
| `bevy_light::probe::Skybox` | component | 1 | Environment (sdk/render/src/3d/effects.tsx) |
-| `bevy_light::rect_light::RectLight` | component | 1 | RectAreaLight (sdk/render/src/3d/lights.tsx) |
-| `bevy_light::spot_light::SpotLight` | component | 1 | SpotLight (sdk/render/src/3d/lights.tsx) |
+| `bevy_light::rect_light::RectLight` | component | 1 | RectLight (sdk/render/src/bevy3d/lights.tsx) |
+| `bevy_light::spot_light::SpotLight` | component | 1 | SpotLight (sdk/render/src/bevy3d/lights.tsx) |
| `bevy_light::spot_light::SpotLightTexture` | component | 2 | bevy.SpotLightTexture (raea/plugins/bevy) |
| `bevy_light::volumetric::FogVolume` | component | 1 | FogVolume (sdk/render/src/3d/effects.tsx) |
| `bevy_light::volumetric::VolumetricFog` | component | 1 | VolumetricFog (sdk/render/src/3d/effects.tsx) |
@@ -604,9 +604,9 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_materialize::generic_material::GenericMaterial3d` | component | 2 | trenchbroom.GenericMaterial3d (raea/plugins/trenchbroom) |
| `bevy_materialize::generic_material::GenericMaterialApplied` | component | 2 | trenchbroom.GenericMaterialApplied (raea/plugins/trenchbroom) |
| `bevy_mesh::components::Mesh2d` | component | 1 | Shape2D (sdk/render/src/3d/sprite.tsx) |
-| `bevy_mesh::components::Mesh3d` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx), ShaderMesh (sdk/render/src/3d/bevy.tsx) |
+| `bevy_mesh::components::Mesh3d` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_mesh::components::MeshTag` | component | 2 | bevy.MeshTag (raea/plugins/bevy) |
-| `bevy_mesh::mesh::Mesh` | asset | 1 | BufferMesh (sdk/render/src/3d/shapes.tsx), Mesh (sdk/render/src/3d/shapes.tsx) |
+| `bevy_mesh::mesh::Mesh` | asset | 1 | BufferMesh (sdk/render/src/3d/shapes.tsx) |
| `bevy_mesh::morph::MeshMorphWeights` | component | 2 | bevy.MeshMorphWeights (raea/plugins/bevy) |
| `bevy_mesh::morph::MorphWeights` | component | 2 | bevy.MorphWeights (raea/plugins/bevy) |
| `bevy_mesh::skinning::SkinnedMesh` | component | 2 | bevy.SkinnedMesh (raea/plugins/bevy) |
@@ -624,8 +624,8 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_look::paint::Paint>>` | component | 2 | bevy.MeshMaterial3dExtendedMaterialStandardMaterialPaint (raea/plugins/bevy) |
| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_material::toon::ToonExt>>` | component | 2 | bevy.MeshMaterial3dExtendedMaterialStandardMaterialToonExt (raea/plugins/bevy) |
| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_shader::ShaderExt>>` | component | 1 | SurfaceShader (sdk/render/src/3d/materials.tsx) |
-| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_wear::Wear>>` | component | 1 | MeshStandardMaterial (sdk/render/src/3d/materials.tsx) |
-| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::pbr_material::StandardMaterial>` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx) |
+| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_wear::Wear>>` | component | 1 | WearExtension (sdk/render/src/bevy3d/materials.tsx) |
+| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::pbr_material::StandardMaterial>` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) |
| `bevy_pbr::mesh_material::MeshMaterial3d<bevy_trenchbroom::special_textures::QuakeSkyMaterial>` | component | 2 | bevy.MeshMaterial3dQuakeSkyMaterial (raea/plugins/bevy) |
| `bevy_pbr::mesh_material::MeshMaterial3d<raea_sys_fog::fire::FireMaterial>` | component | 2 | bevy.MeshMaterial3dFireMaterial (raea/plugins/bevy) |
| `bevy_pbr::mesh_material::MeshMaterial3d<raea_sys_look::look::LookMaterial>` | component | 2 | bevy.MeshMaterial3dLookMaterial (raea/plugins/bevy) |
@@ -637,7 +637,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_pbr::mesh_material::MeshMaterial3d<raea_sys_splat::SplatMaterial>` | component | 2 | bevy.MeshMaterial3dSplatMaterial (raea/plugins/bevy) |
| `bevy_pbr::mesh_material::MeshMaterial3d<raea_sys_volume::VolumeMaterial>` | component | 2 | bevy.MeshMaterial3dVolumeMaterial (raea/plugins/bevy) |
| `bevy_pbr::meshlet::MeshletMesh3d` | component | 2 | bevy.MeshletMesh3d (raea/plugins/bevy) |
-| `bevy_pbr::pbr_material::StandardMaterial` | asset | 1 | MeshBasicMaterial (sdk/render/src/3d/materials.tsx), MeshPhysicalMaterial (sdk/render/src/3d/materials.tsx), MeshStandardMaterial (sdk/render/src/3d/materials.tsx) |
+| `bevy_pbr::pbr_material::StandardMaterial` | asset | 1 | StandardMaterial (sdk/render/src/bevy3d/materials.tsx) |
| `bevy_pbr::ssao::ScreenSpaceAmbientOcclusion` | component | 1 | AmbientOcclusion (sdk/render/src/3d/effects.tsx) |
| `bevy_pbr::ssr::ScreenSpaceReflections` | component | 2 | raea/bevy-own |
| `bevy_pbr::transmission::ScreenSpaceTransmission` | component | 2 | bevy.ScreenSpaceTransmission (raea/plugins/bevy) |
@@ -882,7 +882,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `bevy_time_runner::time_span::TimeSpan` | component | 2 | tween.TimeSpan (raea/plugins/tween) |
| `bevy_time_runner::time_span::TimeSpanProgress` | component | 2 | tween.TimeSpanProgress (raea/plugins/tween) |
| `bevy_transform::components::global_transform::GlobalTransform` | component | 2 | bevy.GlobalTransform (raea/plugins/bevy) |
-| `bevy_transform::components::transform::Transform` | component | 1 | Mesh (sdk/render/src/3d/shapes.tsx), Transform (sdk/app/src/bevy/systems.ts) |
+| `bevy_transform::components::transform::Transform` | component | 1 | Transform (sdk/app/src/bevy/systems.ts) |
| `bevy_transform::components::transform::TransformTreeChanged` | component | 2 | bevy.TransformTreeChanged (raea/plugins/bevy) |
| `bevy_transform_interpolation::NoRotationEasing` | component | 2 | avian.NoRotationEasing (raea/plugins/avian) |
| `bevy_transform_interpolation::NoScaleEasing` | component | 2 | avian.NoScaleEasing (raea/plugins/avian) |
@@ -1143,6 +1143,9 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `common_assets` | declared | 3 | raea.plugins: "common_assets" (bevy_common_assets) |
| `embedded_assets` | declared | blocked upstream | bevy_embedded_assets's latest release (0.16.0) is on bevy ^0.19. Exit: a release of bevy_embedded_assets on Bevy 0.20 |
| `obj` | declared | 3 | raea.plugins: "obj" (bevy_obj) |
+| `asset_loader` | declared | 3 | raea.plugins: "asset_loader" (bevy_asset_loader): compiled in, no Plugin to register |
+| `progress` | declared | 3 | raea.plugins: "progress" (iyes_progress): compiled in, no Plugin to register |
+| `save` | declared | 3 | raea.plugins: "save" (moonshine-save): compiled in, no Plugin to register |
| `svg` | declared | blocked upstream | bevy_svg's latest release (0.19.0) is on bevy ^0.19. Exit: a release of bevy_svg on Bevy 0.20 |
| `vox` | declared | 3 | raea.plugins: "vox" (bevy_vox_scene) |
| `aseprite` | declared | 3 | raea.plugins: "aseprite" (bevy_aseprite_ultra) |
@@ -1173,10 +1176,10 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `flair` | declared | 3 | raea.plugins: "flair" (bevy_flair) |
| `text_input` | declared | blocked upstream | bevy_simple_text_input's latest release (0.15.0) is on bevy ^0.19.0. Exit: a release of bevy_simple_text_input on Bevy 0.20 |
| `ui_anchor` | declared | blocked upstream | bevy_ui_anchor's latest release (0.12.0) is on bevy ^0.19.0. Exit: a release of bevy_ui_anchor on Bevy 0.20 |
-| `navigator` | declared | blocked upstream | vleue_navigator's latest release (0.16.0) is on bevy ^0.19.1. Exit: a release of vleue_navigator on Bevy 0.20 |
-| `northstar` | declared | blocked upstream | bevy_northstar's latest release (0.7.0) is on bevy ^0.19. Exit: a release of bevy_northstar on Bevy 0.20 |
+| `navigator` | declared | unmapped | vleue_navigator: declared for 0.20, not registered in the plugin build |
+| `northstar` | declared | unmapped | bevy_northstar: declared for 0.20, not registered in the plugin build |
| `tween` | declared | 3 | raea.plugins: "tween" (bevy_tween) |
-| `easings` | declared | blocked upstream | bevy_easings's latest release (0.19.0) is on bevy ^0.19.0. Exit: a release of bevy_easings on Bevy 0.20 |
+| `easings` | declared | unmapped | bevy_easings: declared for 0.20, not registered in the plugin build |
| `animation_graph` | declared | blocked upstream | bevy_animation_graph's latest release (0.11.0) is on bevy ^0.19. Exit: a release of bevy_animation_graph on Bevy 0.20 |
| `lookup_curve` | declared | 3 | raea.plugins: "lookup_curve" (bevy_lookup_curve) |
| `ik` | declared | blocked upstream | bevy_mod_inverse_kinematics's latest release (0.12.0) is on bevy ^0.19. Exit: a release of bevy_mod_inverse_kinematics on Bevy 0.20 |
@@ -1194,6 +1197,7 @@ Reached (tiers 1-3): **1544**. The ratchet (`tools/sdk-coverage --check`, in too
| `yarn` | declared | blocked upstream | bevy_yarnspinner's latest release (0.9.0) is on bevy ^0.19. Exit: a release of bevy_yarnspinner on Bevy 0.20 |
| `yoleck` | declared | 3 | raea.plugins: "yoleck" (bevy-yoleck) |
| `trenchbroom` | declared | 3 | raea.plugins: "trenchbroom" (bevy_trenchbroom) |
+| `swatch` | declared | 3 | raea.plugins: "swatch" (raea-bench-swatch): compiled in, no Plugin to register |
## CSS properties (stylo, servo)
diff --git a/docs/web-export.md b/docs/web-export.md
index 96774d2c..afc37a53 100644
--- a/docs/web-export.md
+++ b/docs/web-export.md
@@ -45,3 +45,66 @@ the mixer, Core ML and ONNX Runtime, SQLite and the native calls, the GPU kernel
wasm32 standard library.
- A browser gives WebGPU on recent Chrome, Edge and Safari; the export should say so on a browser without it rather
than fall back to a slower path.
+
+## Rows are the contract; Bevy is the reference
+
+The page and the engine agree on rows, nothing else: the page's `data-3d` parts become rows (runtime/scene's LiveScene,
+the same code native live play runs), and raea-web sets them on raea-render as the native engine does. So a frame in
+a browser is the frame `raea render` draws, and Bevy's own examples stay the reference for what a row means (docs/
+control.feature). Any other host that draws rows is a host of the same edits.
+
+## Measured (meadow-low, 11-06)
+
+Chrome on the M5 Pro Mac, headless (tools in the site lab: webshot.ts), the meadow's composition at 1920x1080 with its
+paint look's 4 px cells:
+
+| | before | now | budget |
+|---|---|---|---|
+| raea_web.wasm, wasm-opt'd and brotli'd | 10.3 MB | 7.9 MB | 8 MB |
+| first live frame | 4.8 s | 1.3-1.5 s | 3 s |
+| a frame | 219 ms | 14-17 ms | 16.7 ms (60 fps) |
+
+What got it there, biggest first:
+
+- **Clouds baked into cards.** A `<Volume>` cloud simulates and raymarches every frame (two thirds of a frame here, and
+ the 4 s of simulation before the first). Each cloud is rendered once natively, lit and in the look, as meadow-low's
+ camera sees it, and the page shows the picture on an `<ImagePlane cutout>` facing the camera: no surface where it's
+ clear, a shadow in its shape.
+- **A mesh's vertex data written once.** `<BufferMesh>` checked and wrote its arrays as text every React render (half
+ a frame for a terrain and its flowers); it's kept per mesh's arrays now.
+- **Drawn at the look's cell size.** `play({ pixel: 4 })` draws at a quarter of the composition's size, a `<Look>`'s
+ cell becomes one drawn pixel, and the canvas is that size, scaled up by the browser with hard pixels
+ (`image-rendering: pixelated`): the GPU shades a sixteenth of the pixels and blits nothing.
+- **One shadow cascade** (`<Shadows cascades={1}>`), for phones.
+- **The web profile** (root Cargo.toml): opt-level s, fat LTO, one codegen unit, abort, stripped. z is 7.2 MB but its
+ frames are 6x slower (the ECS's systems want inlining); 3 is 9.0 MB at the same frame as s. Bevy's built-in font,
+ JPEG, SMAA's and area lights' tables and gamepads are raea-render's `native` features, so a page goes without them.
+
+A browser frame against `raea render --frame 0` of the same composition (`play({ hold: 0 })`, both box-filtered to
+480x270, the page's labels cropped off): SSIM 0.9985 drawn at the composition's size (`pixel: 1`), so the engine in a
+page draws what it draws natively; 0.903 at `pixel: 4`, where a cell is one drawn pixel instead of the mean of 4x4
+(the same scene, framing and light; the grass's texture is sampled differently).
+
+Still to measure: an iPad in Safari (30 fps) and the poster's first paint (1.5 s).
+
+## Sound
+
+In a page raea/tone is Tone.js (the page's bundler maps `raea/tone` to `tone`), so an edit's sound is written once in
+Tone's API: a render mixes it on raea's core, a page plays it through Web Audio. A browser starts audio only after a
+gesture, and a touch counts as one only when the finger lifts (pointerup, touchend), never on pointerdown: the page
+starts Tone on any of them and keeps listening until the context runs. The meadow's bed (wind and birds) is
+site-lab/raea/chair/meadow-sound.ts.
+
+Two gaps of raea/tone against Tone.js, found writing it (worked around there, to build properly):
+
+- A ramp starts at its callback's time, not at the event before it, so several ramps scheduled in one callback start
+ together and the last wins.
+- A Synth's `frequency` automation doesn't move a note that's sounding (the chirps' sweeps are MembraneSynth's own).
+
+## Next
+
+- **three.js as a second, light web host.** The rows are the contract, so a host that draws rows with three.js (a few
+ hundred KB, no wasm) can play the same edits wherever raea-web is too heavy, with raea-web as its reference.
+- **R3F both ways.** Authoring in React Three Fiber compiled to rows, so an R3F scene plays on raea's engines; and an
+ edit exported back out as R3F components, so a team can take a raea scene into its own three.js app. One edit,
+ several targets.
diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.toml
index 30818104..1a4b47d4 100644
--- a/engine/render/Cargo.toml
+++ b/engine/render/Cargo.toml
@@ -13,8 +13,8 @@ raea-sys-frame = { path = "../../systems/frame" }
raea-sys-splat = { path = "../../systems/splat" }
raea-sys-sprite = { path = "../../systems/sprite" }
raea-sys-rt = { path = "../../systems/rt" }
-# experimental_pbr_pcss: soft shadows (a light's softShadow in raea/3d; raea-runtime-scene3d's light)
-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", "bevy_gilrs"] }
+# soft shadows (experimental_pbr_pcss) are under the native feature with raea-runtime-scene3d/pcss: WebGPU refuses their sampling
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "multi_threaded", "3d_bevy_render", "ui_bevy_render", "png", "tonemapping_luts", "ktx2", "zstd_rust"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] }
# an edit as rows keyed per frame, and 3D shapes as values (docs/media.feature M2)
raea-core-program = { path = "../../core/program" }
@@ -43,10 +43,12 @@ raea-sys-post = { path = "../../systems/post" }
raea-sys-fog = { path = "../../systems/fog" }
raea-sys-fog-half = { path = "../../systems/fog-half" }
raea-sys-volume = { path = "../../systems/volume" }
+# a field of grass made in tiles by distance (<Grass>)
+raea-sys-grass = { path = "../../systems/grass" }
serde_json = { version = "1", features = ["float_roundtrip"] }
# the direct render's views, the 2D rows, clips' masks and the paint device (runtime/view)
raea-runtime-view = { path = "../../runtime/view", optional = true }
-raea-sys-page = { path = "../../systems/page" }
+raea-sys-page = { path = "../../systems/page", optional = true }
# the shared device; its passes' errors, stalls and latency in the run's trace, as raea-render's
raea-gpu-device = { path = "../../gpu/device", optional = true }
raea-io-trace = { path = "../../io/trace", optional = true }
@@ -61,8 +63,9 @@ raea-render-raytrace = { path = "raytrace", optional = true }
[features]
# native: everything that only exists to render on the machine itself (clips' decoders, the GPU frame path and its
-# traces, the direct views); without it raea-render is the program format and the 3D engine, which is what a browser build needs (docs/web-export.md, milestone 1)
-native = ["dep:raea-runtime-gpuframe", "dep:raea-runtime-view", "raea-sys-matchmove/native", "raea-sys-frame/native", "raea-sys-splat/native", "raea-sys-material/native", "raea-sys-text3d/native", "dep:raea-io-media", "dep:raea-gpu-device", "dep:raea-io-trace"]
+# traces, the direct views, and Bevy's built-in font, JPEG, SMAA's and area lights' tables and gamepads, which a
+# page's download goes without); without it raea-render is the program format and the 3D engine, which is what a browser build needs (docs/web-export.md, milestone 1)
+native = ["bevy/default_font", "bevy/jpeg", "bevy/smaa_luts", "bevy/area_light_luts", "bevy/bevy_gilrs", "dep:raea-sys-page", "bevy/experimental_pbr_pcss", "raea-runtime-scene3d/pcss", "dep:raea-runtime-gpuframe", "dep:raea-runtime-view", "raea-sys-matchmove/native", "raea-sys-frame/native", "raea-sys-splat/native", "raea-sys-material/native", "raea-sys-text3d/native", "dep:raea-io-media", "dep:raea-gpu-device", "dep:raea-io-trace"]
# web: the 3D engine on WebGPU in a browser (wasm32-unknown-unknown, without native)
web = ["bevy/webgpu"]
# AV1 (dav1d decode, rav1e encode) as a media backend: on by default; an exported game's player goes without it
diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rs
index b3e36b14..c715db23 100644
--- a/engine/render/src/engine.rs
+++ b/engine/render/src/engine.rs
@@ -28,6 +28,7 @@ use raea_core_program::ir::{Program, V};
use raea_runtime_gpuframe::{nv12::*, overlay::*, pool::*};
mod spawn;
pub use spawn::*;
+pub use open::Opening;
// the 2D rows as the page reads them, and the paint device as Bevy's renderer (raea-runtime-view)
#[cfg(feature = "native")]
use raea_runtime_view::rows::*;
@@ -78,6 +79,7 @@ mod screens;
use raea_sys_volume as volume;
// meshes that cast shadows without being drawn (<Mesh shadow="only">)
use raea_sys_material::shadow_only;
+use raea_sys_material::shadow_catch;
// baked simulations played back by the frame (<MeshSequence>, <Goo>) and glitches on any part (physics.tsx)
use raea_sys_meshseq as meshseq;
// toon (cel) surfaces and their ink outlines (<MeshToonMaterial>)
@@ -128,11 +130,11 @@ pub struct Engine {
/// <phase>", to line up with a memory timeline (the footprint is the process's, as the OS counts it).
pub fn mem_mark(what: &str) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
- static T0: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
+ static T0: std::sync::OnceLock<bevy::platform::time::Instant> = std::sync::OnceLock::new();
if !*ON.get_or_init(|| std::env::var_os("RAEA_MEM_MARKS").is_some()) {
return;
}
- let t = T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f64() * 1e3;
+ let t = T0.get_or_init(bevy::platform::time::Instant::now).elapsed().as_secs_f64() * 1e3;
let mb = phys_footprint().map(|b| format!("{:.1}", b as f64 / 1048576.0)).unwrap_or_else(|| "?".into());
eprintln!("mem_mark {t:.1} {mb} {what}");
}
@@ -140,7 +142,7 @@ pub fn mem_mark(what: &str) {
/// The edit has 3D rows (a light or a mesh): its camera draws through the 3D pipeline, and the Apple encoder runs
/// real-time for it.
pub fn has_3d(rows: &[Tup]) -> bool {
- rows.iter().any(|t| matches!(t.kind.as_str(), "light" | "cube" | "sphere" | "plane" | "panel" | "decal" | "mesh" | "model" | "fogvolume" | "fire" | "plate" | "splat" | "meshseq" | "entity" | "text" | "glyph"))
+ rows.iter().any(|t| matches!(t.kind.as_str(), "light" | "cube" | "sphere" | "plane" | "panel" | "decal" | "mesh" | "model" | "fogvolume" | "fire" | "grass" | "plate" | "splat" | "meshseq" | "entity" | "text" | "glyph"))
}
/// RAEA_MEM_MARKS_EVERY: frames between render marks (default 100).
@@ -172,6 +174,13 @@ pub fn phys_footprint() -> Option<u64> {
/// retried by Bevy as before; only those being compiled are waited on.
fn wait_pipelines(mut cache: ResMut<bevy::render::render_resource::PipelineCache>) {
use bevy::render::render_resource::CachedPipelineState;
+ // a browser compiles them asynchronously, on its own event loop: a live frame there draws what's made
+ #[cfg(target_arch = "wasm32")]
+ {
+ cache.process_queue();
+ return;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
loop {
cache.process_queue();
if !cache.pipelines().any(|p| matches!(p.state, CachedPipelineState::Creating(_))) {
@@ -328,6 +337,16 @@ impl Engine {
self.app.world()
}
+ /// The App's World, to change (raea-web: its canvas window and the camera that shows the target on it).
+ pub fn world_mut(&mut self) -> &mut World {
+ self.app.world_mut()
+ }
+
+ /// The image every frame is drawn into (w x h, and the tag row under it).
+ pub fn target_image(&self) -> Handle<Image> {
+ self.target.clone()
+ }
+
/// What went wrong drawing a live frame (a model that failed to load, a row that didn't spawn), taken: a live
/// engine's `draw` keeps going without it, so its caller says it.
pub fn take_error(&mut self) -> Option<String> {
diff --git a/engine/render/src/engine/open.rs b/engine/render/src/engine/open.rs
index 0b6fc0a8..9f3a79dd 100644
--- a/engine/render/src/engine/open.rs
+++ b/engine/render/src/engine/open.rs
@@ -2,10 +2,43 @@
use super::*;
+/// An Engine half made: its App's plugins added, the renderer not yet known to be up. Natively it always is; in a
+/// browser the GPU device comes asynchronously, so the page asks `ready` each animation frame before `finish`.
+pub struct Opening {
+ app: App,
+ prog: Program,
+ inserted: Vec<Tup>,
+ dir: PathBuf,
+ timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>,
+ live: bool,
+}
+
+impl Opening {
+ /// The App's plugins are ready to finish (the render device made).
+ pub fn ready(&mut self) -> bool {
+ self.app.plugins_state() == bevy::app::PluginsState::Ready
+ }
+
+ /// The App's World before it's finished (raea-web adds its canvas window here).
+ pub fn world_mut(&mut self) -> &mut World {
+ self.app.world_mut()
+ }
+
+ /// The rest of the Engine made: plugins finished, target, readback, the program loaded.
+ pub fn finish(self) -> Result<Engine, String> {
+ let Opening { app, prog, inserted, dir, timeline, live } = self;
+ Engine::finish_build(app, &prog, &inserted, &dir, timeline, live)
+ }
+}
+
impl Engine {
pub(crate) fn build(prog: &Program, inserted: &[Tup], dir: &Path, timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>, live: bool) -> Result<Engine, String> {
- let ss = supersampling(live);
- let (w, h) = (prog.width * ss, prog.height * ss);
+ Engine::begin(prog, inserted, dir, timeline, live)?.finish()
+ }
+
+ /// An Engine started, its plugins added: finished by `Opening::finish` once `ready` (a browser's GPU device comes
+ /// asynchronously). `live` as `new_live`'s (raea-web passes no timeline and true).
+ pub fn begin(prog: &Program, inserted: &[Tup], dir: &Path, timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>, live: bool) -> Result<Opening, String> {
mem_mark("engine: new");
let mut app = App::new();
let group = DefaultPlugins
@@ -155,6 +188,12 @@ impl Engine {
app.insert_non_send(Media { backend, decoders: HashMap::new(), dir: dir.to_path_buf() });
}
mem_mark("engine: plugins built (DefaultPlugins, the render device)");
+ Ok(Opening { app, prog: prog.clone(), inserted: inserted.to_vec(), dir: dir.to_path_buf(), timeline, live })
+ }
+
+ fn finish_build(mut app: App, prog: &Program, inserted: &[Tup], dir: &Path, timeline: Option<std::sync::Arc<raea_core_program::timeline::Timeline>>, live: bool) -> Result<Engine, String> {
+ let ss = supersampling(live);
+ let (w, h) = (prog.width * ss, prog.height * ss);
app.finish();
mem_mark("engine: plugins finished");
// RT4: MetalFX's denoiser goes in after Solari's lighting, which Solari's plugin adds as it finishes
diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rs
index d3f16a8d..0af82ef0 100644
--- a/engine/render/src/engine/raea_plugins.rs
+++ b/engine/render/src/engine/raea_plugins.rs
@@ -61,7 +61,9 @@ raea_plugin! {
PassesPlugin: super::passes::install, "Render passes per view (passes.rs).";
TracedAoPlugin: super::traced_ao::install, "Traced ambient occlusion (raea-sys-rt's traced_ao.rs).";
VolumePlugin: super::volume::install, "Simulated smoke, clouds and contrails, raymarched (volume.rs).";
+ GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";
ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";
+ 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).";
FramePassPlugin: raea_sys_framepass::install, "Full-screen passes written in TypeScript (raea-sys-framepass).";
diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rs
index 23c1cbf1..d772a497 100644
--- a/engine/render/src/engine/spawn.rs
+++ b/engine/render/src/engine/spawn.rs
@@ -27,7 +27,7 @@ pub(crate) fn relational(edit: Res<Edit>, clock: Res<Clock>, mut err: ResMut<Err
if frame.live.is_some() {
return;
}
- let t0 = std::time::Instant::now();
+ let t0 = bevy::platform::time::Instant::now();
frame.cols = edit.timeline.cols(clock.0);
frame.parse_looks();
st.rules += t0.elapsed().as_nanos() as u64;
@@ -36,7 +36,7 @@ pub(crate) fn relational(edit: Res<Edit>, clock: Res<Clock>, mut err: ResMut<Err
/// The kinds a row spawns as a thing in the 3D scene (spawn_3d).
pub(crate) fn is_3d_spawn(kind: &str) -> bool {
- matches!(kind, "light" | "model" | "cube" | "sphere" | "plane" | "mesh" | "panel" | "decal" | "fogvolume" | "fire" | "plate" | "splat" | "meshseq" | "entity" | "text" | "glyph" | "screenpage" | "sprite" | "shape2d")
+ matches!(kind, "light" | "model" | "cube" | "sphere" | "plane" | "mesh" | "panel" | "decal" | "fogvolume" | "fire" | "grass" | "plate" | "splat" | "meshseq" | "entity" | "text" | "glyph" | "screenpage" | "sprite" | "shape2d")
}
/// A 3D row's entity made what it draws (a light, a model, a mesh with its surface, a panel): what a load does for each
@@ -48,7 +48,9 @@ pub(crate) fn spawn_camera(world: &mut World, e: Entity, vals: &BTreeMap<String,
let g = |k: &str, d: f32| num(vals, k, d);
world.entity_mut(e).insert((
Camera3d::default(),
- Camera { clear_color: ClearColorConfig::Custom(colour(vals.get("bg"), [0.05, 0.04, 0.1, 1.0])), ..default() },
+ // the row's `bg` when it has one (a live scene's clear, a page export's), else Bevy's ClearColor resource, which
+ // <BevyResource type="bevy_camera::clear_color::ClearColor"> sets (docs/control conventions C17)
+ Camera { clear_color: vals.get("bg").map_or(ClearColorConfig::Default, |b| ClearColorConfig::Custom(colour(Some(b), [0.0, 0.0, 0.0, 1.0]))), ..default() },
target,
// ambient occlusion can't multisample, and SMAA or FXAA replace it (scene3d); composition passes read a
// single-sampled prepass (compose.rs)
@@ -187,6 +189,8 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
"fogvolume" => scene3d::fog_volume(world, e, &t.id, vals),
// a flame drawn as a volume (<Fire>): fire.rs
"fire" => fire::spawn(world, e, vals),
+ // a field of grass (<Grass>): systems/grass
+ "grass" => raea_sys_grass::spawn(world, e, vals)?,
// gaussian splats (<Splat>): splat.rs
"splat" => splat::spawn(world, e, t, inserted, dir)?,
// a bare Bevy entity (<Entity>): placed, and given Bevy's own components by its component rows (plugins.rs)
@@ -267,6 +271,9 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
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) {
+ // `shadow: "catch"`: only the shadows falling on it, in its colour and opacity (shadow_catch.rs)
+ grid::put(world, e, mesh, shadow_catch::ShadowCatchMaterial::of(&mat), vals);
} else if vals.contains_key("toon") {
// a MeshToonMaterial: the surface lit in bands over the standard one, and its ink outline (toon.rs)
world.entity_mut(e).insert((Mesh3d(mesh.clone()), transform_of(vals)));
@@ -350,8 +357,9 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup],
base_color_texture: Some(tex),
unlit: true,
// premultiplied (mip_chain): interpolating straight colour and alpha apart and multiplying them
- // after isn't linear in the sample position, so a moving edge's centroid wobbled (0.10 px)
- alpha_mode: AlphaMode::Premultiplied,
+ // after isn't linear in the sample position, so a moving edge's centroid wobbled (0.10 px). A cut-out
+ // card (`cutout`) is no surface where its picture is clear, and shadows in its picture's shape
+ alpha_mode: if g("cutout", 0.0) > 0.0 { AlphaMode::Mask(0.5) } else { AlphaMode::Premultiplied },
cull_mode: None,
double_sided: true,
uv_transform: scene3d::sheet_uv(g("sheet_frame", 0.0), cols, rows),
diff --git a/engine/rune/Cargo.toml b/engine/rune/Cargo.toml
index 562e5a36..d1567293 100644
--- a/engine/rune/Cargo.toml
+++ b/engine/rune/Cargo.toml
@@ -16,6 +16,7 @@ raea-io-os = { path = "../../io/os" }
raea-runtime-jsengine = { path = "../../runtime/jsengine" }
raea-rune-page = { path = "page" }
raea-rune-media = { path = "media" }
+raea-rune-look = { path = "look" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
png = "0.18"
diff --git a/engine/rune/look/Cargo.toml b/engine/rune/look/Cargo.toml
new file mode 100644
index 00000000..b782efc1
--- /dev/null
+++ b/engine/rune/look/Cargo.toml
@@ -0,0 +1,12 @@
+[package]
+name = "raea-rune-look"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "The native target's page as a check reads it (docs/targets.feature R4b, T3e): the element tree Rune drew, and each element's look (box, colours in 8-bit sRGB, border, outline, shadows, opacity, focus) as Chrome's computed style gives it"
+
+[dependencies]
+rune.workspace = true
+raea-rune-page = { path = "../page" }
+serde_json = "1"
diff --git a/engine/rune/page/src/dump.rs b/engine/rune/look/src/dump.rs
similarity index 82%
rename from engine/rune/page/src/dump.rs
rename to engine/rune/look/src/dump.rs
index 8e2b25bd..428b9456 100644
--- a/engine/rune/page/src/dump.rs
+++ b/engine/rune/look/src/dump.rs
@@ -1,15 +1,17 @@
//! The element tree as an agent checks it (R4b): each wire element Rune drew, with its wire id, Rune key, role,
-//! label, text and box, in paint order.
+//! label, text and box, in paint order, and its look (look.rs, T3e).
use serde_json::{Value, json};
-use crate::session::Session;
+use raea_rune_page::session::Session;
/// The tree after the last frame.
pub fn tree(s: &Session) -> Value {
let els = s.rt.elements();
let ids: Vec<Option<u64>> = els.iter().map(|e| e.key.as_deref().and_then(|k| k.strip_prefix('w')).and_then(|k| k.parse().ok())).collect();
let mut out = Vec::new();
+ let looks = s.rt.state.looks.borrow();
+ let live = s.rt.state.live(false);
for (i, e) in els.iter().enumerate() {
let Some(id) = ids[i] else { continue };
if e.exiting {
@@ -18,7 +20,7 @@ pub fn tree(s: &Session) -> Value {
let n = s.rt.state.tree.get(id);
// the text under it: its own text elements' strings, as Rune drew them
let text: String = els.iter().enumerate().filter(|(j, k)| ids[*j].is_none() && nearest(&els, &ids, *j) == Some(i) && k.text.is_some()).filter_map(|(_, k)| k.text.clone()).collect::<Vec<_>>().join(" ");
- let mut v = json!({"id": id, "key": e.key, "kind": n.map(|n| n.kind.clone()), "rect": crate::session::shown(e).map(|x| (x * 100.0).round() / 100.0)});
+ let mut v = json!({"id": id, "key": e.key, "kind": n.map(|n| n.kind.clone()), "rect": raea_rune_page::session::shown(e).map(|x| (x * 100.0).round() / 100.0)});
if !e.role.is_empty() {
v["role"] = json!(e.role);
}
@@ -31,8 +33,9 @@ pub fn tree(s: &Session) -> Value {
if !text.is_empty() {
v["text"] = json!(text);
}
- if e.focused {
+ if e.focused || live.focus == Some(id) {
v["focused"] = json!(true);
+ v["focusVisible"] = json!(live.focus_visible);
}
// where a transform (an offset, a scale, a turn) drew it, when that isn't its box: Rune's drawn rect, scaled and
// turned, and its scale (T3c)
@@ -43,6 +46,7 @@ pub fn tree(s: &Session) -> Value {
if e.opacity < 0.999 {
v["opacity"] = json!((f64::from(e.opacity) * 1000.0).round() / 1000.0);
}
+ v["look"] = crate::look::of(e, looks.get(&id), live.focus == Some(id) && live.focus_visible);
out.push(v);
}
Value::Array(out)
diff --git a/engine/rune/look/src/lib.rs b/engine/rune/look/src/lib.rs
new file mode 100644
index 00000000..135a3fd3
--- /dev/null
+++ b/engine/rune/look/src/lib.rs
@@ -0,0 +1,5 @@
+//! The native target's page as a check reads it: the element tree Rune drew (dump.rs, R4b) and each element's look
+//! (look.rs, T3e), in the terms of Chrome's computed style, so a run sets beside a reference recorded in Chrome.
+
+pub mod dump;
+pub mod look;
diff --git a/engine/rune/look/src/look.rs b/engine/rune/look/src/look.rs
new file mode 100644
index 00000000..f64aa7c6
--- /dev/null
+++ b/engine/rune/look/src/look.rs
@@ -0,0 +1,33 @@
+//! An element's look as Chrome's computed style gives it (T3e, the T3 set's bar in projects/rune's README): its
+//! background as Rune drew it, its text colour, its top border (width and colour) and outline when it has one, its
+//! shadow layers, all colours in 8-bit sRGB with 8-bit alpha (Rune's are linear). The style ones are what the view
+//! mapped (Page::looks); the background is the drawn fill, so a transition's in-between frame shows as drawn.
+
+use rune::Color;
+use serde_json::{Value, json};
+
+use raea_rune_page::css::Css;
+
+/// A colour as Chrome's canvas reads it back: 8-bit sRGB channels and alpha.
+pub fn rgba(c: Color) -> [u8; 4] {
+ let enc = |x: f32| (rune::color::srgb_encode(x.clamp(0.0, 1.0)) * 255.0).round() as u8;
+ [enc(c.r), enc(c.g), enc(c.b), (c.a.clamp(0.0, 1.0) * 255.0).round() as u8]
+}
+
+/// Element `e`'s look, from its mapped style and text colour (`mapped`); `focus_visible` is whether it has the page's
+/// focus and shows it, which draws Chrome's ring when it has no outline of its own (outline.rs, as the view draws it).
+pub fn of(e: &rune::ElementInfo, mapped: Option<&(Css, Color)>, focus_visible: bool) -> Value {
+ let mut v = json!({"bg": rgba(e.fill)});
+ let Some((c, fg)) = mapped else { return v };
+ v["fg"] = json!(rgba(*fg));
+ if let Some(w) = c.border_width[0].filter(|w| *w > 0.0) {
+ v["border"] = json!([w, rgba(c.border_color.unwrap_or(*fg))]);
+ }
+ if let Some((w, _, col)) = raea_rune_page::outline::drawn(&c.outline, *fg, focus_visible) {
+ v["outline"] = json!([w, rgba(col)]);
+ }
+ if !c.shadows.is_empty() {
+ v["shadow"] = c.shadows.iter().map(|s| json!([rgba(s.color), s.x, s.y, s.blur, s.spread, s.inset])).collect();
+ }
+ v
+}
diff --git a/engine/rune/page/src/events.rs b/engine/rune/page/src/events.rs
index 6f8741ff..7d89e7ac 100644
--- a/engine/rune/page/src/events.rs
+++ b/engine/rune/page/src/events.rs
@@ -48,12 +48,12 @@ pub fn attach(mut e: El, id: u64, n: &Node, root: bool) -> El {
let listens = hears(Ev::PointerEnter) || hears(Ev::PointerLeave);
if listens || styled {
e = e.on_hover_change(move |p: &mut Page, inside: bool, _: &mut Tx| {
- if styled {
- if inside {
- p.hovered.insert(id);
- } else {
- p.hovered.remove(&id);
- }
+ // a leave clears hover whatever the classes are now: one that lost its `hover:` while the pointer was on it
+ // (the row a press opened) mustn't keep it for when it gets one back
+ if !inside {
+ p.hovered.remove(&id);
+ } else if styled {
+ p.hovered.insert(id);
}
if !listens {
return;
@@ -100,10 +100,30 @@ pub fn field(id: u64, edit: &rune::TextEdit, style: rune::TextStyle, color: rune
/// A pointer payload for element `id` at `(lx, ly)` in its own points.
/// A pointer event at a point local to the element, sent as `ev` with `button` and `detail`
fn at(p: &mut Page, id: u64, ev: Ev, m: &PointerEvent, button: u8, detail: u32) {
- let payload = pointer(p, id, m.x, m.y, button, detail, Mods::default());
+ let mut payload = pointer(p, id, m.x, m.y, button, detail, Mods::default());
+ if ev == Ev::PointerMove {
+ targeted(p, id, &mut payload);
+ }
p.send(id, ev, payload);
}
+/// A press's or a move's deepest wire element under the pointer as its `target`, as the other host sends it
+/// (runtime/dom/src/host/bridge.rs): sdk/ui's own hit test reads only classes without their variants (a `hidden md:flex`
+/// sidebar is hidden to it), so without one a release over it found no element and no click came. It's the topmost
+/// element at the point inside `within` (or `within` itself), the element Rune's hit test, which clips, handed the
+/// gesture to: the page's own boxes don't clip, and a list's rows scrolled out under its header are still there.
+fn targeted(p: &Page, within: u64, payload: &mut Value) {
+ let (x, y) = (payload["clientX"].as_f64().unwrap_or(0.0) as f32, payload["clientY"].as_f64().unwrap_or(0.0) as f32);
+ let inside = |t: u64| std::iter::successors(Some(t), |i| p.tree.get(*i).and_then(|n| n.parent)).any(|i| i == within);
+ let hit = |t: &u64| {
+ let r = p.rect(*t);
+ x >= r[0] && y >= r[1] && x < r[0] + r[2] && y < r[1] + r[3] && inside(*t)
+ };
+ if let Some(t) = p.order.iter().rev().copied().find(hit) {
+ payload["target"] = json!(t);
+ }
+}
+
fn pointer(p: &Page, id: u64, lx: f32, ly: f32, button: u8, detail: u32, m: Mods) -> Value {
let r = p.rect(id);
let (cx, cy) = (r[0] + lx, r[1] + ly);
@@ -140,7 +160,8 @@ impl Page {
fn send_up(&mut self, id: u64, ev: Ev, x: f32, y: f32, clicks: u32, m: Mods) {
if let Some(t) = self.up(Some(id), |n| n.on.contains(&ev)) {
let r = self.rect(t);
- let payload = pointer(self, t, x - r[0], y - r[1], 0, clicks, m);
+ let mut payload = pointer(self, t, x - r[0], y - r[1], 0, clicks, m);
+ targeted(self, id, &mut payload);
self.send(t, ev, payload);
}
}
diff --git a/engine/rune/page/src/lib.rs b/engine/rune/page/src/lib.rs
index e418368f..2d34dd92 100644
--- a/engine/rune/page/src/lib.rs
+++ b/engine/rune/page/src/lib.rs
@@ -3,9 +3,8 @@
//! events back to the app.
pub use raea_rune_media::images;
-pub use raea_rune_style::{css, motion, report, runeprops, tailwind, variants};
+pub use raea_rune_style::{css, motion, outline, report, runeprops, tailwind, variants};
-pub mod dump;
pub mod events;
pub mod input;
pub mod kit;
diff --git a/engine/rune/page/src/page.rs b/engine/rune/page/src/page.rs
index 75dc7ff3..532b2ee6 100644
--- a/engine/rune/page/src/page.rs
+++ b/engine/rune/page/src/page.rs
@@ -44,6 +44,8 @@ pub struct Page {
pub last_layout: String,
/// each element's padding and border widths (l t r b, l t r b) as the last view mapped them
pub boxes: RefCell<HashMap<u64, [f32; 8]>>,
+ /// each element's style as the last view mapped it, and its text colour: what raea-rune-look reads (T3e)
+ pub looks: RefCell<HashMap<u64, (crate::css::Css, rune::Color)>>,
/// the pointer in window points, as last seen
pub pointer: (f32, f32),
/// the page asked for a `frame` host event every frame (`__ui_emit("ticks", true)`)
@@ -116,10 +118,13 @@ impl Page {
pub fn view(p: &Page, cx: &mut Cx<Page>) -> El {
let mut report = p.report.borrow_mut();
let mut boxes = p.boxes.borrow_mut();
+ let mut looks = p.looks.borrow_mut();
+ looks.clear();
+ crate::css::set_viewport(p.viewport);
let live = p.live(cx.system_dark());
p.images.unsee();
p.videos.unsee();
- crate::view::build(&p.tree, &mut Ctx { report: &mut report, images: &p.images, videos: &p.videos, edits: &p.edits, boxes: &mut boxes, measure: &p.measure, marks: 0, live })
+ crate::view::build(&p.tree, &mut Ctx { report: &mut report, images: &p.images, videos: &p.videos, edits: &p.edits, boxes: &mut boxes, looks: &mut looks, measure: &p.measure, marks: 0, live })
}
/// A headless Rune runtime for `page` at `viewport` points, with Rune's text (Inter, embedded) so text has its size,
diff --git a/engine/rune/page/src/view.rs b/engine/rune/page/src/view.rs
index 097a6bcd..bd332135 100644
--- a/engine/rune/page/src/view.rs
+++ b/engine/rune/page/src/view.rs
@@ -53,6 +53,8 @@ pub struct Ctx<'a> {
pub edits: &'a HashMap<u64, TextEdit>,
/// each element's padding and border widths as mapped (l t r b, l t r b): the layout snapshot's
pub boxes: &'a mut HashMap<u64, [f32; 8]>,
+ /// each element's mapped style and text colour (Page::looks)
+ pub looks: &'a mut HashMap<u64, (Css, Color)>,
/// unrounded text widths (measure.rs)
pub measure: &'a crate::measure::Measure,
/// elements built so far that asked for Rune motion (runeprops.rs): a subtree that adds none lands at once
@@ -139,6 +141,7 @@ fn node(tree: &Tree, id: u64, n: &Node, inh: &Inherit, path: &str, cx: &mut Ctx)
}
raea_rune_media::view::check_family(c.font_family.as_deref(), path, cx.report);
let mut inh = inherit(inh, &c);
+ cx.looks.insert(id, (c.clone(), inh.color));
// a new strut where a block (or a flex item, or a button or field: inline-blocks) holds the lines; inline elements
// keep their block's
if display != Display::Inline || inh.flex_parent || matches!(n.kind.as_str(), "button" | "editableText" | "img" | "video") {
@@ -202,6 +205,10 @@ fn node(tree: &Tree, id: u64, n: &Node, inh: &Inherit, path: &str, cx: &mut Ctx)
}
let (pad, bw) = padding(&c);
cx.boxes.insert(id, [pad[3], pad[0], pad[1], pad[2], bw[3], bw[0], bw[1], bw[2]]);
+ // its outline (T3e): its own, or Chrome's focus-visible ring on the page's focus
+ if let Some((w, off, col)) = crate::outline::drawn(&c.outline, inh.color, cx.live.focus == Some(id) && cx.live.focus_visible) {
+ e = e.outline(w, off, col);
+ }
Some(boxed(e, &c, &inh, display == Display::Flex, path, cx.report))
}
@@ -229,13 +236,15 @@ fn field(id: u64, n: &Node, inh: &Inherit, cx: &mut Ctx) -> El {
row().items_center().child(input)
}
-/// The element's own line height in points (0: Rune's default, for `normal`).
+/// The element's own line height in points (0: Rune's default, for `normal`), in Chrome's 1/64 px layout units: a
+/// ratio's float error (Tailwind's text-xs, 12 × calc(1 / 0.75)) stays 16, where Rune would round 16.000001 up to 17.
fn line_px(inh: &Inherit) -> f32 {
- match inh.line {
+ let l = match inh.line {
Len::Px(p) => p,
Len::Pct(p) => inh.size * p / 100.0,
Len::Auto => 0.0,
- }
+ };
+ (l * 64.0).round() / 64.0
}
fn text_style(inh: &Inherit) -> TextStyle {
diff --git a/engine/rune/page/tests/variants.rs b/engine/rune/page/tests/variants.rs
index 0c2b5388..23756bee 100644
--- a/engine/rune/page/tests/variants.rs
+++ b/engine/rune/page/tests/variants.rs
@@ -34,8 +34,8 @@ fn variants_hold_per_state_in_tailwinds_order() {
#[test]
fn unmapped_variants_are_reported_in_any_state() {
- let (_, unknown) = style_in("hover:bg-red-500 md:flex dark:hover:ring-2 group-hover:flex first:p-2 placeholder:text-sm -mt-2 p-4", &State::default());
- assert_eq!(unknown, ["dark:hover:ring-2", "group-hover:flex", "first:p-2", "placeholder:text-sm", "-mt-2"]);
+ let (_, unknown) = style_in("hover:bg-red-500 md:flex dark:hover:skew-x-3 group-hover:flex first:p-2 placeholder:text-sm -mt-2 p-4", &State::default());
+ assert_eq!(unknown, ["dark:hover:skew-x-3", "group-hover:flex", "first:p-2", "placeholder:text-sm", "-mt-2"]);
}
/// A page of three: a box with `class` (id 1) after a focusable one (id 2) to Tab from, under an 800x600 viewport.
diff --git a/engine/rune/src/js.rs b/engine/rune/src/js.rs
index fd31b3f3..453d7053 100644
--- a/engine/rune/src/js.rs
+++ b/engine/rune/src/js.rs
@@ -138,10 +138,15 @@ impl Js {
("__ui_flush", push(&asks, |a, x| a.flushed.push(x[0].clone()))),
("__ui_emit", push(&asks, |a, x| a.emits.push((x[0].clone(), x[1].clone())))),
("__ui_call", push(&asks, |a, x| a.calls.push((x[0].parse::<f64>().unwrap_or(0.0) as u64, x[1].clone(), x[2].clone())))),
- // no synchronous host calls yet: each answers that it isn't there, as a host without it does
+ // synchronous host calls answer that they aren't there, as a host without them does; except sdk/ui's
+ // `selection.set(null)` (no selection, which a press sends): nothing is selected, so there's nothing to
+ // paint (T4a). A selection to paint is refused and listed: Rune's host doesn't draw the DOM's yet
("__ui_sync", {
let r = refused.clone();
- Box::new(move |x| Ok(Ret::Str(json!({"err": refuse(&r, arg(x, 0))}).to_string())))
+ Box::new(move |x| {
+ let none = arg(x, 0) == "selection.set" && arg(x, 1).trim() == "null";
+ Ok(Ret::Str(if none { json!({"ok": null}) } else { json!({"err": refuse(&r, arg(x, 0))}) }.to_string()))
+ })
}),
("__ui_log", {
let l = logs.clone();
diff --git a/engine/rune/src/lib.rs b/engine/rune/src/lib.rs
index b920a571..8853fc45 100644
--- a/engine/rune/src/lib.rs
+++ b/engine/rune/src/lib.rs
@@ -2,7 +2,8 @@
//! tree with Rune. docs/rune.feature in raea is the plan.
// the page and its styles, from their crates (raea-rune-page, raea-rune-style), at the paths they had here
-pub use raea_rune_page::{css, dump, events, images, input, kit, layout, measure, motion, page, report, runeprops, session, state, tailwind, tree, variants, view};
+pub use raea_rune_look::{dump, look};
+pub use raea_rune_page::{css, events, images, input, kit, layout, measure, motion, page, report, runeprops, session, state, tailwind, tree, variants, view};
pub mod js;
pub mod macapp;
diff --git a/engine/rune/style/src/css.rs b/engine/rune/style/src/css.rs
index 4f7c43ae..d968efc3 100644
--- a/engine/rune/style/src/css.rs
+++ b/engine/rune/style/src/css.rs
@@ -87,6 +87,7 @@ pub struct Css {
pub border_color: Option<Color>,
pub radius: [Option<f32>; 4],
pub shadows: Vec<ShadowCss>,
+ pub outline: crate::outline::OutlineCss,
pub opacity: Option<f32>,
/// objectFit on an img or video (T3d): contain letterboxes, cover crops; `fill` (CSS's default) stretches
pub fit: Option<Option<rune::SurfaceFit>>,
@@ -128,7 +129,7 @@ pub fn parse(style: &Map<String, Value>) -> (Css, Vec<Unmapped>) {
}
/// The props that set several others, applied before those others.
-const SHORTHANDS: [&str; 7] = ["padding", "margin", "gap", "borderWidth", "borderRadius", "overflow", "transition"];
+const SHORTHANDS: [&str; 8] = ["padding", "margin", "gap", "borderWidth", "borderRadius", "overflow", "transition", "outline"];
fn show(v: &Value) -> String {
match v {
@@ -230,6 +231,7 @@ fn prop(c: &mut Css, k: &str, v: &Value) -> Result<(), &'static str> {
"borderBottomRightRadius" => edges4(&mut c.radius, Some(2))?,
"borderBottomLeftRadius" => edges4(&mut c.radius, Some(3))?,
"boxShadow" => c.shadows = shadows(text(v)?).ok_or(BAD_VALUE)?,
+ "outline" | "outlineStyle" | "outlineWidth" | "outlineColor" | "outlineOffset" => crate::outline::prop(&mut c.outline, k, v)?,
"opacity" => c.opacity = Some(num(v)?),
"objectFit" => c.fit = Some(match text(v)? { "contain" => Some(rune::SurfaceFit::Fit), "cover" => Some(rune::SurfaceFit::Fill), "fill" => None, _ => return Err(BAD_VALUE) }),
"color" => c.color = Some(color(text(v)?).ok_or(BAD_VALUE)?),
@@ -270,7 +272,16 @@ fn num(v: &Value) -> Result<f32, &'static str> {
}
}
-/// A React style length: a number is px; a string is `Npx`, `N%`, `0` or `auto`.
+thread_local! {
+ static VIEWPORT: std::cell::Cell<(f32, f32)> = const { std::cell::Cell::new((800.0, 600.0)) };
+}
+
+/// The viewport `vw` and `vh` (and `dvh`, `svh`, `lvh`: one window has one height) are shares of, set before a build.
+pub fn set_viewport(size: (f32, f32)) {
+ VIEWPORT.set(size);
+}
+
+/// A React style length: a number is px; a string is `Npx`, `N%`, `Nvw`, `Nvh`, `0` or `auto`.
pub fn length(v: &Value) -> Option<Len> {
match v {
Value::Number(n) => Some(Len::Px(n.as_f64()? as f32)),
@@ -280,6 +291,8 @@ pub fn length(v: &Value) -> Option<Len> {
Some(Len::Auto)
} else if let Some(p) = s.strip_suffix('%') {
p.trim().parse().ok().map(Len::Pct)
+ } else if let Some((p, side)) = s.strip_suffix("vw").map(|p| (p, VIEWPORT.get().0)).or_else(|| ["dvh", "svh", "lvh", "vh"].iter().find_map(|u| s.strip_suffix(u)).map(|p| (p, VIEWPORT.get().1))) {
+ p.trim().parse::<f32>().ok().map(|v| Len::Px(v * side / 100.0))
} else {
s.strip_suffix("px").unwrap_or(s).trim().parse().ok().map(Len::Px)
}
@@ -336,7 +349,8 @@ pub fn color(s: &str) -> Option<Color> {
if let Some(body) = s.strip_prefix("oklch(").and_then(|b| b.strip_suffix(')')) {
// Tailwind v4's palette: `oklch(62.3% 0.214 259.815 [/ a])`
let (lch, a) = body.split_once('/').map_or((body, None), |(l, a)| (l, Some(a)));
- let p: Vec<&str> = lch.split_whitespace().collect();
+ // `none` is a missing component, which is 0 (CSS Color 4): the greys' hue
+ let p: Vec<&str> = lch.split_whitespace().map(|c| if c == "none" { "0" } else { c }).collect();
let l = match p.first()?.strip_suffix('%') {
Some(pct) => pct.parse::<f32>().ok()? / 100.0,
None => p.first()?.parse().ok()?,
diff --git a/engine/rune/style/src/lib.rs b/engine/rune/style/src/lib.rs
index 30bb0caa..640391a9 100644
--- a/engine/rune/style/src/lib.rs
+++ b/engine/rune/style/src/lib.rs
@@ -3,7 +3,9 @@
pub mod css;
pub mod motion;
+pub mod outline;
pub mod report;
+mod rings;
pub mod runeprops;
pub mod tailwind;
pub mod variants;
diff --git a/engine/rune/style/src/outline.rs b/engine/rune/style/src/outline.rs
new file mode 100644
index 00000000..7c950d41
--- /dev/null
+++ b/engine/rune/style/src/outline.rs
@@ -0,0 +1,80 @@
+//! CSS `outline` (T3e): its style, width, colour and offset as the style says them, and the outline the host draws
+//! from them with Rune's `El::outline` (a ring `offset` points outside the border box). An element draws its own
+//! outline when its style is one Rune draws (solid, or Chrome's `auto`, drawn solid); with no style set, the focused
+//! element shows Chrome's `:focus-visible` default (`outline: auto 1px -webkit-focus-ring-color`, which Chrome computes
+//! as 1 px of rgb(0, 95, 204)) when its focus is visible. `outline-style: none` (Tailwind's `outline-none`) draws none.
+
+use rune::Color;
+use serde_json::Value;
+
+use crate::css::{BAD_VALUE, Len, color, length};
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct OutlineCss {
+ /// true for a style Rune draws, false for `none` or `hidden`
+ pub drawn: Option<bool>,
+ pub width: Option<f32>,
+ pub color: Option<Color>,
+ pub offset: Option<f32>,
+}
+
+/// Chrome's focus ring colour, `-webkit-focus-ring-color` on the Mac
+const RING: [u8; 3] = [0, 95, 204];
+
+fn style(s: &str) -> Option<bool> {
+ match s {
+ "none" | "hidden" => Some(false),
+ "solid" | "auto" => Some(true),
+ _ => None,
+ }
+}
+
+fn width(v: &Value) -> Option<f32> {
+ match (v.as_str().map(str::trim), length(v)) {
+ (Some("thin"), _) => Some(1.0),
+ (Some("medium"), _) => Some(3.0),
+ (Some("thick"), _) => Some(5.0),
+ (_, Some(Len::Px(p))) => Some(p),
+ _ => None,
+ }
+}
+
+/// An `outline*` prop into `o`, or why not: a style other than none, hidden, solid or auto isn't read.
+pub fn prop(o: &mut OutlineCss, k: &str, v: &Value) -> Result<(), &'static str> {
+ let text = || v.as_str().map(str::trim).ok_or(BAD_VALUE);
+ match k {
+ "outlineStyle" => o.drawn = Some(style(text()?).ok_or(BAD_VALUE)?),
+ "outlineWidth" => o.width = Some(width(v).ok_or(BAD_VALUE)?),
+ "outlineColor" => o.color = Some(color(text()?).ok_or(BAD_VALUE)?),
+ "outlineOffset" => o.offset = Some(width(v).ok_or(BAD_VALUE)?),
+ // the shorthand: a width, a style and a colour in any order, each optional
+ _ => {
+ for t in text()?.split_whitespace() {
+ let tv = Value::String(t.into());
+ if let Some(s) = style(t) {
+ o.drawn = Some(s);
+ } else if let Some(w) = width(&tv) {
+ o.width = Some(w);
+ } else {
+ o.color = Some(color(t).ok_or(BAD_VALUE)?);
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+/// The outline drawn: (width, offset, colour), the colour defaulting to the text's (`fg`); `focus_visible` is whether
+/// this element has the page's focus and shows it.
+pub fn drawn(o: &OutlineCss, fg: Color, focus_visible: bool) -> Option<(f32, f32, Color)> {
+ let (w, c) = match o.drawn {
+ Some(false) => return None,
+ Some(true) => (o.width.unwrap_or(3.0), o.color.unwrap_or(fg)),
+ None if focus_visible => {
+ let d = |x: u8| rune::color::srgb_decode(x as f32 / 255.0);
+ (o.width.unwrap_or(1.0), o.color.unwrap_or(Color { r: d(RING[0]), g: d(RING[1]), b: d(RING[2]), a: 1.0 }))
+ }
+ None => return None,
+ };
+ (w > 0.0).then_some((w, o.offset.unwrap_or(0.0), c))
+}
diff --git a/engine/rune/style/src/rings.rs b/engine/rune/style/src/rings.rs
new file mode 100644
index 00000000..7d403841
--- /dev/null
+++ b/engine/rune/style/src/rings.rs
@@ -0,0 +1,55 @@
+//! Tailwind 4.3.3's box-shadow (T3e): `ring-*`, `ring-offset-*` and `shadow-*` each set a variable, and the element's
+//! `box-shadow` is their layers in Tailwind's order (its inset shadow and inset ring, then the ring's offset, the ring,
+//! the shadow). A ring is a spread the offset wider (`0 0 0 calc(W + O) colour`) over the offset's own layer
+//! (`0 0 0 O colour`, white unless `ring-offset-<colour>`); `ring` alone is 1 px, and its colour is the text's. The
+//! variables are taken out once composed: nothing downstream reads them.
+
+use serde_json::{Map, Value, json};
+
+pub(crate) const WIDTH: &str = "--tw-ring-width";
+pub(crate) const COLOR: &str = "--tw-ring-color";
+pub(crate) const OFFSET: &str = "--tw-ring-offset-width";
+pub(crate) const OFFSET_COLOR: &str = "--tw-ring-offset-color";
+pub(crate) const SHADOW: &str = "--tw-shadow";
+
+/// A `ring-...` utility's variable: `ring` and `ring-N` its width, `ring-offset-N` and `ring-offset-<colour>` the
+/// offset's, `ring-<colour>` its colour.
+pub(crate) fn utility(rest: Option<&str>, colour: impl Fn(&str) -> Option<String>) -> Option<Vec<(&'static str, Value)>> {
+ let Some(rest) = rest else { return Some(vec![(WIDTH, json!(1))]) };
+ let width = |s: &str| s.parse::<f64>().ok().map(Value::from);
+ Some(vec![match rest.strip_prefix("offset-") {
+ Some(o) => match width(o) {
+ Some(w) => (OFFSET, w),
+ None => (OFFSET_COLOR, json!(colour(o)?)),
+ },
+ None => match width(rest) {
+ Some(w) => (WIDTH, w),
+ None => (COLOR, json!(colour(rest)?)),
+ },
+ }])
+}
+
+/// `out`'s ring and shadow variables as its `boxShadow`, when a ring or a shadow is set.
+pub(crate) fn compose(out: &mut Map<String, Value>) {
+ let mut take = |k: &str| out.remove(k);
+ let (w, c, o, oc, shadow) = (take(WIDTH), take(COLOR), take(OFFSET), take(OFFSET_COLOR), take(SHADOW));
+ let mut layers = Vec::new();
+ if let Some(w) = w.and_then(|w| w.as_f64()).filter(|w| *w > 0.0) {
+ let o = o.and_then(|o| o.as_f64()).unwrap_or(0.0);
+ let s = |v: Option<Value>, or: &str| v.and_then(|v| v.as_str().map(str::to_string)).unwrap_or(or.into());
+ if o > 0.0 {
+ layers.push(format!("0 0 0 {o}px {}", s(oc, "#fff")));
+ }
+ layers.push(format!("0 0 0 {}px {}", w + o, s(c, "currentcolor")));
+ }
+ let shadow = shadow.and_then(|s| s.as_str().map(str::to_string));
+ match shadow.as_deref() {
+ Some("none") | None => {}
+ Some(s) => layers.push(s.to_string()),
+ }
+ if !layers.is_empty() {
+ out.insert("boxShadow".into(), json!(layers.join(", ")));
+ } else if shadow.is_some() {
+ out.insert("boxShadow".into(), json!("none"));
+ }
+}
diff --git a/engine/rune/style/src/tailwind.rs b/engine/rune/style/src/tailwind.rs
index 15b0be8e..452af805 100644
--- a/engine/rune/style/src/tailwind.rs
+++ b/engine/rune/style/src/tailwind.rs
@@ -9,6 +9,7 @@ use std::sync::OnceLock;
use serde_json::{Map, Value, json};
+use crate::rings;
use crate::variants::{self, State};
const THEME: &str = include_str!("../assets/tailwind-theme.css");
@@ -67,6 +68,16 @@ fn spacing(s: &str) -> Option<Value> {
Some(json!(n * px(var("spacing")?)?))
}
+/// A size utility's value on an axis (`w` or `h`): spacing, full, auto, or the viewport's (`screen`, `dvh`, ...).
+fn size_on(axis: &str, s: &str) -> Option<Value> {
+ let unit = if axis == "w" { "vw" } else { "vh" };
+ match s {
+ "screen" => Some(json!(format!("100{unit}"))),
+ "dvh" | "svh" | "lvh" | "dvw" | "svw" | "lvw" if s.ends_with(&unit[1..]) => Some(json!(format!("100{unit}"))),
+ _ => size(s),
+ }
+}
+
/// A size utility's value: spacing, or full/auto.
fn size(s: &str) -> Option<Value> {
match s {
@@ -116,6 +127,7 @@ pub fn style_in(class: &str, s: &State) -> (Map<String, Value>, Vec<String>) {
for (k, v) in hits.into_iter().flat_map(|h| h.1) {
out.insert(k.to_string(), v);
}
+ crate::rings::compose(&mut out);
(out, unknown)
}
@@ -155,8 +167,11 @@ fn utility(u: &str) -> Option<Props> {
"rounded" => return one("borderRadius", json!(px(var("radius")?)?)),
"rounded-none" => return one("borderRadius", json!(0)),
"rounded-full" => return one("borderRadius", json!(9999)),
- "shadow" => return one("boxShadow", s(var("shadow")?)),
- "shadow-none" => return one("boxShadow", s("none")),
+ "shadow" => return one(rings::SHADOW, s(var("shadow")?)),
+ "shadow-none" => return one(rings::SHADOW, s("none")),
+ "ring" => return rings::utility(None, colour),
+ "outline" => return Some(vec![("outlineStyle", s("solid")), ("outlineWidth", json!(1))]),
+ "outline-none" => return one("outlineStyle", s("none")),
// transitions (T3c): the property list Tailwind 4.3.3 writes, its default duration and curve under any
// duration-* or ease-* (motion.rs reads --tw-transition first)
"transition" => return transition("color, background-color, border-color, outline-color, opacity, box-shadow, transform, translate, scale, rotate"),
@@ -201,8 +216,8 @@ fn utility(u: &str) -> Option<Props> {
Some(("y", _)) => pad(&["rowGap"]),
_ => one("gap", spacing(rest)?),
},
- "w" => one("width", size(rest)?),
- "h" => one("height", size(rest)?),
+ "w" => one("width", size_on("w", rest)?),
+ "h" => one("height", size_on("h", rest)?),
"size" => one_two("width", "height", size(rest)?),
"min" | "max" => {
let (axis, v) = rest.split_once('-')?;
@@ -215,7 +230,7 @@ fn utility(u: &str) -> Option<Props> {
};
let v = match var(&format!("container-{v}")) {
Some(c) if axis == "w" => json!(px(c)?),
- _ => size(v)?,
+ _ => size_on(axis, v)?,
};
one(k, v)
}
@@ -253,11 +268,16 @@ fn utility(u: &str) -> Option<Props> {
},
"leading" => one("lineHeight", match var(&format!("leading-{rest}")) {
Some(l) => json!(l.parse::<f64>().ok()?),
- None => spacing(rest)?,
+ // a spacing step is a length (leading-6 is 24px), never a bare number, which lineHeight reads as a ratio
+ None => match spacing(rest)? {
+ Value::Number(n) => json!(format!("{}px", n.as_f64()?)),
+ v => v,
+ },
}),
"rounded" => radius(rest),
"border" => border(rest),
- "shadow" => one("boxShadow", s(var(&format!("shadow-{rest}"))?)),
+ "shadow" => one(rings::SHADOW, s(var(&format!("shadow-{rest}"))?)),
+ "ring" => rings::utility(Some(rest), colour),
"duration" => one("transitionDuration", s(&format!("{}ms", rest.parse::<f64>().ok()?))),
"delay" => one("transitionDelay", s(&format!("{}ms", rest.parse::<f64>().ok()?))),
"translate" => match rest.split_once('-') {
diff --git a/engine/rune/style/tests/t3e.rs b/engine/rune/style/tests/t3e.rs
new file mode 100644
index 00000000..5a3de443
--- /dev/null
+++ b/engine/rune/style/tests/t3e.rs
@@ -0,0 +1,73 @@
+//! T3e: what the T3 set's run against Chrome needed mapped, each at the value Chrome computes.
+
+use raea_rune_style::css::{Len, color, length, parse, set_viewport};
+use raea_rune_style::outline::drawn;
+use raea_rune_style::tailwind::style_in;
+use raea_rune_style::variants::State;
+use serde_json::{Value, json};
+
+fn style(class: &str, s: &State) -> serde_json::Map<String, Value> {
+ let (m, unknown) = style_in(class, s);
+ assert!(unknown.is_empty(), "{unknown:?}");
+ m
+}
+
+fn rgb8(c: rune::Color) -> [u8; 4] {
+ let e = |x: f32| (rune::color::srgb_encode(x) * 255.0).round() as u8;
+ [e(c.r), e(c.g), e(c.b), (c.a * 255.0).round() as u8]
+}
+
+#[test]
+fn a_none_component_is_zero() {
+ // Tailwind's greys have no hue: zinc-50, as Chrome computes it
+ assert_eq!(rgb8(color("oklch(98.5% 0 none)").expect("read")), [250, 250, 250, 255]);
+}
+
+#[test]
+fn screen_sizes_are_the_viewport() {
+ let s = style("h-screen min-h-dvh w-screen", &State::default());
+ assert_eq!((s["height"].clone(), s["minHeight"].clone(), s["width"].clone()), (json!("100vh"), json!("100vh"), json!("100vw")));
+ set_viewport((640.0, 480.0));
+ assert_eq!((length(&json!("100vh")), length(&json!("50vw"))), (Some(Len::Px(480.0)), Some(Len::Px(320.0))));
+}
+
+#[test]
+fn leading_steps_are_lengths() {
+ let (c, bad) = parse(&style("text-sm leading-6", &State::default()));
+ assert!(bad.is_empty(), "{bad:?}");
+ assert_eq!(c.line_height, Some(Len::Px(24.0)), "24px, not 24 times the font size");
+}
+
+#[test]
+fn rings_are_shadow_layers_in_tailwinds_order() {
+ let on = State { focus_visible: true, focus: true, ..State::default() };
+ let s = style("shadow-sm focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2", &on);
+ let (c, bad) = parse(&s);
+ assert!(bad.is_empty(), "{bad:?}");
+ // the offset's white, the ring a spread the offset wider, then shadow-sm's two layers
+ let spreads: Vec<f32> = c.shadows.iter().map(|l| l.spread).collect();
+ assert_eq!(spreads, [2.0, 4.0, 0.0, -1.0]);
+ assert_eq!(rgb8(c.shadows[0].color), [255, 255, 255, 255]);
+ assert!(!s.keys().any(|k| k.starts_with("--tw-")), "the variables are composed away: {s:?}");
+ // not focused: only the shadow
+ assert_eq!(parse(&style("shadow-sm focus-visible:ring-2", &State::default())).0.shadows.len(), 2);
+ // an alpha ring
+ let c = parse(&style("ring-2 ring-blue-500/30", &State::default())).0;
+ assert_eq!((c.shadows.len(), c.shadows[0].spread, (c.shadows[0].color.a * 100.0).round()), (1, 2.0, 30.0));
+}
+
+#[test]
+fn outlines_are_drawn_as_chrome_draws_them() {
+ let fg = rune::Color::BLACK;
+ let c = |class: &str| parse(&style(class, &State::default())).0;
+ // no outline of its own: Chrome's focus-visible ring, 1px of -webkit-focus-ring-color
+ let (w, off, col) = drawn(&c("p-1").outline, fg, true).expect("a ring");
+ assert_eq!((w, off, rgb8(col)), (1.0, 0.0, [0, 95, 204, 255]));
+ assert_eq!(drawn(&c("p-1").outline, fg, false), None, "only while the focus shows");
+ assert_eq!(drawn(&c("outline-none").outline, fg, true), None);
+ let (o, bad) = parse(json!({"outline": "2px solid red", "outlineOffset": 3}).as_object().unwrap());
+ assert!(bad.is_empty(), "{bad:?}");
+ let (w, off, col) = drawn(&o.outline, fg, false).expect("its own outline");
+ assert_eq!((w, off, rgb8(col)), (2.0, 3.0, [255, 0, 0, 255]));
+ assert_eq!(parse(json!({"outlineStyle": "dashed"}).as_object().unwrap()).1.len(), 1, "a style Rune doesn't draw is reported");
+}
diff --git a/engine/rune/tests/calls.rs b/engine/rune/tests/calls.rs
index 982a3ba7..c470e5a2 100644
--- a/engine/rune/tests/calls.rs
+++ b/engine/rune/tests/calls.rs
@@ -9,6 +9,8 @@ const SCRIPT: &str = r#"
__ui_call(2, "files.open", "{}");
__ui_call(3, "world.spawn_entity", "{}");
console.log("sync " + __ui_sync("layout.now", "null"));
+ console.log("cleared " + __ui_sync("selection.set", "null"));
+ console.log("selected " + __ui_sync("selection.set", JSON.stringify({ anchor: [1, 0], focus: [1, 3], caret: false })));
"#;
#[test]
@@ -18,7 +20,10 @@ fn a_call_the_native_target_can_t_answer_says_so_and_is_listed() {
assert!(logs.contains("answer 1 false world.spawn_entity: no world on the native target (targets.feature T6)"), "{logs}");
assert!(logs.contains("answer 2 false the Rune host has no files.open"), "{logs}");
assert!(logs.contains("the Rune host has no layout.now"), "{logs}");
+ // T4a: no selection is answered (nothing to paint); a selection to paint is still refused and listed
+ assert!(logs.contains(r#"cleared {"ok":null}"#), "{logs}");
+ assert!(logs.contains("selected {\"err\":\"the Rune host has no selection.set"), "{logs}");
let refused = app.refused.borrow();
let listed: Vec<(&str, u32)> = refused.iter().map(|(k, (_, n))| (k.as_str(), *n)).collect();
- assert_eq!(listed, [("files.open", 1), ("layout.now", 1), ("world.spawn_entity", 2)]);
+ assert_eq!(listed, [("files.open", 1), ("layout.now", 1), ("selection.set", 1), ("world.spawn_entity", 2)]);
}
diff --git a/engine/web/Cargo.toml b/engine/web/Cargo.toml
new file mode 100644
index 00000000..9734ea8c
--- /dev/null
+++ b/engine/web/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "raea-web"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "raea in a browser (docs/web-export.md M2): raea-render's 3D engine on WebGPU in a page's canvas, fed each frame's scene as live play feeds it"
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+raea-render = { path = "../render", default-features = false, features = ["web"] }
+raea-runtime-scene = { path = "../../runtime/scene" }
+raea-core-scene = { path = "../../core/scene" }
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "ui_bevy_render", "webgpu"] }
+serde_json = "1"
+wasm-bindgen = "0.2.129"
+web-sys = { version = "0.3.106", features = ["HtmlCanvasElement", "console"] }
+raw-window-handle = { version = "0.6.2", features = ["wasm-bindgen-0-2"] }
+console_error_panic_hook = "0.1.7"
diff --git a/engine/web/src/canvas.rs b/engine/web/src/canvas.rs
new file mode 100644
index 00000000..1ccdb750
--- /dev/null
+++ b/engine/web/src/canvas.rs
@@ -0,0 +1,78 @@
+//! The page's canvas as a Bevy window (no winit: a window entity whose handle is the canvas, which wgpu's WebGPU
+//! backend makes its surface from), and a camera on it that shows the engine's target, nearest-neighbour: the scene is
+//! drawn at its own size (a pixel look's size) and the canvas scales it up with hard pixels.
+
+use std::ptr::NonNull;
+
+use bevy::camera::{ClearColorConfig, RenderTarget};
+use bevy::image::ImageSampler;
+use bevy::prelude::*;
+use bevy::window::{RawHandleWrapper, WindowRef, WindowResolution, WindowWrapper};
+use raea_render::engine::Engine;
+use raw_window_handle::{DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle, RawWindowHandle, WebCanvasWindowHandle, WebDisplayHandle, WindowHandle};
+use wasm_bindgen::JsValue;
+
+/// The canvas, held where its handle points (a boxed JsValue, as raw-window-handle's WebCanvas wants).
+struct Canvas(Box<JsValue>);
+
+// SAFETY: wasm32 here is one thread; the canvas is only touched from it
+unsafe impl Send for Canvas {}
+unsafe impl Sync for Canvas {}
+
+impl HasWindowHandle for Canvas {
+ fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
+ let obj = NonNull::from(&*self.0).cast();
+ // SAFETY: the handle points at the JsValue this Canvas owns for as long as the window entity holds it
+ Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::WebCanvas(WebCanvasWindowHandle::new(obj))) })
+ }
+}
+
+impl HasDisplayHandle for Canvas {
+ fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
+ // SAFETY: the web's display handle holds nothing
+ Ok(unsafe { DisplayHandle::borrow_raw(RawDisplayHandle::Web(WebDisplayHandle::new())) })
+ }
+}
+
+/// The canvas as a window of the App (before it's finished, so the renderer sees it from the first update).
+pub fn attach(world: &mut World, canvas: &web_sys::HtmlCanvasElement) -> Entity {
+ let (w, h) = (canvas.width().max(1), canvas.height().max(1));
+ let wrapper = WindowWrapper::new(Canvas(Box::new(JsValue::from(canvas.clone()))));
+ let handle = RawHandleWrapper::new(&wrapper).expect("a canvas always has a handle");
+ world
+ .spawn((
+ Window { resolution: WindowResolution::new(w, h).with_scale_factor_override(1.0), present_mode: bevy::window::PresentMode::AutoVsync, ..default() },
+ handle,
+ ))
+ .id()
+}
+
+/// The camera on the canvas, and the target on it filling the canvas, sampled nearest (the tag row under it cut off).
+pub fn show(e: &mut Engine, window: Entity) {
+ let (w, h) = e.size();
+ let target = e.target_image();
+ let world = e.world_mut();
+ if let Some(mut img) = world.resource_mut::<Assets<Image>>().get_mut(&target) {
+ img.sampler = ImageSampler::nearest();
+ }
+ let cam = world
+ .spawn((
+ Camera2d,
+ // after every camera that draws into the target
+ Camera { order: 10_000, clear_color: ClearColorConfig::Custom(Color::BLACK), ..default() },
+ RenderTarget::Window(WindowRef::Entity(window)),
+ ))
+ .id();
+ world.spawn((
+ Node { position_type: PositionType::Absolute, width: Val::Percent(100.0), height: Val::Percent(100.0), ..default() },
+ ImageNode { image: target, rect: Some(Rect::new(0.0, 0.0, w as f32, h as f32)), ..default() },
+ UiTargetCamera(cam),
+ ));
+}
+
+/// The canvas's pixel size changed.
+pub fn resize(world: &mut World, window: Entity, w: u32, h: u32) {
+ if let Some(mut win) = world.get_mut::<Window>(window) {
+ win.resolution.set_physical_resolution(w.max(1), h.max(1));
+ }
+}
diff --git a/engine/web/src/lib.rs b/engine/web/src/lib.rs
new file mode 100644
index 00000000..9274b277
--- /dev/null
+++ b/engine/web/src/lib.rs
@@ -0,0 +1,99 @@
+//! raea in a browser (docs/web-export.md M2): raea-render's 3D engine, compiled to wasm32, drawing on WebGPU into a
+//! page's canvas. The page hands each frame's scene (the `data-3d` parts its React tree rendered, as the tree of
+//! `{kind, props, shape, kids}` that native play reads from its own page) and the frame's number; the scene becomes rows
+//! as live play makes them (raea-runtime-scene's LiveScene), and only what changed is set on the engine, which draws
+//! the frame into its target and shows the target on the canvas, nearest-neighbour (canvas.rs).
+//!
+//! The engine opens in two halves: a browser's GPU device comes asynchronously, so `frame` starts it at the first
+//! frame with any 3D and returns false until the device is up, then finishes it and draws from then on.
+
+use std::path::Path;
+
+use raea_render::engine::{Engine, Opening};
+use raea_runtime_scene::{LiveScene, Shot};
+use wasm_bindgen::prelude::*;
+
+mod canvas;
+mod scene;
+
+#[wasm_bindgen(start)]
+fn start() {
+ console_error_panic_hook::set_once();
+}
+
+/// One canvas's raea: its engine, opened at the first frame with 3D.
+#[wasm_bindgen]
+pub struct Raea {
+ canvas: web_sys::HtmlCanvasElement,
+ /// the size the scene is drawn at (the canvas shows it scaled, nearest-neighbour)
+ w: u32,
+ h: u32,
+ fps: f64,
+ ls: LiveScene,
+ parts: scene::Parts,
+ opening: Option<Opening>,
+ engine: Option<Engine>,
+ window: Option<bevy::prelude::Entity>,
+}
+
+#[wasm_bindgen]
+impl Raea {
+ /// A raea for `canvas`, drawing its scenes at `width` x `height` (the canvas's own pixel size is what it shows at)
+ /// and `fps` frames a second.
+ #[wasm_bindgen(constructor)]
+ pub fn new(canvas: web_sys::HtmlCanvasElement, width: u32, height: u32, fps: f64) -> Result<Raea, JsError> {
+ if width == 0 || height == 0 || !(fps > 0.0) {
+ return Err(JsError::new(&format!("raea: a size and a frame rate, got {width}x{height} at {fps}")));
+ }
+ Ok(Raea { canvas, w: width, h: height, fps, ls: LiveScene::default(), parts: scene::Parts::default(), opening: None, engine: None, window: None })
+ }
+
+ /// Frame `f` with its scene (JSON: the frame's 3D parts, as scene.rs reads them) and the colour
+ /// behind it ("#rrggbb", or none): true when it was drawn, false while the engine is still opening.
+ pub fn frame(&mut self, scene: &str, clear: Option<String>, f: f64) -> Result<bool, JsError> {
+ // a plain JS number (an i64 would be a BigInt there)
+ let f = f as i64;
+ let nodes = self.parts.nodes(scene).map_err(|e| JsError::new(&e))?;
+ let shot = Shot { scene: &nodes, clear: clear.as_deref() };
+ if self.engine.is_none() && self.opening.is_none() {
+ if nodes.is_empty() {
+ return Ok(false);
+ }
+ let p = self.ls.open(shot, self.w, self.h, self.fps);
+ let mut o = Engine::begin(&p, &raea_render::inserted_of(&p), Path::new(""), None, true).map_err(|e| JsError::new(&format!("the 3D didn't open: {e}")))?;
+ self.window = Some(canvas::attach(o.world_mut(), &self.canvas));
+ self.opening = Some(o);
+ return Ok(false);
+ }
+ if let Some(mut o) = self.opening.take() {
+ if !o.ready() {
+ self.opening = Some(o);
+ return Ok(false);
+ }
+ let mut e = o.finish().map_err(|e| JsError::new(&format!("the 3D didn't open: {e}")))?;
+ e.set_rows(&[]).map_err(|e| JsError::new(&e))?;
+ canvas::show(&mut e, self.window.expect("a window with the opening"));
+ self.engine = Some(e);
+ }
+ let e = self.engine.as_mut().expect("opened");
+ let (rows, gone) = self.ls.frame(shot);
+ if !gone.is_empty() {
+ e.remove_rows(&gone);
+ }
+ if !rows.is_empty() {
+ e.set_rows(&rows).map_err(|e| JsError::new(&e))?;
+ }
+ e.draw(f);
+ if let Some(err) = e.take_error() {
+ web_sys::console::warn_1(&format!("raea: frame {f}: {err}").into());
+ }
+ Ok(true)
+ }
+
+ /// The canvas's pixel size changed (its CSS size times the device's pixel ratio): the window follows it.
+ pub fn resize(&mut self, width: u32, height: u32) {
+ if let (Some(e), Some(w)) = (self.engine.as_mut(), self.window) {
+ canvas::resize(e.world_mut(), w, width, height);
+ }
+ }
+}
diff --git a/engine/web/src/scene.rs b/engine/web/src/scene.rs
new file mode 100644
index 00000000..bbd07090
--- /dev/null
+++ b/engine/web/src/scene.rs
@@ -0,0 +1,57 @@
+//! A frame's scene from the page: the tree of `data-3d` parts (sdk/web's collector writes it) as Node3s, the same
+//! values native play reads from its React tree (raea-runtime-react's read3d).
+//!
+//! Each part comes as `{k: kind, i: id, p?: props JSON text, s?: shape text | null, c?: kids}`. The page keeps each
+//! element's id while it lives and sends `p` and `s` only when their text changed since it last sent them; the rest
+//! are this side's, kept by id. A ground's vertex buffer or a field's placements cross once, not every frame, and are
+//! parsed once (native play keeps them the same way, props3d).
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use raea_core_scene::Node3;
+use serde_json::{Map, Value};
+
+#[derive(Default)]
+pub struct Parts {
+ kept: HashMap<u64, (Arc<Map<String, Value>>, Option<Arc<str>>)>,
+}
+
+impl Parts {
+ /// The frame's parts: a list of parts. Ids not seen this frame are forgotten.
+ pub fn nodes(&mut self, json: &str) -> Result<Vec<Node3>, String> {
+ let v: Value = serde_json::from_str(json).map_err(|e| format!("raea: the scene isn't JSON: {e}"))?;
+ let list = v.as_array().ok_or("raea: the scene is a list of parts")?;
+ let mut seen = Vec::new();
+ let out = list.iter().map(|n| self.node(n, &mut seen)).collect::<Result<Vec<_>, _>>()?;
+ if self.kept.len() > seen.len() {
+ let seen: std::collections::HashSet<u64> = seen.into_iter().collect();
+ self.kept.retain(|k, _| seen.contains(k));
+ }
+ Ok(out)
+ }
+
+ fn node(&mut self, v: &Value, seen: &mut Vec<u64>) -> Result<Node3, String> {
+ let kind = v["k"].as_str().ok_or_else(|| format!("raea: a part with no kind: {v}"))?;
+ let id = v["i"].as_u64().ok_or_else(|| format!("raea: {kind} has no id"))?;
+ seen.push(id);
+ let had = self.kept.get(&id).cloned();
+ let props = match &v["p"] {
+ Value::String(s) => Arc::new(serde_json::from_str::<Map<String, Value>>(s).map_err(|e| format!("raea: {kind}'s props: {e}"))?),
+ Value::Null if v.get("p").is_some() => Arc::default(),
+ Value::Null => had.as_ref().map(|h| h.0.clone()).ok_or_else(|| format!("raea: {kind} #{id} sent without props, and none kept"))?,
+ p => return Err(format!("raea: {kind}'s props are JSON text, got {p}")),
+ };
+ let shape = match v.get("s") {
+ Some(Value::String(s)) => Some(s.as_str().into()),
+ Some(_) => None,
+ None => had.and_then(|h| h.1),
+ };
+ self.kept.insert(id, (props.clone(), shape.clone()));
+ let kids = match v["c"].as_array() {
+ Some(k) => k.iter().map(|n| self.node(n, seen)).collect::<Result<Vec<_>, _>>()?,
+ None => Vec::new(),
+ };
+ Ok(Node3 { kind: kind.into(), props, shape, kids: kids.into() })
+ }
+}
diff --git a/io/net/Cargo.toml b/io/net/Cargo.toml
index 3ee7402d..4d0dd256 100644
--- a/io/net/Cargo.toml
+++ b/io/net/Cargo.toml
@@ -14,5 +14,8 @@ ws = ["dep:tungstenite"]
raea-io-home = { path = "../../io/home" }
serde_json = "1"
base64 = "0.22"
-ureq = "2"
tungstenite = { version = "0.30", features = ["rustls-tls-webpki-roots"], optional = true }
+
+# HTTP(S) on the machine; a browser build (wasm32) fetches in the page, so it goes without (ring has no wasm32 randomness)
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+ureq = "2"
diff --git a/io/net/src/cache.rs b/io/net/src/cache.rs
index a3508de6..cae4d934 100644
--- a/io/net/src/cache.rs
+++ b/io/net/src/cache.rs
@@ -3,6 +3,7 @@
//! its key. RAEA_OFFLINE refuses what isn't cached.
use std::path::PathBuf;
+#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
const CHROME_UA: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
@@ -37,6 +38,10 @@ pub fn fetch(url: &str) -> Result<PathBuf, String> {
return Ok(named(path));
}
raea_io_home::offline(&format!("{url} (not in raea's cache)"))?;
+ #[cfg(target_arch = "wasm32")]
+ return Err(format!("{url}: no HTTP in a browser build (the page fetches it)"));
+ #[cfg(not(target_arch = "wasm32"))]
+ {
let agent = ureq::AgentBuilder::new().redirects(10).timeout(Duration::from_secs(300)).build();
let r = agent.get(url).set("User-Agent", if google { CHROME_UA } else { PLAIN_UA }).call().map_err(|e| format!("{url}: {e}"))?;
let mut bytes = Vec::new();
@@ -49,6 +54,7 @@ pub fn fetch(url: &str) -> Result<PathBuf, String> {
std::fs::write(&tmp, &bytes).map_err(|e| e.to_string())?;
std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
Ok(named(path))
+ }
}
/// fetch, read.
diff --git a/io/net/src/http.rs b/io/net/src/http.rs
index 736e130d..1b9194b2 100644
--- a/io/net/src/http.rs
+++ b/io/net/src/http.rs
@@ -3,13 +3,20 @@
//! {url, method, headers: [[k, v]], body: base64 | null, redirect: "follow" | "error" | "manual"}
//! -> {status, statusText, headers: [[k, v]], body: base64, url, redirected}; a network failure is an Err
+#[cfg(not(target_arch = "wasm32"))]
use std::io::Read;
+#[cfg(not(target_arch = "wasm32"))]
use std::time::Duration;
+#[cfg(not(target_arch = "wasm32"))]
use base64::Engine as _;
+#[cfg(not(target_arch = "wasm32"))]
use base64::engine::general_purpose::STANDARD as B64;
-use serde_json::{Value, json};
+#[cfg(not(target_arch = "wasm32"))]
+use serde_json::json;
+use serde_json::Value;
+#[cfg(not(target_arch = "wasm32"))]
/// One request, sent: any status is an answer; Err only when none came (the connection, TLS, a timeout).
pub fn send(req: ureq::Request, body: Option<&[u8]>) -> Result<ureq::Response, ureq::Transport> {
let r = match body {
@@ -22,11 +29,19 @@ pub fn send(req: ureq::Request, body: Option<&[u8]>) -> Result<ureq::Response, u
}
}
+#[cfg(not(target_arch = "wasm32"))]
/// An answer's headers, names lowercase, a repeated header once a value.
pub fn headers(resp: &ureq::Response) -> Vec<(String, String)> {
resp.headers_names().iter().flat_map(|n| resp.all(n).into_iter().map(|v| (n.to_ascii_lowercase(), v.to_string()))).collect()
}
+#[cfg(target_arch = "wasm32")]
+/// A browser build has no HTTP of its own: the page fetches.
+pub fn fetch(args: &Value) -> Result<Value, String> {
+ Err(format!("{}: no HTTP in a browser build (the page fetches it)", args["url"].as_str().unwrap_or("?")))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
/// The page's net.fetch, made on the calling thread.
pub fn fetch(args: &Value) -> Result<Value, String> {
let url = args["url"].as_str().ok_or("no url")?;
diff --git a/io/net/src/lib.rs b/io/net/src/lib.rs
index be5124d0..0e9eee23 100644
--- a/io/net/src/lib.rs
+++ b/io/net/src/lib.rs
@@ -7,6 +7,7 @@ pub mod http;
#[cfg(feature = "ws")]
pub mod ws;
+#[cfg(not(target_arch = "wasm32"))]
pub use ureq;
/// A `data:` URL's media type (lowercase, "" when it names none) and its bytes: base64 when a `;base64` parameter says
diff --git a/runtime/export/src/program.rs b/runtime/export/src/program.rs
index 716aad1e..50837959 100644
--- a/runtime/export/src/program.rs
+++ b/runtime/export/src/program.rs
@@ -14,12 +14,15 @@ pub(crate) fn program(frames: &[(i64, Frame)], w: u32, h: u32, fps: f64) -> raea
r
};
// --alpha: nothing under the pages, so what the composition leaves empty stays transparent
- let clear = if ALPHA.load(std::sync::atomic::Ordering::Relaxed) { "#00000000".into() } else { frames.first().and_then(|(_, f)| f.clear.clone()).and_then(|c| hex_of(&c)).unwrap_or("#000000".into()) };
let has3d = frames.iter().any(|(_, f)| !f.scene.is_empty());
+ // with no holder background: black under 2D pages, and for 3D no `bg`, so the camera clears to Bevy's ClearColor
+ // resource (srgb 43, 44, 47 unless a <BevyResource type="bevy_camera::clear_color::ClearColor"> sets it), as a Bevy
+ // scene does (docs/control conventions C17)
+ let clear = if ALPHA.load(std::sync::atomic::Ordering::Relaxed) { Some("#00000000".into()) } else { frames.first().and_then(|(_, f)| f.clear.clone()).and_then(|c| hex_of(&c)).or_else(|| (!has3d).then(|| "#000000".into())) };
if has3d && ALPHA.load(std::sync::atomic::Ordering::Relaxed) {
eprintln!("raea: --alpha keeps 2D pages and <Video> clips transparent; the frames with 3D are drawn over the 3D and come out opaque");
}
- let mut cam = row("cam", vec![("bg", V::S(clear))]);
+ let mut cam = row("cam", clear.map(|c| ("bg", V::S(c))).into_iter().collect());
if has3d {
// where it is and looks, frame by frame; its lens, ambient light and post-processing (scene3d)
scene3d::camera(frames, &mut p, &mut cam);
diff --git a/runtime/plugins/src/reflect.rs b/runtime/plugins/src/reflect.rs
index acd979c2..0236e571 100644
--- a/runtime/plugins/src/reflect.rs
+++ b/runtime/plugins/src/reflect.rs
@@ -6,7 +6,15 @@ use super::*;
/// Before the first frame: every asset a handle field loaded by path, loaded with its dependencies (a material's
/// textures), or the load's error.
pub fn await_loads(app: &mut App) -> Result<(), String> {
- let t0 = std::time::Instant::now();
+ #[cfg(target_arch = "wasm32")]
+ return { let _ = app; Ok(()) };
+ #[cfg(not(target_arch = "wasm32"))]
+ await_loads_here(app)
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn await_loads_here(app: &mut App) -> Result<(), String> {
+ let t0 = bevy::platform::time::Instant::now();
loop {
let world = app.world_mut();
let Some(l) = world.get_resource::<Loading>() else { return Ok(()) };
diff --git a/runtime/scene/src/grass.rs b/runtime/scene/src/grass.rs
new file mode 100644
index 00000000..3b4e23b6
--- /dev/null
+++ b/runtime/scene/src/grass.rs
@@ -0,0 +1,21 @@
+//! Fields of grass' rows (`<Grass>`, sdk/render/src/3d/grass.tsx): a `grass` row each, its spec (the grids the edit
+//! sampled and the blades' look, as JSON) and whether it casts shadows; systems/grass makes its blades. A field is
+//! the first frame's: it doesn't change over the shot (the wind that moves it is the paint look's).
+
+use super::*;
+
+pub(super) fn rows(tracks: &[Track], p: &mut Program) {
+ for (k, (_, track)) in tracks.iter().enumerate() {
+ let its = filled(track);
+ let first = &its[0].props;
+ let Some(spec) = first.get("spec").filter(|s| s.is_object()) else { continue };
+ let id = format!("grass{k}");
+ let mut row = BTreeMap::new();
+ row.insert("id".into(), V::S(id));
+ row.insert("grass".into(), V::S(spec.to_string()));
+ if first.get("shadow").and_then(Value::as_bool) == Some(true) {
+ row.insert("shadow".into(), V::N(1.0));
+ }
+ p.spawns.push(("grass".into(), vec![row]));
+ }
+}
diff --git a/runtime/scene/src/lib.rs b/runtime/scene/src/lib.rs
index 517aee43..77c852d4 100644
--- a/runtime/scene/src/lib.rs
+++ b/runtime/scene/src/lib.rs
@@ -31,6 +31,8 @@ mod sprite2d;
/// <Instances>: a mesh or model row's placements (its `inst` column).
/// Baked simulations' and glitches' rows (<MeshSequence>, <Goo>, glitch props).
mod meshseq;
+/// Fields of grass' rows (<Grass>).
+mod grass;
fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
let item = |kind: &'static str, world: Mat4, material: Option<Node3>| Item { kind, props: n.props.clone(), shape: n.shape.clone(), material, world };
@@ -157,6 +159,8 @@ fn walk(n: &Node3, parent: Mat4, out: &mut Vec<Item>) {
"Shadows" => out.push(item("shadows", parent, None)),
"FogVolume" => out.push(item("fogvolume", parent * local(&n.props), None)),
"Fire" => out.push(item("fire", parent * local(&n.props), None)),
+ // a field of grass made by the engine from its grids (<Grass>): grass.rs
+ "Grass" => out.push(item("grass", Mat4::IDENTITY, None)),
"Splat" => out.push(item("splat", parent * local(&n.props), None)),
// 2D over the 3D (<Sprite>, <Shape2D>): placed in composition px by their own props, not by groups
"Sprite" => out.push(item("sprite", Mat4::IDENTITY, None)),
@@ -301,6 +305,7 @@ struct Tracks {
decals: Vec<Track>,
fogs: Vec<Track>,
fires: Vec<Track>,
+ grasses: Vec<Track>,
splats: Vec<Track>,
sprites: Vec<Track>,
shapes2d: Vec<Track>,
@@ -320,6 +325,7 @@ impl Tracks {
decals: tracks_of(all, &["decal"]),
fogs: tracks_of(all, &["fogvolume"]),
fires: tracks_of(all, &["fire"]),
+ grasses: tracks_of(all, &["grass"]),
splats: tracks_of(all, &["splat"]),
sprites: tracks_of(all, &["sprite"]),
shapes2d: tracks_of(all, &["shape2d"]),
@@ -347,6 +353,8 @@ fn rows_into_of(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
plates_rows(tr, p);
fogs_rows(tr, p);
fires_rows(tr, p);
+ // fields of grass (<Grass>): grass.rs
+ grass::rows(&tr.grasses, p);
// gaussian splats (<Splat>): splat.rs
splat::rows(&tr.splats, p);
// 2D over the 3D (<Sprite>, <Shape2D>): sprite2d.rs
diff --git a/runtime/scene/src/live.rs b/runtime/scene/src/live.rs
index ab4cda63..272cc127 100644
--- a/runtime/scene/src/live.rs
+++ b/runtime/scene/src/live.rs
@@ -77,7 +77,11 @@ impl LiveScene {
let mut p = Program::default();
let mut cam = BTreeMap::new();
cam.insert("id".into(), V::S("cam".into()));
- cam.insert("bg".into(), V::S(f.clear.and_then(hex_of).unwrap_or("#000000".into())));
+ // the holder's background as the clear colour; with none, Bevy's ClearColor resource (srgb 43, 44, 47 unless a
+ // <BevyResource type="bevy_camera::clear_color::ClearColor"> sets it), not black (docs/control conventions C17)
+ if let Some(bg) = f.clear.and_then(hex_of) {
+ cam.insert("bg".into(), V::S(bg));
+ }
camera(&all, &mut p, &mut cam);
if !all[0].iter().any(|i| i.kind == "camera") {
// no camera this frame: a render holds the one before (filled)
diff --git a/runtime/scene/src/models.rs b/runtime/scene/src/models.rs
index c6717431..53c3ef3e 100644
--- a/runtime/scene/src/models.rs
+++ b/runtime/scene/src/models.rs
@@ -175,6 +175,10 @@ pub(crate) fn panels_rows(tr: &Tracks, names: &[String], p: &mut Program) {
if first.get("shadow").and_then(Value::as_bool) == Some(false) {
row.insert("shadow".into(), V::N(0.0));
}
+ // cut out at half alpha instead of blended (a baked cloud's card): no surface where it's clear, its shadow its shape
+ if first.get("cutout").and_then(Value::as_bool) == Some(true) {
+ row.insert("cutout".into(), V::N(1.0));
+ }
sheet(p, &mut row, &id, &its);
placement(p, &mut row, &id, &its);
visible(p, &mut row, &id, &track);
diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs
index 57a3786e..33456f83 100644
--- a/runtime/scene/src/parts.rs
+++ b/runtime/scene/src/parts.rs
@@ -231,6 +231,10 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) {
if its[0].props.get("shadow").and_then(Value::as_str) == Some("only") {
row.insert("shadow_only".into(), V::N(1.0));
}
+ // `shadow: "catch"`: only the shadows falling on it are drawn (raea-render's shadow_catch.rs)
+ if its[0].props.get("shadow").and_then(Value::as_str) == Some("catch") {
+ row.insert("shadow_catch".into(), V::N(1.0));
+ }
// `receiveShadow: false`: no shadow falls on it (NotShadowReceiver)
if its[0].props.get("receiveShadow") == Some(&Value::Bool(false)) {
row.insert("receive".into(), V::N(0.0));
diff --git a/runtime/scene3d/Cargo.toml b/runtime/scene3d/Cargo.toml
index df39bfaa..ab8be656 100644
--- a/runtime/scene3d/Cargo.toml
+++ b/runtime/scene3d/Cargo.toml
@@ -20,5 +20,10 @@ raea-sys-compose = { path = "../../systems/compose" }
raea-sys-look = { path = "../../systems/look" }
raea-runtime-plugins = { path = "../plugins" }
raea-core-program = { path = "../../core/program" }
-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", "bevy_gilrs"] }
+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", "area_light_luts", "bevy_gilrs"] }
serde_json = "1"
+
+[features]
+# soft shadows (PCSS: a light's softShadow in raea/3d), native only: Bevy 0.20's PCSS samples depth maps with a
+# filtering sampler, which WebGPU refuses, so a browser build (raea-web) goes without and its shadows are filtered (PCF)
+pcss = ["bevy/experimental_pbr_pcss"]
diff --git a/runtime/scene3d/src/light.rs b/runtime/scene3d/src/light.rs
index 75b7c368..ee9678af 100644
--- a/runtime/scene3d/src/light.rs
+++ b/runtime/scene3d/src/light.rs
@@ -25,7 +25,16 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {
match kind {
"point" => {
world.entity_mut(e).insert((
- PointLight { color, intensity: g("lumens", 1.0e6), range: g("range", 20.0), radius, shadow_maps_enabled: (flag(vals, "shadows", false) || volumetric) && !preview(), soft_shadows_enabled: soft > 0.0, ..default() },
+ PointLight {
+ color,
+ intensity: g("lumens", 1.0e6),
+ range: g("range", 20.0),
+ radius,
+ shadow_maps_enabled: (flag(vals, "shadows", false) || volumetric) && !preview(),
+ #[cfg(feature = "pcss")]
+ soft_shadows_enabled: soft > 0.0,
+ ..default()
+ },
Transform::from_translation(pos),
));
}
@@ -40,7 +49,18 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {
"spot" => {
let outer = g("outer", std::f32::consts::FRAC_PI_4);
world.entity_mut(e).insert((
- SpotLight { color, intensity: g("lumens", 1.0e6), range: g("range", 20.0), radius, soft_shadows_enabled: soft > 0.0, outer_angle: outer, inner_angle: g("inner", 0.0).min(outer), shadow_maps_enabled: (flag(vals, "shadows", false) || volumetric) && !preview(), ..default() },
+ SpotLight {
+ color,
+ intensity: g("lumens", 1.0e6),
+ range: g("range", 20.0),
+ radius,
+ #[cfg(feature = "pcss")]
+ soft_shadows_enabled: soft > 0.0,
+ outer_angle: outer,
+ inner_angle: g("inner", 0.0).min(outer),
+ shadow_maps_enabled: (flag(vals, "shadows", false) || volumetric) && !preview(),
+ ..default()
+ },
Transform::from_translation(pos).looking_to(dir, up_for(dir)),
));
}
@@ -56,7 +76,14 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {
}
.build();
world.entity_mut(e).insert((
- DirectionalLight { color, illuminance: g("lux", 8000.0), shadow_maps_enabled: (flag(vals, "shadows", true) || volumetric) && !preview(), soft_shadow_size: (soft > 0.0).then_some(soft), ..default() },
+ DirectionalLight {
+ color,
+ illuminance: g("lux", 8000.0),
+ shadow_maps_enabled: (flag(vals, "shadows", true) || volumetric) && !preview(),
+ #[cfg(feature = "pcss")]
+ soft_shadow_size: (soft > 0.0).then_some(soft),
+ ..default()
+ },
cascades,
Transform::default().looking_to(dir, up_for(dir)),
));
@@ -81,7 +108,10 @@ pub fn light(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) {
}
}
// soft shadows (PCSS): a sun's size as seen from the scene, or a point or spot light's radius; the shadow's
- // penumbra widens with the distance from what casts it, as a real one's does
+ // penumbra widens with the distance from what casts it, as a real one's does. Native only (the pcss feature):
+ // Bevy 0.20's PCSS samples depth maps with a filtering sampler, which WebGPU refuses, so a browser's shadows are
+ // filtered (PCF) without the penumbra
+ #[cfg(feature = "pcss")]
if let Some(soft) = vals.get("soft").map(|v| v.num() as f32).filter(|s| *s > 0.0 && !preview()) {
let mut em = world.entity_mut(e);
if let Some(mut l) = em.get_mut::<DirectionalLight>() {
diff --git a/runtime/scene3d/src/model.rs b/runtime/scene3d/src/model.rs
index 4f390341..ba4d1722 100644
--- a/runtime/scene3d/src/model.rs
+++ b/runtime/scene3d/src/model.rs
@@ -322,12 +322,19 @@ pub fn toon_models(world: &mut World) {
super::shade_scene(world);
}
+/// A browser loads models on its own event loop, between frames: a live frame there draws the models that are ready.
+#[cfg(target_arch = "wasm32")]
+pub fn await_models(_app: &mut App) -> Result<(), String> {
+ Ok(())
+}
+
/// Every model ready (loaded, spawned, its clip set up, its toon surfaces on) before the first frame is drawn: a frame
/// never shows a model half-loaded. It gives up when no model has moved a stage (loaded, spawned, ready, surfaces on) for
/// 60 s, not after 60 s in all: prechorus's 477 models load for about a minute and then turn ready together, so at load
/// 13-20 a count of ready models alone refused it half the time (10-26).
+#[cfg(not(target_arch = "wasm32"))]
pub fn await_models(app: &mut App) -> Result<(), String> {
- let mut t0 = std::time::Instant::now();
+ let mut t0 = bevy::platform::time::Instant::now();
let mut most = 0usize;
loop {
let world = app.world_mut();
@@ -356,7 +363,7 @@ pub fn await_models(app: &mut App) -> Result<(), String> {
}
if done > most {
most = done;
- t0 = std::time::Instant::now();
+ t0 = bevy::platform::time::Instant::now();
}
if t0.elapsed().as_secs_f64() > 60.0 {
let [l, s, r] = stages;
diff --git a/sdk/guides/craft/bevy.md b/sdk/guides/craft/bevy.md
index a328acb6..bdf98a7a 100644
--- a/sdk/guides/craft/bevy.md
+++ b/sdk/guides/craft/bevy.md
@@ -1,4 +1,4 @@
-# 3D and games with Bevy, through raea/3d
+# 3D and games with Bevy, in Bevy's names
You write 3D the way you write the rest of a composition: TSX components whose props are worked out from the frame.
raea's engine turns them into Bevy entities (meshes, lights, cameras, glTF models, post-processing) and draws them
@@ -33,14 +33,17 @@ pieces; then write the file. Each file's example is a complete composition you c
## What exists
-`Canvas3D`, `PerspectiveCamera {position, lookAt, fov}`, `Group`, `Mesh {name, position, rotation, scale}` holding
-one geometry (`Box`, `Sphere`, `Plane`, `Cylinder`, `Cone`, `Torus`, `Text3D`, or `shape={manifold...}`) and one
-material (`MeshStandardMaterial`, `MeshPhysicalMaterial`, `MeshBasicMaterial`, `MeshToonMaterial` with ink `outline`),
-`AmbientLight`, `DirectionalLight`,
-`PointLight`, `SpotLight`, `Model {src, animation, time}`, `ImagePlane {src, width}`, `Decal {src, size, normal}`,
-`Refinish {materials}`, `Bloom`, `Fog`, `ToneMapping`,
-and the ECS world (`raea/ecs`) drawn with `<Entities>`. Everything 3D imports from `raea/3d`;
-`staticFile`, `useCurrentFrame` and the rest from `raea`.
+Bevy's names, with Bevy's fields and units: `Camera3d {transform, projection}` (`raea/camera`), `Transform`
+and `Quat` (`raea/transform`: `Transform.fromXyz(0, 2, 7).lookingAt([0, 0.5, 0])`), `Mesh3d {name, transform}`
+holding one shape (`Cuboid`, `Sphere`, `Plane3d`, `Cylinder`, `Cone`, `Torus`, `Capsule3d`: `raea/mesh`; `Text3D`, or
+`shape={manifold...}`) and one material (`StandardMaterial` with `base_color`, `perceptual_roughness`, `metallic`,
+`emissive`, `unlit`, clearcoat and transmission as its fields; `ToonMaterial` for cel shading and ink outlines;
+`ExtendedMaterial` for a shader of your own: `raea/pbr`), `Entity {transform}` to group parts, the lights in lux and lumens
+(`DirectionalLight {illuminance}`, `PointLight`, `SpotLight`, `RectLight {intensity}`, `AmbientLight {brightness}`,
+and `light_consts` for Bevy's named values: `raea/light`), `Model {src, animation, time}`, `ImagePlane {src, width}`,
+`Decal {src, size, normal}`, `Refinish {materials}`, `Bloom`, `Fog`, `ToneMapping`, and the ECS world (`raea/ecs`)
+drawn with `<Entities>`. `Canvas3D` (`raea/3d`) holds the 3D under the page; `staticFile`, `useCurrentFrame` and
+the rest come from `raea`.
## The rules that keep a render equal to its play
@@ -49,8 +52,9 @@ and the ECS world (`raea/ecs`) drawn with `<Entities>`. Everything 3D imports fr
`useRef` or `useFrame` mutation: there is no render loop to mutate in. `Math.random()` is seeded for each frame, so
it draws new numbers every frame: seed a scatter or anything that holds still from an index. `Date` is the frame's
time.
-2. **Radians for rotation**, on Mesh, Group, Model and ImagePlane (`Math.PI / 4`, not `45`). Manifold's
- `.rotate()` is the one place that takes degrees.
+2. **Radians and quaternions for rotation**: a Transform turns by `Quat.fromRotationY(Math.PI / 4)` or
+ `.lookingAt(...)`, never degrees; a Model and an ImagePlane take radians. Manifold's `.rotate()` is the one place
+ that takes degrees.
3. **Colours are hex** (`"#ff7a00"`), from the brand kit in a branded piece. CSS variables don't reach the 3D.
4. **Name what comes and goes.** Parts are matched across frames by `name`, else by kind and shape in tree order.
A Mesh that appears, disappears or swaps places with one of the same shape needs a `name`.
@@ -58,8 +62,10 @@ and the ECS world (`raea/ecs`) drawn with `<Entities>`. Everything 3D imports fr
roughness and metalness; don't change `args` or `shape` frame to frame (that's a new part each frame).
6. **One camera, one set of effects.** The first camera in the tree is used. Bloom, Fog and ToneMapping take their
first frame's values; the lens (Fisheye, LensDistortion) and MotionBlur animate per frame.
-7. **Import what you use.** Every component in the scene (`PointLight`, `Sphere`, `Bloom`...) comes from
- `raea/3d` in the import line; a missing one fails the render. `staticFile`, `Sequence`, `spring` and the
+7. **Import what you use.** Every component in the scene comes from its module in the import line (`Camera3d`
+ from `raea/camera`, `Mesh3d` and `Cuboid` from `raea/mesh`, `StandardMaterial` from `raea/pbr`, the lights from
+ `raea/light`, `Transform` from `raea/transform`, `Canvas3D`, `Bloom` and the rest from `raea/3d`); a missing one
+ fails the render. `staticFile`, `Sequence`, `spring` and the
hooks come from `raea`.
8. **Render and look.** Render stills where things happen (`raea render edit.tsx --at A,B,C -o stills/`) and look at them. A 3D frame that renders
black usually has no light or a camera inside or behind the subject.
diff --git a/sdk/guides/craft/bevy/lights.md b/sdk/guides/craft/bevy/lights.md
index 112259f0..829fb6c6 100644
--- a/sdk/guides/craft/bevy/lights.md
+++ b/sdk/guides/craft/bevy/lights.md
@@ -25,8 +25,9 @@ with `.lookingAt(point)`.
- Shadows: a light casts them with `shadow_maps_enabled` (Bevy's default is none, so write it on the sun). Point and
spot lights cast them the same way. Every mesh casts and receives. A floor (a wide thin Cuboid) is what makes
shadows read. A Mesh3d's `shadow={false}` casts none; `shadow="only"` casts its shadow (and blocks the sun's shafts
- in fog) without being drawn: a roof or wall out of frame, a blind's slats. Clouds, smoke and contrails cast too
- (post.md).
+ in fog) without being drawn: a roof or wall out of frame, a blind's slats. `shadow="catch"` is the reverse: only the
+ shadows falling on it are drawn, in its material's colour and opacity, and it's clear elsewhere (a floor under a
+ product over a picture or the page; three.js's ShadowMaterial). Clouds, smoke and contrails cast too (post.md).
- Shadow quality: by default the maps are 4096 texels a side and the sun's four cascades cover 150 m from the camera,
the first ending at 8 m, so shadows are sharp up close and still there down a long street. For a different scale
put one `<Shadows>` beside the camera: `distance` (metres the sun's shadows reach; shorter is sharper),
diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.ts
index fe881fd5..c890d829 100644
--- a/sdk/r3f/src/input/kinds.ts
+++ b/sdk/r3f/src/input/kinds.ts
@@ -53,7 +53,7 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:
MeshMatcapMaterial: { status: "near", raea: "MeshBasicMaterial in its colour", note: "the matcap's lighting is left out" },
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: "none", raea: "not drawn", note: "raea has no surface that only catches shadows" },
+ 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" },
diff --git a/sdk/r3f/src/input/material.ts b/sdk/r3f/src/input/material.ts
index 76240467..9952daae 100644
--- a/sdk/r3f/src/input/material.ts
+++ b/sdk/r3f/src/input/material.ts
@@ -15,6 +15,8 @@ export interface Part {
children?: Part[];
/** a MeshNormalMaterial: the mesh's normals become its vertex colours */
normals?: boolean;
+ /** a ShadowMaterial: the mesh shows only the shadows falling on it (raea's shadow="catch") */
+ catchShadow?: boolean;
}
const hex = (c: THREE.Color) => "#" + c.getHexString();
@@ -158,8 +160,7 @@ export function materialOf(m: THREE.Material, vertexColors: boolean): Part {
return { type: "MeshBasicMaterial", props: { color: "#808080" } };
case "ShadowMaterial": {
const s = m as THREE.ShadowMaterial;
- warnOnce(m.type, "only catches shadows, which raea has no surface for: it isn't drawn");
- return { type: "", props: { color: hex(s.color), opacity: s.opacity } };
+ 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
diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.ts
index 9e19de96..ba550657 100644
--- a/sdk/r3f/src/input/scene.ts
+++ b/sdk/r3f/src/input/scene.ts
@@ -71,6 +71,7 @@ function meshParts(mesh: THREE.Mesh, name: string, w: Walk, at: Props): Part[] {
if (!surface.type) return;
if (surface.normals) arrays = normalColours(arrays, mesh, w.camera);
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] });
});
return out;
diff --git a/sdk/r3f/src/parts.tsx b/sdk/r3f/src/parts.tsx
index f1cf2429..f04dc7dd 100644
--- a/sdk/r3f/src/parts.tsx
+++ b/sdk/r3f/src/parts.tsx
@@ -3,10 +3,12 @@
// components.
import type { ReactNode } from "react";
import {
- AmbientLight, BufferMesh, DirectionalLight, Environment, Fog, Gizmo, Group, Instances, Mesh, MeshBasicMaterial,
- MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight,
- RectAreaLight, SpotLight, ToneMapping,
+ BufferMesh, Environment, Fog, Gizmo, Instances, ToneMapping,
} from "raea/3d";
+import {
+ AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
+ MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight, RectAreaLight, SpotLight,
+} from "@raea/render/three";
import type { Part } from "./input/material";
export type { Part, Props } from "./input/material";
diff --git a/sdk/r3f/src/three/kinds.ts b/sdk/r3f/src/three/kinds.ts
index b85db656..5219a58d 100644
--- a/sdk/r3f/src/three/kinds.ts
+++ b/sdk/r3f/src/three/kinds.ts
@@ -6,14 +6,16 @@
// setting a setting of the renderer or the scene, not an object (tone mapping, shadows, fog)
// effect a frame effect, drawn by effects.ts with three's EffectComposer (<Raea> runs it; a three app calls
// Effects.set and render); `note` says where it differs from raea's engine
-// engine Bevy's own (a component, a resource, a WESL shader, a compute pass): it runs in raea's engine only
+// engine Bevy's own (a component, a resource, a WESL shader, a compute pass, raymarched fog): GPU code and ECS
+// data that three.js has no counterpart for. On the web, raea-web (engine/web, @raea/web) runs raea's own
+// engine in the page on WebGPU, the same rows and passes (docs/web-export.md says what stays native)
export type Status = "drawn" | "near" | "setting" | "effect" | "engine";
export const KINDS: Record<string, { status: Status; three: string; note?: string }> = {
Canvas3D: { status: "drawn", three: "the Scene the parts hang from" },
Group: { status: "drawn", three: "Group" },
Entity: { status: "drawn", three: "Group (an ECS entity's transform); a Gizmo component in it is drawn as lines" },
- Mesh: { status: "drawn", three: "Mesh, or InstancedMesh when it has `at`" },
+ Mesh: { status: "drawn", three: "Mesh, or InstancedMesh when it has `at`; shadow=\"catch\" a ShadowMaterial in its material's colour and opacity" },
Box: { status: "drawn", three: "three's BoxGeometry with the same args (the same surface; three's own segment counts)" },
Sphere: { status: "drawn", three: "three's SphereGeometry with the same args (the same surface; three's own segment counts)" },
Plane: { status: "drawn", three: "three's PlaneGeometry with the same args (the same surface; three's own segment counts)" },
diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.ts
index cc18720f..ece4a02d 100644
--- a/sdk/r3f/src/three/scene.ts
+++ b/sdk/r3f/src/three/scene.ts
@@ -316,9 +316,19 @@ export class Scene3d {
// a material inside a Model re-covers it (read there)
if (owner?.kind === "Model") return k;
const mesh = owner?.obj instanceof THREE.Mesh ? owner.obj : undefined;
- if (!k.material || k.material.type !== MATERIAL[kind]().type) {
+ // shadow="catch": only the shadows falling on it, in this material's colour and opacity (three's ShadowMaterial)
+ const catches = !!mesh && (JSON.parse(el.parentElement?.getAttribute("data-props") ?? "{}") as Props).shadow === "catch";
+ const make = catches ? () => new THREE.ShadowMaterial({ transparent: true }) : MATERIAL[kind];
+ if (!k.material || k.material.type !== (catches ? "ShadowMaterial" : MATERIAL[kind]().type)) {
k.material?.dispose();
- k.material = MATERIAL[kind]();
+ k.material = make();
+ }
+ if (catches) {
+ const s = k.material as THREE.ShadowMaterial;
+ s.color.set((p.color as string | undefined) ?? "#000000");
+ s.opacity = typeof p.opacity === "number" ? p.opacity : 1;
+ mesh.material = s;
+ return k;
}
if (mesh) {
mesh.material = k.material;
diff --git a/sdk/r3f/test/parity/fixtures.tsx b/sdk/r3f/test/parity/fixtures.tsx
index 2ab58ac7..4bee6702 100644
--- a/sdk/r3f/test/parity/fixtures.tsx
+++ b/sdk/r3f/test/parity/fixtures.tsx
@@ -6,9 +6,12 @@ import { useRef, type ReactNode } from "react";
import * as THREE from "three";
import { useCurrentFrame } from "raea";
import {
- AmbientLight, Bloom, Cuboid, Grade, LensDistortion, DirectionalLight, Fog, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
- PerspectiveCamera, PointLight, RectAreaLight, Sphere, SpotLight, Text3D, ToneMapping, Torus,
+ Bloom, Cuboid, Grade, LensDistortion, Fog, Sphere, Text3D, ToneMapping, Torus,
} from "raea/3d";
+import {
+ AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
+ PerspectiveCamera, PointLight, RectAreaLight, SpotLight,
+} from "@raea/render/three";
import { AbsoluteFill } from "raea";
export const SIZE = { width: 640, height: 360, fps: 24 };
@@ -122,6 +125,26 @@ export const INPUTS: Record<string, InputCase> = {
</>
),
},
+ // 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 },
+ frame: 0,
+ scene: () => (
+ <>
+ <color attach="background" args={["#d8c9a8"]} />
+ <ambientLight intensity={0.5} />
+ <directionalLight position={[2, 5, 1]} intensity={2.5} castShadow />
+ <mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow>
+ <planeGeometry args={[12, 12]} />
+ <shadowMaterial color="#1a1030" opacity={0.6} />
+ </mesh>
+ <mesh position={[0, 0.6, 0]} rotation={[0, 0.5, 0]} castShadow>
+ <boxGeometry args={[1, 1.2, 1]} />
+ <meshStandardMaterial color="#e05a2b" roughness={0.5} />
+ </mesh>
+ </>
+ ),
+ },
};
// ---- raea compositions ----
@@ -207,6 +230,25 @@ function OutEffects({ fx }: { fx: "bloom" | "grade" | "lens" }) {
);
}
+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>
+ );
+}
+
export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number }> = {
basic: { component: () => <OutBasic />, frame: 24 },
// raea's default tone mapping, TonyMcMapface
@@ -216,4 +258,6 @@ export const OUTPUTS: Record<string, { component: () => ReactNode; frame: number
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 },
};
diff --git a/sdk/r3f/test/roundtrip.test.tsx b/sdk/r3f/test/roundtrip.test.tsx
index ad01a15c..a3c46346 100644
--- a/sdk/r3f/test/roundtrip.test.tsx
+++ b/sdk/r3f/test/roundtrip.test.tsx
@@ -4,9 +4,12 @@
import { describe, expect, test } from "bun:test";
import * as THREE from "three";
import {
- AmbientLight, BufferMesh, Cuboid, DirectionalLight, Fog, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial,
- MeshStandardMaterial, PerspectiveCamera, PointLight, RectAreaLight, Sphere, SpotLight, ToneMapping, Torus,
+ BufferMesh, Cuboid, Fog, Sphere, ToneMapping, Torus,
} from "raea/3d";
+import {
+ AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,
+ PerspectiveCamera, PointLight, RectAreaLight, SpotLight,
+} from "@raea/render/three";
import { Scene3d } from "../src/three/scene";
import { convert } from "../src/input/scene";
import { stepTo, end, standInRenderer } from "../src/input/session";
diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.sh
index f36c2d4e..61fdb749 100755
--- a/sdk/r3f/tools/parity.sh
+++ b/sdk/r3f/tools/parity.sh
@@ -9,7 +9,7 @@ OUT=${1:-$(mktemp -d)}
URL=${R3F_PARITY_URL:-serve}
[ -f wasm/raea_shape_web.js ] || tools/shape-wasm.sh
MIN=${MIN:-0.92}
-CASES=(in-basic:24 in-lights:0 in-things:0 out-basic:24 out-tony:24 out-lights:0 out-bloom:0 out-grade:0 out-lens:0 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0)
+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 src-basic:24 src-tony:24 src-lights:0 src-bloom:0 src-grade:0 src-lens:0 src-catch:0)
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
diff --git a/sdk/r3f/tools/shoot.ts b/sdk/r3f/tools/shoot.ts
index 43451662..2bc6127b 100644
--- a/sdk/r3f/tools/shoot.ts
+++ b/sdk/r3f/tools/shoot.ts
@@ -8,7 +8,7 @@ const [baseArg, out, ...only] = process.argv.slice(2);
if (!baseArg || !out) throw new Error("usage: bun tools/shoot.ts BASE_URL|serve OUT_DIR [in-basic ...]");
const served = baseArg === "serve" ? await serve() : undefined;
const base = served?.url ?? baseArg;
-const cases = only.length ? only : ["in-basic", "in-lights", "in-things", "out-basic", "out-tony", "out-lights", "out-bloom", "out-grade", "out-lens", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens"];
+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", "src-basic", "src-tony", "src-lights", "src-bloom", "src-grade", "src-lens", "src-catch"];
let failed = 0;
for (const c of cases) {
const [dir, name] = c.split("-");
diff --git a/sdk/raea/bench/bevy-ts/cases/rect-light.tsx b/sdk/raea/bench/bevy-ts/cases/rect-light.tsx
index eab75e21..cf951e1b 100644
--- a/sdk/raea/bench/bevy-ts/cases/rect-light.tsx
+++ b/sdk/raea/bench/bevy-ts/cases/rect-light.tsx
@@ -2,7 +2,8 @@
// A white floor lit by one rectangular area light above it (Bevy's RectLight), nothing else: lit in the middle.
// probe: 32 32 r>60
import { AbsoluteFill, Composition, registerRoot } from "raea";
-import { Canvas3D, RectAreaLight } from "raea/3d";
+import { Canvas3D } from "raea/3d";
+import { RectLight } from "raea/light";
import { StandardMaterial } from "raea/pbr";
import { Cuboid, Mesh3d } from "raea/mesh";
import { Transform } from "raea/transform";
@@ -13,7 +14,7 @@ function Shot() {
<AbsoluteFill style={{ background: "#000" }}>
<Canvas3D layered>
<Camera3d transform={Transform.fromXyz(0, 6, 0.01).lookingAt([0, 0, 0])} projection={{ Perspective: { fov: 0.698131700797732 } }} />
- <RectAreaLight position={[0, 2, 0]} target={[0, 0, 0]} width={2} height={2} intensity={1} />
+ <RectLight transform={Transform.fromXyz(0, 2, 0).lookingAt([0, 0, 0])} width={2} height={2} intensity={900000} />
<Mesh3d name="floor"><Cuboid half_size={[4, 0.05, 4]} /><StandardMaterial base_color="#ffffff" perceptual_roughness={1} /></Mesh3d>
</Canvas3D>
</AbsoluteFill>
diff --git a/sdk/raea/conformance/bevy3d.test.tsx b/sdk/raea/conformance/bevy3d.test.tsx
index 5af15212..7054ed73 100644
--- a/sdk/raea/conformance/bevy3d.test.tsx
+++ b/sdk/raea/conformance/bevy3d.test.tsx
@@ -1,8 +1,9 @@
// Bevy's names for 3D (docs/sdk.feature S2a): Transform and Quat as Bevy's, and Mesh3d, Camera3d, StandardMaterial and
// the shape primitives drawing what the three.js-shaped names draw for the same scene.
import { describe, expect, test } from "bun:test";
-import * as three from "../src/3d";
-import { Capsule, Cuboid, Capsule3d, Cylinder, DepthOfField, Entity, Group, Mesh, Model, MeshBasicMaterial, MeshStandardMaterial, MeshToonMaterial, PerspectiveCamera, Plane3d, Screen, Sphere, Torus } from "../src/3d";
+import * as three from "@raea/render/three";
+import { Capsule, Cuboid, Capsule3d, Cylinder, DepthOfField, Entity, Model, Plane3d, Screen, Sphere, Torus } from "../src/3d";
+import { Group, Mesh, MeshBasicMaterial, MeshStandardMaterial, MeshToonMaterial, PerspectiveCamera } from "@raea/render/three";
// the retired three.js shapes, compared against (M5: no longer exported from raea)
import { Box, Plane } from "@raea/render/3d/shapes";
import { Affine2, AmbientLight, Camera3d, DirectionalLight, ExtendedMaterial, GridExtension, LinearRgba, PaintExtension, ToonExtension, WearExtension, Mesh3d, PointLight, Quat, RectLight, SpotLight, Srgba, StandardMaterial, Transform, eulerOf, light_consts } from "@raea/render/bevy3d";
diff --git a/sdk/raea/conformance/character-materials.test.tsx b/sdk/raea/conformance/character-materials.test.tsx
index 081c9d38..f7cae06e 100644
--- a/sdk/raea/conformance/character-materials.test.tsx
+++ b/sdk/raea/conformance/character-materials.test.tsx
@@ -3,7 +3,8 @@
// engine the nodes the old MeshStandardMaterial and MeshPhysicalMaterial with `shader` did.
import { expect, test } from "bun:test";
import { renderFrame } from "../src/test";
-import { MeshPhysicalMaterial, MeshStandardMaterial, Model } from "@raea/render/3d";
+import { Model } from "@raea/render/3d";
+import { MeshPhysicalMaterial, MeshStandardMaterial } from "@raea/render/three";
import { ExtendedMaterial, ShaderExtension, StandardMaterial } from "@raea/render/bevy3d";
import { HAIR_WESL } from "@raea/character/character/hair";
import { SKIN_WESL } from "@raea/character/character/skin";
diff --git a/sdk/raea/conformance/extensions.test.tsx b/sdk/raea/conformance/extensions.test.tsx
index e5a933ae..8cb2aa56 100644
--- a/sdk/raea/conformance/extensions.test.tsx
+++ b/sdk/raea/conformance/extensions.test.tsx
@@ -3,7 +3,8 @@
// over the 3D", "Games: state from input, frame by frame").
import { beforeEach, describe, expect, test } from "bun:test";
import { Audio, Region, lyria, proofBoxes, sao, useGameEvents, useGameState, useInput, useRegion } from "../src";
-import { Canvas3D, Cylinder, DirectionalLight, Fisheye, LensDistortion, Mesh, MeshStandardMaterial, MeshToonMaterial, Model, MotionBlur, PointLight, Sphere } from "../src/3d";
+import { Canvas3D, Cylinder, Fisheye, LensDistortion, Model, MotionBlur, Sphere } from "../src/3d";
+import { DirectionalLight, Mesh, MeshStandardMaterial, MeshToonMaterial, PointLight } from "@raea/render/three";
// the retired three.js shapes, compared against (M5: no longer exported from raea)
import { Box, Plane } from "@raea/render/3d/shapes";
import { renderFrame } from "../src/test";
diff --git a/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx b/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx
index 2410bd92..32600a91 100644
--- a/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx
+++ b/sdk/raea/conformance/golden/04-mesh-sign/edit.tsx
@@ -1,6 +1,6 @@
// golden case 04: a Manifold shape in Bevy (a sign with SALE cut through it), turning, under a camera and two lights
import { AbsoluteFill, interpolate, useCurrentFrame } from "../../../src";
-import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";
+import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "@raea/render/three";
export default function Sign() {
const frame = useCurrentFrame();
diff --git a/sdk/raea/conformance/golden/06-world-entities/edit.tsx b/sdk/raea/conformance/golden/06-world-entities/edit.tsx
index c92227b9..b3f2de9e 100644
--- a/sdk/raea/conformance/golden/06-world-entities/edit.tsx
+++ b/sdk/raea/conformance/golden/06-world-entities/edit.tsx
@@ -2,7 +2,8 @@
// (cylinder) as its child, turned by a system each frame; the gun's Transform is in the ship's space. The reference
// (edit.rrl) is lowered from reference.tsx, which places the same meshes by hand with <Mesh>.
import { AbsoluteFill, useCurrentFrame } from "../../../src";
-import { AmbientLight, DirectionalLight, Entities, PerspectiveCamera } from "../../../src/3d";
+import { Entities } from "../../../src/3d";
+import { AmbientLight, DirectionalLight, PerspectiveCamera } from "@raea/render/three";
import { createWorld } from "raea/ecs";
const game = createWorld();
diff --git a/sdk/raea/conformance/golden/06-world-entities/reference.tsx b/sdk/raea/conformance/golden/06-world-entities/reference.tsx
index 4dfc1026..4f5b7888 100644
--- a/sdk/raea/conformance/golden/06-world-entities/reference.tsx
+++ b/sdk/raea/conformance/golden/06-world-entities/reference.tsx
@@ -1,7 +1,7 @@
// the same picture as edit.tsx, placed by hand: the ship turned by 0.05 rad a frame, the gun 0.6 above its centre (a
// point on the turning axis, so it stays put while it turns with the ship)
import { AbsoluteFill, useCurrentFrame } from "../../../src";
-import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "../../../src/3d";
+import { AmbientLight, DirectionalLight, Mesh, MeshStandardMaterial, PerspectiveCamera } from "@raea/render/three";
export default function Ships() {
const f = useCurrentFrame();
diff --git a/sdk/raea/conformance/instances.test.tsx b/sdk/raea/conformance/instances.test.tsx
index 23100f7e..4ae8f07c 100644
--- a/sdk/raea/conformance/instances.test.tsx
+++ b/sdk/raea/conformance/instances.test.tsx
@@ -1,7 +1,8 @@
// <Instances> and scatter(): placements packed 9 numbers a copy onto a Mesh or Model node, the errors, and scatter's
// determinism, spacing, avoid, clearOf, ground height and density.
import { describe, expect, test } from "bun:test";
-import { BufferMesh, Cuboid, Instances, MeshStandardMaterial, MeshToonMaterial, scatter } from "raea/3d";
+import { BufferMesh, Cuboid, Instances, scatter } from "raea/3d";
+import { MeshStandardMaterial, MeshToonMaterial } from "@raea/render/three";
import { renderFrame } from "../src/test";
const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 30, durationInFrames: 30 });
diff --git a/sdk/raea/conformance/volume-light.test.tsx b/sdk/raea/conformance/volume-light.test.tsx
index 3440b025..1a1224f1 100644
--- a/sdk/raea/conformance/volume-light.test.tsx
+++ b/sdk/raea/conformance/volume-light.test.tsx
@@ -4,7 +4,8 @@
// shadow of their own); `shadow` scales or turns that off and goes to the row as a number; a Mesh's `shadow="only"`
// casts without being drawn.
import { describe, expect, test } from "bun:test";
-import { Canvas3D, Mesh, MeshStandardMaterial, Volume } from "../src/3d";
+import { Canvas3D, Volume } from "../src/3d";
+import { Mesh, MeshStandardMaterial } from "@raea/render/three";
// the retired three.js shapes, compared against (M5: no longer exported from raea)
import { Box } from "@raea/render/3d/shapes";
import { renderFrame } from "../src/test";
diff --git a/sdk/raea/docs/bevy-coverage.md b/sdk/raea/docs/bevy-coverage.md
index 9c2bb706..9fcd7212 100644
--- a/sdk/raea/docs/bevy-coverage.md
+++ b/sdk/raea/docs/bevy-coverage.md
@@ -76,7 +76,7 @@ missing features: the SDK component or hook, the rows and columns, and the raea-
| Spot light | covered | `SpotLight {position, target, angle, penumbra, ...}` | `light type='spot': ... dir_* outer inner` | |
| Ambient light | covered | `AmbientLight {intensity, color}` (summed) | `camera.ambient ambient_color`, keyed | |
| Environment map / IBL, skybox | covered | `<Environment src intensity rotation background backgroundIntensity>` inside Canvas3D: an equirectangular `.hdr` (image crate), `.exr` (decoded by ffmpeg as a PFM) or `.png`/`.jpg` (sRGB); src, intensity, rotation and the sky change per frame | `camera.env_srcs` (JSON list) `env_i` (index, -1 none) `env_k` (cd/m², intensity 1 = 1000) `env_rot` `sky_k`, keyed; engine/render/src/engine/environment.rs: each panorama a CPU-built Rgba16Float cubemap (face = widest width / 4, a power of two from 64 to 2048, one size for all), `GeneratedEnvironmentMapLight` (GPU-filtered every frame from the source the frame picks, fixed blue noise) + `Skybox`; `sync_environment` swaps source, intensity and rotation on both it and the `EnvironmentMapLight` it made | untested in a live game's scene; looked models (`look=`) are drawn by their own camera, which doesn't copy it; light probes / irradiance volumes (one environment for the whole scene); filtering every frame costs 4.5 ms at 1080p from a 1k panorama: caching each panorama's filtered maps would make it free after the first frame |
-| Shadows | partial | `castShadow` per light (directional on by default); every mesh casts and receives; `<Shadows mapSize distance firstCascade cascades overlap bias normalBias filter>` (defaults 4096, 150 m, 8 m, 4, 0.3, Bevy's biases, gaussian); `softShadow` on a light: PCSS (`experimental_pbr_pcss`), `true` or a sun's `soft_shadow_size` / a bulb's radius in metres, its penumbra dithered in a fixed pattern (the gaussian or hardware filter, never the temporal one), so a render equals its play; `<Cloud>`, `<Smoke>`, `<Contrail>` cast into the shadow maps (`shadow`, 1 by default: each texel marches the light's ray through the volume's field and writes where it has stopped half the light, `engine/render/src/engine/volume_shadow.wesl`), so they shadow meshes and the volumetric fog's shafts break round them; `<Mesh shadow="only">` casts without being drawn (`engine/render/src/engine/shadow_only.rs`) | `fire.shadow` (a volume's), `mesh.shadow_only`; `light.shadows shadow_dist shadow_first shadow_cascades shadow_overlap shadow_bias shadow_nbias soft`; `camera.shadow_map shadow_filter` (DirectionalLightShadowMap, PointLightShadowMap at half, ShadowFilteringMethod) | `castShadow`/`receiveShadow` on Mesh → `NotShadowCaster`, `NotShadowReceiver`; the temporal filter (it reseeds by the frame count); per-frame shadow settings |
+| Shadows | partial | `castShadow` per light (directional on by default); every mesh casts and receives; `<Shadows mapSize distance firstCascade cascades overlap bias normalBias filter>` (defaults 4096, 150 m, 8 m, 4, 0.3, Bevy's biases, gaussian); `softShadow` on a light: PCSS (`experimental_pbr_pcss`), `true` or a sun's `soft_shadow_size` / a bulb's radius in metres, its penumbra dithered in a fixed pattern (the gaussian or hardware filter, never the temporal one), so a render equals its play; `<Cloud>`, `<Smoke>`, `<Contrail>` cast into the shadow maps (`shadow`, 1 by default: each texel marches the light's ray through the volume's field and writes where it has stopped half the light, `engine/render/src/engine/volume_shadow.wesl`), so they shadow meshes and the volumetric fog's shafts break round them; `<Mesh shadow="only">` casts without being drawn (`systems/material/src/shadow_only.rs`); `<Mesh shadow="catch">` draws only the shadows falling on it, in its material's colour and opacity (`systems/material/src/shadow_catch.rs`) | `fire.shadow` (a volume's), `mesh.shadow_only`, `mesh.shadow_catch`; `light.shadows shadow_dist shadow_first shadow_cascades shadow_overlap shadow_bias shadow_nbias soft`; `camera.shadow_map shadow_filter` (DirectionalLightShadowMap, PointLightShadowMap at half, ShadowFilteringMethod) | `castShadow`/`receiveShadow` on Mesh → `NotShadowCaster`, `NotShadowReceiver`; the temporal filter (it reseeds by the frame count); per-frame shadow settings |
| Perspective camera | covered | `PerspectiveCamera {position, lookAt, fov, near, far}`, animated | `camera: x y z look_* fov near far`, keyed | |
| Orthographic camera | missing | | | `<OrthographicCamera zoom>` → `camera.ortho` → `Projection::Orthographic` |
| Several cameras, viewports | missing | the first camera wins | | split-screen is rare in ads; a `viewport` column per camera |
diff --git a/sdk/raea/src/camera.ts b/sdk/raea/src/camera.ts
index 1ec6c1e5..cc97ed3f 100644
--- a/sdk/raea/src/camera.ts
+++ b/sdk/raea/src/camera.ts
@@ -1,7 +1,7 @@
// docs/sdk.feature S1b (M1): a Bevy-named entry point, re-exporting what today lives in the files named. Sources move
// into it at M5; until then the old subpaths and this one export the same values.
// raea/camera (bevy_camera): cameras and the views they make.
-export { Canvas3D, PerspectiveCamera, OrthographicCamera, type Canvas3DProps, type PerspectiveCameraProps, type OrthographicCameraProps } from "./3d";
+export { Canvas3D, type Canvas3DProps } from "./3d";
export { Matchmove, useMatchmove, matchmoveView, matchmoveIndex, checkMatchmove, type MatchmoveProps, type MatchmoveSolve, type MatchmoveState, type MatchmoveCamera } from "@raea/render/matchmove";
export { Camera3d, type Camera3dProps, type Projection } from "@raea/render/bevy3d";
// a Bevy texture (a camera's target) drawn in an element (B3 H7)
diff --git a/sdk/raea/src/mesh.ts b/sdk/raea/src/mesh.ts
index e49c7881..4feed682 100644
--- a/sdk/raea/src/mesh.ts
+++ b/sdk/raea/src/mesh.ts
@@ -1,7 +1,7 @@
// docs/sdk.feature S1b (M1): a Bevy-named entry point, re-exporting what today lives in the files named. Sources move
// into it at M5; until then the old subpaths and this one export the same values.
// raea/mesh (bevy_mesh, bevy_shape): shapes and solids.
-export { Mesh, Sphere, Cylinder, Torus, Cone, Capsule, BufferMesh, type MeshProps, type SphereProps, type CylinderProps, type TorusProps, type ConeProps, type CapsuleProps, type BufferMeshProps, type Animate3d } from "./3d";
+export { Sphere, Cylinder, Torus, Cone, Capsule, BufferMesh, type SphereProps, type CylinderProps, type TorusProps, type ConeProps, type CapsuleProps, type BufferMeshProps, type Animate3d } from "./3d";
export * from "@raea/render/solid";
export { Mesh3d, ConicalFrustum, type Mesh3dProps, type ConicalFrustumProps } from "@raea/render/bevy3d";
export { Cuboid, Capsule3d, Plane3d, type CuboidProps, type Capsule3dProps, type Plane3dProps } from "./3d";
diff --git a/sdk/raea/src/pbr.ts b/sdk/raea/src/pbr.ts
index 4574787e..5b1a80e8 100644
--- a/sdk/raea/src/pbr.ts
+++ b/sdk/raea/src/pbr.ts
@@ -1,7 +1,7 @@
// docs/sdk.feature S1b (M1): a Bevy-named entry point, re-exporting what today lives in the files named. Sources move
// into it at M5; until then the old subpaths and this one export the same values.
// raea/pbr (bevy_pbr, bevy_material): materials, fog, volumes and the paint look's things.
-export { MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial, MeshToonMaterial, SurfaceShader, Refinish, Fog, VolumetricFog, FogVolume, Fire, Decal, ShaderMesh, AmbientOcclusion, type MeshStandardMaterialProps, type MeshPhysicalMaterialProps, type MeshBasicMaterialProps, type MeshToonMaterialProps, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonRim, type ToonHighlight, type ToonOutline, type FogProps, type VolumetricFogProps, type FogVolumeProps, type FireProps, type DecalProps, type ShaderMeshProps, type AmbientOcclusionProps } from "./3d";
+export { SurfaceShader, Refinish, Fog, VolumetricFog, FogVolume, Fire, Decal, ShaderMesh, AmbientOcclusion, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonRim, type ToonHighlight, type ToonOutline, type FogProps, type VolumetricFogProps, type FogVolumeProps, type FireProps, type DecalProps, type ShaderMeshProps, type AmbientOcclusionProps } from "./3d";
export * from "@raea/render/splat";
export * from "@raea/render/paint";
export { StandardMaterial, ExtendedMaterial, ToonMaterial, type ToonMaterialProps, GridExtension, PaintExtension, WearExtension, ToonExtension, ShaderExtension, type StandardMaterialProps, type StandardMaterialAnimate, type ToonExtensionAnimate, type ExtendedMaterialProps, type GridExtensionProps, type PaintExtensionProps, type WearExtensionProps, type ToonExtensionProps, type ShaderExtensionProps, type AlphaMode, type SampledImage, type MetallicRoughnessMaps } from "@raea/render/bevy3d";
diff --git a/sdk/raea/src/prelude.ts b/sdk/raea/src/prelude.ts
index 92c245be..6ad853c1 100644
--- a/sdk/raea/src/prelude.ts
+++ b/sdk/raea/src/prelude.ts
@@ -6,6 +6,5 @@ export * from "./3d";
export * from "@raea/render/bevy3d";
// both export a Group (the 3D element; animate.tsx's plan type): the element wins, as a re-export (a const would keep
// 3D code in a 2D bundle, and live play opens a 3D engine for any bundle holding data-3d: runtime/live/src/lib.rs)
-export { Group } from "./3d";
// /3d and Bevy's both name the lights: the prelude's are Bevy's, in Bevy's units (lux, lumens, cd/m²), as /light's
export { AmbientLight, DirectionalLight, PointLight, SpotLight, type AmbientLightProps, type DirectionalLightProps, type PointLightProps, type SpotLightProps } from "@raea/render/bevy3d";
diff --git a/sdk/raea/src/transform.ts b/sdk/raea/src/transform.ts
index 2d260273..18b3eb6f 100644
--- a/sdk/raea/src/transform.ts
+++ b/sdk/raea/src/transform.ts
@@ -1,5 +1,5 @@
// docs/sdk.feature S1b (M1): a Bevy-named entry point, re-exporting what today lives in the files named. Sources move
// into it at M5; until then the old subpaths and this one export the same values.
// raea/transform (bevy_transform): where things are, and nesting.
-export { Group, surfaceTurn, type GroupProps, type Vec3 } from "./3d";
+export { surfaceTurn, type Vec3 } from "./3d";
export { Transform, Quat, eulerOf, type EulerRot, type TransformValue, type TransformBuilt } from "@raea/render/bevy3d";
diff --git a/sdk/render/package.json b/sdk/render/package.json
index 4d688ffc..82d1acc3 100644
--- a/sdk/render/package.json
+++ b/sdk/render/package.json
@@ -17,6 +17,7 @@
"./pick": "./src/pick.ts",
"./splat": "./src/splat.tsx",
"./3d": "./src/3d.tsx",
+ "./three": "./src/three.tsx",
"./plugin": "./src/plugin.ts",
"./screen": "./src/screen.tsx",
"./bevy-own": "./src/bevy-own.gen.tsx"
diff --git a/sdk/render/src/3d.tsx b/sdk/render/src/3d.tsx
index a5b7ee93..237619fb 100644
--- a/sdk/render/src/3d.tsx
+++ b/sdk/render/src/3d.tsx
@@ -2,8 +2,8 @@
// carries its name (data-3d) and props (data-props, JSON) for Bevy to draw; a Mesh also carries its Manifold
// expression (data-shape). Engine-safe: this module imports nothing beyond React.
import { toHex } from "./colour";
-export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, Mesh, MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial, MeshToonMaterial, SurfaceShader, surfaceShader, samplerSpec, FramePass, Compute, AmbientLight, DirectionalLight, PointLight, SpotLight, RectAreaLight, Atmosphere, PerspectiveCamera, OrthographicCamera, eulerOf, Entity, Refinish, Group, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter } from "./3d/all";
-export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, MeshProps, Animate3d, SurfaceDrawProps, MeshStandardMaterialProps, MeshPhysicalMaterialProps, MeshBasicMaterialProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, MeshToonMaterialProps, SurfaceShaderSpec, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, AmbientLightProps, DirectionalLightProps, PointLightProps, SpotLightProps, RectAreaLightProps, AtmosphereProps, PerspectiveCameraProps, BevyParts, OrthographicCameraProps, EntityProps, GroupProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions } from "./3d/all";
+export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, surfaceShader, samplerSpec, FramePass, Compute, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";
+export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";
export { CrossSection, crossSection, manifold, outline, Solid, type Bounds, type Polygons, type Section } from "./solid";
diff --git a/sdk/render/src/3d/all.ts b/sdk/render/src/3d/all.ts
index 67a2131d..2dc04f5a 100644
--- a/sdk/render/src/3d/all.ts
+++ b/sdk/render/src/3d/all.ts
@@ -13,3 +13,4 @@ export * from "./text";
export * from "./shapes";
export * from "./sprite";
export * from "./instances";
+export * from "./grass";
diff --git a/sdk/render/src/3d/bevy.tsx b/sdk/render/src/3d/bevy.tsx
index 94c951e4..e6cbfd1b 100644
--- a/sdk/render/src/3d/bevy.tsx
+++ b/sdk/render/src/3d/bevy.tsx
@@ -95,7 +95,6 @@ export interface ShaderMeshProps {
/** A mesh drawn by a material written here in WESL or WGSL (docs/bevy-ts.feature G20): one generic Bevy material
* (rdb's ShaderMaterial, an AsBindGroup of 16 uniform slots and 4 textures) whose fragment shader is this source, so
* a dissolve, a toon ramp, a hologram or a procedural pattern needs no Rust. Uniforms are set at load.
- * @bevy bevy_mesh::components::Mesh3d
* @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_sys_material::shader_material::ShaderMaterial> */
export function ShaderMesh({ shape, wesl, wgsl, uniforms = {}, textures = {}, defs, alpha, doubleSided, ...place }: ShaderMeshProps) {
if ((wesl === undefined) === (wgsl === undefined)) throw new TypeError("ShaderMesh: give its source as wesl (or wgsl), one of them");
diff --git a/sdk/render/src/3d/grass.tsx b/sdk/render/src/3d/grass.tsx
new file mode 100644
index 00000000..d9dad808
--- /dev/null
+++ b/sdk/render/src/3d/grass.tsx
@@ -0,0 +1,99 @@
+// <Grass>: a field of stylized grass the engine makes itself (raea-sys-grass) from a few functions of the ground,
+// sampled once into grids, instead of a placement per clump: clumps of tapered, leaning blades, root to tip in their
+// patch's greens with a warm highlight on each tip, their normals the ground's. The field is cut into tiles, each as
+// detailed as its distance from the camera asks, so a frame draws what it can show and a phone keeps up. Under a paint
+// look (<Look mode="paint" wind>) the wind bends the blades, on a slope as on the flat.
+import { type PlanBox } from "./all";
+
+/** One step of detail: tiles nearer than `to` metres draw `keep` of their clumps (0 to 1), each with its first
+ * `blades` blades in `segments` segments, `widen` times as wide. */
+export interface GrassLod {
+ to: number;
+ keep: number;
+ blades: number;
+ segments: number;
+ widen: number;
+}
+
+export interface GrassProps {
+ name?: string;
+ /** the ground the field covers: a box on the plan (x, z, metres) */
+ area: PlanBox;
+ /** the ground's height at (x, z): the clumps stand on it, tilted to its slope */
+ height: (x: number, z: number) => number;
+ /** clumps per square metre at (x, z) (0: bare) */
+ density: number | ((x: number, z: number) => number);
+ /** which of `tints` the point (x, z) belongs to (0 everywhere without it) */
+ patch?: (x: number, z: number) => number;
+ /** a multiple of the clumps' size at (x, z) (1 without it) */
+ size?: (x: number, z: number) => number;
+ /** each patch's root and tip colours: ["#2c4a1a", "#5f8a2c"] */
+ tints?: [string, string][];
+ /** the tips' highlight colour ("#f2e7a0") and how much of it each tip takes (0.22) */
+ highlight?: string;
+ highlightMix?: number;
+ /** blades in a clump (14), their height in metres (0.3; each 0.55 to 1.3 times it), width range ([0.034, 0.05]) */
+ blades?: number;
+ bladeHeight?: number;
+ width?: [number, number];
+ /** how far from its clump's centre a blade stands (0.06 m), and how far it leans over its height ([0.2, 0.7]) */
+ spread?: number;
+ lean?: [number, number];
+ /** each clump's scale, a random pick between these ([0.85, 1.35]), times `size` */
+ scale?: [number, number];
+ seed?: number;
+ /** grid points a metre the functions are sampled at (2) */
+ resolution?: number;
+ /** a tile's side in metres (4) */
+ tile?: number;
+ /** the steps of detail, nearest first (the engine's: every clump within 5 m, half of them in 8 blades to 14 m, a
+ * fifth in 5 blades beyond) */
+ lod?: GrassLod[];
+ /** cast shadows (false) */
+ shadow?: boolean;
+}
+
+const fn = (f: number | ((x: number, z: number) => number)) => (typeof f === "number" ? () => f : f);
+const r4 = (v: number) => Math.round(v * 1e4) / 1e4;
+
+/** The part's props as the page carries them, made once per field: React draws the part every frame, and a field's
+ * grids are thousands of numbers. Kept by its `height` function and remade when anything else is new. */
+const made = new WeakMap<object, { deps: unknown[]; json: string }>();
+
+function spec(p: GrassProps): string {
+ const deps = [p.density, p.patch, p.size, JSON.stringify({ ...p, height: 0, density: typeof p.density === "number" ? p.density : 0, patch: 0, size: 0 })];
+ const had = made.get(p.height);
+ if (had && had.deps.every((d, i) => d === deps[i])) return had.json;
+ const { min, max } = p.area;
+ if (!(max[0] > min[0] && max[1] > min[1])) throw new RangeError(`Grass: area's max is past its min on both axes, got ${JSON.stringify(p.area)}`);
+ const res = Math.max(0.1, p.resolution ?? 2);
+ const nx = Math.max(2, Math.ceil((max[0] - min[0]) * res) + 1), nz = Math.max(2, Math.ceil((max[1] - min[1]) * res) + 1);
+ const height: number[] = [], density: number[] = [], patch: number[] = [], size: number[] = [];
+ const d = fn(p.density), pa = p.patch, sz = p.size;
+ for (let k = 0; k < nz; k++) {
+ for (let i = 0; i < nx; i++) {
+ const x = min[0] + ((max[0] - min[0]) * i) / (nx - 1), z = min[1] + ((max[1] - min[1]) * k) / (nz - 1);
+ height.push(r4(p.height(x, z)));
+ density.push(r4(Math.max(0, d(x, z))));
+ if (pa) patch.push(Math.max(0, Math.round(pa(x, z))));
+ if (sz) size.push(r4(sz(x, z)));
+ }
+ }
+ if (![...height, ...density].every(Number.isFinite)) throw new RangeError("Grass: height and density are finite everywhere in the area");
+ const s = {
+ area: [min[0], min[1], max[0], max[1]], grid: [nx, nz], height, density,
+ ...(pa && { patch }), ...(sz && { size }),
+ tints: p.tints, highlight: p.highlight, highlightMix: p.highlightMix, blades: p.blades, bladeHeight: p.bladeHeight, width: p.width,
+ spread: p.spread, lean: p.lean, scale: p.scale, seed: p.seed, tile: p.tile, lod: p.lod,
+ };
+ const json = JSON.stringify({ name: p.name, shadow: p.shadow ?? false, spec: s });
+ made.set(p.height, { deps, json });
+ return json;
+}
+
+/** A field of grass over `area`, made by the engine from the ground's functions (sampled once at `resolution`).
+ */
+export function Grass(props: GrassProps) {
+ if (typeof props.height !== "function") throw new TypeError("Grass: height is a function of (x, z)");
+ return <div data-3d="Grass" data-props={spec(props)} />;
+}
diff --git a/sdk/render/src/3d/lights.tsx b/sdk/render/src/3d/lights.tsx
index 78a0cd2e..a681a7e8 100644
--- a/sdk/render/src/3d/lights.tsx
+++ b/sdk/render/src/3d/lights.tsx
@@ -14,7 +14,7 @@ export interface AmbientLightProps {
}
/** Light from everywhere at once.
- * @bevy bevy_light::ambient_light::AmbientLight */
+ */
export function AmbientLight({ intensity = 1, color = "#ffffff", ...rest }: AmbientLightProps & Pick<BevyUnits, "nits">) {
return node3d("AmbientLight", { ...rest, intensity, color: toHex("AmbientLight", "color", color) });
}
@@ -59,7 +59,7 @@ function checkLight(owner: string, p: { position?: Vec3; target?: Vec3; intensit
}
/** Parallel light (the sun) shining from `position` towards `target`.
- * @bevy bevy_light::directional_light::DirectionalLight */
+ */
export function DirectionalLight({ intensity = 1, color = "#ffffff", children, ...rest }: DirectionalLightProps & BevyParts & Pick<BevyUnits, "lux">) {
checkLight("DirectionalLight", { ...rest, intensity, color });
return node3d("DirectionalLight", { ...rest, intensity, color: toHex("DirectionalLight", "color", color) }, children);
@@ -96,7 +96,7 @@ export interface PointLightProps {
}
/** A bulb: light from a point, every way.
- * @bevy bevy_light::point_light::PointLight */
+ */
export function PointLight({ intensity = 1, color = "#ffffff", children, ...rest }: PointLightProps & BevyParts & Pick<BevyUnits, "lumens">) {
checkLight("PointLight", { ...rest, intensity, color });
return node3d("PointLight", { ...rest, intensity, color: toHex("PointLight", "color", color) }, children);
@@ -112,7 +112,7 @@ export interface SpotLightProps extends PointLightProps {
}
/** A cone of light from `position` towards `target`: a stage spot, a product hero light.
- * @bevy bevy_light::spot_light::SpotLight */
+ */
export function SpotLight({ intensity = 1, color = "#ffffff", children, ...rest }: SpotLightProps & BevyParts & Pick<BevyUnits, "lumens">) {
checkLight("SpotLight", { ...rest, intensity, color });
if (rest.angle !== undefined && !(rest.angle > 0 && rest.angle <= Math.PI / 2)) throw new RangeError(`SpotLight: angle is a half-angle in radians, in (0, π/2], got ${rest.angle}`);
@@ -137,7 +137,6 @@ export interface RectAreaLightProps {
/** A rectangle of light (Bevy's RectLight): a softbox, a window's glow, a TV's face, a light panel. Its light falls
* soft and wide from the whole face, not a point; it casts no shadows (Bevy 0.20 doesn't shadow area lights).
- * @bevy bevy_light::rect_light::RectLight
* @deprecated <RectLight> (lumens, width, height), raea/light */
export function RectAreaLight({ intensity = 1, color = "#ffffff", width = 1, height = 1, ...rest }: RectAreaLightProps & Pick<BevyUnits, "lumens">) {
checkLight("RectAreaLight", { ...rest, intensity, color });
@@ -179,9 +178,6 @@ export interface PerspectiveCameraProps {
}
/** The viewpoint the scene is drawn from.
- * @bevy bevy_camera::components::Camera3d
- * @bevy bevy_camera::camera::Camera
- * @bevy bevy_camera::projection::Projection
* @deprecated <Camera3d> with `projection={{ Perspective: { fov } }}` (fov in radians), raea/camera */
export function PerspectiveCamera({ fov = 50, children, ...rest }: PerspectiveCameraProps & BevyParts) {
if (rest.position !== undefined) checkVec("PerspectiveCamera", "position", rest.position);
diff --git a/sdk/render/src/3d/materials.tsx b/sdk/render/src/3d/materials.tsx
index c4f1be25..0fb43173 100644
--- a/sdk/render/src/3d/materials.tsx
+++ b/sdk/render/src/3d/materials.tsx
@@ -302,11 +302,8 @@ export function checkMaterial(owner: string, props: Record<string, unknown>): vo
}
/** A physically based surface for the Mesh it's inside.
- * @bevy bevy_pbr::pbr_material::StandardMaterial
* `grid` draws graph paper over it (engine/render grid.rs):
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_render::engine::grid::Grid>>
* `wear` chips, grimes and rusts it in the part's own space (systems/wear):
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_wear::Wear>>
* @deprecated <StandardMaterial>, raea/pbr (Bevy's fields: base_color, perceptual_roughness, metallic)
*/
export function MeshStandardMaterial(props: MeshStandardMaterialProps) {
@@ -332,7 +329,6 @@ export interface MeshPhysicalMaterialProps extends MeshStandardMaterialProps {
}
/** The standard surface plus a clearcoat layer and reflectance.
- * @bevy bevy_pbr::pbr_material::StandardMaterial
* @deprecated <StandardMaterial>, raea/pbr (clearcoat and specular_transmission are its fields) */
export function MeshPhysicalMaterial(props: MeshPhysicalMaterialProps) {
const anim = useAnimation3d(props.animate);
@@ -353,7 +349,6 @@ export interface MeshBasicMaterialProps extends SurfaceDrawProps {
}
/** A flat colour no light changes (unlit): signs, screens, backdrops.
- * @bevy bevy_pbr::pbr_material::StandardMaterial
* @deprecated <StandardMaterial unlit>, raea/pbr */
export function MeshBasicMaterial(props: MeshBasicMaterialProps) {
checkMaterial("MeshBasicMaterial", props as Record<string, unknown>);
@@ -426,8 +421,6 @@ export interface MeshToonMaterialProps {
/** A cel-shaded surface (three.js's MeshToonMaterial): lit by the scene's lights in hard bands, with an optional rim,
* highlight and ink outline. Inside a Mesh, or inside a Model to toon its glTF materials.
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_render::engine::toon::ToonExt>>
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::toon::OutlineMaterial>
* @deprecated <ToonMaterial>, raea/pbr */
export function MeshToonMaterial(props: MeshToonMaterialProps) {
const owner = "MeshToonMaterial";
diff --git a/sdk/render/src/3d/model.tsx b/sdk/render/src/3d/model.tsx
index cef19a51..b531012b 100644
--- a/sdk/render/src/3d/model.tsx
+++ b/sdk/render/src/3d/model.tsx
@@ -23,8 +23,6 @@ export interface OrthographicCameraProps extends Omit<PerspectiveCameraProps, "f
/** A camera without perspective: parallel lines stay parallel and size doesn't fall off with distance (isometric and
* top-down games, technical views, flat-shaded product shots). Placed and aimed as a PerspectiveCamera is.
- * @bevy bevy_camera::components::Camera3d
- * @bevy bevy_camera::projection::Projection
* @deprecated <Camera3d> with `projection={{ Orthographic: {} }}`, raea/camera */
export function OrthographicCamera({ height = 10, children, ...rest }: OrthographicCameraProps & BevyParts) {
if (rest.position !== undefined) checkVec("OrthographicCamera", "position", rest.position);
@@ -349,8 +347,13 @@ export interface ImagePlaneProps {
/** radians */
rotation?: Vec3;
scale?: number | Vec3;
+ /** a turn as a quaternion [x, y, z, w], instead of `rotation` (a card turned to face a point) */
+ quaternion?: [number, number, number, number];
/** false: the card casts no shadow (a cursor or a UI floating in the scene); true by default */
shadow?: boolean;
+ /** the picture cut out at half alpha instead of blended: its clear parts are no surface at all (no fog on them, no
+ * sorting) and its shadow is the picture's shape, not the card's. For hard-edged pictures: a baked cloud, a sprite */
+ cutout?: boolean;
/** a sprite sheet: the picture is `[columns, rows]` frames of equal size, read left to right, top to bottom, and the
* card shows one cell (its height follows one cell's shape). A texture atlas of a regular grid */
grid?: [number, number];
diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsx
index bd61dd82..914fc63b 100644
--- a/sdk/render/src/3d/shapes.tsx
+++ b/sdk/render/src/3d/shapes.tsx
@@ -190,7 +190,21 @@ export interface BufferMeshProps {
colors?: number[] | string[];
}
+/** Each mesh's shape text, checked and written once: React draws a <BufferMesh> every frame with the same arrays, and
+ * a terrain's are tens of thousands of numbers (checking and writing them took half a live frame in a browser). Kept by
+ * its positions array, and remade when any of its other arrays is a new one. */
+const shaped = new WeakMap<object, { of: unknown[]; text: string }>();
+
function bufferShape(p: BufferMeshProps): string {
+ const of = [p.indices, p.normals, p.uvs, p.colors];
+ const had = Array.isArray(p.positions) ? shaped.get(p.positions) : undefined;
+ if (had && had.of.every((a, i) => a === of[i])) return had.text;
+ const text = writeBufferShape(p);
+ shaped.set(p.positions, { of, text });
+ return text;
+}
+
+function writeBufferShape(p: BufferMeshProps): string {
const nums = (k: keyof BufferMeshProps, per: number) => {
const a = p[k];
if (a === undefined) return;
@@ -272,8 +286,9 @@ export interface MeshProps extends PointerHandlers3d {
/** false: it casts no shadow (a window's glass, which a blended surface otherwise does; a sky card; a UI floating in
* the scene). True by default. "only": it casts its shadow but isn't drawn (a roof or wall out of frame whose shadow
* falls into it, a blind's slats cutting the sun's shafts in the fog, a stand-in shape for something drawn another
- * way); its surface is ignored */
- shadow?: boolean | "only";
+ * way); its surface is ignored. "catch": it shows only the shadows falling on it, in its material's colour at its
+ * material's opacity, and is clear elsewhere (three.js's ShadowMaterial: a floor under a product over a picture) */
+ shadow?: boolean | "only" | "catch";
/** three.js's name for `shadow`'s true and false (`shadow` wins when both are given) */
castShadow?: boolean;
/** a page drawn on it over its UVs: the screen spec <Mesh3d> makes for a page element with layer="surface"
@@ -336,15 +351,9 @@ function boundsFromChildren(children: ReactNode): LocalBounds | undefined {
/** A drawn object: a geometry child (or `shape`) and a material child, placed by position, rotation and scale. Its
* on* props (onClick, onPointerDown, onPointerOver ...) are called as a page element's (events3d.tsx).
- * @bevy bevy_mesh::components::Mesh3d
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::pbr_material::StandardMaterial>
- * @bevy bevy_transform::components::transform::Transform
- * @bevy bevy_mesh::mesh::Mesh
- * castShadow={false} and receiveShadow={false} put Bevy's markers on it: @bevy bevy_light::NotShadowCaster
- * @bevy bevy_light::NotShadowReceiver
- * `layers` is its RenderLayers (a light's and a camera's too): @bevy bevy_camera::visibility::render_layers::RenderLayers
+ * castShadow={false} and receiveShadow={false} put Bevy's markers on it
+ * `layers` is its RenderLayers (a light's and a camera's too)
* shadow="only" draws it with the shadow-only material (engine/render shadow_only.rs):
- * @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::shadow_only::ShadowOnlyMaterial>
* @deprecated <Mesh3d>, raea/mesh (2D: <Mesh2d>, raea/sprite)
*/
export function Mesh(props: MeshProps) {
@@ -355,7 +364,7 @@ export function Mesh(props: MeshProps) {
if (typeof scale === "number") {
if (!(scale > 0) || !Number.isFinite(scale)) throw new RangeError(`Mesh: scale must be a positive number, got ${scale}`);
} else checkVec("Mesh", "scale", scale);
- if (props.shadow !== undefined && typeof props.shadow !== "boolean" && props.shadow !== "only") throw new TypeError(`Mesh: shadow is true, false or "only", got ${JSON.stringify(props.shadow)}`);
+ if (props.shadow !== undefined && typeof props.shadow !== "boolean" && props.shadow !== "only" && props.shadow !== "catch") throw new TypeError(`Mesh: shadow is true, false, "only" or "catch", got ${JSON.stringify(props.shadow)}`);
checkPass("Mesh", props.pass);
const manifold = shape instanceof Solid ? shape.expr : shape ?? shapeFromChildren(props.children);
const extra: Record<string, string> = {};
diff --git a/sdk/render/src/bevy3d/core.tsx b/sdk/render/src/bevy3d/core.tsx
index f6f00aa5..9f0ee43c 100644
--- a/sdk/render/src/bevy3d/core.tsx
+++ b/sdk/render/src/bevy3d/core.tsx
@@ -1,7 +1,8 @@
// Quat, Transform, Mesh3d and Camera3d.
import { Children, isValidElement, useId, type ReactNode } from "react";
import { meshLayers } from "../layers";
-import { AmbientLight as AmbientLight3, DepthOfField, Mesh, OrthographicCamera, PerspectiveCamera, dofOf, eulerOf, type DepthOfFieldProps, type MeshProps, type Vec3 } from "../3d";
+import { DepthOfField, dofOf, eulerOf, type DepthOfFieldProps, type Vec3 } from "../3d";
+import { AmbientLight as AmbientLight3, Mesh, OrthographicCamera, PerspectiveCamera, type MeshProps } from "../three";
import { Transform as TransformComponent } from "@raea/app/bevy";
import { AmbientLight, ambientOf, type AmbientLightProps } from "./all";
@@ -157,7 +158,14 @@ export interface Mesh3dProps extends Omit<MeshProps, "position" | "rotation" | "
}
/** Bevy's Mesh3d on an entity with its Transform: a shape (Cuboid, Sphere ...) and a material inside, and any page
- * element inside as a page layer in the world at it, or on it with layer="surface" (`meshLayers`). */
+ * element inside as a page layer in the world at it, or on it with layer="surface" (`meshLayers`).
+ * @bevy bevy_mesh::components::Mesh3d
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::pbr_material::StandardMaterial>
+ * castShadow={false} and receiveShadow={false} put Bevy's markers on it: @bevy bevy_light::NotShadowCaster
+ * @bevy bevy_light::NotShadowReceiver
+ * `layers` is its RenderLayers (a light's and a camera's too): @bevy bevy_camera::visibility::render_layers::RenderLayers
+ * shadow="only" draws it with the shadow-only material (engine/render shadow_only.rs):
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::shadow_only::ShadowOnlyMaterial> */
export function Mesh3d({ transform, visibility, children, ...rest }: Mesh3dProps) {
const id = useId();
if (visibility === "Hidden") return null;
@@ -185,7 +193,10 @@ export interface Camera3dProps {
children?: ReactNode;
}
-/** Bevy's Camera3d with its Transform and Projection: it looks along its -Z, +Y up, as Bevy's cameras do. */
+/** Bevy's Camera3d with its Transform and Projection: it looks along its -Z, +Y up, as Bevy's cameras do.
+ * @bevy bevy_camera::components::Camera3d
+ * @bevy bevy_camera::camera::Camera
+ * @bevy bevy_camera::projection::Projection */
export function Camera3d({ transform, projection = { Perspective: {} }, layers, children: kids }: Camera3dProps) {
// Bevy's DepthOfField on the camera: its focal_distance is the camera's focus, the rest the scene's DepthOfField
let dof: DepthOfFieldProps | undefined;
diff --git a/sdk/render/src/bevy3d/lights.tsx b/sdk/render/src/bevy3d/lights.tsx
index a02c7d70..ae905988 100644
--- a/sdk/render/src/bevy3d/lights.tsx
+++ b/sdk/render/src/bevy3d/lights.tsx
@@ -1,6 +1,7 @@
// Lights.
import { type ReactNode } from "react";
-import { AmbientLight as AmbientLight3, DirectionalLight as DirectionalLight3, PointLight as PointLight3, RectAreaLight, SpotLight as SpotLight3, type Vec3 } from "../3d";
+import { type Vec3 } from "../3d";
+import { AmbientLight as AmbientLight3, DirectionalLight as DirectionalLight3, PointLight as PointLight3, RectAreaLight, SpotLight as SpotLight3 } from "../three";
import { OLD_LIGHT_PROPS, Quat, TransformValue } from "./all";
function refuseOld(owner: string, props: Record<string, unknown>, allowed: readonly string[] = []) {
@@ -44,7 +45,8 @@ export interface PointLightProps extends LightCommon {
/** Shadows' size as 3d.tsx takes it: soft with the radius (or the default bulb) when soft_shadows_enabled. */
const soft = (p: { radius?: number; soft_shadows_enabled?: boolean }) => (p.soft_shadows_enabled ? (p.radius !== undefined && p.radius > 0 ? p.radius : true) : undefined);
-/** Bevy's PointLight: a bulb at its transform's translation, in lumens. */
+/** Bevy's PointLight: a bulb at its transform's translation, in lumens.
+ * @bevy bevy_light::point_light::PointLight */
export function PointLight(p: PointLightProps) {
refuseOld("PointLight", p as Record<string, unknown>, ["intensity"]);
const { transform, visibility, intensity = 1_000_000, range = 20, radius, shadow_maps_enabled = false, soft_shadows_enabled, ...rest } = p;
@@ -60,7 +62,8 @@ export interface SpotLightProps extends PointLightProps {
inner_angle?: number;
}
-/** Bevy's SpotLight: a cone along its transform's -Z, in lumens. */
+/** Bevy's SpotLight: a cone along its transform's -Z, in lumens.
+ * @bevy bevy_light::spot_light::SpotLight */
export function SpotLight(p: SpotLightProps) {
refuseOld("SpotLight", p as Record<string, unknown>, ["intensity"]);
const { transform, visibility, intensity = 1_000_000, range = 20, radius, shadow_maps_enabled = false, soft_shadows_enabled, outer_angle = Math.PI / 4, inner_angle = 0, ...rest } = p;
@@ -80,7 +83,8 @@ export interface DirectionalLightProps extends Omit<LightCommon, "children"> {
children?: ReactNode;
}
-/** Bevy's DirectionalLight: parallel light shining along its transform's -Z, in lux. */
+/** Bevy's DirectionalLight: parallel light shining along its transform's -Z, in lux.
+ * @bevy bevy_light::directional_light::DirectionalLight */
export function DirectionalLight(p: DirectionalLightProps) {
refuseOld("DirectionalLight", p as Record<string, unknown>);
const { transform, visibility, illuminance = 10_000, shadow_maps_enabled = false, soft_shadow_size, ...rest } = p;
@@ -97,7 +101,8 @@ export interface AmbientLightProps {
}
/** Bevy's AmbientLight (on the camera in 0.20; GlobalAmbientLight is the same light as a resource): light from
- * everywhere, in cd/m². */
+ * everywhere, in cd/m².
+ * @bevy bevy_light::ambient_light::AmbientLight */
export function AmbientLight(p: AmbientLightProps) {
return <AmbientLight3 {...ambientOf(p)} />;
}
@@ -124,7 +129,8 @@ export interface RectLightProps extends Omit<LightCommon, "children" | "volumetr
height?: number;
}
-/** Bevy's RectLight: a rectangle of light facing its transform's -Z, in lumens (no shadows in Bevy 0.20). */
+/** Bevy's RectLight: a rectangle of light facing its transform's -Z, in lumens (no shadows in Bevy 0.20).
+ * @bevy bevy_light::rect_light::RectLight */
export function RectLight(p: RectLightProps) {
refuseOld("RectLight", p as Record<string, unknown>, ["intensity"]);
const { transform, visibility, intensity = 1_000_000, range = 20, width = 1, height = 1, ...rest } = p;
diff --git a/sdk/render/src/bevy3d/materials.tsx b/sdk/render/src/bevy3d/materials.tsx
index 89ef21e1..92eed8e7 100644
--- a/sdk/render/src/bevy3d/materials.tsx
+++ b/sdk/render/src/bevy3d/materials.tsx
@@ -3,7 +3,8 @@ import { isValidElement, useContext, type ReactElement, type ReactNode } from "r
import type { TrackSpec } from "@raea/math/animate";
import { InModel } from "../3d/all";
import { LinearRgba, MADE_FROM, baseOf, emissiveOf, type Affine2, type Srgba } from "./all";
-import { MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, samplerSpec, surfaceShader, type MeshStandardMaterialProps, type SamplerSpec, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonHighlight, type ToonOutline, type ToonRim } from "../3d";
+import { samplerSpec, surfaceShader, type SamplerSpec, type SurfaceShaderSpec, type SurfaceDrawProps, type ToonBand, type ToonHighlight, type ToonOutline, type ToonRim } from "../3d";
+import { MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, type MeshStandardMaterialProps } from "../three";
/** A picture read with its own sampler: Bevy's load_with_settings, whose ImageLoaderSettings give the Image its
* ImageSamplerDescriptor ({ path: "checker.png", sampler: { filter: "nearest" } } for hard pixels). */
@@ -211,7 +212,8 @@ function uvOf(t: Affine2 | undefined): { repeat?: [number, number]; uvTransform?
}
/** Bevy's StandardMaterial for the Mesh3d it's inside. Unlit draws as MeshBasicMaterial; a clearcoat or transmission
- * as MeshPhysicalMaterial; anything else as MeshStandardMaterial, all on Bevy's StandardMaterial in the engine. */
+ * as MeshPhysicalMaterial; anything else as MeshStandardMaterial, all on Bevy's StandardMaterial in the engine.
+ * @bevy bevy_pbr::pbr_material::StandardMaterial */
export function StandardMaterial<A>(p: StandardMaterialProps & { animate?: Only<A, StandardMaterialAnimate> }) {
return standard(p, {});
}
@@ -300,6 +302,8 @@ export interface GridExtensionProps {
edge?: string;
}
+/** raea's grid over a StandardMaterial, as an ExtendedMaterial's extension (engine/render grid.rs):
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_render::engine::grid::Grid>> */
export function GridExtension(_: GridExtensionProps): ReactNode {
throw new TypeError("GridExtension goes in an ExtendedMaterial: <ExtendedMaterial base={<StandardMaterial />} extension={<GridExtension cell={0.5} />} />");
}
@@ -336,6 +340,8 @@ export interface WearExtensionProps {
rust_color?: string;
}
+/** raea's chips, grime and rust over a StandardMaterial, as an ExtendedMaterial's extension (systems/wear):
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_sys_wear::Wear>> */
export function WearExtension(_: WearExtensionProps): ReactNode {
throw new TypeError("WearExtension goes in an ExtendedMaterial: <ExtendedMaterial base={<StandardMaterial />} extension={<WearExtension amount={0.6} />} />");
}
@@ -423,7 +429,9 @@ function toon(p: StandardMaterialProps, t: ToonExtensionProps) {
export type ToonMaterialProps = Pick<StandardMaterialProps, "base_color" | "base_color_texture" | "emissive" | "alpha_mode" | "material"> & ToonExtensionProps;
/** raea's ToonMaterial: a StandardMaterial's colour, texture and emission drawn in bands, as
- * `<ExtendedMaterial base={<StandardMaterial />} extension={<ToonExtension />} />` is (the old MeshToonMaterial). */
+ * `<ExtendedMaterial base={<StandardMaterial />} extension={<ToonExtension />} />` is (the old MeshToonMaterial).
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<bevy_pbr::extended_material::ExtendedMaterial<bevy_pbr::pbr_material::StandardMaterial, raea_render::engine::toon::ToonExt>>
+ * @bevy bevy_pbr::mesh_material::MeshMaterial3d<raea_render::engine::toon::OutlineMaterial> */
export function ToonMaterial(p: ToonMaterialProps) {
// the extension's fields to ToonExtension, the rest to the base (which refuses what a toon surface has no use for)
const base: Record<string, unknown> = {}, t: Record<string, unknown> = {};
diff --git a/sdk/render/src/daylight.tsx b/sdk/render/src/daylight.tsx
index 1c9da2c8..5d43614b 100644
--- a/sdk/render/src/daylight.tsx
+++ b/sdk/render/src/daylight.tsx
@@ -7,7 +7,8 @@
// so a shot's exposure comes from the light meter (`raea scene light`) and every window agrees with the sky.
//
// const day = daylight({ sky: staticFile("sky.hdr"), lat: 51.5, lon: -0.1, time: "2026-10-21T08:30:00+01:00" });
-import { AmbientLight, DirectionalLight, Environment, SpotLight, type Vec3 } from "./3d";
+import { Environment, type Vec3 } from "./3d";
+import { AmbientLight, DirectionalLight, SpotLight } from "./three";
import { hasNative, native } from "@raea/app/native";
import { onWall, type Opening, type Room } from "@raea/room/room";
diff --git a/sdk/render/src/matchmove.tsx b/sdk/render/src/matchmove.tsx
index da77365f..9d5c3e10 100644
--- a/sdk/render/src/matchmove.tsx
+++ b/sdk/render/src/matchmove.tsx
@@ -7,7 +7,8 @@
// 0 looking down -Z. `<Text3D position={[0, 0, -4]}>` stands on the ground.
import { createContext, useContext, type ReactNode } from "react";
import { useCurrentFrame, useVideoConfig } from "@raea/app/clock";
-import { PerspectiveCamera, Plate, ToneMapping, type Vec3 } from "./3d";
+import { Plate, ToneMapping, type Vec3 } from "./3d";
+import { PerspectiveCamera } from "./three";
import { hasNative, native } from "@raea/app/native";
export interface MatchmoveCamera {
diff --git a/sdk/render/src/three.tsx b/sdk/render/src/three.tsx
new file mode 100644
index 00000000..82afbfd7
--- /dev/null
+++ b/sdk/render/src/three.tsx
@@ -0,0 +1,7 @@
+// The three.js-shaped forms raea/3d had before Bevy's names (docs/control.feature FC1e): <Mesh position rotation
+// scale>, the Mesh*Material set, Group, PerspectiveCamera, OrthographicCamera and the lights with a relative
+// `intensity`. Not public: sdk/r3f's <R3F> maps three.js's JSX onto them, bevy3d's Bevy-named components draw through
+// them, and the conformance tests compare against them. Compositions use Camera3d, Mesh3d, StandardMaterial, Entity
+// and raea/light's lights.
+export { Mesh, MeshStandardMaterial, MeshPhysicalMaterial, MeshBasicMaterial, MeshToonMaterial, AmbientLight, DirectionalLight, PointLight, SpotLight, RectAreaLight, PerspectiveCamera, OrthographicCamera, Group } from "./3d/all";
+export type { MeshProps, MeshStandardMaterialProps, MeshPhysicalMaterialProps, MeshBasicMaterialProps, MeshToonMaterialProps, AmbientLightProps, DirectionalLightProps, PointLightProps, SpotLightProps, RectAreaLightProps, PerspectiveCameraProps, OrthographicCameraProps, GroupProps } from "./3d/all";
diff --git a/sdk/skills/raea/reference/sdk.md b/sdk/skills/raea/reference/sdk.md
index be11e7d9..ce456aa8 100644
--- a/sdk/skills/raea/reference/sdk.md
+++ b/sdk/skills/raea/reference/sdk.md
@@ -35,7 +35,7 @@ with a capital, hooks with `use`. A component's props are in its file.
## `raea/camera` (sdk/raea/src/camera.ts)
-`Camera3d`, `Canvas3D`, `Matchmove`, `OrthographicCamera`, `PerspectiveCamera`, `TextureView`, `checkMatchmove`, `matchmoveIndex`, `matchmoveView`, `useMatchmove`
+`Camera3d`, `Canvas3D`, `Matchmove`, `TextureView`, `checkMatchmove`, `matchmoveIndex`, `matchmoveView`, `useMatchmove`
## `raea/color` (sdk/raea/src/color.ts)
@@ -63,11 +63,11 @@ with a capital, hooks with `use`. A component's props are in its file.
## `raea/mesh` (sdk/raea/src/mesh.ts)
-`BufferMesh`, `Capsule`, `Capsule3d`, `Cone`, `ConicalFrustum`, `Cuboid`, `Cylinder`, `Instances`, `Mesh`, `Mesh2d`, `Mesh3d`, `MeshSequence`, `Plane3d`, `Sphere`, `Torus`, `scatter`
+`BufferMesh`, `Capsule`, `Capsule3d`, `Cone`, `ConicalFrustum`, `Cuboid`, `Cylinder`, `Instances`, `Mesh2d`, `Mesh3d`, `MeshSequence`, `Plane3d`, `Sphere`, `Torus`, `scatter`
## `raea/pbr` (sdk/raea/src/pbr.ts)
-`AmbientOcclusion`, `Decal`, `ExtendedMaterial`, `Fire`, `Fog`, `FogVolume`, `GridExtension`, `MeshBasicMaterial`, `MeshPhysicalMaterial`, `MeshStandardMaterial`, `MeshToonMaterial`, `PaintExtension`, `Refinish`, `ShaderExtension`, `ShaderMesh`, `StandardMaterial`, `SurfaceShader`, `ToonExtension`, `ToonMaterial`, `VolumetricFog`, `WearExtension`
+`AmbientOcclusion`, `Decal`, `ExtendedMaterial`, `Fire`, `Fog`, `FogVolume`, `GridExtension`, `PaintExtension`, `Refinish`, `ShaderExtension`, `ShaderMesh`, `StandardMaterial`, `SurfaceShader`, `ToonExtension`, `ToonMaterial`, `VolumetricFog`, `WearExtension`
## `raea/post_process` (sdk/raea/src/post_process.ts)
@@ -95,7 +95,7 @@ with a capital, hooks with `use`. A component's props are in its file.
## `raea/transform` (sdk/raea/src/transform.ts)
-`Group`, `Quat`, `Transform`, `eulerOf`, `surfaceTurn`
+`Quat`, `Transform`, `eulerOf`, `surfaceTurn`
## `raea/ui` (sdk/raea/src/ui.ts)
diff --git a/sdk/tsconfig.base.json b/sdk/tsconfig.base.json
index 34446da2..32c14058 100644
--- a/sdk/tsconfig.base.json
+++ b/sdk/tsconfig.base.json
@@ -95,6 +95,8 @@
"@raea/ui/plugin": ["./ui/src/plugin.ts"],
"@raea/physics": ["./physics/src/index.ts"],
"@raea/physics/*": ["./physics/src/*"],
+ "@raea/web": ["./web/src/index.tsx"],
+ "@raea/web/*": ["./web/src/*"],
"@raea/room": ["./room/src/index.ts"],
"@raea/room/*": ["./room/src/*"],
"@raea/rune": ["./rune/src/index.ts"],
diff --git a/sdk/web/package.json b/sdk/web/package.json
new file mode 100644
index 00000000..d5d31488
--- /dev/null
+++ b/sdk/web/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "@raea/web",
+ "license": "FSL-1.1-ALv2",
+ "private": true,
+ "version": "0.1.0",
+ "description": "raea in a browser (docs/web-export.md M3): a composition played live in a page, its React in the browser and its 3D drawn by raea's own engine (raea-web, wasm32 and WebGPU) into a canvas under the page.",
+ "type": "module",
+ "main": "src/index.tsx",
+ "exports": {
+ ".": "./src/index.tsx",
+ "./collect": "./src/collect.ts"
+ },
+ "//": "React is the SDK's own copy (sdk/raea), linked, so an edit and the host share one React",
+ "dependencies": {
+ "react": "file:../raea/node_modules/react",
+ "react-dom": "file:../raea/node_modules/react-dom",
+ "scheduler": "file:../raea/node_modules/scheduler"
+ }
+}
diff --git a/sdk/web/src/collect.ts b/sdk/web/src/collect.ts
new file mode 100644
index 00000000..b9598179
--- /dev/null
+++ b/sdk/web/src/collect.ts
@@ -0,0 +1,96 @@
+// A frame's 3D read from the page (docs/web-export.md M3): every `data-3d` element the SDK's components rendered, as
+// the tree raea-web reads (engine/web/src/scene.rs), in tree order. Each element keeps an id while it lives, and its
+// props and shape text go only when they changed since they were last sent: a ground's vertex buffer crosses once.
+
+export interface Part {
+ k: string;
+ i: number;
+ p?: string | null;
+ s?: string | null;
+ c?: Part[];
+}
+
+export class Collector {
+ private ids = new WeakMap<Element, number>();
+ private sent = new WeakMap<Element, { p: string | null; s: string | null }>();
+ private next = 1;
+
+ /** `pixel`: the engine draws at 1/pixel of the composition's size (PlayOptions.pixel) and the canvas scales it up with
+ * hard pixels, so a <Look>'s cell (pixelSize, in the composition's pixels) is that many fewer of the drawn ones: a
+ * pixel look of 4 drawn at a quarter size is one cell a drawn pixel, and the GPU shades a sixteenth of the pixels. */
+ constructor(private pixel = 1) {}
+
+ /** The page's 3D parts this frame. */
+ parts(page: Element): Part[] {
+ const out: Part[] = [];
+ this.visit(page, out);
+ return out;
+ }
+
+ private visit(el: Element, into: Part[]) {
+ for (const c of el.children) {
+ if (c.hasAttribute("data-3d")) {
+ const part = this.part(c);
+ into.push(part);
+ const kids: Part[] = [];
+ this.visit(c, kids);
+ if (kids.length) part.c = kids;
+ } else this.visit(c, into);
+ }
+ }
+
+ private part(el: Element): Part {
+ let i = this.ids.get(el);
+ if (i === undefined) this.ids.set(el, (i = this.next++));
+ let p = el.getAttribute("data-props");
+ if (p && this.pixel !== 1 && el.getAttribute("data-3d") === "Look") p = this.scaled(p);
+ const s = el.getAttribute("data-shape");
+ const was = this.sent.get(el);
+ const part: Part = { k: el.getAttribute("data-3d")!, i };
+ if (!was || was.p !== p) part.p = p;
+ if (!was || was.s !== s) part.s = s;
+ this.sent.set(el, { p, s });
+ return part;
+ }
+
+ private looks = new Map<string, string>();
+
+ /** a Look's props with its cell in drawn pixels (1 at the least) */
+ private scaled(p: string): string {
+ let out = this.looks.get(p);
+ if (out === undefined) {
+ const o = JSON.parse(p) as { pixelSize?: number };
+ if (typeof o.pixelSize === "number") o.pixelSize = Math.max(1, o.pixelSize / this.pixel);
+ out = JSON.stringify(o);
+ this.looks.set(p, out);
+ }
+ return out;
+ }
+}
+
+const UNDER = "data-raea-under3d";
+
+/** The 3D is drawn under the page: the page elements holding it are cleared, and the innermost solid background among
+ * them becomes the 3D's clear colour, as the native engine shows the page's background behind the 3D. */
+export function clearUnder3d(page: HTMLElement): string | undefined {
+ const first = page.querySelector("[data-3d]");
+ if (!first) return undefined;
+ let clear: string | undefined;
+ for (let el = first.parentElement; el && el !== page; el = el.parentElement) {
+ if (!el.hasAttribute(UNDER)) {
+ const bg = getComputedStyle(el).backgroundColor;
+ if (bg && bg !== "transparent" && !bg.endsWith(", 0)")) el.setAttribute(UNDER, hex(bg));
+ else continue;
+ }
+ clear ??= el.getAttribute(UNDER)!;
+ }
+ return clear;
+}
+
+/** rgb(r, g, b) as #rrggbb (the engine's colours are hex) */
+function hex(css: string): string {
+ const m = css.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
+ return m ? "#" + [m[1], m[2], m[3]].map((n) => Number(n).toString(16).padStart(2, "0")).join("") : css;
+}
+
+export const UNDER3D_CSS = `[${UNDER}]{background:transparent!important}`;
diff --git a/sdk/web/src/index.tsx b/sdk/web/src/index.tsx
new file mode 100644
index 00000000..b18ab62b
--- /dev/null
+++ b/sdk/web/src/index.tsx
@@ -0,0 +1,171 @@
+// raea in a browser (docs/web-export.md M3): a registered composition played live in a page, its React in the
+// browser's own engine and its page as real DOM, its 3D drawn by raea's own engine (raea-web: raea-render on wasm32 and
+// WebGPU) into a canvas under the page. A Clock is stepped 1/fps at a time off requestAnimationFrame with the person's
+// input recorded per frame (useInput reads it), the frame's data-3d parts are collected and handed to the engine, and
+// only what changed crosses (collect.ts). The same edit.tsx renders natively with `raea render`.
+import { flushSync } from "react-dom";
+import { createRoot } from "react-dom/client";
+import { Clock, getCompositions, type InputTimeline, type RegisteredComposition } from "raea";
+import { Input } from "@raea/playable/host/input";
+import { Collector, UNDER3D_CSS, clearUnder3d } from "./collect";
+
+/** raea-web's engine, as wasm-bindgen exports it (engine/web: `import init, { Raea } from "./raea_web.js"`). */
+export interface RaeaEngine {
+ frame(scene: string, clear: string | undefined, f: number): boolean;
+ resize(width: number, height: number): void;
+ free(): void;
+}
+export type RaeaEngineClass = new (canvas: HTMLCanvasElement, width: number, height: number, fps: number) => RaeaEngine;
+
+/** raea-web's module, as wasm-bindgen's `--target web` output exports it. */
+export interface RaeaWebModule {
+ default: () => Promise<unknown>;
+ Raea: RaeaEngineClass;
+}
+
+const loaded = new WeakMap<() => Promise<RaeaWebModule>, Promise<RaeaWebModule>>();
+/** raea-web's module imported and its wasm instantiated, once per loader however often it's asked (React's StrictMode
+ * runs effects twice, and two concurrent inits make two instances whose JS glue then shares one binding, which
+ * tears the engine's memory a frame later). Pass the same loader each time: `loadRaea(() => import("./raea_web.js"))`
+ * with the arrow hoisted to module scope. */
+export function loadRaea(load: () => Promise<RaeaWebModule>): Promise<RaeaWebModule> {
+ let p = loaded.get(load);
+ if (!p) {
+ p = load().then(async (m) => (await m.default(), m));
+ loaded.set(load, p);
+ }
+ return p;
+}
+
+export interface PlayOptions {
+ /** where it plays: filled by the canvas and the page over it */
+ stage: HTMLElement;
+ /** raea-web's Raea class, its wasm already initialised (loadRaea) */
+ Raea: RaeaEngineClass;
+ /** the composition's id (else the first registered) */
+ composition?: string;
+ /** the 3D drawn at the composition's size divided by this (4: a quarter, for a pixel look's chunky pixels); the
+ * canvas shows it scaled up, nearest-neighbour */
+ pixel?: number;
+ /** hold this one frame instead of playing: a poster's frame, or one to compare with `raea render --frame N` */
+ hold?: number;
+ /** called once the first frame with 3D is on the canvas */
+ onFirstFrame?: () => void;
+ /** called when a frame fails (the engine's error); playing stops */
+ onError?: (e: unknown) => void;
+}
+
+export interface Playing {
+ stop(): void;
+ /** frames drawn and the time each took, for the budgets (docs/web-export.md) */
+ stats(): { frames: number; msPerFrame: number };
+}
+
+/** Plays the registered composition in `stage`. */
+export function play(o: PlayOptions): Playing {
+ const comps = getCompositions();
+ if (!comps.length) throw new Error("raea web: the edit registered no composition (registerRoot)");
+ const comp: RegisteredComposition = (o.composition ? comps.find((c) => c.id === o.composition) : comps[0]) ?? (() => { throw new Error(`raea web: no composition "${o.composition}" (${comps.map((c) => c.id).join(", ")})`); })();
+ const pixel = Math.max(1, o.pixel ?? 1);
+ const w = Math.max(1, Math.round(comp.width / pixel));
+ const h = Math.max(1, Math.round(comp.height / pixel));
+
+ const style = document.createElement("style");
+ style.textContent = `${UNDER3D_CSS}.raea-web-canvas,.raea-web-page{position:absolute;inset:0;width:100%;height:100%}.raea-web-canvas{image-rendering:pixelated}`;
+ document.head.append(style);
+ const canvas = document.createElement("canvas");
+ canvas.className = "raea-web-canvas";
+ const page = document.createElement("div");
+ page.className = "raea-web-page";
+ o.stage.append(canvas, page);
+
+ // drawn smaller than the composition (pixel > 1), the canvas is the drawn size and the browser scales it up with hard
+ // pixels (image-rendering: pixelated), covering the stage as the composition's frame would; otherwise it's the
+ // stage's own pixels and the engine scales its frame onto them
+ if (pixel > 1) canvas.style.objectFit = "cover";
+ const fit = () => {
+ const r = o.stage.getBoundingClientRect();
+ const dpr = Math.min(2, devicePixelRatio || 1);
+ canvas.width = pixel > 1 ? w : Math.max(1, Math.round(r.width * dpr));
+ canvas.height = pixel > 1 ? h : Math.max(1, Math.round(r.height * dpr));
+ engine?.resize(canvas.width, canvas.height);
+ };
+ let engine: RaeaEngine | undefined;
+ fit();
+ engine = new o.Raea(canvas, w, h, comp.fps);
+ const resized = new ResizeObserver(fit);
+ resized.observe(o.stage);
+
+ const input = new Input(o.stage, () => comp);
+ const root = createRoot(page);
+ const collector = new Collector(pixel);
+ const timeline: InputTimeline = {};
+ const C = comp.component;
+ const hold = o.hold === undefined ? undefined : Math.max(0, Math.floor(o.hold)) % comp.durationInFrames;
+ let frame = hold ?? 0, last = performance.now(), acc = 0, raf = 0, stopped = false, first = false;
+ let drawn = 0, spent = 0;
+
+ const draw = () => {
+ flushSync(() =>
+ root.render(
+ <Clock frame={frame} fps={comp.fps} width={comp.width} height={comp.height} durationInFrames={comp.durationInFrames} input={timeline} defaultProps={comp.defaultProps}>
+ <C {...comp.defaultProps} />
+ </Clock>,
+ ),
+ );
+ const t0 = performance.now();
+ const ok = engine!.frame(JSON.stringify(collector.parts(page)), clearUnder3d(page), frame);
+ if (ok) {
+ drawn++;
+ spent += performance.now() - t0;
+ if (!first) {
+ first = true;
+ o.onFirstFrame?.();
+ }
+ }
+ };
+
+ const tick = (now: number) => {
+ if (stopped) return;
+ raf = requestAnimationFrame(tick);
+ const step = 1000 / comp.fps;
+ acc += Math.min(250, now - last);
+ last = now;
+ let stepped = !first;
+ while (acc >= step) {
+ acc -= step;
+ timeline[frame] = input.now();
+ // a composition loops: a site's scene plays on past its last frame from the start again
+ frame = hold ?? (frame + 1) % comp.durationInFrames;
+ delete timeline[frame];
+ stepped = true;
+ }
+ if (!stepped) return;
+ try {
+ draw();
+ } catch (e) {
+ // stopped, the engine kept: after a fault its memory may be torn, and wgpu's callbacks still hold it
+ stopped = true;
+ cancelAnimationFrame(raf);
+ if (o.onError) o.onError(e);
+ else throw e;
+ }
+ };
+ raf = requestAnimationFrame(tick);
+
+ function stop() {
+ stopped = true;
+ cancelAnimationFrame(raf);
+ resized.disconnect();
+ root.unmount();
+ // after a panic the engine is still borrowed by the call that panicked: it's dropped with the page instead
+ try {
+ engine?.free();
+ } catch {}
+ engine = undefined;
+ canvas.remove();
+ page.remove();
+ style.remove();
+ }
+ return { stop, stats: () => ({ frames: drawn, msPerFrame: drawn ? spent / drawn : 0 }) };
+}
diff --git a/systems/frame/src/lib.rs b/systems/frame/src/lib.rs
index 8968adf6..22d4cb25 100644
--- a/systems/frame/src/lib.rs
+++ b/systems/frame/src/lib.rs
@@ -245,6 +245,11 @@ pub fn num(v: &BTreeMap<String, V>, k: &str, d: f32) -> f32 {
v.get(k).map(|x| x.num() as f32).unwrap_or(d)
}
+/// A number from a JSON spec (a row's JSON column: grass, volumes), else `d`.
+pub fn json_f32(j: &serde_json::Value, k: &str, d: f32) -> f32 {
+ j.get(k).and_then(serde_json::Value::as_f64).map_or(d, |x| x as f32)
+}
+
pub fn flag(vals: &BTreeMap<String, V>, k: &str, d: bool) -> bool {
vals.get(k).map(V::truthy).unwrap_or(d)
}
diff --git a/systems/frame/src/state.rs b/systems/frame/src/state.rs
index 39a954fa..247cabe0 100644
--- a/systems/frame/src/state.rs
+++ b/systems/frame/src/state.rs
@@ -111,10 +111,10 @@ pub struct Stages {
/// the Blitz overlay: rows, style, layout, raster, unpremultiply and upload (only when its digest changed)
pub overlay: u64,
#[cfg(feature = "native")]
- pub overlay_t0: Option<std::time::Instant>,
+ pub overlay_t0: Option<bevy::platform::time::Instant>,
/// the main world's Update, first system to last
pub main: u64,
- pub main_t0: Option<std::time::Instant>,
+ pub main_t0: Option<bevy::platform::time::Instant>,
/// whole app.update() (main world + render world: extract, prepare incl. texture uploads, queue, submit)
pub update: u64,
/// copying readbacks out of the padded rows
@@ -126,7 +126,7 @@ pub struct Stages {
}
pub fn mark_main_start(mut st: ResMut<Stages>) {
- st.main_t0 = Some(std::time::Instant::now());
+ st.main_t0 = Some(bevy::platform::time::Instant::now());
}
pub fn mark_main_end(mut st: ResMut<Stages>) {
@@ -137,7 +137,7 @@ pub fn mark_main_end(mut st: ResMut<Stages>) {
#[cfg(feature = "native")]
pub fn mark_overlay_start(mut st: ResMut<Stages>) {
- st.overlay_t0 = Some(std::time::Instant::now());
+ st.overlay_t0 = Some(bevy::platform::time::Instant::now());
}
#[cfg(feature = "native")]
diff --git a/systems/grass/Cargo.toml b/systems/grass/Cargo.toml
new file mode 100644
index 00000000..53eb34e6
--- /dev/null
+++ b/systems/grass/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "raea-sys-grass"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A field of grass from a few grids (the ground's height, clumps per square metre, colour patches, size): blades made by the engine in tiles, each tile as detailed as its distance from the camera asks, swayed by the paint look's wind"
+
+[dependencies]
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_pbr"] }
+# a grass row's values
+raea-core-program = { path = "../../core/program" }
+raea-sys-frame = { path = "../frame" }
+# the row's `grass` spec, as the SDK sends it
+serde_json = "1"
diff --git a/systems/grass/src/lib.rs b/systems/grass/src/lib.rs
new file mode 100644
index 00000000..ff713595
--- /dev/null
+++ b/systems/grass/src/lib.rs
@@ -0,0 +1,141 @@
+//! A field of grass (`<Grass>` in raea/3d): a stylized meadow's clumps of blades over a box of ground, made by the
+//! engine from a few grids the edit samples once (the ground's height, clumps per square metre, which colour patch,
+//! and a size), instead of a placement per clump sent from the page. The box is cut into square tiles; each tile is
+//! one mesh, as detailed as its distance from the camera asks (`lod`: near tiles every clump and every blade in three
+//! segments; farther ones a share of the clumps, fewer and wider single-segment blades), made again only when the
+//! camera moves it across a step. So a frame's cost is the blades it can show, and a render of frame N, which places
+//! the camera before it draws, has the tiles play has.
+//!
+//! The blades are the meadow's (Dylearn's Waterfowl grass): tapered, leaning, root to tip in their patch's two
+//! greens with a warm highlight on the tip, their normals the ground's (a slope turned from the sun darkens as one).
+//! They're cut-outs (a masked material) so the paint look's wind bends them; each vertex's second UV is how far up its
+//! blade it is, which the paint's vertex stage bends by on any slope (paint_vertex.wesl).
+//!
+//! The row: kind `grass`, its `grass` column the spec as JSON (`Spec`), `shadow` (cast, 0 or 1: none by default).
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use bevy::asset::RenderAssetUsages;
+use bevy::camera::primitives::Aabb;
+use bevy::light::NotShadowCaster;
+use bevy::mesh::{Indices, PrimitiveTopology};
+use bevy::prelude::*;
+use raea_core_program::ir::V;
+use serde_json::Value as J;
+
+mod spec;
+pub use spec::*;
+#[cfg(test)]
+mod tests;
+
+pub fn install(app: &mut App) {
+ app.add_systems(PostUpdate, retile.before(bevy::transform::TransformSystems::Propagate).before(bevy::camera::visibility::VisibilitySystems::VisibilityPropagate));
+}
+
+/// A field on its row's entity: its spec, its material, and each tile's mesh at the detail it was made for.
+#[derive(Component)]
+pub struct Field {
+ spec: Arc<Spec>,
+ material: Handle<StandardMaterial>,
+ shadow: bool,
+ tiles: Vec<Tile>,
+}
+
+struct Tile {
+ ix: u32,
+ iz: u32,
+ /// the step it was made at (None: not yet)
+ lod: Option<usize>,
+ entity: Option<Entity>,
+}
+
+/// A grass row: its field, tiles made as the camera first sees them (retile).
+pub fn spawn(world: &mut World, e: Entity, vals: &BTreeMap<String, V>) -> Result<(), String> {
+ let Some(V::S(s)) = vals.get("grass") else { return Err("a grass row without its spec (`grass`)".into()) };
+ let j: J = serde_json::from_str(s).map_err(|err| format!("grass: its spec isn't JSON: {err}"))?;
+ let spec = Spec::from_json(&j)?;
+ let material = world.resource_mut::<Assets<StandardMaterial>>().add(StandardMaterial {
+ base_color: Color::WHITE,
+ perceptual_roughness: 0.9,
+ double_sided: true,
+ cull_mode: None,
+ // a cut-out, so the paint look's wind bends it (its blades are opaque: every vertex's alpha is 1)
+ alpha_mode: AlphaMode::Mask(0.5),
+ ..default()
+ });
+ let (nx, nz) = spec.tiles();
+ let tiles = (0..nz).flat_map(|iz| (0..nx).map(move |ix| Tile { ix, iz, lod: None, entity: None })).collect();
+ let shadow = matches!(vals.get("shadow"), Some(V::N(x)) if *x > 0.0);
+ world.entity_mut(e).insert((Field { spec: Arc::new(spec), material, shadow, tiles }, Transform::IDENTITY, Visibility::Visible));
+ Ok(())
+}
+
+/// Each frame: each field's tiles at the detail the camera's distance asks, a tile made again only when it changes
+/// step. The camera's own transform (not the propagated one: this runs before propagation, so the tiles it makes are
+/// in this frame's visibility).
+pub fn retile(
+ mut commands: Commands,
+ mut fields: Query<(Entity, &mut Field)>,
+ cams: Query<(&Camera, &Transform), With<Camera3d>>,
+ mut meshes: ResMut<Assets<Mesh>>,
+) {
+ let Some(eye) = cams.iter().filter(|(c, _)| c.is_active).min_by_key(|(c, _)| c.order).map(|(_, t)| t.translation) else { return };
+ for (fe, mut f) in &mut fields {
+ let f = &mut *f;
+ for t in &mut f.tiles {
+ let want = f.spec.lod_at(f.spec.distance(t.ix, t.iz, eye));
+ if t.lod == Some(want) && t.entity.is_some() {
+ continue;
+ }
+ t.lod = Some(want);
+ if let Some(old) = t.entity.take() {
+ commands.entity(old).despawn();
+ }
+ let Some((mesh, aabb)) = f.spec.tile_mesh(t.ix, t.iz, want) else { continue };
+ let mut ec = commands.spawn((Mesh3d(meshes.add(mesh)), MeshMaterial3d(f.material.clone()), Transform::IDENTITY, Visibility::Inherited, aabb, ChildOf(fe)));
+ if !f.shadow {
+ ec.insert(NotShadowCaster);
+ }
+ t.entity = Some(ec.id());
+ }
+ }
+}
+
+/// A tile's blades as one mesh: positions in the world, the ground's normal, colours, the blade's (side, height) as
+/// its UV and (height, its clump's phase) as its second UV, for the wind.
+pub(crate) struct Blades {
+ pub pos: Vec<[f32; 3]>,
+ pub nrm: Vec<[f32; 3]>,
+ pub col: Vec<[f32; 4]>,
+ pub uv: Vec<[f32; 2]>,
+ pub uv1: Vec<[f32; 2]>,
+ pub idx: Vec<u32>,
+}
+
+impl Blades {
+ pub(crate) fn new() -> Blades {
+ Blades { pos: Vec::new(), nrm: Vec::new(), col: Vec::new(), uv: Vec::new(), uv1: Vec::new(), idx: Vec::new() }
+ }
+
+ /// The mesh and its bounds (widened by how far the wind can push a tip), or None when the tile has no blades.
+ pub(crate) fn mesh(self, sway: f32) -> Option<(Mesh, Aabb)> {
+ if self.pos.is_empty() {
+ return None;
+ }
+ let (mut lo, mut hi) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN));
+ for p in &self.pos {
+ lo = lo.min(Vec3::from_array(*p));
+ hi = hi.max(Vec3::from_array(*p));
+ }
+ let aabb = Aabb::from_min_max(lo - Vec3::splat(sway), hi + Vec3::splat(sway));
+ let mut m = Mesh::new(PrimitiveTopology::TriangleList, RenderAssetUsages::RENDER_WORLD);
+ m.insert_attribute(Mesh::ATTRIBUTE_POSITION, self.pos);
+ m.insert_attribute(Mesh::ATTRIBUTE_NORMAL, self.nrm);
+ m.insert_attribute(Mesh::ATTRIBUTE_UV_0, self.uv);
+ m.insert_attribute(Mesh::ATTRIBUTE_UV_1, self.uv1);
+ m.insert_attribute(Mesh::ATTRIBUTE_COLOR, self.col);
+ m.insert_indices(Indices::U32(self.idx));
+ Some((m, aabb))
+ }
+}
diff --git a/systems/grass/src/spec.rs b/systems/grass/src/spec.rs
new file mode 100644
index 00000000..1ee1f1bb
--- /dev/null
+++ b/systems/grass/src/spec.rs
@@ -0,0 +1,302 @@
+//! A field's spec (the row's `grass` JSON, as raea/3d's <Grass> sends it) and its tiles' blades.
+//!
+//! The grids are `grid[0]` x `grid[1]` values over the area, row by row from its min z, the first and last of each row
+//! on the area's edges: `height` (the ground's y), `density` (clumps per square metre), `patch` (which of `tints`),
+//! and `size` (a multiple of each clump's scale; 1 without it). Between grid points a value is the bilinear mix of its
+//! four, a patch the nearest's.
+
+use bevy::camera::primitives::Aabb;
+use bevy::prelude::*;
+use serde_json::Value as J;
+
+use super::Blades;
+
+/// One step of detail: tiles nearer than `to` metres draw this share of their clumps (`keep`), each with its first
+/// `blades` blades in `segments` segments, `widen` times as wide.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Lod {
+ pub to: f32,
+ pub keep: f32,
+ pub blades: u32,
+ pub segments: u32,
+ pub widen: f32,
+}
+
+#[derive(Clone, Debug)]
+pub struct Spec {
+ /// min x, min z, max x, max z
+ pub area: [f32; 4],
+ pub nx: usize,
+ pub nz: usize,
+ pub height: Vec<f32>,
+ pub density: Vec<f32>,
+ pub patch: Vec<u32>,
+ pub size: Vec<f32>,
+ /// each patch's root and tip colours (linear)
+ pub tints: Vec<([f32; 3], [f32; 3])>,
+ pub highlight: [f32; 3],
+ pub highlight_mix: f32,
+ pub blades: u32,
+ pub blade_height: f32,
+ pub width: [f32; 2],
+ pub spread: f32,
+ pub lean: [f32; 2],
+ pub scale: [f32; 2],
+ pub seed: u32,
+ pub tile: f32,
+ pub lod: Vec<Lod>,
+}
+
+fn nums(j: &J, k: &str) -> Result<Vec<f32>, String> {
+ match j.get(k) {
+ Some(J::Array(a)) => a.iter().map(|v| v.as_f64().map(|x| x as f32).ok_or_else(|| format!("grass: {k} is numbers"))).collect(),
+ _ => Err(format!("grass: no {k}")),
+ }
+}
+
+use raea_sys_frame::json_f32 as num;
+
+fn pair(j: &J, k: &str, d: [f32; 2]) -> [f32; 2] {
+ match nums(j, k) {
+ Ok(v) if v.len() == 2 => [v[0], v[1]],
+ _ => d,
+ }
+}
+
+/// "#rrggbb" as linear rgb
+pub fn linear(hex: &str) -> Option<[f32; 3]> {
+ let s = hex.strip_prefix('#')?;
+ if s.len() != 6 {
+ return None;
+ }
+ let c = |i: usize| u8::from_str_radix(&s[i..i + 2], 16).ok();
+ let l = Color::srgb_u8(c(0)?, c(2)?, c(4)?).to_linear();
+ Some([l.red, l.green, l.blue])
+}
+
+impl Spec {
+ pub fn from_json(j: &J) -> Result<Spec, String> {
+ let area = nums(j, "area")?;
+ let grid = nums(j, "grid")?;
+ if area.len() != 4 || !(area[2] > area[0] && area[3] > area[1]) {
+ return Err("grass: area is [min x, min z, max x, max z]".into());
+ }
+ if grid.len() != 2 || grid[0] < 2.0 || grid[1] < 2.0 {
+ return Err("grass: grid is [columns, rows], 2 or more each".into());
+ }
+ let (nx, nz) = (grid[0] as usize, grid[1] as usize);
+ let height = nums(j, "height")?;
+ let density = nums(j, "density")?;
+ let patch: Vec<u32> = nums(j, "patch").unwrap_or_else(|_| vec![0.0; nx * nz]).into_iter().map(|p| p.max(0.0) as u32).collect();
+ let size = nums(j, "size").unwrap_or_else(|_| vec![1.0; nx * nz]);
+ for (k, n) in [("height", height.len()), ("density", density.len()), ("patch", patch.len()), ("size", size.len())] {
+ if n != nx * nz {
+ return Err(format!("grass: {k} has {n} values, the grid {nx} x {nz}"));
+ }
+ }
+ let tints: Vec<([f32; 3], [f32; 3])> = match j.get("tints") {
+ Some(J::Array(a)) if !a.is_empty() => a
+ .iter()
+ .map(|t| {
+ let c = |i: usize| t.get(i).and_then(J::as_str).and_then(linear).ok_or("grass: tints are [root, tip] \"#rrggbb\" pairs".to_string());
+ Ok((c(0)?, c(1)?))
+ })
+ .collect::<Result<_, String>>()?,
+ _ => vec![(linear("#3a5e1e").unwrap(), linear("#7ea535").unwrap())],
+ };
+ let lod = match j.get("lod") {
+ Some(J::Array(a)) if !a.is_empty() => a
+ .iter()
+ .map(|l| Lod { to: num(l, "to", f32::MAX), keep: num(l, "keep", 1.0).clamp(0.0, 1.0), blades: num(l, "blades", 14.0).max(1.0) as u32, segments: num(l, "segments", 3.0).clamp(1.0, 6.0) as u32, widen: num(l, "widen", 1.0).max(0.1) })
+ .collect(),
+ _ => default_lod(),
+ };
+ Ok(Spec {
+ area: [area[0], area[1], area[2], area[3]],
+ nx,
+ nz,
+ height,
+ density,
+ patch,
+ size,
+ tints,
+ highlight: j.get("highlight").and_then(J::as_str).and_then(linear).unwrap_or(linear("#f2e7a0").unwrap()),
+ highlight_mix: num(j, "highlightMix", 0.22),
+ blades: num(j, "blades", 14.0).max(1.0) as u32,
+ blade_height: num(j, "bladeHeight", 0.3),
+ width: pair(j, "width", [0.034, 0.05]),
+ spread: num(j, "spread", 0.06),
+ lean: pair(j, "lean", [0.2, 0.7]),
+ scale: pair(j, "scale", [0.85, 1.35]),
+ seed: num(j, "seed", 1.0) as u32,
+ tile: num(j, "tile", 4.0).max(0.5),
+ lod,
+ })
+ }
+
+ /// tiles across and deep
+ pub fn tiles(&self) -> (u32, u32) {
+ (((self.area[2] - self.area[0]) / self.tile).ceil() as u32, ((self.area[3] - self.area[1]) / self.tile).ceil() as u32)
+ }
+
+ fn tile_box(&self, ix: u32, iz: u32) -> [f32; 4] {
+ let x0 = self.area[0] + ix as f32 * self.tile;
+ let z0 = self.area[1] + iz as f32 * self.tile;
+ [x0, z0, (x0 + self.tile).min(self.area[2]), (z0 + self.tile).min(self.area[3])]
+ }
+
+ /// a grid's value at (x, z), bilinear
+ fn at(&self, g: &[f32], x: f32, z: f32) -> f32 {
+ let fx = ((x - self.area[0]) / (self.area[2] - self.area[0]) * (self.nx - 1) as f32).clamp(0.0, (self.nx - 1) as f32);
+ let fz = ((z - self.area[1]) / (self.area[3] - self.area[1]) * (self.nz - 1) as f32).clamp(0.0, (self.nz - 1) as f32);
+ let (i, k) = ((fx as usize).min(self.nx - 2), (fz as usize).min(self.nz - 2));
+ let (u, v) = (fx - i as f32, fz - k as f32);
+ let g = |a: usize, b: usize| g[b * self.nx + a];
+ (g(i, k) * (1.0 - u) + g(i + 1, k) * u) * (1.0 - v) + (g(i, k + 1) * (1.0 - u) + g(i + 1, k + 1) * u) * v
+ }
+
+ pub fn ground(&self, x: f32, z: f32) -> f32 {
+ self.at(&self.height, x, z)
+ }
+
+ /// the ground's normal at (x, z)
+ pub fn normal(&self, x: f32, z: f32) -> Vec3 {
+ let e = 0.5 * ((self.area[2] - self.area[0]) / (self.nx - 1) as f32).min((self.area[3] - self.area[1]) / (self.nz - 1) as f32);
+ let dx = self.ground(x + e, z) - self.ground(x - e, z);
+ let dz = self.ground(x, z + e) - self.ground(x, z - e);
+ Vec3::new(-dx, 2.0 * e, -dz).normalize_or(Vec3::Y)
+ }
+
+ fn patch_at(&self, x: f32, z: f32) -> usize {
+ let i = (((x - self.area[0]) / (self.area[2] - self.area[0]) * (self.nx - 1) as f32).round() as usize).min(self.nx - 1);
+ let k = (((z - self.area[1]) / (self.area[3] - self.area[1]) * (self.nz - 1) as f32).round() as usize).min(self.nz - 1);
+ (self.patch[k * self.nx + i] as usize).min(self.tints.len() - 1)
+ }
+
+ /// how far the eye is from a tile (its nearest point, at the ground's height there)
+ pub fn distance(&self, ix: u32, iz: u32, eye: Vec3) -> f32 {
+ let b = self.tile_box(ix, iz);
+ let (x, z) = (eye.x.clamp(b[0], b[2]), eye.z.clamp(b[1], b[3]));
+ eye.distance(Vec3::new(x, self.ground(x, z), z))
+ }
+
+ /// the step of detail for a tile this far away
+ pub fn lod_at(&self, d: f32) -> usize {
+ self.lod.iter().position(|l| d < l.to).unwrap_or(self.lod.len() - 1)
+ }
+
+ /// A tile's clumps at step `lod`: scattered as raea/3d's scatter() does (candidates over the tile at its densest,
+ /// each kept by the density where it falls), every draw in the same order whatever the step, so a step's clumps
+ /// are the nearer step's with some left out.
+ pub fn tile_mesh(&self, ix: u32, iz: u32, lod: usize) -> Option<(Mesh, Aabb)> {
+ let l = &self.lod[lod.min(self.lod.len() - 1)];
+ let b = self.tile_box(ix, iz);
+ let (w, d) = (b[2] - b[0], b[3] - b[1]);
+ let mut most = 0.0f32;
+ for i in 0..=4 {
+ for k in 0..=4 {
+ most = most.max(self.at(&self.density, b[0] + w * i as f32 / 4.0, b[1] + d * k as f32 / 4.0));
+ }
+ }
+ // the grid's own points inside the tile too, so a narrow peak isn't missed
+ for k in 0..self.nz {
+ for i in 0..self.nx {
+ let x = self.area[0] + (self.area[2] - self.area[0]) * i as f32 / (self.nx - 1) as f32;
+ let z = self.area[1] + (self.area[3] - self.area[1]) * k as f32 / (self.nz - 1) as f32;
+ if x >= b[0] && x <= b[2] && z >= b[1] && z <= b[3] {
+ most = most.max(self.density[k * self.nx + i]);
+ }
+ }
+ }
+ let mut out = Blades::new();
+ if most <= 0.0 {
+ return None;
+ }
+ let mut r = Rng::new(self.seed ^ ix.wrapping_mul(73_856_093) ^ iz.wrapping_mul(19_349_663) ^ 0x9e37_79b9);
+ let want = most * w * d;
+ let n = want.floor() as u32 + u32::from(r.next() < want.fract());
+ for _ in 0..n {
+ let (x, z) = (b[0] + r.next() * w, b[1] + r.next() * d);
+ let accept = r.next() * most < self.at(&self.density, x, z);
+ let keep = r.next();
+ let s = (self.scale[0] + r.next() * (self.scale[1] - self.scale[0])) * self.at(&self.size, x, z);
+ let seed = (r.next() * u32::MAX as f32) as u32;
+ if !accept || keep >= l.keep {
+ continue;
+ }
+ self.clump(&mut out, l, Vec3::new(x, self.ground(x, z), z), s, seed);
+ }
+ out.mesh(self.blade_height * self.scale[1] * 1.5)
+ }
+
+ /// One clump's blades (raea-site-lab's clump(): tapered, leaning, root to tip in the patch's greens, the tip's
+ /// last point a warm highlight), tilted to the slope at its root.
+ fn clump(&self, out: &mut Blades, l: &Lod, at: Vec3, s: f32, seed: u32) {
+ let mut r = Rng::new(seed);
+ let n = self.normal(at.x, at.z);
+ let tilt = Quat::from_rotation_arc(Vec3::Y, n);
+ let (root, tip) = self.tints[self.patch_at(at.x, at.z)];
+ let mix = |a: [f32; 3], b: [f32; 3], t: f32| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, 1.0];
+ let crown = mix(tip, self.highlight, self.highlight_mix);
+ let phase = r.next();
+ for k in 0..self.blades {
+ let a = r.next() * std::f32::consts::TAU;
+ let dd = r.next().sqrt() * self.spread;
+ let ang = r.next() * std::f32::consts::TAU;
+ let h = self.blade_height * (0.55 + r.next() * 0.75);
+ let w = self.width[0] + r.next() * (self.width[1] - self.width[0]);
+ let lean = self.lean[0] + r.next() * (self.lean[1] - self.lean[0]);
+ if k >= l.blades {
+ continue;
+ }
+ let (x, z) = (a.cos() * dd, a.sin() * dd);
+ let (ca, sa) = (ang.cos(), ang.sin());
+ let o = out.pos.len() as u32;
+ let seg = l.segments;
+ for si in 0..=seg {
+ let t = si as f32 / seg as f32;
+ let bend = lean * t * t * h;
+ let hw = (w * (1.0 - t) / 2.0 + 0.0008) * l.widen;
+ let (cx, cy, cz) = (x + ca * bend, h * t, z + sa * bend);
+ let c = if si == seg { crown } else { mix(root, tip, t) };
+ for side in [-1.0f32, 1.0] {
+ let p = at + tilt * (Vec3::new(cx - sa * hw * side, cy, cz + ca * hw * side) * s);
+ out.pos.push(p.to_array());
+ out.nrm.push(n.to_array());
+ out.col.push(c);
+ out.uv.push([(side + 1.0) / 2.0, t]);
+ // how high above its root (m): what the wind bends it by
+ out.uv1.push([cy * s, phase]);
+ }
+ if si < seg {
+ let q = o + si * 2;
+ out.idx.extend_from_slice(&[q, q + 1, q + 2, q + 1, q + 3, q + 2]);
+ }
+ }
+ }
+ }
+}
+
+fn default_lod() -> Vec<Lod> {
+ vec![
+ Lod { to: 5.0, keep: 1.0, blades: 14, segments: 3, widen: 1.0 },
+ Lod { to: 14.0, keep: 0.5, blades: 8, segments: 1, widen: 1.4 },
+ Lod { to: f32::MAX, keep: 0.18, blades: 5, segments: 1, widen: 2.0 },
+ ]
+}
+
+/// mulberry32, as raea-site-lab's rng(): a draw in [0, 1)
+pub(crate) struct Rng(u32);
+
+impl Rng {
+ pub(crate) fn new(seed: u32) -> Rng {
+ Rng(seed)
+ }
+ pub(crate) fn next(&mut self) -> f32 {
+ self.0 = self.0.wrapping_add(0x6d2b_79f5);
+ let mut t = self.0;
+ t = (t ^ (t >> 15)).wrapping_mul(t | 1);
+ t ^= t.wrapping_add((t ^ (t >> 7)).wrapping_mul(t | 61));
+ ((t ^ (t >> 14)) as f64 / 4_294_967_296.0) as f32
+ }
+}
diff --git a/systems/grass/src/tests.rs b/systems/grass/src/tests.rs
new file mode 100644
index 00000000..670cad44
--- /dev/null
+++ b/systems/grass/src/tests.rs
@@ -0,0 +1,66 @@
+use super::*;
+use serde_json::json;
+
+fn field(density: f32) -> Spec {
+ let n = 5 * 5;
+ Spec::from_json(&json!({
+ "area": [-4, -4, 4, 4], "grid": [5, 5],
+ "height": (0..n).map(|i| (i % 5) as f32 * 0.25).collect::<Vec<_>>(),
+ "density": vec![density; n],
+ "patch": (0..n).map(|i| i % 2).collect::<Vec<_>>(),
+ "tints": [["#2c4a1a", "#5f8a2c"], ["#4d7424", "#a3c04a"]],
+ "seed": 7, "tile": 4,
+ }))
+ .unwrap()
+}
+
+fn verts(s: &Spec, lod: usize) -> usize {
+ s.tile_mesh(0, 0, lod).map_or(0, |(m, _)| m.count_vertices())
+}
+
+#[test]
+fn a_spec_reads_and_tiles_its_area() {
+ let s = field(10.0);
+ assert_eq!(s.tiles(), (2, 2));
+ assert_eq!(s.lod.len(), 3);
+ // the ground rises a quarter metre a column: x from -4 to 4 is 0 to 1
+ assert!((s.ground(0.0, 0.0) - 0.5).abs() < 1e-5);
+ assert!(s.normal(0.0, 0.0).x < 0.0, "the ground rises toward +x, so it faces -x");
+}
+
+#[test]
+fn a_tile_is_the_same_each_time_and_scales_with_density() {
+ let s = field(10.0);
+ let a = s.tile_mesh(1, 0, 0).unwrap().0;
+ let b = s.tile_mesh(1, 0, 0).unwrap().0;
+ assert_eq!(a.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().get_bytes(), b.attribute(Mesh::ATTRIBUTE_POSITION).unwrap().get_bytes());
+ // 16 m2 at 10 a m2: about 160 clumps of 14 blades of 8 vertices
+ let n = verts(&s, 0);
+ assert!((14_000..22_000).contains(&n), "{n} vertices");
+ assert!(field(0.0).tile_mesh(0, 0, 0).is_none(), "no clumps, no mesh");
+}
+
+#[test]
+fn farther_steps_draw_fewer_blades() {
+ let s = field(10.0);
+ let (near, mid, far) = (verts(&s, 0), verts(&s, 1), verts(&s, 2));
+ assert!(near > 4 * mid && mid > 2 * far && far > 0, "{near} {mid} {far}");
+ assert_eq!(s.lod_at(1.0), 0);
+ assert_eq!(s.lod_at(10.0), 1);
+ assert_eq!(s.lod_at(500.0), 2);
+}
+
+#[test]
+fn the_wind_reads_each_vertex_height_above_its_root() {
+ let s = field(10.0);
+ let m = s.tile_mesh(0, 0, 0).unwrap().0;
+ let Some(bevy::mesh::VertexAttributeValues::Float32x2(uv1)) = m.attribute(Mesh::ATTRIBUTE_UV_1) else { panic!("no second uv") };
+ assert!(uv1.iter().all(|u| u[0] >= 0.0 && u[0] < 0.6));
+ assert!(uv1.iter().any(|u| u[0] == 0.0) && uv1.iter().any(|u| u[0] > 0.1));
+}
+
+#[test]
+fn a_bad_spec_says_what_is_wrong() {
+ let e = Spec::from_json(&json!({"area": [0, 0, 1, 1], "grid": [2, 2], "height": [0, 0, 0], "density": [1, 1, 1, 1]})).unwrap_err();
+ assert!(e.contains("height has 3 values"), "{e}");
+}
diff --git a/systems/look/src/paint.rs b/systems/look/src/paint.rs
index 72af0765..328e423e 100644
--- a/systems/look/src/paint.rs
+++ b/systems/look/src/paint.rs
@@ -119,9 +119,9 @@ impl MaterialExtension for Paint {
}
/// a mesh's paint with its material's own part: whether it sways in the wind (a cut-out: masked, blended or to
-/// coverage)
+/// coverage; not an unlit picture, such as a baked cloud's card)
fn for_material(mut p: PaintParams, m: &StandardMaterial) -> PaintParams {
- p.k6.z = if matches!(m.alpha_mode, AlphaMode::Opaque) { 0.0 } else { 1.0 };
+ p.k6.z = if matches!(m.alpha_mode, AlphaMode::Opaque) || m.unlit { 0.0 } else { 1.0 };
p
}
diff --git a/systems/look/src/paint.wesl b/systems/look/src/paint.wesl
index 40d3b874..5dc43c75 100644
--- a/systems/look/src/paint.wesl
+++ b/systems/look/src/paint.wesl
@@ -99,6 +99,20 @@ fn fragment(
if texel > 0.0 {
wp = (floor((fine + pbr_input.world_normal * texel * 0.25) / texel) + 0.5) * texel;
}
+ // the texture's derivatives (below) taken here, before any branch: WGSL (and WebGPU's compiler, which refuses
+ // otherwise) wants them in uniform control flow, and the unlit return below depends on the material
+ var uv0 = vec2<f32>(0.0);
+ var px = vec3<f32>(0.0);
+ var py = vec3<f32>(0.0);
+ var ux = vec2<f32>(0.0);
+ var uy = vec2<f32>(0.0);
+@if(VERTEX_UVS_A) {
+ uv0 = (pbr_input.material.uv_transform * vec3<f32>(in.uv, 1.0)).xy;
+ px = dpdx(fine);
+ py = dpdy(fine);
+ ux = dpdx(uv0);
+ uy = dpdy(uv0);
+}
// unlit (a MeshBasicMaterial, `unlit`): its own colour, as drawn
if (pbr_input.material.flags & STANDARD_MATERIAL_FLAGS_UNLIT_BIT) != 0u {
out.color = main_pass_post_lighting_processing(pbr_input, vec4<f32>(c.rgb + pbr_input.material.emissive.rgb * view_bindings::view.exposure, c.a));
@@ -106,12 +120,7 @@ fn fragment(
}
@if(VERTEX_UVS_A) {
// the texture read at the cell's centre: the uv there found from how uv and the world move across the screen
- // (derivatives taken before any branch, as WGSL needs)
- let uv0 = (pbr_input.material.uv_transform * vec3<f32>(in.uv, 1.0)).xy;
- let px = dpdx(fine);
- let py = dpdy(fine);
- let ux = dpdx(uv0);
- let uy = dpdy(uv0);
+ // (the derivatives taken above, before any branch)
@if(!BINDLESS) {
if texel > 0.0 && (pbr_input.material.flags & STANDARD_MATERIAL_FLAGS_BASE_COLOR_TEXTURE_BIT) != 0u {
let d = wp - fine;
diff --git a/systems/look/src/paint_vertex.wesl b/systems/look/src/paint_vertex.wesl
index 634f7f22..7c5c64fa 100644
--- a/systems/look/src/paint_vertex.wesl
+++ b/systems/look/src/paint_vertex.wesl
@@ -48,14 +48,16 @@ var<uniform> paint: Paint;
// The wind (Bevy 0.20's mesh vertex, and its prepass's, with one change): a cut-out blade or leaf near the ground is
// bent downwind by how high it stands (by the square of its height over twice `foliage height`, so the root stays
// put), in gusts that travel across the field with the wind and a quicker flutter of its own. The prepass (depth,
-// normals, shadows) bends it the same, so the outlines and cast shadows move with the grass.
-fn wind(p: vec3<f32>) -> vec3<f32> {
+// normals, shadows) bends it the same, so the outlines and cast shadows move with the grass. A mesh with a second UV
+// set gives each vertex's height above its own root there (`above`, m; raea-sys-grass's fields on a hill), measured
+// from the ground at `ground y` otherwise (-1).
+fn wind(p: vec3<f32>, above: f32) -> vec3<f32> {
let strength = paint.k7.x;
if strength <= 0.0 || paint.k6.z < 0.5 {
return p;
}
let fh = max(paint.k4.x, 0.01);
- let y = p.y - paint.k0.z;
+ let y = select(p.y - paint.k0.z, above, above >= 0.0);
let h = clamp(y / (2.0 * fh), 0.0, 1.0);
let bend = h * h * (1.0 - smoothstep(2.0 * fh, 3.5 * fh, y));
if bend <= 0.0 {
@@ -108,7 +110,10 @@ fn vertex(vertex_no_morph: Vertex) -> VertexOutput {
@else
var world_from_local = mesh_world_from_local;
out.world_position = mesh_functions::mesh_position_local_to_world(world_from_local, vec4<f32>(vertex.position, 1.0));
- out.world_position = vec4<f32>(wind(out.world_position.xyz), 1.0);
+ var above = -1.0;
+ @if(VERTEX_UVS_B)
+ above = vertex.uv_b.x;
+ out.world_position = vec4<f32>(wind(out.world_position.xyz, above), 1.0);
out.position = position_world_to_clip(out.world_position.xyz);
@if(PREPASS_PIPELINE && UNCLIPPED_DEPTH_ORTHO_EMULATION) {
out.unclipped_depth = out.position.z;
diff --git a/systems/material/src/lib.rs b/systems/material/src/lib.rs
index bc308b5d..4ac3271b 100644
--- a/systems/material/src/lib.rs
+++ b/systems/material/src/lib.rs
@@ -17,4 +17,5 @@ pub mod mesh;
pub mod surface;
pub mod toon;
pub mod shadow_only;
+pub mod shadow_catch;
pub mod shader_material;
diff --git a/systems/material/src/shadow_catch.rs b/systems/material/src/shadow_catch.rs
new file mode 100644
index 00000000..616ab2bd
--- /dev/null
+++ b/systems/material/src/shadow_catch.rs
@@ -0,0 +1,46 @@
+//! A surface that shows only the shadows falling on it (`<Mesh shadow="catch">`, three.js's ShadowMaterial): a floor
+//! under a product shot over a picture or the page, so the product sits on what's behind it. Where nothing shades it,
+//! it's clear; where a light's shadow falls, it's its material's colour at its material's opacity, scaled by how much of
+//! the light is blocked (every shadow-casting light's shadow multiplied, as three's getShadowMask). It's blended and
+//! left out of the depth prepass, so the fog and outlines see through it.
+//!
+//! The row is a mesh row with `shadow_catch` 1 (engine.rs spawns it with this material in place of its standard one).
+//! Its colour and opacity are the spawn's: it isn't re-coloured frame by frame.
+
+use super::*;
+use bevy::pbr::{Material, MaterialPlugin};
+use bevy::render::render_resource::AsBindGroup;
+use bevy::shader::ShaderRef;
+
+pub fn install(app: &mut App) {
+ bevy::asset::embedded_asset!(app, "shadow_catch.wesl");
+ app.add_plugins(MaterialPlugin::<ShadowCatchMaterial>::default());
+}
+
+#[derive(Asset, TypePath, AsBindGroup, Clone, Default)]
+pub struct ShadowCatchMaterial {
+ /// the shadow's colour, linear rgb, and its opacity where the light is wholly blocked
+ #[uniform(0)]
+ pub color: Vec4,
+}
+
+impl ShadowCatchMaterial {
+ /// from the surface the row asked for: its base colour and opacity
+ pub fn of(base: &StandardMaterial) -> Self {
+ let c = base.base_color.to_linear();
+ Self { color: Vec4::new(c.red, c.green, c.blue, c.alpha) }
+ }
+}
+
+impl Material for ShadowCatchMaterial {
+ fn fragment_shader() -> ShaderRef {
+ "embedded://raea_sys_material/shadow_catch.wesl".into()
+ }
+ fn alpha_mode(&self) -> AlphaMode {
+ AlphaMode::Blend
+ }
+ /// not in the camera's depth prepass: what's behind it stays seen by the passes that read that depth
+ fn enable_prepass() -> bool {
+ false
+ }
+}
diff --git a/systems/material/src/shadow_catch.wesl b/systems/material/src/shadow_catch.wesl
new file mode 100644
index 00000000..67ddf06c
--- /dev/null
+++ b/systems/material/src/shadow_catch.wesl
@@ -0,0 +1,47 @@
+// shadow_catch.rs: a surface that shows only the shadows falling on it. Its alpha is its opacity times the share of
+// light blocked, every shadow-casting light's shadow multiplied (three.js's ShadowMaterial: getShadowMask).
+
+import bevy_pbr::render::forward_io::VertexOutput;
+import bevy_pbr::render::mesh_view_bindings as view_bindings;
+import bevy_pbr::render::mesh_view_types;
+import bevy_pbr::render::clustered_forward as clustering;
+import bevy_pbr::render::shadows;
+
+@group(constants::MATERIAL_BIND_GROUP) @binding(0) var<uniform> color: vec4<f32>;
+
+@fragment
+fn fragment(in: VertexOutput, @builtin(front_facing) is_front: bool) -> @location(0) vec4<f32> {
+ let P = in.world_position;
+ let N = normalize(select(-in.world_normal, in.world_normal, is_front));
+ let frag = in.position;
+ let view_z = dot(vec4<f32>(
+ view_bindings::view.view_from_world[0].z,
+ view_bindings::view.view_from_world[1].z,
+ view_bindings::view.view_from_world[2].z,
+ view_bindings::view.view_from_world[3].z
+ ), P);
+ let is_orthographic = view_bindings::view.clip_from_view[3].w == 1.0;
+
+ var lit = 1.0;
+ for (var i: u32 = 0u; i < view_bindings::lights.n_directional_lights; i = i + 1u) {
+ let light = &view_bindings::lights.directional_lights[i];
+ if ((*light).flags & mesh_view_types::DIRECTIONAL_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) != 0u {
+ lit *= shadows::fetch_directional_shadow(i, P, N, view_z, frag.xy);
+ }
+ }
+ let cluster_index = clustering::view_fragment_cluster_index(frag.xy, view_z, is_orthographic);
+ let ranges = clustering::unpack_clusterable_object_index_ranges(cluster_index);
+ for (var i: u32 = ranges.first_point_light_index_offset; i < ranges.first_reflection_probe_index_offset; i = i + 1u) {
+ let id = clustering::get_clusterable_object_id(i);
+ let light = &view_bindings::clustered_lights.data[id];
+ if ((*light).flags & mesh_view_types::POINT_LIGHT_FLAGS_SHADOWS_ENABLED_BIT) == 0u {
+ continue;
+ }
+ if i >= ranges.first_spot_light_index_offset {
+ lit *= shadows::fetch_spot_shadow(id, P, N, (*light).shadow_map_near_z, frag.xy);
+ } else {
+ lit *= shadows::fetch_point_shadow(id, P, N, frag.xy);
+ }
+ }
+ return vec4<f32>(color.rgb, color.a * (1.0 - lit));
+}
diff --git a/systems/volume/src/lib.rs b/systems/volume/src/lib.rs
index 7a0f703f..8b0c0ee7 100644
--- a/systems/volume/src/lib.rs
+++ b/systems/volume/src/lib.rs
@@ -141,9 +141,7 @@ impl Default for Spec {
}
}
-fn f32_of(o: &J, k: &str, d: f32) -> f32 {
- o.get(k).and_then(J::as_f64).map_or(d, |x| x as f32)
-}
+use raea_sys_frame::json_f32 as f32_of;
fn v3_of(o: &J, k: &str) -> Option<[f32; 3]> {
let a = o.get(k)?.as_array()?;