Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): the target frame rate reaches the host, which paces its display-driven loop to it

yhh3822636807bb
diff --git a/native/host/Host.hpp b/native/host/Host.hpp
index b0cecbc0e..31e8a6c28 100644
--- a/native/host/Host.hpp
+++ b/native/host/Host.hpp
@@ -112,6 +112,9 @@ struct Platform {
virtual bool pollMotion(MotionState&) { return false; }
virtual bool vibrate(int, int) { return false; }
virtual bool keepScreenOn(bool) { return false; }
+ /** The game's target frame rate, as App.setTargetFrameRate set it (0 = as fast as the display goes). A host stepped by
+ * the display paces itself to it; one that is not (desktop's own loop) ignores it. */
+ virtual void setTargetFrameRate(float /*fps*/) {}
virtual ~Platform() = default;
/** A packaged, project-relative file — the APK's `assets/` on Android, the
diff --git a/native/host/bindings/DeviceBindings.cpp b/native/host/bindings/DeviceBindings.cpp
index b3c9d9432..4dea35342 100644
--- a/native/host/bindings/DeviceBindings.cpp
+++ b/native/host/bindings/DeviceBindings.cpp
@@ -98,6 +98,12 @@ JSValue js_keepScreenOn(JSContext* ctx, JSValueConst, int argc, JSValueConst* ar
return JS_NewBool(ctx, hostAlive() && host().platform && argc > 0
&& host().platform->keepScreenOn(JS_ToBool(ctx, argv[0]) > 0));
}
+JSValue js_setTargetFrameRate(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {
+ double fps = 0;
+ if (argc > 0 && JS_ToFloat64(ctx, &fps, argv[0]) < 0) return JS_EXCEPTION;
+ if (hostAlive() && host().platform) host().platform->setTargetFrameRate(fps > 0 ? (float)fps : 0.0f);
+ return JS_UNDEFINED;
+}
} // namespace
@@ -109,6 +115,7 @@ void registerDeviceBindings(HostState& h, JSValue global) {
bindGlobal(h, global, "es_pollMotion", js_pollMotion, 0);
bindGlobal(h, global, "es_vibrate", js_vibrate, 2);
bindGlobal(h, global, "es_keepScreenOn", js_keepScreenOn, 1);
+ bindGlobal(h, global, "es_setTargetFrameRate", js_setTargetFrameRate, 1);
}
} // namespace eshost
diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cpp
index 398917d32..34c343e49 100644
--- a/native/host/platform/android.cpp
+++ b/native/host/platform/android.cpp
@@ -165,7 +165,10 @@ void performHttp(JNIEnv* env, const eshost::FetchRequest& req, eshost::FetchResu
env->DeleteLocalRef(conn);
}
+void framesTargetRate(float fps); // FrameDriver, below
+
struct AndroidPlatform final : eshost::Platform {
+ void setTargetFrameRate(float fps) override { framesTargetRate(fps); }
eshost::AndroidDevice device;
int deviceCapabilities() const override { return device.capabilities(); }
bool startMotion(bool a, bool g, int interval) override { return device.start(a, g, interval); }
@@ -514,8 +517,7 @@ void framesResumed(bool is);
// vsync, and the period lands on 16.6 / 25 / 33 ms at random — 45 to 55 fps and uneven motion. 60 Hz is an exact fraction of
// 120 Hz and of 60 Hz, so the system can hold it on either. ANativeWindow_setFrameRate is API 30; the manifest floor is 29,
// so it is looked up like PerformanceHints' symbols rather than made a load-time requirement.
-void hintFrameRate(ANativeWindow* window) {
- constexpr float kTargetFps = 60.0f;
+void hintFrameRate(ANativeWindow* window, float fps) {
constexpr int8_t kCompatibilityDefault = 0; // ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT
using SetFrameRateFn = int32_t (*)(ANativeWindow*, float, int8_t);
const auto set = reinterpret_cast<SetFrameRateFn>(dlsym(RTLD_DEFAULT, "ANativeWindow_setFrameRate"));
@@ -523,11 +525,16 @@ void hintFrameRate(ANativeWindow* window) {
if (window) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, "frame rate hint: unavailable (API < 30)");
return;
}
- const int32_t result = set(window, kTargetFps, kCompatibilityDefault);
+ const int32_t result = set(window, fps, kCompatibilityDefault); // 0 fps = no preference: the panel's own rate
__android_log_print(result == 0 ? ANDROID_LOG_INFO : ANDROID_LOG_WARN, LOG_TAG,
- "frame rate hint: %.0f fps (%s)", kTargetFps, result == 0 ? "accepted" : "refused");
+ "frame rate hint: %.0f fps (%s)", fps, result == 0 ? "accepted" : "refused");
}
+// What the game wants until it says otherwise (App.setTargetFrameRate -> es_setTargetFrameRate).
+constexpr float kDefaultFps = 60.0f;
+float g_targetFps = kDefaultFps;
+bool g_targetSet = false;
+
void onAppCmd(android_app* app, int32_t cmd) {
// NativeActivity supplies a content rectangle in window pixels; the glue
// updates it before delivering CONTENT_RECT_CHANGED, including rotation.
@@ -542,7 +549,7 @@ void onAppCmd(android_app* app, int32_t cmd) {
else eshost::bindSurface();
// Ask for frames only once there is something to present to, the
// same order iOS unpauses its display link in.
- hintFrameRate(app->window); // per window: a recreated surface forgets it
+ hintFrameRate(app->window, g_targetFps); // per window: a recreated surface forgets it
framesSurface(eshost::surfaceBound());
}
break;
@@ -725,10 +732,27 @@ struct FrameDriver {
AChoreographer_postFrameCallback64(choreographer, &FrameDriver::onVsync64, this);
}
+ /// When the next frame is due, on the vsync clock; 0 restarts the cadence.
+ int64_t nextRunNanos = 0;
+
private:
+ /// The cap the game asked for, held as a cadence and not as a minimum gap — the web loop's rule (App.mainLoop): a gap
+ /// measured frame to frame loses to jitter half the time and waits a third. Only an explicit cap paces here; the default
+ /// 60 is the system's to hold, through the hint. Returns false for a vsync this frame is skipped on.
+ bool due(int64_t vsyncNanos) {
+ if (!g_targetSet || g_targetFps <= 0.0f || vsyncNanos <= 0) return true;
+ const int64_t interval = (int64_t)(1e9 / g_targetFps);
+ constexpr int64_t kJitter = 2'000'000; // 2 ms
+ if (vsyncNanos < nextRunNanos - kJitter) return false;
+ nextRunNanos = (nextRunNanos == 0 || vsyncNanos - nextRunNanos > interval)
+ ? vsyncNanos + interval : nextRunNanos + interval;
+ return true;
+ }
+
void tick(int64_t vsyncNanos) {
posted = false;
if (!running) return;
+ if (!due(vsyncNanos)) { post(); return; }
// Timed around the frame alone, and re-posted after it: asking for the
// next vsync first would let a frame that overran queue behind itself.
const auto begin = std::chrono::steady_clock::now();
@@ -743,6 +767,13 @@ private:
FrameDriver g_frames;
+void framesTargetRate(float fps) {
+ if (g_targetSet && fps == g_targetFps) return;
+ g_targetSet = true;
+ g_targetFps = fps;
+ g_frames.nextRunNanos = 0;
+ hintFrameRate(g_platform.window, fps);
+}
void framesSurface(bool has) { g_frames.setSurface(has); }
void framesResumed(bool is) { g_frames.setResumed(is); }
diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.ts
index d848ced00..8480feca7 100644
--- a/sdk/src/app/app.ts
+++ b/sdk/src/app/app.ts
@@ -882,6 +882,9 @@ export class App {
setTargetFrameRate(fps: number): void {
this.targetFrameInterval_ = fps > 0 ? 1000 / fps : 0;
this.nextCapFrameAt_ = 0;
+ // A native host steps the app from its own display-driven loop, not from mainLoop above, so the cap
+ // is the host's to hold (and to tell the OS, so the panel settles on a rate the game can keep).
+ (globalThis as { es_setTargetFrameRate?: (fps: number) => void }).es_setTargetFrameRate?.(fps > 0 ? fps : 0);
}
getTargetFrameRate(): number {
diff --git a/sdk/tests/app-tick.test.ts b/sdk/tests/app-tick.test.ts
index e12d57e24..0488850ca 100644
--- a/sdk/tests/app-tick.test.ts
+++ b/sdk/tests/app-tick.test.ts
@@ -278,6 +278,20 @@ describe('App.stepFrames()', () => {
}
});
+ it('hands the cap to a native host, which paces its own display-driven loop', () => {
+ const host = globalThis as { es_setTargetFrameRate?: (fps: number) => void };
+ const seen: number[] = [];
+ host.es_setTargetFrameRate = (fps) => { seen.push(fps); };
+ try {
+ const app = App.new();
+ app.setTargetFrameRate(45);
+ app.setTargetFrameRate(0);
+ expect(seen).toEqual([45, 0]);
+ } finally {
+ delete host.es_setTargetFrameRate;
+ }
+ });
+
it.each([30, 48])('a %i fps cap on a 60 Hz display runs at the cap, whatever the jitter', async (cap) => {
const realRaf = globalThis.requestAnimationFrame;
let pending: ((ts: number) => void) | null = null;