@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,93 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin, PassContext } from '@margoengine/core/extension';
4
+ import type { StageOutput } from './shared/stack.js';
5
+ import { type ShaderMaterialOptions, type ShaderUniform } from './glsl/material.js';
6
+ import type { ShaderMaterial } from './glsl-material.js';
7
+ type Context = Extract<PassContext, {
8
+ backend: 'webgpu';
9
+ }>;
10
+ /** The program of a {@link ShaderPass}, in the `{uniforms, vertexShader, fragmentShader}` form web engines use. */
11
+ export interface ShaderPassShader {
12
+ /** GLSL ES 1.00 or 3.00 with `void main()`. Default: a full-screen triangle writing `vUv`, `vUV` or `vUv0`, whichever the fragment declares. */
13
+ readonly vertexShader?: string;
14
+ /** GLSL ES 1.00 or 3.00 with `void main()`. */
15
+ readonly fragmentShader: string;
16
+ /** Live values by GLSL name. */
17
+ readonly uniforms?: Record<string, ShaderUniform>;
18
+ /** Object-like macros defined before both stages. */
19
+ readonly defines?: Readonly<Record<string, string | number | boolean>>;
20
+ }
21
+ /** Options for `new ShaderPass(shader, options)`. */
22
+ export interface ShaderPassOptions extends Pick<ShaderMaterialOptions, 'glslVersion' | 'flipY' | 'strict' | 'builtins' | 'attributes' | 'includes' | 'outputColorSpace' | 'blending' | 'unfilterable'> {
23
+ /**
24
+ * `'ldr'` (default) runs after tonemapping on display colour; `'hdr'` runs on linear light before it and, when last,
25
+ * applies the display curve (its `outputColorSpace` defaults to `'linear'`).
26
+ */
27
+ readonly kind?: 'hdr' | 'ldr';
28
+ /** Plugin and debug name. Default `'shader:glsl-pass:<n>'` (n counts passes). */
29
+ readonly name?: string;
30
+ /**
31
+ * The sampler uniform that receives the stack's colour. Default the first of `tDiffuse`, `textureSampler` and
32
+ * `uColorBuffer` the program declares; null for none.
33
+ */
34
+ readonly input?: string | null;
35
+ }
36
+ /** Options for `ShaderPass.attach(engine, shader, options)`. */
37
+ export interface ShaderPassAttachOptions extends ShaderPassOptions {
38
+ /** Aborts the attach while `@margoengine/post` loads; the pass is then disposed and nothing attaches. */
39
+ readonly signal?: AbortSignal;
40
+ }
41
+ /** The vertex stage a pass without one gets: the triangle, with each coordinate varying the fragment reads. */
42
+ export declare function fullscreenVertex(fragmentShader: string, glslVersion?: 100 | 300): string;
43
+ /**
44
+ * A full-screen GLSL program, run by `@margoengine/post`'s PostStack: `PostStack.attach(engine, [new Tonemap(), pass])`,
45
+ * or alone in a stack of its own with `await ShaderPass.attach(engine, shader)`.
46
+ * The stack's colour reaches the sampler named by `input`; `uniforms` stay live (`pass.uniforms.amount.value = 1`).
47
+ */
48
+ export declare class ShaderPass implements EnginePlugin {
49
+ readonly name: string;
50
+ readonly kind: 'hdr' | 'ldr';
51
+ /** The program as a ShaderMaterial: `material.code('fragment')` shows its WGSL. */
52
+ readonly material: ShaderMaterial;
53
+ /** The sampler uniform that receives the stack's colour, or null. */
54
+ readonly input: string | null;
55
+ private readonly raw;
56
+ private readonly mesh;
57
+ private host?;
58
+ private engine?;
59
+ private stack?;
60
+ private disposed;
61
+ private device?;
62
+ private rect;
63
+ private camera?;
64
+ private readonly context;
65
+ private readonly attachment;
66
+ private readonly pass;
67
+ constructor(shader: ShaderPassShader, options?: ShaderPassOptions);
68
+ /**
69
+ * Adds a new ShaderPass to the PostStack of the engine's scene, after the last effect of its kind, or runs it in a new
70
+ * PostStack when the scene has none (loads `@margoengine/post` when called). Disposing the pass removes it from that
71
+ * stack, and a stack made for it goes with it. `PostStack.join(engine, new ShaderPass(shader), index)` places it yourself.
72
+ * @throws MargoError `'unsupported'` on a WebGL engine; the stack's errors (a repeated name, an HDR pass on the LDR
73
+ * tier); the signal's reason when aborted before the pass attaches.
74
+ */
75
+ static attach(engine: EngineKernel, shader: ShaderPassShader, options?: ShaderPassAttachOptions): Promise<ShaderPass>;
76
+ /** Live values by GLSL name. */
77
+ get uniforms(): Record<string, ShaderUniform>;
78
+ private joinStack;
79
+ setup(engine: Engine): void;
80
+ registerPasses(): void;
81
+ /** Resolves when the program's pipelines have compiled. */
82
+ ready(): Promise<void>;
83
+ /** How the program's colour reaches a target of `format`: 0 a float target (linear light), 2 an sRGB format, 1 as written. */
84
+ protected encoding(format: GPUTextureFormat): number;
85
+ /** Draws the program into `output`; a subclass may set its inputs first. */
86
+ protected render(c: Context, input: GPUTextureView, output: StageOutput): void;
87
+ private release;
88
+ onDeviceRestored(): void;
89
+ /** Removes the pass, from the PostStack {@link ShaderPass.attach} joined too; safe to call twice. */
90
+ dispose(): void;
91
+ [Symbol.dispose]: () => void;
92
+ }
93
+ export {};
@@ -0,0 +1,186 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { n as e, r as t, t as n } from "./view-rect-Bm1ac-TK.js";
5
+ import { t as r } from "./own-stack-D1XnXrrz.js";
6
+ import { i } from "./raw-D0W8U3Qa.js";
7
+ import { n as a, t as o } from "./material-CU7p-Q8u.js";
8
+ import { MargoError as s } from "@margoengine/math/errors";
9
+ //#region src/glsl-pass.ts
10
+ var c = [
11
+ "tDiffuse",
12
+ "textureSampler",
13
+ "uColorBuffer"
14
+ ], l = [
15
+ "vUv",
16
+ "vUV",
17
+ "vUv0"
18
+ ], u = [
19
+ 1,
20
+ 0,
21
+ 0,
22
+ 0,
23
+ 0,
24
+ 1,
25
+ 0,
26
+ 0,
27
+ 0,
28
+ 0,
29
+ 1,
30
+ 0,
31
+ 0,
32
+ 0,
33
+ 0,
34
+ 1
35
+ ], d = [
36
+ 1,
37
+ 0,
38
+ 0,
39
+ 0,
40
+ 0,
41
+ 1,
42
+ 0,
43
+ 0,
44
+ 0,
45
+ 0,
46
+ -.5,
47
+ 0,
48
+ 0,
49
+ 0,
50
+ .5,
51
+ 1
52
+ ], f = new Float32Array(u), p = {
53
+ positions: [
54
+ -1,
55
+ -1,
56
+ 0,
57
+ 3,
58
+ -1,
59
+ 0,
60
+ -1,
61
+ 3,
62
+ 0
63
+ ],
64
+ uvs: [
65
+ 0,
66
+ 0,
67
+ 2,
68
+ 0,
69
+ 0,
70
+ 2
71
+ ]
72
+ }, m = (e, t, n) => RegExp(`\\b(?:uniform|varying|in)\\s+(?:(?:highp|mediump|lowp)\\s+)?${t}\\s+${n}\\b`).test(e);
73
+ function h(e, t) {
74
+ let n = /^\s*#\s*version\s+300\s+es\b/m.test(e) || t === 300, r = l.filter((t) => m(e, "vec2", t)), [i, a] = n ? ["in", "out"] : ["attribute", "varying"];
75
+ return `${n ? "#version 300 es\n" : ""}${i} vec3 position;\n${i} vec2 uv;\n${r.map((e) => `${a} vec2 ${e};\n`).join("")}void main() { ${r.map((e) => `${e} = uv; `).join("")}gl_Position = vec4(position.xy, 0.0, 1.0); }\n`;
76
+ }
77
+ var g = 0, _ = class l {coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);
78
+ constructor(e, t = {}) {
79
+ if (this.raw = new i({ name: "shader:glsl-pass:raw" }), this.disposed = !1, this.rect = "", this.context = {
80
+ format: "rgba8unorm",
81
+ descriptor: { multisample: { count: 1 } }
82
+ }, this.attachment = {
83
+ view: void 0,
84
+ loadOp: "clear",
85
+ storeOp: "store"
86
+ }, this.pass = { colorAttachments: [this.attachment] }, !e || typeof e != "object" || typeof e.fragmentShader != "string") throw TypeError("ShaderPass needs {fragmentShader}, with vertexShader and uniforms if the program has them");
87
+ let { kind: n = "ldr", name: r = "shader:glsl-pass:" + g++, input: l, ...u } = t;
88
+ if (n !== "hdr" && n !== "ldr") throw TypeError("ShaderPass kind must be 'hdr' or 'ldr'");
89
+ this.name = r, this.kind = n;
90
+ let d = e.fragmentShader, f = e.vertexShader ?? h(d, u.glslVersion);
91
+ if (this.input = l === void 0 ? c.find((e) => m(d, "sampler2D", e)) ?? null : l, this.material = new o({
92
+ outputColorSpace: n === "hdr" ? "linear" : "srgb",
93
+ blending: "none",
94
+ ...u,
95
+ vertexShader: f,
96
+ fragmentShader: d,
97
+ uniforms: { ...e.uniforms },
98
+ defines: { ...e.defines },
99
+ side: "double",
100
+ depthTest: !1,
101
+ depthWrite: !1,
102
+ name: r
103
+ }), this.input !== null && !this.material.program.textures.some((e) => e.name === this.input)) throw new s("failed", `ShaderPass input ${this.input} is not a sampler of the program; declare it or pass input: null`);
104
+ this.mesh = a(p, this.material, { frustumCulled: !1 });
105
+ }
106
+ static async attach(e, t, n = {}) {__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));
107
+ let { signal: i, ...a } = n;
108
+ i?.throwIfAborted();
109
+ let o = new l(t, a);
110
+ return o.stack = await r(e, o, i), o;
111
+ }
112
+ get uniforms() {
113
+ return this.material.uniforms;
114
+ }
115
+ joinStack(e) {
116
+ if (this.host || this.disposed) throw new s(this.disposed ? "disposed" : "attached", `${this.name} is already attached; create a new ShaderPass for another PostStack`);
117
+ return this.host = e, {
118
+ kind: this.kind,
119
+ render: (e, t, n) => this.render(e, t, n)
120
+ };
121
+ }
122
+ setup(e) {
123
+ if (!this.host || this.disposed) throw new s("state", "ShaderPass runs inside a PostStack: PostStack.attach(engine, [pass])");
124
+ if (!e.gpu) throw new s("unsupported", "ShaderPass requires WebGPU; use a WebGPU engine");
125
+ this.engine = e;
126
+ }
127
+ registerPasses() {}
128
+ ready() {
129
+ return this.raw.ready();
130
+ }
131
+ encoding(e) {
132
+ return e.includes("float") ? 0 : e.endsWith("-srgb") ? 2 : 1;
133
+ }
134
+ render(r, i, a) {
135
+ let o = r.device, s = this.material;
136
+ this.device !== o && this.release(), this.device = o, this.input !== null && (s.uniforms[this.input].value = i);
137
+ let c = this.camera ??= o.createBuffer({
138
+ label: this.name + ":camera",
139
+ size: 240,
140
+ usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
141
+ }), l = a.format, p = t(r), m = this.raw.cameraBlock(r.camera, d, r.width, r.height, r.delta, this.encoding(l), p);
142
+ m.set(u, 0), m.set(d, 16), m.fill(0, 48, 51), o.queue.writeBuffer(c, 0, m);
143
+ let h = p ? p.join() : "";
144
+ if (h !== this.rect && this.mesh.getAttribute("uv")) {
145
+ this.rect = h;
146
+ let [e, t, n, i] = p ?? [
147
+ 0,
148
+ 0,
149
+ r.width,
150
+ r.height
151
+ ], a = (e) => e / r.width, o = (e) => 1 - e / r.height;
152
+ this.mesh.setAttribute("uv", [
153
+ a(e),
154
+ o(t + i),
155
+ a(e + 2 * n),
156
+ o(t + i),
157
+ a(e),
158
+ o(t - i)
159
+ ]);
160
+ }
161
+ let g = this.mesh.upload(o, c, f), _ = s.prepare(o, this.raw.nextPass());
162
+ this.context.format = l, this.context.descriptor.multisample = a.multisample;
163
+ let v = s.pipeline(this.raw, _, o, this.mesh, "color", this.context);
164
+ this.attachment.view = a.view, this.attachment.loadOp = e(r);
165
+ let y = r.encoder.beginRenderPass(this.pass);
166
+ n(y, r), v && (y.setPipeline(v), y.setBindGroup(0, this.mesh.gpu.group), _.group && y.setBindGroup(1, _.group), _.extras.forEach((e, t) => y.setBindGroup(2 + t, e)), this.mesh.draw(y, g[0], g[1], g[2], { slots: [] })), y.end();
167
+ }
168
+ release() {
169
+ let e = this.device;
170
+ this.mesh.release(), e && (this.material.gpu.get(e)?.buffer?.destroy(), this.material.gpu.delete(e)), this.camera?.destroy(), this.camera = this.device = void 0;
171
+ }
172
+ onDeviceRestored() {
173
+ this.release();
174
+ }
175
+ dispose() {
176
+ if (this.disposed) return;
177
+ this.disposed = !0;
178
+ let e = this.engine, t = this.stack;
179
+ this.engine = this.stack = void 0, t?.removeEffect(this), this.release(), this.material.dispose(), this.mesh.dispose(), e?.sceneOf(this)?.removePlugin(this.name);
180
+ }
181
+ [Symbol.dispose ?? Symbol()]() {
182
+ this.dispose();
183
+ }
184
+ };
185
+ //#endregion
186
+ export { _ as ShaderPass, h as fullscreenVertex };
package/dist/glsl.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ import { Node, type NodeInput, type Type } from './node.js';
2
+ import { type BindableTexture } from './texture.js';
3
+ /** How {@link glslFn} and {@link glslToWGSL} read a GLSL source. */
4
+ export interface GLSLFnOptions {
5
+ /** The function to call. Default: the last function the source defines. */
6
+ readonly name?: string;
7
+ /** Object-like macros defined before the source, as `#define NAME value` lines. Default none. */
8
+ readonly defines?: Readonly<Record<string, string | number | boolean>>;
9
+ /** Flip y at every 2D texture lookup and texelFetch, for GLSL written for a bottom-left image origin. Default false. */
10
+ readonly flipY?: boolean;
11
+ /**
12
+ * Keep WGSL's derivative uniformity rule: a texture sample or derivative inside a branch on a per-pixel value is a
13
+ * compile error. Default false: translated functions turn the rule off, so sampling there behaves as GLSL defines it.
14
+ */
15
+ readonly strict?: boolean;
16
+ }
17
+ /** The texture dimension a GLSL sampler parameter takes. */
18
+ export type GLSLSamplerDimension = '2d' | 'cube' | '3d' | '2d-array';
19
+ /** A parameter of a translated GLSL function. */
20
+ export interface GLSLParameter {
21
+ readonly name: string;
22
+ /** Its GLSL type, as written (`vec3`, `sampler2D`). */
23
+ readonly glsl: string;
24
+ /** Its node type (`vec3f`), or the texture dimension a sampler parameter takes. */
25
+ readonly type: Type | GLSLSamplerDimension;
26
+ }
27
+ /** A GLSL function translated to WGSL by {@link glslToWGSL}. */
28
+ export interface GLSLFunction {
29
+ /** WGSL declarations: the translated functions and an entry that calls the chosen one. */
30
+ readonly code: string;
31
+ /** The WGSL entry's name. A sampler parameter takes two WGSL arguments, the texture and its sampler. */
32
+ readonly name: string;
33
+ readonly params: readonly GLSLParameter[];
34
+ /** The node type the function returns. */
35
+ readonly result: Type;
36
+ }
37
+ /** Translations made, for work-count tests: one per distinct source, options and sampling stage. @internal */
38
+ export declare const glslTranslations: {
39
+ count: number;
40
+ };
41
+ /**
42
+ * Translates one GLSL ES 3.00 or 1.00 function (with any helpers, structs and constants it uses) to WGSL, once per
43
+ * distinct source and options. A source without `#version` reads as GLSL ES 3.00. Inputs are the function's
44
+ * parameters: a uniform or a `gl_` built-in inside the source is refused, pass it as an argument.
45
+ * @param stage 'fragment' samples with implicit derivatives; any other stage samples level 0, as `texture()` does.
46
+ * @throws MargoError `failed` (with `line` and `column` for a syntax error or a refused name); TypeError for bad
47
+ * options. MargoError `unsupported` for a `#version` other than 100 and 300 es.
48
+ */
49
+ export declare function glslToWGSL(code: string, options?: GLSLFnOptions, stage?: 'fragment' | 'vertex' | 'compute'): GLSLFunction;
50
+ /**
51
+ * Turns a GLSL function into a node function, as `wgslFn` does for WGSL: the same source runs on WebGPU and on the
52
+ * WebGL2 layer. Call the result with one node or number per parameter, or a `Texture` from `@margoengine/materials`
53
+ * for a sampler parameter. Translation happens here, once per source; errors surface at this call.
54
+ */
55
+ export declare function glslFn<R extends Type = Type>(code: string, options?: GLSLFnOptions): (...args: (NodeInput | boolean | BindableTexture)[]) => Node<R>;
56
+ /** One stage {@link toGLSL} hands to the WebGL2 layer's translator. */
57
+ export interface ToGLSLStage {
58
+ readonly source: string;
59
+ readonly entryPoint?: string;
60
+ }
61
+ /** What {@link toGLSL} hands to the WebGL2 layer's translator (`translateWGSL` of `@margoengine/webgl2-compat/glsl`). */
62
+ export interface ToGLSLInput extends ToGLSLOptions {
63
+ readonly vertex: ToGLSLStage;
64
+ readonly fragment?: ToGLSLStage;
65
+ }
66
+ /** Options of {@link toGLSL}: the layer's own translation options, with its defaults. */
67
+ export interface ToGLSLOptions {
68
+ /** The context clips z to [0, w] (EXT_clip_control). Default true. */
69
+ readonly clipControl?: boolean;
70
+ /** The pipeline draws points. Default false. */
71
+ readonly points?: boolean;
72
+ /** Bytes a GLSL uniform block holds. Default 65,536. */
73
+ readonly uniformBlockSize?: number;
74
+ /** acos, asin and atan2 use the layer's float32 versions. Default false. */
75
+ readonly accurateInverseTrig?: boolean;
76
+ }
77
+ /** The WebGL2 layer's translator, as `await import('@margoengine/webgl2-compat/glsl')` gives it. */
78
+ export interface GLSLTranslator<R> {
79
+ translateWGSL(input: ToGLSLInput): R;
80
+ }
81
+ /** What {@link toGLSL} translates: a NodePass, a NodeMaterial that has drawn, or WGSL stages. */
82
+ export type ToGLSLTarget = {
83
+ code(): string;
84
+ } | object | {
85
+ readonly vertex: string;
86
+ readonly fragment?: string;
87
+ };
88
+ /**
89
+ * The GLSL ES 3.00 program the WebGL2 layer makes from a NodePass, a NodeMaterial (after it has drawn once) or WGSL
90
+ * stages, with each stage's binding tables. The caller supplies the layer's translator,
91
+ * `await import('@margoengine/webgl2-compat/glsl')`, so this entry never loads the layer itself.
92
+ * @throws MargoError `state` for a NodeMaterial that has not drawn yet; TypeError for another target.
93
+ */
94
+ export declare function toGLSL<R>(target: ToGLSLTarget, glsl: GLSLTranslator<R>, options?: ToGLSLOptions): R;
package/dist/glsl.js ADDED
@@ -0,0 +1,170 @@
1
+ import { T as e, o as t, tn as n } from "./node-DzKv9CF2.js";
2
+ import { t as r } from "./texture-D6vy0bam.js";
3
+ import { t as i } from "./errors-CsQwshHA.js";
4
+ import { n as a, r as o, t as s } from "./preprocess-CWGWlBWQ.js";
5
+ //#region src/glsl.ts
6
+ var c = {
7
+ float: "f32",
8
+ int: "i32",
9
+ uint: "u32",
10
+ bool: "bool"
11
+ }, l = (e) => {
12
+ let t = /^([ibu]?)vec([234])$/.exec(e);
13
+ if (t) return t[1] === "b" ? `vec${t[2]}<bool>` : `vec${t[2]}${t[1] || "f"}`;
14
+ let n = /^mat([234])$/.exec(e);
15
+ return n ? `mat${n[1]}x${n[1]}f` : c[e];
16
+ }, u = {
17
+ sampler2D: "2d",
18
+ samplerCube: "cube",
19
+ sampler3D: "3d",
20
+ sampler2DArray: "2d-array"
21
+ }, d = /^[A-Za-z_]\w*$/, f = (e, t, n) => {
22
+ let r = e.slice(0, t);
23
+ return {
24
+ line: r.split("\n").length - n,
25
+ column: t - r.lastIndexOf("\n")
26
+ };
27
+ }, p = /* @__PURE__ */ new Map(), m = 0, h = { count: 0 }, g = (e) => (t, n, r, i) => {
28
+ let a = n === "sampler2DArray" ? `${r}.xy,i32(round(${r}.z))` : r, o = i.offset ? `,${i.offset}` : "", s = `${t},${t}s,${a}`;
29
+ return i.lod ? `textureSampleLevel(${s},${i.lod}${o})` : i.ddx ? `textureSampleGrad(${s},${i.ddx},${i.ddy}${o})` : e ? i.bias ? `textureSampleBias(${s},${i.bias}${o})` : `textureSample(${s}${o})` : `textureSampleLevel(${s},0.0${o})`;
30
+ };
31
+ function _(e, t = {}, n = "fragment") {
32
+ if (typeof e != "string" || !e.trim() || e.length > 65536) throw TypeError("glslToWGSL needs 1..65536 code units of GLSL source with a function in it");
33
+ let { name: r, defines: c = {}, flipY: _ = !1, strict: v = !1 } = t ?? {};
34
+ if (r !== void 0 && (typeof r != "string" || !d.test(r))) throw TypeError("glslFn name must be a GLSL identifier");
35
+ if (typeof _ != "boolean" || typeof v != "boolean") throw TypeError("glslFn flipY and strict must be booleans");
36
+ if (typeof c != "object" || !c) throw TypeError("glslFn defines must be an object");
37
+ for (let [e, t] of Object.entries(c)) if (!d.test(e) || ![
38
+ "string",
39
+ "number",
40
+ "boolean"
41
+ ].includes(typeof t) || /[\r\n\\]/.test(String(t))) throw TypeError(`glslFn define ${e} needs an identifier and a one-line string, number or boolean`);
42
+ let y = n === "fragment", b = JSON.stringify([
43
+ e,
44
+ r ?? null,
45
+ c,
46
+ _,
47
+ v,
48
+ y
49
+ ]), x = p.get(b);
50
+ if (x) return x;
51
+ let S = [.../^\s*#\s*version\b/m.test(e) ? [] : ["#version 300 es"], ...Object.entries(c).map(([e, t]) => `#define ${e} ${typeof t == "boolean" ? +t : t}`)], C = { version: 100 }, w = s(S.length ? S.join("\n") + "\n" + e : e, C), T = S.length, E = (e, t) => {
52
+ throw Object.assign(i("failed", `glslFn: ${e}`), f(w, t, S.length));
53
+ }, D;
54
+ try {
55
+ D = new o(w, "GLSL function").parse();
56
+ } catch (e) {
57
+ throw typeof e?.line == "number" && (e.line -= S.length), e;
58
+ }
59
+ let O = /\buniform\b/.exec(w);
60
+ O && E("a uniform is not available inside a function; pass it as an argument", O.index);
61
+ let k = /\bgl_\w+/.exec(w);
62
+ k && E(`${k[0]} is not available inside a function; pass it as an argument`, k.index);
63
+ let A = (e) => {
64
+ let t = T;
65
+ for (let n of w.matchAll(new RegExp(e, "g"))) t = n.index;
66
+ return t;
67
+ }, j = D.functions.filter((e) => e.body && (r === void 0 || e.name === r)).at(-1) ?? E(r === void 0 ? "the source defines no function" : `the source defines no function ${r}`, T), M = A(String.raw`\b${j.name}\s*\(`), N = j.params.map((e) => {
68
+ if (/\b(out|inout)\b/.test(e.qualifier)) return E(`parameter ${e.name} of ${j.name} is ${e.qualifier}; the called function takes inputs only`, M);
69
+ let t = u[e.type] ?? l(e.type);
70
+ return t ? {
71
+ name: e.name,
72
+ glsl: e.type,
73
+ type: t
74
+ } : E(`parameter ${e.name} has type ${e.type}; use a scalar, vector, square matrix or sampler`, M);
75
+ }), P = l(j.type) ?? E(`${j.name} returns ${j.type}; return a scalar, vector or square matrix`, M);
76
+ h.count++;
77
+ let F = `glsl${m++}_`, I = {
78
+ uniforms: {},
79
+ flipY: _,
80
+ names: {},
81
+ colorReaders: {},
82
+ prologue: "",
83
+ sample: g(y),
84
+ entry: {
85
+ name: j.name,
86
+ type: j.type,
87
+ params: j.params.map((e) => e.type)
88
+ },
89
+ missingEntry: `Define ${j.name}`,
90
+ epilogue: (e) => {
91
+ let t = N.map((e, t) => e.glsl in u ? `a${t}:texture_${e.type.replace("-", "_")}<f32>,a${t}s:sampler` : `a${t}:${e.type}`), n = N.map((e, t) => e.glsl in u ? `a${t},a${t}s` : `a${t}`);
92
+ return `fn user_entry(${t.join(",")})->${P}{return ${e}(${n.join(",")});}`;
93
+ }
94
+ }, L = new a(D, I, C.version).emit();
95
+ L = L.replace(/\buser_/g, F).replace(/\baggregate_equal_/g, F + "equal_").replace(/\bmargo_inverse/g, F + "inverse"), v || (L = L.replace(/^fn /gm, "@diagnostic(off,derivative_uniformity) fn "));
96
+ let R = {
97
+ code: L,
98
+ name: F + "entry",
99
+ params: N,
100
+ result: P
101
+ };
102
+ return p.size >= 256 && p.delete(p.keys().next().value), p.set(b, R), R;
103
+ }
104
+ function v(t, n) {
105
+ let i = r("glslFn", n, t, e(0, "f32"), void 0), a;
106
+ return i.emit({
107
+ resource: (e) => (a = e, "r"),
108
+ expr: () => "0",
109
+ stage: {
110
+ kind: "vertex",
111
+ builtins: {}
112
+ }
113
+ }, i), a;
114
+ }
115
+ function y(r, i = {}) {
116
+ let a = _(r, i), o = n();
117
+ return (...n) => {
118
+ if (n.length !== a.params.length) throw TypeError(`glslFn ${a.name}: ${a.params.length} arguments expected, got ${n.length}`);
119
+ let s = [], c = [];
120
+ a.params.forEach((r, i) => {
121
+ let a = n[i], o = `glslFn argument ${i + 1} (${r.name})`;
122
+ if (r.glsl in u) c.push(v(a, r.type));
123
+ else if (!(a instanceof t) && (typeof a != (r.type === "bool" ? "boolean" : "number") || /^mat/.test(r.type))) throw TypeError(`${o} must be a node${/^mat/.test(r.type) ? "" : " or a " + (r.type === "bool" ? "boolean" : "number")}`);
124
+ else s.push(e(a, r.type, o));
125
+ });
126
+ let l = `g${o}:${c.map((e) => e.id).join(",")}`;
127
+ return new t(a.result, l, s, (e, t) => {
128
+ let n = e.stage.kind, a = _(r, i, n === "fragment" || n === "post" ? "fragment" : "vertex");
129
+ e.declare("glsl#" + a.name, a.code);
130
+ let o = 0, s = 0, l = a.params.map((n) => {
131
+ if (!(n.glsl in u)) return e.expr(t.args[o++]);
132
+ let r = e.resource(c[s++]);
133
+ return `${r}, ${r}s`;
134
+ });
135
+ return `${a.name}(${l.join(", ")})`;
136
+ });
137
+ };
138
+ }
139
+ function b(e, t, n = {}) {
140
+ if (typeof t?.translateWGSL != "function") throw TypeError("toGLSL needs the layer's translator: toGLSL(target, await import('@margoengine/webgl2-compat/glsl'))");
141
+ let r = e, a, o;
142
+ if (r?.patched instanceof Map) {
143
+ let e = [...(r.patchedOutputs instanceof Map && r.patchedOutputs.size ? r.patchedOutputs : r.patched).values()].at(-1);
144
+ if (e === void 0) throw i("state", "toGLSL needs a NodeMaterial that has drawn once; render a frame with it first");
145
+ a = {
146
+ source: e,
147
+ entryPoint: "vertex"
148
+ }, o = {
149
+ source: e,
150
+ entryPoint: "fragment"
151
+ };
152
+ } else if (typeof r?.code == "function") {
153
+ let e = r.code();
154
+ a = {
155
+ source: e,
156
+ entryPoint: "vertex"
157
+ }, o = {
158
+ source: e,
159
+ entryPoint: "fragment"
160
+ };
161
+ } else if (typeof r?.vertex == "string" && (r.fragment === void 0 || typeof r.fragment == "string")) a = { source: r.vertex }, o = r.fragment === void 0 ? void 0 : { source: r.fragment };
162
+ else throw TypeError("toGLSL needs a NodePass, a NodeMaterial or { vertex, fragment } WGSL; pass one of them");
163
+ return t.translateWGSL({
164
+ ...n,
165
+ vertex: a,
166
+ ...o ? { fragment: o } : {}
167
+ });
168
+ }
169
+ //#endregion
170
+ export { y as glslFn, _ as glslToWGSL, h as glslTranslations, b as toGLSL };
@@ -0,0 +1,31 @@
1
+ (globalThis[Symbol.for("margoengine.frame-resources")] ??= { devices: /* @__PURE__ */ new WeakMap() }).devices;
2
+ //#endregion
3
+ //#region ../shared/gpu.js
4
+ var e = "\nstruct Vertex { @builtin(position) position:vec4f,@location(0) uv:vec2f }\n@vertex fn vertex(@builtin(vertex_index) index:u32)->Vertex {\n let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[index];\n return Vertex(vec4f(p,0,1),vec2f(p.x*0.5+0.5,0.5-p.y*0.5));\n}";
5
+ function t(e, t, n, r = {}) {
6
+ let i = e.createShaderModule({ code: t });
7
+ return e.createRenderPipeline({
8
+ layout: "auto",
9
+ vertex: {
10
+ module: i,
11
+ entryPoint: "vertex"
12
+ },
13
+ fragment: {
14
+ module: i,
15
+ entryPoint: "fragment",
16
+ targets: [{ format: n }]
17
+ },
18
+ ...r
19
+ });
20
+ }
21
+ function n(e, t, n = "main") {
22
+ return e.createComputePipeline({
23
+ layout: "auto",
24
+ compute: {
25
+ module: e.createShaderModule({ code: t }),
26
+ entryPoint: n
27
+ }
28
+ });
29
+ }
30
+ //#endregion
31
+ export { e as n, t as r, n as t };
@@ -0,0 +1,82 @@
1
+ import * as s from './node.js';
2
+ import { NodeMaterial, type NodeMaterialOptions } from './material.js';
3
+ /** Portable, bounded surface expression operations. Inputs are ordered node ids. */
4
+ export type SurfaceOperation = 'float' | 'vec3' | 'position' | 'worldPosition' | 'normal' | 'worldNormal' | 'color' | 'uv' | 'add' | 'sub' | 'mul' | 'div' | 'min' | 'max' | 'pow' | 'mix' | 'clamp' | 'sin' | 'cos' | 'abs' | 'floor' | 'fract' | 'saturate' | 'length' | 'dot' | 'normalize' | 'component' | 'combine';
5
+ /** One expression; numeric values are immutable constants exposed as authoring parameters. */
6
+ export interface SurfaceGraphNode {
7
+ id: string;
8
+ op: SurfaceOperation;
9
+ inputs: string[];
10
+ value?: number | [number, number, number];
11
+ }
12
+ /** Constant physical values used by hosts that cannot execute surface graphs. RGB is linear. */
13
+ export interface SurfaceFallback {
14
+ color: [number, number, number];
15
+ emissive: [number, number, number];
16
+ roughness: number;
17
+ metalness: number;
18
+ opacity: number;
19
+ }
20
+ /** Material output slots. An absent slot keeps the host material's existing value. */
21
+ export interface SurfaceOutputs {
22
+ color?: string;
23
+ roughness?: string;
24
+ metalness?: string;
25
+ emissive?: string;
26
+ opacity?: string;
27
+ normal?: string;
28
+ }
29
+ /** Versioned JSON surface graph; arbitrary source code and resource access are intentionally absent. */
30
+ export interface SurfaceGraph {
31
+ version: 1;
32
+ nodes: SurfaceGraphNode[];
33
+ outputs: SurfaceOutputs;
34
+ fallback: SurfaceFallback;
35
+ }
36
+ /** Hard work limits applied before native node construction. */
37
+ export declare const SURFACE_GRAPH_LIMITS: Readonly<{
38
+ nodes: 128;
39
+ depth: 32;
40
+ work: 2048;
41
+ jsonBytes: 65536;
42
+ }>;
43
+ /** The operation catalog shared by graph editors and validators. */
44
+ export declare const SURFACE_OPERATIONS: Readonly<Record<SurfaceOperation, number>>;
45
+ /** Stage inputs substituted by a non-material graph host; every input is a vec3f. */
46
+ export type SurfaceGraphInputs = Partial<Record<'position' | 'worldPosition' | 'normal' | 'worldNormal' | 'color' | 'uv', s.Node<'vec3f'>>>;
47
+ /** Validate structure, cycles, all node types and bounded work using Margo's native typed nodes. */
48
+ export declare function validateSurfaceGraph(value: unknown): asserts value is SurfaceGraph;
49
+ /** Validated output type of every editable node, including disconnected nodes. */
50
+ export declare function inspectSurfaceGraph(value: SurfaceGraph): {
51
+ types: Record<string, 'f32' | 'vec3f'>;
52
+ };
53
+ /** Stable canonical JSON. Node array order is preserved for authoring; object key order is normalized. */
54
+ export declare function serializeSurfaceGraph(value: SurfaceGraph): string;
55
+ /** Parse a portable graph with a bounded input size, returning an independent canonical snapshot. */
56
+ export declare function parseSurfaceGraph(json: string): SurfaceGraph;
57
+ /** Compile graph outputs to native NodeMaterial options; omitted outputs retain material values. */
58
+ export declare function compileSurfaceGraph(value: SurfaceGraph, inputs?: SurfaceGraphInputs): Pick<NodeMaterialOptions, 'colorNode' | 'roughnessNode' | 'metalnessNode' | 'emissiveNode' | 'opacityNode' | 'normalNode'>;
59
+ /** Construct a native Margo surface material. Only the standard PBR raster host executes the graph. */
60
+ export declare function createGraphMaterial(graph: SurfaceGraph, options?: NodeMaterialOptions): NodeMaterial;
61
+ /** Coordinates and original material values supplied by a texture/voxel baking host. RGB is linear. */
62
+ export interface SurfaceSample {
63
+ position: readonly number[];
64
+ normal: readonly number[];
65
+ worldPosition?: readonly number[];
66
+ worldNormal?: readonly number[];
67
+ color?: readonly number[];
68
+ uv?: readonly number[];
69
+ }
70
+ /** Evaluated surface values in linear space. Normal is in world coordinates when supplied by the graph. */
71
+ export interface SurfaceEvaluation {
72
+ color?: [number, number, number];
73
+ emissive?: [number, number, number];
74
+ roughness?: number;
75
+ metalness?: number;
76
+ opacity?: number;
77
+ normal?: [number, number, number];
78
+ }
79
+ /** Compile a deterministic CPU sampler once for many bake texels. Native node validation and semantics are shared. Nonfinite results reject the bake. */
80
+ export declare function surfaceGraphSampler(value: SurfaceGraph): (sample: SurfaceSample) => SurfaceEvaluation;
81
+ /** Evaluate a single sample. For bulk texture baking use surfaceGraphSampler to validate once. */
82
+ export declare function evaluateSurfaceGraph(graph: SurfaceGraph, sample: SurfaceSample): SurfaceEvaluation;