@orkestrel/wgsl 0.0.2 → 0.0.3

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.
@@ -146,14 +146,17 @@ var WGSL_STAGE = Object.freeze({ compute: 4 });
146
146
  */
147
147
  var WGSL_UNIFORM_SIZE = 65536;
148
148
  /**
149
- * Holds the fragment that reads a workgroup's two-axis index from the entry input struct.
149
+ * Holds the fragment that reads a workgroup's two-axis index from the entry's `Dispatch` struct.
150
150
  *
151
151
  * @remarks
152
- * It declares `fn place(invocation: Invocation) -> u32`, which returns
153
- * `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, the
154
- * statement of infer's `readPlace` recast onto the `Invocation` struct. Pair it with
155
- * `computeWGSLGrid`, and multiply by the workgroup size and add `local_invocation_index` for an
156
- * invocation's index. It reads no binding and no uniform member.
152
+ * It declares `fn readPlace(dispatch: Dispatch) -> u32`, which returns
153
+ * `dispatch.workgroup_id.x + dispatch.workgroup_id.y * dispatch.num_workgroups.x`, the statement of
154
+ * `@orkestrel/infer`'s `readPlace`. `Dispatch` holds only values that stay uniform across a
155
+ * workgroup, so a call that returns early on the result stays in uniform control flow before a
156
+ * later `workgroupBarrier()`. `Invocation` holds the per-lane builtins and is not a parameter. Pair
157
+ * the fragment with `computeWGSLGrid`, and multiply by the workgroup size and add
158
+ * `invocation.local_invocation_index` for an invocation's index. It reads no binding and no uniform
159
+ * member.
157
160
  *
158
161
  * @example
159
162
  * ```ts
@@ -161,10 +164,10 @@ var WGSL_UNIFORM_SIZE = 65536;
161
164
  * ```
162
165
  */
163
166
  var WGSL_PLACE = Object.freeze({
164
- name: "place",
167
+ name: "readPlace",
165
168
  source: [
166
- "fn place(invocation: Invocation) -> u32 {",
167
- " return invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x;",
169
+ "fn readPlace(dispatch: Dispatch) -> u32 {",
170
+ " return dispatch.workgroup_id.x + dispatch.workgroup_id.y * dispatch.num_workgroups.x;",
168
171
  "}"
169
172
  ].join("\n"),
170
173
  uses: Object.freeze([])
@@ -173,13 +176,16 @@ var WGSL_PLACE = Object.freeze({
173
176
  * Holds the fragment that sums one `f32` value from each invocation of a 64-invocation workgroup.
174
177
  *
175
178
  * @remarks
176
- * It declares `var<workgroup> sums: array<f32, 64>` and
177
- * `fn sum(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's total to every
178
- * invocation. The entry's workgroup size must hold 64 invocations, and every invocation must call
179
- * it from uniform control flow. The default body reduces in a tree of halving strides. The
179
+ * It declares `var<workgroup> sumShared: array<f32, 64>`, 256 bytes, and
180
+ * `fn sumPartials(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's total
181
+ * to every invocation. The entry's workgroup size must hold 64 invocations, and every invocation
182
+ * must call it from uniform control flow. It takes `Invocation` and never `Dispatch`, because it
183
+ * reads only `local_invocation_index` and, in the variant, `subgroup_invocation_id`. The default
184
+ * body reduces in a tree of halving strides. The
180
185
  * `subgroups` variant stores each subgroup's `subgroupAdd` partial at its first invocation's index
181
- * and `0.0` elsewhere, and invocation 0 adds the 64 entries in index order between 2 barriers, so
182
- * its rounding order differs from the default body's. It reads no binding and no uniform member.
186
+ * and `0.0` elsewhere, and invocation 0 adds the 64 entries in index order between 2 barriers; the
187
+ * variant is `reordered`, so its rounding order differs from the default body's. It reads no
188
+ * binding and no uniform member.
183
189
  *
184
190
  * @example
185
191
  * ```ts
@@ -187,21 +193,21 @@ var WGSL_PLACE = Object.freeze({
187
193
  * ```
188
194
  */
189
195
  var WGSL_SUM = Object.freeze({
190
- name: "sum",
196
+ name: "sumPartials",
191
197
  source: [
192
- "var<workgroup> sums: array<f32, 64>;",
198
+ "var<workgroup> sumShared: array<f32, 64>;",
193
199
  "",
194
- "fn sum(invocation: Invocation, value: f32) -> f32 {",
200
+ "fn sumPartials(invocation: Invocation, value: f32) -> f32 {",
195
201
  " let local = invocation.local_invocation_index;",
196
- " sums[local] = value;",
202
+ " sumShared[local] = value;",
197
203
  " workgroupBarrier();",
198
204
  " for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
199
205
  " if (local < stride) {",
200
- " sums[local] = sums[local] + sums[local + stride];",
206
+ " sumShared[local] = sumShared[local] + sumShared[local + stride];",
201
207
  " }",
202
208
  " workgroupBarrier();",
203
209
  " }",
204
- " let total = sums[0];",
210
+ " let total = sumShared[0];",
205
211
  " workgroupBarrier();",
206
212
  " return total;",
207
213
  "}"
@@ -210,22 +216,22 @@ var WGSL_SUM = Object.freeze({
210
216
  variant: Object.freeze({
211
217
  extension: "subgroups",
212
218
  source: [
213
- "var<workgroup> sums: array<f32, 64>;",
219
+ "var<workgroup> sumShared: array<f32, 64>;",
214
220
  "",
215
- "fn sum(invocation: Invocation, value: f32) -> f32 {",
221
+ "fn sumPartials(invocation: Invocation, value: f32) -> f32 {",
216
222
  " let local = invocation.local_invocation_index;",
217
223
  " let partial = subgroupAdd(value);",
218
- " sums[local] = select(0.0, partial, invocation.subgroup_invocation_id == 0u);",
224
+ " sumShared[local] = select(0.0, partial, invocation.subgroup_invocation_id == 0u);",
219
225
  " workgroupBarrier();",
220
226
  " if (local == 0u) {",
221
227
  " var acc = 0.0;",
222
228
  " for (var i = 0u; i < 64u; i += 1u) {",
223
- " acc = acc + sums[i];",
229
+ " acc = acc + sumShared[i];",
224
230
  " }",
225
- " sums[0] = acc;",
231
+ " sumShared[0] = acc;",
226
232
  " }",
227
233
  " workgroupBarrier();",
228
- " let total = sums[0];",
234
+ " let total = sumShared[0];",
229
235
  " workgroupBarrier();",
230
236
  " return total;",
231
237
  "}"
@@ -236,13 +242,14 @@ var WGSL_SUM = Object.freeze({
236
242
  * Holds the fragment that finds the largest `f32` value across the invocations of a 64-invocation workgroup.
237
243
  *
238
244
  * @remarks
239
- * It declares `var<workgroup> peaks: array<f32, 64>` and
240
- * `fn peak(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's maximum to
241
- * every invocation. The entry's workgroup size must hold 64 invocations, and every invocation must
242
- * call it from uniform control flow. The default body reduces with `max` in a tree of halving
243
- * strides. The `subgroups` variant stores each subgroup's `subgroupMax` partial at its first
244
- * invocation's index and the lowest finite `f32` (`-3.4028234663852886e38`) elsewhere, and invocation 0 folds
245
- * the 64 entries with `max` between 2 barriers (matching `@orkestrel/infer`, so it returns `-3.4028234663852886e38`
245
+ * It declares `var<workgroup> peakShared: array<f32, 64>`, 256 bytes, and
246
+ * `fn peakPartials(invocation: Invocation, value: f32) -> f32`, which returns the workgroup's
247
+ * maximum to every invocation. The entry's workgroup size must hold 64 invocations, and every
248
+ * invocation must call it from uniform control flow. It takes `Invocation` and never `Dispatch`. The
249
+ * default body reduces with `max` in a tree of halving strides. The `subgroups` variant is
250
+ * `reordered`: it stores each subgroup's `subgroupMax` partial at its first invocation's index and
251
+ * the lowest finite `f32` (`-3.4028234663852886e38`) elsewhere, and invocation 0 folds the 64 entries
252
+ * with `max` between 2 barriers (matching `@orkestrel/infer`, so it returns `-3.4028234663852886e38`
246
253
  * rather than `-Infinity` when every input is `-Infinity`). It reads no binding and no uniform member.
247
254
  *
248
255
  * @example
@@ -251,21 +258,21 @@ var WGSL_SUM = Object.freeze({
251
258
  * ```
252
259
  */
253
260
  var WGSL_PEAK = Object.freeze({
254
- name: "peak",
261
+ name: "peakPartials",
255
262
  source: [
256
- "var<workgroup> peaks: array<f32, 64>;",
263
+ "var<workgroup> peakShared: array<f32, 64>;",
257
264
  "",
258
- "fn peak(invocation: Invocation, value: f32) -> f32 {",
265
+ "fn peakPartials(invocation: Invocation, value: f32) -> f32 {",
259
266
  " let local = invocation.local_invocation_index;",
260
- " peaks[local] = value;",
267
+ " peakShared[local] = value;",
261
268
  " workgroupBarrier();",
262
269
  " for (var stride = 32u; stride > 0u; stride = stride >> 1u) {",
263
270
  " if (local < stride) {",
264
- " peaks[local] = max(peaks[local], peaks[local + stride]);",
271
+ " peakShared[local] = max(peakShared[local], peakShared[local + stride]);",
265
272
  " }",
266
273
  " workgroupBarrier();",
267
274
  " }",
268
- " let largest = peaks[0];",
275
+ " let largest = peakShared[0];",
269
276
  " workgroupBarrier();",
270
277
  " return largest;",
271
278
  "}"
@@ -274,22 +281,22 @@ var WGSL_PEAK = Object.freeze({
274
281
  variant: Object.freeze({
275
282
  extension: "subgroups",
276
283
  source: [
277
- "var<workgroup> peaks: array<f32, 64>;",
284
+ "var<workgroup> peakShared: array<f32, 64>;",
278
285
  "",
279
- "fn peak(invocation: Invocation, value: f32) -> f32 {",
286
+ "fn peakPartials(invocation: Invocation, value: f32) -> f32 {",
280
287
  " let local = invocation.local_invocation_index;",
281
288
  " let partial = subgroupMax(value);",
282
- " peaks[local] = select(-3.4028234663852886e38, partial, invocation.subgroup_invocation_id == 0u);",
289
+ " peakShared[local] = select(-3.4028234663852886e38, partial, invocation.subgroup_invocation_id == 0u);",
283
290
  " workgroupBarrier();",
284
291
  " if (local == 0u) {",
285
292
  " var acc = -3.4028234663852886e38;",
286
293
  " for (var i = 0u; i < 64u; i += 1u) {",
287
- " acc = max(acc, peaks[i]);",
294
+ " acc = max(acc, peakShared[i]);",
288
295
  " }",
289
- " peaks[0] = acc;",
296
+ " peakShared[0] = acc;",
290
297
  " }",
291
298
  " workgroupBarrier();",
292
- " let largest = peaks[0];",
299
+ " let largest = peakShared[0];",
293
300
  " workgroupBarrier();",
294
301
  " return largest;",
295
302
  "}"
@@ -300,7 +307,8 @@ var WGSL_PEAK = Object.freeze({
300
307
  * Holds the fragment that widens the IEEE 754 half-precision bits in the low 16 bits of a `u32` to an `f32`.
301
308
  *
302
309
  * @remarks
303
- * It declares `fn widen(bits: u32) -> f32`, which builds the result from integer bit operations, so
310
+ * It declares `fn widenHalf(bits: u32) -> f32`, which takes neither `Invocation` nor `Dispatch`
311
+ * and builds the result from integer bit operations, so
304
312
  * signed zeros, subnormals, infinities, and NaN payloads widen exactly and no `f16` extension is
305
313
  * needed. An exponent of `0x1f` keeps the fraction under an all-ones `f32` exponent, so infinities
306
314
  * stay infinite and NaN payloads survive. A subnormal half rebuilds its `f32` bits from
@@ -309,13 +317,13 @@ var WGSL_PEAK = Object.freeze({
309
317
  *
310
318
  * @example
311
319
  * ```ts
312
- * WGSL_HALF.name // 'half'
320
+ * WGSL_HALF.name // 'widenHalf'
313
321
  * ```
314
322
  */
315
323
  var WGSL_HALF = Object.freeze({
316
- name: "half",
324
+ name: "widenHalf",
317
325
  source: [
318
- "fn widen(bits: u32) -> f32 {",
326
+ "fn widenHalf(bits: u32) -> f32 {",
319
327
  " let sign = (bits & 0x8000u) << 16u;",
320
328
  " let exponent = (bits >> 10u) & 0x1fu;",
321
329
  " let fraction = bits & 0x3ffu;",
@@ -528,13 +536,15 @@ function collectWGSLFragments(roots) {
528
536
  *
529
537
  * @remarks
530
538
  * The text holds, in order: an `enable` directive for each extension a linked fragment's active
531
- * variant names, in `WGSL_EXTENSIONS` order; the uniform struct declaration; the `Invocation` entry
532
- * input struct, which carries `local_invocation_index`, `workgroup_id`, and `num_workgroups`, plus
539
+ * variant names, in `WGSL_EXTENSIONS` order; the uniform struct declaration; the `Dispatch` struct,
540
+ * which carries the workgroup-uniform builtins `workgroup_id` and `num_workgroups`; the
541
+ * `Invocation` struct, which carries the per-lane builtin `local_invocation_index`, plus
533
542
  * `subgroup_invocation_id` and `subgroup_size` when `enable subgroups;` is emitted; one
534
543
  * `@group(0) @binding(N)` storage line per slot in declaration order and the `@group(1) @binding(0)`
535
- * uniform line; each linked fragment's active body, unchanged; and the entry function, which takes
536
- * the input struct as `invocation`. A fragment's variant is active when `extensions` switches its
537
- * extension on.
544
+ * uniform line; each linked fragment's active body, unchanged; and the entry function
545
+ * `fn <entry>(invocation: Invocation, dispatch: Dispatch)`. The split lets a helper that takes only
546
+ * `dispatch` return early before a barrier without a per-lane value reaching that condition. A
547
+ * fragment's variant is active when `extensions` switches its extension on.
538
548
  *
539
549
  * @param program - The program to render
540
550
  * @param extensions - Whether each extension is active
@@ -548,12 +558,17 @@ function collectWGSLFragments(roots) {
548
558
  function renderWGSLProgram(program, extensions) {
549
559
  const variants = program.fragments.map((fragment) => fragment.variant !== void 0 && extensions[fragment.variant.extension] ? fragment.variant : void 0);
550
560
  const enabled = Object.keys(WGSL_EXTENSIONS).filter((name) => variants.some((variant) => variant?.extension === name));
561
+ const subgroups = enabled.includes("subgroups") ? [" @builtin(subgroup_invocation_id) subgroup_invocation_id: u32,", " @builtin(subgroup_size) subgroup_size: u32,"] : [];
562
+ const dispatch = [
563
+ "struct Dispatch {",
564
+ " @builtin(workgroup_id) workgroup_id: vec3u,",
565
+ " @builtin(num_workgroups) num_workgroups: vec3u,",
566
+ "}"
567
+ ];
551
568
  const invocation = [
552
569
  "struct Invocation {",
553
570
  " @builtin(local_invocation_index) local_invocation_index: u32,",
554
- " @builtin(workgroup_id) workgroup_id: vec3u,",
555
- " @builtin(num_workgroups) num_workgroups: vec3u,",
556
- ...enabled.includes("subgroups") ? [" @builtin(subgroup_invocation_id) subgroup_invocation_id: u32,", " @builtin(subgroup_size) subgroup_size: u32,"] : [],
571
+ ...subgroups,
557
572
  "}"
558
573
  ];
559
574
  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};`];
@@ -561,13 +576,14 @@ function renderWGSLProgram(program, extensions) {
561
576
  const [x, y, z] = program.entry.size;
562
577
  const entry = [
563
578
  `@compute @workgroup_size(${x}, ${y}, ${z})`,
564
- `fn ${program.entry.name}(invocation: Invocation) {`,
579
+ `fn ${program.entry.name}(invocation: Invocation, dispatch: Dispatch) {`,
565
580
  program.entry.source,
566
581
  "}"
567
582
  ];
568
583
  return `${[
569
584
  enabled.map((name) => `enable ${name};`).join("\n"),
570
585
  program.uniform.struct.source,
586
+ dispatch.join("\n"),
571
587
  invocation.join("\n"),
572
588
  bindings.join("\n"),
573
589
  ...bodies,
@@ -579,8 +595,9 @@ function renderWGSLProgram(program, extensions) {
579
595
  *
580
596
  * @remarks
581
597
  * A program reads its workgroup's index as
582
- * `invocation.workgroup_id.x + invocation.workgroup_id.y * invocation.num_workgroups.x`, so a
583
- * workgroup past the total finds no work. A total of 0 gives one workgroup. Thrown with code
598
+ * `dispatch.workgroup_id.x + dispatch.workgroup_id.y * dispatch.num_workgroups.x`, which the
599
+ * `WGSL_PLACE` fragment declares as `readPlace(dispatch: Dispatch)`, so a workgroup past the total
600
+ * finds no work. A total of 0 gives one workgroup. Thrown with code
584
601
  * `ARGUMENT` when `total` is not a non-negative safe integer, `-0` included, or `limit` is not a
585
602
  * positive safe integer, and with code `LIMIT` when the total passes `limit * limit`.
586
603
  *
@@ -646,7 +663,7 @@ function computeWGSLOffset(offset, alignment) {
646
663
  }
647
664
  // src/core/WGSLBatch.ts
648
665
  /**
649
- * Records one command encoder's worth of dispatches and buffer reads, then submits them together.
666
+ * Records one command encoder's worth of dispatches, copies, clears, and reads, then submits them together.
650
667
  *
651
668
  * @remarks
652
669
  * The batch owns its command encoder and its compute pass, and keeps one pass open across
@@ -654,14 +671,19 @@ function computeWGSLOffset(offset, alignment) {
654
671
  * previous one. Each dispatch writes its uniform values to the session's slab and binds them through
655
672
  * the 5-argument `setBindGroup(1, group, offsets, 0, 1)` overload. When the slab is full, the batch
656
673
  * ends its pass, uploads the slab, submits, clears the slab, and opens a fresh encoder. The pass
657
- * ends before each `read` copy. Every upload and submit sits between a synchronous push and pop of a
658
- * `validation` and an `out-of-memory` error scope; a device error on a submitted command buffer
659
- * moves the session to `failed` with code `VALIDATION`. `read` resolves after the submission to a
660
- * caller-owned copy of the bytes. Thrown with code `VALIDATION` when a call other than `abort` or
661
- * `execute` arrives after `submit` or `abort`; with code `ARGUMENT` for a malformed grid or read
662
- * range; and with code `LIMIT` when a grid axis passes the device's
663
- * `maxComputeWorkgroupsPerDimension`. Open a batch through `session.batch()`, which supplies the
664
- * options.
674
+ * ends before each `read`, `copy`, and `clear`, which record `copyBufferToBuffer` and `clearBuffer`
675
+ * on the encoder; the next `encode` begins a new pass and sets its pipeline and groups again. Every
676
+ * upload and submit sits between a synchronous push and pop of a `validation` and an `out-of-memory`
677
+ * error scope; a device error on a submitted command buffer moves the session to `failed` with code
678
+ * `VALIDATION`. `read` resolves after the submission to a caller-owned copy of the bytes. Each
679
+ * `read`, `copy`, and `clear` checks the session, the batch, its buffers' usages, and its offsets,
680
+ * sizes, and ranges before it records anything, so a refused call leaves the open pass in place.
681
+ * Thrown with code `VALIDATION` when a call other than `abort` or `execute` arrives after `submit`
682
+ * or `abort`; with code `ARGUMENT` for a malformed grid, a malformed `read`, `copy`, or `clear`
683
+ * range, a buffer without the usage the call needs, or a `copy` between one buffer and itself; with
684
+ * code `DESTROYED` after the session's `destroy`; and with code `LIMIT` when a grid axis passes the
685
+ * device's `maxComputeWorkgroupsPerDimension`. Open a batch through `session.batch()`, which
686
+ * supplies the options.
665
687
  *
666
688
  * @example
667
689
  * ```ts
@@ -753,26 +775,10 @@ var WGSLBatch = class {
753
775
  }
754
776
  read(buffer, offset, size) {
755
777
  this.#check();
756
- 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}.`, {
757
- code: "ARGUMENT",
758
- context: { usage: buffer.usage }
759
- });
760
- if (!(0, _orkestrel_contract.isNonNegativeInteger)(offset) || !(0, _orkestrel_contract.isSafeInteger)(offset) || offset % 4 !== 0) throw new WGSLError(`A read starts at ${(0, _orkestrel_contract.preview)(offset)}; a read offset must be a non-negative safe multiple of 4 bytes.`, {
761
- code: "ARGUMENT",
762
- context: { offset }
763
- });
764
- if (!(0, _orkestrel_contract.isSafeInteger)(size) || size < 4 || size % 4 !== 0) throw new WGSLError(`A read spans ${(0, _orkestrel_contract.preview)(size)} bytes; a read size must be a safe multiple of 4 bytes, at least 4.`, {
765
- code: "ARGUMENT",
766
- context: { size }
767
- });
768
- 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.`, {
769
- code: "ARGUMENT",
770
- context: {
771
- offset,
772
- size,
773
- length: buffer.size
774
- }
775
- });
778
+ this.#checkUsage(buffer, "source", "read");
779
+ this.#checkOffset(offset, "read");
780
+ this.#checkSize(size, "read");
781
+ this.#checkRange(buffer, offset, size, "read");
776
782
  this.#close();
777
783
  const staging = this.#options.lease(size);
778
784
  this.#encoder.copyBufferToBuffer(buffer, offset, staging, 0, size);
@@ -785,6 +791,31 @@ var WGSLBatch = class {
785
791
  ]);
786
792
  return result.promise;
787
793
  }
794
+ copy(source, destination, size) {
795
+ this.#check();
796
+ const [from, start] = this.#readSlice(source, "source", "copy source");
797
+ const [to, at] = this.#readSlice(destination, "destination", "copy destination");
798
+ if (from === to) throw new WGSLError("A copy reads and writes one buffer; copy between two distinct buffers, or stage the range through a second buffer.", {
799
+ code: "ARGUMENT",
800
+ context: { label: from.label }
801
+ });
802
+ this.#checkSize(size, "copy");
803
+ this.#checkRange(from, start, size, "copy source");
804
+ this.#checkRange(to, at, size, "copy destination");
805
+ this.#close();
806
+ this.#encoder.copyBufferToBuffer(from, start, to, at, size);
807
+ }
808
+ clear(buffer, offset, size) {
809
+ this.#check();
810
+ this.#checkUsage(buffer, "destination", "clear");
811
+ const start = offset ?? 0;
812
+ this.#checkOffset(start, "clear");
813
+ const length = size ?? buffer.size - start;
814
+ this.#checkSize(length, "clear");
815
+ this.#checkRange(buffer, start, length, "clear");
816
+ this.#close();
817
+ this.#encoder.clearBuffer(buffer, start, length);
818
+ }
788
819
  submit() {
789
820
  this.#check();
790
821
  this.#close();
@@ -824,6 +855,49 @@ var WGSLBatch = class {
824
855
  context: { status: this.#status }
825
856
  });
826
857
  }
858
+ #checkUsage(buffer, usage, operation) {
859
+ if ((0, _orkestrel_contract.isObject)(buffer) && (buffer.usage & WGSL_USAGE[usage]) !== 0) return;
860
+ const received = (0, _orkestrel_contract.isObject)(buffer) ? buffer.usage : void 0;
861
+ throw new WGSLError(`A ${operation} needs a buffer with the ${usage} usage (WGSL_USAGE.${usage}); its usage is ${(0, _orkestrel_contract.preview)(received)}.`, {
862
+ code: "ARGUMENT",
863
+ context: { usage: received }
864
+ });
865
+ }
866
+ #checkOffset(offset, operation) {
867
+ if ((0, _orkestrel_contract.isNonNegativeInteger)(offset) && (0, _orkestrel_contract.isSafeInteger)(offset) && offset % 4 === 0) return;
868
+ throw new WGSLError(`A ${operation} starts at ${(0, _orkestrel_contract.preview)(offset)}; a ${operation} offset must be a non-negative safe multiple of 4 bytes.`, {
869
+ code: "ARGUMENT",
870
+ context: { offset }
871
+ });
872
+ }
873
+ #checkSize(size, operation) {
874
+ if ((0, _orkestrel_contract.isSafeInteger)(size) && size >= 4 && size % 4 === 0) return;
875
+ throw new WGSLError(`A ${operation} spans ${(0, _orkestrel_contract.preview)(size)} bytes; a ${operation} size must be a safe multiple of 4 bytes, at least 4.`, {
876
+ code: "ARGUMENT",
877
+ context: { size }
878
+ });
879
+ }
880
+ #checkRange(buffer, offset, size, operation) {
881
+ if (offset + size <= buffer.size) return;
882
+ throw new WGSLError(`A ${operation} ends at byte ${offset + size}, past its buffer's ${buffer.size} bytes; shorten the range.`, {
883
+ code: "ARGUMENT",
884
+ context: {
885
+ offset,
886
+ size,
887
+ length: buffer.size
888
+ }
889
+ });
890
+ }
891
+ #readSlice(slice, usage, operation) {
892
+ if (!(0, _orkestrel_contract.isObject)(slice)) throw new WGSLError(`A ${operation} must be a slice such as { buffer, offset: 0 }; received ${(0, _orkestrel_contract.preview)(slice)}.`, {
893
+ code: "ARGUMENT",
894
+ context: { slice }
895
+ });
896
+ const { buffer, offset = 0 } = slice;
897
+ this.#checkUsage(buffer, usage, operation);
898
+ this.#checkOffset(offset, operation);
899
+ return [buffer, offset];
900
+ }
827
901
  #refuseGrid(grid) {
828
902
  throw new WGSLError(`A dispatch grid must hold three positive safe integer workgroup counts, such as [4, 1, 1]; received ${(0, _orkestrel_contract.preview)(grid)}.`, {
829
903
  code: "ARGUMENT",
@@ -1310,13 +1384,17 @@ var WGSLStatement = class {
1310
1384
  * `open`. Thrown with code `LIMIT` when a program's workgroup size or slot count passes the device's
1311
1385
  * limits, and with code `VALIDATION` from `batch()` while another batch is open. A device failure on
1312
1386
  * a submitted batch, or the device's `lost` promise, moves the session to `failed`, making
1313
- * `prepare`, `batch`, and any open batch's `encode`, `read`, and `submit` throw that failure while
1387
+ * `prepare`, `batch`, and any open batch's `encode`, `read`, `copy`, `clear`, and `submit` throw that failure while
1314
1388
  * `destroy` resolves. `destroy` moves the session to `destroyed` at once, aborts the open batch,
1315
1389
  * waits for submitted work and reads, and destroys the uniform buffer and the staging buffers the
1316
1390
  * session created; a repeated `destroy` returns the same promise, settled `abort` and `execute`
1317
1391
  * replay their batch's own settlement, and `prepare`, `batch`, `encode`, `read`, and `submit` throw
1318
- * with code `DESTROYED`. Thrown with code `ARGUMENT`
1319
- * from the constructor when `uniform.size` is not a positive safe multiple of 4.
1392
+ * with code `DESTROYED`, and so do `copy` and `clear` on its batch. The constructor reads its options
1393
+ * through `resolveOptions` and throws with code `ARGUMENT`, carrying the option fault as `cause`,
1394
+ * when `options` is not a record, when a key is not `extensions` or `uniform` at the top level, `f16`
1395
+ * or `subgroups` inside `extensions`, or `size` inside `uniform`, when an `extensions` value is not a
1396
+ * boolean, and when `uniform.size` is `null` or not a number. It throws with code `ARGUMENT` and the
1397
+ * received `size` in `context` when `uniform.size` is not a positive safe multiple of 4.
1320
1398
  *
1321
1399
  * @example
1322
1400
  * ```ts
@@ -1349,12 +1427,34 @@ var WGSLSession = class {
1349
1427
  * @param options - The extensions to switch off and the slab's byte size
1350
1428
  */
1351
1429
  constructor(device, options) {
1352
- const size = options?.uniform?.size ?? 65536;
1353
- if (!(0, _orkestrel_contract.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 ${(0, _orkestrel_contract.preview)(size)}.`, {
1354
- code: "ARGUMENT",
1355
- context: { size }
1430
+ const resolved = (0, _orkestrel_contract.resolveOptions)(options, {
1431
+ extensions: (0, _orkestrel_contract.optionalGroupOption)({
1432
+ f16: (0, _orkestrel_contract.optionalOption)(_orkestrel_contract.isBoolean),
1433
+ subgroups: (0, _orkestrel_contract.optionalOption)(_orkestrel_contract.isBoolean)
1434
+ }),
1435
+ uniform: (0, _orkestrel_contract.groupOption)({ size: (0, _orkestrel_contract.defaultOption)(_orkestrel_contract.isNumber, WGSL_UNIFORM_SIZE) })
1436
+ }, {
1437
+ refuse: (fault) => {
1438
+ const cause = (0, _orkestrel_contract.optionFaultToError)(fault, "createWGSLSession");
1439
+ return new WGSLError(`The session options are malformed: ${cause.message}`, {
1440
+ code: "ARGUMENT",
1441
+ context: {
1442
+ reason: fault.reason,
1443
+ path: fault.path
1444
+ },
1445
+ cause
1446
+ });
1447
+ },
1448
+ check: ({ uniform: { size } }) => {
1449
+ if ((0, _orkestrel_contract.isSafeInteger)(size) && size >= 4 && size % 4 === 0) return;
1450
+ throw new WGSLError(`A session's uniform size must be a positive safe multiple of 4 bytes; received ${(0, _orkestrel_contract.preview)(size)}.`, {
1451
+ code: "ARGUMENT",
1452
+ context: { size }
1453
+ });
1454
+ }
1356
1455
  });
1357
- const requested = options?.extensions;
1456
+ const size = resolved.uniform.size;
1457
+ const requested = resolved.extensions;
1358
1458
  const features = device.features;
1359
1459
  const usage = WGSL_USAGE.uniform | WGSL_USAGE.destination;
1360
1460
  const entry = {