@threenative/runtime-native 0.2.0 → 0.3.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.
@@ -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; build native targets with assets.textures set to \\\"none\\\", or keep those 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; build native targets with assets.models set to \\\"none\\\", or keep those 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 {
@@ -199,6 +297,27 @@ if (typeof globalThis.requestAnimationFrame === "function") {
199
297
  }`;
200
298
  const virtualEntry = 'virtual:threenative-native-entry';
201
299
  const resolvedVirtualEntry = `\0${virtualEntry}`;
300
+ // The bundle is wrapped in a classic-script IIFE, where `import.meta` is a parse-time
301
+ // SyntaxError. Dependencies like three's KTX2Loader build default asset URLs from
302
+ // import.meta.url at module scope; on native those defaults are never the real loader
303
+ // path (the compile step copies the transcoder into public/ and core points at it), so
304
+ // any constructible URL is correct. Rewritten textually before Rollup parses.
305
+ const importMetaPlugin = {
306
+ name: 'threenative-import-meta-url',
307
+ enforce: 'pre',
308
+ transform(code) {
309
+ if (!code.includes('import.meta.url')) return null;
310
+ return code.replaceAll('import.meta.url', '"file:///threenative-bundle/"');
311
+ },
312
+ };
313
+ const mobileDecodersPlugin = {
314
+ name: 'threenative-mobile-decoders',
315
+ enforce: 'pre',
316
+ load(id) {
317
+ const stub = mobileDecoderStub(id);
318
+ return stub === undefined ? null : stub;
319
+ },
320
+ };
202
321
  const nativeEntryPlugin = {
203
322
  name: 'threenative-native-entry',
204
323
  enforce: 'pre',
@@ -222,7 +341,11 @@ void game.start().catch((error) => console.error(
222
341
  mkdirSync(dirname(absoluteOutput), { recursive: true });
223
342
  await build({
224
343
  root: absoluteProject,
225
- plugins: [nativeEntryPlugin],
344
+ define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV) },
345
+ plugins:
346
+ target === 'desktop'
347
+ ? [importMetaPlugin, nativeEntryPlugin]
348
+ : [importMetaPlugin, mobileDecodersPlugin, nativeEntryPlugin],
226
349
  resolve: target === 'desktop' ? undefined : { conditions: ['threenative-native'] },
227
350
  configFile: existsSync(join(absoluteProject, 'vite.config.ts'))
228
351
  ? join(absoluteProject, 'vite.config.ts')