UI/GL thread split like Android, lifecycle pause/resume, safe quit, video playback, control mode for play-testing, crash marker

This commit is contained in:
CRTkafa 2026-10-15 20:50:09 +08:00
parent fb5f17c076
commit 4f0bb5fe2e
5 changed files with 287 additions and 37 deletions

View file

@ -31,8 +31,14 @@ static void vlog(const char* fmt, va_list ap) {
if (g_logfile) { fprintf(g_logfile, "[%s] %s\n", t ? t->name.c_str() : "-", buf); fflush(g_logfile); } if (g_logfile) { fprintf(g_logfile, "[%s] %s\n", t ? t->name.c_str() : "-", buf); fflush(g_logfile); }
} }
void logf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(fmt, ap); va_end(ap); } void logf(const char* fmt, ...) { va_list ap; va_start(ap, fmt); vlog(fmt, ap); va_end(ap); }
std::string g_crash_marker;
void fatal(const char* fmt, ...) { void fatal(const char* fmt, ...) {
va_list ap; va_start(ap, fmt); vlog(fmt, ap); va_end(ap); va_list ap; va_start(ap, fmt); vlog(fmt, ap); va_end(ap);
if (!g_crash_marker.empty()) {
char buf[1024];
va_start(ap, fmt); vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap);
if (FILE* f = fopen(g_crash_marker.c_str(), "w")) { fputs(buf, f); fclose(f); }
}
GThread* t = cur_thread(); GThread* t = cur_thread();
if (t && t->depth > 0) dump_backtrace(t->engines[t->depth - 1]); if (t && t->depth > 0) dump_backtrace(t->engines[t->depth - 1]);
fflush(nullptr); fflush(nullptr);

View file

@ -415,6 +415,8 @@ static std::vector<uint8_t> read_file(const std::string& p, bool* ok) {
static SDL_AudioStream* g_audio = nullptr; static SDL_AudioStream* g_audio = nullptr;
static int g_audio_rate = 44100, g_audio_channels = 2, g_audio_frames = 1024; static int g_audio_rate = 44100, g_audio_channels = 2, g_audio_frames = 1024;
static std::atomic<bool> g_audio_paused{false}; static std::atomic<bool> g_audio_paused{false};
std::atomic<uint64_t> g_audio_bytes{0};
std::atomic<int> g_audio_peak{0};
void jni_set_audio_stream(SDL_AudioStream* s) { g_audio = s; } void jni_set_audio_stream(SDL_AudioStream* s) { g_audio = s; }
void jni_audio_pause(bool p) { g_audio_paused = p; } void jni_audio_pause(bool p) { g_audio_paused = p; }
@ -535,6 +537,14 @@ static void register_java() {
uint32_t off = c.args[1].i, n = c.args[2].i; uint32_t off = c.args[1].i, n = c.args[2].i;
if (!g_audio || !arr) return JVal::I(n); if (!g_audio || !arr) return JVal::I(n);
uint32_t es = jelem_size(arr->elem); uint32_t es = jelem_size(arr->elem);
g_audio_bytes += n * es;
{
// peak level of this buffer, for diagnostics
auto* smp = (const int16_t*)g2h(arr->data + off * es);
int peak = 0;
for (uint32_t k = 0; k < n; k++) peak = std::max(peak, std::abs((int)smp[k]));
g_audio_peak = std::max<int>(g_audio_peak, peak);
}
SDL_PutAudioStreamData(g_audio, g2h(arr->data + off * es), (int)(n * es)); SDL_PutAudioStreamData(g_audio, g2h(arr->data + off * es), (int)(n * es));
// block like a real AudioTrack so the mixer runs at the playback rate // block like a real AudioTrack so the mixer runs at the playback rate
int limit = g_audio_frames * g_audio_channels * 2 * 3; int limit = g_audio_frames * g_audio_channels * 2 * 3;

View file

@ -325,7 +325,8 @@ void register_thread(GThread* t) {
} }
// ---------------------------------------------------------------- time helpers // ---------------------------------------------------------------- time helpers
static uint32_t g_tm = 0; // shared struct tm for localtime/gmtime static uint32_t g_tm = 0;
std::atomic<double> g_main_sleep_ms{0}; // shared struct tm for localtime/gmtime
static void write_tm(uint32_t g, const struct tm& t) { static void write_tm(uint32_t g, const struct tm& t) {
int32_t v[9] = {t.tm_sec, t.tm_min, t.tm_hour, t.tm_mday, t.tm_mon, t.tm_year, t.tm_wday, t.tm_yday, t.tm_isdst}; int32_t v[9] = {t.tm_sec, t.tm_min, t.tm_hour, t.tm_mday, t.tm_mon, t.tm_year, t.tm_wday, t.tm_yday, t.tm_isdst};
memcpy(g2h(g), v, sizeof v); memcpy(g2h(g), v, sizeof v);
@ -787,6 +788,7 @@ void libc_init() {
HLE(clock) { c.ret((uint32_t)(clock() * 1000000 / CLOCKS_PER_SEC)); }); HLE(clock) { c.ret((uint32_t)(clock() * 1000000 / CLOCKS_PER_SEC)); });
HLE(nanosleep) { HLE(nanosleep) {
uint32_t ts = c.u(); uint32_t ts = c.u();
if (cur_thread()->name == "main") g_main_sleep_ms += rd<int32_t>(ts) * 1000.0 + rd<int32_t>(ts + 4) / 1e6;
std::this_thread::sleep_for(std::chrono::seconds(rd<int32_t>(ts)) + std::chrono::nanoseconds(rd<int32_t>(ts + 4))); std::this_thread::sleep_for(std::chrono::seconds(rd<int32_t>(ts)) + std::chrono::nanoseconds(rd<int32_t>(ts + 4)));
c.ret(0); c.ret(0);
}); });

View file

@ -3,9 +3,18 @@
#include <OpenGL/gl.h> #include <OpenGL/gl.h>
#include <OpenGL/glext.h> #include <OpenGL/glext.h>
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include <fcntl.h>
#include <mach-o/dyld.h> #include <mach-o/dyld.h>
#include <signal.h>
#include <unistd.h>
#include <chrono> #include <chrono>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <deque>
#include <fstream>
#include <sstream>
#include <filesystem> #include <filesystem>
#include <thread> #include <thread>
@ -14,6 +23,10 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace sm { namespace sm {
extern std::string g_crash_marker;
extern std::atomic<double> g_main_sleep_ms;
extern std::atomic<uint64_t> g_audio_bytes;
extern std::atomic<int> g_audio_peak;
void video_set_muted(bool m); void video_set_muted(bool m);
void log_open(const std::string& path); void log_open(const std::string& path);
void register_thread(GThread* t); void register_thread(GThread* t);
@ -30,6 +43,7 @@ struct Options {
std::string shot_dir; std::string shot_dir;
std::string script; // scripted input: "frame:x,y;frame:x,y" std::string script; // scripted input: "frame:x,y;frame:x,y"
bool skip_video = false; bool skip_video = false;
std::string control_dir;
}; };
static uint32_t native(const char* name) { static uint32_t native(const char* name) {
@ -44,6 +58,47 @@ static uint32_t call_native(const char* name, std::vector<uint32_t> args) {
return (uint32_t)call_guest_v(a, args); return (uint32_t)call_guest_v(a, args);
} }
static std::string pending_shot;
// Android runs activity callbacks and touch input on the UI thread and rendering on the GL thread.
// The engine relies on that split (e.g. NativeOnPause waits for the render thread), so we keep it.
struct UiThread {
std::mutex m;
std::condition_variable cv;
std::deque<std::function<void()>> q;
void start() {
std::thread([this] {
GThread* t = thread_attach("ui", 2 << 20);
register_thread(t);
for (;;) {
std::function<void()> f;
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [&] { return !q.empty(); });
f = std::move(q.front());
q.pop_front();
}
f();
}
}).detach();
}
void post(std::function<void()> f) {
std::lock_guard<std::mutex> lk(m);
q.push_back(std::move(f));
cv.notify_one();
}
// runs f on the UI thread and waits for it
void run(std::function<void()> f) {
std::mutex dm;
std::condition_variable dcv;
bool done = false;
post([&] { f(); std::lock_guard<std::mutex> lk(dm); done = true; dcv.notify_one(); });
std::unique_lock<std::mutex> lk(dm);
dcv.wait(lk, [&] { return done; });
}
};
static UiThread ui;
static void save_png(const std::string& path, int w, int h) { static void save_png(const std::string& path, int w, int h) {
std::vector<uint8_t> px((size_t)w * h * 4); std::vector<uint8_t> px((size_t)w * h * 4);
glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, g_main_fbo); glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, g_main_fbo);
@ -83,6 +138,7 @@ int main(int argc, char** argv) {
else if (a == "--script") opt.script = next(); else if (a == "--script") opt.script = next();
else if (a == "--verbose") g_verbose = true; else if (a == "--verbose") g_verbose = true;
else if (a == "--skip-video") opt.skip_video = true; else if (a == "--skip-video") opt.skip_video = true;
else if (a == "--control") opt.control_dir = next();
else if (a == "--gl-trace") gl_set_trace(true); else if (a == "--gl-trace") gl_set_trace(true);
} }
// Locate the game data: --game, next to the app bundle, or next to the executable. // Locate the game data: --game, next to the app bundle, or next to the executable.
@ -106,6 +162,25 @@ int main(int argc, char** argv) {
logf("game dir %s, save dir %s", g_game_dir.c_str(), g_save_dir.c_str()); logf("game dir %s, save dir %s", g_game_dir.c_str(), g_save_dir.c_str());
if (opt.headless) SDL_SetHint(SDL_HINT_MAC_BACKGROUND_APP, "1"); if (opt.headless) SDL_SetHint(SDL_HINT_MAC_BACKGROUND_APP, "1");
// Crash reporting: a marker file written on fatal errors and host signals is shown on the next launch.
g_crash_marker = g_save_dir + "/last_crash.txt";
std::string previous_crash;
if (fs::exists(g_crash_marker)) {
std::ifstream in(g_crash_marker);
std::getline(in, previous_crash, '\0');
fs::remove(g_crash_marker);
}
static std::string s_marker = g_crash_marker;
for (int sig : {SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGABRT}) {
signal(sig, [](int sig) {
char msg[128];
int n = snprintf(msg, sizeof msg, "host crash: signal %d\n", sig);
write(2, msg, n);
int fd = open(s_marker.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd >= 0) { write(fd, msg, n); close(fd); }
_exit(128 + sig);
});
}
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) { logf("SDL_Init: %s", SDL_GetError()); return 1; } if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) { logf("SDL_Init: %s", SDL_GetError()); return 1; }
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
@ -120,6 +195,11 @@ int main(int argc, char** argv) {
SDL_GLContext gl = SDL_GL_CreateContext(win); SDL_GLContext gl = SDL_GL_CreateContext(win);
if (!gl) { logf("GL context: %s", SDL_GetError()); return 1; } if (!gl) { logf("GL context: %s", SDL_GetError()); return 1; }
SDL_GL_SetSwapInterval(opt.headless ? 0 : 1); SDL_GL_SetSwapInterval(opt.headless ? 0 : 1);
if (!previous_crash.empty() && !opt.headless) {
std::string m = "Spy Mouse closed unexpectedly last time:\n\n" + previous_crash +
"\n\nDetails are in ~/Library/Application Support/SpyMouse/spymouse.log";
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_WARNING, "Spy Mouse", m.c_str(), win);
}
logf("GL %s / %s", (const char*)glGetString(GL_VERSION), (const char*)glGetString(GL_RENDERER)); logf("GL %s / %s", (const char*)glGetString(GL_VERSION), (const char*)glGetString(GL_RENDERER));
// Offscreen surface that the game sees as the Android window. // Offscreen surface that the game sees as the Android window.
@ -155,38 +235,46 @@ int main(int argc, char** argv) {
GThread* main_t = thread_attach("main", 8 << 20); GThread* main_t = thread_attach("main", 8 << 20);
register_thread(main_t); register_thread(main_t);
g_lib = load_elf(g_game_dir + "/apk/lib/armeabi/libSpyMouse.so", LIB_BASE); ui.start();
for (uint32_t fn : g_lib.init_array) {
if (fn == 0 || fn == 0xffffffff) continue;
call_guest(fn, {});
}
logf("static constructors done");
uint32_t env = jni_env(); uint32_t env = jni_env();
if (uint32_t onload = g_lib.sym("JNI_OnLoad")) logf("JNI_OnLoad -> %x", (uint32_t)call_guest(onload, {jni_vm(), 0}));
auto cls = [](const char* n) { return jclass(n); }; auto cls = [](const char* n) { return jclass(n); };
uint32_t touchCls = cls("com/ea/blast/TouchSurfaceAndroid"); uint32_t touchCls = cls("com/ea/blast/TouchSurfaceAndroid");
uint32_t kDown = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerDown", {env, touchCls}); uint32_t kDown = 0, kUp = 0, kMove = 0, kTouch = 0;
uint32_t kUp = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerUp", {env, touchCls}); ui.run([&] {
uint32_t kMove = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerMove", {env, touchCls}); g_lib = load_elf(g_game_dir + "/apk/lib/armeabi/libSpyMouse.so", LIB_BASE);
uint32_t kTouch = call_native("Java_com_ea_blast_ModuleCatalog_NativeGetModuleTypeIdTouchScreen", {env, cls("com/ea/blast/ModuleCatalog")}); for (uint32_t fn : g_lib.init_array) {
g_orientation_normal = call_native("Java_com_ea_blast_DisplayAndroidDelegate_NativeGetOrientationNormal", {env, cls("com/ea/blast/DisplayAndroidDelegate")}); if (fn == 0 || fn == 0xffffffff) continue;
logf("touch ids down=%u up=%u move=%u module=%u", kDown, kUp, kMove, kTouch); call_guest(fn, {});
}
logf("static constructors done");
uint32_t files = jstring("/data/data/com.ea.spymouse_carrier/files"), ext = jstring("/sdcard"); if (uint32_t onload = g_lib.sym("JNI_OnLoad")) logf("JNI_OnLoad -> %x", (uint32_t)call_guest(onload, {jni_vm(), 0}));
call_native("Java_com_ea_EAIO_EAIO_StartupNativeImpl", {env, cls("com/ea/EAIO/EAIO"), g_asset_manager, files, ext});
call_native("Java_com_ea_EAMIO_StorageDirectory_StartupNativeImpl", {env, cls("com/ea/EAMIO/StorageDirectory")}); kDown = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerDown", {env, touchCls});
call_native("Java_com_ea_blast_MainActivity_NativeOnCreate", {env, g_activity}); kUp = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerUp", {env, touchCls});
call_native("Java_com_ea_rwfilesystem_rwfilesystem_StartupNativeImpl", {env, cls("com/ea/rwfilesystem/rwfilesystem"), g_asset_manager, files, ext}); kMove = call_native("Java_com_ea_blast_TouchSurfaceAndroid_NativeGetIdRawPointerMove", {env, touchCls});
call_native("Java_com_ea_EAAudioCore_AndroidEAAudioCore_Init", {env, cls("com/ea/EAAudioCore/AndroidEAAudioCore"), g_audio_track, (uint32_t)frames, (uint32_t)channels, (uint32_t)rate}); kTouch = call_native("Java_com_ea_blast_ModuleCatalog_NativeGetModuleTypeIdTouchScreen", {env, cls("com/ea/blast/ModuleCatalog")});
call_native("Java_com_ea_VideoPlayer_PlayerAndroid_StartupNativeImpl", {env, cls("com/ea/VideoPlayer/PlayerAndroid")}); g_orientation_normal = call_native("Java_com_ea_blast_DisplayAndroidDelegate_NativeGetOrientationNormal", {env, cls("com/ea/blast/DisplayAndroidDelegate")});
call_native("Java_com_ea_blast_MainActivity_NativeOnResume", {env, g_activity}); logf("touch ids down=%u up=%u move=%u module=%u", kDown, kUp, kMove, kTouch);
uint32_t files = jstring("/data/data/com.ea.spymouse_carrier/files"), ext = jstring("/sdcard");
call_native("Java_com_ea_EAIO_EAIO_StartupNativeImpl", {env, cls("com/ea/EAIO/EAIO"), g_asset_manager, files, ext});
call_native("Java_com_ea_EAMIO_StorageDirectory_StartupNativeImpl", {env, cls("com/ea/EAMIO/StorageDirectory")});
call_native("Java_com_ea_blast_MainActivity_NativeOnCreate", {env, g_activity});
call_native("Java_com_ea_rwfilesystem_rwfilesystem_StartupNativeImpl", {env, cls("com/ea/rwfilesystem/rwfilesystem"), g_asset_manager, files, ext});
call_native("Java_com_ea_EAAudioCore_AndroidEAAudioCore_Init", {env, cls("com/ea/EAAudioCore/AndroidEAAudioCore"), g_audio_track, (uint32_t)frames, (uint32_t)channels, (uint32_t)rate});
call_native("Java_com_ea_VideoPlayer_PlayerAndroid_StartupNativeImpl", {env, cls("com/ea/VideoPlayer/PlayerAndroid")});
call_native("Java_com_ea_blast_MainActivity_NativeOnResume", {env, g_activity});
});
// GL thread: surface callbacks
uint32_t renderer = jobject("com/ea/blast/AndroidRenderer"); uint32_t renderer = jobject("com/ea/blast/AndroidRenderer");
call_native("Java_com_ea_blast_AndroidRenderer_NativeOnSurfaceCreated", {env, renderer}); call_native("Java_com_ea_blast_AndroidRenderer_NativeOnSurfaceCreated", {env, renderer});
call_native("Java_com_ea_blast_AndroidRenderer_NativeOnSurfaceChanged", {env, renderer, (uint32_t)W, (uint32_t)H}); call_native("Java_com_ea_blast_AndroidRenderer_NativeOnSurfaceChanged", {env, renderer, (uint32_t)W, (uint32_t)H});
call_native("Java_com_ea_blast_MainActivity_NativeOnWindowFocusChanged", {env, g_activity, 1}); ui.post([=] {
call_native("Java_com_ea_spymouse_1carrier_BogoMIPSReader_passBogoMIPS", {env, cls("com/ea/spymouse_carrier/BogoMIPSReader"), fbits(998.84f)}); call_native("Java_com_ea_blast_MainActivity_NativeOnWindowFocusChanged", {env, g_activity, 1});
call_native("Java_com_ea_spymouse_1carrier_BogoMIPSReader_passBogoMIPS", {env, cls("com/ea/spymouse_carrier/BogoMIPSReader"), fbits(998.84f)});
});
logf("boot sequence done, entering frame loop"); logf("boot sequence done, entering frame loop");
// Scripted input for automated tests: "frame:down|up|move:x,y;..." // Scripted input for automated tests: "frame:down|up|move:x,y;..."
@ -209,24 +297,70 @@ int main(int argc, char** argv) {
uint32_t ptr_event = native("Java_com_ea_blast_TouchSurfaceAndroid_NativeOnPointerEvent"); uint32_t ptr_event = native("Java_com_ea_blast_TouchSurfaceAndroid_NativeOnPointerEvent");
auto send_touch = [&](uint32_t kind, float x, float y) { auto send_touch = [&](uint32_t kind, float x, float y) {
call_guest(ptr_event, {env, touchCls, kind, kTouch, 0, fbits(x), fbits(y)}); ui.post([=] { call_guest(ptr_event, {env, touchCls, kind, kTouch, 0, fbits(x), fbits(y)}); });
}; };
uint32_t draw = native("Java_com_ea_blast_AndroidRenderer_NativeOnDrawFrame"); uint32_t draw = native("Java_com_ea_blast_AndroidRenderer_NativeOnDrawFrame");
// Android lifecycle: losing focus pauses the game (it saves and stops music), regaining it resumes.
// `paused` is the requested state; rendering keeps going until the UI thread has finished OnPause
// (the engine waits for one more frame), then stops until resume.
std::atomic<bool> paused{false};
std::atomic<bool> render_stopped{false};
auto set_paused = [&](bool p) {
if (p == paused) return;
paused = p;
logf(p ? "lifecycle: pause" : "lifecycle: resume");
if (p) {
ui.post([&, env] {
call_native("Java_com_ea_blast_MainActivity_NativeOnWindowFocusChanged", {env, g_activity, 0});
call_native("Java_com_ea_blast_MainActivity_NativeOnPause", {env, g_activity});
if (paused) render_stopped = true; // a resume may already be queued behind us
logf("lifecycle: paused");
});
} else {
render_stopped = false;
if (audio) SDL_ResumeAudioStreamDevice(audio);
ui.post([env] {
call_native("Java_com_ea_blast_MainActivity_NativeOnResume", {env, g_activity});
call_native("Java_com_ea_blast_MainActivity_NativeOnWindowFocusChanged", {env, g_activity, 1});
});
}
};
// Control directory for automated play-testing: write commands to <dir>/cmd.
// tap X Y | drag X1 Y1 X2 Y2 [frames] | shot NAME | wait FRAMES | pause | resume | quit
struct Cmd { std::string op; std::vector<float> a; std::string name; };
std::deque<Cmd> cmds;
int wait_until = 0;
std::string ctl = opt.control_dir;
if (!ctl.empty()) { fs::create_directories(ctl); logf("control dir %s", ctl.c_str()); }
bool mouse_down = false; bool mouse_down = false;
int frame = 0; int frame = 0;
double draw_ms_sum = 0, draw_ms_max = 0;
auto t_start = std::chrono::steady_clock::now(); auto t_start = std::chrono::steady_clock::now();
while (!g_quit) { while (!g_quit) {
SDL_Event ev; SDL_Event ev;
while (SDL_PollEvent(&ev)) { while (SDL_PollEvent(&ev)) {
if (ev.type == SDL_EVENT_QUIT) g_quit = true; switch (ev.type) {
case SDL_EVENT_QUIT: g_quit = true; break;
case SDL_EVENT_WINDOW_FOCUS_LOST: if (!opt.headless) set_paused(true); break;
case SDL_EVENT_WINDOW_FOCUS_GAINED: set_paused(false); break;
case SDL_EVENT_WINDOW_MINIMIZED: set_paused(true); break;
case SDL_EVENT_WINDOW_RESTORED: set_paused(false); break;
default: break;
}
if (paused) continue;
if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN || ev.type == SDL_EVENT_MOUSE_BUTTON_UP || if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN || ev.type == SDL_EVENT_MOUSE_BUTTON_UP ||
(ev.type == SDL_EVENT_MOUSE_MOTION && mouse_down)) { (ev.type == SDL_EVENT_MOUSE_MOTION && mouse_down)) {
if ((ev.type != SDL_EVENT_MOUSE_MOTION) && ev.button.button != SDL_BUTTON_LEFT) continue;
int ww, wh; int ww, wh;
SDL_GetWindowSize(win, &ww, &wh); SDL_GetWindowSize(win, &ww, &wh);
float scale = std::min(ww / (float)W, wh / (float)H); float scale = std::min(ww / (float)W, wh / (float)H);
float ox = (ww - W * scale) / 2, oy = (wh - H * scale) / 2; float ox = (ww - W * scale) / 2, oy = (wh - H * scale) / 2;
float x = (ev.button.x - ox) / scale, y = (ev.button.y - oy) / scale; float mx = ev.type == SDL_EVENT_MOUSE_MOTION ? ev.motion.x : ev.button.x;
if (ev.type == SDL_EVENT_MOUSE_MOTION) { x = (ev.motion.x - ox) / scale; y = (ev.motion.y - oy) / scale; } float my = ev.type == SDL_EVENT_MOUSE_MOTION ? ev.motion.y : ev.button.y;
float x = std::clamp((mx - ox) / scale, 0.f, (float)W - 1), y = std::clamp((my - oy) / scale, 0.f, (float)H - 1);
uint32_t kind = ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN ? kDown : ev.type == SDL_EVENT_MOUSE_BUTTON_UP ? kUp : kMove; uint32_t kind = ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN ? kDown : ev.type == SDL_EVENT_MOUSE_BUTTON_UP ? kUp : kMove;
if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) mouse_down = true; if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) mouse_down = true;
if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP) mouse_down = false; if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP) mouse_down = false;
@ -235,19 +369,78 @@ int main(int argc, char** argv) {
} }
for (auto& e : script) if (e.frame == frame) { logf("script touch %u at %.0f,%.0f", e.kind, e.x, e.y); send_touch(e.kind, e.x, e.y); } for (auto& e : script) if (e.frame == frame) { logf("script touch %u at %.0f,%.0f", e.kind, e.x, e.y); send_touch(e.kind, e.x, e.y); }
// control commands
if (!ctl.empty() && frame % 10 == 0 && fs::exists(ctl + "/cmd")) {
std::ifstream in(ctl + "/cmd");
std::string line;
while (std::getline(in, line)) {
std::istringstream ls(line);
Cmd c;
ls >> c.op;
if (c.op.empty() || c.op[0] == '#') continue;
if (c.op == "shot") ls >> c.name;
float v;
while (ls >> v) c.a.push_back(v);
// expand gestures into per-frame touch events
if (c.op == "tap" && c.a.size() >= 2) {
cmds.push_back({"down", {c.a[0], c.a[1]}, ""});
cmds.push_back({"wait", {3}, ""});
cmds.push_back({"up", {c.a[0], c.a[1]}, ""});
} else if (c.op == "drag" && c.a.size() >= 4) {
int n = c.a.size() >= 5 ? (int)c.a[4] : 20;
cmds.push_back({"down", {c.a[0], c.a[1]}, ""});
for (int k = 1; k <= n; k++) {
float t = k / (float)n;
cmds.push_back({"wait", {1}, ""});
cmds.push_back({"move", {c.a[0] + (c.a[2] - c.a[0]) * t, c.a[1] + (c.a[3] - c.a[1]) * t}, ""});
}
cmds.push_back({"up", {c.a[2], c.a[3]}, ""});
} else {
cmds.push_back(c);
}
}
in.close();
fs::remove(ctl + "/cmd");
}
while (!cmds.empty() && frame >= wait_until) {
Cmd c = cmds.front();
cmds.pop_front();
if (c.op == "down") send_touch(kDown, c.a[0], c.a[1]);
else if (c.op == "up") send_touch(kUp, c.a[0], c.a[1]);
else if (c.op == "move") send_touch(kMove, c.a[0], c.a[1]);
else if (c.op == "wait") { wait_until = frame + (c.a.empty() ? 1 : (int)c.a[0]); }
else if (c.op == "shot") { pending_shot = ctl + "/" + c.name + ".png"; }
else if (c.op == "pause") set_paused(true);
else if (c.op == "resume") set_paused(false);
else if (c.op == "quit") g_quit = true;
else logf("control: unknown command %s", c.op.c_str());
if (c.op == "wait") break;
}
if (render_stopped) {
if (audio) SDL_PauseAudioStreamDevice(audio);
SDL_Delay(30);
if (wait_until > frame) wait_until--; // waits count down in real time while paused
continue;
}
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
glViewport(0, 0, W, H); glViewport(0, 0, W, H);
auto d0 = std::chrono::steady_clock::now();
call_guest(draw, {env, renderer}); call_guest(draw, {env, renderer});
if (video_draw(W, H) && opt.headless && frame % 60 == 0) logf("video playing"); double dms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - d0).count();
draw_ms_sum += dms;
draw_ms_max = std::max(draw_ms_max, dms);
video_draw(W, H);
uint32_t done = video_poll_completed(); uint32_t done = video_poll_completed();
if (!done && opt.skip_video && video_is_playing(0)) done = video_current(); if (!done && opt.skip_video && video_is_playing(0)) done = video_current();
if (done) { if (done) {
logf("video finished"); logf("video finished");
video_stop(done); video_stop(done);
call_native("Java_com_ea_VideoPlayer_PlayerAndroid_OnCompletionNativeImpl", {env, done}); ui.post([=] { call_native("Java_com_ea_VideoPlayer_PlayerAndroid_OnCompletionNativeImpl", {env, done}); });
} }
frame++; frame++;
for (int f : opt.shot_frames) if (f == frame) save_png(opt.shot_dir + "/frame" + std::to_string(frame) + ".png", W, H); for (int f : opt.shot_frames) if (f == frame) save_png(opt.shot_dir + "/frame" + std::to_string(frame) + ".png", W, H);
if (!pending_shot.empty()) { save_png(pending_shot, W, H); pending_shot.clear(); }
// present: scale the game surface into the window, letterboxed // present: scale the game surface into the window, letterboxed
int pw, ph; int pw, ph;
@ -264,15 +457,41 @@ int main(int argc, char** argv) {
SDL_GL_SwapWindow(win); SDL_GL_SwapWindow(win);
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
if (frame % 300 == 0) { if (frame % 600 == 0) {
double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count(); double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
logf("frame %d, %.1f fps average", frame, frame / s); logf("frame %d, %.1f fps average, audio %.1f s written, peak %d", frame, frame / s,
g_audio_bytes / (44100.0 * 4), g_audio_peak.exchange(0));
logf(" game frame time: avg %.2f ms, max %.2f ms, of which sleeping %.2f ms", draw_ms_sum / 600, draw_ms_max,
g_main_sleep_ms.exchange(0) / 600);
draw_ms_sum = draw_ms_max = 0;
} }
if (opt.frames && frame >= opt.frames) { logf("exit after %d frames (--frames)", frame); fflush(nullptr); _exit(0); } if (opt.frames && frame >= opt.frames) { logf("exit after %d frames (--frames)", frame); fflush(nullptr); _exit(0); }
} }
call_native("Java_com_ea_blast_MainActivity_NativeOnPause", {env, g_activity}); // Quit like Android does when the activity goes away; never hang on exit.
call_native("Java_com_ea_blast_MainActivity_NativeOnStop", {env, g_activity}); std::thread([] {
logf("exit after %d frames", frame); std::this_thread::sleep_for(std::chrono::seconds(5));
logf("shutdown watchdog: forcing exit");
fflush(nullptr);
_exit(0);
}).detach();
std::atomic<bool> stopped{false};
bool was_paused = render_stopped;
ui.post([&, env, was_paused] {
if (!was_paused) {
call_native("Java_com_ea_blast_MainActivity_NativeOnWindowFocusChanged", {env, g_activity, 0});
call_native("Java_com_ea_blast_MainActivity_NativeOnPause", {env, g_activity});
}
call_native("Java_com_ea_blast_MainActivity_NativeOnStop", {env, g_activity});
stopped = true;
});
while (!stopped) {
if (!was_paused) {
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
call_guest(draw, {env, renderer});
}
SDL_Delay(5);
}
logf("exit after %d frames, game state saved", frame);
fflush(nullptr); fflush(nullptr);
_exit(0); _exit(0);
} }

13
tools/ctl.sh Executable file
View file

@ -0,0 +1,13 @@
#!/bin/zsh
# Send commands to a running "spymouse --control DIR" and wait for an optional screenshot.
# usage: ctl.sh DIR "tap 610 360\nwait 60\nshot menu" [shotname] [timeout_s]
dir=$1; cmds=$2; shot=$3; to=${4:-60}
while [[ -e $dir/cmd ]]; do sleep 0.2; done
[[ -n $shot ]] && rm -f "$dir/$shot.png"
print -r -- "$cmds" > $dir/cmd.tmp && mv $dir/cmd.tmp $dir/cmd
[[ -z $shot ]] && exit 0
for i in $(seq 1 $((to*5))); do
[[ -s $dir/$shot.png ]] && { grep "frame stats $dir/$shot.png" /tmp/sm_live.txt | tail -1 | sed 's/.*: //'; exit 0; }
sleep 0.2
done
echo "TIMEOUT waiting for $shot"; exit 1