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