@aardworx/wombat.rendering 0.5.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,26 +1,277 @@
1
1
  // BufferView — a typed slice of an `IBuffer` used as a vertex
2
- // attribute, instance attribute, or index source. The buffer
3
- // itself can be a real GPU buffer or host-side memory; the
4
- // runtime handles upload transparently.
2
+ // attribute, instance attribute, or index source. Mirrors
3
+ // Aardvark.Rendering's `BufferView`:
5
4
  //
6
- // `format` carries the WebGPU vertex format when this view is
7
- // bound as a vertex / instance attribute. `indexFormat` is set
8
- // when the view is bound as an index buffer; in that case
9
- // `format` is ignored. Both are optional so callers don't have
10
- // to fill in the irrelevant one.
5
+ // - `buffer` is `aval<IBuffer>` so per-frame content changes flow
6
+ // through normal aval marking without reshaping the view.
7
+ // - `elementType` carries the element kind; the backend derives
8
+ // `GPUVertexFormat` / `GPUIndexFormat` and a default stride from
9
+ // it.
10
+ // - `singleValue` is set when the view was constructed from a
11
+ // single adaptive value broadcast to all instances/vertices —
12
+ // the runtime can lower it to a uniform binding instead of a
13
+ // per-vertex/per-instance attribute.
14
+ //
15
+ // The view itself is plain (not wrapped in `aval`). Structural
16
+ // fields — `elementType`, `offset`, `stride`, `normalized` — are
17
+ // eager so the binding plan / pipeline layout can be computed
18
+ // without forcing.
11
19
 
12
- import type { IBuffer } from "./buffer.js";
20
+ import type { aval } from "@aardworx/wombat.adaptive";
21
+ import { AVal } from "@aardworx/wombat.adaptive";
22
+ import { IBuffer } from "./buffer.js";
23
+ import type { ElementType } from "./elementType.js";
24
+ import { ElementType as ElementTypeRegistry } from "./elementType.js";
13
25
 
14
26
  export interface BufferView {
15
- readonly buffer: IBuffer;
16
- /** Byte offset into `buffer` where the view starts. */
17
- readonly offset: number;
18
- /** Number of elements (not bytes) in the view. */
19
- readonly count: number;
20
- /** Stride between consecutive elements, in bytes. */
21
- readonly stride: number;
22
- /** Vertex format — used when bound as a vertex / instance attribute. */
23
- readonly format: GPUVertexFormat | GPUIndexFormat;
24
- /** Index format — used when bound as an index buffer. Overrides `format`. */
25
- readonly indexFormat?: GPUIndexFormat;
27
+ /** Adaptive buffer source — content changes flow through this aval. */
28
+ readonly buffer: aval<IBuffer>;
29
+ /** Element kind. Stride defaults from this when `stride` is 0/undefined. */
30
+ readonly elementType: ElementType;
31
+ /** Byte offset into `buffer` where the view starts. Default 0. */
32
+ readonly offset?: number;
33
+ /** Stride between consecutive elements in bytes. 0 = tight (= `byteSize(elementType)`). */
34
+ readonly stride?: number;
35
+ /** Integer attributes treated as normalized fixed-point floats. Default false. */
36
+ readonly normalized?: boolean;
37
+ /**
38
+ * Present iff this view was constructed from a single adaptive
39
+ * value (see `BufferView.ofValue`). Lets the backend lower the
40
+ * binding to a uniform instead of a per-vertex/per-instance
41
+ * attribute.
42
+ */
43
+ readonly singleValue?: aval<unknown>;
44
+ }
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // Inference helpers — discover ElementType from a wombat.base packed
48
+ // array or a TypedArray. Kept as a duck-type lookup so wombat.base
49
+ // doesn't need to expose explicit brands.
50
+ // ---------------------------------------------------------------------------
51
+
52
+ interface WombatArrayLike {
53
+ readonly buffer: ArrayBufferLike;
54
+ readonly length: number;
55
+ }
56
+
57
+ function inferElementType(arr: unknown): ElementType {
58
+ // wombat.base packed types — discover via class name. These all
59
+ // have a distinct `constructor.name` and a `buffer: ArrayBuffer`
60
+ // backing field.
61
+ const ctor = (arr as { constructor?: { name?: string } }).constructor;
62
+ const name = ctor?.name;
63
+ switch (name) {
64
+ case "V2fArray": return "v2f";
65
+ case "V3fArray": return "v3f";
66
+ case "V4fArray": return "v4f";
67
+ case "V2iArray": return "v2i";
68
+ case "V3iArray": return "v3i";
69
+ case "V4iArray": return "v4i";
70
+ case "V2uiArray": return "v2u";
71
+ case "V3uiArray": return "v3u";
72
+ case "V4uiArray": return "v4u";
73
+ // Native typed arrays.
74
+ case "Float32Array": return "f32";
75
+ case "Uint32Array": return "u32";
76
+ case "Int32Array": return "i32";
77
+ case "Uint16Array": return "u16";
78
+ case "Int16Array": return "i16";
79
+ case "Uint8Array": return "u8";
80
+ case "Int8Array": return "i8";
81
+ }
82
+ throw new Error(
83
+ `BufferView.ofArray: cannot infer ElementType from ${name ?? "unknown type"}; ` +
84
+ `pass elementType explicitly`,
85
+ );
86
+ }
87
+
88
+ function arrayToHostBytes(arr: unknown): ArrayBuffer | ArrayBufferView {
89
+ // wombat.base packed types expose `.buffer: ArrayBuffer` covering
90
+ // exactly the packed bytes.
91
+ const a = arr as { buffer?: unknown };
92
+ if (a.buffer instanceof ArrayBuffer) return a.buffer;
93
+ // Native typed array — pass through.
94
+ if (ArrayBuffer.isView(arr as ArrayBufferView)) return arr as ArrayBufferView;
95
+ throw new Error("BufferView.ofArray: unsupported array source");
96
+ }
97
+
98
+ // ---------------------------------------------------------------------------
99
+ // Constructors
100
+ // ---------------------------------------------------------------------------
101
+
102
+ interface OfArrayOptions {
103
+ readonly elementType?: ElementType;
104
+ readonly offset?: number;
105
+ readonly stride?: number;
106
+ readonly normalized?: boolean;
107
+ }
108
+
109
+ interface OfGPUOptions {
110
+ readonly offset?: number;
111
+ readonly stride?: number;
112
+ readonly normalized?: boolean;
113
+ }
114
+
115
+ function isAval<T>(v: unknown): v is aval<T> {
116
+ return typeof v === "object" && v !== null
117
+ && typeof (v as { getValue?: unknown }).getValue === "function";
118
+ }
119
+
120
+ export const BufferView = {
121
+ /**
122
+ * Build a view from a wombat.base packed array (`V3fArray`,
123
+ * `Uint16Array`, …) or an `aval<…>` of one. The element type is
124
+ * inferred from the array constructor; pass it explicitly via
125
+ * `opts.elementType` for unusual cases.
126
+ */
127
+ ofArray<T extends WombatArrayLike | ArrayBufferView>(
128
+ a: aval<T> | T,
129
+ opts: OfArrayOptions = {},
130
+ ): BufferView {
131
+ const adaptive = isAval<T>(a) ? a : AVal.constant(a);
132
+ // Determine element type — eager. We force the aval ONCE here
133
+ // to discover the array kind, which is structural; subsequent
134
+ // changes are expected to keep the same kind.
135
+ const sample = adaptive.force(/* allow-force */);
136
+ const elementType = opts.elementType ?? inferElementType(sample);
137
+ const buffer = adaptive.map((arr): IBuffer =>
138
+ IBuffer.fromHost(arrayToHostBytes(arr)),
139
+ );
140
+ return {
141
+ buffer,
142
+ elementType,
143
+ ...(opts.offset !== undefined ? { offset: opts.offset } : {}),
144
+ ...(opts.stride !== undefined ? { stride: opts.stride } : {}),
145
+ ...(opts.normalized !== undefined ? { normalized: opts.normalized } : {}),
146
+ };
147
+ },
148
+
149
+ /**
150
+ * Build a view that broadcasts a single adaptive value to every
151
+ * vertex / instance. The runtime detects the `singleValue` field
152
+ * and lowers it to a uniform binding instead of a per-element
153
+ * attribute. The `buffer` aval still carries packed bytes for
154
+ * backends that don't recognize the fast path.
155
+ */
156
+ ofValue<T>(
157
+ v: aval<T> | T,
158
+ elementType: ElementType,
159
+ ): BufferView {
160
+ const adaptive = isAval<T>(v) ? v : AVal.constant(v);
161
+ const buffer = adaptive.map((value): IBuffer => {
162
+ const bytes = ElementTypeRegistry.byteSize(elementType);
163
+ const ab = new ArrayBuffer(bytes);
164
+ packSingle(value, elementType, ab);
165
+ return IBuffer.fromHost(ab);
166
+ });
167
+ return {
168
+ buffer,
169
+ elementType,
170
+ singleValue: adaptive,
171
+ };
172
+ },
173
+
174
+ /**
175
+ * Build a view backed by a user-supplied `GPUBuffer`. The
176
+ * runtime binds it directly without an upload step.
177
+ */
178
+ ofGPU(
179
+ buffer: aval<GPUBuffer> | GPUBuffer,
180
+ elementType: ElementType,
181
+ opts: OfGPUOptions = {},
182
+ ): BufferView {
183
+ const adaptive = isAval<GPUBuffer>(buffer) ? buffer : AVal.constant(buffer);
184
+ const ibuffer = adaptive.map((b): IBuffer => IBuffer.fromGPU(b));
185
+ return {
186
+ buffer: ibuffer,
187
+ elementType,
188
+ ...(opts.offset !== undefined ? { offset: opts.offset } : {}),
189
+ ...(opts.stride !== undefined ? { stride: opts.stride } : {}),
190
+ ...(opts.normalized !== undefined ? { normalized: opts.normalized } : {}),
191
+ };
192
+ },
193
+
194
+ /**
195
+ * Wrap an already-built `aval<IBuffer>` with explicit element
196
+ * type. Used by callers that compute their own `IBuffer` (e.g.
197
+ * compositing multiple attributes into one packed buffer).
198
+ */
199
+ ofBuffer(
200
+ buffer: aval<IBuffer>,
201
+ elementType: ElementType,
202
+ opts: OfGPUOptions = {},
203
+ ): BufferView {
204
+ return {
205
+ buffer,
206
+ elementType,
207
+ ...(opts.offset !== undefined ? { offset: opts.offset } : {}),
208
+ ...(opts.stride !== undefined ? { stride: opts.stride } : {}),
209
+ ...(opts.normalized !== undefined ? { normalized: opts.normalized } : {}),
210
+ };
211
+ },
212
+
213
+ // ---------- accessors ----------
214
+
215
+ /** Byte offset, defaulting to 0. */
216
+ offsetOf(v: BufferView): number { return v.offset ?? 0; },
217
+ /**
218
+ * Stride in bytes — `v.stride` if set and non-zero, otherwise
219
+ * tight from `elementType`.
220
+ */
221
+ strideOf(v: BufferView): number {
222
+ return v.stride !== undefined && v.stride > 0
223
+ ? v.stride
224
+ : ElementTypeRegistry.byteSize(v.elementType);
225
+ },
226
+ /** Whether this view is a single-value broadcast. */
227
+ isSingleValue(v: BufferView): boolean {
228
+ return v.singleValue !== undefined;
229
+ },
230
+ } as const;
231
+
232
+ // ---------------------------------------------------------------------------
233
+ // Single-value packing — write one element of `elementType` into a
234
+ // fresh ArrayBuffer. The runtime usually shortcuts this via
235
+ // `singleValue` (lifted to a uniform), so this path runs only for
236
+ // backends that don't recognize the broadcast.
237
+ // ---------------------------------------------------------------------------
238
+
239
+ function packSingle(value: unknown, t: ElementType, dst: ArrayBuffer): void {
240
+ // Lazy import to avoid a hard dep on wombat.base shapes here. We
241
+ // peek at `_data` (the typed-array view exposed by every wombat
242
+ // math type) and copy its bytes into the destination.
243
+ const v = value as { _data?: ArrayLike<number> };
244
+ if (v._data !== undefined) {
245
+ const src = v._data;
246
+ switch (t) {
247
+ case "v2f": case "v3f": case "v4f":
248
+ case "m22f": case "m33f": case "m44f":
249
+ case "f32": {
250
+ const out = new Float32Array(dst);
251
+ for (let i = 0; i < src.length; i++) out[i] = src[i]!;
252
+ return;
253
+ }
254
+ case "v2i": case "v3i": case "v4i": case "i32": {
255
+ const out = new Int32Array(dst);
256
+ for (let i = 0; i < src.length; i++) out[i] = src[i]!;
257
+ return;
258
+ }
259
+ case "v2u": case "v3u": case "v4u": case "u32": {
260
+ const out = new Uint32Array(dst);
261
+ for (let i = 0; i < src.length; i++) out[i] = src[i]!;
262
+ return;
263
+ }
264
+ }
265
+ }
266
+ // Scalars and unbranded values.
267
+ switch (t) {
268
+ case "f32": new Float32Array(dst)[0] = value as number; return;
269
+ case "u32": new Uint32Array(dst)[0] = value as number; return;
270
+ case "i32": new Int32Array(dst)[0] = value as number; return;
271
+ case "u16": new Uint16Array(dst)[0] = value as number; return;
272
+ case "i16": new Int16Array(dst)[0] = value as number; return;
273
+ case "u8": new Uint8Array(dst)[0] = value as number; return;
274
+ case "i8": new Int8Array(dst)[0] = value as number; return;
275
+ }
276
+ throw new Error(`BufferView.ofValue: cannot pack ${typeof value} as ${t}`);
26
277
  }
@@ -0,0 +1,84 @@
1
+ // ElementType — the data type of a single element in a BufferView.
2
+ //
3
+ // Mirrors Aardvark.Rendering's `BufferView.ElementType : System.Type`
4
+ // pattern: structural information about the element kept separate
5
+ // from the per-frame buffer content. The runtime maps `ElementType`
6
+ // to a `GPUVertexFormat`/`GPUIndexFormat` and a byte size at
7
+ // pipeline-layout time.
8
+
9
+ export type ElementType =
10
+ // scalar
11
+ | "f32" | "u32" | "i32"
12
+ | "u16" | "i16"
13
+ | "u8" | "i8"
14
+ // vec — float
15
+ | "v2f" | "v3f" | "v4f"
16
+ // vec — int
17
+ | "v2i" | "v3i" | "v4i"
18
+ // vec — uint
19
+ | "v2u" | "v3u" | "v4u"
20
+ // matrix (float, square)
21
+ | "m22f" | "m33f" | "m44f"
22
+ // packed colour
23
+ | "c4b" | "c3b";
24
+
25
+ export const ElementType = {
26
+ /** Size of one element in bytes. */
27
+ byteSize(t: ElementType): number {
28
+ switch (t) {
29
+ case "f32": case "u32": case "i32": return 4;
30
+ case "u16": case "i16": return 2;
31
+ case "u8": case "i8": return 1;
32
+ case "v2f": case "v2i": case "v2u": return 8;
33
+ case "v3f": case "v3i": case "v3u": return 12;
34
+ case "v4f": case "v4i": case "v4u": return 16;
35
+ case "m22f": return 16;
36
+ case "m33f": return 36;
37
+ case "m44f": return 64;
38
+ case "c4b": return 4;
39
+ case "c3b": return 3;
40
+ }
41
+ },
42
+
43
+ /**
44
+ * GPUVertexFormat for use as a vertex / instance attribute.
45
+ * `normalized=true` only affects integer types — picks the `unorm`
46
+ * / `snorm` form. Matrix types are not directly supported as
47
+ * vertex formats; the auto-instancing pass splits them into
48
+ * column attributes upstream.
49
+ */
50
+ toVertexFormat(t: ElementType, normalized = false): GPUVertexFormat {
51
+ switch (t) {
52
+ case "f32": return "float32";
53
+ case "u32": return "uint32";
54
+ case "i32": return "sint32";
55
+ case "v2f": return "float32x2";
56
+ case "v3f": return "float32x3";
57
+ case "v4f": return "float32x4";
58
+ case "v2i": return "sint32x2";
59
+ case "v3i": return "sint32x3";
60
+ case "v4i": return "sint32x4";
61
+ case "v2u": return "uint32x2";
62
+ case "v3u": return "uint32x3";
63
+ case "v4u": return "uint32x4";
64
+ case "u16": return normalized ? "unorm16x2" as GPUVertexFormat : "uint16";
65
+ case "i16": return normalized ? "snorm16x2" as GPUVertexFormat : "sint16";
66
+ case "u8": return normalized ? "unorm8x4" as GPUVertexFormat : "uint8";
67
+ case "i8": return normalized ? "snorm8x4" as GPUVertexFormat : "sint8";
68
+ case "c4b": return normalized ? "unorm8x4" : "uint8x4";
69
+ case "c3b":
70
+ // No 3-component byte format in WebGPU; promoted to x4 with
71
+ // a dummy fourth byte by the upload path.
72
+ throw new Error(`ElementType.toVertexFormat: c3b cannot be a vertex format directly; pad to c4b`);
73
+ case "m22f": case "m33f": case "m44f":
74
+ throw new Error(`ElementType.toVertexFormat: ${t} is a matrix; split into column attributes first`);
75
+ }
76
+ },
77
+
78
+ /** Index format. Throws unless the type is `u16` or `u32`. */
79
+ toIndexFormat(t: ElementType): GPUIndexFormat {
80
+ if (t === "u16") return "uint16";
81
+ if (t === "u32") return "uint32";
82
+ throw new Error(`ElementType.toIndexFormat: ${t} is not a valid index type (use u16 or u32)`);
83
+ },
84
+ } as const;
package/src/core/index.ts CHANGED
@@ -11,10 +11,14 @@ export type {
11
11
  HostBufferSource,
12
12
  } from "./buffer.js";
13
13
 
14
- export type {
14
+ export {
15
15
  BufferView,
16
16
  } from "./bufferView.js";
17
17
 
18
+ export {
19
+ ElementType,
20
+ } from "./elementType.js";
21
+
18
22
  export type {
19
23
  ClearColor,
20
24
  ClearValues,
@@ -45,9 +45,9 @@ export interface RenderObject {
45
45
  * individual buffer values are reactive. The shader's required-input
46
46
  * set is fixed at compile; the map must contain at least those names.
47
47
  */
48
- readonly vertexAttributes: HashMap<string, aval<BufferView>>;
48
+ readonly vertexAttributes: HashMap<string, BufferView>;
49
49
  /** name → instance buffer view; e.g. "modelMatrix", "instanceColor". */
50
- readonly instanceAttributes?: HashMap<string, aval<BufferView>>;
50
+ readonly instanceAttributes?: HashMap<string, BufferView>;
51
51
  /** name → uniform value; runtime packs into UBO based on shader layout. */
52
52
  readonly uniforms: HashMap<string, aval<unknown>>;
53
53
  /** name → texture source (CPU image or pre-built GPUTexture). */
@@ -58,6 +58,6 @@ export interface RenderObject {
58
58
  readonly storageBuffers?: HashMap<string, aval<IBuffer>>;
59
59
 
60
60
  /** Index buffer for indexed draws. */
61
- readonly indices?: aval<BufferView>;
61
+ readonly indices?: BufferView;
62
62
  readonly drawCall: aval<DrawCall>;
63
63
  }