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.

BK3: the trace on the GPU (sky, emission, bounces), and BK2's origins off their triangles' edges

shinyobjectz057566041722
diff --git a/Cargo.lock b/Cargo.lock
index 1d9ad9e1..0f519a09 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16258,11 +16258,14 @@ dependencies = [
name = "raea-sys-lightbake"
version = "0.1.0"
dependencies = [
- "gltf",
+ "bytemuck",
"parry3d",
+ "pollster 0.4.0",
+ "raea-gpu-device",
"raea-sys-atlas",
"rayon",
"serde_json",
+ "wgpu",
]
[[package]]
diff --git a/docs/bake.feature b/docs/bake.feature
index 3778208d..8edabea4 100644
--- a/docs/bake.feature
+++ b/docs/bake.feature
@@ -144,9 +144,9 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
And a texel whose position is inside other geometry (a table leg's foot in the floor, a wall's end inside the
next wall) is found by a short ray test and marked, so it neither goes black nor leaks light into the bake
And positions are offset along the normal by a scale-aware epsilon, so the trace never hits its own surface
- And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::layout; the
- light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), reads the layout's
- model back as world triangles (each node's transform down its children) into a parry3d BVH, moves each point
+ And built 11-23: `raea_sys_lightbake::texels::texels(glb, request)` lays the model out (BK1's layout, raea_sys_atlas::laid; the
+ light-only request is `request(texels, max_side)`, a worn model passes its wear bake's), takes
+ the model's world triangles as the parry3d BVH the atlas was laid out over, moves each point
off its surface by 1e-5 of the model's size or farthest coordinate (at least 10 microns), and casts 16
cosine-weighted rays from each: a texel is inside when at least half its rays meet a back face and more meet
back faces than front ones (a floor that is one plane is met from below one way and not at all the other).
@@ -154,11 +154,19 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
And raea-sys-atlas (a facility) now holds the atlas, out of raea-sys-weathering, so the light bake builds on it
and not sideways on another system: weathering's bakes are the same bytes and keys after the move (the table
and window sets baked before and after, 12 files equal), and its 11 tests pass
- And measured 11-23 at 64 texels a metre, debug build on the M5 Pro (BK1's layout included in both times)
+ And BK2 landed with a leak, found by BK3's glowing box and fixed 11-23: a chart's edge band takes its points from
+ the edge itself, so an origin on a floor's edge was in the plane of the wall standing on it and half its rays
+ left a closed room (408 of the box's 1944 texels read 1.16 for 2.0: a dark line along every joint). Its tests
+ had left a strip along the contact lines out of their checks. Each origin is now four offsets in from its
+ triangle's edges, moved half a texel at most (a needle narrower than that would send it to its far end), and
+ the box's edge texels read 2.015. The triangles come from raea_sys_atlas::laid, numbered as the texels number
+ them; the layout's model is no longer read back
+ And measured 11-23 at 64 texels a metre, debug build on the M5 Pro (BK1's layout included in both times), after
+ the fix; the atelier's row is from before it
| set | atlas | texels | inside | offset | layout | with texels |
- | table | 2048x1008 | 1 549 350 | 10 366 (0.67%) | 0.17 mm | 0.29 s | 3.4 s |
- | cornell | 1024x296 | 232 060 | 17 345 (7.5%) | 0.04 mm | 0.05 s | 1.3 s |
- | window | 2048x644 | 979 867 | 96 445 (9.8%) | 0.08 mm | 0.21 s | 5.1 s |
+ | table | 2048x1008 | 1 549 350 | 8 772 (0.57%) | 0.17 mm | 0.27 s | 3.1 s |
+ | cornell | 1024x296 | 232 060 | 19 372 (8.4%) | 0.04 mm | 0.05 s | 0.7 s |
+ | window | 2048x644 | 979 867 | 99 153 (10.1%) | 0.08 mm | 0.16 s | 2.7 s |
| atelier | 4096x1820 | 4 136 248 | 200 649 (4.9%) | 0.15 mm | 41 s | 70 s |
And what they say: what's marked is what overlaps. In the window room it is the band where each wall box runs
into the next wall, the floor and the ceiling, the floor under the sofa's and table's feet, and the walls
@@ -170,10 +178,14 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
Scenario: BK3. The light that bounces, traced on raea's ray tracer
Given the plan
| crate | file | lines | job |
+ | raea-sys-lightbake | systems/lightbake/src/trace/tests.rs | 160 | a white furnace, a wall's form factor, a glowing box, a red wall's bleed, the same bytes twice; the measured run |
+ | raea-sys-lightbake | systems/lightbake/src/wgsl/diffuse.wgsl | 60 | the diffuse BSDF and the paths' random numbers, a module systems/rt and LT5's path tracer can include as it is |
| raea-sys-lightbake | systems/lightbake/src/trace.rs | 260 | the passes: dispatch per atlas, samples accumulated over passes, progress, cancel |
- | raea-sys-lightbake | systems/lightbake/src/trace.wgsl | 320 | per texel: cosine-weighted paths against systems/rt's TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
+ | raea-sys-lightbake | systems/lightbake/src/wgsl/trace.wgsl | 320 | per texel: cosine-weighted paths against the bake's own TLAS; the sky from the composition's <Environment>, emissives, baked lights; Russian roulette; Cycles' BSDFs from cycles-port at each bounce |
Then each texel integrates the incoming diffuse light over its hemisphere along paths of up to `bounces`
- (default 4) through systems/rt's BLAS and TLAS, the materials at each hit being the composition's
+ (default 4) through a BLAS and TLAS the bake builds itself from the meshes raea draws, by the wgpu ray queries
+ systems/rt uses. (Not rt's own: a bake runs offline, before any frame, with no Bevy render world to hold them,
+ and over rt its tests would be a cold engine build. What is shared is the WGSL, not the structures), the materials at each hit being the composition's
StandardMaterials (base colour, its texture, roughness, metallic, emissive) as the raster reads them
And the colour that bounces is the albedo raea draws at the hit, extensions included: ProceduralExtension's
patterns (systems/procmat, its dust, dirt and edges), WearExtension (systems/wear) and raea/wear's recipes over
@@ -187,6 +199,16 @@ Feature: Light baked by raea: bounce light into lightmaps on raea's own ray trac
machine stay responsive, with progress printed and a stall guard's line each pass
And a white furnace (a white set under a white sky) converges to the sky's value at every texel, within 1%
And the same request on the same machine gives the same bytes (fixed seeds per texel and pass)
+ And a device without ray queries is refused with its name and backend, and any GPU error is the bake's error:
+ never a black map kept as light (the first kernel failed to compile on Metal and came back as zeros)
+ And in progress, 11-23: the trace of a constant sky, emissive triangles and an albedo a triangle, Lambert (written
+ here: cycles-port isn't on main). A white furnace reads the sky at all 2834 open texels; a 40 m black wall's
+ shadow is its form factor within 0.002 at 0.5, 1, 2 and 4 m; a closed box glowing 1 with an albedo of a half
+ reads 2.004 for 2; breaking the cosine, the offset, the roulette, its weight, the emission or their order each
+ fails one of them. Only Metal has run it. At 512 samples and 4 bounces, every surface 0.7 grey under a white
+ sky, the trace alone takes 0.8 s on the table set, 0.3 s on the Cornell box and 0.9 s on the window room
+ (M5 Pro; linear in samples, 5.6 s at 4096). Not built: the <Environment> panorama, baked lights, the sun left
+ out at the first hit, textures, and the albedo raea draws under procmat, wear and sdk/wear
@needs:BK3
Scenario: BK4. A clean map: denoised, dilated, no seams
diff --git a/systems/atlas/src/lib.rs b/systems/atlas/src/lib.rs
index 5727fcb6..36ef2c24 100644
--- a/systems/atlas/src/lib.rs
+++ b/systems/atlas/src/lib.rs
@@ -115,7 +115,12 @@ pub struct Layout {
}
pub fn layout(bytes: &[u8], req: &Value) -> R<Layout> {
- let (sc, _, at, _) = lay(bytes, req)?;
+ Ok(laid(bytes, req)?.0)
+}
+
+/// The layout with the model's triangles in world space, numbered as its texels number them (`Texel::tri`).
+pub fn laid(bytes: &[u8], req: &Value) -> R<(Layout, parry3d::shape::TriMesh)> {
+ let (sc, mesh, at, _) = lay(bytes, req)?;
let texels = at.texels.iter().map(|t| Texel { x: t.x, y: t.y, p: t.p.to_array(), n: t.n.to_array(), tri: t.tri }).collect();
- Ok(Layout { glb: scene::write(&sc, &at)?, w: at.w, h: at.h, density: at.density, charts: at.charts, hidden: at.hidden, texels })
+ Ok((Layout { glb: scene::write(&sc, &at)?, w: at.w, h: at.h, density: at.density, charts: at.charts, hidden: at.hidden, texels }, mesh))
}
diff --git a/systems/lightbake/Cargo.toml b/systems/lightbake/Cargo.toml
index 8255b944..07d9d9a5 100644
--- a/systems/lightbake/Cargo.toml
+++ b/systems/lightbake/Cargo.toml
@@ -13,5 +13,8 @@ raea-sys-atlas = { path = "../atlas" }
parry3d = "0.31"
rayon = "1"
serde_json = "1"
-# the layout's model read back for its world triangles (no images decoded)
-gltf = { version = "1.4", default-features = false, features = ["utils"] }
+# the process's one shared GPU device, and wgpu's ray queries on it (BK3)
+raea-gpu-device = { path = "../../gpu/device" }
+wgpu = "=30.0.1"
+bytemuck = "1"
+pollster = "0.4"
diff --git a/systems/lightbake/src/lib.rs b/systems/lightbake/src/lib.rs
index 77586e31..558493b1 100644
--- a/systems/lightbake/src/lib.rs
+++ b/systems/lightbake/src/lib.rs
@@ -1,8 +1,10 @@
//! Light baked by raea (docs/bake.feature): bounce light baked into lightmaps on raea's own ray tracer, with no
//! Blender. A bake is a pure function of what it's asked: the static parts, the sky, the lights it carries and the
//! settings. Its maps lie over the atlas raea/wear's cause maps already use (BK1: raea_sys_atlas::layout), so a
-//! model has one second UV set. Built: each texel's place in the world (BK2). Next: the trace (BK3), a clean map
-//! (BK4), and the bake in a composition (BK5).
+//! model has one second UV set. Built: each texel's place in the world (BK2), the light that bounces (BK3, in
+//! progress). Next: a clean map (BK4), and the bake in a composition (BK5).
// each texel's ray origin and the texels inside other geometry (BK2)
pub mod texels;
+// the light that bounces, traced on the GPU (BK3)
+pub mod trace;
diff --git a/systems/lightbake/src/texels.rs b/systems/lightbake/src/texels.rs
index 02e5603d..6fe14147 100644
--- a/systems/lightbake/src/texels.rs
+++ b/systems/lightbake/src/texels.rs
@@ -1,7 +1,8 @@
//! Each texel's place in the world (docs/bake.feature BK2). BK1's layout gives every texel the world point under its
//! centre (or, in a chart's edge band, the nearest point of the chart), its triangle's normal and the triangle, so the
//! texels aren't rasterized a second time. Here each point gets its ray origin, moved off its surface by an offset
-//! from the model's size so the trace never hits the surface it starts on, and the texels inside other geometry (a
+//! from the model's size and off its triangle's edges, so the trace never hits the surface it starts on nor starts in
+//! the plane of the next one, and the texels inside other geometry (a
//! table leg's foot in the floor, a wall's end inside the next wall) are found by rays and marked: they neither go
//! black nor leak light into the bake, and BK4 fills them from their chart's neighbours.
@@ -20,7 +21,7 @@ const RAYS: u32 = 16;
pub struct Texels {
/// BK1's layout: the model with its TEXCOORD_1, the atlas's size and density, the texels' surface points
pub layout: Layout,
- /// each texel's ray origin: its surface point moved `offset` along its normal
+ /// each texel's ray origin: its surface point, four offsets in from its triangle's edges, moved `offset` along its normal
pub origin: Vec<[f32; 3]>,
/// the texels inside other geometry (their rays meet back faces), left for BK4 to fill
pub inside: Vec<bool>,
@@ -38,14 +39,17 @@ pub fn request(texels: f32, max_side: u32) -> Value {
/// Every texel of the model's atlas in the world: its origin and whether it's inside other geometry.
pub fn texels(glb: &[u8], req: &Value) -> Result<Texels, String> {
- let layout = raea_sys_atlas::layout(glb, req)?;
- let mesh = world_mesh(&layout.glb)?;
+ let (layout, mesh) = raea_sys_atlas::laid(glb, req)?;
let (mut lo, mut hi, mut far) = (Vec3::splat(f32::MAX), Vec3::splat(f32::MIN), 0.0f32);
for &v in mesh.vertices() {
(lo, hi, far) = (lo.min(v), hi.max(v), far.max(v.abs().max_element()));
}
let offset = (1e-5 * (hi - lo).length().max(far)).max(1e-5);
- let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| (Vec3::from(t.p) + Vec3::from(t.n) * offset).to_array()).collect();
+ let half = 0.5 / layout.density;
+ let origin: Vec<[f32; 3]> = layout.texels.iter().map(|t| {
+ let tri = mesh.indices()[t.tri as usize].map(|v| mesh.vertices()[v as usize]);
+ (off_edges(tri, Vec3::from(t.p), 4.0 * offset, half) + Vec3::from(t.n) * offset).to_array()
+ }).collect();
let inside = layout.texels.par_iter().zip(&origin).enumerate().map(|(i, (t, &o))| inside(&mesh, Vec3::from(o), Vec3::from(t.n), i as u32)).collect();
Ok(Texels { layout, origin, inside, offset, mesh })
}
@@ -65,35 +69,20 @@ fn inside(mesh: &TriMesh, o: Vec3, n: Vec3, seed: u32) -> bool {
back * 2 >= RAYS && back > front
}
-/// The layout's model as world triangles: every triangle primitive of the default scene's nodes, each node's
-/// transform applied down its children.
-fn world_mesh(glb: &[u8]) -> Result<TriMesh, String> {
- let g = gltf::Gltf::from_slice(glb).map_err(|e| format!("the layout's model: {e}"))?;
- let blob = g.blob.as_deref();
- let scene = g.default_scene().or_else(|| g.scenes().next()).ok_or("the layout's model has no scene")?;
- const ID: [[f32; 4]; 4] = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]];
- let mut stack: Vec<(gltf::Node, [[f32; 4]; 4])> = scene.nodes().map(|n| (n, ID)).collect();
- let (mut pos, mut tri) = (Vec::new(), Vec::new());
- while let Some((node, parent)) = stack.pop() {
- let l = node.transform().matrix();
- let m: [[f32; 4]; 4] = std::array::from_fn(|c| std::array::from_fn(|r| (0..4).map(|k| parent[k][r] * l[c][k]).sum()));
- for prim in node.mesh().iter().flat_map(|m| m.primitives()) {
- if !matches!(prim.mode(), gltf::mesh::Mode::Triangles) {
- continue;
- }
- let r = prim.reader(|b| if b.index() == 0 { blob } else { None });
- let base = pos.len() as u32;
- pos.extend(r.read_positions().ok_or("a primitive with no positions")?.map(|p| Vec3::from(std::array::from_fn(|i| m[0][i] * p[0] + m[1][i] * p[1] + m[2][i] * p[2] + m[3][i]))));
- let ix: Vec<u32> = match r.read_indices() {
- Some(i) => i.into_u32().collect(),
- None => (0..pos.len() as u32 - base).collect(),
- };
- tri.extend(ix.chunks_exact(3).map(|t| [base + t[0], base + t[1], base + t[2]]));
- }
- stack.extend(node.children().map(|c| (c, m)));
- }
- TriMesh::new(pos, tri).map_err(|e| format!("the layout's triangles: {e:?}"))
+/// p moved along its triangle until it's `gap` from each edge, or by `most` (half a texel: its own footprint; a needle
+/// narrower than the gap would send it to its far end). A chart's
+/// edge band takes its texels from the edge itself, and a point on the edge of a floor is in the plane of the wall
+/// standing on it: its rays started in that wall and half of them left the room.
+fn off_edges([a, b, c]: [Vec3; 3], p: Vec3, gap: f32, most: f32) -> Vec3 {
+ let n = (b - a).cross(c - a);
+ let area = n.length_squared().max(f32::MIN_POSITIVE);
+ // barycentric weights, each raised to what stands `gap` from the edge opposite its corner (its height: area / edge)
+ let w = [(c - b, b), (a - c, c), (b - a, a)].map(|(edge, from)| {
+ let least = (gap * edge.length() / area.sqrt()).min(1.0 / 3.0);
+ (edge.cross(p - from).dot(n) / area).max(least)
+ });
+ p + ((a * w[0] + b * w[1] + c * w[2]) / (w[0] + w[1] + w[2]) - p).clamp_length_max(most)
}
#[cfg(test)]
-mod tests;
+pub(crate) mod tests;
diff --git a/systems/lightbake/src/texels/tests.rs b/systems/lightbake/src/texels/tests.rs
index d0c93ac0..1b10471a 100644
--- a/systems/lightbake/src/texels/tests.rs
+++ b/systems/lightbake/src/texels/tests.rs
@@ -2,10 +2,10 @@ use parry3d::query::PointQuery;
use super::*;
-type Tri = [[f32; 3]; 3];
+pub(crate) type Tri = [[f32; 3]; 3];
/// A .glb with a node per part (its translation, its own material), flat normals, every triangle its own vertices.
-fn glb(parts: &[(Vec<Tri>, [f32; 3])]) -> Vec<u8> {
+pub(crate) fn glb(parts: &[(Vec<Tri>, [f32; 3])]) -> Vec<u8> {
let (mut bin, mut acc, mut views, mut meshes, mut nodes, mut mats) = (Vec::<u8>::new(), vec![], vec![], vec![], vec![], vec![]);
for (k, (tris, at)) in parts.iter().enumerate() {
let (mut p, mut n) = (vec![], vec![]);
@@ -46,7 +46,7 @@ fn glb(parts: &[(Vec<Tri>, [f32; 3])]) -> Vec<u8> {
}
/// A box's twelve triangles, wound outwards.
-fn cuboid(lo: [f32; 3], hi: [f32; 3]) -> Vec<Tri> {
+pub(crate) fn cuboid(lo: [f32; 3], hi: [f32; 3]) -> Vec<Tri> {
let mut out = vec![];
for axis in 0..3 {
let (u, v) = ((axis + 1) % 3, (axis + 2) % 3);
@@ -64,7 +64,7 @@ fn cuboid(lo: [f32; 3], hi: [f32; 3]) -> Vec<Tri> {
}
/// A floor slab 20 cm thick, a block sunk 10 cm into it, and a small box set on it by its node's translation.
-fn set() -> Vec<u8> {
+pub(crate) fn set() -> Vec<u8> {
glb(&[
(cuboid([-2.0, -0.2, -2.0], [2.0, 0.0, 2.0]), [0.0; 3]),
(cuboid([-0.25, -0.1, -0.25], [0.25, 0.4, 0.25]), [0.0; 3]),
@@ -79,10 +79,23 @@ fn texels_sit_on_the_world_surface_and_their_origins_just_off_it() {
for (x, o) in t.layout.texels.iter().zip(&t.origin) {
let on = t.mesh.project_local_point(Vec3::from(x.p), false).point;
assert!(on.distance(Vec3::from(x.p)) < 1e-3, "texel at {:?} is off the surface (nearest {on:?})", x.p);
- assert!((Vec3::from(*o) - Vec3::from(x.p) - Vec3::from(x.n) * t.offset).length() < 1e-6);
+ let moved = Vec3::from(*o) - Vec3::from(x.p);
+ assert!((moved.dot(Vec3::from(x.n)) - t.offset).abs() < 0.2 * t.offset && moved.length() < 0.51 / t.layout.density, "the origin of {:?} moved {moved:?} for an offset of {}", x.p, t.offset);
}
}
+#[test]
+fn a_point_on_an_edge_is_moved_off_it_and_never_far() {
+ let [a, b, c] = [Vec3::ZERO, Vec3::X, Vec3::Z];
+ for p in [a, b, Vec3::X * 0.5, (b + c) * 0.5] {
+ let q = off_edges([a, b, c], p, 1e-3, 0.1);
+ assert!(q.x > 0.9e-3 && q.z > 0.9e-3 && 1.0 - q.x - q.z > 0.9e-3 && q.distance(p) < 5e-3, "{p} went to {q}");
+ }
+ assert!(off_edges([a, b, c], Vec3::new(0.3, 0.0, 0.3), 1e-3, 0.1).distance(Vec3::new(0.3, 0.0, 0.3)) < 1e-6, "a point in the open stays");
+ let needle = [Vec3::ZERO, Vec3::X * 4.0, Vec3::new(4.0, 0.0, 2e-4)];
+ assert!(off_edges(needle, Vec3::X * 0.5, 1e-3, 0.01).distance(Vec3::X * 0.5) < 0.0101);
+}
+
#[test]
fn texels_inside_the_slab_are_marked_and_those_in_the_open_are_not() {
let t = texels(&set(), &request(16.0, 1024)).unwrap();
diff --git a/systems/lightbake/src/trace.rs b/systems/lightbake/src/trace.rs
new file mode 100644
index 00000000..1c8a8e79
--- /dev/null
+++ b/systems/lightbake/src/trace.rs
@@ -0,0 +1,167 @@
+//! The light that bounces, traced on the GPU (docs/bake.feature BK3): each texel's paths through the model's own
+//! triangles by wgpu's ray queries (Metal, Vulkan, DX12), on raea-gpu-device, the process's one shared device. A bake
+//! runs offline, before any frame, so it builds its own BLAS and TLAS from the meshes it bakes rather than reading
+//! systems/rt's from a Bevy render world; the kernel's WGSL (wgsl/diffuse.wgsl) is a module rt can include as it is.
+//! A device without ray queries is refused with the reason, and the composition renders unbaked.
+
+use wgpu::util::DeviceExt;
+
+/// What a triangle sends on: the share of light it reflects (diffuse) and the light it gives off, linear RGB.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Surface {
+ pub albedo: [f32; 3],
+ pub emission: [f32; 3],
+}
+
+/// The world a bake traces: triangles in world space, each with its surface.
+pub struct World<'a> {
+ pub positions: &'a [[f32; 3]],
+ pub triangles: &'a [[u32; 3]],
+ pub surfaces: &'a [Surface],
+}
+
+/// What's traced from: each texel's origin (BK2, already off its surface), its normal, and whether it's inside other
+/// geometry (left at zero for BK4 to fill), and the offset each bounce leaves its surface by.
+pub struct Starts<'a> {
+ pub origin: &'a [[f32; 3]],
+ pub normal: &'a [[f32; 3]],
+ pub inside: &'a [bool],
+ pub offset: f32,
+}
+
+#[derive(Clone, Copy, Debug)]
+pub struct Settings {
+ /// samples a texel
+ pub samples: u32,
+ /// a path's most bounces
+ pub bounces: u32,
+ /// samples a texel in each pass: a pass short enough that the machine stays responsive
+ pub per_pass: u32,
+ /// the sky's light, linear RGB (the composition's <Environment> comes in BK3's next step)
+ pub sky: [f32; 3],
+}
+
+impl Default for Settings {
+ fn default() -> Self {
+ Self { samples: 512, bounces: 4, per_pass: 16, sky: [1.0; 3] }
+ }
+}
+
+/// Texels a dispatch: under wgpu's 65,535 workgroups of 64, and short enough that the GPU stays the machine's.
+const CHUNK: u32 = 1 << 18;
+
+/// The light reaching each texel (the mean its cosine-weighted rays bring back), in `from`'s order; inside texels 0.
+pub fn trace(world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result<Vec<[f32; 3]>, String> {
+ let n = from.origin.len();
+ if from.normal.len() != n || from.inside.len() != n || world.surfaces.len() != world.triangles.len() {
+ return Err("trace: the texels' origins, normals and inside marks, and the triangles' surfaces, must match".into());
+ }
+ if n == 0 || world.triangles.is_empty() {
+ return Ok(vec![[0.0; 3]; n]);
+ }
+ let (_, adapter, device, queue) = raea_gpu_device::device()?;
+ if !device.features().contains(wgpu::Features::EXPERIMENTAL_RAY_QUERY) {
+ let info = adapter.get_info();
+ return Err(format!("the light bake needs ray queries, which this GPU doesn't offer ({} on {:?}): the composition renders unbaked", info.name, info.backend));
+ }
+ // every GPU error is the bake's: caught here and returned, never a black map kept as if it were light
+ let scopes = [wgpu::ErrorFilter::Validation, wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal].map(|f| device.push_error_scope(f));
+ let light = dispatch(&device, &queue, world, from, s, progress);
+ let errors: Vec<String> = scopes.into_iter().rev().filter_map(|g| pollster::block_on(g.pop())).map(|e| e.to_string()).collect();
+ if !errors.is_empty() {
+ return Err(format!("the light bake's trace failed on the GPU: {}", errors.join("; ")));
+ }
+ light
+}
+
+/// The passes over a device known to have ray queries, and the texels' light read back.
+fn dispatch(device: &wgpu::Device, queue: &wgpu::Queue, world: &World, from: &Starts, s: &Settings, progress: &mut dyn FnMut(u32, u32)) -> Result<Vec<[f32; 3]>, String> {
+ let n = from.origin.len();
+ let tlas = accel(device, queue, world);
+ let vec4 = |v: [f32; 3], w: f32| [v[0], v[1], v[2], w];
+ let positions: Vec<[f32; 4]> = world.positions.iter().map(|p| vec4(*p, 1.0)).collect();
+ let surfaces: Vec<[f32; 4]> = world.surfaces.iter().flat_map(|s| [vec4(s.albedo, 0.0), vec4(s.emission, 0.0)]).collect();
+ let texels: Vec<[f32; 4]> = (0..n).flat_map(|i| [vec4(from.origin[i], from.inside[i] as u32 as f32), vec4(from.normal[i], 0.0)]).collect();
+ let storage = |label: &str, bytes: &[u8], usage: wgpu::BufferUsages| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::STORAGE | usage });
+ let index: Vec<u32> = world.triangles.iter().flatten().copied().collect();
+ let bufs = [
+ storage("lightbake positions", bytemuck::cast_slice(&positions), wgpu::BufferUsages::empty()),
+ storage("lightbake indices", bytemuck::cast_slice(&index), wgpu::BufferUsages::empty()),
+ storage("lightbake surfaces", bytemuck::cast_slice(&surfaces), wgpu::BufferUsages::empty()),
+ storage("lightbake texels", bytemuck::cast_slice(&texels), wgpu::BufferUsages::empty()),
+ storage("lightbake accum", &vec![0u8; n * 16], wgpu::BufferUsages::COPY_SRC),
+ ];
+ let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake params"), size: 48, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
+ let src = format!("enable wgpu_ray_query;\n{}\n{}", include_str!("wgsl/diffuse.wgsl"), include_str!("wgsl/trace.wgsl"));
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("lightbake trace"), source: wgpu::ShaderSource::Wgsl(src.into()) });
+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("lightbake trace"), layout: None, module: &module, entry_point: Some("main"), compilation_options: Default::default(), cache: None });
+ let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::AccelerationStructure(&tlas) }];
+ entries.extend(bufs.iter().enumerate().map(|(k, b)| wgpu::BindGroupEntry { binding: k as u32 + 1, resource: b.as_entire_binding() }));
+ entries.push(wgpu::BindGroupEntry { binding: 6, resource: params.as_entire_binding() });
+ let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("lightbake trace"), layout: &pipeline.get_bind_group_layout(0), entries: &entries });
+ let passes = s.samples.div_ceil(s.per_pass.max(1));
+ for pass in 0..passes {
+ let per = s.per_pass.max(1).min(s.samples - pass * s.per_pass.max(1));
+ for first in (0..n as u32).step_by(CHUNK as usize) {
+ let mut p = [0u32; 12];
+ for (k, v) in s.sky.iter().enumerate() {
+ p[k] = v.to_bits();
+ }
+ let end = (first + CHUNK).min(n as u32);
+ (p[4], p[5], p[6], p[7], p[8], p[9]) = (end, pass, per, s.bounces, from.offset.to_bits(), first);
+ queue.write_buffer(&params, 0, bytemuck::cast_slice(&p));
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake pass") });
+ {
+ let mut cp = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("lightbake pass"), timestamp_writes: None });
+ cp.set_pipeline(&pipeline);
+ cp.set_bind_group(0, &bind, &[]);
+ cp.dispatch_workgroups((end - first).div_ceil(64), 1, 1);
+ }
+ queue.submit([enc.finish()]);
+ device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(120)) }).map_err(|e| format!("the light bake's pass {pass}: {e}"))?;
+ }
+ progress(pass + 1, passes);
+ }
+ let acc = read(device, queue, &bufs[4], n * 16)?;
+ let acc: &[[f32; 4]] = bytemuck::cast_slice(&acc);
+ Ok(acc.iter().map(|a| if a[3] > 0.0 { [a[0] / a[3], a[1] / a[3], a[2] / a[3]] } else { [0.0; 3] }).collect())
+}
+
+/// The world's one BLAS (its triangles, opaque) under a TLAS of one instance where it stands.
+fn accel(device: &wgpu::Device, queue: &wgpu::Queue, world: &World) -> wgpu::Tlas {
+ let input = |label: &str, bytes: &[u8]| device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents: bytes, usage: wgpu::BufferUsages::BLAS_INPUT });
+ let index: Vec<u32> = world.triangles.iter().flatten().copied().collect();
+ let (vb, ib) = (input("lightbake blas vertices", bytemuck::cast_slice(world.positions)), input("lightbake blas indices", bytemuck::cast_slice(&index)));
+ let size = wgpu::BlasTriangleGeometrySizeDescriptor { vertex_format: wgpu::VertexFormat::Float32x3, vertex_count: world.positions.len() as u32, index_format: Some(wgpu::IndexFormat::Uint32), index_count: Some(index.len() as u32), flags: wgpu::AccelerationStructureGeometryFlags::OPAQUE };
+ let flags = (wgpu::AccelerationStructureFlags::PREFER_FAST_TRACE, wgpu::AccelerationStructureUpdateMode::Build);
+ let blas = device.create_blas(&wgpu::CreateBlasDescriptor { label: Some("lightbake blas"), flags: flags.0, update_mode: flags.1 }, wgpu::BlasGeometrySizeDescriptors::Triangles { descriptors: vec![size.clone()] });
+ let mut tlas = device.create_tlas(&wgpu::CreateTlasDescriptor { label: Some("lightbake tlas"), flags: flags.0, update_mode: flags.1, max_instances: 1 });
+ *tlas.get_mut_single(0).expect("a TLAS of one") = Some(wgpu::TlasInstance::new(&blas, [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0], 0, 0xff));
+ let entry = wgpu::BlasBuildEntry {
+ blas: &blas,
+ geometry: wgpu::BlasGeometries::TriangleGeometries(vec![wgpu::BlasTriangleGeometry { size: &size, vertex_buffer: &vb, first_vertex: 0, vertex_stride: 12, index_buffer: Some(&ib), first_index: Some(0), transform_buffer: None, transform_buffer_offset: None }]),
+ };
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake accel") });
+ enc.build_acceleration_structures([&entry], [&tlas]);
+ queue.submit([enc.finish()]);
+ tlas
+}
+
+/// A storage buffer's bytes back on the CPU.
+fn read(device: &wgpu::Device, queue: &wgpu::Queue, buf: &wgpu::Buffer, size: usize) -> Result<Vec<u8>, String> {
+ let back = device.create_buffer(&wgpu::BufferDescriptor { label: Some("lightbake readback"), size: size as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
+ let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("lightbake readback") });
+ enc.copy_buffer_to_buffer(buf, 0, &back, 0, size as u64);
+ queue.submit([enc.finish()]);
+ let (tx, rx) = std::sync::mpsc::channel();
+ back.slice(..).map_async(wgpu::MapMode::Read, move |r| {
+ let _ = tx.send(r);
+ });
+ device.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(60)) }).map_err(|e| format!("the light bake's readback: {e}"))?;
+ rx.recv().map_err(|e| e.to_string())?.map_err(|e| format!("the light bake's readback: {e}"))?;
+ let bytes = back.slice(..).get_mapped_range().map_err(|e| format!("the light bake's readback: {e}"))?.to_vec();
+ Ok(bytes)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/systems/lightbake/src/trace/tests.rs b/systems/lightbake/src/trace/tests.rs
new file mode 100644
index 00000000..f9497458
--- /dev/null
+++ b/systems/lightbake/src/trace/tests.rs
@@ -0,0 +1,107 @@
+use super::*;
+use crate::texels::tests::{cuboid, glb, set};
+use crate::texels::{request, texels};
+
+fn world(mesh: &parry3d::shape::TriMesh, surfaces: &[Surface]) -> (Vec<[f32; 3]>, Vec<[u32; 3]>, Vec<Surface>) {
+ (mesh.vertices().iter().map(|v| v.to_array()).collect(), mesh.indices().to_vec(), surfaces.to_vec())
+}
+
+/// The light on t's texels, each triangle's surface given by its centroid.
+fn run(t: &crate::texels::Texels, surface: impl Fn([f32; 3]) -> Surface, s: &Settings) -> Vec<[f32; 3]> {
+ let v = t.mesh.vertices();
+ let surfaces: Vec<Surface> = t.mesh.indices().iter().map(|i| surface(std::array::from_fn(|k| i.iter().map(|&j| v[j as usize][k]).sum::<f32>() / 3.0))).collect();
+ let (p, i, s2) = world(&t.mesh, &surfaces);
+ let normal: Vec<[f32; 3]> = t.layout.texels.iter().map(|x| x.n).collect();
+ let starts = Starts { origin: &t.origin, normal: &normal, inside: &t.inside, offset: t.offset };
+ trace(&World { positions: &p, triangles: &i, surfaces: &s2 }, &starts, s, &mut |_, _| {}).unwrap()
+}
+
+/// A white set under a white sky: whatever bounces, every texel's light is the sky's (a white furnace). The block sunk
+/// in the slab and the box set by its node make real concave corners; paths there bounce until they find the sky.
+#[test]
+fn a_white_furnace_is_the_sky_at_every_texel() {
+ let t = texels(&set(), &request(8.0, 1024)).unwrap();
+ let s = Settings { samples: 64, bounces: 64, per_pass: 16, sky: [1.0; 3] };
+ let light = run(&t, |_| Surface { albedo: [1.0; 3], emission: [0.0; 3] }, &s);
+ let open: Vec<[f32; 3]> = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| *l).collect();
+ let off = open.iter().filter(|l| l.iter().any(|c| (c - 1.0).abs() > 0.01)).count();
+ println!("furnace: {off} of {} off by more than 1%", open.len());
+ let worst = open.iter().flatten().fold(0.0f32, |m, c| m.max((c - 1.0).abs()));
+ println!("furnace: worst {worst}, mean {}", open.iter().map(|l| l[0]).sum::<f32>() / open.len() as f32);
+ assert!(open.len() > 500 && off == 0, "{off} of {} texels more than 1% off the sky, worst {worst}", open.len());
+}
+
+/// A black wall 40 m long and 2 m high on a black floor under a white sky: the floor's light at a distance d from its
+/// foot is what the sky leaves, 1/2 (1 + d / sqrt(d^2 + h^2)) (an endless wall's form factor), which only cosine-weighted
+/// rays give.
+#[test]
+fn a_walls_shadow_on_the_floor_is_its_form_factor() {
+ let set = glb(&[(cuboid([0.0, -0.1, -20.0], [6.0, 0.0, 20.0]), [0.0; 3]), (cuboid([-0.2, -0.1, -20.0], [0.0, 2.0, 20.0]), [0.0; 3])]);
+ let t = texels(&set, &request(4.0, 1024)).unwrap();
+ let light = run(&t, |_| Surface { albedo: [0.0; 3], emission: [0.0; 3] }, &Settings { samples: 512, ..Settings::default() });
+ for d in [0.5f32, 1.0, 2.0, 4.0] {
+ let v: Vec<(f32, f32)> = t.layout.texels.iter().zip(&light).filter(|(x, _)| x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && x.p[2].abs() < 4.0 && (x.p[0] - d).abs() < 0.13).map(|(x, l)| (0.5 * (1.0 + x.p[0] / (x.p[0] * x.p[0] + 4.0).sqrt()), l[0])).collect();
+ let (want, got) = v.iter().fold((0.0, 0.0), |(a, b), (w, g)| (a + w / v.len() as f32, b + g / v.len() as f32));
+ println!("wall: d {d} m: {got:.4} for {want:.4} over {} texels", v.len());
+ assert!(v.len() > 20 && (got - want).abs() < 0.01, "{d} m from the wall the floor gets {got}, not {want}");
+ }
+}
+
+/// A closed box glowing 1 all round with an albedo of a half: every point inside gets 1 + 1/2 + 1/4 ... = 2.
+#[test]
+fn a_glowing_box_adds_up_its_bounces() {
+ let inward = cuboid([-1.0; 3], [1.0; 3]).into_iter().map(|[a, b, c]| [a, c, b]).collect();
+ let t = texels(&glb(&[(inward, [0.0; 3])]), &request(8.0, 1024)).unwrap();
+ let light = run(&t, |_| Surface { albedo: [0.5; 3], emission: [1.0; 3] }, &Settings { samples: 64, bounces: 64, per_pass: 16, sky: [0.0; 3] });
+ let mean = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).sum::<f32>() / t.inside.iter().filter(|i| !**i).count() as f32;
+ println!("box: {mean:.4} for 2, {} of {} texels marked inside", t.inside.iter().filter(|i| **i).count(), t.inside.len());
+ assert!((mean - 2.0).abs() < 0.01, "the glowing box's light is {mean}, not 2");
+}
+
+/// A white floor beside a red wall: the floor near the wall gets redder than the floor far from it.
+#[test]
+fn a_red_wall_bleeds_onto_the_floor() {
+ let floor = cuboid([-1.0, -0.1, -2.0], [1.0, 0.0, 2.0]);
+ let wall = cuboid([-1.0, 0.0, -2.0], [-0.9, 2.0, 2.0]);
+ let t = texels(&glb(&[(floor, [0.0; 3]), (wall, [0.0; 3])]), &request(16.0, 1024)).unwrap();
+ let red = |c: [f32; 3]| Surface { albedo: if c[1] > 0.5 { [0.9, 0.0, 0.0] } else { [0.9; 3] }, emission: [0.0; 3] };
+ let light = run(&t, red, &Settings { samples: 128, bounces: 4, per_pass: 32, sky: [1.0; 3] });
+ // floor top texels near the wall (x -0.9..-0.7) and far (x > 0.6)
+ let mean = |near: bool| {
+ let v: Vec<f32> = t.layout.texels.iter().zip(&light).zip(&t.inside).filter(|((x, _), i)| !**i && x.p[1].abs() < 1e-3 && x.n[1] > 0.9 && if near { x.p[0] < -0.7 } else { x.p[0] > 0.6 }).map(|((_, l), _)| l[1] / l[0]).collect();
+ v.iter().sum::<f32>() / v.len() as f32
+ };
+ let (near, far) = (mean(true), mean(false));
+ assert!(near < far * 0.97, "green over red near the red wall {near}, far from it {far}");
+}
+
+#[test]
+fn the_same_bake_gives_the_same_bytes() {
+ let t = texels(&set(), &request(8.0, 1024)).unwrap();
+ let s = Settings { samples: 16, per_pass: 8, ..Settings::default() };
+ let surf = |c: [f32; 3]| Surface { albedo: [0.5 + 0.1 * c[0].abs().fract(); 3], emission: [0.0; 3] };
+ let (a, b) = (run(&t, surf, &s), run(&t, surf, &s));
+ assert!(a.iter().any(|l| l[0] > 0.1), "no light at all");
+ assert_eq!(a, b);
+}
+
+#[test]
+fn mismatched_inputs_are_refused() {
+ let starts = Starts { origin: &[[0.0; 3]], normal: &[], inside: &[], offset: 1e-4 };
+ assert!(trace(&World { positions: &[], triangles: &[], surfaces: &[] }, &starts, &Settings::default(), &mut |_, _| {}).is_err());
+}
+
+/// The measured run (docs/bake.feature BK3): RAEA_BAKE_GLB at 64 texels a metre, every surface 0.7 grey under a white
+/// sky, RAEA_BAKE_SAMPLES (default 512) a texel: the trace's time alone.
+/// `cargo test -p raea-sys-lightbake trace::tests::measured -- --ignored --nocapture`
+#[test]
+#[ignore]
+fn measured() {
+ let glb = std::fs::read(std::env::var("RAEA_BAKE_GLB").expect("RAEA_BAKE_GLB: a .glb")).unwrap();
+ let samples = std::env::var("RAEA_BAKE_SAMPLES").ok().and_then(|v| v.parse().ok()).unwrap_or(512);
+ let t = texels(&glb, &request(64.0, 4096)).unwrap();
+ let t0 = std::time::Instant::now();
+ let light = run(&t, |_| Surface { albedo: [0.7; 3], emission: [0.0; 3] }, &Settings { samples, ..Settings::default() });
+ let lit = light.iter().zip(&t.inside).filter(|(_, i)| !**i).map(|(l, _)| l[0]).collect::<Vec<_>>();
+ println!("{} texels, {} triangles, {samples} samples, 4 bounces: {:.2} s, mean light {:.3}", light.len(), t.mesh.indices().len(), t0.elapsed().as_secs_f64(), lit.iter().sum::<f32>() / lit.len() as f32);
+}
diff --git a/systems/lightbake/src/wgsl/diffuse.wgsl b/systems/lightbake/src/wgsl/diffuse.wgsl
new file mode 100644
index 00000000..84a1668c
--- /dev/null
+++ b/systems/lightbake/src/wgsl/diffuse.wgsl
@@ -0,0 +1,26 @@
+// raea's diffuse BSDF (docs/bake.feature BK3), a module any ray-traced pass may include as it is (the light bake's
+// trace today; systems/rt and LT5's path tracer can take the same file): Lambert, sampled cosine-weighted, so a
+// path's weight is the albedo and the estimate of the light reaching a point is the mean of what its rays see.
+// Written here until tools/cycles-port's diffuse and energy-conserving Oren-Nayar are on main.
+
+// A direction about the unit normal n, cosine-weighted, from u in the unit square.
+fn raea_diffuse_sample(n: vec3<f32>, u: vec2<f32>) -> vec3<f32> {
+ let a = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(n.x) < 0.9);
+ let t = normalize(cross(n, a));
+ let b = cross(n, t);
+ let r = sqrt(u.x);
+ let phi = 6.283185307 * u.y;
+ return normalize(t * (r * cos(phi)) + b * (r * sin(phi)) + n * sqrt(max(0.0, 1.0 - u.x)));
+}
+
+// A hash of one u32 (PCG's output step): the paths' random numbers, fixed by texel, pass and sample.
+fn raea_hash(v: u32) -> u32 {
+ let s = v * 747796405u + 2891336453u;
+ let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
+ return (w >> 22u) ^ w;
+}
+
+fn raea_rand(state: ptr<function, u32>) -> f32 {
+ *state = raea_hash(*state);
+ return f32(*state >> 8u) / 16777216.0;
+}
diff --git a/systems/lightbake/src/wgsl/trace.wgsl b/systems/lightbake/src/wgsl/trace.wgsl
new file mode 100644
index 00000000..6a7063d5
--- /dev/null
+++ b/systems/lightbake/src/wgsl/trace.wgsl
@@ -0,0 +1,93 @@
+// The light that bounces, per texel (docs/bake.feature BK3): paths from the texel's origin through the model's own
+// triangles (one BLAS, one TLAS) by wgpu's ray queries. What a texel keeps is the mean light its cosine-weighted rays
+// bring back, so the lightmap times a surface's albedo is the light it sends on. At each hit the surface's emission
+// is added and the path goes on weighted by its albedo (Lambert, diffuse.wgsl); a miss sees the sky; after the
+// second bounce Russian roulette ends paths by their weight, unbiased. Passes add to `accum` (rgb, samples).
+
+struct Params {
+ sky: vec4<f32>,
+ count: u32,
+ pass_index: u32,
+ per_pass: u32,
+ bounces: u32,
+ offset: f32,
+ // the first texel of this dispatch (a bake's texels go in chunks)
+ first: u32,
+ _pad1: f32,
+ _pad2: f32,
+}
+
+struct Surface {
+ albedo: vec4<f32>,
+ emission: vec4<f32>,
+}
+
+@group(0) @binding(0) var tlas: acceleration_structure;
+@group(0) @binding(1) var<storage, read> positions: array<vec4<f32>>;
+@group(0) @binding(2) var<storage, read> indices: array<u32>;
+@group(0) @binding(3) var<storage, read> surfaces: array<Surface>;
+// per texel: origin (w: 1 when inside other geometry) and normal
+@group(0) @binding(4) var<storage, read> texels: array<vec4<f32>>;
+@group(0) @binding(5) var<storage, read_write> accum: array<vec4<f32>>;
+@group(0) @binding(6) var<uniform> params: Params;
+
+// The nearest hit. Its own function: a ray_query declared in a loop is zeroed again each turn, which naga writes for
+// Metal as an assignment Metal's intersection_query deletes.
+fn nearest(o: vec3<f32>, d: vec3<f32>) -> RayIntersection {
+ var rq: ray_query;
+ rayQueryInitialize(&rq, tlas, RayDesc(0u, 0xffu, 0.0, 1.0e30, o, d));
+ while (rayQueryProceed(&rq)) {}
+ return rayQueryGetCommittedIntersection(&rq);
+}
+
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let i = params.first + gid.x;
+ if (i >= params.count) {
+ return;
+ }
+ let at = texels[2u * i];
+ if (at.w > 0.5) {
+ return;
+ }
+ let n0 = texels[2u * i + 1u].xyz;
+ var sum = vec3<f32>(0.0);
+ for (var s = 0u; s < params.per_pass; s = s + 1u) {
+ var rng = raea_hash(i * 0x9e3779b9u ^ raea_hash(params.pass_index * params.per_pass + s));
+ var o = at.xyz;
+ var n = n0;
+ var weight = vec3<f32>(1.0);
+ var light = vec3<f32>(0.0);
+ for (var b = 0u; b < params.bounces; b = b + 1u) {
+ let d = raea_diffuse_sample(n, vec2<f32>(raea_rand(&rng), raea_rand(&rng)));
+ let hit = nearest(o, d);
+ if (hit.kind == RAY_QUERY_INTERSECTION_NONE) {
+ light = light + weight * params.sky.rgb;
+ break;
+ }
+ let p = hit.primitive_index;
+ let srf = surfaces[p];
+ light = light + weight * srf.emission.rgb;
+ let a = positions[indices[3u * p]].xyz;
+ let bb = positions[indices[3u * p + 1u]].xyz;
+ let c = positions[indices[3u * p + 2u]].xyz;
+ var ng = normalize(cross(bb - a, c - a));
+ if (dot(ng, d) > 0.0) {
+ ng = -ng;
+ }
+ let w = hit.barycentrics;
+ o = a * (1.0 - w.x - w.y) + bb * w.x + c * w.y + ng * params.offset;
+ n = ng;
+ weight = weight * srf.albedo.rgb;
+ if (b >= 2u) {
+ let q = max(weight.r, max(weight.g, weight.b));
+ if (raea_rand(&rng) >= q) {
+ break;
+ }
+ weight = weight / q;
+ }
+ }
+ sum = sum + light;
+ }
+ accum[i] = accum[i] + vec4<f32>(sum, f32(params.per_pass));
+}