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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
R3F20: an InstancedMesh is one <Instances>, still or moving, with a colour a copy
shinyobjectz5b52eb4aede7
diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.mdindex e31b7310..fb411162 100644--- a/docs/manual/reference/sdk/3d.md+++ b/docs/manual/reference/sdk/3d.md@@ -1808,6 +1808,7 @@ copy together). Rotation in radians, XYZ order, as everywhere.| `position` (required) | `Vec3` | where this copy stands, metres, in the Instances' space || `rotation` | `Vec3` | its rotation, Euler angles in radians (x, y, z) || `scale` | `number \| Vec3` | its scale: one number, or x, y and z |+| `color` | `string \| Vec3` | this copy's colour, multiplied with the material's (as three's instanceColor): "#rrggbb", or linear [r, g, b]. When any copy has one, a copy without is white |### `InstancesProps`diff --git a/docs/manual/reference/sdk/mesh.md b/docs/manual/reference/sdk/mesh.mdindex 6e9015ec..ca0bae88 100644--- a/docs/manual/reference/sdk/mesh.md+++ b/docs/manual/reference/sdk/mesh.md@@ -381,6 +381,7 @@ copy together). Rotation in radians, XYZ order, as everywhere.| `position` (required) | `Vec3` | where this copy stands, metres, in the Instances' space || `rotation` | `Vec3` | its rotation, Euler angles in radians (x, y, z) || `scale` | `number \| Vec3` | its scale: one number, or x, y and z |+| `color` | `string \| Vec3` | this copy's colour, multiplied with the material's (as three's instanceColor): "#rrggbb", or linear [r, g, b]. When any copy has one, a copy without is white |### `InstancesProps`diff --git a/engine/render/src/engine.rs b/engine/render/src/engine.rsindex 8f7f6706..7554fd23 100644--- a/engine/render/src/engine.rs+++ b/engine/render/src/engine.rs@@ -80,6 +80,8 @@ use raea_sys_volume as volume;// meshes that cast shadows without being drawn (<Mesh shadow="only">)use raea_sys_material::shadow_only;use raea_sys_material::shadow_catch;+// a colour a copy over an <Instances>' surface (three's instanceColor)+use raea_sys_material::tint;// baked simulations played back by the frame (<MeshSequence>, <Goo>) and glitches on any part (physics.tsx)use raea_sys_meshseq as meshseq;// toon (cel) surfaces and their ink outlines (<MeshToonMaterial>)diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rsindex 8b4a29d1..980601d4 100644--- a/engine/render/src/engine/raea_plugins.rs+++ b/engine/render/src/engine/raea_plugins.rs@@ -64,6 +64,7 @@ raea_plugin! {GrassPlugin: raea_sys_grass::install, "Fields of grass, made in tiles as detailed as the camera's distance asks (systems/grass).";ShadowOnlyPlugin: super::shadow_only::install, "Meshes in the shadow maps only (shadow_only.rs).";ShadowCatchPlugin: super::shadow_catch::install, "Surfaces that show only the shadows falling on them (shadow_catch.rs).";+ TintPlugin: super::tint::install, "A colour a copy over an <Instances>' surface, three's instanceColor (tint.rs).";ToonPlugin: super::toon::install, "The toon surface and its ink outline's materials (toon.rs).";ShaderExtPlugin: super::shader_ext::install, "Shaders written in TypeScript over the lit standard surface (raea-sys-shader).";ThreeShaderPlugin: raea_sys_three_shader::install, "three.js's shaders: a ShaderMaterial's GLSL (naga) and a node material's WGSL, with three's built-ins (raea-sys-three-shader).";diff --git a/runtime/look/src/instances.rs b/runtime/look/src/instances.rsindex 5f5001aa..34518abb 100644--- a/runtime/look/src/instances.rs+++ b/runtime/look/src/instances.rs@@ -1,26 +1,49 @@//! <Instances> (sdk/render 3d/instances.tsx): a Mesh or Model whose props carry `at`, its placements 9 numbers a copy-//! (position, XYZ euler radians, scale), written as the row's `inst` column: 10 numbers a copy (position, rotation as-//! a quaternion xyzw, scale), space-separated. The engine draws one copy per placement, sharing the mesh and material-//! (runtime/scene3d's instance.rs; rows from runtime/scene). Placements that change over the shot are keyed (inst_all, inst_k).+//! (position, XYZ euler radians, scale), or 12 with a colour a copy (its linear r, g, b after; data-at+//! {"stride":12,"at":[...]}), written as the row's `inst` column: 10 numbers a copy (position, rotation as a quaternion+//! xyzw, scale), 13 with the colour (and `inst_tint` 1), space-separated. The engine draws one copy per placement,+//! sharing the mesh and material (runtime/scene3d's instance.rs; rows from runtime/scene). Placements that change over+//! the shot are keyed (inst_all, inst_k).use super::*;use bevy::math::{EulerRot, Quat};+use std::fmt::Write;-fn packed(at: &[Value]) -> Option<String> {- if at.len() % 9 != 0 {- eprintln!("WARN Instances: placements are 9 numbers a copy, got {}", at.len());+/// A data-at's numbers and how many make a copy: a list is 9 a copy, {"stride":12,"at":[...]} (as instances.tsx writes+/// it) 12. Parsed as plain numbers, not JSON values: a set of 20,000 copies is 240,000 of them a frame.+fn numbers(t: &str) -> Option<(usize, Vec<f64>)> {+ let t = t.trim();+ if t.starts_with('[') {+ return serde_json::from_str(t).ok().map(|a| (9, a));+ }+ let (head, list) = t.strip_prefix('{')?.split_once("\"at\":")?;+ let stride: usize = head.split(',').find_map(|kv| kv.trim().strip_prefix("\"stride\":")).and_then(|s| s.trim().parse().ok())?;+ let list: Vec<f64> = serde_json::from_str(list.trim_end().strip_suffix('}')?).ok()?;+ (stride == 9 || stride == 12).then_some((stride, list))+}++fn packed(stride: usize, at: &[f64]) -> Option<String> {+ if at.len() % stride != 0 {+ eprintln!("WARN Instances: placements are {stride} numbers a copy, got {}", at.len());return None;}- let f = |v: &Value| v.as_f64().unwrap_or(0.0);- let nums: Vec<String> = at- .chunks(9)- .flat_map(|c| {- let q = Quat::from_euler(EulerRot::XYZ, f(&c[3]) as f32, f(&c[4]) as f32, f(&c[5]) as f32);- [f(&c[0]), f(&c[1]), f(&c[2]), q.x as f64, q.y as f64, q.z as f64, q.w as f64, f(&c[6]), f(&c[7]), f(&c[8])]- })- .map(|v| format!("{}", r6(v)))- .collect();- Some(nums.join(" "))+ let mut out = String::with_capacity(at.len() * 8);+ let mut put = |v: f64| {+ if !out.is_empty() {+ out.push(' ');+ }+ let _ = write!(out, "{}", r6(v));+ };+ for c in at.chunks(stride) {+ let q = Quat::from_euler(EulerRot::XYZ, c[3] as f32, c[4] as f32, c[5] as f32);+ for v in [c[0], c[1], c[2], q.x as f64, q.y as f64, q.z as f64, q.w as f64, c[6], c[7], c[8]] {+ put(v);+ }+ for v in &c[9..] {+ put(*v);+ }+ }+ Some(out)}/// An item's placements as its text: its data-at (#84, shared across frames while unchanged), or an `at` prop written@@ -38,16 +61,15 @@ fn at_text(it: &Item) -> Option<std::borrow::Cow<'_, str>> {/// as `inst_k`, as a panel's pictures are (src_k): the engine moves its copies to the frame's (scene3d sync_instances)./// The count is the first frame's: a frame with another count holds the list before it.pub fn instances_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &str, its: &[Item]) {- let parse = |t: &str| serde_json::from_str::<Vec<Value>>(t).ok();let Some(first_text) = at_text(&its[0]) else { return };- let Some(at) = parse(&first_text) else { return };- let Some(first) = packed(&at) else { return };+ let Some((stride, at)) = numbers(&first_text) else { return };+ let Some(first) = packed(stride, &at) else { return };// each frame's list against the one before it only, by its text (the same Arc when React kept it): parsed only// when it differs (a frame without one holds the one before)let (mut lists, mut k, mut before, mut recounted) = (vec![first], Vec::with_capacity(its.len()), first_text, false);for it in its {if let Some(t) = at_text(it).filter(|t| *t != before) {- match parse(&t).filter(|a| a.len() == at.len()).and_then(|a| packed(&a)) {+ match numbers(&t).filter(|(s, a)| *s == stride && a.len() == at.len()).and_then(|(s, a)| packed(s, &a)) {Some(s) => {lists.push(s);before = t;@@ -61,6 +83,9 @@ pub fn instances_column(p: &mut Program, row: &mut BTreeMap<String, V>, id: &streprintln!("WARN Instances {}: how many copies it has changes over the shot; a frame with another count holds the placements before it", its[0].props.get("name").and_then(Value::as_str).unwrap_or("?"));}row.insert("inst".into(), V::S(lists[0].clone()));+ if stride == 12 {+ row.insert("inst_tint".into(), V::N(1.0));+ }if lists.len() > 1 {row.insert("inst_all".into(), V::S(lists.join("|")));exact(p, row, id, "inst_k", &k);@@ -100,6 +125,16 @@ mod tests {assert_eq!(k, [0.0, 0.0, 1.0, 2.0]);}+ // R3F20a: a colour a copy rides after its placement, and the row says so+ #[test]+ fn a_colour_a_copy_is_three_more_numbers() {+ let (mut p, mut row) = (Program::default(), BTreeMap::new());+ let it = Item { kind: "mesh", props: Default::default(), shape: None, material: None, at: Some(r#"{"stride":12,"at":[1,0,0,0,0,0,1,1,1,0.5,0.25,1]}"#.into()), world: Default::default() };+ instances_column(&mut p, &mut row, "m0", &[it]);+ assert_eq!(row.get("inst"), Some(&V::S("1 0 0 0 -0 0 1 1 1 1 0.5 0.25 1".into())));+ assert_eq!(row.get("inst_tint"), Some(&V::N(1.0)));+ }+#[test]fn still_placements_are_one_column() {let (mut p, mut row) = (Program::default(), BTreeMap::new());diff --git a/sdk/r3f/src/input/kinds.ts b/sdk/r3f/src/input/kinds.tsindex 4f494dd4..e0d8bb5c 100644--- a/sdk/r3f/src/input/kinds.ts+++ b/sdk/r3f/src/input/kinds.ts@@ -15,7 +15,7 @@ export const CLASSES: Record<string, { status: InputStatus; raea: string; note?:// drawn thingsMesh: { status: "drawn", raea: "Mesh + BufferMesh (its triangles, normals, uvs, vertex colours; a range per geometry group)" },SkinnedMesh: { status: "drawn", raea: "Mesh + BufferMesh posed on the CPU each frame (bones and morph targets)" },- InstancedMesh: { status: "drawn", raea: "Instances while its copies hold still; a Mesh a copy when they move or have colours" },+ InstancedMesh: { status: "drawn", raea: "Instances, its copies the frame's matrices and colours (a Mesh a copy under a ShaderMaterial)" },BatchedMesh: { status: "drawn", raea: "a Mesh per instance: its geometry's range, matrix and colour" },Points: { status: "drawn", raea: "one Mesh of quads facing the camera, three's point size (attenuated or in pixels), vertex colours" },Line: { status: "drawn", raea: "Gizmo strip in world space (vertex colours)", note: "lines are drawn 1 pixel wide in WebGL whatever linewidth says; raea draws linewidth" },diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.tsindex 816ed6dd..bf3a6fe6 100644--- a/sdk/r3f/src/input/scene.ts+++ b/sdk/r3f/src/input/scene.ts@@ -1,7 +1,6 @@// A three.js scene as raea's parts. The scene graph keeps its shape: an object with children is a <Group> at its own// transform (raea composes them as three does, shear included), a mesh a <Mesh> with its <BufferMesh> and material.-// An InstancedMesh is <Instances> while its copies hold still and one mesh a copy when they move or each has its own-// colour; Points are one mesh of quads facing the camera; lines are a <Gizmo>; a Sprite is a quad facing the camera.+// An InstancedMesh is one <Instances> whose copies are the frame's instance matrices and colours; Points are one mesh of quads facing the camera; lines are a <Gizmo>; a Sprite is a quad facing the camera.// Lights, the camera, fog and the environment come out in world space (lights.ts). Each part is named by its place in// the tree (and its own name), so raea matches it across frames.import * as THREE from "three";@@ -122,32 +121,47 @@ function meshParts(mesh: THREE.Mesh, name: string, w: Walk, at: Props): Part[] {return out;}-/** whose copies have moved since the first frame: those are drawn one mesh a copy */-const firstPlacement = new WeakMap<THREE.InstancedMesh, number>();+/** the surfaces raea's <Instances> draws its copies with (scene3d's instance_mesh takes a standard material) */+const INSTANCED = new Set(["MeshStandardMaterial", "MeshPhysicalMaterial", "MeshBasicMaterial"]);+/** An InstancedMesh as one <Instances>, still or moving, its copies this frame's instance matrices and colours (R3F20):+ * one row the engine draws by Bevy's instancing, its list the frame's buffer. All instanceMatrix.count copies are sent+ * so the count holds when `count` changes, those past it shrunk to nothing; a mirrored copy is drawn unmirrored. A+ * ShaderMaterial, several materials, MeshNormalMaterial, a shadow catcher or clipping planes: one mesh a copy. */function instancedParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Props): Part[] {- const v = m.instanceMatrix.version;- if (!firstPlacement.has(m)) firstPlacement.set(m, v);- const moving = firstPlacement.get(m) !== v || m.instanceColor !== null || Array.isArray(m.material);- const one = new THREE.Matrix4();- const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(), e = new THREE.Euler();- const copies: { position: V3; quaternion: Q; rotation: V3; scale: V3 }[] = [];- for (let i = 0; i < m.count; i++) {+ const material = m.material as THREE.Material;+ const surface = Array.isArray(m.material) || !material.visible ? undefined : materialOf(material, colouredByVertex(material), { object: m, scene: w.scene, camera: w.camera, time: w.time, delta: w.delta });+ if (!surface || !INSTANCED.has(surface.type) || surface.normals || surface.catchShadow || clipOf(material, w.gl, w.clips)) return copyParts(m, name, w, at);+ const arrays = arraysOf(m.geometry, { flipV: flipped(material), colors: colouredByVertex(material) });+ if (!arrays) return [];+ const one = new THREE.Matrix4(), p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(), e = new THREE.Euler(), c = new THREE.Color();+ const n = m.instanceMatrix.count, shown = Math.min(m.count, n);+ const colours = m.instanceColor;+ const copies = new Array(n);+ for (let i = 0; i < n; i++) {m.getMatrixAt(i, one);one.decompose(p, q, s);- copies.push({ position: p.toArray() as V3, quaternion: q.toArray() as Q, rotation: e.setFromQuaternion(q, "XYZ").toArray().slice(0, 3) as V3, scale: s.toArray() as V3 });- }- if (!moving) {- const material = m.material as THREE.Material;- const arrays = arraysOf(m.geometry, { flipV: flipped(material), colors: colouredByVertex(material) });- const surface = materialOf(material, false, { object: m, scene: w.scene, camera: w.camera, time: w.time, delta: w.delta });- if (!arrays || !surface.type) return [];- return [{ type: "Instances", props: { name, ...at, at: copies.map(({ position, rotation, scale }) => ({ position, rotation, scale })), shadow: w.shadows && m.castShadow, receiveShadow: m.receiveShadow }, children: [{ type: "BufferMesh", props: { ...arrays } }, surface] }];+ const hide = i >= shown || !Number.isFinite(p.x + p.y + p.z + q.x + q.y + q.z + q.w + s.x + s.y + s.z);+ const size = (v: number) => (hide ? 1e-5 : Math.max(Math.abs(v), 1e-5));+ e.setFromQuaternion(hide ? q.identity() : q, "XYZ");+ const copy: { position: number[]; rotation: number[]; scale: number[]; color?: number[] } = { position: hide ? [0, 0, 0] : [p.x, p.y, p.z], rotation: [e.x, e.y, e.z], scale: [size(s.x), size(s.y), size(s.z)] };+ if (colours) {+ m.getColorAt(i, c);+ copy.color = [c.r, c.g, c.b];+ }+ copies[i] = copy;}+ return [{ type: "Instances", props: { name, ...at, at: copies, shadow: w.shadows && m.castShadow, receiveShadow: m.receiveShadow }, children: [{ type: "BufferMesh", props: { ...arrays } }, surface] }];+}++/** an InstancedMesh whose surface <Instances> can't share: one mesh a copy, each in its colour */+function copyParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Props): Part[] {+ const one = new THREE.Matrix4(), p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(), c = new THREE.Color();const kids: Part[] = [];- const c = new THREE.Color();- copies.forEach((k, i) => {- for (const part of meshParts(m, `${name}.${i}`, w, { position: k.position, quaternion: k.quaternion, scale: k.scale })) {+ for (let i = 0; i < Math.min(m.count, m.instanceMatrix.count); i++) {+ m.getMatrixAt(i, one);+ one.decompose(p, q, s);+ for (const part of meshParts(m, `${name}.${i}`, w, { position: p.toArray() as V3, quaternion: q.toArray() as Q, scale: s.toArray() as V3 })) {if (m.instanceColor) {m.getColorAt(i, c);const surface = part.children![1];@@ -156,7 +170,7 @@ function instancedParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Props}kids.push(part);}- });+ }return [{ type: "Group", props: { name, ...at }, children: kids }];}diff --git a/sdk/r3f/src/three/scene.ts b/sdk/r3f/src/three/scene.tsindex 0c395580..4e5d0000 100644--- a/sdk/r3f/src/three/scene.ts+++ b/sdk/r3f/src/three/scene.ts@@ -220,11 +220,11 @@ export class Scene3d {k.waiting = !primitive && !!shape && !fromShape;if (k.waiting) this.warnOnce("Mesh shape", "is a solid: load raea's shape module (loadShapes) to draw it");// <Instances>' copies: their placements in data-at, apart from its props (sdk/render instances.tsx)- const at = (p.at as number[] | undefined) ?? placements(el);+ const at = p.at ? { at: p.at as number[], stride: 9 } : placements(el);const had = k.obj as THREE.Mesh | undefined;const geometry = fromShape ?? had?.geometry ?? new THREE.BufferGeometry();const material = (had?.material as THREE.Material | undefined) ?? new THREE.MeshStandardMaterial();- const m = at ? instanced(had instanceof THREE.InstancedMesh ? had : undefined, geometry, material, at) : had && !(had instanceof THREE.InstancedMesh) ? had : new THREE.Mesh(geometry, material);+ const m = at ? instanced(had instanceof THREE.InstancedMesh ? had : undefined, geometry, material, at.at, at.stride) : had && !(had instanceof THREE.InstancedMesh) ? had : new THREE.Mesh(geometry, material);m.geometry = geometry;place(m, p);// shadow="only": it casts its shadow and isn't seen@@ -471,13 +471,15 @@ export class Scene3d {export { vec };-/** an <Instances>' placements, 9 numbers a copy (position, rotation, scale), from its data-at; undefined without one */-function placements(el: Element): number[] | undefined {+/** an <Instances>' placements from its data-at: 9 numbers a copy (position, rotation, scale), or 12 with a colour a+ * copy ({"stride":12,"at":[...]}); undefined without one */+function placements(el: Element): { at: number[]; stride: number } | undefined {const raw = el.getAttribute("data-at");if (!raw) return undefined;try {const at = JSON.parse(raw);- return Array.isArray(at) ? (at as number[]) : undefined;+ if (Array.isArray(at)) return { at: at as number[], stride: 9 };+ return at && Array.isArray(at.at) && (at.stride === 9 || at.stride === 12) ? { at: at.at as number[], stride: at.stride as number } : undefined;} catch {return undefined;}diff --git a/sdk/r3f/src/three/things.ts b/sdk/r3f/src/three/things.tsindex 53130f4a..301723dd 100644--- a/sdk/r3f/src/three/things.ts+++ b/sdk/r3f/src/three/things.ts@@ -174,22 +174,25 @@ export function imagePlane(had: THREE.Mesh | undefined, p: Props): THREE.Mesh {return mesh;}-// ---- instanced copies: `at` packs 9 numbers a copy (position, rotation XYZ, scale) -----export function instanced(had: THREE.InstancedMesh | undefined, geometry: THREE.BufferGeometry, material: THREE.Material, at: number[]): THREE.InstancedMesh {- const n = Math.floor(at.length / 9);+// ---- instanced copies: `at` packs 9 numbers a copy (position, rotation XYZ, scale), 12 with its linear colour ----+export function instanced(had: THREE.InstancedMesh | undefined, geometry: THREE.BufferGeometry, material: THREE.Material, at: number[], stride = 9): THREE.InstancedMesh {+ const n = Math.floor(at.length / stride);const m = had && had.count === n ? had : new THREE.InstancedMesh(geometry, material, n);m.geometry = geometry;m.material = material;const o = new THREE.Object3D();+ const c = new THREE.Color();for (let i = 0; i < n; i++) {- const k = i * 9;+ const k = i * stride;o.position.set(at[k], at[k + 1], at[k + 2]);o.rotation.set(at[k + 3], at[k + 4], at[k + 5], "XYZ");o.scale.set(at[k + 6], at[k + 7], at[k + 8]);o.updateMatrix();m.setMatrixAt(i, o.matrix);+ if (stride === 12) m.setColorAt(i, c.setRGB(at[k + 9], at[k + 10], at[k + 11]));}m.instanceMatrix.needsUpdate = true;+ if (m.instanceColor) m.instanceColor.needsUpdate = true;m.castShadow = m.receiveShadow = true;return m;}diff --git a/sdk/r3f/test/input.test.tsx b/sdk/r3f/test/input.test.tsxindex 09a51c42..fb30bbfb 100644--- a/sdk/r3f/test/input.test.tsx+++ b/sdk/r3f/test/input.test.tsx@@ -94,24 +94,40 @@ describe("the clock", () => {});describe("the scene graph", () => {- test("an InstancedMesh holding still is Instances; moving, a mesh a copy", () => {+ test("an InstancedMesh is one Instances, still or moving, its copies' colours with it (R3F20)", () => {const geo = new THREE.BoxGeometry(), mat = new THREE.MeshStandardMaterial({ color: "#336699" });- const im = new THREE.InstancedMesh(geo, mat, 3);+ const im = new THREE.InstancedMesh(geo, mat, 4);const m = new THREE.Matrix4();- for (let i = 0; i < 3; i++) im.setMatrixAt(i, m.makeTranslation(i * 2, 0, 0));+ for (let i = 0; i < 4; i++) im.setMatrixAt(i, m.makeTranslation(i * 2, 0, 0));+ im.count = 3;const a = partsOf(() => <primitive object={im} />);const inst = flat(a.parts).find((p) => p.type === "Instances")!;- expect((inst.props.at as unknown[]).length).toBe(3);- expect((inst.props.at as { position: number[] }[])[2].position).toEqual([4, 0, 0]);+ const at = () => inst.props.at as { position: number[]; scale: number[]; color?: number[] }[];+ expect(at().length).toBe(4);+ expect(at()[2].position).toEqual([4, 0, 0]);+ // past `count`: still sent, so the count holds, shrunk to nothing+ expect(at()[3].scale).toEqual([1e-5, 1e-5, 1e-5]);+ expect(at()[0].color).toBeUndefined();im.setMatrixAt(1, m.makeTranslation(0, 5, 0));+ im.setColorAt(2, new THREE.Color(1, 0, 0));im.instanceMatrix.needsUpdate = true;- const b = convert(a.st.scene, a.st.camera, a.st.gl, 360);- const meshes = flat(b.parts).filter((p) => p.type === "Mesh");- expect(meshes.length).toBe(3);- expect(meshes[1].props.position).toEqual([0, 5, 0]);+ const b = flat(convert(a.st.scene, a.st.camera, a.st.gl, 360).parts);+ expect(b.filter((p) => p.type === "Mesh").length).toBe(0);+ const moved = b.find((p) => p.type === "Instances")!.props.at as { position: number[]; color: number[] }[];+ expect(moved[1].position).toEqual([0, 5, 0]);+ expect(moved[2].color).toEqual([1, 0, 0]);end(a.key);});+ test("an InstancedMesh under a ShaderMaterial is a mesh a copy", () => {+ const sh = new THREE.ShaderMaterial({ vertexShader: "void main() { gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0); }", fragmentShader: "void main() { gl_FragColor = vec4(1.0); }" });+ const im = new THREE.InstancedMesh(new THREE.BoxGeometry(), sh, 2);+ const r = partsOf(() => <primitive object={im} />);+ expect(flat(r.parts).filter((p) => p.type === "Instances").length).toBe(0);+ expect(flat(r.parts).filter((p) => p.type === "Mesh").length).toBe(2);+ end(r.key);+ });+test("a mesh swapped into the same place with another shader program is another part; the same program keeps its", () => {const vs = "void main() { gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }";const shaded = (fs: string, uniforms: Record<string, THREE.IUniform>) => new THREE.Mesh(new THREE.PlaneGeometry(), new THREE.ShaderMaterial({ uniforms, vertexShader: vs, fragmentShader: fs }));diff --git a/sdk/r3f/test/instances.test.tsx b/sdk/r3f/test/instances.test.tsxindex 8e00d31f..38c0fca4 100644--- a/sdk/r3f/test/instances.test.tsx+++ b/sdk/r3f/test/instances.test.tsx@@ -54,4 +54,19 @@ describe("Instances", () => {inst[0].getMatrixAt(0, m);expect(new THREE.Vector3().setFromMatrixPosition(m).toArray()).toEqual([2, 2, 0]);});++ test("a colour a copy is the InstancedMesh's instanceColor (R3F20a)", () => {+ const { out } = meshesOf(+ <Instances at={[{ position: [0, 0, 0], color: [1, 0, 0] }, { position: [1, 0, 0] }]}>+ <Sphere radius={0.1} />+ <StandardMaterial base_color="#ffffff" />+ </Instances>,+ );+ const inst = out.find((m) => (m as THREE.InstancedMesh).isInstancedMesh) as THREE.InstancedMesh;+ const c = new THREE.Color();+ inst.getColorAt(0, c);+ expect(c.toArray()).toEqual([1, 0, 0]);+ inst.getColorAt(1, c);+ expect(c.toArray()).toEqual([1, 1, 1]);+ });});diff --git a/sdk/raea/conformance/instances.test.tsx b/sdk/raea/conformance/instances.test.tsxindex ea4c56b7..36d7dd6f 100644--- a/sdk/raea/conformance/instances.test.tsx+++ b/sdk/raea/conformance/instances.test.tsx@@ -28,6 +28,14 @@ describe("Instances", () => {expect(p.at).toBeUndefined();expect(p.shadow).toBe(false);});+ test("a colour a copy: 12 numbers a copy (linear r, g, b after), a copy without one white (R3F20a)", () => {+ const at = [{ position: [1, 0, 2] as [number, number, number], color: "#ff0000" }, { position: [0, 0, 0] as [number, number, number] }, { position: [0, 1, 0] as [number, number, number], color: [0, 0.5, 0] as [number, number, number] }];+ const h = html(<Instances at={at}><Cuboid args={[1, 1, 1]} /><MeshStandardMaterial /></Instances>);+ const d = placed(h, "Mesh");+ expect(d.stride).toBe(12);+ expect(d.at).toEqual([1, 0, 2, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0.5, 0]);+ expect(() => html(<Instances at={[{ position: [0, 0, 0], color: "red" }]}><Cuboid args={[1, 1, 1]} /><MeshStandardMaterial /></Instances>)).toThrow(/color/);+ });test("the glTF form: a Model node", () => {const h = html(<Instances src="daisy.glb" at={[{ position: [0, 0, 0] }]} />);expect(props(h, "Model").src).toBe("daisy.glb");diff --git a/sdk/render/src/3d/instances.tsx b/sdk/render/src/3d/instances.tsxindex 2ec522b9..7d7286d3 100644--- a/sdk/render/src/3d/instances.tsx+++ b/sdk/render/src/3d/instances.tsx@@ -13,6 +13,9 @@ export interface Instance {rotation?: Vec3;/** its scale: one number, or x, y and z */scale?: number | Vec3;+ /** this copy's colour, multiplied with the material's (as three's instanceColor): "#rrggbb", or linear [r, g, b].+ * When any copy has one, a copy without is white */+ color?: string | Vec3;}export interface InstancesProps {@@ -46,33 +49,60 @@ export interface InstancesProps {children?: ReactNode;}-/** The packed placements, 9 numbers a copy (position, rotation, scale), cached by the list, so a list made once (a- * module's `scatter`) is packed once however many frames draw it. */+/** The packed placements, 9 numbers a copy (position, rotation, scale), or 12 when any copy has a colour (its linear+ * r, g, b after), cached by the list, so a list made once (a module's `scatter`) is packed once however many frames+ * draw it. */const PACKED = new WeakMap<Instance[], number[]>();const r5 = (x: number) => Math.round(x * 1e5) / 1e5;+/** "#rrggbb" (sRGB) as linear r, g, b */+function linearOf(owner: string, i: number, c: string | Vec3): Vec3 {+ if (Array.isArray(c)) {+ checkVec(owner, `at[${i}].color`, c);+ return c;+ }+ const m = typeof c === "string" ? /^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(c) : null;+ if (!m) throw new TypeError(`${owner}: at[${i}].color is "#rrggbb" or linear [r, g, b], got ${JSON.stringify(c)}`);+ return [m[1], m[2], m[3]].map((h) => {+ const v = parseInt(h, 16) / 255;+ return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);+ }) as Vec3;+}export function packInstances(owner: string, at: Instance[]): number[] {const hit = PACKED.get(at);if (hit) return hit;- const out: number[] = new Array(at.length * 9);+ const tinted = at.some((it) => it !== null && typeof it === "object" && it.color !== undefined);+ const stride = tinted ? 12 : 9;+ const out: number[] = new Array(at.length * stride);at.forEach((it, i) => {- if (it === null || typeof it !== "object") throw new TypeError(`${owner}: at[${i}] must be { position, rotation?, scale? }, got ${JSON.stringify(it)}`);+ if (it === null || typeof it !== "object") throw new TypeError(`${owner}: at[${i}] must be { position, rotation?, scale?, color? }, got ${JSON.stringify(it)}`);const { position, rotation = [0, 0, 0], scale = 1 } = it;checkVec(owner, `at[${i}].position`, position);checkVec(owner, `at[${i}].rotation`, rotation);const s: Vec3 = typeof scale === "number" ? [scale, scale, scale] : scale;checkVec(owner, `at[${i}].scale`, s);if (!s.every((v) => v > 0)) throw new RangeError(`${owner}: at[${i}].scale must be positive, got ${JSON.stringify(scale)}`);- const o = i * 9;+ const o = i * stride;for (let k = 0; k < 3; k++) {out[o + k] = r5(position[k]);out[o + 3 + k] = r5(rotation[k]);out[o + 6 + k] = r5(s[k]);}+ if (tinted) {+ const c = it.color === undefined ? ([1, 1, 1] as Vec3) : linearOf(owner, i, it.color);+ for (let k = 0; k < 3; k++) out[o + 9 + k] = r5(c[k]);+ }});PACKED.set(at, out);return out;}+/** An <Instances>' data-at: its packed placements, 9 numbers a copy as a list, or 12 (with the colour) as+ * {"stride":12,"at":[...]} */+function dataAt(owner: string, at: Instance[]): string {+ const packed = packInstances(owner, at);+ return packed.length === at.length * 12 && at.length > 0 ? `{"stride":12,"at":${JSON.stringify(packed)}}` : JSON.stringify(packed);+}+/** One glTF (or one mesh) drawn at many placements, loaded once and drawn by the GPU as instances: a meadow's grass* and flowers, a forest, a suburb's houses. `<Instances src={staticFile("daisy.glb")} at={scatter({...})} />`. The* copies share one surface and can't play a clip.@@ -85,11 +115,10 @@ export function Instances(props: InstancesProps) {if (props.scale !== undefined && typeof props.scale !== "number") checkVec(owner, "scale", props.scale);for (const k of ["animation", "animations", "graph", "morphs"]) if (k in (props as object)) throw new TypeError(`${owner}: instances can't play a clip or set morphs; use a <Model> for an animated one`);checkPass(owner, props.pass);- const at = packInstances(owner, props.at);const { position = [0, 0, 0], rotation = [0, 0, 0], scale = 1 } = props;// the placements in an attribute of their own, not data-props: the engine shares one list across frames while its text// is the same, where a set whose other props change was parsed whole into each frame's props (#84)- const placed = { "data-at": JSON.stringify(at) };+ const placed = { "data-at": dataAt(owner, props.at) };if (props.src !== undefined) return node3d("Model", { ...props, shape: undefined, at: undefined, position, rotation, scale }, props.children, placed);const manifold = props.shape instanceof Solid ? props.shape.expr : props.shape ?? shapeFromChildren(props.children);if (manifold === undefined) throw new TypeError("Instances: give a glTF `src`, or a geometry child (<Cuboid />, <BufferMesh />, ...) or `shape`");diff --git a/systems/compose/src/compose/passes.rs b/systems/compose/src/compose/passes.rsindex 6139cfbb..e9616fa1 100644--- a/systems/compose/src/compose/passes.rs+++ b/systems/compose/src/compose/passes.rs@@ -78,10 +78,12 @@ pub fn sync_passes(let want = (p.round().max(0.0) as u32).min(MOST as u32);let mut all = descendants(e, &kids);all.push(e);+ // the pass in the tag's two low bits; the bits above are an <Instances>' copy's number (raea-sys-material tint.rs)for d in all {if let Ok(t) = tags.get(d) {- if t.map_or(0, |t| t.value) != want {- commands.entity(d).insert(MeshTag::new(want));+ let had = t.map_or(0, |t| t.value);+ if had & 3 != want {+ commands.entity(d).insert(MeshTag::new((had & !3) | want));}}}diff --git a/systems/material/src/lib.rs b/systems/material/src/lib.rsindex cbd0de5f..6f2a18fa 100644--- a/systems/material/src/lib.rs+++ b/systems/material/src/lib.rs@@ -21,3 +21,4 @@ pub mod toon;pub mod shadow_only;pub mod shadow_catch;pub mod shader_material;+pub mod tint;diff --git a/systems/material/src/tint.rs b/systems/material/src/tint.rsnew file mode 100644index 00000000..f0f81615--- /dev/null+++ b/systems/material/src/tint.rs@@ -0,0 +1,57 @@+//! A colour a copy over an <Instances>' shared surface (three's instanceColor, docs/r3f.feature R3F20a): the standard+//! material extended by a storage buffer of the copies' linear colours, which multiply its base colour before the light.+//! Every copy holds the one TintMaterial, so Bevy's automatic batching still draws the set as one instanced call; a+//! copy finds its colour by its MeshTag above the two low bits (compose.rs keeps a mesh's composition pass in those).+//!+//! scene3d's instance.rs makes it for a mesh row with `inst_tint` 1 and rewrites the buffer when the frame's list+//! changes; the standard material it extends is the row's own, copied in again when that changes.++use super::*;+use bevy::pbr::{ExtendedMaterial, MaterialExtension, MaterialPlugin};+use bevy::render::render_resource::AsBindGroup;+use bevy::render::storage::ShaderBuffer;+use bevy::shader::ShaderRef;++pub type TintMaterial = ExtendedMaterial<StandardMaterial, Tint>;++pub fn install(app: &mut App) {+ bevy::asset::embedded_asset!(app, "tint.wesl");+ app.add_plugins(MaterialPlugin::<TintMaterial>::default());+}++#[derive(Asset, TypePath, AsBindGroup, Clone)]+pub struct Tint {+ /// each copy's linear rgba, by its MeshTag >> 2+ #[storage(100, read_only)]+ pub colours: Handle<ShaderBuffer>,+}++impl MaterialExtension for Tint {+ fn fragment_shader() -> ShaderRef {+ "embedded://raea_sys_material/tint.wesl".into()+ }+}++/// The copies' colours as the buffer holds them: linear rgba, alpha 1. A buffer of the same size is written in place+/// on the GPU (GpuShaderBuffer reuses it), so the material's bind group stands.+pub fn colour_buffer(rgb: &[[f32; 3]]) -> ShaderBuffer {+ let words: Vec<[f32; 4]> = rgb.iter().map(|c| [c[0], c[1], c[2], 1.0]).collect();+ ShaderBuffer::new(words, bevy::asset::RenderAssetUsages::default())+}++/// A copy's MeshTag: its number above the two bits a composition pass keeps+pub fn copy_tag(copy: usize, pass: u32) -> u32 {+ ((copy as u32) << 2) | (pass & 3)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_copy_tag_keeps_the_pass_bits() {+ assert_eq!(copy_tag(5, 2), 22);+ assert_eq!(copy_tag(5, 2) >> 2, 5);+ assert_eq!(copy_tag(5, 2) & 3, 2);+ }+}diff --git a/systems/material/src/tint.wesl b/systems/material/src/tint.weslnew file mode 100644index 00000000..ebb34cf2--- /dev/null+++ b/systems/material/src/tint.wesl@@ -0,0 +1,34 @@+// tint.rs: a colour a copy over the standard material (Bevy's extended-material fragment, its lighting kept): the+// copy's colour, found by its MeshTag above compose's two pass bits, multiplies the base colour before the light.+import bevy_pbr::render::pbr_fragment::pbr_input_from_standard_material;+import bevy_pbr::render::pbr_functions::alpha_discard;+import bevy_pbr::render::mesh_functions::get_tag;+@if(PREPASS_PIPELINE) import bevy_pbr::prepass::io::{VertexOutput, FragmentOutput};+@if(PREPASS_PIPELINE) import bevy_pbr::deferred::functions::deferred_output;+@if(!PREPASS_PIPELINE) import bevy_pbr::render::forward_io::{VertexOutput, FragmentOutput};+@if(!PREPASS_PIPELINE) import bevy_pbr::render::pbr_functions::{apply_pbr_lighting, main_pass_post_lighting_processing};++@group(constants::MATERIAL_BIND_GROUP) @binding(100)+var<storage, read> colours: array<vec4<f32>>;++@fragment+fn fragment(+ in: VertexOutput,+ @builtin(front_facing) is_front: bool,+) -> FragmentOutput {+ var pbr_input = pbr_input_from_standard_material(in, is_front);+ let n = arrayLength(&colours);+ let copy = min(get_tag(in.instance_index) >> 2u, max(n, 1u) - 1u);+ let tint = colours[copy];+ pbr_input.material.base_color = vec4(pbr_input.material.base_color.rgb * tint.rgb, pbr_input.material.base_color.a * tint.a);+ pbr_input.material.base_color = alpha_discard(pbr_input.material.flags, pbr_input.material.alpha_cutoff, pbr_input.material.base_color);++@if(PREPASS_PIPELINE) {+ return deferred_output(in, pbr_input);+} @else {+ var out: FragmentOutput;+ out.color = apply_pbr_lighting(pbr_input);+ out.color = main_pass_post_lighting_processing(pbr_input, out.color);+ return out;+}+}