Bevy's deferred_raymarch, exact: a GBufferPass, drawn in the camera's viewport; cameras and lights placed by their own rotation

shader_advanced/deferred_raymarch (docs/control.feature FC2d) ports with a <GBufferPass> on the camera
(systems/phase gbuffer.rs): a shader file's fullscreen fragment writes Bevy's deferred G-buffer, the
lighting pass id and depth after the late deferred prepass, and its shadow entry writes every shadow view
the camera's lights draw, so Bevy's deferred lighting lights it and it casts shadows. It matches Bevy to
the pixel (SSIM 1.000000, 0 px off at frames 5, 10 and 30); the whole suite (147 ports) passes on pixels.

Three gaps closed on the way, each found by probing the shader's inputs on both sides:
- The pass sets the camera's viewport, as Bevy's own passes do. raea's target is w x (h + 1) (its tag
  row), so a fullscreen triangle drawn without it stretched its uv over 721 rows: rays a pixel low at the
  bottom.
- Camera3d sends its rotation, and the engine places the camera by it (rot_qx..qw, exact). It used to send
  a look-at point the engine turned back into a rotation in f32, about a millionth of a radian off. Bevy's
  lights do the same (their direction was also rounded to 1e-6).
- Transform.lookingAt computes in f32 as glam does (Dir3::new, cross, try_normalize,
  Quat::from_rotation_axes), the same quaternion to the bit; glam.test.ts holds it to glam's own bits.

The port sets Bevy's shadow defaults in a <Shadows> (2048 texels, cascades to 150 m, the first to 10 m,
overlap 0.2), as the other shadowed ports do. Mutants (no shadow entry, the first cascade at 8 m, 7000 lux,
the cube moved 5 cm, the camera's target 1 cm up) are each thousands of pixels off.
This commit is contained in:
shinyobjectz committed 2026-11-08 14:40:08 -08:00
1 parent ce63b7a280
commit eeea139ade
20 files changed
+396 -62

No files matched your search

+1
View File
@@ -145,3 +145,4 @@ shader_advanced/custom_vertex_attribute
shader_advanced/fullscreen_material
shader_advanced/custom_render_phase
shader_advanced/custom_shader_instancing
shader_advanced/deferred_raymarch
+1
View File
@@ -144,3 +144,4 @@ shader_advanced/custom_vertex_attribute - 5,10
shader_advanced/fullscreen_material - 10,30,60
shader_advanced/custom_render_phase - 5,10
shader_advanced/custom_shader_instancing - 5,10
shader_advanced/deferred_raymarch - 5,10,30
1 # path example arguments (- for none) frames probed input script, optional (docs/control.feature FC0a; tools/bevy-parity)
144 shader_advanced/fullscreen_material - 10,30,60
145 shader_advanced/custom_render_phase - 5,10
146 shader_advanced/custom_shader_instancing - 5,10
147 shader_advanced/deferred_raymarch - 5,10,30
+4 -1
View File
@@ -4,7 +4,7 @@ Bevy v0.20.0's examples against their raea TSX ports (docs/control.feature FC0a)
don't edit. An example passes when every probed frame passes pixels (SSIM 0.98 and no 32 px tile off by more than 24 of 255) and cost (batch keys and
frame time at most 1.25x the example's). Wall time is one machine's, measured in the same run.
Examples: **438**, ported **145**, passing **145**, excluded **17** (docs/bevy-parity/excluded.tsv), left **276**.
Examples: **438**, ported **146**, passing **146**, excluded **17** (docs/bevy-parity/excluded.tsv), left **275**.
raea's frame ms is its update's plus the time React takes to step a frame for its 3D (step), which the example
doesn't pay.
@@ -236,6 +236,9 @@ doesn't pay.
| shader_advanced/custom_shader_instancing | 5 | 1.000000 | 0 | 0 / 0 | 442 / 524 | 6 / 8 | 1 / 1 | 45.771 / 4.077 = 4.077 + 0 | yes | |
| shader_advanced/custom_phase_item | 10 | 1.000000 | 0 | 0 / 0 | 442 / 523 | 5 / 7 | 1 / 1 | 4.21 / 1.445 = 1.445 + 0 | yes | |
| shader_advanced/custom_phase_item | 5 | 1.000000 | 0 | 0 / 0 | 442 / 523 | 5 / 7 | 1 / 1 | 54.956 / 2.448 = 2.448 + 0 | yes | |
| shader_advanced/deferred_raymarch | 10 | 1.000000 | 0 | 2 / 2 | 445 / 530 | 7 / 9 | 3 / 3 | 4.989 / 6.005 = 6.005 + 0 | yes | |
| shader_advanced/deferred_raymarch | 30 | 1.000000 | 0 | 2 / 2 | 443 / 530 | 7 / 9 | 3 / 3 | 5.479 / 3.62 = 3.62 + 0 | yes | |
| shader_advanced/deferred_raymarch | 5 | 1.000000 | 0 | 2 / 2 | 443 / 530 | 7 / 9 | 3 / 3 | 59.743 / 8.363 = 8.363 + 0 | yes | |
## Excluded
+3
View File
@@ -223,3 +223,6 @@
{"example":"shader_advanced/custom_shader_instancing","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":5,"frame_ms":45.771,"materials":1,"mesh_entities":1,"meshes":6,"other_material":1,"visible":1},"raea":{"frame":12,"entities":524,"mesh_entities":1,"visible":1,"meshes":8,"materials":1,"batch_keys":0,"other_material":1,"extents":[],"frame_ms":4.077,"step_ms":null,"cost_ms":4.077},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/custom_phase_item","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":10,"frame_ms":4.21,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":523,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":1.445,"step_ms":null,"cost_ms":1.445},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/custom_phase_item","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":0,"entities":442,"extents":[],"frame":5,"frame_ms":54.956,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":12,"entities":523,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.448,"step_ms":null,"cost_ms":2.448},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/deferred_raymarch","frame":10,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":2,"entities":445,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame":10,"frame_ms":4.989,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":17,"entities":530,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame_ms":6.005,"step_ms":null,"cost_ms":6.005},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/deferred_raymarch","frame":30,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":2,"entities":443,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame":30,"frame_ms":5.479,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":37,"entities":530,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame_ms":3.62,"step_ms":null,"cost_ms":3.62},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"shader_advanced/deferred_raymarch","frame":5,"ssim":1.000000,"tile":0,"bevy":{"batch_keys":2,"entities":443,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame":5,"frame_ms":59.743,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":12,"entities":530,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.6000 0.6000 0.6000","10.0000 0.0000 10.0000"],"frame_ms":8.363,"step_ms":null,"cost_ms":8.363},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+5
View File
@@ -65,6 +65,11 @@ fn one(all: &[Vec<Item>], p: &mut Program, row: &mut BTreeMap<String, V>, k: usi
}
// which way is up (`up`; +Y by default): a camera that rolls, as a solved one does (raea-render's up_x/y/z, Matchmove)
keyed_vec(p, row, id, &its, "up", &["up_x", "up_y", "up_z"], &[0.0, 1.0, 0.0]);
// a Camera3d's Transform rotation (`rotation`, a quaternion on every frame), exact, which the engine places it by over
// its look-at point
if its.iter().all(|c| c.props.get("rotation").and_then(Value::as_array).is_some_and(|q| q.len() == 4)) {
quat_columns(p, row, id, "rot", &its.iter().map(Some).collect::<Vec<_>>());
}
// a window on a larger view (`view`: its full size and this frame's offset, in frame pixels): a crop of
// footage keeps its lens's centre (raea-render's camera view_*, Matchmove's 9:16 from 16:9)
if its.iter().any(|c| c.props.get("view").is_some_and(Value::is_object)) {
+14
View File
@@ -34,3 +34,17 @@ fn each_camera_after_the_first_is_a_row_with_its_order_clear_and_viewport() {
assert_eq!([n(second, "order"), n(second, "vp_x"), n(second, "vp_y")], [Some(1.0), Some(640.0), Some(360.0)]);
assert_eq!(n(second, "x"), Some(150.0));
}
#[test]
fn a_camera_with_a_rotation_keeps_it_exactly_and_one_without_has_none() {
// a Camera3d's quaternion as glam made it (Transform::looking_at from (4, 3, 6) to (0, 0.2, 0)), unrounded: the
// engine places the camera by it, not by its look-at point turned back into a rotation in f32
let q = [-0.17622831463813782, 0.28482943773269653, 0.05335763469338417, 0.9407277703285217];
let mut row: BTreeMap<String, V> = [("id".to_string(), V::S("cam".into()))].into();
camera(&[vec![cam(json!({ "position": [4, 3, 6], "lookAt": [0, 0.2, 0], "rotation": q }))]], &mut Program::default(), &mut row);
let got: Vec<Option<f64>> = ["rot_qx", "rot_qy", "rot_qz", "rot_qw"].iter().map(|k| row.get(*k).map(V::num)).collect();
assert_eq!(got, q.map(Some));
let mut plain: BTreeMap<String, V> = [("id".to_string(), V::S("cam".into()))].into();
camera(&[vec![cam(json!({ "position": [4, 3, 6], "lookAt": [0, 0.2, 0], "rotation": [0.1, 0.2, 0.3] }))]], &mut Program::default(), &mut plain);
assert!(!plain.contains_key("rot_qw"), "a rotation that isn't a quaternion places nothing");
}
+5
View File
@@ -117,6 +117,11 @@ impl LiveScene {
put("dir_x", target[0] - pos[0]);
put("dir_y", target[1] - pos[1]);
put("dir_z", target[2] - pos[2]);
if let Some(q) = crate::parts::light_rotation(it) {
for (name, v) in ["rot_qx", "rot_qy", "rot_qz", "rot_qw"].into_iter().zip(q) {
put(name, v);
}
}
}
if it.kind == "spot" {
// its cone, as parts.rs keys it: a spot whose angle moves (3d/spotlight) kept its first (#26)
+1 -1
View File
@@ -55,7 +55,7 @@ pub(crate) const MORPH_COLS: [&str; 64] = ["morph0", "morph1", "morph2", "morph3
/// The columns a frame may change, per kind (what `rows_into` and `camera` key); everything else is the first frame's.
pub(crate) fn live_dynamic(kind: &str) -> &'static [&'static str] {
match kind {
"light" => &["lux", "lumens", "x", "y", "z", "dir_x", "dir_y", "dir_z", "inner", "outer"],
"light" => &["lux", "lumens", "x", "y", "z", "dir_x", "dir_y", "dir_z", "rot_qx", "rot_qy", "rot_qz", "rot_qw", "inner", "outer"],
"mesh" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "col_r", "col_g", "col_b", "rough", "metal", "emissive_k", "opacity", "sh_r", "sh_g", "sh_b", "rim_k", "spec_k", "outline_w", "pass"],
"model" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "anim_t", "mix0_t", "mix0_w", "mix1_t", "mix1_w", "mix2_t", "mix2_w", "mix3_t", "mix3_w", "morph0", "morph1", "morph2", "morph3", "morph4", "morph5", "morph6", "morph7", "morph8", "morph9", "morph10", "morph11", "morph12", "morph13", "morph14", "morph15", "morph16", "morph17", "morph18", "morph19", "morph20", "morph21", "morph22", "morph23", "morph24", "morph25", "morph26", "morph27", "morph28", "morph29", "morph30", "morph31", "morph32", "morph33", "morph34", "morph35", "morph36", "morph37", "morph38", "morph39", "morph40", "morph41", "morph42", "morph43", "morph44", "morph45", "morph46", "morph47", "morph48", "morph49", "morph50", "morph51", "morph52", "morph53", "morph54", "morph55", "morph56", "morph57", "morph58", "morph59", "morph60", "morph61", "morph62", "morph63", "g0_w", "g0_t", "g1_w", "g1_t", "g2_w", "g2_t", "g3_w", "g3_t", "g4_w", "g4_t", "g5_w", "g5_t", "g6_w", "g6_t", "g7_w", "g7_t", "g8_w", "g8_t", "g9_w", "g9_t", "g10_w", "g10_t", "g11_w", "g11_t", "g12_w", "g12_t", "g13_w", "g13_t", "g14_w", "g14_t", "g15_w", "g15_t", "look", "glitch_explode", "glitch_scramble", "glitch_jitter", "glitch_snap", "glitch_smear_x", "glitch_smear_y", "glitch_smear_z", "glitch_seed", "cloth_frame", "screen_power", "pass"],
"panel" => &["x", "y", "z", "q_x", "q_y", "q_z", "q_w", "scale_x", "scale_y", "scale_z", "visible", "screen_power", "screen_bright", "pass"],
+31
View File
@@ -68,6 +68,13 @@ pub(crate) fn lights_rows(all: &[Vec<Item>], tr: &Tracks, p: &mut Program) {
for (k, name) in ["dir_x", "dir_y", "dir_z"].iter().enumerate() {
column(p, &mut row, &id, name, &pos.iter().zip(&target).map(|(a, b)| b[k] - a[k]).collect::<Vec<_>>());
}
// a Bevy light's own rotation (`rotation`, its Transform's), exact, which the engine places it by over its
// direction: one rounded to 1e-6 and turned back into a rotation in f32 moves a sun's shadow cascades
if its.iter().all(|i| light_rotation(i).is_some()) {
for (k, name) in ["rot_qx", "rot_qy", "rot_qz", "rot_qw"].iter().enumerate() {
exact(p, &mut row, &id, name, &its.iter().map(|i| light_rotation(i).map_or(0.0, |q| q[k])).collect::<Vec<_>>());
}
}
}
let first = &its[0].props;
if let Some(c) = hex(first.get("color")).filter(|c| c != "#ffffff") {
@@ -386,3 +393,27 @@ pub(crate) fn texts_rows(tr: &Tracks, names: &[String], p: &mut Program) {
}
}
}
/// A light's `rotation` quaternion, when it has one and sits in no turned or moved group (one in a group keeps its
/// direction, which its group's transform doesn't turn either).
pub(crate) fn light_rotation(i: &Item) -> Option<[f64; 4]> {
let q = i.props.get("rotation")?.as_array()?;
(q.len() == 4 && i.world == Mat4::IDENTITY).then(|| [0, 1, 2, 3].map(|k| q[k].as_f64().unwrap_or(0.0)))
}
#[cfg(test)]
mod light_rotation_tests {
use super::*;
fn sun(props: serde_json::Value, world: Mat4) -> Item {
Item { kind: "directional", props: std::sync::Arc::new(props.as_object().unwrap().clone()), shape: None, material: None, world }
}
#[test]
fn a_light_keeps_its_quaternion_unless_a_group_moves_it() {
let q = [-0.42470818758010864, 0.33985114097595215, 0.17591990530490875, 0.8204732537269592];
assert_eq!(light_rotation(&sun(serde_json::json!({ "rotation": q }), Mat4::IDENTITY)), Some(q));
assert_eq!(light_rotation(&sun(serde_json::json!({ "rotation": q }), Mat4::from_translation(Vec3::X))), None);
assert_eq!(light_rotation(&sun(serde_json::json!({ "target": [0, 0, 0] }), Mat4::IDENTITY)), None);
}
}
+21 -4
View File
@@ -199,15 +199,21 @@ pub fn sync_meshes(
/// once, and a row that moves (or moves back) writes every frame it changes. An entity with no entry always writes,
/// so a render seeking straight to frame N places its camera.
#[allow(clippy::type_complexity)]
pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3)>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>, Option<&mut Camera>), (With<Camera3d>, Without<super::BareEntity>)>) {
pub fn sync_camera(frame: Res<FrameRows>, edit: Option<Res<Edit>>, mut placed: Local<bevy::platform::collections::HashMap<Entity, (Vec3, Vec3, Option<Quat>)>>, mut q: Query<(Entity, &mut Transform, Option<&mut Projection>, Option<&mut AmbientLight>, Option<&mut bevy::post_process::dof::DepthOfField>, Option<&mut super::lens::Lens>, Option<&mut bevy::post_process::effect_stack::ChromaticAberration>, Option<&mut Camera>), (With<Camera3d>, Without<super::BareEntity>)>) {
for (e, mut t, proj, amb, dof, lens, ab, cam) in &mut q {
let Some(v) = frame.vals(e) else { continue };
let v = &v;
let pos = Vec3::new(num(v, "x", 0.0), num(v, "y", 2.0), num(v, "z", 9.0));
let look = Vec3::new(num(v, "look_x", 0.0), num(v, "look_y", 1.0), num(v, "look_z", 0.0));
if (look - pos).length_squared() > 1e-12 && placed.get(&e) != Some(&(pos, look)) {
placed.insert(e, (pos, look));
let nt = Transform::from_translation(pos).looking_at(look, up_for(look - pos));
// a Camera3d's own rotation (rot_qx..qw), exactly as its Transform holds it: its look-at point rebuilt into a
// rotation in f32 is a millionth of a radian off, which a raymarch through the view's matrices shows
let rot = row_rotation(v);
if (rot.is_some() || (look - pos).length_squared() > 1e-12) && placed.get(&e) != Some(&(pos, look, rot)) {
placed.insert(e, (pos, look, rot));
let nt = match rot {
Some(r) => Transform::from_translation(pos).with_rotation(r),
None => Transform::from_translation(pos).looking_at(look, up_for(look - pos)),
};
if *t != nt {
*t = nt;
}
@@ -308,8 +314,12 @@ pub fn sync_lights(frame: Res<FrameRows>, mut commands: Commands, mut q: Query<(
let v = &v;
let pos = Vec3::new(num(v, "x", 0.0), num(v, "y", 0.0), num(v, "z", 0.0));
let dir = Vec3::new(num(v, "dir_x", -0.5), num(v, "dir_y", -1.0), num(v, "dir_z", -0.4));
// a Bevy light's own rotation (rot_qx..qw), exactly as its Transform holds it, over its direction turned back
let rot = row_rotation(v);
let nt = if p.is_some() {
Transform::from_translation(pos)
} else if let Some(r) = rot {
Transform::from_translation(if d.is_some() { Vec3::ZERO } else { pos }).with_rotation(r)
} else if s.is_some() || rect.is_some() {
Transform::from_translation(pos).looking_to(dir, up_for(dir))
} else {
@@ -458,3 +468,10 @@ pub fn sync_bones(
}
}
}
/// A row's own rotation (rot_qx..qw: a Camera3d's or a Bevy light's Transform rotation, exact), normalized only between
/// keyed frames, where its components were interpolated.
fn row_rotation(v: &BTreeMap<String, V>) -> Option<Quat> {
let r = v.contains_key("rot_qw").then(|| Quat::from_xyzw(num(v, "rot_qx", 0.0), num(v, "rot_qy", 0.0), num(v, "rot_qz", 0.0), num(v, "rot_qw", 1.0)))?;
Some(if r.is_normalized() { r } else { r.normalize() })
}
@@ -0,0 +1,46 @@
// Bevy v0.20.0 examples/shader_advanced/deferred_raymarch.rs in raea's TSX (docs/control.feature FC2d): a gyroid
// raymarched in a fullscreen pass that writes Bevy's deferred G-buffer and depth, so deferred lighting lights it and
// the scene's meshes meet it in depth, and its `fragment_shadow` writes the directional light's shadow maps, so it
// casts shadows: a <GBufferPass> of assets/shaders/deferred_raymarch.wesl as written on the camera, which has Msaa off,
// DepthPrepass and DeferredPrepass, and every opaque material deferred (DefaultOpaqueRendererMethod::deferred()). The
// camera at (4, 3, 6) looking at (0, 0.2, 0) with an AmbientLight of 200; a 20 m plane of srgb(0.3, 0.5, 0.3) at
// y -1.5, a 1.2 m cube of srgb(0.2, 0.4, 0.9) and roughness 0.4 at (2.2, -0.9, 0.5), and a shadowed DirectionalLight of
// 8000 lux from (4, 8, 4) to the origin, in Bevy's default 1280 x 720 window. The gyroid moves with Globals' time.
// The cascades and the shadow map's size go in a <Shadows> at Bevy's defaults (2048 texels, four cascades to 150 m, the
// first to 10 m, overlapping by 0.2), as raea's sun keeps a film's. (Its FreeCamera only moves the camera under input,
// which a render has none of.)
import { Composition, registerRoot, staticFile } from "raea";
import { BevyComponent, BevyResource, GBufferPass, Shadows } from "raea/3d";
import { Camera3d } from "raea/camera";
import { Srgba } from "raea/color";
import { AmbientLight, DirectionalLight } from "raea/light";
import { Cuboid, Mesh3d, Plane3d } from "raea/mesh";
import { StandardMaterial } from "raea/pbr";
import { Transform } from "raea/transform";
function Shot() {
return (
<>
<BevyResource type="bevy_pbr::material::DefaultOpaqueRendererMethod" value="Deferred" />
<Camera3d transform={Transform.fromXyz(4, 3, 6).lookingAt([0, 0.2, 0])}>
<BevyComponent type="bevy_render::view::Msaa" value="Off" />
<BevyComponent type="bevy_core_pipeline::prepass::DepthPrepass" value={{}} />
<BevyComponent type="bevy_core_pipeline::prepass::DeferredPrepass" value={{}} />
<GBufferPass shader={staticFile("shaders/deferred_raymarch.wesl")} shadow="fragment_shadow" />
</Camera3d>
<Shadows mapSize={2048} distance={150} firstCascade={10} cascades={4} overlap={0.2} />
<AmbientLight brightness={200} />
<Mesh3d transform={Transform.fromXyz(0, -1.5, 0)}>
<Plane3d half_size={[10, 10]} />
<StandardMaterial base_color={new Srgba(0.3, 0.5, 0.3)} />
</Mesh3d>
<Mesh3d transform={Transform.fromXyz(2.2, -0.9, 0.5)}>
<Cuboid half_size={[0.6, 0.6, 0.6]} />
<StandardMaterial base_color={new Srgba(0.2, 0.4, 0.9)} perceptual_roughness={0.4} />
</Mesh3d>
<DirectionalLight illuminance={8000} shadow_maps_enabled transform={Transform.fromXyz(4, 8, 4).lookingAt([0, 0, 0])} />
</>
);
}
registerRoot(() => <Composition id="main" component={Shot} durationInFrames={31} fps={60} width={1280} height={720} />);
+16 -13
View File
@@ -51,9 +51,10 @@ describe("Quat and Transform", () => {
const t = Transform.fromXyz(0, 2, 7).lookingAt([0, 0.5, 0]);
const f = Quat.mulVec3(t.rotation, [0, 0, -1]);
const want = [0, -1.5, -7].map((v) => v / Math.hypot(1.5, 7));
expect(close(f, want, 1e-9)).toBe(true);
// in f32, as glam computes it (glam.test.ts holds it to glam's own bits)
expect(close(f, want, 1e-6)).toBe(true);
expect(Quat.mulVec3(t.rotation, [0, 1, 0])[1]).toBeGreaterThan(0.9);
expect(Math.hypot(...t.rotation)).toBeCloseTo(1, 12);
expect(Math.hypot(...t.rotation)).toBeCloseTo(1, 6);
// Bevy's fallback, not a throw: a target at the eye looks down -Z (the identity)
expect(Transform.fromXyz(0, 0, 0).lookingAt([0, 0, 0]).rotation.map((v) => v + 0)).toEqual([0, 0, 0, 1]);
});
@@ -104,12 +105,12 @@ describe("Bevy's shapes draw the same args", () => {
describe("Mesh3d, Camera3d and StandardMaterial", () => {
test("Bevy's DepthOfField on a Camera3d: focal_distance is the camera's focus, its fields the old lens's", () => {
const cam = <PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} fov={45} focus={7} />;
const cam = <PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} rotation={[0, 0, 0, 1]} fov={45} focus={7} />;
expect(html(<Camera3d><DepthOfField focal_distance={7} aperture_f_stops={2.8} mode="Gaussian" max_circle_of_confusion_diameter={32} /></Camera3d>)).toBe(
html(<>{cam}<DepthOfField mode="gaussian" aperture={2.8} maxBlur={32} /></>),
);
// Bevy's defaults: focal_distance 10, f/1
expect(html(<Camera3d><DepthOfField /></Camera3d>)).toBe(html(<><PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} fov={45} focus={10} /><DepthOfField aperture={1} /></>));
expect(html(<Camera3d><DepthOfField /></Camera3d>)).toBe(html(<><PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} rotation={[0, 0, 0, 1]} fov={45} focus={10} /><DepthOfField aperture={1} /></>));
expect(html(<Camera3d><DepthOfField aperture_f_stops={2} /></Camera3d>)).toContain(html(<DepthOfField aperture={2} />));
expect(() => html(<DepthOfField focal_distance={3} />)).toThrow(/inside the Camera3d/);
expect(() => html(<DepthOfField aperture={2} aperture_f_stops={2} />)).toThrow(/not both/);
@@ -143,14 +144,16 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => {
const props = JSON.parse(cam.match(/data-props="([^"]*)"/)![1].replace(/&quot;/g, '"'));
expect(props.fov).toBeCloseTo(45, 12);
const dir = [props.lookAt[0] - 0, props.lookAt[1] - 2, props.lookAt[2] - 7];
expect(close(dir.map((v) => v / Math.hypot(...dir)), [0, -1.5, -7].map((v) => v / Math.hypot(1.5, 7)), 1e-9)).toBe(true);
expect(html(<Camera3d />)).toBe(html(<PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} fov={45} />));
// no `up` for a camera that doesn't roll (one sends the row down the engine's roll path); a rolled one keeps it
expect(props.up).toBeUndefined();
expect(close(dir.map((v) => v / Math.hypot(...dir)), [0, -1.5, -7].map((v) => v / Math.hypot(1.5, 7)), 1e-6)).toBe(true);
expect(html(<Camera3d />)).toBe(html(<PerspectiveCamera position={[0, 0, 0]} lookAt={[0, 0, -1]} rotation={[0, 0, 0, 1]} fov={45} />));
// its rotation exactly as its Transform holds it, which the engine places it by (rolled or not), and no `up`
const t = Transform.fromXyz(0, 2, 7).lookingAt([0, 0.5, 0]);
const rolled = html(<Camera3d transform={t.withRotation(Quat.mul(t.rotation, Quat.fromRotationZ(0.3)))} />);
const up = JSON.parse(rolled.match(/data-props="([^"]*)"/)![1].replace(/&quot;/g, '"')).up;
expect(up[0]).toBeCloseTo(-Math.sin(0.3), 9);
expect(props.rotation).toEqual(t.rotation.map((v) => v + 0)); // JSON has no -0
expect(props.up).toBeUndefined();
const turn = Quat.mul(t.rotation, Quat.fromRotationZ(0.3));
const rolled = JSON.parse(html(<Camera3d transform={t.withRotation(turn)} />).match(/data-props="([^"]*)"/)![1].replace(/&quot;/g, '"'));
expect(rolled.rotation).toEqual(turn.map((v) => v + 0));
expect(rolled.up).toBeUndefined();
});
test("StandardMaterial takes Bevy's fields and defaults; unlit is MeshBasicMaterial", () => {
@@ -327,11 +330,11 @@ describe("Bevy's lights, in Bevy's units", () => {
test("SpotLight and DirectionalLight shine along their transform's -Z; the spot's angles are Bevy's", () => {
const t = Transform.fromXyz(0, 4, 0).lookingAt([0, 0, 0], [0, 0, -1]);
const spot = props(html(<SpotLight transform={t} outer_angle={0.6} inner_angle={0.3} />));
expect(close(spot.target, [0, 3, 0], 1e-9)).toBe(true);
expect(close(spot.target, [0, 3, 0], 1e-6)).toBe(true);
expect(spot.angle).toBe(0.6);
expect(spot.penumbra).toBeCloseTo(0.5, 12);
const sun = props(html(<DirectionalLight transform={Transform.fromRotation(Quat.fromRotationX(-Math.PI / 2))} shadow_maps_enabled />));
expect(close(sun.target.map((v: number, i: number) => v - sun.position[i]), [0, -1, 0], 1e-9)).toBe(true);
expect(close(sun.target.map((v: number, i: number) => v - sun.position[i]), [0, -1, 0], 1e-6)).toBe(true);
expect(sun.lux).toBe(10_000);
expect(sun.castShadow).toBe(true);
});
+2 -1
View File
@@ -22,7 +22,8 @@ for (const [n, row] of (fixture as any[]).entries()) {
case "euler": return near(Quat.fromEuler(row.order, ...(row.abc as V)), row.q);
case "mul": return near(Quat.mul(row.a as Q, row.b as Q), row.q);
case "mulVec3": return near(Quat.mulVec3(row.q as Q, row.v as V), row.out);
case "lookingAt": return near(Transform.fromTranslation(row.eye as V).lookingAt(row.target as V, row.up as V).rotation, row.q);
// computed in f32 as glam does it: the same quaternion to the bit
case "lookingAt": return expect(Transform.fromTranslation(row.eye as V).lookingAt(row.target as V, row.up as V).rotation.map(Math.fround)).toEqual(row.q.map(Math.fround));
default: throw new Error(`unknown op ${row.op}`);
}
});
+2 -2
View File
@@ -2,8 +2,8 @@
// carries its name (data-3d) and props (data-props, JSON) for Bevy to draw; a Mesh also carries its Manifold
// expression (data-shape). Engine-safe: this module imports nothing beyond React.
import { toHex } from "./colour";
export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, PhaseItem, MeshPass, ShaderInstances, MeshVertexAttribute, ATTRIBUTE_POSITION, ATTRIBUTE_NORMAL, ATTRIBUTE_UV_0, ATTRIBUTE_UV_1, ATTRIBUTE_TANGENT, ATTRIBUTE_COLOR, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, EnvironmentMapLight, Skybox, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";
export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, ThreeShaderMaterialProps, ThreeUniform, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, MeshSlab, PhaseItemProps, PhaseAttribute, MeshPassProps, ShaderInstancesProps, VertexFormat, MeshAttribute, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, FogColor, FogFalloff, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, EnvironmentMapLightProps, SkyboxProps, AmbientOcclusionProps, AntiAliasingProps, ShadowsProps, VolumetricFogProps, FogVolumeProps, FireProps, DepthOfFieldProps, OutlineProps, LensCommon, FisheyeProps, LensDistortionProps, MotionBlurProps, LookProps, LookPass, SceneProps, BevyComponentProps, GizmoProps, ShaderMeshProps, SpanProps, GlyphInfo, GlyphStyle, RichTextProps, Instance, InstancesProps, PlanBox, ScatterOptions, GrassProps, GrassLod } from "./3d/all";
export { Canvas3D, Cuboid, Sphere, Plane3d, Cylinder, Torus, Cone, Capsule, Capsule3d, BufferMesh, Text3D, SurfaceShader, ThreeShaderMaterial, surfaceShader, samplerSpec, FramePass, Compute, PhaseItem, MeshPass, ShaderInstances, GBufferPass, MeshVertexAttribute, ATTRIBUTE_POSITION, ATTRIBUTE_NORMAL, ATTRIBUTE_UV_0, ATTRIBUTE_UV_1, ATTRIBUTE_TANGENT, ATTRIBUTE_COLOR, Atmosphere, eulerOf, Entity, Refinish, clipEvents, Model, ImagePlane, surfaceTurn, Decal, Plate, Bloom, Fog, ToneMapping, Grade, Environment, EnvironmentMapLight, Skybox, AmbientOcclusion, AntiAliasing, Shadows, VolumetricFog, FogVolume, Fire, dofOf, DepthOfField, Outline, Fisheye, LensDistortion, MotionBlur, checkPass, Look, Scene, Entities, BevyComponent, Gizmo, ShaderMesh, BevyResource, Span, RichText, Instances, scatter, Grass } from "./3d/all";
export type { Vec3, Canvas3DProps, CuboidProps, SphereProps, CylinderProps, TorusProps, Plane3dProps, ConeProps, CapsuleProps, Capsule3dProps, BufferMeshProps, Text3DProps, Animate3d, SurfaceDrawProps, ToonBand, ToonRim, ToonHighlight, ToonOutline, SurfaceShaderSpec, ThreeShaderMaterialProps, ThreeUniform, SamplerSpec, SamplerWrap, FramePassProps, ComputeProps, MeshSlab, PhaseItemProps, PhaseAttribute, MeshPassProps, ShaderInstancesProps, GBufferPassProps, VertexFormat, MeshAttribute, AtmosphereProps, BevyParts, EntityProps, ModelProps, AnimGraphNode, ImagePlaneProps, DecalProps, PlateProps, BloomProps, FogProps, FogColor, FogFalloff, ToneMappingProps, GradeSection, GradeProps, EnvironmentProps, EnvironmentMapLightProps, SkyboxProps, 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";
// blended distance fields and generated growth (trees, lofts, terrain, boulders, rosettes), as Solids (grow.ts)
+12
View File
@@ -25,6 +25,9 @@ export interface DirectionalLightProps {
position?: Vec3;
/** where it shines towards (the origin by default) */
target?: Vec3;
/** its rotation, a quaternion [x, y, z, w], as a Bevy light's Transform holds it: placed by it exactly over
* `target` (raea/light sends it) */
rotation?: [number, number, number, number];
intensity?: number;
color?: string;
/** shadows (on by default for a directional light) */
@@ -105,6 +108,9 @@ export function PointLight({ intensity = 1, color = "#ffffff", children, ...rest
export interface SpotLightProps extends PointLightProps {
/** where it points (the origin by default) */
target?: Vec3;
/** its rotation, a quaternion [x, y, z, w], as a Bevy light's Transform holds it: placed by it exactly over
* `target` (raea/light sends it) */
rotation?: [number, number, number, number];
/** the cone's half-angle in radians (π/3 by default), up to π/2 */
angle?: number;
/** 0..1: how soft the cone's edge is */
@@ -124,6 +130,9 @@ export interface RectAreaLightProps {
position?: Vec3;
/** where its face looks (the origin by default) */
target?: Vec3;
/** its rotation, a quaternion [x, y, z, w], as a Bevy light's Transform holds it: placed by it exactly over
* `target` (raea/light sends it) */
rotation?: [number, number, number, number];
/** its face's size in metres (1 x 1 by default) */
width?: number;
height?: number;
@@ -171,6 +180,9 @@ export interface PerspectiveCameraProps {
focus?: number;
/** which way is up for the camera ([0, 1, 0] by default): tilt it to roll the camera (a solved camera rolls) */
up?: Vec3;
/** its rotation, a quaternion [x, y, z, w], which places it exactly (rolled or not) over `lookAt` and `up`, as a
* Camera3d's Transform does; lookAt still says where it looks, for its focus */
rotation?: [number, number, number, number];
/** the frame is a window on a larger view: the view's `width` x `height` (frame pixels; `fov` is its vertical field)
* and the window's top-left `x`, `y` in it. A crop of footage that keeps its lens's centre (<Matchmove> in 9:16 from
* 16:9 footage) */
+21
View File
@@ -89,3 +89,24 @@ export function ShaderInstances(p: ShaderInstancesProps) {
for (const a of attributes) if (!(Number.isInteger(a.offset) && a.offset >= 0 && a.offset < stride && Number.isInteger(a.location) && a.location >= 0)) throw new TypeError(`ShaderInstances: an attribute is { format, offset (under the stride), location }, got ${JSON.stringify(a)}`);
return <BevyComponent type="raea_sys_phase::ShaderInstances" value={{ shader: assetPath(shader), stride, attributes, words }} />;
}
export interface GBufferPassProps {
/** the shader file, compiled as written: staticFile("shaders/x.wesl"). Its entry points take Bevy's
* FullscreenVertexOutput; bind group 0 is the view uniform (binding 0) and Globals (binding 1) */
shader: string;
/** the entry point writing the G-buffer: its deferred vec4<u32> (location 0), its lighting pass id u32 (location 1)
* and its frag_depth ("fragment") */
fragment?: string;
/** the entry point writing a shadow view's frag_depth, so it casts shadows; none when left out */
shadow?: string;
}
/** Inside a Camera3d with Bevy's DepthPrepass and DeferredPrepass: your shader over the whole view, written into the
* deferred G-buffer after the deferred prepass (depth compared GreaterEqual), so Bevy's deferred lighting lights it as
* any surface, and into the shadow maps of the camera's lights (Bevy's shader_advanced/deferred_raymarch).
* @bevy raea_sys_phase::GBufferPass */
export function GBufferPass(p: GBufferPassProps) {
const { shader, fragment = "fragment", shadow = "" } = p;
if (typeof shader !== "string" || !shader) throw new TypeError(`GBufferPass: shader is a shader file, staticFile("shaders/x.wesl"), got ${JSON.stringify(shader)}`);
return <BevyComponent type="raea_sys_phase::GBufferPass" value={{ shader: assetPath(shader), fragment, shadow }} />;
}
+38 -35
View File
@@ -80,41 +80,45 @@ export const Affine2 = {
fromScaleAngleTranslation: (scale: [number, number], angle: number, translation: [number, number]): Affine2 => ({ scale, angle, translation }),
};
/** The rotation that points -Z from `eye` at `target` with +Y toward `up`, as Bevy's Transform::looking_at. */
/** The rotation that points -Z from `eye` at `target` with +Y toward `up`, as Bevy's Transform::looking_at computes it:
* in f32, step by step as glam does (Dir3::new, cross, try_normalize, Quat::from_rotation_axes), so it is the same
* quaternion to the bit, not one an ulp off (which a raymarch through the view's matrices shows). */
function lookingAt(eye: Vec3, target: Vec3, up: Vec3): Quat {
const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
// Bevy's fallbacks (look_to): a target at the eye looks down -Z, a zero up is +Y, and an up along the view takes glam's
// any_orthonormal_vector of up
const norm = (a: Vec3, or: () => Vec3): Vec3 => {
const n = Math.hypot(...a);
return n > 0 && Number.isFinite(n) ? [a[0] / n, a[1] / n, a[2] / n] : or();
const f = Math.fround;
const v = (a: Vec3): Vec3 => [f(a[0]), f(a[1]), f(a[2])];
const length = (a: Vec3) => f(Math.sqrt(f(f(f(a[0] * a[0]) + f(a[1] * a[1])) + f(a[2] * a[2]))));
const cross = (a: Vec3, b: Vec3): Vec3 => [f(f(a[1] * b[2]) - f(b[1] * a[2])), f(f(a[2] * b[0]) - f(b[2] * a[0])), f(f(a[0] * b[1]) - f(b[0] * a[1]))];
// Dir3::new: the vector over its length, or Bevy's fallback when it has none
const dir = (a: Vec3, or: Vec3): Vec3 => {
const n = length(a);
return n > 0 && Number.isFinite(n) ? [f(a[0] / n), f(a[1] / n), f(a[2] / n)] : or;
};
const back = norm(sub(eye, target), () => [0, 0, 1]);
const up1 = norm(up, () => [0, 1, 0]);
const right = norm(cross(up1, back), () => {
const [e, t] = [v(eye), v(target)];
const d = dir([f(t[0] - e[0]), f(t[1] - e[1]), f(t[2] - e[2])], [0, 0, -1]);
const back: Vec3 = [-d[0], -d[1], -d[2]];
const up1 = dir(v(up), [0, 1, 0]);
const r0 = cross(up1, back);
const rcp = f(1 / length(r0));
// try_normalize, or glam's any_orthonormal_vector of up for an up along the view
const right: Vec3 = Number.isFinite(rcp) && rcp > 0 ? [f(r0[0] * rcp), f(r0[1] * rcp), f(r0[2] * rcp)] : (() => {
const sign = up1[2] < 0 || Object.is(up1[2], -0) ? -1 : 1;
const a = -1 / (sign + up1[2]);
return [up1[0] * up1[1] * a, sign + up1[1] * up1[1] * a, -up1[1]];
});
const u = cross(back, right);
// the rotation matrix's columns are right, u, back; its quaternion (Shepperd's method)
const [m00, m10, m20, m01, m11, m21, m02, m12, m22] = [right[0], right[1], right[2], u[0], u[1], u[2], back[0], back[1], back[2]];
const t = m00 + m11 + m22;
if (t > 0) {
const s = Math.sqrt(t + 1) * 2;
return [(m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s, s / 4];
const a = f(-1 / f(sign + up1[2]));
return [f(f(up1[0] * up1[1]) * a), f(sign + f(f(up1[1] * up1[1]) * a)), -up1[1]];
})();
// Quat::from_rotation_axes(right, up, back), DirectXMath's XMQuaternionRotationMatrix as glam writes it
const [[m00, m01, m02], [m10, m11, m12], [m20, m21, m22]] = [right, cross(back, right), back];
const q = (sq: number, at: number, a: number, b: number, c: number): Quat => {
const inv = f(0.5 / f(Math.sqrt(sq)));
const out = [f(a * inv), f(b * inv), f(c * inv)];
out.splice(at, 0, f(sq * inv));
return out as Quat;
};
if (m22 <= 0) {
const dif10 = f(m11 - m00), omm22 = f(1 - m22);
return dif10 <= 0 ? q(f(omm22 - dif10), 0, f(m01 + m10), f(m02 + m20), f(m12 - m21)) : q(f(omm22 + dif10), 1, f(m01 + m10), f(m12 + m21), f(m20 - m02));
}
if (m00 > m11 && m00 > m22) {
const s = Math.sqrt(1 + m00 - m11 - m22) * 2;
return [s / 4, (m01 + m10) / s, (m02 + m20) / s, (m21 - m12) / s];
}
if (m11 > m22) {
const s = Math.sqrt(1 + m11 - m00 - m22) * 2;
return [(m01 + m10) / s, s / 4, (m12 + m21) / s, (m02 - m20) / s];
}
const s = Math.sqrt(1 + m22 - m00 - m11) * 2;
return [(m02 + m20) / s, (m12 + m21) / s, s / 4, (m10 - m01) / s];
const sum10 = f(m11 + m00), opm22 = f(1 + m22);
return sum10 <= 0 ? q(f(opm22 - sum10), 2, f(m02 + m20), f(m12 + m21), f(m01 - m10)) : q(f(opm22 + sum10), 3, f(m12 - m21), f(m20 - m02), f(m01 - m10));
}
/** A Transform's value, as Bevy reflects it. */
@@ -263,10 +267,9 @@ export function Camera3d({ transform, projection = { Perspective: {} }, layers,
const q = transform?.rotation ?? Quat.IDENTITY;
const f = Quat.mulVec3(q, [0, 0, -1]);
const lookAt: Vec3 = [eye[0] + f[0], eye[1] + f[1], eye[2] + f[2]];
// `up` only for a camera that rolls: one that doesn't is placed as the old camera is (+Y up), and an `up` sends its
// row down the engine's roll path (matchmove.rs sync_view), which draws a moving camera elsewhere
const level = Math.abs(f[1]) < 1 - 1e-9 && Math.abs(qdot(q, lookingAt(eye, lookAt, [0, 1, 0]))) > 1 - 1e-9;
const look = { position: eye, lookAt, ...(level ? {} : { up: Quat.mulVec3(q, [0, 1, 0]) }), ...(layers ? { layers } : {}), ...(order ? { order } : {}), ...clear, ...(viewport ? { viewport } : {}) };
// its rotation as its Transform holds it, which the engine places it by (rolled or not), exactly; the look-at point
// is for what reads a camera by where it looks (its lens's focus, picking, sound)
const look = { position: eye, lookAt, rotation: q, ...(layers ? { layers } : {}), ...(order ? { order } : {}), ...clear, ...(viewport ? { viewport } : {}) };
if ("Orthographic" in projection) {
const o = projection.Orthographic;
const height = o.scaling_mode?.FixedVertical.viewport_height;
+5 -3
View File
@@ -10,10 +10,12 @@ function refuseOld(owner: string, props: Record<string, unknown>, allowed: reado
}
}
function forward(t: TransformValue | undefined): { position: Vec3; target: Vec3 } {
function forward(t: TransformValue | undefined): { position: Vec3; target: Vec3; rotation: Quat } {
const position: Vec3 = t?.translation ?? [0, 0, 0];
const f = Quat.mulVec3(t?.rotation ?? Quat.IDENTITY, [0, 0, -1]);
return { position, target: [position[0] + f[0], position[1] + f[1], position[2] + f[2]] };
const rotation = t?.rotation ?? Quat.IDENTITY;
const f = Quat.mulVec3(rotation, [0, 0, -1]);
// the rotation too, which the engine places the light by exactly (the target is for what reads where it shines)
return { position, target: [position[0] + f[0], position[1] + f[1], position[2] + f[2]], rotation };
}
/** The props every Bevy light shares beside its own fields. */
+162
View File
@@ -0,0 +1,162 @@
//! A fullscreen draw into the deferred G-buffer and the shadow maps (docs/control.feature FC2d), as Bevy's
//! shader_advanced/deferred_raymarch draws its gyroid: a camera with a GBufferPass (and Bevy's DepthPrepass and
//! DeferredPrepass) runs your shader file's `fragment` over Bevy's fullscreen triangle after the late deferred prepass,
//! writing the G-buffer, the lighting pass id and depth (compared GreaterEqual), so Bevy's deferred lighting lights it
//! as any other surface; its `shadow` entry, when it has one, writes the depth of every shadow view the camera's lights
//! draw (and of each shared one), so it casts shadows too. Bind group 0 is the view uniform (dynamic) and Globals.
use std::collections::HashMap;
use bevy::camera::{MainPassResolutionOverride, Viewport};
use bevy::core_pipeline::core_3d::CORE_3D_DEPTH_FORMAT;
use bevy::core_pipeline::deferred::copy_lighting_id::copy_deferred_lighting_id;
use bevy::core_pipeline::deferred::node::late_deferred_prepass;
use bevy::core_pipeline::deferred::{DEFERRED_LIGHTING_PASS_ID_FORMAT, DEFERRED_PREPASS_FORMAT};
use bevy::core_pipeline::prepass::ViewPrepassTextures;
use bevy::core_pipeline::{Core3d, Core3dSystems, FullscreenShader};
use bevy::pbr::{per_view_shadow_pass, shared_shadow_pass, ShadowView, ViewLightEntities, LATE_SHADOW_PASS};
use bevy::prelude::*;
use bevy::render::camera::ExtractedCamera;
use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};
use bevy::render::globals::{GlobalsBuffer, GlobalsUniform};
use bevy::render::render_resource::binding_types::uniform_buffer;
use bevy::render::render_resource::*;
use bevy::render::renderer::{RenderContext, ViewQuery};
use bevy::render::view::{ViewDepthStencilTexture, ViewUniform, ViewUniformOffset, ViewUniforms};
use bevy::render::{Render, RenderApp, RenderStartup, RenderSystems};
/// A camera's fullscreen G-buffer draw: its shader file (as written), its G-buffer entry point and its shadow one
/// ("" for none).
#[derive(Component, Clone, Debug, Default, Reflect, ExtractComponent)]
#[extract_app(RenderApp)]
#[reflect(Component, Default)]
#[type_path = "raea_sys_phase"]
pub struct GBufferPass {
pub shader: String,
pub fragment: String,
pub shadow: String,
/// its shader file, registered as written (raea-sys-shader), and the id register gave it
#[reflect(ignore)]
pub registered: Option<(String, u128)>,
}
pub fn install(app: &mut App) {
app.register_type::<GBufferPass>();
app.add_systems(PostUpdate, crate::register::<GBufferPass>);
app.add_plugins(ExtractComponentPlugin::<GBufferPass>::default());
let Some(r) = app.get_sub_app_mut(RenderApp) else { return };
r.add_systems(RenderStartup, init).add_systems(Render, queue.in_set(RenderSystems::Queue)).add_systems(
Core3d,
(
gbuffer.in_set(Core3dSystems::Prepass).after(late_deferred_prepass).before(copy_deferred_lighting_id),
directional_shadows.after(per_view_shadow_pass::<LATE_SHADOW_PASS>).before(Core3dSystems::MainPass),
shared_shadows.after(shared_shadow_pass::<LATE_SHADOW_PASS>).before(Core3dSystems::MainPass),
),
);
}
/// The passes' bind group layout, the fullscreen vertex stage, and each pass's pipelines (its G-buffer one and its
/// shadow one) by what decides them.
#[derive(Resource)]
struct Pipelines {
layout: BindGroupLayoutDescriptor,
vertex: VertexState,
made: HashMap<(u128, String, String), (CachedRenderPipelineId, Option<CachedRenderPipelineId>)>,
}
fn init(mut commands: Commands, fullscreen: Res<FullscreenShader>) {
let layout = BindGroupLayoutDescriptor::new("raea_gbuffer_pass", &BindGroupLayoutEntries::sequential(ShaderStages::FRAGMENT, (uniform_buffer::<ViewUniform>(true), uniform_buffer::<GlobalsUniform>(false))));
commands.insert_resource(Pipelines { layout, vertex: fullscreen.to_vertex_state(), made: HashMap::new() });
}
/// The key a pass's pipelines are kept by.
fn key(p: &GBufferPass) -> Option<(u128, String, String)> {
Some((p.registered.as_ref()?.1, p.fragment.clone(), p.shadow.clone()))
}
/// Each pass's pipelines queued once its shader is registered.
fn queue(cache: Res<PipelineCache>, mut pipes: ResMut<Pipelines>, passes: Query<&GBufferPass>) {
for p in &passes {
let Some(k) = key(p) else { continue };
if pipes.made.contains_key(&k) {
continue;
}
let shader = Handle::Uuid(bevy::asset::uuid::Uuid::from_u128(k.0), core::marker::PhantomData);
let depth = DepthStencilState { format: CORE_3D_DEPTH_FORMAT, depth_write_enabled: Some(true), depth_compare: Some(CompareFunction::GreaterEqual), stencil: default(), bias: default() };
let target = |format| Some(ColorTargetState { format, blend: None, write_mask: ColorWrites::ALL });
let pipeline = |entry: &str, targets: Vec<Option<ColorTargetState>>| {
cache.queue_render_pipeline(RenderPipelineDescriptor {
label: Some("raea_gbuffer_pass".into()),
layout: vec![pipes.layout.clone()],
vertex: pipes.vertex.clone(),
fragment: Some(FragmentState { shader: shader.clone(), entry_point: Some(entry.to_owned().into()), targets, ..default() }),
depth_stencil: Some(depth.clone()),
..default()
})
};
let g = pipeline(&k.1, vec![target(DEFERRED_PREPASS_FORMAT), target(DEFERRED_LIGHTING_PASS_ID_FORMAT)]);
let s = (!k.2.is_empty()).then(|| pipeline(&k.2, vec![]));
pipes.made.insert(k, (g, s));
}
}
/// Its bind group: the view uniform and Globals.
fn bind_group(ctx: &RenderContext, cache: &PipelineCache, pipes: &Pipelines, views: &ViewUniforms, globals: &GlobalsBuffer) -> Option<BindGroup> {
let entries = BindGroupEntries::sequential((views.uniforms.binding()?, globals.buffer.binding()?));
Some(ctx.render_device().create_bind_group("raea_gbuffer_pass", &cache.get_bind_group_layout(&pipes.layout), &entries))
}
/// The G-buffer draw in the camera's viewport (as Bevy's own passes draw: a target bigger than the view, as raea's
/// is by its tag row, would otherwise stretch the fullscreen triangle's uv over it), then the view's depth copied to its
/// prepass depth, as the example does.
#[allow(clippy::too_many_arguments)]
fn gbuffer(view: ViewQuery<(&ExtractedCamera, Option<&MainPassResolutionOverride>, &ViewUniformOffset, &ViewDepthStencilTexture, &ViewPrepassTextures, &GBufferPass)>, pipes: Res<Pipelines>, cache: Res<PipelineCache>, views: Res<ViewUniforms>, globals: Res<GlobalsBuffer>, mut ctx: RenderContext) {
let (camera, over, offset, depth, prepass, p) = view.into_inner();
let Some(&(id, _)) = key(p).and_then(|k| pipes.made.get(&k)) else { return };
let (Some(pipeline), Some(deferred), Some(pass_id)) = (cache.get_render_pipeline(id), &prepass.deferred, &prepass.deferred_lighting_pass_id) else { return };
let Some(group) = bind_group(&ctx, &cache, &pipes, &views, &globals) else { return };
{
let mut pass = ctx.begin_tracked_render_pass(RenderPassDescriptor { label: Some("raea_gbuffer_pass"), color_attachments: &[Some(deferred.get_attachment()), Some(pass_id.get_attachment())], depth_stencil_attachment: Some(depth.get_attachment(StoreOp::Store)), timestamp_writes: None, occlusion_query_set: None, multiview_mask: None });
if let Some(v) = Viewport::from_viewport_and_override(camera.viewport.as_ref(), over) {
pass.set_camera_viewport(&v);
}
pass.set_render_pipeline(pipeline);
pass.set_bind_group(0, &group, &[offset.offset]);
pass.draw(0..3, 0..1);
}
if let Some(d) = &prepass.depth {
ctx.command_encoder().copy_texture_to_texture(depth.texture().as_image_copy(), d.texture.texture.as_image_copy(), prepass.size);
}
}
/// The shadow entry drawn into one shadow view's depth.
fn shadow(ctx: &mut RenderContext, cache: &PipelineCache, pipes: &Pipelines, views: &ViewUniforms, globals: &GlobalsBuffer, id: CachedRenderPipelineId, view: &ShadowView, offset: &ViewUniformOffset) {
let (Some(pipeline), Some(group)) = (cache.get_render_pipeline(id), bind_group(ctx, cache, pipes, views, globals)) else { return };
let mut pass = ctx.begin_tracked_render_pass(RenderPassDescriptor { label: Some("raea_gbuffer_pass_shadow"), color_attachments: &[], depth_stencil_attachment: Some(view.depth_attachment.get_attachment(StoreOp::Store)), timestamp_writes: None, occlusion_query_set: None, multiview_mask: None });
pass.set_render_pipeline(pipeline);
pass.set_bind_group(0, &group, &[offset.offset]);
pass.draw(0..3, 0..1);
}
/// The camera's lights' own shadow views (a directional light's cascades).
#[allow(clippy::too_many_arguments)]
fn directional_shadows(view: ViewQuery<(&ViewLightEntities, &GBufferPass)>, shadow_views: Query<(&ShadowView, &ViewUniformOffset)>, pipes: Res<Pipelines>, cache: Res<PipelineCache>, views: Res<ViewUniforms>, globals: Res<GlobalsBuffer>, mut ctx: RenderContext) {
let (lights, p) = view.into_inner();
let Some(&(_, Some(id))) = key(p).and_then(|k| pipes.made.get(&k)) else { return };
for light in lights.lights.iter().copied() {
if let Ok((v, offset)) = shadow_views.get(light) {
shadow(&mut ctx, &cache, &pipes, &views, &globals, id, v, offset);
}
}
}
/// A shared shadow view (a point or spot light's), drawn by every pass with a shadow entry.
#[allow(clippy::too_many_arguments)]
fn shared_shadows(view: ViewQuery<(&ShadowView, &ViewUniformOffset)>, passes: Query<&GBufferPass>, pipes: Res<Pipelines>, cache: Res<PipelineCache>, views: Res<ViewUniforms>, globals: Res<GlobalsBuffer>, mut ctx: RenderContext) {
let (v, offset) = view.into_inner();
for p in &passes {
if let Some(&(_, Some(id))) = key(p).and_then(|k| pipes.made.get(&k)) {
shadow(&mut ctx, &cache, &pipes, &views, &globals, id, v, offset);
}
}
}
+6 -2
View File
@@ -5,7 +5,8 @@
//! prepares and draws it. A MeshPass on a Mesh3d entity draws that mesh again by its own shader in a phase after the
//! main opaque pass, as Bevy's shader_advanced/custom_render_phase draws its stencil (mesh_pass.rs), and
//! ShaderInstances draws it many times in one draw, a vertex buffer of yours stepped per instance
//! (shader_advanced/custom_shader_instancing, instances.rs).
//! (shader_advanced/custom_shader_instancing, instances.rs). A camera's GBufferPass draws a fullscreen shader into the
//! deferred G-buffer and the shadow maps (shader_advanced/deferred_raymarch, gbuffer.rs).
use bevy::camera::visibility::{self, VisibilityClass};
use bevy::prelude::*;
@@ -13,9 +14,11 @@ use bevy::render::extract_component::{ExtractComponent, ExtractComponentPlugin};
use bevy::render::RenderApp;
mod draw;
mod gbuffer;
mod instances;
mod mesh_pass;
pub use gbuffer::GBufferPass;
pub use instances::ShaderInstances;
pub use mesh_pass::MeshPass;
@@ -75,7 +78,7 @@ macro_rules! shaded {
}
)*};
}
shaded!(PhaseItem: "PhaseItem", MeshPass: "MeshPass", ShaderInstances: "ShaderInstances");
shaded!(PhaseItem: "PhaseItem", MeshPass: "MeshPass", ShaderInstances: "ShaderInstances", GBufferPass: "GBufferPass");
/// Each new or changed `C`'s shader file read and registered as written (a file it can't read is logged).
pub(crate) fn register<C: Shaded>(world: &mut World) {
@@ -112,6 +115,7 @@ pub fn install(app: &mut App) {
draw::install(app);
mesh_pass::install(app);
instances::install(app);
gbuffer::install(app);
if let Some(r) = app.get_sub_app_mut(bevy::render::RenderApp) {
r.add_systems(bevy::render::RenderStartup, pipelines.after(bevy::pbr::MeshPipelineSystems));
}