@null3d/vite-plugin 0.0.0 → 0.1.1

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/lib/index.js CHANGED
@@ -1,23 +1,26 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
+ import { tmpdir } from 'node:os';
4
5
  import { dirname, join, posix, relative, resolve, sep } from 'node:path';
5
6
  import MagicString from 'magic-string';
6
7
  import { ASSET_FOLDER, assetType, cachedFile, cacheFolder, OPTIMIZED_MODEL, optimizedModel, } from "./assets.js";
7
8
  import { CompilerPool } from "./compile-pool.js";
9
+ import { compressAnswers, compressedFiles, fromLoopback } from "./compress.js";
8
10
  import { writeWgslDeclaration } from "./declarations.js";
9
11
  import { ENGINE_SHADERS_ENV, engineShaderFolder, engineShadersRoot, ensureEngineShaders, } from "./engine-shaders.js";
10
12
  import { buildEngineShadersLocally } from "./engine-shaders-local.js";
11
13
  import { HashPool } from "./hash-pool.js";
12
- import { changedLiterals, HOT_CLIENT, HOT_CLIENT_ADDRESS, HOT_CLIENT_CODE, HOT_CLIENT_ID, HotState, hotKey, WGSL_UPDATE_EVENT, } from "./hot.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";
13
15
  import { MATERIAL_BUILDS_ADDRESS, MaterialBuilds, ModuleBuilds } from "./material-builds.js";
14
16
  import { engineModule, FILES_LIST, featuresOf, listedFiles, missingWorkerAssets, offlineFiles, workerFilesPlugin, } from "./offline.js";
15
17
  import { ShaderPack } from "./pack.js";
16
18
  import { null3dPackages } from "./package-files.js";
17
- import { emitParagraphTables, shaderParagraphsPlugin, tableStemsOfFile } from "./paragraphs.js";
19
+ import { emitParagraphTables, shaderParagraphsPlugin, tableImportsOfFile } from "./paragraphs.js";
18
20
  import { ShaderCache, shaderCacheOff } from "./shader-cache.js";
21
+ import { builtWords, holdWord, listedPermutationsModule, narrowParagraphTable, narrowShaderModule, ShaderList, UNLISTED_MODULE, UnlistedWords, wordText, } from "./shader-list.js";
19
22
  import { compileLiteral, compileTaggedWgsl, compileWgslFile, WGSL_TAG, } from "./wgsl.js";
20
- import { workerPreloadPlugin } from "./worker-preload.js";
23
+ import { directImports, workerPreloadPlugin } from "./worker-preload.js";
21
24
  export { FILES_LIST } from "./offline.js";
22
25
  /** Headers that make a page cross-origin isolated, which shared memory and worker threads need. */
23
26
  export const ISOLATION_HEADERS = {
@@ -45,12 +48,35 @@ export const immutableAssetsMiddleware = (req, res, next) => {
45
48
  next();
46
49
  };
47
50
  /**
48
- * The HTTPS server's settings: the certificate, and HTTP/1.1 only. Vite serves HTTPS over HTTP/2,
49
- * where Safari on iPad sometimes stalls while a worker loads its modules: a development server
50
- * sends each module as its own file, and every engine thread loads its own copies.
51
+ * Takes `Origin` out of the Vary header of an answer to a request from the page's own origin, with
52
+ * the CORS header that the origin chose. Vite's CORS step marks every answer as varying by the
53
+ * request's Origin. The engine's page downloads the sketch module early with `fetch`, which sends no
54
+ * Origin, and the worker's import of it sends one. Without this, the browser cannot use the early
55
+ * copy and asks the server again, one round trip per such file. A request from the same origin needs
56
+ * no CORS header, and the browser names such a request in its Sec-Fetch-Site header.
51
57
  */
52
- function httpsOptions(certificate) {
53
- return { ...certificate, ALPNCallback: () => 'http/1.1' };
58
+ export const sameOriginMiddleware = (req, res, next) => {
59
+ if (req.headers['sec-fetch-site'] !== 'same-origin')
60
+ return next();
61
+ const vary = String(res.getHeader('Vary') ?? '')
62
+ .split(',')
63
+ .map((field) => field.trim())
64
+ .filter((field) => field !== '' && field.toLowerCase() !== 'origin');
65
+ if (vary.length > 0)
66
+ res.setHeader('Vary', vary.join(', '));
67
+ else
68
+ res.removeHeader('Vary');
69
+ res.removeHeader('Access-Control-Allow-Origin');
70
+ next();
71
+ };
72
+ /**
73
+ * The HTTPS server's settings: the certificate, and HTTP/1.1 only unless `http2` asks for HTTP/2.
74
+ * Vite serves HTTPS over HTTP/2, where Safari on iPad sometimes stalls while a worker loads its
75
+ * modules: a development server sends each module as its own file, and every engine thread loads
76
+ * its own copies.
77
+ */
78
+ function httpsOptions(certificate, http2) {
79
+ return http2 ? certificate : { ...certificate, ALPNCallback: () => 'http/1.1' };
54
80
  }
55
81
  function readCertificate(root, certDir) {
56
82
  const dir = resolve(root, certDir);
@@ -234,13 +260,46 @@ export function emptyWorkerPreloads(bundle, seeds) {
234
260
  */
235
261
  function isGeneratedShaderFile(importer, address) {
236
262
  const name = importer.slice(importer.lastIndexOf('/') + 1);
237
- return (/^shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/.test(name) &&
238
- /^\.\/shaders-[a-z0-9-]+\.js$/.test(address));
263
+ return GENERATED_MODULE.test(name) && /^\.\/shaders-[a-z0-9-]+\.js$/.test(address);
264
+ }
265
+ /** The name of one of the engine's generated shader modules: the main module, or one it names. */
266
+ const GENERATED_MODULE = /^shaders(?:-[a-z0-9-]+)?\.[cm]?[jt]s$/;
267
+ /** The name of the generated module that names the words a narrowed shader set holds. */
268
+ const LISTED_MODULE = /^shader-permutations\.[cm]?[jt]s$/;
269
+ /** The start of the name of the module that stands for every device file a list leaves out. */
270
+ const UNLISTED_STEM = 'shaders-unlisted';
271
+ /** The docs on a project's list of permutation words, which the build's report names. */
272
+ 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
+ /** A number of bytes in megabytes, as the build's report gives it. */
274
+ function megabytes(bytes) {
275
+ return `${Math.round(bytes / 1e6).toLocaleString('en-US')} MB`;
239
276
  }
240
277
  /** A WGSL file that a module imports, without a query such as `?raw`. */
241
278
  const WGSL_FILE = /\.wgsl$/;
242
279
  /** A script module, whose code the plugin parses for tagged WGSL. */
243
280
  const SCRIPT_FILE = /\.[cm]?[jt]sx?$/;
281
+ /** The parameter that keeps a dotted query from naming a module's extension. */
282
+ export const QUERY_EXTENSION_PARAM = 'null3d-query';
283
+ /**
284
+ * Keeps a module's query from deciding its type. Vite reads a dotted word at the end of a module's
285
+ * address as the extension, so a sketch at `sketch.ts?render-scale=0.5` parses as JavaScript and
286
+ * fails on its types. The middleware adds a parameter after such a query, which the sketch sees in
287
+ * `import.meta.url` and ignores, and Vite then reads the file's own extension.
288
+ */
289
+ export function queryExtensionMiddleware() {
290
+ return (req, _res, next) => {
291
+ const url = req.url ?? '';
292
+ const at = url.indexOf('?');
293
+ if (at < 0)
294
+ return next();
295
+ const path = url.slice(0, at);
296
+ const query = url.slice(at + 1);
297
+ if (!SCRIPT_FILE.test(path) || !/\.\w+$/.test(query))
298
+ return next();
299
+ req.url = `${url}&${QUERY_EXTENSION_PARAM}=1`;
300
+ next();
301
+ };
302
+ }
244
303
  /** Modules of installed packages, which the plugin leaves as they are. */
245
304
  const PACKAGE_MODULE = /\/node_modules\//;
246
305
  /** A file's path from the project's root, as messages name it. */
@@ -314,6 +373,8 @@ export default function null3d(options = {}) {
314
373
  const emitted = new Map();
315
374
  /** The chunks emitted for the scripts that a worker imports, by their rollup reference. */
316
375
  const workerChunks = new Set();
376
+ /** The modules of the scripts that a worker imports, which those chunks are built from. */
377
+ const workerModules = new Set();
317
378
  /** Hashes the generated shader files on worker threads, so the build goes on meanwhile. */
318
379
  const hasher = new HashPool();
319
380
  /**
@@ -323,20 +384,60 @@ export default function null3d(options = {}) {
323
384
  */
324
385
  const copiedShaders = new Map();
325
386
  /**
326
- * The content hash of each generated shader file by its path, which the pool computes. A page
327
- * build and its workers reach the same files, so each file is hashed once for the whole build,
328
- * and a second name for it waits for the same hash.
387
+ * The copy of each generated shader file by its path, which the pool works out. A page build and
388
+ * its workers reach the same files, so each file is read once for the whole build, and a second
389
+ * name for it waits for the same copy.
390
+ */
391
+ const shaderCopies = new Map();
392
+ /** The tables of shared paragraphs that the copies import, which the build emits beside them. */
393
+ const copiedTables = { files: 0, bytes: 0 };
394
+ /** The project's list of permutation words, in a build whose options name one. */
395
+ let shaderList;
396
+ /** Each word that a build of the engine's shader set answers, as this build has read them. */
397
+ const heldWords = new Set();
398
+ /** The folder of this build's narrowed copies, made when the first one is written. */
399
+ let narrowedFolder;
400
+ /** Writes the text of a narrowed copy, named by its hash, into this build's folder of them. */
401
+ const narrowedCopy = (stem, text, source) => {
402
+ narrowedFolder ??= mkdtempSync(join(tmpdir(), 'null3d-shaders-'));
403
+ const name = `${stem}-${createHash('sha256').update(text).digest('hex').slice(0, 8)}.js`;
404
+ const bytes = join(narrowedFolder, name);
405
+ if (!existsSync(bytes))
406
+ writeFileSync(bytes, text);
407
+ return { name, bytes, source: source ?? bytes };
408
+ };
409
+ /**
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.
329
413
  */
330
- const copiedShaderHashes = new Map();
331
- /** The hash of a generated shader file, read on the pool when a module first names it. */
332
- const copiedShaderHash = (file) => {
333
- let hash = copiedShaderHashes.get(file);
334
- if (hash === undefined) {
335
- hash = hasher.hash(file);
336
- copiedShaderHashes.set(file, hash);
414
+ const copyOf = async (file) => {
415
+ const stem = file.slice(file.lastIndexOf('/') + 1).replace(/\.js$/, '');
416
+ const list = shaderList;
417
+ if (list === undefined)
418
+ return { name: `${stem}-${await hasher.hash(file)}.js`, bytes: file, source: file };
419
+ const { hash, words } = await hasher.scan(file);
420
+ for (const word of words)
421
+ holdWord(heldWords, word);
422
+ const kept = words.filter((word) => list.holds(word)).length;
423
+ if (kept === words.length)
424
+ return { name: `${stem}-${hash}.js`, bytes: file, source: file };
425
+ if (kept === 0)
426
+ return narrowedCopy(UNLISTED_STEM, UNLISTED_MODULE);
427
+ const narrowed = narrowShaderModule(readFileSync(file, 'utf8'), (word) => list.holds(word), file);
428
+ return narrowedCopy(stem, narrowed.text, file);
429
+ };
430
+ /** The copy of a generated shader file, worked out on the pool when a module first names it. */
431
+ const shaderCopy = (file) => {
432
+ let copy = shaderCopies.get(file);
433
+ if (copy === undefined) {
434
+ copy = copyOf(file);
435
+ shaderCopies.set(file, copy);
337
436
  }
338
- return hash;
437
+ return copy;
339
438
  };
439
+ /** Vite's logger, for the build's report of the shader files it copied. */
440
+ let logger;
340
441
  /** A copied shader file's path in the output, whatever the assets folder is called. */
341
442
  const assetPath = (name) => (assetsDir === '' ? name : posix.join(assetsDir, name));
342
443
  /** Compiles WGSL on worker threads, so the dev server answers other requests meanwhile. */
@@ -381,6 +482,18 @@ export default function null3d(options = {}) {
381
482
  const asSource = join(folder, name.replace(/\.js$/, '.ts'));
382
483
  return existsSync(asSource) ? asSource : null;
383
484
  };
485
+ /**
486
+ * Reports the shader files that the build copied. Without a list, the build copied the whole
487
+ * set, which a host stores although a page downloads a few files of it, so the report warns and
488
+ * names the way to copy less.
489
+ */
490
+ const reportShaderCopies = (files, bytes) => {
491
+ const copied = `null3D: copied ${files.toLocaleString('en-US')} shader files, ${megabytes(bytes)}`;
492
+ if (shaderList !== undefined)
493
+ logger?.info(`${copied}: the builds of the ${shaderList.words.size} permutation words of ${shaderList.file}.`);
494
+ else
495
+ 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
+ };
384
497
  const plugin = {
385
498
  name: 'null3d',
386
499
  // Runs before Vite's own asset handling, which would copy a sketch file as raw text, and
@@ -389,7 +502,7 @@ export default function null3d(options = {}) {
389
502
  config(config, { mode }) {
390
503
  const root = config.root ?? process.cwd();
391
504
  const https = options.https
392
- ? httpsOptions(readCertificate(root, options.certDir ?? DEV_CERT_DIR))
505
+ ? httpsOptions(readCertificate(root, options.certDir ?? DEV_CERT_DIR), !!options.http2)
393
506
  : undefined;
394
507
  return {
395
508
  // Development checks stay in dev builds; release builds drop them as dead code.
@@ -427,8 +540,10 @@ export default function null3d(options = {}) {
427
540
  build: {
428
541
  assetsInlineLimit: inlineLimit(config.build?.assetsInlineLimit),
429
542
  },
430
- // A prebundled copy of the engine would lose the addresses of its workers and core files.
431
- optimizeDeps: { exclude: ['@null3d/engine'] },
543
+ // A prebundled copy of the engine would lose the addresses of its workers and core files,
544
+ // and one of the sound add-on's page half the address of the mixer it loads into the
545
+ // browser's audio thread.
546
+ optimizeDeps: { exclude: ['@null3d/engine', '@null3d/sound'] },
432
547
  };
433
548
  },
434
549
  configResolved(config) {
@@ -441,20 +556,38 @@ export default function null3d(options = {}) {
441
556
  config.logger.warn(`null3D: workers build as ${config.worker.format}, not as ES modules, so each engine worker takes in every shader file and grows to tens of MB. Set worker.format to 'es', or leave it unset for the null3D plugin to set.`);
442
557
  }
443
558
  notices = building && !config.build.ssr ? thirdPartyNotices(root) : null;
559
+ logger = config.logger;
444
560
  // Vite's `--force` ignores its own caches; it ignores the shader cache too.
445
561
  noShaderCache ||= config.optimizeDeps?.force === true;
446
562
  },
447
563
  buildStart() {
448
564
  emitted.clear();
449
565
  workerChunks.clear();
566
+ workerModules.clear();
450
567
  // The copies follow the generated set: a watch rebuild reads the files again, so a hash
451
568
  // from the last build would name old bytes, and a file that went away would be copied.
452
569
  copiedShaders.clear();
453
- copiedShaderHashes.clear();
570
+ shaderCopies.clear();
571
+ copiedTables.files = 0;
572
+ copiedTables.bytes = 0;
573
+ heldWords.clear();
574
+ if (narrowedFolder !== undefined)
575
+ rmSync(narrowedFolder, { recursive: true, force: true });
576
+ narrowedFolder = undefined;
577
+ shaderList = undefined;
454
578
  earlyCoreId = undefined;
455
579
  earlyCoreSought = false;
456
580
  if (!building)
457
581
  return;
582
+ const list = options.shaders?.list;
583
+ if (list !== undefined) {
584
+ try {
585
+ shaderList = ShaderList.read(resolve(root, list), list);
586
+ }
587
+ catch (error) {
588
+ this.error(`null3D: ${error.message}`);
589
+ }
590
+ }
458
591
  const missing = missingCoreFiles(root);
459
592
  if (missing && missing.length > 0) {
460
593
  this.error(`null3D: the installed @null3d/engine lacks its WebAssembly core (${missing.join(', ')}). Reinstall the package; in a copy of the engine's source, run bun run build first.`);
@@ -463,6 +596,11 @@ export default function null3d(options = {}) {
463
596
  async buildEnd() {
464
597
  await Promise.all([compiler.close(), hasher.close()]);
465
598
  },
599
+ closeBundle() {
600
+ if (narrowedFolder !== undefined)
601
+ rmSync(narrowedFolder, { recursive: true, force: true });
602
+ narrowedFolder = undefined;
603
+ },
466
604
  // The dev server's pages import the client module of hot updates. A build of pages that
467
605
  // imports the engine ships the early script, found from the module that imports the engine,
468
606
  // as the engine itself is. The page's own scripts run only once all of them have arrived. The
@@ -520,7 +658,7 @@ export default function null3d(options = {}) {
520
658
  },
521
659
  async handler(id) {
522
660
  if (id === HOT_CLIENT_ID)
523
- return HOT_CLIENT_CODE;
661
+ return hotClientCode(options.shaders?.list !== undefined);
524
662
  if (MATERIAL_BUILDS_ADDRESS.test(id))
525
663
  return (materialBuilds.module(id) ??
526
664
  this.error(`null3D has no custom material builds named ${id.slice(1)}. Reload the page so the dev server compiles its WGSL again.`));
@@ -627,6 +765,7 @@ export default function null3d(options = {}) {
627
765
  preserveSignature: 'strict',
628
766
  });
629
767
  workerChunks.add(ref);
768
+ workerModules.add(script.id);
630
769
  out ??= new MagicString(code);
631
770
  out.overwrite(start, start + match[0].length, `new URL(import.meta.ROLLUP_FILE_URL_${ref}, import.meta.url)`);
632
771
  }
@@ -687,6 +826,21 @@ export default function null3d(options = {}) {
687
826
  sendUpdates(environment, updates);
688
827
  return otherModules(modules, file);
689
828
  },
829
+ // A worker that imports a script by its address asks for the script's imports only once the
830
+ // script has arrived, so the script names them all. This runs before the build names the
831
+ // files, so each file's name follows its code.
832
+ renderChunk(code, chunk, _options, meta) {
833
+ const module = chunk.facadeModuleId;
834
+ if (!chunk.isEntry || module === null || !workerModules.has(module))
835
+ return null;
836
+ const chunks = meta.chunks;
837
+ if (!chunks)
838
+ return null;
839
+ const edited = new MagicString(code);
840
+ if (!directImports(edited, chunk.fileName, chunks))
841
+ return null;
842
+ return { code: edited.toString(), map: edited.generateMap({ hires: true }) };
843
+ },
690
844
  // After Vite's own plugins, which add the worker builds' files and the pages to the bundle.
691
845
  generateBundle: {
692
846
  order: 'post',
@@ -695,6 +849,8 @@ export default function null3d(options = {}) {
695
849
  // document to read.
696
850
  if (workerChunks.size > 0)
697
851
  emptyWorkerPreloads(bundle, [...workerChunks].map((ref) => this.getFileName(ref)));
852
+ /** True for a build with a list that reached the engine's shader set. */
853
+ const listing = shaderList !== undefined && copiedShaders.size > 0;
698
854
  // Each file that names a copy now knows where it sits, so the mark becomes the
699
855
  // address from there to the copy's own place in the output. A worker's files reach
700
856
  // this bundle as the worker built them, so they take the same pass.
@@ -704,6 +860,12 @@ export default function null3d(options = {}) {
704
860
  : typeof file.source === 'string'
705
861
  ? file.source
706
862
  : new TextDecoder().decode(file.source);
863
+ // The builds that the bundle holds answer their words: the set's own main module,
864
+ // and the project's custom materials and add-on shaders, in the worker builds' files
865
+ // too.
866
+ if (listing)
867
+ for (const word of builtWords(text))
868
+ holdWord(heldWords, word);
707
869
  if (!text.includes(SHADER_URL_MARK))
708
870
  continue;
709
871
  const from = posix.dirname(file.fileName);
@@ -716,6 +878,11 @@ export default function null3d(options = {}) {
716
878
  else
717
879
  file.source = rewritten;
718
880
  }
881
+ // A listed word that no build answers, a copied one or one that the bundle holds,
882
+ // would fail its pipeline on a device, so the build fails first and names it.
883
+ const missing = listing ? (shaderList?.missing(heldWords) ?? []) : [];
884
+ if (missing.length > 0)
885
+ 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.`);
719
886
  const tables = emitParagraphTables.call(this, bundle, root);
720
887
  // The copied device modules are not in the bundle, so the tables of shared
721
888
  // paragraphs that they import are emitted from here, once each, and each copy's
@@ -723,27 +890,45 @@ export default function null3d(options = {}) {
723
890
  // whatever it is for.
724
891
  const emittedTables = new Set([...tables.values()].flat());
725
892
  const loads = new Map();
726
- for (const [name, source] of copiedShaders) {
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) {
727
898
  const own = [];
728
- for (const stem of tableStemsOfFile(source)) {
899
+ for (const { stem, names } of tableImportsOfFile(copy.bytes)) {
729
900
  const table = assetPath(`${stem}.js`);
730
901
  own.push(table);
731
902
  if (emittedTables.has(table))
732
903
  continue;
733
- const file = join(dirname(source), `${stem}.js`);
734
- if (!existsSync(file))
735
- 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.`);
736
- emittedTables.add(table);
737
- this.emitFile({ type: 'asset', fileName: table, source: readFileSync(file) });
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);
738
913
  }
739
914
  loads.set(name, own);
740
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
+ }
741
926
  if (buildingPages) {
742
927
  const listed = listedFiles(bundle, workerFiles, packageOf, root, tables);
743
928
  // The copied shader files are not in the bundle, so the list of files for offline
744
929
  // play takes them here, by the module each one holds.
745
- for (const [name, source] of copiedShaders) {
746
- const module = engineModule(source, packageOf);
930
+ for (const [name, copy] of copiedShaders) {
931
+ const module = engineModule(copy.source, packageOf);
747
932
  listed.push({
748
933
  fileName: assetPath(name),
749
934
  entry: false,
@@ -777,8 +962,12 @@ export default function null3d(options = {}) {
777
962
  if (copiedShaders.size > 0) {
778
963
  const folder = join(outDir, assetsDir);
779
964
  mkdirSync(folder, { recursive: true });
780
- for (const [name, source] of copiedShaders)
781
- copyFileSync(source, join(folder, name));
965
+ let bytes = copiedTables.bytes;
966
+ for (const [name, copy] of copiedShaders) {
967
+ copyFileSync(copy.bytes, join(folder, name));
968
+ bytes += statSync(copy.bytes).size;
969
+ }
970
+ reportShaderCopies(copiedShaders.size + copiedTables.files, bytes);
782
971
  }
783
972
  const recovered = missingWorkerAssets(bundle, workerFiles).filter(({ fileName, source }) => !existsSync(join(outDir, fileName)) && existsSync(source));
784
973
  if (recovered.length === 0)
@@ -818,6 +1007,9 @@ export default function null3d(options = {}) {
818
1007
  },
819
1008
  },
820
1009
  configureServer(server) {
1010
+ // Ahead of every other step, so it sees each answer of the server and its plugins.
1011
+ server.middlewares.use(compressAnswers((req) => !fromLoopback(req)));
1012
+ server.middlewares.use(queryExtensionMiddleware());
821
1013
  // The engine's shader modules sit outside the project, in the machine's cache or in the
822
1014
  // folder that names a set, and the page and its workers reach them from there.
823
1015
  const allowed = server.config.server.fs.allow;
@@ -825,6 +1017,23 @@ export default function null3d(options = {}) {
825
1017
  if (shaders && !allowed.includes(shaders))
826
1018
  allowed.push(shaders);
827
1019
  server.middlewares.use(isolationMiddleware);
1020
+ // The dev server draws with the whole shader set. It warns about each word that a page
1021
+ // draws with and the project's list lacks, because a production build stops that page.
1022
+ const list = options.shaders?.list;
1023
+ if (list !== undefined) {
1024
+ const unlisted = new UnlistedWords(resolve(server.config.root, list), list);
1025
+ server.environments.client.hot.on(PERMUTATION_WORD_EVENT, (data, client) => {
1026
+ const { word, page } = (data ?? {});
1027
+ if (typeof word !== 'number' || typeof page !== 'string')
1028
+ return;
1029
+ const warning = unlisted.check(word, page);
1030
+ if (warning === undefined)
1031
+ return;
1032
+ if (warning.first)
1033
+ server.config.logger.warn(`null3D: ${warning.message}`, { timestamp: true });
1034
+ client.send(UNLISTED_WORD_EVENT, { message: warning.message });
1035
+ });
1036
+ }
828
1037
  server.middlewares.use(`${server.config.base}${ASSET_FOLDER}/`, (req, res, next) => {
829
1038
  const path = decodeURIComponent((req.url ?? '').split('?')[0]?.slice(1) ?? '');
830
1039
  const bytes = cachedFile(root, path);
@@ -836,8 +1045,15 @@ export default function null3d(options = {}) {
836
1045
  });
837
1046
  },
838
1047
  configurePreviewServer(server) {
1048
+ const { config } = server;
1049
+ // Every visitor gets compressed answers, as from a host: the build's own files from the
1050
+ // step below, and the answers of other plugins' routes, such as model files, from this one.
1051
+ server.middlewares.use(compressAnswers(() => true));
1052
+ server.middlewares.use(queryExtensionMiddleware());
839
1053
  server.middlewares.use(isolationMiddleware);
840
1054
  server.middlewares.use(immutableAssetsMiddleware);
1055
+ server.middlewares.use(sameOriginMiddleware);
1056
+ server.middlewares.use(compressedFiles(resolve(config.root, config.build.outDir), config.base, config.preview.headers));
841
1057
  },
842
1058
  };
843
1059
  /**
@@ -846,7 +1062,8 @@ export default function null3d(options = {}) {
846
1062
  * `new URL('./shaders-<name>.js', import.meta.url)`, and a bundler reads every one of them into
847
1063
  * memory to emit it as an asset; here a pool of worker threads hashes each file and the build
848
1064
  * copies it on its own, and the module names the copy, so the build never holds the whole set
849
- * at once.
1065
+ * 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.
850
1067
  *
851
1068
  * The argument is a mark rather than an address: where a copy lands is fixed, but the file that
852
1069
  * names it can sit anywhere in the output, and only `generateBundle` knows where.
@@ -856,10 +1073,16 @@ export default function null3d(options = {}) {
856
1073
  enforce: 'pre',
857
1074
  apply: 'build',
858
1075
  async transform(code, id) {
1076
+ const file = id.split('?')[0] ?? id;
1077
+ // The engine names a missing word as one that the list lacks, and the list to record.
1078
+ const name = file.slice(file.lastIndexOf('/') + 1);
1079
+ if (shaderList !== undefined &&
1080
+ LISTED_MODULE.test(name) &&
1081
+ code.includes('LISTED_PERMUTATIONS'))
1082
+ return { code: listedPermutationsModule(shaderList.words), map: null };
859
1083
  if (!code.includes('import.meta.url'))
860
1084
  return;
861
- const file = id.split('?')[0] ?? id;
862
- // The files this module names, and the base of the copy name that each one's hash fixes.
1085
+ // The files this module names.
863
1086
  const named = [];
864
1087
  for (const match of code.matchAll(SCRIPT_URL)) {
865
1088
  const address = match[2] ?? '';
@@ -868,23 +1091,19 @@ export default function null3d(options = {}) {
868
1091
  const target = resolve(dirname(file), address);
869
1092
  if (!existsSync(target))
870
1093
  continue;
871
- const base = target.slice(target.lastIndexOf('/') + 1).replace(/\.js$/, '');
872
- named.push({ match, base, target });
1094
+ named.push({ match, target });
873
1095
  }
874
1096
  if (named.length === 0)
875
1097
  return;
876
1098
  // The pool reads each file in chunks and hashes it, so the build's own thread reads none
877
- // of the files and holds none of their bytes.
878
- const hashed = await Promise.all(named.map(async ({ match, base, target }) => ({
879
- match,
880
- target,
881
- name: `${base}-${await copiedShaderHash(target)}.js`,
882
- })));
1099
+ // of the files and holds none of their bytes; only a file that a list narrows is read
1100
+ // here, to write the copy of its listed builds.
1101
+ const copies = await Promise.all(named.map(async ({ match, target }) => ({ match, copy: await shaderCopy(target) })));
883
1102
  let out;
884
- for (const { match, name, target } of hashed) {
885
- copiedShaders.set(name, target);
1103
+ for (const { match, copy } of copies) {
1104
+ copiedShaders.set(copy.name, copy);
886
1105
  out ??= new MagicString(code);
887
- out.overwrite(match.index, match.index + match[0].length, `((u) => new URL(u, import.meta.url))(${JSON.stringify(SHADER_URL_MARK + name)})`);
1106
+ out.overwrite(match.index, match.index + match[0].length, `((u) => new URL(u, import.meta.url))(${JSON.stringify(SHADER_URL_MARK + copy.name)})`);
888
1107
  }
889
1108
  return out
890
1109
  ? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
@@ -14,6 +14,8 @@ export declare const DRAW_INDEX = 1;
14
14
  export declare const TONE_MAP = 2;
15
15
  /** The permutation bit of builds that skin in the vertex shader. */
16
16
  export declare const SKIN = 64;
17
+ /** The permutation bit of builds that do their color math at half precision. */
18
+ export declare const HALF = 8192;
17
19
  /** A GPU path, as a build's field of its output names it. */
18
20
  type Target = 'wgsl' | 'glsl';
19
21
  /** The builds of one custom material, by name. */
@@ -30,6 +30,8 @@ export const DRAW_INDEX = 1;
30
30
  export const TONE_MAP = 2;
31
31
  /** The permutation bit of builds that skin in the vertex shader. */
32
32
  export const SKIN = 64;
33
+ /** The permutation bit of builds that do their color math at half precision. */
34
+ export const HALF = 8192;
33
35
  /** The permutation bits that a device of each GPU path fixes, which split its builds into sets. */
34
36
  const FIXED = { wgsl: TONE_MAP, glsl: TONE_MAP | DRAW_INDEX };
35
37
  /** Each value of the bits of `mask`, from 0 up. */
@@ -1,9 +1,15 @@
1
1
  import type { Plugin, Rollup } from 'vite';
2
+ /** One import of a table of shared paragraphs: the table's file name without `.js`, and its names. */
3
+ export interface TableImport {
4
+ readonly stem: string;
5
+ readonly names: readonly string[];
6
+ }
2
7
  /**
3
- * The tables that a device module on disk imports. The file is read from its start only, so a
4
- * build covers the whole generated set without holding any of it in memory.
8
+ * The tables that a device module on disk imports, with the names it takes from each. The file is
9
+ * read from its start only, so a build covers the whole generated set without holding any of it
10
+ * in memory.
5
11
  */
6
- export declare function tableStemsOfFile(file: string): string[];
12
+ export declare function tableImportsOfFile(file: string): TableImport[];
7
13
  /**
8
14
  * Emits each shared table of shader paragraphs beside the copied device modules that import it,
9
15
  * and gives the files of the tables of each of those modules. A build's bundle is the same after a