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.

R3F21: a lit TSL node material's surface lit by Bevy's lights: three's builder writes it with no lights of its own, its output (context.getOutput) the colour and opacity, view normal and roughness, emission and metalness, and world point after positionNode (sdk/r3f src/input/tsl-lit.ts); three-shader's lit entry makes Bevy's PbrInput of it and runs the standard lighting, fog and tone mapping, the instance carried to the fragment for the mesh's shadow flags (systems/three-shader surface.rs). Lambert is fully rough, Phong's shininess a roughness. The plan in docs/r3f.feature; test/tsl.test.ts 8/8. Also carries R3F16's three:uniforms on a part whose shader fell back: Ok, never a refused frame

shinyobjectzfcd8105d93c4
diff --git a/docs/r3f.feature b/docs/r3f.feature
index 9a74be13..32cf1949 100644
--- a/docs/r3f.feature
+++ b/docs/r3f.feature
@@ -330,12 +330,22 @@ Feature: React Three Fiber both ways: an R3F scene drawn by raea, a raea composi
And in-instanced (2,000 moving copies with colours): SSIM at least 0.92 against three.js
Scenario: R3F21. A lit TSL node material is lit by the scene's lights
- Given a MeshStandardNodeMaterial or MeshPhysicalNodeMaterial with nodes of its own (colorNode, positionNode,
- normalNode, roughnessNode, metalnessNode, emissiveNode, opacityNode)
+ Given the plan
+ | crate | file | lines | job |
+ | raea-sys-three-shader | systems/three-shader/src/surface.rs | 90 | the lit fragment entry: three's surface as Bevy's PbrInput, lit |
+ | sdk/r3f | sdk/r3f/src/input/tsl-lit.ts | 85 | three's builder writing the surface, the lit contract |
+ And a MeshStandardNodeMaterial or MeshPhysicalNodeMaterial (or a Lambert, Phong or toon one) with nodes of its
+ own (colorNode, positionNode, normalNode, roughnessNode, metalnessNode, emissiveNode, opacityNode)
When raea draws it
- Then its nodes become a surface shader over Bevy's standard material (docs/shaders.feature SH1): the colour,
- normal, roughness, metalness, emission and opacity its nodes give, the position its positionNode moves a vertex
- to, lit by Bevy's lights and shadows
+ Then three's builder writes its surface with no lights of three's: its output (three's `context.getOutput`) is
+ the colour and opacity, the view-space normal and roughness three lights with, the emission and metalness, and
+ the point in world space after positionNode, returned by the fragment stage as `three_surface` (tsl-lit.ts)
+ And three-shader's lit entry makes Bevy's PbrInput of it and runs the standard material's lighting, fog and tone
+ mapping (surface.rs): lit by Bevy's lights and shadows as raea's StandardMaterial is, in three-shader's own
+ material rather than SH1's ShaderExt, so the vertex stage is three's (positionNode moves it) and its uniforms
+ have 254 slots, not 16
+ And a Lambert surface is fully rough and Phong's shininess a roughness, neither metal; a basic, shadow or volume
+ node material, or one with a fragmentNode, keeps three's own output
And in-tsl-lit (a noise-displaced, noise-coloured icosahedron under a directional light): SSIM at least 0.92
Scenario: R3F22. TSL compute and storage buffers
diff --git a/sdk/r3f/src/input/tsl-lit.ts b/sdk/r3f/src/input/tsl-lit.ts
new file mode 100644
index 00000000..3e9b691f
--- /dev/null
+++ b/sdk/r3f/src/input/tsl-lit.ts
@@ -0,0 +1,71 @@
+// A lit TSL node material (docs/r3f.feature R3F21): a MeshStandardNodeMaterial or MeshPhysicalNodeMaterial (or a
+// Lambert, Phong or toon one) with nodes of its own, lit by Bevy's lights and shadows instead of three's. three's
+// builder still writes the whole surface (colorNode, opacityNode, normalNode, roughnessNode, metalnessNode,
+// emissiveNode, the vertex moved by positionNode), but with no lights of three's: the material's output is replaced
+// (three's `context.getOutput`) by four values for the engine, which systems/three-shader's surface.rs hands to Bevy's
+// PbrInput and lights as raea's StandardMaterial is lit:
+// base the colour and opacity (three's DiffuseColor)
+// normal xyz the normal in view space (three's normalView), w the roughness three lights with (Roughness)
+// emissive xyz the emission (EmissiveColor), w the metalness (Metalness)
+// world xyz the point in world space (positionWorld, after positionNode)
+// The fragment stage then returns that surface (`fn three_surface(in, front) -> ThreeSurface`), and the varyings carry
+// the instance (`three_instance`, set by the engine's vertex entry) so the fragment reads the mesh's shadow flags.
+import type * as THREE from "three";
+import * as TSLTyped from "three/tsl";
+
+// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes
+const { outputStruct, diffuseColor, normalView, roughness, metalness, emissive, positionWorld, vec4, float } = TSLTyped as unknown as Record<string, any>;
+
+/** the lit node materials whose surface Bevy lights (Basic, shadow and volume ones keep three's own output) */
+const LIT = new Set(["MeshStandardNodeMaterial", "MeshPhysicalNodeMaterial", "MeshSSSNodeMaterial", "MeshLambertNodeMaterial", "MeshPhongNodeMaterial", "MeshToonNodeMaterial"]);
+
+export interface LitBuilder {
+ context: { getOutput?: (result: unknown) => unknown } & object;
+}
+
+/** whether a node material's graph is a surface Bevy lights: a lit kind, its fragment three's surface (no fragmentNode) */
+export function isLit(m: THREE.Material): boolean {
+ const own = m as unknown as { lights?: boolean; fragmentNode?: unknown; isMeshStandardNodeMaterial?: boolean };
+ return own.lights === true && own.fragmentNode == null && (LIT.has(m.type) || own.isMeshStandardNodeMaterial === true);
+}
+
+/** the material's roughness and metalness where three's lighting model keeps none: Lambert is fully rough, Phong's
+ * shininess a GGX roughness (material.ts's roughnessOfShininess), neither metal */
+function surfaceOf(m: THREE.Material): [unknown, unknown] {
+ if ((m as unknown as { isMeshStandardNodeMaterial?: boolean }).isMeshStandardNodeMaterial) return [roughness, metalness];
+ const shininess = (m as unknown as { shininess?: number }).shininess;
+ const r = shininess === undefined ? 1 : Math.min(1, Math.sqrt(Math.sqrt(2 / (Math.max(0, shininess) + 2))));
+ return [float(r), float(0)];
+}
+
+/** the builder set to write the surface (no lights of three's: the caller leaves its lightsNode unset) */
+export function litBuilder(b: LitBuilder, m: THREE.Material): void {
+ const [r, metal] = surfaceOf(m);
+ b.context.getOutput = () => outputStruct(vec4(diffuseColor), vec4(normalView, r), vec4(emissive, metal), vec4(positionWorld, float(1)));
+}
+
+const FIELDS = ["base", "normal", "emissive", "world"];
+const SURFACE = `struct ThreeSurface {\n${FIELDS.map((f) => `\t${f} : vec4<f32>,`).join("\n")}\n};`;
+
+/** the rewritten stages (tsl.ts's contract, its fragment returning three's first output) made the lit contract: the
+ * fragment returns the whole surface, and the varyings carry the instance */
+export function litStages(vertex: string, fragment: string): { vertex: string; fragment: string } {
+ // three's output struct (OutputType, its members m0..m3) and the private variable the fragment fills
+ const out = fragment.match(/var<private>\s+(\w+)\s*:\s*(\w+)\s*;/g)?.map((d) => d.match(/var<private>\s+(\w+)\s*:\s*(\w+)/)!).find(([, , t]) => new RegExp(`struct\\s+${t}\\s*\\{[^}]*@location\\(\\s*3\\s*\\)`).test(fragment));
+ if (!out) throw new Error("three's lit fragment stage has no four outputs");
+ const [, v, type] = out;
+ let f = fragment.replace(new RegExp(`struct\\s+${type}\\s*\\{[^}]*\\};?`), SURFACE);
+ f = f.replace(new RegExp(`var<private>\\s+${v}\\s*:\\s*${type}\\s*;`), `var<private> ${v} : ThreeSurface;`);
+ FIELDS.forEach((name, i) => (f = f.replace(new RegExp(`(?<![A-Za-z0-9_])${v}\\.m${i}(?![A-Za-z0-9_])`, "g"), `${v}.${name}`)));
+ f = f.replace(/fn three_fragment\(in: ThreeVaryings, front: bool\) -> vec4<f32> \{/, "fn three_surface(in: ThreeVaryings, front: bool) -> ThreeSurface {");
+ f = f.replace(new RegExp(`return\\s+${v}\\.base\\s*;`, "g"), `return ${v};`);
+ return { vertex: carryInstance(vertex), fragment: carryInstance(f) };
+}
+
+/** `three_instance` added to the varyings, at the location after three's last (flat: an index) */
+function carryInstance(src: string): string {
+ return src.replace(/struct\s+ThreeVaryings\s*\{([^}]*)\}/, (all, body: string) => {
+ const at = Math.max(-1, ...[...body.matchAll(/@location\(\s*(\d+)\s*\)/g)].map((m) => Number(m[1]))) + 1;
+ return `struct ThreeVaryings {\n\t@location( ${at} ) @interpolate( flat ) three_instance : u32,${body}}`;
+ });
+}
diff --git a/sdk/r3f/src/input/tsl.ts b/sdk/r3f/src/input/tsl.ts
index 4ed12b55..646c8c8d 100644
--- a/sdk/r3f/src/input/tsl.ts
+++ b/sdk/r3f/src/input/tsl.ts
@@ -17,6 +17,7 @@ import * as THREE from "three";
import { ModelNode, NodeFrame, WebGPURenderer } from "three/webgpu";
import type { Part, Props } from "./material";
import { srcOf } from "./texture";
+import { isLit, litBuilder, litStages } from "./tsl-lit";
/** what a node material is drawn for this frame: the object it's on, its scene and camera, R3F's clock */
export interface NodeAt {
@@ -108,6 +109,7 @@ interface Compiled {
textures: { name: string; texture: THREE.Texture }[];
/** the mesh's own attributes it reads, in order (the contract's a0..a3) */
attributes: string[];
+ lit: boolean; // a surface Bevy lights (tsl-lit.ts), not a colour
frame: NodeFrame;
}
@@ -131,8 +133,10 @@ function compile(m: THREE.Material, at: NodeAt): Compiled {
b.camera = at.camera;
b.material = m;
b.context.material = m;
- // a lit node material is lit by three's own light nodes, their colours and places this frame's
- if ((m as unknown as { lights?: boolean }).lights) b.lightsNode = (r as unknown as { lighting: { getNode(s: THREE.Scene, c: THREE.Camera): unknown } }).lighting.getNode(at.scene, at.camera);
+ // a lit node material's surface is lit by Bevy's lights (tsl-lit.ts); a basic one's light map by three's light nodes
+ const lit = isLit(m);
+ if (lit) litBuilder(b, m);
+ else if ((m as unknown as { lights?: boolean }).lights) b.lightsNode = (r as unknown as { lighting: { getNode(s: THREE.Scene, c: THREE.Camera): unknown } }).lighting.getNode(at.scene, at.camera);
const errors: string[] = [];
const err = console.error;
console.error = (...a: unknown[]) => errors.push(a.map(String).join(" "));
@@ -144,7 +148,7 @@ function compile(m: THREE.Material, at: NodeAt): Compiled {
if (errors.length) throw new Unsupported(`three couldn't build its graph: ${errors[0]}`);
if (b.updateBeforeNodes.length || b.updateAfterNodes.length) throw new Unsupported("it renders the scene again first (a reflector, a render target, a pass): raea draws one scene");
const c = rewrite(b);
- const out: Compiled = { key, builder: b, ...c, frame: new NodeFrame() };
+ const out: Compiled = { key, builder: b, ...c, ...(lit ? litStages(c.vertex, c.fragment) : {}), lit, frame: new NodeFrame() };
compiled.set(m, out);
return out;
}
@@ -236,7 +240,7 @@ const STORED: Record<string, string> = {
"mat3x3<f32>": "mat3x3<f32>", "mat4x4<f32>": "mat4x4<f32>",
};
-function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame"> {
+function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"> {
let vertex = b.vertexShader;
let fragment = b.fragmentShader;
const groups = b.getBindings();
@@ -459,7 +463,8 @@ export function nodeMaterialOf(m: THREE.Material, at: NodeAt): Part | undefined
const vals = values(c, m, at);
const props: Props = {
// <ThreeShaderMaterial wgsl>: the contract's two stages and its uniforms' types; this frame's values apart
- wgsl: { vertex: c.vertex, fragment: c.fragment, uniforms: vals.map(({ name, type, array }) => ({ name, type, ...(array ? { array } : {}) })), ...(c.attributes.length ? { attributes: c.attributes } : {}) },
+ wgsl: { vertex: c.vertex, fragment: c.fragment, uniforms: vals.map(({ name, type, array }) => ({ name, type, ...(array ? { array } : {}) })), ...(c.attributes.length ? { attributes: c.attributes } : {}), ...(c.lit ? { lit: true } : {}) },
+ ...(c.lit && (m as { fog?: boolean }).fog === false ? { fog: false } : {}),
uniforms: Object.fromEntries(vals.map((u) => [u.name, u.value])),
textures: Object.fromEntries(c.textures.map(({ name, texture }) => [name, { src: srcOf(texture)!, colorSpace: texture.colorSpace === THREE.SRGBColorSpace ? "srgb" : "linear" }])),
// three's node materials write linear colour (the renderer's output pass tone-maps and encodes), as raea's do
diff --git a/sdk/r3f/test/tsl.test.ts b/sdk/r3f/test/tsl.test.ts
index 92f3b2e6..8024380d 100644
--- a/sdk/r3f/test/tsl.test.ts
+++ b/sdk/r3f/test/tsl.test.ts
@@ -6,10 +6,10 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import * as THREE from "three";
-import { MeshBasicNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";
+import { MeshBasicNodeMaterial, MeshLambertNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";
import * as TSLTyped from "three/tsl";
// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes
-const { attribute, color, mix, sin, texture, time, uv } = TSLTyped as unknown as Record<string, (...a: unknown[]) => any> & { time: any };
+const { attribute, color, float, mix, mx_noise_float, normalLocal, positionLocal, sin, texture, time, uv } = TSLTyped as unknown as Record<string, (...a: unknown[]) => any> & { time: any };
import { composeEffects, configureFontTexture, createText, parseFont, scramble, wipe } from "lettra/three";
import { materialOf } from "../src/input/material";
import { nodeMaterialOf, type NodeAt, type ShaderSpec } from "../src/input/tsl";
@@ -71,7 +71,9 @@ function compiles(spec: ShaderSpec) {
if (!naga) return;
const dir = mkdtempSync(join(tmpdir(), "raea-tsl-"));
const vs = prelude(spec) + spec.vertex + "\n@vertex fn vs(@location(0) p: vec3<f32>, @location(1) n: vec3<f32>, @location(2) t: vec2<f32>, @builtin(instance_index) i: u32) -> ThreeVaryings { return three_vertex(ThreeVertex(p, n, t, vec4<f32>(1.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), vec4<f32>(0.0), i)); }\n";
- const fs = prelude(spec) + spec.fragment + "\n@fragment fn fs(v: ThreeVaryings, @builtin(front_facing) f: bool) -> @location(0) vec4<f32> { return three_fragment(v, f); }\n";
+ // a lit one's fragment returns its surface (tsl-lit.ts), which the engine lights
+ const entry = spec.fragment.includes("fn three_surface(") ? "three_surface(v, f).base" : "three_fragment(v, f)";
+ const fs = prelude(spec) + spec.fragment + `\n@fragment fn fs(v: ThreeVaryings, @builtin(front_facing) f: bool) -> @location(0) vec4<f32> { return ${entry}; }\n`;
for (const [name, src] of [["vertex", vs], ["fragment", fs]]) {
const f = join(dir, `${name}.wgsl`);
writeFileSync(f, src);
@@ -160,15 +162,39 @@ describe("TSL node materials → raea's ThreeShaderMaterial", () => {
expect(part.props).toMatchObject({ color: "#3fb950", roughness: 0.3, metalness: 0.2 });
});
- test("a lit node material with a graph is lit by three's own light nodes", () => {
+ test("a lit node material's surface is lit by Bevy's lights, not three's (R3F21)", () => {
+ // the noise blob: a displaced, noise-coloured icosahedron with its own roughness, metalness and glow
const m = new MeshStandardNodeMaterial();
- m.colorNode = mix(color("#ff0000"), color("#0000ff"), uv().x);
- const mesh = new THREE.Mesh(new THREE.SphereGeometry(), m);
+ const n = mx_noise_float(positionLocal.mul(2).add(time.mul(0.5)));
+ m.positionNode = positionLocal.add(normalLocal.mul(n.mul(0.3)));
+ m.colorNode = mix(color("#ff7744"), color("#3355ff"), n.mul(0.5).add(0.5));
+ m.roughnessNode = float(0.35);
+ m.metalnessNode = n.mul(0.2).add(0.1);
+ m.emissiveNode = color("#220800");
+ const mesh = new THREE.Mesh(new THREE.IcosahedronGeometry(1, 8), m);
const at = scene(mesh);
at.scene.add(new THREE.DirectionalLight("#ffffff", 2));
const part = materialOf(m, false, at);
expect(part.type).toBe("ThreeShaderMaterial");
- compiles(specOf(part.props));
+ expect((part.props.wgsl as { lit?: boolean }).lit).toBe(true);
+ const spec = specOf(part.props);
+ expect(spec.fragment).toContain("fn three_surface(in: ThreeVaryings, front: bool) -> ThreeSurface {");
+ expect(spec.fragment).toContain("return output;");
+ for (const f of ["base", "normal", "emissive", "world"]) expect(spec.fragment).toMatch(new RegExp(`output\\.${f} = `));
+ // the positionNode moves the vertex; three's lights are nowhere in the graph
+ expect(spec.vertex).toContain("mx_perlin_noise_float");
+ expect(spec.fragment).not.toMatch(/BRDF|directLight|DirectionalLight/i);
+ for (const s of [spec.vertex, spec.fragment]) expect(s).toMatch(/struct ThreeVaryings \{\s*@location\( \d+ \) @interpolate\( flat \) three_instance : u32,/);
+ compiles(spec);
+ });
+
+ test("a Lambert node material is a fully rough, unmetallic surface Bevy lights", () => {
+ const m = new MeshLambertNodeMaterial();
+ m.colorNode = mix(color("#ff0000"), color("#0000ff"), uv().x);
+ const part = materialOf(m, false, scene(new THREE.Mesh(new THREE.SphereGeometry(), m)));
+ expect((part.props.wgsl as { lit?: boolean }).lit).toBe(true);
+ expect(specOf(part.props).fragment).toMatch(/output\.normal = vec4<f32>\( \w+, 1\.0 \)/);
+ expect(specOf(part.props).fragment).toMatch(/output\.emissive = vec4<f32>\( \w+, 0\.0 \)/);
});
test("a graph raea can't carry is refused by name and drawn flat", () => {
diff --git a/systems/three-shader/src/lib.rs b/systems/three-shader/src/lib.rs
index 2248dbd6..50195cad 100644
--- a/systems/three-shader/src/lib.rs
+++ b/systems/three-shader/src/lib.rs
@@ -26,6 +26,7 @@ pub mod scan;
pub mod linear;
pub mod module;
mod row;
+pub mod surface;
pub use row::{fitted, of_row};
use module::{Ty, Uniform, ATTRIBUTES, DISPLAY_SLOT, SLOTS, TEXTURES, TIME_SLOT};
@@ -148,15 +149,22 @@ fn register(world: &mut World, module: String, kind: &str) -> u128 {
id
}
-/// The two modules of a material, from its stages' WGSL: the prelude in front of each, the entry point after.
-pub fn modules(vertex: &str, fragment: &str, layout: &[Uniform], textures: Option<&[String]>, attributes: usize) -> (String, String) {
+/// The two modules of a material, from its stages' WGSL: the prelude in front of each, the entry point after. A lit one
+/// (surface.rs) returns its surface from the fragment stage, and Bevy's lighting makes its colour.
+pub fn modules(vertex: &str, fragment: &str, layout: &[Uniform], textures: Option<&[String]>, attributes: usize, lit: bool) -> (String, String) {
let pre = module::prelude(layout, textures, attributes);
- (format!("{pre}{vertex}\n{}", module::vertex_entry(attributes)), format!("{pre}{fragment}\n{}", module::fragment_entry()))
+ let mut ve = module::vertex_entry(attributes);
+ if lit {
+ ve = ve.replace(" return three_vertex(v);\n", surface::VERTEX_TAIL);
+ }
+ let fe = if lit { surface::fragment_entry() } else { module::fragment_entry() };
+ (format!("{pre}{vertex}\n{ve}"), format!("{pre}{fragment}\n{fe}"))
}
/// A three shader's spec, as the SDK's ThreeShaderMaterial gives it:
/// glsl: {vertex, fragment, raw?, vertexColors?} a ShaderMaterial's (includes expanded, defines in front)
-/// wgsl: {vertex, fragment, uniforms: [{name, type, array?}], attributes?: [name]} the contract's, written already
+/// wgsl: {vertex, fragment, uniforms: [{name, type, array?}], attributes?: [name], lit?} the contract's, written
+/// already; `lit`: its fragment stage returns a surface Bevy lights (surface.rs)
/// uniforms: {name: number | [numbers]} each one's value (a matrix column-major, an array's elements in turn)
/// textures: {name: picture | {src, colorSpace: "srgb" | "linear", sampler}} "linear": sampled raw, as three
/// samples a NoColorSpace texture
@@ -191,6 +199,7 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
}
}
let names: Vec<String> = tex.iter().map(|t| t.0.clone()).collect();
+ let lit = o.get("wgsl").and_then(|w| w.get("lit")) == Some(&Value::Bool(true));
let (vsrc, fsrc, list, bound, attrs, own_textures) = if let Some(g) = o.get("glsl") {
let s = |k: &str| g.get(k).and_then(Value::as_str).ok_or_else(|| format!("a three shader's glsl needs {k}"));
let flag = |k: &str| g.get(k) == Some(&Value::Bool(true));
@@ -217,7 +226,7 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
// three's textures with flipY count v from the picture's bottom; Bevy's images from their top
let flip: Vec<String> = o.get("flipY").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).filter_map(|n| bound.iter().position(|b| b == n)).map(|k| if own_textures { format!("tex_{}", bound[k]) } else { format!("rgt{k}x") }).collect();
let (vsrc, fsrc) = (module::flip_samples(&vsrc, &flip), module::flip_samples(&fsrc, &flip));
- let (vm, fm) = modules(&vsrc, &fsrc, &layout, own_textures.then_some(bound.as_slice()), attrs.len());
+ let (vm, fm) = modules(&vsrc, &fsrc, &layout, own_textures.then_some(bound.as_slice()), attrs.len(), lit);
let vertex = register(world, vm, "v");
let fragment = register(world, fm, "f");
let mut slots = [[0f32; 4]; SLOTS];
@@ -247,6 +256,9 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
None => AlphaMode::Opaque,
},
};
+ // a lit surface's alpha mode and fog as the standard material's flags give them (surface.rs)
+ slots[DISPLAY_SLOT][2] = surface::alpha_code(alpha);
+ slots[DISPLAY_SLOT][3] = if o.get("fog") == Some(&Value::Bool(false)) { 0.0 } else { 1.0 };
let cull = match o.get("side").and_then(Value::as_str).unwrap_or("front") {
"double" => None,
"back" => Some(Face::Front),
@@ -275,7 +287,9 @@ pub fn build(world: &mut World, v: &Value, mut image: impl FnMut(&mut World, &Va
/// A `three:uniforms` component row: the frame's uniform values ({uniforms: {name: value}, time: [t, delta, frame]})
/// onto the part's three shader.
pub fn patch(world: &mut World, e: Entity, v: &Value) -> Result<(), String> {
- let Some(h) = world.get::<MeshMaterial3d<ThreeShader>>(e).map(|m| m.0.clone()) else { return Err("three:uniforms: the part has no three shader".into()) };
+ // a part whose shader didn't build here is drawn in its colour (of_row warned once, naming why): its uniforms have
+ // nothing to move, and its frame is never refused for them (docs/r3f.feature R3F16)
+ let Some(h) = world.get::<MeshMaterial3d<ThreeShader>>(e).map(|m| m.0.clone()) else { return Ok(()) };
let mut mats = world.resource_mut::<Assets<ThreeShader>>();
let Some(mut m) = mats.get_mut(&h) else { return Err("three:uniforms: its material isn't loaded".into()) };
let mut slots = m.slots.map(|s| s.to_array());
@@ -364,7 +378,7 @@ mod tests {
#[test]
fn modules_wrap_the_contract() {
let l = super::module::layout(&[("tint".into(), super::Ty::Vec(3), None)]).unwrap();
- let (v, f) = super::modules("struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_vertex(v: ThreeVertex) -> ThreeVaryings { var o: ThreeVaryings; o.clip = three_projection() * three_view() * three_model(v.instance) * vec4(v.position, 1.0); return o; }", "struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> { return vec4(u_tint(), 1.0); }", &l, Some(&[]), 0);
+ let (v, f) = super::modules("struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_vertex(v: ThreeVertex) -> ThreeVaryings { var o: ThreeVaryings; o.clip = three_projection() * three_view() * three_model(v.instance) * vec4(v.position, 1.0); return o; }", "struct ThreeVaryings { @builtin(position) clip: vec4<f32>, };\nfn three_fragment(in: ThreeVaryings, front: bool) -> vec4<f32> { return vec4(u_tint(), 1.0); }", &l, Some(&[]), 0, false);
assert!(v.contains("@vertex\nfn vertex(m: ThreeMeshIn) -> ThreeVaryings"));
assert!(f.contains("return three_untone(three_fragment(in, front));"));
assert!(f.contains("@group(constants::MATERIAL_BIND_GROUP) @binding(9) var three_lut: texture_3d<f32>;"));
diff --git a/systems/three-shader/src/surface.rs b/systems/three-shader/src/surface.rs
new file mode 100644
index 00000000..b2bba08e
--- /dev/null
+++ b/systems/three-shader/src/surface.rs
@@ -0,0 +1,74 @@
+//! A lit node material (docs/r3f.feature R3F21): three's MeshStandardNodeMaterial or MeshPhysicalNodeMaterial with
+//! nodes of its own, lit by Bevy's lights and shadows as raea's StandardMaterial is. three's builder writes the
+//! material's surface without its lights (sdk/r3f's input/tsl-lit.ts), and its fragment stage returns that surface:
+//! fn three_surface(in: ThreeVaryings, front: bool) -> ThreeSurface
+//! struct ThreeSurface { base: vec4<f32>, normal: vec4<f32>, emissive: vec4<f32>, world: vec4<f32> }
+//! base is the colour and opacity its colorNode and opacityNode give, normal.xyz its normal in view space (normalNode's,
+//! or the mesh's) and normal.w its roughness, emissive.xyz its emission and emissive.w its metalness, world.xyz the
+//! point in world space (moved by its positionNode). The varyings carry `three_instance`, the mesh's instance, which
+//! the vertex entry sets: Bevy's mesh flags (whether it takes shadows) are read with it. This entry makes Bevy's
+//! PbrInput of that surface and runs the standard material's lighting and its fog, tone mapping and alpha after.
+
+use crate::module::DISPLAY_SLOT;
+use bevy::prelude::AlphaMode;
+
+/// The vertex entry's last line for a lit material: the varyings carry the instance to the fragment stage.
+pub const VERTEX_TAIL: &str = " var o = three_vertex(v);\n o.three_instance = v.instance;\n return o;\n";
+
+/// The fragment entry of a lit material.
+pub fn fragment_entry() -> String {
+ format!(
+ "import bevy_pbr::render::pbr_types::{{pbr_input_new, STANDARD_MATERIAL_FLAGS_FOG_ENABLED_BIT}};\n\
+ import bevy_pbr::render::pbr_functions::{{apply_pbr_lighting, main_pass_post_lighting_processing, calculate_view}};\n\
+ import bevy_pbr::render::mesh_bindings::mesh;\n\n\
+ @fragment\n\
+ fn fragment(in: ThreeVaryings, @builtin(front_facing) front: bool) -> @location(0) vec4<f32> {{\n\
+ \x20 let s = three_surface(in, front);\n\
+ \x20 var pbr = pbr_input_new();\n\
+ \x20 pbr.material.base_color = s.base;\n\
+ \x20 pbr.material.perceptual_roughness = s.normal.w;\n\
+ \x20 pbr.material.metallic = s.emissive.w;\n\
+ \x20 // past the camera's exposure, as raea's StandardMaterial's emissive is (core/scene props.rs EMISSIVE)\n\
+ \x20 pbr.material.emissive = vec4<f32>(s.emissive.xyz, 0.0);\n\
+ \x20 let look = three_slots.s[{DISPLAY_SLOT}];\n\
+ \x20 pbr.material.flags = (u32(look.z + 0.5) << 29u) | select(0u, STANDARD_MATERIAL_FLAGS_FOG_ENABLED_BIT, look.w > 0.5);\n\
+ \x20 pbr.frag_coord = in.clip;\n\
+ \x20 pbr.world_position = vec4<f32>(s.world.xyz, 1.0);\n\
+ \x20 let n = normalize((view.world_from_view * vec4<f32>(s.normal.xyz, 0.0)).xyz);\n\
+ \x20 pbr.world_normal = n;\n\
+ \x20 pbr.N = n;\n\
+ \x20 pbr.is_orthographic = view.clip_from_view[3].w == 1.0;\n\
+ \x20 pbr.V = calculate_view(pbr.world_position, pbr.is_orthographic);\n\
+ \x20 pbr.flags = mesh[in.three_instance].flags;\n\
+ \x20 return main_pass_post_lighting_processing(pbr, apply_pbr_lighting(pbr));\n\
+ }}\n"
+ )
+}
+
+/// The alpha mode as the standard material's flags count it (pbr_types' STANDARD_MATERIAL_FLAGS_ALPHA_MODE_*, shifted
+/// down 29 bits): the lighting keeps an opaque surface's alpha at 1, and the post-lighting step premultiplies an
+/// additive or multiplied one.
+pub fn alpha_code(a: AlphaMode) -> f32 {
+ match a {
+ AlphaMode::Opaque => 0.0,
+ AlphaMode::Mask(_) => 1.0,
+ AlphaMode::Blend => 2.0,
+ AlphaMode::Premultiplied => 3.0,
+ AlphaMode::Add => 4.0,
+ AlphaMode::Multiply => 5.0,
+ AlphaMode::AlphaToCoverage => 6.0,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn the_surface_is_lit_by_bevy() {
+ let f = super::fragment_entry();
+ assert!(f.contains("let s = three_surface(in, front);"));
+ assert!(f.contains("apply_pbr_lighting(pbr)"));
+ assert!(f.contains("pbr.flags = mesh[in.three_instance].flags;"));
+ assert!(f.contains(&format!("three_slots.s[{}]", super::DISPLAY_SLOT)));
+ assert_eq!(super::alpha_code(bevy::prelude::AlphaMode::Add), 4.0);
+ }
+}