@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,1500 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { t as e } from "./errors-CsQwshHA.js";
5
+ import { r as t, t as n } from "./view-rect-Bm1ac-TK.js";
6
+ import { t as r } from "./clock-BLGNexlt.js";
7
+ import { t as i } from "./display-BrJM_Qkd.js";
8
+ import { parseColor as a } from "@margoengine/math/color";
9
+ import { MargoError as o } from "@margoengine/math/errors";
10
+ import { meshWorldMatrix as s } from "@margoengine/math/mesh";
11
+ //#region ../shared/pick-base.js
12
+ function c(e, t) {
13
+ let n = e.encoder.beginRenderPass({
14
+ colorAttachments: [{
15
+ view: e.color,
16
+ loadOp: "load",
17
+ storeOp: "store"
18
+ }],
19
+ depthStencilAttachment: {
20
+ view: e.depth,
21
+ depthLoadOp: "load",
22
+ depthStoreOp: "store"
23
+ }
24
+ });
25
+ return n.setBindGroup(0, t), n;
26
+ }
27
+ //#endregion
28
+ //#region ../shared/view.js
29
+ function l(e, t) {
30
+ let n = t.position, r = t.up ?? [
31
+ 0,
32
+ 1,
33
+ 0
34
+ ], i = n[0] - t.target[0], a = n[1] - t.target[1], o = n[2] - t.target[2], s = Math.abs(i), c = Math.abs(a), l = Math.abs(o), u = s > c ? s : c, d = u > l ? u : l, f;
35
+ if (s === Infinity || c === Infinity || l === Infinity) f = Infinity;
36
+ else if (s !== s || c !== c || l !== l) f = s + c + l;
37
+ else if (d === 0) f = 0;
38
+ else {
39
+ let e = s / d * (s / d), t = c / d * (c / d), n = e + t - e - t, r = l / d * (l / d) - n;
40
+ f = Math.sqrt(e + t + r) * d;
41
+ }
42
+ i /= f, a /= f, o /= f;
43
+ let p = r[1] * o - r[2] * a, m = r[2] * i - r[0] * o, h = r[0] * a - r[1] * i, g = Math.abs(p), _ = Math.abs(m), v = Math.abs(h), y = g > _ ? g : _, b = y > v ? y : v, x;
44
+ if (g === Infinity || _ === Infinity || v === Infinity) x = Infinity;
45
+ else if (g !== g || _ !== _ || v !== v) x = g + _ + v;
46
+ else if (b === 0) x = 0;
47
+ else {
48
+ let e = g / b * (g / b), t = _ / b * (_ / b), n = e + t - e - t, r = v / b * (v / b) - n;
49
+ x = Math.sqrt(e + t + r) * b;
50
+ }
51
+ if (!f || !x) throw RangeError("Invalid camera view; pass distinct eye and target and another up vector");
52
+ p /= x, m /= x, h /= x;
53
+ let S = a * h - o * m, C = o * p - i * h, w = i * m - a * p;
54
+ return e[0] = p, e[1] = S, e[2] = i, e[3] = 0, e[4] = m, e[5] = C, e[6] = a, e[7] = 0, e[8] = h, e[9] = w, e[10] = o, e[11] = 0, e[12] = -p * n[0] - m * n[1] - h * n[2], e[13] = -S * n[0] - C * n[1] - w * n[2], e[14] = -i * n[0] - a * n[1] - o * n[2], e[15] = 1, e;
55
+ }
56
+ //#endregion
57
+ //#region ../shared/borrowed.js
58
+ function u(e, t, n) {
59
+ return e.value = t, e.device = typeof t == "function" ? void 0 : n, e.made = void 0, e.told = !1, e;
60
+ }
61
+ function d(e, t) {
62
+ typeof e.value != "function" && (e.device ??= t);
63
+ }
64
+ var f = (e, t, n, r) => u({
65
+ name: t,
66
+ setter: n
67
+ }, e, r);
68
+ function p(t, n, r) {
69
+ let { value: i } = t;
70
+ if (typeof i == "function") return t.device !== n && (t.made = i(t.device = n)), t.made;
71
+ if (i != null) {
72
+ if (t.device ??= n, t.device === n) return i;
73
+ t.told || (t.told = !0, r?.onError(e("state", `${t.name} lost with the device; pass a function or call ${t.setter}`, "borrowed-lost")));
74
+ }
75
+ }
76
+ function m(e) {
77
+ if (!e || typeof e != "object") return !1;
78
+ let t = Object.getPrototypeOf(e);
79
+ return t === null || Object.getPrototypeOf(t) === null;
80
+ }
81
+ //#endregion
82
+ //#region ../shared/pass.js
83
+ var h = /* @__PURE__ */ Object.freeze({
84
+ color: {
85
+ srcFactor: "src-alpha",
86
+ dstFactor: "one-minus-src-alpha",
87
+ operation: "add"
88
+ },
89
+ alpha: {
90
+ srcFactor: "one",
91
+ dstFactor: "one-minus-src-alpha",
92
+ operation: "add"
93
+ }
94
+ }), g = /^(f32|i32|u32|vec[234][fiu])$/, _ = (e) => e === "mat3x3f" ? 9 : e === "mat4x4f" ? 16 : +(/^vec(\d)/.exec(e)?.[1] ?? 1), v = (e) => e === "i32" || e.endsWith("i") ? "i" : e === "u32" || e.endsWith("u") ? "u" : "f", y = (e) => e.startsWith("mat") ? 16 : [
95
+ 4,
96
+ 8,
97
+ 16,
98
+ 16
99
+ ][_(e) - 1], b = (e) => e === "mat3x3f" ? 48 : _(e) * 4, x = (e) => {
100
+ let t = _(e);
101
+ return `${{
102
+ f: "float",
103
+ i: "sint",
104
+ u: "uint"
105
+ }[v(e)]}32${t > 1 ? "x" + t : ""}`;
106
+ }, S = /^(alias|array|atomic|bitcast|bool|break|case|const|const_assert|continue|continuing|default|diagnostic|discard|else|enable|f16|f32|false|fn|for|i32|if|let|loop|mat\d\w*|override|ptr|requires|return|sampler\w*|struct|switch|texture\w*|true|u32|var|vec\d\w*|while|module|target|type|self|this|camera|mesh|uniforms|Attributes|Uniforms|margo\w*|Margo\w*)$/;
107
+ function C(e, t) {
108
+ if (!/^[A-Za-z]\w*$/.test(e) || S.test(e)) throw TypeError(`${t} name ${JSON.stringify(e)} is not a usable WGSL identifier; use letters, digits and _, not a WGSL keyword or a prelude name (camera, mesh, uniforms, margo*)`);
109
+ return e;
110
+ }
111
+ var w = (e, t, n = []) => {
112
+ for (let r of e.matchAll(RegExp(`@${t}\\s+fn\\s+([A-Za-z_]\\w*)`, "g"))) if (!n.includes(r[1])) return r[1];
113
+ }, T = (e) => g.test(e) || e === "mat3x3f" || e === "mat4x4f", E = (e, t) => Math.ceil(e / t) * t, D = `${i.replace("pbrNeutral", "margoNeutral")}fn margoSRGB(x:vec3f)->vec3f {return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>=vec3f(0.0031308));}
114
+ fn margoDisplay(c:vec4f)->vec4f {if(camera.encoding==0.0){return c;}let x=margoNeutral(max(c.rgb,vec3f(0)));if(camera.encoding==2.0){return vec4f(x,c.a);}return vec4f(margoSRGB(x),c.a);}
115
+ fn margoEncode(c:vec4f)->vec4f {if(camera.encoding!=1.0){return c;}return vec4f(margoSRGB(max(c.rgb,vec3f(0))),c.a);}
116
+ struct MargoCamera { view:mat4x4f, projection:mat4x4f, viewProjection:mat4x4f, position:vec3f, time:f32, resolution:vec2f, deltaTime:f32, encoding:f32, viewport:vec4f }
117
+ struct MargoMesh { world:mat4x4f, normal:mat3x3f, pickId:u32 }
118
+ @group(0) @binding(0) var<uniform> camera:MargoCamera;
119
+ @group(0) @binding(1) var<uniform> mesh:MargoMesh;
120
+ struct MargoGBuffer { @location(0) normal:vec4f, @location(1) ambient:vec4f }
121
+ fn margoGBuffer(normal:vec3f,position:vec3f,ambient:vec3f)->MargoGBuffer {return MargoGBuffer(vec4f(normalize((camera.view*vec4f(normal,0)).xyz),-(camera.view*vec4f(position,1)).z),vec4f(ambient,1));}`, O = "struct MargoMaterial { position:vec3f, normal:vec3f, view:vec3f, base:vec3f, metal:f32, rough:f32, ambient:vec3f }", k = "\nstruct MargoCapture { @location(0) unused:vec4f }\nfn margoCapture(m:MargoMaterial)->MargoCapture {return MargoCapture(vec4f(0));}", A = /* @__PURE__ */ new Map(), j = 0, M = (e) => {
122
+ let t = A.get(e);
123
+ return t === void 0 && (A.size >= 64 && A.clear(), A.set(e, t = ++j)), t;
124
+ }, ee = "struct MargoBefore { viewProjection:mat4x4f, world:mat4x4f, time:f32, valid:f32, relativeCurrent:mat4x4f, relativePrevious:mat4x4f, origin:vec4f }\n@group(0) @binding(2) var<uniform> margoBefore:MargoBefore;\nstruct MargoVelocity { @builtin(position) @invariant clip:vec4f, @location(0) previous:vec4f, @location(1) current:vec4f }\nfn margoVelocity(position:vec3f,before:vec3f)->MargoVelocity {return MargoVelocity(camera.viewProjection*mesh.world*vec4f(position,1),margoBefore.relativePrevious*vec4f((margoBefore.world*vec4f(before,1)).xyz-margoBefore.origin.xyz,1),margoBefore.relativeCurrent*vec4f((mesh.world*vec4f(position,1)).xyz-margoBefore.origin.xyz,1));}\n", te = "\nstruct MargoMotion { @location(0) velocity:vec4f, @location(1) depth:f32 }\n@fragment fn margoVelocityFragment(i:MargoVelocity)->MargoMotion {var o:MargoMotion;o.velocity=vec4f(0,0,0,1);o.depth=-1;\n if(i.previous.w>0&&margoBefore.valid>0){let margoDepth=i.previous.z/i.previous.w;let margoNow=select(i.clip.xy/camera.resolution,i.current.xy/i.current.w*vec2f(0.5,-0.5)+0.5,i.current.w>0);o.velocity=vec4f(margoNow-(i.previous.xy/i.previous.w*vec2f(0.5,-0.5)+0.5),select(0.0,log2(margoDepth),margoDepth>0),1);o.depth=margoDepth;}return o;}\n", ne = "@fragment fn margoPick()->@location(0) u32 {return mesh.pickId;}\n", re = 112, ie = 128;
125
+ function ae(e, t, n) {
126
+ if (!t || typeof t != "object") throw TypeError(`${e} struct must be an object of field types`);
127
+ let r = [], i = 0;
128
+ for (let [a, o] of Object.entries(t)) {
129
+ C(a, `${e} field`);
130
+ let t = `${e} field ${a}`;
131
+ if (typeof o == "string" || !o || typeof o != "object") {
132
+ if (!T(o)) throw TypeError(`${t} needs a type from 'f32' to 'vec4f', their i32/u32 variants, 'mat3x3f' or 'mat4x4f', or {struct} or {type, count}`);
133
+ let e = E(i, y(o));
134
+ r.push({
135
+ name: a,
136
+ type: o,
137
+ offset: e
138
+ }), i = e + b(o);
139
+ continue;
140
+ }
141
+ let { count: s } = o;
142
+ if (s !== void 0 && (!Number.isInteger(s) || s < 1)) throw RangeError(`${t} count must be a positive integer`);
143
+ let c = E(i, 16);
144
+ if (o.struct) {
145
+ let e = ae(t, o.struct, n), l = `Raw${n.length}_${a}`;
146
+ n.push({
147
+ type: l,
148
+ fields: e.fields
149
+ }), r.push({
150
+ name: a,
151
+ type: l,
152
+ offset: c,
153
+ count: s,
154
+ stride: e.size,
155
+ fields: e.fields
156
+ }), i = c + e.size * (s ?? 1);
157
+ continue;
158
+ }
159
+ let l = o.type;
160
+ if (s === void 0 || !l || !T(l)) throw TypeError(`${t} needs {struct} for a nested struct, or {type, count} with type 'f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f' for an array`);
161
+ let u = E(b(l), y(l));
162
+ if (u % 16) throw TypeError(`${t}: elements of a uniform array sit 16 bytes apart, so ${l} does not fit; use vec3, vec4, a matrix or a struct, or put it in a storage buffer`);
163
+ r.push({
164
+ name: a,
165
+ type: l,
166
+ offset: c,
167
+ count: s,
168
+ stride: u
169
+ }), i = c + u * s;
170
+ }
171
+ if (!r.length) throw TypeError(`${e} struct needs at least one field`);
172
+ return {
173
+ fields: r,
174
+ size: E(i, 16)
175
+ };
176
+ }
177
+ var oe = /* @__PURE__ */ new WeakMap(), se = /* @__PURE__ */ new WeakMap(), N = /* @__PURE__ */ new WeakMap(), P = /* @__PURE__ */ new WeakMap(), F = /* @__PURE__ */ new WeakMap(), I = /* @__PURE__ */ new WeakMap(), L = /* @__PURE__ */ new WeakMap(), R = /* @__PURE__ */ new WeakMap(), z = () => GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT;
178
+ function B(e, t = !1) {
179
+ let n = t ? se : oe, r = n.get(e);
180
+ return r || (r = e.createBindGroupLayout({
181
+ label: t ? "shader:raw:velocity" : "shader:raw:frame",
182
+ entries: (t ? [
183
+ 0,
184
+ 1,
185
+ 2
186
+ ] : [0, 1]).map((e) => ({
187
+ binding: e,
188
+ visibility: z(),
189
+ buffer: { type: "uniform" }
190
+ }))
191
+ }), n.set(e, r)), r;
192
+ }
193
+ function V(e, t = {}) {
194
+ let n = N.get(e);
195
+ n || N.set(e, n = /* @__PURE__ */ new Map());
196
+ let r = {
197
+ magFilter: "linear",
198
+ minFilter: "linear",
199
+ ...t
200
+ }, i = JSON.stringify(r), a = n.get(i);
201
+ return a || n.set(i, a = e.createSampler(r)), a;
202
+ }
203
+ function H(e, t) {
204
+ let n = R.get(e);
205
+ n || R.set(e, n = /* @__PURE__ */ new Map());
206
+ let r = t.dimension ?? "2d", i = t.sampleType ?? "float", a = r + i, o = n.get(a);
207
+ if (!o) {
208
+ let t = r === "cube" ? 6 : 1, s = i === "sint" || i === "uint", c = i === "depth", l = e.createTexture({
209
+ label: "shader:raw:white",
210
+ size: [
211
+ 1,
212
+ 1,
213
+ t
214
+ ],
215
+ dimension: r === "3d" ? "3d" : "2d",
216
+ format: c ? "depth32float" : s ? i === "sint" ? "rgba8sint" : "rgba8uint" : "rgba8unorm",
217
+ usage: GPUTextureUsage.TEXTURE_BINDING | (c ? GPUTextureUsage.RENDER_ATTACHMENT : GPUTextureUsage.COPY_DST)
218
+ });
219
+ if (c) {
220
+ let n = e.createCommandEncoder();
221
+ for (let e = 0; e < t; e++) n.beginRenderPass({
222
+ colorAttachments: [],
223
+ depthStencilAttachment: {
224
+ view: l.createView({
225
+ dimension: "2d",
226
+ baseArrayLayer: e,
227
+ arrayLayerCount: 1
228
+ }),
229
+ depthClearValue: 1,
230
+ depthLoadOp: "clear",
231
+ depthStoreOp: "store"
232
+ }
233
+ }).end();
234
+ e.queue.submit([n.finish()]);
235
+ } else s || e.queue.writeTexture({ texture: l }, new Uint8Array(4 * t).fill(255), {
236
+ bytesPerRow: 4,
237
+ rowsPerImage: 1
238
+ }, [
239
+ 1,
240
+ 1,
241
+ t
242
+ ]);
243
+ n.set(a, o = l.createView({ dimension: r }));
244
+ }
245
+ return o;
246
+ }
247
+ function ce(e, t, n) {
248
+ if (typeof t.buffer == "function") return t.buffer(e);
249
+ let r = I.get(t.buffer);
250
+ r || I.set(t.buffer, r = f(t.buffer, "RawShaderMaterial storage buffer", "assign a new buffer", e));
251
+ let i = p(r, e, n);
252
+ if (i) return i;
253
+ let a = L.get(e);
254
+ return a || L.set(e, a = e.createBuffer({
255
+ label: "shader:raw:storage-stand-in",
256
+ size: 256,
257
+ usage: GPUBufferUsage.STORAGE
258
+ })), a;
259
+ }
260
+ function le(e, t, n) {
261
+ let r = t.sampleType ?? "float", i = r === "float", a = (n) => r === "depth" ? V(e, {
262
+ compare: "less-equal",
263
+ ...t.sampler
264
+ }) : i ? t.sampler || !n ? V(e, t.sampler) : n : V(e, {
265
+ ...t.sampler,
266
+ magFilter: "nearest",
267
+ minFilter: "nearest",
268
+ mipmapFilter: "nearest"
269
+ }), o = t.texture;
270
+ if (o && typeof o != "function" && typeof o.bind == "function") {
271
+ let n = o.bind(e, !0);
272
+ return n ? [n[0], a(n[1])] : [H(e, t), a()];
273
+ }
274
+ if (!o) return [H(e, t), a()];
275
+ let s = F.get(o);
276
+ if (s || F.set(o, s = f(o, "RawShaderMaterial texture", "assign a new texture", e)), o = p(s, e, n) ?? null, !o) return [H(e, t), a()];
277
+ let c = o;
278
+ if (typeof o.createView == "function") {
279
+ let e = o, n = t.dimension ?? "2d", r = P.get(e);
280
+ r || P.set(e, r = /* @__PURE__ */ new Map()), c = r.get(n) ?? e.createView({ dimension: n }), r.set(n, c);
281
+ }
282
+ return [c, a()];
283
+ }
284
+ var U = {
285
+ normal: h,
286
+ additive: {
287
+ color: {
288
+ srcFactor: "src-alpha",
289
+ dstFactor: "one",
290
+ operation: "add"
291
+ },
292
+ alpha: {
293
+ srcFactor: "one",
294
+ dstFactor: "one",
295
+ operation: "add"
296
+ }
297
+ },
298
+ subtractive: {
299
+ color: {
300
+ srcFactor: "src-alpha",
301
+ dstFactor: "one",
302
+ operation: "reverse-subtract"
303
+ },
304
+ alpha: {
305
+ srcFactor: "zero",
306
+ dstFactor: "one",
307
+ operation: "add"
308
+ }
309
+ },
310
+ multiply: {
311
+ color: {
312
+ srcFactor: "zero",
313
+ dstFactor: "src",
314
+ operation: "add"
315
+ },
316
+ alpha: {
317
+ srcFactor: "zero",
318
+ dstFactor: "src-alpha",
319
+ operation: "add"
320
+ }
321
+ },
322
+ premultiplied: {
323
+ color: {
324
+ srcFactor: "one",
325
+ dstFactor: "one-minus-src-alpha",
326
+ operation: "add"
327
+ },
328
+ alpha: {
329
+ srcFactor: "one",
330
+ dstFactor: "one-minus-src-alpha",
331
+ operation: "add"
332
+ }
333
+ }
334
+ }, ue = 0, W = class {
335
+ constructor(e) {
336
+ if (this.gpu = /* @__PURE__ */ new Map(), this.revision = 0, this.compiled = 0, this.uniformChanges = 0, this.vertexCode = "", this.vertexName = "", this.fragmentName = "", !e || typeof e != "object") throw TypeError("RawShaderMaterial needs {vertexShader, ...}");
337
+ if (this.name = e.name ?? "raw:" + ue++, this.entries = {
338
+ vertex: e.vertexEntry,
339
+ fragment: e.fragmentEntry
340
+ }, this.transparent = e.transparent ?? !1, this.blending = e.blending ?? "normal", this.depthTest = e.depthTest ?? !0, this.depthCompare = e.depthCompare ?? "greater-equal", this.depthBias = e.depthBias ?? 0, this.depthBiasSlopeScale = e.depthBiasSlopeScale ?? 0, this.alphaToCoverage = e.alphaToCoverage ?? !1, this.depthWrite = e.depthWrite ?? !0, this.cull = e.cull ?? "back", this.colorWrite = e.colorWrite ?? !0, this.wireframe = e.wireframe ?? !1, this.gbufferName = e.gbufferEntry, this.captureName = e.captureEntry, this.velocityName = e.velocityEntry, this.groups = e.groups ?? [], this.groups.length > 2 || this.groups.some((e) => typeof e != "function")) throw TypeError("RawShaderMaterial groups must be at most two functions of the device, for @group(2) and @group(3)");
341
+ this.setCode(e.vertexShader, e.fragmentShader);
342
+ let t = [], n = [], r = 0, i = {};
343
+ this.uniforms = i;
344
+ for (let [a, o] of Object.entries(e.uniforms ?? {})) {
345
+ if (C(a, "RawShaderMaterial uniform"), !o || typeof o != "object" || !("value" in o)) throw TypeError(`RawShaderMaterial uniform ${a} must be {value, type?}`);
346
+ let { count: e } = o;
347
+ if (e !== void 0 && (!Number.isInteger(e) || e < 1)) throw RangeError(`RawShaderMaterial uniform ${a} count must be a positive integer`);
348
+ if (o.struct) {
349
+ let { fields: s, size: c } = ae(`RawShaderMaterial uniform ${a}`, o.struct, n), l = E(r, 16);
350
+ n.push({
351
+ type: "Raw_" + a,
352
+ fields: s
353
+ }), t.push({
354
+ name: a,
355
+ type: "Raw_" + a,
356
+ offset: l,
357
+ count: e,
358
+ stride: c,
359
+ fields: s
360
+ }), r = l + c * (e ?? 1), i[a] = o;
361
+ continue;
362
+ }
363
+ if (e !== void 0) {
364
+ let n = o.type;
365
+ if (!n || !T(n)) throw TypeError(`RawShaderMaterial uniform ${a} is an array, so it needs type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
366
+ let s = E(b(n), y(n));
367
+ if (s % 16) throw TypeError(`RawShaderMaterial uniform ${a}: elements of a uniform array sit 16 bytes apart, so ${n} does not fit; use vec3, vec4, a matrix or a struct, or put it in a storage buffer`);
368
+ let c = E(r, 16);
369
+ t.push({
370
+ name: a,
371
+ type: n,
372
+ offset: c,
373
+ count: e,
374
+ stride: s
375
+ }), r = c + s * e, i[a] = o;
376
+ continue;
377
+ }
378
+ let s = o.value, c = typeof s == "number" ? 1 : typeof s == "string" ? 3 : s?.length, l = o.type ?? {
379
+ 1: "f32",
380
+ 2: "vec2f",
381
+ 3: "vec3f",
382
+ 4: "vec4f",
383
+ 9: "mat3x3f",
384
+ 16: "mat4x4f"
385
+ }[c];
386
+ if (!l || !T(l)) throw TypeError(`RawShaderMaterial uniform ${a} has no WGSL type; give type ('f32' to 'vec4f', i32/u32 variants, 'mat3x3f' or 'mat4x4f')`);
387
+ let u = Math.ceil(r / y(l)) * y(l);
388
+ t.push({
389
+ name: a,
390
+ type: l,
391
+ offset: u
392
+ }), r = u + b(l), i[a] = o.type ? o : Object.assign(o, { type: l });
393
+ }
394
+ this.members = t, this.structs = n, this.size = t.length ? Math.ceil(r / 16) * 16 : 0, this.bytes = new Uint8Array(this.size), this.data = new DataView(this.bytes.buffer), this.textures = {};
395
+ for (let [t, n] of Object.entries(e.textures ?? {})) {
396
+ C(t, "RawShaderMaterial texture");
397
+ let e = m(n) && "texture" in n ? n : { texture: n };
398
+ if (e.dimension !== void 0 && ![
399
+ "2d",
400
+ "2d-array",
401
+ "cube",
402
+ "3d"
403
+ ].includes(e.dimension)) throw TypeError(`RawShaderMaterial texture ${t} dimension must be 2d, 2d-array, cube or 3d`);
404
+ if (e.dimension && e.dimension !== "2d" && typeof e.texture?.bind == "function") throw TypeError(`RawShaderMaterial texture ${t}: a materials Texture is 2d; pass a GPUTexture for ${e.dimension}`);
405
+ if (e.sampleType !== void 0 && ![
406
+ "float",
407
+ "unfilterable-float",
408
+ "sint",
409
+ "uint",
410
+ "depth"
411
+ ].includes(e.sampleType)) throw TypeError(`RawShaderMaterial texture ${t} sampleType must be float, unfilterable-float, sint, uint or depth`);
412
+ if (e.sampleType === "depth" && e.dimension === "3d") throw TypeError(`RawShaderMaterial texture ${t}: depth textures are 2d, 2d-array or cube; use one of those dimensions`);
413
+ this.textures[t] = e;
414
+ }
415
+ this.storage = {};
416
+ for (let [t, n] of Object.entries(e.storage ?? {})) {
417
+ if (C(t, "RawShaderMaterial storage"), !n || typeof n != "object" || !n.buffer || typeof n.type != "string" || !n.type) throw TypeError(`RawShaderMaterial storage ${t} must be {buffer, type, access?} or a storage() node`);
418
+ if (n.access !== void 0 && n.access !== "read" && n.access !== "read_write") throw TypeError(`RawShaderMaterial storage ${t} access must be read or read_write`);
419
+ this.storage[t] = n;
420
+ }
421
+ }
422
+ get vertexShader() {
423
+ return this.vertexCode;
424
+ }
425
+ set vertexShader(e) {
426
+ this.setCode(e, this.fragmentCode);
427
+ }
428
+ get fragmentShader() {
429
+ return this.fragmentCode;
430
+ }
431
+ set fragmentShader(e) {
432
+ this.setCode(this.vertexCode, e);
433
+ }
434
+ setCode(e, t) {
435
+ if (typeof e != "string" || !e.trim()) throw TypeError("RawShaderMaterial vertexShader must be WGSL source with a @vertex fn");
436
+ if (t !== void 0 && typeof t != "string") throw TypeError("RawShaderMaterial fragmentShader must be WGSL source or undefined");
437
+ let n = this.entries.vertex ?? w(e, "vertex"), r = this.entries.fragment ?? w(t ?? e, "fragment", [this.gbufferName, this.captureName]);
438
+ if (!n) throw TypeError(`RawShaderMaterial ${this.name} has no @vertex fn; add one or pass vertexEntry`);
439
+ if (!r) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn; add one to fragmentShader (or vertexShader) or pass fragmentEntry`);
440
+ if (this.gbufferName && !RegExp(`@fragment\\s+fn\\s+${this.gbufferName}\\b`).test(t ?? e)) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn ${this.gbufferName}; add it beside the colour fragment or drop gbufferEntry`);
441
+ if (this.captureName && !RegExp(`@fragment\\s+fn\\s+${this.captureName}\\b`).test(t ?? e)) throw TypeError(`RawShaderMaterial ${this.name} has no @fragment fn ${this.captureName}; add it beside the colour fragment or drop captureEntry`);
442
+ if (this.velocityName && !RegExp(`@vertex\\s+fn\\s+${this.velocityName}\\b`).test(e)) throw TypeError(`RawShaderMaterial ${this.name} has no @vertex fn ${this.velocityName}; add it to vertexShader or drop velocityEntry`);
443
+ this.vertexCode = e, this.fragmentCode = t, this.vertexName = n, this.fragmentName = r, this.error = void 0, this.revision++;
444
+ for (let e of this.gpu.values()) e.modules.clear(), e.pipelines.clear();
445
+ }
446
+ prelude(e, t = !1) {
447
+ let n = [D], r = e?.layout ?? [];
448
+ r.length && n.push(`struct Attributes {\n${r.map((e, t) => ` @location(${t}) ${e.name}:${e.type},`).join("\n")}\n}`);
449
+ for (let e of this.structs) n.push(`struct ${e.type} {\n${e.fields.map((e, t) => ` ${t ? "" : "@align(16) "}${e.name}:${e.count === void 0 ? e.type : `array<${e.type},${e.count}>`},`).join("\n")}\n}`);
450
+ this.velocityName && n.push(ee), (this.captureName || /\bmargoCapture\s*\(/.test(this.fragmentCode ?? this.vertexCode)) && n.push(t ? O : O + k), this.members.length && n.push(`struct Uniforms {\n${this.members.map((e) => ` ${e.name}:${e.count === void 0 ? e.type : `array<${e.type},${e.count}>`},`).join("\n")}\n}\n@group(1) @binding(0) var<uniform> uniforms:Uniforms;`), Object.entries(this.textures).forEach(([e, t], r) => {
451
+ let i = {
452
+ float: "f32",
453
+ "unfilterable-float": "f32",
454
+ sint: "i32",
455
+ uint: "u32",
456
+ depth: ""
457
+ }[t.sampleType ?? "float"], a = (t.dimension ?? "2d").replace("-", "_");
458
+ n.push(`@group(1) @binding(${1 + 2 * r}) var ${e}:texture_${i ? a + "<" + i + ">" : "depth_" + a};\n@group(1) @binding(${2 + 2 * r}) var ${e}Sampler:sampler${i ? "" : "_comparison"};`);
459
+ });
460
+ let i = 1 + 2 * Object.keys(this.textures).length;
461
+ return Object.entries(this.storage).forEach(([e, t], r) => n.push(`@group(1) @binding(${i + r}) var<storage,${t.access ?? "read"}> ${e}:array<${t.type}>;`)), n.join("\n") + "\n";
462
+ }
463
+ code(e, t) {
464
+ return this.prelude(t) + (e === "fragment" ? this.fragmentCode ?? this.vertexCode : this.vertexCode);
465
+ }
466
+ dispose() {
467
+ for (let e of this.gpu.values()) e.buffer?.destroy();
468
+ this.gpu.clear();
469
+ }
470
+ [Symbol.dispose ?? Symbol()]() {
471
+ this.dispose();
472
+ }
473
+ state() {
474
+ let e = this.blending;
475
+ return `${this.transparent}|${typeof e == "string" ? e : JSON.stringify(e)}|${this.depthTest}|${this.depthCompare}|${this.depthBias}|${this.depthBiasSlopeScale}|${this.alphaToCoverage}|${this.depthWrite}|${this.cull}|${this.colorWrite}|${this.revision}`;
476
+ }
477
+ blend() {
478
+ let e = this.blending;
479
+ if (typeof e != "string") return e;
480
+ if (!(e in U) && e !== "none") throw TypeError(`RawShaderMaterial ${this.name} blending must be none, normal, additive, subtractive, multiply, premultiplied or a GPUBlendState`);
481
+ return e === "normal" && !this.transparent ? void 0 : U[e];
482
+ }
483
+ prepare(e, t, n) {
484
+ n && (this.drawnBy = n);
485
+ let r = this.gpu.get(e);
486
+ if (!r) {
487
+ let t = Object.values(this.textures), n = [];
488
+ this.size && n.push({
489
+ binding: 0,
490
+ visibility: z(),
491
+ buffer: { type: "uniform" }
492
+ }), t.forEach((e, t) => {
493
+ let r = e.sampleType ?? "float";
494
+ n.push({
495
+ binding: 1 + 2 * t,
496
+ visibility: z(),
497
+ texture: {
498
+ sampleType: r,
499
+ viewDimension: e.dimension ?? "2d"
500
+ }
501
+ }, {
502
+ binding: 2 + 2 * t,
503
+ visibility: z(),
504
+ sampler: { type: r === "float" ? "filtering" : r === "depth" ? "comparison" : "non-filtering" }
505
+ });
506
+ }), Object.values(this.storage).forEach((e, r) => {
507
+ let i = (e.access ?? "read") === "read";
508
+ n.push({
509
+ binding: 1 + 2 * t.length + r,
510
+ visibility: i ? z() : GPUShaderStage.FRAGMENT,
511
+ buffer: { type: i ? "read-only-storage" : "storage" }
512
+ });
513
+ });
514
+ let i = this.groups.map((t) => t(e)), a = n.length || i.length ? e.createBindGroupLayout({
515
+ label: "shader:raw:" + this.name,
516
+ entries: n
517
+ }) : void 0, o = a ? [a, ...i.map((e) => e.layout)] : [];
518
+ r = {
519
+ layout: a,
520
+ groupLayouts: o,
521
+ pipelineLayout: e.createPipelineLayout({ bindGroupLayouts: [B(e), ...o] }),
522
+ bound: [],
523
+ extras: i.map((e) => e.group),
524
+ modules: /* @__PURE__ */ new Map(),
525
+ pipelines: /* @__PURE__ */ new Map()
526
+ }, this.gpu.set(e, r);
527
+ }
528
+ if (r.pass === t) return r;
529
+ if (r.pass = t, this.size) {
530
+ for (let e of this.members) this.write(e);
531
+ r.buffer || (r.buffer = e.createBuffer({
532
+ label: "shader:raw:uniforms",
533
+ size: this.size,
534
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
535
+ })), (!r.written || r.written.some((e, t) => e !== this.bytes[t])) && (e.queue.writeBuffer(r.buffer, 0, this.bytes), (r.written ??= new Uint8Array(this.size)).set(this.bytes));
536
+ }
537
+ if (r.layout) {
538
+ let t = this.size ? [r.buffer] : [], i = Object.values(this.textures), a = n?.engine;
539
+ for (let n of i) t.push(...le(e, n, a));
540
+ let o = Object.values(this.storage);
541
+ for (let n of o) t.push(ce(e, n, a));
542
+ if (!r.group || t.some((e, t) => e !== r.bound[t])) {
543
+ r.bound = t;
544
+ let n = [], a = 0;
545
+ this.size && n.push({
546
+ binding: 0,
547
+ resource: { buffer: t[a++] }
548
+ });
549
+ for (let e = 0; e < i.length; e++) n.push({
550
+ binding: 1 + 2 * e,
551
+ resource: t[a++]
552
+ }, {
553
+ binding: 2 + 2 * e,
554
+ resource: t[a++]
555
+ });
556
+ for (let e = 0; e < o.length; e++) n.push({
557
+ binding: 1 + 2 * i.length + e,
558
+ resource: { buffer: t[a++] }
559
+ });
560
+ r.group = e.createBindGroup({
561
+ layout: r.layout,
562
+ entries: n
563
+ });
564
+ }
565
+ }
566
+ return r;
567
+ }
568
+ uniformVersion() {
569
+ if (!this.size) return 0;
570
+ for (let e of this.members) this.write(e);
571
+ let e = this.uniformSeen;
572
+ return (!e || e.some((e, t) => e !== this.bytes[t])) && ((this.uniformSeen ??= new Uint8Array(this.size)).set(this.bytes), e && this.uniformChanges++), this.uniformChanges;
573
+ }
574
+ write(e) {
575
+ this.store(e, e.offset, this.uniforms[e.name]?.value, e.name);
576
+ }
577
+ store(e, t, n, r) {
578
+ if (e.count === void 0 && !e.fields) return this.put(e.type, t, n, r);
579
+ if (e.count === void 0) return this.fields(e, t, n, r);
580
+ let i = _(e.type), a = n, o = !e.fields && typeof a?.[0] == "number";
581
+ if ((o ? a.length / i : a?.length) !== e.count) throw RangeError(`RawShaderMaterial ${this.name} uniform ${r} needs ${e.count} element${e.count > 1 ? "s" : ""}; assign a matching value`);
582
+ for (let n = 0; n < e.count; n++) {
583
+ let s = o ? Array.prototype.slice.call(a, n * i, (n + 1) * i) : a[n], c = t + n * e.stride;
584
+ e.fields ? this.fields(e, c, s, `${r}[${n}]`) : this.put(e.type, c, s, `${r}[${n}]`);
585
+ }
586
+ }
587
+ fields(e, t, n, r) {
588
+ for (let i of e.fields) this.store(i, t + i.offset, n?.[i.name], `${r}.${i.name}`);
589
+ }
590
+ put(e, t, n, r) {
591
+ let i = _(e), o = typeof n == "number" && i === 1 ? [n] : (typeof n == "string" || typeof n == "number") && e === "vec3f" ? Array.from(a(n)) : typeof n == "object" && n ? Array.from(n) : [];
592
+ if (o.length !== i || o.some((e) => !Number.isFinite(e))) throw RangeError(`RawShaderMaterial ${this.name} uniform ${r} needs ${i} finite number${i > 1 ? "s" : ""} for ${e}; assign a matching value`);
593
+ let s = v(e), c = e === "mat3x3f" ? 3 : 0;
594
+ o.forEach((e, n) => {
595
+ let r = t + (c ? Math.floor(n / 3) * 16 + n % 3 * 4 : n * 4);
596
+ s === "f" ? this.data.setFloat32(r, e, !0) : s === "i" ? this.data.setInt32(r, e, !0) : this.data.setUint32(r, e, !0);
597
+ });
598
+ }
599
+ get writesGBuffer() {
600
+ return !!this.gbufferName;
601
+ }
602
+ captureCode(e, t) {
603
+ let n = this.prelude(e, !0) + (this.fragmentCode ?? this.vertexCode), r = t.declarations(n);
604
+ if (!/fn\s+margoCapture\s*\(\s*\w+\s*:\s*MargoMaterial\s*\)/.test(r)) throw new o("unsupported", `RawShaderMaterial ${this.name}: this effect's capture takes no MargoMaterial; add raw meshes with captureEntry to SSR, SSGI, SceneTargets or LightBounce`);
605
+ return this.prelude(e, !0) + r + "\n" + (this.fragmentCode ?? this.vertexCode);
606
+ }
607
+ target(e, t, n, r = "rg16float", i) {
608
+ let a = t?.descriptor.depthStencil?.format;
609
+ if (e === "shadow") return {
610
+ entry: /\bdiscard\b/.test(this.fragmentCode ?? this.vertexCode) ? this.fragmentName : void 0,
611
+ targets: [],
612
+ depthStencil: {
613
+ format: "depth32float",
614
+ depthWriteEnabled: !0,
615
+ depthCompare: n
616
+ }
617
+ };
618
+ if (e === "pick") return {
619
+ entry: "margoPick",
620
+ targets: [{ format: "r32uint" }],
621
+ depthStencil: {
622
+ format: "depth32float",
623
+ depthWriteEnabled: !0,
624
+ depthCompare: this.depthTest ? this.depthCompare : "always",
625
+ ...this.bias()
626
+ }
627
+ };
628
+ if (e === "velocity") return {
629
+ entry: "margoVelocityFragment",
630
+ targets: [{ format: r }, { format: "r32float" }],
631
+ depthStencil: {
632
+ format: a,
633
+ depthWriteEnabled: !1,
634
+ depthCompare: "equal"
635
+ }
636
+ };
637
+ if (e === "captureDepth") return {
638
+ entry: this.fragmentName,
639
+ targets: (i?.targets ?? []).map((e) => ({
640
+ format: e.format,
641
+ writeMask: 0
642
+ })),
643
+ depthStencil: {
644
+ format: a,
645
+ depthWriteEnabled: !0,
646
+ depthCompare: "greater-equal"
647
+ }
648
+ };
649
+ if (e === "capture") return {
650
+ entry: this.captureName,
651
+ targets: [...i?.targets ?? []],
652
+ depthStencil: {
653
+ format: a,
654
+ depthWriteEnabled: !0,
655
+ depthCompare: "greater-equal"
656
+ }
657
+ };
658
+ if (e === "gbuffer") return {
659
+ entry: this.gbufferName,
660
+ targets: [{ format: "rgba16float" }, { format: "rgba16float" }],
661
+ depthStencil: {
662
+ format: a,
663
+ depthWriteEnabled: !1,
664
+ depthCompare: n
665
+ }
666
+ };
667
+ let o = this.blend();
668
+ return {
669
+ entry: this.fragmentName,
670
+ targets: [{
671
+ format: t.format,
672
+ ...o ? { blend: o } : {},
673
+ writeMask: this.colorWrite ? 15 : 0
674
+ }],
675
+ depthStencil: a && {
676
+ format: a,
677
+ depthWriteEnabled: this.depthWrite,
678
+ depthCompare: this.depthTest ? this.depthCompare : "always",
679
+ ...this.bias()
680
+ }
681
+ };
682
+ }
683
+ bias() {
684
+ return this.depthBias || this.depthBiasSlopeScale ? {
685
+ depthBias: this.depthBias,
686
+ depthBiasSlopeScale: this.depthBiasSlopeScale
687
+ } : {};
688
+ }
689
+ pipeline(e, t, n, r, i, a, s = "equal", c = "rg16float", l) {
690
+ let u = i === "capture" && l ? this.captureCode(r, l) : void 0, d = (u === void 0 ? "" : M(u)) + (l ? "|" + l.targets.map((e) => e.format).join(",") : ""), f = r.drawTopology, p = f.endsWith("strip") && r.indexFormat, m = a?.descriptor.multisample?.count ?? 1, h = a?.descriptor.depthStencil?.format, g = `${i}|${r.layoutKey}|${f}|${p || ""}|${a?.format}|${m}|${h}|${s}|${c}|${d}|${this.state()}`, _ = t.pipelines.get(g);
691
+ if (_) return _.pipeline;
692
+ _ = { state: "pending" }, t.pipelines.set(g, _);
693
+ let v = (e) => {
694
+ let i = e + "|" + r.layoutKey + (e === "capture" ? "|" + M(u) : ""), a = t.modules.get(i);
695
+ if (!a) {
696
+ let o = e === "pick" ? this.prelude(r) + ne : e === "velocity" ? this.code("vertex", r) + te : e === "capture" ? u : this.code(e, r);
697
+ a = n.createShaderModule({
698
+ label: `shader:raw:${this.name}:${e}`,
699
+ code: o
700
+ }), t.modules.set(i, a), G.set(a, a.getCompilationInfo?.().catch(() => void 0) ?? Promise.resolve(void 0));
701
+ }
702
+ return a;
703
+ };
704
+ n.pushErrorScope?.("validation");
705
+ let { entry: y, targets: b, depthStencil: x } = this.target(i, a, s, c, l), S = i === "velocity", C = v(S ? "velocity" : "vertex"), w = i === "pick" ? v("pick") : i === "capture" ? v("capture") : S || this.fragmentCode === void 0 ? C : v("fragment"), T = n.popErrorScope?.(), E = {
706
+ label: "shader:raw:" + this.name,
707
+ layout: S ? t.velocityLayout ??= n.createPipelineLayout({ bindGroupLayouts: [B(n, !0), ...t.groupLayouts] }) : t.pipelineLayout,
708
+ vertex: {
709
+ module: C,
710
+ entryPoint: S ? this.velocityName : this.vertexName,
711
+ buffers: r.buffers()
712
+ },
713
+ ...y ? { fragment: {
714
+ module: w,
715
+ entryPoint: y,
716
+ targets: b
717
+ } } : {},
718
+ primitive: {
719
+ topology: f,
720
+ cullMode: i === "shadow" || S ? "none" : this.cull,
721
+ ...p ? { stripIndexFormat: p } : {}
722
+ },
723
+ ...x && { depthStencil: f.startsWith("triangle") ? x : {
724
+ ...x,
725
+ depthBias: 0,
726
+ depthBiasSlopeScale: 0
727
+ } },
728
+ multisample: {
729
+ count: m,
730
+ ...i === "color" && m > 1 && this.alphaToCoverage ? { alphaToCoverageEnabled: !0 } : {}
731
+ }
732
+ }, D = _;
733
+ if (typeof n.createRenderPipelineAsync != "function" || a && !h || i === "capture" || i === "captureDepth") return D.pipeline = n.createRenderPipeline(E), D.state = "ready", this.compiled++, D.pipeline;
734
+ let O = (u === void 0 ? this.prelude(r) : u.slice(0, u.length - (this.fragmentCode ?? this.vertexCode).length)).split("\n").length - 1, k = this.revision, A = async (e) => {
735
+ if (D.state = "failed", k !== this.revision) return;
736
+ let t = e?.message ?? String(e);
737
+ for (let [e, n] of [["vertex", C], ["fragment", w]]) {
738
+ let r = (await G.get(n))?.messages.find((e) => e.type === "error");
739
+ if (r) {
740
+ let n = r.lineNum - O;
741
+ t = `${e}Shader ${n > 0 ? `line ${n}:${r.linePos}` : `prelude line ${r.lineNum}`}: ${r.message}`;
742
+ break;
743
+ }
744
+ }
745
+ let n = new o("failed", `RawShaderMaterial ${this.name} did not compile (${t}); fix the WGSL and assign vertexShader/fragmentShader again`);
746
+ this.error = n, this.onError ? this.onError(n) : console.error(n);
747
+ }, j = Promise.all([T, n.createRenderPipelineAsync(E)]).then(([e, t]) => {
748
+ if (e) return A(e);
749
+ D.pipeline = t, D.state = "ready", this.compiled++;
750
+ }).catch(A);
751
+ e.track(j);
752
+ }
753
+ }, G = /* @__PURE__ */ new WeakMap(), K = /* @__PURE__ */ new WeakMap();
754
+ function q(e, t, n, r) {
755
+ let i = e.createBuffer({
756
+ label: n,
757
+ size: r.byteLength,
758
+ usage: t
759
+ });
760
+ return e.queue.writeBuffer(i, 0, r), i;
761
+ }
762
+ function J(e, t, n, r) {
763
+ let i = K.get(e);
764
+ i || K.set(e, i = /* @__PURE__ */ new Map());
765
+ let a = 2166136261;
766
+ for (let e = 0; e < r.length; e++) a = Math.imul(a ^ r[e], 16777619);
767
+ let o = `${t}:${r.length}:${a}`, s = i.get(o);
768
+ s || i.set(o, s = []);
769
+ for (let e of s) {
770
+ let t = e.words, n = 0;
771
+ for (; n < r.length && t[n] === r[n];) n++;
772
+ if (n === r.length) return e.users++, e;
773
+ }
774
+ let c = {
775
+ buffer: q(e, t, n, r),
776
+ users: 1,
777
+ usage: t,
778
+ label: n,
779
+ key: o,
780
+ words: r.slice()
781
+ };
782
+ return s.push(c), c;
783
+ }
784
+ function Y(e, t) {
785
+ if (t.key === void 0) return;
786
+ let n = K.get(e), r = n.get(t.key);
787
+ r.splice(r.indexOf(t), 1), r.length || n.delete(t.key), t.key = t.words = void 0;
788
+ }
789
+ function X(e, t) {
790
+ !t || --t.users || (Y(e, t), t.buffer.destroy());
791
+ }
792
+ function Z(e, t, n) {
793
+ if (t.users === 1) return Y(e, t), t.fresh = !1, t;
794
+ t.users--;
795
+ let { usage: r, label: i } = t;
796
+ return {
797
+ buffer: q(e, r, i, n),
798
+ users: 1,
799
+ usage: r,
800
+ label: i,
801
+ fresh: !0
802
+ };
803
+ }
804
+ var de = class {
805
+ constructor(e) {
806
+ this.step = e, this.attributes = [], this.stride = 0, this.count = 0, this.capacity = 0, this.words = /* @__PURE__ */ new Uint32Array(), this.floats = /* @__PURE__ */ new Float32Array(), this.ints = /* @__PURE__ */ new Int32Array(), this.start = Infinity, this.end = 0, this.full = !0;
807
+ }
808
+ rebuild() {
809
+ let e = 0;
810
+ for (let t of this.attributes) t.offset = e, e += t.size;
811
+ this.stride = e * 4, this.count = this.attributes.length ? Math.min(...this.attributes.map((e) => e.count)) : 0, this.capacity = this.attributes.length ? Math.max(...this.attributes.map((e) => e.count)) : 0;
812
+ let t = new ArrayBuffer(Math.max(4, this.capacity * this.stride));
813
+ this.words = new Uint32Array(t), this.floats = new Float32Array(t), this.ints = new Int32Array(t);
814
+ for (let e of this.attributes) this.pack(e, 0, e.count);
815
+ this.full = !0;
816
+ }
817
+ pack(e, t, n) {
818
+ let r = e.data instanceof Float32Array ? this.floats : e.data instanceof Int32Array ? this.ints : this.words, i = this.stride / 4;
819
+ for (let a = t; a < n; a++) for (let t = 0; t < e.size; t++) r[a * i + e.offset + t] = e.data[a * e.size + t];
820
+ this.start = Math.min(this.start, t), this.end = Math.max(this.end, n);
821
+ }
822
+ upload(e, t) {
823
+ if (!this.attributes.length) {
824
+ X(e, t);
825
+ return;
826
+ }
827
+ let n = Math.max(4, this.capacity * this.stride);
828
+ return !t || this.full || t.buffer.size < n ? (X(e, t), t = J(e, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST, "shader:raw:" + this.step, this.words)) : this.end > this.start && (t = Z(e, t, this.words), t.fresh || e.queue.writeBuffer(t.buffer, this.start * this.stride, this.words.buffer, this.start * this.stride, (this.end - this.start) * this.stride)), this.full = !1, this.start = Infinity, this.end = 0, t;
829
+ }
830
+ }, fe = [
831
+ 1,
832
+ 0,
833
+ 0,
834
+ 0,
835
+ 0,
836
+ 1,
837
+ 0,
838
+ 0,
839
+ 0,
840
+ 0,
841
+ 1,
842
+ 0,
843
+ 0,
844
+ 0,
845
+ 0,
846
+ 1
847
+ ], pe = class {
848
+ constructor(e) {
849
+ if (this.drawRange = {
850
+ start: 0,
851
+ count: Infinity
852
+ }, this.streams = {
853
+ vertex: new de("vertex"),
854
+ instance: new de("instance")
855
+ }, this.map = /* @__PURE__ */ new Map(), this.indices = null, this.indexDirty = !0, this.key = "", this.disposed = !1, this.changes = 0, this.world = /* @__PURE__ */ new Float32Array(16), this.object = /* @__PURE__ */ new Float32Array(28), !(e?.material instanceof W)) throw TypeError("RawMesh needs {material: new RawShaderMaterial(...)}");
856
+ if (this.material = e.material, this.matrix = Float32Array.from(e.matrix ?? fe), this.matrix.length !== 16) throw RangeError("RawMesh matrix needs 16 numbers (column-major)");
857
+ this.mesh = e.mesh ?? null, this.visible = e.visible ?? !0, this.renderOrder = e.renderOrder ?? 0, this.instanceCount = e.instanceCount, this.vertexCount = e.vertexCount, this.topology = e.topology ?? "triangle-list", this.frustumCulled = e.frustumCulled ?? !0, this.bounds = e.bounds ?? null;
858
+ for (let [t, n] of Object.entries(e.attributes ?? {})) this.define(t, n);
859
+ this.restructure(), e.index && this.setIndex(e.index);
860
+ }
861
+ get drawTopology() {
862
+ return this.material.wireframe && this.topology.startsWith("triangle") ? "line-list" : this.topology;
863
+ }
864
+ edges(e) {
865
+ let t = this.indices, n = this.wire;
866
+ if (n && n[0] === t && n[1] === e && n[2] === this.topology && !this.indexDirty) return n[3];
867
+ let r = t ? t.length : e, i = (e) => t ? t[e] : e, a = t instanceof Uint16Array ? 65535 : 4294967295, o = this.topology === "triangle-strip", s = /* @__PURE__ */ new Set(), c = [], l = (e, t) => {
868
+ let n = e < t ? `${e},${t}` : `${t},${e}`;
869
+ e !== t && !s.has(n) && (s.add(n), c.push(e, t));
870
+ };
871
+ for (let e = 0; e + 2 < r; e += o ? 1 : 3) {
872
+ let t = i(e), n = i(e + 1), r = i(e + 2);
873
+ (!o || t !== a && n !== a && r !== a) && (l(t, n), l(n, r), l(r, t));
874
+ }
875
+ let u = Uint32Array.from(c);
876
+ return this.wire = [
877
+ t,
878
+ e,
879
+ this.topology,
880
+ u
881
+ ], u;
882
+ }
883
+ get layout() {
884
+ return [...this.map.values()];
885
+ }
886
+ get layoutKey() {
887
+ return this.key;
888
+ }
889
+ get indexFormat() {
890
+ return this.indices ? this.indices instanceof Uint16Array ? "uint16" : "uint32" : void 0;
891
+ }
892
+ getAttribute(e) {
893
+ let t = this.map.get(e);
894
+ return t && {
895
+ data: t.data,
896
+ type: t.type,
897
+ step: t.step
898
+ };
899
+ }
900
+ setAttribute(e, t, n) {
901
+ this.alive(), this.changed();
902
+ let r = this.map.get(e);
903
+ if (me(t)) {
904
+ if (!r || r.type !== t.type || r.step !== (t.step ?? "vertex")) return r && this.streams[r.step].attributes.splice(this.streams[r.step].attributes.indexOf(r), 1), this.define(e, t), this.restructure(), this;
905
+ t = t.data;
906
+ }
907
+ if (!r) throw TypeError(`RawMesh has no attribute ${e}; pass {data, type, step?} to add one`);
908
+ let i = Q(t, r.type, e), a = i.length / r.size, o = this.streams[r.step];
909
+ if (n) {
910
+ let [t, s] = n;
911
+ if (!Number.isInteger(t) || !Number.isInteger(s) || t < 0 || s < 0 || t + s > a || a !== r.count) throw RangeError(`RawMesh ${e} range [${t}, ${s}] must lie inside ${r.count} elements, with data of the same length`);
912
+ return r.data = i, o.pack(r, t, t + s), this;
913
+ }
914
+ return r.data = i, a === r.count ? o.pack(r, 0, a) : (r.count = a, o.rebuild()), this;
915
+ }
916
+ removeAttribute(e) {
917
+ let t = this.map.get(e);
918
+ return t && (this.map.delete(e), this.streams[t.step].attributes.splice(this.streams[t.step].attributes.indexOf(t), 1), this.restructure(), this.changed()), this;
919
+ }
920
+ setIndex(e) {
921
+ if (this.alive(), this.changes++, e === null) this.indices = null;
922
+ else if (e instanceof Uint16Array || e instanceof Uint32Array) this.indices = e;
923
+ else {
924
+ let t = Array.from(e);
925
+ if (t.some((e) => !Number.isInteger(e) || e < 0 || e > 4294967295)) throw RangeError("RawMesh indices must be integers from 0 to 2^32 - 1");
926
+ this.indices = Uint32Array.from(t);
927
+ }
928
+ return this.indexDirty = !0, this;
929
+ }
930
+ get shadowVersion() {
931
+ let e = this.owner?.engine, t = e && this.worldMatrix(e), n = this.seenWorld;
932
+ return this.material !== this.seenMaterial && (this.seenMaterial && this.changes++, this.seenMaterial = this.material), t && (!n || n.some((e, n) => e !== t[n])) && (n && this.changes++, (this.seenWorld ??= /* @__PURE__ */ new Float32Array(16)).set(t)), this.changes + this.material.compiled + this.material.uniformVersion();
933
+ }
934
+ invalidateShadow() {
935
+ this.changes++;
936
+ }
937
+ drawShadow(e) {
938
+ this.owner?.shadow(this, e);
939
+ }
940
+ drawLocalShadow(e) {
941
+ this.owner?.localShadow(this, e);
942
+ }
943
+ dispose() {
944
+ this.release(), this.owner?.remove(this), this.disposed = !0;
945
+ }
946
+ [Symbol.dispose ?? Symbol()]() {
947
+ this.dispose();
948
+ }
949
+ alive() {
950
+ if (this.disposed) throw new o("disposed", "RawMesh is disposed; create a new RawMesh");
951
+ }
952
+ changed() {
953
+ this.changes++, this.sphere = void 0;
954
+ }
955
+ ownBounds() {
956
+ let e = this.map.get("position");
957
+ if (!e || e.type !== "vec3f" || e.step !== "vertex" || !e.count || this.streams.instance.attributes.length || (this.instanceCount ?? 1) > 1) return null;
958
+ let t = [
959
+ Infinity,
960
+ Infinity,
961
+ Infinity
962
+ ], n = [
963
+ -Infinity,
964
+ -Infinity,
965
+ -Infinity
966
+ ], r = e.data;
967
+ for (let e = 0; e < r.length; e += 3) for (let i = 0; i < 3; i++) t[i] = Math.min(t[i], r[e + i]), n[i] = Math.max(n[i], r[e + i]);
968
+ let i = t.map((e, t) => (e + n[t]) / 2), a = 0;
969
+ for (let e = 0; e < r.length; e += 3) a = Math.max(a, Math.hypot(r[e] - i[0], r[e + 1] - i[1], r[e + 2] - i[2]));
970
+ return [
971
+ i[0],
972
+ i[1],
973
+ i[2],
974
+ a
975
+ ];
976
+ }
977
+ culled(e, t) {
978
+ if (!this.frustumCulled) return !1;
979
+ let n = this.bounds;
980
+ !n && this.sphere === void 0 && (this.sphere = this.ownBounds());
981
+ let r = n ? [...n.center, n.radius] : this.sphere;
982
+ if (!r) return !1;
983
+ let i = e[0] * r[0] + e[4] * r[1] + e[8] * r[2] + e[12], a = e[1] * r[0] + e[5] * r[1] + e[9] * r[2] + e[13], o = e[2] * r[0] + e[6] * r[1] + e[10] * r[2] + e[14], s = r[3] * Math.max(Math.hypot(e[0], e[1], e[2]), Math.hypot(e[4], e[5], e[6]), Math.hypot(e[8], e[9], e[10]));
984
+ for (let e = 0; e < 6; e++) {
985
+ let n = e >> 1, r = e % 2 == 0 ? 1 : -1, c = e === 4, l = c ? t[2] : t[3] + r * t[n], u = c ? t[6] : t[7] + r * t[4 + n], d = c ? t[10] : t[11] + r * t[8 + n], f = c ? t[14] : t[15] + r * t[12 + n];
986
+ if (l * i + u * a + d * o + f < -s * Math.hypot(l, u, d)) return !0;
987
+ }
988
+ return !1;
989
+ }
990
+ define(e, t) {
991
+ if (C(e, "RawMesh attribute"), !me(t) || !g.test(t.type)) throw TypeError(`RawMesh attribute ${e} needs {data, type} with type f32, vec2f-vec4f or their i32/u32 variants`);
992
+ let n = t.step ?? "vertex";
993
+ if (n !== "vertex" && n !== "instance") throw TypeError(`RawMesh attribute ${e} step must be vertex or instance`);
994
+ if (!this.map.has(e) && this.map.size >= 16) throw RangeError("RawMesh supports at most 16 attributes (the WebGPU vertex attribute limit); remove an attribute or pack them together.");
995
+ let r = Q(t.data, t.type, e), i = _(t.type), a = {
996
+ name: e,
997
+ type: t.type,
998
+ step: n,
999
+ size: i,
1000
+ data: r,
1001
+ count: r.length / i,
1002
+ offset: 0
1003
+ };
1004
+ this.map.set(e, a), this.streams[n].attributes.push(a);
1005
+ }
1006
+ restructure() {
1007
+ for (let e of Object.values(this.streams)) e.attributes = [...this.map.values()].filter((t) => t.step === e.step);
1008
+ this.streams.vertex.rebuild(), this.streams.instance.rebuild(), this.sphere = void 0, this.key = [...this.map.values()].map((e) => `${e.name}:${e.type}:${e.step[0]}`).join(",");
1009
+ }
1010
+ buffers() {
1011
+ let e = [...this.map.values()];
1012
+ return Object.values(this.streams).filter((e) => e.attributes.length).map((t) => ({
1013
+ arrayStride: t.stride,
1014
+ stepMode: t.step,
1015
+ attributes: t.attributes.map((t) => ({
1016
+ shaderLocation: e.indexOf(t),
1017
+ offset: t.offset * 4,
1018
+ format: x(t.type)
1019
+ }))
1020
+ }));
1021
+ }
1022
+ release() {
1023
+ let e = this.gpu;
1024
+ if (e) {
1025
+ e.object.destroy();
1026
+ for (let t of [
1027
+ e.vertex,
1028
+ e.instance,
1029
+ e.index
1030
+ ]) X(e.device, t);
1031
+ this.gpu = void 0, this.streams.vertex.full = this.streams.instance.full = this.indexDirty = !0;
1032
+ }
1033
+ }
1034
+ worldMatrix(e) {
1035
+ if (!this.mesh) return this.matrix;
1036
+ let t = s(e, this.mesh);
1037
+ if (!t) return null;
1038
+ let n = this.world, r = this.matrix;
1039
+ for (let e = 0; e < 4; e++) for (let i = 0; i < 4; i++) n[e * 4 + i] = t[i] * r[e * 4] + t[4 + i] * r[e * 4 + 1] + t[8 + i] * r[e * 4 + 2] + t[12 + i] * r[e * 4 + 3];
1040
+ return n;
1041
+ }
1042
+ upload(e, t, n) {
1043
+ let r = this.gpu;
1044
+ r && r.device !== e && (this.release(), r = void 0), r ||= this.gpu = {
1045
+ device: e,
1046
+ object: e.createBuffer({
1047
+ label: "shader:raw:mesh",
1048
+ size: ie,
1049
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1050
+ }),
1051
+ groups: /* @__PURE__ */ new Map()
1052
+ };
1053
+ let i = r.written, a = !!i;
1054
+ for (let e = 0; a && e < 16; e++) a = Object.is(i[e], n[e]);
1055
+ if (!a) {
1056
+ let t = this.object;
1057
+ t.set(n);
1058
+ let a = n[0], o = n[1], s = n[2], c = n[4], l = n[5], u = n[6], d = n[8], f = n[9], p = n[10], m = l * p - u * f, h = u * d - c * p, g = c * f - l * d, _ = a * m + o * h + s * g, v = _ ? 1 / _ : 0;
1059
+ t[16] = m * v, t[17] = h * v, t[18] = g * v, t[20] = (f * s - p * o) * v, t[21] = (p * a - d * s) * v, t[22] = (d * o - f * a) * v, t[24] = (o * u - s * l) * v, t[25] = (s * c - a * u) * v, t[26] = (a * l - o * c) * v, (!i || i.some((e, n) => !Object.is(e, t[n]))) && (e.queue.writeBuffer(r.object, 0, t), (r.written ??= /* @__PURE__ */ new Float32Array(28)).set(t));
1060
+ }
1061
+ r.group = r.groups.get(t), r.group || (r.group = e.createBindGroup({
1062
+ layout: B(e),
1063
+ entries: [{
1064
+ binding: 0,
1065
+ resource: { buffer: t }
1066
+ }, {
1067
+ binding: 1,
1068
+ resource: { buffer: r.object }
1069
+ }]
1070
+ }), r.groups.set(t, r.group)), r.vertex = this.streams.vertex.upload(e, r.vertex), r.instance = this.streams.instance.upload(e, r.instance);
1071
+ let o = this.drawTopology !== this.topology, s = this.streams.vertex.attributes.length ? Math.min(this.streams.vertex.count, this.vertexCount ?? Infinity) : this.vertexCount ?? 0, c = o ? this.edges(s) : this.indices;
1072
+ if (r.wire !== o && (r.wire = o, this.indexDirty = !0), !c) X(e, r.index), r.index = void 0;
1073
+ else if (this.indexDirty || !r.index) {
1074
+ let t = Math.ceil(c.byteLength / 4) * 4 || 4, n = new Uint8Array(t);
1075
+ n.set(new Uint8Array(c.buffer, c.byteOffset, c.byteLength));
1076
+ let i = new Uint32Array(n.buffer);
1077
+ r.index?.users === 1 && r.index.buffer.size >= t ? (r.index = Z(e, r.index, i), e.queue.writeBuffer(r.index.buffer, 0, n)) : (X(e, r.index), r.index = J(e, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST, "shader:raw:index", i));
1078
+ }
1079
+ this.indexDirty = !1;
1080
+ let l = this.streams.vertex, u = this.streams.instance, d = c ? c.length : l.attributes.length ? Math.min(l.count, this.vertexCount ?? Infinity) : this.vertexCount ?? 0, f = u.attributes.length ? Math.min(u.count, this.instanceCount ?? Infinity) : this.instanceCount ?? 1, p = Math.min(Math.max(0, Math.floor(this.drawRange.start) || 0), d), m = Math.min(Math.max(0, Math.floor(this.drawRange.count)), d - p);
1081
+ return m > 0 && f > 0 ? [
1082
+ p,
1083
+ m,
1084
+ Math.floor(f)
1085
+ ] : void 0;
1086
+ }
1087
+ draw(e, t, n, r, i) {
1088
+ let a = this.gpu, o = a.vertex?.buffer, s = a.instance?.buffer, c = a.index?.buffer, l = 0;
1089
+ if (o && (i.slots[0] !== o && e.setVertexBuffer(0, i.slots[0] = o), l = 1), s && i.slots[l] !== s && e.setVertexBuffer(l, i.slots[l] = s), c) {
1090
+ let o = a.wire ? "uint32" : this.indexFormat;
1091
+ (i.index !== c || i.format !== o) && e.setIndexBuffer(i.index = c, i.format = o), e.drawIndexed(n, r, t);
1092
+ } else e.draw(n, r, t);
1093
+ }
1094
+ }, me = (e) => !!e && typeof e == "object" && "data" in e && typeof e.type == "string";
1095
+ function Q(e, t, n) {
1096
+ let r = _(t), i = v(t);
1097
+ if (!e || typeof e.length != "number" || e.length % r) throw RangeError(`RawMesh attribute ${n} needs a multiple of ${r} numbers for ${t}`);
1098
+ let a = i === "f" ? Float32Array : i === "i" ? Int32Array : Uint32Array;
1099
+ return e instanceof a ? e : a.from(e);
1100
+ }
1101
+ function $(e, t) {
1102
+ let n, r, i = { slots: [] };
1103
+ for (let a of t) {
1104
+ let t = a.gpu.group;
1105
+ a.pipeline !== n && e.setPipeline(n = a.pipeline), e.setBindGroup(0, a.mesh.gpu.group), t && t !== r && (e.setBindGroup(1, r = t), a.gpu.extras.forEach((t, n) => e.setBindGroup(2 + n, t))), a.mesh.draw(e, a.call[0], a.call[1], a.call[2], i);
1106
+ }
1107
+ }
1108
+ var he = class e {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
1109
+ get pass() {
1110
+ return this.passes;
1111
+ }
1112
+ get kernel() {
1113
+ return this.engine;
1114
+ }
1115
+ static attach(t, n) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
1116
+ let r = new e(n);
1117
+ return t.use(r), r;
1118
+ }
1119
+ constructor(e = {}) {
1120
+ if (this.stats = {
1121
+ meshes: 0,
1122
+ drawCalls: 0,
1123
+ culled: 0,
1124
+ pending: 0
1125
+ }, this.watchers = /* @__PURE__ */ new Set(), this.meshes = /* @__PURE__ */ new Set(), this.jobs = /* @__PURE__ */ new Set(), this.shadowCameras = [], this.shadowPass = 0, this.shadowWritten = [], this.localCameras = [], this.localWritten = [], this.localSlots = /* @__PURE__ */ new Map(), this.passes = 0, this.cameraData = /* @__PURE__ */ new Float32Array(60), this.view = /* @__PURE__ */ new Float64Array(16), this.inverse = /* @__PURE__ */ new Float64Array(16), this.velocityStates = /* @__PURE__ */ new Map(), this.beforeData = /* @__PURE__ */ new Float32Array(72), this.captureCameras = [], this.captureSlots = /* @__PURE__ */ new Map(), this.disposers = /* @__PURE__ */ new Set(), this.name = e.name ?? "shader:raw", this.opaqueOrder = e.opaqueOrder ?? .5, this.transparentOrder = e.transparentOrder ?? 7, !this.name || typeof this.name != "string") throw TypeError("RawShaders name must be a non-empty string");
1126
+ if (!Number.isFinite(this.opaqueOrder) || !Number.isFinite(this.transparentOrder)) throw RangeError("RawShaders opaqueOrder and transparentOrder must be finite numbers");
1127
+ }
1128
+ add(e) {
1129
+ if (!(e instanceof pe)) throw TypeError("RawShaders.add needs a RawMesh");
1130
+ if (e.owner && e.owner !== this) throw new o("attached", "RawMesh already belongs to another RawShaders; remove it there first");
1131
+ e.alive(), e.owner = this, this.meshes.add(e);
1132
+ for (let t of this.watchers) t.added(e);
1133
+ return e;
1134
+ }
1135
+ remove(e) {
1136
+ if (!this.meshes.delete(e)) return !1;
1137
+ for (let t of this.velocityStates.values()) t.meshes.get(e)?.before.destroy(), t.meshes.delete(e);
1138
+ e.release(), e.owner = void 0;
1139
+ for (let t of this.watchers) t.removed(e);
1140
+ return !0;
1141
+ }
1142
+ async ready() {
1143
+ for (; this.jobs.size;) await Promise.allSettled([...this.jobs]);
1144
+ }
1145
+ track(e) {
1146
+ let t = () => {
1147
+ this.jobs.delete(e);
1148
+ };
1149
+ this.jobs.add(e), e.then(t, t);
1150
+ }
1151
+ setup(e) {
1152
+ if (this.engine && this.engine !== e) throw new o("attached", `${this.name} is attached to another engine; create a new RawShaders`);
1153
+ if (!e.gpu) throw new o("unsupported", "RawShaders requires WebGPU; see https://margoengine.com/errors#webgpu");
1154
+ this.engine = e, this.device = e.gpu ?? void 0, r.hold(e, this);
1155
+ }
1156
+ registerPasses(e) {
1157
+ e.add({
1158
+ name: this.name + ":opaque",
1159
+ order: this.opaqueOrder,
1160
+ execute: (e) => this.execute(e, !1)
1161
+ }), e.add({
1162
+ name: this.name + ":transparent",
1163
+ order: this.transparentOrder,
1164
+ execute: (e) => this.execute(e, !0)
1165
+ });
1166
+ }
1167
+ onDeviceRestored(e) {
1168
+ this.release(), this.device = e.gpu ?? void 0;
1169
+ }
1170
+ setCapture(e) {
1171
+ if (!e || typeof e.declarations != "function" || typeof e.begin != "function" || !Array.isArray(e.targets)) throw TypeError("Invalid RawShaders capture hook; pass an object with declarations() and begin() functions and a targets array");
1172
+ return this.capture = e, () => {
1173
+ this.capture === e && (this.capture = void 0);
1174
+ };
1175
+ }
1176
+ onDispose(e) {
1177
+ if (typeof e != "function") throw TypeError("RawShaders onDispose needs a function");
1178
+ return this.disposers.add(e), () => this.disposers.delete(e);
1179
+ }
1180
+ dispose() {
1181
+ let e = this.engine;
1182
+ for (let e of [...this.disposers]) e();
1183
+ this.disposers.clear(), this.release(), this.engine = this.device = void 0, r.release(e, this), e?.sceneOf(this)?.removePlugin(this.name);
1184
+ }
1185
+ [Symbol.dispose ?? Symbol()]() {
1186
+ this.dispose();
1187
+ }
1188
+ release() {
1189
+ let e = this.device;
1190
+ for (let t of this.meshes) t.release(), (e && t.material.gpu.get(e))?.buffer?.destroy(), e && t.material.gpu.delete(e);
1191
+ this.camera?.destroy(), this.camera = void 0;
1192
+ for (let e of [...this.velocityStates.keys()]) this.releaseVelocity(e);
1193
+ for (let e of [
1194
+ ...this.shadowCameras,
1195
+ ...this.localCameras,
1196
+ ...this.captureCameras
1197
+ ]) e?.destroy();
1198
+ this.captureCameras.length = 0, this.captureEncoder = void 0, this.captureSlots.clear(), this.shadowCameras.length = this.shadowWritten.length = 0, this.localCameras.length = this.localWritten.length = 0, this.localEncoder = void 0, this.localSlots.clear(), this.shadowEncoder = void 0;
1199
+ }
1200
+ cameraBuffer(e) {
1201
+ return e.createBuffer({
1202
+ label: "shader:raw:camera",
1203
+ size: 240,
1204
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1205
+ });
1206
+ }
1207
+ writeCamera(e) {
1208
+ let n = e.device;
1209
+ this.camera ??= this.cameraBuffer(n);
1210
+ let r = e.format.includes("float") ? 0 : e.format.endsWith("-srgb") ? 2 : 1;
1211
+ return n.queue.writeBuffer(this.camera, 0, this.cameraBlock(e.camera, e.camera.matrix, e.width, e.height, e.delta, r, t(e))), this.camera;
1212
+ }
1213
+ cameraBlock(e, t, n, i, a, o, s) {
1214
+ let c = this.cameraData, u = l(this.view, e), d = this.inverse;
1215
+ for (let e = 0; e < 3; e++) {
1216
+ for (let t = 0; t < 3; t++) d[t * 4 + e] = u[e * 4 + t];
1217
+ d[12 + e] = -(u[e * 4] * u[12] + u[e * 4 + 1] * u[13] + u[e * 4 + 2] * u[14]), d[e * 4 + 3] = 0;
1218
+ }
1219
+ d[15] = 1, c.set(u, 0);
1220
+ for (let e = 0; e < 4; e++) for (let n = 0; n < 4; n++) c[16 + e * 4 + n] = t[n] * d[e * 4] + t[4 + n] * d[e * 4 + 1] + t[8 + n] * d[e * 4 + 2] + t[12 + n] * d[e * 4 + 3];
1221
+ return c.set(t, 32), c.set(e.position, 48), c[51] = r.find(this.engine)?.time ?? 0, c[52] = n, c[53] = i, c[54] = a, c[55] = o, s ? c.set(s, 56) : c.set([
1222
+ 0,
1223
+ 0,
1224
+ n,
1225
+ i
1226
+ ], 56), c;
1227
+ }
1228
+ nextPass() {
1229
+ return ++this.passes;
1230
+ }
1231
+ shadow(e, { context: t, pass: n, matrix: r, cascade: i }) {
1232
+ this.depthCaster(e, t, n, r, i, this.shadowCameras, this.shadowWritten, "less-equal");
1233
+ }
1234
+ localShadow(e, { context: t, pass: n, matrix: r, depthCompare: i = "greater" }) {
1235
+ if (i !== "greater" && i !== "less-equal") throw RangeError("Invalid local shadow depthCompare; pass 'greater' or 'less-equal'");
1236
+ this.localEncoder !== t.encoder && (this.localEncoder = t.encoder, this.localSlots.clear());
1237
+ let a = this.localSlots.get(n);
1238
+ a === void 0 && this.localSlots.set(n, a = this.localSlots.size), this.depthCaster(e, t, n, r, a, this.localCameras, this.localWritten, i);
1239
+ }
1240
+ depthCaster(e, t, n, r, i, a, o, s) {
1241
+ let c = this.device, l = this.engine, u = e.material;
1242
+ if (!c || !l || t.device !== c || !e.visible || u.transparent) return;
1243
+ let d = e.worldMatrix(l);
1244
+ if (!d || e.culled(d, r)) return;
1245
+ this.shadowEncoder !== t.encoder && (this.shadowEncoder = t.encoder, this.shadowPass = this.nextPass());
1246
+ let f = a[i] ??= this.cameraBuffer(c);
1247
+ if (o[i] !== t.encoder) {
1248
+ o[i] = t.encoder;
1249
+ let e = this.cameraBlock(t.camera, r, t.width, t.height, t.delta, 0);
1250
+ e.set(fe, 0), e.set(r, 16), c.queue.writeBuffer(f, 0, e);
1251
+ }
1252
+ let p = e.upload(c, f, d);
1253
+ if (!p) return;
1254
+ let m = u.prepare(c, this.shadowPass, this), h = u.pipeline(this, m, c, e, "shadow", void 0, s);
1255
+ h && $(n, [{
1256
+ mesh: e,
1257
+ pipeline: h,
1258
+ gpu: m,
1259
+ call: p,
1260
+ distance: 0
1261
+ }]);
1262
+ }
1263
+ draw(e, t, n, r, i, a) {
1264
+ let o = e, s = this.device, c = this.engine;
1265
+ if (t === "capture") return this.drawCapture(o, s, c);
1266
+ if (t !== "occlusion" || !a || o.backend !== "webgpu" || !s || !c || o.device !== s) return;
1267
+ let l = this.nextPass(), u = [], d;
1268
+ for (let e of this.meshes) {
1269
+ let t = e.material;
1270
+ if (!e.visible || t.transparent || !t.writesGBuffer) continue;
1271
+ let n = e.worldMatrix(c);
1272
+ if (!n || e.culled(n, o.camera.matrix)) continue;
1273
+ d ??= this.writeCamera(o);
1274
+ let r = e.upload(s, d, n);
1275
+ if (!r) continue;
1276
+ let i = t.prepare(s, l, this), f = t.pipeline(this, i, s, e, "gbuffer", o, a.depthCompare);
1277
+ f && u.push({
1278
+ mesh: e,
1279
+ pipeline: f,
1280
+ gpu: i,
1281
+ call: r,
1282
+ distance: 0
1283
+ });
1284
+ }
1285
+ $(a.pass, u);
1286
+ }
1287
+ drawCapture(e, t, n) {
1288
+ let r = this.capture;
1289
+ if (!r || e.backend !== "webgpu" || !t || !n || e.device !== t) return;
1290
+ let i = this.nextPass(), a = [], o, s;
1291
+ for (let c of this.meshes) {
1292
+ let l = c.material;
1293
+ if (!c.visible || l.transparent || !l.depthWrite) continue;
1294
+ let u = c.worldMatrix(n);
1295
+ if (!u || c.culled(u, e.camera.matrix)) continue;
1296
+ s ??= r.begin(), o ??= this.captureCamera(e, t, s);
1297
+ let d = c.upload(t, o, u);
1298
+ if (!d) continue;
1299
+ let f = l.captureName ? "capture" : "captureDepth", p = l.prepare(t, i, this), m = l.pipeline(this, p, t, c, f, e, "greater-equal", void 0, r);
1300
+ m && a.push({
1301
+ mesh: c,
1302
+ pipeline: m,
1303
+ gpu: p,
1304
+ call: d,
1305
+ distance: 0
1306
+ });
1307
+ }
1308
+ s && $(s, a);
1309
+ }
1310
+ captureCamera(e, n, r) {
1311
+ this.captureEncoder !== e.encoder && (this.captureEncoder = e.encoder, this.captureSlots.clear());
1312
+ let i = this.captureSlots.get(r), a = i === void 0;
1313
+ i === void 0 && this.captureSlots.set(r, i = this.captureSlots.size);
1314
+ let o = this.captureCameras[i] ??= this.cameraBuffer(n);
1315
+ if (a) {
1316
+ let r = e.format.includes("float") ? 0 : e.format.endsWith("-srgb") ? 2 : 1;
1317
+ n.queue.writeBuffer(o, 0, this.cameraBlock(e.camera, e.camera.matrix, e.width, e.height, e.delta, r, t(e)));
1318
+ }
1319
+ return o;
1320
+ }
1321
+ drawVelocity(e, n) {
1322
+ let r = n.context, i = this.device, a = this.engine, o = n.targets?.[0]?.format;
1323
+ if (r.backend !== "webgpu" || !i || !a || r.device !== i || !this.camera) return;
1324
+ let s = this.velocityStates.get(n.key);
1325
+ s || this.velocityStates.set(n.key, s = {
1326
+ camera: this.cameraBuffer(i),
1327
+ frame: 0,
1328
+ meshes: /* @__PURE__ */ new Map()
1329
+ }), s.frame++;
1330
+ let c = n.camera, l = n.relative, u = c.subarray(0, 16), d = this.nextPass(), f = [], p;
1331
+ for (let e of this.meshes) {
1332
+ let n = e.material;
1333
+ if (!e.visible || n.transparent || !n.velocityName) continue;
1334
+ let m = e.worldMatrix(a);
1335
+ if (!m || e.culled(m, u)) continue;
1336
+ if (p === void 0) {
1337
+ let e = this.cameraBlock(r.camera, u, r.width, r.height, r.delta, 0, t(r));
1338
+ p = e[51], i.queue.writeBuffer(s.camera, 0, e);
1339
+ }
1340
+ let h = e.upload(i, this.camera, m), g = e.gpu?.object;
1341
+ if (!h || !g) continue;
1342
+ let _ = s.meshes.get(e);
1343
+ if (!_ || _.object !== g) {
1344
+ _?.before.destroy();
1345
+ let t = i.createBuffer({
1346
+ label: "shader:raw:before",
1347
+ size: 288,
1348
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
1349
+ });
1350
+ _ = {
1351
+ before: t,
1352
+ object: g,
1353
+ world: /* @__PURE__ */ new Float32Array(16),
1354
+ frame: -1,
1355
+ group: i.createBindGroup({
1356
+ layout: B(i, !0),
1357
+ entries: [
1358
+ s.camera,
1359
+ g,
1360
+ t
1361
+ ].map((e, t) => ({
1362
+ binding: t,
1363
+ resource: { buffer: e }
1364
+ }))
1365
+ })
1366
+ }, s.meshes.set(e, _);
1367
+ }
1368
+ let v = _.frame === s.frame - 1 && c[34] > 0 && s.time !== void 0, y = this.beforeData;
1369
+ y.set(c.subarray(16, 32), 0), y.set(v ? _.world : m, 16), y[32] = v ? s.time : p, y[33] = +v, l?.length === 36 ? (y.set(l.subarray(0, 32), 36), y.set(l.subarray(32, 35), 68)) : (y.set(c.subarray(0, 32), 36), y[68] = y[69] = y[70] = 0), y[71] = 1, i.queue.writeBuffer(_.before, 0, y), _.world.set(m), _.frame = s.frame;
1370
+ let b = n.prepare(i, d, this), x = n.pipeline(this, b, i, e, "velocity", r, "equal", o);
1371
+ x && f.push({
1372
+ mesh: e,
1373
+ pipeline: x,
1374
+ gpu: b,
1375
+ call: h,
1376
+ group: _.group
1377
+ });
1378
+ }
1379
+ p !== void 0 && (s.time = p);
1380
+ let m = { slots: [] };
1381
+ for (let t of f) e.setPipeline(t.pipeline), e.setBindGroup(0, t.group), t.gpu.group && (e.setBindGroup(1, t.gpu.group), t.gpu.extras.forEach((t, n) => e.setBindGroup(2 + n, t))), t.mesh.draw(e, t.call[0], t.call[1], t.call[2], m);
1382
+ }
1383
+ releaseVelocity(e) {
1384
+ let t = this.velocityStates.get(e);
1385
+ if (t) {
1386
+ t.camera.destroy();
1387
+ for (let e of t.meshes.values()) e.before.destroy();
1388
+ this.velocityStates.delete(e);
1389
+ }
1390
+ }
1391
+ execute(e, t) {
1392
+ if (t || (this.stats.meshes = this.stats.drawCalls = this.stats.culled = 0), e.backend !== "webgpu" || !this.device || !this.engine || e.device !== this.device || !this.meshes.size) return;
1393
+ let r = this.device, i = this.engine, a = e.camera.position, o = [], s = this.nextPass(), c;
1394
+ for (let n of this.meshes) {
1395
+ let l = n.material;
1396
+ if (!n.visible || l.transparent !== t) continue;
1397
+ let u = n.worldMatrix(i);
1398
+ if (!u) continue;
1399
+ if (n.culled(u, e.camera.matrix)) {
1400
+ this.stats.culled++;
1401
+ continue;
1402
+ }
1403
+ c ??= this.writeCamera(e);
1404
+ let d = n.upload(r, c, u);
1405
+ if (!d) continue;
1406
+ let f = l.prepare(r, s, this), p = l.pipeline(this, f, r, n, "color", e);
1407
+ if (this.watchers.size && l.pipeline(this, f, r, n, "pick"), !p) continue;
1408
+ let m = u[12] - a[0], h = u[13] - a[1], g = u[14] - a[2];
1409
+ o.push({
1410
+ mesh: n,
1411
+ pipeline: p,
1412
+ gpu: f,
1413
+ call: d,
1414
+ distance: m * m + h * h + g * g
1415
+ });
1416
+ }
1417
+ if (this.stats.pending = this.jobs.size, !o.length) return;
1418
+ o.sort((e, n) => e.mesh.renderOrder - n.mesh.renderOrder || (t ? n.distance - e.distance : 0));
1419
+ let l = e.descriptor.depthStencil.format.includes("stencil"), u = e.encoder.beginRenderPass({
1420
+ label: this.name + (t ? ":transparent" : ":opaque"),
1421
+ colorAttachments: [{
1422
+ view: e.color,
1423
+ loadOp: "load",
1424
+ storeOp: "store"
1425
+ }],
1426
+ depthStencilAttachment: {
1427
+ view: e.depth,
1428
+ depthLoadOp: "load",
1429
+ depthStoreOp: "store",
1430
+ ...l ? { stencilReadOnly: !0 } : {}
1431
+ }
1432
+ });
1433
+ n(u, e), $(u, o), this.stats.meshes += o.length, this.stats.drawCalls += o.length, u.end();
1434
+ }
1435
+ }, ge = class e {
1436
+ static attach(t, n) {__margoAssertCore(t,__margoCoreRequirement("1.0.0",import.meta.url));
1437
+ if (!n.engine) throw new o("state", "Attach RawShaders to the engine before RawPicking.attach");
1438
+ let r = new e(n);
1439
+ r.remove = t.addOverlay(r), n.watchers.add(r);
1440
+ for (let e of n.meshes) r.added(e);
1441
+ return r;
1442
+ }
1443
+ constructor(e) {
1444
+ this.raw = e, this.hits = [], this.id = /* @__PURE__ */ new Uint32Array(1), this.standIns = /* @__PURE__ */ new Map(), this.owners = /* @__PURE__ */ new Map();
1445
+ }
1446
+ rawOf(e) {
1447
+ return e ? this.owners.get(e) ?? [...this.raw.meshes].find((t) => t.mesh === e) ?? null : null;
1448
+ }
1449
+ added(e) {
1450
+ if (this.standIns.has(e)) return;
1451
+ let t = this.raw.engine.createMesh();
1452
+ this.standIns.set(e, t), this.owners.set(t, e);
1453
+ }
1454
+ removed(e) {
1455
+ let t = this.standIns.get(e);
1456
+ t && (this.standIns.delete(e), this.owners.delete(t), t.dispose());
1457
+ }
1458
+ drawPick(e) {
1459
+ let t = this.raw, n = t.device, r = t.engine;
1460
+ if (this.hits = [], !n || !r) return;
1461
+ this.device !== n && (this.camera?.destroy(), this.device = n, this.camera = t.cameraBuffer(n));
1462
+ let i = this.camera, a = t.nextPass(), o = [];
1463
+ n.queue.writeBuffer(i, 0, t.cameraBlock(e.camera, e.matrix, 3, 3, 0, 0));
1464
+ for (let s of t.meshes) {
1465
+ let c = s.material;
1466
+ if (!s.visible || c.error) continue;
1467
+ let l = s.worldMatrix(r);
1468
+ if (!l || s.culled(l, e.matrix)) continue;
1469
+ let u = s.upload(n, i, l);
1470
+ if (!u) continue;
1471
+ let d = c.prepare(n, a, t), f = c.pipeline(t, d, n, s, "pick");
1472
+ f && (this.id[0] = e.firstId + this.hits.length, n.queue.writeBuffer(s.gpu.object, re, this.id), this.hits.push(s), o.push({
1473
+ mesh: s,
1474
+ pipeline: f,
1475
+ gpu: d,
1476
+ call: u,
1477
+ distance: 0
1478
+ }));
1479
+ }
1480
+ if (!o.length) return;
1481
+ let s = c(e, o[0].mesh.gpu.group);
1482
+ $(s, o), s.end();
1483
+ }
1484
+ pickHit(e) {
1485
+ let t = this.hits[e];
1486
+ if (!t) return null;
1487
+ let n = t.mesh ?? this.standIns.get(t);
1488
+ return n ? { mesh: n } : null;
1489
+ }
1490
+ dispose() {
1491
+ this.remove?.(), this.remove = void 0, this.raw.watchers.delete(this);
1492
+ for (let e of this.standIns.values()) e.dispose();
1493
+ this.standIns.clear(), this.owners.clear(), this.hits = [], this.camera?.destroy(), this.camera = this.device = void 0;
1494
+ }
1495
+ [Symbol.dispose ?? Symbol()]() {
1496
+ this.dispose();
1497
+ }
1498
+ };
1499
+ //#endregion
1500
+ export { f as a, p as c, he as i, u as l, ge as n, d as o, W as r, m as s, pe as t };