@margoengine/shader 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1919 -2
  4. package/dist/attribute.d.ts +28 -0
  5. package/dist/black-hole.d.ts +246 -0
  6. package/dist/black-hole.js +445 -0
  7. package/dist/clock-BLGNexlt.js +52 -0
  8. package/dist/clock.d.ts +42 -0
  9. package/dist/compute-CXGG9qvI.js +360 -0
  10. package/dist/compute-texture.d.ts +100 -0
  11. package/dist/compute-texture.js +131 -0
  12. package/dist/compute-volume.d.ts +57 -0
  13. package/dist/compute-volume.js +130 -0
  14. package/dist/compute.d.ts +200 -0
  15. package/dist/control-CFjkGPBk.js +201 -0
  16. package/dist/control.d.ts +93 -0
  17. package/dist/deform.d.ts +111 -0
  18. package/dist/deform.js +89 -0
  19. package/dist/display-BrJM_Qkd.js +5 -0
  20. package/dist/editor-model.d.ts +192 -0
  21. package/dist/editor-pass.d.ts +71 -0
  22. package/dist/editor-pass.js +216 -0
  23. package/dist/editor.d.ts +150 -0
  24. package/dist/editor.js +1071 -0
  25. package/dist/effects.d.ts +150 -0
  26. package/dist/effects.js +87 -0
  27. package/dist/errors-CsQwshHA.js +7 -0
  28. package/dist/glsl/emit.d.ts +43 -0
  29. package/dist/glsl/host.d.ts +55 -0
  30. package/dist/glsl/material.d.ts +173 -0
  31. package/dist/glsl/parser.d.ts +76 -0
  32. package/dist/glsl/preprocess.d.ts +9 -0
  33. package/dist/glsl/presets.d.ts +33 -0
  34. package/dist/glsl/program.d.ts +210 -0
  35. package/dist/glsl/scene.d.ts +9 -0
  36. package/dist/glsl-material.d.ts +82 -0
  37. package/dist/glsl-material.js +288 -0
  38. package/dist/glsl-pass.d.ts +93 -0
  39. package/dist/glsl-pass.js +186 -0
  40. package/dist/glsl.d.ts +94 -0
  41. package/dist/glsl.js +170 -0
  42. package/dist/gpu-DQJk2xAv.js +55 -0
  43. package/dist/graph.d.ts +82 -0
  44. package/dist/graph.js +365 -0
  45. package/dist/index.d.ts +8 -0
  46. package/dist/index.js +103 -0
  47. package/dist/lighting-JU9yQPfM.js +77 -0
  48. package/dist/lighting.d.ts +62 -0
  49. package/dist/lighting.js +1 -0
  50. package/dist/material-C6bpqlnE.js +1184 -0
  51. package/dist/material-CZ8V1FeA.js +299 -0
  52. package/dist/material.d.ts +79 -0
  53. package/dist/node-B6yoIC9V.js +590 -0
  54. package/dist/node.d.ts +433 -0
  55. package/dist/noise.d.ts +38 -0
  56. package/dist/noise.js +107 -0
  57. package/dist/own-stack-D1XnXrrz.js +11 -0
  58. package/dist/own-stack.d.ts +12 -0
  59. package/dist/pass.d.ts +109 -0
  60. package/dist/pass.js +239 -0
  61. package/dist/post-DLpZ110L.js +113 -0
  62. package/dist/post.d.ts +69 -0
  63. package/dist/preprocess-CWGWlBWQ.js +1195 -0
  64. package/dist/raw-0AYej3Ak.js +1500 -0
  65. package/dist/raw.d.ts +744 -0
  66. package/dist/raw.js +1 -0
  67. package/dist/readback.d.ts +42 -0
  68. package/dist/readback.js +85 -0
  69. package/dist/scope.d.ts +21 -0
  70. package/dist/serialization.d.ts +11 -0
  71. package/dist/serialization.js +192 -0
  72. package/dist/shadertoy/sound.d.ts +48 -0
  73. package/dist/shadertoy.d.ts +249 -0
  74. package/dist/shadertoy.js +909 -0
  75. package/dist/shared/caster.d.ts +159 -0
  76. package/dist/shared/fog.d.ts +33 -0
  77. package/dist/shared/fractal.d.ts +9 -0
  78. package/dist/shared/msaa.d.ts +30 -0
  79. package/dist/shared/stack.d.ts +22 -0
  80. package/dist/sound-CF_dzP41.js +78 -0
  81. package/dist/storage-format-DWaiSxmq.js +25 -0
  82. package/dist/storage-format.d.ts +7 -0
  83. package/dist/subgroups.d.ts +97 -0
  84. package/dist/subgroups.js +95 -0
  85. package/dist/texture-BawKO_h9.js +62 -0
  86. package/dist/texture-array.d.ts +7 -0
  87. package/dist/texture-array.js +11 -0
  88. package/dist/texture.d.ts +16 -0
  89. package/dist/utils.d.ts +106 -0
  90. package/dist/utils.js +90 -0
  91. package/dist/view-rect-Bm1ac-TK.js +16 -0
  92. package/package.json +149 -4
@@ -0,0 +1,130 @@
1
+ import { T as e, cn as t, in as n, o as r, tn as i } from "./node-B6yoIC9V.js";
2
+ import { d as a, f as o } from "./control-CFjkGPBk.js";
3
+ import { c as s } from "./compute-CXGG9qvI.js";
4
+ import { n as c, r as l, t as u } from "./storage-format-DWaiSxmq.js";
5
+ import { MargoError as d } from "@margoengine/math/errors";
6
+ //#region src/compute-volume.ts
7
+ var f = (e) => {
8
+ if (e?.type !== "vec3u" && e?.type !== "vec3i") throw TypeError("Volume coordinates must be vec3u or vec3i; use volume.coord(index)");
9
+ return e;
10
+ }, p = class {
11
+ constructor(e, t, n, r = {}) {
12
+ this.width = e, this.height = t, this.depth = n, this.id = i(), this.devices = /* @__PURE__ */ new Map(), this.uses = /* @__PURE__ */ new WeakMap();
13
+ let { dimension: a = "3d", format: o = "rgba16float", data: s, filter: l = "linear", wrap: d = "clamp-to-edge", pingPong: f = !1, readWrite: p = !1 } = r;
14
+ if (![
15
+ e,
16
+ t,
17
+ n
18
+ ].every((e) => Number.isSafeInteger(e) && e > 0) || !Number.isSafeInteger(e * t * n) || e * t * n > 4294967295) throw RangeError("Use positive integer volume dimensions with at most 4294967295 voxels");
19
+ if (a !== "3d" && a !== "2d-array") throw TypeError("Use dimension '3d' or '2d-array'");
20
+ if (!Object.hasOwn(u, o)) throw TypeError("Use a supported storage texture format");
21
+ if (s && s.byteLength !== e * t * n * u[o]) throw RangeError(`Use volume data containing ${e * t * n * u[o]} bytes in x, y, z order`);
22
+ if (l !== "linear" && l !== "nearest") throw TypeError("Use filter 'linear' or 'nearest'");
23
+ if (![
24
+ "clamp-to-edge",
25
+ "repeat",
26
+ "mirror-repeat"
27
+ ].includes(d)) throw TypeError("Use a supported texture wrap mode");
28
+ if (p && (f || !/^r32/.test(o))) throw TypeError("Use readWrite with an r32 format and without pingPong");
29
+ this.dimension = a, this.format = o, this.data = s, this.filter = l, this.wrap = d, this.pixels = e * t * n, this.pingPong = f, this.readWrite = p;
30
+ let m = a.replace("-", "_"), h, g = (e, t, n) => ({
31
+ prefix: e,
32
+ bindings: 1,
33
+ declare: (e, n, r) => `@group(${n}) @binding(${r}) var ${e}:${t};`,
34
+ entries: (e) => {
35
+ let t = this.images(e);
36
+ return n && (h = t), [t.images[n && f ? 1 - t.current : t.current].view];
37
+ },
38
+ ...n && f ? { finish: () => {
39
+ h && (h.current = 1 - h.current);
40
+ } } : {}
41
+ });
42
+ this.writer = g("ndw", `texture_storage_${m}<${o}, ${p ? "read_write" : "write"}>`, !0), this.reader = p ? this.writer : g("ndr", `texture_${m}<${c(o)}>`, !1);
43
+ }
44
+ images(e) {
45
+ let t = this.devices.get(e);
46
+ if (t) return t;
47
+ let n = this.dimension === "3d" ? e.limits.maxTextureDimension3D : e.limits.maxTextureDimension2D, r = this.dimension === "3d" ? n : e.limits.maxTextureArrayLayers;
48
+ if (this.width > n || this.height > n || this.depth > r) throw new d("unsupported", `Volume exceeds this device's ${n} x ${n} x ${r} limit; reduce its dimensions`);
49
+ if (this.readWrite && !globalThis.navigator?.gpu?.wgslLanguageFeatures?.has("readonly_and_readwrite_storage_textures")) throw new d("unsupported", "This browser lacks read-write storage textures; use pingPong instead");
50
+ return t = {
51
+ images: Array.from({ length: this.pingPong ? 2 : 1 }, () => {
52
+ let t = e.createTexture({
53
+ label: "shader:compute-volume",
54
+ dimension: this.dimension === "3d" ? "3d" : "2d",
55
+ size: [
56
+ this.width,
57
+ this.height,
58
+ this.depth
59
+ ],
60
+ format: this.format,
61
+ usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.COPY_SRC | GPUTextureUsage.COPY_DST
62
+ });
63
+ return this.data && e.queue.writeTexture({ texture: t }, this.data, {
64
+ bytesPerRow: this.width * u[this.format],
65
+ rowsPerImage: this.height
66
+ }, [
67
+ this.width,
68
+ this.height,
69
+ this.depth
70
+ ]), {
71
+ texture: t,
72
+ view: t.createView({ dimension: this.dimension })
73
+ };
74
+ }),
75
+ current: 0,
76
+ stop: s(e, () => this.devices.delete(e))
77
+ }, this.devices.set(e, t), t;
78
+ }
79
+ use(e, t) {
80
+ if (this.pingPong || this.readWrite) return;
81
+ let n = (this.uses.get(e.program) ?? 0) | t;
82
+ if (this.uses.set(e.program, n), n === 3) throw TypeError("One pass cannot read and write the same image; use pingPong or r32 readWrite");
83
+ }
84
+ at(e, t) {
85
+ let n = e.expr(t);
86
+ return this.dimension === "3d" ? n : `${n}.xy, i32(${n}.z)`;
87
+ }
88
+ load(e) {
89
+ return new r(l(this.format), "volume" + this.id, [f(e)], (e, t) => (this.use(e, 1), `textureLoad(${e.resource(this.reader)}, ${this.at(e, t.args[0])}${this.readWrite ? "" : ", 0"})`), 32);
90
+ }
91
+ store(t, n) {
92
+ return a(o([f(t), e(n, l(this.format), "stored voxel")], (e, t) => {
93
+ if (e.stage.kind !== "compute") throw TypeError("Use volume.store inside a ComputePass body");
94
+ this.use(e, 2), e.line(`textureStore(${e.resource(this.writer)}, ${this.at(e, t.args[0])}, ${e.expr(t.args[1])});`), e.epoch++;
95
+ }), "store");
96
+ }
97
+ coord(e) {
98
+ return n(e.mod(this.width), e.div(this.width).mod(this.height), e.div(this.width * this.height));
99
+ }
100
+ uv(e) {
101
+ return t(f(e).toFloat().add(.5)).div(t(this.width, this.height, this.depth));
102
+ }
103
+ bind(e) {
104
+ if (c(this.format) !== "f32" || /32float$/.test(this.format) && !e.features.has("float32-filterable")) throw new d("unsupported", "Use load() for integer or unfilterable float32 volumes, or use rgba16float");
105
+ let t = this.images(e);
106
+ return t.sampler ??= e.createSampler({
107
+ magFilter: this.filter,
108
+ minFilter: this.filter,
109
+ addressModeU: this.wrap,
110
+ addressModeV: this.wrap,
111
+ addressModeW: this.wrap
112
+ }), [t.images[t.current].view, t.sampler];
113
+ }
114
+ texture(e) {
115
+ let t = this.images(e);
116
+ return t.images[t.current].texture;
117
+ }
118
+ dispose() {
119
+ for (let e of this.devices.values()) {
120
+ e.stop();
121
+ for (let t of e.images) t.texture.destroy();
122
+ }
123
+ this.devices.clear();
124
+ }
125
+ [Symbol.dispose ?? Symbol()]() {
126
+ this.dispose();
127
+ }
128
+ }, m = (e, t, n, r) => new p(e, t, n, r);
129
+ //#endregion
130
+ export { p as ComputeVolume, m as storageVolume };
@@ -0,0 +1,200 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph } from '@margoengine/core/extension';
4
+ import { Node, Program, type Host, type NodeInput, type Resource, type Type } from './node.js';
5
+ /** Element types with a 4-byte-aligned array stride (vec3 would pad; use vec4). */
6
+ export type StorageType = 'f32' | 'i32' | 'u32' | 'vec2f' | 'vec2i' | 'vec2u' | 'vec4f' | 'vec4i' | 'vec4u';
7
+ type Atomic = 'u32' | 'i32';
8
+ /** What a ComputePass body returns: writes, atomic results to keep, or nothing when it only makes atomic operations. */
9
+ export type ComputeBody = Store | Node | readonly (Store | Node)[] | void;
10
+ type Index = NodeInput<'u32' | 'i32'>;
11
+ type LossListener = (info: GPUDeviceLostInfo) => void;
12
+ /** @internal Calls `listener` once when `device` is lost; returns the unsubscribe. Keeps no closure alive after it. */
13
+ export declare function observeDeviceLoss(device: GPUDevice, listener: LossListener): () => void;
14
+ /** What `compareExchange` gives: the value before the attempt, and whether the swap happened. */
15
+ export interface Exchange<T extends Type> {
16
+ readonly old: Node<T>;
17
+ readonly exchanged: Node<'bool'>;
18
+ }
19
+ /** One write `buffer[index] = value`, made by `StorageBuffer.store` inside a ComputePass body. */
20
+ export interface Store {
21
+ readonly buffer: StorageBuffer;
22
+ readonly index: Node;
23
+ readonly value: Node;
24
+ }
25
+ /** A GPU array that compute nodes write and any node reads (`element(i)`); `buffer(device)` hands it to other passes (it is also a vertex buffer). */
26
+ export declare class StorageBuffer<T extends StorageType = StorageType> implements Resource {
27
+ readonly data: Float32Array | Int32Array | Uint32Array;
28
+ readonly type: T;
29
+ readonly atomic: boolean;
30
+ readonly prefix = "ndb";
31
+ readonly bindings = 1;
32
+ readonly count: number;
33
+ private readonly id;
34
+ private version;
35
+ private readonly buffers;
36
+ private readonly lossSubscriptions;
37
+ /** `atomic: true` (u32 or i32 only) declares `array<atomic<T>>` in compute passes so `atomicAdd`/`atomicMax`/`atomicMin` work. */
38
+ constructor(data: Float32Array | Int32Array | Uint32Array, type: T, atomic?: boolean);
39
+ /** @internal */ declare(name: string, group: number, binding: number, write: boolean): string;
40
+ /** @internal */ entries(device: GPUDevice): GPUBindingResource[];
41
+ /** The GPU copy for `device`, created from `data` on first use and after `update()`. */
42
+ buffer(device: GPUDevice): GPUBuffer;
43
+ /**
44
+ * Re-upload `data` on next use, replacing what the GPU computed. With `range` (in elements), only those elements are
45
+ * written, at once, to each copy that is otherwise up to date.
46
+ */
47
+ update(range?: {
48
+ start: number;
49
+ count: number;
50
+ }): void;
51
+ /** Element `i` (an `atomicLoad` on an atomic buffer inside a ComputePass; use `atomicLoad` to fix when it reads relative to other atomics). */
52
+ element(i: Index): Node<T>;
53
+ /** A write made at the end of the ComputePass body (`atomicStore` on an atomic buffer); inside `If`, `Loop` and other statement bodies it happens right where it is called. */
54
+ store(i: Index, value: NodeInput<T>): Store;
55
+ /** Atomically adds `value` to element `i` and returns the previous value (compaction: `out.store(counter.atomicAdd(0, 1), i)`).
56
+ * Runs where it is made, in order with other atomics, even when its result is unused; inside `loop` or `Fn` only when the result is used. */
57
+ atomicAdd(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
58
+ /** Atomic subtraction; returns the previous value. */
59
+ atomicSub(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
60
+ /** Atomic maximum; returns the previous value. */
61
+ atomicMax(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
62
+ /** Atomic minimum; returns the previous value. */
63
+ atomicMin(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
64
+ /** Atomic bitwise and; returns the previous value. */
65
+ atomicAnd(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
66
+ /** Atomic bitwise or; returns the previous value. */
67
+ atomicOr(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
68
+ /** Atomic bitwise xor; returns the previous value. */
69
+ atomicXor(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
70
+ /** Atomically replaces element `i`; returns the previous value. */
71
+ atomicExchange(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Node<T>;
72
+ /**
73
+ * Sets element `i` to `value` if it equals `compare`. It may fail even when they are equal (WGSL's weak form), so
74
+ * retry in a `Loop` or `While` on `exchanged`.
75
+ */
76
+ atomicCompareExchange(this: StorageBuffer<T & Atomic>, i: Index, compare: NodeInput<T>, value: NodeInput<T>): Exchange<T>;
77
+ /** Reads element `i` at this point of the body, after the atomics made before it (unlike `element`, which reads up front). */
78
+ atomicLoad(this: StorageBuffer<T & Atomic>, i: Index): Node<T>;
79
+ /** `store` on an atomic buffer. */
80
+ atomicStore(this: StorageBuffer<T & Atomic>, i: Index, value: NodeInput<T>): Store;
81
+ private rmw;
82
+ /** Destroys the GPU copies; a later use uploads `data` again. */
83
+ dispose(): void;
84
+ [Symbol.dispose]: () => void;
85
+ }
86
+ /** `storage(new Float32Array(4 * n), 'vec4f')` or `storage(n, 'vec4f')` for zeros; `storage(1, 'u32', {atomic: true})` for a counter. */
87
+ export declare function storage<T extends StorageType>(data: number | Float32Array | Int32Array | Uint32Array, type: T, { atomic }?: {
88
+ atomic?: boolean;
89
+ }): StorageBuffer<T>;
90
+ /** The invocation number in a ComputePass, 0..count-1 (row by row in a 2D or 3D pass). */
91
+ export declare const instanceIndex: Node<"u32">;
92
+ /** The invocation's position in the whole dispatch, `global_invocation_id`: `globalId.xy` is the texel of a 2D pass. */
93
+ export declare const globalId: Node<"vec3u">;
94
+ /** The invocation's position in its workgroup, and the same as one number 0..size-1. */
95
+ export declare const localId: Node<"vec3u">, localIndex: Node<"u32">;
96
+ /** Which workgroup this is, and how many the dispatch has. */
97
+ export declare const workgroupId: Node<"vec3u">, workgroupCount: Node<"vec3u">;
98
+ /** @internal Marks a pass as running whole workgroups: subgroup operations need the uniform control flow a barrier does. */
99
+ export declare const wholeGroups: (program: Program) => void;
100
+ /**
101
+ * Waits until every invocation of the workgroup arrives and sees each other's `workgroup` writes. Every invocation
102
+ * must reach it, so not under a branch or loop that differs between them (WGSL refuses that when the pipeline compiles).
103
+ */
104
+ export declare function workgroupBarrier(): void;
105
+ /** {@link workgroupBarrier} for storage buffers: writes before it are seen by the workgroup after it. */
106
+ export declare function storageBarrier(): void;
107
+ /** {@link workgroupBarrier} for read-write storage textures. */
108
+ export declare function textureBarrier(): void;
109
+ /** Element types of workgroup memory. */
110
+ export type WorkgroupType = StorageType | 'vec3f' | 'vec3i' | 'vec3u';
111
+ /** Memory shared by one workgroup, gone when it ends. Made with {@link workgroup}. */
112
+ export declare class WorkgroupArray<T extends WorkgroupType = WorkgroupType> implements Resource {
113
+ readonly count: number;
114
+ readonly type: T;
115
+ readonly atomic: boolean;
116
+ readonly prefix = "ndg";
117
+ readonly bindings = 0;
118
+ private readonly id;
119
+ constructor(count: number, type: T, atomic?: boolean);
120
+ /** @internal */ declare(name: string): string;
121
+ /** @internal */ entries(): GPUBindingResource[];
122
+ /** Element `i` where it is used (an `atomicLoad` on atomic memory). */
123
+ element(i: Index): Node<T>;
124
+ /** Writes element `i` here in the body, in order with barriers and other statements. */
125
+ store(i: Index, value: NodeInput<T>): void;
126
+ /**
127
+ * Element `i`, the same for the whole workgroup, so a branch or loop on it may hold a barrier (`workgroupUniformLoad`,
128
+ * which is itself a barrier). Not on atomic memory.
129
+ */
130
+ uniformLoad(i: Index): Node<T>;
131
+ private rmw;
132
+ /** Atomic addition; returns the previous value. The others match StorageBuffer's. */
133
+ atomicAdd(i: Index, value: NodeInput<T>): Node<T>;
134
+ atomicSub(i: Index, value: NodeInput<T>): Node<T>;
135
+ atomicMax(i: Index, value: NodeInput<T>): Node<T>;
136
+ atomicMin(i: Index, value: NodeInput<T>): Node<T>;
137
+ atomicAnd(i: Index, value: NodeInput<T>): Node<T>;
138
+ atomicOr(i: Index, value: NodeInput<T>): Node<T>;
139
+ atomicXor(i: Index, value: NodeInput<T>): Node<T>;
140
+ atomicExchange(i: Index, value: NodeInput<T>): Node<T>;
141
+ atomicCompareExchange(i: Index, compare: NodeInput<T>, value: NodeInput<T>): Exchange<T>;
142
+ /** `atomicLoad` at this point of the body. */
143
+ atomicLoad(i: Index): Node<T>;
144
+ /** `atomicStore` here in the body. */
145
+ atomicStore(i: Index, value: NodeInput<T>): void;
146
+ }
147
+ /**
148
+ * Declares memory shared by the invocations of one workgroup: `workgroup(64, 'f32')`, or `{atomic: true}` for u32 and i32.
149
+ * All workgroup memory of a pass must fit the device's 16,384 bytes.
150
+ */
151
+ export declare const workgroup: <T extends WorkgroupType>(count: number, type: T, { atomic }?: {
152
+ atomic?: boolean;
153
+ }) => WorkgroupArray<T>;
154
+ /** Invocations of a pass: a count, or `[x, y]` and `[x, y, z]` for a grid. */
155
+ export type ComputeCount = number | readonly [number, number] | readonly [number, number, number];
156
+ /**
157
+ * Options for `new ComputePass(count, body, options)`. `count` (invocations, >= 1) divided by `workgroupSize`, rounded
158
+ * up, must stay <= 65,535 workgroups.
159
+ */
160
+ export interface ComputeOptions {
161
+ /** Invocations per workgroup, up to 256 in all and 64 along z. Default 64, `[8, 8]` for a 2D pass, `[4, 4, 4]` for a 3D one. */
162
+ workgroupSize?: ComputeCount;
163
+ /** Frame-graph order; the default -100 runs before the scene draws. */
164
+ order?: number;
165
+ /** Plugin and debug name. Default `'shader:compute:<n>'` (n counts passes). */
166
+ name?: string;
167
+ /**
168
+ * Takes the workgroup counts from three u32 elements of this buffer when it dispatches, so an earlier pass can decide
169
+ * how much work there is. `count` stays the limit: invocations past it return at once.
170
+ */
171
+ indirect?: StorageBuffer<'u32'>;
172
+ /** Element of `indirect` where the three counts start. Default 0. */
173
+ indirectOffset?: number;
174
+ }
175
+ /** Runs `body` for `count` invocations every frame: atomic operations and statements first, in the order they were made, then its writes, returned ones first (their reads happen before any write). */
176
+ export declare class ComputePass implements EnginePlugin {
177
+ readonly count: ComputeCount;
178
+ readonly name: string;
179
+ readonly program: Program;
180
+ readonly code: string;
181
+ private readonly order;
182
+ private readonly groups;
183
+ private readonly indirect?;
184
+ private readonly indirectOffset;
185
+ private engine?;
186
+ private pipeline?;
187
+ private group?;
188
+ private last;
189
+ constructor(count: ComputeCount, body: (index: Node<'u32'>) => ComputeBody, { workgroupSize, order, name, indirect, indirectOffset, }?: ComputeOptions);
190
+ static attach(engine: EngineKernel, count: ComputeCount, body: (index: Node<'u32'>) => ComputeBody, options?: ComputeOptions): ComputePass;
191
+ setup(engine: Engine): void;
192
+ registerPasses(graph: FrameGraph): void;
193
+ private dispatch;
194
+ /** @internal Records one dispatch of every invocation into `encoder`, uploading uniforms and storage first. */
195
+ encode(device: GPUDevice, encoder: GPUCommandEncoder, host: Host): void;
196
+ onDeviceRestored(): void;
197
+ dispose(): void;
198
+ [Symbol.dispose]: () => void;
199
+ }
200
+ export {};
@@ -0,0 +1,201 @@
1
+ import { Ht as e, It as t, Q as n, T as r, gn as i, k as a, o, tn as s } from "./node-B6yoIC9V.js";
2
+ //#region src/control.ts
3
+ var c = (e) => {
4
+ throw TypeError(e);
5
+ };
6
+ function l(e, t) {
7
+ return (i.list ?? c(`${t} runs inside block(), a ComputePass body or another statement body`)).push(e), e;
8
+ }
9
+ var u = (e, t) => new o("bool", "S" + s(), e, (e, n) => (t(e, n), "false"), 4);
10
+ function d(e) {
11
+ l(u([e.index, e.value], (t, n) => {
12
+ t.stage.kind !== "compute" && c("Storage writes are only available in ComputePass nodes");
13
+ let [r, i] = n.args.map((e) => t.expr(e)), a = `${t.resource(e.buffer)}[${r}]`;
14
+ t.line(e.buffer.atomic ? `atomicStore(&${a}, ${i});` : `${a} = ${i};`), t.epoch++;
15
+ }), "store");
16
+ }
17
+ function f(e) {
18
+ let { list: t, store: n, flush: r } = i, a = i.list = [];
19
+ i.store = d, i.flush = void 0;
20
+ try {
21
+ e();
22
+ } finally {
23
+ i.list = t, i.store = n, i.flush = r;
24
+ }
25
+ return a;
26
+ }
27
+ var p = /* @__PURE__ */ new WeakMap(), m = (e) => {
28
+ let t = p.get(e);
29
+ return t || p.set(e, t = {
30
+ loops: 0,
31
+ breaks: 0
32
+ }), t;
33
+ }, h = /* @__PURE__ */ new WeakMap();
34
+ function g(e, t, n) {
35
+ for (let n of t) e.expr(n);
36
+ n?.();
37
+ for (let n of t) {
38
+ let t = h.get(n);
39
+ t && e.unbind(t);
40
+ }
41
+ }
42
+ function _(e, t) {
43
+ return e.push(), g(e, t), e.pop().map((e) => " " + e);
44
+ }
45
+ function v(e, t) {
46
+ for (let n of t) e.line(n);
47
+ }
48
+ function y(e, t, n) {
49
+ l(u(t ? [
50
+ e,
51
+ t,
52
+ n
53
+ ] : [e, n], (e, n) => {
54
+ let r = n.args.map((t) => e.expr(t));
55
+ e.epoch++, e.line(t ? `${r[0]}[${r[1]}] = ${r[2]};` : `${r[0]} = ${r[1]};`);
56
+ }), "assign");
57
+ }
58
+ var b = class extends o {
59
+ constructor(e) {
60
+ super(e, "V" + s(), [], (e, t) => e.param(t), 33);
61
+ }
62
+ assign(e) {
63
+ y(this, void 0, r(e, this.type, "assigned value"));
64
+ }
65
+ addAssign(e) {
66
+ this.assign(this.add(e));
67
+ }
68
+ subAssign(e) {
69
+ this.assign(this.sub(e));
70
+ }
71
+ mulAssign(e) {
72
+ this.assign(this.mul(e));
73
+ }
74
+ divAssign(e) {
75
+ this.assign(this.div(e));
76
+ }
77
+ assignElement(i, s) {
78
+ let l = n(this.type);
79
+ !l && e(this.type) === 1 && c("assignElement() needs a vector or matrix Var");
80
+ let u = i instanceof o ? i : a(i, "i32"), d = l ? `vec${this.type[3]}f` : t(this.type);
81
+ y(this, u, r(s, d, "assigned element"));
82
+ }
83
+ };
84
+ function x(e, t) {
85
+ let n = r(e, t ?? (e instanceof o ? e.type : typeof e == "boolean" ? "bool" : "f32"), "Var value"), i = new b(n.type), a = u([n], (e, t) => {
86
+ let n = e.expr(t.args[0]), r = e.name();
87
+ e.line(`var ${r}:${i.type} = ${n};`), e.bind(i, r);
88
+ });
89
+ return l(a, "Var"), h.set(a, i), i;
90
+ }
91
+ function S(e) {
92
+ return l(new o(e.type, "S" + s(), [e], (e, t) => {
93
+ let n = e.expr(t.args[0]), r = e.name();
94
+ return e.line(`let ${r} = ${n};`), r;
95
+ }, 28), "Let");
96
+ }
97
+ function C(e) {
98
+ let t, n = f(() => {
99
+ t = e();
100
+ });
101
+ t instanceof o || c("A block() body must return the node it worked out");
102
+ let r = t;
103
+ return new o(r.type, "S" + s(), [...n, r], (e) => {
104
+ let t = m(e), i = e.name();
105
+ return p.set(e, {
106
+ loops: 0,
107
+ breaks: 0
108
+ }), g(e, n, () => e.line(`let ${i} = ${e.expr(r)};`)), p.set(e, t), i;
109
+ }, 12);
110
+ }
111
+ function w(e, t) {
112
+ let n = [r(e, "bool", "If condition")], i = [f(t)], a = [n[0], ...i[0]], o, s = (e, t) => {
113
+ let r = e.expr(n[t]), a = _(e, i[t]), c = o && t + 1 === n.length ? _(e, o) : void 0;
114
+ t + 1 < n.length && (e.push(), s(e, t + 1), c = e.pop().map((e) => " " + e)), e.line(`if (${r}) {`), v(e, a), c && (e.line("} else {"), v(e, c)), e.line("}");
115
+ };
116
+ l(u(a, (e) => s(e, 0)), "If");
117
+ let d = {
118
+ ElseIf(e, t) {
119
+ o && c("ElseIf comes before Else");
120
+ let s = r(e, "bool", "ElseIf condition"), l = f(t);
121
+ return n.push(s), i.push(l), a.push(s, ...l), d;
122
+ },
123
+ Else(e) {
124
+ o && c("If has two Else bodies"), o = f(e), a.push(...o);
125
+ }
126
+ };
127
+ return d;
128
+ }
129
+ var T = (e) => e instanceof o ? e.type === "i32" ? e : e.toInt() : a(e, "i32");
130
+ function E(e, t) {
131
+ let n = m(e);
132
+ n.loops++, n.breaks++;
133
+ let r = _(e, t);
134
+ return n.loops--, n.breaks--, r;
135
+ }
136
+ function D(e, t) {
137
+ let { from: n = 0, to: r, step: i = 1 } = typeof e == "number" || e instanceof o ? { to: e } : e;
138
+ (!Number.isInteger(i) || i === 0) && c("Loop step must be a non-zero integer");
139
+ let a = new o("i32", "p" + s(), [], (e, t) => e.param(t), 1), d = f(() => t(a));
140
+ l(u([
141
+ T(n),
142
+ T(r),
143
+ ...d
144
+ ], (e, t) => {
145
+ let n = e.expr(t.args[0]), r = e.expr(t.args[1]), o = e.name(), s = e.name();
146
+ e.line(`let ${o} = ${r};`), e.bind(a, s), e.epoch++;
147
+ let c = E(e, d);
148
+ e.line(`for (var ${s} = ${n}; ${s} ${i > 0 ? "<" : ">"} ${o}; ${s} += ${i}i) {`), v(e, c), e.line("}");
149
+ }), "Loop");
150
+ }
151
+ function O(e, t) {
152
+ let n = r(e, "bool", "While condition"), i = f(t);
153
+ l(u([n, ...i], (e) => {
154
+ e.epoch++, e.push(), e.line(` if (!(${e.expr(n)})) { break; }`), v(e, E(e, i));
155
+ let t = e.pop();
156
+ e.line("loop {"), v(e, t), e.line("}");
157
+ }), "While");
158
+ }
159
+ function k() {
160
+ l(u([], (e) => {
161
+ m(e).breaks || c("Break() needs a Loop, While or Switch around it in the same block"), e.line("break;");
162
+ }), "Break");
163
+ }
164
+ function A() {
165
+ l(u([], (e) => {
166
+ m(e).loops || c("Continue() needs a Loop or While around it in the same block"), e.line("continue;");
167
+ }), "Continue");
168
+ }
169
+ function j(e) {
170
+ let t = e?.type;
171
+ t !== "i32" && t !== "u32" && c(`Switch needs an i32 or u32 node, got ${t}`);
172
+ let n = [], r = /* @__PURE__ */ new Set(), i = [e], o;
173
+ l(u(i, (t) => {
174
+ let r = t.expr(e), i = m(t), a = (e) => {
175
+ i.breaks++;
176
+ let n = _(t, e);
177
+ return i.breaks--, n.map((e) => " " + e);
178
+ }, s = n.map((e) => [e.labels.map((e) => t.expr(e)).join(", "), a(e.list)]), c = a(o ?? []);
179
+ t.line(`switch (${r}) {`);
180
+ for (let [e, n] of s) t.line(` case ${e}: {`), v(t, n), t.line(" }");
181
+ t.line(" default: {"), v(t, c), t.line(" }"), t.line("}");
182
+ }), "Switch");
183
+ let s = {
184
+ Case(e, o) {
185
+ let l = [e].flat();
186
+ l.length || c("Case needs at least one value");
187
+ for (let e of l) r.has(e) && c(`Switch has two cases for ${e}`), r.add(e);
188
+ let u = f(o);
189
+ return n.push({
190
+ labels: l.map((e) => a(e, t)),
191
+ list: u
192
+ }), i.push(...u), s;
193
+ },
194
+ Default(e) {
195
+ o && c("Switch has two Default bodies"), o = f(e), i.push(...o);
196
+ }
197
+ };
198
+ return s;
199
+ }
200
+ //#endregion
201
+ export { D as a, b as c, l as d, u as f, S as i, O as l, A as n, j as o, d as p, w as r, x as s, k as t, C as u };
@@ -0,0 +1,93 @@
1
+ import { Node, type Builder, type NodeInput, type Type } from './node.js';
2
+ import { type Write } from './scope.js';
3
+ type Body = () => unknown;
4
+ /** @internal Adds a statement to the body being recorded. */
5
+ export declare function push<T extends Node>(n: T, name: string): T;
6
+ /** @internal A node that writes statements and has no value. */
7
+ export declare const statement: (args: Node[], emit: (b: Builder, n: Node) => void) => Node;
8
+ /** A storage write made in a statement body: it happens here, in order with the statements around it. */
9
+ export declare function write(w: Write): void;
10
+ /**
11
+ * A variable that statements can change: `const sum = Var(vec3(0)); sum.assign(sum.add(c));`. It is a node, so it reads
12
+ * like any other. A node that reads it is worked out where it is used, so it sees the value at that statement;
13
+ * {@link Let} keeps a value as it is now.
14
+ */
15
+ export declare class VarNode<T extends Type = Type> extends Node<T> {
16
+ constructor(type: T);
17
+ /** `this = value`. */
18
+ assign(value: NodeInput<T>): void;
19
+ /** `this += value`; `value` follows the rules of `add`. */
20
+ addAssign(value: NodeInput): void;
21
+ /** `this -= value`. */
22
+ subAssign(value: NodeInput): void;
23
+ /** `this *= value`. */
24
+ mulAssign(value: NodeInput): void;
25
+ /** `this /= value`. */
26
+ divAssign(value: NodeInput): void;
27
+ /** `this[index] = value`: one component of a vector, or one column of a matrix. */
28
+ assignElement(index: NodeInput<'i32' | 'u32'>, value: NodeInput): void;
29
+ }
30
+ /**
31
+ * Declares a variable here, set to `init`. A number is f32 unless `type` says otherwise: `Var(0, 'u32')`.
32
+ * @throws TypeError outside a statement body, or when `init` is not of `type`.
33
+ */
34
+ export declare function Var<T extends Type>(init: Node<T>): VarNode<T>;
35
+ export declare function Var(init: number): VarNode<'f32'>;
36
+ export declare function Var<T extends Type>(init: NodeInput<T> | boolean, type: T): VarNode<T>;
37
+ /** Keeps `value` as it is at this point of the body, whatever is assigned later. Use it in this body or ones inside it. */
38
+ export declare function Let<T extends Type>(value: Node<T>): Node<T>;
39
+ /**
40
+ * A value worked out by statements. The body runs at build time and records them; what it returns is the value:
41
+ * `colorNode: block(() => { const c = Var(vec3(0)); If(a, () => c.assign(b)); return c; })`.
42
+ * @throws TypeError when the body returns no node.
43
+ */
44
+ export declare function block<T extends Type>(body: () => Node<NoInfer<T>> & {
45
+ readonly type: T;
46
+ }): Node<T>;
47
+ /** What `If` returns, to add the other branches. */
48
+ export interface Branch {
49
+ /** Runs `body` when the earlier conditions failed and `condition` holds; its condition is only worked out then. */
50
+ ElseIf(condition: NodeInput<'bool'> | boolean, body: Body): Branch;
51
+ /** Runs `body` when every condition failed. */
52
+ Else(body: Body): void;
53
+ }
54
+ /**
55
+ * Runs `body` only when `condition` holds, unlike `select`, which works out both sides. Chain `.ElseIf()` and `.Else()`.
56
+ * @throws TypeError outside a statement body, or when `condition` is not a bool (a bool vector needs `select`).
57
+ */
58
+ export declare function If(condition: NodeInput<'bool'> | boolean, body: Body): Branch;
59
+ /** The bounds of a {@link Loop}: `i` runs from `from` (default 0) up to but not including `to`, by `step` (default 1). A negative step counts down, stopping before `to`. */
60
+ export interface LoopRange {
61
+ from?: NodeInput<'i32' | 'u32'>;
62
+ to: NodeInput<'i32' | 'u32'>;
63
+ step?: number;
64
+ }
65
+ /**
66
+ * Runs `body` for each `i`, with `Break()` and `Continue()` available: `Loop(64, i => { ...; If(done, () => Break()); })`.
67
+ * Takes a count or a {@link LoopRange}. `loop` is the plain fold; this one is for early exits and for changing several `Var`s.
68
+ * @throws TypeError outside a statement body, or for a step that is not a non-zero integer.
69
+ */
70
+ export declare function Loop(range: NodeInput<'i32' | 'u32'> | LoopRange, body: (i: Node<'i32'>) => unknown): void;
71
+ /**
72
+ * Runs `body` while `condition` holds, tested before each pass, so it must read a `Var` that the body changes:
73
+ * `While(n.greaterThan(1), () => n.assign(n.div(2)))`. A condition that never fails hangs the GPU until the browser resets it.
74
+ * @throws TypeError outside a statement body, or when `condition` is not a bool.
75
+ */
76
+ export declare function While(condition: Node<'bool'>, body: Body): void;
77
+ /** Leaves the innermost `Loop`, `While` or `Switch` (inside a `Case` it ends the Switch, as in C and WGSL). */
78
+ export declare function Break(): void;
79
+ /** Goes on to the next pass of the innermost `Loop` or `While`. */
80
+ export declare function Continue(): void;
81
+ /** What `Switch` returns, to add its cases. */
82
+ export interface Cases {
83
+ /** Runs `body` when the selector equals one of `values` (integers, one or more). There is no fall-through. */
84
+ Case(values: number | readonly number[], body: Body): Cases;
85
+ /** Runs `body` when no case matched. Without it nothing runs. */
86
+ Default(body: Body): void;
87
+ }
88
+ /**
89
+ * Picks one body by an integer: `Switch(mode).Case(0, () => ...).Case([1, 2], () => ...).Default(() => ...)`.
90
+ * @throws TypeError outside a statement body, when `selector` is not i32 or u32, for a repeated case, or for a second Default.
91
+ */
92
+ export declare function Switch(selector: Node<'i32' | 'u32'>): Cases;
93
+ export {};