Add touch input router for mobile (step 3)

Route each finger to UI, the attack button, a floating lower-left joystick or
the camera (drag rotate, pinch zoom, tap = world click). Touch mode is default
on Android/iOS and available on desktop via --touch / AVA2_TOUCH=1; it disables
SDL touch-to-mouse and drives app.ENABLE_MOBILE_HUD. The joystick feeds the
original camera-relative movement path and the attack button sets the same
attack-key state as player.SetAttackKeyState. New `touch` Python module; the
mobile HUD joystick and combat wheel become display-only.

Tests: ava2.touch_router, ava2.touch_game (GameWindow + mobile HUD).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-12 19:46:24 +09:00
co-authored by Claude Opus 5.5
parent 1dfdcba739
commit 5597842d90
18 changed files with 978 additions and 103 deletions
+222
View File
@@ -0,0 +1,222 @@
#include "touch_router.h"
#include <algorithm>
#include <cmath>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
namespace ava2::input {
TouchLayout TouchLayout::ForScreen(float w, float h) {
TouchLayout layout;
layout.screen_w = w;
layout.screen_h = h;
const float unit = std::min(w, h);
layout.joy_x = 0.0f;
layout.joy_y = h * 0.45f;
layout.joy_w = w * 0.40f;
layout.joy_h = h * 0.55f;
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.tap_slop = unit * 0.02f;
return layout;
}
void TouchRouter::SetWorldEnabled(bool enabled) {
if (enabled == m_world) return;
// Phase change: world fingers would otherwise keep a stale joystick or attack state.
if (!enabled) {
for (auto it = m_fingers.begin(); it != m_fingers.end();) {
if (it->second.owner != Owner::Ui) {
Release(it->first, it->second, true);
it = m_fingers.erase(it);
} else {
++it;
}
}
}
m_world = enabled;
}
bool TouchRouter::InAttack(float x, float y) const {
if (m_layout.attack_r <= 0.0f) return false;
const float dx = x - m_layout.attack_x, dy = y - m_layout.attack_y;
return dx * dx + dy * dy <= m_layout.attack_r * m_layout.attack_r;
}
bool TouchRouter::InJoystickArea(float x, float y) const {
return x >= m_layout.joy_x && x < m_layout.joy_x + m_layout.joy_w &&
y >= m_layout.joy_y && y < m_layout.joy_y + m_layout.joy_h;
}
void TouchRouter::UpdateJoystick(float x, float y) {
const float r = m_layout.joy_radius;
float dx = x - m_joy.base_x, dy = y - m_joy.base_y;
const float dist = std::sqrt(dx * dx + dy * dy);
if (dist > r && dist > 0.0f) {
dx *= r / dist;
dy *= r / dist;
}
m_joy.knob_x = m_joy.base_x + dx;
m_joy.knob_y = m_joy.base_y + dy;
if (!m_sink) return;
const float len = std::min(dist, r) / r;
if (len < m_layout.joy_dead_zone)
m_sink->Joystick(true, 0.0f, 0.0f);
else
m_sink->Joystick(true, dx / r, dy / r);
}
TouchRouter::Finger* TouchRouter::OtherCameraFinger(std::uint64_t id) {
for (auto& [other, finger] : m_fingers)
if (other != id && finger.owner == Owner::Camera) return &finger;
return nullptr;
}
void TouchRouter::FingerDown(std::uint64_t raw_id, float x, float y, std::uint64_t ms) {
const std::uint64_t id = raw_id + 1;
if (m_fingers.count(id)) return;
Finger finger;
finger.x = finger.start_x = x;
finger.y = finger.start_y = y;
finger.start_ms = ms;
const bool ui = m_sink && m_sink->IsUiAt(x, y);
if (!m_world || ui) {
// wndMgr tracks a single pointer; further fingers on UI are ignored.
if (m_ui_finger || !m_sink) return;
finger.owner = Owner::Ui;
m_ui_finger = id;
m_fingers[id] = finger;
m_sink->UiMouseMove(x, y);
m_sink->UiMouseDown(x, y);
return;
}
if (!m_attack_finger && InAttack(x, y)) {
finger.owner = Owner::Attack;
m_attack_finger = id;
m_fingers[id] = finger;
if (m_sink) m_sink->Attack(true);
return;
}
if (!m_joy_finger && InJoystickArea(x, y)) {
finger.owner = Owner::Joystick;
m_joy_finger = id;
m_fingers[id] = finger;
const float r = m_layout.joy_radius;
m_joy.active = true;
m_joy.base_x = std::clamp(x, r, std::max(r, m_layout.screen_w - r));
m_joy.base_y = std::clamp(y, r, std::max(r, m_layout.screen_h - r));
UpdateJoystick(x, y);
return;
}
finger.owner = Owner::Camera;
if (Finger* other = OtherCameraFinger(id)) {
// Second camera finger: a pinch, neither finger can still be a tap.
other->tap = false;
finger.tap = false;
}
m_fingers[id] = finger;
}
void TouchRouter::FingerMove(std::uint64_t raw_id, float x, float y, std::uint64_t) {
const std::uint64_t id = raw_id + 1;
auto it = m_fingers.find(id);
if (it == m_fingers.end()) return;
Finger& finger = it->second;
const float prev_x = finger.x, prev_y = finger.y;
finger.x = x;
finger.y = y;
switch (finger.owner) {
case Owner::Ui:
if (m_sink) m_sink->UiMouseMove(x, y);
break;
case Owner::Attack:
break;
case Owner::Joystick:
UpdateJoystick(x, y);
break;
case Owner::Camera: {
if (Finger* other = OtherCameraFinger(id)) {
const float before = std::hypot(prev_x - other->x, prev_y - other->y);
const float after = std::hypot(x - other->x, y - other->y);
if (before > 1.0f && after > 1.0f && m_sink) m_sink->CameraZoom(after / before);
break;
}
if (finger.tap) {
if (std::hypot(x - finger.start_x, y - finger.start_y) <= m_layout.tap_slop) break;
finger.tap = false;
// The slop distance is part of the drag so the camera does not jump.
if (m_sink) m_sink->CameraRotate(x - finger.start_x, y - finger.start_y);
break;
}
if (m_sink) m_sink->CameraRotate(x - prev_x, y - prev_y);
break;
}
}
}
void TouchRouter::Release(std::uint64_t id, Finger& finger, bool cancelled) {
switch (finger.owner) {
case Owner::Ui:
m_ui_finger = 0;
// A cancelled UI finger still releases the button so no window keeps the capture.
if (m_sink) m_sink->UiMouseUp(finger.x, finger.y);
break;
case Owner::Attack:
m_attack_finger = 0;
if (m_sink) m_sink->Attack(false);
break;
case Owner::Joystick:
m_joy_finger = 0;
m_joy = JoystickView{};
if (m_sink) m_sink->Joystick(false, 0.0f, 0.0f);
break;
case Owner::Camera:
if (!cancelled && finger.tap && m_sink) m_sink->WorldTap(finger.x, finger.y);
break;
}
(void)id;
}
void TouchRouter::FingerUp(std::uint64_t raw_id, float x, float y, std::uint64_t ms) {
const std::uint64_t id = raw_id + 1;
auto it = m_fingers.find(id);
if (it == m_fingers.end()) return;
Finger finger = it->second;
m_fingers.erase(it);
finger.x = x;
finger.y = y;
if (finger.owner == Owner::Ui && m_sink) m_sink->UiMouseMove(x, y);
if (finger.owner == Owner::Camera && finger.tap &&
(ms - finger.start_ms > m_layout.tap_ms ||
std::hypot(x - finger.start_x, y - finger.start_y) > m_layout.tap_slop))
finger.tap = false;
Release(id, finger, false);
}
void TouchRouter::CancelAll() {
for (auto& [id, finger] : m_fingers) Release(id, finger, true);
m_fingers.clear();
}
TouchRouter& GetTouchRouter() {
static TouchRouter router;
return router;
}
namespace {
#if defined(__ANDROID__) || (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
bool s_touch_mode = true;
#else
bool s_touch_mode = false;
#endif
} // namespace
bool IsTouchMode() { return s_touch_mode; }
void SetTouchMode(bool enabled) { s_touch_mode = enabled; }
} // namespace ava2::input
+109
View File
@@ -0,0 +1,109 @@
#pragma once
// Touch input router for the mobile client (docs/MOBILE-ARCHITECTURE.md, input/).
//
// Every finger is assigned an owner when it goes down and keeps it until it lifts:
//
// UI window under the finger -> mouse events for the window manager (one finger at a time)
// attack button circle -> attack key held while the finger is down
// joystick area (lower left) -> floating virtual joystick, camera-relative movement
// anything else -> one finger drags the camera, two fingers pinch-zoom,
// a short tap clicks the game world (target / ground)
//
// Outside the game phase only the UI owner exists. Coordinates are UI pixels (the same space as
// wndMgr). The router has no SDL or game dependencies; the host implements TouchSink.
#include <cstdint>
#include <map>
namespace ava2::input {
struct TouchSink {
virtual ~TouchSink() = default;
// True when a UI window other than the full-screen game window is under the point.
virtual bool IsUiAt(float x, float y) = 0;
virtual void UiMouseMove(float x, float y) = 0;
virtual void UiMouseDown(float x, float y) = 0;
virtual void UiMouseUp(float x, float y) = 0;
// Short tap on the game world: the host clicks there as the original left button would.
virtual void WorldTap(float x, float y) = 0;
// Joystick vector in screen axes (x right, y down), length 0..1; active=false releases it.
virtual void Joystick(bool active, float x, float y) = 0;
virtual void Attack(bool pressed) = 0;
// Camera drag in UI pixels since the last call.
virtual void CameraRotate(float dx, float dy) = 0;
// Pinch ratio since the last call: > 1 fingers moved apart (zoom in).
virtual void CameraZoom(float ratio) = 0;
};
struct TouchLayout {
float screen_w = 1280.0f, screen_h = 720.0f;
// Joystick area; the stick centres where the finger lands inside it.
float joy_x = 0.0f, joy_y = 0.0f, joy_w = 0.0f, joy_h = 0.0f;
float joy_radius = 80.0f; // full deflection distance
float joy_dead_zone = 0.18f; // fraction of joy_radius treated as centred
// Attack button circle; radius 0 disables it.
float attack_x = 0.0f, attack_y = 0.0f, attack_r = 0.0f;
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);
};
struct JoystickView {
bool active = false;
float base_x = 0.0f, base_y = 0.0f; // where the finger landed (clamped on screen)
float knob_x = 0.0f, knob_y = 0.0f; // knob centre, at most joy_radius from the base
};
class TouchRouter {
public:
enum class Owner { Ui, Attack, Joystick, Camera };
void SetSink(TouchSink* sink) { m_sink = sink; }
void SetLayout(const TouchLayout& layout) { m_layout = layout; }
const TouchLayout& GetLayout() const { return m_layout; }
// World controls (joystick, attack, camera, world taps) exist only in the game phase.
void SetWorldEnabled(bool enabled);
bool IsWorldEnabled() const { return m_world; }
void FingerDown(std::uint64_t id, float x, float y, std::uint64_t ms);
void FingerMove(std::uint64_t id, float x, float y, std::uint64_t ms);
void FingerUp(std::uint64_t id, float x, float y, std::uint64_t ms);
// Lost focus / app paused: release everything without taps or clicks.
void CancelAll();
JoystickView GetJoystick() const { return m_joy; }
bool IsAttackPressed() const { return m_attack_finger != 0; }
std::size_t FingerCount() const { return m_fingers.size(); }
private:
struct Finger {
Owner owner = Owner::Ui;
float x = 0.0f, y = 0.0f; // last position
float start_x = 0.0f, start_y = 0.0f;
std::uint64_t start_ms = 0;
bool tap = true; // still a tap candidate (camera fingers)
};
bool InAttack(float x, float y) const;
bool InJoystickArea(float x, float y) const;
void UpdateJoystick(float x, float y);
Finger* OtherCameraFinger(std::uint64_t id);
void Release(std::uint64_t id, Finger& finger, bool cancelled);
TouchSink* m_sink = nullptr;
TouchLayout m_layout;
bool m_world = false;
std::map<std::uint64_t, Finger> m_fingers; // ids are offset by one so 0 means "none"
std::uint64_t m_ui_finger = 0, m_joy_finger = 0, m_attack_finger = 0;
JoystickView m_joy;
};
// The client's router, shared by the host loop and the Python `touch` module.
TouchRouter& GetTouchRouter();
// Touch mode: on for Android/iOS, or desktop with --touch (mouse emulates one finger).
bool IsTouchMode();
void SetTouchMode(bool enabled);
} // namespace ava2::input
+112 -3
View File
@@ -36,6 +36,7 @@
#include "python_ime.h"
#include "player_settings.h"
#include "eter_render/RaceData.h"
#include "app/input/touch_router.h"
#endif
#include <algorithm>
#include <array>
@@ -235,7 +236,7 @@ int main(int argc, char** argv) {
float render_scale = 1.0f;
#endif
bool auto_connect = false, until_loading = false, until_select = false, until_game = false;
bool use_gpu_raster = true, preview_data = false;
bool use_gpu_raster = true, preview_data = false, touch_flag = false;
std::string stdlib, script_root, view_script, screenshot, game_script, frame_profile;
bool game_script_executed = false;
std::string start_phase = "login";
@@ -270,9 +271,17 @@ int main(int argc, char** argv) {
else if (arg == "--game-frames") game_frames = std::max(1, std::stoi(next()));
else if (arg == "--preview-data") preview_data = true;
else if (arg == "--software-raster") use_gpu_raster = false;
else throw std::invalid_argument("Usage: ava2_client [--frames N] [--fps-cap N] [--render-scale 0.25..1] [--stdlib ZIP --python-root DIR] [--login-ui SCRIPT | --phase login|select|create|loading|game] [--auth-host HOST --auth-port PORT --game-host HOST --game-port PORT --account ACCOUNT] [--auto-connect] [--auto-select 0..4] [--until-select|--until-loading|--until-game] [--game-script FILE.py] [--software-raster] [--screenshot FILE.bmp]");
else if (arg == "--touch") touch_flag = true;
else throw std::invalid_argument("Usage: ava2_client [--frames N] [--fps-cap N] [--render-scale 0.25..1] [--stdlib ZIP --python-root DIR] [--login-ui SCRIPT | --phase login|select|create|loading|game] [--auth-host HOST --auth-port PORT --game-host HOST --game-port PORT --account ACCOUNT] [--auto-connect] [--auto-select 0..4] [--until-select|--until-loading|--until-game] [--game-script FILE.py] [--software-raster] [--touch] [--screenshot FILE.bmp]");
}
#ifdef AVA2_HAS_PYTHON
// Before the Python runtime starts: app.ENABLE_MOBILE_HUD follows the touch mode.
if (const char* env = std::getenv("AVA2_TOUCH"); touch_flag || (env && std::strcmp(env, "0") != 0))
ava2::input::SetTouchMode(true);
#else
(void)touch_flag;
#endif
if (fps_cap < 0) {
if (const char* env = std::getenv("MT_FPS_CAP")) fps_cap = std::max(0, std::atoi(env));
else if (const char* env = std::getenv("AVA2_FPS_CAP")) fps_cap = std::max(0, std::atoi(env));
@@ -353,6 +362,15 @@ int main(int argc, char** argv) {
#ifdef AVA2_HAS_PYTHON
// WinMain: srandom(time(NULL) + DWORD(GetCurrentProcess())) for EterBase random_range.
eter::srandom(uint32_t(std::time(nullptr)) + std::random_device{}());
#endif
#ifdef AVA2_HAS_PYTHON
// Touch mode: fingers go through the touch router instead of SDL's touch-to-mouse emulation.
// On desktop (--touch) the mouse emulates one finger.
const bool touch_mode = ava2::input::IsTouchMode();
if (touch_mode) {
SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0");
SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "1");
}
#endif
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS)) throw std::runtime_error(SDL_GetError());
struct Quit { ~Quit(){ SDL_Quit(); } } quit;
@@ -669,6 +687,62 @@ int main(int argc, char** argv) {
orbit_camera.SetYaw(0.0f);
orbit_camera.SetTargetHeight(120.0f);
#ifdef AVA2_HAS_PYTHON
// Touch router sink: fingers become wndMgr mouse events, the joystick and attack key of the
// original player module, and orbit camera drags / pinches.
struct HostTouchSink final : ava2::input::TouchSink {
UI::CWindowManager* wm = nullptr;
ava2::OrbitCamera* camera = nullptr;
bool release_pending = false; // world tap: button goes up on the next frame
float release_x = 0.0f, release_y = 0.0f;
bool IsUiAt(float x, float y) override {
if (!wm) return false;
auto* window = wm->PickWindow(long(x), long(y));
return window && !ava2::IsPlayerGameWindow(window->GetHandler());
}
void UiMouseMove(float x, float y) override { if (wm) wm->RunMouseMove(long(x), long(y)); }
void UiMouseDown(float x, float y) override { if (wm) wm->RunMouseLeftButtonDown(long(x), long(y)); }
void UiMouseUp(float x, float y) override { if (wm) wm->RunMouseLeftButtonUp(long(x), long(y)); }
void WorldTap(float x, float y) override {
if (!wm) return;
// GameWindow.OnMouseLeftButtonDown sets player.SetMouseState; holding it for one
// game update picks the target or ground under the finger like a mouse click.
FlushRelease();
wm->RunMouseMove(long(x), long(y));
wm->RunMouseLeftButtonDown(long(x), long(y));
release_pending = true;
release_x = x;
release_y = y;
}
void FlushRelease() {
if (!release_pending || !wm) return;
release_pending = false;
wm->RunMouseLeftButtonUp(long(release_x), long(release_y));
}
void Joystick(bool active, float x, float y) override { ava2::SetPlayerJoystick(active, x, y); }
void Attack(bool pressed) override { ava2::SetPlayerAttackKey(pressed); }
void CameraRotate(float dx, float dy) override {
camera->SetYaw(camera->GetYaw() + dx * 0.25f);
camera->SetPitch(camera->GetPitch() - dy * 0.25f);
}
void CameraZoom(float ratio) override { camera->SetDistance(camera->GetDistance() / ratio); }
} touch_sink;
touch_sink.wm = wm;
touch_sink.camera = &orbit_camera;
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)));
}
// Finger position in UI pixels (SDL gives it normalized to the window).
auto finger_point = [&](const SDL_TouchFingerEvent& finger, float& x, float& y) {
int ww = 0, wh = 0;
SDL_GetWindowSize(window.get(), &ww, &wh);
SDL_RenderCoordinatesFromWindow(renderer.get(), finger.x * float(ww), finger.y * float(wh), &x, &y);
};
#endif
// Initialize Minimap Radar System
ava2::MinimapManager minimap_mgr;
minimap_mgr.SetWorldBounds(outdoor_terrain.GetWorldMinX(), outdoor_terrain.GetWorldMaxX(),
@@ -1224,6 +1298,12 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
if (want != SDL_TextInputActive(window.get()))
want ? SDL_StartTextInput(window.get()) : SDL_StopTextInput(window.get());
}
#endif
#ifdef AVA2_HAS_PYTHON
if (touch_mode) {
touch_sink.FlushRelease();
touch_router.SetWorldEnabled(last_phase == "game");
}
#endif
SDL_Event event;
while (SDL_PollEvent(&event)) {
@@ -1232,8 +1312,37 @@ const auto profileActiveStart = std::chrono::steady_clock::now();
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;
if (touch_mode) touch_router.CancelAll();
}
if (wm) {
if (touch_mode) {
float tx = 0.0f, ty = 0.0f;
const std::uint64_t tms = event.common.timestamp / 1000000;
switch (event.type) {
case SDL_EVENT_FINGER_DOWN:
finger_point(event.tfinger, tx, ty);
touch_router.FingerDown(event.tfinger.fingerID, tx, ty, tms);
break;
case SDL_EVENT_FINGER_MOTION:
finger_point(event.tfinger, tx, ty);
touch_router.FingerMove(event.tfinger.fingerID, tx, ty, tms);
break;
case SDL_EVENT_FINGER_UP:
finger_point(event.tfinger, tx, ty);
touch_router.FingerUp(event.tfinger.fingerID, tx, ty, tms);
break;
case SDL_EVENT_FINGER_CANCELED:
touch_router.CancelAll();
break;
default:
break;
}
}
// In touch mode the window manager only sees fingers; desktop mouse input arrives
// a second time as the emulated finger.
const bool touch_owns_mouse = touch_mode &&
(event.type == SDL_EVENT_MOUSE_MOTION || event.type == SDL_EVENT_MOUSE_BUTTON_DOWN ||
event.type == SDL_EVENT_MOUSE_BUTTON_UP);
if (wm && !touch_owns_mouse) {
if (event.type == SDL_EVENT_MOUSE_MOTION) {
float mx, my;
SDL_RenderCoordinatesFromWindow(renderer.get(), event.motion.x, event.motion.y, &mx, &my);