From 1a637b07b11c2a205eeb5936b8f020d36d8b07a9 Mon Sep 17 00:00:00 2001 From: Fabio Alessandrelli Date: Mon, 29 Jun 2020 21:00:20 +0200 Subject: [PATCH] Limit FPS in JS by skipping iterations. --- platform/javascript/javascript_main.cpp | 10 ++++++++++ platform/javascript/os_javascript.h | 3 +++ 2 files changed, 13 insertions(+) diff --git a/platform/javascript/javascript_main.cpp b/platform/javascript/javascript_main.cpp index a2d9031f4b5..8b7bd2170f7 100644 --- a/platform/javascript/javascript_main.cpp +++ b/platform/javascript/javascript_main.cpp @@ -36,6 +36,7 @@ #include static OS_JavaScript *os = nullptr; +static uint64_t target_ticks = 0; void exit_callback() { emscripten_cancel_main_loop(); // After this, we can exit! @@ -47,9 +48,18 @@ void exit_callback() { } void main_loop_callback() { + uint64_t current_ticks = os->get_ticks_usec(); + bool force_draw = DisplayServerJavaScript::get_singleton()->check_size_force_redraw(); if (force_draw) { Main::force_redraw(); + } else if (current_ticks < target_ticks) { + return; // Skip frame. + } + + int target_fps = Engine::get_singleton()->get_target_fps(); + if (target_fps > 0) { + target_ticks += (uint64_t)(1000000 / target_fps); } if (os->main_loop_iterate()) { emscripten_cancel_main_loop(); // Cancel current loop and wait for finalize_async. diff --git a/platform/javascript/os_javascript.h b/platform/javascript/os_javascript.h index f0f18b44f87..dddeef836c4 100644 --- a/platform/javascript/os_javascript.h +++ b/platform/javascript/os_javascript.h @@ -83,6 +83,9 @@ public: String get_executable_path() const; virtual Error shell_open(String p_uri); virtual String get_name() const; + // Override default OS implementation which would block the main thread with delay_usec. + // Implemented in javascript_main.cpp loop callback instead. + virtual void add_frame_delay(bool p_can_draw) {} virtual bool can_draw() const; virtual String get_cache_path() const;