@threenative/runtime-native 0.3.4 → 0.3.6

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.
Files changed (33) hide show
  1. package/NOTICE +1 -1
  2. package/android/README.md +10 -0
  3. package/android/app/build.gradle.kts +23 -0
  4. package/android/app/src/main/java/com/mystral/engine/MystralActivity.java +52 -1
  5. package/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  6. package/build/web/tn-native-engine-web.mjs +2 -0
  7. package/build/web/tn-native-engine-web.wasm +0 -0
  8. package/package.json +18 -6
  9. package/scripts/bundle-native-engine.mjs +303 -0
  10. package/scripts/bundle.mjs +40 -41
  11. package/scripts/check-source-list.mjs +11 -5
  12. package/scripts/desktop-distribution.mjs +33 -5
  13. package/scripts/install-prebuilt.mjs +27 -18
  14. package/scripts/package-android.mjs +63 -5
  15. package/scripts/package-desktop.mjs +50 -13
  16. package/scripts/package-engine-desktop.mjs +102 -0
  17. package/scripts/package-ios.mjs +6 -1
  18. package/scripts/profile-production.mjs +64 -9
  19. package/scripts/verify-starter-consumer.mjs +6 -5
  20. package/scripts/verify-starter-desktop-base.mjs +30 -4
  21. package/scripts/windows-installer.mjs +12 -5
  22. package/scripts/xvfb.sh +15 -0
  23. package/src/engine/player/core-addons.mjs +15 -0
  24. package/src/engine/player/core-assets.mjs +59 -0
  25. package/src/engine/player/core-audio.mjs +11 -0
  26. package/src/engine/player/core-hdr.mjs +29 -0
  27. package/src/engine/player/core-host.mjs +148 -0
  28. package/src/engine/player/core-lut.mjs +7 -0
  29. package/src/engine/player/core-textures.mjs +167 -0
  30. package/src/engine/player/core-three.mjs +294 -0
  31. package/src/engine/player/core-tsl.mjs +80 -0
  32. package/src/engine/player/core-unused.mjs +21 -0
  33. package/src/engine/player/core-webgpu.mjs +207 -0
@@ -2,12 +2,18 @@
2
2
 
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { createHash } from 'node:crypto';
5
- import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
6
6
  import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  import { PNG } from 'pngjs';
9
9
 
10
- import { parseLinkedLibraries, resolveContainer } from './desktop-distribution.mjs';
10
+ import {
11
+ desktopLaunchTarget,
12
+ isEnginePlayerLaunch,
13
+ parseLinkedLibraries,
14
+ resolveContainer,
15
+ } from './desktop-distribution.mjs';
16
+ import { verifyStarterConsumerGameplay } from './verify-starter-consumer.mjs';
11
17
  import { inspectContainerBrand } from './inspect-container-brand.mjs';
12
18
  import { inspectMacosIcon } from './inspect-macos-icon.mjs';
13
19
 
@@ -292,6 +298,8 @@ function judgeStarterRun({ artifact, brand, frames, log, logPath, reportPath, sc
292
298
  return report;
293
299
  }
294
300
 
301
+ export { desktopLaunchTarget };
302
+
295
303
  export function verifyStarterDesktop({ frames = 300, project = process.cwd() } = {}) {
296
304
  const projectRoot = resolve(project);
297
305
  const manifest = JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8'));
@@ -306,8 +314,22 @@ export function verifyStarterDesktop({ frames = 300, project = process.cwd() } =
306
314
  const logPath = join(artifactDirectory, 'starter-desktop.log');
307
315
  const reportPath = join(artifactDirectory, 'starter-desktop-report.json');
308
316
  mkdirSync(artifactDirectory, { recursive: true });
309
- const log = launchStarterExecutable(artifact, { frames, logPath, project: projectRoot, screenshot });
310
- return judgeStarterRun({ artifact, frames, log, logPath, reportPath, screenshot });
317
+ const launch = desktopLaunchTarget(artifact, executableName);
318
+ // The engine player takes neither `--frames` nor `--screenshot` and prints none of the legacy
319
+ // host's markers, so the playtest runner drives it (PRD-637). The report keeps the same path.
320
+ if (isEnginePlayerLaunch(launch)) {
321
+ const { row } = verifyStarterConsumerGameplay({ project: projectRoot, target: 'desktop' });
322
+ const report = {
323
+ artifact: launch,
324
+ assertions: row.assertions,
325
+ gate: 'consumer-playtest',
326
+ pass: row.pass === true,
327
+ };
328
+ writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`);
329
+ return report;
330
+ }
331
+ const log = launchStarterExecutable(launch, { frames, logPath, project: projectRoot, screenshot });
332
+ return judgeStarterRun({ artifact: launch, frames, log, logPath, reportPath, screenshot });
311
333
  }
312
334
 
313
335
  /**
@@ -447,6 +469,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.ar
447
469
  process.exit(0);
448
470
  }
449
471
  const report = options.root ? verifyStarterContainer(options) : verifyStarterDesktop(options);
472
+ if (report.gate === 'consumer-playtest') {
473
+ console.log(`starter desktop gate passed: engine player, ${report.assertions} playtest assertions`);
474
+ process.exit(0);
475
+ }
450
476
  const brand = report.brand === undefined || report.brand === null
451
477
  ? 'brand NOT inspected (pass --config <resolved config json>)'
452
478
  : `brand ${report.brand.name?.name ?? 'unnamed'} verified`;
@@ -48,11 +48,18 @@ export function verifyWindowsUninstall(directory, files) {
48
48
  }
49
49
  if (!existsSync(directory)) return [];
50
50
  // Dirents let us inventory links without traversing their targets.
51
- return readdirSync(directory, { recursive: true, withFileTypes: true })
52
- .map((entry) => ({
53
- path: relative(directory, join(entry.parentPath, entry.name)).replaceAll('\\', '/'),
54
- type: entry.isSymbolicLink() ? 'link' : entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other',
55
- }))
51
+ const entries = [];
52
+ const directories = [directory];
53
+ while (directories.length) {
54
+ const current = directories.pop();
55
+ for (const entry of readdirSync(current, { withFileTypes: true })) {
56
+ const path = join(current, entry.name);
57
+ const type = entry.isSymbolicLink() ? 'link' : entry.isDirectory() ? 'directory' : entry.isFile() ? 'file' : 'other';
58
+ entries.push({ path: relative(directory, path).replaceAll('\\', '/'), type });
59
+ if (type === 'directory') directories.push(path);
60
+ }
61
+ }
62
+ return entries
56
63
  // NSIS cannot remove its own running executable in synchronous _?= mode; the verifier does.
57
64
  .filter((entry) => entry.path !== 'Uninstall.exe')
58
65
  .sort((a, b) => a.path.localeCompare(b.path));
package/scripts/xvfb.sh CHANGED
@@ -33,6 +33,17 @@ display_file="$runtime/display"
33
33
  Xvfb -displayfd 3 +extension COMPOSITE +extension SHAPE -screen 0 "$screen" -nolisten tcp 3>"$display_file" &
34
34
  xvfb_pid=$!
35
35
 
36
+ # This script hands the command an X11 server, so it is also the honest place to answer a Wayland
37
+ # request: say which display the run really uses instead of letting an X11 result pass as Wayland.
38
+ # Both spellings are set because SDL 3 reads SDL_VIDEO_DRIVER and src/platform/window.cpp also
39
+ # honours the SDL 2 spelling SDL_VIDEODRIVER.
40
+ if [ "${SDL_VIDEO_DRIVER:-${SDL_VIDEODRIVER:-}}" = "wayland" ]; then
41
+ echo "scripts/xvfb.sh: SDL_VIDEO_DRIVER/SDL_VIDEODRIVER asks for Wayland; this gate runs on the X11 display this script provides." >&2
42
+ fi
43
+ SDL_VIDEO_DRIVER=x11
44
+ SDL_VIDEODRIVER=x11
45
+ export SDL_VIDEO_DRIVER SDL_VIDEODRIVER
46
+
36
47
  compositor_pid=""
37
48
 
38
49
  cleanup() {
@@ -48,6 +59,10 @@ cleanup() {
48
59
  }
49
60
  trap cleanup EXIT INT TERM
50
61
 
62
+ # Child libraries (including PulseAudio) leave scratch directories for their caller to own.
63
+ TMPDIR="$runtime"
64
+ export TMPDIR
65
+
51
66
  # 10s was enough until a loaded two-core CI runner missed it: run 33789430714's installed-verifier
52
67
  # case reported "Xvfb did not report a display within 10 seconds" while Xvfb was still alive and
53
68
  # starting. The loop already exits the moment Xvfb dies, so a higher ceiling costs a healthy run
@@ -0,0 +1,15 @@
1
+ // three/addons/tsl/display's GTAO, Denoise, SMAA and Bloom as the engine's live effects, shared with
2
+ // the Wasm back end (three-native/src/addons/post-effects.ts). Each returns the effect's node; its
3
+ // scalar uniforms read and write the native effect (`ao(...).radius.value`).
4
+ import { unsupportedExport } from "../../../../three-native/src/refused.ts";
5
+ import { definePostEffects } from "../../../../three-native/src/addons/post-effects.ts";
6
+
7
+ export const { ao, denoise, smaa, bloom, traa, film, lut3D } = definePostEffects(globalThis.tsl);
8
+
9
+ // The other display nodes need live addon-node construction and update scheduling, which the native
10
+ // renderer lacks (it consumes cooked post graphs). They stay importable and refuse at use, by name.
11
+ export const fxaa = unsupportedExport("fxaa");
12
+ export const godrays = unsupportedExport("godrays");
13
+ export const ssgi = unsupportedExport("ssgi");
14
+ export const ssr = unsupportedExport("ssr");
15
+ export const sharpen = unsupportedExport("sharpen");
@@ -0,0 +1,59 @@
1
+ // The owned engine consumes verified TNPK entries, never browser loaders or network fallbacks.
2
+ import { audio } from "./core-audio.mjs";
3
+ export function createAssetLoader(options = {}) {
4
+ if (Object.keys(options).some((key) => !["renderer", "basePath", "manifest", "sourcePath"].includes(key)))
5
+ throw new Error("TN_NATIVE_ASSET_OPTIONS_UNSUPPORTED: this player accepts cooked package paths only");
6
+ // core's fallback for a game without a manifest: the verbatim path, then `<sourcePath>/<path>`.
7
+ const sourcePath = (options.sourcePath ?? "assets").replace(/^\/+|\/+$/g, "");
8
+ const read = (kind, path) => {
9
+ try {
10
+ return [globalThis.tn.loadAsset(kind, path), "manifest"];
11
+ } catch (error) {
12
+ if (!sourcePath || !/TN_NATIVE_ASSET_MISSING/.test(String(error?.message))) throw error;
13
+ try { return [globalThis.tn.loadAsset(kind, `${sourcePath}/${path.replace(/^\/+/, "")}`), "source"]; }
14
+ catch { throw error; }
15
+ }
16
+ };
17
+ const cache = new Map();
18
+ const pending = new Set();
19
+ const resolved = new Map();
20
+ const progress = { requested: 0, settled: 0, requestedBytes: 0, settledBytes: 0,
21
+ get pending() { return [...pending]; } };
22
+ const load = (kind, path, copy = false) => {
23
+ if (typeof path !== "string" || !path || path.includes("\0"))
24
+ return Promise.reject(new Error("TN_NATIVE_ASSET_INVALID: expected a nonempty logical path"));
25
+ const key = `${kind}:${path}`;
26
+ if (!copy && cache.has(key)) return cache.get(key);
27
+ progress.requested++;
28
+ pending.add(path);
29
+ const result = Promise.resolve().then(() => {
30
+ const [record, via] = read(kind, path);
31
+ progress.requestedBytes += record.bytes;
32
+ progress.settledBytes += record.bytes;
33
+ resolved.set(path, { url: record.url, via });
34
+ // Audio is a Buffer entry of encoded bytes; the shared context decodes it, as three's AudioLoader does.
35
+ return kind === "audio" ? audio.AudioContext.getContext().decodeAudioData(record.value) : record.value;
36
+ }).finally(() => { pending.delete(path); progress.settled++; });
37
+ if (!copy) cache.set(key, result);
38
+ result.catch(() => { if (cache.get(key) === result) cache.delete(key); });
39
+ return result;
40
+ };
41
+ return {
42
+ progress, resolved,
43
+ model: (path) => load("model", path),
44
+ async texture(path, settings) {
45
+ const value = await load("texture", path, settings !== undefined);
46
+ if (settings === undefined) return value;
47
+ if (settings.anisotropy !== undefined) value.anisotropy = settings.anisotropy;
48
+ value.colorSpace = settings.data === true ? "" : "srgb";
49
+ if (settings.wrap !== undefined) value.wrapS = value.wrapT = settings.wrap;
50
+ if (typeof settings.repeat === "number") value.repeat.setScalar(settings.repeat);
51
+ else if (settings.repeat !== undefined) value.repeat.set(...settings.repeat);
52
+ return value;
53
+ },
54
+ audio: (path) => load("audio", path),
55
+ resolve: async (path) => [resolved.get(path)?.url ?? `tnpk:${path}`],
56
+ release: (kind, path) => cache.delete(`${kind}:${path}`),
57
+ clear() { cache.clear(); resolved.clear(); },
58
+ };
59
+ }
@@ -0,0 +1,11 @@
1
+ // three's audio classes over the engine Object3D and the player's WebAudio (the legacy host's).
2
+ // The facade re-exports the classes; core-host pushes poses to WebAudio once per tick. One set per
3
+ // isolate: a game entry that imports core-host itself bundles this module twice, and a second set
4
+ // would tick voices the game never made.
5
+ import { defineAudioClasses } from "../../../../three-native/src/audio.ts";
6
+
7
+ const { Object3D, Vector3, Quaternion } = globalThis;
8
+ if (!globalThis.__tnAudio)
9
+ globalThis.__tnAudio = defineAudioClasses({ Object3D, Vector3, Quaternion,
10
+ read: async (url) => globalThis.tn.loadAsset("audio", url).value });
11
+ export const audio = globalThis.__tnAudio;
@@ -0,0 +1,29 @@
1
+ // three's HDRLoader over the cooked package: the .hdr's bytes from a Buffer entry, decoded by the
2
+ // shared RGBE parser into a native DataTexture with the settings three's DataTextureLoader applies.
3
+ import { parseHDR } from "../../../../three-native/src/addons/hdr.ts";
4
+ import { logicalPath } from "./core-textures.mjs";
5
+
6
+ const NativeDataTexture = globalThis.DataTexture;
7
+
8
+ export class HDRLoader {
9
+ constructor() {
10
+ this.type = 1016; // HalfFloatType, three's default
11
+ this.path = "";
12
+ }
13
+ setDataType(type) { this.type = type; return this; }
14
+ setPath(path) { this.path = path; return this; }
15
+ load(url, onLoad, onProgress, onError) {
16
+ const result = this.loadAsync(url);
17
+ result.then(onLoad, (error) => { if (onError) onError(error); else throw error; });
18
+ }
19
+ async loadAsync(url) {
20
+ const image = parseHDR(globalThis.tn.loadAsset("buffer", logicalPath(this.path + url)).value, this.type);
21
+ // The native constructor, not the facade's: nothing here edits the texels after the upload,
22
+ // so there is no JS-side source to re-send (8M values for a 2K sky).
23
+ const texture = new NativeDataTexture(image.data, image.width, image.height, globalThis.RGBAFormat, image.type);
24
+ Object.assign(texture, { colorSpace: globalThis.LinearSRGBColorSpace, minFilter: globalThis.LinearFilter,
25
+ magFilter: globalThis.LinearFilter, flipY: true });
26
+ texture.needsUpdate = true;
27
+ return texture;
28
+ }
29
+ }
@@ -0,0 +1,148 @@
1
+ // Browser-service compatibility for core's existing seams; time advances on native fixed ticks.
2
+ // The native marker keeps assets/physics/platform selection on the native path, even without DOM.
3
+ import { audio } from "./core-audio.mjs";
4
+ import { GAME_SPANS } from "../../../../core/src/profiling/Spans.ts";
5
+ globalThis.__THREENATIVE_NATIVE__ = { ...globalThis.__THREENATIVE_NATIVE__, platform: globalThis.tn.platform, presentMode: globalThis.tn.presentMode };
6
+ let time = 0;
7
+ let nextId = 0;
8
+ const frames = new Map();
9
+ const timers = new Map();
10
+ const listeners = new Map();
11
+ const held = new Set();
12
+
13
+ export const canvas = {
14
+ width: 1280, height: 720, clientWidth: 1280, clientHeight: 720, parentElement: null,
15
+ addEventListener(type, callback) {
16
+ if (!listeners.has(type)) listeners.set(type, new Set());
17
+ listeners.get(type).add(callback);
18
+ },
19
+ removeEventListener(type, callback) { listeners.get(type)?.delete(callback); },
20
+ };
21
+ // Pointer lock on the canvas core reads input from, as the legacy host gives it (SDL relative mouse
22
+ // mode, __tnPointerCapture): core's captureMouse/releaseMouse, with the pointerlockchange they await.
23
+ const pointerLock = (on) => {
24
+ globalThis.__tnPointerCapture(on);
25
+ for (const callback of [...(listeners.get("pointerlockchange") ?? [])]) callback({ type: "pointerlockchange" });
26
+ };
27
+ // The legacy host installs the drawing surface as a global too; a script entry (the load test) reads it there.
28
+ globalThis.canvas = canvas;
29
+ canvas.requestPointerLock = () => pointerLock(true);
30
+ canvas.exitPointerLock = () => pointerLock(false);
31
+ // A real monotonic clock, as a page has: ticks and timers keep their fixed-step time, but
32
+ // intra-frame phases and startup milestones must read real milliseconds.
33
+ globalThis.performance = { now: typeof globalThis.__tnWallMs === "function" ? globalThis.__tnWallMs : () => time };
34
+ globalThis.console = Object.fromEntries(["log", "info", "warn", "error"].map((name) => [name, (...args) => globalThis.tn.log(...args)]));
35
+ globalThis.requestAnimationFrame = (callback) => {
36
+ frames.set(++nextId, callback);
37
+ return nextId;
38
+ };
39
+ globalThis.cancelAnimationFrame = (id) => frames.delete(id);
40
+ globalThis.setTimeout = (callback, delay = 0) => {
41
+ timers.set(++nextId, { callback, due: time + delay });
42
+ return nextId;
43
+ };
44
+ globalThis.clearTimeout = (id) => timers.delete(id);
45
+ globalThis.setInterval = (callback, delay) => {
46
+ if (!Number.isFinite(delay) || delay <= 0) throw new Error("TN_CORE_TIMER: interval must be positive");
47
+ timers.set(++nextId, { callback, due: time + delay, interval: delay });
48
+ return nextId;
49
+ };
50
+ globalThis.clearInterval = globalThis.clearTimeout;
51
+
52
+ const runnerAttached = () => globalThis.TN_PLAYTEST_ENDPOINT !== undefined;
53
+ // Frame callbacks follow the presented frame, never the 60 Hz tick: one callback per drawn frame, as a page's
54
+ // requestAnimationFrame. Flushing them per catch-up tick ran core's whole frame (update, matrix walk, cull)
55
+ // up to five times per drawn frame, and each pass made the next frame later (PRD-610).
56
+ globalThis.tn.onFrame((frameMs) => {
57
+ const pending = [...frames.values()];
58
+ frames.clear();
59
+ for (const callback of pending) callback(frameMs);
60
+ });
61
+
62
+ // A person's input from the player's window (SDL through the legacy host's DOM translation), as the events
63
+ // core's listeners on the canvas read. A key also enters the held set, so the per-tick diff below does not
64
+ // raise it a second time.
65
+ globalThis.__tnDispatchInput = (event) => {
66
+ if (event.type === "keydown") held.add(event.code);
67
+ else if (event.type === "keyup") held.delete(event.code);
68
+ const dom = { ...event, isTrusted: true, target: canvas, preventDefault() {}, stopPropagation() {} };
69
+ for (const callback of [...(listeners.get(event.type) ?? [])]) callback(dom);
70
+ };
71
+
72
+ // The player has no fetch, so a run it hosts makes no request. The runner's desktop network check needs the
73
+ // `runtime.network` capability and a `network` observation from the bridge core installs: report the honest
74
+ // zero, as playtest/src/three/device.ts does for the legacy host's retained fetch failures.
75
+ {
76
+ let installed;
77
+ Object.defineProperty(globalThis, "__THREENATIVE_PLAYTEST_BRIDGE__", {
78
+ configurable: true,
79
+ get: () => installed,
80
+ set(bridge) {
81
+ if (typeof bridge?.describe === "function" && typeof bridge.sample === "function") {
82
+ const describe = bridge.describe.bind(bridge);
83
+ bridge.describe = async () => {
84
+ const description = await describe();
85
+ return { ...description, capabilities: [...description.capabilities, "runtime.network"] };
86
+ };
87
+ const sample = bridge.sample.bind(bridge);
88
+ bridge.sample = async (request) => ({ ...await sample(request), network: { entries: [], requests: 0 } });
89
+ }
90
+ installed = bridge;
91
+ },
92
+ });
93
+ }
94
+
95
+ globalThis.tn.onUpdate((dt) => {
96
+ time += dt * 1000;
97
+ // Every held key by code (KeyW, ArrowUp), as keydown/keyup events with the DOM key beside the code.
98
+ const now = new Set(globalThis.__tnHeldCodes());
99
+ const send = (type, code) => {
100
+ const key = /^Key[A-Z]$/.test(code) ? code[3].toLowerCase() : code;
101
+ for (const callback of listeners.get(type) ?? []) callback({ code, key });
102
+ };
103
+ for (const code of now) if (!held.has(code)) { held.add(code); send("keydown", code); }
104
+ for (const code of [...held]) if (!now.has(code)) { held.delete(code); send("keyup", code); }
105
+ for (const [id, timer] of timers) {
106
+ if (timer.due > time) continue;
107
+ if (timer.interval === undefined) timers.delete(id);
108
+ else timer.due += timer.interval;
109
+ timer.callback();
110
+ }
111
+ // Under a playtest runner core freezes its loop, so ticks are the only clock: the legacy host's
112
+ // mailbox advance calls the bridge's fixed step, and here each native tick is that advance. The
113
+ // frame callbacks then run once per presented frame on its frame clock (tn.onFrame below), so a
114
+ // render sample is a real frame time: tick time never satisfies minFps or p95 (owner, 2026-10-08).
115
+ if (runnerAttached()) {
116
+ const bridge = globalThis.__THREENATIVE_PLAYTEST_BRIDGE__;
117
+ if (typeof bridge?.advance === "function") {
118
+ globalThis.__tnGameSpan?.(GAME_SPANS.playtest, 0);
119
+ try { void bridge.advance(1, { render: false }); } finally { globalThis.__tnGameSpan?.(GAME_SPANS.playtest, 1); }
120
+ }
121
+ }
122
+ audio.updateAudio();
123
+ });
124
+
125
+ const readSize = () => ({ width: canvas.width, height: canvas.height, aspect: canvas.width / canvas.height });
126
+ export const platform = {
127
+ input: () => [],
128
+ inputTarget: canvas,
129
+ renderer: { createCanvas: () => canvas, hasWebGPU: () => true, readSize: () => [1280, 720], observeResize: () => () => {} },
130
+ viewport: { readSize, observeResize: () => () => {} },
131
+ mountCanvas() {},
132
+ unmountCanvas() {},
133
+ };
134
+
135
+ if (globalThis.__tnGameSpan !== undefined) {
136
+ const calls = 100_000;
137
+ for (let warm = 0; warm < 10_000; warm++) globalThis.__tnGameSpan(-3, 0);
138
+ for (let batch = 0; batch < 3; batch++) {
139
+ let checksum = 0;
140
+ const emptyStart = globalThis.__tnGameSpan(-2, 0);
141
+ for (let i = 0; i < calls; i++) checksum += i & 1;
142
+ const emptyMs = globalThis.__tnGameSpan(-2, 0) - emptyStart;
143
+ const start = globalThis.__tnGameSpan(-2, 0);
144
+ for (let i = 0; i < calls; i++) { globalThis.__tnGameSpan(-3, 0); checksum += i & 1; }
145
+ const ms = globalThis.__tnGameSpan(-2, 0) - start;
146
+ console.log(`TN_GAME_FFI:${JSON.stringify({ calls, ms, emptyMs, netNs: (ms - emptyMs) * 1e6 / calls, checksum })}`);
147
+ }
148
+ }
@@ -0,0 +1,7 @@
1
+ import { defineLUTCubeLoader } from "../../../../three-native/src/addons/lut-cube-loader.ts";
2
+ import { Data3DTexture, logicalPath } from "./core-textures.mjs";
3
+
4
+ export const LUTCubeLoader = defineLUTCubeLoader({ textureClass: Data3DTexture, vectorClass: globalThis.Vector3 }, async (url) => {
5
+ const bytes = globalThis.tn.loadAsset("buffer", logicalPath(url)).value;
6
+ return decodeURIComponent(Array.from(new Uint8Array(bytes), (byte) => `%${byte.toString(16).padStart(2, "0")}`).join(""));
7
+ });
@@ -0,0 +1,167 @@
1
+ // three's texture sources over the V8 adapter: the typed array a DataTexture was built from, a 2D
2
+ // canvas, and an ImageBitmap from the cooked package. The engine keeps a copy of the texels, so the
3
+ // JS-side source is re-sent on `needsUpdate`, as three re-reads `texture.image` before an upload.
4
+ import { DataUtils } from "../../../../three-native/src/addons/data-utils.ts";
5
+
6
+ export { DataUtils };
7
+ export const HalfFloatType = 1016;
8
+
9
+ const NativeTexture = globalThis.Texture;
10
+ const NativeDataTexture = globalThis.DataTexture;
11
+ const NativeVolumeTexture = globalThis.Data3DTexture;
12
+ const NativeCanvasTexture = globalThis.CanvasTexture;
13
+ const sources = new WeakMap();
14
+ const bitmaps = new WeakMap();
15
+ const nativeFlipY = Object.getOwnPropertyDescriptor(NativeTexture.prototype, "flipY").set;
16
+
17
+ /** The package entry a URL names: `tnpk:<path>` and `<package>#<path>` from `assets.resolve`, or the path. */
18
+ export function logicalPath(url) {
19
+ if (typeof url !== "string" || !url) throw new Error("TN_NATIVE_ASSET_INVALID: expected a nonempty URL");
20
+ if (url.startsWith("tnpk:")) return url.slice(5);
21
+ const hash = url.indexOf("#");
22
+ return hash < 0 ? url : url.slice(hash + 1);
23
+ }
24
+
25
+ /** A canvas-like image's RGBA pixels, read through the standard 2D API. */
26
+ function canvasPixels(canvas) {
27
+ const pixels = canvas?.getContext?.("2d")?.getImageData?.(0, 0, canvas.width, canvas.height)?.data;
28
+ if (!pixels) throw new Error("TN_NATIVE_CANVAS_TEXTURE_SOURCE: expected a canvas whose 2D context answers getImageData");
29
+ return pixels;
30
+ }
31
+
32
+ // `image` is the JS source; `needsUpdate` re-sends its texels, as three re-reads `texture.image`.
33
+ for (const Native of [NativeDataTexture, NativeCanvasTexture, NativeVolumeTexture]) {
34
+ const nativeImage = Object.getOwnPropertyDescriptor(Native.prototype, "image").get;
35
+ const nativeNeedsUpdate = Object.getOwnPropertyDescriptor(Native.prototype, "needsUpdate").set;
36
+ Object.defineProperties(Native.prototype, {
37
+ image: {
38
+ configurable: true,
39
+ get() { return sources.get(this) ?? nativeImage.call(this); },
40
+ set(image) { sources.set(this, image); },
41
+ },
42
+ needsUpdate: {
43
+ configurable: true,
44
+ set(value) {
45
+ const image = value ? sources.get(this) : undefined;
46
+ if (image) nativeImage.call(this).data = image.getContext ? canvasPixels(image) : image.data;
47
+ nativeNeedsUpdate.call(this, value);
48
+ },
49
+ },
50
+ });
51
+ }
52
+
53
+ export function DataTexture(data = null, width = 1, height = 1, ...rest) {
54
+ const texture = Reflect.construct(NativeDataTexture, [data ?? undefined, width, height, ...rest], new.target ?? DataTexture);
55
+ if (data) sources.set(texture, { data, width, height });
56
+ return texture;
57
+ }
58
+ DataTexture.prototype = NativeDataTexture.prototype;
59
+ // The adapter finds the engine class a subclass constructs by walking new.target's prototype chain.
60
+ Object.setPrototypeOf(DataTexture, NativeDataTexture);
61
+
62
+ export function Data3DTexture(data = null, width = 1, height = 1, depth = 1) {
63
+ const texture = Reflect.construct(NativeVolumeTexture, [data ?? undefined, width, height, depth], new.target ?? Data3DTexture);
64
+ if (data) sources.set(texture, { data, width, height, depth });
65
+ return texture;
66
+ }
67
+ Data3DTexture.prototype = NativeVolumeTexture.prototype;
68
+ Object.setPrototypeOf(Data3DTexture, NativeVolumeTexture);
69
+
70
+ // three's CanvasTexture: the engine's own class over the canvas's pixels, with a full mip chain.
71
+ export function CanvasTexture(canvas, ...rest) {
72
+ const texture = Reflect.construct(NativeCanvasTexture, [canvasPixels(canvas), canvas.width, canvas.height, ...rest],
73
+ new.target ?? CanvasTexture);
74
+ sources.set(texture, canvas);
75
+ return texture;
76
+ }
77
+ CanvasTexture.prototype = NativeCanvasTexture.prototype;
78
+ Object.setPrototypeOf(CanvasTexture, NativeCanvasTexture);
79
+ if (!Object.hasOwn(CanvasTexture.prototype, "isCanvasTexture")) CanvasTexture.prototype.isCanvasTexture = true;
80
+
81
+ /** `new Texture(bitmap)` adopts an ImageBitmapLoader result; any other image has no native source. */
82
+ export function Texture(image, ...rest) {
83
+ if (image === undefined || image === null) return Reflect.construct(NativeTexture, rest, new.target ?? Texture);
84
+ const bitmap = bitmaps.get(image);
85
+ if (!bitmap) throw new Error("TN_NATIVE_TEXTURE_IMAGE_UNSUPPORTED: a native Texture takes an ImageBitmapLoader result or no image");
86
+ if (bitmap.texture === undefined)
87
+ throw new Error("TN_NATIVE_IMAGE_BITMAP_CLOSED: this ImageBitmap was closed or already adopted by a Texture");
88
+ const { texture, flipped } = bitmap;
89
+ bitmap.texture = undefined;
90
+ // A bitmap decoded with imageOrientation "flipY" is stored upside down; three's WebGPU upload
91
+ // then applies texture.flipY on top, so the engine flips when exactly one of the two asks.
92
+ let flipY = texture.flipY;
93
+ Object.defineProperty(texture, "flipY", {
94
+ configurable: true,
95
+ get() { return flipY; },
96
+ set(value) { flipY = Boolean(value); nativeFlipY.call(texture, flipY !== flipped); },
97
+ });
98
+ texture.flipY = flipY;
99
+ return texture;
100
+ }
101
+ Texture.prototype = NativeTexture.prototype;
102
+ Object.setPrototypeOf(Texture, NativeTexture);
103
+
104
+ /** An ImageBitmap whose pixels are a native Texture, adopted once by `new Texture(bitmap)`. */
105
+ function imageBitmap(texture, options = {}, width = undefined, height = undefined) {
106
+ if (options.premultiplyAlpha === "premultiply")
107
+ throw new Error("TN_NATIVE_IMAGE_BITMAP_OPTION: premultiplyAlpha \"premultiply\" is unsupported; the engine keeps straight alpha");
108
+ for (const option of ["resizeWidth", "resizeHeight", "resizeQuality"])
109
+ if (options[option] !== undefined) throw new Error(`TN_NATIVE_IMAGE_BITMAP_OPTION: ${option} is unsupported`);
110
+ const bitmap = { width, height, close() { bitmaps.get(bitmap).texture = undefined; } };
111
+ bitmaps.set(bitmap, { texture, flipped: options.imageOrientation === "flipY" });
112
+ return bitmap;
113
+ }
114
+
115
+ /**
116
+ * The browser's createImageBitmap for encoded PNG or JPEG bytes (a Blob, an ArrayBuffer or a typed
117
+ * array), decoded by the engine's image decoder. Installed only when the player has that decoder.
118
+ */
119
+ export async function createImageBitmap(source, ...rest) {
120
+ if (rest.length > 1) throw new Error("TN_NATIVE_IMAGE_BITMAP_CROP: a source rectangle is unsupported");
121
+ const bytes = typeof source?.arrayBuffer === "function" ? await source.arrayBuffer() : source;
122
+ if (!(bytes instanceof ArrayBuffer) && !ArrayBuffer.isView(bytes))
123
+ throw new TypeError("TN_NATIVE_IMAGE_BITMAP_SOURCE: expected a Blob, an ArrayBuffer or a typed array of PNG or JPEG bytes");
124
+ const { texture, width, height } = globalThis.tn.decodeImage(bytes);
125
+ return imageBitmap(texture, rest[0], width, height);
126
+ }
127
+ if (typeof globalThis.tn?.decodeImage === "function") globalThis.createImageBitmap = createImageBitmap;
128
+
129
+ /** three's ImageBitmapLoader over the cooked package: the bitmap is the package's decoded texture. */
130
+ export class ImageBitmapLoader {
131
+ constructor() {
132
+ this.options = { premultiplyAlpha: "none" };
133
+ this.path = "";
134
+ }
135
+ setOptions(options) { this.options = options; return this; }
136
+ setPath(path) { this.path = path; return this; }
137
+ load(url, onLoad, onProgress, onError) {
138
+ this.loadAsync(url).then(onLoad, (error) => { if (onError) onError(error); else throw error; });
139
+ }
140
+ async loadAsync(url) {
141
+ return imageBitmap(globalThis.tn.loadAsset("texture", logicalPath(this.path + url)).value, this.options);
142
+ }
143
+ }
144
+
145
+ /**
146
+ * three's TextureLoader over the cooked package. The package texture is already decoded, so `load`
147
+ * returns it at once (upright, flipY true, as three's <img> path) and calls onLoad a microtask later.
148
+ */
149
+ export class TextureLoader {
150
+ constructor() { this.path = ""; }
151
+ setPath(path) { this.path = path; return this; }
152
+ setCrossOrigin() { return this; }
153
+ load(url, onLoad, onProgress, onError) {
154
+ let texture;
155
+ try {
156
+ texture = globalThis.tn.loadAsset("texture", logicalPath(this.path + url)).value;
157
+ } catch (error) {
158
+ Promise.resolve().then(() => { if (onError) onError(error); else throw error; });
159
+ return new NativeTexture();
160
+ }
161
+ if (onLoad) Promise.resolve().then(() => onLoad(texture));
162
+ return texture;
163
+ }
164
+ loadAsync(url) {
165
+ return new Promise((resolve, reject) => this.load(url, resolve, undefined, reject));
166
+ }
167
+ }