@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
package/dist/graph.js ADDED
@@ -0,0 +1,365 @@
1
+ import { D as e, Dt as t, Et as n, H as r, I as i, Kt as a, L as o, T as s, _t as c, bt as l, cn as u, dn as d, dt as f, ft as p, ht as m, m as h, nn as g, nt as _, ut as v, vt as y, wt as b, xt as x } from "./node-B6yoIC9V.js";
2
+ import { t as S } from "./material-CZ8V1FeA.js";
3
+ //#region src/graph.ts
4
+ var C = Object.freeze({
5
+ nodes: 128,
6
+ depth: 32,
7
+ work: 2048,
8
+ jsonBytes: 65536
9
+ }), w = Object.freeze({
10
+ float: 0,
11
+ vec3: 0,
12
+ position: 0,
13
+ worldPosition: 0,
14
+ normal: 0,
15
+ worldNormal: 0,
16
+ color: 0,
17
+ uv: 0,
18
+ add: 2,
19
+ sub: 2,
20
+ mul: 2,
21
+ div: 2,
22
+ min: 2,
23
+ max: 2,
24
+ pow: 2,
25
+ mix: 3,
26
+ clamp: 3,
27
+ sin: 1,
28
+ cos: 1,
29
+ abs: 1,
30
+ floor: 1,
31
+ fract: 1,
32
+ saturate: 1,
33
+ length: 1,
34
+ dot: 2,
35
+ normalize: 1,
36
+ component: 1,
37
+ combine: 3
38
+ }), T = [
39
+ "color",
40
+ "roughness",
41
+ "metalness",
42
+ "emissive",
43
+ "opacity",
44
+ "normal"
45
+ ], E = /* @__PURE__ */ new Set([
46
+ "color",
47
+ "emissive",
48
+ "normal"
49
+ ]), D = (e) => !!e && typeof e == "object" && !Array.isArray(e), O = (e) => typeof e == "number" && Number.isFinite(Math.fround(e)) && Math.abs(e) <= 1e6, k = (e) => Array.isArray(e) && e.length === 3 && O(e[0]) && O(e[1]) && O(e[2]), A = (e) => {
50
+ throw TypeError(`Surface graph is invalid; ${e}`);
51
+ }, j = (e) => typeof e == "string" && /^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(e);
52
+ function M(e) {
53
+ if (!D(e) || e.version !== 1) return A("set version to 1");
54
+ (!Array.isArray(e.nodes) || e.nodes.length > C.nodes) && A("nodes must be an array with at most 128 entries"), (!D(e.outputs) || Object.keys(e.outputs).some((e) => !T.includes(e))) && A("outputs must contain supported surface slots");
55
+ let t = e.fallback;
56
+ (!D(t) || !k(t.color) || !k(t.emissive) || !O(t.roughness) || !O(t.metalness) || !O(t.opacity) || [...t.color, ...t.emissive].some((e) => e < 0) || [
57
+ t.roughness,
58
+ t.metalness,
59
+ t.opacity
60
+ ].some((e) => e < 0 || e > 1)) && A("fallback requires finite nonnegative RGB and physical scalar values in 0..1");
61
+ let n = e, r = /* @__PURE__ */ new Map(), i = 0;
62
+ for (let e of n.nodes) (!D(e) || !j(e.id) || r.has(e.id)) && A("use unique node ids beginning with a letter"), (typeof e.op != "string" || !Object.hasOwn(w, e.op)) && A(`use a supported operation on ${e.id}`), (!Array.isArray(e.inputs) || e.inputs.length !== w[e.op] || !e.inputs.every(j)) && A(`${e.id} needs the right number of inputs and valid node ids`), e.op === "float" && !O(e.value) && A(`${e.id} needs a finite float value within ±1000000`), e.op === "vec3" && !k(e.value) && A(`${e.id} needs three finite values within ±1000000`), e.op === "component" && (!Number.isInteger(e.value) || Number(e.value) < 0 || Number(e.value) > 2) && A(`${e.id} component must be 0, 1 or 2`), ![
63
+ "float",
64
+ "vec3",
65
+ "component"
66
+ ].includes(e.op) && e.value !== void 0 && A(`remove the parameter value from ${e.id}`), i += [
67
+ "sin",
68
+ "cos",
69
+ "pow",
70
+ "normalize"
71
+ ].includes(e.op) ? 16 : 1, r.set(e.id, e);
72
+ if (i > C.work) throw RangeError("Surface graph exceeds 2048 work units; remove expensive nodes");
73
+ let a = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map(), s = [], c = (e) => {
74
+ let t = r.get(e);
75
+ if (!t) return A(`add the missing input node ${e}`);
76
+ if (a.get(e) === 1) return A(`cycle at ${e}; remove the connection`);
77
+ if (a.get(e) === 2) return o.get(e);
78
+ a.set(e, 1);
79
+ let n = 1 + Math.max(0, ...t.inputs.map(c));
80
+ if (n > C.depth) throw RangeError("Surface graph depth exceeds 32; shorten the expression chain");
81
+ return a.set(e, 2), o.set(e, n), s.push(t), n;
82
+ };
83
+ n.nodes.forEach((e) => c(e.id));
84
+ for (let e of T) n.outputs[e] !== void 0 && (!j(n.outputs[e]) || !r.has(n.outputs[e])) && A(`add the missing ${e} output node`);
85
+ return {
86
+ graph: n,
87
+ order: s
88
+ };
89
+ }
90
+ function N(S, C = {}) {
91
+ let { graph: w, order: D } = M(S), O = /* @__PURE__ */ new Map();
92
+ for (let S of D) {
93
+ let w = S.inputs.map((e) => O.get(e)), T;
94
+ switch (S.op) {
95
+ case "float":
96
+ T = r(S.value);
97
+ break;
98
+ case "vec3":
99
+ T = u(...S.value);
100
+ break;
101
+ case "position":
102
+ T = b;
103
+ break;
104
+ case "worldPosition":
105
+ T = n;
106
+ break;
107
+ case "normal":
108
+ T = y;
109
+ break;
110
+ case "worldNormal":
111
+ T = l;
112
+ break;
113
+ case "color":
114
+ T = d().rgb;
115
+ break;
116
+ case "uv":
117
+ T = u(g(), 0);
118
+ break;
119
+ case "component":
120
+ w[0].type !== "vec3f" && A(`${S.id} component input must be vec3f`), T = w[0][[
121
+ "x",
122
+ "y",
123
+ "z"
124
+ ][S.value]];
125
+ break;
126
+ case "combine":
127
+ w.some((e) => e.type !== "f32") && A(`${S.id} combine inputs must be f32`), T = u(w[0], w[1], w[2]);
128
+ break;
129
+ case "mix":
130
+ T = p(w[0], w[1], w[2]);
131
+ break;
132
+ case "clamp":
133
+ T = e(w[0], w[1], w[2]);
134
+ break;
135
+ case "length":
136
+ T = _(w[0]);
137
+ break;
138
+ case "dot":
139
+ w.some((e) => e.type !== "vec3f") && A(`${S.id} dot inputs must be vec3f`), T = o(w[0], w[1]);
140
+ break;
141
+ case "normalize":
142
+ w[0].type !== "vec3f" && A(`${S.id} normalize input must be vec3f`), T = x(w[0]);
143
+ break;
144
+ case "add":
145
+ T = h(w[0], w[1]);
146
+ break;
147
+ case "sub":
148
+ T = a(w[0], w[1]);
149
+ break;
150
+ case "mul":
151
+ T = m(w[0], w[1]);
152
+ break;
153
+ case "div":
154
+ T = i(w[0], w[1]);
155
+ break;
156
+ case "min":
157
+ T = f(w[0], w[1]);
158
+ break;
159
+ case "max":
160
+ T = v(w[0], w[1]);
161
+ break;
162
+ case "pow":
163
+ T = t(w[0], w[1]);
164
+ break;
165
+ default: T = c[S.op](w[0]);
166
+ }
167
+ let E = C[S.op];
168
+ E && (T = s(E, "vec3f", S.id)), T.type !== "f32" && T.type !== "vec3f" && A(`${S.id} must produce f32 or vec3f`), O.set(S.id, T);
169
+ }
170
+ for (let e of T) {
171
+ let t = w.outputs[e], n = E.has(e) ? "vec3f" : "f32";
172
+ t && O.get(t).type !== n && A(`${e} output must be ${n}`);
173
+ }
174
+ return {
175
+ graph: w,
176
+ order: D,
177
+ nodes: O
178
+ };
179
+ }
180
+ function P(e) {
181
+ N(e);
182
+ }
183
+ function F(e) {
184
+ let { nodes: t } = N(e);
185
+ return { types: Object.fromEntries([...t].map(([e, t]) => [e, t.type])) };
186
+ }
187
+ function I(e) {
188
+ P(e);
189
+ let t = {};
190
+ for (let n of T) e.outputs[n] && (t[n] = e.outputs[n]);
191
+ let n = e.fallback, r = JSON.stringify({
192
+ version: 1,
193
+ nodes: e.nodes.map((e) => ({
194
+ id: e.id,
195
+ op: e.op,
196
+ inputs: [...e.inputs],
197
+ ...e.value === void 0 ? {} : { value: e.value }
198
+ })),
199
+ outputs: t,
200
+ fallback: {
201
+ color: n.color,
202
+ emissive: n.emissive,
203
+ roughness: n.roughness,
204
+ metalness: n.metalness,
205
+ opacity: n.opacity
206
+ }
207
+ });
208
+ if (new TextEncoder().encode(r).length > C.jsonBytes) throw RangeError("Surface graph JSON exceeds 65536 bytes; reduce node metadata");
209
+ return r;
210
+ }
211
+ function L(e) {
212
+ if (typeof e != "string" || new TextEncoder().encode(e).length > C.jsonBytes) throw RangeError("Surface graph JSON must be at most 65536 bytes");
213
+ let t = JSON.parse(e);
214
+ return P(t), JSON.parse(I(t));
215
+ }
216
+ function R(e, t) {
217
+ let { graph: n, nodes: r } = N(e, t), i = {};
218
+ for (let e of T) n.outputs[e] && (i[`${e}Node`] = r.get(n.outputs[e]));
219
+ return i;
220
+ }
221
+ function z(e, t = {}) {
222
+ let n = L(I(e)), r = new S({
223
+ ...t,
224
+ ...R(n)
225
+ });
226
+ return r.surfaceGraph = n, r;
227
+ }
228
+ var B = (e, t) => typeof e == "number" ? e : e[t], V = (e, t) => e.every((e) => typeof e == "number") ? t(...e) : [
229
+ 0,
230
+ 1,
231
+ 2
232
+ ].map((n) => t(...e.map((e) => B(e, n))));
233
+ function H(e) {
234
+ let t = L(I(e)), { order: n } = N(t), r = new Map(n.map((e) => [e.id, e])), i = /* @__PURE__ */ new Set(), a = (e) => {
235
+ i.has(e) || (i.add(e), r.get(e).inputs.forEach(a));
236
+ };
237
+ Object.values(t.outputs).forEach(a);
238
+ let o = n.filter((e) => i.has(e.id));
239
+ return (e) => {
240
+ let n = /* @__PURE__ */ new Map();
241
+ for (let t of o) {
242
+ let r = t.inputs.map((e) => n.get(e)), i;
243
+ switch (t.op) {
244
+ case "float":
245
+ case "vec3":
246
+ i = t.value;
247
+ break;
248
+ case "position":
249
+ i = [...e.position];
250
+ break;
251
+ case "worldPosition":
252
+ i = [...e.worldPosition ?? e.position];
253
+ break;
254
+ case "normal":
255
+ i = [...e.normal];
256
+ break;
257
+ case "worldNormal":
258
+ i = [...e.worldNormal ?? e.normal];
259
+ break;
260
+ case "color":
261
+ i = [...e.color ?? [
262
+ 1,
263
+ 1,
264
+ 1
265
+ ]];
266
+ break;
267
+ case "uv":
268
+ i = [
269
+ e.uv?.[0] ?? 0,
270
+ e.uv?.[1] ?? 0,
271
+ 0
272
+ ];
273
+ break;
274
+ case "component":
275
+ i = B(r[0], t.value);
276
+ break;
277
+ case "combine":
278
+ i = r;
279
+ break;
280
+ case "add":
281
+ i = V(r, (e, t) => e + t);
282
+ break;
283
+ case "sub":
284
+ i = V(r, (e, t) => e - t);
285
+ break;
286
+ case "mul":
287
+ i = V(r, (e, t) => e * t);
288
+ break;
289
+ case "div":
290
+ i = V(r, (e, t) => e / t);
291
+ break;
292
+ case "min":
293
+ i = V(r, Math.min);
294
+ break;
295
+ case "max":
296
+ i = V(r, Math.max);
297
+ break;
298
+ case "pow":
299
+ i = V(r, Math.pow);
300
+ break;
301
+ case "mix":
302
+ i = V(r, (e, t, n) => e * (1 - n) + t * n);
303
+ break;
304
+ case "clamp":
305
+ i = V(r, (e, t, n) => Math.max(t, Math.min(n, e)));
306
+ break;
307
+ case "sin":
308
+ i = V(r, Math.sin);
309
+ break;
310
+ case "cos":
311
+ i = V(r, Math.cos);
312
+ break;
313
+ case "abs":
314
+ i = V(r, Math.abs);
315
+ break;
316
+ case "floor":
317
+ i = V(r, Math.floor);
318
+ break;
319
+ case "fract":
320
+ i = V(r, (e) => e - Math.floor(e));
321
+ break;
322
+ case "saturate":
323
+ i = V(r, (e) => Math.min(1, Math.max(0, e)));
324
+ break;
325
+ case "length":
326
+ i = typeof r[0] == "number" ? Math.abs(r[0]) : Math.hypot(...r[0]);
327
+ break;
328
+ case "dot":
329
+ i = [
330
+ 0,
331
+ 1,
332
+ 2
333
+ ].reduce((e, t) => e + B(r[0], t) * B(r[1], t), 0);
334
+ break;
335
+ case "normalize": {
336
+ let e = Math.hypot(...r[0]);
337
+ i = V(r, (t) => t / e);
338
+ break;
339
+ }
340
+ }
341
+ if (!(typeof i == "number" ? [i] : i).every((e) => Number.isFinite(e))) throw RangeError(`Surface graph ${t.id} produced a nonfinite bake value; avoid zero division, zero normals and invalid powers`);
342
+ n.set(t.id, i);
343
+ }
344
+ let r = {};
345
+ for (let e of T) if (t.outputs[e]) {
346
+ let i = n.get(t.outputs[e]);
347
+ if (e === "normal") {
348
+ let e = Math.hypot(...i);
349
+ if (!e) throw RangeError("Surface graph normal is zero; supply a nonzero normal");
350
+ i = V([i], (t) => t / e);
351
+ }
352
+ [
353
+ "opacity",
354
+ "metalness",
355
+ "roughness"
356
+ ].includes(e) && (i = Math.max(e === "roughness" ? .045 : 0, Math.min(1, i))), r[e] = typeof i == "number" ? i : [...i];
357
+ }
358
+ return r;
359
+ };
360
+ }
361
+ function U(e, t) {
362
+ return H(e)(t);
363
+ }
364
+ //#endregion
365
+ export { C as SURFACE_GRAPH_LIMITS, w as SURFACE_OPERATIONS, R as compileSurfaceGraph, z as createGraphMaterial, U as evaluateSurfaceGraph, F as inspectSurfaceGraph, L as parseSurfaceGraph, I as serializeSurfaceGraph, H as surfaceGraphSampler, P as validateSurfaceGraph };
@@ -0,0 +1,8 @@
1
+ export * from './node.js';
2
+ export { attribute } from './attribute.js';
3
+ export { texture, textureCube, texture3D, type BindableTexture } from './texture.js';
4
+ export { block, If, Loop, While, Break, Continue, Switch, Var, Let, VarNode, type Branch, type Cases, type LoopRange, } from './control.js';
5
+ export { NodeMaterial, materialColor, materialNormal, materialRoughness, materialMetalness, materialEmissive, frontFacing, type NodeMaterialOptions, } from './material.js';
6
+ export { NodePass, inputColor, inputDepth, type NodePassOptions, type NodePassAttachOptions } from './post.js';
7
+ export { ShaderClock } from './clock.js';
8
+ export { ComputePass, StorageBuffer, storage, workgroup, WorkgroupArray, workgroupBarrier, storageBarrier, textureBarrier, instanceIndex, globalId, localId, localIndex, workgroupId, workgroupCount, type ComputeCount, type Exchange, type WorkgroupType, type Store, type StorageType, type ComputeOptions, type ComputeBody, } from './compute.js';
package/dist/index.js ADDED
@@ -0,0 +1,103 @@
1
+ import { $ as e, $t as t, A as n, At as r, B as i, Bt as a, C as o, Ct as s, D as c, Dt as l, E as u, Et as d, F as f, Ft as ee, G as te, Gt as ne, H as re, Ht as ie, I as ae, It as oe, J as se, Jt as ce, K as p, Kt as m, L as h, Lt as g, M as _, Mt as v, N as y, Nt as b, O as x, Ot as S, P as C, Pt as w, Q as T, Qt as E, R as D, Rt as O, S as k, St as A, T as j, Tt as M, U as N, Ut as P, V as F, Vt as I, W as L, Wt as R, X as z, Xt as B, Y as V, Yt as H, Z as U, Zt as W, _ as G, a as le, an as ue, at as de, b as fe, bt as pe, c as me, cn as he, ct as ge, d as _e, dn as ve, dt as ye, en as be, et as xe, f as Se, fn as Ce, ft as we, g as Te, gt as Ee, h as De, hn as Oe, ht as ke, i as Ae, in as je, it as Me, j as Ne, jt as Pe, k as Fe, kt as Ie, l as Le, ln as Re, lt as ze, m as Be, mn as Ve, mt as He, n as Ue, nn as We, nt as Ge, o as K, on as Ke, ot as qe, p as Je, pn as Ye, pt as Xe, q as Ze, qt as Qe, r as $e, rn as et, rt as tt, s as nt, sn as rt, st as it, t as at, tn as ot, tt as st, u as ct, un as lt, ut, v as dt, vt as ft, w as pt, wt as mt, x as ht, xt as gt, y as _t, yt as vt, z as yt, zt as bt } from "./node-B6yoIC9V.js";
2
+ import { t as xt } from "./clock-BLGNexlt.js";
3
+ import { a as St, c as Ct, i as wt, l as Tt, n as Et, o as Dt, r as Ot, s as kt, t as At, u as jt } from "./control-CFjkGPBk.js";
4
+ import { a as Mt, d as Nt, g as Pt, h as Ft, i as It, l as Lt, m as Rt, n as q, o as zt, p as Bt, r as Vt, s as Ht, t as Ut, u as Wt } from "./compute-CXGG9qvI.js";
5
+ import { i as Gt, n as Kt, r as qt } from "./texture-BawKO_h9.js";
6
+ import { a as Jt, c as Yt, i as Xt, o as Zt, r as Qt, s as J, t as $t } from "./material-CZ8V1FeA.js";
7
+ import { n as en, r as tn, t as nn } from "./post-DLpZ110L.js";
8
+ import { MargoError as rn } from "@margoengine/math/errors";
9
+ //#region src/attribute.ts
10
+ var an = /^[A-Za-z_][A-Za-z0-9_]*$/, Y = /^(?:([fiu])32|vec([234])([fiu]))$/, X = (e) => +(Y.exec(e)[2] ?? 1), Z = (e) => Y.exec(e)[1] ?? Y.exec(e)[3], Q = {
11
+ i: [-2147483648, 2147483647],
12
+ u: [0, 4294967295]
13
+ }, on = class {
14
+ constructor() {
15
+ this.prefix = "ndat", this.bindings = 1, this.list = [], this.stride = 0;
16
+ }
17
+ add(e, t) {
18
+ let n = this.list.find((t) => t.name === e);
19
+ if (n) {
20
+ if (n.type !== t) throw TypeError(`attribute('${e}') is read as ${n.type} and as ${t}; read it with one type`);
21
+ } else this.list.push({
22
+ name: e,
23
+ type: t,
24
+ offset: this.stride
25
+ }), this.stride += X(t);
26
+ }
27
+ declare(e, t, n) {
28
+ return `@group(${t}) @binding(${n}) var<storage, read> ${e}:array<u32>;\nconst ${e}Stride:u32=${this.stride}u;\n` + this.list.map((t) => `const ${e}_${t.name}:u32=${t.offset}u;`).join("\n");
29
+ }
30
+ entries(e, t) {
31
+ let n = t.meshData;
32
+ if (!(n instanceof $) || n.reads !== this) throw new rn("state", "A material that reads attribute() draws a mesh's own geometry; use it on a mesh from createMesh or createInstancedMesh");
33
+ return [{ buffer: n.words.buffer(e) }];
34
+ }
35
+ read(e) {
36
+ let t = new $(this);
37
+ return t.prepare(e)(), t;
38
+ }
39
+ pack(e, t, n) {
40
+ let r = e.positions.length / 3, i = new Uint32Array(n * this.stride), a = {
41
+ f: new Float32Array(i.buffer),
42
+ i: new Int32Array(i.buffer),
43
+ u: i
44
+ };
45
+ for (let { name: i, type: o, offset: s } of this.list) {
46
+ let c = e.attributes?.[i], l = c && !("type" in c) ? {
47
+ data: c,
48
+ type: "f32"
49
+ } : c, u = X(o), d = Z(o);
50
+ if (!l) throw TypeError(`Mesh geometry has no attribute '${i}', which its material reads; add attributes: {${i}: {data, type: '${o}'}}`);
51
+ if (l.type !== o) throw TypeError(`Mesh geometry attribute '${i}' is ${l.type}, and its material reads it as ${o}; use it as ${o}`);
52
+ if (l.data?.length !== r * u) throw RangeError(`Mesh geometry attribute '${i}' needs ${r * u} values (${r} vertices of ${o}), not ${l.data?.length}`);
53
+ let f = a[d];
54
+ for (let e = 0; e < n; e++) for (let n = 0; n < u; n++) {
55
+ let r = l.data[(t + e) * u + n];
56
+ if (d === "f" ? !Number.isFinite(r) : !Number.isInteger(r) || r < Q[d][0] || r > Q[d][1]) throw RangeError(`Mesh geometry attribute '${i}' holds ${r}; give ${d === "f" ? "finite numbers" : `whole numbers that fit ${d}32`}`);
57
+ f[e * this.stride + s + n] = r;
58
+ }
59
+ }
60
+ return i;
61
+ }
62
+ get words() {
63
+ return this.stride;
64
+ }
65
+ }, $ = class {
66
+ constructor(e) {
67
+ this.reads = e;
68
+ }
69
+ prepare(e, t) {
70
+ let n = t?.start ?? 0, r = t?.count ?? e.positions.length / 3, i = this.reads.pack(e, n, r);
71
+ return () => {
72
+ if (!t && this.words?.data.length !== i.length) {
73
+ this.words?.dispose(), this.words = new q(i, "u32");
74
+ return;
75
+ }
76
+ let e = this.reads.words;
77
+ this.words.data.set(i, n * e), this.words.update(t && {
78
+ start: n * e,
79
+ count: r * e
80
+ });
81
+ };
82
+ }
83
+ dispose() {
84
+ this.words.dispose();
85
+ }
86
+ };
87
+ function sn(e, t) {
88
+ if (typeof e != "string" || !an.test(e)) throw TypeError(`attribute() needs a name of letters, digits and underscores, not '${e}'`);
89
+ if (!Y.test(t)) throw TypeError(`attribute('${e}') type '${t}' is not one to four of f32, i32 or u32; pass 'f32' to 'vec4u'`);
90
+ return new K(t, `at:${e}:${t}`, [], (n, r) => {
91
+ if (n.stage.kind === "fragment") return n.stage.varying(n, r);
92
+ if (n.stage.kind !== "vertex") throw TypeError("attribute() reads a mesh vertex; use it in the nodes of a NodeMaterial");
93
+ let i = n.program, a = i.attributes ??= new on();
94
+ a.add(e, t);
95
+ let o = n.resource(a), s = `${n.builtin("vertexIndex")}*${o}Stride+${o}_${e}`, c = (e) => {
96
+ let n = `${o}[${s}${e ? `+${e}u` : ""}]`;
97
+ return Z(t) === "u" ? n : `bitcast<${Z(t)}32>(${n})`;
98
+ }, l = X(t);
99
+ return l === 1 ? c(0) : `${t}(${Array.from({ length: l }, (e, t) => c(t)).join(",")})`;
100
+ });
101
+ }
102
+ //#endregion
103
+ export { At as Break, at as Builder, Ut as ComputePass, Et as Continue, Ue as FIXED, $e as Fn, Ot as If, Ae as LEAF, wt as Let, St as Loop, le as MUTABLE, K as Node, $t as NodeMaterial, nn as NodePass, nt as ONCE, me as OP, Le as Program, ct as STMT, xt as ShaderClock, q as StorageBuffer, Dt as Switch, _e as UniformNode, kt as Var, Ct as VarNode, Tt as While, Vt as WorkgroupArray, Se as abs, Je as acos, Be as add, De as asin, Te as atan, G as atan2, sn as attribute, dt as bitangentWorld, jt as block, _t as bool, fe as builtin, ht as call, k as cameraFar, o as cameraNear, pt as cameraPosition, j as cast, u as ceil, c as clamp, x as color, Fe as constant, n as cos, Ne as cross, _ as degrees, y as deltaTime, C as discard, f as distance, ae as div, h as dot, D as dpdx, yt as dpdy, i as exp, F as exp2, re as float, N as floor, L as fract, Qt as frontFacing, te as fwidth, It as globalId, p as hdrTarget, en as inputColor, tn as inputDepth, Ze as instanceColor, Mt as instanceIndex, se as instanceMatrix, V as instanceUV, z as int, U as inverseSqrt, T as isMatrix, e as ivec2, xe as ivec3, st as ivec4, Ge as length, tt as linearColor, Me as linearDepth, zt as localId, Ht as localIndex, de as log, qe as log2, it as loop, ge as mat3, ze as mat4, Xt as materialColor, Jt as materialEmissive, Zt as materialMetalness, J as materialNormal, Yt as materialRoughness, ut as max, ye as min, we as mix, Xe as mod, He as modelMatrix, ke as mul, Ee as negate, ft as normalLocal, vt as normalView, pe as normalWorld, gt as normalize, A as not, s as oneMinus, mt as positionLocal, M as positionView, d as positionWorld, l as pow, S as projectionMatrix, Ie as radians, r as reflect, Pe as refract, v as resolution, b as round, w as sameEntries, ee as saturate, oe as scalarOf, g as screenCoordinate, O as screenUV, bt as select, a as sign, I as sin, ie as sizeOf, P as smoothstep, R as sqrt, ne as step, Lt as storage, Wt as storageBarrier, m as sub, Qe as tan, ce as tangentLocal, H as tangentWorld, B as tanh, Kt as texture, qt as texture3D, Nt as textureBarrier, Gt as textureCube, W as time, E as trunc, t as uint, be as uniform, ot as unique, We as uv, et as uvec2, je as uvec3, ue as uvec4, Ke as varying, rt as vec2, he as vec3, Re as vec4, lt as vecOf, ve as vertexColor, Ce as vertexIndex, Ye as viewDirection, Ve as viewMatrix, Oe as wgslFn, Bt as workgroup, Rt as workgroupBarrier, Ft as workgroupCount, Pt as workgroupId };
@@ -0,0 +1,77 @@
1
+ import { T as e, b as t, o as n } from "./node-B6yoIC9V.js";
2
+ import { n as r, t as i } from "./material-CZ8V1FeA.js";
3
+ import { MargoError as a } from "@margoengine/math/errors";
4
+ //#region ../shared/light-terms.js
5
+ var o = "((1-mix(max(dielectricF0.r,max(dielectricF0.g,dielectricF0.b)),dielectricF90,pow(1-vh,5.0)))*(1-metal)*base/3.14159265+d*g*fresnel/max(4*nl*nv,0.0001))", s = "var<private> margoDirectVisible:vec3f=vec3f(1);", c = /*@__PURE__*/ t("sunDirection", "vec3f"), l = /*@__PURE__*/ t("sunColor", "vec3f"), u = /*@__PURE__*/ t("sunVisibility", "vec3f"), d = /*@__PURE__*/ t("ambientLight", "vec3f"), f = /*@__PURE__*/ t("localLight", "vec3f"), p = /*@__PURE__*/ t("litColor", "vec3f");
6
+ function m(t, r = 0) {
7
+ return new n("vec3f", "E", [e(t, "vec3f", "environment direction"), e(r, "f32", "environment roughness")], (e, t) => `${e.builtin("environment")}(i,s,${e.expr(t.args[0])},${e.expr(t.args[1])})`);
8
+ }
9
+ var h = "margoNodeBrdf", g = "margoNodeEnvironment", _ = "margoNodeLocal", v = "let direct=direct_light(s,v,l);", y = `result+=${o}*nl*`, b = /(let margoAmbient=([^;]*);)?var color=([^;]*);/, x = /\n\s*(?:if\(f\.ext\.x>0\.5\)|color=[^;]*pbrNeutral|if\(f\.settings\.w<0\.5\))/, S = (e) => ({
10
+ ...r,
11
+ builtins: {
12
+ ...r.builtins,
13
+ normalWorld: "s.n",
14
+ environment: g,
15
+ ...e
16
+ }
17
+ }), C = /*@__PURE__*/ S({
18
+ viewDirection: "v",
19
+ sunDirection: "l",
20
+ sunColor: "f.radiance.rgb*f.light.w",
21
+ sunVisibility: "margoDirectVisible",
22
+ ambientLight: "margoNodeAmbient",
23
+ localLight: _,
24
+ litColor: "color"
25
+ }), w = /*@__PURE__*/ S({
26
+ modelDirection: "l",
27
+ modelView: "v",
28
+ modelNormal: "n",
29
+ modelColor: "base",
30
+ modelRoughness: "roughness",
31
+ modelMetalness: "metal"
32
+ }), T = (e) => {
33
+ throw new a("unsupported", `LightingMaterial requires the standard gltf/pbr shader (${e} is missing); use matching @margoengine/gltf/pbr and shader versions`);
34
+ }, E = (e) => e.map((e) => " " + e + "\n").join(""), D = class extends i {
35
+ constructor(n = {}) {
36
+ let { lightModel: r, lightingNode: i, ...a } = n;
37
+ if (i !== void 0 && i?.type !== "vec3f") throw TypeError("lightingNode must be a vec3f node");
38
+ if (r !== void 0 && typeof r != "function") throw TypeError("lightModel must be a function from a LightInput to a vec3f node");
39
+ if ((a.shading ?? "standard") !== "standard") throw TypeError("LightingMaterial writes its own lighting; leave shading at standard");
40
+ let o = "", s, c = "";
41
+ super(a, (n) => {
42
+ if (i) {
43
+ let e = n.stage(C, [i]);
44
+ o = E(e.lines), s = e.values[0];
45
+ }
46
+ if (r) {
47
+ let i = e(r({
48
+ direction: t("modelDirection", "vec3f"),
49
+ view: t("modelView", "vec3f"),
50
+ normal: t("modelNormal", "vec3f"),
51
+ color: t("modelColor", "vec3f"),
52
+ roughness: t("modelRoughness", "f32"),
53
+ metalness: t("modelMetalness", "f32")
54
+ }), "vec3f", "lightModel result"), a = n.stage(w, [i]);
55
+ c = `var<private> margoNodeIn:Out;\nvar<private> margoNodeSurface:Surface;\nvar<private> margoNodeFront:bool;\nfn ${h}(l:vec3f,v:vec3f,n:vec3f,base:vec3f,roughness:f32,metal:f32)->vec3f {\n let i=margoNodeIn;let s=margoNodeSurface;let front=margoNodeFront;\n${E(a.lines)} return ${a.values[0]};\n}\n`;
56
+ }
57
+ }), this.declared = /* @__PURE__ */ new Map(), this.relit = /* @__PURE__ */ new Map(), this.lightingCode = o, this.finalColor = s, this.lightModelCode = c;
58
+ }
59
+ shader(e, t) {
60
+ let n = super.shader(e, t), r = this.declared.get(n);
61
+ return r === void 0 && (r = n.includes("var<private> margoDirectVisible:vec3f=vec3f(1);") ? n : s + "\n" + n, this.declared.set(n, r)), r;
62
+ }
63
+ relight(e) {
64
+ if (!this.lightModelCode && this.finalColor === void 0) return e;
65
+ let t = this.relit.get(e);
66
+ if (t !== void 0) return t;
67
+ t = e, this.lightModelCode && (t.includes(v) || T("its direct_light call"), t = t.replace(v, `margoNodeIn=i;margoNodeSurface=s;margoNodeFront=front;let direct=${h}(l,v,s.n,s.base.rgb,s.roughness,s.metal)*f.radiance.rgb*f.light.w;`).replaceAll(y, `result+=${h}(l,v,n,base,roughness,metal)*`) + "\n" + this.lightModelCode);
68
+ let n = b.exec(t) ?? T("its var color line");
69
+ if (this.finalColor !== void 0) {
70
+ let e = /^(.*?)direct(?:\*margoDirectVisible)?\+ambient\(s\)/.exec(n[3]) ?? T("direct+ambient(s)"), r = t.slice(n.index + n[0].length), i = r.search(x);
71
+ i < 0 && T("its tone map line"), t = t.slice(0, n.index) + `let ${_}=${e[1]}vec3f(0);${n[1] ?? ""}var color=${_}+${n[3].slice(e[1].length)};` + r.slice(0, i) + `\n let margoNodeAmbient=ambient(s)${n[1] ? "+margoAmbient" : ""};\n {\n${this.lightingCode} color=${this.finalColor};\n }` + r.slice(i);
72
+ }
73
+ return (this.lightingCode + this.finalColor + this.lightModelCode).includes(g) && (t += `\nfn ${g}(i:Out,surface:Surface,d:vec3f,r:f32)->vec3f {\n var s=surface;s.base=vec4f(1);s.metal=1.0;s.n=d;s.occlusion=1.0;s.roughness=clamp(r,0.045,1.0);let v=d;\n return ambient(s)${n[2] ? "+" + n[2] : ""};\n}\n`), this.relit.size >= 64 && this.relit.clear(), this.relit.set(e, t), t;
74
+ }
75
+ };
76
+ //#endregion
77
+ export { f as a, u as c, p as i, d as n, l as o, m as r, c as s, D as t };
@@ -0,0 +1,62 @@
1
+ import { NodeMaterial, type NodeMaterialOptions } from './material.js';
2
+ import { Node, type NodeInput } from './node.js';
3
+ /** Unit vector from the surface towards the sun. `lightingNode` only. */
4
+ export declare const sunDirection: Node<"vec3f">;
5
+ /** The sun's light (colour times intensity), before shadows. `lightingNode` only. */
6
+ export declare const sunColor: Node<"vec3f">;
7
+ /** How much of the sun reaches this pixel per colour channel, 0 in full shadow to 1; 1 without a shadow effect. `lightingNode` only. */
8
+ export declare const sunVisibility: Node<"vec3f">;
9
+ /** Ambient light on this surface, with the material's response: image-based light, probes or the sky. `lightingNode` only. */
10
+ export declare const ambientLight: Node<"vec3f">;
11
+ /** The sum of the clustered lights on this surface, shadows included; zero without them. `lightingNode` only. */
12
+ export declare const localLight: Node<"vec3f">;
13
+ /** The colour the material shows with its usual lighting, before tone mapping. `lightingNode` only. */
14
+ export declare const litColor: Node<"vec3f">;
15
+ /**
16
+ * What the scene's environment shows towards `direction`, blurred as a surface of `roughness` (0..1) would see it. It is
17
+ * the scene's ambient light on a mirror facing that way, so it follows whichever effect provides that light.
18
+ */
19
+ export declare function environment(direction: NodeInput<'vec3f'>, roughness?: NodeInput<'f32'>): Node<'vec3f'>;
20
+ /** What a {@link LightModel} receives for each light. Vectors are unit length, in world space. */
21
+ export interface LightInput {
22
+ /** Towards the light. */
23
+ readonly direction: Node<'vec3f'>;
24
+ /** Towards the camera. */
25
+ readonly view: Node<'vec3f'>;
26
+ /** The shading normal. */
27
+ readonly normal: Node<'vec3f'>;
28
+ /** The surface's base colour. */
29
+ readonly color: Node<'vec3f'>;
30
+ readonly roughness: Node<'f32'>;
31
+ readonly metalness: Node<'f32'>;
32
+ }
33
+ /**
34
+ * A surface's response to one light: how much of the light's colour leaves towards the camera, the cosine term included.
35
+ * The sun and each clustered point, spot and extra directional light use it, with their colour, falloff and shadows
36
+ * applied around it.
37
+ */
38
+ export type LightModel = (light: LightInput) => Node<'vec3f'>;
39
+ /** Options for `new LightingMaterial(options)`: every NodeMaterial option, and the two ways to take over the lighting. */
40
+ export interface LightingMaterialOptions extends NodeMaterialOptions {
41
+ /** Replaces the physically based response to the sun and clustered lights. Ambient and emissive light stay. */
42
+ lightModel?: LightModel;
43
+ /** The final linear colour of the pixel, before fog and tone mapping. It can read every node of this entry. */
44
+ lightingNode?: Node<'vec3f'>;
45
+ }
46
+ /**
47
+ * A NodeMaterial that writes its own lighting: toon steps, hatching, a custom BRDF. Shadows, clustered lights and the
48
+ * environment keep working, because the graph reads what those effects worked out.
49
+ */
50
+ export declare class LightingMaterial extends NodeMaterial {
51
+ /** Generated statements of `lightingNode` (for inspection and tests). */
52
+ readonly lightingCode: string;
53
+ /** The generated WGSL function of `lightModel` (for inspection and tests). */
54
+ readonly lightModelCode: string;
55
+ private readonly finalColor?;
56
+ private readonly declared;
57
+ private readonly relit;
58
+ constructor(options?: LightingMaterialOptions);
59
+ shader(source: string, group: number): string;
60
+ /** @internal Runs once the scene's lighting effects are composed into `code`. */
61
+ relight(code: string): string;
62
+ }
@@ -0,0 +1 @@
1
+ export { t as LightingMaterial, n as ambientLight, r as environment, i as litColor, a as localLight, o as sunColor, s as sunDirection, c as sunVisibility } from "./lighting-JU9yQPfM.js";