@null3d/vite-plugin 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE-APACHE +176 -0
  2. package/LICENSE-MIT +21 -0
  3. package/THIRD-PARTY-NOTICES.txt +398 -0
  4. package/dist/shader-compiler.stamp.json +4 -0
  5. package/dist/shader-compiler.wasm +0 -0
  6. package/lib/assets.d.ts +94 -0
  7. package/lib/assets.js +189 -0
  8. package/lib/client.d.ts +21 -0
  9. package/lib/compile-pool.d.ts +25 -0
  10. package/lib/compile-pool.js +90 -0
  11. package/lib/compile-worker.js +11 -0
  12. package/lib/compiler-calls.d.ts +26 -0
  13. package/lib/compiler-calls.js +97 -0
  14. package/lib/compiler-stamp.d.ts +8 -0
  15. package/lib/compiler-stamp.js +34 -0
  16. package/lib/declarations.d.ts +10 -0
  17. package/lib/declarations.js +80 -0
  18. package/lib/engine-shaders-local.d.ts +6 -0
  19. package/lib/engine-shaders-local.js +75 -0
  20. package/lib/engine-shaders.d.ts +61 -0
  21. package/lib/engine-shaders.js +170 -0
  22. package/lib/hash-pool.d.ts +24 -0
  23. package/lib/hash-pool.js +84 -0
  24. package/lib/hash-worker.js +53 -0
  25. package/lib/hot.d.ts +53 -0
  26. package/lib/hot.js +101 -0
  27. package/lib/index.d.ts +95 -0
  28. package/lib/index.js +895 -0
  29. package/lib/material-builds.d.ts +91 -0
  30. package/lib/material-builds.js +236 -0
  31. package/lib/offline.d.ts +92 -0
  32. package/lib/offline.js +304 -0
  33. package/lib/pack.d.ts +30 -0
  34. package/lib/pack.js +112 -0
  35. package/lib/package-files.d.ts +12 -0
  36. package/lib/package-files.js +39 -0
  37. package/lib/paragraphs.d.ts +19 -0
  38. package/lib/paragraphs.js +131 -0
  39. package/lib/shader-cache.d.ts +59 -0
  40. package/lib/shader-cache.js +213 -0
  41. package/lib/shader-compiler.d.ts +258 -0
  42. package/lib/shader-compiler.js +169 -0
  43. package/lib/shader-types.d.ts +261 -0
  44. package/lib/shader-types.js +4 -0
  45. package/lib/wgsl.d.ts +118 -0
  46. package/lib/wgsl.js +446 -0
  47. package/lib/worker-preload.d.ts +17 -0
  48. package/lib/worker-preload.js +65 -0
  49. package/package.json +69 -5
  50. package/README.md +0 -3
package/lib/offline.js ADDED
@@ -0,0 +1,304 @@
1
+ // The list of a production build's files for offline play. A game's own service worker caches the
2
+ // files that a page needs to start, and the files of each feature that the game uses, so the game
3
+ // runs with no network after its first visit. Each feature's files download only on its first use,
4
+ // so a game that leaves a feature out of its cache leaves out its files, such as the twelve device
5
+ // variants of each shader feature or the KTX2 transcoder. A file of the shader builds that need
6
+ // several features is listed under each of them.
7
+ //
8
+ // The plugin knows what each file holds from the bundler: the modules of each chunk and the source
9
+ // of each copied file. Vite builds each worker in a bundle of its own, and hands the main bundle
10
+ // its files without that knowledge, so a small plugin in each worker build records it. A file's
11
+ // group then follows from the files that name it. A page's start takes every file that its pages
12
+ // and entry scripts name, directly or through other files, except a feature's own files. A feature
13
+ // takes the files that its own files name, except the start's files and other features' files.
14
+ // A file that nothing names goes to the start, so a list never leaves out a file a page may need.
15
+ import { createHash } from 'node:crypto';
16
+ import { posix, relative, resolve, sep } from 'node:path';
17
+ import { ENGINE_SHADERS_ENV, engineShadersRoot } from "./engine-shaders.js";
18
+ /** The file that a production build writes beside the page, with the build's files by group. */
19
+ export const FILES_LIST = 'null3d-files.json';
20
+ /**
21
+ * The engine's modules that make up the features which are not shader features, by feature, as
22
+ * paths in the engine package. A shader feature's files are the shader modules named after it.
23
+ */
24
+ export const FEATURE_MODULES = {
25
+ gltf: [
26
+ 'scene/gltf',
27
+ 'workers/gltf-worker',
28
+ 'scene/gltf-meshopt',
29
+ 'vendor/meshopt/meshopt_decoder.wasm',
30
+ 'scene/gltf-draco',
31
+ 'vendor/draco/draco_wasm_wrapper_gltf',
32
+ 'vendor/draco/draco_decoder_gltf.wasm',
33
+ ],
34
+ ktx2: [
35
+ 'scene/ktx2',
36
+ 'scene/ktx2-file',
37
+ 'scene/ktx2-transcode',
38
+ 'vendor/basis/basis_transcoder.wasm',
39
+ ],
40
+ environment: [
41
+ 'scene/environment-file',
42
+ 'scene/builtin-environments',
43
+ 'scene/panorama',
44
+ 'workers/panorama-worker',
45
+ 'gpu/environment',
46
+ ],
47
+ lut: ['scene/lut-files'],
48
+ sprites: ['scene/sprites'],
49
+ lines: ['scene/lines'],
50
+ };
51
+ /**
52
+ * A shader module of the engine: the main module, a device module of the start, such as
53
+ * `shaders-glsl-draw-index`, or the module of features, such as `shaders-skinning-wgsl-half` or
54
+ * `shaders-hash-and-skinning-wgsl`.
55
+ */
56
+ const SHADER_MODULE = /^generated\/shaders-(?:([a-z][a-z0-9-]*?)-)?(?:wgsl|glsl)(?:-(?:draw-index|tone-map|half))*$/;
57
+ const FEATURE_OF_MODULE = new Map(Object.entries(FEATURE_MODULES).flatMap(([feature, modules]) => modules.map((module) => [module, feature])));
58
+ /**
59
+ * The features whose files hold the engine module `module`, none for a module of the start. A
60
+ * shader feature takes the name that `createEngine`'s `preload` gives it, such as `instance_index`
61
+ * for `shaders-instance-index-wgsl`. The module of the shader builds that need several features
62
+ * belongs to each of them.
63
+ */
64
+ export function featuresOf(module) {
65
+ const feature = FEATURE_OF_MODULE.get(module);
66
+ if (feature)
67
+ return [feature];
68
+ const shaders = SHADER_MODULE.exec(module)?.[1];
69
+ return shaders ? shaders.split('-and-').map((name) => name.replaceAll('-', '_')) : [];
70
+ }
71
+ /**
72
+ * The path of a module in the engine package, as the list's groups name it: from the package's
73
+ * source or built folder, without the extension of a script. Undefined for a file of another
74
+ * package or of the project.
75
+ */
76
+ export function engineModule(id, packageOf) {
77
+ if (id.startsWith('\0'))
78
+ return undefined;
79
+ const file = id.split('?')[0] ?? id;
80
+ // The engine's generated shader modules come from the set on this machine, or from the folder
81
+ // that names one, not from the package, and keep the names that the engine's files import.
82
+ for (const root of [engineShadersRoot(), process.env[ENGINE_SHADERS_ENV]]) {
83
+ if (!root || !file.startsWith(root + sep))
84
+ continue;
85
+ const name = file.slice(file.lastIndexOf(sep) + 1).replace(/\.[cm]?[jt]s$/, '');
86
+ return `generated/${name}`;
87
+ }
88
+ const found = packageOf(file);
89
+ if (found?.name !== '@null3d/engine')
90
+ return undefined;
91
+ return relative(found.root, file)
92
+ .split(sep)
93
+ .join('/')
94
+ .replace(/^(?:src|lib)\//, '')
95
+ .replace(/\.[cm]?[jt]s$/, '');
96
+ }
97
+ /** Files that no page loads: source maps. */
98
+ const UNLISTED = /\.map$/;
99
+ /** The list of the files of a build. */
100
+ export function offlineFiles(files) {
101
+ const listed = files.filter((file) => !UNLISTED.test(file.fileName));
102
+ const byName = new Map(listed.map((file) => [file.fileName, file]));
103
+ const named = namedFiles(listed);
104
+ const fileFeatures = new Map(listed.map((file) => [file.fileName, new Set(file.modules.flatMap(featuresOf))]));
105
+ /**
106
+ * Every file that `from` reaches: each file that a reached file imports, and each that it names
107
+ * when `enters` lets the walk into that file.
108
+ */
109
+ const reach = (from, enters) => {
110
+ const seen = new Set(from);
111
+ for (const name of seen) {
112
+ const file = byName.get(name);
113
+ if (!file)
114
+ continue;
115
+ for (const next of file.imports)
116
+ if (byName.has(next))
117
+ seen.add(next);
118
+ for (const next of named.get(name) ?? [])
119
+ if (!seen.has(next) && enters(fileFeatures.get(next) ?? new Set()))
120
+ seen.add(next);
121
+ }
122
+ return seen;
123
+ };
124
+ const start = reach(listed.filter((file) => file.entry).map((file) => file.fileName), (features) => features.size === 0);
125
+ const features = {};
126
+ const grouped = new Set(start);
127
+ const allFeatures = [...new Set([...fileFeatures.values()].flatMap((set) => [...set]))].sort();
128
+ for (const feature of allFeatures) {
129
+ const roots = listed.filter((file) => fileFeatures.get(file.fileName)?.has(feature));
130
+ const own = reach(roots.map((file) => file.fileName), (others) => others.size === 0 || others.has(feature));
131
+ features[feature] = [...own].filter((name) => !start.has(name)).sort();
132
+ for (const name of own)
133
+ grouped.add(name);
134
+ }
135
+ for (const file of listed)
136
+ if (!grouped.has(file.fileName))
137
+ start.add(file.fileName);
138
+ const list = { start: [...start].sort(), features };
139
+ const version = createHash('sha256').update(JSON.stringify(list)).digest('hex').slice(0, 16);
140
+ return { version, ...list };
141
+ }
142
+ /** The files that each file's text names by their file names, which hold the bundler's hashes. */
143
+ function namedFiles(files) {
144
+ const byBase = new Map();
145
+ for (const { fileName } of files) {
146
+ const base = posix.basename(fileName);
147
+ byBase.set(base, [...(byBase.get(base) ?? []), fileName]);
148
+ }
149
+ const find = baseNamesIn([...byBase.keys()]);
150
+ const named = new Map();
151
+ for (const file of files) {
152
+ if (file.text === undefined) {
153
+ named.set(file.fileName, new Set(file.loads));
154
+ continue;
155
+ }
156
+ const found = new Set(file.loads);
157
+ for (const base of find(file.text))
158
+ for (const name of byBase.get(base) ?? [])
159
+ if (name !== file.fileName)
160
+ found.add(name);
161
+ named.set(file.fileName, found);
162
+ }
163
+ return named;
164
+ }
165
+ /** A pattern that matches `text` as it stands. */
166
+ const literal = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
167
+ /** A base name with an extension, from its last dot on. */
168
+ const WITH_EXTENSION = /\.[^.]+$/;
169
+ /** How many of a base name's last characters index it. */
170
+ const TAIL = 16;
171
+ /**
172
+ * Finds in a text each of `bases`, the base names of a build's files, wherever it stands: inside a
173
+ * longer name too, as one pattern of every base name finds it. Such a pattern grows with the
174
+ * build's files, and a build holds thousands of shader modules, so in Node it took a quarter of a
175
+ * build of the demos. So, when every name has an extension, the search looks only for the names'
176
+ * extensions. At each, it reads the characters that end there, finds the names with that ending,
177
+ * and checks each of them in place. That finds each name the pattern finds, and a name that
178
+ * overlaps another as well.
179
+ */
180
+ export function baseNamesIn(bases) {
181
+ if (bases.length === 0)
182
+ return () => [];
183
+ if (!bases.every((base) => WITH_EXTENSION.test(base))) {
184
+ const longestFirst = [...bases].sort((a, b) => b.length - a.length);
185
+ const pattern = new RegExp(longestFirst.map(literal).join('|'), 'g');
186
+ return (text) => [...text.matchAll(pattern)].map(([base]) => base);
187
+ }
188
+ const byTail = new Map();
189
+ const tails = new Set();
190
+ for (const base of new Set(bases)) {
191
+ const length = Math.min(base.length, TAIL);
192
+ const tail = base.slice(-length);
193
+ tails.add(length);
194
+ byTail.set(tail, [...(byTail.get(tail) ?? []), base]);
195
+ }
196
+ const extensions = [...new Set(bases.map((base) => base.slice(base.lastIndexOf('.'))))].sort((a, b) => b.length - a.length);
197
+ const ends = new RegExp(extensions.map(literal).join('|'), 'g');
198
+ return (text) => {
199
+ const found = [];
200
+ // An extension may begin another, as .js begins .json, so each one that the match begins
201
+ // ends a name of its own.
202
+ for (const match of text.matchAll(ends))
203
+ for (const extension of extensions) {
204
+ if (!match[0].startsWith(extension))
205
+ continue;
206
+ const end = match.index + extension.length;
207
+ for (const length of tails) {
208
+ if (length > end)
209
+ continue;
210
+ for (const base of byTail.get(text.slice(end - length, end)) ?? [])
211
+ if (base.length <= end && text.startsWith(base, end - base.length))
212
+ found.push(base);
213
+ }
214
+ }
215
+ return found;
216
+ };
217
+ }
218
+ /**
219
+ * The files that a worker build made and that a file in the bundle still names, but that the
220
+ * bundle lacks, each with the source that the worker copied. Vite drops a worker's files when it
221
+ * reads the worker as dead, even when another file names one of them: a page then fails to
222
+ * download an engine shader module at run time, although the build succeeded. The caller emits
223
+ * these back, so a build's files always hold every file that its files name.
224
+ */
225
+ export function missingWorkerAssets(bundle, workerFiles) {
226
+ const names = [...workerFiles].flatMap(([fileName, file]) => bundle[fileName] === undefined && !file.chunk ? [fileName] : []);
227
+ if (names.length === 0)
228
+ return [];
229
+ // Only the files that the bundle lacks are searched for, which costs nothing in a whole build.
230
+ const pattern = new RegExp(`${names
231
+ .sort((a, b) => b.length - a.length)
232
+ .map(literal)
233
+ .join('|')}`, 'g');
234
+ const named = new Set();
235
+ for (const file of Object.values(bundle)) {
236
+ const text = file.type === 'chunk' ? file.code : typeof file.source === 'string' ? file.source : '';
237
+ for (const [name] of text.matchAll(pattern))
238
+ named.add(name);
239
+ }
240
+ return [...named].flatMap((fileName) => {
241
+ const source = workerFiles.get(fileName)?.moduleIds[0];
242
+ return source === undefined ? [] : [{ fileName, source }];
243
+ });
244
+ }
245
+ /** A plugin for each worker build that records what each of its files holds, by file name. */
246
+ export function workerFilesPlugin(record) {
247
+ return {
248
+ name: 'null3d:worker-files',
249
+ generateBundle(_options, bundle) {
250
+ for (const file of Object.values(bundle))
251
+ record.set(file.fileName, file.type === 'chunk'
252
+ ? {
253
+ moduleIds: file.moduleIds,
254
+ imports: file.imports,
255
+ loads: file.dynamicImports,
256
+ chunk: true,
257
+ }
258
+ : { moduleIds: file.originalFileNames, imports: [], loads: [], chunk: false });
259
+ },
260
+ };
261
+ }
262
+ /** The list of the files that a script's imports on demand import, as Vite writes it. */
263
+ const PRELOAD_LIST = /^const __vite__mapDeps=.*?=>i\.map\(i=>d\[i\]\);/;
264
+ /** A file's text as UTF-8, when the file is a script, a page or a style sheet. */
265
+ function textOf(fileName, source) {
266
+ if (!/\.(?:[cm]?js|html|css)$/.test(fileName))
267
+ return undefined;
268
+ const text = typeof source === 'string' ? source : new TextDecoder().decode(source);
269
+ return text.replace(PRELOAD_LIST, '');
270
+ }
271
+ /**
272
+ * The files of a client build's bundle as the list reads them, with what the worker builds
273
+ * recorded for the files that they made. A file copied from the engine's source, such as a shader
274
+ * module, holds no script that names another file, so its text is left out; `tables` names the
275
+ * files such a module does load, its kind's shared table of shader paragraphs and one for each
276
+ * feature family whose paragraphs it holds. A module of a feature that loads on first use names
277
+ * them, so the tables join that feature's files and never the start's, which is what keeps a
278
+ * page's first download free of them.
279
+ */
280
+ export function listedFiles(bundle, workerFiles, packageOf, root, tables = new Map()) {
281
+ const modulesOf = (ids) => ids.flatMap((id) => engineModule(id.startsWith('\0') ? id : resolve(root, id), packageOf) ?? []);
282
+ return Object.values(bundle).map((file) => {
283
+ if (file.type === 'chunk')
284
+ return {
285
+ fileName: file.fileName,
286
+ entry: file.isEntry,
287
+ modules: modulesOf(file.moduleIds),
288
+ imports: file.imports,
289
+ loads: file.dynamicImports,
290
+ text: textOf(file.fileName, file.code),
291
+ };
292
+ const worker = workerFiles.get(file.fileName);
293
+ const modules = modulesOf(worker?.moduleIds ?? file.originalFileNames);
294
+ const copied = !worker?.chunk && modules.length > 0;
295
+ return {
296
+ fileName: file.fileName,
297
+ entry: file.fileName.endsWith('.html'),
298
+ modules,
299
+ imports: worker?.imports ?? [],
300
+ loads: [...(worker?.loads ?? []), ...(tables.get(file.fileName) ?? [])],
301
+ text: copied ? undefined : textOf(file.fileName, file.source),
302
+ };
303
+ });
304
+ }
package/lib/pack.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** The function that the plugin adds to a module, which rebuilds the module's compiled shaders. */
2
+ export declare const UNPACK = "__null3dShader";
3
+ /**
4
+ * The function of a module whose custom materials' builds load on first use, which imports the
5
+ * builds of a GPU path and a set by its permutation bits, as `material-builds.ts` writes it.
6
+ */
7
+ export declare const LOAD_BUILDS = "__null3dBuilds";
8
+ /** The compiled shaders of one module, with the tables of text that they share. */
9
+ export declare class ShaderPack {
10
+ /** Each distinct WGSL source and GLSL source, by its number. */
11
+ private readonly wgsl;
12
+ private readonly glsl;
13
+ private used;
14
+ /** Whether the module holds no compiled shader, and so needs no function. */
15
+ get empty(): boolean;
16
+ /**
17
+ * The JavaScript expression that takes the place of a compiled shader in the module: a call of
18
+ * the function with the shader's records as JSON text, each WGSL source as its number and each
19
+ * GLSL source as -1 less its number. `hot` is the key of the shader's hot updates on the dev
20
+ * server. `builds` is a shader's place among the module's shaders of its `kind` whose builds
21
+ * load on first use, which the shader's `builds` function imports through the module's function.
22
+ */
23
+ value(shader: object, hot?: string, builds?: number, kind?: string): string;
24
+ /**
25
+ * The function that the module ends with. A function declaration is set up before any of the
26
+ * module's code runs, so a shader in the module's first line can call it. It reads a path's
27
+ * tables the first time a getter needs a source of that path.
28
+ */
29
+ unpacker(): string;
30
+ }
package/lib/pack.js ADDED
@@ -0,0 +1,112 @@
1
+ // Compiled shaders as a module carries them. The builds of one material or effect share most of
2
+ // their text: a custom material joins the same library functions into every variant of the
3
+ // standard material, for both GPU paths, and many builds share whole stages. Written out in full, a
4
+ // sketch with a few such materials made a module of tens of megabytes. So a module keeps each
5
+ // top-level block of text once, and each distinct source once, as the list of its blocks' numbers.
6
+ // WGSL and GLSL have tables of their own, as a page draws with one GPU path and needs the text of
7
+ // that path only. A shader's records name each source by its number in its path's table. A
8
+ // function that the plugin adds to the end of the module gives each source field a getter, which
9
+ // builds the source's text when something reads it, so the engine and the project's code get the
10
+ // same values as before. The module keeps no built text: the sketch reads each source once, when it
11
+ // sends the shader to the thread that draws, so the text lives only in that thread. The other
12
+ // path's text is never built. The records and the tables go into the module as JSON text, which `JSON.parse`
13
+ // reads faster than an object literal of the same size, and which the transforms after the plugin
14
+ // leave on one line. The function makes no code from strings, so a strict Content Security Policy
15
+ // allows it.
16
+ /** The function that the plugin adds to a module, which rebuilds the module's compiled shaders. */
17
+ export const UNPACK = '__null3dShader';
18
+ /**
19
+ * The function of a module whose custom materials' builds load on first use, which imports the
20
+ * builds of a GPU path and a set by its permutation bits, as `material-builds.ts` writes it.
21
+ */
22
+ export const LOAD_BUILDS = '__null3dBuilds';
23
+ /** The key of each field that holds a shader's text, in a compiled shader's records. */
24
+ const SOURCE = 'source';
25
+ /** The field of a WGSL module beside its text, which a GLSL stage does not have. */
26
+ const WGSL_FIELD = 'pipelines';
27
+ /**
28
+ * A source's top-level blocks, each with the line break before it: a block starts at each line that
29
+ * starts with neither white space nor a closing bracket, so a function or struct is one block with
30
+ * its closing line. Joined in order, the blocks give the source back.
31
+ */
32
+ const blocksOf = (source) => source.split(/(?=\n[^\s}\])])/);
33
+ /** A value's number in a table, which adds the value at the end when it is new. */
34
+ function numberIn(table, value) {
35
+ let n = table.get(value);
36
+ if (n === undefined) {
37
+ n = table.size;
38
+ table.set(value, n);
39
+ }
40
+ return n;
41
+ }
42
+ /** The JSON text of the tables of `sources`: each distinct block once, and each source's blocks. */
43
+ function tablesOf(sources) {
44
+ const blocks = new Map();
45
+ const lists = [...sources.keys()].map((source) => blocksOf(source).map((block) => numberIn(blocks, block)));
46
+ return JSON.stringify(JSON.stringify({ blocks: [...blocks.keys()], lists }));
47
+ }
48
+ /** The compiled shaders of one module, with the tables of text that they share. */
49
+ export class ShaderPack {
50
+ /** Each distinct WGSL source and GLSL source, by its number. */
51
+ wgsl = new Map();
52
+ glsl = new Map();
53
+ used = false;
54
+ /** Whether the module holds no compiled shader, and so needs no function. */
55
+ get empty() {
56
+ return !this.used;
57
+ }
58
+ /**
59
+ * The JavaScript expression that takes the place of a compiled shader in the module: a call of
60
+ * the function with the shader's records as JSON text, each WGSL source as its number and each
61
+ * GLSL source as -1 less its number. `hot` is the key of the shader's hot updates on the dev
62
+ * server. `builds` is a shader's place among the module's shaders of its `kind` whose builds
63
+ * load on first use, which the shader's `builds` function imports through the module's function.
64
+ */
65
+ value(shader, hot, builds, kind) {
66
+ this.used = true;
67
+ const { wgsl, glsl } = this;
68
+ const packed = JSON.stringify(shader, function (key, value) {
69
+ if (key !== SOURCE || typeof value !== 'string')
70
+ return value;
71
+ return WGSL_FIELD in this ? numberIn(wgsl, value) : -1 - numberIn(glsl, value);
72
+ });
73
+ const args = [JSON.stringify(packed)];
74
+ if (hot !== undefined || builds !== undefined)
75
+ args.push(hot === undefined ? 'undefined' : JSON.stringify(hot));
76
+ if (builds !== undefined)
77
+ args.push(`${LOAD_BUILDS}, ${builds}, ${JSON.stringify(kind ?? '')}`);
78
+ return `${UNPACK}(${args.join(', ')})`;
79
+ }
80
+ /**
81
+ * The function that the module ends with. A function declaration is set up before any of the
82
+ * module's code runs, so a shader in the module's first line can call it. It reads a path's
83
+ * tables the first time a getter needs a source of that path.
84
+ */
85
+ unpacker() {
86
+ const tables = `[${tablesOf(this.wgsl)}, ${tablesOf(this.glsl)}]`;
87
+ return `
88
+ function ${UNPACK}(text, hot, load, index, kind) {
89
+ const paths = ${UNPACK}.paths || (${UNPACK}.paths = ${tables}.map((json) => ({ json })));
90
+ const sourceOf = (n) => {
91
+ const path = paths[n < 0 ? 1 : 0];
92
+ const tables = path.tables || (path.tables = JSON.parse(path.json));
93
+ return tables.lists[n < 0 ? -1 - n : n].map((block) => tables.blocks[block]).join('');
94
+ };
95
+ const walk = (item) => {
96
+ for (const key in item) {
97
+ const field = item[key];
98
+ if (key === ${JSON.stringify(SOURCE)} && typeof field === 'number')
99
+ Object.defineProperty(item, key, { get: () => sourceOf(field), enumerable: true });
100
+ else if (field !== null && typeof field === 'object') walk(field);
101
+ }
102
+ };
103
+ const shader = JSON.parse(text);
104
+ walk(shader);
105
+ if (hot !== undefined) shader.hot = hot;
106
+ if (load !== undefined)
107
+ shader.builds = (target, set) => load(kind, target, set).then((module) => module.default[index] || {});
108
+ return shader;
109
+ }
110
+ `;
111
+ }
112
+ }
@@ -0,0 +1,12 @@
1
+ /** A published package of the @null3d scope: its name and its folder. */
2
+ export interface Null3dPackage {
3
+ name: string;
4
+ root: string;
5
+ }
6
+ /**
7
+ * Finds the null3D package that a file belongs to: the nearest package.json above the file, when
8
+ * it names a published package of the @null3d scope. This holds for an installed package and for
9
+ * a package's source in a copy of the repository, where the project may not install it. Each
10
+ * folder's answer is kept for later files.
11
+ */
12
+ export declare function null3dPackages(): (file: string) => Null3dPackage | undefined;
@@ -0,0 +1,39 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ /**
4
+ * Finds the null3D package that a file belongs to: the nearest package.json above the file, when
5
+ * it names a published package of the @null3d scope. This holds for an installed package and for
6
+ * a package's source in a copy of the repository, where the project may not install it. Each
7
+ * folder's answer is kept for later files.
8
+ */
9
+ export function null3dPackages() {
10
+ const folders = new Map();
11
+ const packageOf = (folder) => {
12
+ let known = folders.get(folder);
13
+ if (known === undefined) {
14
+ const manifest = join(folder, 'package.json');
15
+ const parent = dirname(folder);
16
+ if (existsSync(manifest)) {
17
+ const name = null3dPackageName(manifest);
18
+ known = name === undefined ? null : { name, root: folder };
19
+ }
20
+ else
21
+ known = parent === folder ? null : packageOf(parent);
22
+ folders.set(folder, known);
23
+ }
24
+ return known;
25
+ };
26
+ return (file) => packageOf(dirname(file)) ?? undefined;
27
+ }
28
+ /** The name in the package.json at `manifest`, when it names a published package of the @null3d scope. */
29
+ function null3dPackageName(manifest) {
30
+ try {
31
+ const { name, private: unpublished } = JSON.parse(readFileSync(manifest, 'utf8'));
32
+ return typeof name === 'string' && name.startsWith('@null3d/') && unpublished !== true
33
+ ? name
34
+ : undefined;
35
+ }
36
+ catch {
37
+ return undefined;
38
+ }
39
+ }
@@ -0,0 +1,19 @@
1
+ import type { Plugin, Rollup } from 'vite';
2
+ /**
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.
5
+ */
6
+ export declare function tableStemsOfFile(file: string): string[];
7
+ /**
8
+ * Emits each shared table of shader paragraphs beside the copied device modules that import it,
9
+ * and gives the files of the tables of each of those modules. A build's bundle is the same after a
10
+ * second call, because a table is emitted once for each folder it belongs in.
11
+ */
12
+ export declare function emitParagraphTables(this: Rollup.PluginContext, bundle: Rollup.OutputBundle, root?: string): Map<string, string[]>;
13
+ /**
14
+ * A plugin for each worker build, which emits the shared tables of shader paragraphs beside the
15
+ * device modules that import them. A worker build copies the engine's device modules as the
16
+ * client build does, so each build emits its own file of the table. The client build does the same
17
+ * through `emitParagraphTables`, and no build emits a table twice.
18
+ */
19
+ export declare function shaderParagraphsPlugin(): Plugin;
@@ -0,0 +1,131 @@
1
+ // The shared tables of shader paragraphs, one for each GPU path. The shader build writes a
2
+ // paragraph that many of a target's device modules hold once, in a module of its own beside them,
3
+ // and each device module imports that module by a relative path.
4
+ //
5
+ // A bundler emits a device module as an asset and copies its bytes without reading them, so the
6
+ // imports survive exactly as the shader build wrote them. Nothing else names the tables, so the
7
+ // bundler never emits them, and the load fails only in a browser. This plugin reads each copied
8
+ // device module's imports and emits the tables they name, in the folder the bundler put the module
9
+ // in, at the names the imports use. The tables then sit beside every module that imports them,
10
+ // whatever the project's assets folder and asset naming pattern are.
11
+ import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from 'node:fs';
12
+ import { dirname, isAbsolute, join, posix, resolve } from 'node:path';
13
+ /** An import of a table of shared paragraphs, at the top of a device module of its kind. */
14
+ const PARAGRAPH_IMPORT = /from '\.\/(shader-paragraphs-[a-z0-9-]+)\.js';/g;
15
+ /**
16
+ * How much of a copied file this reads at first. The shader build writes the imports among the
17
+ * first lines, and a device module is hundreds of kilobytes, so the rest is never read. A device
18
+ * module names a table for each family of paragraphs that it holds, so its imports can run past
19
+ * this much: the reader then takes a larger part of the file, up to the end of its imports.
20
+ */
21
+ const IMPORT_WINDOW = 4096;
22
+ /** A file's first `bytes` bytes as text. */
23
+ function headOf(source, bytes) {
24
+ if (typeof source === 'string')
25
+ return source.slice(0, bytes);
26
+ return new TextDecoder().decode(source.subarray(0, bytes));
27
+ }
28
+ /**
29
+ * The names of the paragraph tables that a device module imports. A module imports its
30
+ * kind's table and one for each feature family whose paragraphs it holds, so the module of a
31
+ * relief feature imports several. The imports end at the first blank line after them.
32
+ */
33
+ function tableStems(read, length) {
34
+ let window = Math.min(IMPORT_WINDOW, length);
35
+ for (;;) {
36
+ const head = read(window);
37
+ // A device module's imports follow its short header, so a file with none in the first
38
+ // window is no device module and holds no table.
39
+ const first = head.indexOf('import ');
40
+ if (first < 0)
41
+ return [];
42
+ const complete = window >= length || head.indexOf('\n\n', first) >= 0;
43
+ if (complete)
44
+ return [...head.matchAll(PARAGRAPH_IMPORT)].map((match) => match[1]);
45
+ window = Math.min(window * 2, length);
46
+ }
47
+ }
48
+ /**
49
+ * The tables that a device module on disk imports. The file is read from its start only, so a
50
+ * build covers the whole generated set without holding any of it in memory.
51
+ */
52
+ export function tableStemsOfFile(file) {
53
+ const fd = openSync(file, 'r');
54
+ try {
55
+ const length = statSync(file).size;
56
+ const read = (bytes) => {
57
+ const buffer = Buffer.alloc(Math.min(bytes, length));
58
+ const count = readSync(fd, buffer, 0, buffer.length, 0);
59
+ return buffer.subarray(0, count).toString('utf8');
60
+ };
61
+ return tableStems(read, length);
62
+ }
63
+ finally {
64
+ closeSync(fd);
65
+ }
66
+ }
67
+ /**
68
+ * The file of the table that `file` imports, or undefined when the engine's package does not hold
69
+ * it: a table the build did not write, which would otherwise fail as a load in a browser and never
70
+ * in the build.
71
+ */
72
+ function tablePath(file, stem, root) {
73
+ for (const name of file.originalFileNames) {
74
+ // A build names a copied file as the page's root sees it, relative or absolute; the table
75
+ // sits beside the file it came from.
76
+ const folder = isAbsolute(name) ? dirname(name) : resolve(root, dirname(name));
77
+ const path = join(folder, `${stem}.js`);
78
+ if (existsSync(path))
79
+ return path;
80
+ }
81
+ return undefined;
82
+ }
83
+ /**
84
+ * Emits each shared table of shader paragraphs beside the copied device modules that import it,
85
+ * and gives the files of the tables of each of those modules. A build's bundle is the same after a
86
+ * second call, because a table is emitted once for each folder it belongs in.
87
+ */
88
+ export function emitParagraphTables(bundle, root = process.cwd()) {
89
+ const tables = new Map();
90
+ const emitted = new Set();
91
+ for (const file of Object.values(bundle)) {
92
+ if (file.type !== 'asset')
93
+ continue;
94
+ const stems = [
95
+ ...new Set(tableStems((bytes) => headOf(file.source, bytes), file.source.length)),
96
+ ];
97
+ if (stems.length === 0)
98
+ continue;
99
+ const own = stems.map((stem) => posix.join(posix.dirname(file.fileName), `${stem}.js`));
100
+ for (const table of own) {
101
+ if (emitted.has(table))
102
+ continue;
103
+ emitted.add(table);
104
+ const stem = posix.basename(table, '.js');
105
+ const path = tablePath(file, stem, root);
106
+ if (!path)
107
+ return this.error(`null3D: ${file.fileName} 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.`);
108
+ this.emitFile({ type: 'asset', fileName: table, source: readFileSync(path) });
109
+ }
110
+ tables.set(file.fileName, own);
111
+ }
112
+ return tables;
113
+ }
114
+ /**
115
+ * A plugin for each worker build, which emits the shared tables of shader paragraphs beside the
116
+ * device modules that import them. A worker build copies the engine's device modules as the
117
+ * client build does, so each build emits its own file of the table. The client build does the same
118
+ * through `emitParagraphTables`, and no build emits a table twice.
119
+ */
120
+ export function shaderParagraphsPlugin() {
121
+ let root = process.cwd();
122
+ return {
123
+ name: 'null3d:shader-paragraphs',
124
+ configResolved(config) {
125
+ root = config.root;
126
+ },
127
+ generateBundle(_options, bundle) {
128
+ emitParagraphTables.call(this, bundle, root);
129
+ },
130
+ };
131
+ }