diff --git a/CMakeLists.txt b/CMakeLists.txt index 7806c7cd..b695c260 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -345,6 +345,14 @@ if(BUILD_TESTING AND NOT ANDROID) endif() if(AVA2_BUILD_HOST) find_package(SDL3 CONFIG REQUIRED) + add_library(ava2_platform src/app/platform/platform.cpp) + target_include_directories(ava2_platform PUBLIC src) + target_link_libraries(ava2_platform PUBLIC SDL3::SDL3) + if(BUILD_TESTING) + add_executable(platform_test tests/platform_test.cpp) + target_link_libraries(platform_test PRIVATE ava2_platform ava2_input) + add_test(NAME ava2.platform COMMAND platform_test) + endif() if(ANDROID) add_library(main SHARED src/app/main.cpp) set(AVA2_HOST main) @@ -353,7 +361,7 @@ if(AVA2_BUILD_HOST) set(AVA2_HOST ava2_client) endif() target_include_directories(${AVA2_HOST} PRIVATE src src/app src/game src/network src/scripting) - target_link_libraries(${AVA2_HOST} PRIVATE SDL3::SDL3 ava2_protocol ava2_render) + target_link_libraries(${AVA2_HOST} PRIVATE SDL3::SDL3 ava2_protocol ava2_render ava2_platform) if(AVA2_EMBED_PYTHON) target_link_libraries(${AVA2_HOST} PRIVATE ava2_python) target_compile_definitions(${AVA2_HOST} PRIVATE AVA2_HAS_PYTHON) diff --git a/docs/MOBILE-ARCHITECTURE.md b/docs/MOBILE-ARCHITECTURE.md index d9edf026..23d67368 100644 --- a/docs/MOBILE-ARCHITECTURE.md +++ b/docs/MOBILE-ARCHITECTURE.md @@ -7,7 +7,7 @@ - `android/build.sh` 可以编出 arm64 调试 APK(SDL3 + FreeType 自动编译,16 KB 页对齐),连接手机时自动安装启动;真机运行尚未验证。 - `android/push_assets.py` 把资源(`assets/loose` + python-root + `python27.zip`)推送到应用外部存储目录,客户端启动时切换到该目录。 - 游戏资源为 2.8 GB、约 5 万个散文件(`assets/loose`),17 个源文件中 120 多处通过 `std::filesystem` / `ifstream` 直接读文件,无法读取 APK 内置资源。 -- 没有处理前后台切换(`SDL_EVENT_WILL_ENTER_BACKGROUND` / `DID_ENTER_FOREGROUND`)和低内存事件。 +- 平台层已实现(`src/app/platform/`):资源根目录与配置目录;前后台切换(进后台时保存配置、暂停声音、取消输入、停止渲染,网络照常收发;Android 设 `SDL_ANDROID_BLOCK_ON_PAUSE=0`);安全区域按逻辑分辨率换算后放进触摸布局,HUD 用 `touch.GetSafeArea()` 内缩。低内存事件目前只记日志;HUD 只在创建时读安全区;均未真机验证。 - 触摸分流已实现(`src/app/input/touch_router.*`,见下文 `input/`):移动端或 `--touch` / `AVA2_TOUCH=1` 时关闭 SDL 触摸转鼠标,每个手指分到界面、攻击键、左下浮动摇杆或镜头(单指拖动转向、双指缩放、轻点=点地移动)。Python 模块 `touch` 供 HUD 设置攻击键位置并读取摇杆状态;`ui_mobile_joystick` / `ui_mobile_combat` 改为只做显示(`not_pick`)。多指同时操作尚未在真机验证。 - 出招已接通(PORT-PLAN「Mobile step 3b」):触摸攻击键和键盘共用 `ProcessPlayerAttack`,按原版连招时序出招,发送 FUNC_COMBO 移动包,命中检测后发 `CG_ATTACK`;尚未在真服验证,弓箭飞行、技能、PvP 规则等仍缺。 - 原型 HUD 用到的 `taskbar/attack_button_0x.sub`、`quickslot_0x.sub` 不在资源包里:攻击键暂用色块,技能圈槽位不可见。 diff --git a/docs/PORT-PLAN.md b/docs/PORT-PLAN.md index 361a9cbc..842be151 100644 --- a/docs/PORT-PLAN.md +++ b/docs/PORT-PLAN.md @@ -1222,3 +1222,36 @@ skills are not wired; PvP `IsAttackableInstance` rules and the `__CanAttack` checks (emotion, private shop, observer, new mount) are missing; remote FUNC_ATTACK / FUNC_COMBO snap to the packet position instead of walking there when 50+ away. + +### 2026-10-12 Mobile step 2 — platform layer + +`src/app/platform/` (`ava2_platform`) takes the per-platform code out of +`main.cpp`: + +- `EnterClientDataDirectory` (macOS per-user data dir linking the bundle + Resources; Android external files dir) and `ConfigDirectory` (Android + internal storage for metin2.cfg / interface.cfg) — moved unchanged. +- `Lifecycle`: an SDL event watch records background / foreground / low + memory / terminating; the main loop applies them. Entering the background + cancels movement and touch fingers, saves the config and interface status, + and pauses the audio device (`SoundManager::SetPaused`); while in the + background the loop skips game update and rendering but keeps receiving and + dispatching network packets. Foreground resets the frame clock. Android + runs with `SDL_ANDROID_BLOCK_ON_PAUSE=0` (SDL then waits up to 100 ms per + poll while paused); SDL's Vulkan backend recreates the surface on resume. +- Safe area: `SDL_GetWindowSafeArea` mapped through the letterboxed logical + presentation (`MapSafeInsets`) into `TouchLayout` (`safe_*`; + `ForScreen` keeps the joystick area and attack button inside) and + re-queried on `SDL_EVENT_WINDOW_SAFE_AREA_CHANGED` / resize. Python + `touch.GetSafeArea()`; the mobile HUD prototype insets the player panel, + target bar, drawer, quick belt and combat wheel. + +Verified: `ava2.platform` (lifecycle transitions incl. pause+resume between +frames, inset mapping with letterbox bars and scaling, safe touch layout), +`ava2.touch_game` (desktop insets 0; a HUD built with insets puts the attack +button inside them), 53/53 desktop tests, `ava2_client --touch` starts, +Android APK builds. +Outstanding: no device run (background/resume, surface recreation, audio +resume, server keepalive while paused); low memory only logs (no cache purge); +the HUD reads the insets only when it is built; iOS lifecycle needs the event +watch to do the save work synchronously. diff --git a/src/app/input/touch_router.cpp b/src/app/input/touch_router.cpp index ec954b65..eb2bdfc2 100644 --- a/src/app/input/touch_router.cpp +++ b/src/app/input/touch_router.cpp @@ -8,19 +8,24 @@ namespace ava2::input { -TouchLayout TouchLayout::ForScreen(float w, float h) { +TouchLayout TouchLayout::ForScreen(float w, float h, float safeLeft, float safeTop, float safeRight, float safeBottom) { TouchLayout layout; layout.screen_w = w; layout.screen_h = h; + layout.safe_left = safeLeft; + layout.safe_top = safeTop; + layout.safe_right = safeRight; + layout.safe_bottom = safeBottom; const float unit = std::min(w, h); - layout.joy_x = 0.0f; + // The joystick area starts at the safe edge; the stick floats, so its bottom can stay wide. + layout.joy_x = safeLeft; layout.joy_y = h * 0.45f; layout.joy_w = w * 0.40f; - layout.joy_h = h * 0.55f; + layout.joy_h = h * 0.55f - safeBottom; layout.joy_radius = unit * 0.12f; layout.attack_r = unit * 0.11f; - layout.attack_x = w - layout.attack_r - unit * 0.06f; - layout.attack_y = h - layout.attack_r - unit * 0.06f; + layout.attack_x = w - safeRight - layout.attack_r - unit * 0.06f; + layout.attack_y = h - safeBottom - layout.attack_r - unit * 0.06f; layout.tap_slop = unit * 0.02f; return layout; } diff --git a/src/app/input/touch_router.h b/src/app/input/touch_router.h index 31a8c971..1a7b0e46 100644 --- a/src/app/input/touch_router.h +++ b/src/app/input/touch_router.h @@ -46,8 +46,13 @@ struct TouchLayout { float tap_slop = 14.0f; // movement that turns a tap into a camera drag std::uint64_t tap_ms = 300; // longer presses are not taps - // Default layout for a screen: joystick in the lower-left 40% x 55%, attack bottom right. - static TouchLayout ForScreen(float w, float h); + // Unobstructed-area insets (platform::SafeInsets); the HUD reads them through `touch`. + float safe_left = 0.0f, safe_top = 0.0f, safe_right = 0.0f, safe_bottom = 0.0f; + + // Default layout for a screen: joystick in the lower-left 40% x 55%, attack bottom right, + // both kept inside the safe insets. + static TouchLayout ForScreen(float w, float h, float safeLeft = 0.0f, float safeTop = 0.0f, + float safeRight = 0.0f, float safeBottom = 0.0f); }; struct JoystickView { diff --git a/src/app/main.cpp b/src/app/main.cpp index 1366e7ba..ff4433a9 100644 --- a/src/app/main.cpp +++ b/src/app/main.cpp @@ -38,6 +38,7 @@ #include "eter_render/RaceData.h" #include "app/input/touch_router.h" #endif +#include "app/platform/platform.h" #include #include #include @@ -176,58 +177,10 @@ int SDLKeyToDIK(SDL_Keycode key) { } // namespace int main(int argc, char** argv) { -#if defined(__APPLE__) - // Keep legacy Python's relative config/chat writes outside the signed application. - try { - std::filesystem::path base = std::filesystem::path(SDL_GetBasePath()).lexically_normal(); - if (base.filename().empty()) base = base.parent_path(); - // SDL on macOS returns the bundle's Resources directory by default. - if (base.filename() == "Resources" && base.parent_path().filename() == "Contents") - base = base.parent_path() / "MacOS"; - const auto resources = base / "../Resources"; - if (base.filename() == "MacOS" && std::filesystem::is_directory(resources)) { - std::filesystem::path data; - if (const char* overridePath = std::getenv("AVA2_USER_DATA_DIR")) data = overridePath; - else { - char* preferences = SDL_GetPrefPath("AVA2", "Client"); - if (!preferences) throw std::runtime_error(SDL_GetError()); - data = preferences; SDL_free(preferences); - } - std::filesystem::create_directories(data); - for (const auto& entry : std::filesystem::directory_iterator(resources)) { - const auto name = entry.path().filename(); - const auto extension = name.extension().string(); - if (name == "lib" || extension == ".cfg" || extension == ".inf" || extension == ".chat") continue; - const auto link = data / name; - const auto target = std::filesystem::canonical(entry.path()); - if (std::filesystem::is_symlink(link) && std::filesystem::read_symlink(link) != target) - std::filesystem::remove(link); - if (!std::filesystem::exists(link)) std::filesystem::create_symlink(target, link); - } - std::filesystem::current_path(data); - SDL_Log("Client user data: %s", data.string().c_str()); - } - } catch (const std::exception& error) { - SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Cannot initialize client data directory: %s", error.what()); + if (std::string error; !ava2::platform::EnterClientDataDirectory(&error)) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "%s", error.c_str()); return 1; } - -#elif defined(__ANDROID__) - // The APK holds code only. The flattened client root (assets/loose + python-root + python27.zip, - // android/push_assets.py) lives in the app's external files directory; the legacy code reads - // paths relative to the working directory. - { - const char* data = SDL_GetAndroidExternalStoragePath(); - std::error_code error; - if (data) std::filesystem::current_path(data, error); - if (!data || error) { - SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Cannot enter client data directory: %s", - data ? error.message().c_str() : SDL_GetError()); - return 1; - } - SDL_Log("Client data: %s", data); - } -#endif try { int frame_limit = 0, auto_slot = -1, fps_cap = -1, game_frames = 1, rendered_game_frames = 0; #ifdef __ANDROID__ @@ -326,12 +279,8 @@ int main(int argc, char** argv) { #endif #ifdef AVA2_HAS_PYTHON -#ifdef __ANDROID__ - // metin2.cfg / interface.cfg live in the client's working directory on Windows; the APK's - // working directory is not writable, so they go to the app's internal storage instead. - if (const char* internal = SDL_GetAndroidInternalStoragePath()) - ava2::CPythonSystem::SetConfigDirectory(internal); -#endif + if (const std::string config = ava2::platform::ConfigDirectory(); !config.empty()) + ava2::CPythonSystem::SetConfigDirectory(config); std::unique_ptr python; if (!stdlib.empty() || !script_root.empty()) { python = std::make_unique(stdlib, script_root); @@ -372,8 +321,12 @@ int main(int argc, char** argv) { SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "1"); } #endif + ava2::platform::Lifecycle::SetHints(); if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw std::runtime_error(SDL_GetError()); struct Quit { ~Quit(){ SDL_Quit(); } } quit; + ava2::platform::Lifecycle lifecycle; + lifecycle.Install(); + struct Unwatch { ava2::platform::Lifecycle& l; ~Unwatch(){ l.Uninstall(); } } unwatch{lifecycle}; std::unique_ptr gpu( SDL_CreateGPUDevice(SDL_GPU_SHADERFORMAT_SPIRV | SDL_GPU_SHADERFORMAT_MSL, std::getenv("AVA2_GPU_DEBUG") != nullptr, nullptr), @@ -733,7 +686,10 @@ int main(int argc, char** argv) { auto& touch_router = ava2::input::GetTouchRouter(); if (touch_mode) { touch_router.SetSink(&touch_sink); - touch_router.SetLayout(ava2::input::TouchLayout::ForScreen(float(screen_width), float(screen_height))); + const auto safe = ava2::platform::QuerySafeInsets(window.get(), renderer.get()); + touch_router.SetLayout(ava2::input::TouchLayout::ForScreen(float(screen_width), float(screen_height), + safe.left, safe.top, safe.right, safe.bottom)); + SDL_Log("Safe area insets: %.0f %.0f %.0f %.0f", safe.left, safe.top, safe.right, safe.bottom); } // Finger position in UI pixels (SDL gives it normalized to the window). auto finger_point = [&](const SDL_TouchFingerEvent& finger, float& x, float& y) { @@ -1309,6 +1265,14 @@ const auto profileActiveStart = std::chrono::steady_clock::now(); while (SDL_PollEvent(&event)) { if (event.type == SDL_EVENT_QUIT) running = false; #ifdef AVA2_HAS_PYTHON + if (touch_mode && (event.type == SDL_EVENT_WINDOW_SAFE_AREA_CHANGED || event.type == SDL_EVENT_WINDOW_RESIZED)) { + // The HUD reads the insets when it is built; the router keeps its button positions. + const auto safe = ava2::platform::QuerySafeInsets(window.get(), renderer.get()); + auto layout = touch_router.GetLayout(); + layout.safe_left = safe.left; layout.safe_top = safe.top; + layout.safe_right = safe.right; layout.safe_bottom = safe.bottom; + touch_router.SetLayout(layout); + } if (event.type == SDL_EVENT_WINDOW_FOCUS_LOST) { ava2::CancelPlayerMovement(); orbit_camera.EndDrag(); key_move_fwd = key_move_back = key_turn_left = key_turn_right = false; @@ -1743,6 +1707,49 @@ const auto profileActiveStart = std::chrono::steady_clock::now(); #endif } + // platform/ lifecycle: save and go quiet in the background, keep the connection. + switch (lifecycle.Poll()) { + case ava2::platform::Lifecycle::Change::EnterBackground: + SDL_Log("Entering background"); +#ifdef AVA2_HAS_PYTHON + ava2::CancelPlayerMovement(); orbit_camera.EndDrag(); + key_move_fwd = key_move_back = key_turn_left = key_turn_right = false; + if (touch_mode) touch_router.CancelAll(); + // The OS may kill a background app without another event. + if (python) { + ava2::CPythonSystem::Instance().SaveConfig(); + ava2::CPythonSystem::Instance().SaveInterfaceStatus(); + } +#endif + ava2::SoundManager::Instance().SetPaused(true); + break; + case ava2::platform::Lifecycle::Change::EnterForeground: + SDL_Log("Entering foreground"); + ava2::SoundManager::Instance().SetPaused(false); + // The first foreground frame must not see the whole pause as one frame. + prev_frame_time = std::chrono::steady_clock::now(); + break; + default: break; + } + if (lifecycle.TakeLowMemory()) SDL_Log("Low memory warning"); + if (lifecycle.IsTerminating()) running = false; + if (lifecycle.IsBackground() && running) { + // No rendering (the surface is gone on Android) and no game update; the network keeps + // its keepalive and the queue drained. SDL itself waits up to 100 ms per poll on Android. +#ifdef AVA2_HAS_PYTHON + if (python) { + if (!view_script.empty()) python->pump_network(); + ava2::PythonNetworkStream::Instance().ProcessRecvData(); + ava2::pump_python_net(); + if (ava2::PythonNetworkStream::Instance().IsQuitRequested()) running = false; + } +#endif +#ifndef __ANDROID__ + SDL_Delay(50); +#endif + continue; + } + #ifdef AVA2_HAS_PYTHON if (python && !view_script.empty()) { if (auto_connect && !requested) { requested = true; connect(); if (!local_error.empty()) throw std::runtime_error(local_error); } diff --git a/src/app/platform/platform.cpp b/src/app/platform/platform.cpp new file mode 100644 index 00000000..97c5ca2e --- /dev/null +++ b/src/app/platform/platform.cpp @@ -0,0 +1,149 @@ +#include "platform.h" + +#include +#include +#include +#include +#include + +namespace ava2::platform { + +bool EnterClientDataDirectory(std::string* error) { +#if defined(__APPLE__) + // Keep legacy Python's relative config/chat writes outside the signed application. + try { + std::filesystem::path base = std::filesystem::path(SDL_GetBasePath()).lexically_normal(); + if (base.filename().empty()) base = base.parent_path(); + // SDL on macOS returns the bundle's Resources directory by default. + if (base.filename() == "Resources" && base.parent_path().filename() == "Contents") + base = base.parent_path() / "MacOS"; + const auto resources = base / "../Resources"; + if (base.filename() == "MacOS" && std::filesystem::is_directory(resources)) { + std::filesystem::path data; + if (const char* overridePath = std::getenv("AVA2_USER_DATA_DIR")) data = overridePath; + else { + char* preferences = SDL_GetPrefPath("AVA2", "Client"); + if (!preferences) throw std::runtime_error(SDL_GetError()); + data = preferences; SDL_free(preferences); + } + std::filesystem::create_directories(data); + for (const auto& entry : std::filesystem::directory_iterator(resources)) { + const auto name = entry.path().filename(); + const auto extension = name.extension().string(); + if (name == "lib" || extension == ".cfg" || extension == ".inf" || extension == ".chat") continue; + const auto link = data / name; + const auto target = std::filesystem::canonical(entry.path()); + if (std::filesystem::is_symlink(link) && std::filesystem::read_symlink(link) != target) + std::filesystem::remove(link); + if (!std::filesystem::exists(link)) std::filesystem::create_symlink(target, link); + } + std::filesystem::current_path(data); + SDL_Log("Client user data: %s", data.string().c_str()); + } + } catch (const std::exception& e) { + if (error) *error = std::string("Cannot initialize client data directory: ") + e.what(); + return false; + } +#elif defined(__ANDROID__) + // The APK holds code only. The flattened client root (assets/loose + python-root + python27.zip, + // android/push_assets.py) lives in the app's external files directory; the legacy code reads + // paths relative to the working directory. + const char* data = SDL_GetAndroidExternalStoragePath(); + std::error_code ec; + if (data) std::filesystem::current_path(data, ec); + if (!data || ec) { + if (error) *error = std::string("Cannot enter client data directory: ") + (data ? ec.message() : SDL_GetError()); + return false; + } + SDL_Log("Client data: %s", data); +#else + (void)error; +#endif + return true; +} + +std::string ConfigDirectory() { +#ifdef __ANDROID__ + // metin2.cfg / interface.cfg live in the client's working directory on Windows; the APK's + // working directory is not writable, so they go to the app's internal storage instead. + if (const char* internal = SDL_GetAndroidInternalStoragePath()) return internal; +#endif + return {}; +} + +namespace { +bool SDLCALL LifecycleWatch(void* userdata, SDL_Event* event) { + static_cast(userdata)->OnEvent(event->type); + return true; +} +} // namespace + +void Lifecycle::SetHints() { + // Keep the loop (and the game connection) alive while paused; rendering and sound stop. + SDL_SetHint(SDL_HINT_ANDROID_BLOCK_ON_PAUSE, "0"); +} + +void Lifecycle::Install() { + if (m_installed) return; + m_installed = SDL_AddEventWatch(LifecycleWatch, this); +} + +void Lifecycle::Uninstall() { + if (!m_installed) return; + SDL_RemoveEventWatch(LifecycleWatch, this); + m_installed = false; +} + +void Lifecycle::OnEvent(unsigned int type) { + switch (type) { + case SDL_EVENT_WILL_ENTER_BACKGROUND: + case SDL_EVENT_DID_ENTER_BACKGROUND: + if (!m_background.exchange(true)) m_enteredBackground = true; + break; + case SDL_EVENT_WILL_ENTER_FOREGROUND: + case SDL_EVENT_DID_ENTER_FOREGROUND: + if (m_background.exchange(false)) m_enteredForeground = true; + break; + case SDL_EVENT_LOW_MEMORY: m_lowMemory = true; break; + case SDL_EVENT_TERMINATING: m_terminating = true; break; + default: break; + } +} + +Lifecycle::Change Lifecycle::Poll() { + if (m_enteredBackground.exchange(false)) { + // A resume that already happened is reported on the next poll. + return Change::EnterBackground; + } + if (m_enteredForeground.exchange(false)) return Change::EnterForeground; + return Change::None; +} + +SafeInsets MapSafeInsets(float windowW, float windowH, float safeX, float safeY, float safeW, float safeH, + float logicalW, float logicalH) { + SafeInsets out; + if (windowW <= 0.0f || windowH <= 0.0f || logicalW <= 0.0f || logicalH <= 0.0f) return out; + // Letterbox: uniform scale, centred. + const float scale = std::min(windowW / logicalW, windowH / logicalH); + const float offX = (windowW - logicalW * scale) * 0.5f; + const float offY = (windowH - logicalH * scale) * 0.5f; + auto clampInset = [](float v, float limit) { return std::clamp(v, 0.0f, limit); }; + out.left = clampInset((safeX - offX) / scale, logicalW); + out.top = clampInset((safeY - offY) / scale, logicalH); + out.right = clampInset((offX + logicalW * scale - (safeX + safeW)) / scale, logicalW); + out.bottom = clampInset((offY + logicalH * scale - (safeY + safeH)) / scale, logicalH); + return out; +} + +SafeInsets QuerySafeInsets(SDL_Window* window, SDL_Renderer* renderer) { + int ww = 0, wh = 0, lw = 0, lh = 0; + SDL_Rect safe{}; + SDL_RendererLogicalPresentation mode; + if (!window || !renderer || !SDL_GetWindowSize(window, &ww, &wh) || !SDL_GetWindowSafeArea(window, &safe) || + !SDL_GetRenderLogicalPresentation(renderer, &lw, &lh, &mode) || lw <= 0 || lh <= 0) + return {}; + return MapSafeInsets(float(ww), float(wh), float(safe.x), float(safe.y), float(safe.w), float(safe.h), + float(lw), float(lh)); +} + +} // namespace ava2::platform diff --git a/src/app/platform/platform.h b/src/app/platform/platform.h new file mode 100644 index 00000000..fa68c383 --- /dev/null +++ b/src/app/platform/platform.h @@ -0,0 +1,71 @@ +#pragma once +// Platform layer for the client host (docs/MOBILE-ARCHITECTURE.md, platform/): data and config +// directories, application lifecycle (background / foreground / low memory / terminate) and the +// screen safe area. Keeps the per-platform #ifdefs out of the main loop. + +#include +#include + +struct SDL_Window; +struct SDL_Renderer; + +namespace ava2::platform { + +// Enters the client root the legacy code reads relative paths from: on macOS the per-user data +// directory that links the bundle Resources (config/chat writes stay outside the signed app); on +// Android the app's external files directory (android/push_assets.py). Elsewhere a no-op. +// False with *error set when the directory cannot be entered. +bool EnterClientDataDirectory(std::string* error); + +// Where metin2.cfg / interface.cfg are written when the working directory is not writable +// (Android internal storage); empty keeps the working directory. +std::string ConfigDirectory(); + +// Background/foreground handling. SDL delivers the app events from the OS thread on mobile +// (SDL_AddEventWatch), so the watch only records them; the main loop applies them with Poll(). +// Android runs with SDL_ANDROID_BLOCK_ON_PAUSE=0 so the loop keeps pumping the network while +// paused (SDL then waits up to 100 ms per poll). +class Lifecycle { +public: + enum class Change { None, EnterBackground, EnterForeground }; + + // Sets the hints (before SDL_Init) and installs the event watch (after SDL_Init). + static void SetHints(); + void Install(); + void Uninstall(); + + // Records one app event (called by the watch; public for tests). + void OnEvent(unsigned int sdlEventType); + + // The next background/foreground transition since the last call (background wins when both + // happened, so a quick pause-resume still saves the config once). + Change Poll(); + bool IsBackground() const { return m_background.load(); } + // True once per SDL_EVENT_LOW_MEMORY. + bool TakeLowMemory() { return m_lowMemory.exchange(false); } + bool IsTerminating() const { return m_terminating.load(); } + +private: + std::atomic m_background{false}, m_enteredBackground{false}, m_enteredForeground{false}; + std::atomic m_lowMemory{false}, m_terminating{false}; + bool m_installed = false; +}; + +// Insets of the unobstructed area (notch, rounded corners, gesture bar) in logical UI pixels. +struct SafeInsets { + float left = 0.0f, top = 0.0f, right = 0.0f, bottom = 0.0f; + bool operator==(const SafeInsets& o) const { + return left == o.left && top == o.top && right == o.right && bottom == o.bottom; + } +}; + +// Maps a window-space safe rectangle into a letterboxed logical presentation of logicalW x +// logicalH inside a windowW x windowH window (SDL_LOGICAL_PRESENTATION_LETTERBOX). Insets that +// fall into the letterbox bars are 0; results are clamped to the logical screen. +SafeInsets MapSafeInsets(float windowW, float windowH, float safeX, float safeY, float safeW, float safeH, + float logicalW, float logicalH); + +// SDL_GetWindowSafeArea mapped through the renderer's logical presentation. +SafeInsets QuerySafeInsets(SDL_Window* window, SDL_Renderer* renderer); + +} // namespace ava2::platform diff --git a/src/eter_sound/SoundManager.cpp b/src/eter_sound/SoundManager.cpp index 818771b3..9381667b 100644 --- a/src/eter_sound/SoundManager.cpp +++ b/src/eter_sound/SoundManager.cpp @@ -87,6 +87,12 @@ bool SoundManager::Initialize() { return true; } +void SoundManager::SetPaused(bool paused) { + if (m_deviceId == 0) return; + if (paused) SDL_PauseAudioDevice(m_deviceId); + else SDL_ResumeAudioDevice(m_deviceId); +} + void SoundManager::Destroy() { if (!m_initialized) return; m_initialized = false; diff --git a/src/eter_sound/SoundManager.h b/src/eter_sound/SoundManager.h index f359237f..e10bae31 100644 --- a/src/eter_sound/SoundManager.h +++ b/src/eter_sound/SoundManager.h @@ -26,6 +26,8 @@ public: void Destroy(); bool IsInitialized() const { return m_initialized; } bool HasAudioDevice() const { return m_deviceId != 0; } + // Application background (platform::Lifecycle): stops the device without dropping streams. + void SetPaused(bool paused); // Frame update for music fades, 3D stream lifetimes, and looping void Update(float dt = 0.016f); diff --git a/src/scripting/python_touch.cpp b/src/scripting/python_touch.cpp index fe3122c4..12db986f 100644 --- a/src/scripting/python_touch.cpp +++ b/src/scripting/python_touch.cpp @@ -54,6 +54,14 @@ PyObject* touch_get_layout(PyObject*, PyObject*) { l.joy_x, l.joy_y, l.joy_w, l.joy_h, l.joy_radius); } +// (left, top, right, bottom) insets of the unobstructed screen area in UI pixels (notch, +// rounded corners, gesture bar); 0 on desktop. +PyObject* touch_get_safe_area(PyObject*, PyObject*) { + const auto& l = GetTouchRouter().GetLayout(); + return Py_BuildValue("(iiii)", int(l.safe_left + 0.5f), int(l.safe_top + 0.5f), + int(l.safe_right + 0.5f), int(l.safe_bottom + 0.5f)); +} + } // namespace void inittouch() { @@ -64,6 +72,7 @@ void inittouch() { {"SetAttackButton", touch_set_attack_button, METH_VARARGS, nullptr}, {"SetJoystickArea", touch_set_joystick_area, METH_VARARGS, nullptr}, {"GetLayout", touch_get_layout, METH_NOARGS, nullptr}, + {"GetSafeArea", touch_get_safe_area, METH_NOARGS, nullptr}, {nullptr, nullptr, 0, nullptr} }; Py_InitModule("touch", methods); diff --git a/tests/platform_test.cpp b/tests/platform_test.cpp new file mode 100644 index 00000000..9048b0b5 --- /dev/null +++ b/tests/platform_test.cpp @@ -0,0 +1,88 @@ +// platform/ (mobile step 2): lifecycle transitions, safe-area mapping into the letterboxed UI and +// the touch layout kept inside the safe insets. +#include "app/platform/platform.h" +#include "app/input/touch_router.h" +#include +#include +#include +#include + +namespace { + +using ava2::platform::Lifecycle; +using ava2::platform::MapSafeInsets; +using ava2::platform::SafeInsets; + +bool Near(float a, float b) { return std::fabs(a - b) < 0.01f; } + +void TestLifecycle() { + Lifecycle l; + assert(l.Poll() == Lifecycle::Change::None && !l.IsBackground()); + // Android sends WILL and DID together; one transition. + l.OnEvent(SDL_EVENT_WILL_ENTER_BACKGROUND); + l.OnEvent(SDL_EVENT_DID_ENTER_BACKGROUND); + assert(l.IsBackground()); + assert(l.Poll() == Lifecycle::Change::EnterBackground); + assert(l.Poll() == Lifecycle::Change::None); + l.OnEvent(SDL_EVENT_WILL_ENTER_FOREGROUND); + l.OnEvent(SDL_EVENT_DID_ENTER_FOREGROUND); + assert(!l.IsBackground()); + assert(l.Poll() == Lifecycle::Change::EnterForeground); + assert(l.Poll() == Lifecycle::Change::None); + // A pause and resume between two frames still reports both, background first. + l.OnEvent(SDL_EVENT_DID_ENTER_BACKGROUND); + l.OnEvent(SDL_EVENT_DID_ENTER_FOREGROUND); + assert(l.Poll() == Lifecycle::Change::EnterBackground); + assert(l.Poll() == Lifecycle::Change::EnterForeground); + assert(!l.IsBackground()); + // Foreground without background is ignored. + l.OnEvent(SDL_EVENT_DID_ENTER_FOREGROUND); + assert(l.Poll() == Lifecycle::Change::None); + assert(!l.TakeLowMemory()); + l.OnEvent(SDL_EVENT_LOW_MEMORY); + assert(l.TakeLowMemory() && !l.TakeLowMemory()); + assert(!l.IsTerminating()); + l.OnEvent(SDL_EVENT_TERMINATING); + assert(l.IsTerminating()); +} + +void TestSafeInsets() { + // Full safe area: no insets. + SafeInsets none = MapSafeInsets(1280, 720, 0, 0, 1280, 720, 1280, 720); + assert(none == SafeInsets{}); + // 20:9 phone (2400x1080 window points) showing a 16:9 UI 1280x720 letterboxed: scale 1.5, + // bars of 240 px left/right. A 100 px notch on the left lies inside the bar -> no inset. + SafeInsets bar = MapSafeInsets(2400, 1080, 100, 0, 2300, 1080, 1280, 720); + assert(bar == SafeInsets{}); + // Same screen with a UI as wide as the window (2400x1080 logical = 1:1): the notch shows. + SafeInsets wide = MapSafeInsets(2400, 1080, 100, 0, 2240, 1040, 2400, 1080); + assert(Near(wide.left, 100) && Near(wide.top, 0) && Near(wide.right, 60) && Near(wide.bottom, 40)); + // Scaled: 1600x720 UI in a 2400x1080 window (scale 1.5); a 150 px cutout is 100 UI px. + SafeInsets scaled = MapSafeInsets(2400, 1080, 150, 0, 2250, 1035, 1600, 720); + assert(Near(scaled.left, 100) && Near(scaled.right, 0) && Near(scaled.bottom, 30)); + // Degenerate input. + assert(MapSafeInsets(0, 0, 0, 0, 0, 0, 1280, 720) == SafeInsets{}); +} + +void TestTouchLayout() { + using ava2::input::TouchLayout; + const TouchLayout plain = TouchLayout::ForScreen(1600, 720); + const TouchLayout safe = TouchLayout::ForScreen(1600, 720, 100, 0, 60, 30); + assert(Near(safe.safe_left, 100) && Near(safe.safe_right, 60) && Near(safe.safe_bottom, 30)); + assert(Near(safe.joy_x, plain.joy_x + 100)); + assert(Near(safe.attack_x, plain.attack_x - 60) && Near(safe.attack_y, plain.attack_y - 30)); + assert(Near(safe.attack_r, plain.attack_r)); + // The attack circle stays inside the safe area. + assert(safe.attack_x + safe.attack_r <= 1600 - 60 && safe.attack_y + safe.attack_r <= 720 - 30); + assert(safe.joy_y + safe.joy_h <= 720 - 30 + 0.01f); +} + +} // namespace + +int main() { + TestLifecycle(); + TestSafeInsets(); + TestTouchLayout(); + std::cout << "Platform lifecycle and safe area insets behave\n"; + return 0; +} diff --git a/tests/touch_game_test.cpp b/tests/touch_game_test.cpp index 55f21a86..8d9bf370 100644 --- a/tests/touch_game_test.cpp +++ b/tests/touch_game_test.cpp @@ -118,6 +118,18 @@ int main(int argc, char** argv) { router.FingerUp(4, W * 0.6f, H * 0.4f, 450); assert(sink.taps == 1); + // Safe area (platform/): desktop has none; a HUD built with insets keeps the attack button inside. + runtime.execute("assert touch.GetSafeArea() == (0, 0, 0, 0)\n"); + router.SetLayout(ava2::input::TouchLayout::ForScreen(W, H, 40.0f, 0.0f, 30.0f, 20.0f)); + runtime.execute("assert touch.GetSafeArea() == (40, 0, 30, 20)\n" + "import ui_mobile_hud\n" + "safe_hud = ui_mobile_hud.MobileHUD(game.interface)\n" + "(ax, ay, ar), joy = touch.GetLayout()\n" + "assert (ax, ay, ar) == (1024 - 30 - 120, 768 - 20 - 120, 60), (ax, ay, ar)\n" + "assert safe_hud.player_hud.GetGlobalPosition()[0] == 40 + 25\n" + "safe_hud.Hide()\nsafe_hud = None\n"); + router.SetLayout(layout); + SDL_FillSurfaceRect(surface, nullptr, 0xff10141e); wm->Render(); SDL_RenderPresent(renderer); if (argc > 3) SDL_SaveBMP(surface, argv[3]); diff --git a/upstream/python-root/ui_mobile_combat.py b/upstream/python-root/ui_mobile_combat.py index cb54a248..67d5693e 100644 --- a/upstream/python-root/ui_mobile_combat.py +++ b/upstream/python-root/ui_mobile_combat.py @@ -27,10 +27,12 @@ class MobileCombatWheel(ui.Window): sw = wndMgr.GetScreenWidth() sh = wndMgr.GetScreenHeight() + # 安全区(刘海/圆角/手势条)内缩,桌面为 0 + safe_l, safe_t, safe_r, safe_b = touch.GetSafeArea() if origin_x is None: - origin_x = sw - 120 + origin_x = sw - safe_r - 120 if origin_y is None: - origin_y = sh - 120 + origin_y = sh - safe_b - 120 self.origin_x = origin_x self.origin_y = origin_y diff --git a/upstream/python-root/ui_mobile_drawer.py b/upstream/python-root/ui_mobile_drawer.py index ec56603f..6b895b7f 100644 --- a/upstream/python-root/ui_mobile_drawer.py +++ b/upstream/python-root/ui_mobile_drawer.py @@ -2,6 +2,7 @@ import ui import grp import wndMgr +import touch class MobileDrawer(ui.Window): """ @@ -17,7 +18,8 @@ class MobileDrawer(ui.Window): sw = wndMgr.GetScreenWidth() self.sw = sw - self.SetPosition(sw - 380, 15) + safe_l, safe_t, safe_r, safe_b = touch.GetSafeArea() + self.SetPosition(sw - safe_r - 380, safe_t + 15) self.SetSize(360, 240) self.AddFlag("attach") diff --git a/upstream/python-root/ui_mobile_hud.py b/upstream/python-root/ui_mobile_hud.py index 28c7c919..3e6dfb73 100644 --- a/upstream/python-root/ui_mobile_hud.py +++ b/upstream/python-root/ui_mobile_hud.py @@ -10,6 +10,7 @@ import math import ui_mobile_joystick import ui_mobile_combat import ui_mobile_drawer +import touch class MobileHUD(ui.Window): """ @@ -35,6 +36,7 @@ class MobileHUD(ui.Window): self.AddFlag("attach") self.AddFlag("not_pick") + self.safe_area = touch.GetSafeArea() self.__BuildUI(sw, sh) def __del__(self): @@ -46,7 +48,8 @@ class MobileHUD(ui.Window): # --------------------------------------------------------------------- self.player_hud = ui.Window() self.player_hud.SetParent(self) - self.player_hud.SetPosition(25, 20) + safe_l, safe_t, safe_r, safe_b = self.safe_area + self.player_hud.SetPosition(safe_l + 25, safe_t + 20) self.player_hud.SetSize(320, 100) self.player_hud.Show() @@ -108,7 +111,7 @@ class MobileHUD(ui.Window): # --------------------------------------------------------------------- self.target_hud = ui.Window() self.target_hud.SetParent(self) - self.target_hud.SetPosition((w - 420) / 2, 20) + self.target_hud.SetPosition((w - 420) / 2, safe_t + 20) self.target_hud.SetSize(420, 50) self.target_bg = ui.Bar() @@ -155,7 +158,7 @@ class MobileHUD(ui.Window): # --------------------------------------------------------------------- # 5. 右下角:核心战斗轮盘 (Mobile Combat Wheel) # --------------------------------------------------------------------- - self.combat_wheel = ui_mobile_combat.MobileCombatWheel(origin_x=w - 120, origin_y=h - 120) + self.combat_wheel = ui_mobile_combat.MobileCombatWheel(origin_x=w - safe_r - 120, origin_y=h - safe_b - 120) self.combat_wheel.SetParent(self) self.combat_wheel.Show() @@ -164,7 +167,7 @@ class MobileHUD(ui.Window): # --------------------------------------------------------------------- self.quick_belt = ui.Window() self.quick_belt.SetParent(self) - self.quick_belt.SetPosition((w - 360) / 2, h - 70) + self.quick_belt.SetPosition((w - 360) / 2, h - safe_b - 70) self.quick_belt.SetSize(360, 60) self.quick_belt.Show()