@skathi-native/cli 0.1.0-beta.3 → 0.2.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.
- package/aot-inputs.ts +21 -2
- package/build.ts +241 -60
- package/check/bundle.ts +265 -0
- package/check/codes.ts +19 -0
- package/check/command.ts +5 -3
- package/check/graph.ts +3 -1
- package/check/index.ts +54 -2
- package/check/program.ts +26 -6
- package/cli/aot-build.ts +10 -7
- package/cli/build-app.ts +37 -8
- package/cli/config.ts +2 -2
- package/cli/create.ts +31 -8
- package/cli/dev.ts +109 -19
- package/cli/effects.ts +162 -0
- package/cli/elf.ts +3 -2
- package/cli/help.ts +56 -147
- package/cli/host-fetch.ts +33 -10
- package/cli/host.ts +43 -33
- package/cli/sk.ts +437 -234
- package/cli/skpk.ts +2 -0
- package/cli/stamp.ts +2 -2
- package/cli/term.ts +169 -38
- package/cli/workload-cache.ts +258 -0
- package/devtools/commands.ts +25 -0
- package/effects/compile.ts +1081 -0
- package/effects/redslangc.json +23 -0
- package/effects/redslangc.ts +220 -0
- package/effects/sk.slang +882 -0
- package/package.json +10 -4
- package/prod.ts +40 -7
- package/svelte.ts +76 -0
- package/templates/icon.png +0 -0
- package/templates/minimal/src/App.vue +2 -2
- package/templates/showcase/assets/textures/golden.png +0 -0
- package/templates/showcase/assets/textures/hammered.png +0 -0
- package/templates/showcase/assets/textures/noir.png +0 -0
- package/templates/showcase/assets/textures/reeded.png +0 -0
- package/templates/showcase/assets/textures/teal-orange.png +0 -0
- package/templates/showcase/shaders/dissolve.slang +40 -0
- package/templates/showcase/shaders/fireflies.slang +58 -0
- package/templates/showcase/shaders/glass.slang +31 -0
- package/templates/showcase/shaders/grade.slang +34 -0
- package/templates/showcase/shaders/halftone.slang +42 -0
- package/templates/showcase/shaders/lens.slang +51 -0
- package/templates/showcase/shaders/nebula.slang +57 -0
- package/templates/showcase/shaders/orbit.slang +52 -0
- package/templates/showcase/shaders/pond.slang +76 -0
- package/templates/showcase/shaders/ripples.slang +71 -0
- package/templates/showcase/shaders/shatter.slang +116 -0
- package/templates/showcase/shaders/sheen.slang +23 -0
- package/templates/showcase/shaders/snow.slang +57 -0
- package/templates/showcase/shaders/spotlight.slang +52 -0
- package/templates/showcase/src/App.vue +11 -16
- package/templates/showcase/src/components/FullWindow.vue +77 -0
- package/templates/showcase/src/components/Page.vue +2 -0
- package/templates/showcase/src/fullwindow.ts +36 -0
- package/templates/showcase/src/icons.ts +2 -0
- package/templates/showcase/src/pages/GraphicsPage.vue +122 -0
- package/templates/showcase/src/pages/MotionPage.vue +71 -1
- package/templates/showcase/src/pages/ShadersPage.vue +443 -0
- package/templates/showcase/src/pages/StylesPage.vue +9 -1
- package/templates/showcase/src/router.ts +32 -1
- package/templates/showcase/src/styles.css +2 -2
- package/templates/svelte/.vscode/settings.json +3 -0
- package/templates/svelte/assets/hello.txt +1 -0
- package/templates/svelte/src/App.svelte +142 -0
- package/templates/svelte/src/main.ts +4 -0
- package/vitecompat.ts +2 -0
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
// Effect shader compiler: `.slang` -> one fragment stage per renderer target (`TARGETS`: HLSL for
|
|
2
|
+
// DirectX, WGSL for gpui_wgpu, MSL for Metal) + a reflected schema (`effects.json`), through redslangc.
|
|
3
|
+
// `sk build`, `sk dev` and `sk check` run it over an app's shaders/*.slang; scripts/shaders.ts over the
|
|
4
|
+
// built-ins.
|
|
5
|
+
//
|
|
6
|
+
// An effect author writes one struct (`[SkEffect("ripple")] struct Ripple : IEffect { ... }`).
|
|
7
|
+
// The reflection of its attributes, field order and types is the single source of truth for the CSS
|
|
8
|
+
// function name, argument order, packing slots, types, defaults and flags, so a new effect needs no
|
|
9
|
+
// registration in Rust or JS.
|
|
10
|
+
//
|
|
11
|
+
// The vertex stage is hand-written per renderer (gpui_windows/src/effects.hlsl,
|
|
12
|
+
// gpui_wgpu/src/shaders_effects.wgsl): gpui clips with `float4 : SV_ClipDistance` and no spelling of
|
|
13
|
+
// that survives both Slang's front end and fxc.
|
|
14
|
+
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
17
|
+
import { availableParallelism } from "node:os";
|
|
18
|
+
import { basename, join, relative } from "node:path";
|
|
19
|
+
import { PIN, ShaderCompilerError } from "./redslangc";
|
|
20
|
+
|
|
21
|
+
/// Bumped when the prelude or generated wrapper changes codegen or schema shape; rides in every
|
|
22
|
+
/// header and effects.json. Rust refuses an effects.json with an unknown schema.
|
|
23
|
+
export const SCHEMA = 10;
|
|
24
|
+
|
|
25
|
+
export const PRELUDE = join(import.meta.dir, "sk.slang");
|
|
26
|
+
|
|
27
|
+
/// The built-in numbering is a contract: this list, `gpui::effect_id`, the pipeline tables in
|
|
28
|
+
/// `gpui_windows` and `gpui_wgpu`, and the ids in `crates/sk-effects/generated/effects.json`. It is not alphabetical.
|
|
29
|
+
export const BUILTIN_EFFECTS = ["frost", "noise", "glow"];
|
|
30
|
+
|
|
31
|
+
/// Floats per instance (`EffectQuad::params`); raising it widens every effect quad.
|
|
32
|
+
const PARAM_SLOTS = 32;
|
|
33
|
+
|
|
34
|
+
const ENTRY = "effect_fragment";
|
|
35
|
+
|
|
36
|
+
export type TargetName = "hlsl" | "wgsl" | "metal";
|
|
37
|
+
|
|
38
|
+
/// One renderer's shading language. `name` is the effects.json key naming each effect's file and the
|
|
39
|
+
/// file's extension, which is how a renderer finds its own.
|
|
40
|
+
interface Target {
|
|
41
|
+
name: TargetName;
|
|
42
|
+
/// redslangc's `--target`.
|
|
43
|
+
spec: string;
|
|
44
|
+
/// The last lines of the generated header: what the renderer adds to this fragment stage.
|
|
45
|
+
note: () => string;
|
|
46
|
+
/// Refuses code the renderer's pipeline layout cannot run.
|
|
47
|
+
check: (code: string, file: string) => void;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const TARGETS: Target[] = [
|
|
51
|
+
{
|
|
52
|
+
name: "hlsl",
|
|
53
|
+
spec: "hlsl:sm_5_0",
|
|
54
|
+
note: () =>
|
|
55
|
+
`// Compiled at ps_5_0 (effects only — the core gpui shaders stay at ps_4_1).\n` +
|
|
56
|
+
`// The VERTEX half lives in gpui_windows/src/effects.hlsl and is shared by\n` +
|
|
57
|
+
`// every effect; Slang cannot author it (SV_ClipDistance, see that file).\n`,
|
|
58
|
+
check: () => {},
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: "wgsl",
|
|
62
|
+
spec: "wgsl",
|
|
63
|
+
note: () =>
|
|
64
|
+
`// The VERTEX half lives in gpui_wgpu/src/shaders_effects.wgsl and is shared\n` +
|
|
65
|
+
`// by every effect; it clips the quad to the content mask.\n`,
|
|
66
|
+
check: checkWgslBindings,
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "metal",
|
|
70
|
+
spec: "metal",
|
|
71
|
+
note: () => METAL_NOTE,
|
|
72
|
+
check: checkMetal,
|
|
73
|
+
},
|
|
74
|
+
];
|
|
75
|
+
|
|
76
|
+
// Group 0 the globals, 1 the instance buffer, 2 the backdrop, its sampler and the snapshot, the
|
|
77
|
+
// `SkTexture` images (3..6), the element's content (7) and history (8), and the images' repeating
|
|
78
|
+
// sampler (9).
|
|
79
|
+
const WGSL_BINDINGS = new Set(["0:0", "1:0", "2:0", "2:1", "2:2", "2:3", "2:4", "2:5", "2:6", "2:7", "2:8", "2:9"]);
|
|
80
|
+
|
|
81
|
+
/// The renderer builds one pipeline layout for every effect; a resource outside it would fail at
|
|
82
|
+
/// pipeline creation on the user's machine, so refuse it here.
|
|
83
|
+
function checkWgslBindings(code: string, file: string) {
|
|
84
|
+
for (const m of code.matchAll(/@binding\((\d+)\)\s*@group\((\d+)\)\s*var(?:<[^>]*>)?\s+(\w+)/g)) {
|
|
85
|
+
if (!WGSL_BINDINGS.has(`${m[2]}:${m[1]}`)) {
|
|
86
|
+
throw new SchemaError(
|
|
87
|
+
`${basename(file)}: \`${m[3]}\` needs @group(${m[2]}) @binding(${m[1]}) in wgsl, which the ` +
|
|
88
|
+
"engine does not provide — an effect reads only `EffectInput` and its own parameters, it " +
|
|
89
|
+
"cannot declare textures, samplers or buffers of its own",
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// The prelude's resources on Metal, where Slang keeps the HLSL registers (b0, t1, t0, t2, t3..t8, s1, s2). One
|
|
96
|
+
/// argument table for every effect, so the renderer binds these and nothing else.
|
|
97
|
+
const METAL_BINDINGS: Array<[at: string, name: string, what: string]> = [
|
|
98
|
+
["buffer(0)", "GlobalParams", "constant, the 48-byte globals"],
|
|
99
|
+
["buffer(1)", "sk_effect_quads", "device EffectQuad[], 224 bytes each"],
|
|
100
|
+
["texture(0)", "sk_backdrop_input", "the blurred backdrop"],
|
|
101
|
+
["texture(2)", "sk_backdrop_original", "the render-target snapshot"],
|
|
102
|
+
["texture(7)", "sk_content", "the element's content"],
|
|
103
|
+
["texture(8)", "sk_history", "the effect's history"],
|
|
104
|
+
["sampler(1)", "sk_clamp_sampler", "clamp to edge"],
|
|
105
|
+
["texture(3)", "sk_texture0", "the first SkTexture"],
|
|
106
|
+
["texture(4)", "sk_texture1", "the second SkTexture"],
|
|
107
|
+
["texture(5)", "sk_texture2", "the third SkTexture"],
|
|
108
|
+
["texture(6)", "sk_texture3", "the fourth SkTexture"],
|
|
109
|
+
["sampler(2)", "sk_repeat_sampler", "repeat"],
|
|
110
|
+
];
|
|
111
|
+
|
|
112
|
+
/// Refuses Metal output whose entry point or arguments are not the ones the renderer provides.
|
|
113
|
+
function checkMetal(code: string, file: string): void {
|
|
114
|
+
const entry = new RegExp(`\\[\\[fragment\\]\\]\\s+\\w+\\s+${ENTRY}\\s*\\(([^{]*)\\)\\s*\\{`).exec(code);
|
|
115
|
+
if (!entry) throw new SchemaError(`${basename(file)}: the Metal output has no \`[[fragment]] ${ENTRY}\``);
|
|
116
|
+
if (!/\[\[flat\]\]\s+uint\s+sk_id_\d+\s+\[\[user\(TEXCOORD\)\]\]/.test(code)) {
|
|
117
|
+
throw new SchemaError(`${basename(file)}: the Metal stage_in is not \`[[flat]] uint sk_id [[user(TEXCOORD)]]\``);
|
|
118
|
+
}
|
|
119
|
+
for (const m of entry[1]!.matchAll(/(\w+)\s*\[\[\s*((?:buffer|texture|sampler)\(\d+\))\s*\]\]/g)) {
|
|
120
|
+
const name = m[1]!.replace(/_\d+$/, "");
|
|
121
|
+
if (!METAL_BINDINGS.some(([at, n]) => n === name && at === m[2])) {
|
|
122
|
+
throw new SchemaError(
|
|
123
|
+
`${basename(file)}: \`${m[1]}\` is bound to [[${m[2]}]] in metal, which the engine does not provide — ` +
|
|
124
|
+
"an effect reads only `EffectInput` and its own parameters, it cannot declare textures, samplers or " +
|
|
125
|
+
"buffers of its own",
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const METAL_NOTE =
|
|
132
|
+
`// Entry point \`[[fragment]] ${ENTRY}\`. Its [[stage_in]] is the vertex half's\n` +
|
|
133
|
+
`// \`[[flat]] uint sk_id [[user(TEXCOORD)]]\`, beside [[position]]; it writes a\n` +
|
|
134
|
+
`// premultiplied [[color(0)]]. Arguments, the same for every effect:\n` +
|
|
135
|
+
METAL_BINDINGS.map(([at, name, what]) => `// [[${at}]]`.padEnd(20) + `${name.padEnd(22)}${what}\n`).join("") +
|
|
136
|
+
`// The VERTEX half is the Metal renderer's own, shared by every effect.\n`;
|
|
137
|
+
|
|
138
|
+
type ParamKind = "number" | "length" | "color" | "texture";
|
|
139
|
+
|
|
140
|
+
type ParamSchema = {
|
|
141
|
+
name: string;
|
|
142
|
+
kind: ParamKind;
|
|
143
|
+
/// A texture's first slot holds its width and the next its height, which the host writes.
|
|
144
|
+
slot: number;
|
|
145
|
+
required: boolean;
|
|
146
|
+
/// A texture's is what it reads as while missing, straight RGBA.
|
|
147
|
+
default: [number, number, number, number];
|
|
148
|
+
range: [number, number] | null;
|
|
149
|
+
/// A texture's binding, 0..3 (t3..t6), in declaration order.
|
|
150
|
+
texture?: number;
|
|
151
|
+
/// A texture sampled as stored, without premultiplying ([SkLinear]).
|
|
152
|
+
linear?: boolean;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/// `SkTexture` fields per effect: the bindings the renderers provide.
|
|
156
|
+
const TEXTURE_SLOTS = 4;
|
|
157
|
+
|
|
158
|
+
export type EffectSchema = {
|
|
159
|
+
name: string;
|
|
160
|
+
struct: string;
|
|
161
|
+
doc: string | null;
|
|
162
|
+
backdrop: boolean;
|
|
163
|
+
/// `[SkContent]`: drawn in place of its element's own painting, which it reads.
|
|
164
|
+
content: boolean;
|
|
165
|
+
/// `[SkHistory]`: keeps state per element from frame to frame.
|
|
166
|
+
history: boolean;
|
|
167
|
+
params: ParamSchema[];
|
|
168
|
+
backdropRadiusParam: number | null;
|
|
169
|
+
bleedParam: number | null;
|
|
170
|
+
animatedParam: number | null;
|
|
171
|
+
/// `[SkPointer]`'s first slot: the host writes the pointer there; not a CSS argument.
|
|
172
|
+
pointerParam: number | null;
|
|
173
|
+
/// `[SkPointerTimes]`'s first slot, host-filled like `pointerParam`.
|
|
174
|
+
pointerTimesParam: number | null;
|
|
175
|
+
/// Every slot of an `[SkAnimatedFor]` field: times on the effect clock.
|
|
176
|
+
clockSlots: number[];
|
|
177
|
+
/// The longest `[SkAnimatedFor]` window, in seconds.
|
|
178
|
+
clockWindow: number | null;
|
|
179
|
+
signature: string;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// Two wrappers. The probe makes the author's struct a reflectable parameter without reading a
|
|
183
|
+
// field, so Slang strips the cbuffer from the HLSL while reflection still describes it. The real
|
|
184
|
+
// one unpacks the slots into the named fields.
|
|
185
|
+
|
|
186
|
+
const WRAPPER_BANNER = `
|
|
187
|
+
// ===========================================================================
|
|
188
|
+
// engine-generated wrapper — DO NOT EDIT, DO NOT COPY INTO AN EFFECT
|
|
189
|
+
// (appended by the effect compiler, schema ${SCHEMA})
|
|
190
|
+
// Appended, never prepended, so diagnostics keep YOUR line numbers.
|
|
191
|
+
// ===========================================================================
|
|
192
|
+
`;
|
|
193
|
+
|
|
194
|
+
function probeWrapper(structName: string): string {
|
|
195
|
+
return `${WRAPPER_BANNER}
|
|
196
|
+
// b3 is unused by gpui (b0 = globals, b1 = batch params). This declaration is
|
|
197
|
+
// never read, so it does not reach the HLSL; it exists solely so that the
|
|
198
|
+
// reflection describes \`${structName}\` and its user-defined attributes.
|
|
199
|
+
[[vk::binding(0, 3)]]
|
|
200
|
+
ConstantBuffer<${structName}> sk_reflect : register(b3);
|
|
201
|
+
|
|
202
|
+
[shader("fragment")]
|
|
203
|
+
float4 sk_reflect_probe(float4 sk_position : SV_Position) : SV_Target
|
|
204
|
+
{
|
|
205
|
+
return float4(0.0, 0.0, 0.0, 0.0);
|
|
206
|
+
}
|
|
207
|
+
`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const slotExpr = (slot: number): string => `sk_in.param(${slot}u)`;
|
|
211
|
+
|
|
212
|
+
function loadExpr(field: Field): string {
|
|
213
|
+
if (field.texture) {
|
|
214
|
+
const { index, fallback } = field.texture;
|
|
215
|
+
return (
|
|
216
|
+
`sk_texture(${index}u, float2(${slotExpr(field.slot)}, ${slotExpr(field.slot + 1)}), ` +
|
|
217
|
+
`float4(${fallback.join(", ")}))`
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
if (field.components === 1) return slotExpr(field.slot);
|
|
221
|
+
const parts: string[] = [];
|
|
222
|
+
for (let c = 0; c < field.components; c += 1) parts.push(slotExpr(field.slot + c));
|
|
223
|
+
return `float${field.components}(${parts.join(", ")})`;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function realWrapper(effect: EffectSchema, fields: Field[]): string {
|
|
227
|
+
const assignments = fields.map((field) => ` sk_material.${field.name} = ${loadExpr(field)};`).join("\n");
|
|
228
|
+
return `${WRAPPER_BANNER}
|
|
229
|
+
// Kept for the record: reflection reads this declaration, every backend
|
|
230
|
+
// strips it (nothing references it), and the renderer never binds it.
|
|
231
|
+
[[vk::binding(0, 3)]]
|
|
232
|
+
ConstantBuffer<${effect.struct}> sk_reflect : register(b3);
|
|
233
|
+
|
|
234
|
+
// The varyings of the engine-owned vertex stage (gpui_windows/src/effects.hlsl,
|
|
235
|
+
// gpui_wgpu/src/shaders_effects.wgsl), in their order. Separate parameters:
|
|
236
|
+
// Slang's WGSL keeps \`nointerpolation\` on a struct it copies them into, and
|
|
237
|
+
// naga rejects an interpolated member without a location.
|
|
238
|
+
[shader("fragment")]
|
|
239
|
+
float4 ${ENTRY}(nointerpolation uint sk_id : TEXCOORD0, float4 sk_position : SV_Position) : SV_Target
|
|
240
|
+
{
|
|
241
|
+
EffectInput sk_in = sk_begin(sk_id, sk_position);
|
|
242
|
+
|
|
243
|
+
// Parameter unpacking, generated from the reflection of
|
|
244
|
+
// \`${effect.struct}\`: field order IS slot order IS CSS argument order.
|
|
245
|
+
${effect.struct} sk_material;
|
|
246
|
+
${assignments || " // (this effect declares no parameters)"}
|
|
247
|
+
|
|
248
|
+
return sk_finish(sk_material, sk_in);
|
|
249
|
+
}
|
|
250
|
+
`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/// One compiler message, at the author's line numbers.
|
|
254
|
+
export interface Problem {
|
|
255
|
+
severity: "error" | "warning" | "note";
|
|
256
|
+
/// The effect's path; `sk.slang` for the prelude, `<engine wrapper>` for the generated tail.
|
|
257
|
+
file: string;
|
|
258
|
+
line: number;
|
|
259
|
+
column: number;
|
|
260
|
+
message: string;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export class EffectsError extends Error {
|
|
264
|
+
constructor(readonly problems: Problem[]) {
|
|
265
|
+
super(formatProblems(problems.filter((p) => p.severity === "error")));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
class SchemaError extends Error {}
|
|
270
|
+
|
|
271
|
+
export function formatProblems(problems: Problem[], cwd: string = process.cwd()): string {
|
|
272
|
+
return problems
|
|
273
|
+
.map((p) => {
|
|
274
|
+
const file = p.file.startsWith("<") || p.file === "sk.slang" ? p.file : relative(cwd, p.file) || p.file;
|
|
275
|
+
const at = p.line ? `:${p.line}${p.column ? `:${p.column}` : ""}` : "";
|
|
276
|
+
return `${file.replace(/\\/g, "/")}${at}: ${p.severity}: ${p.message}`;
|
|
277
|
+
})
|
|
278
|
+
.join("\n");
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const sha256 = (text: string): string => createHash("sha256").update(text).digest("hex");
|
|
282
|
+
|
|
283
|
+
/// A Windows checkout may hold CRLF; hashes and the generated headers must match a Linux one.
|
|
284
|
+
const readText = (file: string): string => readFileSync(file, "utf8").replace(/\r\n/g, "\n");
|
|
285
|
+
|
|
286
|
+
interface ReflType {
|
|
287
|
+
kind?: string;
|
|
288
|
+
name?: string;
|
|
289
|
+
scalarType?: string;
|
|
290
|
+
elementType?: ReflType;
|
|
291
|
+
elementCount?: number | string;
|
|
292
|
+
userAttribs?: Attribute[];
|
|
293
|
+
fields?: ReflField[];
|
|
294
|
+
}
|
|
295
|
+
interface ReflField {
|
|
296
|
+
name?: unknown;
|
|
297
|
+
type?: ReflType;
|
|
298
|
+
userAttribs?: Attribute[];
|
|
299
|
+
}
|
|
300
|
+
interface ReflParam {
|
|
301
|
+
name?: string;
|
|
302
|
+
type?: ReflType;
|
|
303
|
+
binding?: { kind?: unknown; index?: unknown };
|
|
304
|
+
}
|
|
305
|
+
interface Reflection {
|
|
306
|
+
parameters?: ReflParam[];
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
interface Message {
|
|
310
|
+
severity: Problem["severity"];
|
|
311
|
+
file: string | null;
|
|
312
|
+
line: number | null;
|
|
313
|
+
column: number | null;
|
|
314
|
+
message: string;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
interface RunResult {
|
|
318
|
+
ok: boolean;
|
|
319
|
+
code: Partial<Record<TargetName, string>>;
|
|
320
|
+
reflection: Reflection | null;
|
|
321
|
+
messages: Message[];
|
|
322
|
+
diagnostics: string;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
interface Request {
|
|
326
|
+
compiler: string;
|
|
327
|
+
source: string;
|
|
328
|
+
sourceName: string;
|
|
329
|
+
module: string;
|
|
330
|
+
includes: string[];
|
|
331
|
+
targets: Target[];
|
|
332
|
+
entry: string;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
async function redslangc(r: Request): Promise<RunResult> {
|
|
336
|
+
const args = [
|
|
337
|
+
"-",
|
|
338
|
+
"--module",
|
|
339
|
+
r.module,
|
|
340
|
+
"--source-name",
|
|
341
|
+
r.sourceName,
|
|
342
|
+
"--import",
|
|
343
|
+
`sk=${PRELUDE}`,
|
|
344
|
+
...r.includes.flatMap((dir) => ["-I", dir]),
|
|
345
|
+
...r.targets.flatMap((t) => ["-t", t.spec]),
|
|
346
|
+
"-e",
|
|
347
|
+
r.entry,
|
|
348
|
+
// Pinned even though no effect takes a matrix yet: Slang 2026.14 flipped this default.
|
|
349
|
+
"--matrix-layout",
|
|
350
|
+
"row-major",
|
|
351
|
+
];
|
|
352
|
+
const child = Bun.spawn([r.compiler, ...args], {
|
|
353
|
+
stdin: new TextEncoder().encode(r.source),
|
|
354
|
+
stdout: "pipe",
|
|
355
|
+
stderr: "pipe",
|
|
356
|
+
windowsHide: true,
|
|
357
|
+
});
|
|
358
|
+
const [stdout, stderr, status] = await Promise.all([
|
|
359
|
+
new Response(child.stdout).text(),
|
|
360
|
+
new Response(child.stderr).text(),
|
|
361
|
+
child.exited,
|
|
362
|
+
]);
|
|
363
|
+
if (status !== 0 && status !== 1) {
|
|
364
|
+
throw new ShaderCompilerError(`${r.compiler} failed (exit ${status}): ${stderr.trim() || stdout.trim()}`);
|
|
365
|
+
}
|
|
366
|
+
let json: Record<string, unknown>;
|
|
367
|
+
try {
|
|
368
|
+
json = JSON.parse(stdout) as Record<string, unknown>;
|
|
369
|
+
} catch {
|
|
370
|
+
throw new ShaderCompilerError(`${r.compiler} printed no JSON (exit ${status}): ${stderr.trim()}`);
|
|
371
|
+
}
|
|
372
|
+
const code: Partial<Record<TargetName, string>> = {};
|
|
373
|
+
for (const t of r.targets) {
|
|
374
|
+
const text = json[t.name];
|
|
375
|
+
if (typeof text === "string") code[t.name] = text;
|
|
376
|
+
}
|
|
377
|
+
return {
|
|
378
|
+
ok: json.ok === true,
|
|
379
|
+
code,
|
|
380
|
+
reflection: (json.reflection as Reflection | null) ?? null,
|
|
381
|
+
messages: Array.isArray(json.messages) ? (json.messages as Message[]) : [],
|
|
382
|
+
diagnostics: typeof json.diagnostics === "string" ? json.diagnostics : "",
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/// The register each top-level parameter landed on: the contract with the D3D11 renderer
|
|
387
|
+
/// (t0 backdrop, t1 instance buffer, t2 snapshot, b0 globals, s1 clamp).
|
|
388
|
+
function bindings(reflection: Reflection | null): Array<Record<string, unknown>> {
|
|
389
|
+
const params = Array.isArray(reflection?.parameters) ? reflection.parameters : [];
|
|
390
|
+
return params
|
|
391
|
+
.filter((p) => p?.name !== "sk_reflect")
|
|
392
|
+
.map((p) => ({ name: p?.name, kind: p?.binding?.kind, index: p?.binding?.index }));
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
type Attribute = { name: string; arguments: unknown[] };
|
|
396
|
+
type Field = {
|
|
397
|
+
name: string;
|
|
398
|
+
components: number;
|
|
399
|
+
slot: number;
|
|
400
|
+
/// An `SkTexture`: its binding and the colour it reads as while missing, as `sample` returns it.
|
|
401
|
+
texture?: { index: number; fallback: [number, number, number, number] };
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
function attr(attrs: Attribute[], name: string): Attribute | undefined {
|
|
405
|
+
return attrs.find((a) => a.name === name);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function parseDefault(text: string, components: number, where: string): [number, number, number, number] {
|
|
409
|
+
const out: [number, number, number, number] = [0, 0, 0, 0];
|
|
410
|
+
const raw = text.trim();
|
|
411
|
+
if (raw.startsWith("#")) {
|
|
412
|
+
const hex = raw.slice(1);
|
|
413
|
+
const wide = hex.length > 4;
|
|
414
|
+
const step = wide ? 2 : 1;
|
|
415
|
+
const groups = hex.length / step;
|
|
416
|
+
if (![3, 4].includes(groups) || !/^[0-9a-fA-F]+$/.test(hex)) {
|
|
417
|
+
throw new SchemaError(`${where}: \`${raw}\` is not a #rgb/#rgba/#rrggbb/#rrggbbaa colour`);
|
|
418
|
+
}
|
|
419
|
+
for (let c = 0; c < 4; c += 1) {
|
|
420
|
+
if (c >= groups) {
|
|
421
|
+
out[c] = 1;
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
const piece = hex.slice(c * step, c * step + step);
|
|
425
|
+
const value = parseInt(wide ? piece : piece + piece, 16);
|
|
426
|
+
out[c] = value / 255;
|
|
427
|
+
}
|
|
428
|
+
return out;
|
|
429
|
+
}
|
|
430
|
+
const numbers = raw
|
|
431
|
+
.split(/[\s,]+/)
|
|
432
|
+
.filter(Boolean)
|
|
433
|
+
.map((n) => {
|
|
434
|
+
const v = Number(n);
|
|
435
|
+
if (!Number.isFinite(v)) throw new SchemaError(`${where}: \`${n}\` is not a number`);
|
|
436
|
+
return v;
|
|
437
|
+
});
|
|
438
|
+
if (numbers.length === 0) throw new SchemaError(`${where}: empty [SkDefault]`);
|
|
439
|
+
if (numbers.length === 1) {
|
|
440
|
+
for (let c = 0; c < components; c += 1) out[c] = numbers[0]!;
|
|
441
|
+
return out;
|
|
442
|
+
}
|
|
443
|
+
if (numbers.length !== components) {
|
|
444
|
+
throw new SchemaError(
|
|
445
|
+
`${where}: [SkDefault] has ${numbers.length} values but the field has ${components} component(s)`,
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
for (let c = 0; c < components; c += 1) out[c] = numbers[c]!;
|
|
449
|
+
return out;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/// Whether a `components`-wide field may start at `slot`: free, in range, and not straddling a
|
|
453
|
+
/// 16-byte (four-slot) boundary (HLSL's rule).
|
|
454
|
+
function fits(used: boolean[], slot: number, components: number): boolean {
|
|
455
|
+
if (slot < 0 || slot + components > PARAM_SLOTS) return false;
|
|
456
|
+
if (components > 1 && Math.floor(slot / 4) !== Math.floor((slot + components - 1) / 4)) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
for (let c = 0; c < components; c += 1) if (used[slot + c]) return false;
|
|
460
|
+
return true;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function allocate(used: boolean[], components: number): number {
|
|
464
|
+
for (let slot = 0; slot + components <= PARAM_SLOTS; slot += 1) {
|
|
465
|
+
if (fits(used, slot, components)) return slot;
|
|
466
|
+
}
|
|
467
|
+
return -1;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const isTexture = (type: ReflType | undefined): boolean => type?.kind === "struct" && type.name === "SkTexture";
|
|
471
|
+
|
|
472
|
+
function fieldComponents(type: ReflType | undefined, where: string): number {
|
|
473
|
+
if (isTexture(type)) return 2;
|
|
474
|
+
if (type?.kind === "scalar") {
|
|
475
|
+
if (type.scalarType !== "float32") {
|
|
476
|
+
throw new SchemaError(
|
|
477
|
+
`${where}: parameters are floats in the instance buffer, so \`${type.scalarType}\` ` +
|
|
478
|
+
"is not a legal parameter type — declare it `float` and compare in `shade`",
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
return 1;
|
|
482
|
+
}
|
|
483
|
+
if (type?.kind === "vector") {
|
|
484
|
+
if (type.elementType?.scalarType !== "float32") {
|
|
485
|
+
throw new SchemaError(`${where}: only float vectors may be parameters`);
|
|
486
|
+
}
|
|
487
|
+
const n = Number(type.elementCount);
|
|
488
|
+
if (![2, 3, 4].includes(n)) throw new SchemaError(`${where}: unsupported vector width ${n}`);
|
|
489
|
+
return n;
|
|
490
|
+
}
|
|
491
|
+
throw new SchemaError(
|
|
492
|
+
`${where}: unsupported parameter type \`${type?.name ?? type?.kind ?? "?"}\` — a parameter must be ` +
|
|
493
|
+
"`float`, `float2`, `float3`, `float4` or `SkTexture` (an image: matrices, arrays, raw " +
|
|
494
|
+
"textures and samplers cannot ride in the 32-float parameter block)",
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const COMPONENT_SUFFIX = ["x", "y", "z", "w"];
|
|
499
|
+
|
|
500
|
+
const HOST_FILLED_REFUSES = [
|
|
501
|
+
"SkDefault",
|
|
502
|
+
"SkRange",
|
|
503
|
+
"SkLength",
|
|
504
|
+
"SkColor",
|
|
505
|
+
"SkOptional",
|
|
506
|
+
"SkAnimated",
|
|
507
|
+
"SkBleed",
|
|
508
|
+
"SkBackdropRadius",
|
|
509
|
+
];
|
|
510
|
+
|
|
511
|
+
function buildSchema(
|
|
512
|
+
reflection: Reflection | null,
|
|
513
|
+
structName: string,
|
|
514
|
+
source: string,
|
|
515
|
+
): {
|
|
516
|
+
effect: EffectSchema;
|
|
517
|
+
fields: Field[];
|
|
518
|
+
} {
|
|
519
|
+
const param = (reflection?.parameters ?? []).find((p) => p?.name === "sk_reflect");
|
|
520
|
+
const element = param?.type?.elementType;
|
|
521
|
+
if (!element || element.kind !== "struct") {
|
|
522
|
+
throw new SchemaError(
|
|
523
|
+
`${source}: the compiler reflected no struct for \`${structName}\` — this is an internal ` +
|
|
524
|
+
"error in the effect toolchain, not in your shader",
|
|
525
|
+
);
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
const structAttrs: Attribute[] = element.userAttribs ?? [];
|
|
529
|
+
const effectAttr = attr(structAttrs, "SkEffect");
|
|
530
|
+
if (!effectAttr) {
|
|
531
|
+
throw new SchemaError(
|
|
532
|
+
`${source}: \`struct ${structName}\` has no [SkEffect("<name>")] attribute — that ` +
|
|
533
|
+
"attribute is what gives the effect its CSS function name",
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
const name = String(effectAttr.arguments?.[0] ?? "");
|
|
537
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) {
|
|
538
|
+
throw new SchemaError(
|
|
539
|
+
`${source}: [SkEffect("${name}")] — an effect name must be a lowercase CSS ident ` +
|
|
540
|
+
"(`[a-z][a-z0-9-]*`), because it becomes a CSS function name",
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
const docAttr = attr(structAttrs, "SkDoc");
|
|
544
|
+
|
|
545
|
+
const params: ParamSchema[] = [];
|
|
546
|
+
const fields: Field[] = [];
|
|
547
|
+
let backdropRadiusParam: number | null = null;
|
|
548
|
+
let bleedParam: number | null = null;
|
|
549
|
+
let animatedParam: number | null = null;
|
|
550
|
+
let pointerParam: number | null = null;
|
|
551
|
+
let pointerTimesParam: number | null = null;
|
|
552
|
+
const clockSlots: number[] = [];
|
|
553
|
+
let clockWindow: number | null = null;
|
|
554
|
+
let textures = 0;
|
|
555
|
+
let backdrop = attr(structAttrs, "SkBackdrop") !== undefined;
|
|
556
|
+
// Taken float slots: `[SkSlot]` runs are reserved first, then fields pack in declaration order.
|
|
557
|
+
const used: boolean[] = new Array(PARAM_SLOTS).fill(false);
|
|
558
|
+
const pinned = new Map<string, number>();
|
|
559
|
+
for (const field of element.fields ?? []) {
|
|
560
|
+
const slotAttr = attr(field.userAttribs ?? [], "SkSlot");
|
|
561
|
+
if (!slotAttr) continue;
|
|
562
|
+
const where = `${source}: \`${structName}.${String(field.name)}\``;
|
|
563
|
+
const components = fieldComponents(field.type, where);
|
|
564
|
+
const slot = Number(slotAttr.arguments?.[0]);
|
|
565
|
+
if (!Number.isInteger(slot) || !fits(used, slot, components)) {
|
|
566
|
+
throw new SchemaError(
|
|
567
|
+
`${where}: [SkSlot(${slotAttr.arguments?.[0]})] is not a legal home for a ` +
|
|
568
|
+
`${components}-component parameter — it must be free, inside 0..${PARAM_SLOTS - 1}, ` +
|
|
569
|
+
"and must not straddle a four-slot boundary",
|
|
570
|
+
);
|
|
571
|
+
}
|
|
572
|
+
for (let c = 0; c < components; c += 1) used[slot + c] = true;
|
|
573
|
+
pinned.set(String(field.name), slot);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
for (const field of element.fields ?? []) {
|
|
577
|
+
const fieldName = String(field.name);
|
|
578
|
+
const where = `${source}: \`${structName}.${fieldName}\``;
|
|
579
|
+
const attrs: Attribute[] = field.userAttribs ?? [];
|
|
580
|
+
const components = fieldComponents(field.type, where);
|
|
581
|
+
|
|
582
|
+
const isColor = attr(attrs, "SkColor") !== undefined;
|
|
583
|
+
const isLength = attr(attrs, "SkLength") !== undefined;
|
|
584
|
+
const optional = attr(attrs, "SkOptional") !== undefined;
|
|
585
|
+
const rangeAttr = attr(attrs, "SkRange");
|
|
586
|
+
const defaultAttr = attr(attrs, "SkDefault");
|
|
587
|
+
|
|
588
|
+
if (isColor && components !== 4) {
|
|
589
|
+
throw new SchemaError(`${where}: [SkColor] is only legal on a float4 (RGBA)`);
|
|
590
|
+
}
|
|
591
|
+
if (isColor && isLength) {
|
|
592
|
+
throw new SchemaError(`${where}: [SkColor] and [SkLength] are mutually exclusive`);
|
|
593
|
+
}
|
|
594
|
+
if (optional && components > 1 && !isColor && !isTexture(field.type)) {
|
|
595
|
+
// A bare vector expands to one CSS argument per component and optional parameters are
|
|
596
|
+
// skipped one argument at a time, so half a `float2` could be filled in: refuse.
|
|
597
|
+
throw new SchemaError(
|
|
598
|
+
`${where}: [SkOptional] is not allowed on a float${components} — it expands to ` +
|
|
599
|
+
`${components} CSS arguments and only some of them could be omitted. Split it into ` +
|
|
600
|
+
"scalar fields, or drop [SkOptional].",
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
let slot = pinned.get(fieldName) ?? -1;
|
|
605
|
+
if (slot < 0) {
|
|
606
|
+
slot = allocate(used, components);
|
|
607
|
+
if (slot < 0) {
|
|
608
|
+
throw new SchemaError(
|
|
609
|
+
`${where}: no room left in the parameter block. An effect quad carries ` +
|
|
610
|
+
`${PARAM_SLOTS} floats (EffectQuad::params) and a <color> costs 4; ` +
|
|
611
|
+
"drop or merge a parameter.",
|
|
612
|
+
);
|
|
613
|
+
}
|
|
614
|
+
for (let c = 0; c < components; c += 1) used[slot + c] = true;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
const linear = attr(attrs, "SkLinear") !== undefined;
|
|
618
|
+
if (isTexture(field.type)) {
|
|
619
|
+
const refused = [
|
|
620
|
+
...HOST_FILLED_REFUSES.filter((a) => a !== "SkDefault" && a !== "SkOptional"),
|
|
621
|
+
"SkAnimatedFor",
|
|
622
|
+
"SkPointer",
|
|
623
|
+
"SkPointerTimes",
|
|
624
|
+
].find((a) => attr(attrs, a) !== undefined);
|
|
625
|
+
if (refused) throw new SchemaError(`${where}: [${refused}] cannot go on an SkTexture`);
|
|
626
|
+
if (textures === TEXTURE_SLOTS) {
|
|
627
|
+
throw new SchemaError(`${where}: an effect samples at most ${TEXTURE_SLOTS} SkTexture images`);
|
|
628
|
+
}
|
|
629
|
+
const fallback = defaultAttr
|
|
630
|
+
? parseDefault(String(defaultAttr.arguments?.[0] ?? ""), 4, where)
|
|
631
|
+
: ([0, 0, 0, 0] as [number, number, number, number]);
|
|
632
|
+
const [r, g, b, a] = fallback;
|
|
633
|
+
fields.push({
|
|
634
|
+
name: fieldName,
|
|
635
|
+
components,
|
|
636
|
+
slot,
|
|
637
|
+
texture: { index: textures, fallback: linear ? fallback : [r * a, g * a, b * a, a] },
|
|
638
|
+
});
|
|
639
|
+
params.push({
|
|
640
|
+
name: fieldName,
|
|
641
|
+
kind: "texture",
|
|
642
|
+
slot,
|
|
643
|
+
required: !optional,
|
|
644
|
+
default: fallback,
|
|
645
|
+
range: null,
|
|
646
|
+
texture: textures,
|
|
647
|
+
linear,
|
|
648
|
+
});
|
|
649
|
+
textures += 1;
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
if (linear) throw new SchemaError(`${where}: [SkLinear] is only legal on an SkTexture`);
|
|
653
|
+
fields.push({ name: fieldName, components, slot });
|
|
654
|
+
|
|
655
|
+
const animatedFor = attr(attrs, "SkAnimatedFor");
|
|
656
|
+
if (animatedFor) {
|
|
657
|
+
const seconds = Number(animatedFor.arguments?.[0]);
|
|
658
|
+
if (!Number.isFinite(seconds) || seconds <= 0) {
|
|
659
|
+
throw new SchemaError(
|
|
660
|
+
`${where}: [SkAnimatedFor(${animatedFor.arguments?.[0]})] needs a positive number of seconds`,
|
|
661
|
+
);
|
|
662
|
+
}
|
|
663
|
+
clockWindow = Math.max(clockWindow ?? 0, seconds);
|
|
664
|
+
for (let c = 0; c < components; c += 1) clockSlots.push(slot + c);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const host = (["SkPointer", "SkPointerTimes"] as const).filter((a) => attr(attrs, a) !== undefined);
|
|
668
|
+
if (host.length > 1) throw new SchemaError(`${where}: [SkPointer] and [SkPointerTimes] are mutually exclusive`);
|
|
669
|
+
if (host[0]) {
|
|
670
|
+
const kind = host[0];
|
|
671
|
+
const wanted = kind === "SkPointer" ? 2 : 3;
|
|
672
|
+
if (components !== wanted) throw new SchemaError(`${where}: [${kind}] is only legal on a float${wanted}`);
|
|
673
|
+
const css = HOST_FILLED_REFUSES.find((a) => attr(attrs, a) !== undefined);
|
|
674
|
+
if (css) {
|
|
675
|
+
throw new SchemaError(
|
|
676
|
+
`${where}: [${css}] cannot go on a [${kind}] parameter — the host fills it, it is not a CSS argument`,
|
|
677
|
+
);
|
|
678
|
+
}
|
|
679
|
+
const current = kind === "SkPointer" ? pointerParam : pointerTimesParam;
|
|
680
|
+
if (current !== null) throw new SchemaError(`${where}: [${kind}] appears more than once in \`${structName}\``);
|
|
681
|
+
if (kind === "SkPointer") pointerParam = slot;
|
|
682
|
+
else pointerTimesParam = slot;
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const defaults = defaultAttr
|
|
687
|
+
? parseDefault(String(defaultAttr.arguments?.[0] ?? ""), components, where)
|
|
688
|
+
: ([0, 0, 0, 0] as [number, number, number, number]);
|
|
689
|
+
const range = rangeAttr
|
|
690
|
+
? ([Number(rangeAttr.arguments?.[0]), Number(rangeAttr.arguments?.[1])] as [number, number])
|
|
691
|
+
: null;
|
|
692
|
+
|
|
693
|
+
if (isColor) {
|
|
694
|
+
params.push({ name: fieldName, kind: "color", slot, required: !optional, default: defaults, range: null });
|
|
695
|
+
} else {
|
|
696
|
+
for (let c = 0; c < components; c += 1) {
|
|
697
|
+
params.push({
|
|
698
|
+
name: components === 1 ? fieldName : `${fieldName}.${COMPONENT_SUFFIX[c]}`,
|
|
699
|
+
kind: isLength ? "length" : "number",
|
|
700
|
+
slot: slot + c,
|
|
701
|
+
required: !optional,
|
|
702
|
+
default: [defaults[c]!, 0, 0, 0],
|
|
703
|
+
range,
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const marker = (attrName: string, current: number | null, requires: string) => {
|
|
709
|
+
if (attr(attrs, attrName) === undefined) return current;
|
|
710
|
+
if (current !== null) {
|
|
711
|
+
throw new SchemaError(`${where}: [${attrName}] appears more than once in \`${structName}\``);
|
|
712
|
+
}
|
|
713
|
+
if (components !== 1) {
|
|
714
|
+
throw new SchemaError(`${where}: [${attrName}] is only legal on a scalar \`float\``);
|
|
715
|
+
}
|
|
716
|
+
if (requires === "length" && !isLength) {
|
|
717
|
+
throw new SchemaError(`${where}: [${attrName}] requires [SkLength] on the same field`);
|
|
718
|
+
}
|
|
719
|
+
return slot;
|
|
720
|
+
};
|
|
721
|
+
backdropRadiusParam = marker("SkBackdropRadius", backdropRadiusParam, "length");
|
|
722
|
+
bleedParam = marker("SkBleed", bleedParam, "length");
|
|
723
|
+
animatedParam = marker("SkAnimated", animatedParam, "number");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
if (backdropRadiusParam !== null) backdrop = true;
|
|
727
|
+
|
|
728
|
+
// Type-directed matching needs a skippable parameter's kind to differ from the next one's, else
|
|
729
|
+
// `ripple(1)` is ambiguous.
|
|
730
|
+
for (let i = 0; i < params.length; i += 1) {
|
|
731
|
+
const cur = params[i]!;
|
|
732
|
+
if (cur.required) continue;
|
|
733
|
+
const nextParam = params[i + 1];
|
|
734
|
+
if (nextParam && nextParam.kind === cur.kind) {
|
|
735
|
+
throw new SchemaError(
|
|
736
|
+
`${source}: \`${name}\` — optional parameter \`${cur.name}\` has the same CSS ` +
|
|
737
|
+
`type (${cur.kind}) as the parameter after it (\`${nextParam.name}\`), so an ` +
|
|
738
|
+
"argument in that position would be ambiguous. Make it required, reorder, or change " +
|
|
739
|
+
"its type.",
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const signature = `${name}(${params
|
|
745
|
+
.map((p) => `<${p.name === p.kind ? p.kind : `${p.kind}:${p.name}`}>${p.required ? "" : "?"}`)
|
|
746
|
+
.join(", ")})`;
|
|
747
|
+
|
|
748
|
+
return {
|
|
749
|
+
effect: {
|
|
750
|
+
name,
|
|
751
|
+
struct: structName,
|
|
752
|
+
doc: docAttr ? String(docAttr.arguments?.[0] ?? "") : null,
|
|
753
|
+
backdrop,
|
|
754
|
+
content: attr(structAttrs, "SkContent") !== undefined,
|
|
755
|
+
history: attr(structAttrs, "SkHistory") !== undefined,
|
|
756
|
+
params,
|
|
757
|
+
backdropRadiusParam,
|
|
758
|
+
bleedParam,
|
|
759
|
+
animatedParam,
|
|
760
|
+
pointerParam,
|
|
761
|
+
pointerTimesParam,
|
|
762
|
+
clockSlots,
|
|
763
|
+
clockWindow,
|
|
764
|
+
signature,
|
|
765
|
+
},
|
|
766
|
+
fields,
|
|
767
|
+
};
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
export interface EffectSource {
|
|
771
|
+
/// The `.slang` file.
|
|
772
|
+
file: string;
|
|
773
|
+
/// Its name in `#line` directives, diagnostics and the generated header: stable across machines.
|
|
774
|
+
sourceName: string;
|
|
775
|
+
struct: string;
|
|
776
|
+
source: string;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/// The struct name must be known before compiling (the probe wrapper names it): one `struct <Name> : IEffect` per file.
|
|
780
|
+
function findStruct(file: string, source: string): string {
|
|
781
|
+
const stripped = source.replace(/\/\/[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
782
|
+
const matches = [...stripped.matchAll(/\bstruct\s+([A-Za-z_]\w*)\s*:\s*(?:sk\.)?IEffect\b/g)];
|
|
783
|
+
if (matches.length === 0) {
|
|
784
|
+
throw new SchemaError(
|
|
785
|
+
`${basename(file)}: no \`struct <Name> : IEffect\` found. An effect is a struct that ` +
|
|
786
|
+
"conforms to the `IEffect` interface from the `sk` prelude (`import sk;`).",
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
if (matches.length > 1) {
|
|
790
|
+
throw new SchemaError(
|
|
791
|
+
`${basename(file)}: ${matches.length} effect structs in one file ` +
|
|
792
|
+
`(${matches.map((m) => m[1]).join(", ")}) — one effect per file`,
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
return matches[0]![1]!;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
export const stemOf = (file: string): string => basename(file).replace(/\.slang$/, "");
|
|
799
|
+
|
|
800
|
+
/// Where a schema complaint about `Struct.field` points: the field's declaration.
|
|
801
|
+
function locate(source: string, message: string): { line: number; column: number } {
|
|
802
|
+
const field = /`\w+\.(\w+)`/.exec(message)?.[1];
|
|
803
|
+
const struct = /`(?:struct )?(\w+)`/.exec(message)?.[1];
|
|
804
|
+
const lines = source.split("\n");
|
|
805
|
+
const find = (re: RegExp) => lines.findIndex((l) => re.test(l.replace(/\/\/.*$/, "")));
|
|
806
|
+
let at = field ? find(new RegExp(`\\b${field}\\s*;`)) : -1;
|
|
807
|
+
if (at < 0 && struct) at = find(new RegExp(`\\bstruct\\s+${struct}\\b`));
|
|
808
|
+
if (at < 0) return { line: 0, column: 0 };
|
|
809
|
+
const column = (field ? lines[at]!.search(new RegExp(`\\b${field}\\b`)) : lines[at]!.indexOf("struct")) + 1;
|
|
810
|
+
return { line: at + 1, column: Math.max(column, 1) };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function schemaProblem(file: string, source: string | null, error: SchemaError): Problem {
|
|
814
|
+
const message = error.message.replace(/^[^:`]+\.slang: /, "");
|
|
815
|
+
const where = source === null ? { line: 0, column: 0 } : locate(source, message);
|
|
816
|
+
return { severity: "error", file, ...where, message };
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const DECLARES_EFFECT = /\[\s*SkEffect\s*\(/;
|
|
820
|
+
|
|
821
|
+
function slangFiles(dir: string): string[] {
|
|
822
|
+
return (readdirSync(dir, { recursive: true }) as string[])
|
|
823
|
+
.filter((f) => f.endsWith(".slang"))
|
|
824
|
+
.map((f) => join(dir, f))
|
|
825
|
+
.sort();
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
/// The effects under `dir`: every `.slang` that declares an `[SkEffect]`; the rest are modules they import.
|
|
829
|
+
export function discover(
|
|
830
|
+
dir: string,
|
|
831
|
+
sourceName: (file: string) => string,
|
|
832
|
+
): { sources: EffectSource[]; problems: Problem[] } {
|
|
833
|
+
const sources: EffectSource[] = [];
|
|
834
|
+
const problems: Problem[] = [];
|
|
835
|
+
const stems = new Map<string, string>();
|
|
836
|
+
for (const file of slangFiles(dir)) {
|
|
837
|
+
const source = readText(file);
|
|
838
|
+
if (!DECLARES_EFFECT.test(source)) continue;
|
|
839
|
+
const f = relative(dir, file);
|
|
840
|
+
try {
|
|
841
|
+
if (stemOf(file) === "sk") {
|
|
842
|
+
throw new SchemaError(`${f}: an effect cannot be named sk.slang — \`sk\` is the prelude's module`);
|
|
843
|
+
}
|
|
844
|
+
const other = stems.get(stemOf(file));
|
|
845
|
+
if (other) throw new SchemaError(`${f}: ${other} is an effect file with the same name; rename one`);
|
|
846
|
+
stems.set(stemOf(file), f);
|
|
847
|
+
sources.push({ file, sourceName: sourceName(file), struct: findStruct(file, source), source });
|
|
848
|
+
} catch (e) {
|
|
849
|
+
if (!(e instanceof SchemaError)) throw e;
|
|
850
|
+
problems.push(schemaProblem(file, source, e));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
return { sources, problems };
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
export type Compiled = {
|
|
857
|
+
file: string;
|
|
858
|
+
effect: EffectSchema;
|
|
859
|
+
/// The generated source per target, in `TARGETS` order.
|
|
860
|
+
outputs: Array<{ target: TargetName; code: string }>;
|
|
861
|
+
reflection: unknown;
|
|
862
|
+
sourceSha256: string;
|
|
863
|
+
warnings: Problem[];
|
|
864
|
+
};
|
|
865
|
+
|
|
866
|
+
function problemsOf(messages: Message[], s: EffectSource, userLines: number): Problem[] {
|
|
867
|
+
return messages.map((m) => {
|
|
868
|
+
const line = m.line ?? 0;
|
|
869
|
+
const ours = m.file === s.sourceName;
|
|
870
|
+
const inUser = ours && line <= userLines;
|
|
871
|
+
return {
|
|
872
|
+
severity: m.severity,
|
|
873
|
+
file: inUser ? s.file : ours ? "<engine wrapper>" : (m.file ?? "<unknown>"),
|
|
874
|
+
line: ours && !inUser ? line - userLines : line,
|
|
875
|
+
column: m.column ?? 0,
|
|
876
|
+
message: m.message,
|
|
877
|
+
};
|
|
878
|
+
});
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
async function compile(compiler: string, s: EffectSource, includes: string[]): Promise<Compiled> {
|
|
882
|
+
const userLines = s.source.split("\n").length;
|
|
883
|
+
const module = stemOf(s.file).replace(/[^A-Za-z0-9_]/g, "_");
|
|
884
|
+
const run = (source: string, entry: string, targets: Target[]) =>
|
|
885
|
+
redslangc({ compiler, source, sourceName: s.sourceName, module, includes, targets, entry });
|
|
886
|
+
const fail = (r: RunResult) => {
|
|
887
|
+
let problems = problemsOf(r.messages, s, userLines);
|
|
888
|
+
if (problems.some((p) => p.severity === "error" && p.file === s.file)) {
|
|
889
|
+
problems = problems.filter((p) => p.file !== "<unknown>");
|
|
890
|
+
}
|
|
891
|
+
if (!problems.some((p) => p.severity === "error")) {
|
|
892
|
+
problems.push({ severity: "error", file: s.file, line: 0, column: 0, message: r.diagnostics.trim() });
|
|
893
|
+
}
|
|
894
|
+
return new EffectsError(problems);
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
// PASS 1: reflection only; the probe's cbuffer is dropped from the HLSL we discard.
|
|
898
|
+
const probe = await run(`${s.source}\n${probeWrapper(s.struct)}`, "sk_reflect_probe", [TARGETS[0]!]);
|
|
899
|
+
if (!probe.ok) throw fail(probe);
|
|
900
|
+
const { effect, fields } = buildSchema(probe.reflection, s.struct, basename(s.file));
|
|
901
|
+
|
|
902
|
+
const header =
|
|
903
|
+
`// GENERATED by the Skathi effect compiler — DO NOT EDIT.\n` +
|
|
904
|
+
`//\n` +
|
|
905
|
+
`// effect: ${effect.name}\n` +
|
|
906
|
+
`// struct: ${effect.struct}\n` +
|
|
907
|
+
`// source: ${s.sourceName}\n` +
|
|
908
|
+
`// signature: ${effect.signature}\n` +
|
|
909
|
+
`// slang: ${PIN.slang}\n` +
|
|
910
|
+
`// schema: ${SCHEMA}\n` +
|
|
911
|
+
`// src-sha256: ${sha256(s.source)}\n` +
|
|
912
|
+
`// output: ${
|
|
913
|
+
effect.backdrop
|
|
914
|
+
? "premultiplied RGBA, written with blending disabled (it owns its quad)"
|
|
915
|
+
: "premultiplied RGBA, blended One, OneMinusSrcAlpha"
|
|
916
|
+
}\n` +
|
|
917
|
+
`//\n`;
|
|
918
|
+
|
|
919
|
+
const real = await run(`${s.source}\n${realWrapper(effect, fields)}`, ENTRY, TARGETS);
|
|
920
|
+
if (!real.ok) throw fail(real);
|
|
921
|
+
const outputs = TARGETS.map((target) => {
|
|
922
|
+
const body = real.code[target.name];
|
|
923
|
+
if (body === undefined) throw new ShaderCompilerError(`redslangc returned no ${target.name} for ${s.file}`);
|
|
924
|
+
target.check(body, s.file);
|
|
925
|
+
return { target: target.name, code: `${header}${target.note()}\n${body}` };
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
return {
|
|
929
|
+
file: s.file,
|
|
930
|
+
effect,
|
|
931
|
+
outputs,
|
|
932
|
+
reflection: bindings(real.reflection),
|
|
933
|
+
sourceSha256: sha256(s.source),
|
|
934
|
+
warnings: problemsOf(real.messages, s, userLines).filter((p) => p.severity !== "error"),
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
/// Compiles every source, in parallel; an `EffectsError` lists every effect's problems at once.
|
|
939
|
+
export async function compileEffects(
|
|
940
|
+
compiler: string,
|
|
941
|
+
sources: EffectSource[],
|
|
942
|
+
includes: string[] = [],
|
|
943
|
+
): Promise<Compiled[]> {
|
|
944
|
+
const results: Array<Compiled | Problem[]> = new Array(sources.length);
|
|
945
|
+
let next = 0;
|
|
946
|
+
const worker = async () => {
|
|
947
|
+
while (next < sources.length) {
|
|
948
|
+
const i = next++;
|
|
949
|
+
const s = sources[i]!;
|
|
950
|
+
try {
|
|
951
|
+
results[i] = await compile(compiler, s, includes);
|
|
952
|
+
} catch (e) {
|
|
953
|
+
if (e instanceof EffectsError) results[i] = e.problems;
|
|
954
|
+
else if (e instanceof SchemaError) results[i] = [schemaProblem(s.file, s.source, e)];
|
|
955
|
+
else throw e;
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
await Promise.all(Array.from({ length: Math.min(sources.length, availableParallelism()) }, worker));
|
|
960
|
+
const problems = results.flatMap((r) => (Array.isArray(r) ? r : []));
|
|
961
|
+
if (problems.length) throw new EffectsError(problems);
|
|
962
|
+
return results as Compiled[];
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
export interface EffectFile {
|
|
966
|
+
name: string;
|
|
967
|
+
text: string;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/// The generated sources and, last, the effects.json that lists them.
|
|
971
|
+
export function effectFiles(
|
|
972
|
+
kind: "builtin" | "user",
|
|
973
|
+
compiled: Compiled[],
|
|
974
|
+
sourceOf: (file: string) => string,
|
|
975
|
+
): EffectFile[] {
|
|
976
|
+
const manifest = {
|
|
977
|
+
schema: SCHEMA,
|
|
978
|
+
slang: PIN.slang,
|
|
979
|
+
compiler: `redslangc ${PIN.version}`,
|
|
980
|
+
kind,
|
|
981
|
+
preludeSha256: sha256(readText(PRELUDE)),
|
|
982
|
+
effects: compiled.map((c, index) => ({
|
|
983
|
+
id: index,
|
|
984
|
+
name: c.effect.name,
|
|
985
|
+
struct: c.effect.struct,
|
|
986
|
+
doc: c.effect.doc,
|
|
987
|
+
backdrop: c.effect.backdrop,
|
|
988
|
+
content: c.effect.content,
|
|
989
|
+
history: c.effect.history,
|
|
990
|
+
...Object.fromEntries(c.outputs.map((o) => [o.target, `${stemOf(c.file)}.${o.target}`])),
|
|
991
|
+
source: sourceOf(c.file),
|
|
992
|
+
sourceSha256: c.sourceSha256,
|
|
993
|
+
generatedSha256: Object.fromEntries(c.outputs.map((o) => [o.target, sha256(o.code)])),
|
|
994
|
+
signature: c.effect.signature,
|
|
995
|
+
backdropRadiusParam: c.effect.backdropRadiusParam,
|
|
996
|
+
bleedParam: c.effect.bleedParam,
|
|
997
|
+
animatedParam: c.effect.animatedParam,
|
|
998
|
+
pointerParam: c.effect.pointerParam,
|
|
999
|
+
pointerTimesParam: c.effect.pointerTimesParam,
|
|
1000
|
+
clockSlots: c.effect.clockSlots,
|
|
1001
|
+
clockWindow: c.effect.clockWindow,
|
|
1002
|
+
params: c.effect.params,
|
|
1003
|
+
bindings: c.reflection,
|
|
1004
|
+
})),
|
|
1005
|
+
};
|
|
1006
|
+
return [
|
|
1007
|
+
...compiled.flatMap((c) => c.outputs.map((o) => ({ name: `${stemOf(c.file)}.${o.target}`, text: o.code }))),
|
|
1008
|
+
{ name: "effects.json", text: `${JSON.stringify(manifest, null, 2)}\n` },
|
|
1009
|
+
];
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
export const appShadersDir = (appRoot: string) => join(appRoot, "shaders");
|
|
1013
|
+
|
|
1014
|
+
/// Whether the app has effects of its own: any `shaders/*.slang`.
|
|
1015
|
+
export function hasAppEffects(appRoot: string): boolean {
|
|
1016
|
+
const dir = appShadersDir(appRoot);
|
|
1017
|
+
try {
|
|
1018
|
+
return statSync(dir).isDirectory() && slangFiles(dir).some((f) => DECLARES_EFFECT.test(readText(f)));
|
|
1019
|
+
} catch {
|
|
1020
|
+
return false;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
export interface AppEffects {
|
|
1025
|
+
compiled: Compiled[];
|
|
1026
|
+
files: EffectFile[];
|
|
1027
|
+
warnings: Problem[];
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
/// Compiles `<appRoot>/shaders/*.slang`; the app's shaders directory is an include path too, for shared helpers.
|
|
1031
|
+
export async function compileAppEffects(appRoot: string, compiler: string): Promise<AppEffects> {
|
|
1032
|
+
const dir = appShadersDir(appRoot);
|
|
1033
|
+
const posix = (file: string) => relative(appRoot, file).split(/[\\/]/).join("/");
|
|
1034
|
+
const { sources, problems } = discover(dir, (file) => `${posix(file)}+wrapper`);
|
|
1035
|
+
if (problems.length) throw new EffectsError(problems);
|
|
1036
|
+
const compiled = await compileEffects(compiler, sources, [dir]);
|
|
1037
|
+
const seen = new Map<string, string>();
|
|
1038
|
+
for (const c of compiled) {
|
|
1039
|
+
if (BUILTIN_EFFECTS.includes(c.effect.name)) {
|
|
1040
|
+
problems.push({
|
|
1041
|
+
...schemaProblemAt(c, `[SkEffect("${c.effect.name}")] shadows a built-in effect; pick another name`),
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
const previous = seen.get(c.effect.name);
|
|
1045
|
+
if (previous) {
|
|
1046
|
+
problems.push(
|
|
1047
|
+
schemaProblemAt(
|
|
1048
|
+
c,
|
|
1049
|
+
`[SkEffect("${c.effect.name}")] is declared in ${basename(previous)} too; names must be unique`,
|
|
1050
|
+
),
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
seen.set(c.effect.name, c.file);
|
|
1054
|
+
}
|
|
1055
|
+
if (problems.length) throw new EffectsError(problems);
|
|
1056
|
+
return { compiled, files: effectFiles("user", compiled, posix), warnings: compiled.flatMap((c) => c.warnings) };
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
function schemaProblemAt(c: Compiled, message: string): Problem {
|
|
1060
|
+
const lines = readText(c.file).split("\n");
|
|
1061
|
+
const at = lines.findIndex((l) => l.includes("SkEffect"));
|
|
1062
|
+
return {
|
|
1063
|
+
severity: "error",
|
|
1064
|
+
file: c.file,
|
|
1065
|
+
line: at + 1,
|
|
1066
|
+
column: at < 0 ? 0 : lines[at]!.indexOf("SkEffect") + 1,
|
|
1067
|
+
message,
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/// Replaces `dir`'s generated files with `files`, effects.json last: a host reads it to decide what to load.
|
|
1072
|
+
export function writeEffectFiles(dir: string, files: EffectFile[]): void {
|
|
1073
|
+
mkdirSync(dir, { recursive: true });
|
|
1074
|
+
const keep = new Set(files.map((f) => f.name));
|
|
1075
|
+
for (const name of readdirSync(dir)) {
|
|
1076
|
+
if (!keep.has(name) && /\.(hlsl|wgsl|metal)$/.test(name)) rmSync(join(dir, name), { force: true });
|
|
1077
|
+
}
|
|
1078
|
+
for (const f of files) if (f.name !== "effects.json") writeFileSync(join(dir, f.name), f.text);
|
|
1079
|
+
const manifest = files.find((f) => f.name === "effects.json");
|
|
1080
|
+
if (manifest) writeFileSync(join(dir, manifest.name), manifest.text);
|
|
1081
|
+
}
|