@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.
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # @threenative/runtime-native
2
+
3
+ ## What it is
4
+
5
+ `@threenative/runtime-native` is the optional ThreeNative host for running the same portable game
6
+ entry on desktop, Android, and iOS. Native compilation is opt-in: installing this package does
7
+ not require CMake, an NDK, or Xcode. It is a host, not a second renderer or scene API; upstream
8
+ Three.js and the game's `src/game.ts` remain the portable runtime contract.
9
+
10
+ ## Install
11
+
12
+ Add the optional native host when you want native builds:
13
+
14
+ ```sh
15
+ pnpm add @threenative/runtime-native
16
+ ```
17
+
18
+ ## Example
19
+
20
+ The `minimal` template ships the native build command:
21
+
22
+ ```sh
23
+ pnpm create threenative my-game --template minimal
24
+ cd my-game
25
+ pnpm install
26
+ pnpm build:desktop
27
+ ```
28
+
29
+ The template's `threenative.config.ts` uses `nativeEntry: "src/game.ts"`; native builds read that
30
+ portable entry and bundle it as the game's single native module.
31
+
32
+ ## Where the native binaries come from
33
+
34
+ An installed copy of this package contains no C++ and no build system. `build --target android`
35
+ therefore downloads prebuilt artifacts for the version you installed, listed in the release's
36
+ `prebuilt-lock.json`, and verifies each one against the SHA-256 the manifest records. Only an
37
+ Android SDK and a JDK are needed; no NDK, no CMake, and nothing is compiled on your machine.
38
+
39
+ Two environment variables change where those artifacts come from.
40
+
41
+ ### `THREENATIVE_PREBUILT_MANIFEST`
42
+
43
+ Points at a local `prebuilt-lock.json` instead of the release URL. Use it to build against
44
+ artifacts you already have, or offline. Checksums are still verified, and a manifest missing an
45
+ asset still fails by name — it redirects the lookup, it does not relax it.
46
+
47
+ ### `THREENATIVE_RUNTIME_SOURCE` — needs a full engine checkout, not an installed package
48
+
49
+ Points the packager at a **source checkout** of `packages/runtime-native` from the ThreeNative
50
+ repository, so it compiles rather than downloading. It cannot be pointed at an installed copy of
51
+ this package, and pointing it at one will not work: the packager only takes the source path when it
52
+ finds both `CMakeLists.txt` and a staged `third_party/sdl3-android/SDL3-3.2.8.aar`, and a published
53
+ tarball ships neither. The `third_party/` tree is populated by `node scripts/download-deps.mjs`
54
+ inside that checkout.
55
+
56
+ If you have no engine checkout, the prebuilt path above is your path — `THREENATIVE_RUNTIME_SOURCE`
57
+ is not a way around a failing download.
58
+
59
+ ## Links
60
+
61
+ - [Repository](https://github.com/ThreeNativeHQ/threenative)
62
+ - [MIT License](https://github.com/ThreeNativeHQ/threenative/blob/main/LICENSE)
63
+ - Start a project with `pnpm create threenative my-game`.
package/android/README.md CHANGED
@@ -1,11 +1,11 @@
1
- # Mystral Native - Android Build
1
+ # ThreeNative Runtime — Android Build
2
2
 
3
3
  ## Prerequisites
4
4
 
5
5
  1. **Android Studio** (or command-line SDK tools)
6
6
  2. **Android NDK** r25 or later
7
7
  3. **CMake** 3.22.1+
8
- 4. **Mystral dependencies** downloaded
8
+ 4. **ThreeNative runtime dependencies** downloaded
9
9
 
10
10
  ## Download Dependencies
11
11
 
@@ -7,32 +7,83 @@ plugins {
7
7
 
8
8
  val runtimeRoot = layout.projectDirectory.dir("../..")
9
9
  val prebuiltRoot = layout.projectDirectory.dir("../prebuilt")
10
- val prebuiltFiles = listOf(
11
- prebuiltRoot.file("SDL3-3.2.8.aar"),
10
+
11
+ // The engine, read before anything else, because the prebuilt contract depends on it.
12
+ // V8 is the Android default as of 2026-08-16 (PRD-130) on PRD-118's measurement: 115.64 ms of
13
+ // script per frame under QuickJS against 5.25 ms under V8. `-PthreenativeJsEngine=quickjs` is the
14
+ // documented rollback — keep it working, it is the escape if a device or ABI does not tolerate V8,
15
+ // and a rollback nobody runs is not a rollback.
16
+ val nativeJsEngineName = providers.gradleProperty("threenativeJsEngine").orElse("v8").get().lowercase()
17
+ if (nativeJsEngineName != "quickjs" && nativeJsEngineName != "v8") {
18
+ throw GradleException("-PthreenativeJsEngine must be quickjs or v8, got '$nativeJsEngineName'")
19
+ }
20
+
21
+ // What a prebuilt (no-NDK) build needs, per engine. Until 2026-08-16 this listed five files, none of
22
+ // them V8, so `android/prebuilt/` could not express a V8 build at all and a project assembled from a
23
+ // release artifact got QuickJS whatever the default said. The V8 runtime binary is a different file,
24
+ // not the same one plus a library: QuickJS is compiled into the runtime and V8 is not.
25
+ val prebuiltEngineFiles = if (nativeJsEngineName == "v8") listOf(
26
+ prebuiltRoot.file("jniLibs/arm64-v8a/libv8android.so"),
27
+ prebuiltRoot.file("jniLibs/arm64-v8a/libc++_shared.so"),
28
+ prebuiltRoot.file("assets/v8/arm64-v8a/snapshot_blob.bin"),
29
+ prebuiltRoot.file("jniLibs/x86_64/libv8android.so"),
30
+ prebuiltRoot.file("jniLibs/x86_64/libc++_shared.so"),
31
+ prebuiltRoot.file("assets/v8/x86_64/snapshot_blob.bin"),
32
+ ) else emptyList()
33
+
34
+ // The SDL3 AAR is found by name rather than named by hand. Its version was written out in four
35
+ // separate places, and the bump to 3.2.30 — for 16 KB page alignment on Android 15 — left this one
36
+ // pointing at an archive that no longer existed, which surfaced as a Gradle input-file error three
37
+ // layers away from the pin it disagreed with.
38
+ fun sdl3AarIn(directory: java.io.File): java.io.File? =
39
+ directory.listFiles { file -> file.name.startsWith("SDL3-") && file.name.endsWith(".aar") }
40
+ ?.sortedBy { it.name }
41
+ ?.lastOrNull()
42
+
43
+ val prebuiltSdl3Aar = sdl3AarIn(prebuiltRoot.asFile)
44
+ val sourceSdl3Aar = sdl3AarIn(runtimeRoot.file("third_party/sdl3-android").asFile)
45
+
46
+ val prebuiltFiles = listOfNotNull(
47
+ prebuiltSdl3Aar?.let { prebuiltRoot.file(it.name) },
12
48
  prebuiltRoot.file("jniLibs/arm64-v8a/libSDL3.so"),
13
49
  prebuiltRoot.file("jniLibs/arm64-v8a/libmystral-runtime.so"),
14
50
  prebuiltRoot.file("jniLibs/x86_64/libSDL3.so"),
15
51
  prebuiltRoot.file("jniLibs/x86_64/libmystral-runtime.so")
16
- )
52
+ ) + prebuiltEngineFiles
53
+
17
54
  val prebuiltCount = prebuiltFiles.count { it.asFile.isFile }
18
55
  if (prebuiltCount != 0 && prebuiltCount != prebuiltFiles.size) {
19
- throw GradleException("Android prebuilt runtime is incomplete: $prebuiltCount/${prebuiltFiles.size} files")
56
+ // Naming the engine matters: the most likely way to land here is a prebuilt directory populated
57
+ // for one engine while the build asks for the other, and "incomplete" alone sends the reader
58
+ // looking for a corrupted download instead of a mismatched engine.
59
+ val missing = prebuiltFiles.filter { !it.asFile.isFile }.joinToString(", ") { it.asFile.name }
60
+ throw GradleException(
61
+ "Android prebuilt runtime is incomplete for engine '$nativeJsEngineName': " +
62
+ "$prebuiltCount/${prebuiltFiles.size} files. Missing: $missing. " +
63
+ "Populate android/prebuilt/ for this engine, or build with -PthreenativeJsEngine to match what is there.",
64
+ )
20
65
  }
21
66
  val usePrebuiltRuntime = prebuiltCount == prebuiltFiles.size
22
67
  if (!usePrebuiltRuntime && !runtimeRoot.file("CMakeLists.txt").asFile.isFile) {
23
68
  throw GradleException("Android prebuilt runtime is missing and source compilation is unavailable")
24
69
  }
25
- val sdl3Aar = if (usePrebuiltRuntime) prebuiltRoot.file("SDL3-3.2.8.aar")
26
- else runtimeRoot.file("third_party/sdl3-android/SDL3-3.2.8.aar")
70
+ val sdl3Aar = if (usePrebuiltRuntime) prebuiltRoot.file(prebuiltSdl3Aar!!.name)
71
+ else runtimeRoot.file("third_party/sdl3-android/${sourceSdl3Aar?.name ?: "SDL3.aar"}")
27
72
  val extractedSdl3JniLibs = layout.buildDirectory.dir("generated/sdl3-jniLibs")
28
73
  val generatedThreeNativeAssets = layout.buildDirectory.dir("generated/threenative/assets")
29
74
  val nativeVsync = providers.gradleProperty("threenativeVsync").orElse("true")
75
+ val uploadStaging = providers.gradleProperty("threenativeUploadStaging").orElse("true")
76
+ val frameLatency = providers.gradleProperty("threenativeFrameLatency").orElse("0")
77
+ val gpuDrainProfile = providers.gradleProperty("threenativeGpuDrainProfile").orElse("false")
30
78
  val nativeJsProfile = providers.gradleProperty("threenativeJsProfile").orElse("false")
31
79
  val nativeJsProfileBusyLoop = providers.gradleProperty("threenativeJsProfileBusyLoop").orElse("false")
32
- // QuickJS stays the default. It is the only JIT-less engine ThreeNative ships on any platform, and
33
- // the phone is where that costs the most (PRD-118), so the alternative has to be reachable without
34
- // editing this file. `-PthreenativeJsEngine=v8` needs third_party/v8-android present.
35
- val nativeJsEngine = providers.gradleProperty("threenativeJsEngine").orElse("quickjs")
80
+ // V8 is the Android default, decided by the product owner on 2026-08-16 (PRD-130) on PRD-118's
81
+ // measurement: 115.64 ms of script per frame under QuickJS against 5.25 ms under V8. It needs
82
+ // third_party/v8-android, which `scripts/download-deps.mjs --android` now provisions.
83
+ //
84
+ // `-PthreenativeJsEngine=quickjs` is the documented rollback. Keep it working: it is the escape if
85
+ // a device or an ABI turns out not to tolerate V8, and a rollback nobody runs is not a rollback.
86
+ val nativeJsEngine = providers.provider { nativeJsEngineName }
36
87
 
37
88
  fun Provider<String>.asCmakeBoolean(propertyName: String): String = map { value ->
38
89
  when (value.lowercase()) {
@@ -42,30 +93,75 @@ fun Provider<String>.asCmakeBoolean(propertyName: String): String = map { value
42
93
  }
43
94
  }.get()
44
95
 
96
+ // Every ABI this APK targets. `copyV8Snapshot` and `abiFilters` both read this list, so the set of
97
+ // slices shipped and the set of snapshots staged cannot drift apart — which is the defect this
98
+ // single declaration exists to make impossible. `-PthreenativeAbis=arm64-v8a` builds one slice,
99
+ // which is how a device measurement loop halves its native compile and install time.
100
+ val supportedThreeNativeAbis = setOf("arm64-v8a", "x86_64")
101
+ val threeNativeAbis = providers.gradleProperty("threenativeAbis")
102
+ .orElse("arm64-v8a,x86_64")
103
+ .map { value -> value.split(',').map(String::trim).filter(String::isNotEmpty).distinct() }
104
+ .get()
105
+ if (threeNativeAbis.isEmpty() || threeNativeAbis.any { it !in supportedThreeNativeAbis }) {
106
+ throw GradleException(
107
+ "-PthreenativeAbis must name arm64-v8a and/or x86_64, received: ${threeNativeAbis.joinToString()}"
108
+ )
109
+ }
110
+
111
+ // Per-ABI APKs instead of one universal APK. Opt-in: see the `splits` block below.
112
+ val threeNativeAbiSplits =
113
+ providers.gradleProperty("threenativeAbiSplits").orElse("false").get().toBoolean()
114
+
45
115
  // V8 on Android keeps its startup snapshot outside the library, so the APK has to carry it and the
46
116
  // runtime reads it back at launch. QuickJS builds have no snapshot and skip this entirely.
117
+ //
118
+ // The snapshot is per-ABI and so is the staging. Until 2026-08-16 this copied arm64's snapshot to a
119
+ // single `v8/snapshot_blob.bin` while `abiFilters` shipped x86_64 as well, so the emulator slice
120
+ // carried an arm64 snapshot. Nothing caught it because every V8 run had been on the phone.
121
+ //
122
+ // **That mismatch did not crash anything, and the control proving so is recorded** — an x86_64
123
+ // emulator handed arm64's snapshot still reported `JS engine created: V8` and ran 300 frames
124
+ // (`docs/verification/prd-130-phase-1-2026-08-16.md`). V8 tolerates a blob whose checksum does not
125
+ // match, silently. So this is correctness of what ships, not a fix for a reproduced failure: the two
126
+ // blobs differ in 44,884 of 45,420 bytes, and shipping one ABI the other's bytes is wrong whether or
127
+ // not this V8 build happens to survive it. Do not restate it as a crash fix.
47
128
  tasks.register("copyV8Snapshot") {
48
129
  val engine = nativeJsEngine.get().lowercase()
49
- val source = runtimeRoot.file("third_party/v8-android/snapshot_blob/arm64-v8a/snapshot_blob.bin")
50
- val target = generatedThreeNativeAssets.map { it.file("v8/snapshot_blob.bin") }
130
+ // A prebuilt (no-NDK) build has no `third_party/`; its snapshots arrive in the prebuilt
131
+ // directory beside the libraries. Same file, two provenances, one staging path.
132
+ val sources = threeNativeAbis.associateWith { abi ->
133
+ if (usePrebuiltRuntime) prebuiltRoot.file("assets/v8/$abi/snapshot_blob.bin")
134
+ else runtimeRoot.file("third_party/v8-android/snapshot_blob/$abi/snapshot_blob.bin")
135
+ }
136
+ val targets = threeNativeAbis.associateWith { abi ->
137
+ generatedThreeNativeAssets.map { it.file("v8/$abi/snapshot_blob.bin") }
138
+ }
51
139
  // Declaring only the output made Gradle skip this whenever the file happened to survive from an
52
140
  // earlier build, and an APK then shipped `libv8android.so` with no snapshot beside it — it
53
141
  // installs, launches, and dies with "V8 startup snapshot asset is missing". The engine choice is
54
142
  // the real input, so switching engines has to invalidate the copy.
55
143
  inputs.property("threenativeJsEngine", engine)
56
- if (engine == "v8") inputs.file(source)
57
- outputs.file(target)
144
+ inputs.property("threenativeAbis", threeNativeAbis)
145
+ if (engine == "v8") sources.values.forEach { inputs.file(it) }
146
+ targets.values.forEach { outputs.file(it) }
58
147
  doLast {
59
- val out = target.get().asFile
60
- out.parentFile.mkdirs()
61
- if (engine == "v8") {
62
- val input = source.asFile
63
- if (!input.isFile) {
64
- throw GradleException("V8 startup snapshot is missing: ${'$'}{input.absolutePath}")
148
+ for (abi in threeNativeAbis) {
149
+ val out = targets.getValue(abi).get().asFile
150
+ out.parentFile.mkdirs()
151
+ if (engine == "v8") {
152
+ val input = sources.getValue(abi).asFile
153
+ // Shipping an ABI with no snapshot is a build failure, never a runtime surprise:
154
+ // the APK would install and launch on that ABI and die inside V8::Initialize.
155
+ if (!input.isFile) {
156
+ throw GradleException(
157
+ "V8 startup snapshot is missing for ABI '$abi': ${'$'}{input.absolutePath}. " +
158
+ "Every ABI in abiFilters must have one, or that slice cannot start.",
159
+ )
160
+ }
161
+ input.copyTo(out, overwrite = true)
162
+ } else if (out.exists()) {
163
+ out.delete()
65
164
  }
66
- input.copyTo(out, overwrite = true)
67
- } else if (out.exists()) {
68
- out.delete()
69
165
  }
70
166
  }
71
167
  }
@@ -179,6 +275,12 @@ tasks.named("preBuild") {
179
275
 
180
276
  dependencies {
181
277
  if (usePrebuiltRuntime) implementation(files(sdl3Aar))
278
+ // `androidx.webkit` is what makes the UI layer's two open questions closed ones:
279
+ // `WebViewAssetLoader` serves the UI bundle from an HTTPS-like origin instead of `file://`,
280
+ // so `fetch` and module imports behave as they do on web, and `addWebMessageListener` gives
281
+ // the bridge an origin-scoped, `MessagePort`-shaped channel rather than
282
+ // `addJavascriptInterface` plus `evaluateJavascript` string-slinging.
283
+ implementation("androidx.webkit:webkit:1.12.1")
182
284
  }
183
285
 
184
286
  android {
@@ -197,7 +299,14 @@ android {
197
299
  // Target modern 64-bit architectures
198
300
  // arm64-v8a: Most Android devices (ARM64)
199
301
  // x86_64: Android emulator on Intel/AMD
200
- abiFilters.addAll(listOf("arm64-v8a", "x86_64"))
302
+ //
303
+ // Declared once, at the top of this file, because `copyV8Snapshot` stages one V8
304
+ // snapshot per entry. Adding an ABI here without a snapshot for it now fails the build
305
+ // rather than shipping a slice that dies inside V8::Initialize.
306
+ //
307
+ // AGP refuses `abiFilters` and `splits.abi` together, so the split build leaves this
308
+ // empty and the `splits` block below carries the same list.
309
+ if (!threeNativeAbiSplits) abiFilters.addAll(threeNativeAbis)
201
310
  }
202
311
 
203
312
  if (!usePrebuiltRuntime) externalNativeBuild {
@@ -223,6 +332,9 @@ android {
223
332
  "-DTN_ENABLE_DEBUG_SERVER=OFF",
224
333
  "-DTN_ENABLE_NATIVE_PHYSICS=ON",
225
334
  "-DTN_ANDROID_VSYNC=${nativeVsync.asCmakeBoolean("PthreenativeVsync")}",
335
+ "-DTN_WEBGPU_UPLOAD_STAGING=${uploadStaging.asCmakeBoolean("PthreenativeUploadStaging")}",
336
+ "-DTN_WEBGPU_DESIRED_FRAME_LATENCY=${frameLatency.get()}",
337
+ "-DTN_WEBGPU_GPU_DRAIN_PROFILE=${gpuDrainProfile.asCmakeBoolean("PthreenativeGpuDrainProfile")}",
226
338
  "-DTN_ANDROID_JS_PROFILE=${nativeJsProfile.asCmakeBoolean("PthreenativeJsProfile")}",
227
339
  "-DTN_ANDROID_JS_PROFILE_BUSY_LOOP=${nativeJsProfileBusyLoop.asCmakeBoolean("PthreenativeJsProfileBusyLoop")}",
228
340
  )
@@ -236,6 +348,26 @@ android {
236
348
  }
237
349
  }
238
350
 
351
+ // Per-ABI APKs, off by default.
352
+ //
353
+ // Every APK this repository built until 2026-08-16 was universal: it carried arm64-v8a and
354
+ // x86_64 together, so its size answered no question anyone has. "How many extra megabytes does
355
+ // an arm64 phone download to get V8" was answered by summing uncompressed native libraries
356
+ // instead, which is a different number from an artifact's size and was the only figure on
357
+ // record when the engine default was decided.
358
+ //
359
+ // `-PthreenativeAbiSplits=true` produces one APK per ABI so that number can be read off a file.
360
+ // It stays opt-in because every device gate here installs by path and a split build changes
361
+ // which paths exist.
362
+ splits {
363
+ abi {
364
+ isEnable = threeNativeAbiSplits
365
+ reset()
366
+ include(*threeNativeAbis.toTypedArray())
367
+ isUniversalApk = false
368
+ }
369
+ }
370
+
239
371
  buildTypes {
240
372
  debug {
241
373
  // AGP pins the debug variant's native build to CMAKE_BUILD_TYPE=Debug and ignores
@@ -273,7 +405,16 @@ android {
273
405
  // Compile the vendored SDL Java glue so ThreeNative can request a
274
406
  // larger SDLThread stack while retaining the official SDL native libs.
275
407
  if (!usePrebuiltRuntime) {
276
- java.srcDir("../../third_party/sdl3/SDL3-3.2.8/android-project/app/src/main/java")
408
+ // Located rather than named, for the same reason as the AAR above: CMake already
409
+ // globs this directory, so a version bump used to move the native build and leave
410
+ // the Java source root pointing at a directory that no longer existed.
411
+ java.srcDir(
412
+ (rootProject.file("../third_party/sdl3").listFiles { file ->
413
+ file.isDirectory && file.name.startsWith("SDL3-")
414
+ }?.sortedBy { it.name }?.lastOrNull()
415
+ ?.resolve("android-project/app/src/main/java")
416
+ ?: rootProject.file("../third_party/sdl3/missing-sdl3-source"))
417
+ )
277
418
  }
278
419
  // SDLActivity loads libSDL3.so before libmystral-runtime.so. The SDL3 AAR
279
420
  // stores native libs under prefab/, so extract and package both official
@@ -283,10 +424,6 @@ android {
283
424
  }
284
425
  }
285
426
 
286
- packaging {
287
- jniLibs.keepDebugSymbols.add("**/*.so")
288
- }
289
-
290
427
  compileOptions {
291
428
  sourceCompatibility = JavaVersion.VERSION_1_8
292
429
  targetCompatibility = JavaVersion.VERSION_1_8
@@ -25,11 +25,18 @@
25
25
  android:supportsRtl="true"
26
26
  android:theme="@style/Theme.ThreeNative"
27
27
  android:hasCode="true">
28
+ <!-- package-android.mjs writes the project adaptive launcher icon here. -->
28
29
 
29
30
  <!-- Main SDL Activity -->
31
+ <!-- configChanges must cover every axis a mid-play environment change can hit. An
32
+ uncovered axis recreates the activity in-process, and SDL then exits the whole
33
+ process (nativeAllowRecreateActivity defaults false and is deliberately left
34
+ unhinted — PRD-222 Phase 1), so the player's return from split-screen or a
35
+ font-scale change replays the entire loading sequence. smallestScreenSize covers
36
+ split-screen/freeform entry; the rest cover user-facing display settings. -->
30
37
  <activity
31
38
  android:name="com.threenative.runtime.MystralActivity"
32
- android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|navigation|uiMode|density"
39
+ android:configChanges="keyboard|keyboardHidden|orientation|screenSize|smallestScreenSize|screenLayout|navigation|uiMode|density|fontScale|locale|layoutDirection|colorMode"
33
40
  android:exported="true"
34
41
  android:hardwareAccelerated="true">
35
42
  <intent-filter>
@@ -1,8 +1,16 @@
1
1
  package com.threenative.runtime;
2
2
 
3
+ import android.content.pm.ActivityInfo;
3
4
  import android.content.pm.ApplicationInfo;
4
5
  import android.content.pm.PackageManager;
6
+ import android.graphics.Insets;
7
+ import android.os.Build;
5
8
  import android.os.Bundle;
9
+ import android.util.Log;
10
+ import android.view.Surface;
11
+ import android.view.SurfaceHolder;
12
+ import android.view.View;
13
+ import android.view.WindowInsets;
6
14
  import android.view.WindowManager;
7
15
  import org.libsdl.app.SDLActivity;
8
16
 
@@ -20,6 +28,27 @@ import org.libsdl.app.SDLActivity;
20
28
  */
21
29
  public class MystralActivity extends SDLActivity {
22
30
 
31
+ private static final String LOG_TAG = "MystralRuntime";
32
+
33
+ /** The transparent WebView the UI renders into, or null when this game ships no overlay. */
34
+ private TnUiOverlay uiOverlay;
35
+
36
+ /** Reapply the preference whenever Android replaces the drawable surface. */
37
+ private final SurfaceHolder.Callback frameRateCallback = new SurfaceHolder.Callback() {
38
+ @Override
39
+ public void surfaceCreated(SurfaceHolder holder) {
40
+ requestPreferredFrameRate(holder, applicationMetadata());
41
+ }
42
+
43
+ @Override
44
+ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
45
+ requestPreferredFrameRate(holder, applicationMetadata());
46
+ }
47
+
48
+ @Override
49
+ public void surfaceDestroyed(SurfaceHolder holder) {}
50
+ };
51
+
23
52
  private Bundle applicationMetadata() {
24
53
  try {
25
54
  ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo(
@@ -30,15 +59,144 @@ public class MystralActivity extends SDLActivity {
30
59
  }
31
60
  }
32
61
 
62
+ /**
63
+ * Return top, right, bottom and left display cutout/system-bar insets in drawable pixels.
64
+ * Native refreshes this coarse value when SDL reports a resize or system-bar change.
65
+ */
66
+ public int[] getSafeAreaInsets() {
67
+ View decor = getWindow().getDecorView();
68
+ WindowInsets windowInsets = decor.getRootWindowInsets();
69
+ if (windowInsets == null) return new int[] {0, 0, 0, 0};
70
+ Insets insets = windowInsets.getInsets(
71
+ WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout());
72
+ return new int[] {insets.top, insets.right, insets.bottom, insets.left};
73
+ }
74
+
33
75
  @Override
34
76
  protected void onCreate(Bundle savedInstanceState) {
35
77
  super.onCreate(savedInstanceState);
36
78
  Bundle metadata = applicationMetadata();
79
+ applyOrientation(metadata);
37
80
  if (metadata != null && metadata.getBoolean("TN_KEEP_SCREEN_ON", false)) {
38
81
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
39
82
  } else {
40
83
  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
41
84
  }
85
+ installPreferredFrameRate(metadata);
86
+ attachUiOverlay(metadata);
87
+ }
88
+
89
+ @Override
90
+ protected void onResume() {
91
+ super.onResume();
92
+ if (mSurface != null) requestPreferredFrameRate(mSurface.getHolder(), applicationMetadata());
93
+ }
94
+
95
+ private void installPreferredFrameRate(Bundle metadata) {
96
+ if (mSurface == null) {
97
+ Log.w(LOG_TAG, "TN_DISPLAY_FRAME_RATE_REQUEST:{\"applied\":false,\"reason\":\"surface-missing\"}");
98
+ return;
99
+ }
100
+ SurfaceHolder holder = mSurface.getHolder();
101
+ holder.addCallback(frameRateCallback);
102
+ requestPreferredFrameRate(holder, metadata);
103
+ }
104
+
105
+ private void requestPreferredFrameRate(SurfaceHolder holder, Bundle metadata) {
106
+ int maxFps = metadata == null ? 60 : metadata.getInt("TN_MAX_FPS", 60);
107
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
108
+ Log.i(LOG_TAG, "TN_DISPLAY_FRAME_RATE_REQUEST:{\"maxFps\":" + maxFps + ",\"applied\":false,\"reason\":\"api<30\"}");
109
+ return;
110
+ }
111
+ Surface surface = holder == null ? null : holder.getSurface();
112
+ if (surface == null || !surface.isValid()) {
113
+ Log.w(LOG_TAG, "TN_DISPLAY_FRAME_RATE_REQUEST:{\"maxFps\":" + maxFps + ",\"applied\":false,\"reason\":\"surface-invalid\"}");
114
+ return;
115
+ }
116
+ try {
117
+ surface.setFrameRate((float) maxFps, Surface.FRAME_RATE_COMPATIBILITY_DEFAULT);
118
+ Log.i(LOG_TAG, "TN_DISPLAY_FRAME_RATE_REQUEST:{\"maxFps\":" + maxFps + ",\"applied\":true}");
119
+ } catch (RuntimeException exception) {
120
+ Log.w(LOG_TAG, "TN_DISPLAY_FRAME_RATE_REQUEST:{\"maxFps\":" + maxFps + ",\"applied\":false,\"reason\":\"" + exception.getClass().getSimpleName() + "\"}");
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Attach the UI layer when the game asked for it.
126
+ *
127
+ * `TN_UI_RENDERER` is written by the packager from `ui.renderer` in the game's config, and
128
+ * "native" (the other value) means PRD-216's CanvasLayer renderer with no WebView and no
129
+ * second process — so a game that did not opt in ships no overlay at all.
130
+ *
131
+ * The attach is deliberately not wrapped in a try/catch. A game that asked for this
132
+ * renderer and cannot have it must fail at launch with the reason named; a swallowed
133
+ * exception here presents as a game with no HUD, which sends the reader to the UI code.
134
+ */
135
+ private void attachUiOverlay(Bundle metadata) {
136
+ String renderer = metadata == null ? "native" : metadata.getString("TN_UI_RENDERER", "native");
137
+ if (!"web".equals(renderer)) return;
138
+ uiOverlay = TnUiOverlay.attach(this);
139
+ }
140
+
141
+ /**
142
+ * Deliver one bridge frame to the UI layer. Called from the runtime over JNI, on the thread
143
+ * that owns JavaScript, so the post itself is handed to the UI thread that owns the view.
144
+ */
145
+ public void postUiOverlayMessage(final String frame) {
146
+ final TnUiOverlay overlay = uiOverlay;
147
+ if (overlay == null) return;
148
+ runOnUiThread(new Runnable() {
149
+ @Override
150
+ public void run() {
151
+ overlay.postToPage(frame);
152
+ }
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Re-assert the declared orientation from the activity itself.
158
+ *
159
+ * `android:screenOrientation` is already written into the manifest by the packager, and on
160
+ * this device it was not enough: a landscape-declared build still came up in portrait, because
161
+ * the activity declares `configChanges=...|orientation|screenSize`, so the system hands
162
+ * rotation to the app instead of recreating it, and recent Android releases increasingly treat
163
+ * the manifest value as advisory. Calling `setRequestedOrientation` in `onCreate` is the
164
+ * request the window manager honours, and it costs nothing when the manifest already agreed.
165
+ *
166
+ * `sensor` is deliberately the only value that leaves rotation to the user; `landscape` and
167
+ * `portrait` lock, and landscape allows both ways up so the phone can be held either way.
168
+ */
169
+ private void applyOrientation(Bundle metadata) {
170
+ String orientation = metadata == null ? null : metadata.getString("TN_ORIENTATION");
171
+ if (!applyFixedOrientation(orientation)) {
172
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
173
+ }
174
+ }
175
+
176
+ private boolean applyFixedOrientation(String orientation) {
177
+ if ("landscape".equals(orientation)) {
178
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
179
+ return true;
180
+ }
181
+ if ("portrait".equals(orientation)) {
182
+ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
183
+ return true;
184
+ }
185
+ return false;
186
+ }
187
+
188
+ /**
189
+ * SDL3 calls this again when it creates or resizes its window. With no SDL orientation hint a
190
+ * resizable window becomes FULL_USER, overwriting the game metadata applied in onCreate. Keep
191
+ * a fixed game orientation authoritative; sensor games retain SDL's normal policy.
192
+ */
193
+ @Override
194
+ public void setOrientationBis(int width, int height, boolean resizable, String hint) {
195
+ Bundle metadata = applicationMetadata();
196
+ String orientation = metadata == null ? null : metadata.getString("TN_ORIENTATION");
197
+ if (!applyFixedOrientation(orientation)) {
198
+ super.setOrientationBis(width, height, resizable, hint);
199
+ }
42
200
  }
43
201
 
44
202
  /**
@@ -73,16 +231,35 @@ public class MystralActivity extends SDLActivity {
73
231
  Bundle metadata = applicationMetadata();
74
232
  String title = metadata == null ? "ThreeNative" : metadata.getString("TN_WINDOW_TITLE", "ThreeNative");
75
233
  boolean fullscreen = metadata == null || metadata.getBoolean("TN_FULLSCREEN", true);
234
+ // `display.backgroundMode`. The native side parses it and keeps the default for anything it
235
+ // does not recognize, so an unset value and a typo behave the same and both get logged.
236
+ // Default "pause" again as of 2026-08-23: resume now rebuilds the surface against the
237
+ // window Android hands back, so backgrounding no longer trades a battery cost for a black
238
+ // screen. This default must match the native one in `platform/lifecycle.cpp`, or an APK
239
+ // that carries no metadata runs one mode while the host reports the other.
240
+ String backgroundMode = metadata == null ? "pause" : metadata.getString("TN_BACKGROUND_MODE", "pause");
241
+ int maxFps = metadata == null ? 60 : metadata.getInt("TN_MAX_FPS", 60);
242
+ // Ask Android to provision the app-owned external directory before honoring a runner-
243
+ // supplied path beneath it. Creating /sdcard/Android/data/<package> directly is rejected
244
+ // by scoped storage on a clean install, even though a later app-owned child is writable.
245
+ java.io.File externalFiles = getExternalFilesDir(null);
76
246
  if (mailboxRoot == null) {
77
- java.io.File externalFiles = getExternalFilesDir(null);
78
247
  mailboxRoot = externalFiles == null ? getFilesDir().getAbsolutePath() : externalFiles.getAbsolutePath();
79
248
  }
249
+ java.io.File mailboxDirectory = new java.io.File(mailboxRoot);
250
+ if (!mailboxDirectory.isDirectory() && !mailboxDirectory.mkdirs()) {
251
+ throw new IllegalStateException(
252
+ "TN_PLAYTEST_MAILBOX_UNAVAILABLE: cannot create " + mailboxRoot
253
+ );
254
+ }
80
255
  return new String[] {
81
256
  "asset://scripts/main.js",
82
257
  endpoint == null ? "" : endpoint,
83
258
  mailboxRoot,
84
259
  title,
85
- Boolean.toString(fullscreen)
260
+ Boolean.toString(fullscreen),
261
+ backgroundMode == null ? "pause" : backgroundMode,
262
+ Integer.toString(maxFps)
86
263
  };
87
264
  }
88
265
  }