@threenative/runtime-native 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Which files in a compiled asset directory the packagers stage.
3
+ *
4
+ * `threenative build` compiles a project's assets into its output root (`public/`) beside a
5
+ * manifest (`assets.manifest.json`) and a receipt (`bake.receipt.json`). Copying only what the
6
+ * build named was the first attempt and it broke real games: measured on real sandbox builds,
7
+ * `public/` holds hand-placed runtime files the manifest never names — wildwood's 536 files
8
+ * including `audio/*.ogg`, fps-framework's 100 `.glb`/`.jpg`, lumen-hall's and menu-spike's
9
+ * `basis/basis_transcoder.*`. Dropping those breaks KTX2 on native.
10
+ *
11
+ * So the rule is inverted: copy everything EXCEPT what is provably junk, and print every skip.
12
+ *
13
+ * 1. Editor and VCS leftovers anywhere in the tree, by basename — `*.orig`, `*.rej`, `*.bak`,
14
+ * `*.swp`, `*~`, `.DS_Store`, `Thumbs.db`, `.gitkeep`.
15
+ * 2. Superseded digest outputs, only when a manifest is present: a `<stem>.<8 hex>.<ext>` whose
16
+ * manifest names a different-hash `<stem>.*.<ext>` in the same directory and not this one.
17
+ * A digest-shaped file whose stem the manifest never names is kept — it may be hand-placed.
18
+ * 3. Everything else, including hand-placed files and the bookkeeping the runtime needs
19
+ * (the manifest and the bake receipt both ship, as they did before this rule).
20
+ *
21
+ * A file the manifest names but disk lacks fails closed with `TN_ASSETS_MANIFEST_MISSING`. With
22
+ * no manifest, rule 1 still applies and rule 2 does not.
23
+ */
24
+
25
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
26
+ import { basename, dirname, join, posix } from "node:path";
27
+
28
+ export const ASSET_MANIFEST_NAME = "assets.manifest.json";
29
+ const RECEIPT_NAME = "bake.receipt.json";
30
+
31
+ /** Basenames that are always an editor's or a VCS's dropping, never a shipped asset. */
32
+ const LEFTOVER_NAMES = new Set([".DS_Store", "Thumbs.db", ".gitkeep"]);
33
+ const LEFTOVER_SUFFIXES = [".orig", ".rej", ".bak", ".swp", "~"];
34
+ /** `<stem>.<8 lowercase hex>.<ext>` — the shape `threenative build` writes a compiled digest as. */
35
+ const DIGEST = /^(?<stem>.+)\.(?<hash>[0-9a-f]{8})\.(?<ext>[^.]+)$/u;
36
+
37
+ /**
38
+ * Every file under `directory`, as `/`-separated paths relative to it, sorted.
39
+ *
40
+ * A symlink or any other non-file entry is refused rather than silently dropped: a package that
41
+ * quietly omits an input is the failure this whole file exists to prevent.
42
+ */
43
+ export function listFiles(directory, relative = "") {
44
+ const files = [];
45
+ for (const entry of readdirSync(join(directory, relative), { withFileTypes: true })) {
46
+ const path = relative ? posix.join(relative, entry.name) : entry.name;
47
+ if (entry.isDirectory()) files.push(...listFiles(directory, path));
48
+ else if (entry.isFile()) files.push(path);
49
+ else throw new Error(`Unsupported asset entry: ${join(directory, path)}`);
50
+ }
51
+ return files.sort();
52
+ }
53
+
54
+ /** The paths one manifest entry names beyond its own `output`: array fields carrying records. */
55
+ function entryOutputs(entry) {
56
+ if (!entry || typeof entry !== "object") return [];
57
+ const outputs = [];
58
+ if (typeof entry.output === "string") outputs.push(entry.output);
59
+ for (const field of Object.values(entry)) {
60
+ if (!Array.isArray(field)) continue;
61
+ for (const auxiliary of field) {
62
+ if (
63
+ auxiliary &&
64
+ typeof auxiliary === "object" &&
65
+ typeof auxiliary.output === "string"
66
+ )
67
+ outputs.push(auxiliary.output);
68
+ }
69
+ }
70
+ return outputs;
71
+ }
72
+
73
+ /** The payloads the bake's receipt owns beyond the manifest, or none when it is absent or unreadable. */
74
+ function readReceiptOutputs(receiptPath) {
75
+ if (!existsSync(receiptPath)) return [];
76
+ try {
77
+ const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
78
+ return Array.isArray(receipt?.outputs)
79
+ ? receipt.outputs.flatMap((output) =>
80
+ typeof output?.path === "string" ? [output.path] : [],
81
+ )
82
+ : [];
83
+ } catch {
84
+ // A corrupt receipt must not fail the package; the manifest still governs, and it is the file
85
+ // the runtime reads. The receipt's own bytes still ship with the rest of the directory.
86
+ return [];
87
+ }
88
+ }
89
+
90
+ /** An editor's or VCS's dropping, keyed by basename anywhere in the tree. */
91
+ function isEditorLeftover(file) {
92
+ const name = basename(file);
93
+ return LEFTOVER_NAMES.has(name) || LEFTOVER_SUFFIXES.some((suffix) => name.endsWith(suffix));
94
+ }
95
+
96
+ /** The `<stem>, <hash>, <ext>` a digest-shaped basename carries, or `null` when it is not one. */
97
+ function digestParts(file) {
98
+ const match = DIGEST.exec(basename(file));
99
+ return match === null
100
+ ? null
101
+ : { stem: match.groups.stem, hash: match.groups.hash, ext: match.groups.ext };
102
+ }
103
+
104
+ /**
105
+ * The manifest-named path that supersedes `file`, or `null` when nothing does.
106
+ *
107
+ * Only a same-directory named file with the same `<stem>` and `<ext>` but a different hash
108
+ * supersedes; a digest-shaped file whose stem the manifest never names is kept, because it may be
109
+ * hand-placed rather than an older output.
110
+ */
111
+ function supersededBy(file, named) {
112
+ const digest = digestParts(file);
113
+ if (digest === null) return null;
114
+ const directory = dirname(file);
115
+ for (const candidate of [...named].sort()) {
116
+ if (candidate === file || dirname(candidate) !== directory) continue;
117
+ const other = digestParts(candidate);
118
+ if (other !== null && other.stem === digest.stem && other.ext === digest.ext) return candidate;
119
+ }
120
+ return null;
121
+ }
122
+
123
+ /**
124
+ * The files to copy from a compiled asset directory: everything except provable junk.
125
+ *
126
+ * Editor leftovers are skipped everywhere, printed with `(editor leftover)`. With a manifest, a
127
+ * digest output superseded by a differently-hashed sibling is skipped and printed with
128
+ * `(superseded by <path>)`, and a file the manifest named but disk lacks fails closed with
129
+ * `TN_ASSETS_MANIFEST_MISSING`. Without a manifest only the editor rule applies.
130
+ */
131
+ export function selectManifestAssets(assets, { log = console.log } = {}) {
132
+ const manifestPath = join(assets, ASSET_MANIFEST_NAME);
133
+ const hasManifest = existsSync(manifestPath);
134
+ const named = new Set();
135
+ if (hasManifest) {
136
+ let manifest;
137
+ try {
138
+ manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
139
+ } catch (error) {
140
+ throw new Error(
141
+ `TN_ASSETS_MANIFEST_INVALID: '${manifestPath}' is not valid JSON: ${
142
+ error instanceof Error ? error.message : String(error)
143
+ }`,
144
+ );
145
+ }
146
+ if (
147
+ manifest?.version !== 1 ||
148
+ typeof manifest.entries !== "object" ||
149
+ manifest.entries === null ||
150
+ Array.isArray(manifest.entries)
151
+ ) {
152
+ throw new Error(`TN_ASSETS_MANIFEST_INVALID: '${manifestPath}' must hold version 1 entries.`);
153
+ }
154
+ for (const entry of Object.values(manifest.entries))
155
+ for (const output of entryOutputs(entry)) named.add(output);
156
+ for (const output of readReceiptOutputs(join(assets, RECEIPT_NAME))) named.add(output);
157
+ }
158
+
159
+ const present = listFiles(assets);
160
+ if (hasManifest) {
161
+ for (const file of [...named].sort()) {
162
+ if (!present.includes(file)) {
163
+ throw new Error(
164
+ `TN_ASSETS_MANIFEST_MISSING: '${file}' is named by '${ASSET_MANIFEST_NAME}' but was not found under ${assets}.`,
165
+ );
166
+ }
167
+ }
168
+ }
169
+
170
+ const selected = [];
171
+ for (const file of present) {
172
+ if (hasManifest && named.has(file)) {
173
+ selected.push(file);
174
+ continue;
175
+ }
176
+ if (isEditorLeftover(file)) {
177
+ log(`ThreeNative packaging: skipped ${file} (editor leftover)`);
178
+ continue;
179
+ }
180
+ if (hasManifest) {
181
+ const superseding = supersededBy(file, named);
182
+ if (superseding !== null) {
183
+ log(`ThreeNative packaging: skipped ${file} (superseded by ${superseding})`);
184
+ continue;
185
+ }
186
+ }
187
+ selected.push(file);
188
+ }
189
+ return selected;
190
+ }
@@ -32,7 +32,9 @@
32
32
  * been built with decoders this file does not know about yet.
33
33
  */
34
34
 
35
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
35
+ import { spawnSync } from 'node:child_process';
36
+ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
37
+ import { tmpdir } from 'node:os';
36
38
  import { join, posix, extname } from 'node:path';
37
39
 
38
40
  /**
@@ -46,14 +48,110 @@ import { join, posix, extname } from 'node:path';
46
48
  * from the same facts CMake reads.
47
49
  */
48
50
 
51
+
52
+ /**
53
+ * What the INSTALLED runtime can decode, asked of the binary that will actually run the game.
54
+ *
55
+ * The derivations below read a source checkout, which a consumer does not have: installing the
56
+ * published tarball is the supported path, and there `deriveDesktopWebpSupport` could only say
57
+ * "I cannot tell" — and then refused, which is the same hardcoded staleness this file exists to
58
+ * prevent, only pointing the other way. A release built WITH libwebp was rejecting the very
59
+ * WebP-packed GLBs the documented `gltf-transform webp` pipeline produces.
60
+ *
61
+ * So ask it. The runtime already answers this question on every boot, in
62
+ * `src/runtime-scripts/image-support-init.js`, by the same `canvas.toDataURL("image/webp")` test
63
+ * @loaders.gl uses. Running that one line under `--no-sdl` needs no display and no GPU window,
64
+ * reports the selected desktop binary's compiled feature. It is not Android/device evidence.
65
+ */
66
+
67
+ /**
68
+ * The packaged runtime executable inside an installed prebuilt, for the host running this build.
69
+ *
70
+ * Keyed by the host, never by "whichever prebuilt directory is listed first". An installed release
71
+ * can carry several keys at once, and only the host's own can be executed: asking a win32-x64
72
+ * binary on Linux answers nothing, and asking a desktop binary about Android answers the wrong
73
+ * question confidently. `package-desktop.mjs` refuses any key but the host's, so this is the
74
+ * binary that will run the game.
75
+ */
76
+ function prebuiltExecutable(runtimeRoot, key = `${process.platform}-${process.arch}`) {
77
+ if (!runtimeRoot) return undefined;
78
+ // Host keyed: the installer names desktop payloads by OS and architecture, and a neighbouring
79
+ // target's executable cannot establish support for the host that will run this build. The
80
+ // candidate has to be a file, not a directory.
81
+ const prebuilt = join(runtimeRoot, 'prebuilt', key);
82
+ try {
83
+ for (const name of ['threenative-runtime', 'threenative-runtime.exe', 'mystral', 'mystral.exe']) {
84
+ const candidate = join(prebuilt, name);
85
+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate;
86
+ }
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ /**
94
+ * Ask an installed prebuilt runtime which image decoders it was built with.
95
+ *
96
+ * Returns `undefined` when there is nothing to ask or the question could not be put — the caller
97
+ * then keeps its existing refusal, so a probe that cannot run never *grants* support.
98
+ */
99
+ export function probePrebuiltDecoders(runtimeRoot, options = {}) {
100
+ const executable = options.executable ?? prebuiltExecutable(runtimeRoot, options.key);
101
+ if (executable === undefined || !existsSync(executable)) return undefined;
102
+ let directory;
103
+ try {
104
+ if (!statSync(executable).isFile()) return undefined;
105
+ directory = mkdtempSync(join(tmpdir(), 'tn-decoder-probe-'));
106
+ const script = join(directory, 'probe.js');
107
+ writeFileSync(
108
+ script,
109
+ 'const c = document.createElement("canvas");\n' +
110
+ 'const webp = c && c.toDataURL ? c.toDataURL("image/webp").indexOf("data:image/webp") === 0 : false;\n' +
111
+ 'console.log(`TN_DECODERS:{"webp":${webp}}`);\n',
112
+ );
113
+ const run = (options.spawn ?? spawnSync)(executable, ['run', script, '--no-sdl', '--frames', '1', '--quiet'], {
114
+ encoding: 'utf8',
115
+ timeout: options.timeoutMs ?? 30_000,
116
+ maxBuffer: 64 * 1024,
117
+ // The feature probe must neither inherit a display nor launch an unrelated game bundle.
118
+ env: { ...process.env, DISPLAY: undefined, WAYLAND_DISPLAY: undefined, MYSTRAL_BUNDLE: undefined },
119
+ });
120
+ // A run that failed to spawn, crashed, timed out or was signalled answers nothing. A decoder
121
+ // line salvaged from a failed run is not the binary's verdict, and reading one as an answer
122
+ // would let a broken probe grant support the runtime does not have.
123
+ if (run.error || run.signal || run.status !== 0) return undefined;
124
+ // Native console.log emits "[log] "; accept only that owned prefix or a plain receipt.
125
+ // A quoted diagnostic, duplicate receipt, malformed payload or absent field is not evidence.
126
+ const output = `${run.stdout ?? ''}\n${run.stderr ?? ''}`;
127
+ const lines = [...output.matchAll(/^(?:\[log\] )?TN_DECODERS:(\{[^\r\n]*\})\r?$/gmu)];
128
+ if (lines.length !== 1) return undefined;
129
+ const payload = JSON.parse(lines[0][1]);
130
+ if (Object.keys(payload).length !== 1 || typeof payload.webp !== 'boolean') return undefined;
131
+ return { webp: payload.webp, executable };
132
+ } catch {
133
+ return undefined;
134
+ } finally {
135
+ // The probe script is a temporary file, not an artifact: leaving one per build behind fills
136
+ // the packaging host's temp directory over a session of repeated builds.
137
+ if (directory !== undefined) rmSync(directory, { force: true, recursive: true });
138
+ }
139
+ }
140
+
49
141
  /** Mirrors the ANDROID branch of the libwebp block in CMakeLists.txt. */
50
142
  export function deriveAndroidWebpSupport(runtimeSource) {
51
143
  if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
144
+ // Deliberately no probe here. The desktop branch asks the binary that will run the game; the
145
+ // Android runtime is an arm64 payload this host cannot execute, so the only executable a probe
146
+ // could reach is the host's desktop build — a different CMake configuration answering a
147
+ // different question. Granting Android WebP from it would be the same stale claim this file
148
+ // exists to prevent, arrived at by a longer route. Unknown stays unknown.
52
149
  return {
53
150
  supported: false,
54
151
  reason:
55
- `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, and a prebuilt ` +
56
- 'Android release does not declare which decoders it was built with',
152
+ `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, a prebuilt ` +
153
+ 'Android release does not declare which decoders it was built with, and no host binary ' +
154
+ 'can answer for it',
57
155
  };
58
156
  }
59
157
  const sourceRoot = join(runtimeSource, 'third_party', 'webp-source');
@@ -92,13 +190,46 @@ export function deriveAndroidWebpSupport(runtimeSource) {
92
190
  * `third_party/webp/libwebp-*` with both a library and headers, which is what CMake's
93
191
  * `WEBP_LIBRARY AND WEBP_INCLUDE_DIR` requires before it defines `MYSTRAL_HAS_WEBP`.
94
192
  */
95
- export function deriveDesktopWebpSupport(runtimeSource) {
193
+ export function deriveDesktopWebpSupport(runtimeSource, runtimeExecutable = undefined) {
194
+ // A selected runtime outranks anything a directory listing suggests, source checkout or not: it
195
+ // is the binary this container ships and the one that will decode the player's textures. A
196
+ // checkout can hold libwebp sources downloaded *after* that binary was built — `download-deps
197
+ // --only webp` then a repackage is a normal sequence — and reading the directory would grant
198
+ // WebP for a runtime compiled without MYSTRAL_HAS_WEBP, turning a build-time refusal into a
199
+ // texture that fails at play.
200
+ if (runtimeExecutable !== undefined) {
201
+ const probed = probePrebuiltDecoders(runtimeSource, { executable: runtimeExecutable });
202
+ if (probed !== undefined) {
203
+ return {
204
+ supported: probed.webp,
205
+ reason: `${probed.executable} answers the @loaders.gl WebP decode test with ` +
206
+ `${probed.webp ? 'YES' : 'NO'}`,
207
+ };
208
+ }
209
+ // Fail closed. A probe that could not run has granted nothing, and falling back to the source
210
+ // tree here would grant support from files this binary may never have been compiled against.
211
+ return {
212
+ supported: false,
213
+ reason:
214
+ `${runtimeExecutable} is the runtime selected for this build and could not answer the ` +
215
+ '@loaders.gl WebP decode test, so nothing can claim WebP support on its behalf',
216
+ };
217
+ }
96
218
  if (!runtimeSource || !existsSync(join(runtimeSource, 'CMakeLists.txt'))) {
219
+ // No source checkout and no selected runtime: this is an installed release, so ask the host's
220
+ // own prebuilt rather than refusing what it may well decode.
221
+ const probed = probePrebuiltDecoders(runtimeSource);
222
+ if (probed !== undefined) {
223
+ return {
224
+ supported: probed.webp,
225
+ reason: `${probed.executable} answers the @loaders.gl WebP decode test with ` +
226
+ `${probed.webp ? 'YES' : 'NO'}`,
227
+ };
228
+ }
97
229
  return {
98
230
  supported: false,
99
231
  reason:
100
- `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, and a prebuilt ` +
101
- 'desktop release does not declare which decoders it was built with',
232
+ `${runtimeSource || '(no runtime root)'} is not a runtime source checkout, a prebuilt desktop release does not declare which decoders it was built with, and its runtime could not be probed`,
102
233
  };
103
234
  }
104
235
  const prebuiltRoot = join(runtimeSource, 'third_party', 'webp');
@@ -243,7 +243,7 @@ function mobileDecoderStub(id) {
243
243
  /**
244
244
  * Main
245
245
  */
246
- async function bundleProject(project, entryPoint, outputPath, target) {
246
+ async function bundleProject(project, entryPoint, outputPath, target, nativeBackend) {
247
247
  const absoluteProject = resolve(project);
248
248
  const absoluteEntry = resolve(absoluteProject, entryPoint);
249
249
  const absoluteOutput = resolve(outputPath);
@@ -350,8 +350,13 @@ void game.start().catch((error) => console.error(
350
350
  // material is not the copy the renderer pushed onto, and the first material build on the phone
351
351
  // dies with "No stack defined for assign operation". `mergeConfig` concatenates arrays, so a
352
352
  // project that dedupes its own packages keeps every one of them.
353
+ // The native physics backend is selected where the runtime has no WebAssembly to run Rapier
354
+ // as WASM: every mobile target, and any desktop host whose engine is not V8. `threenative
355
+ // build` reads that capability from the runtime binary it will package and passes
356
+ // `--native-backend`; a direct call without it keeps the historical desktop backend. The
357
+ // choice is one export map here rather than a platform branch in game code.
353
358
  resolve:
354
- target === 'desktop'
359
+ target === 'desktop' && !nativeBackend
355
360
  ? { dedupe: ['three'] }
356
361
  : { conditions: ['threenative-native'], dedupe: ['three'] },
357
362
  configFile: existsSync(join(absoluteProject, 'vite.config.ts'))
@@ -364,14 +369,26 @@ void game.start().catch((error) => console.error(
364
369
  fileName: () => basename(absoluteOutput),
365
370
  formats: ['es'],
366
371
  },
367
- minify: false,
372
+ // Minified for the shipped asset (roughly half the raw bytes). `keepNames` is not optional:
373
+ // core reads `backend.constructor.name` for the renderer's backend stamp (`renderer.ts`,
374
+ // `geometry-capture.ts`), and the runtime's structured-clone description reads
375
+ // `value.constructor.name` (`url-worker-polyfill.js`). Without it those class names mangle
376
+ // and the reports lie. `comments.legal` keeps the bundled dependencies' `@license`/SPDX
377
+ // banners minification would otherwise strip; sourcemaps stay off, as today.
378
+ minify: true,
368
379
  outDir: dirname(absoluteOutput),
369
380
  rollupOptions: {
370
381
  input: virtualEntry,
371
382
  output: {
372
- banner: `/* TN_NATIVE_BUNDLE_SCOPE */\n(() => {\n${nativePrelude}`,
383
+ // `/*!` makes the scope marker a legal comment, the one class the minifier keeps.
384
+ banner: `/*! TN_NATIVE_BUNDLE_SCOPE */\n(() => {\n${nativePrelude}`,
373
385
  codeSplitting: false,
374
386
  footer: '})();',
387
+ // Vite's lib path defaults the minifier to `{ codegen: false }` for an ES lib, which
388
+ // mangles identifiers but keeps every newline and indent. Force the full pass.
389
+ minify: true,
390
+ keepNames: true,
391
+ comments: { legal: true },
375
392
  },
376
393
  },
377
394
  target: 'es2022',
@@ -393,6 +410,7 @@ async function main() {
393
410
  let outputDir = 'dist';
394
411
  let project = null;
395
412
  let target = null;
413
+ let nativeBackend = false;
396
414
 
397
415
  for (let i = 0; i < args.length; i++) {
398
416
  if (args[i] === '--entry' && args[i + 1]) {
@@ -405,6 +423,8 @@ async function main() {
405
423
  project = args[++i];
406
424
  } else if (args[i] === '--target' && args[i + 1]) {
407
425
  target = args[++i];
426
+ } else if (args[i] === '--native-backend') {
427
+ nativeBackend = true;
408
428
  }
409
429
  }
410
430
 
@@ -413,7 +433,7 @@ async function main() {
413
433
  if (!['android', 'desktop', 'ios'].includes(target)) {
414
434
  throw new Error('--project requires --target android|desktop|ios.');
415
435
  }
416
- await bundleProject(project, entryPoint, outputDir, target);
436
+ await bundleProject(project, entryPoint, outputDir, target, nativeBackend);
417
437
  return;
418
438
  }
419
439