@orkestrel/wgsl 0.0.0-stage → 0.0.1
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.
- package/LICENSE +21 -0
- package/README.md +9 -2
- package/dist/src/core/index.cjs +1836 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +1207 -0
- package/dist/src/core/index.d.ts +1207 -0
- package/dist/src/core/index.js +1805 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +99 -5
|
@@ -0,0 +1,1805 @@
|
|
|
1
|
+
import { INTRINSICS, errorToMessage, holds, isArray, isError, isFunction, isNonEmptyString, isNonNegativeInteger, isObject, isRecord, isSafeInteger, isString, preview } from "@orkestrel/contract";
|
|
2
|
+
// src/core/constants.ts
|
|
3
|
+
/**
|
|
4
|
+
* Lists the condition codes a `WGSLError` carries.
|
|
5
|
+
*
|
|
6
|
+
* @remarks
|
|
7
|
+
* `ARGUMENT` marks a malformed argument, `COMPILE` a shader the compiler refuses, `VALIDATION` a
|
|
8
|
+
* declaration or command the package or the device refuses, `LIMIT` an exceeded device limit,
|
|
9
|
+
* `HOST` a lost device, `DESTROYED` a call after `destroy`, and `ABORT` an aborted signal or batch.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```ts
|
|
13
|
+
* WGSL_ERROR_CODES.includes('VALIDATION') // true
|
|
14
|
+
* ```
|
|
15
|
+
*/
|
|
16
|
+
var WGSL_ERROR_CODES = Object.freeze([
|
|
17
|
+
"ARGUMENT",
|
|
18
|
+
"COMPILE",
|
|
19
|
+
"VALIDATION",
|
|
20
|
+
"LIMIT",
|
|
21
|
+
"HOST",
|
|
22
|
+
"DESTROYED",
|
|
23
|
+
"ABORT"
|
|
24
|
+
]);
|
|
25
|
+
/**
|
|
26
|
+
* Keys the global brand a `WGSLError` carries, so another installed copy recognizes it.
|
|
27
|
+
*
|
|
28
|
+
* @remarks
|
|
29
|
+
* The key follows the package-and-class form, `Symbol.for('<package>.<ClassName>')`. The brand is
|
|
30
|
+
* a recognition marker and never proof that the class's constructor ran.
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* WGSL_ERROR_BRAND === Symbol.for('@orkestrel/wgsl.WGSLError') // true
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
var WGSL_ERROR_BRAND = Symbol.for("@orkestrel/wgsl.WGSLError");
|
|
38
|
+
/**
|
|
39
|
+
* Lists the scalar types a uniform struct member can hold.
|
|
40
|
+
*
|
|
41
|
+
* @remarks
|
|
42
|
+
* Each scalar aligns to 4 bytes and takes 4 bytes in the `uniform` and `storage` address spaces.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* WGSL_SCALARS.includes('f32') // true
|
|
47
|
+
* ```
|
|
48
|
+
*/
|
|
49
|
+
var WGSL_SCALARS = Object.freeze([
|
|
50
|
+
"u32",
|
|
51
|
+
"i32",
|
|
52
|
+
"f32"
|
|
53
|
+
]);
|
|
54
|
+
/**
|
|
55
|
+
* Lists the access modes a storage slot can declare.
|
|
56
|
+
*
|
|
57
|
+
* @remarks
|
|
58
|
+
* Each member mirrors the WGSL `var<storage, ACCESS>` access mode of the same spelling.
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* WGSL_ACCESSES.includes('read_write') // true
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
var WGSL_ACCESSES = Object.freeze(["read", "read_write"]);
|
|
66
|
+
/**
|
|
67
|
+
* Maps each WGSL extension a fragment variant can enable to the device feature that admits it.
|
|
68
|
+
*
|
|
69
|
+
* @remarks
|
|
70
|
+
* Each key mirrors the WGSL `enable` directive of the same spelling, and each value mirrors the
|
|
71
|
+
* WebGPU `GPUFeatureName` a device reports in `device.features`. The key order is the order in
|
|
72
|
+
* which a rendered program emits its `enable` directives.
|
|
73
|
+
*
|
|
74
|
+
* @example
|
|
75
|
+
* ```ts
|
|
76
|
+
* WGSL_EXTENSIONS.f16 // 'shader-f16'
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
var WGSL_EXTENSIONS = Object.freeze({
|
|
80
|
+
f16: "shader-f16",
|
|
81
|
+
subgroups: "subgroups"
|
|
82
|
+
});
|
|
83
|
+
/**
|
|
84
|
+
* Mirrors the WebGPU `GPUBufferUsage` bit values under one-word members.
|
|
85
|
+
*
|
|
86
|
+
* @remarks
|
|
87
|
+
* `read` mirrors `MAP_READ`, `write` mirrors `MAP_WRITE`, `source` mirrors `COPY_SRC`,
|
|
88
|
+
* `destination` mirrors `COPY_DST`, `uniform` mirrors `UNIFORM`, `storage` mirrors `STORAGE`,
|
|
89
|
+
* `indirect` mirrors `INDIRECT`, and `query` mirrors `QUERY_RESOLVE`. The library declares
|
|
90
|
+
* `GPUBufferUsage` only as a type, so `src/core` reads these values instead.
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```ts
|
|
94
|
+
* WGSL_USAGE.uniform | WGSL_USAGE.destination // 72
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
var WGSL_USAGE = Object.freeze({
|
|
98
|
+
read: 1,
|
|
99
|
+
write: 2,
|
|
100
|
+
source: 4,
|
|
101
|
+
destination: 8,
|
|
102
|
+
uniform: 64,
|
|
103
|
+
storage: 128,
|
|
104
|
+
indirect: 256,
|
|
105
|
+
query: 512
|
|
106
|
+
});
|
|
107
|
+
/**
|
|
108
|
+
* Mirrors the WebGPU `GPUMapMode` bit values under one-word members.
|
|
109
|
+
*
|
|
110
|
+
* @remarks
|
|
111
|
+
* `read` mirrors `READ` and `write` mirrors `WRITE`.
|
|
112
|
+
*
|
|
113
|
+
* @example
|
|
114
|
+
* ```ts
|
|
115
|
+
* WGSL_MAP.read // 1
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
var WGSL_MAP = Object.freeze({
|
|
119
|
+
read: 1,
|
|
120
|
+
write: 2
|
|
121
|
+
});
|
|
122
|
+
/**
|
|
123
|
+
* Mirrors the WebGPU `GPUShaderStage` bit value of the compute stage.
|
|
124
|
+
*
|
|
125
|
+
* @remarks
|
|
126
|
+
* `compute` mirrors `COMPUTE`.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* WGSL_STAGE.compute // 4
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
var WGSL_STAGE = Object.freeze({ compute: 4 });
|
|
134
|
+
/**
|
|
135
|
+
* Holds the default byte capacity of a session's uniform slab.
|
|
136
|
+
*
|
|
137
|
+
* @remarks
|
|
138
|
+
* The session's `uniform.size` option replaces it. At a 256-byte offset alignment the default
|
|
139
|
+
* holds 256 dispatches before a batch flushes.
|
|
140
|
+
*
|
|
141
|
+
* @example
|
|
142
|
+
* ```ts
|
|
143
|
+
* WGSL_UNIFORM_SIZE // 65536
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
var WGSL_UNIFORM_SIZE = 65536;
|
|
147
|
+
/**
|
|
148
|
+
* Holds the fragment that reads a workgroup's two-axis index from the entry input struct.
|
|
149
|
+
*
|
|
150
|
+
* @remarks
|
|
151
|
+
* It declares `fn place(invocation: Invocation) -> u32`, which returns
|
|
152
|
+
* `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, the
|
|
153
|
+
* statement of infer's `readPlace` recast onto the `Invocation` struct. Pair it with
|
|
154
|
+
* `computeWGSLGrid`, and multiply by the workgroup size and add `local_invocation_index` for an
|
|
155
|
+
* invocation's index. It reads no binding and no uniform member.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* ```ts
|
|
159
|
+
* createWGSLProgram({ name: 'clear', entry, slots, uniform, uses: [WGSL_PLACE] }).fragments // [WGSL_PLACE]
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
var WGSL_PLACE = Object.freeze({
|
|
163
|
+
name: "place",
|
|
164
|
+
source: [
|
|
165
|
+
"fn place(invocation: Invocation) -> u32 {",
|
|
166
|
+
" return invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x;",
|
|
167
|
+
"}"
|
|
168
|
+
].join("\n"),
|
|
169
|
+
uses: Object.freeze([])
|
|
170
|
+
});
|
|
171
|
+
/**
|
|
172
|
+
* Holds the fragment that sums one `f32` value from each invocation of a 64-invocation workgroup.
|
|
173
|
+
*
|
|
174
|
+
* @remarks
|
|
175
|
+
* It declares `var<workgroup> sums: array<f32, 64>` and
|
|
176
|
+
* `fn sum(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's total to every
|
|
177
|
+
* invocation. The entry's workgroup size must hold 64 invocations, and every invocation must call
|
|
178
|
+
* it from uniform control flow. The default body reduces in a tree of halving strides. The
|
|
179
|
+
* `subgroups` variant stores each subgroup's `subgroupAdd` partial at its first invocation's index
|
|
180
|
+
* and `0.0` elsewhere, and invocation 0 adds the 64 entries in index order between 2 barriers, so
|
|
181
|
+
* its rounding order differs from the default body's. It reads no binding and no uniform member.
|
|
182
|
+
*
|
|
183
|
+
* @example
|
|
184
|
+
* ```ts
|
|
185
|
+
* WGSL_SUM.variant?.extension // 'subgroups'
|
|
186
|
+
* ```
|
|
187
|
+
*/
|
|
188
|
+
var WGSL_SUM = Object.freeze({
|
|
189
|
+
name: "sum",
|
|
190
|
+
source: [
|
|
191
|
+
"var<workgroup> sums: array<f32, 64>;",
|
|
192
|
+
"",
|
|
193
|
+
"fn sum(invocation: Invocation, value: f32) -> f32 {",
|
|
194
|
+
" let local = invocation.local_invocation_index;",
|
|
195
|
+
" sums[local] = value;",
|
|
196
|
+
" workgroupBarrier();",
|
|
197
|
+
" for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
|
|
198
|
+
" if (local < stride) {",
|
|
199
|
+
" sums[local] = sums[local] + sums[local + stride];",
|
|
200
|
+
" }",
|
|
201
|
+
" workgroupBarrier();",
|
|
202
|
+
" }",
|
|
203
|
+
" let total = sums[0];",
|
|
204
|
+
" workgroupBarrier();",
|
|
205
|
+
" return total;",
|
|
206
|
+
"}"
|
|
207
|
+
].join("\n"),
|
|
208
|
+
uses: Object.freeze([]),
|
|
209
|
+
variant: Object.freeze({
|
|
210
|
+
extension: "subgroups",
|
|
211
|
+
source: [
|
|
212
|
+
"var<workgroup> sums: array<f32, 64>;",
|
|
213
|
+
"",
|
|
214
|
+
"fn sum(invocation: Invocation, value: f32) -> f32 {",
|
|
215
|
+
" let local = invocation.local_invocation_index;",
|
|
216
|
+
" let partial = subgroupAdd(value);",
|
|
217
|
+
" sums[local] = select(0.0, partial, invocation.subgroup_invocation_id == 0u);",
|
|
218
|
+
" workgroupBarrier();",
|
|
219
|
+
" if (local == 0u) {",
|
|
220
|
+
" var acc = 0.0;",
|
|
221
|
+
" for (var i = 0u; i < 64u; i += 1u) {",
|
|
222
|
+
" acc = acc + sums[i];",
|
|
223
|
+
" }",
|
|
224
|
+
" sums[0] = acc;",
|
|
225
|
+
" }",
|
|
226
|
+
" workgroupBarrier();",
|
|
227
|
+
" let total = sums[0];",
|
|
228
|
+
" workgroupBarrier();",
|
|
229
|
+
" return total;",
|
|
230
|
+
"}"
|
|
231
|
+
].join("\n")
|
|
232
|
+
})
|
|
233
|
+
});
|
|
234
|
+
/**
|
|
235
|
+
* Holds the fragment that finds the largest `f32` value across the invocations of a 64-invocation workgroup.
|
|
236
|
+
*
|
|
237
|
+
* @remarks
|
|
238
|
+
* It declares `var<workgroup> peaks: array<f32, 64>` and
|
|
239
|
+
* `fn peak(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's maximum to
|
|
240
|
+
* every invocation. The entry's workgroup size must hold 64 invocations, and every invocation must
|
|
241
|
+
* call it from uniform control flow. The default body reduces with `max` in a tree of halving
|
|
242
|
+
* strides. The `subgroups` variant stores each subgroup's `subgroupMax` partial at its first
|
|
243
|
+
* invocation's index and the lowest finite `f32` (`-3.4028234663852886e38`) elsewhere, and invocation 0 folds
|
|
244
|
+
* the 64 entries with `max` between 2 barriers (matching `@orkestrel/infer`, so it returns `-3.4028234663852886e38`
|
|
245
|
+
* rather than `-Infinity` when every input is `-Infinity`). It reads no binding and no uniform member.
|
|
246
|
+
*
|
|
247
|
+
* @example
|
|
248
|
+
* ```ts
|
|
249
|
+
* WGSL_PEAK.variant?.extension // 'subgroups'
|
|
250
|
+
* ```
|
|
251
|
+
*/
|
|
252
|
+
var WGSL_PEAK = Object.freeze({
|
|
253
|
+
name: "peak",
|
|
254
|
+
source: [
|
|
255
|
+
"var<workgroup> peaks: array<f32, 64>;",
|
|
256
|
+
"",
|
|
257
|
+
"fn peak(invocation: Invocation, value: f32) -> f32 {",
|
|
258
|
+
" let local = invocation.local_invocation_index;",
|
|
259
|
+
" peaks[local] = value;",
|
|
260
|
+
" workgroupBarrier();",
|
|
261
|
+
" for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
|
|
262
|
+
" if (local < stride) {",
|
|
263
|
+
" peaks[local] = max(peaks[local], peaks[local + stride]);",
|
|
264
|
+
" }",
|
|
265
|
+
" workgroupBarrier();",
|
|
266
|
+
" }",
|
|
267
|
+
" let largest = peaks[0];",
|
|
268
|
+
" workgroupBarrier();",
|
|
269
|
+
" return largest;",
|
|
270
|
+
"}"
|
|
271
|
+
].join("\n"),
|
|
272
|
+
uses: Object.freeze([]),
|
|
273
|
+
variant: Object.freeze({
|
|
274
|
+
extension: "subgroups",
|
|
275
|
+
source: [
|
|
276
|
+
"var<workgroup> peaks: array<f32, 64>;",
|
|
277
|
+
"",
|
|
278
|
+
"fn peak(invocation: Invocation, value: f32) -> f32 {",
|
|
279
|
+
" let local = invocation.local_invocation_index;",
|
|
280
|
+
" let partial = subgroupMax(value);",
|
|
281
|
+
" peaks[local] = select(-3.4028234663852886e38, partial, invocation.subgroup_invocation_id == 0u);",
|
|
282
|
+
" workgroupBarrier();",
|
|
283
|
+
" if (local == 0u) {",
|
|
284
|
+
" var acc = -3.4028234663852886e38;",
|
|
285
|
+
" for (var i = 0u; i < 64u; i += 1u) {",
|
|
286
|
+
" acc = max(acc, peaks[i]);",
|
|
287
|
+
" }",
|
|
288
|
+
" peaks[0] = acc;",
|
|
289
|
+
" }",
|
|
290
|
+
" workgroupBarrier();",
|
|
291
|
+
" let largest = peaks[0];",
|
|
292
|
+
" workgroupBarrier();",
|
|
293
|
+
" return largest;",
|
|
294
|
+
"}"
|
|
295
|
+
].join("\n")
|
|
296
|
+
})
|
|
297
|
+
});
|
|
298
|
+
/**
|
|
299
|
+
* Holds the fragment that widens the IEEE 754 half-precision bits in the low 16 bits of a `u32` to an `f32`.
|
|
300
|
+
*
|
|
301
|
+
* @remarks
|
|
302
|
+
* It declares `fn widen(bits: u32) -> f32`, which builds the result from integer bit operations, so
|
|
303
|
+
* signed zeros, subnormals, infinities, and NaN payloads widen exactly and no `f16` extension is
|
|
304
|
+
* needed. An exponent of `0x1f` keeps the fraction under an all-ones `f32` exponent, so infinities
|
|
305
|
+
* stay infinite and NaN payloads survive. A subnormal half rebuilds its `f32` bits from
|
|
306
|
+
* `firstLeadingBit(fraction)`: the leading bit sets the exponent and the bits under it shift into
|
|
307
|
+
* the `f32` fraction, with no float arithmetic. It reads no binding and no uniform member.
|
|
308
|
+
*
|
|
309
|
+
* @example
|
|
310
|
+
* ```ts
|
|
311
|
+
* WGSL_HALF.name // 'half'
|
|
312
|
+
* ```
|
|
313
|
+
*/
|
|
314
|
+
var WGSL_HALF = Object.freeze({
|
|
315
|
+
name: "half",
|
|
316
|
+
source: [
|
|
317
|
+
"fn widen(bits: u32) -> f32 {",
|
|
318
|
+
" let sign = (bits & 0x8000u) << 16u;",
|
|
319
|
+
" let exponent = (bits >> 10u) & 0x1fu;",
|
|
320
|
+
" let fraction = bits & 0x3ffu;",
|
|
321
|
+
" if (exponent == 0x1fu) {",
|
|
322
|
+
" return bitcast<f32>(sign | 0x7f800000u | (fraction << 13u));",
|
|
323
|
+
" }",
|
|
324
|
+
" if (exponent != 0u) {",
|
|
325
|
+
" return bitcast<f32>(sign | ((exponent + 112u) << 23u) | (fraction << 13u));",
|
|
326
|
+
" }",
|
|
327
|
+
" if (fraction == 0u) {",
|
|
328
|
+
" return bitcast<f32>(sign);",
|
|
329
|
+
" }",
|
|
330
|
+
" let top = firstLeadingBit(fraction);",
|
|
331
|
+
" return bitcast<f32>(sign | ((top + 103u) << 23u) | ((fraction << (23u - top)) & 0x7fffffu));",
|
|
332
|
+
"}"
|
|
333
|
+
].join("\n"),
|
|
334
|
+
uses: Object.freeze([])
|
|
335
|
+
});
|
|
336
|
+
// src/core/errors.ts
|
|
337
|
+
/**
|
|
338
|
+
* Reports one WGSL failure under a stable condition code.
|
|
339
|
+
*
|
|
340
|
+
* @remarks
|
|
341
|
+
* Every refusal the factories, the linker, the helpers, and the slab raise arrives as one of these,
|
|
342
|
+
* so a caller branches on `code` rather than on message text. Narrow a caught value with
|
|
343
|
+
* `isWGSLError` before reading `code`.
|
|
344
|
+
*
|
|
345
|
+
* @example
|
|
346
|
+
* ```ts
|
|
347
|
+
* const error = new WGSLError('The slab capacity must be a multiple of 4.', { code: 'ARGUMENT' })
|
|
348
|
+
* error.code // 'ARGUMENT'
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
var WGSLError = class extends Error {
|
|
352
|
+
name = "WGSLError";
|
|
353
|
+
code;
|
|
354
|
+
context;
|
|
355
|
+
/**
|
|
356
|
+
* Creates one classified WGSL failure.
|
|
357
|
+
*
|
|
358
|
+
* @param message - Human-readable description of what failed
|
|
359
|
+
* @param options - The condition, optional structured context, and optional cause
|
|
360
|
+
*/
|
|
361
|
+
constructor(message, options) {
|
|
362
|
+
super(message, "cause" in options ? { cause: options.cause } : void 0);
|
|
363
|
+
INTRINSICS.define(this, WGSL_ERROR_BRAND, { value: this });
|
|
364
|
+
this.code = options.code;
|
|
365
|
+
this.context = options.context;
|
|
366
|
+
}
|
|
367
|
+
};
|
|
368
|
+
/**
|
|
369
|
+
* Checks whether an unknown value is a WGSL error.
|
|
370
|
+
*
|
|
371
|
+
* @remarks
|
|
372
|
+
* Recognition requires a native `Error` whose prototype is not `Error.prototype`, an own brand
|
|
373
|
+
* property holding the tested value itself, a declared condition code, and an object, callable, or
|
|
374
|
+
* absent context. It recognizes an error from another installed copy of this package, and refuses a
|
|
375
|
+
* look-alike with the same code and no brand, a proxy over a branded error, and a plain object that
|
|
376
|
+
* only carries the brand.
|
|
377
|
+
*
|
|
378
|
+
* @param value - The value to inspect
|
|
379
|
+
* @returns True if the value is a `WGSLError`; false otherwise
|
|
380
|
+
*
|
|
381
|
+
* @example
|
|
382
|
+
* ```ts
|
|
383
|
+
* isWGSLError(new WGSLError('The batch was aborted.', { code: 'ABORT' })) // true
|
|
384
|
+
* isWGSLError(new Error('The batch was aborted.')) // false
|
|
385
|
+
* ```
|
|
386
|
+
*/
|
|
387
|
+
function isWGSLError(value) {
|
|
388
|
+
return holds(() => {
|
|
389
|
+
if (!isError(value) || INTRINSICS.prototype(value) === INTRINSICS.error.prototype) return false;
|
|
390
|
+
if (INTRINSICS.describe(value, WGSL_ERROR_BRAND)?.value !== value) return false;
|
|
391
|
+
const code = INTRINSICS.reflect.read(value, "code");
|
|
392
|
+
const context = INTRINSICS.reflect.read(value, "context");
|
|
393
|
+
return WGSL_ERROR_CODES.some((declared) => declared === code) && (context === void 0 || isObject(context) || isFunction(context));
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
// src/core/validators.ts
|
|
397
|
+
/**
|
|
398
|
+
* Checks whether a value names a scalar type a uniform struct member can hold.
|
|
399
|
+
*
|
|
400
|
+
* @param value - The value to inspect
|
|
401
|
+
* @returns True if the value is one of the `WGSL_SCALARS` members; false otherwise
|
|
402
|
+
*
|
|
403
|
+
* @example
|
|
404
|
+
* ```ts
|
|
405
|
+
* isWGSLScalar('f32') // true
|
|
406
|
+
* isWGSLScalar('f64') // false
|
|
407
|
+
* ```
|
|
408
|
+
*/
|
|
409
|
+
function isWGSLScalar(value) {
|
|
410
|
+
return WGSL_SCALARS.some((scalar) => scalar === value);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Checks whether a value names a storage slot access mode.
|
|
414
|
+
*
|
|
415
|
+
* @param value - The value to inspect
|
|
416
|
+
* @returns True if the value is one of the `WGSL_ACCESSES` members; false otherwise
|
|
417
|
+
*
|
|
418
|
+
* @example
|
|
419
|
+
* ```ts
|
|
420
|
+
* isWGSLAccess('read_write') // true
|
|
421
|
+
* isWGSLAccess('write') // false
|
|
422
|
+
* ```
|
|
423
|
+
*/
|
|
424
|
+
function isWGSLAccess(value) {
|
|
425
|
+
return WGSL_ACCESSES.some((access) => access === value);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Checks whether a value names a WGSL extension a fragment variant can enable.
|
|
429
|
+
*
|
|
430
|
+
* @remarks
|
|
431
|
+
* Only an own key of `WGSL_EXTENSIONS` passes, so an inherited name such as `toString` fails.
|
|
432
|
+
*
|
|
433
|
+
* @param value - The value to inspect
|
|
434
|
+
* @returns True if the value is a key of `WGSL_EXTENSIONS`; false otherwise
|
|
435
|
+
*
|
|
436
|
+
* @example
|
|
437
|
+
* ```ts
|
|
438
|
+
* isWGSLExtension('subgroups') // true
|
|
439
|
+
* isWGSLExtension('shader-f16') // false
|
|
440
|
+
* ```
|
|
441
|
+
*/
|
|
442
|
+
function isWGSLExtension(value) {
|
|
443
|
+
return isString(value) && Object.hasOwn(WGSL_EXTENSIONS, value);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Checks whether a value holds a positive safe integer count on each of three axes.
|
|
447
|
+
*
|
|
448
|
+
* @remarks
|
|
449
|
+
* The value must be an array of length 3, and each of its indices must hold a safe integer of at
|
|
450
|
+
* least 1, so a sparse array, a zero count, and a fraction fail.
|
|
451
|
+
*
|
|
452
|
+
* @param value - The value to inspect
|
|
453
|
+
* @returns True if the value is a `WGSLGrid`; false otherwise
|
|
454
|
+
*
|
|
455
|
+
* @example
|
|
456
|
+
* ```ts
|
|
457
|
+
* isWGSLGrid([64, 1, 1]) // true
|
|
458
|
+
* isWGSLGrid([0, 1, 1]) // false
|
|
459
|
+
* ```
|
|
460
|
+
*/
|
|
461
|
+
function isWGSLGrid(value) {
|
|
462
|
+
if (!isArray(value) || value.length !== 3) return false;
|
|
463
|
+
try {
|
|
464
|
+
const [x, y, z] = value;
|
|
465
|
+
return isSafeInteger(x) && x >= 1 && isSafeInteger(y) && y >= 1 && isSafeInteger(z) && z >= 1;
|
|
466
|
+
} catch {
|
|
467
|
+
return false;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// src/core/helpers.ts
|
|
471
|
+
/**
|
|
472
|
+
* Collects every fragment the roots reach, each once, in dependency order.
|
|
473
|
+
*
|
|
474
|
+
* @remarks
|
|
475
|
+
* The walk is an iterative postorder over each fragment's `uses`, so a fragment follows every
|
|
476
|
+
* fragment it uses. A fragment reached twice, as in a diamond, appears once, keyed on identity.
|
|
477
|
+
* Thrown with code `VALIDATION` when two distinct fragments share one name, and when a fragment
|
|
478
|
+
* reaches itself, with the cycle's names in order in `context.cycle`.
|
|
479
|
+
*
|
|
480
|
+
* @param roots - The fragments an entry body calls, in the order they are listed
|
|
481
|
+
* @returns The reached fragments, frozen
|
|
482
|
+
*
|
|
483
|
+
* @example
|
|
484
|
+
* ```ts
|
|
485
|
+
* const square = createWGSLFragment({ name: 'square', source: 'fn square(value: f32) -> f32 { return value * value; }' })
|
|
486
|
+
* const cube = createWGSLFragment({ name: 'cube', source: 'fn cube(value: f32) -> f32 { return square(value) * value; }', uses: [square] })
|
|
487
|
+
* collectWGSLFragments([cube, square]).map((fragment) => fragment.name) // ['square', 'cube']
|
|
488
|
+
* ```
|
|
489
|
+
*/
|
|
490
|
+
function collectWGSLFragments(roots) {
|
|
491
|
+
const order = [];
|
|
492
|
+
const linked = /* @__PURE__ */ new Set();
|
|
493
|
+
const names = /* @__PURE__ */ new Set();
|
|
494
|
+
const path = [];
|
|
495
|
+
const stack = roots.toReversed().map((root) => [root, false]);
|
|
496
|
+
while (stack.length > 0) {
|
|
497
|
+
const frame = stack.pop();
|
|
498
|
+
if (frame === void 0) break;
|
|
499
|
+
const [fragment, exit] = frame;
|
|
500
|
+
if (exit) {
|
|
501
|
+
path.pop();
|
|
502
|
+
linked.add(fragment);
|
|
503
|
+
order.push(fragment);
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
if (linked.has(fragment)) continue;
|
|
507
|
+
const start = path.indexOf(fragment);
|
|
508
|
+
if (start !== -1) {
|
|
509
|
+
const cycle = [...path.slice(start), fragment].map((member) => member.name);
|
|
510
|
+
throw new WGSLError(`The fragment ${preview(fragment.name)} reaches itself through ${cycle.join(" -> ")}; remove one of these uses.`, {
|
|
511
|
+
code: "VALIDATION",
|
|
512
|
+
context: { cycle }
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
if (names.has(fragment.name)) throw new WGSLError(`Two distinct fragments are named ${preview(fragment.name)}; a linked program holds one fragment per name, so rename one or pass the same fragment object.`, {
|
|
516
|
+
code: "VALIDATION",
|
|
517
|
+
context: { name: fragment.name }
|
|
518
|
+
});
|
|
519
|
+
names.add(fragment.name);
|
|
520
|
+
path.push(fragment);
|
|
521
|
+
stack.push([fragment, true], ...fragment.uses.toReversed().map((used) => [used, false]));
|
|
522
|
+
}
|
|
523
|
+
return Object.freeze(order);
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* Renders a program's complete WGSL text for one set of active extensions.
|
|
527
|
+
*
|
|
528
|
+
* @remarks
|
|
529
|
+
* The text holds, in order: an `enable` directive for each extension a linked fragment's active
|
|
530
|
+
* variant names, in `WGSL_EXTENSIONS` order; the uniform struct declaration; the `Invocation` entry
|
|
531
|
+
* input struct, which carries `local_invocation_index`, `workgroup_id`, and `num_workgroups`, plus
|
|
532
|
+
* `subgroup_invocation_id` and `subgroup_size` when `enable subgroups;` is emitted; one
|
|
533
|
+
* `@group(0) @binding(N)` storage line per slot in declaration order and the `@group(1) @binding(0)`
|
|
534
|
+
* uniform line; each linked fragment's active body, unchanged; and the entry function, which takes
|
|
535
|
+
* the input struct as `invocation`. A fragment's variant is active when `extensions` switches its
|
|
536
|
+
* extension on.
|
|
537
|
+
*
|
|
538
|
+
* @param program - The program to render
|
|
539
|
+
* @param extensions - Whether each extension is active
|
|
540
|
+
* @returns The WGSL text, ending in a line feed
|
|
541
|
+
*
|
|
542
|
+
* @example
|
|
543
|
+
* ```ts
|
|
544
|
+
* renderWGSLProgram(program, { f16: false, subgroups: false }).startsWith('struct Shape {') // true
|
|
545
|
+
* ```
|
|
546
|
+
*/
|
|
547
|
+
function renderWGSLProgram(program, extensions) {
|
|
548
|
+
const variants = program.fragments.map((fragment) => fragment.variant !== void 0 && extensions[fragment.variant.extension] ? fragment.variant : void 0);
|
|
549
|
+
const enabled = Object.keys(WGSL_EXTENSIONS).filter((name) => variants.some((variant) => variant?.extension === name));
|
|
550
|
+
const invocation = [
|
|
551
|
+
"struct Invocation {",
|
|
552
|
+
" @builtin(local_invocation_index) local_invocation_index: u32,",
|
|
553
|
+
" @builtin(workgroup_id) workgroup_id: vec3u,",
|
|
554
|
+
" @builtin(num_workgroups) num_workgroups: vec3u,",
|
|
555
|
+
...enabled.includes("subgroups") ? [" @builtin(subgroup_invocation_id) subgroup_invocation_id: u32,", " @builtin(subgroup_size) subgroup_size: u32,"] : [],
|
|
556
|
+
"}"
|
|
557
|
+
];
|
|
558
|
+
const bindings = [...Object.entries(program.slots).map(([name, slot], index) => `@group(0) @binding(${index}) var<storage, ${slot.access}> ${name}: array<${slot.element}>;`), `@group(1) @binding(0) var<uniform> ${program.uniform.name}: ${program.uniform.struct.name};`];
|
|
559
|
+
const bodies = program.fragments.map((fragment, index) => variants[index]?.source ?? fragment.source);
|
|
560
|
+
const [x, y, z] = program.entry.size;
|
|
561
|
+
const entry = [
|
|
562
|
+
`@compute @workgroup_size(${x}, ${y}, ${z})`,
|
|
563
|
+
`fn ${program.entry.name}(invocation: Invocation) {`,
|
|
564
|
+
program.entry.source,
|
|
565
|
+
"}"
|
|
566
|
+
];
|
|
567
|
+
return `${[
|
|
568
|
+
enabled.map((name) => `enable ${name};`).join("\n"),
|
|
569
|
+
program.uniform.struct.source,
|
|
570
|
+
invocation.join("\n"),
|
|
571
|
+
bindings.join("\n"),
|
|
572
|
+
...bodies,
|
|
573
|
+
entry.join("\n")
|
|
574
|
+
].filter((section) => section.length > 0).join("\n\n")}\n`;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Computes a dispatch's workgroup counts for a total: the x axis up to the limit, then the y axis.
|
|
578
|
+
*
|
|
579
|
+
* @remarks
|
|
580
|
+
* A program reads its workgroup's index as
|
|
581
|
+
* `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, so a
|
|
582
|
+
* workgroup past the total finds no work. A total of 0 gives one workgroup. Thrown with code
|
|
583
|
+
* `ARGUMENT` when `total` is not a non-negative safe integer, `-0` included, or `limit` is not a
|
|
584
|
+
* positive safe integer, and with code `LIMIT` when the total passes `limit * limit`.
|
|
585
|
+
*
|
|
586
|
+
* @param total - The number of workgroups
|
|
587
|
+
* @param limit - The device's `maxComputeWorkgroupsPerDimension`
|
|
588
|
+
* @returns The counts on the x, y, and z axes
|
|
589
|
+
*
|
|
590
|
+
* @example
|
|
591
|
+
* ```ts
|
|
592
|
+
* computeWGSLGrid(70_000, 65_535) // [65535, 2, 1]
|
|
593
|
+
* ```
|
|
594
|
+
*/
|
|
595
|
+
function computeWGSLGrid(total, limit) {
|
|
596
|
+
if (!isNonNegativeInteger(total) || !isSafeInteger(total)) throw new WGSLError(`A workgroup total must be a non-negative safe integer; received ${preview(total)}.`, {
|
|
597
|
+
code: "ARGUMENT",
|
|
598
|
+
context: { total }
|
|
599
|
+
});
|
|
600
|
+
if (!isSafeInteger(limit) || limit < 1) throw new WGSLError(`A per-axis workgroup limit must be a positive safe integer; received ${preview(limit)}.`, {
|
|
601
|
+
code: "ARGUMENT",
|
|
602
|
+
context: { limit }
|
|
603
|
+
});
|
|
604
|
+
const x = Math.max(1, Math.min(total, limit));
|
|
605
|
+
const y = Math.max(1, Math.ceil(total / x));
|
|
606
|
+
if (y > limit) throw new WGSLError(`A dispatch of ${total} workgroups passes the limit of ${limit} on each of two axes; split it into dispatches of at most ${limit * limit} workgroups.`, {
|
|
607
|
+
code: "LIMIT",
|
|
608
|
+
context: {
|
|
609
|
+
total,
|
|
610
|
+
limit
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
return Object.freeze([
|
|
614
|
+
x,
|
|
615
|
+
y,
|
|
616
|
+
1
|
|
617
|
+
]);
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Computes the smallest multiple of an alignment at or above an offset.
|
|
621
|
+
*
|
|
622
|
+
* @remarks
|
|
623
|
+
* Thrown with code `ARGUMENT` when `offset` is not a non-negative safe integer, `-0` included, or
|
|
624
|
+
* `alignment` is not a positive safe integer.
|
|
625
|
+
*
|
|
626
|
+
* @param offset - The byte offset to align
|
|
627
|
+
* @param alignment - The byte alignment
|
|
628
|
+
* @returns The aligned byte offset
|
|
629
|
+
*
|
|
630
|
+
* @example
|
|
631
|
+
* ```ts
|
|
632
|
+
* computeWGSLOffset(36, 256) // 256
|
|
633
|
+
* ```
|
|
634
|
+
*/
|
|
635
|
+
function computeWGSLOffset(offset, alignment) {
|
|
636
|
+
if (!isNonNegativeInteger(offset) || !isSafeInteger(offset)) throw new WGSLError(`A byte offset must be a non-negative safe integer; received ${preview(offset)}.`, {
|
|
637
|
+
code: "ARGUMENT",
|
|
638
|
+
context: { offset }
|
|
639
|
+
});
|
|
640
|
+
if (!isSafeInteger(alignment) || alignment < 1) throw new WGSLError(`A byte alignment must be a positive safe integer; received ${preview(alignment)}.`, {
|
|
641
|
+
code: "ARGUMENT",
|
|
642
|
+
context: { alignment }
|
|
643
|
+
});
|
|
644
|
+
return Math.ceil(offset / alignment) * alignment;
|
|
645
|
+
}
|
|
646
|
+
// src/core/WGSLBatch.ts
|
|
647
|
+
/**
|
|
648
|
+
* Records one command encoder's worth of dispatches and buffer reads, then submits them together.
|
|
649
|
+
*
|
|
650
|
+
* @remarks
|
|
651
|
+
* The batch owns its command encoder and its compute pass, and keeps one pass open across
|
|
652
|
+
* consecutive `encode` calls, skipping a `setPipeline` or a `setBindGroup(0, ...)` that repeats the
|
|
653
|
+
* previous one. Each dispatch writes its uniform values to the session's slab and binds them through
|
|
654
|
+
* the 5-argument `setBindGroup(1, group, offsets, 0, 1)` overload. When the slab is full, the batch
|
|
655
|
+
* ends its pass, uploads the slab, submits, clears the slab, and opens a fresh encoder. The pass
|
|
656
|
+
* ends before each `read` copy. Every upload and submit sits between a synchronous push and pop of a
|
|
657
|
+
* `validation` and an `out-of-memory` error scope; a device error on a submitted command buffer
|
|
658
|
+
* moves the session to `failed` with code `VALIDATION`. `read` resolves after the submission to a
|
|
659
|
+
* caller-owned copy of the bytes. Thrown with code `VALIDATION` when a call other than `abort` or
|
|
660
|
+
* `execute` arrives after `submit` or `abort`; with code `ARGUMENT` for a malformed grid or read
|
|
661
|
+
* range; and with code `LIMIT` when a grid axis passes the device's
|
|
662
|
+
* `maxComputeWorkgroupsPerDimension`. Open a batch through `session.batch()`, which supplies the
|
|
663
|
+
* options.
|
|
664
|
+
*
|
|
665
|
+
* @example
|
|
666
|
+
* ```ts
|
|
667
|
+
* const batch = session.batch()
|
|
668
|
+
* batch.encode(binding, { count: 64 }, [1, 1, 1])
|
|
669
|
+
* const bytes = batch.read(buffer, 0, 256)
|
|
670
|
+
* await batch.execute()
|
|
671
|
+
* new Uint32Array(await bytes)[0] // the first word the dispatch wrote
|
|
672
|
+
* ```
|
|
673
|
+
*/
|
|
674
|
+
var WGSLBatch = class {
|
|
675
|
+
#device;
|
|
676
|
+
#limit;
|
|
677
|
+
#options;
|
|
678
|
+
#checkSession;
|
|
679
|
+
#slab;
|
|
680
|
+
#offsets = /* @__PURE__ */ new Uint32Array(1);
|
|
681
|
+
#submissions = [];
|
|
682
|
+
#reads = [];
|
|
683
|
+
#result = Promise.withResolvers();
|
|
684
|
+
#encoder;
|
|
685
|
+
#pass;
|
|
686
|
+
#pipeline;
|
|
687
|
+
#group;
|
|
688
|
+
#binding;
|
|
689
|
+
#uniform;
|
|
690
|
+
#status = "open";
|
|
691
|
+
/**
|
|
692
|
+
* Creates an open batch with a fresh command encoder.
|
|
693
|
+
*
|
|
694
|
+
* @param device - The device whose encoder records the commands and whose queue runs them
|
|
695
|
+
* @param options - The session's slab and the session hooks
|
|
696
|
+
*/
|
|
697
|
+
constructor(device, options) {
|
|
698
|
+
this.#device = device;
|
|
699
|
+
this.#limit = device.limits.maxComputeWorkgroupsPerDimension;
|
|
700
|
+
this.#options = options;
|
|
701
|
+
this.#checkSession = options.check;
|
|
702
|
+
this.#slab = options.slab;
|
|
703
|
+
this.#encoder = device.createCommandEncoder();
|
|
704
|
+
}
|
|
705
|
+
get submitted() {
|
|
706
|
+
return this.#status === "submitted";
|
|
707
|
+
}
|
|
708
|
+
encode(binding, values, grid) {
|
|
709
|
+
this.#checkSession();
|
|
710
|
+
if (this.#status !== "open") this.#check();
|
|
711
|
+
if (!Array.isArray(grid) || grid.length !== 3) this.#refuseGrid(grid);
|
|
712
|
+
const x = grid[0];
|
|
713
|
+
const y = grid[1];
|
|
714
|
+
const z = grid[2];
|
|
715
|
+
if (typeof x !== "number" || typeof y !== "number" || typeof z !== "number" || x < 1 || y < 1 || z < 1 || (x | 0) !== x && !Number.isSafeInteger(x) || (y | 0) !== y && !Number.isSafeInteger(y) || (z | 0) !== z && !Number.isSafeInteger(z)) this.#refuseGrid(grid);
|
|
716
|
+
const limit = this.#limit;
|
|
717
|
+
if (x > limit || y > limit || z > limit) throw new WGSLError(`The grid [${x}, ${y}, ${z}] passes the device's ${limit} workgroups per axis; compute the grid with computeWGSLGrid or split the dispatch.`, {
|
|
718
|
+
code: "LIMIT",
|
|
719
|
+
context: {
|
|
720
|
+
grid: [
|
|
721
|
+
x,
|
|
722
|
+
y,
|
|
723
|
+
z
|
|
724
|
+
],
|
|
725
|
+
limit
|
|
726
|
+
}
|
|
727
|
+
});
|
|
728
|
+
const { statement } = binding;
|
|
729
|
+
const struct = statement.program.uniform.struct;
|
|
730
|
+
const written = this.#slab.write(struct, values);
|
|
731
|
+
const offset = written === void 0 ? this.#flushWrite(struct, values) : written;
|
|
732
|
+
if (this.#binding === binding && this.#pass !== void 0 && this.#uniform !== void 0) {
|
|
733
|
+
this.#offsets[0] = offset;
|
|
734
|
+
this.#pass.setBindGroup(1, this.#uniform, this.#offsets, 0, 1);
|
|
735
|
+
this.#pass.dispatchWorkgroups(x, y, z);
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
const pass = this.#pass ?? this.#open();
|
|
739
|
+
if (this.#pipeline !== statement.pipeline) {
|
|
740
|
+
pass.setPipeline(statement.pipeline);
|
|
741
|
+
this.#pipeline = statement.pipeline;
|
|
742
|
+
}
|
|
743
|
+
if (this.#group !== binding.group) {
|
|
744
|
+
pass.setBindGroup(0, binding.group);
|
|
745
|
+
this.#group = binding.group;
|
|
746
|
+
}
|
|
747
|
+
this.#binding = binding;
|
|
748
|
+
this.#uniform = statement.uniform;
|
|
749
|
+
this.#offsets[0] = offset;
|
|
750
|
+
pass.setBindGroup(1, statement.uniform, this.#offsets, 0, 1);
|
|
751
|
+
pass.dispatchWorkgroups(x, y, z);
|
|
752
|
+
}
|
|
753
|
+
read(buffer, offset, size) {
|
|
754
|
+
this.#check();
|
|
755
|
+
if ((buffer.usage & WGSL_USAGE.source) === 0) throw new WGSLError(`A read needs a buffer with the source usage (WGSL_USAGE.source), so the batch can copy it; its usage is ${buffer.usage}.`, {
|
|
756
|
+
code: "ARGUMENT",
|
|
757
|
+
context: { usage: buffer.usage }
|
|
758
|
+
});
|
|
759
|
+
if (!isNonNegativeInteger(offset) || !isSafeInteger(offset) || offset % 4 !== 0) throw new WGSLError(`A read starts at ${preview(offset)}; a read offset must be a non-negative safe multiple of 4 bytes.`, {
|
|
760
|
+
code: "ARGUMENT",
|
|
761
|
+
context: { offset }
|
|
762
|
+
});
|
|
763
|
+
if (!isSafeInteger(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`A read spans ${preview(size)} bytes; a read size must be a safe multiple of 4 bytes, at least 4.`, {
|
|
764
|
+
code: "ARGUMENT",
|
|
765
|
+
context: { size }
|
|
766
|
+
});
|
|
767
|
+
if (offset + size > buffer.size) throw new WGSLError(`A read ends at byte ${offset + size}, past its buffer's ${buffer.size} bytes; shorten the range.`, {
|
|
768
|
+
code: "ARGUMENT",
|
|
769
|
+
context: {
|
|
770
|
+
offset,
|
|
771
|
+
size,
|
|
772
|
+
length: buffer.size
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
this.#close();
|
|
776
|
+
const staging = this.#options.lease(size);
|
|
777
|
+
this.#encoder.copyBufferToBuffer(buffer, offset, staging, 0, size);
|
|
778
|
+
const result = Promise.withResolvers();
|
|
779
|
+
result.promise.catch(() => void 0);
|
|
780
|
+
this.#reads.push([
|
|
781
|
+
staging,
|
|
782
|
+
size,
|
|
783
|
+
result
|
|
784
|
+
]);
|
|
785
|
+
return result.promise;
|
|
786
|
+
}
|
|
787
|
+
submit() {
|
|
788
|
+
this.#check();
|
|
789
|
+
this.#close();
|
|
790
|
+
this.#commit();
|
|
791
|
+
this.#status = "submitted";
|
|
792
|
+
this.#options.release(this);
|
|
793
|
+
this.#result.resolve(this.#finish());
|
|
794
|
+
this.#options.track(this.#result.promise);
|
|
795
|
+
}
|
|
796
|
+
async execute(signal) {
|
|
797
|
+
if (signal?.aborted === true) {
|
|
798
|
+
this.abort();
|
|
799
|
+
throw new WGSLError("The signal aborted the batch before it finished.", {
|
|
800
|
+
code: "ABORT",
|
|
801
|
+
cause: signal.reason
|
|
802
|
+
});
|
|
803
|
+
}
|
|
804
|
+
if (this.#status === "open") this.submit();
|
|
805
|
+
const failure = signal === void 0 ? await this.#result.promise : await this.#race(signal);
|
|
806
|
+
if (failure !== void 0) throw failure;
|
|
807
|
+
}
|
|
808
|
+
abort() {
|
|
809
|
+
const error = new WGSLError("The batch was aborted, and its pending reads were rejected.", { code: "ABORT" });
|
|
810
|
+
for (const [, , result] of this.#reads) result.reject(error);
|
|
811
|
+
if (this.#status !== "open") return;
|
|
812
|
+
this.#status = "aborted";
|
|
813
|
+
this.#slab.clear();
|
|
814
|
+
for (const [staging] of this.#reads) this.#options.restore(staging);
|
|
815
|
+
this.#options.release(this);
|
|
816
|
+
this.#result.resolve(this.#discard(error));
|
|
817
|
+
this.#options.track(this.#result.promise);
|
|
818
|
+
}
|
|
819
|
+
#check() {
|
|
820
|
+
this.#options.check();
|
|
821
|
+
if (this.#status !== "open") throw new WGSLError(`The batch is ${this.#status} and takes no more commands; open another with session.batch().`, {
|
|
822
|
+
code: "VALIDATION",
|
|
823
|
+
context: { status: this.#status }
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
#refuseGrid(grid) {
|
|
827
|
+
throw new WGSLError(`A dispatch grid must hold three positive safe integer workgroup counts, such as [4, 1, 1]; received ${preview(grid)}.`, {
|
|
828
|
+
code: "ARGUMENT",
|
|
829
|
+
context: { grid }
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
#flushWrite(struct, values) {
|
|
833
|
+
this.#flush();
|
|
834
|
+
const retry = this.#slab.write(struct, values);
|
|
835
|
+
if (retry === void 0) throw new WGSLError(`The struct ${preview(struct.name)} does not fit an empty slab of ${this.#slab.capacity} bytes; raise the session's uniform size.`, {
|
|
836
|
+
code: "LIMIT",
|
|
837
|
+
context: {
|
|
838
|
+
name: struct.name,
|
|
839
|
+
size: struct.size
|
|
840
|
+
}
|
|
841
|
+
});
|
|
842
|
+
return retry;
|
|
843
|
+
}
|
|
844
|
+
#open() {
|
|
845
|
+
if (this.#pass !== void 0) return this.#pass;
|
|
846
|
+
const pass = this.#encoder.beginComputePass();
|
|
847
|
+
this.#pass = pass;
|
|
848
|
+
return pass;
|
|
849
|
+
}
|
|
850
|
+
#close() {
|
|
851
|
+
this.#pass?.end();
|
|
852
|
+
this.#pass = void 0;
|
|
853
|
+
this.#pipeline = void 0;
|
|
854
|
+
this.#group = void 0;
|
|
855
|
+
this.#binding = void 0;
|
|
856
|
+
this.#uniform = void 0;
|
|
857
|
+
}
|
|
858
|
+
#flush() {
|
|
859
|
+
this.#close();
|
|
860
|
+
this.#commit();
|
|
861
|
+
this.#encoder = this.#device.createCommandEncoder();
|
|
862
|
+
}
|
|
863
|
+
#commit() {
|
|
864
|
+
const device = this.#device;
|
|
865
|
+
device.pushErrorScope("out-of-memory");
|
|
866
|
+
device.pushErrorScope("validation");
|
|
867
|
+
this.#options.slab.upload();
|
|
868
|
+
device.queue.submit([this.#encoder.finish()]);
|
|
869
|
+
const validation = device.popErrorScope();
|
|
870
|
+
const memory = device.popErrorScope();
|
|
871
|
+
this.#slab.clear();
|
|
872
|
+
this.#submissions.push(this.#scope(validation, memory));
|
|
873
|
+
}
|
|
874
|
+
async #scope(validation, memory) {
|
|
875
|
+
try {
|
|
876
|
+
const [invalid, exhausted] = await Promise.all([validation, memory]);
|
|
877
|
+
const error = invalid ?? exhausted;
|
|
878
|
+
if (error === null) return void 0;
|
|
879
|
+
const filter = invalid === null ? "out-of-memory" : "validation";
|
|
880
|
+
return new WGSLError(`The device refused a submitted batch (${filter}): ${error.message}`, {
|
|
881
|
+
code: "VALIDATION",
|
|
882
|
+
context: {
|
|
883
|
+
filter,
|
|
884
|
+
message: error.message
|
|
885
|
+
}
|
|
886
|
+
});
|
|
887
|
+
} catch (cause) {
|
|
888
|
+
return new WGSLError(`The device stopped reporting a submitted batch's errors: ${errorToMessage(cause)}`, {
|
|
889
|
+
code: "HOST",
|
|
890
|
+
cause
|
|
891
|
+
});
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
async #drain() {
|
|
895
|
+
try {
|
|
896
|
+
const done = this.#device.queue.onSubmittedWorkDone();
|
|
897
|
+
const [errors] = await Promise.all([Promise.all(this.#submissions), done]);
|
|
898
|
+
const failure = errors.find((error) => error !== void 0);
|
|
899
|
+
if (failure !== void 0) this.#options.fail(failure);
|
|
900
|
+
return failure;
|
|
901
|
+
} catch (cause) {
|
|
902
|
+
const failure = new WGSLError(`The device stopped before the batch finished: ${errorToMessage(cause)}`, {
|
|
903
|
+
code: "HOST",
|
|
904
|
+
cause
|
|
905
|
+
});
|
|
906
|
+
this.#options.fail(failure);
|
|
907
|
+
return failure;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
async #finish() {
|
|
911
|
+
const failure = await this.#drain();
|
|
912
|
+
if (failure === void 0) {
|
|
913
|
+
await Promise.all(this.#reads.map((read) => this.#map(read)));
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
for (const [staging, , result] of this.#reads) {
|
|
917
|
+
result.reject(failure);
|
|
918
|
+
this.#options.restore(staging);
|
|
919
|
+
}
|
|
920
|
+
return failure;
|
|
921
|
+
}
|
|
922
|
+
async #discard(error) {
|
|
923
|
+
return await this.#drain() ?? error;
|
|
924
|
+
}
|
|
925
|
+
async #map(read) {
|
|
926
|
+
const [staging, size, result] = read;
|
|
927
|
+
try {
|
|
928
|
+
await staging.mapAsync(WGSL_MAP.read, 0, size);
|
|
929
|
+
result.resolve(staging.getMappedRange(0, size).slice(0));
|
|
930
|
+
staging.unmap();
|
|
931
|
+
} catch (cause) {
|
|
932
|
+
const error = new WGSLError(`The device could not map a read: ${errorToMessage(cause)}`, {
|
|
933
|
+
code: "HOST",
|
|
934
|
+
cause
|
|
935
|
+
});
|
|
936
|
+
result.reject(error);
|
|
937
|
+
} finally {
|
|
938
|
+
this.#options.restore(staging);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
async #race(signal) {
|
|
942
|
+
const cleanup = new AbortController();
|
|
943
|
+
const aborted = new Promise((resolve) => {
|
|
944
|
+
signal.addEventListener("abort", () => {
|
|
945
|
+
this.abort();
|
|
946
|
+
resolve(new WGSLError("The signal aborted the batch while it ran.", {
|
|
947
|
+
code: "ABORT",
|
|
948
|
+
cause: signal.reason
|
|
949
|
+
}));
|
|
950
|
+
}, {
|
|
951
|
+
once: true,
|
|
952
|
+
signal: cleanup.signal
|
|
953
|
+
});
|
|
954
|
+
});
|
|
955
|
+
try {
|
|
956
|
+
return await Promise.race([this.#result.promise, aborted]);
|
|
957
|
+
} finally {
|
|
958
|
+
cleanup.abort();
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
};
|
|
962
|
+
// src/core/WGSLSlab.ts
|
|
963
|
+
/**
|
|
964
|
+
* Packs each dispatch's uniform values into one host buffer at the device's uniform offset alignment and uploads them in one write.
|
|
965
|
+
*
|
|
966
|
+
* @remarks
|
|
967
|
+
* The slab owns one `ArrayBuffer` with a `Uint32Array` view and a `Float32Array` view over it, and
|
|
968
|
+
* steps a struct's frozen `members` for each write. An `f32` member writes through the float view,
|
|
969
|
+
* so `-0` and subnormals keep their binary32 patterns; a `u32` or `i32` member writes through the
|
|
970
|
+
* unsigned view, so `-5` stores `0xFFFFFFFB`. Each write starts at the next multiple of the
|
|
971
|
+
* device's `minUniformBufferOffsetAlignment`. A write that meets a missing value zeroes the span it
|
|
972
|
+
* started and throws, so the bytes past `used` stay zero. `clear` zeroes the bytes the written
|
|
973
|
+
* values spanned.
|
|
974
|
+
* The constructor throws with code `ARGUMENT` when `capacity` is not a positive safe multiple of 4
|
|
975
|
+
* or passes the buffer's size, when the buffer lacks the `uniform` or `destination` usage, and when
|
|
976
|
+
* the device reports an alignment that is not a positive safe multiple of 4.
|
|
977
|
+
*
|
|
978
|
+
* @example
|
|
979
|
+
* ```ts
|
|
980
|
+
* const slab = new WGSLSlab(device, { buffer, capacity: 65536 })
|
|
981
|
+
* slab.write(createWGSLStruct('Shape', { rows: 'u32' }), { rows: 64 }) // 0
|
|
982
|
+
* slab.upload()
|
|
983
|
+
* ```
|
|
984
|
+
*/
|
|
985
|
+
var WGSLSlab = class {
|
|
986
|
+
#device;
|
|
987
|
+
#buffer;
|
|
988
|
+
#capacity;
|
|
989
|
+
#alignment;
|
|
990
|
+
#mask;
|
|
991
|
+
#bytes;
|
|
992
|
+
#words;
|
|
993
|
+
#floats;
|
|
994
|
+
#used = 0;
|
|
995
|
+
/**
|
|
996
|
+
* Creates an empty slab over a uniform buffer.
|
|
997
|
+
*
|
|
998
|
+
* @param device - The device whose queue receives the upload and whose limits set the alignment
|
|
999
|
+
* @param options - The uniform buffer and the slab's byte capacity
|
|
1000
|
+
*/
|
|
1001
|
+
constructor(device, options) {
|
|
1002
|
+
const { buffer, capacity } = options;
|
|
1003
|
+
const alignment = device.limits.minUniformBufferOffsetAlignment;
|
|
1004
|
+
if (!isSafeInteger(capacity) || capacity < 4 || capacity % 4 !== 0) throw new WGSLError(`A slab capacity must be a positive safe multiple of 4 bytes; received ${preview(capacity)}.`, {
|
|
1005
|
+
code: "ARGUMENT",
|
|
1006
|
+
context: { capacity }
|
|
1007
|
+
});
|
|
1008
|
+
if ((buffer.usage & WGSL_USAGE.uniform) === 0 || (buffer.usage & WGSL_USAGE.destination) === 0) throw new WGSLError(`A slab buffer must carry the uniform and destination usages (WGSL_USAGE.uniform | WGSL_USAGE.destination); its usage is ${buffer.usage}.`, {
|
|
1009
|
+
code: "ARGUMENT",
|
|
1010
|
+
context: { usage: buffer.usage }
|
|
1011
|
+
});
|
|
1012
|
+
if (capacity > buffer.size) throw new WGSLError(`A slab capacity of ${capacity} bytes passes its buffer's ${buffer.size} bytes.`, {
|
|
1013
|
+
code: "ARGUMENT",
|
|
1014
|
+
context: {
|
|
1015
|
+
capacity,
|
|
1016
|
+
size: buffer.size
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
if (!isSafeInteger(alignment) || alignment < 4 || alignment % 4 !== 0) throw new WGSLError(`The device reports a minUniformBufferOffsetAlignment of ${preview(alignment)}; a slab needs a positive safe multiple of 4.`, {
|
|
1020
|
+
code: "ARGUMENT",
|
|
1021
|
+
context: { alignment }
|
|
1022
|
+
});
|
|
1023
|
+
this.#device = device;
|
|
1024
|
+
this.#buffer = buffer;
|
|
1025
|
+
this.#capacity = capacity;
|
|
1026
|
+
this.#alignment = alignment;
|
|
1027
|
+
this.#mask = capacity <= 0x40000000 && alignment <= 0x40000000 && (alignment & alignment - 1) === 0 ? alignment - 1 : -1;
|
|
1028
|
+
this.#bytes = new ArrayBuffer(capacity);
|
|
1029
|
+
this.#words = new Uint32Array(this.#bytes);
|
|
1030
|
+
this.#floats = new Float32Array(this.#bytes);
|
|
1031
|
+
}
|
|
1032
|
+
get capacity() {
|
|
1033
|
+
return this.#capacity;
|
|
1034
|
+
}
|
|
1035
|
+
get used() {
|
|
1036
|
+
return this.#used;
|
|
1037
|
+
}
|
|
1038
|
+
write(struct, values) {
|
|
1039
|
+
const offset = this.#mask >= 0 ? this.#used + this.#mask & ~this.#mask : this.#used % this.#alignment === 0 ? this.#used : this.#used + (this.#alignment - this.#used % this.#alignment);
|
|
1040
|
+
if (offset + struct.size > this.#capacity) {
|
|
1041
|
+
if (struct.size > this.#capacity) throw new WGSLError(`The struct ${preview(struct.name)} takes ${struct.size} bytes, more than the slab's ${this.#capacity}; raise the uniform size.`, {
|
|
1042
|
+
code: "ARGUMENT",
|
|
1043
|
+
context: {
|
|
1044
|
+
name: struct.name,
|
|
1045
|
+
size: struct.size
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
const record = values;
|
|
1051
|
+
const base = this.#mask >= 0 ? offset >>> 2 : offset / 4;
|
|
1052
|
+
const { members } = struct;
|
|
1053
|
+
const first = members[0];
|
|
1054
|
+
if (members.length === 1 && first !== void 0) {
|
|
1055
|
+
const value = record[first.name];
|
|
1056
|
+
if (typeof value !== "number") throw new WGSLError(`The values for ${preview(struct.name)} carry no number for the field ${preview(first.name)}.`, {
|
|
1057
|
+
code: "ARGUMENT",
|
|
1058
|
+
context: {
|
|
1059
|
+
name: struct.name,
|
|
1060
|
+
field: first.name
|
|
1061
|
+
}
|
|
1062
|
+
});
|
|
1063
|
+
if (first.element === "f32") this.#floats[base + first.word] = value;
|
|
1064
|
+
else this.#words[base + first.word] = value;
|
|
1065
|
+
this.#used = offset + struct.size;
|
|
1066
|
+
return offset;
|
|
1067
|
+
}
|
|
1068
|
+
for (const member of members) {
|
|
1069
|
+
const value = record[member.name];
|
|
1070
|
+
if (typeof value !== "number") {
|
|
1071
|
+
this.#words.fill(0, base, base + struct.size / 4);
|
|
1072
|
+
throw new WGSLError(`The values for ${preview(struct.name)} carry no number for the field ${preview(member.name)}.`, {
|
|
1073
|
+
code: "ARGUMENT",
|
|
1074
|
+
context: {
|
|
1075
|
+
name: struct.name,
|
|
1076
|
+
field: member.name
|
|
1077
|
+
}
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
if (member.element === "f32") this.#floats[base + member.word] = value;
|
|
1081
|
+
else this.#words[base + member.word] = value;
|
|
1082
|
+
}
|
|
1083
|
+
this.#used = offset + struct.size;
|
|
1084
|
+
return offset;
|
|
1085
|
+
}
|
|
1086
|
+
upload() {
|
|
1087
|
+
if (this.#used === 0) return;
|
|
1088
|
+
this.#device.queue.writeBuffer(this.#buffer, 0, this.#bytes, 0, this.#used);
|
|
1089
|
+
}
|
|
1090
|
+
clear() {
|
|
1091
|
+
this.#words.fill(0, 0, this.#used / 4);
|
|
1092
|
+
this.#used = 0;
|
|
1093
|
+
}
|
|
1094
|
+
};
|
|
1095
|
+
// src/core/WGSLStatement.ts
|
|
1096
|
+
/**
|
|
1097
|
+
* Runs one prepared program on its session's device and caches a storage bind group per set of slot ranges.
|
|
1098
|
+
*
|
|
1099
|
+
* @remarks
|
|
1100
|
+
* `bind` walks a per-statement `WeakMap` trie keyed on each slot's buffer, byte offset, and byte
|
|
1101
|
+
* size, so a repeated range set returns the same `WGSLBinding` without allocating, and a destroyed
|
|
1102
|
+
* buffer's entries leave with the buffer. A range set the trie lacks is checked before its bind
|
|
1103
|
+
* group is created: thrown with code `ARGUMENT` when the slot names differ from the program's, when
|
|
1104
|
+
* a buffer lacks the `storage` usage, when an offset is not a multiple of the device's
|
|
1105
|
+
* `minStorageBufferOffsetAlignment`, when a size is under 4 bytes or not a multiple of 4, and when a
|
|
1106
|
+
* range passes its buffer's end; with code `LIMIT` when a size passes the device's
|
|
1107
|
+
* `maxStorageBufferBindingSize`; and with code `VALIDATION` when a `read_write` slot shares its
|
|
1108
|
+
* `GPUBuffer` with any other slot, even over disjoint ranges, because Dawn refuses that pair.
|
|
1109
|
+
* `execute` opens a batch on the session, records one dispatch, and resolves when the device
|
|
1110
|
+
* finishes it.
|
|
1111
|
+
*
|
|
1112
|
+
* @example
|
|
1113
|
+
* ```ts
|
|
1114
|
+
* const statement = await session.prepare(program)
|
|
1115
|
+
* const binding = statement.bind({ destination: { buffer } })
|
|
1116
|
+
* await statement.execute(binding, { count: 64 }, [1, 1, 1])
|
|
1117
|
+
* ```
|
|
1118
|
+
*/
|
|
1119
|
+
var WGSLStatement = class {
|
|
1120
|
+
program;
|
|
1121
|
+
pipeline;
|
|
1122
|
+
uniform;
|
|
1123
|
+
#session;
|
|
1124
|
+
#layout;
|
|
1125
|
+
#slots;
|
|
1126
|
+
#root;
|
|
1127
|
+
/**
|
|
1128
|
+
* Creates a statement over a pipeline its session prepared.
|
|
1129
|
+
*
|
|
1130
|
+
* @param session - The session whose device creates the bind groups and whose batches run the dispatches
|
|
1131
|
+
* @param options - The program, the pipeline, the storage layout, and the uniform bind group
|
|
1132
|
+
*/
|
|
1133
|
+
constructor(session, options) {
|
|
1134
|
+
const slots = options.program.slots;
|
|
1135
|
+
this.program = options.program;
|
|
1136
|
+
this.pipeline = options.pipeline;
|
|
1137
|
+
this.uniform = options.uniform;
|
|
1138
|
+
this.#session = session;
|
|
1139
|
+
this.#layout = options.layout;
|
|
1140
|
+
this.#slots = Object.freeze(Object.entries(slots));
|
|
1141
|
+
this.#root = {
|
|
1142
|
+
next: /* @__PURE__ */ new WeakMap(),
|
|
1143
|
+
binding: this.#slots.length === 0 ? this.#create([]) : void 0
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
bind(buffers) {
|
|
1147
|
+
const record = buffers;
|
|
1148
|
+
const cached = this.#find(this.#root, record, 0);
|
|
1149
|
+
if (cached !== void 0) return cached;
|
|
1150
|
+
const entries = this.#resolve(record);
|
|
1151
|
+
const binding = this.#create(entries);
|
|
1152
|
+
this.#store(this.#root, entries, 0, binding);
|
|
1153
|
+
return binding;
|
|
1154
|
+
}
|
|
1155
|
+
async execute(binding, values, grid, signal) {
|
|
1156
|
+
const batch = this.#session.batch();
|
|
1157
|
+
try {
|
|
1158
|
+
batch.encode(binding, values, grid);
|
|
1159
|
+
} catch (error) {
|
|
1160
|
+
batch.abort();
|
|
1161
|
+
throw error;
|
|
1162
|
+
}
|
|
1163
|
+
await batch.execute(signal);
|
|
1164
|
+
}
|
|
1165
|
+
#find(node, record, depth) {
|
|
1166
|
+
const entry = this.#slots[depth];
|
|
1167
|
+
if (entry === void 0) return node.binding;
|
|
1168
|
+
const binding = record[entry[0]];
|
|
1169
|
+
if (!isObject(binding)) return void 0;
|
|
1170
|
+
const offset = binding.offset ?? 0;
|
|
1171
|
+
const next = (node.next.get(binding.buffer)?.get(offset))?.get(binding.size ?? binding.buffer.size - offset);
|
|
1172
|
+
return next === void 0 ? void 0 : this.#find(next, record, depth + 1);
|
|
1173
|
+
}
|
|
1174
|
+
#resolve(record) {
|
|
1175
|
+
const name = this.program.name;
|
|
1176
|
+
const names = this.#slots.map(([slot]) => slot);
|
|
1177
|
+
const extra = Object.keys(record).filter((key) => !names.includes(key));
|
|
1178
|
+
const missing = names.filter((slot) => !isObject(record[slot]));
|
|
1179
|
+
if (extra.length > 0 || missing.length > 0) throw new WGSLError(`The program ${preview(name)} binds exactly the slots ${names.map(preview).join(", ") || "none"}; give each one a buffer range and no other key.`, {
|
|
1180
|
+
code: "ARGUMENT",
|
|
1181
|
+
context: {
|
|
1182
|
+
name,
|
|
1183
|
+
missing,
|
|
1184
|
+
extra
|
|
1185
|
+
}
|
|
1186
|
+
});
|
|
1187
|
+
const limits = this.#session.device.limits;
|
|
1188
|
+
const entries = this.#slots.map(([slot]) => this.#range(slot, record[slot], limits));
|
|
1189
|
+
const shared = names.filter((_slot, index) => this.#aliased(entries, index));
|
|
1190
|
+
if (shared.length > 0) throw new WGSLError(`The read_write slots ${shared.map(preview).join(", ")} of ${preview(name)} share a GPUBuffer with another slot; Dawn refuses a writable binding beside any other binding of one buffer, even over disjoint ranges, so bind a separate buffer.`, {
|
|
1191
|
+
code: "VALIDATION",
|
|
1192
|
+
context: {
|
|
1193
|
+
name,
|
|
1194
|
+
slots: shared
|
|
1195
|
+
}
|
|
1196
|
+
});
|
|
1197
|
+
return Object.freeze(entries);
|
|
1198
|
+
}
|
|
1199
|
+
#aliased(entries, index) {
|
|
1200
|
+
if (this.#slots[index]?.[1].access !== "read_write") return false;
|
|
1201
|
+
const buffer = entries[index]?.buffer;
|
|
1202
|
+
return entries.some((other, position) => position !== index && other.buffer === buffer);
|
|
1203
|
+
}
|
|
1204
|
+
#range(slot, binding, limits) {
|
|
1205
|
+
const name = this.program.name;
|
|
1206
|
+
if (binding === void 0 || !isObject(binding.buffer)) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} needs a buffer range object whose buffer member holds a GPUBuffer.`, {
|
|
1207
|
+
code: "ARGUMENT",
|
|
1208
|
+
context: {
|
|
1209
|
+
name,
|
|
1210
|
+
slot
|
|
1211
|
+
}
|
|
1212
|
+
});
|
|
1213
|
+
const { buffer } = binding;
|
|
1214
|
+
if ((buffer.usage & WGSL_USAGE.storage) === 0) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} needs a buffer with the storage usage (WGSL_USAGE.storage); its usage is ${buffer.usage}.`, {
|
|
1215
|
+
code: "ARGUMENT",
|
|
1216
|
+
context: {
|
|
1217
|
+
name,
|
|
1218
|
+
slot,
|
|
1219
|
+
usage: buffer.usage
|
|
1220
|
+
}
|
|
1221
|
+
});
|
|
1222
|
+
const offset = binding.offset ?? 0;
|
|
1223
|
+
const alignment = limits.minStorageBufferOffsetAlignment;
|
|
1224
|
+
if (!isNonNegativeInteger(offset) || !isSafeInteger(offset) || offset % alignment !== 0) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} starts at ${preview(offset)}; a storage offset must be a non-negative multiple of the device's ${alignment}-byte alignment.`, {
|
|
1225
|
+
code: "ARGUMENT",
|
|
1226
|
+
context: {
|
|
1227
|
+
name,
|
|
1228
|
+
slot,
|
|
1229
|
+
offset,
|
|
1230
|
+
alignment
|
|
1231
|
+
}
|
|
1232
|
+
});
|
|
1233
|
+
const size = binding.size ?? buffer.size - offset;
|
|
1234
|
+
if (!isSafeInteger(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} spans ${preview(size)} bytes; a storage range must span a multiple of 4 bytes, at least 4.`, {
|
|
1235
|
+
code: "ARGUMENT",
|
|
1236
|
+
context: {
|
|
1237
|
+
name,
|
|
1238
|
+
slot,
|
|
1239
|
+
size
|
|
1240
|
+
}
|
|
1241
|
+
});
|
|
1242
|
+
if (offset + size > buffer.size) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} ends at byte ${offset + size}, past its buffer's ${buffer.size} bytes.`, {
|
|
1243
|
+
code: "ARGUMENT",
|
|
1244
|
+
context: {
|
|
1245
|
+
name,
|
|
1246
|
+
slot,
|
|
1247
|
+
offset,
|
|
1248
|
+
size,
|
|
1249
|
+
length: buffer.size
|
|
1250
|
+
}
|
|
1251
|
+
});
|
|
1252
|
+
if (size > limits.maxStorageBufferBindingSize) throw new WGSLError(`The slot ${preview(slot)} of ${preview(name)} spans ${size} bytes, past the device's maxStorageBufferBindingSize of ${limits.maxStorageBufferBindingSize}; split the range.`, {
|
|
1253
|
+
code: "LIMIT",
|
|
1254
|
+
context: {
|
|
1255
|
+
name,
|
|
1256
|
+
slot,
|
|
1257
|
+
size,
|
|
1258
|
+
limit: limits.maxStorageBufferBindingSize
|
|
1259
|
+
}
|
|
1260
|
+
});
|
|
1261
|
+
return Object.freeze({
|
|
1262
|
+
buffer,
|
|
1263
|
+
offset,
|
|
1264
|
+
size
|
|
1265
|
+
});
|
|
1266
|
+
}
|
|
1267
|
+
#create(entries) {
|
|
1268
|
+
const group = this.#session.device.createBindGroup({
|
|
1269
|
+
label: this.program.name,
|
|
1270
|
+
layout: this.#layout,
|
|
1271
|
+
entries: entries.map((resource, binding) => ({
|
|
1272
|
+
binding,
|
|
1273
|
+
resource
|
|
1274
|
+
}))
|
|
1275
|
+
});
|
|
1276
|
+
return Object.freeze({
|
|
1277
|
+
statement: this,
|
|
1278
|
+
group
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
#store(node, entries, depth, binding) {
|
|
1282
|
+
const entry = entries[depth];
|
|
1283
|
+
if (entry === void 0) return;
|
|
1284
|
+
const offsets = node.next.get(entry.buffer) ?? /* @__PURE__ */ new Map();
|
|
1285
|
+
const sizes = offsets.get(entry.offset) ?? /* @__PURE__ */ new Map();
|
|
1286
|
+
const leaf = depth === entries.length - 1 ? binding : void 0;
|
|
1287
|
+
const child = sizes.get(entry.size) ?? {
|
|
1288
|
+
next: /* @__PURE__ */ new WeakMap(),
|
|
1289
|
+
binding: leaf
|
|
1290
|
+
};
|
|
1291
|
+
sizes.set(entry.size, child);
|
|
1292
|
+
offsets.set(entry.offset, sizes);
|
|
1293
|
+
node.next.set(entry.buffer, offsets);
|
|
1294
|
+
this.#store(child, entries, depth + 1, binding);
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
// src/core/WGSLSession.ts
|
|
1298
|
+
/**
|
|
1299
|
+
* Prepares programs as statements on a borrowed device and opens one batch of dispatches at a time.
|
|
1300
|
+
*
|
|
1301
|
+
* @remarks
|
|
1302
|
+
* The session reads its limits and features from the device and never requests or destroys the
|
|
1303
|
+
* device. An extension is active when the device reports its feature and the `extensions` option
|
|
1304
|
+
* does not switch it off. Pipelines sit in a table keyed on the rendered WGSL text: a ready map
|
|
1305
|
+
* beside a pending map, so a warm `prepare` creates no pipeline. A pending entry that fails with any
|
|
1306
|
+
* code but `COMPILE` leaves the table, so a later `prepare` retries it. Shader compilation runs
|
|
1307
|
+
* inside one synchronous push and pop of a `validation` error scope, and a compiler error rejects
|
|
1308
|
+
* that `prepare` with code `COMPILE` and its `line` and `column` in `context`; the session stays
|
|
1309
|
+
* `open`. Thrown with code `LIMIT` when a program's workgroup size or slot count passes the device's
|
|
1310
|
+
* limits, and with code `VALIDATION` from `batch()` while another batch is open. A device failure on
|
|
1311
|
+
* a submitted batch, or the device's `lost` promise, moves the session to `failed`, making
|
|
1312
|
+
* `prepare`, `batch`, and any open batch's `encode`, `read`, and `submit` throw that failure while
|
|
1313
|
+
* `destroy` resolves. `destroy` moves the session to `destroyed` at once, aborts the open batch,
|
|
1314
|
+
* waits for submitted work and reads, and destroys the uniform buffer and the staging buffers the
|
|
1315
|
+
* session created; a repeated `destroy` returns the same promise, settled `abort` and `execute`
|
|
1316
|
+
* replay their batch's own settlement, and `prepare`, `batch`, `encode`, `read`, and `submit` throw
|
|
1317
|
+
* with code `DESTROYED`. Thrown with code `ARGUMENT`
|
|
1318
|
+
* from the constructor when `uniform.size` is not a positive safe multiple of 4.
|
|
1319
|
+
*
|
|
1320
|
+
* @example
|
|
1321
|
+
* ```ts
|
|
1322
|
+
* const session = new WGSLSession(device, { extensions: { f16: false } })
|
|
1323
|
+
* const statement = await session.prepare(program)
|
|
1324
|
+
* await statement.execute(statement.bind({ destination: { buffer } }), { count: 64 }, [1, 1, 1])
|
|
1325
|
+
* await session.destroy()
|
|
1326
|
+
* ```
|
|
1327
|
+
*/
|
|
1328
|
+
var WGSLSession = class {
|
|
1329
|
+
#device;
|
|
1330
|
+
#extensions;
|
|
1331
|
+
#buffer;
|
|
1332
|
+
#slab;
|
|
1333
|
+
#uniform;
|
|
1334
|
+
#ready = /* @__PURE__ */ new Map();
|
|
1335
|
+
#pending = /* @__PURE__ */ new Map();
|
|
1336
|
+
#layouts = /* @__PURE__ */ new Map();
|
|
1337
|
+
#groups = /* @__PURE__ */ new Map();
|
|
1338
|
+
#staging = /* @__PURE__ */ new Set();
|
|
1339
|
+
#leased = /* @__PURE__ */ new Set();
|
|
1340
|
+
#inflight = /* @__PURE__ */ new Set();
|
|
1341
|
+
#batch;
|
|
1342
|
+
#failure;
|
|
1343
|
+
#ending;
|
|
1344
|
+
/**
|
|
1345
|
+
* Creates an open session over a borrowed device, with its uniform slab and uniform layout.
|
|
1346
|
+
*
|
|
1347
|
+
* @param device - The device the session borrows
|
|
1348
|
+
* @param options - The extensions to switch off and the slab's byte size
|
|
1349
|
+
*/
|
|
1350
|
+
constructor(device, options) {
|
|
1351
|
+
const size = options?.uniform?.size ?? 65536;
|
|
1352
|
+
if (!isSafeInteger(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`A session's uniform size must be a positive safe multiple of 4 bytes; received ${preview(size)}.`, {
|
|
1353
|
+
code: "ARGUMENT",
|
|
1354
|
+
context: { size }
|
|
1355
|
+
});
|
|
1356
|
+
const requested = options?.extensions;
|
|
1357
|
+
const features = device.features;
|
|
1358
|
+
const usage = WGSL_USAGE.uniform | WGSL_USAGE.destination;
|
|
1359
|
+
const entry = {
|
|
1360
|
+
binding: 0,
|
|
1361
|
+
visibility: WGSL_STAGE.compute,
|
|
1362
|
+
buffer: {
|
|
1363
|
+
type: "uniform",
|
|
1364
|
+
hasDynamicOffset: true
|
|
1365
|
+
}
|
|
1366
|
+
};
|
|
1367
|
+
this.#device = device;
|
|
1368
|
+
this.#extensions = Object.freeze({
|
|
1369
|
+
f16: features.has(WGSL_EXTENSIONS.f16) && requested?.f16 !== false,
|
|
1370
|
+
subgroups: features.has(WGSL_EXTENSIONS.subgroups) && requested?.subgroups !== false
|
|
1371
|
+
});
|
|
1372
|
+
this.#buffer = device.createBuffer({
|
|
1373
|
+
label: "wgsl uniform",
|
|
1374
|
+
size,
|
|
1375
|
+
usage
|
|
1376
|
+
});
|
|
1377
|
+
this.#slab = new WGSLSlab(device, {
|
|
1378
|
+
buffer: this.#buffer,
|
|
1379
|
+
capacity: size
|
|
1380
|
+
});
|
|
1381
|
+
this.#uniform = device.createBindGroupLayout({
|
|
1382
|
+
label: "wgsl uniform",
|
|
1383
|
+
entries: [entry]
|
|
1384
|
+
});
|
|
1385
|
+
device.lost.then((info) => this.#lose(info));
|
|
1386
|
+
}
|
|
1387
|
+
get device() {
|
|
1388
|
+
return this.#device;
|
|
1389
|
+
}
|
|
1390
|
+
get extensions() {
|
|
1391
|
+
return this.#extensions;
|
|
1392
|
+
}
|
|
1393
|
+
get status() {
|
|
1394
|
+
if (this.#ending !== void 0) return "destroyed";
|
|
1395
|
+
return this.#failure === void 0 ? "open" : "failed";
|
|
1396
|
+
}
|
|
1397
|
+
async prepare(program) {
|
|
1398
|
+
this.#check();
|
|
1399
|
+
const { name, entry } = program;
|
|
1400
|
+
const slots = program.slots;
|
|
1401
|
+
const accesses = Object.values(slots).map((slot) => slot.access);
|
|
1402
|
+
this.#fit(name, entry.size, accesses.length);
|
|
1403
|
+
const text = renderWGSLProgram(program, this.#extensions);
|
|
1404
|
+
const layout = this.#layout(accesses);
|
|
1405
|
+
const pipeline = this.#ready.get(text) ?? await this.#compile(text, name, entry.name, layout);
|
|
1406
|
+
this.#check();
|
|
1407
|
+
const uniform = this.#group(program.uniform.struct.size);
|
|
1408
|
+
return new WGSLStatement(this, {
|
|
1409
|
+
program,
|
|
1410
|
+
pipeline,
|
|
1411
|
+
layout,
|
|
1412
|
+
uniform
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1415
|
+
batch() {
|
|
1416
|
+
this.#check();
|
|
1417
|
+
if (this.#batch !== void 0) throw new WGSLError("The session already holds an open batch; submit or abort it before opening another.", { code: "VALIDATION" });
|
|
1418
|
+
const batch = new WGSLBatch(this.#device, {
|
|
1419
|
+
slab: this.#slab,
|
|
1420
|
+
check: () => this.#check(),
|
|
1421
|
+
lease: (size) => this.#lease(size),
|
|
1422
|
+
restore: (buffer) => this.#restore(buffer),
|
|
1423
|
+
release: (ended) => this.#release(ended),
|
|
1424
|
+
fail: (error) => this.#fail(error),
|
|
1425
|
+
track: (work) => this.#track(work)
|
|
1426
|
+
});
|
|
1427
|
+
this.#batch = batch;
|
|
1428
|
+
return batch;
|
|
1429
|
+
}
|
|
1430
|
+
destroy() {
|
|
1431
|
+
if (this.#ending !== void 0) return this.#ending;
|
|
1432
|
+
const ending = Promise.withResolvers();
|
|
1433
|
+
this.#ending = ending.promise;
|
|
1434
|
+
ending.resolve(this.#end());
|
|
1435
|
+
return ending.promise;
|
|
1436
|
+
}
|
|
1437
|
+
#check() {
|
|
1438
|
+
if (this.#ending !== void 0) throw new WGSLError("The session was destroyed; create another with createWGSLSession.", { code: "DESTROYED" });
|
|
1439
|
+
if (this.#failure !== void 0) throw this.#failure;
|
|
1440
|
+
}
|
|
1441
|
+
#fit(name, size, count) {
|
|
1442
|
+
const limits = this.#device.limits;
|
|
1443
|
+
const [x, y, z] = size;
|
|
1444
|
+
const wide = x > limits.maxComputeWorkgroupSizeX || y > limits.maxComputeWorkgroupSizeY;
|
|
1445
|
+
const deep = z > limits.maxComputeWorkgroupSizeZ;
|
|
1446
|
+
if (wide || deep || x * y * z > limits.maxComputeInvocationsPerWorkgroup) throw new WGSLError(`The program ${preview(name)} declares a workgroup of [${x}, ${y}, ${z}], past the device's per-axis workgroup sizes or its ${limits.maxComputeInvocationsPerWorkgroup} invocations per workgroup.`, {
|
|
1447
|
+
code: "LIMIT",
|
|
1448
|
+
context: {
|
|
1449
|
+
name,
|
|
1450
|
+
size: [
|
|
1451
|
+
x,
|
|
1452
|
+
y,
|
|
1453
|
+
z
|
|
1454
|
+
]
|
|
1455
|
+
}
|
|
1456
|
+
});
|
|
1457
|
+
if (count > limits.maxStorageBuffersPerShaderStage) throw new WGSLError(`The program ${preview(name)} declares ${count} storage slots, past the device's ${limits.maxStorageBuffersPerShaderStage} storage buffers per shader stage.`, {
|
|
1458
|
+
code: "LIMIT",
|
|
1459
|
+
context: {
|
|
1460
|
+
name,
|
|
1461
|
+
count,
|
|
1462
|
+
limit: limits.maxStorageBuffersPerShaderStage
|
|
1463
|
+
}
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
#layout(accesses) {
|
|
1467
|
+
const key = accesses.join(",");
|
|
1468
|
+
const cached = this.#layouts.get(key);
|
|
1469
|
+
if (cached !== void 0) return cached;
|
|
1470
|
+
const entries = accesses.map((access, binding) => ({
|
|
1471
|
+
binding,
|
|
1472
|
+
visibility: WGSL_STAGE.compute,
|
|
1473
|
+
buffer: { type: access === "read" ? "read-only-storage" : "storage" }
|
|
1474
|
+
}));
|
|
1475
|
+
const layout = this.#device.createBindGroupLayout({
|
|
1476
|
+
label: key,
|
|
1477
|
+
entries
|
|
1478
|
+
});
|
|
1479
|
+
this.#layouts.set(key, layout);
|
|
1480
|
+
return layout;
|
|
1481
|
+
}
|
|
1482
|
+
#group(size) {
|
|
1483
|
+
const cached = this.#groups.get(size);
|
|
1484
|
+
if (cached !== void 0) return cached;
|
|
1485
|
+
const resource = {
|
|
1486
|
+
buffer: this.#buffer,
|
|
1487
|
+
offset: 0,
|
|
1488
|
+
size
|
|
1489
|
+
};
|
|
1490
|
+
const group = this.#device.createBindGroup({
|
|
1491
|
+
label: "wgsl uniform",
|
|
1492
|
+
layout: this.#uniform,
|
|
1493
|
+
entries: [{
|
|
1494
|
+
binding: 0,
|
|
1495
|
+
resource
|
|
1496
|
+
}]
|
|
1497
|
+
});
|
|
1498
|
+
this.#groups.set(size, group);
|
|
1499
|
+
return group;
|
|
1500
|
+
}
|
|
1501
|
+
#compile(text, name, entry, layout) {
|
|
1502
|
+
const pending = this.#pending.get(text);
|
|
1503
|
+
if (pending !== void 0) return pending;
|
|
1504
|
+
const created = this.#build(text, name, entry, layout);
|
|
1505
|
+
this.#pending.set(text, created);
|
|
1506
|
+
created.then((pipeline) => {
|
|
1507
|
+
this.#ready.set(text, pipeline);
|
|
1508
|
+
this.#pending.delete(text);
|
|
1509
|
+
}, (error) => {
|
|
1510
|
+
if (!isWGSLError(error) || error.code !== "COMPILE") this.#pending.delete(text);
|
|
1511
|
+
});
|
|
1512
|
+
return created;
|
|
1513
|
+
}
|
|
1514
|
+
async #build(text, name, entry, layout) {
|
|
1515
|
+
const device = this.#device;
|
|
1516
|
+
const groups = [layout, this.#uniform];
|
|
1517
|
+
device.pushErrorScope("validation");
|
|
1518
|
+
const module = device.createShaderModule({
|
|
1519
|
+
label: name,
|
|
1520
|
+
code: text
|
|
1521
|
+
});
|
|
1522
|
+
const layouts = device.createPipelineLayout({
|
|
1523
|
+
label: name,
|
|
1524
|
+
bindGroupLayouts: groups
|
|
1525
|
+
});
|
|
1526
|
+
const popped = device.popErrorScope();
|
|
1527
|
+
const [info, error] = await Promise.all([module.getCompilationInfo(), popped]);
|
|
1528
|
+
const message = info.messages.find((candidate) => candidate.type === "error");
|
|
1529
|
+
if (message !== void 0) {
|
|
1530
|
+
const { lineNum: line, linePos: column } = message;
|
|
1531
|
+
throw new WGSLError(`The program ${preview(name)} does not compile at line ${line}, column ${column}: ${message.message}`, {
|
|
1532
|
+
code: "COMPILE",
|
|
1533
|
+
context: {
|
|
1534
|
+
name,
|
|
1535
|
+
line,
|
|
1536
|
+
column,
|
|
1537
|
+
message: message.message
|
|
1538
|
+
}
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
if (error !== null) throw new WGSLError(`The device refused the shader module or pipeline layout of ${preview(name)}: ${error.message}`, {
|
|
1542
|
+
code: "VALIDATION",
|
|
1543
|
+
context: {
|
|
1544
|
+
name,
|
|
1545
|
+
message: error.message
|
|
1546
|
+
}
|
|
1547
|
+
});
|
|
1548
|
+
return this.#pipeline(module, layouts, name, entry);
|
|
1549
|
+
}
|
|
1550
|
+
async #pipeline(module, layout, name, entry) {
|
|
1551
|
+
try {
|
|
1552
|
+
return await this.#device.createComputePipelineAsync({
|
|
1553
|
+
label: name,
|
|
1554
|
+
layout,
|
|
1555
|
+
compute: {
|
|
1556
|
+
module,
|
|
1557
|
+
entryPoint: entry
|
|
1558
|
+
}
|
|
1559
|
+
});
|
|
1560
|
+
} catch (cause) {
|
|
1561
|
+
throw new WGSLError(`The device refused the compute pipeline of ${preview(name)}: ${errorToMessage(cause)}`, {
|
|
1562
|
+
code: "VALIDATION",
|
|
1563
|
+
context: { name },
|
|
1564
|
+
cause
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
#lease(size) {
|
|
1569
|
+
const buffer = this.#idle(size) ?? this.#allocate(size);
|
|
1570
|
+
this.#leased.add(buffer);
|
|
1571
|
+
return buffer;
|
|
1572
|
+
}
|
|
1573
|
+
#idle(size) {
|
|
1574
|
+
for (const buffer of this.#staging) {
|
|
1575
|
+
if (this.#leased.has(buffer) || buffer.mapState !== "unmapped") continue;
|
|
1576
|
+
if (buffer.size >= size) return buffer;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
#allocate(size) {
|
|
1580
|
+
const usage = WGSL_USAGE.read | WGSL_USAGE.destination;
|
|
1581
|
+
const buffer = this.#device.createBuffer({
|
|
1582
|
+
label: "wgsl staging",
|
|
1583
|
+
size,
|
|
1584
|
+
usage
|
|
1585
|
+
});
|
|
1586
|
+
this.#staging.add(buffer);
|
|
1587
|
+
return buffer;
|
|
1588
|
+
}
|
|
1589
|
+
#restore(buffer) {
|
|
1590
|
+
this.#leased.delete(buffer);
|
|
1591
|
+
this.#trim();
|
|
1592
|
+
}
|
|
1593
|
+
#release(batch) {
|
|
1594
|
+
if (this.#batch === batch) this.#batch = void 0;
|
|
1595
|
+
this.#trim();
|
|
1596
|
+
}
|
|
1597
|
+
#trim() {
|
|
1598
|
+
if (this.#batch !== void 0) return;
|
|
1599
|
+
const excess = [...this.#staging].filter((buffer) => !this.#leased.has(buffer)).slice(0, Math.max(0, this.#staging.size - 2));
|
|
1600
|
+
for (const buffer of excess) {
|
|
1601
|
+
this.#staging.delete(buffer);
|
|
1602
|
+
this.#retire(buffer);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
#retire(buffer) {
|
|
1606
|
+
const done = this.#device.queue.onSubmittedWorkDone();
|
|
1607
|
+
this.#track(done.then(() => buffer.destroy(), () => buffer.destroy()));
|
|
1608
|
+
}
|
|
1609
|
+
#fail(error) {
|
|
1610
|
+
this.#failure ??= error;
|
|
1611
|
+
}
|
|
1612
|
+
#track(work) {
|
|
1613
|
+
this.#inflight.add(work);
|
|
1614
|
+
work.then(() => this.#inflight.delete(work), () => this.#inflight.delete(work));
|
|
1615
|
+
}
|
|
1616
|
+
#lose(info) {
|
|
1617
|
+
this.#failure ??= new WGSLError(`The device was lost (${info.reason}): ${info.message}`, {
|
|
1618
|
+
code: "HOST",
|
|
1619
|
+
context: {
|
|
1620
|
+
reason: info.reason,
|
|
1621
|
+
message: info.message
|
|
1622
|
+
}
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
async #end() {
|
|
1626
|
+
this.#batch?.abort();
|
|
1627
|
+
await Promise.allSettled(this.#inflight);
|
|
1628
|
+
for (const buffer of this.#staging) buffer.destroy();
|
|
1629
|
+
this.#buffer.destroy();
|
|
1630
|
+
this.#staging.clear();
|
|
1631
|
+
this.#leased.clear();
|
|
1632
|
+
this.#ready.clear();
|
|
1633
|
+
this.#pending.clear();
|
|
1634
|
+
this.#layouts.clear();
|
|
1635
|
+
this.#groups.clear();
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
// src/core/factories.ts
|
|
1639
|
+
function createWGSLStruct(name, fields) {
|
|
1640
|
+
if (!isNonEmptyString(name)) throw new WGSLError(`A struct name must be a non-empty string; received ${preview(name)}.`, {
|
|
1641
|
+
code: "ARGUMENT",
|
|
1642
|
+
context: { name }
|
|
1643
|
+
});
|
|
1644
|
+
if (!isRecord(fields)) throw new WGSLError(`The struct ${preview(name)} needs a plain record of fields; received ${preview(fields)}.`, {
|
|
1645
|
+
code: "ARGUMENT",
|
|
1646
|
+
context: { name }
|
|
1647
|
+
});
|
|
1648
|
+
const entries = Object.entries(fields);
|
|
1649
|
+
if (entries.length === 0) throw new WGSLError(`The struct ${preview(name)} declares no field; declare at least one 'u32', 'i32', or 'f32' field.`, {
|
|
1650
|
+
code: "ARGUMENT",
|
|
1651
|
+
context: { name }
|
|
1652
|
+
});
|
|
1653
|
+
const invalid = entries.filter(([, element]) => !isWGSLScalar(element)).map(([field]) => field);
|
|
1654
|
+
if (invalid.length > 0) throw new WGSLError(`The struct ${preview(name)} declares ${invalid.map(preview).join(", ")} with a type outside 'u32', 'i32', and 'f32'.`, {
|
|
1655
|
+
code: "ARGUMENT",
|
|
1656
|
+
context: {
|
|
1657
|
+
name,
|
|
1658
|
+
fields: invalid
|
|
1659
|
+
}
|
|
1660
|
+
});
|
|
1661
|
+
const members = Object.freeze(entries.map(([field, element], word) => Object.freeze({
|
|
1662
|
+
name: field,
|
|
1663
|
+
element,
|
|
1664
|
+
word
|
|
1665
|
+
})));
|
|
1666
|
+
const lines = members.map((member) => `\t${member.name}: ${member.element},`);
|
|
1667
|
+
return Object.freeze({
|
|
1668
|
+
name,
|
|
1669
|
+
fields: Object.freeze(Object.fromEntries(entries)),
|
|
1670
|
+
size: members.length * 4,
|
|
1671
|
+
offsets: Object.freeze(Object.fromEntries(members.map((member) => [member.name, member.word * 4]))),
|
|
1672
|
+
members,
|
|
1673
|
+
source: `struct ${name} {\n${lines.join("\n")}\n}`
|
|
1674
|
+
});
|
|
1675
|
+
}
|
|
1676
|
+
/**
|
|
1677
|
+
* Creates a frozen fragment from author-written WGSL text and the fragments it uses.
|
|
1678
|
+
*
|
|
1679
|
+
* @remarks
|
|
1680
|
+
* The text reaches the compiler unchanged. Thrown with code `ARGUMENT` when the name is empty, when
|
|
1681
|
+
* a source is not a string, and when the variant names an extension outside `WGSL_EXTENSIONS`.
|
|
1682
|
+
*
|
|
1683
|
+
* @param input - The fragment's name, text, used fragments, and optional variant
|
|
1684
|
+
* @returns The fragment, frozen
|
|
1685
|
+
*
|
|
1686
|
+
* @example
|
|
1687
|
+
* ```ts
|
|
1688
|
+
* createWGSLFragment({ name: 'square', source: 'fn square(value: f32) -> f32 { return value * value; }' }).uses // []
|
|
1689
|
+
* ```
|
|
1690
|
+
*/
|
|
1691
|
+
function createWGSLFragment(input) {
|
|
1692
|
+
if (!isNonEmptyString(input.name)) throw new WGSLError(`A fragment name must be a non-empty string; received ${preview(input.name)}.`, {
|
|
1693
|
+
code: "ARGUMENT",
|
|
1694
|
+
context: { name: input.name }
|
|
1695
|
+
});
|
|
1696
|
+
if (!isString(input.source)) throw new WGSLError(`The fragment ${preview(input.name)} needs WGSL text in source; received ${preview(input.source)}.`, {
|
|
1697
|
+
code: "ARGUMENT",
|
|
1698
|
+
context: { name: input.name }
|
|
1699
|
+
});
|
|
1700
|
+
const uses = Object.freeze([...input.uses ?? []]);
|
|
1701
|
+
const variant = input.variant;
|
|
1702
|
+
if (variant === void 0) return Object.freeze({
|
|
1703
|
+
name: input.name,
|
|
1704
|
+
source: input.source,
|
|
1705
|
+
uses
|
|
1706
|
+
});
|
|
1707
|
+
if (!isWGSLExtension(variant.extension)) throw new WGSLError(`The fragment ${preview(input.name)} names the extension ${preview(variant.extension)}; use 'f16' or 'subgroups'.`, {
|
|
1708
|
+
code: "ARGUMENT",
|
|
1709
|
+
context: { name: input.name }
|
|
1710
|
+
});
|
|
1711
|
+
if (!isString(variant.source)) throw new WGSLError(`The fragment ${preview(input.name)} needs WGSL text in variant.source; received ${preview(variant.source)}.`, {
|
|
1712
|
+
code: "ARGUMENT",
|
|
1713
|
+
context: { name: input.name }
|
|
1714
|
+
});
|
|
1715
|
+
return Object.freeze({
|
|
1716
|
+
name: input.name,
|
|
1717
|
+
source: input.source,
|
|
1718
|
+
uses,
|
|
1719
|
+
variant: Object.freeze({
|
|
1720
|
+
extension: variant.extension,
|
|
1721
|
+
source: variant.source
|
|
1722
|
+
})
|
|
1723
|
+
});
|
|
1724
|
+
}
|
|
1725
|
+
function createWGSLProgram(input) {
|
|
1726
|
+
const { entry, uniform } = input;
|
|
1727
|
+
if (!isNonEmptyString(input.name)) throw new WGSLError(`A program name must be a non-empty string; received ${preview(input.name)}.`, {
|
|
1728
|
+
code: "ARGUMENT",
|
|
1729
|
+
context: { name: input.name }
|
|
1730
|
+
});
|
|
1731
|
+
if (!isNonEmptyString(entry.name)) throw new WGSLError(`The program ${preview(input.name)} needs a non-empty entry name; received ${preview(entry.name)}.`, {
|
|
1732
|
+
code: "ARGUMENT",
|
|
1733
|
+
context: { name: input.name }
|
|
1734
|
+
});
|
|
1735
|
+
if (!isWGSLGrid(entry.size)) throw new WGSLError(`The entry ${preview(entry.name)} needs a workgroup size of three positive safe integers, such as [64, 1, 1].`, {
|
|
1736
|
+
code: "ARGUMENT",
|
|
1737
|
+
context: {
|
|
1738
|
+
name: input.name,
|
|
1739
|
+
size: entry.size
|
|
1740
|
+
}
|
|
1741
|
+
});
|
|
1742
|
+
if (!isString(entry.source)) throw new WGSLError(`The entry ${preview(entry.name)} needs WGSL text in source; received ${preview(entry.source)}.`, {
|
|
1743
|
+
code: "ARGUMENT",
|
|
1744
|
+
context: { name: input.name }
|
|
1745
|
+
});
|
|
1746
|
+
const slots = Object.entries(input.slots);
|
|
1747
|
+
const invalid = slots.filter(([, slot]) => !isWGSLAccess(slot.access) || !isWGSLScalar(slot.element)).map(([name]) => name);
|
|
1748
|
+
if (invalid.length > 0) throw new WGSLError(`The program ${preview(input.name)} declares slots ${invalid.map(preview).join(", ")} with an access outside 'read' and 'read_write' or an element outside 'u32', 'i32', and 'f32'.`, {
|
|
1749
|
+
code: "ARGUMENT",
|
|
1750
|
+
context: {
|
|
1751
|
+
name: input.name,
|
|
1752
|
+
slots: invalid
|
|
1753
|
+
}
|
|
1754
|
+
});
|
|
1755
|
+
if (!isNonEmptyString(uniform.name)) throw new WGSLError(`The program ${preview(input.name)} needs a non-empty uniform name; received ${preview(uniform.name)}.`, {
|
|
1756
|
+
code: "ARGUMENT",
|
|
1757
|
+
context: { name: input.name }
|
|
1758
|
+
});
|
|
1759
|
+
const [x, y, z] = entry.size;
|
|
1760
|
+
const size = [
|
|
1761
|
+
x,
|
|
1762
|
+
y,
|
|
1763
|
+
z
|
|
1764
|
+
];
|
|
1765
|
+
return Object.freeze({
|
|
1766
|
+
name: input.name,
|
|
1767
|
+
entry: Object.freeze({
|
|
1768
|
+
name: entry.name,
|
|
1769
|
+
size: Object.freeze(size),
|
|
1770
|
+
source: entry.source
|
|
1771
|
+
}),
|
|
1772
|
+
slots: Object.freeze(Object.fromEntries(slots.map(([name, slot]) => [name, Object.freeze({
|
|
1773
|
+
access: slot.access,
|
|
1774
|
+
element: slot.element
|
|
1775
|
+
})]))),
|
|
1776
|
+
uniform: Object.freeze({
|
|
1777
|
+
name: uniform.name,
|
|
1778
|
+
struct: uniform.struct
|
|
1779
|
+
}),
|
|
1780
|
+
fragments: collectWGSLFragments(input.uses ?? [])
|
|
1781
|
+
});
|
|
1782
|
+
}
|
|
1783
|
+
/**
|
|
1784
|
+
* Creates an open session that prepares programs and runs batches on a borrowed device.
|
|
1785
|
+
*
|
|
1786
|
+
* @remarks
|
|
1787
|
+
* The session never requests or destroys the device; its `destroy` releases only the buffers it
|
|
1788
|
+
* created. Thrown with code `ARGUMENT` when `uniform.size` is not a positive safe multiple of 4.
|
|
1789
|
+
*
|
|
1790
|
+
* @param device - The device the session borrows
|
|
1791
|
+
* @param options - The extensions to switch off and the uniform slab's byte size
|
|
1792
|
+
* @returns The session
|
|
1793
|
+
*
|
|
1794
|
+
* @example
|
|
1795
|
+
* ```ts
|
|
1796
|
+
* const session = createWGSLSession(device, { extensions: { f16: false } })
|
|
1797
|
+
* session.status // 'open'
|
|
1798
|
+
* ```
|
|
1799
|
+
*/
|
|
1800
|
+
function createWGSLSession(device, options) {
|
|
1801
|
+
return new WGSLSession(device, options);
|
|
1802
|
+
}
|
|
1803
|
+
export { WGSLBatch, WGSLError, WGSLSession, WGSLSlab, WGSLStatement, WGSL_ACCESSES, WGSL_ERROR_BRAND, WGSL_ERROR_CODES, WGSL_EXTENSIONS, WGSL_HALF, WGSL_MAP, WGSL_PEAK, WGSL_PLACE, WGSL_SCALARS, WGSL_STAGE, WGSL_SUM, WGSL_UNIFORM_SIZE, WGSL_USAGE, collectWGSLFragments, computeWGSLGrid, computeWGSLOffset, createWGSLFragment, createWGSLProgram, createWGSLSession, createWGSLStruct, isWGSLAccess, isWGSLError, isWGSLExtension, isWGSLGrid, isWGSLScalar, renderWGSLProgram };
|
|
1804
|
+
|
|
1805
|
+
//# sourceMappingURL=index.js.map
|