@null3d/vite-plugin 0.1.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/README.md +8 -1
- package/dist/shader-compiler.stamp.json +1 -1
- package/dist/shader-compiler.wasm +0 -0
- package/lib/assets.d.ts +3 -3
- package/lib/assets.js +3 -3
- package/lib/engine-shaders.d.ts +4 -2
- package/lib/engine-shaders.js +34 -7
- package/lib/hash-pool.d.ts +12 -0
- package/lib/hash-pool.js +17 -4
- package/lib/hash-worker.js +32 -9
- package/lib/hot.d.ts +12 -2
- package/lib/hot.js +25 -4
- package/lib/index.d.ts +9 -0
- package/lib/index.js +185 -43
- package/lib/material-builds.d.ts +2 -0
- package/lib/material-builds.js +2 -0
- package/lib/paragraphs.d.ts +9 -3
- package/lib/paragraphs.js +25 -11
- package/lib/shader-list.d.ts +127 -0
- package/lib/shader-list.js +352 -0
- package/package.json +3 -3
package/lib/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
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";
|
|
@@ -10,13 +11,14 @@ import { writeWgslDeclaration } from "./declarations.js";
|
|
|
10
11
|
import { ENGINE_SHADERS_ENV, engineShaderFolder, engineShadersRoot, ensureEngineShaders, } from "./engine-shaders.js";
|
|
11
12
|
import { buildEngineShadersLocally } from "./engine-shaders-local.js";
|
|
12
13
|
import { HashPool } from "./hash-pool.js";
|
|
13
|
-
import { changedLiterals, HOT_CLIENT, HOT_CLIENT_ADDRESS,
|
|
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
15
|
import { MATERIAL_BUILDS_ADDRESS, MaterialBuilds, ModuleBuilds } from "./material-builds.js";
|
|
15
16
|
import { engineModule, FILES_LIST, featuresOf, listedFiles, missingWorkerAssets, offlineFiles, workerFilesPlugin, } from "./offline.js";
|
|
16
17
|
import { ShaderPack } from "./pack.js";
|
|
17
18
|
import { null3dPackages } from "./package-files.js";
|
|
18
|
-
import { emitParagraphTables, shaderParagraphsPlugin,
|
|
19
|
+
import { emitParagraphTables, shaderParagraphsPlugin, tableImportsOfFile } from "./paragraphs.js";
|
|
19
20
|
import { ShaderCache, shaderCacheOff } from "./shader-cache.js";
|
|
21
|
+
import { builtWords, holdWord, listedPermutationsModule, narrowParagraphTable, narrowShaderModule, ShaderList, UNLISTED_MODULE, UnlistedWords, wordText, } from "./shader-list.js";
|
|
20
22
|
import { compileLiteral, compileTaggedWgsl, compileWgslFile, WGSL_TAG, } from "./wgsl.js";
|
|
21
23
|
import { directImports, workerPreloadPlugin } from "./worker-preload.js";
|
|
22
24
|
export { FILES_LIST } from "./offline.js";
|
|
@@ -258,8 +260,19 @@ export function emptyWorkerPreloads(bundle, seeds) {
|
|
|
258
260
|
*/
|
|
259
261
|
function isGeneratedShaderFile(importer, address) {
|
|
260
262
|
const name = importer.slice(importer.lastIndexOf('/') + 1);
|
|
261
|
-
return (
|
|
262
|
-
|
|
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`;
|
|
263
276
|
}
|
|
264
277
|
/** A WGSL file that a module imports, without a query such as `?raw`. */
|
|
265
278
|
const WGSL_FILE = /\.wgsl$/;
|
|
@@ -371,20 +384,60 @@ export default function null3d(options = {}) {
|
|
|
371
384
|
*/
|
|
372
385
|
const copiedShaders = new Map();
|
|
373
386
|
/**
|
|
374
|
-
* The
|
|
375
|
-
*
|
|
376
|
-
*
|
|
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.
|
|
377
390
|
*/
|
|
378
|
-
const
|
|
379
|
-
/** The
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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.
|
|
413
|
+
*/
|
|
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);
|
|
385
436
|
}
|
|
386
|
-
return
|
|
437
|
+
return copy;
|
|
387
438
|
};
|
|
439
|
+
/** Vite's logger, for the build's report of the shader files it copied. */
|
|
440
|
+
let logger;
|
|
388
441
|
/** A copied shader file's path in the output, whatever the assets folder is called. */
|
|
389
442
|
const assetPath = (name) => (assetsDir === '' ? name : posix.join(assetsDir, name));
|
|
390
443
|
/** Compiles WGSL on worker threads, so the dev server answers other requests meanwhile. */
|
|
@@ -429,6 +482,18 @@ export default function null3d(options = {}) {
|
|
|
429
482
|
const asSource = join(folder, name.replace(/\.js$/, '.ts'));
|
|
430
483
|
return existsSync(asSource) ? asSource : null;
|
|
431
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
|
+
};
|
|
432
497
|
const plugin = {
|
|
433
498
|
name: 'null3d',
|
|
434
499
|
// Runs before Vite's own asset handling, which would copy a sketch file as raw text, and
|
|
@@ -491,6 +556,7 @@ export default function null3d(options = {}) {
|
|
|
491
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.`);
|
|
492
557
|
}
|
|
493
558
|
notices = building && !config.build.ssr ? thirdPartyNotices(root) : null;
|
|
559
|
+
logger = config.logger;
|
|
494
560
|
// Vite's `--force` ignores its own caches; it ignores the shader cache too.
|
|
495
561
|
noShaderCache ||= config.optimizeDeps?.force === true;
|
|
496
562
|
},
|
|
@@ -501,11 +567,27 @@ export default function null3d(options = {}) {
|
|
|
501
567
|
// The copies follow the generated set: a watch rebuild reads the files again, so a hash
|
|
502
568
|
// from the last build would name old bytes, and a file that went away would be copied.
|
|
503
569
|
copiedShaders.clear();
|
|
504
|
-
|
|
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;
|
|
505
578
|
earlyCoreId = undefined;
|
|
506
579
|
earlyCoreSought = false;
|
|
507
580
|
if (!building)
|
|
508
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
|
+
}
|
|
509
591
|
const missing = missingCoreFiles(root);
|
|
510
592
|
if (missing && missing.length > 0) {
|
|
511
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.`);
|
|
@@ -514,6 +596,11 @@ export default function null3d(options = {}) {
|
|
|
514
596
|
async buildEnd() {
|
|
515
597
|
await Promise.all([compiler.close(), hasher.close()]);
|
|
516
598
|
},
|
|
599
|
+
closeBundle() {
|
|
600
|
+
if (narrowedFolder !== undefined)
|
|
601
|
+
rmSync(narrowedFolder, { recursive: true, force: true });
|
|
602
|
+
narrowedFolder = undefined;
|
|
603
|
+
},
|
|
517
604
|
// The dev server's pages import the client module of hot updates. A build of pages that
|
|
518
605
|
// imports the engine ships the early script, found from the module that imports the engine,
|
|
519
606
|
// as the engine itself is. The page's own scripts run only once all of them have arrived. The
|
|
@@ -571,7 +658,7 @@ export default function null3d(options = {}) {
|
|
|
571
658
|
},
|
|
572
659
|
async handler(id) {
|
|
573
660
|
if (id === HOT_CLIENT_ID)
|
|
574
|
-
return
|
|
661
|
+
return hotClientCode(options.shaders?.list !== undefined);
|
|
575
662
|
if (MATERIAL_BUILDS_ADDRESS.test(id))
|
|
576
663
|
return (materialBuilds.module(id) ??
|
|
577
664
|
this.error(`null3D has no custom material builds named ${id.slice(1)}. Reload the page so the dev server compiles its WGSL again.`));
|
|
@@ -762,6 +849,8 @@ export default function null3d(options = {}) {
|
|
|
762
849
|
// document to read.
|
|
763
850
|
if (workerChunks.size > 0)
|
|
764
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;
|
|
765
854
|
// Each file that names a copy now knows where it sits, so the mark becomes the
|
|
766
855
|
// address from there to the copy's own place in the output. A worker's files reach
|
|
767
856
|
// this bundle as the worker built them, so they take the same pass.
|
|
@@ -771,6 +860,12 @@ export default function null3d(options = {}) {
|
|
|
771
860
|
: typeof file.source === 'string'
|
|
772
861
|
? file.source
|
|
773
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);
|
|
774
869
|
if (!text.includes(SHADER_URL_MARK))
|
|
775
870
|
continue;
|
|
776
871
|
const from = posix.dirname(file.fileName);
|
|
@@ -783,6 +878,11 @@ export default function null3d(options = {}) {
|
|
|
783
878
|
else
|
|
784
879
|
file.source = rewritten;
|
|
785
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.`);
|
|
786
886
|
const tables = emitParagraphTables.call(this, bundle, root);
|
|
787
887
|
// The copied device modules are not in the bundle, so the tables of shared
|
|
788
888
|
// paragraphs that they import are emitted from here, once each, and each copy's
|
|
@@ -790,27 +890,45 @@ export default function null3d(options = {}) {
|
|
|
790
890
|
// whatever it is for.
|
|
791
891
|
const emittedTables = new Set([...tables.values()].flat());
|
|
792
892
|
const loads = new Map();
|
|
793
|
-
|
|
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) {
|
|
794
898
|
const own = [];
|
|
795
|
-
for (const stem of
|
|
899
|
+
for (const { stem, names } of tableImportsOfFile(copy.bytes)) {
|
|
796
900
|
const table = assetPath(`${stem}.js`);
|
|
797
901
|
own.push(table);
|
|
798
902
|
if (emittedTables.has(table))
|
|
799
903
|
continue;
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
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);
|
|
805
913
|
}
|
|
806
914
|
loads.set(name, own);
|
|
807
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
|
+
}
|
|
808
926
|
if (buildingPages) {
|
|
809
927
|
const listed = listedFiles(bundle, workerFiles, packageOf, root, tables);
|
|
810
928
|
// The copied shader files are not in the bundle, so the list of files for offline
|
|
811
929
|
// play takes them here, by the module each one holds.
|
|
812
|
-
for (const [name,
|
|
813
|
-
const module = engineModule(source, packageOf);
|
|
930
|
+
for (const [name, copy] of copiedShaders) {
|
|
931
|
+
const module = engineModule(copy.source, packageOf);
|
|
814
932
|
listed.push({
|
|
815
933
|
fileName: assetPath(name),
|
|
816
934
|
entry: false,
|
|
@@ -844,8 +962,12 @@ export default function null3d(options = {}) {
|
|
|
844
962
|
if (copiedShaders.size > 0) {
|
|
845
963
|
const folder = join(outDir, assetsDir);
|
|
846
964
|
mkdirSync(folder, { recursive: true });
|
|
847
|
-
|
|
848
|
-
|
|
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);
|
|
849
971
|
}
|
|
850
972
|
const recovered = missingWorkerAssets(bundle, workerFiles).filter(({ fileName, source }) => !existsSync(join(outDir, fileName)) && existsSync(source));
|
|
851
973
|
if (recovered.length === 0)
|
|
@@ -895,6 +1017,23 @@ export default function null3d(options = {}) {
|
|
|
895
1017
|
if (shaders && !allowed.includes(shaders))
|
|
896
1018
|
allowed.push(shaders);
|
|
897
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
|
+
}
|
|
898
1037
|
server.middlewares.use(`${server.config.base}${ASSET_FOLDER}/`, (req, res, next) => {
|
|
899
1038
|
const path = decodeURIComponent((req.url ?? '').split('?')[0]?.slice(1) ?? '');
|
|
900
1039
|
const bytes = cachedFile(root, path);
|
|
@@ -923,7 +1062,8 @@ export default function null3d(options = {}) {
|
|
|
923
1062
|
* `new URL('./shaders-<name>.js', import.meta.url)`, and a bundler reads every one of them into
|
|
924
1063
|
* memory to emit it as an asset; here a pool of worker threads hashes each file and the build
|
|
925
1064
|
* copies it on its own, and the module names the copy, so the build never holds the whole set
|
|
926
|
-
* 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.
|
|
927
1067
|
*
|
|
928
1068
|
* The argument is a mark rather than an address: where a copy lands is fixed, but the file that
|
|
929
1069
|
* names it can sit anywhere in the output, and only `generateBundle` knows where.
|
|
@@ -933,10 +1073,16 @@ export default function null3d(options = {}) {
|
|
|
933
1073
|
enforce: 'pre',
|
|
934
1074
|
apply: 'build',
|
|
935
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 };
|
|
936
1083
|
if (!code.includes('import.meta.url'))
|
|
937
1084
|
return;
|
|
938
|
-
|
|
939
|
-
// The files this module names, and the base of the copy name that each one's hash fixes.
|
|
1085
|
+
// The files this module names.
|
|
940
1086
|
const named = [];
|
|
941
1087
|
for (const match of code.matchAll(SCRIPT_URL)) {
|
|
942
1088
|
const address = match[2] ?? '';
|
|
@@ -945,23 +1091,19 @@ export default function null3d(options = {}) {
|
|
|
945
1091
|
const target = resolve(dirname(file), address);
|
|
946
1092
|
if (!existsSync(target))
|
|
947
1093
|
continue;
|
|
948
|
-
|
|
949
|
-
named.push({ match, base, target });
|
|
1094
|
+
named.push({ match, target });
|
|
950
1095
|
}
|
|
951
1096
|
if (named.length === 0)
|
|
952
1097
|
return;
|
|
953
1098
|
// The pool reads each file in chunks and hashes it, so the build's own thread reads none
|
|
954
|
-
// of the files and holds none of their bytes
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
target,
|
|
958
|
-
name: `${base}-${await copiedShaderHash(target)}.js`,
|
|
959
|
-
})));
|
|
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) })));
|
|
960
1102
|
let out;
|
|
961
|
-
for (const { match,
|
|
962
|
-
copiedShaders.set(name,
|
|
1103
|
+
for (const { match, copy } of copies) {
|
|
1104
|
+
copiedShaders.set(copy.name, copy);
|
|
963
1105
|
out ??= new MagicString(code);
|
|
964
|
-
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)})`);
|
|
965
1107
|
}
|
|
966
1108
|
return out
|
|
967
1109
|
? { code: out.toString(), map: out.generateMap({ hires: 'boundary' }) }
|
package/lib/material-builds.d.ts
CHANGED
|
@@ -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. */
|
package/lib/material-builds.js
CHANGED
|
@@ -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. */
|
package/lib/paragraphs.d.ts
CHANGED
|
@@ -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
|
|
4
|
-
* build covers the whole generated set without holding any of it
|
|
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
|
|
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
|
package/lib/paragraphs.js
CHANGED
|
@@ -10,8 +10,11 @@
|
|
|
10
10
|
// whatever the project's assets folder and asset naming pattern are.
|
|
11
11
|
import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
|
|
12
12
|
import { dirname, isAbsolute, join, posix, resolve } from 'node:path';
|
|
13
|
-
/**
|
|
14
|
-
|
|
13
|
+
/**
|
|
14
|
+
* An import of a table of shared paragraphs, at the top of a device module of its kind, with the
|
|
15
|
+
* names it takes from the table.
|
|
16
|
+
*/
|
|
17
|
+
const PARAGRAPH_IMPORT = /import\s*\{([^}]*)\}\s*from '\.\/(shader-paragraphs-[a-z0-9-]+)\.js';/g;
|
|
15
18
|
/**
|
|
16
19
|
* How much of a copied file this reads at first. The shader build writes the imports among the
|
|
17
20
|
* first lines, and a device module is hundreds of kilobytes, so the rest is never read. A device
|
|
@@ -26,11 +29,11 @@ function headOf(source, bytes) {
|
|
|
26
29
|
return new TextDecoder().decode(source.subarray(0, bytes));
|
|
27
30
|
}
|
|
28
31
|
/**
|
|
29
|
-
* The
|
|
30
|
-
* kind's table and one for each feature family whose paragraphs it holds, so the module
|
|
31
|
-
* relief feature imports several. The imports end at the first blank line after them.
|
|
32
|
+
* The paragraph tables that a device module imports, with the names it takes from each. A module
|
|
33
|
+
* imports its kind's table and one for each feature family whose paragraphs it holds, so the module
|
|
34
|
+
* of a relief feature imports several. The imports end at the first blank line after them.
|
|
32
35
|
*/
|
|
33
|
-
function
|
|
36
|
+
function tableImports(read, length) {
|
|
34
37
|
let window = Math.min(IMPORT_WINDOW, length);
|
|
35
38
|
for (;;) {
|
|
36
39
|
const head = read(window);
|
|
@@ -41,15 +44,26 @@ function tableStems(read, length) {
|
|
|
41
44
|
return [];
|
|
42
45
|
const complete = window >= length || head.indexOf('\n\n', first) >= 0;
|
|
43
46
|
if (complete)
|
|
44
|
-
return [...head.matchAll(PARAGRAPH_IMPORT)].map((match) =>
|
|
47
|
+
return [...head.matchAll(PARAGRAPH_IMPORT)].map((match) => ({
|
|
48
|
+
stem: match[2],
|
|
49
|
+
names: match[1]
|
|
50
|
+
.split(',')
|
|
51
|
+
.map((name) => name.trim())
|
|
52
|
+
.filter((name) => name !== ''),
|
|
53
|
+
}));
|
|
45
54
|
window = Math.min(window * 2, length);
|
|
46
55
|
}
|
|
47
56
|
}
|
|
57
|
+
/** The names of the paragraph tables that a device module imports. */
|
|
58
|
+
function tableStems(read, length) {
|
|
59
|
+
return tableImports(read, length).map((entry) => entry.stem);
|
|
60
|
+
}
|
|
48
61
|
/**
|
|
49
|
-
* The tables that a device module on disk imports
|
|
50
|
-
* build covers the whole generated set without holding any of it
|
|
62
|
+
* The tables that a device module on disk imports, with the names it takes from each. The file is
|
|
63
|
+
* read from its start only, so a build covers the whole generated set without holding any of it
|
|
64
|
+
* in memory.
|
|
51
65
|
*/
|
|
52
|
-
export function
|
|
66
|
+
export function tableImportsOfFile(file) {
|
|
53
67
|
const fd = openSync(file, 'r');
|
|
54
68
|
try {
|
|
55
69
|
const length = statSync(file).size;
|
|
@@ -58,7 +72,7 @@ export function tableStemsOfFile(file) {
|
|
|
58
72
|
const count = readSync(fd, buffer, 0, buffer.length, 0);
|
|
59
73
|
return buffer.subarray(0, count).toString('utf8');
|
|
60
74
|
};
|
|
61
|
-
return
|
|
75
|
+
return tableImports(read, length);
|
|
62
76
|
}
|
|
63
77
|
finally {
|
|
64
78
|
closeSync(fd);
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The permutation bits that a device fixes when it starts. A listed word leaves them out, so one
|
|
3
|
+
* list serves every device module, and a build matches a word with those bits cleared.
|
|
4
|
+
*/
|
|
5
|
+
export declare const DEVICE_BITS: number;
|
|
6
|
+
/** The shader options of the plugin. */
|
|
7
|
+
export interface ShaderOptions {
|
|
8
|
+
/**
|
|
9
|
+
* The file that lists the permutation words that the project's pages draw with, one
|
|
10
|
+
* hexadecimal word on each line, as `bunx @null3d/cli shaders record` writes it. The path is
|
|
11
|
+
* relative to Vite's root. A production build then copies only the shader builds of those words,
|
|
12
|
+
* for every value of the bits a device fixes, and fails when the engine's shader set lacks a
|
|
13
|
+
* listed word. Without it, a build copies the whole set. The dev server draws with the whole
|
|
14
|
+
* set, and warns in the terminal and the browser's console about each word that a page draws
|
|
15
|
+
* with and the list lacks.
|
|
16
|
+
*/
|
|
17
|
+
list?: string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The words of a list file's text: one word on each line, as hexadecimal with `0x` or as a decimal
|
|
21
|
+
* number, with `#` starting a comment, the rule that the engine's shader build reads. Throws with
|
|
22
|
+
* the line of a word it cannot read, and for a list without a word.
|
|
23
|
+
*/
|
|
24
|
+
export declare function parseShaderList(text: string, file: string): number[];
|
|
25
|
+
/** A project's list of permutation words. */
|
|
26
|
+
export declare class ShaderList {
|
|
27
|
+
/** The list's file, as the build names it in its messages. */
|
|
28
|
+
readonly file: string;
|
|
29
|
+
/** The listed words, without the bits that a device fixes. */
|
|
30
|
+
readonly words: ReadonlySet<number>;
|
|
31
|
+
constructor(
|
|
32
|
+
/** The list's file, as the build names it in its messages. */
|
|
33
|
+
file: string, words: Iterable<number>);
|
|
34
|
+
/**
|
|
35
|
+
* Reads the list at `path`, which messages name as `name`. Throws for a list without the word
|
|
36
|
+
* that has no bit set, which every page's start draws its own passes with.
|
|
37
|
+
*/
|
|
38
|
+
static read(path: string, name?: string): ShaderList;
|
|
39
|
+
/**
|
|
40
|
+
* True when the list names the build whose permutation word is `permutation`: the word itself,
|
|
41
|
+
* or the word with the bits that a device fixes cleared.
|
|
42
|
+
*/
|
|
43
|
+
holds(permutation: number): boolean;
|
|
44
|
+
/** The listed words that none of `held`, the words that a set's builds answer, holds. */
|
|
45
|
+
missing(held: ReadonlySet<number>): number[];
|
|
46
|
+
}
|
|
47
|
+
/** The dev server's warning about a word that a page draws with and the project's list lacks. */
|
|
48
|
+
export interface UnlistedWord {
|
|
49
|
+
readonly message: string;
|
|
50
|
+
/** True for the first warning about the word since the list last changed. */
|
|
51
|
+
readonly first: boolean;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The dev server's check of the words that its pages draw with against the project's list. The
|
|
55
|
+
* dev server draws with the whole shader set, so a page there draws a word that the list lacks,
|
|
56
|
+
* while a production build with the list stops that page. The check names such a word when a page
|
|
57
|
+
* first draws with it. It reads the list again whenever the file changes, so a recording made
|
|
58
|
+
* while the server runs counts at once.
|
|
59
|
+
*/
|
|
60
|
+
export declare class UnlistedWords {
|
|
61
|
+
private readonly path;
|
|
62
|
+
/** The list's file, as the warnings name it. */
|
|
63
|
+
private readonly name;
|
|
64
|
+
/** The list file's change time when it was last read, or undefined before the first read. */
|
|
65
|
+
private stamp;
|
|
66
|
+
private list;
|
|
67
|
+
/** Why the list cannot be read, when it cannot. */
|
|
68
|
+
private problem;
|
|
69
|
+
/** The words that the check has warned about since the list last changed. */
|
|
70
|
+
private readonly warned;
|
|
71
|
+
/** True once the check has reported the list's problem since the list last changed. */
|
|
72
|
+
private problemShown;
|
|
73
|
+
constructor(path: string,
|
|
74
|
+
/** The list's file, as the warnings name it. */
|
|
75
|
+
name: string);
|
|
76
|
+
/**
|
|
77
|
+
* The warning about `word`, which the page at `page` draws with, without the bits that a device
|
|
78
|
+
* fixes. Undefined when the list holds the word.
|
|
79
|
+
*/
|
|
80
|
+
check(word: number, page: string): UnlistedWord | undefined;
|
|
81
|
+
/** Reads the list again when its file changed since the last read. */
|
|
82
|
+
private refresh;
|
|
83
|
+
}
|
|
84
|
+
/** Adds to `held` each word that a build with the permutation word `permutation` answers. */
|
|
85
|
+
export declare function holdWord(held: Set<number>, permutation: number): void;
|
|
86
|
+
/** A word as the list writes it: eight hexadecimal digits after `0x`. */
|
|
87
|
+
export declare function wordText(word: number): string;
|
|
88
|
+
/**
|
|
89
|
+
* A line of a generated shader module that holds a build's permutation word. The hash workers
|
|
90
|
+
* read the same lines in `hash-worker.js`, which cannot import this module.
|
|
91
|
+
*/
|
|
92
|
+
export declare const PERMUTATION_LINE: RegExp;
|
|
93
|
+
/** The permutation word of each build that a generated module's text holds. */
|
|
94
|
+
export declare function moduleWords(text: string): number[];
|
|
95
|
+
/**
|
|
96
|
+
* The permutation words that a built file's text names: those of the builds that it bundles, such
|
|
97
|
+
* as the main shader module's own, a custom material's and an add-on's. A key of that name in other
|
|
98
|
+
* code adds a word too, so the words that a check reads from here can only be more, never fewer.
|
|
99
|
+
*/
|
|
100
|
+
export declare function builtWords(text: string): number[];
|
|
101
|
+
/**
|
|
102
|
+
* The module that stands for a device file whose builds the list leaves out. It holds no build,
|
|
103
|
+
* so a page that asks for one of those words loads it, finds no build, and the engine names the
|
|
104
|
+
* word.
|
|
105
|
+
*/
|
|
106
|
+
export declare const UNLISTED_MODULE = "// The builds of a device module that the project's shader list leaves out.\nexport const SHADERS = {};\n";
|
|
107
|
+
/** The generated module that names the listed words, in place of the set's own. */
|
|
108
|
+
export declare function listedPermutationsModule(words: ReadonlySet<number>): string;
|
|
109
|
+
/**
|
|
110
|
+
* The text of the generated device module `text` with only the builds whose permutation word
|
|
111
|
+
* `keep` takes, and the counts of the builds it kept and held. A shader keeps its entry with no
|
|
112
|
+
* build. Each shared paragraph and imported name that no kept build reads goes too, and so does an
|
|
113
|
+
* import of a table of paragraphs that no kept build reads. Throws when the module is not in the
|
|
114
|
+
* form that the shader build writes, so a build never ships a module it misread.
|
|
115
|
+
*/
|
|
116
|
+
export declare function narrowShaderModule(text: string, keep: (permutation: number) => boolean, file?: string): {
|
|
117
|
+
text: string;
|
|
118
|
+
kept: number;
|
|
119
|
+
builds: number;
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* The text of a table of shared paragraphs with only the paragraphs that `names` lists, the names
|
|
123
|
+
* that the build's copies import from it. A paragraph of a table reads no other value, so each
|
|
124
|
+
* one stays or goes on its own. Throws when the table is not in the form that the shader build
|
|
125
|
+
* writes.
|
|
126
|
+
*/
|
|
127
|
+
export declare function narrowParagraphTable(text: string, names: ReadonlySet<string>, file?: string): string;
|