@threenative/runtime-native 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -15,10 +15,10 @@
15
15
  * node scripts/bundle.mjs --entry game.js --output dist/bundle
16
16
  */
17
17
 
18
- import { readFileSync, writeFileSync, writeSync, readdirSync, statSync, mkdirSync, existsSync } from 'fs';
19
- import { createRequire } from 'module';
20
- import { join, dirname, basename, resolve } from 'path';
21
- import { fileURLToPath, pathToFileURL } from 'url';
18
+ import { readFileSync, writeFileSync, writeSync, readdirSync, statSync, mkdirSync, existsSync } from 'node:fs';
19
+ import { createRequire } from 'node:module';
20
+ import { join, dirname, basename, resolve } from 'node:path';
21
+ import { fileURLToPath, pathToFileURL } from 'node:url';
22
22
 
23
23
  const __dirname = dirname(fileURLToPath(import.meta.url));
24
24
 
@@ -29,9 +29,9 @@ function bufferToCArray(buffer, varName) {
29
29
  const bytes = Array.from(buffer);
30
30
  const lines = [];
31
31
 
32
- lines.push(`// Auto-generated - do not edit`);
32
+ lines.push("// Auto-generated - do not edit");
33
33
  lines.push(`// Size: ${buffer.length} bytes`);
34
- lines.push(``);
34
+ lines.push("");
35
35
  lines.push(`static const unsigned char ${varName}[] = {`);
36
36
 
37
37
  // Output 16 bytes per line
@@ -41,8 +41,8 @@ function bufferToCArray(buffer, varName) {
41
41
  lines.push(` ${hex}${i + 16 < bytes.length ? ',' : ''}`);
42
42
  }
43
43
 
44
- lines.push(`};`);
45
- lines.push(``);
44
+ lines.push("};");
45
+ lines.push("");
46
46
  lines.push(`static const unsigned int ${varName}_len = ${buffer.length};`);
47
47
 
48
48
  return lines.join('\n');
@@ -68,7 +68,7 @@ function bundleDirectory(dirPath, prefix = '') {
68
68
  const stat = statSync(fullPath);
69
69
 
70
70
  if (stat.isDirectory()) {
71
- files.push(...bundleDirectory(fullPath, prefix + entry + '_'));
71
+ files.push(...bundleDirectory(fullPath, `${prefix + entry}_`));
72
72
  } else {
73
73
  const varName = prefix + entry.replace(/[^a-zA-Z0-9]/g, '_');
74
74
  files.push({
@@ -88,55 +88,55 @@ function bundleDirectory(dirPath, prefix = '') {
88
88
  function generateVFSHeader(files, outputPath) {
89
89
  const lines = [];
90
90
 
91
- lines.push(`// Auto-generated virtual filesystem`);
92
- lines.push(`// Do not edit`);
93
- lines.push(``);
94
- lines.push(`#pragma once`);
95
- lines.push(``);
96
- lines.push(`#include <cstddef>`);
97
- lines.push(`#include <cstring>`);
98
- lines.push(``);
99
- lines.push(`namespace mystral {`);
100
- lines.push(`namespace vfs {`);
101
- lines.push(``);
91
+ lines.push("// Auto-generated virtual filesystem");
92
+ lines.push("// Do not edit");
93
+ lines.push("");
94
+ lines.push("#pragma once");
95
+ lines.push("");
96
+ lines.push("#include <cstddef>");
97
+ lines.push("#include <cstring>");
98
+ lines.push("");
99
+ lines.push("namespace mystral {");
100
+ lines.push("namespace vfs {");
101
+ lines.push("");
102
102
 
103
103
  // Embed each file
104
104
  for (const file of files) {
105
105
  const buffer = readFileSync(file.path);
106
106
  lines.push(bufferToCArray(buffer, file.varName));
107
- lines.push(``);
107
+ lines.push("");
108
108
  }
109
109
 
110
110
  // File table
111
- lines.push(`struct EmbeddedFile {`);
112
- lines.push(` const char* path;`);
113
- lines.push(` const unsigned char* data;`);
114
- lines.push(` unsigned int size;`);
115
- lines.push(`};`);
116
- lines.push(``);
117
- lines.push(`static const EmbeddedFile files[] = {`);
111
+ lines.push("struct EmbeddedFile {");
112
+ lines.push(" const char* path;");
113
+ lines.push(" const unsigned char* data;");
114
+ lines.push(" unsigned int size;");
115
+ lines.push("};");
116
+ lines.push("");
117
+ lines.push("static const EmbeddedFile files[] = {");
118
118
 
119
119
  for (const file of files) {
120
120
  lines.push(` { "${file.relativePath}", ${file.varName}, ${file.varName}_len },`);
121
121
  }
122
122
 
123
- lines.push(` { nullptr, nullptr, 0 } // Sentinel`);
124
- lines.push(`};`);
125
- lines.push(``);
123
+ lines.push(" { nullptr, nullptr, 0 } // Sentinel");
124
+ lines.push("};");
125
+ lines.push("");
126
126
 
127
127
  // Lookup function
128
- lines.push(`inline const EmbeddedFile* findFile(const char* path) {`);
129
- lines.push(` for (const EmbeddedFile* f = files; f->path != nullptr; ++f) {`);
130
- lines.push(` if (strcmp(f->path, path) == 0) {`);
131
- lines.push(` return f;`);
132
- lines.push(` }`);
133
- lines.push(` }`);
134
- lines.push(` return nullptr;`);
135
- lines.push(`}`);
136
- lines.push(``);
137
-
138
- lines.push(`} // namespace vfs`);
139
- lines.push(`} // namespace mystral`);
128
+ lines.push("inline const EmbeddedFile* findFile(const char* path) {");
129
+ lines.push(" for (const EmbeddedFile* f = files; f->path != nullptr; ++f) {");
130
+ lines.push(" if (strcmp(f->path, path) == 0) {");
131
+ lines.push(" return f;");
132
+ lines.push(" }");
133
+ lines.push(" }");
134
+ lines.push(" return nullptr;");
135
+ lines.push("}");
136
+ lines.push("");
137
+
138
+ lines.push("} // namespace vfs");
139
+ lines.push("} // namespace mystral");
140
140
 
141
141
  const outputDir = dirname(outputPath);
142
142
  if (!existsSync(outputDir)) {
@@ -147,6 +147,99 @@ function generateVFSHeader(files, outputPath) {
147
147
  console.log(`Generated: ${outputPath}`);
148
148
  }
149
149
 
150
+ /**
151
+ * Three's compressed-asset decoders that cannot run on a mobile native target.
152
+ *
153
+ * Android runs QuickJS and iOS runs JavaScriptCore without a WASM JIT: neither has
154
+ * `WebAssembly`, so the Basis/zstd transcoder behind `KTX2Loader`, the Meshopt decoder and
155
+ * Draco's wasm decoder have nothing to instantiate there. Their specifiers are static strings
156
+ * inside `await import(...)`, so a bundler resolves and inlines them whether or not the game
157
+ * ships a single compressed asset — which is how one `.ktx2`-free game came to fail
158
+ * `TN_NATIVE_WASM_ON_MOBILE`. Replacing them here keeps that guard intact by keeping WASM out
159
+ * of the bundle instead of by ignoring it.
160
+ *
161
+ * The replacements construct and configure exactly like the originals so a game that ships no
162
+ * compressed asset boots normally (`createAssetLoader` builds the shared KTX2 loader eagerly);
163
+ * they refuse, by name, only when asked to decode. A game whose compiled assets do need one is
164
+ * refused earlier and louder, by `threenative build`, before this bundle is written.
165
+ */
166
+ const MOBILE_KTX2_MESSAGE =
167
+ // Deliberately never spells the WASM host object: `TN_NATIVE_WASM_ON_MOBILE` greps the
168
+ // finished bundle for that identifier, and a refusal message must not read as the thing it
169
+ // refuses.
170
+ "TN_NATIVE_KTX2_UNSUPPORTED: this Android/iOS bundle carries no Basis transcoder, because the mobile native runtime has no WASM engine. Compiled .ktx2 textures cannot be decoded here; native compilation automatically keeps decoder-free authored textures, or keep compressed textures on the web target.";
171
+ const MOBILE_MESH_MESSAGE =
172
+ "TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: this Android/iOS bundle carries no Meshopt or Draco decoder, because the mobile native runtime has no WASM engine. Compressed model geometry cannot be decoded here; native compilation keeps shared images and decoder-free model geometry, or keep compressed models on the web target.";
173
+
174
+ const MOBILE_DECODER_STUBS = [
175
+ {
176
+ endsWith: '/examples/jsm/loaders/KTX2Loader.js',
177
+ source: `const message = "${MOBILE_KTX2_MESSAGE}";
178
+ export class KTX2Loader {
179
+ constructor() { this.transcoderPath = ""; this.workerConfig = undefined; }
180
+ setTranscoderPath(path) { this.transcoderPath = path; return this; }
181
+ setWorkerLimit() { return this; }
182
+ // Support detection is where core asks whether this platform can transcode at all. Throwing
183
+ // is the documented "renderer exposed no surface to probe" answer: the asset loader resolves
184
+ // its shared loader to undefined and the game boots without compressed textures.
185
+ detectSupport() { throw new Error(message); }
186
+ load(url, onLoad, onProgress, onError) {
187
+ const error = new Error(\`\${message} (requested '\${url}')\`);
188
+ if (typeof onError === "function") onError(error);
189
+ else throw error;
190
+ }
191
+ parse() { throw new Error(message); }
192
+ dispose() { return this; }
193
+ }
194
+ `,
195
+ },
196
+ {
197
+ endsWith: '/examples/jsm/libs/meshopt_decoder.module.js',
198
+ source: `const message = "${MOBILE_MESH_MESSAGE}";
199
+ function refuse() { throw new Error(message); }
200
+ export const MeshoptDecoder = {
201
+ supported: false,
202
+ get ready() { return refuse(); },
203
+ decodeVertexBuffer: refuse,
204
+ decodeIndexBuffer: refuse,
205
+ decodeIndexSequence: refuse,
206
+ decodeGltfBuffer: refuse,
207
+ decodeGltfBufferAsync: refuse,
208
+ useWorkers: refuse,
209
+ };
210
+ `,
211
+ },
212
+ {
213
+ endsWith: '/examples/jsm/loaders/DRACOLoader.js',
214
+ source: `const message = "${MOBILE_MESH_MESSAGE}";
215
+ export class DRACOLoader {
216
+ setDecoderPath() { return this; }
217
+ setDecoderConfig() { return this; }
218
+ setWorkerLimit() { return this; }
219
+ preload() { return this; }
220
+ load(url, onLoad, onProgress, onError) {
221
+ const error = new Error(\`\${message} (requested '\${url}')\`);
222
+ if (typeof onError === "function") onError(error);
223
+ else throw error;
224
+ }
225
+ parse() { throw new Error(message); }
226
+ decodeDracoFile() { throw new Error(message); }
227
+ dispose() { return this; }
228
+ }
229
+ `,
230
+ },
231
+ ];
232
+
233
+ /**
234
+ * Matched on the resolved module path rather than the import specifier so every spelling of
235
+ * the same file — `three/addons/...`, `three/examples/jsm/...`, or a relative import from
236
+ * inside three — lands on the same replacement.
237
+ */
238
+ function mobileDecoderStub(id) {
239
+ const normalized = id.split('\\').join('/');
240
+ return MOBILE_DECODER_STUBS.find((stub) => normalized.endsWith(stub.endsWith))?.source;
241
+ }
242
+
150
243
  /**
151
244
  * Main
152
245
  */
@@ -154,6 +247,11 @@ async function bundleProject(project, entryPoint, outputPath, target) {
154
247
  const absoluteProject = resolve(project);
155
248
  const absoluteEntry = resolve(absoluteProject, entryPoint);
156
249
  const absoluteOutput = resolve(outputPath);
250
+ // Vite's CLI supplies this default; its JavaScript API does not. Native bundling uses the API,
251
+ // so without an explicit default CommonJS packages such as React select their development
252
+ // builds and every game has to repeat this platform seam in vite.config.ts. Preserve an
253
+ // explicitly selected development mode for diagnostics while making shipping builds honest.
254
+ process.env.NODE_ENV ??= 'production';
157
255
  const require = createRequire(join(absoluteProject, 'package.json'));
158
256
  let viteEntry;
159
257
  try {
@@ -166,12 +264,9 @@ async function bundleProject(project, entryPoint, outputPath, target) {
166
264
  const nativeElements = new Map();
167
265
  const nativeGetElementById = document.getElementById.bind(document);
168
266
  const nativeQuerySelector = document.querySelector.bind(document);
169
- const nativeCreateElement = document.createElement.bind(document);
170
267
  document.getElementById = (id) => nativeElements.get(id) ?? nativeGetElementById(id);
171
268
  document.querySelector = (selector) =>
172
269
  selector.startsWith("#") ? nativeElements.get(selector.slice(1)) ?? null : nativeQuerySelector(selector);
173
- document.createElement = (tag) =>
174
- String(tag).toLowerCase() === "canvas" ? globalThis.canvas : nativeCreateElement(tag);
175
270
  for (const id of ["app", "root"]) {
176
271
  if (nativeGetElementById(id) == null) {
177
272
  const element = document.createElement("div");
@@ -199,6 +294,27 @@ if (typeof globalThis.requestAnimationFrame === "function") {
199
294
  }`;
200
295
  const virtualEntry = 'virtual:threenative-native-entry';
201
296
  const resolvedVirtualEntry = `\0${virtualEntry}`;
297
+ // The bundle is wrapped in a classic-script IIFE, where `import.meta` is a parse-time
298
+ // SyntaxError. Dependencies like three's KTX2Loader build default asset URLs from
299
+ // import.meta.url at module scope; on native those defaults are never the real loader
300
+ // path (the compile step copies the transcoder into public/ and core points at it), so
301
+ // any constructible URL is correct. Rewritten textually before Rollup parses.
302
+ const importMetaPlugin = {
303
+ name: 'threenative-import-meta-url',
304
+ enforce: 'pre',
305
+ transform(code) {
306
+ if (!code.includes('import.meta.url')) return null;
307
+ return code.replaceAll('import.meta.url', '"file:///threenative-bundle/"');
308
+ },
309
+ };
310
+ const mobileDecodersPlugin = {
311
+ name: 'threenative-mobile-decoders',
312
+ enforce: 'pre',
313
+ load(id) {
314
+ const stub = mobileDecoderStub(id);
315
+ return stub === undefined ? null : stub;
316
+ },
317
+ };
202
318
  const nativeEntryPlugin = {
203
319
  name: 'threenative-native-entry',
204
320
  enforce: 'pre',
@@ -222,8 +338,22 @@ void game.start().catch((error) => console.error(
222
338
  mkdirSync(dirname(absoluteOutput), { recursive: true });
223
339
  await build({
224
340
  root: absoluteProject,
225
- plugins: [nativeEntryPlugin],
226
- resolve: target === 'desktop' ? undefined : { conditions: ['threenative-native'] },
341
+ define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
342
+ plugins:
343
+ target === 'desktop'
344
+ ? [importMetaPlugin, nativeEntryPlugin]
345
+ : [importMetaPlugin, mobileDecodersPlugin, nativeEntryPlugin],
346
+ // One three, whatever the import graph looks like. The game resolves `three` beside itself
347
+ // while a linked engine package — `@threenative/core`, or anything else installed outside the
348
+ // project — resolves the same bare specifier beside *itself*, so a second physical copy enters
349
+ // the bundle. Three keeps the TSL node stack in module scope, so the copy that builds a
350
+ // material is not the copy the renderer pushed onto, and the first material build on the phone
351
+ // dies with "No stack defined for assign operation". `mergeConfig` concatenates arrays, so a
352
+ // project that dedupes its own packages keeps every one of them.
353
+ resolve:
354
+ target === 'desktop'
355
+ ? { dedupe: ['three'] }
356
+ : { conditions: ['threenative-native'], dedupe: ['three'] },
227
357
  configFile: existsSync(join(absoluteProject, 'vite.config.ts'))
228
358
  ? join(absoluteProject, 'vite.config.ts')
229
359
  : undefined,
@@ -0,0 +1,90 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ const sourceToken = /src\/[A-Za-z0-9_./-]+\.cpp/gu;
6
+ const explicitlyExcludedSources = new Set([
7
+ "src/gltf/gltf_loader.cpp",
8
+ "src/utils/cgltf_impl.cpp",
9
+ ]);
10
+
11
+ function normalizePath(path) {
12
+ return path.replaceAll("\\", "/");
13
+ }
14
+
15
+ function stripCmakeComments(cmakeSource) {
16
+ const withoutBracketComments = cmakeSource.replace(
17
+ /#\[(=*)\[[\s\S]*?\]\1\]/gu,
18
+ (comment) => comment.replace(/[^\r\n]/gu, " "),
19
+ );
20
+ return withoutBracketComments.replace(/#[^\r\n]*/gu, "");
21
+ }
22
+
23
+ function sourcePathsOnDisk(directory, root = directory) {
24
+ const paths = [];
25
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) =>
26
+ a.name.localeCompare(b.name),
27
+ )) {
28
+ const path = join(directory, entry.name);
29
+ if (entry.isDirectory()) {
30
+ paths.push(...sourcePathsOnDisk(path, root));
31
+ } else if (entry.isFile() && entry.name.endsWith(".cpp")) {
32
+ paths.push(`src/${normalizePath(relative(root, path))}`);
33
+ }
34
+ }
35
+ return paths;
36
+ }
37
+
38
+ function excludedSourcePaths(cmakeSource) {
39
+ const block = /set\s*\(\s*MYSTRAL_EXCLUDED_CPP_SOURCES([\s\S]*?)\)/u.exec(cmakeSource);
40
+ return new Set([
41
+ ...explicitlyExcludedSources,
42
+ ...(block?.[1]?.match(sourceToken) ?? []),
43
+ ]);
44
+ }
45
+
46
+ export function checkSourceList({ cmakeSource, sourceRoot, sourcePaths } = {}) {
47
+ if (typeof cmakeSource !== "string")
48
+ throw new TypeError("checkSourceList requires the CMake source text");
49
+
50
+ const activeCmakeSource = stripCmakeComments(cmakeSource);
51
+ const excluded = excludedSourcePaths(activeCmakeSource);
52
+ const listed = new Set(activeCmakeSource.match(sourceToken) ?? []);
53
+ for (const path of excluded) listed.delete(path);
54
+
55
+ const hasExplicitSourcePaths = Array.isArray(sourcePaths);
56
+ const actualSources = (hasExplicitSourcePaths
57
+ ? sourcePaths
58
+ : sourcePathsOnDisk(resolve(sourceRoot ?? "src")))
59
+ .map(normalizePath)
60
+ .sort();
61
+ const unlisted = actualSources.filter((path) => !listed.has(path) && !excluded.has(path));
62
+ const missing = hasExplicitSourcePaths
63
+ ? []
64
+ : [...listed].filter((path) => !existsSync(join(resolve(sourceRoot ?? "src"), path.slice(4))));
65
+ return { unlisted, missing, excluded: [...excluded].sort() };
66
+ }
67
+
68
+ function main() {
69
+ const scriptDirectory = dirname(fileURLToPath(import.meta.url));
70
+ const packageRoot = resolve(scriptDirectory, "..");
71
+ const cmakePath = join(packageRoot, "CMakeLists.txt");
72
+ const sourceRoot = join(packageRoot, "src");
73
+ const report = checkSourceList({
74
+ cmakeSource: readFileSync(cmakePath, "utf8"),
75
+ sourceRoot,
76
+ });
77
+ if (report.unlisted.length > 0 || report.missing.length > 0) {
78
+ if (report.unlisted.length > 0)
79
+ console.error(`Unlisted native C++ sources: ${report.unlisted.join(", ")}`);
80
+ if (report.missing.length > 0)
81
+ console.error(`Missing CMake native C++ sources: ${report.missing.join(", ")}`);
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ console.log(
86
+ `native source list passed (${report.excluded.length} explicit exclusions)`,
87
+ );
88
+ }
89
+
90
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();