@null3d/vite-plugin 0.0.0-stage → 0.1.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.
- package/LICENSE-APACHE +176 -0
- package/LICENSE-MIT +21 -0
- package/README.md +87 -2
- package/THIRD-PARTY-NOTICES.txt +413 -0
- package/dist/shader-compiler.stamp.json +4 -0
- package/dist/shader-compiler.wasm +0 -0
- package/lib/assets.d.ts +94 -0
- package/lib/assets.js +189 -0
- package/lib/client.d.ts +21 -0
- package/lib/compile-pool.d.ts +25 -0
- package/lib/compile-pool.js +90 -0
- package/lib/compile-worker.js +11 -0
- package/lib/compiler-calls.d.ts +26 -0
- package/lib/compiler-calls.js +97 -0
- package/lib/compiler-stamp.d.ts +8 -0
- package/lib/compiler-stamp.js +34 -0
- package/lib/compress.d.ts +47 -0
- package/lib/compress.js +391 -0
- package/lib/declarations.d.ts +10 -0
- package/lib/declarations.js +80 -0
- package/lib/engine-shaders-local.d.ts +6 -0
- package/lib/engine-shaders-local.js +75 -0
- package/lib/engine-shaders.d.ts +61 -0
- package/lib/engine-shaders.js +170 -0
- package/lib/hash-pool.d.ts +24 -0
- package/lib/hash-pool.js +84 -0
- package/lib/hash-worker.js +53 -0
- package/lib/hot.d.ts +53 -0
- package/lib/hot.js +101 -0
- package/lib/index.d.ts +122 -0
- package/lib/index.js +972 -0
- package/lib/material-builds.d.ts +91 -0
- package/lib/material-builds.js +236 -0
- package/lib/offline.d.ts +92 -0
- package/lib/offline.js +304 -0
- package/lib/pack.d.ts +30 -0
- package/lib/pack.js +112 -0
- package/lib/package-files.d.ts +12 -0
- package/lib/package-files.js +39 -0
- package/lib/paragraphs.d.ts +19 -0
- package/lib/paragraphs.js +131 -0
- package/lib/shader-cache.d.ts +59 -0
- package/lib/shader-cache.js +213 -0
- package/lib/shader-compiler.d.ts +258 -0
- package/lib/shader-compiler.js +169 -0
- package/lib/shader-types.d.ts +261 -0
- package/lib/shader-types.js +4 -0
- package/lib/wgsl.d.ts +118 -0
- package/lib/wgsl.js +447 -0
- package/lib/worker-preload.d.ts +30 -0
- package/lib/worker-preload.js +84 -0
- package/package.json +69 -5
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// The engine's shader modules come from the release's asset, not from the package: the built set is
|
|
2
|
+
// hundreds of megabytes, which no npm package can carry. A project downloads one Brotli-compressed
|
|
3
|
+
// tar, checks it against the hash the installed package names, and unpacks it into a cache that the
|
|
4
|
+
// whole machine shares. A failed download falls back to building the modules locally, so this is an
|
|
5
|
+
// accelerator and never a dependency.
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { homedir } from 'node:os';
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { brotliDecompressSync } from 'node:zlib';
|
|
11
|
+
/** The file in the engine package that names the release's asset. */
|
|
12
|
+
export const ARTIFACT_FILE = 'shader-artifact.json';
|
|
13
|
+
/** The folder that holds each unpacked set, one for each hash, inside the machine's cache. */
|
|
14
|
+
export function engineShadersRoot() {
|
|
15
|
+
return join(process.env.NULL3D_BUILD_CACHE ?? join(homedir(), '.cache', 'null3d'), 'engine-shaders');
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A folder of the engine's generated modules to use as they are, named by `NULL3D_ENGINE_SHADERS`.
|
|
19
|
+
* A build of the engine's sources writes the same modules to `packages/engine/src/generated`, so a
|
|
20
|
+
* checkout that has them, and CI's package test, need neither the download nor a build.
|
|
21
|
+
*/
|
|
22
|
+
export const ENGINE_SHADERS_ENV = 'NULL3D_ENGINE_SHADERS';
|
|
23
|
+
/** The record of a set that a project may use: its hash and the files it holds. */
|
|
24
|
+
const MARKER = '.complete';
|
|
25
|
+
/** The answer for each engine package, so the download and the build happen once per build. */
|
|
26
|
+
const folders = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* The folder that holds one engine package's built shader modules. The release asset is used when
|
|
29
|
+
* it can be had; otherwise the modules are built here, so a project without a network still works.
|
|
30
|
+
*/
|
|
31
|
+
export function engineShaderFolder(lib, sources) {
|
|
32
|
+
let folder = folders.get(lib);
|
|
33
|
+
if (!folder) {
|
|
34
|
+
folder = (async () => {
|
|
35
|
+
const named = process.env[ENGINE_SHADERS_ENV];
|
|
36
|
+
if (named) {
|
|
37
|
+
const given = resolve(named);
|
|
38
|
+
if (existsSync(join(given, 'shaders.ts')))
|
|
39
|
+
return given;
|
|
40
|
+
}
|
|
41
|
+
const artifact = readArtifact(lib);
|
|
42
|
+
if (artifact) {
|
|
43
|
+
const fetched = await sources.fetch(artifact);
|
|
44
|
+
if (fetched)
|
|
45
|
+
return fetched;
|
|
46
|
+
}
|
|
47
|
+
return sources.build();
|
|
48
|
+
})();
|
|
49
|
+
folders.set(lib, folder);
|
|
50
|
+
}
|
|
51
|
+
return folder;
|
|
52
|
+
}
|
|
53
|
+
/** Reads the artifact record beside an engine package's `lib` folder, or nothing when it has none. */
|
|
54
|
+
export function readArtifact(libFolder) {
|
|
55
|
+
const path = join(libFolder, ARTIFACT_FILE);
|
|
56
|
+
try {
|
|
57
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
58
|
+
if (typeof parsed.tag === 'string' &&
|
|
59
|
+
typeof parsed.file === 'string' &&
|
|
60
|
+
typeof parsed.url === 'string' &&
|
|
61
|
+
typeof parsed.sha256 === 'string' &&
|
|
62
|
+
/^[a-f0-9]{64}$/.test(parsed.sha256))
|
|
63
|
+
return parsed;
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
// No record, or one that cannot be read: the caller builds the modules locally instead.
|
|
67
|
+
}
|
|
68
|
+
return undefined;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The folder that holds the modules of `artifact`, downloading and unpacking them when the cache
|
|
72
|
+
* has none. It returns nothing when the download fails or the bytes do not match the hash, and the
|
|
73
|
+
* caller then builds the modules itself.
|
|
74
|
+
*/
|
|
75
|
+
export async function ensureEngineShaders(artifact, report) {
|
|
76
|
+
const folder = join(engineShadersRoot(), artifact.sha256);
|
|
77
|
+
if (existsSync(join(folder, MARKER)))
|
|
78
|
+
return folder;
|
|
79
|
+
try {
|
|
80
|
+
report(`null3D: fetching the engine's shaders from ${artifact.url}`);
|
|
81
|
+
const response = await fetch(artifact.url, { redirect: 'follow' });
|
|
82
|
+
if (!response.ok)
|
|
83
|
+
throw new Error(`the server answered ${response.status}`);
|
|
84
|
+
const compressed = Buffer.from(await response.arrayBuffer());
|
|
85
|
+
const digest = createHash('sha256').update(compressed).digest('hex');
|
|
86
|
+
if (digest !== artifact.sha256)
|
|
87
|
+
throw new Error(`the bytes hash to ${digest}, not ${artifact.sha256}`);
|
|
88
|
+
unpackInto(folder, brotliDecompressSync(compressed));
|
|
89
|
+
return folder;
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
report(`null3D: could not fetch the engine's shaders (${error.message}). Building them from the engine's sources instead, which takes longer.`);
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Writes the files of a tar's bytes into `folder`, which appears whole or not at all: the files go
|
|
98
|
+
* to a folder beside it first, and one rename puts them in place. A file whose name leaves the
|
|
99
|
+
* folder is refused, so an archive can never write outside it.
|
|
100
|
+
*/
|
|
101
|
+
export function unpackInto(folder, tar) {
|
|
102
|
+
const staging = `${folder}.incoming-${process.pid}`;
|
|
103
|
+
rmSync(staging, { recursive: true, force: true });
|
|
104
|
+
mkdirSync(staging, { recursive: true });
|
|
105
|
+
try {
|
|
106
|
+
for (const entry of tarEntries(tar)) {
|
|
107
|
+
const target = join(staging, entry.name);
|
|
108
|
+
if (!target.startsWith(`${staging}/`) && target !== staging)
|
|
109
|
+
throw new Error(`the archive holds ${entry.name}, which leaves its folder`);
|
|
110
|
+
if (entry.directory) {
|
|
111
|
+
mkdirSync(target, { recursive: true });
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
mkdirSync(join(target, '..'), { recursive: true });
|
|
115
|
+
writeFileSync(target, entry.bytes);
|
|
116
|
+
}
|
|
117
|
+
writeFileSync(join(staging, MARKER), '');
|
|
118
|
+
rmSync(folder, { recursive: true, force: true });
|
|
119
|
+
mkdirSync(join(folder, '..'), { recursive: true });
|
|
120
|
+
renameSync(staging, folder);
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
rmSync(staging, { recursive: true, force: true });
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
const BLOCK = 512;
|
|
128
|
+
/** The number in a tar header field: octal digits and spaces, or empty for zero. */
|
|
129
|
+
function octal(header, offset, length) {
|
|
130
|
+
const text = header
|
|
131
|
+
.subarray(offset, offset + length)
|
|
132
|
+
.toString('ascii')
|
|
133
|
+
.replace(/\0.*$/, '')
|
|
134
|
+
.trim();
|
|
135
|
+
return text === '' ? 0 : Number.parseInt(text, 8);
|
|
136
|
+
}
|
|
137
|
+
/** The text in a tar header field, up to its first zero byte. */
|
|
138
|
+
function text(header, offset, length) {
|
|
139
|
+
const field = header.subarray(offset, offset + length);
|
|
140
|
+
const end = field.indexOf(0);
|
|
141
|
+
return field.subarray(0, end < 0 ? field.length : end).toString('utf8');
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* The entries of a tar archive, in its order. The reader takes the ustar form, with the long name
|
|
145
|
+
* in the prefix field, and skips the entry kinds that the release does not use.
|
|
146
|
+
*/
|
|
147
|
+
export function* tarEntries(tar) {
|
|
148
|
+
let at = 0;
|
|
149
|
+
while (at + BLOCK <= tar.length) {
|
|
150
|
+
const header = tar.subarray(at, at + BLOCK);
|
|
151
|
+
// Two zero blocks end an archive; a block that cannot hold a name ends it too.
|
|
152
|
+
if (header.every((byte) => byte === 0))
|
|
153
|
+
return;
|
|
154
|
+
const name = text(header, 0, 100);
|
|
155
|
+
if (name === '')
|
|
156
|
+
return;
|
|
157
|
+
const size = octal(header, 124, 12);
|
|
158
|
+
const type = String.fromCharCode(header[156] ?? 0);
|
|
159
|
+
const prefix = text(header, 345, 155);
|
|
160
|
+
const full = prefix === '' ? name : `${prefix}/${name}`;
|
|
161
|
+
const start = at + BLOCK;
|
|
162
|
+
const end = start + size;
|
|
163
|
+
if (end > tar.length)
|
|
164
|
+
throw new Error(`the archive ends inside ${full}`);
|
|
165
|
+
const directory = type === '5' || full.endsWith('/');
|
|
166
|
+
const bytes = directory ? Buffer.alloc(0) : tar.subarray(start, end);
|
|
167
|
+
yield { name: full.replace(/^\.\//, '').replace(/\/$/, ''), bytes, directory };
|
|
168
|
+
at = end + ((BLOCK - (size % BLOCK)) % BLOCK);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
|
|
2
|
+
export declare function defaultHashWorkers(): number;
|
|
3
|
+
/**
|
|
4
|
+
* Hashes files on worker threads, which start at the first file. An idle worker does not keep the
|
|
5
|
+
* process alive, so a build ends without `close`.
|
|
6
|
+
*/
|
|
7
|
+
export declare class HashPool {
|
|
8
|
+
/** The most workers that run at once. */
|
|
9
|
+
readonly size: number;
|
|
10
|
+
private readonly workers;
|
|
11
|
+
private nextId;
|
|
12
|
+
constructor(size?: number);
|
|
13
|
+
/**
|
|
14
|
+
* The first eight hexadecimal digits of the file's SHA-256, which is the same digest a hash of
|
|
15
|
+
* the whole file's bytes gives. A file that cannot be read rejects with the failure that the
|
|
16
|
+
* read raised.
|
|
17
|
+
*/
|
|
18
|
+
hash(file: string): Promise<string>;
|
|
19
|
+
/** Stops every worker. A later hash starts them again. */
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
/** The worker with the fewest files waiting, or a new one while there is room. */
|
|
22
|
+
private pick;
|
|
23
|
+
private start;
|
|
24
|
+
}
|
package/lib/hash-pool.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The content hashes of the generated shader files, on worker threads. A build names each file it
|
|
2
|
+
// copies by a hash of the file, and the engine's set alone is thousands of files and gigabytes
|
|
3
|
+
// together: on the build's own thread that pass holds up module loading. The pool splits the files
|
|
4
|
+
// across a few workers, each of which reads its file in chunks, so the build hashes many files at
|
|
5
|
+
// once and keeps none of their bytes.
|
|
6
|
+
import { availableParallelism } from 'node:os';
|
|
7
|
+
import { Worker } from 'node:worker_threads';
|
|
8
|
+
/** The most workers a pool starts, where a wider pool read no faster. */
|
|
9
|
+
const MOST_WORKERS = 4;
|
|
10
|
+
/** The workers of a pool by default: one for each core but one, at most `MOST_WORKERS`. */
|
|
11
|
+
export function defaultHashWorkers() {
|
|
12
|
+
return Math.max(1, Math.min(MOST_WORKERS, availableParallelism() - 1));
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Hashes files on worker threads, which start at the first file. An idle worker does not keep the
|
|
16
|
+
* process alive, so a build ends without `close`.
|
|
17
|
+
*/
|
|
18
|
+
export class HashPool {
|
|
19
|
+
/** The most workers that run at once. */
|
|
20
|
+
size;
|
|
21
|
+
workers = [];
|
|
22
|
+
nextId = 0;
|
|
23
|
+
constructor(size = defaultHashWorkers()) {
|
|
24
|
+
this.size = size;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The first eight hexadecimal digits of the file's SHA-256, which is the same digest a hash of
|
|
28
|
+
* the whole file's bytes gives. A file that cannot be read rejects with the failure that the
|
|
29
|
+
* read raised.
|
|
30
|
+
*/
|
|
31
|
+
hash(file) {
|
|
32
|
+
const worker = this.pick();
|
|
33
|
+
const id = this.nextId++;
|
|
34
|
+
const { thread, waiting } = worker;
|
|
35
|
+
const answer = new Promise((resolve, reject) => waiting.set(id, { resolve, reject }));
|
|
36
|
+
thread.ref();
|
|
37
|
+
thread.postMessage({ id, file });
|
|
38
|
+
return answer;
|
|
39
|
+
}
|
|
40
|
+
/** Stops every worker. A later hash starts them again. */
|
|
41
|
+
async close() {
|
|
42
|
+
const workers = this.workers.splice(0);
|
|
43
|
+
await Promise.all(workers.map((worker) => worker.thread.terminate()));
|
|
44
|
+
}
|
|
45
|
+
/** The worker with the fewest files waiting, or a new one while there is room. */
|
|
46
|
+
pick() {
|
|
47
|
+
let worker = this.workers.reduce((best, next) => (!best || next.waiting.size < best.waiting.size ? next : best), undefined);
|
|
48
|
+
if (!worker || (worker.waiting.size > 0 && this.workers.length < this.size))
|
|
49
|
+
worker = this.start();
|
|
50
|
+
return worker;
|
|
51
|
+
}
|
|
52
|
+
start() {
|
|
53
|
+
const thread = new Worker(new URL('./hash-worker.js', import.meta.url));
|
|
54
|
+
const worker = { thread, waiting: new Map() };
|
|
55
|
+
thread.on('message', (answer) => {
|
|
56
|
+
const call = worker.waiting.get(answer.id);
|
|
57
|
+
if (call === undefined)
|
|
58
|
+
return;
|
|
59
|
+
worker.waiting.delete(answer.id);
|
|
60
|
+
if (answer.hash === undefined) {
|
|
61
|
+
call.reject(Object.assign(new Error(answer.error?.message ?? ''), answer.error));
|
|
62
|
+
}
|
|
63
|
+
else
|
|
64
|
+
call.resolve(answer.hash);
|
|
65
|
+
if (worker.waiting.size === 0)
|
|
66
|
+
thread.unref();
|
|
67
|
+
});
|
|
68
|
+
// A thread that stops takes every file it held with it, and the build fails rather than
|
|
69
|
+
// naming a copy by a hash that was never computed.
|
|
70
|
+
const fail = (error) => {
|
|
71
|
+
const index = this.workers.indexOf(worker);
|
|
72
|
+
if (index >= 0)
|
|
73
|
+
this.workers.splice(index, 1);
|
|
74
|
+
for (const call of worker.waiting.values())
|
|
75
|
+
call.reject(error);
|
|
76
|
+
worker.waiting.clear();
|
|
77
|
+
};
|
|
78
|
+
thread.on('error', (error) => fail(new Error(`null3D: a shader hash thread stopped: ${error.message}`)));
|
|
79
|
+
thread.on('exit', (code) => fail(new Error(`null3D: a shader hash thread exited with code ${code}`)));
|
|
80
|
+
thread.unref();
|
|
81
|
+
this.workers.push(worker);
|
|
82
|
+
return worker;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// A worker thread of the hash pool. It reads one file in fixed-size chunks into one buffer of its
|
|
2
|
+
// own and answers with the prefix of the file's SHA-256, so the build hashes many files at once and
|
|
3
|
+
// the page's thread reads no file and keeps none of their bytes. The buffer is reused for every
|
|
4
|
+
// file, so a worker holds no whole file and its memory does not grow with the number of files. The
|
|
5
|
+
// worker imports only Node's own modules, so the plugin runs under Node as well as Bun.
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { open } from 'node:fs/promises';
|
|
8
|
+
import { parentPort } from 'node:worker_threads';
|
|
9
|
+
|
|
10
|
+
/** The bytes that one read takes; a file is hashed in as many reads as it needs. */
|
|
11
|
+
const CHUNK = 64 * 1024;
|
|
12
|
+
/** The buffer that every read fills, so a worker allocates one buffer for its whole life. */
|
|
13
|
+
const chunk = Buffer.allocUnsafe(CHUNK);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Answers with the first eight hexadecimal digits of the file's SHA-256, which is how a copied
|
|
17
|
+
* shader file's name carries its content. The digest is the same as a hash of the whole file's
|
|
18
|
+
* bytes, whatever the chunks are.
|
|
19
|
+
*/
|
|
20
|
+
async function hashFile(file) {
|
|
21
|
+
const handle = await open(file, 'r');
|
|
22
|
+
try {
|
|
23
|
+
const hash = createHash('sha256');
|
|
24
|
+
for (;;) {
|
|
25
|
+
const { bytesRead } = await handle.read(chunk, 0, CHUNK, null);
|
|
26
|
+
if (bytesRead === 0) return hash.digest('hex').slice(0, 8);
|
|
27
|
+
hash.update(chunk.subarray(0, bytesRead));
|
|
28
|
+
}
|
|
29
|
+
} finally {
|
|
30
|
+
await handle.close();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Answers one request with its file's hash, or with the failure that reading it raised. */
|
|
35
|
+
async function answer({ id, file }) {
|
|
36
|
+
try {
|
|
37
|
+
parentPort?.postMessage({ id, hash: await hashFile(file) });
|
|
38
|
+
} catch (error) {
|
|
39
|
+
// The pool raises the failure on the build's thread, which fails the build as a direct read
|
|
40
|
+
// does. The code lets a caller tell a vanished file from a worker that stopped.
|
|
41
|
+
parentPort?.postMessage({
|
|
42
|
+
id,
|
|
43
|
+
error: { message: error.message, code: error.code },
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// The pool sends many files to one worker, and the read buffer is shared, so the files are
|
|
49
|
+
// answered one after another; the other workers run meanwhile.
|
|
50
|
+
let answering = Promise.resolve();
|
|
51
|
+
parentPort?.on('message', (request) => {
|
|
52
|
+
answering = answering.then(() => answer(request));
|
|
53
|
+
});
|
package/lib/hot.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { CompiledWgsl } from './shader-types.js';
|
|
2
|
+
import { type TaggedWgsl } from './wgsl.js';
|
|
3
|
+
/** The event that carries hot updates, on Vite's channel and on the page's global object. */
|
|
4
|
+
export declare const WGSL_UPDATE_EVENT = "null3d:wgsl";
|
|
5
|
+
/** The module that hands hot updates to the engines on a page, which the dev server injects. */
|
|
6
|
+
export declare const HOT_CLIENT = "virtual:null3d/hot";
|
|
7
|
+
/** The module id of the hot client, which no other plugin loads. */
|
|
8
|
+
export declare const HOT_CLIENT_ID = "\0virtual:null3d/hot";
|
|
9
|
+
/** The hot client's name or its module id, as Vite's hook filters match them. */
|
|
10
|
+
export declare const HOT_CLIENT_ADDRESS: RegExp;
|
|
11
|
+
/** The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. */
|
|
12
|
+
export declare const HOT_CLIENT_CODE: string;
|
|
13
|
+
/** One hot update: the new compiled WGSL under its key. */
|
|
14
|
+
export interface WgslUpdate {
|
|
15
|
+
readonly key: string;
|
|
16
|
+
readonly shader: CompiledWgsl;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The key of a project's WGSL: a `.wgsl` file's path from the project's root, or that of a script
|
|
20
|
+
* with the place of a tagged literal among the script's literals, from 0.
|
|
21
|
+
*/
|
|
22
|
+
export declare function hotKey(path: string, literal?: number): string;
|
|
23
|
+
/**
|
|
24
|
+
* What a running page keeps of compiled WGSL, as text: everything of a custom material but its
|
|
25
|
+
* builds. A material whose new WGSL keeps it can swap its shader. Null for a whole shader, which
|
|
26
|
+
* code outside the engine uses as it likes, and for a custom effect or tone curve, which the
|
|
27
|
+
* engine does not swap. Only a reload brings either a new one.
|
|
28
|
+
*/
|
|
29
|
+
export declare function contractOf(shader: CompiledWgsl): string | null;
|
|
30
|
+
/** A tagged literal of a script, with its place among the script's literals. */
|
|
31
|
+
export interface ChangedLiteral {
|
|
32
|
+
readonly index: number;
|
|
33
|
+
readonly literal: TaggedWgsl;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The tagged literals of a script whose WGSL differs between two versions of its code, or null
|
|
37
|
+
* when the code differs elsewhere too, so the script itself must run again.
|
|
38
|
+
*/
|
|
39
|
+
export declare function changedLiterals(before: string, after: string, file: string): ChangedLiteral[] | null;
|
|
40
|
+
/** What the dev server knows of the WGSL that pages run, to judge each change. */
|
|
41
|
+
export declare class HotState {
|
|
42
|
+
/** The contract of each key's WGSL as the page runs it. */
|
|
43
|
+
private readonly contracts;
|
|
44
|
+
/** The code of each script with tagged WGSL, as the page runs it, by file. */
|
|
45
|
+
readonly scripts: Map<string, string>;
|
|
46
|
+
/** Notes the WGSL that the page runs under a key. */
|
|
47
|
+
remember(key: string, shader: CompiledWgsl): void;
|
|
48
|
+
/**
|
|
49
|
+
* True when the page can swap the WGSL under a key for `shader` without a reload: both are
|
|
50
|
+
* custom materials with the same contract.
|
|
51
|
+
*/
|
|
52
|
+
swaps(key: string, shader: CompiledWgsl): boolean;
|
|
53
|
+
}
|
package/lib/hot.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { findTaggedWgsl } from "./wgsl.js";
|
|
2
|
+
/** The event that carries hot updates, on Vite's channel and on the page's global object. */
|
|
3
|
+
export const WGSL_UPDATE_EVENT = 'null3d:wgsl';
|
|
4
|
+
/** The module that hands hot updates to the engines on a page, which the dev server injects. */
|
|
5
|
+
export const HOT_CLIENT = 'virtual:null3d/hot';
|
|
6
|
+
/** The module id of the hot client, which no other plugin loads. */
|
|
7
|
+
export const HOT_CLIENT_ID = `\0${HOT_CLIENT}`;
|
|
8
|
+
/** The hot client's name or its module id, as Vite's hook filters match them. */
|
|
9
|
+
export const HOT_CLIENT_ADDRESS = /^\0?virtual:null3d\/hot$/;
|
|
10
|
+
/** The hot client's code. It also closes Vite's overlay, which may show an earlier WGSL error. */
|
|
11
|
+
export const HOT_CLIENT_CODE = `if (import.meta.hot) {
|
|
12
|
+
import.meta.hot.on(${JSON.stringify(WGSL_UPDATE_EVENT)}, ({ updates }) => {
|
|
13
|
+
for (const overlay of document.querySelectorAll('vite-error-overlay')) overlay.close();
|
|
14
|
+
globalThis.dispatchEvent(new CustomEvent(${JSON.stringify(WGSL_UPDATE_EVENT)}, { detail: updates }));
|
|
15
|
+
console.debug('[null3D] hot updated: ' + updates.map((update) => update.key).join(', '));
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
`;
|
|
19
|
+
/**
|
|
20
|
+
* The key of a project's WGSL: a `.wgsl` file's path from the project's root, or that of a script
|
|
21
|
+
* with the place of a tagged literal among the script's literals, from 0.
|
|
22
|
+
*/
|
|
23
|
+
export function hotKey(path, literal) {
|
|
24
|
+
return literal === undefined ? path : `${path}#${literal}`;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* What a running page keeps of compiled WGSL, as text: everything of a custom material but its
|
|
28
|
+
* builds. A material whose new WGSL keeps it can swap its shader. Null for a whole shader, which
|
|
29
|
+
* code outside the engine uses as it likes, and for a custom effect or tone curve, which the
|
|
30
|
+
* engine does not swap. Only a reload brings either a new one.
|
|
31
|
+
*/
|
|
32
|
+
export function contractOf(shader) {
|
|
33
|
+
if (shader.kind !== 'material')
|
|
34
|
+
return null;
|
|
35
|
+
const { uniforms, textures, locations, attributes, baseColor, objectIds, sceneDepth, alpha } = shader;
|
|
36
|
+
// A vertex offset gives the material the builds of its shadow casters, and reading an index or
|
|
37
|
+
// an id makes the engine keep the table of object ranges. Reading the scene's depth makes it
|
|
38
|
+
// bind the copy. The engine fixes each when it creates the material.
|
|
39
|
+
const casts = shader.functions.includes('vertexOffset');
|
|
40
|
+
return JSON.stringify({
|
|
41
|
+
uniforms,
|
|
42
|
+
textures,
|
|
43
|
+
locations,
|
|
44
|
+
attributes,
|
|
45
|
+
baseColor,
|
|
46
|
+
casts,
|
|
47
|
+
objectIds,
|
|
48
|
+
sceneDepth,
|
|
49
|
+
// A surface that sets or reads the alpha gives the material the cut-out builds, and the
|
|
50
|
+
// engine fixes those and the draw list's mask when it creates it.
|
|
51
|
+
alpha,
|
|
52
|
+
// A draw shader's pipelines declare no vertex buffer, so a change to or from one reloads.
|
|
53
|
+
meshless: shader.meshless === true,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* The code of a script with the text of its tagged literals left out, so two scripts whose code
|
|
58
|
+
* differs only in their WGSL give the same text.
|
|
59
|
+
*/
|
|
60
|
+
function frameOf(code, literals) {
|
|
61
|
+
let frame = '';
|
|
62
|
+
let at = 0;
|
|
63
|
+
for (const { start, end } of literals) {
|
|
64
|
+
frame += `${code.slice(at, start)}\`\``;
|
|
65
|
+
at = end;
|
|
66
|
+
}
|
|
67
|
+
return frame + code.slice(at);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The tagged literals of a script whose WGSL differs between two versions of its code, or null
|
|
71
|
+
* when the code differs elsewhere too, so the script itself must run again.
|
|
72
|
+
*/
|
|
73
|
+
export function changedLiterals(before, after, file) {
|
|
74
|
+
const old = findTaggedWgsl(before, file);
|
|
75
|
+
const now = findTaggedWgsl(after, file);
|
|
76
|
+
if (old.length === 0 || old.length !== now.length)
|
|
77
|
+
return null;
|
|
78
|
+
if (frameOf(before, old) !== frameOf(after, now))
|
|
79
|
+
return null;
|
|
80
|
+
return now.flatMap((literal, index) => literal.source === old[index]?.source ? [] : [{ index, literal }]);
|
|
81
|
+
}
|
|
82
|
+
/** What the dev server knows of the WGSL that pages run, to judge each change. */
|
|
83
|
+
export class HotState {
|
|
84
|
+
/** The contract of each key's WGSL as the page runs it. */
|
|
85
|
+
contracts = new Map();
|
|
86
|
+
/** The code of each script with tagged WGSL, as the page runs it, by file. */
|
|
87
|
+
scripts = new Map();
|
|
88
|
+
/** Notes the WGSL that the page runs under a key. */
|
|
89
|
+
remember(key, shader) {
|
|
90
|
+
this.contracts.set(key, contractOf(shader));
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* True when the page can swap the WGSL under a key for `shader` without a reload: both are
|
|
94
|
+
* custom materials with the same contract.
|
|
95
|
+
*/
|
|
96
|
+
swaps(key, shader) {
|
|
97
|
+
const before = this.contracts.get(key);
|
|
98
|
+
const after = contractOf(shader);
|
|
99
|
+
return before !== undefined && before !== null && before === after;
|
|
100
|
+
}
|
|
101
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { Connect, HtmlTagDescriptor, Plugin, Rollup } from 'vite';
|
|
2
|
+
import { type AssetOptions } from './assets.js';
|
|
3
|
+
export type { AssetOptions } from './assets.js';
|
|
4
|
+
export { FILES_LIST, type OfflineFiles } from './offline.js';
|
|
5
|
+
export type * from './shader-types.js';
|
|
6
|
+
/** Headers that make a page cross-origin isolated, which shared memory and worker threads need. */
|
|
7
|
+
export declare const ISOLATION_HEADERS: Readonly<Record<string, string>>;
|
|
8
|
+
/** Where `bun run dev-cert` writes the local HTTPS certificate. */
|
|
9
|
+
export declare const DEV_CERT_DIR = "target/dev-cert";
|
|
10
|
+
export interface Null3dPluginOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Serve HTTPS on the local network with the certificate in `certDir`, such as one made with
|
|
13
|
+
* mkcert. Phones and tablets reached over the network need HTTPS for shared memory and WebGPU.
|
|
14
|
+
*/
|
|
15
|
+
https?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Serve the `https` server over HTTP/2, which sends every request at once on one connection,
|
|
18
|
+
* where HTTP/1.1 sends six at a time. The dev server sends each module as its own file, and every
|
|
19
|
+
* engine thread loads its own copies, so a page asks for hundreds. The default is false, because
|
|
20
|
+
* Safari on an iPad sometimes stops while a worker loads its modules over HTTP/2.
|
|
21
|
+
*/
|
|
22
|
+
http2?: boolean;
|
|
23
|
+
/** Directory that holds `cert.pem` and `key.pem`; the default is `target/dev-cert` under the project root. */
|
|
24
|
+
certDir?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Write a TypeScript declaration beside each `.wgsl` file that a module imports, such as
|
|
27
|
+
* `glow.wgsl.d.ts` beside `glow.wgsl`, with the types of the file's uniforms. The default is
|
|
28
|
+
* true. Set it to false in a project without TypeScript.
|
|
29
|
+
*/
|
|
30
|
+
wgslDeclarations?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Options of the asset tool for the models that modules import with `?optimized`, such as
|
|
33
|
+
* `import city from './city.glb?optimized'`. The import gives the optimized model's address,
|
|
34
|
+
* which `assets.loadGltf` takes. The tool comes from `@null3d/cli`, which the project installs.
|
|
35
|
+
*/
|
|
36
|
+
assets?: AssetOptions;
|
|
37
|
+
/**
|
|
38
|
+
* Let the page's address set the engine's test switches, such as `?gpu=` and `?hold=`, in
|
|
39
|
+
* production builds too. Without the option, development builds read them and production builds
|
|
40
|
+
* do not, so a link cannot change how a shipped game runs. An explicit false turns them off in
|
|
41
|
+
* every build, the dev server's and the `null3d` command's included. Turn it on for builds of
|
|
42
|
+
* test and benchmark pages.
|
|
43
|
+
*/
|
|
44
|
+
urlSwitches?: boolean;
|
|
45
|
+
}
|
|
46
|
+
/** Sets the isolation headers on every response, including `.wasm` files and worker scripts. */
|
|
47
|
+
export declare const isolationMiddleware: Connect.NextHandleFunction;
|
|
48
|
+
/**
|
|
49
|
+
* Lets the browser keep hashed build files, as a host should. Each engine thread loads its own copy
|
|
50
|
+
* of its script and the core's loader; without this, the browser checks each copy with the server
|
|
51
|
+
* in turn, one round trip per thread.
|
|
52
|
+
*/
|
|
53
|
+
export declare const immutableAssetsMiddleware: Connect.NextHandleFunction;
|
|
54
|
+
/**
|
|
55
|
+
* Takes `Origin` out of the Vary header of an answer to a request from the page's own origin, with
|
|
56
|
+
* the CORS header that the origin chose. Vite's CORS step marks every answer as varying by the
|
|
57
|
+
* request's Origin. The engine's page downloads the sketch module early with `fetch`, which sends no
|
|
58
|
+
* Origin, and the worker's import of it sends one. Without this, the browser cannot use the early
|
|
59
|
+
* copy and asks the server again, one round trip per such file. A request from the same origin needs
|
|
60
|
+
* no CORS header, and the browser names such a request in its Sec-Fetch-Site header.
|
|
61
|
+
*/
|
|
62
|
+
export declare const sameOriginMiddleware: Connect.NextHandleFunction;
|
|
63
|
+
/** The engine core's files, which every production build ships. */
|
|
64
|
+
export declare const CORE_FILES: string[];
|
|
65
|
+
/**
|
|
66
|
+
* The engine's early script, which starts the core's download as soon as a page's HTML arrives.
|
|
67
|
+
* A production build ships it as a file of its own, and each page whose scripts load the core gets
|
|
68
|
+
* a script tag for it.
|
|
69
|
+
*/
|
|
70
|
+
export declare const EARLY_CORE_MODULE = "@null3d/engine/early-core";
|
|
71
|
+
/**
|
|
72
|
+
* The script tag of the early script for a built page, or undefined when the page's scripts do not
|
|
73
|
+
* load the engine core. The core files are the WebAssembly files that the early script names, and a
|
|
74
|
+
* page loads the core when one of its chunks names one of them too. `htmlFile` is the page's path in
|
|
75
|
+
* the build, and `base` the build's public base.
|
|
76
|
+
*/
|
|
77
|
+
export declare function earlyCoreTag(early: Rollup.OutputChunk, entry: Rollup.OutputChunk, bundle: Rollup.OutputBundle, htmlFile: string, base: string): HtmlTagDescriptor | undefined;
|
|
78
|
+
/** The file that a production build writes beside the page, with every package's notices. */
|
|
79
|
+
export declare const NOTICES_FILE = "null3d-third-party-notices.txt";
|
|
80
|
+
/**
|
|
81
|
+
* The third-party notices of the null3D packages that the project depends on: the engine's first,
|
|
82
|
+
* then each add-on's, by name. The tools' notices stay out, since a page ships none of their code.
|
|
83
|
+
* Null when none has notices, as in a project without the engine.
|
|
84
|
+
*/
|
|
85
|
+
export declare function thirdPartyNotices(root: string): string | null;
|
|
86
|
+
/** Vite's setting that decides which assets become data: addresses. */
|
|
87
|
+
type InlineLimit = number | ((file: string, content: Buffer) => boolean | undefined);
|
|
88
|
+
/**
|
|
89
|
+
* Vite's inline limit with one change: no file of a null3D package becomes a data: address. The
|
|
90
|
+
* engine loads its workers' scripts, its WebAssembly and its shader files by address, and a strict
|
|
91
|
+
* Content-Security-Policy blocks a data: address, as does a worker's origin. `own` is the
|
|
92
|
+
* project's setting, which every other file keeps.
|
|
93
|
+
*/
|
|
94
|
+
export declare function inlineLimit(own: InlineLimit | undefined, isPackageFile?: (file: string) => boolean): InlineLimit;
|
|
95
|
+
/**
|
|
96
|
+
* Empties the preload lists of the chunks that a worker imports. Vite's preload helper adds a link
|
|
97
|
+
* to the page's head for each file that a dynamic import needs, and it reads `document`, which a
|
|
98
|
+
* worker has not. A sketch module and a task module run in workers, with every chunk they import,
|
|
99
|
+
* so their lists go: an import still fetches its own file, as any worker's import does.
|
|
100
|
+
*/
|
|
101
|
+
export declare function emptyWorkerPreloads(bundle: Rollup.OutputBundle, seeds: readonly string[]): void;
|
|
102
|
+
/** The parameter that keeps a dotted query from naming a module's extension. */
|
|
103
|
+
export declare const QUERY_EXTENSION_PARAM = "null3d-query";
|
|
104
|
+
/**
|
|
105
|
+
* Keeps a module's query from deciding its type. Vite reads a dotted word at the end of a module's
|
|
106
|
+
* address as the extension, so a sketch at `sketch.ts?render-scale=0.5` parses as JavaScript and
|
|
107
|
+
* fails on its types. The middleware adds a parameter after such a query, which the sketch sees in
|
|
108
|
+
* `import.meta.url` and ignores, and Vite then reads the file's own extension.
|
|
109
|
+
*/
|
|
110
|
+
export declare function queryExtensionMiddleware(): Connect.NextHandleFunction;
|
|
111
|
+
/**
|
|
112
|
+
* The core files missing from the installed engine package, or null when the project does not
|
|
113
|
+
* install the engine.
|
|
114
|
+
*/
|
|
115
|
+
export declare function missingCoreFiles(root: string): string[] | null;
|
|
116
|
+
/**
|
|
117
|
+
* The null3D Vite plugin: isolation headers on the dev and preview servers, optional HTTPS, WGSL
|
|
118
|
+
* compiled for WebGPU and WebGL2 in dev and in builds, hot updates of WGSL on the dev server, and a
|
|
119
|
+
* production build that compiles each sketch module, ships the engine core and starts its download
|
|
120
|
+
* from each page that loads it.
|
|
121
|
+
*/
|
|
122
|
+
export default function null3d(options?: Null3dPluginOptions): Plugin[];
|