@null3d/vite-plugin 0.0.0-stage → 0.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 (50) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +21 -0
  3. package/THIRD-PARTY-NOTICES.txt +398 -0
  4. package/dist/shader-compiler.stamp.json +4 -0
  5. package/dist/shader-compiler.wasm +0 -0
  6. package/lib/assets.d.ts +94 -0
  7. package/lib/assets.js +189 -0
  8. package/lib/client.d.ts +21 -0
  9. package/lib/compile-pool.d.ts +25 -0
  10. package/lib/compile-pool.js +90 -0
  11. package/lib/compile-worker.js +11 -0
  12. package/lib/compiler-calls.d.ts +26 -0
  13. package/lib/compiler-calls.js +97 -0
  14. package/lib/compiler-stamp.d.ts +8 -0
  15. package/lib/compiler-stamp.js +34 -0
  16. package/lib/declarations.d.ts +10 -0
  17. package/lib/declarations.js +80 -0
  18. package/lib/engine-shaders-local.d.ts +6 -0
  19. package/lib/engine-shaders-local.js +75 -0
  20. package/lib/engine-shaders.d.ts +61 -0
  21. package/lib/engine-shaders.js +170 -0
  22. package/lib/hash-pool.d.ts +24 -0
  23. package/lib/hash-pool.js +84 -0
  24. package/lib/hash-worker.js +53 -0
  25. package/lib/hot.d.ts +53 -0
  26. package/lib/hot.js +101 -0
  27. package/lib/index.d.ts +95 -0
  28. package/lib/index.js +895 -0
  29. package/lib/material-builds.d.ts +91 -0
  30. package/lib/material-builds.js +236 -0
  31. package/lib/offline.d.ts +92 -0
  32. package/lib/offline.js +304 -0
  33. package/lib/pack.d.ts +30 -0
  34. package/lib/pack.js +112 -0
  35. package/lib/package-files.d.ts +12 -0
  36. package/lib/package-files.js +39 -0
  37. package/lib/paragraphs.d.ts +19 -0
  38. package/lib/paragraphs.js +131 -0
  39. package/lib/shader-cache.d.ts +59 -0
  40. package/lib/shader-cache.js +213 -0
  41. package/lib/shader-compiler.d.ts +258 -0
  42. package/lib/shader-compiler.js +169 -0
  43. package/lib/shader-types.d.ts +261 -0
  44. package/lib/shader-types.js +4 -0
  45. package/lib/wgsl.d.ts +118 -0
  46. package/lib/wgsl.js +446 -0
  47. package/lib/worker-preload.d.ts +17 -0
  48. package/lib/worker-preload.js +65 -0
  49. package/package.json +69 -5
  50. package/README.md +0 -3
package/lib/wgsl.js ADDED
@@ -0,0 +1,446 @@
1
+ // The WGSL in a project's own modules: `.wgsl` files that modules import, and template literals
2
+ // that a `wgsl` block comment tags, as in `const glow = /* wgsl */ `...``. The plugin compiles
3
+ // each with the engine's shader library, checks it against the portable WGSL rules, and puts the
4
+ // compiled result where its source was: WGSL for WebGPU, and GLSL ES 3.00 for WebGL2 with the
5
+ // reflection that the WebGL2 backend binds by. WGSL with entry points is a whole shader. WGSL
6
+ // without them holds a custom material's functions, such as `fn surface`, which the plugin builds
7
+ // into every variant of the engine's standard material, a custom effect's `fn effect` or tone
8
+ // curve's `fn toneCurve`, which it builds into the effect template or the final pass, or a sky
9
+ // layer's `fn skyLayer`, which it builds into the sky-layer template. WGSL that does not compile
10
+ // stops the module with an error at the file, line and column of each problem.
11
+ import { parseSync, Visitor } from 'vite';
12
+ import { compileHere, } from "./shader-compiler.js";
13
+ /** The block comment that tags a template literal as WGSL, with any spacing inside it. */
14
+ export const WGSL_TAG = /\/\*\s*wgsl\s*\*\//;
15
+ /** How to keep WGSL away from the plugin, for messages about WGSL that it cannot compile. */
16
+ const TAG_HINT = 'The plugin compiles every template literal that a `/* wgsl */` comment tags, so remove the tag from WGSL that null3D does not draw.';
17
+ const FILE_HINT = 'To import the text of a `.wgsl` file without compiling it, add `?raw` to the import.';
18
+ /** What is wrong with a substitution in a tagged template literal, and how to fix it. */
19
+ const SUBSTITUTION =
20
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: the message names the substitution syntax.
21
+ 'a template literal that a `/* wgsl */` comment tags cannot hold `${...}`. The plugin compiles the WGSL while it builds the project, before any of your code runs, so write the value in the WGSL itself.';
22
+ /** The parser's language for a script file, from its extension. */
23
+ function languageOf(file) {
24
+ const extension = /\.[cm]?([jt]sx?)$/.exec(file)?.[1];
25
+ return extension === 'ts' || extension === 'tsx' || extension === 'jsx' ? extension : 'js';
26
+ }
27
+ /**
28
+ * The template literals that a `wgsl` block comment tags in a script module. Only a real comment
29
+ * directly before a real template literal counts, so the same text inside a string or a line
30
+ * comment does not. Code that does not parse gives none: Vite reports its syntax error.
31
+ */
32
+ export function findTaggedWgsl(code, file) {
33
+ const parsed = parseSync(file, code, { lang: languageOf(file) });
34
+ if (parsed.errors.length > 0)
35
+ return [];
36
+ const literals = new Map();
37
+ new Visitor({
38
+ TemplateLiteral: (node) => {
39
+ literals.set(node.start, node);
40
+ },
41
+ }).visit(parsed.program);
42
+ const tagged = [];
43
+ for (const comment of parsed.comments) {
44
+ if (comment.type !== 'Block' || comment.value.trim() !== 'wgsl')
45
+ continue;
46
+ let at = comment.end;
47
+ while (at < code.length && /\s/.test(code.charAt(at)))
48
+ at++;
49
+ const literal = literals.get(at);
50
+ if (!literal)
51
+ continue;
52
+ const first = literal.expressions[0];
53
+ tagged.push({
54
+ start: literal.start,
55
+ end: literal.end,
56
+ source: code.slice(literal.start + 1, literal.end - 1).replaceAll('\r\n', '\n'),
57
+ substitution: first ? code.lastIndexOf('${', first.start) : null,
58
+ });
59
+ }
60
+ return tagged;
61
+ }
62
+ /** The place of an offset in a text. */
63
+ export function placeOf(text, offset) {
64
+ const lineStart = text.lastIndexOf('\n', offset - 1) + 1;
65
+ let line = 1;
66
+ for (let at = text.indexOf('\n'); at !== -1 && at < offset; at = text.indexOf('\n', at + 1))
67
+ line++;
68
+ return { line, column: offset - lineStart + 1 };
69
+ }
70
+ /** A WGSL name, as the language defines identifiers. */
71
+ const NAME = String.raw `[\p{XID_Start}_]\p{XID_Continue}*`;
72
+ /** A function declaration, with the attributes directly before it. */
73
+ const FUNCTION = new RegExp(String.raw `((?:@\s*${NAME}\s*(?:\([^()]*\))?\s*)*)\bfn\s+(${NAME})`, 'gu');
74
+ /** The stage attribute among a function's attributes. */
75
+ const STAGE = /@\s*(vertex|fragment|compute)\b/;
76
+ /** WGSL with each comment turned into spaces, so every other character keeps its offset. */
77
+ function blankComments(source) {
78
+ let text = '';
79
+ let depth = 0;
80
+ for (let i = 0; i < source.length; i++) {
81
+ const pair = source.slice(i, i + 2);
82
+ if (depth === 0 && pair === '//') {
83
+ const end = source.indexOf('\n', i);
84
+ const stop = end === -1 ? source.length : end;
85
+ text += ' '.repeat(stop - i);
86
+ i = stop - 1;
87
+ }
88
+ else if (pair === '/*') {
89
+ depth++;
90
+ text += ' ';
91
+ i++;
92
+ }
93
+ else if (depth > 0 && pair === '*/') {
94
+ depth--;
95
+ text += ' ';
96
+ i++;
97
+ }
98
+ else {
99
+ const char = source.charAt(i);
100
+ text += depth > 0 && char !== '\n' ? ' ' : char;
101
+ }
102
+ }
103
+ return text;
104
+ }
105
+ /** The functions that a custom material's WGSL may declare for the engine to call. */
106
+ const MATERIAL_FUNCTIONS = new Set([
107
+ 'surface',
108
+ 'vertexOffset',
109
+ 'lobe',
110
+ 'unlit',
111
+ ]);
112
+ /**
113
+ * True when WGSL is a draw shader: its `@vertex` entry point takes the vertex and instance indices
114
+ * and no mesh attribute, so the shader makes every vertex of every copy. Such a shader draws as a
115
+ * custom material of a draw that has no mesh data. A vertex entry point that reads a mesh attribute
116
+ * or an `InstanceIn` is not one, and a pass's own vertex shader reads the vertex index alone.
117
+ */
118
+ function isDrawShader(source) {
119
+ const text = blankComments(source);
120
+ for (const match of text.matchAll(FUNCTION)) {
121
+ if (!/@\s*vertex\b/.test(match[1] ?? ''))
122
+ continue;
123
+ const open = text.indexOf('(', match.index + match[0].length);
124
+ const close = open < 0 ? -1 : text.indexOf('{', open);
125
+ if (close <= open)
126
+ return false;
127
+ const args = text.slice(open, close);
128
+ if (/\bInstanceIn\b/.test(args) || /@\s*location\b/.test(args))
129
+ return false;
130
+ return /@\s*builtin\s*\(\s*instance_index\s*\)/.test(args);
131
+ }
132
+ return false;
133
+ }
134
+ /**
135
+ * True when WGSL is a mesh shader of its own: its `@vertex` entry point takes an `InstanceIn`, as
136
+ * `null3d::mesh` finds each instance of a mesh with. Such a shader draws as a custom material.
137
+ */
138
+ function isMeshShader(source) {
139
+ const text = blankComments(source);
140
+ for (const match of text.matchAll(FUNCTION)) {
141
+ if (!/@\s*vertex\b/.test(match[1] ?? ''))
142
+ continue;
143
+ const open = text.indexOf('(', match.index + match[0].length);
144
+ const close = open < 0 ? -1 : text.indexOf('{', open);
145
+ if (close > open && /\bInstanceIn\b/.test(text.slice(open, close)))
146
+ return true;
147
+ }
148
+ return false;
149
+ }
150
+ /** The functions that a custom effect's or tone curve's WGSL declares for the engine to call. */
151
+ const POST_FUNCTIONS = new Set(['effect', 'toneCurve']);
152
+ /** The functions that a sky layer's WGSL declares for the engine to call. */
153
+ const SKY_LAYER_FUNCTIONS = new Set(['skyLayer']);
154
+ /** True when WGSL declares a function of `functions`, such as a custom material's `fn surface`. */
155
+ function declaresFunction(source, functions) {
156
+ for (const match of blankComments(source).matchAll(FUNCTION))
157
+ if (functions.has(match[2] ?? ''))
158
+ return true;
159
+ return false;
160
+ }
161
+ /**
162
+ * The entry points that a shader declares, each once. Code behind shader defs counts too, so a
163
+ * stage that `#ifdef` lines declare twice under one name is one entry point.
164
+ */
165
+ function entryPoints(source) {
166
+ const found = new Map();
167
+ for (const match of blankComments(source).matchAll(FUNCTION)) {
168
+ const stage = STAGE.exec(match[1] ?? '');
169
+ const name = match[2] ?? '';
170
+ const kind = stage?.[1];
171
+ if (!stage || !kind || found.has(`${kind} ${name}`))
172
+ continue;
173
+ found.set(`${kind} ${name}`, { stage: kind, name, at: match.index + stage.index });
174
+ }
175
+ return [...found.values()];
176
+ }
177
+ /**
178
+ * A problem that the plugin finds itself, at an offset in a text. Its column counts characters, as
179
+ * the compiler's columns do.
180
+ */
181
+ function problemAt(path, text, offset, message) {
182
+ const { line, column } = placeOf(text, offset);
183
+ const before = [...text.slice(offset - column + 1, offset)].length;
184
+ return { file: path, line, column: before + 1, feature: null, message, variants: [] };
185
+ }
186
+ /**
187
+ * The render pipelines of a shader: one for each `@fragment` entry point, named after it, with
188
+ * the shader's `@vertex` entry point. A shader with only `@compute` entry points has none.
189
+ */
190
+ function pipelinesOf(path, source, hint) {
191
+ const entries = entryPoints(source);
192
+ const [vertex, secondVertex] = entries.filter((entry) => entry.stage === 'vertex');
193
+ const fragments = entries.filter((entry) => entry.stage === 'fragment');
194
+ const problem = (at, message) => ({
195
+ problem: problemAt(path, source, at, message),
196
+ });
197
+ if (entries.length === 0) {
198
+ return problem(0, `the WGSL has no entry point and no function of a custom material, effect or sky layer. For a custom material, declare \`fn surface(input: SurfaceInput) -> Surface\`, \`fn vertexOffset(input: VertexInput) -> vec3f\`, \`fn lobe(input: LobeInput) -> vec3f\`, or some of them. For an effect, declare \`fn effect(input: EffectInput) -> vec4f\`, for a tone curve \`fn toneCurve(color: vec3f) -> vec3f\`, and for a sky layer \`fn skyLayer(input: SkyLayerInput) -> SkyLayer\`. For a shader of your own, give it a \`@vertex\` and a \`@fragment\` entry point, or a \`@compute\` one. ${hint}`);
199
+ }
200
+ if (secondVertex) {
201
+ return problem(secondVertex.at, 'the WGSL has more than one `@vertex` entry point. The plugin pairs each `@fragment` entry point with the one `@vertex` entry point of its shader, so keep one, or split the shader in two.');
202
+ }
203
+ const [fragment] = fragments;
204
+ if (fragment && !vertex) {
205
+ return problem(fragment.at, 'the WGSL has a `@fragment` entry point but no `@vertex` one. A render pipeline needs both, so add a `@vertex` entry point.');
206
+ }
207
+ if (vertex && !fragment) {
208
+ return problem(vertex.at, 'the WGSL has a `@vertex` entry point but no `@fragment` one. A render pipeline needs both, so add a `@fragment` entry point.');
209
+ }
210
+ const pipelines = {};
211
+ for (const { name } of fragments)
212
+ pipelines[name] = { vertex: vertex?.name ?? '', fragment: name };
213
+ return { pipelines };
214
+ }
215
+ /** The builds of a shader from a project: one for WebGPU, and one for WebGL2. */
216
+ const BUILDS = {
217
+ webgpu: { targets: ['wgsl'] },
218
+ webgl2: { defs: ['WEBGL2'], targets: ['glsl'] },
219
+ };
220
+ /**
221
+ * What a compile of a project's WGSL of `source` does. WGSL without entry points that declares a
222
+ * post function is an effect or a tone curve, one that declares `skyLayer` is a sky layer, and one
223
+ * that declares a material function is a custom material. WGSL with entry points is a whole
224
+ * shader, one that the engine's mesh calls or a draw shader. `hint` ends the message about WGSL
225
+ * that is none of these.
226
+ */
227
+ function planOf(path, source, hint) {
228
+ const noEntryPoints = entryPoints(source).length === 0;
229
+ if (noEntryPoints && declaresFunction(source, SKY_LAYER_FUNCTIONS))
230
+ return { kind: 'skyLayer' };
231
+ if (noEntryPoints && declaresFunction(source, POST_FUNCTIONS))
232
+ return { kind: 'effect' };
233
+ const draw = isDrawShader(source);
234
+ if ((noEntryPoints && declaresFunction(source, MATERIAL_FUNCTIONS)) ||
235
+ draw ||
236
+ isMeshShader(source))
237
+ return { kind: 'material', draw };
238
+ const shape = pipelinesOf(path, source, hint);
239
+ if ('problem' in shape)
240
+ return { kind: 'problem', problem: shape.problem };
241
+ const render = Object.keys(shape.pipelines).length > 0;
242
+ const variants = render ? BUILDS : { webgpu: BUILDS.webgpu };
243
+ return { kind: 'shader', pipelines: shape.pipelines, variants, builds: Object.keys(variants) };
244
+ }
245
+ /** An effect's or a tone curve's compile as the result of compiling WGSL from a project. */
246
+ function effectOutcome(result) {
247
+ // Effects and tone curves build for both GPU paths.
248
+ const builds = ['webgpu', 'webgl2'];
249
+ if (!result.ok)
250
+ return { ok: false, problems: result.problems, builds };
251
+ const { warnings } = result;
252
+ const { function: kind, uniforms, depth, bloom, joins, textures, variants, pieces, } = result.effect;
253
+ if (kind === 'toneCurve')
254
+ return { ok: true, shader: { kind, variants, pieces }, warnings, builds };
255
+ return {
256
+ ok: true,
257
+ shader: { kind, uniforms, depth, bloom, joins, textures, variants, pieces },
258
+ warnings,
259
+ builds,
260
+ };
261
+ }
262
+ /** A sky layer's compile as the result of compiling WGSL from a project. */
263
+ function skyLayerOutcome(result) {
264
+ // A sky layer builds for both GPU paths.
265
+ const builds = ['webgpu', 'webgl2'];
266
+ if (!result.ok)
267
+ return { ok: false, problems: result.problems, builds };
268
+ return {
269
+ ok: true,
270
+ shader: { kind: 'skyLayer', variants: result.layer.variants, map: result.layer.map },
271
+ warnings: result.warnings,
272
+ builds,
273
+ };
274
+ }
275
+ /** A custom material's compile as the result of compiling WGSL from a project. */
276
+ function materialOutcome(result, draw) {
277
+ // Custom materials build for both GPU paths.
278
+ const builds = ['webgpu', 'webgl2'];
279
+ if (!result.ok)
280
+ return { ok: false, problems: result.problems, builds };
281
+ const shader = {
282
+ kind: 'material',
283
+ ...result.material,
284
+ ...(draw && { meshless: true }),
285
+ };
286
+ return { ok: true, shader, warnings: result.warnings, builds };
287
+ }
288
+ /** A whole shader's compile as the result of compiling WGSL from a project. */
289
+ function shaderOutcome(result, builds) {
290
+ if (!result.ok)
291
+ return { ok: false, problems: result.problems, builds };
292
+ const { webgpu, webgl2 } = result.variants;
293
+ if (!webgpu)
294
+ throw new Error('null3D: the shader compiler gave no WebGPU build.');
295
+ const shader = { kind: 'shader', webgpu, webgl2: webgl2 ?? null };
296
+ return { ok: true, shader, warnings: result.warnings, builds };
297
+ }
298
+ /**
299
+ * Compiles WGSL from a project with the engine's shader library. A whole shader builds for WebGPU,
300
+ * and for WebGL2 when it has a render pipeline. A custom material's functions build into every
301
+ * variant of the engine's standard material, and a custom effect's or tone curve's into its
302
+ * template. `path` names the file in messages, and `hint` ends the message about WGSL that is
303
+ * none of these. `compiler` runs the compile, on this thread by default.
304
+ */
305
+ export async function compileWgsl(path, source, hint, compiler = compileHere) {
306
+ const plan = planOf(path, source, hint);
307
+ switch (plan.kind) {
308
+ case 'problem':
309
+ return { ok: false, problems: [plan.problem], builds: [] };
310
+ case 'effect':
311
+ return effectOutcome(await compiler.effect({ path, source }));
312
+ case 'skyLayer':
313
+ return skyLayerOutcome(await compiler.skyLayer({ path, source }));
314
+ case 'material':
315
+ return materialOutcome(await compiler.material({ path, source }), plan.draw);
316
+ case 'shader':
317
+ return shaderOutcome(await compiler.shader({ path, source, pipelines: plan.pipelines, variants: plan.variants }), plan.builds);
318
+ }
319
+ }
320
+ /** The 1-based UTF-16 column of a 1-based column that counts characters, in a line. */
321
+ function utf16Column(line, column) {
322
+ const chars = [...line];
323
+ return chars.slice(0, column - 1).join('').length + 1 + Math.max(0, column - 1 - chars.length);
324
+ }
325
+ /**
326
+ * A problem at its place in the file that holds the WGSL. The compiler counts from the start of
327
+ * the WGSL, and a template literal starts part way into a module.
328
+ */
329
+ function inFile(problem, source, origin) {
330
+ if (problem.file !== origin.path || problem.line === null)
331
+ return problem;
332
+ const text = source.split('\n')[problem.line - 1] ?? '';
333
+ const column = problem.column === null ? null : utf16Column(text, problem.column);
334
+ const first = problem.line === 1;
335
+ return {
336
+ ...problem,
337
+ line: origin.line + problem.line - 1,
338
+ column: column === null ? null : first ? origin.column + column - 1 : column,
339
+ };
340
+ }
341
+ /** The GPU path of a build, as messages name it, from the start of the build's name. */
342
+ function pathOf(build) {
343
+ return build.startsWith('webgl2') ? 'WebGL2' : 'WebGPU';
344
+ }
345
+ /**
346
+ * A problem as one line of a message: its place, what is wrong, and the GPU path whose builds have
347
+ * it, when not every path's builds do. `builds` names every build that the compile made.
348
+ */
349
+ function describe(problem, builds) {
350
+ const place = [problem.file, problem.line, problem.column].filter((part) => part !== null);
351
+ const paths = new Set(problem.variants.map(pathOf));
352
+ const [only] = paths;
353
+ const partial = paths.size === 1 && new Set(builds.map(pathOf)).size > 1;
354
+ const build = partial ? ` (in the ${only} build)` : '';
355
+ return `${place.length > 0 ? `${place.join(':')}: ` : ''}${problem.message}${build}`;
356
+ }
357
+ /**
358
+ * The error for WGSL that did not compile. It lists every problem, and shows the first one in the
359
+ * WGSL's own file, or else the WGSL's start. `id` is the file's module id, and `text` its text.
360
+ */
361
+ export function wgslError(failed, source, origin, id, text) {
362
+ const problems = failed.problems.map((problem) => inFile(problem, source, origin));
363
+ const shown = problems.find((problem) => problem.file === origin.path && problem.line !== null);
364
+ const line = shown?.line ?? origin.line;
365
+ const column = shown ? (shown.column ?? 1) : origin.column;
366
+ const lines = problems.map((problem) => describe(problem, failed.builds));
367
+ return {
368
+ message: `null3D could not compile the WGSL:\n${lines.join('\n')}`,
369
+ id,
370
+ loc: { file: id, line, column },
371
+ frame: codeFrame(text, line, column),
372
+ };
373
+ }
374
+ /**
375
+ * The warnings of compiled WGSL, each as one line of a message with its place in the file that
376
+ * holds the WGSL.
377
+ */
378
+ function warningLines(compiled, source, origin) {
379
+ return compiled.warnings.map((warning) => `null3D: ${describe(inFile(warning, source, origin), compiled.builds)}`);
380
+ }
381
+ /** A `.wgsl` file's compile as the shader that takes its place, or the error that stops it. */
382
+ function fileOutcome(compiled, source, origin, id) {
383
+ if (compiled.ok)
384
+ return { shader: compiled.shader, warnings: warningLines(compiled, source, origin) };
385
+ return { error: wgslError(compiled, source, origin, id, source) };
386
+ }
387
+ /**
388
+ * Compiles a `.wgsl` file. `path` names the file in messages, `id` is its module id, and `text` its
389
+ * content as read from disk.
390
+ */
391
+ export async function compileWgslFile(path, id, text, compiler = compileHere) {
392
+ const source = text.replaceAll('\r\n', '\n');
393
+ const compiled = await compileWgsl(path, source, FILE_HINT, compiler);
394
+ return fileOutcome(compiled, source, { path, line: 1, column: 1 }, id);
395
+ }
396
+ /**
397
+ * Compiles one tagged template literal of a script module, whose code is `code`: the compiled
398
+ * WGSL that takes its place, or the error that stops the module.
399
+ */
400
+ export async function compileLiteral(literal, code, id, path, compiler = compileHere) {
401
+ if (literal.substitution !== null) {
402
+ const problem = problemAt(path, code, literal.substitution, SUBSTITUTION);
403
+ const failed = { ok: false, problems: [problem], builds: [] };
404
+ return { error: wgslError(failed, code, { path, line: 1, column: 1 }, id, code) };
405
+ }
406
+ const origin = { path, ...placeOf(code, literal.start + 1) };
407
+ const compiled = await compileWgsl(path, literal.source, TAG_HINT, compiler);
408
+ if (compiled.ok)
409
+ return { shader: compiled.shader, warnings: warningLines(compiled, literal.source, origin) };
410
+ return { error: wgslError(compiled, literal.source, origin, id, code) };
411
+ }
412
+ /**
413
+ * Compiles each tagged template literal in a script module, all at once, with every literal's
414
+ * warnings, or gives the error that stops the module at its first literal that does not compile.
415
+ */
416
+ export async function compileTaggedWgsl(code, id, path, compiler = compileHere) {
417
+ const literals = findTaggedWgsl(code, id);
418
+ const results = await Promise.all(literals.map((literal) => compileLiteral(literal, code, id, path, compiler)));
419
+ const shaders = [];
420
+ const warnings = [];
421
+ for (const [k, result] of results.entries()) {
422
+ if ('error' in result)
423
+ return result;
424
+ const { start, end } = literals[k];
425
+ shaders.push({ start, end, shader: result.shader });
426
+ warnings.push(...result.warnings);
427
+ }
428
+ return { shaders, warnings };
429
+ }
430
+ /** Lines of text around a place, each with its number, and a caret under the place's column. */
431
+ export function codeFrame(text, line, column) {
432
+ const lines = text.split('\n');
433
+ const first = Math.max(1, line - 2);
434
+ const last = Math.min(lines.length, line + 2);
435
+ const width = String(last).length;
436
+ const frame = [];
437
+ for (let number = first; number <= last; number++) {
438
+ const content = (lines[number - 1] ?? '').replace(/\r$/, '');
439
+ frame.push(`${String(number).padStart(width)} | ${content}`);
440
+ if (number === line) {
441
+ const indent = content.slice(0, column - 1).replace(/[^\t]/g, ' ');
442
+ frame.push(`${' '.repeat(width)} | ${indent}^`);
443
+ }
444
+ }
445
+ return frame.join('\n');
446
+ }
@@ -0,0 +1,17 @@
1
+ import MagicString from 'magic-string';
2
+ import type { Plugin } from 'vite';
3
+ /** The chunks that a chunk imports, directly or through others, with the chunk itself. */
4
+ export declare function staticImports(fileName: string, chunks: Readonly<Record<string, {
5
+ imports: readonly string[];
6
+ }>>): Set<string>;
7
+ /**
8
+ * Rewrites each import on demand in a chunk's code so that it also starts the downloads of the
9
+ * files that the imported file needs and the chunk has not loaded yet. Each of those downloads
10
+ * ignores a failure, which the imported file's own import reports. Returns true when an import
11
+ * changed.
12
+ */
13
+ export declare function preloadImports(code: MagicString, fileName: string, chunks: Readonly<Record<string, {
14
+ imports: readonly string[];
15
+ }>>): boolean;
16
+ /** The plugin for each worker build. */
17
+ export declare function workerPreloadPlugin(): Plugin;
@@ -0,0 +1,65 @@
1
+ // Starts the downloads of the files that an on-demand file of a worker imports, together with the
2
+ // file. Vite does this on the page, where it loads such a file through its preload helper, and not
3
+ // in a worker. In a worker, the browser asks for a file's imports only once the file has arrived,
4
+ // one round trip later. The engine's drawing threads load their GPU path's renderers on demand, and
5
+ // the bundler puts the code that both paths share into a file of its own that each path's file
6
+ // imports. Without this plugin, a worker that draws would ask for that file a round trip after its
7
+ // path's file, at the start, while the core downloads.
8
+ import { posix } from 'node:path';
9
+ import MagicString from 'magic-string';
10
+ /** An import on demand of another file of the bundle, as the bundler writes it: `import("./x.js")`. */
11
+ const DYNAMIC_IMPORT = /\bimport\(\s*(["'`])(\.{1,2}\/[^"'`]+)\1\s*\)/g;
12
+ /** The chunks that a chunk imports, directly or through others, with the chunk itself. */
13
+ export function staticImports(fileName, chunks) {
14
+ const seen = new Set([fileName]);
15
+ for (const name of seen)
16
+ for (const imported of chunks[name]?.imports ?? [])
17
+ seen.add(imported);
18
+ return seen;
19
+ }
20
+ /** The address of `to` from the folder of `from`, as an import names it. */
21
+ function importAddress(from, to) {
22
+ const path = posix.relative(posix.dirname(from), to);
23
+ return path.startsWith('.') ? path : `./${path}`;
24
+ }
25
+ /**
26
+ * Rewrites each import on demand in a chunk's code so that it also starts the downloads of the
27
+ * files that the imported file needs and the chunk has not loaded yet. Each of those downloads
28
+ * ignores a failure, which the imported file's own import reports. Returns true when an import
29
+ * changed.
30
+ */
31
+ export function preloadImports(code, fileName, chunks) {
32
+ const loaded = staticImports(fileName, chunks);
33
+ let changed = false;
34
+ for (const match of code.original.matchAll(DYNAMIC_IMPORT)) {
35
+ const [text, quote, address] = match;
36
+ const target = posix.join(posix.dirname(fileName), address);
37
+ if (!chunks[target])
38
+ continue;
39
+ const missing = [...staticImports(target, chunks)].filter((name) => name !== target && !loaded.has(name));
40
+ if (missing.length === 0)
41
+ continue;
42
+ const starts = missing
43
+ .map((name) => `import(${quote}${importAddress(fileName, name)}${quote}).catch(()=>{}),`)
44
+ .join('');
45
+ code.prependLeft(match.index, `(${starts}`);
46
+ code.appendRight(match.index + text.length, ')');
47
+ changed = true;
48
+ }
49
+ return changed;
50
+ }
51
+ /** The plugin for each worker build. */
52
+ export function workerPreloadPlugin() {
53
+ return {
54
+ name: 'null3d:worker-preload',
55
+ renderChunk(code, chunk, _options, meta) {
56
+ const chunks = meta.chunks;
57
+ if (!chunks || chunk.dynamicImports.length === 0)
58
+ return null;
59
+ const edited = new MagicString(code);
60
+ if (!preloadImports(edited, chunk.fileName, chunks))
61
+ return null;
62
+ return { code: edited.toString(), map: edited.generateMap({ hires: true }) };
63
+ },
64
+ };
65
+ }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
- "name": "@null3d/vite-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@null3d/vite-plugin",
3
+ "version": "0.0.0",
4
+ "description": "Vite plugin for null3D projects: cross-origin isolation headers, HTTPS for testing on phones and tablets, WGSL compiled for WebGPU and WebGL2, glTF models optimized on import, and production builds that compile the sketch module and ship the engine core.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "author": "Ramesh Nair (https://hiddentao.com)",
7
+ "homepage": "https://github.com/null3d-engine/null3d#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/null3d-engine/null3d.git",
11
+ "directory": "packages/vite-plugin"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/null3d-engine/null3d/issues"
15
+ },
16
+ "keywords": [
17
+ "null3d",
18
+ "vite-plugin",
19
+ "wgsl",
20
+ "webgpu",
21
+ "webgl2"
22
+ ],
23
+ "type": "module",
24
+ "exports": {
25
+ ".": {
26
+ "null3d-source": "./src/index.ts",
27
+ "types": "./lib/index.d.ts",
28
+ "default": "./lib/index.js"
29
+ },
30
+ "./client": {
31
+ "null3d-source": "./src/client.d.ts",
32
+ "types": "./lib/client.d.ts"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "files": [
37
+ "lib",
38
+ "dist/shader-compiler.wasm",
39
+ "dist/shader-compiler.stamp.json",
40
+ "LICENSE-MIT",
41
+ "LICENSE-APACHE",
42
+ "THIRD-PARTY-NOTICES.txt"
43
+ ],
44
+ "publishConfig": {
45
+ "access": "public",
46
+ "provenance": true
47
+ },
48
+ "engines": {
49
+ "node": "^20.19.0 || >=22.12.0"
50
+ },
51
+ "scripts": {
52
+ "prepack": "bun ../../tools/build-package.ts vite-plugin"
53
+ },
54
+ "peerDependencies": {
55
+ "@null3d/cli": "0.0.0",
56
+ "vite": ">=8"
57
+ },
58
+ "peerDependenciesMeta": {
59
+ "@null3d/cli": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "devDependencies": {
64
+ "@null3d/cli": "0.0.0",
65
+ "vite": "8.3.1"
66
+ },
67
+ "dependencies": {
68
+ "magic-string": "^1.4.2"
69
+ }
70
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.