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
R3F22: sdk/r3f runs TSL compute: gl.compute and computeAsync record each ComputeNode as three's own WGSL (its WGSLNodeBuilder against the stand-in renderer), its dispatch size as three's WebGPU backend works it out and its uniforms' values then, and the walk empties them into one Compute part a frame (src/input/tsl-compute.ts: kernels, shared buffers by their attribute's key, the frame's runs in order; epoch, seq, fresh). A node material reading a storage buffer (.element(i), .toAttribute()) reads the same shared buffer by key (tsl-storage.ts, tsl.ts: at most two, tsl_s0 and tsl_s1), and one on an InstancedMesh is compiled for copies: one BufferMesh of the geometry with copies {count, attributes, matrices}, instance_index its own attribute tsl_copy (tsl-instances.ts, scene.ts instancedParts before copyParts). sdk/render: Compute takes {kernels, shared, runs} as keyed columns, BufferMesh takes copies. test/compute.test.tsx 6/6; the parity case in-tsl-particles (65,536 particles a compute swirls, drawn as copies) in test/parity/tsl.tsx and tools/parity.sh
shinyobjectz371751d5ed6b
diff --git a/docs/manual/reference/sdk/3d.md b/docs/manual/reference/sdk/3d.mdindex da6bd848..143105ff 100644--- a/docs/manual/reference/sdk/3d.md+++ b/docs/manual/reference/sdk/3d.md@@ -178,8 +178,6 @@ A compute over the frame, in the 3D beside the camera; several run in the orderRust: `raea_sys_compute::Computes`.-Takes [`ComputeProps`](#computeprops)'s props.-Used in: [shader/compute_shader_game_of_life](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/shader/compute_shader_game_of_life.tsx), [shader_advanced/compute_mesh](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/bench/bevy-parity/shader_advanced/compute_mesh.tsx).### `Cone`@@ -1379,6 +1377,7 @@ The props of [`Body`](#body), tabled there.| `uvs` | `number[]` | u, v of each vertex (without them a picture map is projected onto the mesh's bounds) || `colors` | `number[] \| string[]` | each vertex's colour: r, g, b, a (linear, 0 to 1) per vertex, or one "#rrggbb" per vertex; the material's colour is multiplied by it (Bevy's ATTRIBUTE_COLOR), so leave the material white to see them as given || `attributes` | `Record<string, { size: number; values: number[] }>` | a mesh's own attributes beyond those, for a three.js shader that reads them (<ThreeShaderMaterial>): each one's size (1 to 4 numbers a vertex) and values, per vertex |+| `copies` | `{ count: number; attributes?: Record<string, { size: number; values: number[] }>; matri…` | the mesh repeated `count` times as one, for a three.js node material drawn as copies: each copy's number is its own attribute `tsl_copy`, each of `attributes` (size numbers a copy) is on every vertex of its copy, and `matrices` (16 numbers a copy, column-major) place the copies (none: each where the mesh is) |### `Canvas3DProps`@@ -2543,7 +2542,7 @@ from the first frame.| Field | Type | What it is || --- | --- | --- || `glsl` | `{ vertex: string; fragment: string; raw?: boolean; vertexColors?: boolean }` | a ShaderMaterial's GLSL, its `#include`s expanded and its `defines` as #define lines in front; `raw` for a RawShaderMaterial (which declares three's built-ins itself), `vertexColors` as the material's |-| `wgsl` | `{ vertex: string; fragment: string; uniforms?: { name: string; type: string; array?: nu…` | a node material's WGSL, as three's TSL builder writes it for raea (sdk/r3f's input/tsl.ts): the contract's `three_vertex` and `three_fragment`, its uniforms' types, the mesh attributes it reads beyond the standard four |+| `wgsl` | `{ vertex: string; fragment: string; uniforms?: { name: string; type: string; array?: nu…` | a node material's WGSL, as three's TSL builder writes it for raea (sdk/r3f's input/tsl.ts): the contract's `three_vertex` and `three_fragment`, its uniforms' types, the mesh attributes it reads beyond the standard four, whether it is a lit surface (three_surface), and the storage buffers it reads (`tsl_s0`, `tsl_s1`: each a buffer a <Compute>'s kernels share by key, its size in bytes and first contents) || `uniforms` | `Record<string, ThreeUniform>` | each uniform's value this frame || `textures` | `Record<string, string \| { src: string; colorSpace?: "srgb" \| "linear"; sampler?: Record…` | each sampler's picture: a file, a data URL, "render:NAME" (at most four); `colorSpace: "linear"` for one three samples raw (NoColorSpace: a distance field, a data map), "srgb" (the default) for a colour picture || `output` | `"display" \| "linear"` | "display": its colour is what three's canvas shows (a ShaderMaterial's); "linear": scene light, tone-mapped as the rest of the frame is (a node material's) |diff --git a/docs/manual/reference/sdk/mesh.md b/docs/manual/reference/sdk/mesh.mdindex ca0bae88..b79b4f5c 100644--- a/docs/manual/reference/sdk/mesh.md+++ b/docs/manual/reference/sdk/mesh.md@@ -316,6 +316,7 @@ type Animate3d = Record<string, TrackSpec | TrackSpec[] | Keys> | Move| `uvs` | `number[]` | u, v of each vertex (without them a picture map is projected onto the mesh's bounds) || `colors` | `number[] \| string[]` | each vertex's colour: r, g, b, a (linear, 0 to 1) per vertex, or one "#rrggbb" per vertex; the material's colour is multiplied by it (Bevy's ATTRIBUTE_COLOR), so leave the material white to see them as given || `attributes` | `Record<string, { size: number; values: number[] }>` | a mesh's own attributes beyond those, for a three.js shader that reads them (<ThreeShaderMaterial>): each one's size (1 to 4 numbers a vertex) and values, per vertex |+| `copies` | `{ count: number; attributes?: Record<string, { size: number; values: number[] }>; matri…` | the mesh repeated `count` times as one, for a three.js node material drawn as copies: each copy's number is its own attribute `tsl_copy`, each of `attributes` (size numbers a copy) is on every vertex of its copy, and `matrices` (16 numbers a copy, column-major) place the copies (none: each where the mesh is) |### `Capsule3dProps`diff --git a/sdk/r3f/src/input/material.ts b/sdk/r3f/src/input/material.tsindex 21bbc46f..bae5ff94 100644--- a/sdk/r3f/src/input/material.ts+++ b/sdk/r3f/src/input/material.ts@@ -19,6 +19,9 @@ export interface Part {normals?: boolean;/** a ShadowMaterial: the mesh shows only the shadows falling on it (raea's shadow="catch") */catchShadow?: boolean;+ /** a node material compiled for copies (an InstancedMesh, docs/r3f.feature R3F22): the attributes it reads a copy+ * at a time, each one of its own (tsl-instances.ts puts them on the copies) */+ copies?: { name: string; attribute: THREE.BufferAttribute }[];}const hex = (c: THREE.Color) => "#" + c.getHexString();diff --git a/sdk/r3f/src/input/renderer.ts b/sdk/r3f/src/input/renderer.tsindex c3ea35a1..b4f7953f 100644--- a/sdk/r3f/src/input/renderer.ts+++ b/sdk/r3f/src/input/renderer.ts@@ -3,6 +3,7 @@// Its own module, so a composition's `import "three"` (vanilla.ts) needs nothing of React Three Fiber's.import * as THREE from "three";import { renderInto } from "./targets";+import { Dispatches } from "./tsl-compute";const warned = new Set<string>();export function warnOnce(k: string, why: string) {@@ -30,17 +31,12 @@ export function standInRenderer(): THREE.WebGLRenderer {// state.buffers.depth.setMask): every call does nothing, every flag reads as off (docs/r3f.feature R3F16)const inert = (): unknown => new Proxy(noop, { get: (_, k) => (k === "then" || typeof k !== "string" ? undefined : inert()), apply: () => undefined });const state = { buffers: { color: inert(), depth: inert(), stencil: inert() }, enable: noop, disable: noop, reset: noop, bindTexture: noop, unbindTexture: noop, activeTexture: noop, setBlending: noop, setFlipSided: noop, setCullFace: noop, viewport: noop, scissor: noop, setScissorTest: noop, useProgram: () => false, bindFramebuffer: () => false, drawBuffers: noop, setPolygonOffset: noop, setLineWidth: noop, setMaterial: noop };- // what an app dispatched with gl.compute this frame (TSL's compute nodes), in order: raea runs them as <Compute>s- // once they can be (R3F22); until then each is named once and the scene drawn without it- const dispatched: unknown[] = [];- const compute = (node: unknown) => {- dispatched.push(node);- if (dispatched.length > 4096) dispatched.splice(0, dispatched.length - 4096);- warnOnce("gl.compute", "dispatches a compute raea doesn't run yet: the scene is drawn without what it computes");- };+ // what an app dispatches with gl.compute (TSL's compute nodes), in order: each frame's runs as a <Compute> kernel+ // each, its storage shared with the materials reading it (tsl-compute.ts, docs/r3f.feature R3F22)+ const dispatched = new Dispatches(null);const own = {- compute,- computeAsync: async (node: unknown) => compute(node),+ compute: (nodes: unknown, size?: number | number[] | null) => dispatched.compute(nodes, size),+ computeAsync: async (nodes: unknown, size?: number | number[] | null) => dispatched.compute(nodes, size),__raea: { computes: dispatched },// three's WebGL clip space (a CubeCamera asks, drei's <Environment> with children): raea draws in Bevy's anywaycoordinateSystem: THREE.WebGLCoordinateSystem,diff --git a/sdk/r3f/src/input/scene.ts b/sdk/r3f/src/input/scene.tsindex bf3a6fe6..8be69381 100644--- a/sdk/r3f/src/input/scene.ts+++ b/sdk/r3f/src/input/scene.ts@@ -12,6 +12,8 @@ import { materialOf, type Part, type Props } from "./material";import { isShader, ownAttributes, shaderPart } from "./shader";import { composerEffects, postParts } from "./post";import { classicOf } from "./tsl";+import { dispatchesOf } from "./tsl-compute";+import { nodeInstancedParts } from "./tsl-instances";type V3 = [number, number, number];type Q = [number, number, number, number];@@ -131,6 +133,9 @@ const INSTANCED = new Set(["MeshStandardMaterial", "MeshPhysicalMaterial", "Meshfunction instancedParts(m: THREE.InstancedMesh, name: string, w: Walk, at: Props): Part[] {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 });+ // a node material compiled for copies: one mesh of them, its copies made by the engine (tsl-instances.ts, R3F22)+ const node = surface?.type === "ThreeShaderMaterial" ? nodeInstancedParts(m, name, surface, w, at) : undefined;+ if (node) return node;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 [];@@ -423,5 +428,7 @@ export function convert(scene: THREE.Scene, camera: THREE.Camera, gl: THREE.WebGconst composer = composerEffects(scene);const post = composer.found ? postParts(composer.effects) : { parts: [] as Part[], tone: undefined };const tone = composer.found ? post.tone ?? { type: "ToneMapping", props: { mode: "none" } } : toneOf(gl);- return { parts: [...(cam ? [cam] : []), tone, ...(fog ? [fog] : []), ...sky.parts, ...post.parts, ...w.world, ...drawn], background: sky.background };+ // what the app dispatched with gl.compute since the last frame, run before the cameras draw (tsl-compute.ts, R3F22)+ const computes = dispatchesOf(gl)?.part(time);+ return { parts: [...(cam ? [cam] : []), tone, ...(fog ? [fog] : []), ...sky.parts, ...post.parts, ...(computes ? [computes] : []), ...w.world, ...drawn], background: sky.background };}diff --git a/sdk/r3f/src/input/tsl-compute.ts b/sdk/r3f/src/input/tsl-compute.tsnew file mode 100644index 00000000..30b7f49a--- /dev/null+++ b/sdk/r3f/src/input/tsl-compute.ts@@ -0,0 +1,200 @@+// TSL compute (docs/r3f.feature R3F22): a ComputeNode (`Fn(...)().compute(count)`) an app runs with gl.compute or+// computeAsync is three's own WGSL, which its WGSLNodeBuilder writes against the stand-in renderer (tsl.ts), run by the+// engine as a <Compute> kernel (systems/compute three.rs). Its storage buffers are the engine's shared buffers by+// their attributes' keys (tsl-storage.ts), so the node materials reading them see what it wrote; its uniform groups+// (`object`, `render`) are packed by the engine from each dispatch's values, read as three's node updates leave them+// when it was dispatched (a uniform set in useFrame before gl.compute is that frame's).+//+// The renderer's dispatches are a list (Dispatches, on gl.__raea.computes) the scene's walk empties into one Compute+// part a frame: the kernels so far, their shared buffers, and that frame's runs in the order dispatched. The engine runs+// each frame's runs once, in order, before the cameras draw; a composition with a compute steps every frame from 0+// (runtime/plugins steps()), so a still at frame F has run every frame's. `epoch` is this list's session (a seek back+// makes a new stand-in renderer), `fresh` its first part: the engine resets the buffers to their first contents for it.+import type * as THREE from "three";+import { NodeFrame, type WebGPURenderer } from "three/webgpu";+import type { Part } from "./material";+import { standIn } from "./tsl";+import { isStorage, keyOf, sharedOf, type SharedBuffer, type StorageAttribute } from "./tsl-storage";++/** a ComputeNode as three makes one */+interface ComputeNodeLike {+ isComputeNode?: boolean;+ count: number | null;+ dispatchSize: number | number[] | null;+ workgroupSize: number[];+ version: number;+}++/** a kernel as the engine takes it: three's WGSL (its group 0 bindings as written) and each storage buffer's key */+export interface Kernel {+ wgsl: string;+ buffers: Record<string, string>;+}++/** one dispatch: its kernel, workgroups and uniform values ({group: {field: value}}) */+export type Run = [kernel: number, workgroups: [number, number, number], uniforms: Record<string, Record<string, number | number[]>>];++interface Built {+ version: number;+ id: number;+ kernel: Kernel;+ shared: Record<string, SharedBuffer>;+ updates: unknown[];+ frame: NodeFrame;+ /** each uniform group's fields and how their values are read */+ fields: { group: string; field: string; read: () => unknown }[];+}++type BuilderLike = {+ computeShader: string;+ updateNodes: unknown[];+ build(): void;+ getBindings(): { bindings: { name: string; isNodeUniformsGroup?: boolean; isStorageBuffer?: boolean; uniforms?: { name: string; nodeUniform?: { value: unknown } }[] }[] }[];+ uniforms?: Record<string, { name: string; type: string; node?: { value?: unknown } }[]>;+};++const built = new WeakMap<object, Built>();+let kernels = 0;++/** the workgroups a dispatch runs, as three's WebGPU backend works them out: a count over the workgroup size, past+ * 65,535 groups split into rows */+export function workgroupsOf(node: ComputeNodeLike, size: number | number[] | null | undefined): [number, number, number] {+ const d = size ?? node.dispatchSize ?? node.count;+ if (Array.isArray(d)) return [d[0] ?? 1, d[1] ?? 1, d[2] ?? 1];+ if (typeof d !== "number" || !(d >= 0)) throw new Error("a dispatch with no count or dispatch size (an indirect dispatch raea doesn't run)");+ const per = node.workgroupSize.reduce((a, b) => a * b, 1);+ const n = Math.ceil(d / per);+ return n > 65535 ? [65535, Math.ceil(n / 65535), 1] : [Math.max(1, n), 1, 1];+}++/** three's `@binding( N ) @group( 0 )` as the engine reads a declaration (`@group(0) @binding(N)`) */+const bindings = (src: string) =>+ src.replace(/@binding\(\s*(\d+)\s*\)\s*@group\(\s*(\d+)\s*\)/g, (_all, b: string, g: string) => {+ if (g !== "0") throw new Error(`three's compute binds group ${g} (raea's computes bind group 0)`);+ return `@group(0) @binding(${b})`;+ });++function build(node: ComputeNodeLike): Built {+ const had = built.get(node);+ if (had && had.version === node.version) return had;+ const r = standIn(true);+ const b = (r as unknown as { backend: { createNodeBuilder(n: unknown, r: WebGPURenderer): BuilderLike } }).backend.createNodeBuilder(node, r);+ const errors: string[] = [];+ const err = console.error;+ console.error = (...a: unknown[]) => errors.push(a.map(String).join(" "));+ try {+ b.build();+ } finally {+ console.error = err;+ }+ if (errors.length) throw new Error(`three couldn't build it: ${errors[0]}`);+ const buffers: Record<string, string> = {};+ const shared: Record<string, SharedBuffer> = {};+ for (const u of b.uniforms?.compute ?? []) {+ if (u.type !== "storageBuffer") continue;+ if (!isStorage(u.node?.value)) throw new Error(`storage buffer ${u.name} has no storage attribute raea can share`);+ const a = u.node!.value as StorageAttribute;+ buffers[u.name] = keyOf(a);+ shared[keyOf(a)] = sharedOf(a);+ }+ const fields: Built["fields"] = [];+ for (const g of b.getBindings()) {+ for (const x of g.bindings) {+ if (x.isNodeUniformsGroup) for (const u of x.uniforms ?? []) fields.push({ group: x.name, field: u.name, read: () => u.nodeUniform?.value });+ else if (!x.isStorageBuffer) throw new Error(`binding ${x.name} is a ${(x as object).constructor.name}, which raea's computes don't bind (a texture, a storage texture)`);+ }+ }+ const out: Built = { version: node.version, id: had?.id ?? kernels++, kernel: { wgsl: bindings(b.computeShader), buffers }, shared, updates: b.updateNodes, frame: new NodeFrame(), fields };+ built.set(node, out);+ return out;+}++/** a uniform's value as the engine packs it: a number or a list of numbers */+function plain(v: unknown): number | number[] {+ if (typeof v === "number") return v;+ if (typeof v === "boolean") return v ? 1 : 0;+ const o = v as { isColor?: boolean; r: number; g: number; b: number; isMatrix3?: boolean; isMatrix4?: boolean; toArray?: () => number[] };+ if (o?.isColor) return [o.r, o.g, o.b];+ if (o?.isMatrix3 || o?.isMatrix4) throw new Error("a matrix uniform (raea's computes pack numbers and vectors)");+ if (typeof o?.toArray === "function") return o.toArray();+ throw new Error(`a uniform's value ${String(v)} isn't a number or vector`);+}++/** its uniforms' values now, three's node updates run first (the count, a uniform's onObjectUpdate) */+function valuesOf(k: Built, renderer: unknown): Run[2] {+ const f = k.frame as unknown as Record<string, unknown> & { updateNode(n: unknown): void; frameId: number; renderId: number };+ f.renderer = renderer;+ f.time = performance.now() / 1000;+ f.frameId++;+ f.renderId++;+ for (const n of k.updates) f.updateNode(n);+ const out: Run[2] = {};+ for (const { group, field, read } of k.fields) (out[group] ??= {})[field] = plain(read());+ return out;+}++const warned = new Set<string>();+let epochs = 0;++/** A renderer's dispatches (gl.__raea.computes): compute and computeAsync record each, the walk empties them into one+ * Compute part a frame (part). */+export class Dispatches {+ readonly epoch = epochs++;+ /** the runs since the last part, in the order dispatched */+ readonly runs: Run[] = [];+ private kernels = new Map<number, Kernel>();+ private shared = new Map<string, SharedBuffer>();+ private parts = 0;+ private last?: { time: number; part: Part };++ constructor(private readonly renderer: unknown) {}++ get length(): number {+ return this.runs.length;+ }++ /** gl.compute(node | nodes, dispatchSize?): each node's kernel and its values now; one raea can't run is named once */+ compute(nodes: unknown, size?: number | number[] | null): void {+ for (const node of Array.isArray(nodes) ? nodes : [nodes]) {+ try {+ const n = node as ComputeNodeLike;+ if (!n?.isComputeNode || typeof (n as { build?: unknown }).build !== "function") throw new Error("it isn't a ComputeNode");+ const k = build(n);+ this.kernels.set(k.id, k.kernel);+ for (const [key, b] of Object.entries(k.shared)) if (!this.shared.has(key)) this.shared.set(key, b);+ this.runs.push([k.id, workgroupsOf(n, size), valuesOf(k, this.renderer)]);+ } catch (e) {+ if (!(e instanceof Error)) throw e;+ if (!warned.has(e.message)) {+ warned.add(e.message);+ console.warn(`raea/r3f: gl.compute dispatches a compute raea can't run (${e.message}): the scene is drawn without it`);+ }+ }+ }+ }++ /** this frame's Compute part (none before the first dispatch): the runs since the last, emptied. Asked again at the+ * same time (a frame converted twice), the same part. */+ part(time: number): Part | undefined {+ if (this.last && this.last.time === time) return this.last.part;+ if (!this.kernels.size) return undefined;+ const runs = this.runs.splice(0, this.runs.length);+ const part: Part = {+ type: "Compute",+ props: {+ kernels: Object.fromEntries(this.kernels),+ shared: Object.fromEntries(this.shared),+ runs: { epoch: this.epoch, seq: this.parts, fresh: this.parts === 0, runs },+ },+ };+ this.parts++;+ this.last = { time, part };+ return part;+ }+}++/** the dispatches of a renderer that has them (raea's stand-ins: renderer.ts) */+export function dispatchesOf(gl: THREE.WebGLRenderer | undefined): Dispatches | undefined {+ const d = (gl as unknown as { __raea?: { computes?: unknown } } | undefined)?.__raea?.computes;+ return d instanceof Dispatches ? d : undefined;+}diff --git a/sdk/r3f/src/input/tsl-instances.ts b/sdk/r3f/src/input/tsl-instances.tsnew file mode 100644index 00000000..11c01c68--- /dev/null+++ b/sdk/r3f/src/input/tsl-instances.ts@@ -0,0 +1,74 @@+// A node material on an InstancedMesh (docs/r3f.feature R3F22): one mesh of the copies, which the engine repeats from+// the geometry (systems/three-shader storage.rs: a BufferMesh's `copies`), each copy's number its own attribute+// `tsl_copy` (three's instanceIndex, tsl.ts), its matrix baked into its vertices, and what the material reads a copy at+// a time (instanceColor, a range) on each of the copy's vertices. So 65,536 particles a compute places are one mesh+// and one draw, as three draws them. The copies are made once for each change of the geometry, count, matrices and+// colours; past what one mesh should hold, or for what this doesn't take, scene.ts draws a mesh a copy.+import * as THREE from "three";+import { arraysOf } from "./geometry";+import type { Part, Props } from "./material";+import { ownAttributes } from "./shader";++/** the vertices (triangle corners) one mesh of copies may hold */+export const MAX_CORNERS = 4_000_000;++interface Made {+ key: string;+ mesh: Props;+}+const made = new WeakMap<THREE.InstancedMesh, Made>();+const warned = new Set<string>();++/** whether every copy's matrix is the identity (a fresh InstancedMesh: a compute or positionNode places the copies) */+function identity(a: ArrayLike<number>, n: number): boolean {+ for (let i = 0; i < n; i++) for (let k = 0; k < 16; k++) if (a[i * 16 + k] !== (k % 5 === 0 ? 1 : 0)) return false;+ return true;+}++/** the BufferMesh of the copies: the geometry once, and what the engine repeats it with */+function copiesMesh(m: THREE.InstancedMesh, surface: Part, count: number): Props | undefined {+ const arrays = arraysOf(m.geometry, { flipV: false, colors: false });+ if (!arrays) return undefined;+ const corners = (arrays.indices?.length ?? arrays.positions.length / 3) * count;+ if (corners > MAX_CORNERS) {+ const k = `${m.uuid}`;+ if (!warned.has(k)) {+ warned.add(k);+ console.warn(`raea/r3f: an InstancedMesh of ${count} copies of ${arrays.positions.length / 3} vertices is more than one mesh holds (${MAX_CORNERS} corners): drawn a mesh a copy`);+ }+ return undefined;+ }+ const attributes: Record<string, { size: number; values: number[] }> = {};+ for (const { name, attribute } of surface.copies ?? []) {+ const values: number[] = new Array(count * attribute.itemSize);+ for (let i = 0; i < count; i++) for (let c = 0; c < attribute.itemSize; c++) values[i * attribute.itemSize + c] = attribute.array[i * attribute.itemSize + c];+ attributes[name] = { size: attribute.itemSize, values };+ }+ const copies: Props = { count, ...(Object.keys(attributes).length ? { attributes } : {}) };+ const mats = m.instanceMatrix.array;+ if (!identity(mats, count)) copies.matrices = Array.from(mats.subarray(0, count * 16));+ // the geometry's own attributes a three shader reads (aRandom, aOffset...), each vertex's, repeated with the copies+ const own = surface.props.wgsl && (surface.props.wgsl as { attributes?: string[] }).attributes?.some((a) => m.geometry.getAttribute(a)) ? ownAttributes(m.geometry) : undefined;+ return { ...arrays, ...(own ? { attributes: own } : {}), copies };+}++/** An InstancedMesh whose node material is compiled for copies (tsl.ts) as one mesh of its copies; undefined for+ * anything else (several materials, a GLSL shader, more corners than a mesh holds), which scene.ts draws a mesh a copy. */+export function nodeInstancedParts(m: THREE.InstancedMesh, name: string, surface: Part, w: { shadows: boolean }, at: Props): Part[] | undefined {+ if (!surface.copies || Array.isArray(m.material)) return undefined;+ const count = Math.min(m.count, m.instanceMatrix.count);+ if (count < 1) return [];+ const g = m.geometry;+ const versions = Object.values(g.attributes).map((a) => (a as THREE.BufferAttribute).version).join(",");+ const key = [g.uuid, versions, g.index?.version ?? -1, count, m.instanceMatrix.version, m.instanceColor?.version ?? -1, ...surface.copies.map((c) => `${c.name}:${c.attribute.version}`)].join("|");+ let hit = made.get(m);+ if (hit?.key !== key) {+ const mesh = copiesMesh(m, surface, count);+ if (!mesh) return undefined;+ made.set(m, (hit = { key, mesh }));+ }+ // a copy moved on the GPU (a positionNode, a compute's positions) casts no shadow of where its vertices were+ const moved = (m.material as { positionNode?: unknown }).positionNode != null;+ const { copies: _per, ...own } = surface;+ return [{ type: "Mesh", props: { name, ...at, castShadow: w.shadows && m.castShadow && !moved, receiveShadow: m.receiveShadow }, children: [{ type: "BufferMesh", props: hit.mesh }, own] }];+}diff --git a/sdk/r3f/src/input/tsl-storage.ts b/sdk/r3f/src/input/tsl-storage.tsnew file mode 100644index 00000000..b9f794c8--- /dev/null+++ b/sdk/r3f/src/input/tsl-storage.ts@@ -0,0 +1,95 @@+// TSL storage buffers (docs/r3f.feature R3F22): an `instancedArray`, `attributeArray` or `storage` attribute is one+// buffer the engine keeps from frame to frame, shared by key between the computes that write it (tsl-compute.ts) and+// the node materials that read it (tsl.ts): `.element(i)` in a material is a storage binding, `.toAttribute()` a+// vertex attribute three makes of it, which raea reads from the same buffer at the copy being drawn. The engine binds+// a material's buffers as `tsl_s0` and `tsl_s1` (systems/three-shader storage.rs) and a compute's under the names+// three gave them (systems/compute three.rs), each by its key.+import type * as THREE from "three";++/** a storage attribute as three makes one (StorageBufferAttribute, StorageInstancedBufferAttribute) */+export interface StorageAttribute {+ array: Float32Array | Uint32Array | Int32Array;+ itemSize: number;+ count: number;+ isStorageBufferAttribute?: boolean;+ isStorageInstancedBufferAttribute?: boolean;+}++/** a shared buffer as the engine makes it: its size in bytes and first contents, in WGSL's storage layout */+export interface SharedBuffer {+ size: number;+ f32?: number[];+ u32?: number[];+ i32?: number[];+}++/** the storage buffers a material reads (the engine's two) */+export const MATERIAL_STORAGE = 2;++const keys = new WeakMap<object, string>();+let next = 0;++/** a storage attribute's key: one buffer however many graphs read or write it */+export function keyOf(a: object): string {+ let k = keys.get(a);+ if (!k) keys.set(a, (k = `tsl:${next++}`));+ return k;+}++export const isStorage = (a: unknown): a is StorageAttribute => !!a && ((a as StorageAttribute).isStorageBufferAttribute === true || (a as StorageAttribute).isStorageInstancedBufferAttribute === true);++const scalar = (a: StorageAttribute) => (a.array instanceof Uint32Array ? "u32" : a.array instanceof Int32Array ? "i32" : "f32");++/** an element's WGSL type: f32, u32 or i32, or a vec2-4 of one */+export function elementType(a: StorageAttribute): string {+ const s = scalar(a);+ if (a.itemSize === 1) return s;+ if (a.itemSize >= 2 && a.itemSize <= 4) return `vec${a.itemSize}<${s}>`;+ throw new Error(`a storage buffer of ${a.itemSize} numbers an element (raea's take 1 to 4)`);+}++/** an element's words in storage: a vec3 takes four, as WGSL's `array<vec3<f32>>` strides 16 bytes */+const strideOf = (itemSize: number) => (itemSize === 3 ? 4 : itemSize);++/** the buffer the engine makes for a storage attribute: its contents only when any is set (three's are zeros at first) */+export function sharedOf(a: StorageAttribute): SharedBuffer {+ elementType(a);+ const stride = strideOf(a.itemSize);+ const size = Math.max(1, a.count) * stride * 4;+ if (!a.array.some((x) => x !== 0)) return { size };+ const words: number[] = new Array(Math.max(1, a.count) * stride).fill(0);+ for (let i = 0; i < a.count; i++) for (let c = 0; c < a.itemSize; c++) words[i * stride + c] = a.array[i * a.itemSize + c];+ return { size, [scalar(a)]: words };+}++/** the storage buffers a node material reads, in the order the engine binds them (tsl_s0, tsl_s1) */+export class MaterialStorage {+ readonly list: { key: string; attribute: StorageAttribute }[] = [];++ /** the WGSL name of a storage attribute's buffer, added if it's new */+ name(a: StorageAttribute): string {+ const key = keyOf(a);+ let i = this.list.findIndex((s) => s.key === key);+ if (i < 0) {+ if (this.list.length === MATERIAL_STORAGE) throw new Error(`it reads more than ${MATERIAL_STORAGE} storage buffers`);+ i = this.list.push({ key, attribute: a }) - 1;+ }+ return `tsl_s${i}`;+ }++ /** the spec's `storage`: each buffer's name, key, size and first contents */+ spec(): ({ name: string; key: string } & SharedBuffer)[] {+ return this.list.map((s, i) => ({ name: `tsl_s${i}`, key: s.key, ...sharedOf(s.attribute) }));+ }+}++/** a stage's own declaration of a storage buffer it reads but three didn't declare in it (a `.toAttribute()` read) */+export function declaration(name: string, a: StorageAttribute): string {+ return `struct ${name}Struct {\n\tvalue : array< ${elementType(a)} >\n};\nvar<storage, read> ${name} : ${name}Struct;\n`;+}++/** an attribute a copy at a time that three made of a storage attribute (`.toAttribute()`): its storage attribute */+export function storageOfAttribute(node: { value?: unknown } | undefined): StorageAttribute | undefined {+ const v = node?.value as (THREE.BufferAttribute & StorageAttribute) | undefined;+ return isStorage(v) ? v : undefined;+}diff --git a/sdk/r3f/src/input/tsl.ts b/sdk/r3f/src/input/tsl.tsindex 646c8c8d..315d2ad8 100644--- a/sdk/r3f/src/input/tsl.ts+++ b/sdk/r3f/src/input/tsl.ts@@ -10,14 +10,19 @@// three_model(instance), so Bevy's own camera and transform place it (Bevy's projection is reverse-Z). Every other// uniform takes the value three's own node updates give it this frame (time from R3F's clock, a light's colour), so a// uniform the scene animates in useFrame moves with it. A uniformArray is packed element by element and read as-// u_NAME(i); a vertex attribute of the mesh's own is one of the contract's a0..a3. A graph this can't carry (more than 4-// textures or 4 attributes of the mesh's own, a storage buffer, a render target) is refused with the reason, and the-// material is drawn flat as before.+// u_NAME(i); a vertex attribute of the mesh's own is one of the contract's a0..a3. A storage buffer it reads+// (`.element(i)`, `.toAttribute()`) is the engine's shared buffer by its attribute's key (tsl-storage.ts, R3F22). On an+// InstancedMesh it is compiled for copies (R3F22): three built with no uniform room, so the copies' matrices and+// colours are attributes; the engine draws one mesh of the copies, instance_index the copy's number (`tsl_copy`, its+// own attribute a0), the matrices identity (the engine bakes them into the copies) and any other attribute a copy at a+// time the copy's own. A graph this can't carry (more than 4 textures or 4 attributes of the mesh's own, more than 2+// storage buffers, a render target) is refused with the reason, and the material is drawn flat as before.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";+import { MaterialStorage, declaration, elementType, isStorage, storageOfAttribute, type SharedBuffer, type StorageAttribute } from "./tsl-storage";/** what a node material is drawn for this frame: the object it's on, its scene and camera, R3F's clock */export interface NodeAt {@@ -68,6 +73,10 @@ interface Builder {updateAfterNodes: AnyNode[];build(): void;getBindings(): { name: string; bindings: BindingLike[] }[];+ /** each stage's uniforms, a storage buffer's among them (its WGSL name, type "storageBuffer", its node's attribute) */+ uniforms?: Record<string, { name: string; type: string; node?: { value?: unknown } }[]>;+ /** the attributes three made itself (an InstancedMesh's matrices and colours, a `.toAttribute()`), by WGSL name */+ bufferAttributes?: { name: string; type: string; node?: { value?: unknown; bufferOffset?: number } }[];}/** a refusal: what the graph needs that the engine's contract doesn't carry */@@ -78,7 +87,7 @@ export class Unsupported extends Error {}let renderer: WebGPURenderer | undefined;/** three's WebGPURenderer, never initialised: WGSLNodeBuilder reads its node library and asks it what the GPU can do */-function standIn(fresh = false): WebGPURenderer {+export function standIn(fresh = false): WebGPURenderer {if (renderer && !fresh) return renderer;const noop = () => {};const canvas = { style: {}, width: 1, height: 1, addEventListener: noop, removeEventListener: noop, getContext: () => null };@@ -109,6 +118,10 @@ interface Compiled {textures: { name: string; texture: THREE.Texture }[];/** the mesh's own attributes it reads, in order (the contract's a0..a3) */attributes: string[];+ /** the storage buffers it reads (tsl_s0, tsl_s1), and the spec's list of them, made once */+ storage: ({ name: string; key: string } & SharedBuffer)[];+ /** compiled for copies (an InstancedMesh): the attributes it reads a copy at a time, each one of its own */+ copies?: { name: string; attribute: THREE.BufferAttribute }[];lit: boolean; // a surface Bevy lights (tsl-lit.ts), not a colourframe: NodeFrame;}@@ -118,9 +131,12 @@ const compiled = new WeakMap<THREE.Material, Compiled>();/** what a compile depends on beyond the material: the geometry's attributes (a graph reads the ones it has) */function keyOf(m: THREE.Material, o: THREE.Object3D): string {const g = (o as THREE.Mesh).geometry as THREE.BufferGeometry | undefined;- return `${m.version}|${g ? Object.keys(g.attributes).sort().join(",") : ""}|${(o as THREE.InstancedMesh).isInstancedMesh ? "i" : ""}`;+ return `${m.version}|${g ? Object.keys(g.attributes).sort().join(",") : ""}|${copiesOf(o) ? "c" : ""}|${(o as THREE.InstancedMesh).instanceColor ? "k" : ""}`;}+/** whether an object draws its material as copies (R3F22): an InstancedMesh */+export const copiesOf = (o: THREE.Object3D) => (o as THREE.InstancedMesh).isInstancedMesh === true;+function compile(m: THREE.Material, at: NodeAt): Compiled {const key = keyOf(m, at.object);const had = compiled.get(m);@@ -128,6 +144,9 @@ function compile(m: THREE.Material, at: NodeAt): Compiled {// a renderer of its own: three caches a shared group's binding (render, frame) per renderer, with the uniforms of// whichever material built it firstconst r = standIn(true);+ // copies: no uniform room, so three reads an InstancedMesh's matrices and colours as attributes a copy at a time+ const copies = copiesOf(at.object);+ if (copies) ((r as unknown as { backend: { device: { limits: Record<string, number> } } }).backend.device.limits.maxUniformBufferBindingSize = 0);const b = (r as unknown as { backend: { createNodeBuilder(o: THREE.Object3D, r: WebGPURenderer): Builder } }).backend.createNodeBuilder(at.object, r);b.scene = at.scene;b.camera = at.camera;@@ -147,7 +166,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 c = rewrite(b, copies ? (at.object as THREE.InstancedMesh) : undefined);const out: Compiled = { key, builder: b, ...c, ...(lit ? litStages(c.vertex, c.fragment) : {}), lit, frame: new NodeFrame() };compiled.set(m, out);return out;@@ -240,7 +259,7 @@ const STORED: Record<string, string> = {"mat3x3<f32>": "mat3x3<f32>", "mat4x4<f32>": "mat4x4<f32>",};-function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"> {+function rewrite(b: Builder, copies?: THREE.InstancedMesh): Omit<Compiled, "key" | "builder" | "frame" | "lit"> {let vertex = b.vertexShader;let fragment = b.fragmentShader;const groups = b.getBindings();@@ -255,6 +274,8 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"const flipped = new Set<string>();/** a uniformArray's buffer: three's WGSL name for it, and the packed uniform it reads as */const buffers: { wgsl: string; name: string }[] = [];+ /** the storage buffers it reads, by the engine's names for them (tsl_s0, tsl_s1) */+ const storage = new MaterialStorage();let slots = 0;for (const g of groups) {for (const x of g.bindings) {@@ -305,11 +326,21 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"uniforms.push({ name, type, array: n.array.length, read: () => n.array, stored: "f32" });slots += slotsOf(type, n.array.length);buffers.push({ wgsl: `NodeBuffer_${n.id}`, name });- } else throw new Unsupported(`binding ${x.name} is a ${x.isStorageBuffer ? "storage buffer" : x.isBuffer ? "uniform array (uniformArray)" : (x as object).constructor.name}, which raea's shaders don't carry`);+ } else if (x.isStorageBuffer) {+ // a storage buffer (`.element(i)`): the engine's buffer shared by its attribute's key (R3F22), named below+ if (!isStorage((x as unknown as { attribute?: unknown }).attribute)) throw new Unsupported(`storage buffer ${x.name} has no storage attribute raea can share`);+ } else throw new Unsupported(`binding ${x.name} is a ${x.isBuffer ? "uniform array (uniformArray)" : (x as object).constructor.name}, which raea's shaders don't carry`);}}if (slots > SLOTS) throw new Unsupported(`its uniforms take ${slots} vec4 slots, more than raea's ${SLOTS}`);if (textures.length > TEXTURES) throw new Unsupported(`it samples ${textures.length} textures, more than raea's ${TEXTURES}`);+ // each storage buffer's WGSL name (three's NodeBuffer_N, a stage's uniform of type storageBuffer) as the engine's+ const storageNames = new Map<string, string>();+ for (const stage of ["vertex", "fragment"]) {+ for (const u of b.uniforms?.[stage] ?? []) if (u.type === "storageBuffer" && isStorage(u.node?.value)) storageNames.set(u.name, storage.name(u.node!.value as StorageAttribute));+ }+ /** the storage buffers each stage declares */+ const declared = { vertex: new Set<string>(), fragment: new Set<string>() };const common = (src: string, stage: "vertex" | "fragment") => {let s = src.replace(/^\s*diagnostic\s*\([^)]*\)\s*;\s*$/gm, "");@@ -317,8 +348,15 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"const groupTypes = new Set<string>();s = s.replace(/@binding\(\s*\d+\s*\)\s*@group\(\s*\d+\s*\)\s*var(?:<[^>]*>)?\s+(\w+)\s*:\s*([^;]+);/g, (_all, name: string, type: string) => {if (members.has(name)) groupTypes.add(type.trim());+ // a storage buffer stays, read-only and unbound: the engine binds tsl_sN (three-shader storage.rs)+ const st = storageNames.get(name);+ if (st && !declared[stage].has(st)) {+ declared[stage].add(st);+ return `var<storage, read> ${st} : ${type.trim()};`;+ }return "";});+ for (const [from, to] of storageNames) s = word(s, from, to);for (const b of buffers) {s = s.replace(new RegExp(`struct\\s+${b.wgsl}Struct\\s*\\{[^}]*\\};?`, "g"), "");s = s.replace(new RegExp(`var<uniform>\\s+${b.wgsl}\\s*:[^;]*;`, "g"), "");@@ -341,17 +379,51 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"if (!ve) throw new Unsupported("three's vertex stage has no main returning its varyings");const vlets: string[] = ["\ttsl_instance = v.instance;"];const own: string[] = [];+ /** drawn as copies: the copy's number is its own attribute a0; the attributes it reads a copy at a time */+ const perCopy: { name: string; attribute: THREE.BufferAttribute }[] = [];+ if (copies) {+ own.push("tsl_copy");+ vlets.push("\tlet tsl_copy = u32(v.a0.x);");+ }+ /** the storage buffers the vertex stage reads that three didn't declare in it (`.toAttribute()`) */+ const extra: string[] = [];for (const p of params(ve[1])) {- if (p.builtin === "instance_index") vlets.push(`\tlet ${p.name} = v.instance;`);+ // three's instance: the copy, or 0 for a mesh drawn once (Bevy's instance index is its place in a batch)+ if (p.builtin === "instance_index") vlets.push(`\tlet ${p.name} = ${copies ? "tsl_copy" : "0u"};`);else if (p.location !== undefined) {const a = ATTRIBUTES[p.name];+ const made = b.bufferAttributes?.find((x) => x.name === p.name)?.node;+ const sa = storageOfAttribute(made);+ const mv = made?.value as { array?: unknown; isInstancedBufferAttribute?: boolean; isInstancedInterleavedBuffer?: boolean } | undefined;if (a) vlets.push(`\tlet ${p.name} = ${fit(`v.${a.field}`, a.type, p.type)};`);- else {- // an attribute three made itself or one a copy at a time (an InstancedMesh's matrices past a uniform buffer's- // worth of copies, `nodeAttribute0`; an InstancedBufferAttribute): the mesh raea draws carries per-vertex- // attributes only, so the graph can't run here yet (R3F16; R3F20/R3F22 bring instance data)+ else if (sa) {+ // `.toAttribute()` of a storage buffer: the shared buffer read at the copy being drawn+ if (!sa.isStorageInstancedBufferAttribute) throw new Unsupported(`it reads ${p.name}, a storage buffer a vertex at a time (raea reads one a copy at a time)`);+ const name = storage.name(sa);+ if (!declared.vertex.has(name)) {+ declared.vertex.add(name);+ extra.push(declaration(name, sa));+ }+ vlets.push(`\tlet ${p.name} = ${fit(`${name}.value[${copies ? "tsl_copy" : "0u"}]`, elementType(sa), p.type)};`);+ } else if (copies && mv && mv.array === copies.instanceMatrix.array) {+ // a column of the copy's matrix: identity, as the engine bakes each copy's matrix into its vertices+ const col = Math.round((made?.bufferOffset ?? 0) / 4);+ vlets.push(`\tlet ${p.name} = vec4<f32>(${[0, 1, 2, 3].map((i) => (i === col ? "1.0" : "0.0")).join(", ")});`);+ } else if (copies && mv?.isInstancedBufferAttribute) {+ // instanceColor or another attribute a copy at a time: one of the copy's own, which the engine puts on each of+ // the copy's vertices+ const attr = mv as unknown as THREE.BufferAttribute;+ // (three wraps instanceColor and a geometry's own in attributes of its own over the same array)+ const name = attr.array === copies.instanceColor?.array ? "instanceColor" : (Object.entries(copies.geometry.attributes).find(([, x]) => (x as THREE.BufferAttribute).array === attr.array)?.[0] ?? `copy_${p.name}`);+ if (own.length === ATTRIBUTES_OWN) throw new Unsupported(`it reads more than ${ATTRIBUTES_OWN} vertex attributes of the mesh's own (${[...own, name].join(", ")})`);+ vlets.push(`\tlet ${p.name} = ${fit(`v.a${own.length}`, "vec4<f32>", p.type)};`);+ own.push(name);+ perCopy.push({ name, attribute: attr });+ } else {+ // an attribute three made itself, or one a copy at a time on a mesh not drawn as copies: the mesh raea draws+ // carries per-vertex attributes only (R3F16)const ga = (b as unknown as { geometry?: THREE.BufferGeometry }).geometry?.getAttribute(p.name) as (THREE.BufferAttribute & { isInstancedBufferAttribute?: boolean; isInterleavedBufferAttribute?: boolean; data?: { isInstancedInterleavedBuffer?: boolean } }) | undefined;- if (!ga) throw new Unsupported(`it reads ${p.name}, an attribute three makes for itself (an InstancedMesh's copies past what a uniform buffer holds)`);+ if (!ga) throw new Unsupported(`it reads ${p.name}, an attribute three makes for itself`);if (ga.isInstancedBufferAttribute || ga.data?.isInstancedInterleavedBuffer) throw new Unsupported(`it reads ${p.name}, an attribute a copy at a time`);// one of the mesh's own (lettra's layoutX, glyphIndex, cellUv): a0..a3, four floats eachif (own.length === ATTRIBUTES_OWN) throw new Unsupported(`it reads more than ${ATTRIBUTES_OWN} vertex attributes of the mesh's own (${[...own, p.name].join(", ")})`);@@ -361,7 +433,7 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"} else throw new Unsupported(`its vertex stage reads the builtin ${p.builtin}`);}vertex = vertex.replace(ve[0], `fn three_vertex(v: ThreeVertex) -> ThreeVaryings {\n${vlets.join("\n")}\n`);- vertex = "var<private> tsl_instance : u32;\n" + (flipped.size ? FLIP : "") + vertex;+ vertex = "var<private> tsl_instance : u32;\n" + extra.join("") + (flipped.size ? FLIP : "") + vertex;const varyings = vertex.match(/struct\s+ThreeVaryings\s*\{[^}]*\};?/)?.[0];if (!varyings) throw new Unsupported("three's vertex stage declares no varyings");@@ -383,7 +455,7 @@ function rewrite(b: Builder): Omit<Compiled, "key" | "builder" | "frame" | "lit"fragment = fragment.replace(/return\s+(\w+)\s*;/g, (all, v: string) => (fragment.includes(`var<private> ${v} : ${fe[2]}`) ? `return ${v}.${colour};` : all));fragment = varyings + "\n" + (flipped.size ? FLIP : "") + fragment;- return { vertex, fragment, uniforms, textures, attributes: own };+ return { vertex, fragment, uniforms, textures, attributes: own, storage: storage.spec(), ...(copies ? { copies: perCopy } : {}) };}/** each `name[ EXPR ]` in `src` (EXPR to its own closing bracket) as `to(EXPR)` */@@ -463,7 +535,7 @@ export function nodeMaterialOf(m: THREE.Material, at: NodeAt): Part | undefinedconst 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 } : {}), ...(c.lit ? { lit: true } : {}) },+ wgsl: { vertex: c.vertex, fragment: c.fragment, uniforms: vals.map(({ name, type, array }) => ({ name, type, ...(array ? { array } : {}) })), ...(c.attributes.length ? { attributes: c.attributes } : {}), ...(c.storage.length ? { storage: c.storage } : {}), ...(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" }])),@@ -475,7 +547,7 @@ export function nodeMaterialOf(m: THREE.Material, at: NodeAt): Part | undefinedblending: m.blending === THREE.AdditiveBlending ? "add" : m.blending === THREE.MultiplyBlending ? "multiply" : m.blending === THREE.NoBlending ? "none" : "normal",};if (m.alphaTest > 0) props.alphaTest = m.alphaTest;- return { type: "ThreeShaderMaterial", props };+ return { type: "ThreeShaderMaterial", props, ...(c.copies ? { copies: c.copies } : {}) };} catch (e) {// a graph three itself can't build against the stand-in (what it asks of a GPU raea hasn't answered) is named and drawn// flat, as a refused one is: never the whole render refused for one material (docs/r3f.feature R3F16)diff --git a/sdk/r3f/src/parts.tsx b/sdk/r3f/src/parts.tsxindex 1c2cd750..f73dd776 100644--- a/sdk/r3f/src/parts.tsx+++ b/sdk/r3f/src/parts.tsx@@ -3,7 +3,7 @@// components.import type { ReactNode } from "react";import {- AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, DepthOfField, Environment, Fog, Gizmo, Grade, Instances, LensDistortion, Look, RichText, ToneMapping,+ AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, Environment, Fog, Gizmo, Grade, Instances, LensDistortion, Look, RichText, ToneMapping,} from "raea/3d";import {AmbientLight, DirectionalLight, Group, Mesh, MeshBasicMaterial, MeshPhysicalMaterial, MeshStandardMaterial,@@ -16,7 +16,7 @@ export type { Part, Props } from "./input/material";/** every component a Part may name */// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const COMPONENTS: Record<string, (p: any) => ReactNode> = {- AmbientLight, AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, DepthOfField, DirectionalLight, Environment, Fog, Gizmo, Grade, Group, Instances,+ AmbientLight, AmbientOcclusion, AntiAliasing, Bloom, BufferMesh, Compute, DepthOfField, DirectionalLight, Environment, Fog, Gizmo, Grade, Group, Instances,LensDistortion, Look, Mesh, MeshBasicMaterial,MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, OrthographicCamera, PerspectiveCamera, PointLight,RectAreaLight, RichText, SpotLight, ThreeShaderMaterial, ToneMapping,diff --git a/sdk/r3f/test/compute.test.tsx b/sdk/r3f/test/compute.test.tsxnew file mode 100644index 00000000..0847bafc--- /dev/null+++ b/sdk/r3f/test/compute.test.tsx@@ -0,0 +1,169 @@+// TSL compute and storage buffers (docs/r3f.feature R3F22): gl.compute's dispatches as one Compute part a frame (three's+// own WGSL a kernel, its storage buffer shared by key, the runs in order with their uniforms then), and a node+// material reading the buffer on an InstancedMesh as one mesh of copies (src/input/tsl-compute.ts, tsl-storage.ts,+// tsl-instances.ts, tsl.ts).+import { describe, expect, test } from "bun:test";+import { useFrame } from "@react-three/fiber";+import { useRef, type ReactNode } from "react";+import * as THREE from "three";+import { MeshBasicNodeMaterial } from "three/webgpu";+import * as TSLTyped from "three/tsl";+import { convert } from "../src/input/scene";+import { end, stepTo } from "../src/input/session";+import { workgroupsOf } from "../src/input/tsl-compute";+import type { Part } from "../src/parts";+import { TSL_INPUTS } from "./parity/tsl";++// untyped: @types/three's chained TSL types make tsc take minutes and gigabytes+const { Fn, color, float, instanceIndex, instancedArray, positionLocal, uniform, vec3 } = TSLTyped as unknown as Record<string, any>;++const flat = (parts: Part[]): Part[] => parts.flatMap((p) => [p, ...flat(p.children ?? [])]);+const COUNT = 4096;++/** a buffer of positions, set by one compute on the first frame and moved by another every frame */+function particles() {+ const pos = instancedArray(COUNT, "vec3");+ const speed = uniform(0.5);+ const init = Fn(() => {+ pos.element(instanceIndex).assign(vec3(float(instanceIndex).mul(0.001), 0, 0));+ })().compute(COUNT);+ const update = Fn(() => {+ const p = pos.element(instanceIndex);+ p.assign(p.add(vec3(0, speed, 0)));+ })().compute(COUNT);+ return { pos, speed, init, update };+}++function Dispatch({ p, children }: { p: ReturnType<typeof particles>; children: ReactNode }) {+ const started = useRef(false);+ useFrame(({ gl }) => {+ const g = gl as unknown as { compute(n: unknown): void };+ if (!started.current) g.compute(p.init);+ started.current = true;+ g.compute(p.update);+ });+ return <>{children}</>;+}++let n = 0;+function frames(scene: () => ReactNode, last: number) {+ const key = `c${n++}`;+ const out: Part[][] = [];+ for (let f = 0; f <= last; f++) {+ const s = stepTo(key, f, 24, 320, 180, {}, scene);+ const st = s.state as unknown as { scene: THREE.Scene; camera: THREE.Camera; gl: THREE.WebGLRenderer };+ out.push(flat(convert(st.scene, st.camera, st.gl, 180, f / 24, 1 / 24).parts));+ }+ end(key);+ return out;+}++type ComputeProps = { kernels: Record<string, { wgsl: string; buffers: Record<string, string> }>; shared: Record<string, { size: number }>; runs: { epoch: number; seq: number; fresh: boolean; runs: [number, number[], Record<string, Record<string, number | number[]>>][] } };++describe("TSL compute", () => {+ test("each dispatch is three's WGSL as a kernel, its buffer shared by key, run in order with its uniforms then", () => {+ const p = particles();+ const [f0, f1] = frames(() => <Dispatch p={p}><group /></Dispatch>, 1);+ const c0 = f0.find((x) => x.type === "Compute")?.props as ComputeProps;+ expect(c0).toBeDefined();+ expect(Object.keys(c0.kernels)).toHaveLength(2);+ const [init, update] = c0.runs.runs;+ expect(c0.runs.fresh).toBe(true);+ expect([init[1], update[1]]).toEqual([[64, 1, 1], [64, 1, 1]]);+ const k = c0.kernels[String(update[0])];+ expect(k.wgsl).toMatch(/@group\(0\) @binding\(0\)\s*var<storage, read_write> NodeBuffer_\d+/);+ expect(k.wgsl).toContain("@compute");+ // both kernels write the one buffer: 4,096 vec3s, 16 bytes each in storage+ const keys = Object.values(c0.kernels).flatMap((x) => Object.values(x.buffers));+ expect(new Set(keys).size).toBe(1);+ expect(c0.shared[keys[0]].size).toBe(COUNT * 16);+ // its uniforms as three's node updates left them: the speed and the count+ expect(Object.values(update[2].object)).toEqual(expect.arrayContaining([0.5, COUNT]));+ // the next frame: only its own dispatch, the same session, not fresh+ const c1 = f1.find((x) => x.type === "Compute")?.props as ComputeProps;+ expect(c1.runs.runs.map((r) => r[0])).toEqual([update[0]]);+ expect([c1.runs.epoch, c1.runs.seq, c1.runs.fresh]).toEqual([c0.runs.epoch, 1, false]);+ });++ test("three's dispatch size: a count over the workgroup, past 65,535 groups in rows; a size given as it is", () => {+ const node = { count: 1000, dispatchSize: null, workgroupSize: [64], version: 1 };+ expect(workgroupsOf(node, undefined)).toEqual([16, 1, 1]);+ expect(workgroupsOf({ ...node, count: 64 * 65535 * 2 }, undefined)).toEqual([65535, 2, 1]);+ expect(workgroupsOf(node, [4, 4])).toEqual([4, 4, 1]);+ });++ test("a node material reading the buffer (.toAttribute()) on an InstancedMesh is one mesh of copies, its storage the compute's", () => {+ const p = particles();+ const m = new MeshBasicNodeMaterial();+ m.positionNode = positionLocal.add(p.pos.toAttribute());+ m.colorNode = color(1, 0.5, 0.2);+ const geo = new THREE.PlaneGeometry(0.05, 0.05);+ const [f0] = frames(() => <Dispatch p={p}><instancedMesh args={[geo, m, COUNT]} /></Dispatch>, 0);+ const c0 = f0.find((x) => x.type === "Compute")!.props as ComputeProps;+ const key = Object.values(Object.values(c0.kernels)[0].buffers)[0];+ const mesh = f0.find((x) => x.type === "Mesh" && x.children?.[1]?.type === "ThreeShaderMaterial")!;+ expect(mesh).toBeDefined();+ const buf = mesh.children![0].props as { positions: number[]; copies: { count: number; matrices?: number[] } };+ // the geometry once (a quad), repeated by the engine; its copies all where the mesh is+ expect(buf.positions).toHaveLength(12);+ expect(buf.copies.count).toBe(COUNT);+ expect(buf.copies.matrices).toBeUndefined();+ const wgsl = mesh.children![1].props.wgsl as { vertex: string; attributes: string[]; storage: { name: string; key: string; size: number }[] };+ expect(wgsl.storage).toEqual([{ name: "tsl_s0", key, size: COUNT * 16 }]);+ expect(wgsl.attributes[0]).toBe("tsl_copy");+ expect(wgsl.vertex).toContain("let tsl_copy = u32(v.a0.x);");+ expect(wgsl.vertex).toMatch(/var<storage, read> tsl_s0 : tsl_s0Struct;/);+ expect(wgsl.vertex).toMatch(/= tsl_s0\.value\[tsl_copy\];/);+ // the copy's matrix is the identity: the engine bakes the copies' matrices into their vertices+ expect(wgsl.vertex).toContain("vec4<f32>(1.0, 0.0, 0.0, 0.0)");+ // moved on the GPU: no shadow of where its vertices were+ expect(mesh.props.castShadow).toBe(false);+ });++ test(".element(instanceIndex) in both stages reads the shared buffer read-only; instanceColor and the matrices go with the copies", () => {+ const p = particles();+ const m = new MeshBasicNodeMaterial();+ m.positionNode = positionLocal.mul(0.05).add(p.pos.element(instanceIndex));+ m.colorNode = color(1, 0.6, 0.2).mul(p.pos.element(instanceIndex).y.mul(0.5).add(0.5));+ const geo = new THREE.PlaneGeometry(1, 1);+ const im = new THREE.InstancedMesh(geo, m, 8);+ for (let i = 0; i < 8; i++) {+ im.setMatrixAt(i, new THREE.Matrix4().makeTranslation(i, 0, 0));+ im.setColorAt(i, new THREE.Color(i / 8, 0, 0));+ }+ const [f0] = frames(() => <Dispatch p={p}><primitive object={im} /></Dispatch>, 0);+ const mesh = f0.find((x) => x.type === "Mesh" && x.children?.[1]?.type === "ThreeShaderMaterial")!;+ const wgsl = mesh.children![1].props.wgsl as { vertex: string; fragment: string; attributes: string[]; storage: { name: string }[] };+ expect(wgsl.storage.map((s) => s.name)).toEqual(["tsl_s0"]);+ expect(wgsl.vertex).toMatch(/var<storage, read> tsl_s0 : NodeBuffer_\d+Struct;/);+ expect(wgsl.fragment).toMatch(/var<storage, read> tsl_s0 : NodeBuffer_\d+Struct;/);+ expect(wgsl.vertex).not.toMatch(/NodeBuffer_\d+\.value/);+ expect(wgsl.attributes).toEqual(["tsl_copy", "instanceColor"]);+ const copies = (mesh.children![0].props as { copies: { count: number; attributes: Record<string, { size: number; values: number[] }>; matrices: number[] } }).copies;+ expect(copies.attributes.instanceColor.size).toBe(3);+ expect(copies.attributes.instanceColor.values[3 * 4]).toBeCloseTo(0.5, 6);+ expect(copies.matrices).toHaveLength(8 * 16);+ expect(copies.matrices[16 * 3 + 12]).toBe(3);+ });++ test("the parity swirl: two buffers both computes write and the copies' material reads, a frame's update once", () => {+ const [f0, f1, f2] = frames(TSL_INPUTS["tsl-particles"].scene, 2);+ const c0 = f0.find((x) => x.type === "Compute")!.props as ComputeProps;+ expect(c0.runs.runs.map((r) => r[1])).toEqual([[1024, 1, 1], [1024, 1, 1]]);+ expect(Object.keys(c0.shared)).toHaveLength(2);+ const mesh = f0.find((x) => x.type === "Mesh" && x.children?.[1]?.type === "ThreeShaderMaterial")!;+ const m = mesh.children![1].props as { wgsl: { storage: { key: string }[]; vertex: string }; blending: string };+ expect(m.wgsl.storage.map((s) => s.key).sort()).toEqual(Object.keys(c0.shared).sort());+ expect((mesh.children![0].props as { copies: { count: number } }).copies.count).toBe(65536);+ for (const f of [f1, f2]) expect((f.find((x) => x.type === "Compute")!.props as ComputeProps).runs.runs).toHaveLength(1);+ });++ test("a mesh drawn once reads instance 0 (Bevy's instance index is its place in a batch)", () => {+ const p = particles();+ const m = new MeshBasicNodeMaterial();+ m.positionNode = positionLocal.add(p.pos.element(instanceIndex));+ const [f0] = frames(() => <Dispatch p={p}><mesh material={m}><planeGeometry /></mesh></Dispatch>, 0);+ const wgsl = f0.find((x) => x.type === "ThreeShaderMaterial")!.props.wgsl as { vertex: string };+ expect(wgsl.vertex).toMatch(/let instanceIndex = 0u;/);+ });+});diff --git a/sdk/r3f/test/errors.test.tsx b/sdk/r3f/test/errors.test.tsxindex 106f9778..e8cb0eab 100644--- a/sdk/r3f/test/errors.test.tsx+++ b/sdk/r3f/test/errors.test.tsx@@ -123,16 +123,16 @@ describe("what the 11-15 audit found refused", () => {}});- test("gl.compute in useFrame is taken and named, not thrown", () => {+ test("gl.compute of a node raea can't run is named, not thrown (a TSL ComputeNode runs: test/compute.test.tsx)", () => {const { useFrame } = require("@react-three/fiber") as typeof import("@react-three/fiber");const Dispatch = () => {useFrame(({ gl }) => (gl as unknown as { compute(n: unknown): void }).compute({ isComputeNode: true }));return <Box />;};- const s = stepTo("compute", 0, 30, 400, 400, {}, () => <Dispatch />);- const { warned } = quiet(() => stepTo("compute", 1, 30, 400, 400, {}, () => <Dispatch />));+ const { out: s, warned } = quiet(() => (stepTo("compute", 0, 30, 400, 400, {}, () => <Dispatch />), stepTo("compute", 1, 30, 400, 400, {}, () => <Dispatch />)));const gl = (s.state as unknown as { gl: { __raea: { computes: unknown[] } } }).gl;- expect(gl.__raea.computes.length).toBeGreaterThan(0);+ expect(gl.__raea.computes.length).toBe(0);+ expect(warned.filter((w) => /gl\.compute dispatches a compute raea can't run/.test(w))).toHaveLength(1);expect(warned.every((w) => !/TypeError/.test(w))).toBe(true);end("compute");});diff --git a/sdk/r3f/test/parity/tsl.tsx b/sdk/r3f/test/parity/tsl.tsxindex 1a5e2d2a..82b88246 100644--- a/sdk/r3f/test/parity/tsl.tsx+++ b/sdk/r3f/test/parity/tsl.tsx@@ -2,12 +2,15 @@// draws from three's own WGSL (src/input/tsl.ts, tsl-lit.ts). A graph's motion comes from a uniform R3F's clock sets in// useFrame, never TSL's `time` (three's renderer counts that from performance.now(), so Chrome's frame would differ).import { useFrame } from "@react-three/fiber";-import { MeshStandardNodeMaterial } from "three/webgpu";+import { useRef } from "react";+import * as THREE from "three";+import { MeshBasicNodeMaterial, MeshStandardNodeMaterial } from "three/webgpu";import * as TSLTyped from "three/tsl";import type { InputCase } from "./fixtures";// untyped: @types/three's chained TSL types make tsc take minutes and gigabytesconst { color, mix, mx_noise_float, normalLocal, positionLocal, uniform } = TSLTyped as unknown as Record<string, (...a: unknown[]) => any> & { normalLocal: any; positionLocal: any };+const { Fn, cos, float, fract, hash, instanceIndex, instancedArray, length, sin, step, vec3 } = TSLTyped as unknown as Record<string, any>;/** three's WebGPURenderer for a TSL scene: its WebGL 2 backend (headless Chrome may have no WebGPU) */async function nodeRenderer(props: object) {@@ -37,6 +40,49 @@ function Blob() {);}+// a swirl of 65,536 particles a compute moves on the GPU (R3F22): `init` sets each on a golden-angle disk with its colour,+// one of four arms by its first angle, and `update` turns each about the centre, faster the nearer it is, once a+// frame; an InstancedMesh of small quads draws them where the buffers say (positionNode and colorNode read them+// .toAttribute()), added up. The arms wind into a spiral only if the computes ran, frame by frame.+const PARTICLES = 65536;+const swirl = (() => {+ const pos = instancedArray(PARTICLES, "vec3");+ const col = instancedArray(PARTICLES, "vec3");+ const i = float(instanceIndex);+ const init = Fn(() => {+ const turn = fract(i.mul(0.38196601));+ const a = turn.mul(6.28318531);+ const r = i.div(PARTICLES).sqrt().mul(1.9);+ pos.element(instanceIndex).assign(vec3(cos(a).mul(r), sin(a).mul(r), hash(instanceIndex).sub(0.5).mul(0.4)));+ col.element(instanceIndex).assign(mix(vec3(1, 0.45, 0.15), vec3(0.2, 0.45, 1), step(0.5, fract(turn.mul(4)))));+ })().compute(PARTICLES);+ const update = Fn(() => {+ const p = pos.element(instanceIndex);+ const w = float(0.06).div(length(p.xy).add(0.25));+ const c = cos(w);+ const s = sin(w);+ p.assign(vec3(p.x.mul(c).sub(p.y.mul(s)), p.x.mul(s).add(p.y.mul(c)), p.z));+ })().compute(PARTICLES);+ const m = new MeshBasicNodeMaterial({ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });+ m.positionNode = positionLocal.add(pos.toAttribute());+ m.colorNode = col.toAttribute().mul(0.3);+ return { init, update, m, geo: new THREE.PlaneGeometry(0.025, 0.025) };+})();++/** the computes a frame at a time by the clock's frame (Chrome's page draws its last frame twice: no second update) */+function Swirl() {+ const done = useRef(-1);+ useFrame(({ clock, gl }) => {+ const g = gl as unknown as { compute(n: unknown): void };+ const f = Math.round(clock.elapsedTime * 24);+ for (; done.current < f; done.current++) {+ if (done.current < 0) g.compute(swirl.init);+ g.compute(swirl.update);+ }+ });+ return <instancedMesh args={[swirl.geo, swirl.m, PARTICLES]} frustumCulled={false} />;+}+export const TSL_INPUTS: Record<string, InputCase> = {"tsl-lit": {canvas: { camera: { position: [0, 0.4, 4], fov: 45 }, gl: nodeRenderer },@@ -50,4 +96,14 @@ export const TSL_INPUTS: Record<string, InputCase> = {</>),},+ "tsl-particles": {+ canvas: { camera: { position: [0, 0, 5], fov: 45 }, gl: nodeRenderer },+ frame: 12,+ scene: () => (+ <>+ <color attach="background" args={["#0b0d12"]} />+ <Swirl />+ </>+ ),+ },};diff --git a/sdk/r3f/test/tsl.test.ts b/sdk/r3f/test/tsl.test.tsindex 8024380d..95649d1d 100644--- a/sdk/r3f/test/tsl.test.ts+++ b/sdk/r3f/test/tsl.test.ts@@ -9,7 +9,7 @@ import * as THREE from "three";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, float, mix, mx_noise_float, normalLocal, positionLocal, 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, 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";diff --git a/sdk/r3f/tools/parity.sh b/sdk/r3f/tools/parity.shindex 6ccb7a00..38de51b0 100755--- a/sdk/r3f/tools/parity.sh+++ b/sdk/r3f/tools/parity.sh@@ -13,6 +13,8 @@ CASES=(in-basic:24 in-instanced:12 in-lights:0 in-things:0 in-catch:0 in-lettra:# R3F_CASES="in-sky:0 in-shader:12": just those (a lane checking its own cases)# the TSL cases (test/parity/tsl.tsx): a lit node material (R3F21)CASES+=(in-tsl-lit:12)+# TSL compute: particles a compute moves, drawn by a node material on an InstancedMesh (R3F22)+CASES+=(in-tsl-particles:12)# a plain three.js program (test/parity/programs.ts) through <Three> (R3F19)CASES+=(in-vanilla:24)# postprocessing's effects as raea <FramePass>es (test/parity/post2.tsx), before and after an ACES tone mapping (R3F25)diff --git a/sdk/render/src/3d/compute.tsx b/sdk/render/src/3d/compute.tsxindex d551f1fc..59e59b2e 100644--- a/sdk/render/src/3d/compute.tsx+++ b/sdk/render/src/3d/compute.tsx@@ -74,9 +74,35 @@ function written(props: ComputeProps) {const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;+/** three.js's compute nodes as <R3F> runs them (sdk/r3f's tsl-compute.ts, docs/r3f.feature R3F22): each kernel three's+ * own WGSL, its storage buffers shared by key with the node materials that read them, and this frame's dispatches,+ * each run once in the order given before the cameras draw. */+export interface ThreeComputeProps {+ /** each kernel by its id: three's WGSL (its `@group(0)` bindings as written, entry `main`) and each storage+ * buffer's key, by the name it declares */+ kernels: Record<string, { wgsl: string; buffers: Record<string, string> }>;+ /** each shared storage buffer by key: its size in bytes and first contents (zeros when none) */+ shared: Record<string, { size: number; f32?: number[]; u32?: number[]; i32?: number[] }>;+ /** this frame's dispatches: [kernel id, workgroups [x, y, z], uniforms {NAME: {field: value}}], in order; `epoch`+ * and `seq` name them (run once each), `fresh` resets the buffers to their first contents first */+ runs: { epoch: number; seq: number; fresh: boolean; runs: [number, number[], Record<string, Record<string, number | number[]>>][] };+}++function threeCompute(props: ThreeComputeProps) {+ const { kernels, shared, runs } = props;+ if (typeof kernels !== "object" || kernels === null || Object.values(kernels).some((k) => typeof k?.wgsl !== "string")) throw new TypeError("Compute: kernels are {id: {wgsl, buffers}}");+ if (typeof shared !== "object" || shared === null || Object.values(shared).some((b) => !Number.isInteger(b?.size) || b.size < 4)) throw new TypeError("Compute: shared buffers are {key: {size (bytes), f32 | u32 | i32}}");+ if (!Array.isArray(runs?.runs) || runs.runs.some((r) => !(String(r[0]) in kernels))) throw new TypeError("Compute: runs are [kernel id, workgroups, uniforms], each a kernel it has");+ for (const r of runs.runs) checkWorkgroups(r[1]);+ // each a keyed column: the kernels and buffers change when a new one is dispatched, the runs every frame+ return node3d("Compute", { shader: { three: true }, kernels: JSON.stringify(kernels), shared: JSON.stringify(shared), runs: JSON.stringify(runs) });+}+/** A compute over the frame, in the 3D beside the camera; several run in the order written, before the cameras draw.* @bevy raea_sys_compute::Computes */-export function Compute(props: ComputeProps) {+export function Compute(props: ComputeProps | ThreeComputeProps) {+ if ("kernels" in props && props.kernels !== undefined) return threeCompute(props);+ props = props as ComputeProps;const { wesl, wgsl, workgroups, uniforms = {}, buffers = {}, images = {}, defs } = props;if (props.file !== undefined) return written(props);if ((wesl === undefined) === (wgsl === undefined)) throw new TypeError("Compute: give its source as wesl (or wgsl), one of them");diff --git a/sdk/render/src/3d/shapes.tsx b/sdk/render/src/3d/shapes.tsxindex 00d69ad2..90f1047a 100644--- a/sdk/render/src/3d/shapes.tsx+++ b/sdk/render/src/3d/shapes.tsx@@ -280,6 +280,11 @@ export interface BufferMeshProps {/** a mesh's own attributes beyond those, for a three.js shader that reads them (<ThreeShaderMaterial>): each one's* size (1 to 4 numbers a vertex) and values, per vertex */attributes?: Record<string, { size: number; values: number[] }>;+ /** the mesh repeated `count` times as one, for a three.js node material drawn as copies (an InstancedMesh's,+ * docs/r3f.feature R3F22): each copy's number is its own attribute `tsl_copy`, each of `attributes` (size numbers+ * a copy) is on every vertex of its copy, and `matrices` (16 numbers a copy, column-major) place the copies (none:+ * each where the mesh is) */+ copies?: { count: number; attributes?: Record<string, { size: number; values: number[] }>; matrices?: number[] };}/** Each mesh's shape text, checked and written once: React draws a <BufferMesh> every frame with the same arrays, and@@ -288,7 +293,7 @@ export interface BufferMeshProps {const shaped = new WeakMap<object, { of: unknown[]; text: string }>();function bufferShape(p: BufferMeshProps): string {- const of = [p.indices, p.normals, p.uvs, p.colors, p.attributes];+ const of = [p.indices, p.normals, p.uvs, p.colors, p.attributes, p.copies];const had = Array.isArray(p.positions) ? shaped.get(p.positions) : undefined;if (had && had.of.every((a, i) => a === of[i])) return had.text;const text = writeBufferShape(p);@@ -318,7 +323,15 @@ function writeBufferShape(p: BufferMeshProps): string {for (const [k, a] of Object.entries(p.attributes ?? {})) {if (!(a && Number.isInteger(a.size) && a.size >= 1 && a.size <= 4 && Array.isArray(a.values) && a.values.length === n * a.size)) throw new RangeError(`BufferMesh: attribute ${k} is {size: 1 to 4, values: size numbers for each of the ${n} vertices}`);}- return "buffer:" + JSON.stringify({ positions: p.positions, indices: p.indices, normals: p.normals, uvs: p.uvs, colors: p.colors, attributes: p.attributes });+ const c = p.copies;+ if (c !== undefined) {+ if (!(Number.isInteger(c.count) && c.count >= 1)) throw new RangeError(`BufferMesh: copies.count is a whole number of copies, 1 or more, got ${c.count}`);+ for (const [k, a] of Object.entries(c.attributes ?? {})) {+ if (!(a && Number.isInteger(a.size) && a.size >= 1 && a.size <= 4 && Array.isArray(a.values) && a.values.length === c.count * a.size)) throw new RangeError(`BufferMesh: copies attribute ${k} is {size: 1 to 4, values: size numbers for each of the ${c.count} copies}`);+ }+ if (c.matrices !== undefined && !(Array.isArray(c.matrices) && c.matrices.length === c.count * 16)) throw new RangeError(`BufferMesh: copies.matrices are 16 numbers for each of the ${c.count} copies`);+ }+ return "buffer:" + JSON.stringify({ positions: p.positions, indices: p.indices, normals: p.normals, uvs: p.uvs, colors: p.colors, attributes: p.attributes, copies: c });}/** A mesh from its own vertex buffers, as the geometry of a <Mesh> (Bevy's Mesh built from attributes): a terrain fromdiff --git a/sdk/render/src/3d/three-shader.tsx b/sdk/render/src/3d/three-shader.tsxindex d44019a1..84a30bd2 100644--- a/sdk/render/src/3d/three-shader.tsx+++ b/sdk/render/src/3d/three-shader.tsx@@ -13,8 +13,10 @@ export interface ThreeShaderMaterialProps {* RawShaderMaterial (which declares three's built-ins itself), `vertexColors` as the material's */glsl?: { vertex: string; fragment: string; raw?: boolean; vertexColors?: boolean };/** a node material's WGSL, as three's TSL builder writes it for raea (sdk/r3f's input/tsl.ts): the contract's- * `three_vertex` and `three_fragment`, its uniforms' types, the mesh attributes it reads beyond the standard four */- wgsl?: { vertex: string; fragment: string; uniforms?: { name: string; type: string; array?: number }[]; attributes?: string[] };+ * `three_vertex` and `three_fragment`, its uniforms' types, the mesh attributes it reads beyond the standard four,+ * whether it is a lit surface (three_surface), and the storage buffers it reads (`tsl_s0`, `tsl_s1`: each a buffer+ * a <Compute>'s kernels share by key, its size in bytes and first contents) */+ wgsl?: { vertex: string; fragment: string; uniforms?: { name: string; type: string; array?: number }[]; attributes?: string[]; lit?: boolean; storage?: { name: string; key: string; size: number; f32?: number[]; u32?: number[]; i32?: number[] }[] };/** each uniform's value this frame */uniforms?: Record<string, ThreeUniform>;/** each sampler's picture: a file, a data URL, "render:NAME" (at most four); `colorSpace: "linear"` for one three