@threenative/runtime-native 0.3.12 → 0.3.13

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.
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/runtime-native",
3
- "version": "0.3.12",
3
+ "version": "0.3.13",
4
4
  "description": "ThreeNative-owned native host for desktop and Android",
5
5
  "keywords": [
6
6
  "threenative",
@@ -80,15 +80,15 @@
80
80
  "publint": "0.3.22",
81
81
  "three": "0.187.0",
82
82
  "vitest": "4.1.10",
83
- "@threenative/playtest": "0.3.12"
83
+ "@threenative/playtest": "0.3.13"
84
84
  },
85
85
  "dependencies": {
86
86
  "pngjs": "7.0.0",
87
87
  "esbuild": "0.27.0",
88
88
  "typescript": "npm:@typescript/typescript6@6.0.2",
89
- "@threenative/core": "0.3.12",
90
- "@threenative/assets": "0.3.13",
91
- "@threenative/three-native": "0.3.12"
89
+ "@threenative/assets": "0.3.14",
90
+ "@threenative/three-native": "0.3.13",
91
+ "@threenative/core": "0.3.13"
92
92
  },
93
93
  "scripts": {
94
94
  "deps:download": "node scripts/download-deps.mjs",
@@ -105,7 +105,7 @@
105
105
  "native:physics:parity": "pnpm --dir ../.. exec vitest run packages/physics/__tests__/parity.spec.ts && cargo test --manifest-path native/physics/Cargo.toml --lib --test parity -- --nocapture",
106
106
  "native:physics:parity:device": "node scripts/verify-android-physics-parity.mjs",
107
107
  "native:qualify:physical": "node scripts/qualify-physical-mobile.mjs",
108
- "native:verify:desktop": "node scripts/verify-desktop-audio.mjs && node scripts/verify-desktop-stability.mjs && node scripts/verify-desktop-core.mjs && node scripts/verify-desktop-physics.mjs && sh ../../scripts/xvfb.sh node scripts/verify-native-contracts.mjs && pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs && sh ../../scripts/xvfb.sh node scripts/verify-desktop-ui-frame.mjs && vitest run --config vitest.config.ts tests/external-bundle-discovery.test.mjs",
108
+ "native:verify:desktop": "node scripts/verify-desktop-audio.mjs && node scripts/verify-desktop-stability.mjs && node scripts/verify-desktop-core.mjs && node scripts/verify-desktop-physics.mjs && sh ../../scripts/xvfb.sh node scripts/verify-native-contracts.mjs && pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs && sh ../../scripts/xvfb.sh node scripts/verify-desktop-ui-frame.mjs && vitest run --config vitest.config.ts tests/external-bundle-discovery.test.mjs tests/host-cli.test.mjs tests/host-window.test.mjs",
109
109
  "native:verify:metahuman": "node scripts/verify-desktop-metahuman.mjs",
110
110
  "native:verify:loading": "pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-loading.mjs",
111
111
  "native:verify:ui-frame": "pnpm --dir ../playtest build && sh ../../scripts/xvfb.sh node scripts/verify-desktop-ui-frame.mjs",
@@ -15,6 +15,17 @@ const require = createRequire(resolve(native, "package.json"));
15
15
  const { build } = require("esbuild");
16
16
  const ts = require("typescript");
17
17
  const core = dirname(require.resolve("@threenative/core/package.json"));
18
+ // A core subpath bundles from the source its package export names: "./spells" -> dist/spells/index.js
19
+ // -> src/spells/index.ts. Guessing src/<last segment>.ts missed the nested spells entries.
20
+ export function coreSubpathSource(coreDir, specifier) {
21
+ try {
22
+ return coreSourcePath(specifier, coreDir);
23
+ } catch (failure) {
24
+ // The mapping rule lives in `coreSourcePath`; this keeps the name and the code #621's test pins.
25
+ const reason = failure instanceof Error ? failure.message : String(failure);
26
+ throw new Error(`TN_NATIVE_ENGINE_UNBOUND: ${specifier} [${reason}]`);
27
+ }
28
+ }
18
29
  const threeNative = dirname(require.resolve("@threenative/three-native/package.json"));
19
30
  const assetsEntry = resolve(dirname(require.resolve("@threenative/assets/package.json")), "dist/index.js");
20
31
 
@@ -27,8 +38,26 @@ const packageImports = { name: "native-player-packages", setup(builder) {
27
38
  });
28
39
  } };
29
40
 
30
- function rejectUpstream(metafile) {
31
- const upstream = Object.keys(metafile.inputs).filter((file) => /(?:^|\/)node_modules\/three\//.test(file));
41
+ /**
42
+ * The source file behind one `@threenative/core/<subpath>` import.
43
+ *
44
+ * The native player bundles source, so the subpath maps through the package's own `exports`: the
45
+ * published target `./dist/render-environment.js` is written from `src/render-environment.ts`.
46
+ * Reading the last path segment as the file name is what broke every kit that imports
47
+ * `@threenative/core/render/environment` after PRD-833 moved the module: it asked for
48
+ * `src/environment.ts`, which does not exist, and the desktop build died on that read.
49
+ */
50
+ export function coreSourcePath(specifier, root = core) {
51
+ const subpath = specifier.replace(/^@threenative\/core\//u, "");
52
+ const manifest = JSON.parse(readFileSync(resolve(root, "package.json"), "utf8"));
53
+ const exported = manifest.exports?.[`./${subpath}`];
54
+ const target = typeof exported === "string" ? exported : exported?.import;
55
+ if (typeof target !== "string")
56
+ throw new Error(`TN_NATIVE_ENGINE_CORE_SUBPATH: @threenative/core/${subpath} is not exported.`);
57
+ return resolve(root, "src", target.replace(/^\.\/dist\//u, "").replace(/\.js$/u, ".ts"));
58
+ }
59
+
60
+ function rejectUpstream(metafile) { const upstream = Object.keys(metafile.inputs).filter((file) => /(?:^|\/)node_modules\/three\//.test(file));
32
61
  if (upstream.length) throw new Error(`TN_NATIVE_ENGINE_UPSTREAM: ${upstream.join(", ")}`);
33
62
  }
34
63
 
@@ -114,6 +143,9 @@ function unboundDiagnostic(specifier, name) {
114
143
 
115
144
  /** Bundle the portable entry against native imports; publish nothing when a binding is absent. */
116
145
  export async function bundleNativeEngine({ entry, outfile, boot = true, define = {}, host = boot }) {
146
+ // React and its reconciler branch on `process.env.NODE_ENV`; the player has no `process` (Vite defines it
147
+ // on the desktop path, bundle.mjs). A caller's own define wins.
148
+ define = { "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "production"), ...define };
117
149
  let engineCommit;
118
150
  try {
119
151
  const git = (args) => execFileSync("git", args, { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -134,6 +166,9 @@ export async function bundleNativeEngine({ entry, outfile, boot = true, define =
134
166
  external: ["three", "three/*", "three-mesh-bvh", "three-mesh-bvh/*",
135
167
  "@threenative/core", "@threenative/core/*"],
136
168
  logLevel: "silent", metafile: true, sourcemap: "inline", sourcesContent: true,
169
+ // A UI component imports its stylesheet; the native-css backend reads the extracted sheets from the
170
+ // ui dir, so in the JS realm the import is only a side effect (the desktop path is Vite's CSS split).
171
+ loader: { ".css": "empty" },
137
172
  // A script entry that imports core's loader by relative path (the load test's Fox) would inline the
138
173
  // browser loader and its GLTFLoader; it reads the cooked package like core's own imports do.
139
174
  plugins: [packageImports, { name: "native-assets", setup(builder) {
@@ -189,8 +224,10 @@ export async function bundleNativeEngine({ entry, outfile, boot = true, define =
189
224
  "three/addons/loaders/LUTCubeLoader.js": resolve(player, "core-lut.mjs"),
190
225
  "three/addons/loaders/HDRLoader.js": resolve(player, "core-hdr.mjs"),
191
226
  "three-mesh-bvh": resolve(threeNative, "src/addons/mesh-bvh.ts"),
227
+ "three-mesh-bvh/webgpu": resolve(player, "core-unused.mjs"),
192
228
  "three/addons/utils/BufferGeometryUtils.js": resolve(threeNative, "src/addons/buffer-geometry-utils.ts"),
193
229
  "three/addons/geometries/DecalGeometry.js": resolve(threeNative, "src/addons/decal-geometry.ts"),
230
+ "three/addons/animation/CCDIKSolver.js": resolve(threeNative, "src/addons/ccd-ik-solver.ts"),
194
231
  };
195
232
  const exports = new Map(await Promise.all(Object.values(modules).map(async (facade) => {
196
233
  // A facade's own exports; `three` inside one (an addon over the engine) is the facade above.
@@ -206,6 +243,7 @@ export async function bundleNativeEngine({ entry, outfile, boot = true, define =
206
243
  bundle: true, write: false, format: "iife", platform: "neutral", target: "es2022",
207
244
  conditions: ["threenative-native"], define: { "import.meta.env": "{}", ...define }, metafile: true,
208
245
  logLevel: "silent", outfile, sourcemap: "external", sourcesContent: true,
246
+ loader: { ".css": "empty" },
209
247
  plugins: [packageImports, { name: "native-engine", setup(builder) {
210
248
  builder.onResolve({ filter: /(?:^|\/)assets\.js$/ }, (args) => {
211
249
  if (args.importer.startsWith(`${resolve(core, "src")}${sep}`))
@@ -221,7 +259,7 @@ export async function bundleNativeEngine({ entry, outfile, boot = true, define =
221
259
  builder.onResolve({ filter: /^@threenative\/core$/ }, () => ({ path: "core", namespace: "native-core" }));
222
260
  builder.onLoad({ filter: /.*/, namespace: "native-core" }, () => ({ contents: coreExports, resolveDir: repo }));
223
261
  builder.onResolve({ filter: /^@threenative\/core\// }, (args) => ({
224
- path: resolve(core, "src", `${args.path.split("/").at(-1)}.ts`),
262
+ path: coreSourcePath(args.path),
225
263
  }));
226
264
  builder.onResolve({ filter: /^(three(?:\/|$)|three-mesh-bvh(?:\/|$))/ }, async (args) => {
227
265
  const source = args.namespace === "native-game" ? code : await readFile(args.importer, "utf8");
@@ -272,8 +310,10 @@ export async function bundleNativeEngine({ entry, outfile, boot = true, define =
272
310
 
273
311
  /**
274
312
  * Cooks a project's assets for the native engine beside the game bundle: its own `assets` config,
275
- * decoder-free (the engine's loaders decode no meshopt or KTX2), with the native package on, which
276
- * the player reads from `<bundle dir>/native/assets.tnpk`. `source` overrides the config's source dir.
313
+ * with the native package on, which the player reads from `<bundle dir>/native/assets.tnpk`.
314
+ * Meshopt stays on: the engine compiles the meshoptimizer decoders and its glTF loader decodes
315
+ * EXT/KHR_meshopt_compression (PRD-515). KTX2 is still refused (TN_NATIVE_KTX2_UNSUPPORTED), so its
316
+ * cook output is not kept. `source` overrides the config's source dir.
277
317
  */
278
318
  export async function cookNativeEngineAssets({ project, outfile, source }) {
279
319
  project = resolve(project);
@@ -288,7 +328,7 @@ export async function cookNativeEngineAssets({ project, outfile, source }) {
288
328
  // A file URL: on Windows, `import("D:\\...")` reads `d:` as a URL scheme and throws (engine#612).
289
329
  const { compileAssets } = await import(pathToFileURL(assetsEntry).href);
290
330
  await compileAssets({ cwd: project, config: { ...assets, ...(source && { source: resolve(source) }), nativePackage: true }, platform: "desktop",
291
- runtimeDecoders: { ktx2: false, meshopt: false } });
331
+ runtimeDecoders: { ktx2: false, meshopt: true } });
292
332
  const output = resolve(project, assets.output ?? "public", "native/assets.tnpk");
293
333
  const target = resolve(dirname(resolve(outfile)), "native/assets.tnpk");
294
334
  // A game with no asset files gets no pack (TN_ASSETS_NATIVE_PACKAGE_EMPTY), and the player opens
@@ -357,6 +357,9 @@ export function containerMetadata({ platform = process.platform, config }) {
357
357
  ` <key>CFBundleVersion</key><string>${xml(build)}</string>`,
358
358
  ` <key>CFBundleIconFile</key><string>${xml(slug)}</string>`,
359
359
  ' <key>LSMinimumSystemVersion</key><string>11.0</string>',
360
+ // PRD-859: macOS starts Game Mode for a fullscreen game (CPU and GPU priority, lower input latency).
361
+ ' <key>LSApplicationCategoryType</key><string>public.app-category.games</string>',
362
+ ' <key>LSSupportsGameMode</key><true/>',
360
363
  ' <key>NSHighResolutionCapable</key><true/>',
361
364
  '</dict>',
362
365
  '</plist>',
@@ -586,6 +586,8 @@ export function renderAndroidManifest(source, orientation = 'landscape') {
586
586
  }
587
587
  rendered = upsertApplicationMetadata(rendered, 'TN_KEEP_SCREEN_ON', String(config.display.keepScreenOn));
588
588
  rendered = upsertApplicationMetadata(rendered, 'TN_MAX_FPS', String(config.display.maxFps));
589
+ // `display.priority` (PRD-859): the game thread's CPU priority; anything but "normal" ships the default.
590
+ rendered = upsertApplicationMetadata(rendered, 'TN_PRIORITY', config.display.priority === 'normal' ? 'normal' : 'game');
589
591
  // `display.backgroundMode`. Carried as metadata beside the others so the activity can hand it to
590
592
  // the native host, which decides whether the render loop parks when the player leaves. Fail
591
593
  // closed on a value nobody defined: an unrecognized mode ships as 'pause'.
@@ -10,15 +10,20 @@ import { bundleNativeEngine, cookNativeEngineAssets } from "./bundle-native-engi
10
10
 
11
11
  const PLAYER = "tn-native-engine-player-v8";
12
12
 
13
- /** The launcher: the window opens with the game's title and size, and every argument reaches the player. */
14
- export function launcher(width, height, title) {
13
+ /**
14
+ * The launcher: the window opens with the game's title and size, the player takes the game's CPU priority
15
+ * (`display.priority`, PRD-859), and every argument reaches the player.
16
+ */
17
+ export function launcher(width, height, title, priority = "game") {
18
+ if (priority !== "game" && priority !== "normal") throw new Error(`TN_ENGINE_PACKAGE_ARGS: --priority must be game or normal, got ${priority}`);
15
19
  return [
16
20
  "#!/bin/sh",
17
21
  'DIR=$(cd "$(dirname "$0")" && pwd)',
18
22
  ...(title ? [`TN_PLAYER_TITLE=\${TN_PLAYER_TITLE:-'${title.replaceAll("'", "'\\''")}'}`, "export TN_PLAYER_TITLE"] : []),
19
23
  `: "\${TN_PLAYER_WIDTH:=${width}}"`,
20
24
  `: "\${TN_PLAYER_HEIGHT:=${height}}"`,
21
- "export TN_PLAYER_WIDTH TN_PLAYER_HEIGHT",
25
+ `: "\${TN_PLAYER_PRIORITY:=${priority}}"`,
26
+ "export TN_PLAYER_WIDTH TN_PLAYER_HEIGHT TN_PLAYER_PRIORITY",
22
27
  `exec "$DIR/${PLAYER}" "$DIR/game.js" "$@"`,
23
28
  "",
24
29
  ].join("\n");
@@ -29,7 +34,7 @@ export function launcher(width, height, title) {
29
34
  * and, for a web UI, `ui/`. `bundle` and `cook` are the engine bundler's, injectable for the unit test.
30
35
  */
31
36
  export async function packageEngineDesktop(
32
- { project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title },
37
+ { project, entry, player, ui, output, buildReceipt, width = 1280, height = 720, title, priority },
33
38
  { bundle = bundleNativeEngine, cook = cookNativeEngineAssets } = {},
34
39
  ) {
35
40
  if (!player || !existsSync(player)) {
@@ -50,7 +55,7 @@ export async function packageEngineDesktop(
50
55
  cpSync(ui, join(output, "ui"), { recursive: true });
51
56
  }
52
57
  const start = join(output, basename(output));
53
- writeFileSync(start, launcher(width, height, title));
58
+ writeFileSync(start, launcher(width, height, title, priority));
54
59
  chmodSync(start, 0o755);
55
60
  if (buildReceipt) {
56
61
  const receipt = JSON.parse(readFileSync(buildReceipt, "utf8"));
@@ -79,7 +84,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
79
84
  const args = process.argv.slice(2);
80
85
  const flags = new Map();
81
86
  for (let i = 0; i < args.length; i += 2) {
82
- if (!["--project", "--entry", "--player", "--ui", "--output", "--build-receipt", "--width", "--height", "--title"].includes(args[i]) || !args[i + 1] || flags.has(args[i]))
87
+ if (!["--project", "--entry", "--player", "--ui", "--output", "--build-receipt", "--width", "--height", "--title", "--priority"].includes(args[i]) || !args[i + 1] || flags.has(args[i]))
83
88
  throw new Error(`TN_ENGINE_PACKAGE_ARGS: invalid or repeated option ${args[i]}`);
84
89
  flags.set(args[i], args[i + 1]);
85
90
  }
@@ -94,6 +99,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1]
94
99
  width: flags.has("--width") ? Number(flags.get("--width")) : undefined,
95
100
  height: flags.has("--height") ? Number(flags.get("--height")) : undefined,
96
101
  title: flags.get("--title"),
102
+ priority: flags.get("--priority"),
97
103
  });
98
104
  } catch (error) {
99
105
  console.error(error instanceof Error ? error.message : String(error));
@@ -331,8 +331,15 @@ function verifyOwnedDesktop({ frames, project, artifact, artifactDirectory, logP
331
331
  TN_PLAYTEST_COMPLETION_WINDOW_TIMEOUT_MS: String(Math.max(1, timeout - 10_000)) },
332
332
  });
333
333
  writeFileSync(logPath, `${result.stdout ?? ''}\n${result.stderr ?? ''}`);
334
- if (result.error || result.signal || result.status !== 0)
335
- throw new Error(`TN_NATIVE_STARTER_SMOKE: runner failed: ${result.error?.message ?? result.signal ?? result.stderr ?? result.status}`);
334
+ if (result.error || result.signal || result.status !== 0) {
335
+ // An empty-but-present stderr is still a string, so `??` never reached the exit status: every
336
+ // failed runner read `runner failed: (empty stderr)`, which names neither the status nor the
337
+ // log the run just wrote. PRD-840's native capture stopped here twice with nothing to read.
338
+ const output = `${result.stderr ?? ''}${result.stdout ?? ''}`.trim();
339
+ const why = result.error?.message ?? (result.signal ? `signal ${result.signal}` :
340
+ output.length > 0 ? output : `exit ${result.status}`);
341
+ throw new Error(`TN_NATIVE_STARTER_SMOKE: runner failed: ${why} (log: ${logPath})`);
342
+ }
336
343
  const report = JSON.parse(result.stdout);
337
344
  if (report?.pass !== true || !report.assertionResults?.length
338
345
  || report.assertionResults.some((assertion) => assertion.pass !== true))
@@ -66,5 +66,35 @@ export function createAssetLoader(options = {}) {
66
66
  },
67
67
  prefetch: async () => ({ requested: 0, requestedBytes: 0, settled: 0, settledBytes: 0 }),
68
68
  startBackgroundFill: async () => {},
69
+ // core's memo (PRD-860) stores on the web Cache API; a native host has none, so `build` runs every time.
70
+ memo: async (key, build) => {
71
+ if (typeof key !== "string" || key === "") throw new Error("TN_ASSET_MEMO_INVALID: key must be a non-empty string.");
72
+ return build();
73
+ },
69
74
  };
70
75
  }
76
+
77
+ // core's fetchAsset, verbatim in behaviour: the player's fetch (core-host.mjs) reads `tnpk:` urls.
78
+ export async function fetchAsset(assets, path) {
79
+ const candidates = await assets.resolve(path);
80
+ const failures = [];
81
+ let answered = false;
82
+ let lastError;
83
+ for (const url of candidates) {
84
+ let response;
85
+ try {
86
+ response = await fetch(url);
87
+ } catch (error) {
88
+ lastError = error;
89
+ failures.push(`${url} (${error instanceof Error ? error.message : String(error)})`);
90
+ continue;
91
+ }
92
+ answered = true;
93
+ if (response.ok) return response;
94
+ failures.push(`${url} (status ${String(response.status)})`);
95
+ }
96
+ throw new Error(
97
+ `TN_ASSET_NOT_SERVED: '${path}' is not served by any of ${String(candidates.length)} candidate url(s): ${failures.join("; ") || "none"}.`,
98
+ answered || candidates.length === 0 ? undefined : { cause: lastError },
99
+ );
100
+ }
@@ -26,6 +26,10 @@ const pointerLock = (on) => {
26
26
  };
27
27
  // The legacy host installs the drawing surface as a global too; a script entry (the load test) reads it there.
28
28
  globalThis.canvas = canvas;
29
+ // A page's window is an event target too, and a game may read its input there (`inputTarget: globalThis`):
30
+ // the player's input reaches the window's listeners as it reaches the canvas's.
31
+ globalThis.addEventListener = canvas.addEventListener;
32
+ globalThis.removeEventListener = canvas.removeEventListener;
29
33
  canvas.requestPointerLock = () => pointerLock(true);
30
34
  canvas.exitPointerLock = () => pointerLock(false);
31
35
  // A real monotonic clock, as a page has: ticks and timers keep their fixed-step time, but
@@ -69,7 +73,21 @@ globalThis.__tnDispatchInput = (event) => {
69
73
  for (const callback of [...(listeners.get(event.type) ?? [])]) callback(dom);
70
74
  };
71
75
 
72
- // The player has no fetch, so a run it hosts makes no request. The runner's desktop network check needs the
76
+ // `assets.resolve()` answers `tnpk:<path>` on the player, and a game reads that URL with fetch (procedural-animals
77
+ // loads its `.animal` packs so). This fetch serves the installed package's Buffer entries and nothing else: a
78
+ // network URL is refused by name, so the player still makes no request.
79
+ globalThis.fetch = async (input, init) => {
80
+ const url = typeof input === "string" ? input : String(input?.url ?? input);
81
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(url))
82
+ throw new TypeError(`TN_NATIVE_FETCH_NETWORK_UNSUPPORTED: ${url} (the native player reads only its installed package)`);
83
+ init?.signal?.throwIfAborted?.();
84
+ // core-textures' logicalPath, inlined: that module reads engine globals at import, which this host precedes.
85
+ const hash = url.indexOf("#");
86
+ const path = url.startsWith("tnpk:") ? url.slice(5) : hash < 0 ? url : url.slice(hash + 1);
87
+ return new Response(globalThis.tn.loadAsset("buffer", path).value, { url });
88
+ };
89
+
90
+ // The player makes no network request. The runner's desktop network check needs the
73
91
  // `runtime.network` capability and a `network` observation from the bridge core installs: report the honest
74
92
  // zero, as playtest/src/three/device.ts does for the legacy host's retained fetch failures.
75
93
  {
@@ -124,7 +142,8 @@ globalThis.tn.onUpdate((dt) => {
124
142
 
125
143
  const readSize = () => ({ width: canvas.width, height: canvas.height, aspect: canvas.width / canvas.height });
126
144
  export const platform = {
127
- input: () => [],
145
+ // The player's navigator.getGamepads (v8_main.cpp: scePad on PS4, SDL3 on desktop) in the W3C standard mapping.
146
+ input: () => globalThis.navigator?.getGamepads?.() ?? [],
128
147
  inputTarget: canvas,
129
148
  renderer: { createCanvas: () => canvas, hasWebGPU: () => true, readSize: () => [1280, 720], observeResize: () => () => {} },
130
149
  viewport: { readSize, observeResize: () => () => {} },
@@ -6,6 +6,12 @@ import {
6
6
  defineTypeFlags,
7
7
  } from "../../../../three-native/src/object-surface.ts";
8
8
  import { definePropertyBinding } from "../../../../three-native/src/property-binding.ts";
9
+ import { defineGridHelper } from "../../../../three-native/src/grid-helper.ts";
10
+ import { AnimationUtils, defineCreateInterpolant } from "../../../../three-native/src/animation-utils.ts";
11
+ import { defineBox2 } from "../../../../three-native/src/box2.ts";
12
+ import { defineTypedBufferAttribute } from "../../../../three-native/src/buffer-attributes.ts";
13
+ import { defineEdgesGeometry } from "../../../../three-native/src/edges-geometry.ts";
14
+ import { defineLayeredTargets } from "../../../../three-native/src/render-target.ts";
9
15
  // Identity-preserving imports over the V8 adapter, never upstream Three.js.
10
16
  import { audio } from "./core-audio.mjs";
11
17
  export const {
@@ -33,8 +39,10 @@ export const {
33
39
  ConeGeometry,
34
40
  ConstantAlphaFactor,
35
41
  ConstantColorFactor,
42
+ CubeTexture,
36
43
  CustomBlending,
37
44
  CylinderGeometry,
45
+ DataArrayTexture,
38
46
  DepthTexture,
39
47
  DirectionalLight,
40
48
  DodecahedronGeometry,
@@ -112,6 +120,8 @@ export const {
112
120
  RepeatWrapping,
113
121
  ReverseSubtractEquation,
114
122
  RingGeometry,
123
+ Points,
124
+ PointsMaterial,
115
125
  RoundedBoxGeometry,
116
126
  SRGBColorSpace,
117
127
  Scene,
@@ -168,14 +178,43 @@ export const clone = (root) => skeletonUtils.clone(root);
168
178
  export const { BatchedMesh } = globalThis;
169
179
  // three's InstancedBufferGeometry: an engine class, drawn instanceCount times.
170
180
  export const { InstancedBufferGeometry } = globalThis;
181
+ // three's GridHelper: engine LineSegments with vertex colours (shared definer, ported from three).
182
+ export const GridHelper = defineGridHelper(globalThis);
183
+ // three's EdgesGeometry, Box2, typed BufferAttributes and AnimationUtils: JS ports over engine classes,
184
+ // shared with the Wasm entry (PRD-784 P5-9).
185
+ export const EdgesGeometry = defineEdgesGeometry(globalThis);
186
+ export const Box2 = defineBox2(globalThis);
187
+ export const Uint8BufferAttribute = defineTypedBufferAttribute(BufferAttribute, Uint8Array);
188
+ export const Uint16BufferAttribute = defineTypedBufferAttribute(BufferAttribute, Uint16Array);
189
+ export const Uint32BufferAttribute = defineTypedBufferAttribute(BufferAttribute, Uint32Array);
190
+ export { AnimationUtils };
191
+ // three's track.createInterpolant over the engine tracks (shared with the Wasm entry, PRD-854).
192
+ defineCreateInterpolant(globalThis);
193
+ // three's flags on the engine's layered texture, as the Wasm entry sets them (texture-sources.ts).
194
+ Object.assign(DataArrayTexture.prototype, { isArrayTexture: true, isDataArrayTexture: true });
171
195
  // three exports the engine does not provide: refused at use, by name, as on Wasm (unsupportedExport).
172
196
  export const LineLoop = unsupportedExport("LineLoop");
173
- export const Points = unsupportedExport("Points");
174
197
  export const WebGLRenderer = unsupportedExport("WebGLRenderer");
198
+ export const CompressedArrayTexture = unsupportedExport("CompressedArrayTexture");
199
+ export const InstancedInterleavedBuffer = unsupportedExport("InstancedInterleavedBuffer");
200
+ export const TextureUtils = unsupportedExport("TextureUtils");
201
+ // three's CubeRenderTarget, RenderTarget3D and CubeCamera (shared with the Wasm back end).
202
+ export const { CubeRenderTarget, RenderTarget3D, CubeCamera } = defineLayeredTargets(globalThis);
175
203
  export const { AudioContext, AudioListener, Audio, PositionalAudio, AudioLoader } = audio;
176
204
 
177
205
  // Native traversal and child enumeration are host callbacks, not a second JS scene graph.
178
206
  const bags = new WeakMap();
207
+ // three's userData is the game's object, kept with the wrapper; a game may also replace it (`x.userData = {...}`).
208
+ const userData = {
209
+ configurable: true,
210
+ get() {
211
+ if (!bags.has(this)) bags.set(this, {});
212
+ return bags.get(this);
213
+ },
214
+ set(value) {
215
+ bags.set(this, value);
216
+ },
217
+ };
179
218
  for (const name of [
180
219
  "Object3D",
181
220
  "Scene",
@@ -196,6 +235,7 @@ for (const name of [
196
235
  "Sprite",
197
236
  "Line",
198
237
  "LineSegments",
238
+ "Points",
199
239
  ]) {
200
240
  const prototype = globalThis[name].prototype;
201
241
  const parent = Object.getOwnPropertyDescriptor(prototype, "parent").get;
@@ -205,12 +245,7 @@ for (const name of [
205
245
  return parent.call(this) ?? null;
206
246
  },
207
247
  },
208
- userData: {
209
- get() {
210
- if (!bags.has(this)) bags.set(this, {});
211
- return bags.get(this);
212
- },
213
- },
248
+ userData,
214
249
  });
215
250
  // The engine's walk (`__walk`, shared with the Wasm back end): one call for the whole subtree.
216
251
  prototype.traverse = function (callback) {
@@ -222,6 +257,13 @@ for (const name of [
222
257
  }
223
258
  defineTypeFlags(globalThis);
224
259
  defineReleaseNoops(globalThis);
260
+ // three gives Material, Texture and BufferGeometry a userData too: as on Wasm (browser-backend.ts), every engine
261
+ // class with a dispose method (prd493's terrain splat writes material.userData.TN_TERRAIN_SPLAT).
262
+ for (const name of Object.getOwnPropertyNames(globalThis)) {
263
+ const prototype = typeof globalThis[name] === "function" ? globalThis[name].prototype : undefined;
264
+ if (typeof prototype?.dispose === "function" && !Object.hasOwn(prototype, "userData"))
265
+ Object.defineProperty(prototype, "userData", userData);
266
+ }
225
267
  const geometries = [
226
268
  BoxGeometry,
227
269
  CircleGeometry,
@@ -268,7 +310,7 @@ for (const [base, names] of [
268
310
  [Mesh, [SkinnedMesh, InstancedMesh]],
269
311
  [BufferGeometry, geometries],
270
312
  [BufferAttribute, [Float32BufferAttribute, InstancedBufferAttribute]],
271
- [Texture, [DepthTexture, DataTexture, globalThis.CanvasTexture]],
313
+ [Texture, [DepthTexture, DataTexture, DataArrayTexture, globalThis.CanvasTexture]],
272
314
  [Path, [Shape]],
273
315
  ]) {
274
316
  for (const derived of names) Object.setPrototypeOf(derived.prototype, base.prototype);
@@ -307,6 +349,7 @@ defineObjectSurface({
307
349
  MeshPhysicalMaterial,
308
350
  MeshStandardMaterial,
309
351
  SpriteMaterial,
352
+ PointsMaterial,
310
353
  ],
311
354
  });
312
355
  export { Material };
@@ -323,3 +366,10 @@ export const GreaterEqualCompare = 518;
323
366
  export const CustomToneMapping = 5;
324
367
  export const AlwaysDepth = 1;
325
368
  export const VSMShadowMap = 3;
369
+ // three's interpolation and animation blend constants (constants.js); the engine's keyframe track and
370
+ // AnimationClip constructors accept exactly these values.
371
+ export const InterpolateDiscrete = 2300;
372
+ export const InterpolateLinear = 2301;
373
+ export const InterpolateSmooth = 2302;
374
+ export const NormalAnimationBlendMode = 2500;
375
+ export const AdditiveAnimationBlendMode = 2501;
@@ -15,7 +15,12 @@ withConstValues(constants, { Vector2, Vector3, Vector4, Color });
15
15
 
16
16
  // three's `uniform.value = x` (shared with the Wasm back end): a number goes through at once; an
17
17
  // edited Color or VectorN goes through `syncUniforms`, which the renderer calls before each frame.
18
- const live = liveUniforms(globalThis.tsl.uniform, (node, lanes) => globalThis.tsl.setUniform(node, ...lanes));
18
+ const live = liveUniforms(
19
+ globalThis.tsl.uniform,
20
+ (node, lanes) => globalThis.tsl.setUniform(node, ...lanes),
21
+ // PRD-828: a sync's changed uniforms cross as one call.
22
+ globalThis.tsl.setUniforms && ((nodes, counts, lanes) => globalThis.tsl.setUniforms(nodes, counts, lanes)),
23
+ );
19
24
  // A boolean uniform (the exposure meter's `enabled`) is the live float compared with zero, as on the Wasm back end.
20
25
  export const uniform = booleanUniforms(live.uniform, (scalar) => globalThis.tsl.notEqual(scalar, 0));
21
26
  export const uniformArray = live.uniformArray;
@@ -25,15 +30,19 @@ export const syncUniforms = live.sync;
25
30
  export const { float, int, uint, vec2, vec3, color } = constants;
26
31
  export const vec4 = markNormalTarget(constants.vec4, globalThis.tsl.normalView);
27
32
  export const Fn = withFnBuilder(globalThis.tsl.Fn);
33
+ // three's compute(node, count, workgroupSize) is node.compute(...), which the engine binds (PRD-784 P5-9).
34
+ // An absent workgroup size stays absent: the engine refuses an undefined argument.
35
+ export const compute = (node, count, workgroupSize) =>
36
+ workgroupSize === undefined ? node.compute(count) : node.compute(count, workgroupSize);
28
37
  // three's lights([...]) takes one array; each light crosses as its own engine object.
29
38
  export const lights = (list = []) => globalThis.tsl.lights(...list);
30
39
  export const {
31
- atomicAdd, atomicStore, atomicLoad, Break, Continue, Return, Discard, log, lightShadowMatrix, attribute, uv, renderOutput, If, Loop, luminance, viewZToOrthographicDepth, viewZToPerspectiveDepth, logarithmicDepthToViewZ, vertexIndex,
40
+ atomicAdd, atomicSub, atomicMax, atomicMin, atomicAnd, atomicOr, atomicXor, atomicStore, atomicLoad, Break, Continue, Return, Discard, log, lightShadowMatrix, attribute, uv, renderOutput, If, Loop, luminance, viewZToOrthographicDepth, viewZToPerspectiveDepth, logarithmicDepthToViewZ, vertexIndex,
32
41
  add, sub, mul, div, negate, lessThan, greaterThan, equal, lessThanEqual, greaterThanEqual, and, or, not, all, any, abs, sin, cos,
33
42
  floor, fract, sqrt, exp, exp2, log2, normalize, length, min, max, pow, step, dot,
34
43
  distance, cross, mix, clamp, smoothstep, select, positionLocal, positionWorld, positionWorldDirection,
35
- normalViewGeometry, instanceIndex, cameraViewMatrix, modelWorldMatrix, ivec2, uvec2, nodeObject, reflect, textureLoad, textureSize,
36
- mx_noise_float, mx_worley_noise_float, mx_worley_noise_vec2, pmremTexture, texture3D,
44
+ normalViewGeometry, instanceIndex, cameraViewMatrix, modelWorldMatrix, ivec2, ivec3, ivec4, uvec2, uvec3, uvec4, nodeObject, reflect, textureLoad, textureSize,
45
+ mx_noise_float, mx_worley_noise_float, mx_worley_noise_vec2, pmremTexture,
37
46
  convertToTexture, screenUV, materialColor, materialEmissive, materialMetalness, materialRoughness,
38
47
  cameraPosition, cameraProjectionMatrix, cameraWorldMatrix, positionGeometry, normalWorld, varying,
39
48
  cameraNear, cameraFar, screenSize, depth, viewportSharedTexture, viewportDepthTexture, linearDepth, viewportLinearDepth,
@@ -44,12 +53,15 @@ export const {
44
53
  atan, mod, fwidth, saturation, mat2, hash, time, deltaTime, transformDirection, normalWorldGeometry,
45
54
  getViewPosition, frameGroup, renderGroup, objectGroup, transformNormalToView, property,
46
55
  } = globalThis.tsl;
56
+ // three's viewportCoordinate is screenCoordinate.sub(viewport.xy) (ScreenNode.js). Every native pass
57
+ // draws the full target, so viewport.xy is (0, 0) and the two are equal.
58
+ export const viewportCoordinate = screenCoordinate;
47
59
 
48
60
  export const { storageTexture, textureStore } = defineStorageTextures(globalThis.tsl);
49
61
 
50
62
  // three's storage buffers over engine BufferAttributes (shared with the Wasm back end): `storage`,
51
63
  // `instancedArray` and `attributeArray` build the engine's storage node, whose kernels `renderer.compute` runs.
52
- export const { storage, instancedArray, attributeArray, StorageBufferAttribute, StorageInstancedBufferAttribute } =
64
+ export const { storage, instancedArray, attributeArray, StorageBufferAttribute, StorageInstancedBufferAttribute, IndirectStorageBufferAttribute } =
53
65
  defineStorage(globalThis.tsl, BufferAttribute);
54
66
 
55
67
  // three's pass(), mrt() and MRT slots over the player's one scene pass (shared with the Wasm back
@@ -87,8 +99,9 @@ export const rtt = defineRtt(globalThis.tsl.rtt, { NodeMaterial: globalThis.Node
87
99
  import { defineWgslFn } from "../../../../three-native/src/wgsl-fn.ts";
88
100
  export const wgslFn = defineWgslFn(globalThis.tsl.wgslFunction);
89
101
 
90
- export function texture(value, ...args) {
91
- const node = globalThis.tsl.texture(value, ...args);
102
+ // three's TextureNode.value: assigning another texture swaps the one the node samples (ProbeVolume swaps its volume).
103
+ const swappable = (make) => (value, ...args) => {
104
+ const node = make(value, ...args);
92
105
  let current = value;
93
106
  return Object.defineProperty(node, "value", {
94
107
  get: () => current,
@@ -98,7 +111,10 @@ export function texture(value, ...args) {
98
111
  current = next;
99
112
  },
100
113
  });
101
- }
114
+ };
115
+ export const texture = swappable((...args) => globalThis.tsl.texture(...args));
116
+ export const texture3D = swappable((...args) => globalThis.tsl.texture3D(...args));
117
+ export const cubeTexture = swappable((...args) => globalThis.tsl.cubeTexture(...args));
102
118
 
103
119
  export const {
104
120
  EPSILON, INFINITY, PI, PI2, TWO_PI, HALF_PI, radians,
@@ -114,11 +130,16 @@ export const {
114
130
  // Refused at use, as on Wasm: the engine draws a lamp's cube shadow taps (shadowFilterOptions) and the
115
131
  // virtual shadow map (virtualShadowOptions) in C++, so the three-only bodies of core's soft-shadow.ts
116
132
  // and VirtualShadowNode.setup name these and never call them here.
117
- export const cubeTexture = unsupportedExport("cubeTexture");
118
133
  export const Stack = unsupportedExport("Stack");
119
134
  export const getShadowMaterial = unsupportedExport("getShadowMaterial");
120
135
  export const shadow = unsupportedExport("shadow");
121
136
  export const shadowPositionWorld = unsupportedExport("shadowPositionWorld");
137
+ export const element = unsupportedExport("element");
138
+ export const instancedBufferAttribute = unsupportedExport("instancedBufferAttribute");
139
+ export const instancedDynamicBufferAttribute = unsupportedExport("instancedDynamicBufferAttribute");
140
+ export const positionView = unsupportedExport("positionView");
141
+ export const transformNormal = unsupportedExport("transformNormal");
142
+ export const varyingProperty = unsupportedExport("varyingProperty");
122
143
  // Core's rough diffuse lighting model reads these on three's renderer only; the engine shades roughDiffuse in C++.
123
144
  // biome-ignore lint/style/useNamingConvention: the name is three/tsl's export, which core imports.
124
145
  export const F_Schlick = unsupportedExport("F_Schlick");
@@ -19,3 +19,7 @@ export const {
19
19
  positionPrevious, storage, tangentGeometry, tangentLocal, uint, vec4,
20
20
  context, mrt, output, velocity,
21
21
  } = globalThis;
22
+ // three-mesh-bvh/webgpu's TSL ray query: core's GPUSceneBVH reads these at import, and a scene that builds one is refused.
23
+ export const bvhIntersectFirstHit = unsupportedExport("bvhIntersectFirstHit");
24
+ export const bvhNodeStruct = unsupportedExport("bvhNodeStruct");
25
+ export const rayStruct = unsupportedExport("rayStruct");