Files
shenleiandClaude Opus 5.5 3c25cd89fc Android: move the shell to dm/android and the Vulkan backend to dm/gfx/vulkan
Mirror the iOS layout instead of nesting Android inside dm/host:
- dm/android/app       GameActivity app (manifest, java, res, build_apk.sh)
- dm/android/Sources   front_app.c, touch_app.c, front_headless.c
- dm/android/Makefile  entry point (apk / lib / install / headless / tests);
                       rules in build.mk (was dm/host/Makefile.android),
                       run with dm/host as cwd; outputs in dm/android/build/
- dm/android/tests     t_vk_perf
- dm/gfx/vulkan        nvn_vk.c and friends, next to the Metal backend

Only include paths, build paths and docs change; no code changes.
The Mac / iOS source lists do not pick up gfx/vulkan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:59:36 +09:00

241 lines
17 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Android App 前端(libd2r.so,由 GameActivity 加载):替换无头的 front_headless.c。
// 宿主照常从 main() 起跑(在 JNI 起的线程里),这里给它窗口、输入、软键盘和前后台切换。
// 游戏数据放在 App 私有目录 files/d2r/(dm/ 模块、romfs/、romfs_overlay/、rt64/ 着色器包、save/、temp/);
// files/d2r/env.txt 每行 KEY=VALUE 在起跑前 setenv(调试开关,如 DM_VK_VRS=2x2)。日志写 files/d2r/run.log。
// Android app front end (libd2r.so, loaded by GameActivity): replaces the headless front_headless.c.
// The host starts from main() as usual (on a thread started over JNI); this file gives it the window, input, software keyboard and foreground / background switching.
// Game data lives in the app's private directory files/d2r/ (dm/ modules, romfs/, romfs_overlay/, rt64/ shader pack, save/, temp/);
// each KEY=VALUE line of files/d2r/env.txt is setenv'd before start (debug switches such as DM_VK_VRS=2x2). The log is written to files/d2r/run.log.
#include "../../host/dm.h"
#include "../../host/hle.h"
#include "../../host/front.h"
#include "../../host/dm_input.h"
#include "../../host/dm_padmap.h"
#include "../../host/dm_cursor.h"
#include "../../gfx/vulkan/vk_platform.h"
#include <jni.h>
#include <android/native_window_jni.h>
#include <android/log.h>
#include <fcntl.h>
#include <math.h>
#include <signal.h>
#include <stdatomic.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char **argv);
static char g_root[512];
static unsigned g_screen_w, g_screen_h;
static _Atomic int g_started, g_window;
static void path_of(char *out, size_t n, const char *leaf) { snprintf(out, n, "%s/%s", g_root, leaf); }
static int exists(const char *p) { struct stat st; return !stat(p, &st); }
// env.txt:KEY=VALUE 每行一条,# 开头为注释 | env.txt: one KEY=VALUE per line, lines starting with # are comments
static void env_file(void) {
char p[600]; path_of(p, sizeof p, "env.txt"); FILE *f = fopen(p, "r"); if (!f) return;
char line[1024];
while (fgets(line, sizeof line, f)) {
line[strcspn(line, "\r\n")] = 0; char *eq = strchr(line, '=');
if (line[0] == '#' || !eq) continue;
*eq = 0; setenv(line, eq + 1, 1); LOG("app: env %s=%s", line, eq + 1);
}
fclose(f);
}
static void *host_thread(void *unused) {
(void)unused;
char dm[600]; path_of(dm, sizeof dm, "dm");
char *argv[] = {"dmhost", dm, "main", "sdk", NULL};
int rc = main(4, argv);
LOG("app: 宿主 main 返回 %d | host main returned %d", rc, rc);
return NULL;
}
// ---- front.h ----
// 客体在 64 MB 栈的线程里跑(与无头前端、iOS 壳一致)| The guest runs on a thread with a 64 MB stack (same as the headless front end and the iOS shell)
static void *guest_thread(void *p) {
static char alt[65536]; // 信号备用栈每线程一份:客体栈溢出时崩溃打印也要能跑 | per-thread alternate signal stack, so the crash printout runs even on guest stack overflow
stack_t ss = {.ss_sp = alt, .ss_size = sizeof alt}; sigaltstack(&ss, NULL);
sigset_t all; sigfillset(&all); pthread_sigmask(SIG_UNBLOCK, &all, NULL); // JNI 线程继承了 ART 的信号屏蔽字 | the JNI thread inherited ART's signal mask
void touch_app_guest_start(void); touch_app_guest_start(); // 触屏 HUD(touch_app.c)| touch HUD (touch_app.c)
((void (*)(void))p)(); return NULL;
}
void front_run(void (*guest)(void)) {
pthread_attr_t a; pthread_t t;
pthread_attr_init(&a); pthread_attr_setstacksize(&a, 64 << 20);
if (pthread_create(&t, &a, guest_thread, (void *)guest)) die("建客体线程失败");
pthread_join(t, NULL);
}
// 只当「有窗口」标志用(hle_swkbd 据此决定弹不弹输入框)| Used only as a "has a window" flag (hle_swkbd decides from it whether to show the input box)
void *front_metal_layer(void) { return (void *)(uintptr_t)1; }
// 主机档:屏幕原生高(夹在 900–1080)× 屏幕比例(宽取 8 的倍数,≤ 4096);掌机档 720 同比。比 16:9 窄的屏按 16:9。DM_GAME_RES=宽x高 覆盖
// Docked profile: the screen's native height (clamped to 900–1080) × the screen aspect ratio (width rounded to a multiple of 8, ≤ 4096); handheld uses 720 the same way. Screens narrower than 16:9 use 16:9. DM_GAME_RES=WxH overrides
uint64_t front_game_res(int docked) {
unsigned w, h; const char *e = getenv("DM_GAME_RES");
if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4;
double aspect = g_screen_w && g_screen_h ? (double)g_screen_w / g_screen_h : 16.0 / 9;
if (aspect < 16.0 / 9) aspect = 16.0 / 9;
// 主机档按屏幕原生高(900–1080 之间):界面与文字 1:1 上屏,不再经 1.2 倍线性放大发糊;3D 目标仍按 720 高(hle_oe.c),GPU 不变(OnePlus 13 实测 12.1 → 12.0 ms/帧)。
// 上限 1080:2K 屏(1440 高)界面多画 78% 像素,换来的清晰度看不出
// Docked uses the screen's native height (between 900 and 1080): UI and text go to the screen 1:1 instead of a blurry 1.2x linear upscale; the 3D target stays 720 high (hle_oe.c), GPU unchanged (OnePlus 13 measured 12.1 -> 12.0 ms/frame).
// Capped at 1080: on 2K screens (1440 high) the UI would draw 78% more pixels for sharpness nobody can see
uint64_t sh = g_screen_h < 900 ? 900 : g_screen_h > 1080 ? 1080 : g_screen_h, hh = docked ? sh : 720, ww = (uint64_t)llround(hh * aspect / 8) * 8;
if (ww > 4096) ww = 4096;
return hh << 32 | ww;
}
// 软键盘:客体线程挂一条请求并阻塞;Java 界面线程轮询 nativeTextRequest 弹框,结果经 nativeTextResult 交回
// Software keyboard: the guest thread posts a request and blocks; the Java UI thread polls nativeTextRequest to show the dialog and returns the result via nativeTextResult
static pthread_mutex_t text_mu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t text_cv = PTHREAD_COND_INITIALIZER;
static struct { int pending, done, ok, max_chars; const char *title, *sub, *guide, *initial; char result[1024]; } g_text;
int front_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
pthread_mutex_lock(&text_mu);
g_text.title = title ? title : ""; g_text.sub = sub ? sub : ""; g_text.guide = guide ? guide : ""; g_text.initial = initial ? initial : "";
g_text.max_chars = max_chars; g_text.done = 0; g_text.pending = 1;
while (!g_text.done) pthread_cond_wait(&text_cv, &text_mu);
int ok = g_text.ok; if (ok) snprintf(out, (size_t)out_cap, "%s", g_text.result);
pthread_mutex_unlock(&text_mu);
return ok;
}
// ---- JNI ----
#define JNI(name) JNICALL Java_org_d2rmobile_app_GameActivity_##name
// root = files/d2r;返回 0 = 已起跑,否则错误码(缺文件等)| root = files/d2r; returns 0 = started, otherwise an error code (missing files etc.)
JNIEXPORT jint JNI(nativeStart)(JNIEnv *env, jclass cls, jstring root, jint screen_w, jint screen_h) {
(void)cls;
if (atomic_exchange(&g_started, 1)) return 0;
const char *r = (*env)->GetStringUTFChars(env, root, NULL); snprintf(g_root, sizeof g_root, "%s", r); (*env)->ReleaseStringUTFChars(env, root, r);
g_screen_w = (unsigned)(screen_w > screen_h ? screen_w : screen_h); g_screen_h = (unsigned)(screen_w > screen_h ? screen_h : screen_w);
char p[600];
path_of(p, sizeof p, "run.log"); int fd = open(p, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd >= 0) { dup2(fd, 2); close(fd); setvbuf(stderr, NULL, _IONBF, 0); }
if (chdir(g_root)) { __android_log_print(ANDROID_LOG_ERROR, "d2r", "chdir %s failed", g_root); return 2; }
path_of(p, sizeof p, "dm/main.patched.bin"); if (!exists(p)) return 3;
path_of(p, sizeof p, "romfs"); if (!exists(p)) return 4;
path_of(p, sizeof p, "rt64"); if (!exists(p)) return 5;
// 缺省值:命令行版 run.sh 的那几项;env.txt 可覆盖 | Defaults: the items of the command-line run.sh; env.txt may override
setenv("DM_ROOT", g_root, 1);
path_of(p, sizeof p, "romfs"); setenv("DM_ROMFS", p, 1);
path_of(p, sizeof p, "romfs_overlay"); if (exists(p)) setenv("DM_ROMFS_OVERLAY", p, 1);
path_of(p, sizeof p, "save"); mkdir(p, 0755); setenv("DM_SAVE", p, 1);
path_of(p, sizeof p, "temp"); mkdir(p, 0755); setenv("DM_TEMP", p, 1);
path_of(p, sizeof p, "rt64"); setenv("DM_VK_SHADERS", p, 1);
// App 总有窗口,只是熄屏启动时第一次出图前还没拿到:出图间隔模式不能靠那一刻「有没有窗口」定(否则锁成 game 模式的间隔 2 = 30 帧)
// The app always has a window, it just may not have one yet before the first present when started with the screen off: the present interval mode must not be decided by "is there a window" at that moment (that locks game mode, interval 2 = 30 fps)
setenv("DM_PRESENT_INTERVAL", "display", 1);
env_file();
LOG("app: 起跑 root=%s screen=%ux%u game=%llux%llu", g_root, g_screen_w, g_screen_h,
(unsigned long long)(uint32_t)front_game_res(1), (unsigned long long)(front_game_res(1) >> 32));
dm_vk_hold_without_window(1);
pthread_attr_t a; pthread_t t;
pthread_attr_init(&a); pthread_attr_setstacksize(&a, 8 << 20);
if (pthread_create(&t, &a, host_thread, NULL)) return 6;
pthread_detach(t);
return 0;
}
// surface = NULL:窗口没了(切后台 / 销毁),出图阻塞到窗口回来 | surface = NULL: the window is gone (background / destroyed), present blocks until it returns
JNIEXPORT void JNI(nativeSurface)(JNIEnv *env, jclass cls, jobject surface, jfloat hz) {
(void)cls;
ANativeWindow *w = surface ? ANativeWindow_fromSurface(env, surface) : NULL;
if (hz > 0) dm_vk_set_display_hz((int)(hz + 0.5f));
dm_vk_set_window(w); // 后端自己 acquire 一份 | the backend acquires its own reference
if (w) ANativeWindow_release(w);
atomic_store(&g_window, w != NULL);
LOG("app: surface %s", w ? "attached" : "detached");
}
// ---- 前后台(同 iOS front_ios_focus_event)| foreground / background (same as iOS front_ios_focus_event) ----
// 进后台(onStop):局内先请游戏存一次盘、等提交完成再挂起。等的时候游戏主循环照常跑,窗口可能已经没了,所以临时不让出图因「没窗口」阻塞
// (没窗口就照常回放、不上屏,同 adb 无头);等到「出现过存档提交、之后 0.2 秒没有新提交」(角色与共享箱分两次),最多 2.5 秒。
// 之后 dm_gfx_suspend(1) 挡住后续提交 / 出图——必须在恢复「没窗口阻塞」之前:出图若已停在等窗口,挂起会等它退出而卡死
// Entering background (onStop): in a run, first ask the game to save once and wait for the commit before suspending. While waiting the game main loop runs as usual and the window may already be gone, so presents temporarily do not block on "no window"
// (with no window they replay as usual without presenting, like adb headless); wait until "a save commit has appeared and no new commit for 0.2 s after it" (character and shared stash commit separately), at most 2.5 s.
// Then dm_gfx_suspend(1) blocks later submits / presents -- this must come before "block without window" is restored: if a present were already parked waiting for a window, the suspend would wait for it to exit and deadlock
static void background_wait_save(void) {
int dm_ingame_now(void); uint64_t dm_fs_commit_count(void); int dm_request_save(void);
if (!dm_ingame_now() || !dm_request_save()) return; // 让游戏下一拍走它自己的定时存盘(diag.c) | let the game run its own timed save on the next tick (diag.c)
uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0;
for (;;) {
usleep(20000);
uint64_t c = dm_fs_commit_count(), t = now_ns();
if (c != last) { last = c; last_t = t; }
if (last_t && t - last_t >= 200000000ull) break;
if (t - t0 >= 2500000000ull) break;
}
LOG("app: 进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), last == c0 ? "【红】(2.5 秒内没等到)" : "");
}
// 失活(onPause)也请游戏存一次盘、不等:多任务界面里直接划掉进程时未必走得到 onStop 的存盘;30 秒内只请一次
// Pausing (onPause) also asks the game to save once without waiting: swiping the process away in the recents screen may not reach the onStop save; at most once per 30 s
static void resign_save(void) {
int dm_ingame_now(void); int dm_request_save(void);
static uint64_t last; uint64_t now = now_ns();
if (!dm_ingame_now() || (last && now - last < 30000000000ull)) return;
if (dm_request_save()) { last = now; LOG("app: 失活,请游戏下一拍存一次盘(不等)"); }
}
// ev:0 onPause(失活)、1 onStop(进后台)、2 onStart(回前台)、3 onResume(激活)。在 UI 线程调;1 最多挡 2.5 秒
// ev: 0 onPause (resign active), 1 onStop (background), 2 onStart (foreground), 3 onResume (active). Called on the UI thread; 1 blocks for at most 2.5 s
JNIEXPORT void JNI(nativeLifecycle)(JNIEnv *env, jclass cls, jint ev) {
(void)env; (void)cls;
static const char *k[] = {"onPause", "onStop", "onStart", "onResume"};
static int bg; // 进过后台、还没回前台(第一次 onStart 没有对应的 onStop) | went to background and not back yet (the first onStart has no matching onStop)
if (ev < 0 || ev > 3 || !atomic_load(&g_started)) return;
{ uint64_t guest_ns(void); LOG("app: %s(客体时钟 %.3f s)", k[ev], guest_ns() / 1e9); }
void guest_clock_freeze_for(int reason, int on); void dm_ui_lifecycle(int background); void dm_3d_scale_resumed(void);
switch (ev) {
case 0: dm_focus_set(2); resign_save(); break; // 触点、手柄键由 Java 端先清 | touches and controller keys are cleared on the Java side first
// 客体时钟一并冻结(等效 Switch 挂起):否则回来时游戏内时间一下跳过整段后台时长 | the guest clock is frozen as well (like Switch suspend): otherwise in-game time jumps over the whole background period on return
case 1: dm_focus_set(3); dm_ui_lifecycle(1); dm_audio_suspend(1);
dm_vk_hold_without_window(0); background_wait_save(); dm_gfx_suspend(1); dm_vk_hold_without_window(1);
guest_clock_freeze_for(1, 1); bg = 1; break;
case 2: if (!bg) break; bg = 0;
dm_ui_lifecycle(0); dm_3d_scale_resumed(); dm_gfx_suspend(0); guest_clock_freeze_for(1, 0); dm_audio_suspend(0); dm_focus_set(2); break; // 窗口未回来前出图仍停在等窗口 | until the window returns, presents still park waiting for it
case 3: dm_focus_set(1); break;
}
}
// 游戏已出的帧数,Java 端据此算 FPS 标签 | frames the game has presented, for the Java FPS label
JNIEXPORT jlong JNI(nativeFrames)(JNIEnv *env, jclass cls) {
(void)env; (void)cls;
extern uint64_t mtl_present_count(void);
return (jlong)mtl_present_count();
}
// 触点由 touch_app.c 的 nativeTouchEvent 接 | touches are taken by nativeTouchEvent in touch_app.c
// 实体手柄:face 位 0–3 = 下 / 右 / 左 / 上面键(按位置),其余按钮已是 DM_BTN_* 位;摇杆 ±1 浮点
// Physical controller: face bits 0–3 = bottom / right / left / top face buttons (by position), other buttons already as DM_BTN_* bits; sticks as ±1 floats
JNIEXPORT void JNI(nativePad)(JNIEnv *env, jclass cls, jint face, jint other, jboolean nintendo, jfloat lx, jfloat ly, jfloat rx, jfloat ry) {
(void)env; (void)cls;
uint64_t b = dm_padmap_face(nintendo ? DM_PADKIND_NINTENDO : DM_PADKIND_XBOX, face & 1, face >> 1 & 1, face >> 2 & 1, face >> 3 & 1) | (uint32_t)other;
// Android 的 Y 轴向下为正,nn::hid 向上为正 | Android's Y axis is positive downwards, nn::hid's is positive upwards
void touch_app_pad(uint64_t, int32_t, int32_t, int32_t, int32_t);
touch_app_pad(b, (int32_t)(lx * DM_STICK_MAX), (int32_t)(-ly * DM_STICK_MAX), (int32_t)(rx * DM_STICK_MAX), (int32_t)(-ry * DM_STICK_MAX));
}
// 软键盘请求:没有就返回 null;有则 [标题, 说明, 提示, 初值, 最大字数] | Software keyboard request: null if none, otherwise [title, subtitle, hint, initial, max chars]
JNIEXPORT jobjectArray JNI(nativeTextRequest)(JNIEnv *env, jclass cls) {
(void)cls; jobjectArray a = NULL;
pthread_mutex_lock(&text_mu);
if (g_text.pending) {
g_text.pending = 0; char max[16]; snprintf(max, sizeof max, "%d", g_text.max_chars);
const char *v[5] = {g_text.title, g_text.sub, g_text.guide, g_text.initial, max};
a = (*env)->NewObjectArray(env, 5, (*env)->FindClass(env, "java/lang/String"), NULL);
for (int i = 0; i < 5; i++) (*env)->SetObjectArrayElement(env, a, i, (*env)->NewStringUTF(env, v[i]));
}
pthread_mutex_unlock(&text_mu);
return a;
}
JNIEXPORT void JNI(nativeTextResult)(JNIEnv *env, jclass cls, jboolean ok, jstring text) {
(void)cls;
pthread_mutex_lock(&text_mu);
g_text.ok = ok && text; g_text.result[0] = 0;
if (g_text.ok) { const char *s = (*env)->GetStringUTFChars(env, text, NULL); snprintf(g_text.result, sizeof g_text.result, "%s", s); (*env)->ReleaseStringUTFChars(env, text, s); }
g_text.done = 1; pthread_cond_broadcast(&text_cv);
pthread_mutex_unlock(&text_mu);
}