@null3d/vite-plugin 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -70,6 +70,12 @@ null3d({ shaders: { list: 'shader-permutations.txt' } });
70
70
  copies only the builds of the listed words, and fails when the engine's shader set lacks a listed
71
71
  word. Without it, a build copies the whole set, thousands of files and gigabytes, and warns with
72
72
  the size that it copied.
73
+ - `shaders.gpuPaths` names the GPU paths whose shaders a build ships, such as `['webgpu']` for an
74
+ app whose browser always offers WebGPU. A build then copies no WebGL2 shader files, and compiles
75
+ your own shaders for WebGPU alone. A page on a device that would need WebGL2 fails with E1308,
76
+ and the value must include `webgpu` (the default is both paths). The dev server keeps both paths
77
+ and warns when a page draws the one that a build drops, and the option combines with
78
+ `shaders.list`.
73
79
  - `urlSwitches` lets the page's address set the engine's test switches, such as `?gpu=`, in a
74
80
  production build too. Leave it out for a shipped game. Development builds then read the
75
81
  switches and production builds do not, so a link cannot change how the game runs. An explicit
@@ -1,4 +1,4 @@
1
1
  {
2
2
  "format": 1,
3
- "version": "21d3fb43a511eea0e400339541b061b731b80422a47f8fa65c2e9013b6f45691"
3
+ "version": "cd52f437944c959009d454c1c6cab1be5287d0762ce24ee56a562fb783e98c23"
4
4
  }
Binary file
package/lib/hot.d.ts CHANGED
@@ -12,14 +12,19 @@ export declare const HOT_CLIENT_ADDRESS: RegExp;
12
12
  export declare const PERMUTATION_WORD_EVENT = "null3d:permutation";
13
13
  /** The event that carries the dev server's warning about a word that the project's list lacks. */
14
14
  export declare const UNLISTED_WORD_EVENT = "null3d:unlisted";
15
+ /** The event that carries the GPU path that a page's engine started on, from the page to the server. */
16
+ export declare const GPU_PATH_EVENT = "null3d:gpu-path";
17
+ /** The event that carries the dev server's warning about a GPU path that a build does not ship. */
18
+ export declare const UNSHIPPED_PATH_EVENT = "null3d:unshipped-path";
15
19
  /**
16
20
  * The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. In a
17
21
  * project with a shader list (`listed`), it also sends the dev server each permutation word that
18
22
  * the page's engines draw with, once, and shows the server's warning about a word that the list
19
23
  * lacks in the browser's console. A recording run adds its page's words to the list, so it sends
20
- * none.
24
+ * none. With `paths`, it sends the GPU path that each engine started on, and shows the server's
25
+ * warning about a path that a production build does not ship.
21
26
  */
22
- export declare function hotClientCode(listed: boolean): string;
27
+ export declare function hotClientCode(listed: boolean, paths?: boolean): string;
23
28
  /** One hot update: the new compiled WGSL under its key. */
24
29
  export interface WgslUpdate {
25
30
  readonly key: string;
@@ -61,3 +66,9 @@ export declare class HotState {
61
66
  */
62
67
  swaps(key: string, shader: CompiledWgsl): boolean;
63
68
  }
69
+ /**
70
+ * The dev server's warning when a page draws a GPU path that a production build does not ship, or
71
+ * undefined when the page draws a path that the build ships. Only the WebGL2 path can be left out:
72
+ * the shader compiler builds every shader for WebGPU.
73
+ */
74
+ export declare function unshippedPathWarning(path: string, page: string, glsl: boolean): string | undefined;
package/lib/hot.js CHANGED
@@ -11,14 +11,19 @@ export const HOT_CLIENT_ADDRESS = /^\0?virtual:null3d\/hot$/;
11
11
  export const PERMUTATION_WORD_EVENT = 'null3d:permutation';
12
12
  /** The event that carries the dev server's warning about a word that the project's list lacks. */
13
13
  export const UNLISTED_WORD_EVENT = 'null3d:unlisted';
14
+ /** The event that carries the GPU path that a page's engine started on, from the page to the server. */
15
+ export const GPU_PATH_EVENT = 'null3d:gpu-path';
16
+ /** The event that carries the dev server's warning about a GPU path that a build does not ship. */
17
+ export const UNSHIPPED_PATH_EVENT = 'null3d:unshipped-path';
14
18
  /**
15
19
  * The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. In a
16
20
  * project with a shader list (`listed`), it also sends the dev server each permutation word that
17
21
  * the page's engines draw with, once, and shows the server's warning about a word that the list
18
22
  * lacks in the browser's console. A recording run adds its page's words to the list, so it sends
19
- * none.
23
+ * none. With `paths`, it sends the GPU path that each engine started on, and shows the server's
24
+ * warning about a path that a production build does not ship.
20
25
  */
21
- export function hotClientCode(listed) {
26
+ export function hotClientCode(listed, paths = false) {
22
27
  const wgsl = ` import.meta.hot.on(${JSON.stringify(WGSL_UPDATE_EVENT)}, ({ updates }) => {
23
28
  for (const overlay of document.querySelectorAll('vite-error-overlay')) overlay.close();
24
29
  globalThis.dispatchEvent(new CustomEvent(${JSON.stringify(WGSL_UPDATE_EVENT)}, { detail: updates }));
@@ -35,7 +40,17 @@ export function hotClientCode(listed) {
35
40
  import.meta.hot.on(${JSON.stringify(UNLISTED_WORD_EVENT)}, ({ message }) => console.warn('[null3D] ' + message));
36
41
  }
37
42
  `;
38
- return `if (import.meta.hot) {\n${wgsl}${listed ? words : ''}}\n`;
43
+ const gpuPaths = ` {
44
+ const sent = new Set();
45
+ globalThis.addEventListener(${JSON.stringify(GPU_PATH_EVENT)}, ({ detail: path }) => {
46
+ if (sent.has(path)) return;
47
+ sent.add(path);
48
+ import.meta.hot.send(${JSON.stringify(GPU_PATH_EVENT)}, { path, page: location.pathname });
49
+ });
50
+ import.meta.hot.on(${JSON.stringify(UNSHIPPED_PATH_EVENT)}, ({ message }) => console.warn('[null3D] ' + message));
51
+ }
52
+ `;
53
+ return `if (import.meta.hot) {\n${wgsl}${listed ? words : ''}${paths ? gpuPaths : ''}}\n`;
39
54
  }
40
55
  /**
41
56
  * The key of a project's WGSL: a `.wgsl` file's path from the project's root, or that of a script
@@ -120,3 +135,13 @@ export class HotState {
120
135
  return before !== undefined && before !== null && before === after;
121
136
  }
122
137
  }
138
+ /**
139
+ * The dev server's warning when a page draws a GPU path that a production build does not ship, or
140
+ * undefined when the page draws a path that the build ships. Only the WebGL2 path can be left out:
141
+ * the shader compiler builds every shader for WebGPU.
142
+ */
143
+ export function unshippedPathWarning(path, page, glsl) {
144
+ if (glsl || path !== 'webgl2')
145
+ return undefined;
146
+ return `${page} draws with WebGL2, which a production build with shaders.gpuPaths: ['webgpu'] does not ship. That build stops the page with E1308. Run the page's tests on WebGPU, or build with both GPU paths.`;
147
+ }
package/lib/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { type AssetOptions } from './assets.js';
3
3
  import { type ShaderOptions } from './shader-list.js';
4
4
  export type { AssetOptions } from './assets.js';
5
5
  export { FILES_LIST, type OfflineFiles } from './offline.js';
6
- export type { ShaderOptions } from './shader-list.js';
6
+ export type { GpuPath, ShaderOptions } from './shader-list.js';
7
7
  export type * from './shader-types.js';
8
8
  /** Headers that make a page cross-origin isolated, which shared memory and worker threads need. */
9
9
  export declare const ISOLATION_HEADERS: Readonly<Record<string, string>>;
package/lib/index.js CHANGED
@@ -11,14 +11,14 @@ import { writeWgslDeclaration } from "./declarations.js";
11
11
  import { ENGINE_SHADERS_ENV, engineShaderFolder, engineShadersRoot, ensureEngineShaders, } from "./engine-shaders.js";
12
12
  import { buildEngineShadersLocally } from "./engine-shaders-local.js";
13
13
  import { HashPool } from "./hash-pool.js";
14
- import { changedLiterals, HOT_CLIENT, HOT_CLIENT_ADDRESS, HOT_CLIENT_ID, HotState, hotClientCode, hotKey, PERMUTATION_WORD_EVENT, UNLISTED_WORD_EVENT, WGSL_UPDATE_EVENT, } from "./hot.js";
14
+ import { changedLiterals, GPU_PATH_EVENT, HOT_CLIENT, HOT_CLIENT_ADDRESS, HOT_CLIENT_ID, HotState, hotClientCode, hotKey, PERMUTATION_WORD_EVENT, UNLISTED_WORD_EVENT, UNSHIPPED_PATH_EVENT, unshippedPathWarning, WGSL_UPDATE_EVENT, } from "./hot.js";
15
15
  import { MATERIAL_BUILDS_ADDRESS, MaterialBuilds, ModuleBuilds } from "./material-builds.js";
16
16
  import { engineModule, FILES_LIST, featuresOf, listedFiles, missingWorkerAssets, offlineFiles, workerFilesPlugin, } from "./offline.js";
17
- import { ShaderPack } from "./pack.js";
17
+ import { narrowShaderPack, ShaderPack, UNPACK } from "./pack.js";
18
18
  import { null3dPackages } from "./package-files.js";
19
- import { emitParagraphTables, shaderParagraphsPlugin, tableImportsOfFile } from "./paragraphs.js";
19
+ import { emitParagraphTables, rewriteCopyFile, tableImportsOfFile, } from "./paragraphs.js";
20
20
  import { ShaderCache, shaderCacheOff } from "./shader-cache.js";
21
- import { builtWords, holdWord, listedPermutationsModule, narrowParagraphTable, narrowShaderModule, ShaderList, UNLISTED_MODULE, UnlistedWords, wordText, } from "./shader-list.js";
21
+ import { builtWords, holdWord, moduleWords, narrowShaderModule, ShaderList, shaderMarkersModule, shippedTargets, targetOfModule, UNLISTED_MODULE, UnlistedWords, wordText, } from "./shader-list.js";
22
22
  import { compileLiteral, compileTaggedWgsl, compileWgslFile, WGSL_TAG, } from "./wgsl.js";
23
23
  import { directImports, workerPreloadPlugin } from "./worker-preload.js";
24
24
  export { FILES_LIST } from "./offline.js";
@@ -268,6 +268,37 @@ const GENERATED_MODULE = /^shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/;
268
268
  const LISTED_MODULE = /^shader-permutations\.[cm]?[jt]s$/;
269
269
  /** The start of the name of the module that stands for every device file a list leaves out. */
270
270
  const UNLISTED_STEM = 'shaders-unlisted';
271
+ /**
272
+ * The module id that stands for a generated module of a GPU path that a build does not ship. The
273
+ * names that the module exports follow it, so one stub serves every table that exports the same
274
+ * names, such as the tables of builds that need several features.
275
+ */
276
+ const NO_SHADER_MARK = 'null3d:no-shader/';
277
+ const NO_SHADER_ID = `\0${NO_SHADER_MARK}`;
278
+ /** The start of the id of a stub module, with or without Vite's null byte. */
279
+ const NO_SHADER_PATTERN = /^\0?null3d:no-shader\//;
280
+ /** The code of a stub module, which exports each name that it stands for as an empty object. */
281
+ function stubModule(names) {
282
+ return `${names.map((name) => `export const ${name} = {};`).join('\n')}\n`;
283
+ }
284
+ /**
285
+ * True for the folder of a generated shader set, which holds the marker module that every set has.
286
+ * Only a module of such a folder takes a stub, so a project's own file that happens to share a name
287
+ * never does.
288
+ */
289
+ function inShaderSet(folder) {
290
+ return ['shader-permutations.ts', 'shader-permutations.js'].some((name) => existsSync(join(folder, name)));
291
+ }
292
+ /**
293
+ * The names that a generated shader module exports, in the order the shader build writes them. The
294
+ * stub of a module that a build drops exports the same names, so every import of it resolves.
295
+ */
296
+ function exportNamesOf(text, file) {
297
+ const names = [...text.matchAll(/^export (?:const|function|class) ([A-Za-z_$][\w$]*)/gm)].map((match) => match[1]);
298
+ if (names.length === 0)
299
+ throw new Error(`null3D cannot read the exports of the engine's shader module ${file}, so it cannot stand an empty one in its place. Install the same version of @null3d/vite-plugin as of @null3d/engine, or run bun run shaders in a checkout.`);
300
+ return names;
301
+ }
271
302
  /** The docs on a project's list of permutation words, which the build's report names. */
272
303
  const SHADER_LIST_DOCS = 'https://github.com/null3d-engine/null3d/blob/generated/docs/guides/assets-pipeline.md#build-only-the-shader-permutations-you-draw-with';
273
304
  /** A number of bytes in megabytes, as the build's report gives it. */
@@ -355,6 +386,11 @@ export default function null3d(options = {}) {
355
386
  let building = false;
356
387
  /** True for a production build of pages, which gets the early script. */
357
388
  let buildingPages = false;
389
+ /**
390
+ * The GPU paths whose shaders a build ships. The dev server keeps both, so a developer can test
391
+ * the other path, and a build narrows the set and the project's own shaders to this.
392
+ */
393
+ const shipped = shippedTargets(options.shaders);
358
394
  /** The early script's module, once a build of pages that imports the engine has added it. */
359
395
  let earlyCoreId;
360
396
  /** True once the build has looked for the early script. */
@@ -404,24 +440,34 @@ export default function null3d(options = {}) {
404
440
  const bytes = join(narrowedFolder, name);
405
441
  if (!existsSync(bytes))
406
442
  writeFileSync(bytes, text);
407
- return { name, bytes, source: source ?? bytes };
443
+ return { name, stem, bytes, source: source ?? bytes };
408
444
  };
409
445
  /**
410
- * The copy of a generated shader file. Without a list it is the file itself, named by its hash.
411
- * With one, a file whose builds the list all names stays whole, a file of which it names some
412
- * keeps only those, and a file of which it names none gives way to one module without builds.
446
+ * The copy of a generated shader file. A file of a GPU path that this build does not ship gives
447
+ * way to one module without builds, and the build copies it for every such file. With a list, a
448
+ * file whose builds the list all names stays whole, a file of which it names some keeps only
449
+ * those, and a file of which it names none gives way to one module without builds.
413
450
  */
414
451
  const copyOf = async (file) => {
415
452
  const stem = file.slice(file.lastIndexOf('/') + 1).replace(/\.js$/, '');
453
+ const target = targetOfModule(file);
454
+ if (target !== null && !shipped[target]) {
455
+ // The words of a dropped file still answer the project's list, which may hold a word that
456
+ // only the other GPU path builds, such as a morph target's.
457
+ if (shaderList !== undefined)
458
+ for (const word of (await hasher.scan(file)).words)
459
+ holdWord(heldWords, word);
460
+ return narrowedCopy(UNLISTED_STEM, UNLISTED_MODULE);
461
+ }
416
462
  const list = shaderList;
417
463
  if (list === undefined)
418
- return { name: `${stem}-${await hasher.hash(file)}.js`, bytes: file, source: file };
464
+ return { name: `${stem}-${await hasher.hash(file)}.js`, stem, bytes: file, source: file };
419
465
  const { hash, words } = await hasher.scan(file);
420
466
  for (const word of words)
421
467
  holdWord(heldWords, word);
422
468
  const kept = words.filter((word) => list.holds(word)).length;
423
469
  if (kept === words.length)
424
- return { name: `${stem}-${hash}.js`, bytes: file, source: file };
470
+ return { name: `${stem}-${hash}.js`, stem, bytes: file, source: file };
425
471
  if (kept === 0)
426
472
  return narrowedCopy(UNLISTED_STEM, UNLISTED_MODULE);
427
473
  const narrowed = narrowShaderModule(readFileSync(file, 'utf8'), (word) => list.holds(word), file);
@@ -445,7 +491,7 @@ export default function null3d(options = {}) {
445
491
  /** Keeps each compiled shader in the project's cache, so a later build skips the compile. */
446
492
  const shaders = new ShaderCache(() => root, compiler, { disabled: () => noShaderCache });
447
493
  /** Custom materials' builds, which load on first use from modules of their own by device. */
448
- const materialBuilds = new MaterialBuilds();
494
+ const materialBuilds = new MaterialBuilds(() => !building || shipped.glsl);
449
495
  /** What the dev server's pages run, to judge each change of WGSL. */
450
496
  const hot = new HotState();
451
497
  /** The key of a project module's WGSL on the dev server, which builds and packages lack. */
@@ -489,8 +535,11 @@ export default function null3d(options = {}) {
489
535
  */
490
536
  const reportShaderCopies = (files, bytes) => {
491
537
  const copied = `null3D: copied ${files.toLocaleString('en-US')} shader files, ${megabytes(bytes)}`;
538
+ const paths = shipped.glsl ? '' : ' for the WebGPU path alone';
492
539
  if (shaderList !== undefined)
493
- logger?.info(`${copied}: the builds of the ${shaderList.words.size} permutation words of ${shaderList.file}.`);
540
+ logger?.info(`${copied}${paths}: the builds of the ${shaderList.words.size} permutation words of ${shaderList.file}.`);
541
+ else if (!shipped.glsl)
542
+ logger?.info(`${copied}: every build of every permutation word of the WebGPU path. A page downloads only the few that its device needs. Record the words that your pages draw with in a list, and name it in the plugin's shaders.list option, to copy only their builds: ${SHADER_LIST_DOCS}`);
494
543
  else
495
544
  logger?.warn(`${copied}: every build of every permutation word in the engine's shader set. A page downloads only the few that its device needs, but the host stores them all. Record the words that your pages draw with in a list, and name it in the plugin's shaders.list option, to copy only their builds: ${SHADER_LIST_DOCS}`);
496
545
  };
@@ -524,7 +573,6 @@ export default function null3d(options = {}) {
524
573
  streamedShaderAssets,
525
574
  workerFilesPlugin(workerFiles),
526
575
  workerPreloadPlugin(),
527
- shaderParagraphsPlugin(),
528
576
  {
529
577
  // A worker build keeps these plugins alone, so the engine's generated
530
578
  // modules resolve here as they do on the page.
@@ -571,6 +619,8 @@ export default function null3d(options = {}) {
571
619
  copiedTables.files = 0;
572
620
  copiedTables.bytes = 0;
573
621
  heldWords.clear();
622
+ // A rebuild reads the dropped files again, so the scan must answer the new list too.
623
+ scannedWords.clear();
574
624
  if (narrowedFolder !== undefined)
575
625
  rmSync(narrowedFolder, { recursive: true, force: true });
576
626
  narrowedFolder = undefined;
@@ -658,7 +708,7 @@ export default function null3d(options = {}) {
658
708
  },
659
709
  async handler(id) {
660
710
  if (id === HOT_CLIENT_ID)
661
- return hotClientCode(options.shaders?.list !== undefined);
711
+ return hotClientCode(options.shaders?.list !== undefined, !shipped.glsl);
662
712
  if (MATERIAL_BUILDS_ADDRESS.test(id))
663
713
  return (materialBuilds.module(id) ??
664
714
  this.error(`null3D has no custom material builds named ${id.slice(1)}. Reload the page so the dev server compiles its WGSL again.`));
@@ -692,7 +742,7 @@ export default function null3d(options = {}) {
692
742
  return `export default new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url).href;\n`;
693
743
  }
694
744
  const path = projectPath(root, id);
695
- const compiled = await compileWgslFile(path, id, readFileSync(id, 'utf8'), shaders);
745
+ const compiled = await compileWgslFile(path, id, readFileSync(id, 'utf8'), shaders, !building || shipped.glsl);
696
746
  if ('error' in compiled)
697
747
  return this.error(compiled.error);
698
748
  for (const warning of compiled.warnings)
@@ -709,7 +759,7 @@ export default function null3d(options = {}) {
709
759
  }
710
760
  }
711
761
  const pack = new ShaderPack();
712
- const builds = new ModuleBuilds();
762
+ const builds = new ModuleBuilds(!building || shipped.glsl);
713
763
  const value = builds.value(pack, compiled.shader, key);
714
764
  return {
715
765
  code: `export default ${value};\n${pack.unpacker()}${materialBuilds.finish(id, builds)}`,
@@ -728,13 +778,13 @@ export default function null3d(options = {}) {
728
778
  let out;
729
779
  if (SCRIPT_FILE.test(file) && WGSL_TAG.test(code)) {
730
780
  const path = projectPath(root, file);
731
- const tagged = await compileTaggedWgsl(code, file, path, shaders);
781
+ const tagged = await compileTaggedWgsl(code, file, path, shaders, !building || shipped.glsl);
732
782
  if ('error' in tagged)
733
783
  return this.error(tagged.error);
734
784
  for (const warning of tagged.warnings)
735
785
  this.warn(warning);
736
786
  const pack = new ShaderPack();
737
- const builds = new ModuleBuilds();
787
+ const builds = new ModuleBuilds(!building || shipped.glsl);
738
788
  for (const [literal, { start, end, shader }] of tagged.shaders.entries()) {
739
789
  const key = keyOf(file, path, literal);
740
790
  if (key !== undefined)
@@ -783,7 +833,7 @@ export default function null3d(options = {}) {
783
833
  return;
784
834
  const path = projectPath(root, file);
785
835
  if (WGSL_FILE.test(file)) {
786
- const compiled = await compileWgslFile(path, file, await read(), shaders);
836
+ const compiled = await compileWgslFile(path, file, await read(), shaders, !building || shipped.glsl);
787
837
  if ('error' in compiled) {
788
838
  showError(environment, compiled.error);
789
839
  return otherModules(modules, file);
@@ -804,7 +854,7 @@ export default function null3d(options = {}) {
804
854
  const changed = changedLiterals(before, code, file);
805
855
  if (!changed)
806
856
  return;
807
- const results = await Promise.all(changed.map(({ literal }) => compileLiteral(literal, code, file, path, shaders)));
857
+ const results = await Promise.all(changed.map(({ literal }) => compileLiteral(literal, code, file, path, shaders, !building || shipped.glsl)));
808
858
  const updates = [];
809
859
  for (const [k, result] of results.entries()) {
810
860
  if ('error' in result) {
@@ -851,6 +901,68 @@ export default function null3d(options = {}) {
851
901
  emptyWorkerPreloads(bundle, [...workerChunks].map((ref) => this.getFileName(ref)));
852
902
  /** True for a build with a list that reached the engine's shader set. */
853
903
  const listing = shaderList !== undefined && copiedShaders.size > 0;
904
+ // Each table takes its final content and name first, from every module that imports
905
+ // one: the copies that the streamed shader step made, and the bundle's own assets.
906
+ // Its name hashes that content, so a changed paragraph always has a new address.
907
+ const moduleCopies = [...copiedShaders.values()].map((copy) => ({
908
+ file: copy.bytes,
909
+ source: copy.source,
910
+ folder: assetsDir,
911
+ module: projectPath(root, copy.source),
912
+ }));
913
+ const paragraphs = emitParagraphTables.call(this, bundle, {
914
+ root,
915
+ narrow: shaderList !== undefined,
916
+ workerFiles,
917
+ copies: moduleCopies,
918
+ });
919
+ // A worker's copied file reaches this bundle without its build's records, so a
920
+ // renamed entry takes the record that the worker build kept for it.
921
+ for (const [from, to] of paragraphs.renamed) {
922
+ const worker = workerFiles.get(from);
923
+ if (worker === undefined)
924
+ continue;
925
+ workerFiles.delete(from);
926
+ workerFiles.set(to, worker);
927
+ }
928
+ // A copied module that imports a table takes the name of its final bytes, after the
929
+ // table's new address replaces the old one. The import head is read once and rewritten,
930
+ // and the rest of the source streams to a temp file. A module that imports no table
931
+ // keeps the name that the pool gave its bytes.
932
+ const tableNameOf = (source, stem) => {
933
+ const table = paragraphs.plan.get(join(dirname(source), `${stem}.js`));
934
+ if (table === undefined)
935
+ this.error(`null3D: ${source} imports ${stem}.js, which the build did not plan. Run \`bun run shaders\` again, and reinstall @null3d/engine if the build still fails.`);
936
+ return table.name;
937
+ };
938
+ const renamedCopies = new Map();
939
+ const copies = new Map();
940
+ const loads = new Map();
941
+ for (const [name, copy] of copiedShaders) {
942
+ const imports = tableImportsOfFile(copy.bytes);
943
+ if (imports.length === 0) {
944
+ copies.set(name, copy);
945
+ continue;
946
+ }
947
+ const names = new Map(imports.map(({ stem }) => [stem, tableNameOf(copy.source, stem)]));
948
+ narrowedFolder ??= mkdtempSync(join(tmpdir(), 'null3d-shaders-'));
949
+ const temp = join(narrowedFolder, `rewrite-${name}`);
950
+ const hash = rewriteCopyFile(copy.bytes, temp, names) ??
951
+ this.error(`null3D: ${projectPath(root, copy.source)} names no import, so the build cannot give it a table address. Run \`bun run shaders\` again, and reinstall @null3d/engine if the build still fails.`);
952
+ const finalName = `${copy.stem}-${hash}.js`;
953
+ copies.set(finalName, { ...copy, name: finalName, bytes: temp });
954
+ renamedCopies.set(name, finalName);
955
+ loads.set(finalName, [
956
+ ...new Set(imports.map(({ stem }) => assetPath(tableNameOf(copy.source, stem)))),
957
+ ]);
958
+ }
959
+ copiedShaders.clear();
960
+ for (const [name, copy] of copies)
961
+ copiedShaders.set(name, copy);
962
+ for (const table of paragraphs.tables.values()) {
963
+ copiedTables.files++;
964
+ copiedTables.bytes += table.source.length;
965
+ }
854
966
  // Each file that names a copy now knows where it sits, so the mark becomes the
855
967
  // address from there to the copy's own place in the output. A worker's files reach
856
968
  // this bundle as the worker built them, so they take the same pass.
@@ -870,7 +982,8 @@ export default function null3d(options = {}) {
870
982
  continue;
871
983
  const from = posix.dirname(file.fileName);
872
984
  const rewritten = text.replaceAll(/__null3d_shader__([^"'`\s)]+)/g, (_match, name) => {
873
- const address = posix.relative(from, assetPath(name));
985
+ const final = renamedCopies.get(name) ?? name;
986
+ const address = posix.relative(from, assetPath(final));
874
987
  return address.startsWith('.') ? address : `./${address}`;
875
988
  });
876
989
  if (file.type === 'chunk')
@@ -883,48 +996,8 @@ export default function null3d(options = {}) {
883
996
  const missing = listing ? (shaderList?.missing(heldWords) ?? []) : [];
884
997
  if (missing.length > 0)
885
998
  this.error(`null3D: the shader list ${shaderList?.file} names ${missing.map(wordText).join(', ')}, which no shader build of this project holds: none of the engine's shader set and none of its own shaders. Record the list again against this version of the engine with bunx @null3d/cli shaders record, or remove the word. A set that ${ENGINE_SHADERS_ENV} names must hold every listed word.`);
886
- const tables = emitParagraphTables.call(this, bundle, root);
887
- // The copied device modules are not in the bundle, so the tables of shared
888
- // paragraphs that they import are emitted from here, once each, and each copy's
889
- // module names them as its loads. Every build that copies the files needs them,
890
- // whatever it is for.
891
- const emittedTables = new Set([...tables.values()].flat());
892
- const loads = new Map();
893
- /** The file of each table that the copies import, by its place in the output. */
894
- const tableFiles = new Map();
895
- /** The names that the copies import from each of those tables. */
896
- const tableNames = new Map();
897
- for (const [name, copy] of copiedShaders) {
898
- const own = [];
899
- for (const { stem, names } of tableImportsOfFile(copy.bytes)) {
900
- const table = assetPath(`${stem}.js`);
901
- own.push(table);
902
- if (emittedTables.has(table))
903
- continue;
904
- if (!tableFiles.has(table)) {
905
- const file = join(dirname(copy.source), `${stem}.js`);
906
- if (!existsSync(file))
907
- this.error(`null3D: ${assetPath(name)} imports ${stem}.js, which the engine's shader modules do not hold. Run \`bun run shaders\` again, and reinstall @null3d/engine if the build still fails.`);
908
- tableFiles.set(table, file);
909
- tableNames.set(table, new Set());
910
- }
911
- for (const imported of names)
912
- tableNames.get(table)?.add(imported);
913
- }
914
- loads.set(name, own);
915
- }
916
- // With a list, a table keeps only the paragraphs that the narrowed copies import.
917
- for (const [table, file] of tableFiles) {
918
- const whole = readFileSync(file);
919
- const source = shaderList === undefined
920
- ? whole
921
- : Buffer.from(narrowParagraphTable(whole.toString('utf8'), tableNames.get(table) ?? new Set(), file));
922
- copiedTables.files++;
923
- copiedTables.bytes += source.length;
924
- this.emitFile({ type: 'asset', fileName: table, source });
925
- }
926
999
  if (buildingPages) {
927
- const listed = listedFiles(bundle, workerFiles, packageOf, root, tables);
1000
+ const listed = listedFiles(bundle, workerFiles, packageOf, root, paragraphs.files);
928
1001
  // The copied shader files are not in the bundle, so the list of files for offline
929
1002
  // play takes them here, by the module each one holds.
930
1003
  for (const [name, copy] of copiedShaders) {
@@ -1034,6 +1107,24 @@ export default function null3d(options = {}) {
1034
1107
  client.send(UNLISTED_WORD_EVENT, { message: warning.message });
1035
1108
  });
1036
1109
  }
1110
+ // The dev server draws with both GPU paths. It warns when a page draws with a path that a
1111
+ // production build with these options does not ship, because that build stops the page.
1112
+ if (!shipped.glsl) {
1113
+ const warned = new Set();
1114
+ server.environments.client.hot.on(GPU_PATH_EVENT, (data, client) => {
1115
+ const { path, page } = (data ?? {});
1116
+ if (typeof path !== 'string' || typeof page !== 'string')
1117
+ return;
1118
+ if (warned.has(page))
1119
+ return;
1120
+ const message = unshippedPathWarning(path, page, shipped.glsl);
1121
+ if (message === undefined)
1122
+ return;
1123
+ warned.add(page);
1124
+ server.config.logger.warn(`null3D: ${message}`, { timestamp: true });
1125
+ client.send(UNSHIPPED_PATH_EVENT, { message });
1126
+ });
1127
+ }
1037
1128
  server.middlewares.use(`${server.config.base}${ASSET_FOLDER}/`, (req, res, next) => {
1038
1129
  const path = decodeURIComponent((req.url ?? '').split('?')[0]?.slice(1) ?? '');
1039
1130
  const bytes = cachedFile(root, path);
@@ -1056,6 +1147,28 @@ export default function null3d(options = {}) {
1056
1147
  server.middlewares.use(compressedFiles(resolve(config.root, config.build.outDir), config.base, config.preview.headers));
1057
1148
  },
1058
1149
  };
1150
+ /** The device files whose words this build has read for the project's shader list. */
1151
+ const scannedWords = new Set();
1152
+ /**
1153
+ * Adds to `heldWords` the words of every device file that a generated module names. A build
1154
+ * that drops the module must still answer the project's list with its words, which the module's
1155
+ * own text does not hold: a table of combined builds names them through the addresses below.
1156
+ */
1157
+ const holdNamedWords = (text, file) => {
1158
+ if (shaderList === undefined)
1159
+ return;
1160
+ for (const match of text.matchAll(SCRIPT_URL)) {
1161
+ const address = match[2] ?? '';
1162
+ if (!isGeneratedShaderFile(file, address))
1163
+ continue;
1164
+ const named = resolve(dirname(file), address);
1165
+ if (scannedWords.has(named) || !existsSync(named))
1166
+ continue;
1167
+ scannedWords.add(named);
1168
+ for (const word of moduleWords(readFileSync(named, 'utf8')))
1169
+ holdWord(heldWords, word);
1170
+ }
1171
+ };
1059
1172
  /**
1060
1173
  * Names the generated shader files' copies before Vite's own asset step sees them, which runs
1061
1174
  * after the plugins that declare no order. A generated module loads each of its builds by
@@ -1063,7 +1176,8 @@ export default function null3d(options = {}) {
1063
1176
  * memory to emit it as an asset; here a pool of worker threads hashes each file and the build
1064
1177
  * copies it on its own, and the module names the copy, so the build never holds the whole set
1065
1178
  * at once. With a list of words, each copy holds only the listed builds, and the set's module of
1066
- * listed words names the project's list.
1179
+ * listed words names the project's list. With a GPU path set, a file of the other path gives way
1180
+ * to one module without builds, so the build copies none of that path's text.
1067
1181
  *
1068
1182
  * The argument is a mark rather than an address: where a copy lands is fixed, but the file that
1069
1183
  * names it can sit anywhere in the output, and only `generateBundle` knows where.
@@ -1076,15 +1190,32 @@ export default function null3d(options = {}) {
1076
1190
  const file = id.split('?')[0] ?? id;
1077
1191
  // The engine names a missing word as one that the list lacks, and the list to record.
1078
1192
  const name = file.slice(file.lastIndexOf('/') + 1);
1079
- if (shaderList !== undefined &&
1193
+ if ((shaderList !== undefined || !shipped.glsl) &&
1080
1194
  LISTED_MODULE.test(name) &&
1081
- code.includes('LISTED_PERMUTATIONS'))
1082
- return { code: listedPermutationsModule(shaderList.words), map: null };
1083
- if (!code.includes('import.meta.url'))
1084
- return;
1195
+ inShaderSet(dirname(file)) &&
1196
+ code.includes('LISTED_PERMUTATIONS')) {
1197
+ // The engine reads the shipped paths from the same module. A set that predates the
1198
+ // constant would keep both paths, so the build refuses rather than ship one silently.
1199
+ if (!code.includes('SHIPPED_GPU_PATHS'))
1200
+ this.error("null3D: the engine's shader set is older than the plugin: its shader-permutations module has no SHIPPED_GPU_PATHS. Install the same version of @null3d/engine as of @null3d/vite-plugin, or run bun run shaders in a checkout.");
1201
+ return {
1202
+ code: shaderMarkersModule(shaderList?.words ?? null, shipped.glsl ? null : ['webgpu']),
1203
+ map: null,
1204
+ };
1205
+ }
1206
+ let text = code;
1207
+ let changed = false;
1208
+ // An add-on package's compiled shaders keep both GPU paths, which a build that ships one
1209
+ // path drops here, including the modules of the other path's build sets.
1210
+ if (!shipped.glsl && text.includes(UNPACK)) {
1211
+ text = narrowShaderPack(text, file);
1212
+ changed = true;
1213
+ }
1214
+ if (!text.includes('import.meta.url'))
1215
+ return changed ? { code: text, map: null } : undefined;
1085
1216
  // The files this module names.
1086
1217
  const named = [];
1087
- for (const match of code.matchAll(SCRIPT_URL)) {
1218
+ for (const match of text.matchAll(SCRIPT_URL)) {
1088
1219
  const address = match[2] ?? '';
1089
1220
  if (!isGeneratedShaderFile(file, address))
1090
1221
  continue;
@@ -1094,7 +1225,7 @@ export default function null3d(options = {}) {
1094
1225
  named.push({ match, target });
1095
1226
  }
1096
1227
  if (named.length === 0)
1097
- return;
1228
+ return changed ? { code: text, map: null } : undefined;
1098
1229
  // The pool reads each file in chunks and hashes it, so the build's own thread reads none
1099
1230
  // of the files and holds none of their bytes; only a file that a list narrows is read
1100
1231
  // here, to write the copy of its listed builds.
@@ -1102,12 +1233,70 @@ export default function null3d(options = {}) {
1102
1233
  let out;
1103
1234
  for (const { match, copy } of copies) {
1104
1235
  copiedShaders.set(copy.name, copy);
1105
- out ??= new MagicString(code);
1236
+ out ??= new MagicString(text);
1106
1237
  out.overwrite(match.index, match.index + match[0].length, `((u) => new URL(u, import.meta.url))(${JSON.stringify(SHADER_URL_MARK + copy.name)})`);
1107
1238
  }
1108
- return out
1109
- ? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
1110
- : undefined;
1239
+ if (out === undefined)
1240
+ return changed ? { code: text, map: null } : undefined;
1241
+ return { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) };
1242
+ },
1243
+ // A generated module of a GPU path that this build does not ship, named by a module of the
1244
+ // set itself, such as a table of builds that need several features, takes the place of one
1245
+ // stub module. The stub exports the names of the module it stands for, so every import of it
1246
+ // resolves, and the lookups find no build rather than failing to load the module.
1247
+ resolveId: {
1248
+ filter: { id: /^\.\/shaders(?:-[a-z0-9-]+)+$/ },
1249
+ handler(source, importer) {
1250
+ if (shipped.glsl || importer === undefined)
1251
+ return;
1252
+ const importerFile = importer.split('?')[0] ?? importer;
1253
+ const importerName = importerFile.slice(importerFile.lastIndexOf('/') + 1);
1254
+ if (!GENERATED_MODULE.test(importerName))
1255
+ return;
1256
+ if (!inShaderSet(dirname(importerFile)))
1257
+ return;
1258
+ if (targetOfModule(source) !== 'glsl')
1259
+ return;
1260
+ const named = resolve(dirname(importerFile), source);
1261
+ const file = [named, `${named}.ts`, `${named}.js`].find((path) => existsSync(path));
1262
+ if (file === undefined)
1263
+ return;
1264
+ const text = readFileSync(file, 'utf8');
1265
+ holdNamedWords(text, file);
1266
+ return `${NO_SHADER_ID}${exportNamesOf(text, file).join(',')}`;
1267
+ },
1268
+ },
1269
+ // A dropped generated module that a module imports by name, such as a whole shader that loads
1270
+ // on first use, gives way to a stub of the same exports. Its words still answer a project's
1271
+ // shader list, which may hold a word that only the other GPU path builds.
1272
+ load: {
1273
+ filter: {
1274
+ id: { include: [/shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/, NO_SHADER_PATTERN] },
1275
+ },
1276
+ handler(id) {
1277
+ const bare = id.startsWith('\0') ? id.slice(1) : id;
1278
+ if (bare.startsWith(NO_SHADER_MARK))
1279
+ return stubModule(bare
1280
+ .slice(NO_SHADER_MARK.length)
1281
+ .split(',')
1282
+ .filter((name) => name !== ''));
1283
+ if (shipped.glsl)
1284
+ return;
1285
+ const file = id.split('?')[0] ?? id;
1286
+ const name = file.slice(file.lastIndexOf('/') + 1);
1287
+ if (!GENERATED_MODULE.test(name))
1288
+ return;
1289
+ if (!inShaderSet(dirname(file)))
1290
+ return;
1291
+ if (targetOfModule(name) !== 'glsl')
1292
+ return;
1293
+ const text = readFileSync(file, 'utf8');
1294
+ if (shaderList !== undefined)
1295
+ for (const word of moduleWords(text))
1296
+ holdWord(heldWords, word);
1297
+ holdNamedWords(text, file);
1298
+ return stubModule(exportNamesOf(text, file));
1299
+ },
1111
1300
  },
1112
1301
  };
1113
1302
  return [streamedShaderAssets, plugin];