Android port (Adreno): Vulkan backend, GameActivity app, touch HUD, lifecycle, minimap quest goals

- host/android: Vulkan replay backend (nvn_vk.c) with pipeline/descriptor caching, ADPF,
  AChoreographer present link; Linux compat layer; Makefile.android (headless dmhost + APK lib)
- android/app: GameActivity shell without Gradle (build_apk.sh), AAudio output, touch HUD port
  (touch_app.c + TouchOverlay.java, three layers: body / joystick / minimap goals),
  lifecycle save-on-background like iOS, art_from_ipa.py for touch / HUD / mapgoal art
- touch: shared touch controls moved from ios/Sources to dm/touch
- patch_nso.py Android ruleset, dmsh_vk.py shader pack, DM_TOUCH_PRODUCT defaults
- hle_audio: AAudio resume waits through STARTING and reopens once on failure
- .gitignore: local resources/ (original game data) never committed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-14 14:55:05 +09:00
co-authored by Claude Opus 5.5
parent 5bc5a01087
commit 4d91f80bae
106 changed files with 7009 additions and 181 deletions
+3
View File
@@ -3,3 +3,6 @@
.iosdd_mac/
.iosdd_*/
.DS_Store
# 本地原版游戏资源与安装包(不进仓库) | local original game resources and builds (never committed)
/resources/
+1 -1
View File
@@ -53,7 +53,7 @@ The following are generated at build time and are already listed in the `.gitign
|---|---|
| `dm/host/dm_vault_tab.h`, `dm/host/dm_hud_exp.h`, `dm/host/dm_bright_levels.inc` | Headers generated from the game's data tables (by `dm/host/Makefile` at build time) |
| `dm/ios/Gen/` | Generated parts of the iOS package: UI images made from the game files, the embedded game program, the overlay |
| `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/ios/Sources/dm_touch_native_art.c` | The skill atlas and skill index |
| `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/touch/dm_touch_native_art.c` | The skill atlas and skill index |
| `dm/ios/DmIOS.xcodeproj/`, `dm/ios/Sources/Info.plist`, `dm/ios/Sources/DmIOS.entitlements`, and `Info.plist` and `RomfsDownloader.entitlements` under `dm/ios/RomfsDownloader/` | The project and configuration generated from `dm/ios/project.yml` |
| `dm/ios/local.env` | Your own signing configuration |
| `dm/host/dmhost`, `*.dSYM/`, `*.bin`, `*.pkl`, `__pycache__/`, the test programs built under each `tests/` | Build output and intermediate files |
+1 -1
View File
@@ -53,7 +53,7 @@ English: [CONTRIBUTING.md](CONTRIBUTING.md)
|---|---|
| `dm/host/dm_vault_tab.h`、`dm/host/dm_hud_exp.h`、`dm/host/dm_bright_levels.inc` | 由游戏的数据表生成的表头(`dm/host/Makefile` 构建时生成) |
| `dm/ios/Gen/` | iOS 包的生成物:由游戏文件做出的界面图、内嵌的游戏程序、覆盖层 |
| `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/ios/Sources/dm_touch_native_art.c` | 技能图集与技能索引 |
| `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/touch/dm_touch_native_art.c` | 技能图集与技能索引 |
| `dm/ios/DmIOS.xcodeproj/`、`dm/ios/Sources/Info.plist`、`dm/ios/Sources/DmIOS.entitlements`、`dm/ios/RomfsDownloader/` 下的 `Info.plist` 与 `RomfsDownloader.entitlements` | 由 `dm/ios/project.yml` 生成的工程与配置 |
| `dm/ios/local.env` | 你自己的签名配置 |
| `dm/host/dmhost`、`*.dSYM/`、`*.bin`、`*.pkl`、`__pycache__/`、各 `tests/` 下编出的测试程序 | 编译产物与中间文件 |
+1 -1
View File
@@ -217,7 +217,7 @@ When game files are missing, a one-sentence message says directly which director
| Right-hand panel of character select | `dm/ios/Gen/assets/NativeHUD/touch/` | `gen_fe_rightpanel.py` |
| Minimap goal marker | `dm/ios/Gen/assets/NativeHUD/mapgoal/` | `gen_map_goal_art.py` |
| Bottom UI (background and layout) | `dm/ios/Gen/assets/NativeHUD/v4/` | `gen_hud_v4.py` (geometry in `hud_v4_design.py`; layout = original layout + `touchrectv1_patch.json`) |
| Skill atlas, skill index | `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/ios/Sources/dm_touch_native_art.c` | `native_art/generate.py` (checks the originals against `dm/ios/Sources/TouchArt/native_art_manifest.json`) |
| Skill atlas, skill index | `dm/ios/Sources/TouchArt/dm_native_*.png`, `dm/touch/dm_touch_native_art.c` | `native_art/generate.py` (checks the originals against `dm/ios/Sources/TouchArt/native_art_manifest.json`) |
| Chronicle vault table, experience table | `dm/host/dm_vault_tab.h`, `dm/host/dm_hud_exp.h` | `gen_vault_table.py`, `gen_hud_exp.py` (called by `dm/host/Makefile`) |
| Level day/night table (used by 3D picture brightening) | `dm/host/dm_bright_levels.inc` | `dm/tools/gen_bright_levels.py` (also called by `dm/host/Makefile`) |
+1 -1
View File
@@ -217,7 +217,7 @@ DM_ROMFS=<Update/RomFS 目录> DM_SAVE=<存档目录> DM_TEMP=<临时目录> DM_
| 选角右侧面板 | `dm/ios/Gen/assets/NativeHUD/touch/` | `gen_fe_rightpanel.py` |
| 小地图终点标记 | `dm/ios/Gen/assets/NativeHUD/mapgoal/` | `gen_map_goal_art.py` |
| 底部 UI(底图与布局) | `dm/ios/Gen/assets/NativeHUD/v4/` | `gen_hud_v4.py`(几何在 `hud_v4_design.py`,布局 = 原版布局 + `touchrectv1_patch.json`) |
| 技能图集、技能索引 | `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/ios/Sources/dm_touch_native_art.c` | `native_art/generate.py`(按 `dm/ios/Sources/TouchArt/native_art_manifest.json` 核原件) |
| 技能图集、技能索引 | `dm/ios/Sources/TouchArt/dm_native_*.png`、`dm/touch/dm_touch_native_art.c` | `native_art/generate.py`(按 `dm/ios/Sources/TouchArt/native_art_manifest.json` 核原件) |
| 编年史仓库表、经验表 | `dm/host/dm_vault_tab.h`、`dm/host/dm_hud_exp.h` | `gen_vault_table.py`、`gen_hud_exp.py`(由 `dm/host/Makefile` 调用) |
| 关卡昼夜表(3D 画面加亮用) | `dm/host/dm_bright_levels.inc` | `dm/tools/gen_bright_levels.py`(同样由 `dm/host/Makefile` 调用) |
+1 -1
View File
@@ -1,3 +1,3 @@
// 生成文件(dm/gfx/tools/dmsh_chain.py --header):本源码树期望的 B 着色器库翻译链版本(缺省选项);宿主只加载 <库目录>/b-<V>/
// Generated file (dm/gfx/tools/dmsh_chain.py --header): the translation chain version of the B shader library expected by this source tree (default options); the host only loads <library dir>/b-<V>/
#define DMSH_CHAIN "15cf7ca29eaf"
#define DMSH_CHAIN "f0d74f7f12a9"
+46 -4
View File
@@ -66,13 +66,13 @@ typedef struct { const char *name; void *fn; } nvn_impl;
#define NVN(name, ret, ...) \
static ret h_##name(__VA_ARGS__); \
static const NVNT_##name chk_##name __attribute__((unused)) = h_##name; \
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
static ret h_##name(__VA_ARGS__)
// 无原型的新版接口:不做签名检查
// Newer interfaces without prototypes: no signature check
#define NVN_NOPROTO(name, ret, ...) \
static ret h_##name(__VA_ARGS__); \
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
__attribute__((used, DM_SECT("swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
static ret h_##name(__VA_ARGS__)
static int g_log;
@@ -164,7 +164,12 @@ NVN(nvnDeviceGetSeparateSamplerHandle, NVNseparateSamplerHandle, const NVNdevice
NVN(nvnDeviceInstallDebugCallback, void, NVNdevice *d, const PFNNVNDEBUGCALLBACKPROC cb, void *data, uint32_t enable) {
dev_t_ *o = (dev_t_ *)d; o->dbg_cb = B(enable) ? (void *)cb : NULL; o->dbg_data = data;
}
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) { ((dev_t_ *)d)->origin = m; LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
NVN(nvnDeviceSetWindowOriginMode, void, NVNdevice *d, NVNwindowOriginMode m) {
((dev_t_ *)d)->origin = m;
#ifdef __ANDROID__
mtl_set_window_origin_mode(m); // Vulkan 后端按原点选负高视口 | the Vulkan backend picks a negative-height viewport by origin
#endif
LOG("[nvn] 窗口原点 %s", m ? "左上(同 D3D / Metal)" : "左下(GL)"); }
NVN(nvnDeviceSetDepthMode, void, NVNdevice *d, NVNdepthMode m) { ((dev_t_ *)d)->depth_mode = m; LOG("[nvn] 深度模式 %s", m ? "近=0(同 D3D / Metal)" : "近=-w(GL)"); }
NVN(nvnDeviceFinalizeCommandHandle, void, NVNdevice *d, NVNcommandHandle h) { (void)d; (void)h; }
@@ -399,7 +404,11 @@ NVN(nvnQueueFinalize, void, NVNqueue *q) { ((queue_t *)q)->magic = 0; }
NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *info) {
(void)q; if (info) memset(info, 0, sizeof *info); return NVN_QUEUE_GET_ERROR_RESULT_GPU_NO_ERROR;
}
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q; }
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q;
#ifdef __ANDROID__
mtl_queue_flush();
#endif
}
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); }
// ---------- 命令缓冲:录进游戏的命令内存,提交时执行 CPU 可见副作用 ----------
@@ -535,6 +544,30 @@ static void *rec(NVNcommandBuffer *c, uint32_t op, size_t payload) {
return p + 8;
}
#define REC(c, OP, T) ((T *)rec((c), (OP), sizeof(T)))
#ifdef __ANDROID__
// Vulkan 后端要按命令序处理的同步命令(Metal 端仍当空操作,见 g_nops);格式与 dodola/d2r-mobile 的 nvn_vk.c 一致
// Sync commands the Vulkan backend handles in command order (still no-ops on Metal, see g_nops); format matches nvn_vk.c of dodola/d2r-mobile
NVN(nvnCommandBufferSetShaderScratchMemory, void, NVNcommandBuffer *c, const NVNmemoryPool *p, ptrdiff_t off, size_t size) {
const pool_t *pool = (const pool_t *)p;
if (!pool || pool->magic != MAGIC('P', 'O', 'O', 'L') || !pool->mem || off < 0 || (uint64_t)off > pool->size || size > pool->size - (uint64_t)off)
die("ShaderScratchMemory 范围非法 off=%lld size=%llu", (long long)off, (unsigned long long)size);
*REC(c, OP_SHADER_SCRATCH, p_bind_buf) = (p_bind_buf){.addr = (uint64_t)(uintptr_t)(pool->mem + off), .size = size};
}
NVN(nvnCommandBufferWaitSync, void, NVNcommandBuffer *c, const NVNsync *s) {
if (!s || ((const sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C')) die("CommandBufferWaitSync 同步对象非法");
*REC(c, OP_WAIT_SYNC, p_sync) = (p_sync){(sync_t *)s, 0, 0};
}
NVN(nvnCommandBufferFenceSync, void, NVNcommandBuffer *c, NVNsync *s, NVNsyncCondition cond, int flags) {
if (!s || ((sync_t *)s)->magic != MAGIC('S', 'Y', 'N', 'C') || cond < 0 || cond > 1 || (flags & ~1)) die("CommandBufferFenceSync 参数非法");
*REC(c, OP_FENCE_SYNC, p_sync) = (p_sync){(sync_t *)s, cond, flags};
}
NVN(nvnCommandBufferWaitEvent, void, NVNcommandBuffer *c, const NVNevent *e, NVNeventWaitMode mode, uint32_t v) {
const ev_t *ev = (const ev_t *)e;
if (!ev || ev->magic != MAGIC('E', 'V', 'N', 'T') || !ev->val || mode < 0 || mode > 1) die("CommandBufferWaitEvent 参数非法");
uint8_t *p = rec(c, OP_WAIT_EVENT, 16); uint64_t a = (uint64_t)(uintptr_t)ev->val; uint32_t mm = mode;
memcpy(p, &a, 8); memcpy(p + 8, &mm, 4); memcpy(p + 12, &v, 4);
}
#endif
// 带数组的绑定记录按实际个数分配:前缀字段 + n 个元素(回放端只读前 n 个)。原先按最大个数定长记(绑顶点缓冲 272 字节、绑贴图 / 采样器 280 字节,
// 实际常只有 1–2 个),空尾占每帧命令字节的四到五成;88 级法师的高级属性页每帧录 12.5 MB,把游戏自己的命令内存池(约每帧 105 段 × 128 KB)用空
// Binding records with arrays are allocated by the actual count: prefix fields + n elements (the replay side reads only the first n). Previously they were recorded at fixed length for the maximum count (bind vertex buffers 272 bytes, bind textures / samplers 280 bytes,
@@ -777,12 +810,18 @@ static const char *const g_nops[] = {
"nvnCommandBufferDispatchComputeIndirect",
"nvnCommandBufferSetDepthBounds",
"nvnCommandBufferDownsampleTextureView",
#ifndef __ANDROID__
"nvnCommandBufferWaitSync",
#endif
#ifndef __ANDROID__
"nvnCommandBufferSetShaderScratchMemory",
#endif
"nvnCommandBufferPushDebugGroupDynamic",
"nvnCommandBufferPopDebugGroup",
"nvnCommandBufferInsertDebugMarkerDynamic",
#ifndef __ANDROID__
"nvnCommandBufferWaitEvent",
#endif
"nvnWindowFinalize",
};
__attribute__((constructor)) static void nvn_nops_register(void) {
@@ -840,6 +879,7 @@ static double g_rt_period_ms;
static void sleep_until_ns(uint64_t dl);
static uint64_t present_period(const win_t *o);
__attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests
__attribute__((weak)) void mtl_pace_slept(uint64_t ns) { (void)ns; } // 取图里节拍等待的墙钟;安卓后端(nvn_vk.c)据此算每帧真实工作时长报给 ADPF | Wall time spent in the acquire pacing wait; the Android backend (nvn_vk.c) uses it to derive each frame's real work time for ADPF
__attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; }
extern uint32_t mtl_present_qos(void);
static uint64_t g_frame;
@@ -856,8 +896,10 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
static uint64_t rt_period; uint64_t period = present_period(o);
if (period && rt_period != period) { rt_period = period; set_time_constraint(period); }
rt_comp_tick(period);
uint64_t pace_t0 = now_ns();
if (mtl_link_active()) { if (!mtl_link_wait_tick(period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK:节拍完全跟显示节拍(跑得快就等下一拍,落后立刻走);自己的 60 Hz 时钟只作等不到节拍时的兜底 | DM_PRESENT_LINK: pacing fully follows the display link (wait for the next display-link tick when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
else if (wait) sleep_until_ns(at);
mtl_pace_slept(now_ns() - pace_t0);
} else { // DM_DETCLOCK_PACE=1(画面闸门用):客体时钟按帧走的同时,每帧墙钟不短于一个步长——帧数与游戏内时间确定,后台加载线程每帧至少有一个步长的墙钟可用; | DM_DETCLOCK_PACE=1 (used by the screenshot gate): while the guest clock advances per frame, each frame's wall clock is no shorter than one step -- frame count and in-game time are deterministic, and the background loading thread has at least one step of wall clock available per frame;
// 机器满载时帧只会更慢、后台得到的墙钟只会更多,所以「消息后第 N 帧」截到的画面与负载无关
// When the machine is fully loaded frames only get slower and the background only gets more wall clock, so the picture captured at "the Nth frame after the message" is independent of load
+3
View File
@@ -37,6 +37,9 @@ uint64_t mtl_sub_commit(void);
uint64_t mtl_last_fence(void); // 最近一次提交的栅栏值(0 = 从未提交) | Fence value of the most recent submit (0 = never submitted)
int mtl_wait(uint64_t fence, uint64_t timeout_ns); // GPU 完成到 fence 返回 1,超时 0 | Returns 1 when the GPU has completed up to fence, 0 on timeout
#ifdef __ANDROID__
void mtl_queue_flush(void); // Submit deferred Vulkan work without waiting.
#endif
void mtl_finish(void); // 等所有已提交的命令完成 | Wait for all submitted commands to complete
void mtl_drain(void); // 等队列上全部命令(含出图)完成:提交空命令缓冲并等它 | Wait for all commands on the queue (including presents) to complete: submit an empty command buffer and wait for it
void mtl_xv_window_tex(uint64_t serial); // 登记窗口(交换链)贴图:跨提交有效性账本永不收它 | Register a window (swapchain) texture: the cross-submit validity ledger never collects it
+5 -1
View File
@@ -92,7 +92,7 @@ enum {
OP_BIND_PROGRAM, OP_BIND_STATE, OP_BIND_VATTR, OP_BIND_VSTREAM, OP_BIND_VBUF,
OP_BIND_UBO, OP_BIND_SSBO, OP_BIND_TEX, OP_BIND_SAMP,
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_COUNT_
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_SHADER_SCRATCH, OP_WAIT_SYNC, OP_FENCE_SYNC, OP_WAIT_EVENT, OP_COUNT_
};
// 载荷(紧跟 op_hdr)
// Payload (immediately follows op_hdr)
@@ -120,6 +120,7 @@ typedef struct { const tex_t *src, *dst; view_t sv, dv; uint8_t has_sv, has_dv;
typedef struct { const tex_t *tex; view_t view; uint8_t has_view, is_uint; NVNcopyRegion r; int32_t mask; union { float f[4]; uint32_t u[4]; } c; } p_clear_tex;
typedef struct { int64_t stride; } p_copy_stride;
typedef struct { float rgba[4]; } p_blend_color;
typedef struct { sync_t *sync; int32_t condition, flags; } p_sync; // OP_WAIT_SYNC / OP_FENCE_SYNC(仅 Android 录制) | OP_WAIT_SYNC / OP_FENCE_SYNC (recorded on Android only)
// Metal 回放层入口(nvn_mtl.m):把一组命令句柄回放进当前提交
// Entry point of the Metal replay layer (nvn_mtl.m): replays a set of command handles into the current submission
@@ -171,6 +172,9 @@ void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNc
void mtl_reg_tex(int id, const tex_t *t, const view_t *v);
void mtl_reg_samp(int id, const samp_par *p);
void mtl_prog_release(prog_t *p);
#ifdef __ANDROID__
void mtl_set_window_origin_mode(int mode);
#endif
// 新序号(> 0,全局递增)
// New serial (> 0, globally increasing)
uint64_t nvn_new_serial(void);
+1 -1
View File
@@ -2,7 +2,7 @@
dmsh_xlate.dll aff3b70cff6bf29e
Ryujinx.Graphics.Shader.dll 72886c0b30bc0016
Ryujinx.Common.dll 614dced78b44547d
xlate_source 1cc46907ca1ee8d0
xlate_source d379d76ef969729f
spirv-cross c95d3fc88f6ae5f5
metal_macosx Apple metal version 32023.883 (metalfe-32023.883)
metal_iphoneos Apple metal version 32023.883 (metalfe-32023.883)
+378
View File
@@ -0,0 +1,378 @@
#!/usr/bin/env python3
# Vulkan 路线离线出包(Android):Switch 原版着色器 → SPIR-V(dmsh_xlate,Ryujinx 翻译器)→ 直接给 Vulkan 用,不经 spirv-cross / Metal。
# 与 dmsh_build.py 共用作业构造(作答表 nvn/shader_facts.tsv、映射表 nvn/shader_map.tsv、c1、内嵌着色器);反射直接从 SPIR-V 的名字与修饰里读,
# 资源分类与 dmsh_build.reflect 同口径(Ryujinx 的资源名 spirv-cross 原样保留进 MSL,所以同一套名字规则在 SPIR-V 上同样成立)。
# 改写:描述符组号按阶段分开——顶点 / 计算 = 0,像素 = 1(Ryujinx 一律放进第 0 组,绑定号各阶段都从 1 起,同一管线里会撞)。
# 用法:dmsh_vk.py <Switch 着色器包目录> <输出目录> [键…](不给键 = 全部) 环境:XLATE=翻译工具,MAIN=Switch main NSO(内嵌着色器),J=并发,SPIRV_VAL=校验工具
# 产物:<输出目录>/<键>.spv(已改组号)、<输出目录>/<键>.vk.json(反射)、<输出目录>/_vk_build.json(逐键结果);
# <输出目录>/rt/:设备端运行时缓存(nvn_vk.c 读)= shader_index.bin(控制段 → 键)+ <键>.vkmeta(绑定表)+ <键>.spv.gz
# PACK_ONLY=1 只按已有 .spv / .vk.json 重出 rt/;GLSLC=glslc 时一并编译 main 内嵌的 4 个计数报告内核(nvn_builtin.h)
# SB_ALIGN=宿主存储缓冲偏移对齐(缺省 64 = Adreno):翻译器按 base & -SB_ALIGN 求 SSBO 偏移,vkmeta 绑定标志位 1 告诉宿主可下对齐绑定、免拷贝;16 = 与 iOS 同样的翻译
# Vulkan-route offline build (Android): original Switch shaders → SPIR-V (dmsh_xlate, the Ryujinx translator) → used by Vulkan directly, no spirv-cross / Metal.
# Shares job construction with dmsh_build.py (answer table nvn/shader_facts.tsv, mapping table nvn/shader_map.tsv, c1, embedded shaders); reflection is read straight from SPIR-V names and decorations,
# resource classification follows dmsh_build.reflect (spirv-cross keeps Ryujinx's resource names in the MSL unchanged, so the same naming rules hold on SPIR-V).
# Rewrite: descriptor set numbers are split by stage - vertex / compute = 0, pixel = 1 (Ryujinx puts everything in set 0 with binding numbers starting at 1 in every stage, which collide within one pipeline).
# Usage: dmsh_vk.py <Switch shader package dir> <output dir> [key...] (no keys = all) Environment: XLATE=translator, MAIN=Switch main NSO (embedded shaders), J=concurrency, SPIRV_VAL=validator
# Output: <output dir>/<key>.spv (set numbers rewritten), <output dir>/<key>.vk.json (reflection), <output dir>/_vk_build.json (per-key results);
# <output dir>/rt/: the on-device runtime cache (read by nvn_vk.c) = shader_index.bin (control segment → key) + <key>.vkmeta (binding table) + <key>.spv.gz
# PACK_ONLY=1 only re-emits rt/ from the existing .spv / .vk.json; with GLSLC=glslc the 4 counter-report kernels embedded in main (nvn_builtin.h) are compiled too
# SB_ALIGN=host storage buffer offset alignment (default 64 = Adreno): the translator takes SSBO offsets from base & -SB_ALIGN, and vkmeta binding flag bit 1 tells the host it may bind aligned down without copying; 16 = the same translation as iOS
import os, sys, re, json, struct, gzip, hashlib, shutil, subprocess, tempfile, collections, concurrent.futures as cf
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE); import dmsh_facts
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work')
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:])
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
SPIRV_VAL = os.environ.get('SPIRV_VAL', shutil.which('spirv-val') or '')
MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
FACTS = dmsh_facts.load()
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv')
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120
SET_OF = {'vs': 0, 'cs': 0, 'ps': 1}
def records(d):
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
loc, stage_of = {}, {}
for ln in open(MAP):
c = ln.rstrip('\n').split('\t')
if len(c) > 4 and c[0].endswith('.bin'): loc.setdefault(c[3], (c[0], int(c[1])))
if len(c) > 4 and c[0].startswith('main.rodata@'):
loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
def main_rec(mi, o):
# 同 dmsh_build.main_rec:内嵌代码区紧贴控制段之前 | same as dmsh_build.main_rec: the embedded code area sits right before the control segment
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
if g < 0 or mi[o:o + 4] != bytes.fromhex('34127698'): sys.exit(f'【红】main 映像 @{o:#x} 不是内嵌着色器控制段(MAIN={MAIN})')
return bytes(0x38) + mi[g:o + 0x880]
def job_for(key, name, rec, w):
# 同 dmsh_build.job_for | same as dmsh_build.job_for
ci = rec.find(bytes.fromhex('34127698')); code = rec[0x38:ci]; stage = stage_of.get(key, name[:2])
c1o, c1t = struct.unpack_from('<2I', rec, ci + 0x700)
c1 = rec[0x38 + c1o:0x38 + c1t]
if stage != 'cs': code = code[0x30:]
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1',
'sb_align': int(os.environ.get('SB_ALIGN', '64'))} # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
if key not in FACTS: j['pc_missing'] = True; return j, c1
j.update(FACTS[key])
return j, c1
def decode_tex(name):
# 同 dmsh_build.decode_tex | same as dmsh_build.decode_tex
m = re.match(r'[a-z]+_[ti]\w*?_(?:cb(\d+)|tcb)_([0-9A-F]+)', name)
if not m: return None
slots = int(m.group(1)) if m.group(1) else -1; h = int(m.group(2), 16)
tb = (slots & 0xffff) if slots >= 0 else 2; sb = ((slots >> 16) - 1) if slots >= 0 and (slots >> 16) else tb
o0, o1, ty = h & 0x3fff, (h >> 14) & 0x3fff, h >> 28
def slot(word, base, cb): return (word * 4 - base) // 8 if cb == 2 and word * 4 >= base and (word * 4 - base) % 8 == 0 else None
words = [o0] + ([o1] if ty else [])
if re.match(r'[a-z]+_i', name):
return next((slot(x, IMG_BASE, tb) for x in words if IMG_BASE <= x * 4 < TEX_BASE and slot(x, IMG_BASE, tb) is not None), None), None, ty
t = next((slot(x, TEX_BASE, tb) for x in words if slot(x, TEX_BASE, tb) is not None and x * 4 < SAMP_BASE), None)
s = next((slot(x, SAMP_BASE, sb) for x in words if x * 4 >= SAMP_BASE and slot(x, SAMP_BASE, sb) is not None), None)
return t, s, ty
# ---- SPIR-V 解析 | SPIR-V parsing ----
OP_NAME, OP_DECORATE, OP_VARIABLE, OP_TYPE_POINTER, OP_ENTRY, OP_EXEC_MODE = 5, 71, 59, 32, 15, 16
OP_TYPE_IMAGE, OP_TYPE_SAMPLER, OP_TYPE_SAMPLED_IMAGE, OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY, OP_TYPE_STRUCT = 25, 26, 27, 28, 29, 30
DEC_BINDING, DEC_SET, DEC_LOCATION, DEC_BUILTIN = 33, 34, 30, 11
SC_UNIFORM_CONSTANT, SC_INPUT, SC_UNIFORM, SC_OUTPUT, SC_STORAGE_BUFFER = 0, 1, 2, 3, 12
def spv_insts(words):
o = 5
while o < len(words):
n, op = words[o] >> 16, words[o] & 0xffff
if not n or o + n > len(words): raise ValueError(f'SPIR-V 指令越界 @{o}')
yield o, op, words[o + 1:o + n]; o += n
def spv_str(ops):
b = struct.pack(f'<{len(ops)}I', *ops); return b[:b.index(0)].decode()
def reflect_spv(key, stage, words, res):
names, deco, types, var = {}, collections.defaultdict(dict), {}, {}
for o, op, a in spv_insts(words):
if op == OP_NAME: names[a[0]] = spv_str(a[1:])
elif op == OP_DECORATE and len(a) >= 2: deco[a[0]][a[1]] = a[2] if len(a) > 2 else 1
elif 19 <= op <= 39: types[a[0]] = (op, a[1:])
elif op == OP_VARIABLE: var[a[1]] = (a[0], a[2])
def pointee(tid):
t = types.get(tid); return t[1][1] if t and t[0] == OP_TYPE_POINTER else None
def base(tid):
while tid in types and types[tid][0] in (OP_TYPE_ARRAY, OP_TYPE_RUNTIME_ARRAY): tid = types[tid][1][0]
return tid
def desc_type(sc, tid):
"""VkDescriptorType:0 采样器、1 组合、2 采样图像、3 存储图像、4 uniform 纹素缓冲、5 存储纹素缓冲、6 uniform 缓冲、7 存储缓冲 | VkDescriptorType numbering"""
t = types.get(base(tid))
if sc == SC_UNIFORM: return 7 if deco[base(tid)].get(3) else 6 # BufferBlock(3) 旧式存储缓冲 | BufferBlock (3) is the legacy storage buffer form
if sc == SC_STORAGE_BUFFER: return 7
if not t: return None
if t[0] == OP_TYPE_SAMPLER: return 0
if t[0] == OP_TYPE_SAMPLED_IMAGE:
im = types[t[1][0]]; return 4 if im[1][1] == 5 else 1 # Dim Buffer = 5
if t[0] == OP_TYPE_IMAGE:
dim, sampled = t[1][1], t[1][5]
if dim == 5: return 4 if sampled == 1 else 5
return 2 if sampled == 1 else 3
return None
binds = []
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
sb_by_binding = {b['binding']: (i, b) for i, b in enumerate(sb_sorted)}
sbase = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}[stage]
for vid, (ptype, sc) in var.items():
if sc not in (SC_UNIFORM_CONSTANT, SC_UNIFORM, SC_STORAGE_BUFFER) or DEC_BINDING not in deco[vid]: continue
nm = names.get(vid, ''); ty = desc_type(sc, pointee(ptype))
tdef = types.get(pointee(ptype)); count = 1
if tdef and tdef[0] == OP_TYPE_ARRAY: count = -1 # 描述符数组:Ryujinx 只在无绑定贴图时出,这里不支持 | descriptor array: Ryujinx only emits it for bindless textures; unsupported here
e = {'name': nm, 'binding': deco[vid][DEC_BINDING], 'set': deco[vid].get(DEC_SET, 0), 'vk_type': ty, 'count': count, 'var': vid}
if nm == 'support_buffer': e['kind'] = 'support'
elif re.fullmatch(r'[a-z]+_c(\d+)', nm):
n = int(re.fullmatch(r'[a-z]+_c(\d+)', nm).group(1))
e.update(kind='cbuf', reg=n - 3) if 3 <= n <= 16 else e.update(kind='c1' if n == 1 else 'drvcb', bank=n)
elif re.fullmatch(r'[a-z]+_s(\d+)', nm):
idx, b = sb_by_binding.get(e['binding'], (None, None))
e.update(kind='sbuf', index=idx)
off = b['cb_offset'] * 4 if b and b['cb_slot'] == 0 else None
if stage == 'cs' and off is not None and 0x210 <= off < 0x310 and (off - 0x210) % 16 == 0:
e.update(kind='ubo_ptr', reg=(off - 0x210) // 16)
else: e['reg'] = (off - sbase) // 16 if off is not None and 0 <= off - sbase < 0x100 and (off - sbase) % 16 == 0 else None
e['rw'] = bool(b and b['flags'] & 2)
elif ty == 0:
t, s, hty = decode_tex(nm[:-5] if nm.endswith('Smplr') else nm) or (None, None, 0)
e.update(kind='samp', reg=s) if hty else e.update(kind='samp_tex', reg=t)
else:
d = decode_tex(nm)
if not d: e['kind'] = '?'
else:
img = bool(re.match(r'[a-z]+_i', nm))
e.update(kind='img' if img else ('tbuf' if ty in (4, 5) else 'tex'), reg=d[0])
if not img and ty == 1: # 组合采样:采样器号取同一句柄(类型 0 = 贴图槽句柄高位) | combined: sampler from the same handle (type 0 = high bits of the texture slot's handle)
e['samp'] = d[1] if d[2] else None; e['samp_from_tex'] = not d[2]
binds.append(e)
binds.sort(key=lambda b: b['binding'])
inputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_INPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
outputs = sorted(deco[v][DEC_LOCATION] for v, (_, sc) in var.items() if sc == SC_OUTPUT and DEC_LOCATION in deco[v] and DEC_BUILTIN not in deco[v])
return binds, inputs, outputs
def drv_reads(words, binds):
"""对驱动段 c0 / c2 的访问:OpAccessChain(var, 0, 常量 vec4 下标, 常量分量) → 字节偏移;非常量 → 动态 | accesses to driver segments c0 / c2"""
consts, out = {}, {}
for o, op, a in spv_insts(words):
if op == 43 and len(a) == 3: consts[a[1]] = a[2]
drv = {b['var']: b['bank'] for b in binds if b['kind'] == 'drvcb'}
for o, op, a in spv_insts(words):
if op in (65, 66) and len(a) >= 3 and a[2] in drv:
d = out.setdefault(str(drv[a[2]]), {'offsets': set(), 'dynamic': False})
idx = a[3:]
if len(idx) >= 2 and all(i in consts for i in idx[:3]): d['offsets'].add(consts[idx[1]] * 16 + (consts[idx[2]] * 4 if len(idx) > 2 else 0))
else: d['dynamic'] = True
return {k: {'offsets': sorted(v['offsets']), 'dynamic': v['dynamic']} for k, v in out.items()}
def set_rewrite(words, stage):
"""组号按阶段改写;去掉 Ryujinx 无条件声明、实际没用到的能力(Float64 / Int64 / 像素互锁 / 绘制参数),免得驱动按缺特性拒收
Rewrite set numbers per stage; drop capabilities Ryujinx declares unconditionally but never uses (Float64 / Int64 / pixel interlock / draw parameters), so drivers lacking the feature do not reject the module"""
s = SET_OF[stage]; used = set(); keep = []
for o, op, a in spv_insts(words):
if op == 22 and a[1] == 64: used.add(10) # OpTypeFloat 64 → Float64
if op == 21 and a[1] == 64: used.add(11) # OpTypeInt 64 → Int64
if op in (5364, 5365): used.add(5378) # Begin / EndInvocationInterlockEXT
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_BUILTIN and a[2] in (4424, 4425, 4426): used.add(4427) # BaseVertex / BaseInstance / DrawIndex
drop = {10, 11, 5378, 4427} - used
have = {a[0] for o, op, a in spv_insts(words) if op == 17}
unk = any(op == OP_TYPE_IMAGE and a[6] == 2 and a[7] == 0 for o, op, a in spv_insts(words)) # 无格式存储图像 | storage image with Unknown format
add = [c for c in (55, 56) if unk and c not in have] # Storage Image Read / WriteWithoutFormat(Adreno 两个特性都有 | Adreno has both features)
for o, op, a in spv_insts(words):
if op == 17 and add:
for c in add: keep.extend([2 << 16 | 17, c])
add = []
ins = list(words[o:o + 1 + len(a)])
if op == 17 and a[0] in drop: continue
if op == 10 and spv_str(a) == 'SPV_EXT_fragment_shader_interlock' and 5378 in drop: continue
if op == 16 and a[1] in (5366, 5367, 5368, 5369, 5370, 5371) and 5378 in drop: continue # 互锁执行模式 | interlock execution modes
if op == OP_DECORATE and len(a) == 3 and a[1] == DEC_SET: ins[3] = s
keep.extend(ins)
return list(words[:5]) + keep
# 翻译器对每个着色器都声明 GroupNonUniform{Vote,Ballot,Shuffle}(cap 62/64/65),实际只有少数 ps / cs 用到;
# Adreno 的 subgroup 只支持 fragment / compute,顶点着色器带着这些声明会被拒,所以没用到 subgroup 指令 / 内建量的就把声明去掉
# The translator declares GroupNonUniform{Vote,Ballot,Shuffle} (cap 62/64/65) on every shader but only a few ps / cs use them;
# Adreno supports subgroups only in fragment / compute and a vertex shader carrying them is rejected, so drop the declarations when no subgroup instruction / builtin is used
SUBGROUP_CAPS = set(range(61, 69))
SUBGROUP_BUILTINS = {36, 37, 38, 39, 40, 41, 4416, 4417, 4418, 4419, 4420}
def strip_subgroup(words):
used = False
for o, op, a in spv_insts(words):
if 333 <= op <= 366 or op in (4421, 4422, 4428, 4429, 4430, 4431, 4432) or \
(op == 71 and len(a) >= 3 and a[1] == DEC_BUILTIN and a[2] in SUBGROUP_BUILTINS): used = True; break
if used: return words
keep = [x for o, op, a in spv_insts(words) for x in words[o:o + (words[o] >> 16)] if not (op == 17 and a[0] in SUBGROUP_CAPS)]
return list(words[:5]) + keep
def finish(key, w, j, c1, name, k):
if j['stage'] not in SET_OF: return 'skip stage ' + j['stage'], None # 外壳 / 域各 1 个,Metal 回放层同样不用 | one hull / one domain shader; the Metal replay does not use them either
spv = os.path.join(w, key + '.spv')
if not os.path.exists(spv): return 'no spv', None
res = json.load(open(os.path.join(w, key + '.res.json')))
data = open(spv, 'rb').read(); words = list(struct.unpack(f'<{len(data) // 4}I', data))
if words[0] != 0x07230203: return 'bad magic', None
binds, inputs, outputs = reflect_spv(key, j['stage'], words, res)
words = set_rewrite(words, j['stage'])
words = strip_subgroup(words)
open(os.path.join(out, key + '.spv'), 'wb').write(struct.pack(f'<{len(words)}I', *words))
caps = sorted({a[0] for o, op, a in spv_insts(words) if op == 17})
exts = sorted({spv_str(a) for o, op, a in spv_insts(words) if op == 10})
refl = {'key': key, 'stage': j['stage'], 'set': SET_OF[j['stage']], 'source': f'{name}#{k}', 'c1': c1.hex(),
'local': j.get('local'), 'shared': j.get('shared', 0), 'notes': res['notes'] + (['pc_missing'] if j.get('pc_missing') else []),
'bindings': [{x: v for x, v in b.items() if x not in ('var', 'set')} for b in binds], 'inputs': inputs, 'outputs': outputs,
'sb_align': res.get('sb_align', 16), 'frag_out_map': res.get('frag_out_map'), 'uses_frag_coord': res.get('uses_frag_coord'),
'drv_reads': drv_reads(words, binds), 'caps': caps, 'exts': exts}
bad = [b for b in binds if b['kind'] == '?' or b['vk_type'] is None or b['count'] != 1 or
(b['kind'] in ('cbuf', 'samp', 'samp_tex', 'tex', 'img', 'tbuf', 'sbuf', 'ubo_ptr') and b.get('reg') is None)]
if bad: refl['unresolved'] = [b['name'] for b in bad]
json.dump(refl, open(os.path.join(out, key + '.vk.json'), 'w'), ensure_ascii=False, indent=1)
if SPIRV_VAL:
r = subprocess.run([SPIRV_VAL, '--target-env', 'vulkan1.1', os.path.join(out, key + '.spv')], capture_output=True, text=True)
if r.returncode: return 'spirv-val: ' + (r.stdout + r.stderr).strip().splitlines()[0][:140], refl
return ('unresolved' if bad else 'ok'), refl
# ---- 设备端运行时缓存(nvn_vk.c 的 RHeader / RBinding 布局) | on-device runtime cache (RHeader / RBinding layout of nvn_vk.c) ----
STAGE_NO = {'vs': 0, 'ps': 1, 'cs': 5}
# 资源种类码 | resource kind codes: 1 support 2 uniform 3 storage 4 texture 6 image 7 c1 8 driver table 9 uniform via storage 10 texel buffer
KIND_NO = {'support': 1, 'cbuf': 2, 'sbuf': 3, 'tex': 4, 'img': 6, 'c1': 7, 'drvcb': 8, 'ubo_ptr': 9, 'tbuf': 10}
# 计数报告内核(nvn_builtin.h 的 Vulkan 版):u64 用 uvec2 进位算,免 Int64 | counter-report kernels (Vulkan form of nvn_builtin.h): u64 as uvec2 with carry, no Int64
BUILTIN = {'d0f769bb916bbba9': (0x1df10e8, 'ST(LD(id * 4u));'),
'16479cc6d75c2b28': (0x1df1a94, 'ST(LD(id * 4u + 2u));'),
'0687e2ef95133577': (0x1df2440, 'ST(SUB(LD(id * 8u + 4u), LD(id * 8u)));'),
'4df5909e6dabee05': (0x1df2dec, 'ST(SUB(LD(id * 8u + 6u), LD(id * 8u + 2u)));')}
BUILTIN_GLSL = """#version 450
layout(local_size_x = 32) in;
layout(set = 0, binding = 0) uniform U { uint n; } u;
layout(set = 0, binding = 1) readonly buffer S { uint s[]; };
layout(set = 0, binding = 2) writeonly buffer D { uint d[]; };
#define LD(w) uvec2(s[w], s[(w) + 1u])
#define ST(v) { uvec2 v_ = v; d[id * 2u] = v_.x; d[id * 2u + 1u] = v_.y; }
uvec2 SUB(uvec2 a, uvec2 b) { uint borrow; uint lo = usubBorrow(a.x, b.x, borrow); return uvec2(lo, a.y - b.y - borrow); }
void main() { uint id = (gl_WorkGroupID.x << 5) + gl_LocalInvocationID.x; if (id >= u.n) return; BODY }
"""
def vkmeta(refl, spv_size):
st = STAGE_NO[refl['stage']]; bs = refl['bindings']
attrs = [(l, 0) for l in refl['inputs']] if refl['stage'] == 'vs' else []
c1 = bytes.fromhex(refl['c1']).rstrip(b'\0')
c1 += bytes(-len(c1) % 4)
caps = refl['caps']; local = refl.get('local') or [0, 0, 0]
fout = refl.get('frag_out_map'); fout = 0 if fout is None else fout
if len(bs) > 64 or len(attrs) > 32 or len(caps) > 32 or len(c1) > 4096: raise ValueError(f"{refl['key']} 超出 vkmeta 上限")
h = struct.pack('<11I', 0x4d4b5644, 1, st, len(bs), len(attrs), len(c1), len(caps), *local[:3], fout) + struct.pack('<I', spv_size)
for b in bs:
k = KIND_NO[b['kind']]
slot = 0 if k in (1, 7) else b['bank'] if k == 8 else b['reg']
samp = b['samp'] if k == 4 and b.get('samp') is not None else -1
# 位 0 可写;位 1 着色器偏移相对 base & -64(翻译器实际答的对齐),宿主可下对齐绑定 | bit 0 writable; bit 1 shader offsets are relative to base & -64 (the alignment the translator actually used), so the host may bind aligned down
flags = (int(bool(b.get('rw'))) | (2 if refl.get('sb_align', 16) == 64 else 0)) if k == 3 else 0
h += struct.pack('<4I2i2I', SET_OF[refl['stage']], b['binding'], b['vk_type'], k, slot, samp, 1, flags)
for a in attrs: h += struct.pack('<2I', *a)
h += struct.pack(f'<{len(caps)}I', *caps) + c1
return h
def emit_runtime(entries):
"""entries: [(键, 控制段 0x880 字节, 反射, SPIR-V 字节)] → <out>/rt | entries: [(key, 0x880-byte control segment, reflection, SPIR-V bytes)] → <out>/rt"""
rt = os.path.join(out, 'rt'); os.makedirs(rt, exist_ok=True)
idx = [struct.pack('<3I', 0x494b5644, 1, len(entries))]
for key, ctl, refl, spv in entries:
assert len(ctl) == 0x880 and len(key) == 16
words = strip_subgroup(list(struct.unpack(f'<{len(spv) // 4}I', spv))) # PACK_ONLY 读的旧产物也要剔 | old outputs read by PACK_ONLY need it too
spv = struct.pack(f'<{len(words)}I', *words); refl = dict(refl, caps=sorted({a[0] for o, op, a in spv_insts(words) if op == 17}))
idx.append(key.encode() + struct.pack('<I', STAGE_NO[refl['stage']]) + ctl)
open(os.path.join(rt, key + '.vkmeta'), 'wb').write(vkmeta(refl, len(spv)))
open(os.path.join(rt, key + '.spv.gz'), 'wb').write(gzip.compress(spv, 9, mtime=0))
open(os.path.join(rt, 'shader_index.bin'), 'wb').write(b''.join(idx))
print(f'运行时缓存:{len(entries)} 条 → {rt}')
def builtin_entries(mi):
glslc = os.environ.get('GLSLC')
if not glslc: print('【黄】没给 GLSLC,跳过 4 个内嵌计数报告内核'); return []
res = []
for key, (o, body) in BUILTIN.items():
ctl = mi[o:o + 0x880]
if hashlib.sha256(ctl).hexdigest()[:16] != key: sys.exit(f'【红】main @{o:#x} 控制段哈希与内嵌内核键 {key} 不符')
with tempfile.TemporaryDirectory() as t:
src = os.path.join(t, 'k.comp'); open(src, 'w').write(BUILTIN_GLSL.replace('BODY', body))
r = subprocess.run([glslc, '--target-env=vulkan1.1', '-O', src, '-o', os.path.join(t, 'k.spv')], capture_output=True, text=True)
if r.returncode: sys.exit('【红】内嵌内核编译失败:' + r.stderr)
spv = open(os.path.join(t, 'k.spv'), 'rb').read()
refl = {'key': key, 'stage': 'cs', 'c1': '', 'local': [32, 1, 1], 'inputs': [], 'caps': [1], 'frag_out_map': 0,
'bindings': [{'binding': 0, 'vk_type': 6, 'kind': 'cbuf', 'reg': 0},
{'binding': 1, 'vk_type': 7, 'kind': 'sbuf', 'reg': 0, 'rw': False},
{'binding': 2, 'vk_type': 7, 'kind': 'sbuf', 'reg': 1, 'rw': True}]}
res.append((key, ctl, refl, spv))
return res
def main():
keys = sorted(want) if want else sorted(loc)
NJ = int(os.environ.get('J', '8'))
os.makedirs(out, exist_ok=True)
w = tempfile.mkdtemp(prefix='dmsh_vk_', dir=os.environ.get('WORK'))
packs, jobs, c1s, ctls = {}, {}, {}, {}
pack_only = os.environ.get('PACK_ONLY') == '1'
for key in keys:
name, k = loc[key]
if name.startswith('main.rodata@'):
if 'main' not in packs:
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
packs['main'] = nsoimg.load(MAIN)
rec = main_rec(packs['main'], k)
else:
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
rec = packs[name][k]
ci = rec.find(bytes.fromhex('34127698'))
if hashlib.sha256(rec[ci:ci + 0x880]).hexdigest()[:16] != key: sys.exit(f'【红】{name}#{k} 控制段哈希与键 {key} 不符')
ctls[key] = rec[ci:ci + 0x880]
if not pack_only: jobs[key], c1s[key] = job_for(key, name, rec, w)
if 'main' not in packs and os.environ.get('GLSLC'):
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
packs['main'] = nsoimg.load(MAIN)
if pack_only:
shutil.rmtree(w, ignore_errors=True)
st = {r['key']: r['st'] for r in json.load(open(os.path.join(out, '_vk_build.json')))}
ents = [(k, ctls[k], json.load(open(os.path.join(out, k + '.vk.json'))), open(os.path.join(out, k + '.spv'), 'rb').read())
for k in keys if st.get(k) == 'ok']
emit_runtime(ents + builtin_entries(packs.get('main', b''))); return
chunks = [c for c in (keys[i::NJ] for i in range(NJ)) if c]
def xl(ch):
jp = os.path.join(w, f'job_{ch[0]}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
return subprocess.run([XLATE, jp, w], capture_output=True, text=True)
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, chunks))
xerr = {}
for r in xr:
for ln in r.stderr.splitlines():
m = re.match(r'【红】(\w+):(.*)', ln)
if m: xerr[m.group(1)] = m.group(2)[:160]
def fin(key):
if key in xerr: return key, 'xlate: ' + xerr[key], None
st, refl = finish(key, w, jobs[key], c1s[key], *loc[key])
return key, st, refl
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(fin, keys))
shutil.rmtree(w, ignore_errors=True)
st = collections.Counter(r[1].split(':')[0] for r in res)
print(f'着色器 {len(res)}:' + ','.join(f'{k} {v}' for k, v in st.most_common()))
for e, n in collections.Counter(r[1] for r in res if r[1] != 'ok').most_common(12): print(f' {n:5d} {e}')
ok = [r[2] for r in res if r[2]]
for e, n in collections.Counter(u for x in ok for u in x.get('unresolved', [])).most_common(8): print(f' 未解绑定 {n:5d} {e}')
for e, n in collections.Counter(c for x in ok for c in x['caps']).most_common(): print(f' cap {e}: {n}')
for e, n in collections.Counter(c for x in ok for c in x['exts']).most_common(): print(f' ext {e}: {n}')
dr = collections.Counter()
for x in ok:
for bank, d in x['drv_reads'].items():
dr[f'c{bank} dyn'] += d['dynamic']
for o in d['offsets']: dr[f'c{bank}+{o:#x}'] += 1
print('驱动段读取(前 20):', ', '.join(f'{k}×{v}' for k, v in dr.most_common(20)))
json.dump([{'key': r[0], 'st': r[1]} for r in res], open(os.path.join(out, '_vk_build.json'), 'w'), ensure_ascii=False)
emit_runtime([(r[0], ctls[r[0]], r[2], open(os.path.join(out, r[0] + '.spv'), 'rb').read()) for r in res if r[1] == 'ok']
+ builtin_entries(packs.get('main', b'')))
if __name__ == '__main__': main()
+5 -1
View File
@@ -93,6 +93,10 @@ static class SwshXlate
false /* 不做 Y 取反 | no Y flip */, true /* 原点左上 | origin upper-left */, false);
}
public bool QueryHostSupportsTextureShadowLod() => true;
// 作业 sb_align:宿主存储缓冲偏移对齐(Adreno 64)。大于 NVN 的 16 时,着色器按 base & -sb_align 求偏移,宿主下对齐绑定、不再拷贝
// Job sb_align: host storage buffer offset alignment (Adreno 64). Above NVN's 16, shaders take offsets from base & -sb_align, so the host binds aligned down without copying
public int QueryHostStorageBufferOffsetAlignment() => _job["sb_align"] is JsonNode n ? (int)n : 16;
public bool QueryHasUnalignedStorageBuffer() => QueryHostStorageBufferOffsetAlignment() > 16;
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
@@ -126,7 +130,7 @@ static class SwshXlate
{
["key"] = key, ["stage"] = (string)job["stage"], ["notes"] = new JsonArray(acc.Notes.ConvertAll(n => (JsonNode)n).ToArray()),
["cbufs"] = new JsonArray(), ["sbufs"] = new JsonArray(), ["textures"] = new JsonArray(), ["images"] = new JsonArray(),
["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
["sb_align"] = acc.QueryHostStorageBufferOffsetAlignment(), ["uses_frag_coord"] = p.Info.UsesFragCoord, ["frag_out_map"] = p.Info.FragmentOutputMap,
};
foreach (var b in p.Info.CBuffers) res["cbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot });
foreach (var b in p.Info.SBuffers) res["sbufs"].AsArray().Add(new JsonObject { ["binding"] = b.Binding, ["slot"] = b.Slot, ["cb_slot"] = b.SbCbSlot, ["cb_offset"] = b.SbCbOffset, ["flags"] = (int)b.Flags });
+3
View File
@@ -4,3 +4,6 @@ dm_hud_exp.h
dm_bright_levels.inc
*.h.tmp
*.inc.tmp
# Android generated binaries, logs, caches and game frame captures
build-android/
+3 -3
View File
@@ -61,7 +61,7 @@ SRC=\
touch_mac.c \
../ios/Sources/cloud_ios.m \
../ios/Sources/dm_gamepad.m \
../ios/Sources/dm_touch_controls.c \
../touch/dm_touch_controls.c \
$(sort $(wildcard hle_*.c))
# NVN 空设备 + nn::vi(dm/gfx/)
# 按通配纳入 dm/gfx 与 dm/gfx/nvn 下的源(tests/ metal/ 不进宿主):新增文件不改这一行
@@ -95,9 +95,9 @@ dm_hud_exp.h: ../ios/tools/gen_hud_exp.py ../ios/tools/romfs_art.py
dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py
$(NEED_ROMFS)
python3 ../tools/gen_bright_levels.py "$(ROMFS)" > $@.tmp && mv $@.tmp $@
dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH)
dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH)
clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController
# 老接口版宿主(图形后端不用 Metal 4,目标 macOS 15.0):同一棵树、同一份源码,只多一个编译开关;不在缺省目标里,要用时 make dmhost_m3
# Older-API host (graphics backend without Metal 4, target macOS 15.0): the same tree and the same source, with just one more compile switch; not in the default targets, run make dmhost_m3 when needed
dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH)
dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../touch/dm_touch_controls.[ch] $(GFX_H) $(GENH)
clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController
+64
View File
@@ -0,0 +1,64 @@
# Android(arm64,仅 Adreno 机型)无头宿主:adb shell 直接跑,用来先把引导链跑通;图形 / 音频 / 前端后续接入
# Android (arm64, Adreno devices only) headless host: run directly from adb shell to get the boot chain working first; graphics / audio / front end come later
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
API ?= 33
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android$(API)-clang
OUT ?= build-android
# 表头:没有游戏文件时可用 DM_GENH_DIR 指向现成的表头目录 | generated headers: without game files, DM_GENH_DIR can point at a directory of ready-made headers
GENH_DIR ?= $(or $(DM_GENH_DIR),.)
# -ffixed-x18:x18 是客体的平台寄存器,宿主代码不许碰;16K 页对齐(Android 15+ 16K 页设备);保留 __start_/__stop_ 段登记表
# -ffixed-x18: x18 is the guest's platform register, host code must not touch it; 16K page alignment (Android 15+ 16K-page devices); keep the __start_/__stop_ section registration tables
CFLAGS = -O1 -g -Wall -Wno-unused-function -Wno-format -ffixed-x18 -fPIE \
-include compat/linux/compat_linux.h -Icompat/linux/include -I. -I$(GENH_DIR) -I../gfx/nvn/include -I../gfx/nvn
LDFLAGS = -pie -Wl,-z,max-page-size=16384 -Wl,-z,nostart-stop-gc -Wl,--export-dynamic
# APP=1:同一份源编成 libd2r.so 给 GameActivity 加载(android/app/),前端换成 front_app.c;APK 由 android/app/build_apk.sh 打
# APP=1: build the same sources into libd2r.so for GameActivity to load (android/app/), with front_app.c as the front end; the APK is packed by android/app/build_apk.sh
ifeq ($(APP),1)
OUT := build-android/app
CFLAGS := $(subst -fPIE,-fPIC,$(CFLAGS))
LDFLAGS := -shared -Wl,-soname,libd2r.so -Wl,-Bsymbolic -Wl,--no-undefined -Wl,-z,max-page-size=16384 -Wl,-z,nostart-stop-gc
endif
LIBS = -llog -lm -ldl -lz -landroid -laaudio
# 与 Makefile 同一份源单,去掉 macOS 专属(.m、touch_mac.c、front_mac.m、memstat.m)
# Same source list as Makefile, minus the macOS-only ones (.m, touch_mac.c, front_mac.m, memstat.m)
# Makefile 的 SRC 是续行写的(一行一个),读到第一条不带续行符的行为止 | Makefile's SRC uses continuation lines (one per line); read up to the first line without a continuation
SRC_MAC := $(filter %.c,$(shell awk '/^SRC=/{f=1} f{l=$$0; sub(/^SRC=/,"",l); c=(l ~ /[\\\\]$$/); sub(/[\\\\]$$/,"",l); print l; if(!c) exit}' Makefile))
SRC := $(filter-out touch_mac.c,$(SRC_MAC)) $(sort $(wildcard hle_*.c)) $(wildcard compat/linux/*.c) $(wildcard android/*.c)
ifeq ($(APP),1)
SRC := $(filter-out android/front_headless.c,$(SRC)) android/app/front_app.c android/app/touch_app.c \
../touch/dm_touch_game_bridge.c ../touch/dm_touch_game_state.c ../touch/dm_touch_game_identity.c ../touch/dm_touch_native_art.c
endif
GFX := $(sort $(wildcard ../gfx/*.c ../gfx/nvn/*.c ../gfx/tex/*.c))
LIBDEFLATE := $(shell sed -n 's/^LIBDEFLATE=//p' Makefile)
ASM := entry.S ../gfx/nvn/nvn_entry.S ../gfx/nvn/nvn_thunks.S
OBJ := $(patsubst %.c,$(OUT)/obj/%.o,$(subst ../,up/,$(SRC) $(GFX) $(LIBDEFLATE))) \
$(patsubst %.S,$(OUT)/obj/%.o,$(subst ../,up/,$(ASM)))
$(OUT)/dmhost: $(OBJ)
$(CC) $(LDFLAGS) -Wl,--error-limit=0 -o $@ $^ $(LIBS)
$(OUT)/libd2r.so: $(OBJ)
$(CC) $(LDFLAGS) -Wl,--error-limit=0 -o $@ $^ $(LIBS)
# 图形回放(gfx/、android/)是逐绘制热路径,用 -O2;其余宿主代码保持 -O1,与 Mac 构建一致
# Graphics replay (gfx/, android/) is the per-draw hot path, built at -O2; the rest of the host stays at -O1 like the Mac build
$(OUT)/obj/up/gfx/%.o $(OUT)/obj/android/%.o: CFLAGS += -O2
$(OUT)/obj/up/%.o: ../%.c
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) -c $< -o $@
$(OUT)/obj/%.o: %.c dm.h hle.h compat/linux/compat_linux.h
@mkdir -p $(dir $@)
$(CC) $(CFLAGS) -c $< -o $@
# Mach-O 汇编转 ELF:去符号前导 _、@PAGE/@PAGEOFF 换 ELF 写法、.cstring 换 .rodata
# Mach-O assembly to ELF: strip the leading _ of symbols, @PAGE/@PAGEOFF to the ELF forms, .cstring to .rodata
ASM2ELF = perl -pe 's/(?<![\w.])_([A-Za-z])/$$1/g; s/(\w+)\@PAGEOFF/:lo12:$$1/g; s/(\w+)\@PAGE\b/$$1/g; s/^\s*\.cstring\b/\t.section .rodata/'
$(OUT)/obj/up/%.o: ../%.S
@mkdir -p $(dir $@)
$(ASM2ELF) $< > $(@:.o=.elf.S) && $(CC) -c $(@:.o=.elf.S) -o $@
$(OUT)/obj/%.o: %.S
@mkdir -p $(dir $@)
$(ASM2ELF) $< > $(@:.o=.elf.S) && $(CC) -c $(@:.o=.elf.S) -o $@
clean:
rm -rf $(OUT)
.PHONY: clean
+67
View File
@@ -0,0 +1,67 @@
# Vulkan performance verification — 2026-10-13
Device: OnePlus 13, Adreno 830. Build: Android NDK 28.2.13676358, API 33, repository Android `-O1` build. Headless, audio disabled, existing game resources and `save.work`. Game content, shaders, caches and captures are excluded from Git.
## Observed results / 实测结果
The final binary ran under `timeout 90`. It produced a complete hero selection capture at frame 601, reached the frame 602 profile interval, received SIGTERM, drained GPU work, and exited through the timeout path (`rc=124`). Graceful shutdown took 0.043 seconds. No `STOP`, abort or crash occurred in this run. The final capture shows the camp, characters, fire, Chinese title/description and Create button without visible corruption.
| 60-frame interval | Existing baseline log, frame 602 | Final build, frame 602 |
|---|---:|---:|
| Elapsed | 38,066.393 ms | 9,557.800 ms |
| Pipeline creation | 11,268.754 ms | 0.000 ms |
| Draws | 68,566 | 81,902 |
| Actual Vulkan submissions | 240 (180 logged + 60 Present) | 240 |
| Render pass begins | One per draw in the old implementation | 4,380 |
| Graphics + compute pipeline hits / misses | Recreated each time | 82,382 / 0 |
| Framebuffer cache hits | Uncached | 83,702 |
Final steady hero selection intervals (frames 302 through 602) took 9.147–12.410 seconds per 60 frames, median 11.373 seconds, with about 81,800–82,000 draws per interval and zero pipeline creation time. The historical baseline and final run have different loading/animation timing and draw counts; this is a practical scene comparison, not a controlled benchmark with identical command traces. Sustained rendering remains roughly 5–6.5 FPS in this scene and still needs further CPU/upload/descriptor optimization.
最终版 90 秒无崩溃,角色选择第 601 帧正常,第 602 帧区间约 9.56 秒 / 60 帧。稳定区间约 9.15–12.41 秒 / 60 帧,pipeline 创建时间持续为零。旧日志约 38.07 秒 / 60 帧;两次运行的加载 / 动画时间及 draw 数不同,不作为严格同指令流 benchmark。
The disk cache successfully loaded 1,628,103 bytes at startup. An invalid 32-byte all-zero cache was rejected (`pipeline_cache_load bytes=0`) and the real-Vulkan regression still passed.
## Update: Redmi 25098RA98C (Adreno 710) — 2026-10-13
Changes: `BATCH_SLOTS` raised to 8; GPU timestamp queries report `gpu_ms` per interval; shader pack built with `SB_ALIGN=64` so storage buffers bind directly from `addr & -64` instead of being copied to aligned transient buffers; draw-time SSBO write detection now tests vkmeta flag bit 0 only. `DM_VK_PASSPROF=N` gives a per-pass GPU breakdown.
| Hero selection, 60-frame interval | Before (`redmi1`, old pack) | After (`redmi8`–`redmi10`, `rt64` pack) |
|---|---:|---:|
| Elapsed | 18,230–34,909 ms | 7,080–7,164 ms |
| Storage-buffer bind time | ~9,800 ms (up to 32,000 ms in later intervals) | ~400 ms |
| Transient buffers created | 8,309 | 0 |
| Render passes / pass breaks | 5,336 / 4,927 | 4,380 / 2,880 |
| GPU time (`gpu_ms`) | not measured | ~5,060 ms (≈85 ms/frame) |
| Draws | — | ~81,900 |
The scene now runs at about 8.4 FPS on this device (60 frames in ~7.1 s) and is GPU-bound: GPU time alone caps it near 12 FPS. `PASSPROF` shows one 1600×900 forward+ lighting pass (pixel shader `5c1ca4e7c3e4657c`, 385 draws) takes ~44 ms of ~87 ms per frame; `spirv-opt -O` made no difference. The 60 FPS target applies to Adreno 830-class devices, which still need re-measuring with this build.
更新(Redmi,Adreno 710):批次槽位改为 8,新增 GPU 时间戳 `gpu_ms`,着色器包使用 `SB_ALIGN=64` 后存储缓冲区按 64 字节对齐直接绑定,不再拷贝。角色选择每 60 帧从 18–35 秒降到约 7.1 秒,临时缓冲区创建从 8,309 降为 0;当前为 GPU 瓶颈(约 85 ms/帧,其中一个前向+光照 pass 约 44 ms)。60 FPS 目标需在 Adreno 830 上复测。Logs: `build-android/perf/redmi1.log`, `redmi8.log`–`redmi10.log`.
Update (WaitEvent, Redmi): `WAIT_PROFILE` showed every CPU wait came from `OP_WAIT_EVENT` (~5.1 s per 60 frames, two per frame); the host committed and CPU-waited for all prior GPU work although NVN's WaitEvent is a GPU-side wait, so CPU and GPU ran serially. Events already satisfied by queued signals now record only a barrier (`event_queued=120 event_blocked=0`). 60 frames: 7.7 s → 5.03–5.05 s (≈11.9 FPS), submits 4 → 2 per frame; elapsed now equals `gpu_ms`, so the scene is purely GPU-bound. The remaining `sync` wait (~2.6 s / 60, `sync_lag_max=5`) is the game's own one-frame-ahead throttle. Frame 841 matches the baseline. `DM_VK_EVENT_SYNC=1` restores the old path. Logs: `redmi18.log` (before), `redmi19.log` (after).
更新(WaitEvent):`WAIT_PROFILE` 显示所有 CPU 等待都来自 `OP_WAIT_EVENT`(每 60 帧约 5.1 秒、每帧 2 次)——宿主把 GPU 侧等待实现成了“提交 + CPU 等待之前全部 GPU 工作”,导致 CPU 与 GPU 串行。现在事件若可由排队的 signal 满足,只录屏障。每 60 帧 7.7 秒 → 约 5.04 秒(≈11.9 FPS),提交从 4 次/帧降到 2 次/帧,耗时等于 `gpu_ms`,完全 GPU 瓶颈。
Combined with `DM_VK_VRS=2x2` (opt-in): 60 frames 4.37 s (≈13.7 FPS), `gpu_ms` ≈4,356, sync wait ~1.85 s / 60; edges stay sharp, textures slightly softer (frame 841 mean abs diff 3.8 vs no VRS). Log: `redmi20.log`.
叠加 `DM_VK_VRS=2x2`(需手动开启):每 60 帧 4.37 秒(≈13.7 FPS),仍为 GPU 瓶颈;边缘清晰,纹理略软。
## Submission boundary / 提交边界
Deferred commits, reusable fence slots (eight since the update above) and completion publication are implemented. This game path still requires about four actual submissions per frame because explicit QueueFlush / CPU waits and Present end batches; after the WaitEvent change above it is two per frame. No draw creates a new fence or performs its own queue idle. Ordinary consecutive draws retain their render pass; feedback, storage writes and explicit barriers keep required boundaries. Thus the strict “one submit per frame” target has not been reached for this guest command stream.
已实现延迟提交与多槽 fence 轮转(上方更新后为八槽),但游戏的显式 Flush / 等待边界仍导致约 4 次真实提交 / 帧(WaitEvent 改动后为 2 次)。下一步若要继续减少次数,需要根据客体的实际同步消费点优化,不能直接删除这些边界。真实窗口的 WSI 同步优化仍待第四步验证。
## Validation / 验证
- Android host builds and links with no compiler warnings.
- Real Vulkan device regression: `VK_PERF_TEST_PASS` for full key equality after hash collision, immutable CPU input address reuse, GPU-authored input reuse, isolated writeback snapshots across submissions, timeout / fence checks, slot rotations past the ring size, events published while the guest only polls memory, descriptor pool growth past 8,192 sets, and capacity splitting without advancing the logical fence early.
- Invalid disk cache fallback passes the same GPU regression. Final game startup confirms a non-empty compatible disk cache load.
- Final game capture visually checked at frame 601. Headless shutdown drained in-flight work.
- `python3 dm/ios/tools/dm_i18n.py --check`: passes, 301 entries.
- `python3 dm/i18n/scan_literals.py`: fails on two existing unrelated strings in `dm/ios/tools/gen_romfs_overlay.py:200` and `dm/ios/tools/drop_light.py:65`; those files were not changed by this work.
- Khronos validation could not be enabled on this retail device: the Android loader returned `VK_ERROR_LAYER_NOT_PRESENT`, and `/data/local/debug/vulkan` is not writable by shell. No validation-layer-clean claim is made. Android's loader discovery restrictions are described in [the Android Vulkan implementation documentation](https://source.android.com/docs/core/graphics/implement-vulkan).
- Mac / iOS runtime, real-window WSI and AAudio were not exercised. The new QueueFlush declaration/call are guarded by `__ANDROID__`.
Reproduction commands and environment variables are in [README.md](README.md) / [README.zh-CN.md](README.zh-CN.md). Local evidence lives in ignored `dm/host/build-android/perf/`: `baseline.log`, `final.log`, `gpu-tests.log`, `cache-test.log`, and `final-0601.ppm` / `.png`. The device retains the original `dmhost`; the tested binary is `dmhost-perf-final` under `/data/local/tmp/d2r`.
+69
View File
@@ -0,0 +1,69 @@
# Android Vulkan headless backend
中文: [README.zh-CN.md](README.zh-CN.md)
The backend retains the NVN recorder's `mtl_*` interface. Headless rendering is verified on OnePlus 13 / Adreno 830. A minimal GameActivity app (window, raw touch, gamepad, text input) is in `app/`; AAudio and the touch HUD remain subsequent work.
## Build and test
Run from the repository root with generated host headers and your own rewritten game files:
```sh
make -C dm/host -f Makefile.android -j8
make -C dm/host/android/tests
adb push dm/host/build-android/tests/t_vk_perf /data/local/tmp/d2r/t_vk_perf
adb shell /data/local/tmp/d2r/t_vk_perf
```
Use `NDK=...` or `ANDROID_NDK_HOME` to override the newest local SDK NDK. The device test uses real Vulkan and checks hash collisions, reused CPU input addresses, GPU writebacks, fence rotation, event publication during memory polling, descriptor pool growth and capacity splits. Success prints `VK_PERF_TEST_PASS`.
| Environment variable | Purpose |
|---|---|
| `DM_VK_SHADERS` | Vulkan shader pack generated by `dmsh_vk.py` |
| `DM_VK_PIPELINE_CACHE` | Driver cache file; defaults to the shader directory with vendor / device / driver version in its name |
| `DM_DISABLE_PIPELINE_CACHE=1` | Disable the driver cache; the state-to-pipeline memory cache remains active |
| `DM_VK_SYNC=1` | Submit and wait at every logical commit for comparison |
| `DM_FRAME_DIR` | Existing PPM frame capture and requested diagnostics |
| `DM_VULKAN_VALIDATION=1` | Request the Khronos layer, which must be discoverable by Android's loader |
| `DM_VK_PASSPROF=N` | Timestamp every render pass / dispatch of frame N and print per-pass GPU time (`PASSPROF` lines) at frame N+3 |
| `DM_VK_VRS=WxH[:hash,...]` | Pipeline fragment shading rate for the listed pixel shaders (default: forward+ lighting `5c1ca4e7c3e4657c`); needs `VK_KHR_fragment_shading_rate`, otherwise ignored |
| `DM_VK_AHB_POOL=1` | Try AHardwareBuffer BLOBs for memory-pool remapping before OPAQUE_FD. Off by default: on OnePlus 13 a large BLOB crashes the vendor allocator service (and the display stack with it), and it never succeeded on tested devices |
| `DM_3D_SCALE=0.5–1.0` | 3D internal render scale (the game's own upscale shader brings it back to the output size; the UI stays at output resolution). Android default 0.8: 3D at 720 lines under a 900-line output. Dynamic levels 0.72 / 0.70 kick in only on sustained dropped frames |
| `DM_FPS=30\|60` | Pin the frame rate. Otherwise it follows the Custom page's power-saving mode (`eco_fps`): 30 fps uses a software 30 Hz tick and hints the panel down with `ANativeWindow_setFrameRate` |
| `DM_VK_EVENT_SYNC=1` | Restore the old WaitEvent behavior (commit and CPU-wait for all prior GPU work) for comparison |
Following the [Vulkan cache header contract](https://docs.vulkan.org/spec/latest/chapters/pipelines.html), loading checks size, header version, vendor / device and UUID, and falls back to an empty cache. New compilation data is saved every 60 frames and on Finish / Drain using a temporary file and rename. Cache I/O failure does not stop rendering.
## App (GameActivity)
```sh
make -C dm/host -f Makefile.android APP=1 -j8 build-android/app/libd2r.so
sh dm/host/android/app/build_apk.sh # -> dm/host/build-android/app/d2r.apk, no Gradle
adb install -r dm/host/build-android/app/d2r.apk
```
`APP=1` builds the host as `libd2r.so` with `app/front_app.c` in place of `front_headless.c`. `build_apk.sh` uses javac (Android Studio's JBR by default), d8, aapt2, zipalign and apksigner with the debug keystore. The app is debuggable so game data can be copied in with `run-as`:
```sh
adb shell run-as org.d2rmobile.app sh -c 'mkdir -p files/d2r && cp -r /data/local/tmp/d2r/dm /data/local/tmp/d2r/romfs /data/local/tmp/d2r/romfs_overlay /data/local/tmp/d2r/rt64 /data/local/tmp/d2r/save files/d2r/'
adb shell am start -n org.d2rmobile.app/.GameActivity
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
```
The data root is `files/d2r` (`dm/main.patched.bin`, `romfs`, `rt64` required). stderr goes to `run.log`; optional `env.txt` lines `KEY=VALUE` are exported before start (e.g. `DM_VK_VRS=2x2`). Audio is off (`DM_AUDIO=0`) until AAudio lands. Render resolution is 720 lines times the screen aspect (`DM_GAME_RES` overrides). Without a window (app in background) the render thread holds at Present and resumes when a new surface arrives. On front-end pages (main menu, character select / creation) the first finger becomes UI mouse clicks via `dm_ui_touch` (tap = click at the lift point, vertical drag = scroll), as on iOS; in a run touch goes to the game's raw touchscreen until the touch HUD is ported. Gamepad buttons and sticks go to the pad.
## Implementation and boundaries
- Graphics and compute pipelines use effective Vulkan state keys with full equality after hash lookup. Dynamic viewport / scissor / blend constants and resource addresses are excluded; shaders, vertex input, topology, blend, depth / stencil, feedback flags and attachment compatibility are included. Pipelines and layouts live with the device.
- Render passes cache attachment descriptions; framebuffers cache images, mip / layer, extent and pass. Ordinary consecutive draws retain a pass. Layout transitions, copies, barriers, storage writes and feedback sampling preserve required boundaries. Texture release drains work and clears framebuffers. Adreno's GENERAL feedback path retains pass boundaries.
- Logical NVN commits can continue recording until Present, QueueFlush, a CPU wait or capacity boundary. Eight slots (`BATCH_SLOTS`) reuse command buffers, descriptor / query pools and fences; transient resources retire only after GPU completion. A completion worker publishes events / counters for guests that only poll memory and flushes report-bearing work after 2 ms of idle time.
- NVN `CommandBufferWaitEvent` is a GPU-side wait. If the event condition is already met by memory plus the signals queued in pending / recording batches (in submit order), the host records only a barrier and does not wait on the CPU. Only an event that no queued work can satisfy falls back to commit + CPU wait (`event_blocked` in `WAIT_PROFILE`).
- Build the shader pack with `SB_ALIGN=64` (the `dmsh_vk.py` default). Shaders then derive SSBO offsets from `base & -64`, and vkmeta flag bit 1 lets the host bind storage buffers directly from `addr & -64` with no copy. vkmeta storage flag bit 0 means writable. Packs built with `SB_ALIGN=16` still work through the copy path.
- CPU inputs use immutable snapshots. GPU-authored inputs stay in shared GPU buffers; ordered staging copies supply uncovered CPU bytes. Each batch snapshots its GPU writebacks to prevent subsequent batches contaminating earlier results.
- Capacity splits retain the logical fence until the final piece completes. Explicit Flush / wait boundaries prevent a strict one-submit-per-frame guarantee.
- The current real-window path still waits for presentation and queue idle to preserve temporary WSI semaphore lifetimes. This performance work targets headless rendering.
- Windowed present does not drain: each batch slot reuses its acquire semaphore and each swapchain image has its own present semaphore. `VK_ERROR_OUT_OF_DATE_KHR` on acquire recreates the swapchain and retries; on present it marks the swapchain for recreation at the next frame. Surface changes wait for the queue to idle before the swapchain is dropped.
`RENDER_PROFILE` counts actual Vulkan submissions including Present; the old counter excluded Present. `RENDER_CACHE_PROFILE` records cache reuse, pass count, pass breaks, transient buffer use and `gpu_ms` (GPU time of the interval from timestamp queries). `RENDER_INPUT_PROFILE` records uploads and shared GPU reads. `WAIT_PROFILE` splits CPU-side GPU wait time by origin (sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture, as `ms/count`), plus `sync_lag_max` and `event_queued` / `event_blocked`.
See [PERFORMANCE.md](PERFORMANCE.md) for measurements and validation limits. Keep binaries, caches, logs and game screenshots under ignored `build-android/` or device test directories.
+71
View File
@@ -0,0 +1,71 @@
# Android Vulkan 无头后端
English: [README.md](README.md)
`nvn_vk.c` 保留 NVN 记录器的 `mtl_*` 接口。目前在 OnePlus 13 / Adreno 830 上验证无头渲染。`app/` 是最小 GameActivity 应用(窗口、原始触摸、手柄、文字输入);AAudio 与触屏 HUD 是后续步骤。
## 构建与回归
从仓库根目录运行,使用已生成的宿主表头与玩家自己的改写产物:
```sh
make -C dm/host -f Makefile.android -j8
make -C dm/host/android/tests
adb push dm/host/build-android/tests/t_vk_perf /data/local/tmp/d2r/t_vk_perf
adb shell /data/local/tmp/d2r/t_vk_perf
```
NDK 默认取 `ANDROID_NDK_HOME`,否则使用本机 Android SDK 中最新的 NDK;可传 `NDK=...`。`t_vk_perf` 使用设备上的真实 Vulkan,检查哈希碰撞、CPU 输入地址复用、GPU 写回、fence 轮转、独立内存轮询的事件发布、描述符池扩容和容量分批。通过时输出 `VK_PERF_TEST_PASS`。
游戏仍按现有无头宿主方式启动,额外环境变量:
| 变量 | 用途 |
|---|---|
| `DM_VK_SHADERS` | `dmsh_vk.py` 生成的 Vulkan 着色器包目录 |
| `DM_VK_PIPELINE_CACHE` | 驱动缓存文件路径;默认放在着色器包目录,文件名包含 vendor / device / driver 版本 |
| `DM_DISABLE_PIPELINE_CACHE=1` | 关闭驱动缓存,状态到 pipeline 的内存缓存仍启用 |
| `DM_VK_SYNC=1` | 每次逻辑提交立即提交并等待,用于异步行为对照 |
| `DM_FRAME_DIR` | 按现有规则抓取 PPM 帧与按需诊断数据 |
| `DM_VULKAN_VALIDATION=1` | 请求 Khronos validation layer;需要 Android loader 能发现该 layer |
| `DM_VK_PASSPROF=N` | 第 N 帧逐个 render pass / dispatch 打 GPU 时间戳,第 N+3 帧打印每个 pass 的 GPU 耗时(`PASSPROF` 行) |
| `DM_VK_VRS=WxH[:hash,...]` | 对列出的像素着色器使用管线级可变着色率(默认只作用于前向+光照 `5c1ca4e7c3e4657c`);需要 `VK_KHR_fragment_shading_rate`,不支持时忽略 |
| `DM_VK_AHB_POOL=1` | 内存池重映射先尝试 AHardwareBuffer BLOB,再退回 OPAQUE_FD。默认关闭:OnePlus 13 上大 BLOB 会让厂商 allocator 服务崩溃并连带显示栈重启,已测设备上也从未成功 |
| `DM_3D_SCALE=0.5–1.0` | 3D 内部渲染比例(游戏自带的放大着色器拉回输出尺寸,界面仍按输出分辨率画)。安卓缺省 0.8:输出 900 行时 3D 为 720 行。持续掉帧时才动态降到 0.72 / 0.70 |
| `DM_FPS=30\|60` | 钉住帧数。不设则跟自定义页的省电模式(`eco_fps`):30 帧时用软件 30 Hz 节拍,并用 `ANativeWindow_setFrameRate` 提示屏幕降刷新率 |
| `DM_VK_EVENT_SYNC=1` | 恢复旧的 WaitEvent 行为(提交并在 CPU 上等待之前所有 GPU 工作),用于对照 |
按照 [Vulkan cache header 约定](https://docs.vulkan.org/spec/latest/chapters/pipelines.html),缓存加载前检查尺寸、header 版本、vendor / device 和 UUID,加载失败时创建空缓存。新编译结果每 60 帧及 Finish / Drain 时保存,使用临时文件加 rename;缓存读写失败不影响渲染。
## App(GameActivity)
```sh
make -C dm/host -f Makefile.android APP=1 -j8 build-android/app/libd2r.so
sh dm/host/android/app/build_apk.sh # 输出 dm/host/build-android/app/d2r.apk,不用 Gradle
adb install -r dm/host/build-android/app/d2r.apk
```
`APP=1` 把宿主编成 `libd2r.so`,用 `app/front_app.c` 取代 `front_headless.c`。`build_apk.sh` 使用 javac(默认 Android Studio 自带 JBR)、d8、aapt2、zipalign 和 apksigner(debug keystore)。应用是 debuggable 的,游戏数据可以用 `run-as` 拷进去:
```sh
adb shell run-as org.d2rmobile.app sh -c 'mkdir -p files/d2r && cp -r /data/local/tmp/d2r/dm /data/local/tmp/d2r/romfs /data/local/tmp/d2r/romfs_overlay /data/local/tmp/d2r/rt64 /data/local/tmp/d2r/save files/d2r/'
adb shell am start -n org.d2rmobile.app/.GameActivity
adb shell run-as org.d2rmobile.app cat files/d2r/run.log
```
数据根目录是 `files/d2r`(必须有 `dm/main.patched.bin`、`romfs`、`rt64`)。stderr 写入 `run.log`;可选的 `env.txt` 每行 `KEY=VALUE`,启动前导出(例如 `DM_VK_VRS=2x2`)。接入 AAudio 前声音关闭(`DM_AUDIO=0`)。渲染分辨率为 720 行乘屏幕宽高比(`DM_GAME_RES` 可覆盖)。没有窗口(应用在后台)时渲染线程停在 Present,新 surface 到来后继续。前端页(主菜单、选角 / 建角)上第一根手指经 `dm_ui_touch` 变成界面鼠标点击(点按 = 抬起处点击,纵向拖 = 滚动),与 iOS 相同;局内在触屏 HUD 移植前送到游戏的原始触摸屏。手柄按键与摇杆送到 pad。
## 性能实现与边界
- 图形与计算 pipeline 按实际 Vulkan 状态构造 key,哈希定位后比较完整 key。动态 viewport / scissor / blend constants、资源地址不进入 key;shader、顶点布局、拓扑、混合、深度 / 模板、反馈标志、附件兼容性进入 key。pipeline 和 layout 随 device 保留。
- render pass 按附件描述缓存,framebuffer 按 image、mip / layer、尺寸和 pass 缓存。同一 framebuffer 上普通连续 draw 保持在一个 pass 内;布局转换、复制、屏障、存储写入及反馈采样保留所需边界。释放纹理前 Drain,并清理 framebuffer 缓存。Adreno 的 GENERAL 反馈路径保留 pass 边界。
- NVN 逻辑提交可继续向当前 Vulkan command buffer 编码;Present、QueueFlush、CPU 等待、容量上限才提交。八个槽位(`BATCH_SLOTS`)复用 command buffer、descriptor / query pool 和 fence;临时资源在 GPU 完成后释放。事件 / counter 的后台完成线程可在游戏只轮询内存时发布结果;含报告的未提交工作空闲 2 ms 后会提交。
- NVN `CommandBufferWaitEvent` 是 GPU 侧等待。若事件条件由当前内存值加上待完成 / 录制中批次里按提交顺序排队的 signal 即可满足,宿主只录一个屏障,不在 CPU 上等待;只有排队工作无法满足的事件才退回提交 + CPU 等待(`WAIT_PROFILE` 中的 `event_blocked`)。
- 着色器包用 `SB_ALIGN=64` 构建(`dmsh_vk.py` 默认值):着色器按 `base & -64` 计算 SSBO 偏移,vkmeta 标志 bit 1 让宿主直接从 `addr & -64` 绑定存储缓冲区,无需拷贝;bit 0 表示可写。`SB_ALIGN=16` 的旧包仍走拷贝路径。
- CPU 输入使用不可变上传快照。GPU 生成的输入直接读共享 GPU 缓冲区,未覆盖的 CPU 数据通过有序 staging copy 上传。每批 GPU 写回先拷到独立读回副本,防止后批写入污染前批结果。
- 容量不足可在一个逻辑提交内分批,逻辑 fence 在最后一批完成后才可见。显式 Flush / 等待仍会打断合帧,因此不能保证所有游戏路径严格每帧一次提交。
- 当前真实窗口路径仍等待 present 并保留 queue idle,以确保临时 WSI semaphore 生命周期;本次性能验收针对无头路径。
- 有窗口时 Present 不再 Drain:每个批次槽位复用自己的 acquire 信号量,每张 swapchain 图像有独立的 present 信号量。acquire 遇到 `VK_ERROR_OUT_OF_DATE_KHR` 时重建 swapchain 并重试一次;present 遇到时标记,在下一帧重建。surface 变化时先等队列空闲再销毁 swapchain。
`RENDER_PROFILE` 计时并统计实际 Vulkan 提交(包括 Present);`RENDER_CACHE_PROFILE` 记录 pipeline 命中、pass / framebuffer 复用、pass 次数与打断次数、临时缓冲区用量,以及 `gpu_ms`(时间戳查询得到的区间 GPU 时间);`RENDER_INPUT_PROFILE` 记录上传和共享 GPU 输入;`WAIT_PROFILE` 按来源拆分 CPU 等待 GPU 的时间(sync / event / present / slot / readtex / texrel / sampler / pooldel / finish / capture,格式 `毫秒/次数`),并给出 `sync_lag_max` 与 `event_queued` / `event_blocked`。旧后端的提交统计不包含 Present,比较时需注意口径。
2026-10-13 的实测和限制见 [PERFORMANCE.md](PERFORMANCE.md)。构建文件、缓存、日志、游戏截图均留在 `build-android/` 或设备测试目录,不入库。
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.d2rmobile.app"
android:versionCode="1" android:versionName="0.1">
<uses-sdk android:minSdkVersion="29" android:targetSdkVersion="33" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
<!-- debuggable:run-as 往私有目录放游戏数据、读 run.log | debuggable: run-as to put game data into the private directory and read run.log -->
<application android:label="D2R Mobile" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher" android:debuggable="true" android:allowBackup="false" android:hasCode="true"
android:extractNativeLibs="true" android:isGame="true" android:appCategory="game"
android:theme="@android:style/Theme.Material.NoActionBar.Fullscreen">
<activity android:name=".GameActivity" android:exported="true" android:screenOrientation="sensorLandscape"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"
android:launchMode="singleTask" android:resizeableActivity="false">
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
</activity>
</application>
</manifest>
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env python3
# 没有完整原版 RomFS(缺 build_manifest.psv)时,从现成 iOS 安装包解出的 DmIOS.app 取触屏素材:TouchArt PNG、hud_v4_ui、mapgoal、dm_touch_native_art.c。
# 每张 PNG 与技能索引都按仓库里冻结的 native_art_manifest.json 核过哈希(同 ios/tools/native_art/generate.py 的产物)。
# 用法:art_from_ipa.py <解开的 Payload/DmIOS.app> <dm 目录>
# Without a full original RomFS (no build_manifest.psv), take the touch art from an unpacked iOS build (DmIOS.app): TouchArt PNGs, hud_v4_ui, mapgoal, dm_touch_native_art.c.
# Every PNG and the skill index are hash-checked against the frozen native_art_manifest.json (same output as ios/tools/native_art/generate.py).
# Usage: art_from_ipa.py <unpacked Payload/DmIOS.app> <dm directory>
import hashlib, json, shutil, sys
from pathlib import Path
app = Path(sys.argv[1]); dm = Path(sys.argv[2]); ios = dm / 'ios'; nat = ios / 'tools/native_art'
sha = lambda b: hashlib.sha256(b).hexdigest()
mpath = ios / 'Sources/TouchArt/native_art_manifest.json'; man = json.loads(mpath.read_text())
art = ios / 'Sources/TouchArt'; atl = {}
for a in man['assets']:
b = (app / a['asset']).read_bytes()
assert sha(b) == a['decoded_png_sha256'], a['asset']
(art / a['asset']).write_bytes(b); atl[a['asset']] = a
rows = [[int(x) for x in l.split('\t')[1:4]] for l in open(app / 'dm/derived.tsv') if l.startswith('TAROW')]
assert sha(json.dumps(rows, sort_keys=True, separators=(',', ':')).encode()) == man['descriptor_index_sha256']
out = ['/* Generated from frozen official Skills/Skilldesc; do not hand-edit rows. */', '#include "dm_touch_native_art.h"', '#include "../host/dm_input.h"', '#include <stddef.h>',
'const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES]={']
for i in range(9):
a = atl['dm_native_skill_%d.png' % i]; out.append(' {"%s",%d,%d,%d,%d,%d},' % (a['asset'][:-4], *a['atlas_px'], a['frame_width'], a['frame_pitch'], a['frame_count']))
out += ['};', f'const char dm_ta_manifest_sha[]="{sha(mpath.read_bytes())}";', f'const char dm_ta_geometry_sha[]="{sha((ios / "docs/native_art_v1_geometry.json").read_bytes())}";',
f'const char dm_ta_binding_sha[]="{sha((ios / "docs/touch_layout_spec_native_binding_v5.json").read_bytes())}";', 'static const struct { uint32_t id; int atlas,frame; } rows[]={']
out += [' {%d,%d,%d},' % tuple(r) for r in rows] + ['};', (nat / 'implementation.c.inc').read_text()]
(dm / 'touch/dm_touch_native_art.c').write_text('\n'.join(out) + '\n')
hud = ios / 'Gen/assets/NativeHUD/v4/hud_v4_ui'
shutil.rmtree(hud, ignore_errors=True); shutil.copytree(app / 'hud_v4_ui', hud)
goal = ios / 'Gen/assets/NativeHUD/mapgoal' # 小地图任务终点(gen_map_goal_art.py 的产物,按它的 mapgoal.json 核齐) | minimap quest goals (gen_map_goal_art.py output, checked complete against its mapgoal.json)
shutil.rmtree(goal, ignore_errors=True); shutil.copytree(app / 'mapgoal', goal)
gm = json.loads((goal / 'mapgoal.json').read_text())
need = ['cross.png'] + ['sym_%d.png' % i for i in range(gm['symbol_frames'])]
assert all((goal / f).is_file() for f in need), 'mapgoal incomplete'
print(len(rows), 'rows,', len(atl), 'atlases,', len(list(hud.iterdir())), 'hud files,', len(list(goal.iterdir())), 'mapgoal files')
+51
View File
@@ -0,0 +1,51 @@
#!/bin/sh
# Package build-android/app/libd2r.so + GameActivity into a debug-signed APK, without Gradle.
# make -f Makefile.android APP=1 build-android/app/libd2r.so && sh android/app/build_apk.sh
# Env: ANDROID_SDK (default ~/Library/Android/sdk), BUILD_TOOLS (35.0.0), PLATFORM (android-33),
# JAVA_HOME (default: Android Studio's bundled JBR), KEYSTORE (default ~/.android/debug.keystore).
set -eu
here=$(cd "$(dirname "$0")" && pwd)
host=$(cd "$here/../.." && pwd)
out=$host/build-android/app
sdk=${ANDROID_SDK:-$HOME/Library/Android/sdk}
bt=$sdk/build-tools/${BUILD_TOOLS:-35.0.0}
jar=$sdk/platforms/${PLATFORM:-android-33}/android.jar
jh=${JAVA_HOME:-"/Applications/Android Studio.app/Contents/jbr/Contents/Home"}
ks=${KEYSTORE:-$HOME/.android/debug.keystore}
so=$out/libd2r.so
[ -f "$so" ] || { echo "missing $so (build with APP=1 first)" >&2; exit 1; }
[ -f "$jar" ] || { echo "missing $jar" >&2; exit 1; }
[ -x "$jh/bin/javac" ] || { echo "no javac at $jh (set JAVA_HOME to JDK 11+)" >&2; exit 1; }
w=$out/apk
rm -rf "$w"; mkdir -p "$w/classes" "$w/dex" "$w/lib/arm64-v8a"
"$jh/bin/javac" -nowarn --release 11 -classpath "$jar" -d "$w/classes" \
$(find "$here/java" -name '*.java')
PATH="$jh/bin:$PATH" "$bt/d8" --release --min-api 29 --lib "$jar" --output "$w/dex" \
$(find "$w/classes" -name '*.class')
# 触屏 HUD 素材(从玩家自己的游戏文件生成,不进仓库):TouchArt/ = ios/tools/native_art/generate.py,hud_v4_ui/ = ios/tools/gen_hud_v4.py,mapgoal/ = ios/tools/gen_map_goal_art.py
# Touch HUD assets (generated from the player's own game files, not in the repo): TouchArt/ = ios/tools/native_art/generate.py, hud_v4_ui/ = ios/tools/gen_hud_v4.py, mapgoal/ = ios/tools/gen_map_goal_art.py
ios=$host/../ios
mkdir -p "$w/assets/TouchArt"
cp "$ios"/Sources/TouchArt/*.png "$w/assets/TouchArt/" 2>/dev/null || echo "warning: no TouchArt pngs (run ios/tools/gen_assets.py)" >&2
if [ -d "$ios/Gen/assets/NativeHUD/v4/hud_v4_ui" ]; then cp -R "$ios/Gen/assets/NativeHUD/v4/hud_v4_ui" "$w/assets/"
else echo "warning: no hud_v4_ui (run ios/tools/gen_assets.py)" >&2; fi
if [ -d "$ios/Gen/assets/NativeHUD/mapgoal" ]; then rm -rf "$w/assets/mapgoal"; cp -R "$ios/Gen/assets/NativeHUD/mapgoal" "$w/assets/mapgoal" # 小地图任务终点 = ios/tools/gen_map_goal_art.py | minimap quest goals = ios/tools/gen_map_goal_art.py
else echo "warning: no mapgoal (run ios/tools/gen_assets.py)" >&2; fi
# 资源只有启动图标(res/:自适应图标,图同 iOS AppIcon1024.png)| The only resource is the launcher icon (res/: adaptive icon, same art as iOS AppIcon1024.png)
"$bt/aapt2" compile --dir "$here/res" -o "$w/res.zip"
"$bt/aapt2" link -o "$w/base.apk" --manifest "$here/AndroidManifest.xml" -I "$jar" \
--min-sdk-version 29 --target-sdk-version 33 -A "$w/assets" -R "$w/res.zip" --auto-add-overlay
cp "$so" "$w/lib/arm64-v8a/libd2r.so"
(cd "$w/dex" && zip -q -X "$w/base.apk" classes.dex)
# Native libs stored uncompressed so they stay page-aligned for zipalign -P.
(cd "$w" && zip -q -X -0 base.apk lib/arm64-v8a/libd2r.so)
"$bt/zipalign" -f -P 16 4 "$w/base.apk" "$w/aligned.apk"
PATH="$jh/bin:$PATH" "$bt/apksigner" sign --ks "$ks" --ks-pass pass:android \
--ks-key-alias androiddebugkey --key-pass pass:android \
--out "$out/d2r.apk" "$w/aligned.apk"
echo "$out/d2r.apk"
+236
View File
@@ -0,0 +1,236 @@
// 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 "../../dm.h"
#include "../../hle.h"
#include "../../front.h"
#include "../../dm_input.h"
#include "../../dm_padmap.h"
#include "../../dm_cursor.h"
#include "../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 × 屏幕比例(宽取 8 的倍数,≤ 4096);掌机档 720 同比。比 16:9 窄的屏按 16:9。DM_GAME_RES=宽x高 覆盖
// Docked profile: the original height 900 × 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;
uint64_t hh = docked ? 900 : 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);
}
@@ -0,0 +1,286 @@
// 全屏横屏 Activity:SurfaceView 交给 Vulkan 后端出图,上面盖一层触屏 HUD(TouchOverlay);触点 / 手柄 / 软键盘转给 libd2r.so(front_app.c、touch_app.c)。
// Fullscreen landscape Activity: the SurfaceView goes to the Vulkan backend for presenting, with the touch HUD (TouchOverlay) on top; touches / controller / software keyboard go to libd2r.so (front_app.c, touch_app.c).
package org.d2rmobile.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.Choreographer;
import android.view.DisplayCutout;
import android.view.WindowInsets;
import android.widget.FrameLayout;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.util.DisplayMetrics;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
public final class GameActivity extends Activity implements SurfaceHolder.Callback {
private static native int nativeStart(String root, int screenW, int screenH);
private static native void nativeSurface(Object surface, float hz);
// 触屏 HUD(touch_app.c),坐标单位 dp | touch HUD (touch_app.c), coordinates in dp
private static native void nativeLayout(float w, float h, float safeL, float safeR);
private static native void nativeTouchEvent(int action, int pid, int[] pids, float[] xs, float[] ys, int n);
private static native int nativeTick();
static native Object[] nativeDraw(int part);
private static native void nativePad(int face, int other, boolean nintendo, float lx, float ly, float rx, float ry);
private static native long nativeFrames();
private static native String[] nativeTextRequest();
private static native void nativeTextResult(boolean ok, String text);
// 前后台:0 onPause、1 onStop(局内等存盘,最多 2.5 s)、2 onStart、3 onResume(front_app.c)| foreground / background: 0 onPause, 1 onStop (waits for the save in a run, at most 2.5 s), 2 onStart, 3 onResume (front_app.c)
private static native void nativeLifecycle(int ev);
// nn::hid 按钮位(dm_input.h)| nn::hid button bits (dm_input.h)
private static final int LS = 1 << 4, RS = 1 << 5, L = 1 << 6, R = 1 << 7, ZL = 1 << 8, ZR = 1 << 9,
PLUS = 1 << 10, MINUS = 1 << 11, LEFT = 1 << 12, UP = 1 << 13, RIGHT = 1 << 14, DOWN = 1 << 15;
private final Handler ui = new Handler(Looper.getMainLooper());
private SurfaceView view;
private boolean started;
private TouchOverlay overlay, joy, goals;
private float safeL, safeR;
private Vibrator vibrator;
private final int[] tPids = new int[32]; private final float[] tXs = new float[32], tYs = new float[32];
private int padFace, padKeys, padHat;
private float lx, ly, rx, ry, lt, rt;
private boolean nintendo;
private AlertDialog textDialog;
// 左上角 FPS 标签:每 1 s 按游戏出帧数更新 | top-left FPS label: refreshed every 1 s from the game's presented frame count
private TextView fps;
private long fpsFrames, fpsTime;
/* 游戏自己按 60 Hz(省电 30 Hz)出帧;120 Hz 面板上软件时钟和垂直同步拍频,帧落在 1/2/3 个 vsync 上抖动,所以把屏幕钉在同分辨率的 60 Hz 模式
* The game paces itself at 60 Hz (30 Hz in eco); on a 120 Hz panel the software clock beats against vsync and frames land on 1/2/3 vsyncs, so pin the panel to the same-resolution 60 Hz mode */
private void pin60Hz() {
if (android.os.Build.VERSION.SDK_INT < 23) return;
android.view.Display d = getWindowManager().getDefaultDisplay();
android.view.Display.Mode cur = d.getMode(), best = null;
for (android.view.Display.Mode m : d.getSupportedModes()) {
if (m.getPhysicalWidth() != cur.getPhysicalWidth() || m.getPhysicalHeight() != cur.getPhysicalHeight()) continue;
if (Math.abs(m.getRefreshRate() - 60f) < 1f) { best = m; break; }
}
if (best == null) return;
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.preferredDisplayModeId = best.getModeId();
getWindow().setAttributes(lp);
}
@Override protected void onCreate(Bundle state) {
super.onCreate(state);
// 库的构造函数要按 DM_ROOT 找 dm/derived.tsv(经验表等),所以先设环境变量再加载 | the library's constructors locate dm/derived.tsv (EXP table etc.) via DM_ROOT, so set it before loading
try { android.system.Os.setenv("DM_ROOT", new File(getFilesDir(), "d2r").getAbsolutePath(), true); } catch (Exception e) {}
System.loadLibrary("d2r");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (android.os.Build.VERSION.SDK_INT >= 28)
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
pin60Hz();
view = new SurfaceView(this);
view.getHolder().addCallback(this);
view.setFocusable(true); view.setFocusableInTouchMode(true);
// 主体层缓存成 GPU 纹理:手指在摇杆上动时只重画摇杆层(见 touch_app.c op_list) | the body layer is cached as a GPU texture: while a finger moves on the stick only the joystick layer is redrawn (see touch_app.c op_list)
overlay = new TouchOverlay(this, 0); overlay.setLayerType(View.LAYER_TYPE_HARDWARE, null);
joy = new TouchOverlay(this, 1);
goals = new TouchOverlay(this, 2); // 小地图任务终点:跟着玩家走每帧变,单独一层不牵动主体层 | minimap quest goals: change every frame as the player walks, own layer so the body layer is untouched
FrameLayout root = new FrameLayout(this);
root.addView(view, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(goals, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(overlay, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
root.addView(joy, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
fps = new TextView(this);
fps.setTextSize(12); fps.setTextColor(0xffe9d9ba); fps.setBackgroundColor(0x80000000);
fps.setTypeface(android.graphics.Typeface.MONOSPACE); fps.setPadding(12, 4, 12, 4);
root.addView(fps, new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
setContentView(root);
// 刘海 / 挖孔:横屏左右的安全边距交给布局(同 iOS safeAreaInsets)| cutout / punch hole: the landscape left / right safe insets go to the layout (like iOS safeAreaInsets)
root.setOnApplyWindowInsetsListener((v, in) -> {
DisplayCutout cut = in.getDisplayCutout();
safeL = cut != null ? cut.getSafeInsetLeft() : 0; safeR = cut != null ? cut.getSafeInsetRight() : 0;
fps.setTranslationX(safeL);
layoutHud(); return in;
});
overlay.addOnLayoutChangeListener((v, l, t, r, b, ol, ot, or, ob) -> layoutHud());
vibrator = getSystemService(Vibrator.class);
immersive();
ui.post(textPoll);
}
private void immersive() {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
@Override public void onWindowFocusChanged(boolean focus) { super.onWindowFocusChanged(focus); if (focus) immersive(); }
private void fail(String text) {
TextView t = new TextView(this); t.setText(text); t.setTextSize(18); t.setPadding(48, 48, 48, 48);
t.setTextColor(0xffe9d9ba); t.setBackgroundColor(0xff0d0d0f); setContentView(t);
}
// ---- Surface ----
@Override public void surfaceCreated(SurfaceHolder h) {}
@Override public void surfaceChanged(SurfaceHolder h, int format, int w, int hh) {
if (!started) {
DisplayMetrics m = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(m);
File root = new File(getFilesDir(), "d2r");
int rc = nativeStart(root.getAbsolutePath(), m.widthPixels, m.heightPixels);
if (rc != 0) { fail("游戏文件不全(错误 " + rc + ")\n请把 dm/、romfs/、rt64/ 放到\n" + root.getAbsolutePath()); return; }
started = true;
layoutHud();
Choreographer.getInstance().postFrameCallback(frame);
}
// 同步交出窗口:surfaceDestroyed 返回前后端必须已放手,这里对称处理 | Hand the window over synchronously: the backend must let go before surfaceDestroyed returns, handled symmetrically here
nativeSurface(h.getSurface(), getWindowManager().getDefaultDisplay().getRefreshRate());
}
@Override public void surfaceDestroyed(SurfaceHolder h) {
if (started) nativeSurface(null, 0);
cancelTouches();
}
// ---- 触屏 HUD | touch HUD ----
private void layoutHud() {
if (!started || overlay.getWidth() <= 0) return;
float d = getResources().getDisplayMetrics().density;
nativeLayout(overlay.getWidth() / d, overlay.getHeight() / d, safeL / d, safeR / d);
overlay.invalidate(); joy.invalidate(); goals.invalidate();
}
// 每帧:推进 HUD 状态机(长按、松手脉冲、腰带 …),要重画才 invalidate;掉落震动按档位 | per frame: advance the HUD state machine (long press, release pulse, belt …), invalidate only when a redraw is needed; drop haptics by level
private final Choreographer.FrameCallback frame = new Choreographer.FrameCallback() { public void doFrame(long t) {
if (!started) return;
int r = nativeTick();
if ((r & 1) != 0) overlay.invalidate();
if ((r & 2) != 0) joy.invalidate();
if ((r & 4) != 0) goals.invalidate();
if (t - fpsTime >= 1_000_000_000L) {
long n = nativeFrames();
if (fpsTime != 0) fps.setText(String.format(java.util.Locale.ROOT, "%.1f FPS", (n - fpsFrames) * 1e9 / (t - fpsTime)));
fpsFrames = n; fpsTime = t;
}
int hap = r >> 4 & 3;
if (hap != 0 && vibrator != null && vibrator.hasVibrator())
vibrator.vibrate(VibrationEffect.createPredefined(hap == 1 ? VibrationEffect.EFFECT_HEAVY_CLICK : hap == 2 ? VibrationEffect.EFFECT_CLICK : VibrationEffect.EFFECT_TICK));
Choreographer.getInstance().postFrameCallback(this);
}};
private void cancelTouches() { if (started) nativeTouchEvent(3, -1, null, null, null, 0); }
@Override public boolean onTouchEvent(MotionEvent e) {
if (!started) return true;
int act = e.getActionMasked(), action;
switch (act) {
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: action = 0; break;
case MotionEvent.ACTION_MOVE: action = 1; break;
case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: action = 2; break;
case MotionEvent.ACTION_CANCEL: action = 3; break;
default: return true;
}
float d = getResources().getDisplayMetrics().density;
int n = Math.min(e.getPointerCount(), tPids.length);
for (int i = 0; i < n; i++) { tPids[i] = e.getPointerId(i); tXs[i] = e.getX(i) / d; tYs[i] = e.getY(i) / d; }
int pid = action == 0 || action == 2 ? e.getPointerId(e.getActionIndex()) : -1;
nativeTouchEvent(action, pid, tPids, tXs, tYs, n); // 重画交给同一帧随后的 doFrame(nativeTick 比对指令表) | the redraw is left to the doFrame later in the same frame (nativeTick compares the draw lists)
return true;
}
// ---- 实体手柄 | physical controller ----
private static boolean isPad(int source) {
return (source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD || (source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK;
}
private void padPublish() {
int other = padKeys | padHat | (lt > 0.5f ? ZL : 0) | (rt > 0.5f ? ZR : 0);
nativePad(padFace, other, nintendo, lx, ly, rx, ry);
}
private static float dead(float v) { return Math.abs(v) < 0.12f ? 0 : v; }
@Override public boolean dispatchKeyEvent(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.KEYCODE_BACK && !isPad(e.getSource())) return true; // 系统返回键不退出游戏 | the system back key does not quit the game
if (!started || !isPad(e.getSource())) return super.dispatchKeyEvent(e);
int face = 0, key = 0;
switch (code) {
case KeyEvent.KEYCODE_BUTTON_A: face = 1; break; // 下 | bottom
case KeyEvent.KEYCODE_BUTTON_B: face = 2; break; // 右 | right
case KeyEvent.KEYCODE_BUTTON_X: face = 4; break; // 左 | left
case KeyEvent.KEYCODE_BUTTON_Y: face = 8; break; // 上 | top
case KeyEvent.KEYCODE_BUTTON_L1: key = L; break;
case KeyEvent.KEYCODE_BUTTON_R1: key = R; break;
case KeyEvent.KEYCODE_BUTTON_L2: key = ZL; break;
case KeyEvent.KEYCODE_BUTTON_R2: key = ZR; break;
case KeyEvent.KEYCODE_BUTTON_THUMBL: key = LS; break;
case KeyEvent.KEYCODE_BUTTON_THUMBR: key = RS; break;
case KeyEvent.KEYCODE_BUTTON_START: key = PLUS; break;
case KeyEvent.KEYCODE_BUTTON_SELECT: case KeyEvent.KEYCODE_BACK: key = MINUS; break;
case KeyEvent.KEYCODE_DPAD_UP: key = UP; break;
case KeyEvent.KEYCODE_DPAD_DOWN: key = DOWN; break;
case KeyEvent.KEYCODE_DPAD_LEFT: key = LEFT; break;
case KeyEvent.KEYCODE_DPAD_RIGHT: key = RIGHT; break;
default: return super.dispatchKeyEvent(e);
}
InputDevice d = e.getDevice(); nintendo = d != null && d.getName() != null && d.getName().toLowerCase().matches(".*(nintendo|switch|joy-con).*");
boolean down = e.getAction() == KeyEvent.ACTION_DOWN;
if (face != 0) padFace = down ? padFace | face : padFace & ~face;
else padKeys = down ? padKeys | key : padKeys & ~key;
padPublish();
return true;
}
@Override public boolean dispatchGenericMotionEvent(MotionEvent e) {
if (!started || !isPad(e.getSource()) || e.getAction() != MotionEvent.ACTION_MOVE) return super.dispatchGenericMotionEvent(e);
lx = dead(e.getAxisValue(MotionEvent.AXIS_X)); ly = dead(e.getAxisValue(MotionEvent.AXIS_Y));
rx = dead(e.getAxisValue(MotionEvent.AXIS_Z)); ry = dead(e.getAxisValue(MotionEvent.AXIS_RZ));
lt = Math.max(e.getAxisValue(MotionEvent.AXIS_LTRIGGER), e.getAxisValue(MotionEvent.AXIS_BRAKE));
rt = Math.max(e.getAxisValue(MotionEvent.AXIS_RTRIGGER), e.getAxisValue(MotionEvent.AXIS_GAS));
float hx = e.getAxisValue(MotionEvent.AXIS_HAT_X), hy = e.getAxisValue(MotionEvent.AXIS_HAT_Y);
padHat = (hx < -0.5f ? LEFT : 0) | (hx > 0.5f ? RIGHT : 0) | (hy < -0.5f ? UP : 0) | (hy > 0.5f ? DOWN : 0);
padPublish();
return true;
}
// ---- 软键盘 | software keyboard ----
private final Runnable textPoll = new Runnable() { public void run() {
if (started && textDialog == null) {
String[] r = nativeTextRequest();
if (r != null) showText(r);
}
ui.postDelayed(this, 250);
}};
private void showText(String[] r) {
final EditText edit = new EditText(this);
edit.setSingleLine(true); edit.setText(r[3]); edit.setSelection(edit.getText().length());
if (!r[2].isEmpty()) edit.setHint(r[2]);
int max = Integer.parseInt(r[4]); if (max > 0) edit.setFilters(new InputFilter[]{new InputFilter.LengthFilter(max)});
String msg = r[1] + (!r[1].isEmpty() && !r[2].isEmpty() ? "\n" : "") + r[2];
textDialog = new AlertDialog.Builder(this).setTitle(r[0].isEmpty() ? "输入" : r[0]).setMessage(msg.isEmpty() ? null : msg).setView(edit)
.setPositiveButton(android.R.string.ok, (d, w) -> { nativeTextResult(true, edit.getText().toString()); textDialog = null; })
.setNegativeButton(android.R.string.cancel, (d, w) -> { nativeTextResult(false, null); textDialog = null; })
.setOnCancelListener(d -> { nativeTextResult(false, null); textDialog = null; })
.create();
textDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
textDialog.show();
}
// ---- 前后台 | foreground / background ----
// 切走时按着的触点和手柄键一并清零:在后台松开收不到「松开」| touches and controller keys held while switching away are cleared: a release in the background never arrives
@Override protected void onPause() {
super.onPause();
if (!started) return;
cancelTouches();
padFace = padKeys = padHat = 0; lx = ly = rx = ry = lt = rt = 0; padPublish();
nativeLifecycle(0);
}
@Override protected void onStop() { super.onStop(); if (started) nativeLifecycle(1); }
@Override protected void onStart() { super.onStart(); if (started) nativeLifecycle(2); }
@Override protected void onResume() { super.onResume(); if (started) nativeLifecycle(3); }
@Override protected void onDestroy() {
ui.removeCallbacks(textPoll);
super.onDestroy();
// 宿主不支持在同一进程里重新起跑:Activity 销毁就结束进程 | The host cannot restart in the same process: end the process when the Activity is destroyed
if (isFinishing()) android.os.Process.killProcess(android.os.Process.myPid());
}
}
@@ -0,0 +1,179 @@
// 局内触屏 HUD 叠加层:照 touch_app.c 每帧给的绘制指令表画(与 iOS DmTouchOverlay.m drawRect 一一对应);坐标单位 dp。
// 素材取自 APK assets:TouchArt/(原版技能图集等)与 hud_v4_ui/(底部 UI v4,gen_hud_v4.py 生成)。本视图不接触摸,触摸由 Activity 交给 nativeTouchEvent。
// In-run touch HUD overlay: draws from the per-frame draw list given by touch_app.c (one-to-one with iOS DmTouchOverlay.m drawRect); units are dp.
// Assets come from the APK assets: TouchArt/ (original game skill atlases etc.) and hud_v4_ui/ (bottom UI v4, generated by gen_hud_v4.py). This view takes no touches; the Activity hands them to nativeTouchEvent.
package org.d2rmobile.app;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlendMode;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import java.io.InputStream;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
final class TouchOverlay extends View {
// 指令码:与 touch_app.c 的 OP_* 一致 | op codes: same as OP_* in touch_app.c
private static final int FILL_ELLIPSE = 1, STROKE_ELLIPSE = 2, LINE = 3, ARC = 4, IMAGE = 5, TEXT = 6, FILL_RECT = 7, V4 = 8, V4TEXT = 9, LABEL = 10, COVER = 11;
private final float density;
private final int part; // 0 = HUD 主体,1 = 摇杆,2 = 小地图任务终点(touch_app.c draw_overlay) | 0 = HUD body, 1 = joystick, 2 = minimap quest goals (touch_app.c draw_overlay)
private final Paint fill = new Paint(Paint.ANTI_ALIAS_FLAG), stroke = new Paint(Paint.ANTI_ALIAS_FLAG),
img = new Paint(Paint.FILTER_BITMAP_FLAG), text = new Paint(Paint.ANTI_ALIAS_FLAG);
private final HashMap<String, Bitmap> bitmaps = new HashMap<>();
private final RectF rf = new RectF(); private final Rect src = new Rect();
private JSONObject ui; private boolean uiLoaded;
TouchOverlay(Context c, int part) {
super(c);
this.part = part;
density = getResources().getDisplayMetrics().density;
fill.setStyle(Paint.Style.FILL); stroke.setStyle(Paint.Style.STROKE);
text.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL)); text.setTextAlign(Paint.Align.CENTER);
setWillNotDraw(false); setClickable(false); setFocusable(false);
}
private Bitmap bitmap(String path) {
if (bitmaps.containsKey(path)) return bitmaps.get(path);
Bitmap b = null;
try (InputStream in = getContext().getAssets().open(path)) {
BitmapFactory.Options o = new BitmapFactory.Options(); o.inScaled = false; o.inPremultiplied = true;
b = BitmapFactory.decodeStream(in, null, o);
} catch (Exception e) { Log.w("d2r", "触屏 HUD:缺素材 " + path); }
bitmaps.put(path, b); return b; // 缺的也记下,不每帧重试 | misses are remembered too, no per-frame retry
}
private JSONObject ui() {
if (!uiLoaded) { uiLoaded = true;
try (InputStream in = getContext().getAssets().open("hud_v4_ui/ui.json")) {
ui = new JSONObject(new String(in.readAllBytes(), "UTF-8"));
} catch (Exception e) { Log.e("d2r", "【红】底部 UI v4:APK 内缺 hud_v4_ui/ui.json"); } }
return ui;
}
private static int rgba(float r, float g, float b, float a) {
return Color.argb(Math.round(Math.max(0, Math.min(1, a)) * 255), Math.round(r * 255), Math.round(g * 255), Math.round(b * 255));
}
@Override protected void onDraw(Canvas c) {
Object[] d = GameActivity.nativeDraw(part); if (d == null) return;
float[] o = (float[]) d[0]; String[] s = (String[]) d[1];
c.save(); c.scale(density, density);
for (int p = 0; p + 2 <= o.length; ) {
int code = (int) o[p], n = (int) o[p + 1], a = p + 2; p = a + n;
switch (code) {
case FILL_ELLIPSE: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, fill); break;
case STROKE_ELLIPSE: stroke.setStrokeWidth(o[a + 4]); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); rf.set(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3]); c.drawOval(rf, stroke); break;
case LINE: stroke.setStrokeWidth(o[a + 4]); stroke.setStrokeCap(Paint.Cap.BUTT); stroke.setColor(rgba(o[a + 5], o[a + 6], o[a + 7], o[a + 8])); c.drawLine(o[a], o[a + 1], o[a + 2], o[a + 3], stroke); break;
case ARC: { float r = o[a + 2]; stroke.setStrokeWidth(o[a + 5]); stroke.setColor(rgba(o[a + 6], o[a + 7], o[a + 8], o[a + 9]));
rf.set(o[a] - r, o[a + 1] - r, o[a] + r, o[a + 1] + r);
c.drawArc(rf, (float) Math.toDegrees(o[a + 3]), (float) Math.toDegrees(o[a + 4] - o[a + 3]), false, stroke); break; }
case FILL_RECT: fill.setColor(rgba(o[a + 4], o[a + 5], o[a + 6], o[a + 7])); c.drawRect(o[a], o[a + 1], o[a] + o[a + 2], o[a + 1] + o[a + 3], fill); break;
case IMAGE: {
Bitmap b = o[a] >= 0 ? bitmap(s[(int) o[a]]) : null;
if (b == null && o[a + 1] >= 0) b = bitmap(s[(int) o[a + 1]]);
if (b == null) break;
if (o[a + 4] > 0) src.set((int) o[a + 2], (int) o[a + 3], (int) (o[a + 2] + o[a + 4]), (int) (o[a + 3] + o[a + 5]));
else src.set(0, 0, b.getWidth(), b.getHeight());
rf.set(o[a + 6], o[a + 7], o[a + 6] + o[a + 8], o[a + 7] + o[a + 9]);
img.setAlpha(Math.round(Math.max(0, Math.min(1, o[a + 10])) * 255));
img.setBlendMode(o[a + 11] == 1 ? BlendMode.LUMINOSITY : null);
c.drawBitmap(b, src, rf, img); img.setBlendMode(null); break; }
case TEXT: { // 矩形内水平居中、顶对齐(同 NSString drawInRect)| centered horizontally, top-aligned in the rect (like NSString drawInRect)
text.setTextSize(o[a + 5]); text.setColor(rgba(.85f, .79f, .65f, o[a + 6]));
c.drawText(s[(int) o[a]], o[a + 1] + o[a + 3] / 2, o[a + 2] - text.getFontMetrics().ascent, text); break; }
case LABEL: {
Bitmap b = bitmap(s[(int) o[a]]);
if (b == null && n > 4 && o[a + 4] >= 0) b = bitmap(s[(int) o[a + 4]]); // 可选第 5 项 = 备用图 | optional 5th value = fallback image
if (b == null) break;
float h = o[a + 3], w = b.getWidth() * h / b.getHeight();
rf.set(o[a + 1] - w / 2, o[a + 2] - h / 2, o[a + 1] + w / 2, o[a + 2] + h / 2); img.setAlpha(255); c.drawBitmap(b, null, rf, img); break; }
case V4TEXT: { JSONObject u = ui(); if (u == null) break;
float hh = getHeight() / density, ww = getWidth() / density;
v4text(c, s[(int) o[a]], u.optJSONObject("badge").optJSONObject("glyphs"), o[a + 1], o[a + 2], (int) o[a + 3], ww, hh / 1320f); break; }
case V4: drawV4(c, o, a, s); break;
case COVER: fill.setColor(Color.BLACK); c.drawRect(0, 0, o[a], o[a + 1], fill); break;
}
}
c.restore();
}
// ---- 底部 UI v4(同 DmTouchOverlay.m drawV4):几何单位 = 2868×1320 效果图像素,x = (像素 − 1434) × u + 宽/2,y = 像素 × u,u = 高/1320 ----
// ---- Bottom UI v4 (same as DmTouchOverlay.m drawV4): geometry unit = pixels of the 2868×1320 mockup, x = (px − 1434) × u + width/2, y = px × u, u = height/1320 ----
private void v4text(Canvas c, String str, JSONObject glyphs, float x, float baseline, int align, float W, float u) {
if (glyphs == null) return;
float adv = 0; for (int i = 0; i < str.length(); i++) { JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g != null) adv += (float) g.optDouble("adv"); }
float pen = align == 1 ? x - adv : x - adv / 2;
img.setAlpha(255);
for (int i = 0; i < str.length(); i++) {
JSONObject g = glyphs.optJSONObject(str.substring(i, i + 1)); if (g == null) continue;
String f = g.optString("file", null); Bitmap b = f != null && !g.isNull("file") ? bitmap("hud_v4_ui/" + f) : null;
if (b != null) { float l = (pen + (float) g.optDouble("dx") - 1434) * u + W / 2, t = (baseline + (float) g.optDouble("dy")) * u;
rf.set(l, t, l + b.getWidth() * u, t + b.getHeight() * u); c.drawBitmap(b, null, rf, img); }
pen += (float) g.optDouble("adv");
}
}
private float X(float px, float u, float W) { return (px - 1434) * u + W / 2; }
private void blit(Canvas c, Bitmap b, float l, float t, float w, float h, float alpha) {
if (b == null) return; rf.set(l, t, l + w, t + h); img.setAlpha(Math.round(alpha * 255)); c.drawBitmap(b, null, rf, img); img.setAlpha(255);
}
private void digit(Canvas c, int n, float cx, float cy, float alpha, float u, float W) {
Bitmap d = bitmap("hud_v4_ui/diff_" + n + ".png"); if (d == null) return;
blit(c, d, X(cx, u, W) - d.getWidth() * u / 2, cy * u - d.getHeight() * u / 2, d.getWidth() * u, d.getHeight() * u, alpha);
}
private static int rgb(JSONArray a) { return Color.rgb(a.optInt(0), a.optInt(1), a.optInt(2)); }
// v:life, mana, lv(字符串表下标), 十字按住, 有点数, 任务未读, 经验‰, 腰带 ×4, 难度档, 选择条展开
// v: life, mana, lv (string table indices), cross held, has points, quest unread, exp ‰, belt ×4, difficulty level, selector expanded
private void drawV4(Canvas c, float[] o, int a, String[] s) {
JSONObject ui = ui(); if (ui == null) return;
try {
float W = getWidth() / density, u = getHeight() / density / 1320f;
boolean held = o[a + 3] != 0, points = o[a + 4] != 0, alert = points || o[a + 5] != 0;
float exp = o[a + 6]; int players = (int) o[a + 11]; boolean diffOpen = o[a + 12] != 0;
Bitmap full = bitmap("hud_v4_ui/base_full.png"); JSONObject bo = ui.getJSONObject("base");
if (full != null) blit(c, full, X((float) bo.getDouble("x"), u, W), (float) bo.getDouble("y") * u, full.getWidth() * u, full.getHeight() * u, 1);
JSONArray slots = ui.getJSONArray("slots"), s6 = slots.getJSONArray(5);
Bitmap btn = bitmap(alert ? (held ? "hud_v4_ui/lvl_1.png" : "hud_v4_ui/lvl_0.png") : (held ? "hud_v4_ui/lvl_d1.png" : "hud_v4_ui/lvl_d0.png"));
float bl = X((float) s6.getDouble(0), u, W), bt = (float) s6.getDouble(1) * u, bw = (float) (s6.getDouble(2) - s6.getDouble(0)) * u, bh = (float) (s6.getDouble(3) - s6.getDouble(1)) * u;
if (btn != null) {
if (points) { img.setShadowLayer(10 * u, 0, 0, Color.argb(242, 255, 209, 89)); blit(c, btn, bl, bt, bw, bh, 1); img.clearShadowLayer(); }
blit(c, btn, bl, bt, bw, bh, 1);
}
JSONObject e = ui.getJSONObject("exp");
float x0 = (float) e.getDouble("x0"), x1 = (float) e.getDouble("x1"), y = (float) e.getDouble("y"), eh = (float) e.getDouble("h");
fill.setColor(rgb(e.getJSONArray("track"))); c.drawRect(X(x0, u, W), y * u, X(x0, u, W) + (x1 - x0) * u, (y + eh) * u, fill);
stroke.setColor(rgb(e.getJSONArray("edge"))); stroke.setStrokeWidth(u);
c.drawRect(X(x0, u, W) + u / 2, y * u + u / 2, X(x0, u, W) + u / 2 + (x1 - x0 - 1) * u, y * u + u / 2 + (eh - 1) * u, stroke);
fill.setColor(rgb(e.getJSONArray("fill"))); c.drawRect(X(x0 + 1, u, W), (y + 1) * u, X(x0 + 1, u, W) + (x1 - x0 - 2) * u * exp / 1000f, (y + eh - 1) * u, fill);
int ticks = e.getInt("ticks"); fill.setColor(rgb(e.getJSONArray("track")));
for (int t = 1; t < ticks; t++) { float tx = X(x0 + Math.round((x1 - x0) * t / (double) ticks), u, W); c.drawRect(tx, (y + 1) * u, tx + u, (y + eh - 1) * u, fill); }
JSONObject vt = ui.getJSONObject("vital");
v4text(c, s[(int) o[a]], vt.getJSONObject("glyphs"), (float) vt.getDouble("left_x"), (float) vt.getDouble("baseline"), 0, W, u);
v4text(c, s[(int) o[a + 1]], vt.getJSONObject("glyphs"), (float) vt.getDouble("right_x"), (float) vt.getDouble("baseline"), 0, W, u);
JSONObject lv = ui.getJSONObject("lv");
v4text(c, s[(int) o[a + 2]], lv.getJSONObject("glyphs"), (float) lv.getDouble("x"), (float) lv.getDouble("baseline"), 0, W, u);
JSONArray in = ui.getJSONArray("inner"); JSONObject bd = ui.getJSONObject("badge");
for (int i = 1; i <= 4; i++) { int cnt = (int) o[a + 6 + i]; if (cnt == 0) continue;
JSONArray si = slots.getJSONArray(i);
v4text(c, Integer.toString(cnt), bd.getJSONObject("glyphs"), (float) (si.getDouble(0) + in.getDouble(2) + bd.getDouble("dx")), (float) (si.getDouble(1) + in.getDouble(3) + bd.getDouble("dy")), 1, W, u); }
float icx = (float) (in.getDouble(0) + in.getDouble(2) + 1) / 2, icy = (float) (in.getDouble(1) + in.getDouble(3) + 1) / 2;
JSONArray s0 = slots.getJSONArray(0);
if (players >= 1 && players <= 8) digit(c, players, (float) s0.getDouble(0) + icx, (float) s0.getDouble(1) + icy, 1, u, W);
if (diffOpen) {
JSONObject pk = ui.getJSONObject("pick"); Bitmap tile = bitmap("hud_v4_ui/slot.png");
for (int i = 0; i < 8; i++) {
float cx = (float) (pk.getDouble("center_x") + (i - 3.5) * pk.getDouble("pitch")), cy = (float) pk.getDouble("y"), al = i + 1 == players ? 1 : .82f;
if (tile != null) blit(c, tile, X(cx - tile.getWidth() / 2f, u, W), (cy - tile.getHeight() / 2f) * u, tile.getWidth() * u, tile.getHeight() * u, al);
digit(c, i + 1, cx, cy, al, u, W);
}
}
} catch (Exception ex) { Log.e("d2r", "底部 UI v4 绘制失败:" + ex); }
}
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 自适应图标:图在 108dp 画布中缩到 72dp,各家圆形 / 圆角遮罩都不裁到图(iOS 同一张 AppIcon1024.png)| Adaptive icon: the art is scaled to 72dp inside the 108dp canvas so no launcher mask crops it (same AppIcon1024.png as iOS) -->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@android:color/black" />
<foreground android:drawable="@mipmap/ic_launcher_fg" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 120 KiB

+702
View File
@@ -0,0 +1,702 @@
// Android 局内触屏操作层:front_ios.m 里 DmMetalView(手势 → 手势层 dm_touch_controls → 宿主)与 DmTouchOverlay(画操作层)的移植。
// 坐标一律用 dp(≈ UIKit 点):Java 传视图尺寸、安全边距与触点时已除以 density。
// 线程:触点、每帧 tick、绘制都在 Java 界面线程;界面消息(touch_ui_message)在客体线程,只写原子量,界面线程 tick 时取用
// (iOS 这里用 dispatch_async 切主线程)。绘制不直接碰 Canvas:C 产出一张绘制指令表(浮点数组 + 字符串表),Java 照表画。
// 没移植:秘境任务条、货架拖货跟手图、测试脚本触点、操作层截图。
// Android in-run touch layer: port of DmMetalView (gestures → gesture layer dm_touch_controls → host) and DmTouchOverlay (draws the layer) from front_ios.m.
// All coordinates are dp (≈ UIKit points): Java divides the view size, safe insets and touch points by density before passing them.
// Threads: touches, the per-frame tick and drawing all run on the Java UI thread; UI messages (touch_ui_message) arrive on the guest thread and only write
// atomics that the UI-thread tick picks up (iOS uses dispatch_async to the main thread here). Drawing does not touch a Canvas: C emits a draw list
// (float array + string table) that Java executes.
// Not ported: Rift objective bar, the shelf-drag ghost image, scripted test touches, overlay capture.
#include "../../dm.h"
#include "../../front.h"
#include "../../hle.h"
#include "../../dm_input.h"
#include "../../dm_cursor.h"
#include "../../dm_hud.h"
#include "../../dm_world.h"
#include "../../dm_uiscreen.h"
#include "../../dm_actions.h"
#include "../../dm_i18n.h"
#include "../../dm_custom.h"
#include "../../../touch/dm_touch_controls.h"
#include "../../../touch/dm_touch_game_state.h"
#include "../../../touch/dm_touch_native_art.h"
#include <jni.h>
#include <math.h>
#include <stdatomic.h>
#include <string.h>
#include <time.h>
void dm_tp_request(void);
int dm_drop_haptic_take(void);
int dm_padmode_busy(void);
void dm_padmode_request(int pad);
uint32_t dm_padmode_rebuilds(void);
int dm_swapskill_slot(int, int *);
int dm_freetp_zr_free(int zl);
void dm_ui_key_pulse_alone(uint64_t, int);
void uimsg_subscribe(void (*)(const char *, const char *, const char *));
static double now_s(void) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec + t.tv_nsec * 1e-9; }
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
// ---- 客体线程 → 界面线程 | guest thread → UI thread ----
static _Atomic int g_touch_frontend = 1, g_touch_navigation = 1, g_hud_blocked, g_cover;
static _Atomic int g_nav_pub;
int dm_front_navigation(void) { return atomic_load(&g_nav_pub); } // 面板 / 读取画面 / 过场开着:手柄 ZR 只在游戏态接管 | a panel / loading screen / cutscene is open: the pad's ZR is taken over only in game state
int dm_touch_frontend(void) { return atomic_load(&g_touch_frontend); }
static void restart_cover_hook(int on) { atomic_store(&g_cover, on); } // 0 撤 / 1 黑屏 / 2 透明但吞触点 | 0 remove / 1 black / 2 transparent but swallows touches
// ---- 触摸记录:Android 指针 id 会复用,iOS 的 UITouch 身份换成记录下标 | touch records: Android pointer ids get reused, records stand in for UITouch identity ----
enum { NREC = 32 };
static struct { int used, pid, done; float x, y; } R[NREC];
static int pid_rec(int pid) { for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done && R[i].pid == pid) return i; return -1; }
// ---- DmMetalView 状态 | DmMetalView state ----
static dm_tc_state C;
static float W, H; // 视图尺寸(dp) | view size (dp)
static int g_slot[16]; // 手指槽 → 记录;-1 = 空 | finger slot → record; -1 = empty
static uint32_t g_swallow; // 手柄模式 / 切换中 / 遮罩下落下的手指(记录位图) | fingers that landed in pad mode / mid-switch / under the cover (record bitmap)
static int g_pad, g_fe = 1, g_nav = -1, g_blocked_applied, g_dialog_only, g_hud_blocked_v;
static int ui_finger = -1, map_t = -1, mapback_t = -1, bind_t = -1, pend_end = -1;
static float fe_ox, fe_oy, map_x0, map_y0, bind_x0, bind_y0; static int fe_drag, ui_drag_on;
static double map_t0, pend_time, pend_wall; static int pend_fire, final_asked;
static uint64_t bind_key; static uint32_t sel_id; static double stat_next, tip_until, add_at;
static unsigned map_world_seq; static int map_world_asked; static float map_wx, map_wy;
static int pulse_ticking; static uint64_t pulse_epoch, pulse_s0; static double pulse_t0, pulse_seen, pulse_free;
static unsigned item_seq, rel_seq; static int rel_asked, item_asked, item_kind;
static double labels_at; static int labels_done;
static dm_hud_info g_hud; static dm_tg_snapshot g_native;
static int g_dirty = 1, g_haptic;
static int slot_of_rec(int t) { for (int i = 0; i < 16; i++) if (g_slot[i] == t) return i; return -1; }
static int rec_referenced(int t) { return slot_of_rec(t) >= 0 || t == ui_finger || t == map_t || t == mapback_t || t == bind_t || t == pend_end || (g_swallow >> t & 1); }
static void gc_recs(void) { for (int i = 0; i < NREC; i++) if (R[i].used && R[i].done && !rec_referenced(i)) R[i].used = 0; }
static void push(void) {
dm_touch ts[16]; int n = 0;
if (W > 0 && H > 0) for (int i = 0; i < 16; i++) if (g_slot[i] >= 0) {
int t = g_slot[i]; ts[n++] = (dm_touch){(uint32_t)i, fminf(fmaxf(R[t].x / W, 0), .99999f), fminf(fmaxf(R[t].y / H, 0), .99999f)};
}
dm_touch_set(ts, n);
if (C.pointer_valid) dm_cursor_set_screen(C.pointer_x, C.pointer_y, W, H); else dm_cursor_clear();
dm_input_set(C.buttons, C.lx, C.ly, C.rx, C.ry);
if (C.belt_request) { int br = C.belt_request; C.belt_request = 0; if (br == 1 || br == 2) dm_belt_expand(br == 1); else dm_belt_use(br & 0xf, br >> 4 & 0xf); }
if (C.diff_request) { dm_hud_request_players(C.diff_request); C.diff_request = 0; }
g_dirty = 1;
}
static void cancel_controls(void) {
pend_end = -1; final_asked = 0;
for (int i = 0; i < 16; i++) g_slot[i] = -1;
dm_tc_cancel_all(&C); push();
if (ui_drag_on) { ui_drag_on = 0; dm_ui_drag_end(); }
map_t = mapback_t = bind_t = -1;
}
static void set_pad_mode(int pad) {
g_pad = pad;
if (pad) { tip_until = -2; dm_tc_cancel_all(&C); push(); }
g_dirty = 1;
}
static void set_frontend(int fe) {
g_fe = fe;
if (fe) { pend_end = -1; final_asked = 0; for (int i = 0; i < 16; i++) g_slot[i] = -1; dm_tc_cancel_all(&C); push(); }
g_dirty = 1;
}
static void hud_blocked(int n) { g_hud_blocked_v = n > 0; g_dialog_only = n < 0; dm_tc_set_joy_block(&C, n < 0); g_dirty = 1; }
static void navigation_mode(int n) {
if (g_nav == n) return;
dm_tc_set_navigation_mode(&C, n); g_nav = n; atomic_store(&g_nav_pub, n);
static int pad = -1; if (pad < 0) { const char *e = getenv("DM_TOUCH_NAV_PAD"); pad = e && e[0] == '1'; }
uint32_t mask = n ? (dm_tc_nav_mask(pad && n != 2) | (n == 3 ? 1u << DM_TC_MENU : 0)) : (((1u << DM_TC_COUNT) - 1) & ~(1u << DM_TC_MAP));
dm_tc_enable_targets(&C, mask); push();
// 进局后第一次回游戏态:替玩家按一次 L 打开物品名标签(同 iOS itemLabelsOn,1.5 秒后) | first return to game state: press L once for the player to turn item labels on (as iOS itemLabelsOn, after 1.5 s)
if (!n && !labels_done && !labels_at) { const char *e = getenv("DM_TOUCH_DEFAULTS"); if (!(e && !strcmp(e, "0"))) labels_at = now_s() + 1.5; }
if (n && dm_ui_map_is_full()) { dm_ui_map_full(0); LOG("前端:开了面板,全屏地图先收回小地图"); }
}
// 客体线程发布的状态落到界面线程 | apply the state published by the guest thread on the UI thread
static void apply_pending(void) {
int fe = atomic_load(&g_touch_frontend); if (fe != g_fe) set_frontend(fe);
int hb = atomic_load(&g_hud_blocked); if (hb != g_blocked_applied) { g_blocked_applied = hb; hud_blocked(hb); }
navigation_mode(atomic_load(&g_touch_navigation));
}
// ---- 界面消息(客体线程):同 iOS hud_stack_message / touch_ui_message | UI messages (guest thread): as iOS hud_stack_message / touch_ui_message ----
enum { HUD_STACK_MAX = 64 };
static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX];
static void hud_stack_message(const char *act, const char *arg) {
if (!strcmp(act, "UnloadPanel") && !strcmp(arg, "LoadScreenPanel")) {
for (int i = 0; i < HUD_STACK_MAX; i++)
if (!(g_hud_stack[i].open > 0 && strcmp(g_hud_stack[i].name, "LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name))) memset(&g_hud_stack[i], 0, sizeof g_hud_stack[i]);
} else if (!strcmp(act, "UnloadAll")) memset(g_hud_stack, 0, sizeof g_hud_stack);
else {
int tog = !strcmp(act, "TogglePanel");
int open = !strcmp(act, "OpenPanel") || !strcmp(act, "OpenExclusivePanel"), close = !strcmp(act, "ClosePanel") || !strcmp(act, "UnloadPanel");
if (!open && !close && !tog) return;
if (dm_ui_panel_resident(arg)) return;
int slot = -1; for (int i = 0; i < HUD_STACK_MAX; i++) if (!strcmp(g_hud_stack[i].name, arg)) { slot = i; break; }
if (slot < 0) for (int i = 0; i < HUD_STACK_MAX; i++) if (!g_hud_stack[i].name[0]) { slot = i; snprintf(g_hud_stack[i].name, sizeof g_hud_stack[i].name, "%s", arg); break; }
if (slot < 0) return;
if (tog) { open = g_hud_stack[slot].open <= 0; close = !open; }
if (close && g_hud_stack[slot].open <= 0) return;
if (open && g_hud_stack[slot].open > 0) return;
g_hud_stack[slot].open = open ? 1 : 0;
fprintf(stderr, "[hud] 面板栈 %s %s → %d\n", act, arg, g_hud_stack[slot].open);
}
int n = 0, dlg = 0;
for (int i = 0; i < HUD_STACK_MAX; i++) {
if (!strcmp(g_hud_stack[i].name, "NpcDialogPanel") || !strcmp(g_hud_stack[i].name, "ScrollSpeechPanel")) dlg |= g_hud_stack[i].open > 0;
else n += g_hud_stack[i].open;
}
if (!n && dlg) n = -1;
atomic_store(&g_hud_blocked, n);
}
static void touch_ui_message(const char *cat, const char *act, const char *arg) {
if (!strcmp(cat, "PanelManager")) hud_stack_message(act, arg);
static dm_tc_scene scene; static uint64_t scene_epoch = 1, world_epoch = 1; static int prev_mode = 1;
dm_tc_scene before = scene;
dm_tc_set_panel_state(dm_ui_panel_state());
int mode = dm_tc_navigation(&scene, cat, act, arg);
if (scene.game && atomic_load(&g_hud_blocked) > 0) mode = 1;
if (before.game != scene.game) ++world_epoch;
{ static uint32_t rb0; uint32_t rb = dm_padmode_rebuilds(); if (rb != rb0) { rb0 = rb; ++world_epoch; } }
if (mode != prev_mode) ++scene_epoch;
prev_mode = mode;
dm_touch_game_set_scene(!mode, scene_epoch, world_epoch);
atomic_store(&g_touch_frontend, !scene.game);
int nmode = mode ? (dm_tc_scene_dead() ? 2 : dm_tc_scene_dialog_only(&scene) && atomic_load(&g_hud_blocked) <= 0 ? 3 : 1) : 0;
atomic_store(&g_touch_navigation, nmode);
dm_uiscreen_set_panel(nmode == 1);
}
// front_run 在客体线程开头调 | called by front_run at the start of the guest thread
void touch_app_guest_start(void) {
extern void (*g_dm_restart_cover_hook)(int); g_dm_restart_cover_hook = restart_cover_hook;
uimsg_subscribe(touch_ui_message);
dm_touch_game_live_check(1);
if (!dm_touch_game_attach()) LOG("【红】技能绑定读取没挂上(产物没有观测门 OBS_BINDING_GETTER,或 main 模块不符):技能键图标 / 回城键绑定不工作");
}
// ---- 手柄模式(iOS dm_gamepad.m 的 apply / set_mode,Android 只有一路合并后的手柄) | pad mode (iOS dm_gamepad.m apply / set_mode; Android has one merged pad) ----
static int g_need_center;
static void pad_set_mode(int pad) {
if (g_pad == pad) return;
dm_padmode_request(pad); LOG("手柄:%s", pad ? "手柄有输入 → 手柄模式" : "碰了屏幕 → 触屏模式");
set_pad_mode(pad);
}
static int stick_on(int was, int32_t x, int32_t y) { double m = hypot(x, y) / DM_STICK_MAX; return was ? m >= 0.15 : m >= 0.25; }
static uint64_t pad_b; static int32_t pad_ax[4];
static void pad_apply(void) {
uint64_t b = pad_b; int32_t ax[4] = {pad_ax[0], pad_ax[1], pad_ax[2], pad_ax[3]};
static int on[2]; static uint64_t prev_b;
on[0] = stick_on(on[0], ax[0], ax[1]); on[1] = stick_on(on[1], ax[2], ax[3]);
if (!on[0] && !on[1]) g_need_center = 0;
if ((b & ~prev_b) || ((on[0] || on[1]) && !g_need_center)) pad_set_mode(1);
prev_b = b;
if (!g_pad || !on[0]) ax[0] = ax[1] = 0;
if (!g_pad || !on[1]) ax[2] = ax[3] = 0;
{ static uint64_t prev; static int mine;
if ((b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) { mine = !dm_front_navigation() && dm_freetp_zr_free((b & DM_BTN_ZL) != 0); if (mine) { dm_tp_request(); LOG("手柄:ZR(这一格空着)→ 免费回城"); } }
prev = b; if (mine) b &= ~(uint64_t)DM_BTN_ZR; if (!(b & DM_BTN_ZR) && !(prev & DM_BTN_ZR)) mine = 0; }
dm_pad_set(b, ax[0], ax[1], ax[2], ax[3]);
}
void touch_app_pad(uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { pad_b = b; pad_ax[0] = lx; pad_ax[1] = ly; pad_ax[2] = rx; pad_ax[3] = ry; pad_apply(); }
static void gamepad_touched(void) { if (g_pad) { g_need_center = 1; pad_set_mode(0); pad_apply(); } }
// ---- 手势 | gestures ----
static uint64_t skill_key_at(float x, float y, int *empty) {
int i = dm_tc_hit(&C.layout, x, y);
if (i >= DM_TC_SKILL1 && i <= DM_TC_SKILL4 && (C.enabled_targets & (1u << i))) {
const dm_tc_target *t = &C.layout.target[i];
dm_ta_glyph g = dm_ta_current_set(&g_native, t->button, now_ns(), C.skill_set); *empty = g.status == DM_TA_EMPTY;
return t->button | (C.skill_set ? DM_BTN_ZL : 0);
}
return 0;
}
static int in_minimap(float x, float y) {
float r[4]; if (g_nav || W <= 0 || !dm_ui_minimap_rect(r)) return 0;
if (dm_tc_hit(&C.layout, x, y) >= 0) return 0;
float x0 = r[0] * W, y0 = r[1] * H, w = (r[2] - r[0]) * W, h = (r[3] - r[1]) * H, band = h / 4; if (band < 30) band = MIN(30, h * 0.4f);
return x >= x0 && x < x0 + w && y >= y0 && y < y0 + band;
}
static void refresh_portal_binding(void) {
{ dm_hud_info h; dm_hud_get(&h); h.x = h.y = 0; if (memcmp(&h, &g_hud, sizeof h)) { g_hud = h; g_dirty = 1; } }
dm_tg_snapshot s = {0}; dm_touch_game_snapshot(&s);
if (memcmp(&s.raw_skill_id, &g_native.raw_skill_id, sizeof s.raw_skill_id) || memcmp(&s.mapping, &g_native.mapping, sizeof s.mapping) || s.valid != g_native.valid) g_dirty = 1;
g_native = s;
if (g_nav || !s.supported) return;
uint64_t mask = 0; // 回城键不跟原生绑定(同 iOS) | the portal key does not follow the native binding (as iOS)
if (C.layout.target[DM_TC_PORTAL].button != mask || C.portal_binding_identity != s.binding_identity || C.portal_scene_epoch != s.scene_epoch) {
dm_tc_set_portal_binding(&C, mask, s.binding_identity, s.scene_epoch); push();
}
}
static void bind_tap_sync(void) {
float nx = 0, ny = 0;
{ static int was; int st = dm_ui_bind_active(); if (st == 2 && was != 2 && W > 0) { C.pointer_valid = 1; C.pointer_x = 0.155f * W; C.pointer_y = 0.5f * H; } was = st; }
int hk = dm_ui_bind_skill_hit(&nx, &ny); C.tap_button = 0; C.tap_move = 0;
if (!hk) sel_id = 0;
if (hk) { C.tap_x = nx * W; C.tap_y = ny * H;
if (hk == 1 && dm_ui_bind_active() == 2) C.tap_button = DM_BTN_Y;
else if (!dm_ui_bind_active()) C.tap_move = 1; }
}
static void ui_touch(const int *ts, int n, int ph) {
if (W <= 0 || H <= 0) return;
for (int k = 0; k < n; k++) {
int t = ts[k];
if (ph == 0 && ui_finger < 0) { ui_finger = t; fe_ox = R[t].x; fe_oy = R[t].y; fe_drag = 0; }
if (t != ui_finger) continue;
float px = R[t].x, py = R[t].y, dy = fabsf(py - fe_oy);
if (ph == 1 && !fe_drag && !ui_drag_on && dy > 10 && dy > fabsf(px - fe_ox) && dm_ui_fe_drag_ok()) {
fe_drag = 1; ui_drag_on = 1; dm_ui_touch(3, 0, 0); dm_ui_drag_begin(1, fe_ox / W, fe_oy / H, 0);
}
if (fe_drag) { if (ph == 1) dm_ui_drag_move(px / W, py / H); else if (ph == 2) { fe_drag = 0; ui_drag_on = 0; dm_ui_drag_end(); ui_finger = -1; } continue; }
dm_ui_touch(ph, px / W, py / H);
if (ph == 2) ui_finger = -1;
}
}
static void pulse_tick(void);
static void arm_pulse_end(void) {
if (pulse_ticking || (!C.pulse_button && !dm_tc_pulse_pending(&C))) return;
pulse_ticking = 1; pulse_epoch = 0; pulse_tick();
}
static void touches_began(const int *ts, int n) {
{ int was = g_pad; gamepad_touched();
if (was || dm_padmode_busy() || atomic_load(&g_cover)) { for (int k = 0; k < n; k++) g_swallow |= 1u << ts[k]; if (was) LOG("前端:手柄模式下碰屏 → 只切回触屏模式,这一下不执行"); return; } }
if (g_fe) { ui_touch(ts, n, 0); return; }
refresh_portal_binding();
void finish_touches(const int *, int, int);
if (pend_end >= 0) { int pt = pend_end; pend_fire = 1; finish_touches(&pt, 1, 0); pend_fire = 0; pend_end = -1; final_asked = 0; }
double now = now_s();
for (int k = 0; k < n; k++) {
int t = ts[k]; float px = R[t].x, py = R[t].y;
{ int ex = 0; C.belt_rows = dm_belt_rows(&ex); C.belt_open = ex;
if (dm_tc_belt_outside(&C, px, py)) { dm_belt_expand(0); LOG("前端:腰带展开着点别处 (%.0f,%.0f) → 只收腰带", px, py); continue; } }
if (!g_nav && bind_t < 0 && !dm_ui_bind_active()) { int em = 0; uint64_t bk = skill_key_at(px, py, &em); if (bk && em) { bind_t = t; bind_key = bk; bind_x0 = px; bind_y0 = py; map_t0 = now; continue; } }
if (map_t < 0 && in_minimap(px, py)) { map_t = t; map_x0 = px; map_y0 = py; map_t0 = now; continue; }
for (int i = 0; i < 16; i++) if (g_slot[i] < 0) {
g_slot[i] = t; { int ex = 0; C.belt_rows = dm_belt_rows(&ex); C.belt_open = ex; } dm_tc_begin_at(&C, i, px, py, now);
if (!g_nav && C.finger[i].target == DM_TC_PORTAL) { dm_tp_request(); LOG("前端:点回城钮 → 免费回城"); }
if (!g_nav && mapback_t < 0 && C.finger[i].target == DM_TC_NONE && dm_ui_map_is_full()) { mapback_t = t; map_x0 = px; map_y0 = py; map_t0 = now; }
if (C.navigation_mode && C.pointer_slot == i && W > 0) item_seq = dm_ui_item_query(px / W, py / H);
item_asked = 1; item_kind = -1; // iOS 原样:这两句不在 if 里 | as on iOS: these two are outside the if
break;
}
}
push();
}
static void touches_moved(const int *ts0, int n0) {
int ts[NREC], n = 0; for (int k = 0; k < n0; k++) if (!(g_swallow >> ts0[k] & 1)) ts[n++] = ts0[k];
if (!n) return;
if (g_fe) { ui_touch(ts, n, 1); return; }
if (ui_finger >= 0) { int m = 0, hit = 0; for (int k = 0; k < n; k++) { if (ts[k] == ui_finger) hit = 1; else ts[m++] = ts[k]; }
if (hit) { int u = ui_finger; ui_touch(&u, 1, 1); n = m; if (!n) return; } }
double now = now_s(); float sc = dm_tc_scale_for_size(W, H);
for (int k = 0; k < n; k++) {
int t = ts[k], i = slot_of_rec(t); if (i < 0) continue;
float px = R[t].x, py = R[t].y;
dm_tc_move_at(&C, i, px, py, now);
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].ui_drag && W > 0) { dm_tc_finger *f = &C.finger[i];
if (!ui_drag_on) { ui_drag_on = 1; dm_ui_drag_lift(DM_TC_POINTER_LIFT_PT * sc / H); dm_ui_drag_begin(f->ui_drag, f->aim_origin_x / W, f->aim_origin_y / H, 44.0f / H); }
dm_ui_drag_move(px / W, py / H); }
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].pointer_dragged && W > 0) { rel_seq = dm_ui_drop_query(px / W, (py - DM_TC_POINTER_LIFT_PT * sc) / H, py / H); rel_asked = 1; }
}
push();
arm_pulse_end();
}
// cancelled:0 = 抬起,1 = 系统取消 | cancelled: 0 = lifted, 1 = cancelled by the system
void finish_touches(const int *ts0, int n0, int cancelled) {
int ts[NREC], n = 0;
for (int k = 0; k < n0; k++) { if (g_swallow >> ts0[k] & 1) g_swallow &= ~(1u << ts0[k]); else ts[n++] = ts0[k]; }
if (ui_finger >= 0) { int m = 0, hit = 0; for (int k = 0; k < n; k++) { if (ts[k] == ui_finger) hit = 1; else ts[m++] = ts[k]; }
if (hit) { int u = ui_finger; ui_touch(&u, 1, 2); n = m; } }
if (!n) return;
double now = now_s(); float sc = dm_tc_scale_for_size(W, H);
for (int k = 0; k < n; k++) {
int t = ts[k]; float px = R[t].x, py = R[t].y;
if (t == map_t) { map_t = -1;
if (!cancelled && !g_nav && hypotf(px - map_x0, py - map_y0) <= 14 && now - map_t0 < 0.6) {
if (dm_ui_map_is_full()) { dm_ui_map_full(0); LOG("前端:点小地图那一块 (%.0f,%.0f) → 回小地图", px, py); }
else if (W > 0) { map_world_seq = dm_world_tap(px / W, py / H); map_world_asked = 1; map_wx = px; map_wy = py; } }
continue; }
if (t == bind_t) { bind_t = -1;
if (!cancelled && !g_nav && hypotf(px - bind_x0, py - bind_y0) <= 14) { dm_ui_bind_begin(bind_key); LOG("前端:点空技能位 (%.0f,%.0f) → 给键 %#llx 选技能", px, py, (unsigned long long)bind_key); }
continue; }
if (t == mapback_t) { mapback_t = -1;
if (!cancelled && !g_nav && dm_ui_map_is_full() && hypotf(px - map_x0, py - map_y0) <= 14 && now - map_t0 < 0.6) { dm_ui_map_full(0); LOG("前端:全屏地图开着,点空处 (%.0f,%.0f) → 回小地图", px, py); } }
if (!pend_fire && pend_end < 0 && !cancelled && C.navigation_mode && C.pointer_slot >= 0 && g_slot[C.pointer_slot] == t && W > 0) {
dm_tc_finger *pf = &C.finger[C.pointer_slot]; int wait = 0;
if (item_asked && dm_ui_item_result(item_seq) < 0) wait = 1;
else if (pf->pointer_dragged) {
dm_tc_move_at(&C, C.pointer_slot, px, py, now);
rel_seq = dm_ui_drop_query(px / W, (py - DM_TC_POINTER_LIFT_PT * sc) / H, py / H); rel_asked = 1; final_asked = 1; wait = 1; }
if (wait) { pend_end = t; pend_time = now; pend_wall = now; continue; }
}
int i = slot_of_rec(t); if (i < 0) continue;
if (cancelled) { dm_tc_finger *cf = &C.finger[i]; int drag = C.navigation_mode && C.pointer_slot == i && (cf->pointer_dragged || cf->shop_drag);
if (ui_drag_on && C.pointer_slot == i) { ui_drag_on = 0; dm_ui_drag_end(); }
if (drag) { int shop = cf->shop_drag; if (!shop) dm_tc_pointer_release(&C, 0); dm_tc_end_at(&C, i, now); LOG("前端:拖动中被系统取消触摸 → %s", shop ? "不买不取" : "放回原处"); }
else dm_tc_cancel_finger(&C, i);
if (C.pointer_slot < 0) { rel_asked = 0; item_asked = 0; }
g_slot[i] = -1; continue; }
if (C.navigation_mode && C.pointer_slot == i && C.finger[i].shop_drag) {
int rk = rel_asked ? dm_ui_item_result(rel_seq) : 0; if (rk < 0) rk = dm_ui_drop_last();
if (rk == 5 && !dm_ui_drop_bag()) LOG("前端:%s拖出后松在背包格以外的物品区 → 不%s", item_kind == 8 ? "一叠" : "货架上的货", item_kind == 8 ? "取" : "买");
else if ((rk == 5 || rk == 11) && W > 0) { dm_tc_finger *sf = &C.finger[i]; float ax = sf->aim_origin_x / W, ay = sf->aim_origin_y / H;
if (rk == 11) { dm_ui_stack_cube_at(ax, ay); LOG("前端:高级仓库里的一叠拖到魔盒格上松手 → 1 件进魔盒"); }
else if (item_kind == 8) { dm_ui_stack_take_at(ax, ay); LOG("前端:高级仓库里的一叠拖到背包松手 → 取 1 件"); }
else { LOG("前端:货架上的货拖到背包松手 → 买"); dm_ui_shop_buy_at(ax, ay); }
C.pointer_x = sf->aim_origin_x; C.pointer_y = sf->aim_origin_y; }
} else if (C.navigation_mode && C.pointer_slot == i && C.finger[i].pointer_dragged && rel_asked) {
int rr = dm_ui_item_result(rel_seq); if (rr < 0) rr = dm_ui_drop_last(); if (rr < 0) rr = 0; float dx, dy;
if ((rr == 5 && dm_ui_drop_point(&dx, &dy)) || (rr == 0 && dm_ui_origin_point(&dx, &dy))) dm_tc_pointer_release_at(&C, dx * W, dy * H);
else { if (rr == 7) { dm_shop_sell_cursor(); rr = 0; } dm_tc_pointer_release(&C, rr < 0 ? 1 : rr); }
}
rel_asked = 0;
if (C.navigation_mode && C.pointer_slot == i && item_asked) { item_asked = 0; dm_tc_pointer_item(&C, dm_ui_item_result(item_seq)); bind_tap_sync(); }
unsigned wt = C.world_tap_seq, mc = C.mouse_click_seq, tt = C.tab_tap_seq, us = C.use_seq, ids = C.ident_seq, sts = C.stack_take_seq, lps = C.long_press_seq, its = C.item_tap_seq;
if (ui_drag_on && C.pointer_slot == i) { ui_drag_on = 0; dm_ui_drag_end(); }
int was_ptr = C.pointer_slot == i; unsigned tm = C.tap_move_seq;
dm_tc_end_at(&C, i, pend_fire ? pend_time : now); g_slot[i] = -1;
if (C.tap_move_seq != tm) { uint32_t hid = dm_ui_hit_id();
if (hid && hid == sel_id) { if (hid <= 4) { dm_stat_add((int)hid - 1, 1); LOG("前端:再点同一个「+」(属性 %u)→ 加 1 点", hid - 1); } else add_at = C.last_time_s + 0.3; }
else { sel_id = hid; LOG("前端:点加点类按钮 → 选中(标识 %#x)", hid); } }
if (C.tab_tap_seq != tt) dm_ui_tab_go();
if (C.long_press_seq != lps) dm_ui_long_press();
if (C.item_tap_seq != its) dm_ui_item_tap();
if (C.stack_take_seq != sts) { dm_stash_take(1); LOG("前端:双击高级仓库里的一叠 → 取 1 件"); }
if (C.ident_seq != ids) dm_ui_identify_hovered();
if (C.use_seq != us) dm_ui_use_item();
if (C.world_tap_seq != wt && W > 0) { float wx = C.world_tap_x / W, wy = C.world_tap_y / H; dm_ui_world_tap(wx, wy, wx, wy); }
if (was_ptr && C.navigation_mode) tip_until = C.tap_move_seq != tm ? -1 : C.last_time_s + (C.mouse_click_seq != mc ? 0.05 : 2.8);
if (C.mouse_click_seq != mc && W > 0) { float nx = C.mouse_click_x / W, ny = C.mouse_click_y / H; dm_ui_touch(0, nx, ny); dm_ui_touch(2, nx, ny); }
}
push();
arm_pulse_end();
}
// 松手施放的脉冲:游戏真取走了(输入采样数前进、光标不扣着)才收回;iOS 用 120 Hz 定时器,这里每帧 tick 一次
// Release-to-cast pulse: released only once the game has really taken it (input samples advanced, cursor not holding it); iOS uses a 120 Hz timer, here once per frame tick
static void pulse_tick(void) {
uint64_t n = dm_input_samples(); double now = now_s();
if (C.pulse_button) {
if (pulse_epoch != C.pulse_epoch) { pulse_epoch = C.pulse_epoch; pulse_s0 = n; pulse_t0 = now; pulse_seen = 0; pulse_free = 0; }
if (!pulse_seen && n > pulse_s0) pulse_seen = now;
if (pulse_seen && !pulse_free && !dm_cursor_pending()) pulse_free = now;
double hold = C.pulse_hold_s;
int taken = pulse_seen && now - pulse_seen >= 0.12 && n - pulse_s0 >= 3 && !dm_cursor_pending() && (hold <= 0 || (pulse_free && now - pulse_free >= hold));
if (taken || now - pulse_t0 > 2.0 + hold) {
if (!taken) LOG("[touch] 【红】脉冲 2 秒内游戏没取走(取了 %llu 次,扣着 %d 下),强制收回", (unsigned long long)(n - pulse_s0), dm_cursor_pending());
if (dm_tc_pulse_end(&C, pulse_epoch)) push();
pulse_s0 = n; pulse_t0 = now;
}
} else if (dm_tc_pulse_pending(&C)) {
if (n - pulse_s0 >= 2 || now - pulse_t0 > 0.5) { if (dm_tc_pulse_resume(&C)) push(); }
} else pulse_ticking = 0;
}
static void tick(double now) {
apply_pending();
int hide = g_fe || g_pad || dm_padmode_busy();
{ static int lh = -1; if (hide != lh) { lh = hide; g_dirty = 1; } }
{ int t = dm_drop_haptic_take(); if (t >= 1 && t <= 3) { g_haptic = t; LOG("掉落震动:前端震第 %d 档", t); } }
if (labels_at && now >= labels_at) { labels_at = 0; if (!g_nav && !labels_done) { labels_done = 1; dm_ui_key_pulse_alone(DM_BTN_L, 9); } }
dm_tc_set_tap_box(dm_ui_tap_box()); dm_tc_set_cur_stack(dm_ui_cur_stack_id()); dm_tc_set_hover_unid(dm_ui_hover_unid());
{ dm_hud_info hi; dm_hud_get(&hi); dm_tc_set_holding(&C, hi.valid && hi.holding && !dm_ui_targeting()); }
if (item_asked && C.navigation_mode && C.pointer_slot >= 0) { int ir = dm_ui_item_result(item_seq); if (ir >= 0) { item_asked = 0; item_kind = ir; dm_tc_pointer_item(&C, ir); } }
if (pend_end >= 0) {
int ready = !(item_asked && dm_ui_item_result(item_seq) < 0) && !(final_asked && dm_ui_item_result(rel_seq) < 0);
if (ready || now - pend_wall > 0.25) { int pt = pend_end;
pend_fire = 1; finish_touches(&pt, 1, 0); pend_fire = 0; pend_end = -1; final_asked = 0; }
}
bind_tap_sync();
float sc = dm_tc_scale_for_size(W, H);
if (C.navigation_mode && !dm_ui_bind_active() && !item_asked && C.pointer_slot >= 0 && C.pointer_slot < DM_TC_MAX_TOUCH) {
dm_tc_finger *f = &C.finger[C.pointer_slot]; float nx = 0, ny = 0; uint32_t hid = dm_ui_hit_id();
if (f->active && !f->pointer_dragged && !f->ui_drag && now - f->start_time_s >= 0.5 && hypotf(f->x - f->aim_origin_x, f->y - f->aim_origin_y) <= 10 * sc && dm_ui_bind_skill_hit(&nx, &ny) == 2 && hid >= 1 && hid <= 4) {
if (!f->pointer_long) { f->pointer_long = 1; stat_next = now; sel_id = hid; C.pointer_valid = 1; C.pointer_x = nx * W; C.pointer_y = ny * H; LOG("前端:按住「+」(属性 %u)→ 连续加点", hid - 1); }
if (now >= stat_next) { stat_next = now + 0.15; dm_stat_add((int)hid - 1, 1); } }
}
if (C.navigation_mode && !dm_ui_bind_active() && !item_asked && C.pointer_slot >= 0 && C.pointer_slot < DM_TC_MAX_TOUCH) {
dm_tc_finger *f = &C.finger[C.pointer_slot]; float nx = 0, ny = 0;
if (pend_end < 0 && f->active && !f->pointer_dragged && !f->pointer_long && now - f->start_time_s >= 0.5 && hypotf(f->x - f->aim_origin_x, f->y - f->aim_origin_y) <= 10 * sc && dm_ui_bind_skill_hit(&nx, &ny) == 1) {
dm_tc_pointer_press(&C, nx * W, ny * H, DM_BTN_Y); LOG("前端:技能树里长按技能 (%.0f,%.0f) → 开绑定框", nx * W, ny * H); }
}
if (map_world_asked) { int wr = dm_world_tap_result(map_world_seq);
if (wr >= 0) { map_world_asked = 0; if (wr == 0 && !g_nav) { dm_ui_map_full(1); LOG("前端:点小地图那一块 (%.0f,%.0f) → 全屏地图", map_wx, map_wy); }
else LOG("前端:点小地图那一块 (%.0f,%.0f) → 底下有世界目标(类 %d),交互、不切地图", map_wx, map_wy, wr); } }
if (add_at > 0 && now >= add_at) { dm_points_info pi; dm_points_get(&pi);
if (pi.tree_open && pi.sel_skill >= 0 && !dm_cursor_pending()) { add_at = 0; if (pi.sel_block == 0 || pi.sel_block == 5) dm_skill_add_selected(); else LOG("前端:再点同一个技能 → 不能加(原因 %d),不发", pi.sel_block); }
else if (now > add_at + 1.0 || !pi.tree_open) add_at = 0; }
if (!C.navigation_mode || g_pad) tip_until = -2;
else if (C.pointer_slot >= 0) tip_until = -1;
else if (tip_until == -2) { if (dm_ui_free_cursor()) tip_until = now + 0.3; }
else if (tip_until > 0 && now >= tip_until && !C.holding && !dm_ui_bind_active() && !dm_ui_touch_active() && !C.pulse_button && !dm_tc_pulse_pending(&C) && !dm_cursor_pending()) {
C.pointer_valid = 1; C.pointer_x = 0.02f * W; C.pointer_y = 0.5f * H; tip_until = 0; }
uint64_t tb = C.buttons;
dm_tc_tick(&C, now);
{ int fg = 0; for (int i = 0; i < DM_TC_MAX_TOUCH; i++) fg |= C.finger[i].active; dm_ui_hand_idle(!fg && !C.pulse_button && !dm_tc_pulse_pending(&C) && !dm_cursor_pending() && !dm_ui_touch_active()); }
if (C.buttons != tb && !C.pulse_button) push();
else if (C.belt_request && !C.pulse_button) push();
if (C.pulse_button && !pulse_ticking) { push(); arm_pulse_end(); }
if (C.pointer_valid) dm_cursor_set_screen(C.pointer_x, C.pointer_y, W, H);
else if (C.navigation_mode) dm_cursor_clear();
if (pulse_ticking) pulse_tick();
refresh_portal_binding();
{ static uint64_t lb; static int32_t llx, lly; if (C.buttons != lb || C.lx != llx || C.ly != lly) { lb = C.buttons; llx = C.lx; lly = C.ly; g_dirty = 1; } }
}
// ---- 绘制指令表(Java TouchOverlay 照表画;与 DmTouchOverlay.m drawRect 一一对应) | draw list (executed by Java TouchOverlay; mirrors DmTouchOverlay.m drawRect) ----
enum { OP_FILL_ELLIPSE = 1, OP_STROKE_ELLIPSE, OP_LINE, OP_ARC, OP_IMAGE, OP_TEXT, OP_FILL_RECT, OP_V4, OP_V4TEXT, OP_LABEL, OP_COVER };
// 三层:0 = HUD 主体,1 = 摇杆,2 = 小地图任务终点(draw_goals)。手指在摇杆上动时只有摇杆层变,主体层(GPU 缓存成一张纹理)不重画——
// 整层 HUD 每帧在 HWUI 里重画要占 GPU 6–11 ms,和游戏抢同一块 GPU,跑动中转向(手指一直在动)就掉帧
// Three layers: 0 = HUD body, 1 = joystick, 2 = minimap quest goals (draw_goals). While a finger moves on the stick only the joystick layer changes, and the body layer (cached on the GPU as one texture) is not redrawn --
// redrawing the whole HUD in HWUI every frame cost 6-11 ms of GPU, competing with the game for the same GPU, so turning while running (finger always moving) dropped frames
typedef struct { float ops[8192]; int n; char str[96][64]; int nstr; } op_list;
static op_list g_drawn[3], g_probe; static op_list *g_ol = &g_drawn[0];
static void op(int code, int n, const float *v) {
if (g_ol->n + n + 2 > (int)(sizeof g_ol->ops / sizeof *g_ol->ops)) return;
g_ol->ops[g_ol->n++] = (float)code; g_ol->ops[g_ol->n++] = (float)n; memcpy(&g_ol->ops[g_ol->n], v, n * sizeof *v); g_ol->n += n;
}
static float str(const char *s) {
for (int i = 0; i < g_ol->nstr; i++) if (!strcmp(g_ol->str[i], s)) return (float)i;
if (g_ol->nstr >= 96) return -1;
snprintf(g_ol->str[g_ol->nstr], sizeof g_ol->str[0], "%s", s); return (float)g_ol->nstr++;
}
static int same_list(const op_list *a, const op_list *b) {
if (a->n != b->n || a->nstr != b->nstr || memcmp(a->ops, b->ops, a->n * sizeof *a->ops)) return 0;
for (int i = 0; i < a->nstr; i++) if (strcmp(a->str[i], b->str[i])) return 0;
return 1;
}
#define OPV(code, ...) do { const float v_[] = {__VA_ARGS__}; op(code, (int)(sizeof v_ / sizeof *v_), v_); } while (0)
static void fill_ellipse(float x, float y, float w, float h, float r, float g, float b, float a) { OPV(OP_FILL_ELLIPSE, x, y, w, h, r, g, b, a); }
static void stroke_ellipse(float x, float y, float w, float h, float lw, float r, float g, float b, float a) { OPV(OP_STROKE_ELLIPSE, x, y, w, h, lw, r, g, b, a); }
static void caption(const char *s, float x, float y, float w, float h, float size, float alpha) { OPV(OP_TEXT, str(s), x, y, w, h, size, alpha); }
// 图:素材路径(备用路径,-1 无),裁切框(sw ≤ 0 = 整张),目标框,不透明度,混合(0 正常 / 1 灰度) | image: asset path (fallback path, -1 none), crop (sw ≤ 0 = whole), destination, alpha, blend (0 normal / 1 luminosity)
static void image(const char *a, const char *fb, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, float alpha, int blend) {
OPV(OP_IMAGE, str(a), fb ? str(fb) : -1, sx, sy, sw, sh, dx, dy, dw, dh, alpha, (float)blend);
}
static dm_ta_glyph shown_glyph(uint64_t button, uint64_t now, int set) {
dm_ta_glyph g = dm_ta_current_set(&g_native, button, now, set);
if (g.status == DM_TA_UNKNOWN && g_native.captured_ns && now > g_native.captured_ns && now - g_native.captured_ns > DM_TG_MAX_AGE_NS) g = dm_ta_current_set(&g_native, button, g_native.captured_ns, set);
return g;
}
// 技能图标的裁切框;0 = 没有 | skill icon crop rect; 0 = none
static int skill_frame(dm_ta_glyph g, int held, dm_ta_frame *f, char *path, char *sil, size_t n) {
if (g.status != DM_TA_GLYPH) return 0;
if (!dm_ta_frame_at(g.atlas, held ? g.pressed_frame : g.normal_frame, f)) return 0;
snprintf(path, n, "TouchArt/%s.png", dm_ta_atlases[g.atlas].asset); snprintf(sil, n, "hud_v4_ui/sil_%s.png", dm_ta_atlases[g.atlas].asset);
return 1;
}
#define DM_SKILL_IDLE_ALPHA .6f
static void draw_shell(float x, float y, float rr, int held) {
float lw = MAX(1.5f, rr * 0.075f), fr = held ? 1 : DM_SKILL_IDLE_ALPHA, d = rr * 2;
fill_ellipse(x - rr, y - rr, d, d, .086f, .067f, .047f, held ? .92f : .80f * fr);
stroke_ellipse(x - rr + lw / 2, y - rr + lw / 2, d - lw, d - lw, lw, .60f, .47f, .28f, held ? 1 : .9f * fr);
stroke_ellipse(x - rr + lw * 1.3f, y - rr + lw * 1.3f, d - lw * 2.6f, d - lw * 2.6f, lw * .5f, .12f, .09f, .05f, .9f * fr);
}
// 小地图任务终点(同 front_ios.m mapGoalSync;宿主 dm_world.c 找终点、dm_cursor.c 给地图几何):七个墓的真墓口 = 塔拉夏符号,其余 = 原版名牌 + 灰十字;
// 在地图可见范围外 = 只写名字,沿 玩家点 → 终点 的方向贴边(全屏地图让开右下技能区)。世界格 (x, y) 在 玩家点 + ((Δx−Δy)×1.6, (Δx+Δy)×0.8) × 每格像素。
// 画面 = 整个视图(Android 不留边)。面板开着不画;手柄模式照画(同 iOS)。素材 assets/mapgoal/(art_from_ipa.py 从 iOS 包取)
// Minimap quest goals (same as front_ios.m mapGoalSync; the host's dm_world.c finds the goals, dm_cursor.c gives the map geometry): the real tomb of the seven = the Tal Rasha symbol, others = the original nameplate + grey cross;
// outside the visible map range = name only, clamped to the edge along player point → goal (the fullscreen map avoids the bottom-right skill area). World cell (x, y) is at player point + ((Δx−Δy)×1.6, (Δx+Δy)×0.8) × pixels per cell.
// The picture = the whole view (no letterbox on Android). Not drawn while a panel is open; drawn in pad mode too (as on iOS). Art in assets/mapgoal/ (taken from the iOS bundle by art_from_ipa.py)
static void draw_goals(void) {
static int old = -1; if (old < 0) old = dm_custom_get("item_notes") != 0; // 旧译名开关重启生效 | the old-names switch takes effect on restart
dm_map_goal_view v; float cell = 0; int mode = dm_ui_map_geom(&cell), n = dm_map_goals(&v), rw = 0, rh = 0; dm_screen_real(&rw, &rh);
float mm[4]; int mini = dm_ui_minimap_rect(mm);
int show = mode && n > 0 && !g_nav && !g_fe && rw > 0 && cell > 0 && (mode == 2 || mini);
static int lm = -1, ln = -1, lc; int m2 = show ? mode : 0;
if ((m2 != lm || n != ln) && lc < 40) { lm = m2; ln = n; lc++; LOG("小地图终点:%s %d 个(地图 %d,每格 %.2f 像素 = %.2f dp)", show ? "画" : "不画", n, mode, cell, cell * W / (rw > 0 ? rw : 1)); }
if (!show) return;
if (n > 12) n = 12;
float c = cell * W / rw, lh = H * .0236f, sh = H * .085f * (mode == 1 ? .6f : 1), cw = lh * 1.4f, ch = cw * 18 / 34;
float ox, oy, ax0, ay0, ax1, ay1; // 玩家点,可见范围 | player point, visible area
if (mode == 2) { ox = v.sx * W; oy = v.sy * H; ax0 = W * .04f; ay0 = H * .06f; ax1 = ax0 + W * .92f; ay1 = ay0 + H * .72f; }
else { ax0 = mm[0] * W; ay0 = mm[1] * H; ax1 = mm[2] * W; ay1 = mm[3] * H; ox = (ax0 + ax1) / 2; oy = (ay0 + ay1) / 2;
float iw = (ax1 - ax0) * .06f, ih = (ay1 - ay0) * .08f; ax0 += iw; ax1 -= iw; ay0 += ih; ay1 -= ih; }
for (int i = 0; i < n; i++) {
int dx = v.x[i] - v.px, dy = v.y[i] - v.py; float px = ox + (dx - dy) * 1.6f * c, py = oy + (dx + dy) * .8f * c;
int skill = mode == 2 && px > W * .72f && py > H * .45f; // 全屏地图右下是技能区 | the bottom right of the fullscreen map is the skill area
int inside = px >= ax0 && px < ax1 && py >= ay0 && py < ay1 && !skill, art = v.art[i], sym = art >= 64;
char lab[48] = "", fb[48] = "", mark[48] = "";
if (inside && sym) snprintf(mark, sizeof mark, "mapgoal/sym_%d.png", art - 64);
else { int id = sym ? 0 : art; snprintf(fb, sizeof fb, "mapgoal/label_%d.png", id);
if (!dm_lang_zh()) snprintf(lab, sizeof lab, "mapgoal/label_%d_en.png", id); // 简中 / 繁体用中文名牌,其余 enUS;旧译名只跟简中 | zh uses the Chinese label, others enUS; old names only for zhCN
else if (old && dm_lang_index() == 8) snprintf(lab, sizeof lab, "mapgoal/label_%d_old.png", id);
else snprintf(lab, sizeof lab, "%s", fb);
if (inside) snprintf(mark, sizeof mark, "mapgoal/cross.png"); }
if (!inside) { // 画面外:收到可见范围边上,只写名字 | off-screen: clamp to the edge of the visible range, name only
float tx = px > ox ? (ax1 - ox) / (px - ox) : px < ox ? (ax0 - ox) / (px - ox) : 1e9f, ty = py > oy ? (ay1 - oy) / (py - oy) : py < oy ? (ay0 - oy) / (py - oy) : 1e9f, t = MIN(tx, ty);
px = ox + (px - ox) * t; py = oy + (py - oy) * t;
if (mode == 2 && px > W * .72f && py > H * .45f) py = H * .45f; }
if (lab[0]) OPV(OP_LABEL, str(lab), px, mark[0] ? py - ch / 2 - 2 - lh / 2 : py, lh, strcmp(lab, fb) ? str(fb) : -1);
if (mark[0]) { if (sym) OPV(OP_LABEL, str(mark), px, py, sh); else image(mark, NULL, 0, 0, 0, 0, px - cw / 2, py - ch / 2, cw, ch, 1, 0); }
}
}
static void draw_overlay(int part) {
g_ol->n = 0; g_ol->nstr = 0;
int cover = atomic_load(&g_cover);
if (cover == 1) { if (!part) OPV(OP_COVER, W, H); return; }
if (part == 2) { draw_goals(); return; }
if (g_fe || g_pad || dm_padmode_busy()) return;
const dm_tc_state *s = &C; const dm_tc_layout *l = &s->layout;
float k = l->joy_radius / 60; if (k <= 0) return;
if (part) {
if ((g_hud.valid && g_hud.dead) || s->navigation_mode) return;
int moving = s->joy_slot >= 0;
float ox = moving ? s->joy_origin_x : l->joy_x, oy = moving ? s->joy_origin_y : l->joy_y, radius = l->joy_radius;
stroke_ellipse(ox - radius, oy - radius, radius * 2, radius * 2, k, .66f, .53f, .32f, moving ? .32f : .12f);
float dx = s->lx / 32767.0f * radius, dy = -s->ly / 32767.0f * radius;
image("TouchArt/dm_touch_joy.png", NULL, 0, 0, 0, 0, ox + dx - 23 * k, oy + dy - 23 * k, 46 * k, 46 * k, moving ? .8f : .18f, 0);
if (moving && (s->lx || s->ly)) { float ang = atan2f(dy, dx); OPV(OP_ARC, ox, oy, radius + 3 * k, ang - (float)M_PI / 6, ang + (float)M_PI / 6, 2 * k, .66f, .53f, .32f, .7f); }
return;
}
int nav = g_nav != 0; uint64_t host_now = now_ns();
const char *labels[DM_TC_COUNT] = {"主技能", "技能一", "技能二", "技能三", "技能四", "回城", "药剂", "药剂", "药剂", "药剂", "功能", "地图"};
if (nav) { labels[0] = "确认/交换"; labels[1] = "返回"; labels[2] = "操作"; labels[3] = "绑定"; labels[4] = "下一页"; }
for (int i = 0; i < DM_TC_COUNT; i++) {
if (!(s->enabled_targets & (1u << i))) continue;
if (!nav && i > DM_TC_PORTAL && i <= DM_TC_MENU) continue;
const dm_tc_target *t = &l->target[i]; float bx = t->x - t->r, by = t->y - t->r, bw = t->r * 2;
int held = t->button != 0 && (s->buttons & t->button) == t->button;
if (i == DM_TC_PORTAL) for (int f = 0; f < DM_TC_MAX_TOUCH; f++) held |= s->finger[f].active && s->finger[f].target == DM_TC_PORTAL;
float opacity = held ? .6f : .28f;
if (!nav && i == DM_TC_MAP && s->map_cancel_active) { OPV(OP_FILL_RECT, bx, by, bw, bw, .55f, .05f, .04f, .36f); labels[i] = "取消"; }
int skill_key = !nav && (i <= DM_TC_SKILL4 || i == DM_TC_PORTAL);
if (skill_key) draw_shell(t->x, t->y, t->r, held);
else image("TouchArt/dm_native_circle.png", NULL, 0, 0, 0, 0, bx, by, bw, bw, opacity, 0);
int have_icon = 0, show_caption = 1, ss_kind = 0, ss_charges = 0; dm_ta_frame fr; char ip[96], sp[96]; float iw = 0, ih = 0;
if (!nav && i <= DM_TC_SKILL4) {
dm_ta_glyph g = shown_glyph(t->button, host_now, s->skill_set);
if (g.status != DM_TA_EMPTY && g.status != DM_TA_UNKNOWN) ss_kind = dm_swapskill_slot(g.slot, &ss_charges);
have_icon = skill_frame(g, held, &fr, ip, sp, sizeof ip);
show_caption = g.status != DM_TA_EMPTY && !have_icon;
} else if (!nav && i == DM_TC_PORTAL) have_icon = skill_frame(dm_ta_skill(359), held, &fr, ip, sp, sizeof ip);
else if (!nav && (i == DM_TC_MENU || i == DM_TC_MAP)) {
have_icon = 1; fr = (dm_ta_frame){held ? 36 : 0, 0, 36, 36};
snprintf(ip, sizeof ip, "TouchArt/%s", i == DM_TC_MAP ? "dm_native_map.png" : "dm_native_menu.png"); sp[0] = 0;
}
if (!nav && i == DM_TC_MAP && s->map_cancel_active) { have_icon = 0; show_caption = 1; }
if (have_icon) { iw = (float)fr.width; ih = (float)fr.height; }
if (skill_key && !have_icon && (!show_caption || i == DM_TC_MAIN)) { // 空格:十字 | empty slot: a cross
float a_ = t->r * .30f, w_ = MAX(1.5f, t->r * .085f), al = held ? 1 : .9f;
OPV(OP_LINE, t->x - a_, t->y, t->x + a_, t->y, w_, .60f, .47f, .28f, al);
OPV(OP_LINE, t->x, t->y - a_, t->x, t->y + a_, w_, .60f, .47f, .28f, al);
continue;
}
if (skill_key) {
int bare = have_icon, spent = (ss_kind & 2) && ss_charges <= 0;
if (have_icon) { float size = bw * (bare ? .64f : .56f), fit = size / MAX(iw, ih);
float rx_ = t->x - iw * fit / 2, ry_ = t->y - (bare ? 0 : t->r * .12f) - ih * fit / 2;
if (spent) { fill_ellipse(bx + t->r * .14f, by + t->r * .14f, bw - t->r * .28f, bw - t->r * .28f, .30f, .30f, .30f, 1);
image(sp, ip, fr.x, fr.y, fr.width, fr.height, rx_, ry_, iw * fit, ih * fit, .55f, 1);
fill_ellipse(bx, by, bw, bw, 0, 0, 0, .35f); }
else image(sp[0] ? sp : ip, sp[0] ? ip : NULL, fr.x, fr.y, fr.width, fr.height, rx_, ry_, iw * fit, ih * fit, held ? 1 : .92f, 0); }
if (ss_kind & 1) { float br = t->r * .30f, bx2 = t->x + t->r * .74f, by2 = t->y - t->r * .74f, in = MAX(1, br * .08f);
fill_ellipse(bx2 - br, by2 - br, br * 2, br * 2, .11f, .094f, .078f, .95f);
stroke_ellipse(bx2 - br + in, by2 - br + in, br * 2 - in * 2, br * 2 - in * 2, MAX(1, br * .14f), .63f, .50f, .27f, 1);
float ts = br * 1.15f; caption("Ⅱ", bx2 - br, by2 - ts * .62f, br * 2, ts * 1.4f, ts, 1); }
if (ss_kind & 2) { char cs[16]; snprintf(cs, sizeof cs, "%d", ss_charges < 0 ? 0 : ss_charges); float u = H / 1320.0f;
if (u > 0) OPV(OP_V4TEXT, str(cs), (t->x + t->r * .66f - W / 2) / u + 1434, (t->y + t->r * .42f) / u, 1); }
if (bare) continue;
char ln[48]; if (i == DM_TC_MAIN) snprintf(ln, sizeof ln, "hud_v4_ui/lbl_main.png"); else snprintf(ln, sizeof ln, "hud_v4_ui/lbl_f%d.png", i - DM_TC_SKILL1 + 1 + (s->skill_set ? 4 : 0));
OPV(OP_LABEL, str(ln), t->x, t->y + t->r * .50f, t->r * (i == DM_TC_MAIN ? .30f : .36f));
continue;
}
if (have_icon) { float size = bw * (i == DM_TC_MAIN ? .55f : .62f), fit = size / MAX(iw, ih);
image(ip, NULL, fr.x, fr.y, fr.width, fr.height, t->x - iw * fit / 2, t->y - ih * fit / 2, iw * fit, ih * fit, held ? 1 : .82f, 0); show_caption = 0; }
float ts = (i == DM_TC_MAIN ? 13 : 10) * k;
if (show_caption) caption(labels[i], bx, t->y - ts * .6f, bw, ts * 1.6f, ts, held ? 1 : .84f);
if (i >= DM_TC_BELT1 && i <= DM_TC_BELT4) { char d[4]; snprintf(d, sizeof d, "%d", i - DM_TC_BELT1 + 1); caption(d, t->x - 10 * k, t->y + 8 * k, 20 * k, 12 * k, 8 * k, .65f); }
}
if (!nav && l->swap.r > 0) {
int sheld = 0; for (int f = 0; f < DM_TC_MAX_TOUCH; f++) sheld |= s->finger[f].active && hypotf(s->finger[f].x - l->swap.x, s->finger[f].y - l->swap.y) <= l->swap.r;
draw_shell(l->swap.x, l->swap.y, l->swap.r, sheld);
float ts = 14 * k; caption(s->skill_set ? "Ⅱ" : "Ⅰ", l->swap.x - l->swap.r, l->swap.y - ts * .8f, l->swap.r * 2, ts * 1.6f, ts, 1);
}
if (g_hud.valid && g_hud.dead) return;
if (s->navigation_mode) return;
// 底部 UI v4:可见性在这里判,几何与字形 Java 按 hud_v4_ui/ui.json 画 | bottom UI v4: visibility decided here, geometry and glyphs drawn by Java from hud_v4_ui/ui.json
const dm_hud_info *h = &g_hud;
if (dm_hud_bar_visible(h, nav && !g_dialog_only, g_hud_blocked_v)) {
char life[64], mana[64], lv[48];
snprintf(life, sizeof life, dm_ui("dmHudLife"), h->hp, h->hp_max); snprintf(mana, sizeof mana, dm_ui("dmHudMana"), h->mp, h->mp_max);
snprintf(lv, sizeof lv, "Lv %d · %d%%", h->level, h->exp_permille / 10);
OPV(OP_V4, str(life), str(mana), str(lv), (s->buttons & DM_BTN_PLUS) ? 1 : 0, h->points > 0 ? 1 : 0, h->quest_unread ? 1 : 0, (float)h->exp_permille,
(float)h->belt[0], (float)h->belt[1], (float)h->belt[2], (float)h->belt[3], (float)h->players, s->diff_open ? 1 : 0);
}
}
// ---- JNI(GameActivity 界面线程) | JNI (GameActivity UI thread) ----
#define JNI(name) JNICALL Java_org_d2rmobile_app_GameActivity_##name
JNIEXPORT void JNI(nativeLayout)(JNIEnv *env, jclass cls, jfloat w, jfloat h, jfloat safe_l, jfloat safe_r) {
(void)env; (void)cls;
static int inited; static float sl = -1, sr = -1;
if (!inited) {
inited = 1; for (int i = 0; i < 16; i++) g_slot[i] = -1;
dm_tc_set_tall_scale(1); dm_tc_init(&C, w, h); C.mouse_click_mode = 1; W = w; H = h;
g_nav = -1; navigation_mode(atomic_load(&g_touch_navigation));
}
int safe_changed = safe_l != sl || safe_r != sr;
if (safe_changed) { sl = safe_l; sr = safe_r; dm_tc_set_safe_insets(safe_l, safe_r); }
dm_tc_set_edge_bottom(0);
if (h > 0) { dm_ui_safe_left((int)lroundf(safe_l / h * 2160)); dm_ui_safe_right((int)lroundf(safe_r / h * 2160)); }
if (safe_changed || C.layout.width != w || C.layout.height != h) { W = w; H = h; cancel_controls(); dm_tc_resize(&C, w, h); }
LOG("触屏:视图 %.0fx%.0f dp,安全边距 左 %.0f 右 %.0f", w, h, safe_l, safe_r);
g_dirty = 1;
}
// action:0 按下(pid 为新手指)/ 1 移动 / 2 抬起(pid)/ 3 取消(全部);pids / xs / ys 为这一刻全部手指(dp)
// action: 0 down (pid is the new finger) / 1 move / 2 up (pid) / 3 cancel (all); pids / xs / ys are all fingers at this moment (dp)
JNIEXPORT void JNI(nativeTouchEvent)(JNIEnv *env, jclass cls, jint action, jint pid, jintArray pids, jfloatArray xs, jfloatArray ys, jint n) {
(void)cls;
if (W <= 0) return;
jint id[NREC]; jfloat x[NREC], y[NREC]; if (n > NREC) n = NREC;
if (n > 0) { (*env)->GetIntArrayRegion(env, pids, 0, n, id); (*env)->GetFloatArrayRegion(env, xs, 0, n, x); (*env)->GetFloatArrayRegion(env, ys, 0, n, y); }
apply_pending();
int ts[NREC], m = 0;
for (int i = 0; i < n; i++) { int t = pid_rec(id[i]); if (t >= 0) { R[t].x = x[i]; R[t].y = y[i]; } }
if (action == 0) {
if (pid_rec(pid) >= 0) return;
int t = -1; for (int i = 0; i < NREC; i++) if (!R[i].used) { t = i; break; }
if (t < 0) { gc_recs(); return; }
R[t].used = 1; R[t].done = 0; R[t].pid = pid; R[t].x = R[t].y = 0;
for (int i = 0; i < n; i++) if (id[i] == pid) { R[t].x = x[i]; R[t].y = y[i]; }
ts[m++] = t; touches_began(ts, m);
} else if (action == 1) {
for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done) ts[m++] = i;
if (m) touches_moved(ts, m);
} else if (action == 2) {
int t = pid_rec(pid); if (t < 0) return;
R[t].done = 1; ts[m++] = t; finish_touches(ts, m, 0);
} else {
for (int i = 0; i < NREC; i++) if (R[i].used && !R[i].done) { R[i].done = 1; ts[m++] = i; }
if (m) finish_touches(ts, m, 1);
}
gc_recs();
}
// 每帧(Choreographer):返回位 0 / 1 / 2 = 主体层 / 摇杆层 / 终点层要重画,位 4–5 = 掉落震动档(1 重 / 2 中 / 3 轻),位 8–9 = 重开遮罩(1 黑屏 / 2 透明)
// Per frame (Choreographer): bits 0 / 1 / 2 = body / joystick / goals layer needs a redraw, bits 4–5 = drop haptic level (1 heavy / 2 medium / 3 light), bits 8–9 = restart cover (1 black / 2 transparent)
JNIEXPORT jint JNI(nativeTick)(JNIEnv *env, jclass cls) {
(void)env; (void)cls;
if (W <= 0) return 0;
tick(now_s());
static int lc; int cover = atomic_load(&g_cover); if (cover != lc) { lc = cover; g_dirty = 1; if (cover) cancel_controls(); }
// 位 0 / 1 = 主体层 / 摇杆层要重画:重算一遍指令表,和上次画出来的不同才算 | bits 0 / 1 = body / joystick layer needs a redraw: rebuild the draw list, and only count it if it differs from what was last drawn
int r = (g_haptic & 3) << 4 | (cover & 3) << 8;
if (g_dirty) for (int part = 0; part < 2; part++) { g_ol = &g_probe; draw_overlay(part); if (!same_list(&g_probe, &g_drawn[part])) r |= 1 << part; }
{ g_ol = &g_probe; draw_overlay(2); if (!same_list(&g_probe, &g_drawn[2])) r |= 4; } // 终点层跟着玩家走,每帧都比 | the goals layer follows the player, compared every frame
g_dirty = 0; g_haptic = 0;
return r;
}
// 返回 [float[] 指令, String[] 字符串表] | returns [float[] ops, String[] strings]
JNIEXPORT jobjectArray JNI(nativeDraw)(JNIEnv *env, jclass cls, jint part) {
(void)cls;
if (part < 0 || part > 2) part = 0;
g_ol = &g_drawn[part]; draw_overlay(part);
jfloatArray f = (*env)->NewFloatArray(env, g_ol->n); if (g_ol->n) (*env)->SetFloatArrayRegion(env, f, 0, g_ol->n, g_ol->ops);
jclass sc = (*env)->FindClass(env, "java/lang/String");
jobjectArray sa = (*env)->NewObjectArray(env, g_ol->nstr, sc, NULL);
for (int i = 0; i < g_ol->nstr; i++) { jstring js = (*env)->NewStringUTF(env, g_ol->str[i]); (*env)->SetObjectArrayElement(env, sa, i, js); (*env)->DeleteLocalRef(env, js); }
jobjectArray out = (*env)->NewObjectArray(env, 2, (*env)->FindClass(env, "java/lang/Object"), NULL);
(*env)->SetObjectArrayElement(env, out, 0, f); (*env)->SetObjectArrayElement(env, out, 1, sa);
return out;
}
+25
View File
@@ -0,0 +1,25 @@
// Android 无头前端(adb shell 直接跑 dmhost,先跑通引导链):无窗口、无输入框,客体在当前线程跑;GameActivity 前端接上后由它替换
// Android headless front end (run dmhost straight from adb shell to get the boot chain working first): no window, no input box, the guest runs on the current thread; replaced by the GameActivity front end once that is wired up
#include "../dm.h"
#include "../front.h"
// 客体在 64 MB 栈的线程里跑(与 iOS 壳的 boot_thread 一致;adb shell 主线程栈只有 8 MB)
// The guest runs on a thread with a 64 MB stack (same as the iOS shell's boot_thread; the adb shell main thread has only 8 MB)
static void *guest_thread(void *p) { ((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);
}
void *front_metal_layer(void) { return NULL; }
// 与 front_mac.m 同一规则:DM_GAME_RES=宽x高 指定主机模式分辨率,掌机模式取 4/5
// Same rule as front_mac.m: DM_GAME_RES=WxH sets the docked resolution, handheld takes 4/5 of it
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;
return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280;
}
int front_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
(void)title; (void)sub; (void)guide; (void)initial; (void)max_chars; (void)out; (void)out_cap;
return -1;
}
File diff suppressed because it is too large Load Diff
+306
View File
@@ -0,0 +1,306 @@
static PFN_vkGetPipelineCacheData dm_vkGetPipelineCacheData;
#define vkGetPipelineCacheData dm_vkGetPipelineCacheData
static PFN_vkGetFenceStatus dm_vkGetFenceStatus;
#define vkGetFenceStatus dm_vkGetFenceStatus
static PFN_vkResetFences dm_vkResetFences;
#define vkResetFences dm_vkResetFences
static PFN_vkResetCommandBuffer dm_vkResetCommandBuffer;
#define vkResetCommandBuffer dm_vkResetCommandBuffer
static PFN_vkResetDescriptorPool dm_vkResetDescriptorPool;
#define vkResetDescriptorPool dm_vkResetDescriptorPool
/* Vulkan dispatch belongs to the explicitly selected loader instance. */
static PFN_vkGetInstanceProcAddr dm_vk_get;
static PFN_vkAcquireNextImageKHR dm_vkAcquireNextImageKHR;
#define vkAcquireNextImageKHR dm_vkAcquireNextImageKHR
static PFN_vkAllocateCommandBuffers dm_vkAllocateCommandBuffers;
#define vkAllocateCommandBuffers dm_vkAllocateCommandBuffers
static PFN_vkAllocateDescriptorSets dm_vkAllocateDescriptorSets;
#define vkAllocateDescriptorSets dm_vkAllocateDescriptorSets
static PFN_vkAllocateMemory dm_vkAllocateMemory;
#define vkAllocateMemory dm_vkAllocateMemory
static PFN_vkBeginCommandBuffer dm_vkBeginCommandBuffer;
#define vkBeginCommandBuffer dm_vkBeginCommandBuffer
static PFN_vkBindBufferMemory dm_vkBindBufferMemory;
#define vkBindBufferMemory dm_vkBindBufferMemory
static PFN_vkBindImageMemory dm_vkBindImageMemory;
#define vkBindImageMemory dm_vkBindImageMemory
static PFN_vkCmdBeginQuery dm_vkCmdBeginQuery;
#define vkCmdBeginQuery dm_vkCmdBeginQuery
static PFN_vkCmdBeginRenderPass dm_vkCmdBeginRenderPass;
#define vkCmdBeginRenderPass dm_vkCmdBeginRenderPass
static PFN_vkCmdBindDescriptorSets dm_vkCmdBindDescriptorSets;
#define vkCmdBindDescriptorSets dm_vkCmdBindDescriptorSets
static PFN_vkCmdBindIndexBuffer dm_vkCmdBindIndexBuffer;
#define vkCmdBindIndexBuffer dm_vkCmdBindIndexBuffer
static PFN_vkCmdBindPipeline dm_vkCmdBindPipeline;
#define vkCmdBindPipeline dm_vkCmdBindPipeline
static PFN_vkCmdBindVertexBuffers dm_vkCmdBindVertexBuffers;
#define vkCmdBindVertexBuffers dm_vkCmdBindVertexBuffers
static PFN_vkCmdBlitImage dm_vkCmdBlitImage;
#define vkCmdBlitImage dm_vkCmdBlitImage
static PFN_vkCmdClearAttachments dm_vkCmdClearAttachments;
#define vkCmdClearAttachments dm_vkCmdClearAttachments
static PFN_vkCmdClearColorImage dm_vkCmdClearColorImage;
#define vkCmdClearColorImage dm_vkCmdClearColorImage
static PFN_vkCmdClearDepthStencilImage dm_vkCmdClearDepthStencilImage;
#define vkCmdClearDepthStencilImage dm_vkCmdClearDepthStencilImage
static PFN_vkCmdCopyBuffer dm_vkCmdCopyBuffer;
#define vkCmdCopyBuffer dm_vkCmdCopyBuffer
static PFN_vkCmdCopyBufferToImage dm_vkCmdCopyBufferToImage;
#define vkCmdCopyBufferToImage dm_vkCmdCopyBufferToImage
static PFN_vkCmdCopyImageToBuffer dm_vkCmdCopyImageToBuffer;
#define vkCmdCopyImageToBuffer dm_vkCmdCopyImageToBuffer
static PFN_vkCmdDispatch dm_vkCmdDispatch;
#define vkCmdDispatch dm_vkCmdDispatch
static PFN_vkCmdDraw dm_vkCmdDraw;
#define vkCmdDraw dm_vkCmdDraw
static PFN_vkCmdDrawIndexed dm_vkCmdDrawIndexed;
#define vkCmdDrawIndexed dm_vkCmdDrawIndexed
static PFN_vkCmdEndQuery dm_vkCmdEndQuery;
#define vkCmdEndQuery dm_vkCmdEndQuery
static PFN_vkCmdEndRenderPass dm_vkCmdEndRenderPass;
#define vkCmdEndRenderPass dm_vkCmdEndRenderPass
static PFN_vkCmdPipelineBarrier dm_vkCmdPipelineBarrier;
#define vkCmdPipelineBarrier dm_vkCmdPipelineBarrier
static PFN_vkCmdResetQueryPool dm_vkCmdResetQueryPool;
#define vkCmdResetQueryPool dm_vkCmdResetQueryPool
static PFN_vkCmdSetBlendConstants dm_vkCmdSetBlendConstants;
#define vkCmdSetBlendConstants dm_vkCmdSetBlendConstants
static PFN_vkCmdSetScissor dm_vkCmdSetScissor;
#define vkCmdSetScissor dm_vkCmdSetScissor
static PFN_vkCmdSetViewport dm_vkCmdSetViewport;
#define vkCmdSetViewport dm_vkCmdSetViewport
static PFN_vkCmdUpdateBuffer dm_vkCmdUpdateBuffer;
#define vkCmdUpdateBuffer dm_vkCmdUpdateBuffer
static PFN_vkCmdWriteTimestamp dm_vkCmdWriteTimestamp;
#define vkCmdWriteTimestamp dm_vkCmdWriteTimestamp
static PFN_vkCreateAndroidSurfaceKHR dm_vkCreateAndroidSurfaceKHR;
#define vkCreateAndroidSurfaceKHR dm_vkCreateAndroidSurfaceKHR
static PFN_vkCreateBuffer dm_vkCreateBuffer;
#define vkCreateBuffer dm_vkCreateBuffer
static PFN_vkCreateCommandPool dm_vkCreateCommandPool;
#define vkCreateCommandPool dm_vkCreateCommandPool
static PFN_vkCreateComputePipelines dm_vkCreateComputePipelines;
#define vkCreateComputePipelines dm_vkCreateComputePipelines
static PFN_vkCreateDescriptorPool dm_vkCreateDescriptorPool;
#define vkCreateDescriptorPool dm_vkCreateDescriptorPool
static PFN_vkCreateDescriptorSetLayout dm_vkCreateDescriptorSetLayout;
#define vkCreateDescriptorSetLayout dm_vkCreateDescriptorSetLayout
static PFN_vkCreateDevice dm_vkCreateDevice;
#define vkCreateDevice dm_vkCreateDevice
static PFN_vkCreateFence dm_vkCreateFence;
#define vkCreateFence dm_vkCreateFence
static PFN_vkCreateFramebuffer dm_vkCreateFramebuffer;
#define vkCreateFramebuffer dm_vkCreateFramebuffer
static PFN_vkCreateGraphicsPipelines dm_vkCreateGraphicsPipelines;
#define vkCreateGraphicsPipelines dm_vkCreateGraphicsPipelines
static PFN_vkCreateImage dm_vkCreateImage;
#define vkCreateImage dm_vkCreateImage
static PFN_vkCreateImageView dm_vkCreateImageView;
#define vkCreateImageView dm_vkCreateImageView
static PFN_vkCreateInstance dm_vkCreateInstance;
#define vkCreateInstance dm_vkCreateInstance
static PFN_vkCreatePipelineCache dm_vkCreatePipelineCache;
#define vkCreatePipelineCache dm_vkCreatePipelineCache
static PFN_vkCreatePipelineLayout dm_vkCreatePipelineLayout;
#define vkCreatePipelineLayout dm_vkCreatePipelineLayout
static PFN_vkCreateQueryPool dm_vkCreateQueryPool;
#define vkCreateQueryPool dm_vkCreateQueryPool
static PFN_vkCreateRenderPass dm_vkCreateRenderPass;
#define vkCreateRenderPass dm_vkCreateRenderPass
static PFN_vkCreateSampler dm_vkCreateSampler;
#define vkCreateSampler dm_vkCreateSampler
static PFN_vkCreateSemaphore dm_vkCreateSemaphore;
#define vkCreateSemaphore dm_vkCreateSemaphore
static PFN_vkCreateShaderModule dm_vkCreateShaderModule;
#define vkCreateShaderModule dm_vkCreateShaderModule
static PFN_vkCreateSwapchainKHR dm_vkCreateSwapchainKHR;
#define vkCreateSwapchainKHR dm_vkCreateSwapchainKHR
static PFN_vkDestroyBuffer dm_vkDestroyBuffer;
#define vkDestroyBuffer dm_vkDestroyBuffer
static PFN_vkDestroyDescriptorPool dm_vkDestroyDescriptorPool;
#define vkDestroyDescriptorPool dm_vkDestroyDescriptorPool
static PFN_vkDestroyFence dm_vkDestroyFence;
#define vkDestroyFence dm_vkDestroyFence
static PFN_vkDestroyFramebuffer dm_vkDestroyFramebuffer;
#define vkDestroyFramebuffer dm_vkDestroyFramebuffer
static PFN_vkDestroyImage dm_vkDestroyImage;
#define vkDestroyImage dm_vkDestroyImage
static PFN_vkDestroyImageView dm_vkDestroyImageView;
#define vkDestroyImageView dm_vkDestroyImageView
static PFN_vkDestroyPipeline dm_vkDestroyPipeline;
#define vkDestroyPipeline dm_vkDestroyPipeline
static PFN_vkDestroyPipelineLayout dm_vkDestroyPipelineLayout;
#define vkDestroyPipelineLayout dm_vkDestroyPipelineLayout
static PFN_vkDestroyQueryPool dm_vkDestroyQueryPool;
#define vkDestroyQueryPool dm_vkDestroyQueryPool
static PFN_vkDestroyRenderPass dm_vkDestroyRenderPass;
#define vkDestroyRenderPass dm_vkDestroyRenderPass
static PFN_vkDestroySampler dm_vkDestroySampler;
#define vkDestroySampler dm_vkDestroySampler
static PFN_vkDestroySemaphore dm_vkDestroySemaphore;
#define vkDestroySemaphore dm_vkDestroySemaphore
static PFN_vkDestroySurfaceKHR dm_vkDestroySurfaceKHR;
#define vkDestroySurfaceKHR dm_vkDestroySurfaceKHR
static PFN_vkDestroySwapchainKHR dm_vkDestroySwapchainKHR;
#define vkDestroySwapchainKHR dm_vkDestroySwapchainKHR
static PFN_vkDeviceWaitIdle dm_vkDeviceWaitIdle;
#define vkDeviceWaitIdle dm_vkDeviceWaitIdle
static PFN_vkEndCommandBuffer dm_vkEndCommandBuffer;
#define vkEndCommandBuffer dm_vkEndCommandBuffer
static PFN_vkEnumeratePhysicalDevices dm_vkEnumeratePhysicalDevices;
#define vkEnumeratePhysicalDevices dm_vkEnumeratePhysicalDevices
static PFN_vkFreeCommandBuffers dm_vkFreeCommandBuffers;
#define vkFreeCommandBuffers dm_vkFreeCommandBuffers
static PFN_vkFreeMemory dm_vkFreeMemory;
#define vkFreeMemory dm_vkFreeMemory
static PFN_vkGetBufferMemoryRequirements dm_vkGetBufferMemoryRequirements;
#define vkGetBufferMemoryRequirements dm_vkGetBufferMemoryRequirements
static PFN_vkGetDeviceQueue dm_vkGetDeviceQueue;
#define vkGetDeviceQueue dm_vkGetDeviceQueue
static PFN_vkGetImageMemoryRequirements dm_vkGetImageMemoryRequirements;
#define vkGetImageMemoryRequirements dm_vkGetImageMemoryRequirements
static PFN_vkGetPhysicalDeviceFeatures dm_vkGetPhysicalDeviceFeatures;
#define vkGetPhysicalDeviceFeatures dm_vkGetPhysicalDeviceFeatures
static PFN_vkGetPhysicalDeviceFormatProperties dm_vkGetPhysicalDeviceFormatProperties;
#define vkGetPhysicalDeviceFormatProperties dm_vkGetPhysicalDeviceFormatProperties
static PFN_vkGetPhysicalDeviceMemoryProperties dm_vkGetPhysicalDeviceMemoryProperties;
#define vkGetPhysicalDeviceMemoryProperties dm_vkGetPhysicalDeviceMemoryProperties
static PFN_vkGetPhysicalDeviceProperties dm_vkGetPhysicalDeviceProperties;
#define vkGetPhysicalDeviceProperties dm_vkGetPhysicalDeviceProperties
static PFN_vkGetPhysicalDeviceProperties2 dm_vkGetPhysicalDeviceProperties2;
#define vkGetPhysicalDeviceProperties2 dm_vkGetPhysicalDeviceProperties2
static PFN_vkGetPhysicalDeviceQueueFamilyProperties dm_vkGetPhysicalDeviceQueueFamilyProperties;
#define vkGetPhysicalDeviceQueueFamilyProperties dm_vkGetPhysicalDeviceQueueFamilyProperties
static PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR;
#define vkGetPhysicalDeviceSurfaceCapabilitiesKHR dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR
static PFN_vkGetPhysicalDeviceSurfaceFormatsKHR dm_vkGetPhysicalDeviceSurfaceFormatsKHR;
#define vkGetPhysicalDeviceSurfaceFormatsKHR dm_vkGetPhysicalDeviceSurfaceFormatsKHR
static PFN_vkGetPhysicalDeviceSurfaceSupportKHR dm_vkGetPhysicalDeviceSurfaceSupportKHR;
#define vkGetPhysicalDeviceSurfaceSupportKHR dm_vkGetPhysicalDeviceSurfaceSupportKHR
static PFN_vkGetQueryPoolResults dm_vkGetQueryPoolResults;
#define vkGetQueryPoolResults dm_vkGetQueryPoolResults
static PFN_vkGetSwapchainImagesKHR dm_vkGetSwapchainImagesKHR;
#define vkGetSwapchainImagesKHR dm_vkGetSwapchainImagesKHR
static PFN_vkMapMemory dm_vkMapMemory;
#define vkMapMemory dm_vkMapMemory
static PFN_vkQueuePresentKHR dm_vkQueuePresentKHR;
#define vkQueuePresentKHR dm_vkQueuePresentKHR
static PFN_vkQueueSubmit dm_vkQueueSubmit;
#define vkQueueSubmit dm_vkQueueSubmit
static PFN_vkQueueWaitIdle dm_vkQueueWaitIdle;
#define vkQueueWaitIdle dm_vkQueueWaitIdle
static PFN_vkUnmapMemory dm_vkUnmapMemory;
#define vkUnmapMemory dm_vkUnmapMemory
static PFN_vkUpdateDescriptorSets dm_vkUpdateDescriptorSets;
#define vkUpdateDescriptorSets dm_vkUpdateDescriptorSets
static PFN_vkWaitForFences dm_vkWaitForFences;
#define vkWaitForFences dm_vkWaitForFences
static PFN_vkCreateBufferView dm_vkCreateBufferView;
#define vkCreateBufferView dm_vkCreateBufferView
static PFN_vkDestroyBufferView dm_vkDestroyBufferView;
#define vkDestroyBufferView dm_vkDestroyBufferView
static PFN_vkCmdCopyImage dm_vkCmdCopyImage;
#define vkCmdCopyImage dm_vkCmdCopyImage
static void dm_vk_resolve(VkInstance instance) {
dm_vkCmdCopyImage=(PFN_vkCmdCopyImage)dm_vk_get(instance,"vkCmdCopyImage");if(!dm_vkCmdCopyImage)die("Vulkan dispatch vkCmdCopyImage",0);
dm_vkDestroyBufferView=(PFN_vkDestroyBufferView)dm_vk_get(instance,"vkDestroyBufferView");if(!dm_vkDestroyBufferView)die("Vulkan dispatch vkDestroyBufferView",0);
dm_vkCreateBufferView=(PFN_vkCreateBufferView)dm_vk_get(instance,"vkCreateBufferView");if(!dm_vkCreateBufferView)die("Vulkan dispatch vkCreateBufferView",0);
dm_vkAcquireNextImageKHR=(PFN_vkAcquireNextImageKHR)dm_vk_get(instance,"vkAcquireNextImageKHR");if(!dm_vkAcquireNextImageKHR)die("Vulkan dispatch vkAcquireNextImageKHR",0);
dm_vkAllocateCommandBuffers=(PFN_vkAllocateCommandBuffers)dm_vk_get(instance,"vkAllocateCommandBuffers");if(!dm_vkAllocateCommandBuffers)die("Vulkan dispatch vkAllocateCommandBuffers",0);
dm_vkAllocateDescriptorSets=(PFN_vkAllocateDescriptorSets)dm_vk_get(instance,"vkAllocateDescriptorSets");if(!dm_vkAllocateDescriptorSets)die("Vulkan dispatch vkAllocateDescriptorSets",0);
dm_vkAllocateMemory=(PFN_vkAllocateMemory)dm_vk_get(instance,"vkAllocateMemory");if(!dm_vkAllocateMemory)die("Vulkan dispatch vkAllocateMemory",0);
dm_vkBeginCommandBuffer=(PFN_vkBeginCommandBuffer)dm_vk_get(instance,"vkBeginCommandBuffer");if(!dm_vkBeginCommandBuffer)die("Vulkan dispatch vkBeginCommandBuffer",0);
dm_vkBindBufferMemory=(PFN_vkBindBufferMemory)dm_vk_get(instance,"vkBindBufferMemory");if(!dm_vkBindBufferMemory)die("Vulkan dispatch vkBindBufferMemory",0);
dm_vkBindImageMemory=(PFN_vkBindImageMemory)dm_vk_get(instance,"vkBindImageMemory");if(!dm_vkBindImageMemory)die("Vulkan dispatch vkBindImageMemory",0);
dm_vkCmdBeginQuery=(PFN_vkCmdBeginQuery)dm_vk_get(instance,"vkCmdBeginQuery");if(!dm_vkCmdBeginQuery)die("Vulkan dispatch vkCmdBeginQuery",0);
dm_vkCmdBeginRenderPass=(PFN_vkCmdBeginRenderPass)dm_vk_get(instance,"vkCmdBeginRenderPass");if(!dm_vkCmdBeginRenderPass)die("Vulkan dispatch vkCmdBeginRenderPass",0);
dm_vkCmdBindDescriptorSets=(PFN_vkCmdBindDescriptorSets)dm_vk_get(instance,"vkCmdBindDescriptorSets");if(!dm_vkCmdBindDescriptorSets)die("Vulkan dispatch vkCmdBindDescriptorSets",0);
dm_vkCmdBindIndexBuffer=(PFN_vkCmdBindIndexBuffer)dm_vk_get(instance,"vkCmdBindIndexBuffer");if(!dm_vkCmdBindIndexBuffer)die("Vulkan dispatch vkCmdBindIndexBuffer",0);
dm_vkCmdBindPipeline=(PFN_vkCmdBindPipeline)dm_vk_get(instance,"vkCmdBindPipeline");if(!dm_vkCmdBindPipeline)die("Vulkan dispatch vkCmdBindPipeline",0);
dm_vkCmdBindVertexBuffers=(PFN_vkCmdBindVertexBuffers)dm_vk_get(instance,"vkCmdBindVertexBuffers");if(!dm_vkCmdBindVertexBuffers)die("Vulkan dispatch vkCmdBindVertexBuffers",0);
dm_vkCmdBlitImage=(PFN_vkCmdBlitImage)dm_vk_get(instance,"vkCmdBlitImage");if(!dm_vkCmdBlitImage)die("Vulkan dispatch vkCmdBlitImage",0);
dm_vkCmdClearAttachments=(PFN_vkCmdClearAttachments)dm_vk_get(instance,"vkCmdClearAttachments");if(!dm_vkCmdClearAttachments)die("Vulkan dispatch vkCmdClearAttachments",0);
dm_vkCmdClearColorImage=(PFN_vkCmdClearColorImage)dm_vk_get(instance,"vkCmdClearColorImage");if(!dm_vkCmdClearColorImage)die("Vulkan dispatch vkCmdClearColorImage",0);
dm_vkCmdClearDepthStencilImage=(PFN_vkCmdClearDepthStencilImage)dm_vk_get(instance,"vkCmdClearDepthStencilImage");if(!dm_vkCmdClearDepthStencilImage)die("Vulkan dispatch vkCmdClearDepthStencilImage",0);
dm_vkCmdCopyBuffer=(PFN_vkCmdCopyBuffer)dm_vk_get(instance,"vkCmdCopyBuffer");if(!dm_vkCmdCopyBuffer)die("Vulkan dispatch vkCmdCopyBuffer",0);
dm_vkCmdCopyBufferToImage=(PFN_vkCmdCopyBufferToImage)dm_vk_get(instance,"vkCmdCopyBufferToImage");if(!dm_vkCmdCopyBufferToImage)die("Vulkan dispatch vkCmdCopyBufferToImage",0);
dm_vkCmdCopyImageToBuffer=(PFN_vkCmdCopyImageToBuffer)dm_vk_get(instance,"vkCmdCopyImageToBuffer");if(!dm_vkCmdCopyImageToBuffer)die("Vulkan dispatch vkCmdCopyImageToBuffer",0);
dm_vkCmdDispatch=(PFN_vkCmdDispatch)dm_vk_get(instance,"vkCmdDispatch");if(!dm_vkCmdDispatch)die("Vulkan dispatch vkCmdDispatch",0);
dm_vkCmdDraw=(PFN_vkCmdDraw)dm_vk_get(instance,"vkCmdDraw");if(!dm_vkCmdDraw)die("Vulkan dispatch vkCmdDraw",0);
dm_vkCmdDrawIndexed=(PFN_vkCmdDrawIndexed)dm_vk_get(instance,"vkCmdDrawIndexed");if(!dm_vkCmdDrawIndexed)die("Vulkan dispatch vkCmdDrawIndexed",0);
dm_vkCmdEndQuery=(PFN_vkCmdEndQuery)dm_vk_get(instance,"vkCmdEndQuery");if(!dm_vkCmdEndQuery)die("Vulkan dispatch vkCmdEndQuery",0);
dm_vkCmdEndRenderPass=(PFN_vkCmdEndRenderPass)dm_vk_get(instance,"vkCmdEndRenderPass");if(!dm_vkCmdEndRenderPass)die("Vulkan dispatch vkCmdEndRenderPass",0);
dm_vkCmdPipelineBarrier=(PFN_vkCmdPipelineBarrier)dm_vk_get(instance,"vkCmdPipelineBarrier");if(!dm_vkCmdPipelineBarrier)die("Vulkan dispatch vkCmdPipelineBarrier",0);
dm_vkCmdResetQueryPool=(PFN_vkCmdResetQueryPool)dm_vk_get(instance,"vkCmdResetQueryPool");if(!dm_vkCmdResetQueryPool)die("Vulkan dispatch vkCmdResetQueryPool",0);
dm_vkCmdSetBlendConstants=(PFN_vkCmdSetBlendConstants)dm_vk_get(instance,"vkCmdSetBlendConstants");if(!dm_vkCmdSetBlendConstants)die("Vulkan dispatch vkCmdSetBlendConstants",0);
dm_vkCmdSetScissor=(PFN_vkCmdSetScissor)dm_vk_get(instance,"vkCmdSetScissor");if(!dm_vkCmdSetScissor)die("Vulkan dispatch vkCmdSetScissor",0);
dm_vkCmdSetViewport=(PFN_vkCmdSetViewport)dm_vk_get(instance,"vkCmdSetViewport");if(!dm_vkCmdSetViewport)die("Vulkan dispatch vkCmdSetViewport",0);
dm_vkCmdUpdateBuffer=(PFN_vkCmdUpdateBuffer)dm_vk_get(instance,"vkCmdUpdateBuffer");if(!dm_vkCmdUpdateBuffer)die("Vulkan dispatch vkCmdUpdateBuffer",0);
dm_vkCmdWriteTimestamp=(PFN_vkCmdWriteTimestamp)dm_vk_get(instance,"vkCmdWriteTimestamp");if(!dm_vkCmdWriteTimestamp)die("Vulkan dispatch vkCmdWriteTimestamp",0);
dm_vkCreateAndroidSurfaceKHR=(PFN_vkCreateAndroidSurfaceKHR)dm_vk_get(instance,"vkCreateAndroidSurfaceKHR");if(!dm_vkCreateAndroidSurfaceKHR)die("Vulkan dispatch vkCreateAndroidSurfaceKHR",0);
dm_vkCreateBuffer=(PFN_vkCreateBuffer)dm_vk_get(instance,"vkCreateBuffer");if(!dm_vkCreateBuffer)die("Vulkan dispatch vkCreateBuffer",0);
dm_vkCreateCommandPool=(PFN_vkCreateCommandPool)dm_vk_get(instance,"vkCreateCommandPool");if(!dm_vkCreateCommandPool)die("Vulkan dispatch vkCreateCommandPool",0);
dm_vkCreateComputePipelines=(PFN_vkCreateComputePipelines)dm_vk_get(instance,"vkCreateComputePipelines");if(!dm_vkCreateComputePipelines)die("Vulkan dispatch vkCreateComputePipelines",0);
dm_vkCreateDescriptorPool=(PFN_vkCreateDescriptorPool)dm_vk_get(instance,"vkCreateDescriptorPool");if(!dm_vkCreateDescriptorPool)die("Vulkan dispatch vkCreateDescriptorPool",0);
dm_vkCreateDescriptorSetLayout=(PFN_vkCreateDescriptorSetLayout)dm_vk_get(instance,"vkCreateDescriptorSetLayout");if(!dm_vkCreateDescriptorSetLayout)die("Vulkan dispatch vkCreateDescriptorSetLayout",0);
dm_vkCreateDevice=(PFN_vkCreateDevice)dm_vk_get(instance,"vkCreateDevice");if(!dm_vkCreateDevice)die("Vulkan dispatch vkCreateDevice",0);
dm_vkCreateFence=(PFN_vkCreateFence)dm_vk_get(instance,"vkCreateFence");if(!dm_vkCreateFence)die("Vulkan dispatch vkCreateFence",0);
dm_vkCreateFramebuffer=(PFN_vkCreateFramebuffer)dm_vk_get(instance,"vkCreateFramebuffer");if(!dm_vkCreateFramebuffer)die("Vulkan dispatch vkCreateFramebuffer",0);
dm_vkCreateGraphicsPipelines=(PFN_vkCreateGraphicsPipelines)dm_vk_get(instance,"vkCreateGraphicsPipelines");if(!dm_vkCreateGraphicsPipelines)die("Vulkan dispatch vkCreateGraphicsPipelines",0);
dm_vkCreateImage=(PFN_vkCreateImage)dm_vk_get(instance,"vkCreateImage");if(!dm_vkCreateImage)die("Vulkan dispatch vkCreateImage",0);
dm_vkCreateImageView=(PFN_vkCreateImageView)dm_vk_get(instance,"vkCreateImageView");if(!dm_vkCreateImageView)die("Vulkan dispatch vkCreateImageView",0);
dm_vkCreatePipelineCache=(PFN_vkCreatePipelineCache)dm_vk_get(instance,"vkCreatePipelineCache");if(!dm_vkCreatePipelineCache)die("Vulkan dispatch vkCreatePipelineCache",0);
dm_vkCreatePipelineLayout=(PFN_vkCreatePipelineLayout)dm_vk_get(instance,"vkCreatePipelineLayout");if(!dm_vkCreatePipelineLayout)die("Vulkan dispatch vkCreatePipelineLayout",0);
dm_vkCreateQueryPool=(PFN_vkCreateQueryPool)dm_vk_get(instance,"vkCreateQueryPool");if(!dm_vkCreateQueryPool)die("Vulkan dispatch vkCreateQueryPool",0);
dm_vkCreateRenderPass=(PFN_vkCreateRenderPass)dm_vk_get(instance,"vkCreateRenderPass");if(!dm_vkCreateRenderPass)die("Vulkan dispatch vkCreateRenderPass",0);
dm_vkCreateSampler=(PFN_vkCreateSampler)dm_vk_get(instance,"vkCreateSampler");if(!dm_vkCreateSampler)die("Vulkan dispatch vkCreateSampler",0);
dm_vkCreateSemaphore=(PFN_vkCreateSemaphore)dm_vk_get(instance,"vkCreateSemaphore");if(!dm_vkCreateSemaphore)die("Vulkan dispatch vkCreateSemaphore",0);
dm_vkCreateShaderModule=(PFN_vkCreateShaderModule)dm_vk_get(instance,"vkCreateShaderModule");if(!dm_vkCreateShaderModule)die("Vulkan dispatch vkCreateShaderModule",0);
dm_vkCreateSwapchainKHR=(PFN_vkCreateSwapchainKHR)dm_vk_get(instance,"vkCreateSwapchainKHR");if(!dm_vkCreateSwapchainKHR)die("Vulkan dispatch vkCreateSwapchainKHR",0);
dm_vkDestroyBuffer=(PFN_vkDestroyBuffer)dm_vk_get(instance,"vkDestroyBuffer");if(!dm_vkDestroyBuffer)die("Vulkan dispatch vkDestroyBuffer",0);
dm_vkDestroyDescriptorPool=(PFN_vkDestroyDescriptorPool)dm_vk_get(instance,"vkDestroyDescriptorPool");if(!dm_vkDestroyDescriptorPool)die("Vulkan dispatch vkDestroyDescriptorPool",0);
dm_vkDestroyFence=(PFN_vkDestroyFence)dm_vk_get(instance,"vkDestroyFence");if(!dm_vkDestroyFence)die("Vulkan dispatch vkDestroyFence",0);
dm_vkDestroyFramebuffer=(PFN_vkDestroyFramebuffer)dm_vk_get(instance,"vkDestroyFramebuffer");if(!dm_vkDestroyFramebuffer)die("Vulkan dispatch vkDestroyFramebuffer",0);
dm_vkDestroyImage=(PFN_vkDestroyImage)dm_vk_get(instance,"vkDestroyImage");if(!dm_vkDestroyImage)die("Vulkan dispatch vkDestroyImage",0);
dm_vkDestroyImageView=(PFN_vkDestroyImageView)dm_vk_get(instance,"vkDestroyImageView");if(!dm_vkDestroyImageView)die("Vulkan dispatch vkDestroyImageView",0);
dm_vkDestroyPipeline=(PFN_vkDestroyPipeline)dm_vk_get(instance,"vkDestroyPipeline");if(!dm_vkDestroyPipeline)die("Vulkan dispatch vkDestroyPipeline",0);
dm_vkDestroyPipelineLayout=(PFN_vkDestroyPipelineLayout)dm_vk_get(instance,"vkDestroyPipelineLayout");if(!dm_vkDestroyPipelineLayout)die("Vulkan dispatch vkDestroyPipelineLayout",0);
dm_vkDestroyQueryPool=(PFN_vkDestroyQueryPool)dm_vk_get(instance,"vkDestroyQueryPool");if(!dm_vkDestroyQueryPool)die("Vulkan dispatch vkDestroyQueryPool",0);
dm_vkDestroyRenderPass=(PFN_vkDestroyRenderPass)dm_vk_get(instance,"vkDestroyRenderPass");if(!dm_vkDestroyRenderPass)die("Vulkan dispatch vkDestroyRenderPass",0);
dm_vkDestroySampler=(PFN_vkDestroySampler)dm_vk_get(instance,"vkDestroySampler");if(!dm_vkDestroySampler)die("Vulkan dispatch vkDestroySampler",0);
dm_vkDestroySemaphore=(PFN_vkDestroySemaphore)dm_vk_get(instance,"vkDestroySemaphore");if(!dm_vkDestroySemaphore)die("Vulkan dispatch vkDestroySemaphore",0);
dm_vkDestroySurfaceKHR=(PFN_vkDestroySurfaceKHR)dm_vk_get(instance,"vkDestroySurfaceKHR");if(!dm_vkDestroySurfaceKHR)die("Vulkan dispatch vkDestroySurfaceKHR",0);
dm_vkDestroySwapchainKHR=(PFN_vkDestroySwapchainKHR)dm_vk_get(instance,"vkDestroySwapchainKHR");if(!dm_vkDestroySwapchainKHR)die("Vulkan dispatch vkDestroySwapchainKHR",0);
dm_vkDeviceWaitIdle=(PFN_vkDeviceWaitIdle)dm_vk_get(instance,"vkDeviceWaitIdle");if(!dm_vkDeviceWaitIdle)die("Vulkan dispatch vkDeviceWaitIdle",0);
dm_vkEndCommandBuffer=(PFN_vkEndCommandBuffer)dm_vk_get(instance,"vkEndCommandBuffer");if(!dm_vkEndCommandBuffer)die("Vulkan dispatch vkEndCommandBuffer",0);
dm_vkEnumeratePhysicalDevices=(PFN_vkEnumeratePhysicalDevices)dm_vk_get(instance,"vkEnumeratePhysicalDevices");if(!dm_vkEnumeratePhysicalDevices)die("Vulkan dispatch vkEnumeratePhysicalDevices",0);
dm_vkFreeCommandBuffers=(PFN_vkFreeCommandBuffers)dm_vk_get(instance,"vkFreeCommandBuffers");if(!dm_vkFreeCommandBuffers)die("Vulkan dispatch vkFreeCommandBuffers",0);
dm_vkFreeMemory=(PFN_vkFreeMemory)dm_vk_get(instance,"vkFreeMemory");if(!dm_vkFreeMemory)die("Vulkan dispatch vkFreeMemory",0);
dm_vkGetBufferMemoryRequirements=(PFN_vkGetBufferMemoryRequirements)dm_vk_get(instance,"vkGetBufferMemoryRequirements");if(!dm_vkGetBufferMemoryRequirements)die("Vulkan dispatch vkGetBufferMemoryRequirements",0);
dm_vkGetDeviceQueue=(PFN_vkGetDeviceQueue)dm_vk_get(instance,"vkGetDeviceQueue");if(!dm_vkGetDeviceQueue)die("Vulkan dispatch vkGetDeviceQueue",0);
dm_vkGetImageMemoryRequirements=(PFN_vkGetImageMemoryRequirements)dm_vk_get(instance,"vkGetImageMemoryRequirements");if(!dm_vkGetImageMemoryRequirements)die("Vulkan dispatch vkGetImageMemoryRequirements",0);
dm_vkGetPhysicalDeviceFeatures=(PFN_vkGetPhysicalDeviceFeatures)dm_vk_get(instance,"vkGetPhysicalDeviceFeatures");if(!dm_vkGetPhysicalDeviceFeatures)die("Vulkan dispatch vkGetPhysicalDeviceFeatures",0);
dm_vkGetPhysicalDeviceFormatProperties=(PFN_vkGetPhysicalDeviceFormatProperties)dm_vk_get(instance,"vkGetPhysicalDeviceFormatProperties");if(!dm_vkGetPhysicalDeviceFormatProperties)die("Vulkan dispatch vkGetPhysicalDeviceFormatProperties",0);
dm_vkGetPhysicalDeviceMemoryProperties=(PFN_vkGetPhysicalDeviceMemoryProperties)dm_vk_get(instance,"vkGetPhysicalDeviceMemoryProperties");if(!dm_vkGetPhysicalDeviceMemoryProperties)die("Vulkan dispatch vkGetPhysicalDeviceMemoryProperties",0);
dm_vkGetPhysicalDeviceProperties=(PFN_vkGetPhysicalDeviceProperties)dm_vk_get(instance,"vkGetPhysicalDeviceProperties");if(!dm_vkGetPhysicalDeviceProperties)die("Vulkan dispatch vkGetPhysicalDeviceProperties",0);
dm_vkGetPhysicalDeviceProperties2=(PFN_vkGetPhysicalDeviceProperties2)dm_vk_get(instance,"vkGetPhysicalDeviceProperties2");if(!dm_vkGetPhysicalDeviceProperties2)die("Vulkan dispatch vkGetPhysicalDeviceProperties2",0);
dm_vkGetPhysicalDeviceQueueFamilyProperties=(PFN_vkGetPhysicalDeviceQueueFamilyProperties)dm_vk_get(instance,"vkGetPhysicalDeviceQueueFamilyProperties");if(!dm_vkGetPhysicalDeviceQueueFamilyProperties)die("Vulkan dispatch vkGetPhysicalDeviceQueueFamilyProperties",0);
dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR=(PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceCapabilitiesKHR");if(!dm_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceCapabilitiesKHR",0);
dm_vkGetPhysicalDeviceSurfaceFormatsKHR=(PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceFormatsKHR");if(!dm_vkGetPhysicalDeviceSurfaceFormatsKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceFormatsKHR",0);
dm_vkGetPhysicalDeviceSurfaceSupportKHR=(PFN_vkGetPhysicalDeviceSurfaceSupportKHR)dm_vk_get(instance,"vkGetPhysicalDeviceSurfaceSupportKHR");if(!dm_vkGetPhysicalDeviceSurfaceSupportKHR)die("Vulkan dispatch vkGetPhysicalDeviceSurfaceSupportKHR",0);
dm_vkGetQueryPoolResults=(PFN_vkGetQueryPoolResults)dm_vk_get(instance,"vkGetQueryPoolResults");if(!dm_vkGetQueryPoolResults)die("Vulkan dispatch vkGetQueryPoolResults",0);
dm_vkGetSwapchainImagesKHR=(PFN_vkGetSwapchainImagesKHR)dm_vk_get(instance,"vkGetSwapchainImagesKHR");if(!dm_vkGetSwapchainImagesKHR)die("Vulkan dispatch vkGetSwapchainImagesKHR",0);
dm_vkMapMemory=(PFN_vkMapMemory)dm_vk_get(instance,"vkMapMemory");if(!dm_vkMapMemory)die("Vulkan dispatch vkMapMemory",0);
dm_vkQueuePresentKHR=(PFN_vkQueuePresentKHR)dm_vk_get(instance,"vkQueuePresentKHR");if(!dm_vkQueuePresentKHR)die("Vulkan dispatch vkQueuePresentKHR",0);
dm_vkQueueSubmit=(PFN_vkQueueSubmit)dm_vk_get(instance,"vkQueueSubmit");if(!dm_vkQueueSubmit)die("Vulkan dispatch vkQueueSubmit",0);
dm_vkQueueWaitIdle=(PFN_vkQueueWaitIdle)dm_vk_get(instance,"vkQueueWaitIdle");if(!dm_vkQueueWaitIdle)die("Vulkan dispatch vkQueueWaitIdle",0);
dm_vkUnmapMemory=(PFN_vkUnmapMemory)dm_vk_get(instance,"vkUnmapMemory");if(!dm_vkUnmapMemory)die("Vulkan dispatch vkUnmapMemory",0);
dm_vkUpdateDescriptorSets=(PFN_vkUpdateDescriptorSets)dm_vk_get(instance,"vkUpdateDescriptorSets");if(!dm_vkUpdateDescriptorSets)die("Vulkan dispatch vkUpdateDescriptorSets",0);
dm_vkWaitForFences=(PFN_vkWaitForFences)dm_vk_get(instance,"vkWaitForFences");if(!dm_vkWaitForFences)die("Vulkan dispatch vkWaitForFences",0);
dm_vkGetPipelineCacheData=(PFN_vkGetPipelineCacheData)dm_vk_get(instance,"vkGetPipelineCacheData");if(!dm_vkGetPipelineCacheData)die("Vulkan dispatch vkGetPipelineCacheData",0);
dm_vkGetFenceStatus=(PFN_vkGetFenceStatus)dm_vk_get(instance,"vkGetFenceStatus");if(!dm_vkGetFenceStatus)die("Vulkan dispatch vkGetFenceStatus",0);
dm_vkResetFences=(PFN_vkResetFences)dm_vk_get(instance,"vkResetFences");if(!dm_vkResetFences)die("Vulkan dispatch vkResetFences",0);
dm_vkResetCommandBuffer=(PFN_vkResetCommandBuffer)dm_vk_get(instance,"vkResetCommandBuffer");if(!dm_vkResetCommandBuffer)die("Vulkan dispatch vkResetCommandBuffer",0);
dm_vkResetDescriptorPool=(PFN_vkResetDescriptorPool)dm_vk_get(instance,"vkResetDescriptorPool");if(!dm_vkResetDescriptorPool)die("Vulkan dispatch vkResetDescriptorPool",0);
}
+27
View File
@@ -0,0 +1,27 @@
// Vulkan 后端暂不提供的 Metal 统计 / 调度接口:一律「无数据」,宿主诊断按缺数据处理
// Metal statistics / scheduling interfaces the Vulkan backend does not provide yet: all "no data", host diagnostics treat them as missing
#include "../dm.h"
#include "nvn_obj.h"
#include "nvn_mtl.h"
uint32_t mtl_present_qos(void) { return 0; }
__attribute__((weak)) int dm_fps_setting(void) { return 60; } // 宿主 dm_custom.c 提供强定义(省电模式 eco_fps) | The host's dm_custom.c provides the strong definition (power-saving mode eco_fps)
int mtl_fps_target(void) { // 与 nvn_mtl.m 同义:DM_FPS=30/60 钉住,否则跟自定义页的省电模式 | Same as nvn_mtl.m: DM_FPS=30/60 pins it, otherwise follows the Custom page's power-saving mode
static int env = -2;
if (env == -2) { const char *e = getenv("DM_FPS"); env = e ? atoi(e) : -1; if (env != 30 && env != 60) env = -1; }
return env > 0 ? env : dm_fps_setting() == 30 ? 30 : 60;
}
void mtl_args_stats(uint64_t *enc, uint64_t *reuse) { *enc = *reuse = 0; }
void mtl_use_stats(uint64_t *call, uint64_t *skip) { *call = *skip = 0; }
uint64_t mtl_ds_omit(void) { return 0; }
uint64_t mtl_drawable_ns_take(void) { return 0; }
void mtl_bw(uint64_t *load, uint64_t *store, uint64_t *full_rw_passes) { *load = *store = *full_rw_passes = 0; }
uint64_t mtl_udc_saved_bytes(void) { return 0; }
uint64_t mtl_pkg_miss(void) { return 0; }
uint64_t mtl_upload_ns_take(void) { return 0; }
uint64_t mtl_upload_gpu_ns_take(void) { return 0; }
void mtl_alloc_stats(uint64_t *waits, uint64_t *grown, int *n) { *waits = *grown = 0; *n = 0; }
void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb, int heap_ok, unsigned long long heap_mb, unsigned long long heap_free_mb, unsigned long long heap_maxblk_kb) {
(void)frame; (void)rss_mb; (void)heap_ok; (void)heap_mb; (void)heap_free_mb; (void)heap_maxblk_kb;
}
int dm_nvn_ruler_truth(void) { return 0; }
+9
View File
@@ -0,0 +1,9 @@
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android33-clang
OUT ?= ../../build-android/tests
CFLAGS = -O1 -g -Wall -Wno-unused-function -ffunction-sections -fdata-sections -I../../../gfx/nvn -I../../../gfx/nvn/include
$(OUT)/t_vk_perf: t_vk_perf.c ../nvn_vk.c ../nvn_vk_dispatch.h
@mkdir -p $(OUT)
$(CC) $(CFLAGS) -Wl,--gc-sections -Wl,-z,max-page-size=16384 $< -o $@ -landroid -ldl -lm -lz
.PHONY: all
all: $(OUT)/t_vk_perf
+147
View File
@@ -0,0 +1,147 @@
/* Runs real Vulkan buffer/fence regressions on an Android device. The include
* exposes the backend's private cache/batch state without a production API. */
#include "../nvn_vk.c"
#include <assert.h>
static void wait_current(void) { uint64_t ticket=mtl_sub_commit();assert(mtl_wait(ticket,UINT64_MAX)); }
static void copy_input(uint32_t *guest,VBuffer *readback) {
uint64_t offset=0;VPool *input=input_read((uint64_t)(uintptr_t)guest,16,&offset);
all_barrier();VkBufferCopy copy={offset,0,16};vkCmdCopyBuffer(G.batch->command,input->v.b,readback->b,1,&copy);
}
/* Zero-copy pools (host import or mremap of Vulkan memory): GPU reads the guest bytes
* current at execution and writes land in guest memory without writeback. */
static int direct_main(void) {
mtl_init();
if(!G.host_import && !G.get_memory_fd && !G.get_ahb_properties){fprintf(stderr,"VK_PERF_TEST_SKIP direct: no zero-copy path\n");return 0;}
uint32_t *guest=aligned_alloc(4096,4096);assert(guest);memset(guest,0,4096);mtl_pool_add(guest,4096);
uint64_t offset=0;VPool *pool=pool_find((uint64_t)(uintptr_t)guest,16,&offset);assert(pool && pool->direct && offset==0);
VBuffer first=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
for(unsigned i=0;i<4;i++)guest[i]=i+10;
mtl_sub_begin();copy_input(guest,&first);wait_current();
for(unsigned i=0;i<4;i++)assert(((uint32_t *)first.map)[i]==i+10);
uint32_t update[4]={31,32,33,34};
mtl_sub_begin();all_barrier();vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
assert(!G.batch->nwrites);wait_current();assert(!memcmp(guest,update,16));
/* Identical driver tables reuse one slot within a batch; changes get a new one. */
uint8_t table[TABLE_BYTES]={0};mtl_sub_begin();
VkDescriptorBufferInfo t0=table_bind(0,0,table),t1=table_bind(0,0,table);table[0x168]=7;VkDescriptorBufferInfo t2=table_bind(0,0,table);
assert(t0.buffer==t1.buffer && t0.offset==t1.offset && t2.offset!=t0.offset && t2.range==65536);wait_current();
/* Coherence over a cached mapping: lines the CPU holds must observe GPU
* fills, and CPU stores must reach a GPU copy without explicit flushes. */
size_t big=8<<20;uint32_t *wide=aligned_alloc(4096,big);assert(wide);
for(size_t i=0;i<big/4;i++)wide[i]=(uint32_t)i;mtl_pool_add(wide,big);
VPool *wp=pool_find((uint64_t)(uintptr_t)wide,big,&offset);assert(wp && wp->direct);
uint64_t sum=0;for(size_t i=0;i<big/4;i++)sum+=wide[i];assert(sum==(uint64_t)(big/4)*(big/4-1)/2);
static uint32_t fill[16384];for(size_t i=0;i<16384;i++)fill[i]=0x5a5a5a5au;
mtl_sub_begin();all_barrier();for(size_t at=0;at<big;at+=sizeof(fill))vkCmdUpdateBuffer(G.batch->command,wp->v.b,at,sizeof(fill),fill);wait_current();
for(size_t i=0;i<big/4;i++)assert(wide[i]==0x5a5a5a5au);
for(size_t i=0;i<big/4;i++)wide[i]=(uint32_t)i*3;
VBuffer check=buffer_make(big,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
mtl_sub_begin();all_barrier();VkBufferCopy whole={0,0,big};vkCmdCopyBuffer(G.batch->command,wp->v.b,check.b,1,&whole);wait_current();
for(size_t i=0;i<big/4;i++)assert(((uint32_t *)check.map)[i]==(uint32_t)i*3);
mtl_pool_del(wide);buffer_free(&check);free(wide);
volatile uint32_t event=0;mtl_sub_begin();mtl_sub_event(&event,0,73);mtl_sub_commit();
uint64_t deadline=dm_android_nvn_clock_ns()+1000000000;
while(!atomic_load((_Atomic uint32_t *)&event) && dm_android_nvn_clock_ns()<deadline){struct timespec pause={0,1000000};nanosleep(&pause,NULL);}
assert(event==73);
guest[5]=99;mtl_pool_del(guest);assert(guest[0]==31 && guest[5]==99);guest[6]=1; /* bytes survive unremap, pages stay writable */
mtl_finish();buffer_free(&first);free(guest);
fprintf(stderr,"VK_PERF_TEST_PASS direct_pool gpu_write_in_place cached_coherence driver_table_reuse events\n");return 0;
}
/* Memory-type microbenchmark for upload arenas: CPU write, CPU read-back
* (snapshot dedupe memcmp) and GPU copy throughput per host-visible type. */
static double ms_since(uint64_t t){return (dm_android_nvn_clock_ns()-t)/1e6;}
static int bench_main(void) {
mtl_init();size_t n=16<<20;uint8_t *src=malloc(n);assert(src);for(size_t i=0;i<n;i++)src[i]=(uint8_t)(i*7);
VBuffer dst=buffer_make(n,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
for(uint32_t type=0;type<G.memory.memoryTypeCount;type++){VkMemoryPropertyFlags f=G.memory.memoryTypes[type].propertyFlags;
if(!(f&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)&&type)continue;VBuffer b={.size=n};VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.size=n,.usage=VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_VERTEX_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT|VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT};
CHECK(vkCreateBuffer(G.device,&info,NULL,&b.b));VkMemoryRequirements r;vkGetBufferMemoryRequirements(G.device,b.b,&r);
if(type==0)fprintf(stderr,"VK_BENCH memoryTypeBits=%#x\n",r.memoryTypeBits);
if(!(r.memoryTypeBits&(1u<<type))){vkDestroyBuffer(G.device,b.b,NULL);continue;}
if(!(f&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)){vkDestroyBuffer(G.device,b.b,NULL);continue;}
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=r.size,.memoryTypeIndex=type};
uint64_t t=dm_android_nvn_clock_ns();CHECK(vkAllocateMemory(G.device,&a,NULL,&b.m));CHECK(vkBindBufferMemory(G.device,b.b,b.m,0));
void *m;CHECK(vkMapMemory(G.device,b.m,0,n,0,&m));b.map=m;double alloc=ms_since(t);
t=dm_android_nvn_clock_ns();memset(b.map,0,n);double zero=ms_since(t);
t=dm_android_nvn_clock_ns();for(int k=0;k<4;k++)memcpy(b.map,src,n);double write=ms_since(t)/4;
t=dm_android_nvn_clock_ns();int diff=0;for(int k=0;k<4;k++)diff|=memcmp(b.map,src,n);double read=ms_since(t)/4;assert(!diff);
double gpu=0;for(int k=0;k<4;k++){mtl_sub_begin();VkBufferCopy c={0,0,n};vkCmdCopyBuffer(G.batch->command,b.b,dst.b,1,&c);
t=dm_android_nvn_clock_ns();wait_current();gpu+=ms_since(t);}gpu/=4;assert(!memcmp(dst.map,src,n));
fprintf(stderr,"VK_BENCH type=%u flags=%#x MiB=16 alloc_map_ms=%.3f memset_ms=%.3f write_ms=%.3f read_cmp_ms=%.3f gpu_copy_ms=%.3f\n",type,f,alloc,zero,write,read,gpu);
buffer_free(&b);}
mtl_finish();buffer_free(&dst);free(src);return 0;
}
/* Game-shaped input load: ~11k distinct ~3 KiB snapshots over 4 batches per frame. */
static double input_frames(int frames) {
size_t n=64<<20;uint8_t *guest=aligned_alloc(4096,n);assert(guest);memset(guest,1,n);mtl_pool_add(guest,n);
uint64_t t=dm_android_nvn_clock_ns();
for(int f=0;f<frames;f++)for(int b=0;b<4;b++){mtl_sub_begin();
for(int i=0;i<2750;i++){uint64_t at=((uint64_t)(f*11000+b*2750+i)*3072)%(n-4096),off;input_read((uint64_t)(uintptr_t)guest+at,3072,&off);}
mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();pthread_mutex_unlock(&G.lock);}
mtl_finish();double ms=ms_since(t);mtl_pool_del(guest);free(guest);return ms;
}
int main(int argc,char **argv) {
if(argc>1 && !strcmp(argv[1],"bench"))return bench_main();
if(argc>1 && !strcmp(argv[1],"input")){setenv("DM_VK_POOL_COPY","1",1);mtl_init();
double recycled=input_frames(60);temporary_keep_bytes=0;double fresh=input_frames(60);
fprintf(stderr,"VK_BENCH input 60 frames recycled_ms=%.1f fresh_ms=%.1f\n",recycled,fresh);return 0;}
if(argc>1 && !strcmp(argv[1],"direct"))return direct_main();
setenv("DM_VK_POOL_COPY","1",1); /* staged copy path: snapshot semantics */
mtl_init();
/* Deliberate hash collision must never conflate distinct effective states. */
PipelineKey a={0},b={0};key_word(&a,71);key_word(&b,72);
Pso *pa=pso_insert(&a,12345),*pb=pso_insert(&b,12345);
assert(pso_find(&a,12345)==pa && pso_find(&b,12345)==pb);
uint32_t *guest=aligned_alloc(4096,4096);assert(guest);memset(guest,0,4096);mtl_pool_add(guest,4096);
VBuffer first=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT),second=buffer_make(16,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
for(unsigned i=0;i<4;i++)guest[i]=i+10;
mtl_sub_begin();copy_input(guest,&first);uint64_t ticket=mtl_sub_commit();
assert(G.batch->recording && !G.batch->pending); /* Logical commit stays batched. */
for(unsigned i=0;i<4;i++)guest[i]=i+20;
mtl_sub_begin();copy_input(guest,&second);wait_current();
assert(mtl_wait(ticket,0));
for(unsigned i=0;i<4;i++)assert(((uint32_t *)first.map)[i]==i+10 && ((uint32_t *)second.map)[i]==i+20);
/* GPU updates override stale guest bytes in a subsequent input snapshot. */
mtl_sub_begin();uint64_t offset=0;VPool *pool=pool_find((uint64_t)(uintptr_t)guest,16,&offset);pool_materialize(pool);
uint32_t update[4]={31,32,33,34};all_barrier();vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
copy_input(guest,&first);wait_current();assert(!memcmp(first.map,update,16));assert(!memcmp(guest,update,16));
/* Across separately submitted batches the newer write must not contaminate
* the older batch's CPU-visible writeback snapshot. */
mtl_sub_begin();all_barrier();update[0]=41;vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
ticket=mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();Batch *old=G.batch;pthread_mutex_unlock(&G.lock);
mtl_sub_begin();copy_input(guest,&second);all_barrier();update[0]=51;vkCmdUpdateBuffer(G.batch->command,pool->v.b,offset,16,update);mark_write((uint64_t)(uintptr_t)guest,16);
uint64_t newer=mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();
if(old->pending){assert(retire_locked(old,UINT64_MAX));assert(guest[0]==41);}
pthread_mutex_unlock(&G.lock);assert(mtl_wait(newer,UINT64_MAX));assert(guest[0]==51 && ((uint32_t *)second.map)[0]==41);
assert(!mtl_wait(newer+100,0));
/* An event must reach a guest that polls memory without another API call. */
volatile uint32_t event=0;mtl_sub_begin();mtl_sub_event(&event,0,73);mtl_sub_commit();
uint64_t deadline=dm_android_nvn_clock_ns()+1000000000;
while(!atomic_load((_Atomic uint32_t *)&event) && dm_android_nvn_clock_ns()<deadline){struct timespec pause={0,1000000};nanosleep(&pause,NULL);}
assert(event==73);
/* Descriptor chunks grow within a batch without invalidating old sets. */
VkDescriptorSetLayoutBinding binding={.binding=0,.descriptorType=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,.descriptorCount=1,.stageFlags=VK_SHADER_STAGE_VERTEX_BIT};
VkDescriptorSetLayoutCreateInfo layout_info={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,.bindingCount=1,.pBindings=&binding};
VShader shader={0};shader.h.nb=1;shader.b[0].type=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
CHECK(vkCreateDescriptorSetLayout(G.device,&layout_info,NULL,&shader.layout));
mtl_sub_begin();for(unsigned i=0;i<8200;i++)assert(shader_set_allocate(&shader));assert(G.batch->nextra_descriptors==1);
/* Capacity splits keep the logical fence reserved for the final piece. */
uint64_t before=G.fence;G.batch->ncounter=3000;
for(int i=0;i<3000;i++)G.batch->counter_ops[i]=(CounterOp){0,0,0};
batch_checkpoint();assert(G.fence==before && G.batch->recording);wait_current();
PFN_vkDestroyDescriptorSetLayout destroy_layout=(PFN_vkDestroyDescriptorSetLayout)dm_vk_get(G.instance,"vkDestroyDescriptorSetLayout");assert(destroy_layout);destroy_layout(G.device,shader.layout,NULL);
/* Slot rotation and destruction drain work before recycling resources. */
G.profile_gpu_ns=0;unsigned pending_max=0;
for(unsigned i=0;i<2*BATCH_SLOTS+4;i++){mtl_sub_begin();copy_input(guest,&first);mtl_sub_commit();pthread_mutex_lock(&G.lock);flush_locked();
unsigned pending=0;for(unsigned j=0;j<BATCH_SLOTS;j++)pending+=G.batches[j].pending;if(pending>pending_max)pending_max=pending;pthread_mutex_unlock(&G.lock);}
/* Every retired batch contributes its begin/end GPU span. */
mtl_finish();assert(!G.timestamp_bits || G.profile_gpu_ns>0);
fprintf(stderr,"ring slots=%u pending_max=%u gpu_ms=%.3f\n",BATCH_SLOTS,pending_max,G.profile_gpu_ns/1e6);
/* Retired transient buffers are recycled by size class, not reallocated. */
mtl_finish();mtl_sub_begin();VBuffer *recycled=temporary(5000,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);VkBuffer handle=recycled->b;assert(recycled->size==8192);wait_current();
mtl_finish();mtl_sub_begin();assert(temporary(8192,VK_BUFFER_USAGE_TRANSFER_DST_BIT)->b==handle);wait_current();mtl_finish();
mtl_pool_del(guest);mtl_finish();buffer_free(&first);buffer_free(&second);free(guest);
fprintf(stderr,"VK_PERF_TEST_PASS snapshots collisions GPU_writebacks fences ring_rotation gpu_timestamps events descriptor_chunks capacity_split temporary_recycle\n");return 0;
}
+16
View File
@@ -0,0 +1,16 @@
// Vulkan 后端的平台钩子(移植自 dodola/d2r-mobile 的 android/nvn_platform_*):单调时钟 + 前端交给后端的窗口 / 着色器目录
// Platform hooks of the Vulkan backend (ported from android/nvn_platform_* of dodola/d2r-mobile): monotonic clock + window / shader directory handed over by the front end
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <time.h>
static inline uint64_t dm_android_nvn_clock_ns(void) {
struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec;
}
void dm_vk_set_shader_root(const char *path); // 着色器运行包目录(shader_index.bin / *.vkmeta / *.spv.gz) | shader runtime pack directory
void dm_vk_set_window(void *native); // ANativeWindow*;NULL = 无头(不上屏,只按需读回) | ANativeWindow*; NULL = headless (no swapchain, readback on demand)
void dm_vk_set_display_hz(int hz);
// on = 1:没有窗口时出图阻塞到 dm_vk_set_window 给回窗口(App 切后台);0 = 无头照常跑 | on = 1: with no window, present blocks until dm_vk_set_window returns one (app in background); 0 = headless runs as usual
void dm_vk_hold_without_window(int on);
void *dm_vk_native_window(void);
+296
View File
@@ -0,0 +1,296 @@
// Linux / Android 兼容层实现:compat_linux.h 与 include/ 替身头里声明的函数。
// Linux / Android compatibility layer implementation: the functions declared in compat_linux.h and the stand-in headers under include/.
#include "compat_linux.h"
#include <CommonCrypto/CommonDigest.h>
#include <dirent.h>
#include <dispatch/dispatch.h>
#include <limits.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/uio.h>
#include <sys/xattr.h>
// ---- 读自己进程的内存:process_vm_readv 读自己,不可读返回 EFAULT 而不是崩 ----
// ---- Reading our own memory: process_vm_readv on ourselves returns EFAULT for unreadable ranges instead of faulting ----
kern_return_t vm_read_overwrite(mach_port_t task, vm_address_t addr, vm_size_t size, vm_address_t data, vm_size_t *outsize) {
(void)task;
struct iovec l = {(void *)data, size}, r = {(void *)addr, size};
ssize_t n = process_vm_readv(getpid(), &l, 1, &r, 1, 0);
if (n < 0 && errno == ENOSYS) {
// 退路:写进管道再读出;write 遇不可读源地址返回 EFAULT | Fallback: write into a pipe and read back; write returns EFAULT on an unreadable source
int p[2]; if (pipe(p)) return KERN_FAILURE;
n = size <= 65536 ? write(p[1], (void *)addr, size) : -1;
if (n > 0 && read(p[0], (void *)data, (size_t)n) != n) n = -1;
close(p[0]); close(p[1]);
}
if (n != (ssize_t)size) return KERN_INVALID_ADDRESS;
if (outsize) *outsize = size;
return KERN_SUCCESS;
}
kern_return_t task_info(mach_port_t task, task_flavor_t flavor, task_info_t out, mach_msg_type_number_t *count) {
(void)task;
if (flavor != TASK_VM_INFO || *count < TASK_VM_INFO_COUNT) return KERN_FAILURE;
unsigned long long vsz = 0, rss = 0; FILE *f = fopen("/proc/self/statm", "r");
if (!f) return KERN_FAILURE;
int ok = fscanf(f, "%llu %llu", &vsz, &rss) == 2; fclose(f);
if (!ok) return KERN_FAILURE;
uint64_t pg = (uint64_t)sysconf(_SC_PAGESIZE);
task_vm_info_data_t *vi = (task_vm_info_data_t *)out;
vi->virtual_size = vsz * pg; vi->resident_size = vi->phys_footprint = rss * pg;
return KERN_SUCCESS;
}
// ---- pthread 栈:Darwin 的 stackaddr 是栈顶 ----
// ---- pthread stack: Darwin's stackaddr is the stack top ----
static int stack_of(pthread_t t, void **lo, size_t *sz) {
pthread_attr_t a;
if (pthread_getattr_np(t, &a)) return -1;
int r = pthread_attr_getstack(&a, lo, sz);
pthread_attr_destroy(&a);
return r;
}
void *pthread_get_stackaddr_np(pthread_t t) { void *lo; size_t sz; return stack_of(t, &lo, &sz) ? NULL : (char *)lo + sz; }
size_t pthread_get_stacksize_np(pthread_t t) { void *lo; size_t sz; return stack_of(t, &lo, &sz) ? 0 : sz; }
// ---- 文件 ----
// ---- Files ----
int dm_fcntl_getpath(int fd, char *out) {
char p[64]; snprintf(p, sizeof p, "/proc/self/fd/%d", fd);
ssize_t n = readlink(p, out, PATH_MAX - 1);
if (n < 0) return -1;
out[n] = 0; return 0;
}
// 缓冲一律放堆上:clonefile 由存档挂载(svc 门)调用,跑在客体线程的小栈上
// All buffers live on the heap: clonefile is called by save mounting (an svc gate) and runs on a guest thread's small stack
static int copy_xattrs(int sfd, int dfd) {
char *names = malloc(4096), *v = malloc(4096); int r = 0;
ssize_t n = names && v ? flistxattr(sfd, names, 4096) : -1;
for (char *k = names; n > 0 && k < names + n; k += strlen(k) + 1) {
if (strncmp(k, "user.", 5)) continue;
ssize_t vn = fgetxattr(sfd, k, v, 4096);
if (vn >= 0 && fsetxattr(dfd, k, v, (size_t)vn, 0)) { r = -1; break; }
}
free(names); free(v);
return r;
}
static int copy_file(const char *src, const char *dst, mode_t mode) {
int sfd = open(src, O_RDONLY), dfd = sfd < 0 ? -1 : open(dst, O_WRONLY | O_CREAT | O_EXCL, mode);
char *buf = malloc(65536);
int r = sfd < 0 || dfd < 0 || !buf ? -1 : 0; ssize_t n;
while (!r && (n = read(sfd, buf, 65536)) != 0) {
if (n < 0) { r = -1; break; }
for (ssize_t o = 0; o < n;) { ssize_t w = write(dfd, buf + o, (size_t)(n - o)); if (w < 0) { r = -1; break; } o += w; }
}
if (!r) r = copy_xattrs(sfd, dfd);
free(buf);
if (sfd >= 0) close(sfd);
if (dfd >= 0) close(dfd);
return r;
}
static int copy_tree(const char *src, const char *dst) {
struct stat st; if (lstat(src, &st)) return -1;
if (S_ISREG(st.st_mode)) return copy_file(src, dst, st.st_mode & 07777);
if (!S_ISDIR(st.st_mode)) { errno = ENOTSUP; return -1; }
if (mkdir(dst, st.st_mode & 07777)) return -1;
DIR *d = opendir(src); if (!d) return -1;
char *s2 = NULL, *d2 = NULL; struct dirent *e; int r = 0;
while (!r && (e = readdir(d))) {
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
if (asprintf(&s2, "%s/%s", src, e->d_name) < 0 || asprintf(&d2, "%s/%s", dst, e->d_name) < 0) r = -1;
else r = copy_tree(s2, d2);
free(s2); free(d2); s2 = d2 = NULL;
}
closedir(d);
if (!r) { int sfd = open(src, O_RDONLY | O_DIRECTORY), dfd = open(dst, O_RDONLY | O_DIRECTORY);
if (sfd >= 0 && dfd >= 0) r = copy_xattrs(sfd, dfd);
if (sfd >= 0) close(sfd); if (dfd >= 0) close(dfd); }
return r;
}
int clonefile(const char *src, const char *dst, uint32_t flags) {
(void)flags;
struct stat st; if (!lstat(dst, &st)) { errno = EEXIST; return -1; }
return copy_tree(src, dst);
}
int renamex_np(const char *from, const char *to, unsigned flags) {
if (flags & RENAME_SWAP) return (int)syscall(SYS_renameat2, AT_FDCWD, from, AT_FDCWD, to, 2 /* RENAME_EXCHANGE */);
return rename(from, to);
}
// ---- 进程映像 ----
// ---- Process image ----
// 安卓 App 里 /proc/self/exe 是 app_process:GameActivity 在加载 libd2r.so 前设好 DM_ROOT(数据根),这里把「可执行文件」报成 <DM_ROOT>/dmhost,
// 与 adb 无头时 dmhost 和 dm/ 同目录的布局一致——库构造函数(dm/derived.tsv 的经验表等)在 chdir 之前就要用它
// In the Android app /proc/self/exe is app_process: GameActivity sets DM_ROOT (the data root) before loading libd2r.so, and the "executable" is reported as <DM_ROOT>/dmhost,
// matching the adb headless layout where dmhost sits next to dm/ -- library constructors (the EXP table from dm/derived.tsv, etc.) need it before the chdir
int _NSGetExecutablePath(char *buf, uint32_t *size) {
char p[PATH_MAX]; ssize_t n;
#ifdef __ANDROID__
const char *root = getenv("DM_ROOT");
if (root && *root) n = snprintf(p, sizeof p, "%s/dmhost", root); else
#endif
n = readlink("/proc/self/exe", p, sizeof p - 1);
if (n < 0 || n >= (ssize_t)sizeof p) return -1;
p[n] = 0;
if ((uint32_t)n + 1 > *size) { *size = (uint32_t)n + 1; return -1; }
memcpy(buf, p, (size_t)n + 1); return 0;
}
const struct mach_header_64 _mh_execute_header = {0xfeedfacf};
// Mach-O "__DATA,<名>" 登记段 → ELF 段 <名>(DM_SECT),链接器给 __start_<名> / __stop_<名>;未用到的段弱引用为空
// Mach-O "__DATA,<name>" registration section -> ELF section <name> (DM_SECT); the linker provides __start_<name> / __stop_<name>; unused sections are weak and empty
#define SECT(n) extern uint8_t __start_##n[] __attribute__((weak)), __stop_##n[] __attribute__((weak));
SECT(swhle) SECT(swforce) SECT(swnvn)
#undef SECT
uint8_t *getsectiondata(const struct mach_header_64 *mh, const char *seg, const char *sect, unsigned long *size) {
(void)mh; (void)seg;
uint8_t *a = NULL, *b = NULL;
if (!strcmp(sect, "swhle")) a = __start_swhle, b = __stop_swhle;
else if (!strcmp(sect, "swforce")) a = __start_swforce, b = __stop_swforce;
else if (!strcmp(sect, "swnvn")) a = __start_swnvn, b = __stop_swnvn;
*size = a && b ? (unsigned long)(b - a) : 0;
return *size ? a : NULL;
}
// ---- 摘要:MD5 / SHA-1 / SHA-256(只做校验与诊断用,不涉安全) ----
// ---- Digests: MD5 / SHA-1 / SHA-256 (only for checksums and diagnostics, not security) ----
#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
static void md5_block(uint32_t h[4], const uint8_t *p) {
static const uint32_t K[64] = {
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
static const uint8_t S[16] = {7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21};
uint32_t m[16]; for (int i = 0; i < 16; i++) m[i] = p[4 * i] | p[4 * i + 1] << 8 | p[4 * i + 2] << 16 | (uint32_t)p[4 * i + 3] << 24;
uint32_t a = h[0], b = h[1], c = h[2], d = h[3];
for (int i = 0; i < 64; i++) {
uint32_t f; int g;
if (i < 16) f = (b & c) | (~b & d), g = i;
else if (i < 32) f = (d & b) | (~d & c), g = (5 * i + 1) & 15;
else if (i < 48) f = b ^ c ^ d, g = (3 * i + 5) & 15;
else f = c ^ (b | ~d), g = (7 * i) & 15;
uint32_t t = d; d = c; c = b;
b = b + ROL(a + f + K[i] + m[g], S[(i >> 4) * 4 + (i & 3)]);
a = t;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
}
// 通用 Merkle–Damgård 外壳:64 字节块,长度尾按 big 端或 little 端
// Generic Merkle-Damgard wrapper: 64-byte blocks, length trailer big- or little-endian
static void md_run(const uint8_t *p, uint64_t len, int big, void (*blk)(uint32_t *, const uint8_t *), uint32_t *h) {
uint64_t full = len & ~63ull;
for (uint64_t o = 0; o < full; o += 64) blk(h, p + o);
uint8_t t[128] = {0}; size_t r = (size_t)(len - full);
memcpy(t, p + full, r); t[r] = 0x80;
size_t tl = r + 9 <= 64 ? 64 : 128; uint64_t bits = len * 8;
for (int i = 0; i < 8; i++) t[tl - 8 + i] = big ? (uint8_t)(bits >> (56 - 8 * i)) : (uint8_t)(bits >> (8 * i));
for (size_t o = 0; o < tl; o += 64) blk(h, t + o);
}
static void md5_blk(uint32_t *h, const uint8_t *p) { md5_block(h, p); }
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md) {
uint32_t h[4] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476};
md_run(data, len, 0, md5_blk, h);
for (int i = 0; i < 16; i++) md[i] = (uint8_t)(h[i / 4] >> (8 * (i & 3)));
return md;
}
static void sha1_blk(uint32_t *h, const uint8_t *p) {
uint32_t w[80];
for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | p[4 * i + 1] << 16 | p[4 * i + 2] << 8 | p[4 * i + 3];
for (int i = 16; i < 80; i++) w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
for (int i = 0; i < 80; i++) {
uint32_t f, k;
if (i < 20) f = (b & c) | (~b & d), k = 0x5a827999;
else if (i < 40) f = b ^ c ^ d, k = 0x6ed9eba1;
else if (i < 60) f = (b & c) | (b & d) | (c & d), k = 0x8f1bbcdc;
else f = b ^ c ^ d, k = 0xca62c1d6;
uint32_t t = ROL(a, 5) + f + e + k + w[i]; e = d; d = c; c = ROL(b, 30); b = a; a = t;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
}
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md) {
uint32_t h[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
md_run(data, len, 1, sha1_blk, h);
for (int i = 0; i < 20; i++) md[i] = (uint8_t)(h[i / 4] >> (24 - 8 * (i & 3)));
return md;
}
static void sha256_blk(uint32_t *h, const uint8_t *p) {
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
uint32_t w[64];
for (int i = 0; i < 16; i++) w[i] = (uint32_t)p[4 * i] << 24 | p[4 * i + 1] << 16 | p[4 * i + 2] << 8 | p[4 * i + 3];
for (int i = 16; i < 64; i++) {
uint32_t s0 = ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3), s1 = ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (int i = 0; i < 64; i++) {
uint32_t t1 = hh + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i];
uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
int CC_SHA256_Init(CC_SHA256_CTX *c) {
static const uint32_t H0[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
memcpy(c->h, H0, sizeof H0); c->len = 0; c->n = 0; return 1;
}
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len) {
const uint8_t *p = data; c->len += len;
while (len) {
if (!c->n && len >= 64) { sha256_blk(c->h, p); p += 64; len -= 64; continue; }
uint32_t k = 64 - c->n < len ? 64 - c->n : len;
memcpy(c->buf + c->n, p, k); c->n += k; p += k; len -= k;
if (c->n == 64) { sha256_blk(c->h, c->buf); c->n = 0; }
}
return 1;
}
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c) {
uint8_t t[128] = {0}; memcpy(t, c->buf, c->n); t[c->n] = 0x80;
size_t tl = c->n + 9 <= 64 ? 64 : 128; uint64_t bits = c->len * 8;
for (int i = 0; i < 8; i++) t[tl - 8 + i] = (uint8_t)(bits >> (56 - 8 * i));
for (size_t o = 0; o < tl; o += 64) sha256_blk(c->h, t + o);
for (int i = 0; i < 32; i++) md[i] = (uint8_t)(c->h[i / 4] >> (24 - 8 * (i & 3)));
return 1;
}
// ---- dispatch 计数信号量 ----
// ---- dispatch counting semaphore ----
struct dm_dsema { sem_t s; };
dispatch_semaphore_t dispatch_semaphore_create(long value) {
dispatch_semaphore_t d = malloc(sizeof *d);
if (d && sem_init(&d->s, 0, (unsigned)value)) { free(d); d = NULL; }
return d;
}
long dispatch_semaphore_signal(dispatch_semaphore_t d) { sem_post(&d->s); return 0; }
long dispatch_semaphore_wait(dispatch_semaphore_t d, dispatch_time_t timeout) {
if (timeout == DISPATCH_TIME_FOREVER) { while (sem_wait(&d->s) && errno == EINTR) {} return 0; }
if (timeout == DISPATCH_TIME_NOW) return sem_trywait(&d->s) ? 1 : 0;
struct timespec ts = {(time_t)(timeout / 1000000000ull), (long)(timeout % 1000000000ull)}; // 绝对 CLOCK_REALTIME 纳秒 | absolute CLOCK_REALTIME ns
while (sem_timedwait(&d->s, &ts)) if (errno != EINTR) return 1;
return 0;
}
void dispatch_release(void *obj) { struct dm_dsema *d = obj; if (d) { sem_destroy(&d->s); free(d); } }
uint64_t mach_absolute_time(void) { return clock_gettime_nsec_np(CLOCK_MONOTONIC); }
+150
View File
@@ -0,0 +1,150 @@
// Linux / Android 兼容层:宿主源码按 Darwin 写,在 Linux 上用 -include 强制先包含本头,
// 再由 compat/linux/include 下的同名替身头(mach/mach.h、CommonCrypto/CommonDigest.h…)吃掉 Apple 头的 #include。
// 这里只补「同一语义、换个名字」的接口;语义不同的(线程暂停取寄存器、AudioUnit、GCD 信号源、xattr 参数)在源码里按 __APPLE__ 分支。
// Linux / Android compatibility layer: the host sources are written against Darwin; on Linux this header is force-included first with -include,
// and the same-named stand-in headers under compat/linux/include (mach/mach.h, CommonCrypto/CommonDigest.h, ...) absorb the #include of Apple headers.
// Only "same semantics, different name" interfaces are provided here; the ones with different semantics (suspending a thread to read its registers,
// AudioUnit, GCD signal sources, xattr arguments) branch on __APPLE__ in the sources.
#pragma once
#if !defined(__linux__)
#error "compat_linux.h 只给 Linux / Android 用 | compat_linux.h is for Linux / Android only"
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
// ---- TargetConditionals:Linux 既不是 iPhone 也不是 OSX;运行时可写代码(探针 / 计数桩)这类「非 iPhone」路径照常可用 ----
// ---- TargetConditionals: Linux is neither iPhone nor OSX; "non-iPhone" paths such as runtime-written code (probes / counting stubs) work as usual ----
#define TARGET_OS_IPHONE 0
#define TARGET_OS_IOS 0
#define TARGET_OS_OSX 0
#define TARGET_OS_MAC 0
#define TARGET_OS_SIMULATOR 0
#define TARGET_OS_MACCATALYST 0
#define DM_LINUX 1
// ---- 时钟:CLOCK_UPTIME_RAW(不含睡眠)= Linux CLOCK_MONOTONIC(同样不含挂起);mach 时基取 1/1 = 纳秒 ----
// ---- Clocks: CLOCK_UPTIME_RAW (excludes sleep) = Linux CLOCK_MONOTONIC (also excludes suspend); the mach time base is 1/1 = nanoseconds ----
#define CLOCK_UPTIME_RAW CLOCK_MONOTONIC
#define CLOCK_UPTIME_RAW_APPROX CLOCK_MONOTONIC_COARSE
#define CLOCK_MONOTONIC_RAW_APPROX CLOCK_MONOTONIC_COARSE
static inline uint64_t clock_gettime_nsec_np(clockid_t c) {
struct timespec ts; if (clock_gettime(c, &ts)) return 0;
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
}
typedef int kern_return_t;
#define KERN_SUCCESS 0
#define KERN_FAILURE 5
#define KERN_INVALID_ADDRESS 1
typedef struct { uint32_t numer, denom; } mach_timebase_info_data_t;
typedef mach_timebase_info_data_t *mach_timebase_info_t;
static inline kern_return_t mach_timebase_info(mach_timebase_info_t t) { t->numer = t->denom = 1; return KERN_SUCCESS; }
// 真符号:nvn_entry.S 直接 bl mach_absolute_time | a real symbol: nvn_entry.S calls mach_absolute_time directly
uint64_t mach_absolute_time(void);
static inline uint64_t mach_continuous_time(void) { return clock_gettime_nsec_np(CLOCK_BOOTTIME); }
static inline kern_return_t mach_wait_until(uint64_t deadline) {
struct timespec ts = {(time_t)(deadline / 1000000000ull), (long)(deadline % 1000000000ull)};
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == EINTR) {}
return KERN_SUCCESS;
}
// ---- 任务 / 内存:只有「读自己进程一段可能不可读的内存」这一种用法(诊断),用 process_vm_readv 读自己,缺页返回错误而不是崩 ----
// ---- Task / memory: the only use is "read a possibly unreadable range of our own process" (diagnostics); process_vm_readv on ourselves returns an error instead of faulting ----
typedef int mach_port_t;
typedef mach_port_t task_t, thread_t, thread_act_t;
typedef unsigned mach_msg_type_number_t;
typedef uintptr_t vm_address_t;
typedef size_t vm_size_t;
typedef int vm_prot_t;
static inline mach_port_t mach_task_self(void) { return 0; }
static inline mach_port_t mach_thread_self(void) { return (mach_port_t)gettid(); }
static inline mach_port_t pthread_mach_thread_np(pthread_t t) { return (mach_port_t)pthread_gettid_np(t); }
static inline kern_return_t mach_port_deallocate(mach_port_t task, mach_port_t p) { (void)task; (void)p; return KERN_SUCCESS; }
// task_info(TASK_VM_INFO):只给 phys_footprint(取 /proc/self/statm 的常驻页) | task_info(TASK_VM_INFO): only phys_footprint (resident pages from /proc/self/statm)
typedef int task_flavor_t;
typedef int *task_info_t;
#define TASK_VM_INFO 22
typedef struct { uint64_t virtual_size, resident_size, phys_footprint; } task_vm_info_data_t;
#define TASK_VM_INFO_COUNT ((mach_msg_type_number_t)(sizeof(task_vm_info_data_t) / sizeof(int)))
kern_return_t task_info(mach_port_t task, task_flavor_t flavor, task_info_t out, mach_msg_type_number_t *count);
kern_return_t vm_read_overwrite(mach_port_t task, vm_address_t addr, vm_size_t size, vm_address_t data, vm_size_t *outsize);
// ---- 指令缓存 ----
// ---- Instruction cache ----
static inline void sys_icache_invalidate(void *p, size_t n) { __builtin___clear_cache((char *)p, (char *)p + n); }
static inline void sys_dcache_flush(void *p, size_t n) { (void)p; (void)n; }
// ---- QoS:Linux 没有,按「不设」处理;查询返回 UNSPECIFIED ----
// ---- QoS: Linux has none; treated as "not set", queries return UNSPECIFIED ----
typedef enum {
QOS_CLASS_USER_INTERACTIVE = 0x21, QOS_CLASS_USER_INITIATED = 0x19, QOS_CLASS_DEFAULT = 0x15,
QOS_CLASS_UTILITY = 0x11, QOS_CLASS_BACKGROUND = 0x09, QOS_CLASS_UNSPECIFIED = 0x00,
} qos_class_t;
static inline int pthread_set_qos_class_self_np(qos_class_t q, int rel) { (void)q; (void)rel; return 0; }
static inline int pthread_get_qos_class_np(pthread_t t, qos_class_t *q, int *rel) { (void)t; if (q) *q = QOS_CLASS_UNSPECIFIED; if (rel) *rel = 0; return 0; }
static inline qos_class_t qos_class_self(void) { return QOS_CLASS_UNSPECIFIED; }
// ---- pthread 的 Darwin 扩展 ----
// ---- Darwin extensions of pthread ----
// Darwin pthread_setname_np 只给当前线程起名
// Darwin pthread_setname_np only names the current thread
#define pthread_setname_np(n) pthread_setname_np(pthread_self(), (n))
// Darwin 的 stackaddr 是栈顶(高地址)
// Darwin's stackaddr is the stack top (high address)
void *pthread_get_stackaddr_np(pthread_t t);
size_t pthread_get_stacksize_np(pthread_t t);
static inline int pthread_threadid_np(pthread_t t, uint64_t *id) { *id = (uint64_t)pthread_gettid_np(t ? t : pthread_self()); return 0; }
static inline int pthread_main_np(void) { return getpid() == gettid(); }
// ---- 文件 ----
// ---- Files ----
#define st_mtimespec st_mtim
#define st_atimespec st_atim
#define st_ctimespec st_ctim
static inline int getdtablesize(void) { return (int)sysconf(_SC_OPEN_MAX); }
#define F_GETPATH 0x7fff0032 // 由 dm_fcntl_getpath 处理(fcntl 不认识这个号) | handled by dm_fcntl_getpath (fcntl does not know this number)
#ifndef ENOATTR
#define ENOATTR ENODATA
#endif
int dm_fcntl_getpath(int fd, char *out);
// 整树复制(含 user.* 扩展属性);Linux 没有写时复制克隆,存档目录小,复制可接受
// Whole-tree copy (including user.* extended attributes); Linux has no copy-on-write clone, save directories are small so copying is acceptable
int clonefile(const char *src, const char *dst, uint32_t flags);
#define RENAME_SWAP 2u
int renamex_np(const char *from, const char *to, unsigned flags);
// ---- 进程映像:可执行文件路径;Mach-O 段登记表的 ELF 对应(__start_<段> / __stop_<段>) ----
// ---- Process image: executable path; the ELF counterpart of the Mach-O registration sections (__start_<sect> / __stop_<sect>) ----
int _NSGetExecutablePath(char *buf, uint32_t *size);
struct mach_header_64 { uint32_t magic; };
extern const struct mach_header_64 _mh_execute_header;
uint8_t *getsectiondata(const struct mach_header_64 *mh, const char *seg, const char *sect, unsigned long *size);
// ---- 随机数:bionic 自带 arc4random;glibc 2.36 起也有 ----
// ---- Random numbers: bionic ships arc4random; glibc has it since 2.36 ----
#include <stdlib.h>
#include <stdio.h>
#include <sys/ucontext.h>
// ---- 信号上下文:ESR 在 __reserved 的 esr_context 里(magic 0x45535201) ----
// ---- Signal context: ESR lives in the esr_context inside __reserved (magic 0x45535201) ----
static inline uint64_t dm_uc_esr(const ucontext_t *uc) {
const uint8_t *p = (const uint8_t *)uc->uc_mcontext.__reserved, *end = p + sizeof uc->uc_mcontext.__reserved;
while (p + 8 <= end) {
uint32_t magic, size; memcpy(&magic, p, 4); memcpy(&size, p + 4, 4);
if (!magic || size < 8) break;
if (magic == 0x45535201u) { uint64_t esr; memcpy(&esr, p + 8, 8); return esr; }
p += size;
}
return 0;
}
@@ -0,0 +1,15 @@
// Linux 替身:CommonCrypto/CommonDigest.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: CommonCrypto/CommonDigest.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
#include <stdint.h>
typedef uint32_t CC_LONG;
#define CC_MD5_DIGEST_LENGTH 16
#define CC_SHA1_DIGEST_LENGTH 20
#define CC_SHA256_DIGEST_LENGTH 32
typedef struct { uint32_t h[8]; uint64_t len; uint8_t buf[64]; uint32_t n; } CC_SHA256_CTX;
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md);
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md);
int CC_SHA256_Init(CC_SHA256_CTX *c);
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len);
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c);
@@ -0,0 +1,3 @@
// Linux 替身:TargetConditionals.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: TargetConditionals.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,15 @@
// Linux 替身:dispatch/dispatch.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: dispatch/dispatch.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
#include <stdint.h>
// 只实现计数信号量(hle_audio 用);队列 / 定时 / 信号源在源码里按 __APPLE__ 分支
// Only the counting semaphore is implemented (used by hle_audio); queues / timers / signal sources branch on __APPLE__ in the sources
typedef struct dm_dsema *dispatch_semaphore_t;
typedef uint64_t dispatch_time_t;
#define DISPATCH_TIME_NOW 0ull
#define DISPATCH_TIME_FOREVER (~0ull)
dispatch_semaphore_t dispatch_semaphore_create(long value);
long dispatch_semaphore_signal(dispatch_semaphore_t s);
long dispatch_semaphore_wait(dispatch_semaphore_t s, dispatch_time_t timeout);
void dispatch_release(void *obj);
@@ -0,0 +1,3 @@
// Linux 替身:libkern/OSCacheControl.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: libkern/OSCacheControl.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,4 @@
// Linux 替身:mach-o/dyld.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach-o/dyld.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
#include <dlfcn.h>
@@ -0,0 +1,3 @@
// Linux 替身:mach-o/getsect.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach-o/getsect.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,3 @@
// Linux 替身:mach-o/ldsyms.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach-o/ldsyms.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
+33
View File
@@ -0,0 +1,33 @@
// Linux 替身:mach/mach.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach/mach.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
#include <stdint.h>
// ---- 线程诊断接口:Linux 上一律返回失败,调用方走「拿不到」分支(暂停取寄存器、线程信息、实时策略都只用于诊断 / 调优) ----
// ---- Thread diagnostic interfaces: always fail on Linux, callers take their "unavailable" branch (suspend-and-read-registers, thread info and real-time policy are only for diagnostics / tuning) ----
typedef int boolean_t;
typedef int *thread_info_t, *thread_state_t, *thread_policy_t;
typedef int thread_flavor_t, thread_state_flavor_t, thread_policy_flavor_t;
typedef mach_port_t *thread_act_array_t;
typedef struct { int seconds, microseconds; } time_value_t;
typedef struct { time_value_t user_time, system_time; int cpu_usage, policy, run_state, flags, suspend_count, sleep_time; } thread_basic_info_data_t;
typedef struct { uint64_t pth_user_time, pth_system_time; int32_t pth_cpu_usage, pth_policy, pth_run_state, pth_flags, pth_sleep_time, pth_curpri, pth_priority, pth_maxpriority; char pth_name[64]; } thread_extended_info_data_t;
typedef struct { uint64_t __x[29], __fp, __lr, __sp, __pc; uint32_t __cpsr, __pad; } arm_thread_state64_t;
#define THREAD_BASIC_INFO 3
#define THREAD_BASIC_INFO_COUNT ((mach_msg_type_number_t)(sizeof(thread_basic_info_data_t) / sizeof(int)))
#define THREAD_EXTENDED_INFO 5
#define THREAD_EXTENDED_INFO_COUNT ((mach_msg_type_number_t)(sizeof(thread_extended_info_data_t) / sizeof(int)))
#define ARM_THREAD_STATE64 6
#define ARM_THREAD_STATE64_COUNT ((mach_msg_type_number_t)(sizeof(arm_thread_state64_t) / sizeof(int)))
#define __darwin_arm_thread_state64_get_pc(s) ((s).__pc)
#define __darwin_arm_thread_state64_get_lr(s) ((s).__lr)
#define __darwin_arm_thread_state64_get_fp(s) ((s).__fp)
#define __darwin_arm_thread_state64_get_sp(s) ((s).__sp)
static inline kern_return_t thread_info(mach_port_t t, thread_flavor_t f, thread_info_t o, mach_msg_type_number_t *n) { (void)t; (void)f; (void)o; (void)n; return KERN_FAILURE; }
static inline kern_return_t thread_suspend(mach_port_t t) { (void)t; return KERN_FAILURE; }
static inline kern_return_t thread_resume(mach_port_t t) { (void)t; return KERN_FAILURE; }
static inline kern_return_t thread_get_state(mach_port_t t, thread_state_flavor_t f, thread_state_t s, mach_msg_type_number_t *n) { (void)t; (void)f; (void)s; (void)n; return KERN_FAILURE; }
static inline kern_return_t task_threads(mach_port_t task, thread_act_array_t *a, mach_msg_type_number_t *n) { (void)task; *a = 0; *n = 0; return KERN_FAILURE; }
static inline kern_return_t vm_deallocate(mach_port_t task, vm_address_t a, vm_size_t n) { (void)task; (void)a; (void)n; return KERN_SUCCESS; }
// libSystem 私有:本线程 {指令, 周期};Linux 版给 0(可改用 perf_event_open) | libSystem private: this thread's {instructions, cycles}; Linux gives 0 (perf_event_open could be used instead)
static inline int thread_selfcounts(int type, void *buf, size_t nbytes) { (void)type; memset(buf, 0, nbytes); return -1; }
@@ -0,0 +1,3 @@
// Linux 替身:mach/mach_time.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach/mach_time.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,3 @@
// Linux 替身:mach/thread_info.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach/thread_info.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,15 @@
// Linux 替身:mach/thread_policy.h —— 实时线程策略在 Linux 上一律失败(调用方只记日志)
// Linux stand-in: mach/thread_policy.h -- real-time thread policy always fails on Linux (callers only log)
#pragma once
#include <mach/mach.h>
typedef struct { uint32_t period, computation, constraint; boolean_t preemptible; } thread_time_constraint_policy_data_t;
#define THREAD_TIME_CONSTRAINT_POLICY 2
#define THREAD_TIME_CONSTRAINT_POLICY_COUNT ((mach_msg_type_number_t)(sizeof(thread_time_constraint_policy_data_t) / sizeof(int)))
typedef struct { int importance; } thread_precedence_policy_data_t;
#define THREAD_PRECEDENCE_POLICY 3
#define THREAD_PRECEDENCE_POLICY_COUNT 1
typedef struct { boolean_t timeshare; } thread_extended_policy_data_t;
#define THREAD_EXTENDED_POLICY 1
#define THREAD_EXTENDED_POLICY_COUNT 1
static inline kern_return_t thread_policy_set(mach_port_t t, thread_policy_flavor_t f, thread_policy_t p, mach_msg_type_number_t n) { (void)t; (void)f; (void)p; (void)n; return KERN_FAILURE; }
static inline kern_return_t thread_policy_get(mach_port_t t, thread_policy_flavor_t f, thread_policy_t p, mach_msg_type_number_t *n, boolean_t *def) { (void)t; (void)f; (void)p; (void)n; if (def) *def = 1; return KERN_FAILURE; }
@@ -0,0 +1,3 @@
// Linux 替身:mach/vm_statistics.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: mach/vm_statistics.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,10 @@
// Linux 替身:malloc/malloc.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: malloc/malloc.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
#include <malloc.h>
typedef struct { unsigned blocks_in_use; size_t size_in_use, max_size_in_use, size_allocated; } malloc_statistics_t;
// 只填 size_in_use(mallinfo 的 uordblks);zone 参数忽略 | Only size_in_use is filled (mallinfo uordblks); the zone argument is ignored
static inline void malloc_zone_statistics(void *zone, malloc_statistics_t *s) {
(void)zone; struct mallinfo mi = mallinfo();
memset(s, 0, sizeof *s); s->size_in_use = s->size_allocated = (size_t)mi.uordblks;
}
@@ -0,0 +1,3 @@
// Linux 替身:pthread/qos.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: pthread/qos.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
@@ -0,0 +1,3 @@
// Linux 替身:sys/clonefile.h —— 实际定义见 compat_linux.h(-include 强制先含)
// Linux stand-in: sys/clonefile.h -- the actual definitions are in compat_linux.h (force-included with -include)
#pragma once
+5 -5
View File
@@ -133,15 +133,15 @@ static void on_crash(int sig, siginfo_t *si, void *uc_) {
ucontext_t *uc = uc_;
if (sig == SIGTRAP && g_trap_hook && g_trap_hook(uc)) return;
if (sig == SIGSEGV || sig == SIGBUS) {
int is_write = (int)((uc->uc_mcontext->__es.__esr >> 6) & 1); // ESR 的 WnR 位 | The WnR bit of ESR
int is_write = (int)((UC_ESR(uc) >> 6) & 1); // ESR 的 WnR 位 | The WnR bit of ESR
for (int i = 0; i < g_nfault_hook; i++) if (g_fault_hook[i](si->si_addr, is_write, uc)) return;
}
fprintf(stderr, "[dm] CRASH sig=%d", sig);
off("addr", (uint64_t)si->si_addr); off("pc", uc->uc_mcontext->__ss.__pc); off("lr", uc->uc_mcontext->__ss.__lr);
fprintf(stderr, " sp=%#llx\n", uc->uc_mcontext->__ss.__sp);
for (int i = 0; i < 29; i++) fprintf(stderr, "x%d=%#llx%s", i, uc->uc_mcontext->__ss.__x[i], i % 6 == 5 ? "\n" : " ");
off("addr", (uint64_t)si->si_addr); off("pc", UC_PC(uc)); off("lr", UC_LR(uc));
fprintf(stderr, " sp=%#llx\n", UC_SP(uc));
for (int i = 0; i < 29; i++) fprintf(stderr, "x%d=%#llx%s", i, UC_X(uc, i), i % 6 == 5 ? "\n" : " ");
fprintf(stderr, "\n");
dm_backtrace(uc->uc_mcontext->__ss.__fp);
dm_backtrace(UC_FP(uc));
if (g_dump_hook) g_dump_hook();
_exit(128 + sig);
}
+10 -10
View File
@@ -166,25 +166,25 @@ static void probe_dump_once(void) {
LOG("探针转储 %s+%s 长 %s → %s", mod, o, n, f ? f : def);
}
static int probe_hit(ucontext_t *uc) { // 由 probe_install 注册给 crash.c 的 SIGTRAP 分支 | Registered by probe_install with the SIGTRAP branch of crash.c
uint64_t pc = uc->uc_mcontext->__ss.__pc;
uint64_t pc = UC_PC(uc);
for (int i = 0; i < g_nprobe; i++) if (g_probe[i].at == pc) {
probe_dump_once();
if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot; return 1; }
if (g_probe[i].fn) { g_probe[i].hits++; g_probe[i].fn(uc); UC_PC(uc) = (uint64_t)g_probe[i].slot; return 1; }
{ extern uint64_t g_t0_ns; uint64_t now_ns(void); fprintf(stderr, "[dm] PROBE %s #%u [%.4fs]", g_probe[i].name, ++g_probe[i].hits, (now_ns() - g_t0_ns) / 1e9); }
for (int r = 0; r < 4; r++) { uint64_t v = uc->uc_mcontext->__ss.__x[r]; fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); }
for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, uc->uc_mcontext->__ss.__x[r]);
{ uint64_t x8 = uc->uc_mcontext->__ss.__x[8]; Dl_info di; fprintf(stderr, " x8=%#llx", x8); // x8:间接调用目标常在这里(blr x8 前下探针) | x8: indirect call targets are often here (probe placed before blr x8)
for (int r = 0; r < 4; r++) { uint64_t v = UC_X(uc, r); fprintf(stderr, " x%d=%#llx", r, v); probe_str(v); }
for (int r = 19; r < 24; r++) fprintf(stderr, " x%d=%#llx", r, UC_X(uc, r));
{ uint64_t x8 = UC_X(uc, 8); Dl_info di; fprintf(stderr, " x8=%#llx", x8); // x8:间接调用目标常在这里(blr x8 前下探针) | x8: indirect call targets are often here (probe placed before blr x8)
if (dladdr((void *)x8, &di) && di.dli_sname) fprintf(stderr, "(%s+%#lx)", di.dli_sname, (unsigned long)(x8 - (uint64_t)di.dli_saddr)); }
if (g_probe[i].dump >= 0) {
uint8_t b[16]; vm_size_t got = 0;
uint64_t at = uc->uc_mcontext->__ss.__x[0] + (g_probe[i].dump & 0xffffff);
uint64_t at = UC_X(uc, 0) + (g_probe[i].dump & 0xffffff);
if (g_probe[i].dump & 0x1000000) { uint64_t p = 0; vm_size_t g = 0; if (!vm_read_overwrite(mach_task_self(), at, 8, (vm_address_t)&p, &g)) at = p; else at = 0; } // @*偏移:先解引用再转储 | @*offset: dereference first, then dump
if (at && !vm_read_overwrite(mach_task_self(), at, 16, (vm_address_t)b, &got) && got == 16) {
fprintf(stderr, " [%s%#lx]=", (g_probe[i].dump & 0x1000000) ? "*x0+" : "x0+", g_probe[i].dump & 0xffffff); for (int k = 0; k < 16; k++) fprintf(stderr, "%02x", b[k]); }
}
fputc('\n', stderr);
dm_backtrace(uc->uc_mcontext->__ss.__fp);
uc->uc_mcontext->__ss.__pc = (uint64_t)g_probe[i].slot;
dm_backtrace(UC_FP(uc));
UC_PC(uc) = (uint64_t)g_probe[i].slot;
return 1;
}
return 0;
@@ -480,8 +480,8 @@ static void on_sample(int sig, siginfo_t *si, void *uc_) {
unsigned i = atomic_load(&g_shead) % SRING;
extern uint64_t now_ns(void);
uint32_t thr_cur_handle(void);
g_sring[i].h = thr_cur_handle(); g_sring[i].t = now_ns(); g_sring[i].pc = uc->uc_mcontext->__ss.__pc; g_sring[i].lr = uc->uc_mcontext->__ss.__lr;
uint64_t fp = uc->uc_mcontext->__ss.__fp; int n = 0;
g_sring[i].h = thr_cur_handle(); g_sring[i].t = now_ns(); g_sring[i].pc = UC_PC(uc); g_sring[i].lr = UC_LR(uc);
uint64_t fp = UC_FP(uc); int n = 0;
// 帧链用安全读:被打断的函数可能把 x29 当普通寄存器用(直接解引用曾段错误)
// The frame chain uses safe reads: the interrupted function may be using x29 as an ordinary register (a direct dereference once segfaulted)
for (; n < 16 && fp && !(fp & 7); n++) {
+9
View File
@@ -6,6 +6,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dm_plat.h"
#define MAX_MOD 8
#define LOG(...) do { fprintf(stderr, "[dm] " __VA_ARGS__); fputc('\n', stderr); } while (0)
@@ -43,6 +44,14 @@ extern int g_nmod;
// Four thread-local slots: K18 = the Switch's x18, KTLS = tpidr_el0, KTLR = tpidrro_el0 (ThreadLocalRegion), KGATE = host gate entry; the actual key numbers are written into the key page by the loader
extern pthread_key_t g_key18, g_keytls, g_keytlr, g_keygate;
extern pthread_key_t g_keyres[2], g_keyaspect, g_keyaspectui;
// 槽写入:Apple 槽 = pthread TSD(tpidrro_el0 + 8*键);Linux / Android 槽 = tp[2](bionic TLS_SLOT_APP)指向的每线程槽块 + 8*键,键是 1..8 的小整数
// Slot write: on Apple a slot = pthread TSD (tpidrro_el0 + 8*key); on Linux / Android a slot = the per-thread slot block pointed to by tp[2] (bionic TLS_SLOT_APP) + 8*key, keys being small integers 1..8
#ifdef __APPLE__
#define dm_slot_set(k, v) pthread_setspecific((k), (v))
#else
void dm_slot_set(pthread_key_t k, void *v);
uint64_t *dm_slot_block(void);
#endif
void load_modules(const char *dir, const char **names, int n);
void run_module_inits(void);
+1 -1
View File
@@ -99,7 +99,7 @@ static int skipped(int skill) { if (getenv("DM_TEST_BUFF_NOSKIP")) return 0; /
uint32_t dm_cur_tick(void);
static int enabled(void) { static int env = -2; if (env == -2) { const char *e = getenv("DM_AUTOBUFF"); env = e ? e[0] != '0' : -1; }
return env >= 0 ? env : (TARGET_OS_IPHONE && dm_custom_get("auto_buff")); }
return env >= 0 ? env : (DM_TOUCH_PRODUCT && dm_custom_get("auto_buff")); }
static int cfg(const char *nm, int def) { const char *e = getenv(nm); return e && atoi(e) > 0 ? atoi(e) : def; }
static int has_state(uint64_t u, int st) {
uint64_t sl = *(uint64_t *)(u + 0x88); if (!sl || !(*(uint32_t *)(sl + 0x1c) >> 31)) return 0;
+2 -2
View File
@@ -61,11 +61,11 @@ static void grant(uint8_t *mb, uint64_t unit, int srv) { // 这个单位的技
uint64_t nd = ((uint64_t (*)(uint64_t, int))(mb + 0x7bf010))(unit, sk); static int lg; if (lg++ < 8) LOG("免费回城:%s玩家技能链挂上回城技能 %d → %s", srv ? "服务端" : "客户端", sk, nd ? "成" : "【红】失败");
}
// ZR 这一格现在是不是空的:面 → 格表 main+0x2d13cbc(6 × {逻辑键, 普通格, 替代格},ZR 的逻辑键 0x800)、格 → 技能表 main+0x2d5f0c0(每格 28 字节,首 4 字节技能号;武器第二组在 +16 格),
// 读法同前端的技能格快照(dm/ios/Sources/dm_touch_game_bridge.c)。[0] = 没按 ZL 时 ZR 用的那格,[1] = 按着 ZL 时的那格
// 读法同前端的技能格快照(dm/touch/dm_touch_game_bridge.c)。[0] = 没按 ZL 时 ZR 用的那格,[1] = 按着 ZL 时的那格
// Whether the ZR slot is empty right now: face button -> slot table main+0x2d13cbc (6 x {logical key, normal slot, alternate slot}, the logical key
// of ZR is 0x800), slot -> skill table main+0x2d5f0c0 (28 bytes per slot, the first 4 bytes are the skill number; the second weapon set is at
// +16 slots),
// read the same way as the front end's skill slot snapshot (dm/ios/Sources/dm_touch_game_bridge.c). [0] = the slot ZR uses when ZL is not held,
// read the same way as the front end's skill slot snapshot (dm/touch/dm_touch_game_bridge.c). [0] = the slot ZR uses when ZL is not held,
// [1] = the slot used while ZL is held
static _Atomic int g_zr_free[2];
int dm_freetp_zr_free(int zl) { return atomic_load(&g_zr_free[zl != 0]); }
+34
View File
@@ -0,0 +1,34 @@
// 平台差异的最小公共面:信号上下文寄存器、宿主登记段。Darwin 与 Linux 各一份定义,其余差异见 compat/linux/compat_linux.h。
// Minimal common surface of platform differences: signal-context registers and host registration sections. One definition each for Darwin and Linux;
// other differences are in compat/linux/compat_linux.h.
#pragma once
#if defined(__APPLE__)
#define UC_X(uc, i) ((uc)->uc_mcontext->__ss.__x[i])
#define UC_PC(uc) ((uc)->uc_mcontext->__ss.__pc)
#define UC_LR(uc) ((uc)->uc_mcontext->__ss.__lr)
#define UC_FP(uc) ((uc)->uc_mcontext->__ss.__fp)
#define UC_SP(uc) ((uc)->uc_mcontext->__ss.__sp)
#define UC_ESR(uc) ((uint64_t)(uc)->uc_mcontext->__es.__esr)
// 登记段:Mach-O 段名 "__DATA,<名>"
// Registration section: Mach-O section name "__DATA,<name>"
#define DM_SECT(name) section("__DATA," name)
#else
#define UC_X(uc, i) ((uc)->uc_mcontext.regs[i])
#define UC_PC(uc) ((uc)->uc_mcontext.pc)
#define UC_LR(uc) ((uc)->uc_mcontext.regs[30])
#define UC_FP(uc) ((uc)->uc_mcontext.regs[29])
#define UC_SP(uc) ((uc)->uc_mcontext.sp)
#define UC_ESR(uc) dm_uc_esr(uc)
// 登记段:ELF 段名须是 C 标识符,链接器才给 __start_<名> / __stop_<名>;retain 防 --gc-sections 丢弃
// Registration section: the ELF section name must be a C identifier for the linker to provide __start_<name> / __stop_<name>; retain keeps --gc-sections from dropping it
#define DM_SECT(name) section(name), retain
#endif
// 触摸产品(iOS 包、Android 包):设置缺省、掉落过滤规则、自动补增益这类「产品缺省开、Mac 宿主对拍时缺省关」的开关看它,不看 TARGET_OS_IPHONE。
// 展开时才读 TARGET_OS_IPHONE,用处须已包含 TargetConditionals(Linux 由 compat_linux.h 定义)。
// Touch product (iOS build, Android build): switches that are "on by default in the product, off by default for Mac host parity" (settings defaults, loot filter rules, auto-buff)
// check this rather than TARGET_OS_IPHONE. TARGET_OS_IPHONE is read at expansion, so the use site must already include TargetConditionals (compat_linux.h defines it on Linux).
#if defined(__ANDROID__)
#define DM_TOUCH_PRODUCT 1
#else
#define DM_TOUCH_PRODUCT TARGET_OS_IPHONE
#endif
+2 -2
View File
@@ -9,7 +9,7 @@
typedef struct { const char *name; void *fn; } hle_ent;
#define HLE(mangled, ret, cname, ...) \
static ret cname(__VA_ARGS__); \
__attribute__((used, section("__DATA,swhle"))) static const hle_ent hle_ent_##cname = {mangled, (void *)cname}; \
__attribute__((used, DM_SECT("swhle"))) static const hle_ent hle_ent_##cname = {mangled, (void *)cname}; \
static ret cname(__VA_ARGS__)
typedef uint32_t Result; // nn::Result:w0,0 = 成功 | nn::Result: w0, 0 = success
@@ -39,7 +39,7 @@ void guest_clock_freeze_for(int reason, int on); // 按原因冻结(1 后台
typedef struct { const char *name; void *fn; const char *why; } hle_force_ent;
#define HLE_FORCE(mangled, why, ret, cname, ...) \
static ret cname(__VA_ARGS__); \
__attribute__((used, section("__DATA,swforce"))) static const hle_force_ent hle_force_##cname = {mangled, (void *)cname, why}; \
__attribute__((used, DM_SECT("swforce"))) static const hle_force_ent hle_force_##cname = {mangled, (void *)cname, why}; \
static ret cname(__VA_ARGS__)
// 运行模式(0 掌机 / 1 主机):hle_oe.c 持有,hid 的手柄样式跟它走;前端可在运行中切换
+133 -1
View File
@@ -7,7 +7,28 @@
// iOS defaults to real audio output (the product must have sound), tests that want silence set DM_AUDIO=0 explicitly; Mac defaults to the silent sink (replay / gate checks are silent), DM_AUDIO=1 for real audio output.
// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and only writes the front part of the structs.
#include "hle.h"
#if defined(__APPLE__)
#include <AudioToolbox/AudioToolbox.h>
#elif defined(__ANDROID__)
// Android:出声端 = AAudio 流(数据回调拉同一条待播队列);句柄借 AudioUnit 这个名字,开 / 起 / 停 / 关见下方 au_open 一节
// Android: the output = an AAudio stream (its data callback pulls the same pending queue); the handle borrows the AudioUnit name, open / start / stop / close are in the au_open section below
#include <aaudio/AAudio.h>
typedef AAudioStream *AudioUnit;
typedef int OSStatus;
static OSStatus AudioOutputUnitStart(AudioUnit au);
static OSStatus AudioOutputUnitStop(AudioUnit au);
#define AudioUnitUninitialize(au) 0
#define AudioComponentInstanceDispose(au) AAudioStream_close(au)
#else
// Linux:真出声后端没接,只有静音接收端;AudioUnit 句柄恒空,下列调用不会走到
// Linux: no real audio backend, only the silent sink; the AudioUnit handle is always null and the calls below are never reached
typedef void *AudioUnit;
typedef int OSStatus;
#define AudioOutputUnitStart(au) 0
#define AudioOutputUnitStop(au) 0
#define AudioUnitUninitialize(au) 0
#define AudioComponentInstanceDispose(au) 0
#endif
#include <TargetConditionals.h>
#include <dispatch/dispatch.h>
#include <stdatomic.h>
@@ -27,6 +48,11 @@ typedef struct {
gbuf *rel[RELMAX]; _Atomic uint32_t rel_head, rel_tail; // 已释放:出声端写,游戏侧读 | Released: written by the output side, read by the game side
uint64_t pos; // 当前块已播字节 | Bytes already played of the current block
AudioUnit au;
#if defined(__ANDROID__)
int out_ch; // 流的声道数:设备收原声道数就等于 ch,否则 2(回调里自己下混) | the stream's channel count: equal to ch when the device takes the original count, otherwise 2 (downmixed in the callback)
int16_t *mix; // 下混用的暂存(ch 声道) | scratch for downmixing (ch channels)
_Atomic int lost; // 设备断开(换耳机 / 蓝牙):等普通线程重开 | device disconnected (headphones / Bluetooth switch): waiting for an ordinary thread to reopen
#endif
pthread_t null_th; _Atomic int null_run;
dispatch_semaphore_t notify_sem;
pthread_t notify_th; _Atomic int notify_run, notify_pending, notify_armed;
@@ -89,6 +115,7 @@ static void pull(aout *a, uint8_t *dst, uint64_t n) {
static _Atomic uint64_t g_render_calls; // 声卡回调累计(生命周期验证:恢复后须继续增长) | Cumulative sound card callbacks (lifecycle verification: must keep growing after resume)
uint64_t dm_audio_render_calls(void) { return atomic_load_explicit(&g_render_calls, memory_order_relaxed); }
#if defined(__APPLE__)
static OSStatus au_render(void *ctx, AudioUnitRenderActionFlags *f, const AudioTimeStamp *ts, UInt32 bus, UInt32 frames, AudioBufferList *bl) {
(void)f; (void)ts; (void)bus; (void)frames;
aout *a = ctx;
@@ -115,6 +142,97 @@ static void au_open(aout *a) {
AudioUnitSetProperty(a->au, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &cb, sizeof cb) ||
AudioUnitInitialize(a->au)) die("AudioUnit 设置失败");
}
#elif defined(__ANDROID__)
// AAudio:48 kHz PCM16,先按游戏的声道数(常见 6)开;设备不收就开双声道,回调里按 ITU 系数把 5.1 下混成立体声
// AAudio: 48 kHz PCM16, opened first with the game's channel count (usually 6); if the device refuses, open stereo and downmix 5.1 to stereo with ITU coefficients in the callback
enum { MIX_FRAMES = 1024 };
static void downmix(const int16_t *in, int16_t *out, int frames, int ch) {
for (int i = 0; i < frames; i++, in += ch, out += 2) {
float l = in[0], r = ch > 1 ? in[1] : in[0];
if (ch >= 6) { float c = in[2] * .7071f; l += c + in[4] * .7071f; r += c + in[5] * .7071f; } // FL FR C LFE SL SR;低音声道不混 | FL FR C LFE SL SR; the LFE channel is not mixed in
else if (ch >= 4) { l += in[2] * .7071f; r += in[3] * .7071f; }
if (ch >= 4) { l *= .5858f; r *= .5858f; } // 1/(1+.7071+.7071):不削波 | 1/(1+.7071+.7071): no clipping
out[0] = (int16_t)(l > 32767 ? 32767 : l < -32768 ? -32768 : l); out[1] = (int16_t)(r > 32767 ? 32767 : r < -32768 ? -32768 : r);
}
}
static aaudio_data_callback_result_t au_render(AAudioStream *st, void *ctx, void *data, int32_t frames) {
(void)st; aout *a = ctx;
atomic_fetch_add_explicit(&g_render_calls, 1, memory_order_relaxed);
if (a->out_ch == a->ch) { pull(a, data, (uint64_t)frames * 2 * a->ch); return AAUDIO_CALLBACK_RESULT_CONTINUE; }
int16_t *out = data;
while (frames > 0) { int n = frames < MIX_FRAMES ? frames : MIX_FRAMES;
pull(a, (uint8_t *)a->mix, (uint64_t)n * 2 * a->ch); downmix(a->mix, out, n, a->ch);
out += n * 2; frames -= n; }
return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
static void au_reopen(aout *a);
static void *null_sink(void *p);
// 设备断开(拔耳机、切蓝牙):AAudio 的回调线程里不许关流重开,交给一条普通线程 | device disconnected (headphones unplugged, Bluetooth switched): the stream must not be closed / reopened on AAudio's callback thread, hand it to an ordinary thread
static void *au_reopen_th(void *p) { au_reopen(p); return NULL; }
static void au_error(AAudioStream *st, void *ctx, aaudio_result_t err) {
(void)st; aout *a = ctx;
LOG("【红】AAudio 出错 %d(%s):换设备重开", err, AAudio_convertResultToText(err));
if (atomic_exchange(&a->lost, 1)) return;
pthread_t t; if (!pthread_create(&t, NULL, au_reopen_th, a)) pthread_detach(t);
}
static AAudioStream *au_stream(aout *a, int ch, int low_latency) {
AAudioStreamBuilder *b; AAudioStream *st = NULL;
if (AAudio_createStreamBuilder(&b) != AAUDIO_OK) return NULL;
AAudioStreamBuilder_setDirection(b, AAUDIO_DIRECTION_OUTPUT);
AAudioStreamBuilder_setSharingMode(b, AAUDIO_SHARING_MODE_SHARED);
AAudioStreamBuilder_setSampleRate(b, RATE); AAudioStreamBuilder_setChannelCount(b, ch);
AAudioStreamBuilder_setFormat(b, AAUDIO_FORMAT_PCM_I16);
AAudioStreamBuilder_setUsage(b, AAUDIO_USAGE_GAME); AAudioStreamBuilder_setContentType(b, AAUDIO_CONTENT_TYPE_MUSIC);
AAudioStreamBuilder_setPerformanceMode(b, low_latency ? AAUDIO_PERFORMANCE_MODE_LOW_LATENCY : AAUDIO_PERFORMANCE_MODE_NONE);
AAudioStreamBuilder_setDataCallback(b, au_render, a); AAudioStreamBuilder_setErrorCallback(b, au_error, a);
if (AAudioStreamBuilder_openStream(b, &st) != AAUDIO_OK) st = NULL;
AAudioStreamBuilder_delete(b);
// 系统可能悄悄改格式(重采样到别的率、改声道):不是要的就不用 | the system may silently change the format (resample to another rate, change channels): reject it if it is not what was asked for
if (st && (AAudioStream_getSampleRate(st) != RATE || AAudioStream_getChannelCount(st) != ch || AAudioStream_getFormat(st) != AAUDIO_FORMAT_PCM_I16)) { AAudioStream_close(st); st = NULL; }
return st;
}
static int au_try_open(aout *a) {
for (int lat = 1; lat >= 0; lat--) {
if ((a->au = au_stream(a, a->ch, lat))) { a->out_ch = a->ch; break; }
if (a->ch != 2 && (a->au = au_stream(a, 2, lat))) { a->out_ch = 2; break; }
}
if (!a->au) return 0;
if (a->out_ch != a->ch && !a->mix) a->mix = malloc((size_t)MIX_FRAMES * 2 * a->ch);
int burst = AAudioStream_getFramesPerBurst(a->au);
if (burst > 0) AAudioStream_setBufferSizeInFrames(a->au, burst * 4); // 4 个突发 ≈ 几毫秒:游戏自己有 FMOD 缓冲,这里少留防爆音 | 4 bursts ≈ a few ms: the game has its own FMOD buffering, keep a little here against crackles
LOG("AAudio 打开:48 kHz PCM16 声道 %d(游戏 %d%s)突发 %d 帧 性能模式 %d", a->out_ch, a->ch, a->out_ch != a->ch ? ",下混" : "", burst, AAudioStream_getPerformanceMode(a->au));
return 1;
}
static void au_open(aout *a) { if (!au_try_open(a)) LOG("【红】AAudio 打不开:用静音接收端"); }
static OSStatus au_wait(AudioUnit au, aaudio_stream_state_t want) {
aaudio_stream_state_t st = AAudioStream_getState(au), next;
for (int i = 0; i < 10 && st != want; i++) { // 超时不算失败(回前台时 STARTING 常要一百多毫秒):最多等 1 秒 | a timeout is not a failure (STARTING often takes 100+ ms when returning to foreground): wait up to 1 s
aaudio_result_t r = AAudioStream_waitForStateChange(au, st, &next, 100000000);
if (r == AAUDIO_OK) st = next; else if (r == AAUDIO_ERROR_TIMEOUT) st = AAudioStream_getState(au); else break; }
return st == want ? 0 : -1;
}
static OSStatus AudioOutputUnitStart(AudioUnit au) {
aaudio_result_t r = AAudioStream_requestStart(au); OSStatus st = r == AAUDIO_OK ? au_wait(au, AAUDIO_STREAM_STATE_STARTED) : -1;
if (st) LOG("AAudio 启动失败:%s,流状态 %s", AAudio_convertResultToText(r), AAudio_convertStreamStateToText(AAudioStream_getState(au)));
return st;
}
// 停要等回调真停:之后静音接收端接手同一条队列,两边不能同时拉 | stopping waits until callbacks have really stopped: afterwards the silent sink takes over the same queue, the two must not pull at once
static OSStatus AudioOutputUnitStop(AudioUnit au) { return AAudioStream_requestStop(au) == AAUDIO_OK ? au_wait(au, AAUDIO_STREAM_STATE_STOPPED) : -1; }
static void au_reopen(aout *a) {
pthread_mutex_lock(&g_aos_lock);
int live = 0; for (int i = 0; i < AOMAX; i++) live |= g_aos[i] == a;
if (live && a->au) {
AAudioStream_close(a->au); a->au = NULL; // 断开的流回调已停 | callbacks of a disconnected stream have stopped
if (!au_try_open(a)) { LOG("【红】AAudio 重开失败:改用静音接收端");
if (atomic_load(&a->state) == STATE_STARTED && !g_suspended) { atomic_store(&a->null_run, 1); pthread_create(&a->null_th, NULL, null_sink, a); } }
else if (atomic_load(&a->state) == STATE_STARTED && !g_suspended && AudioOutputUnitStart(a->au)) LOG("【红】AAudio 重开后启动失败");
}
atomic_store(&a->lost, 0);
pthread_mutex_unlock(&g_aos_lock);
}
#else
static void au_open(aout *a) { (void)a; die("Linux 宿主还没有真出声后端:用 DM_AUDIO=0(静音接收端)"); }
#endif
// 静音接收端:每 5 ms 按 48 kHz 实时消耗
// Silent sink: consumes in real time at 48 kHz every 5 ms
static void *null_sink(void *p) {
@@ -126,7 +244,12 @@ static void *null_sink(void *p) {
}
return NULL;
}
static int real_audio(void) { const char *e = getenv("DM_AUDIO"); return e ? atoi(e) != 0 : TARGET_OS_IPHONE; }
#if defined(__ANDROID__)
#define DM_AUDIO_DEFAULT 1 // Android App 同 iOS:缺省真出声 | Android app, like iOS: real audio by default
#else
#define DM_AUDIO_DEFAULT TARGET_OS_IPHONE
#endif
static int real_audio(void) { const char *e = getenv("DM_AUDIO"); return e ? atoi(e) != 0 : DM_AUDIO_DEFAULT; }
// AudioOutParameter = { int32 sampleRate; uint16 channelCount; uint16 _r; ... },0 = 系统默认(48 kHz / 2 声道)
// AudioOutParameter = { int32 sampleRate; uint16 channelCount; uint16 _r; ... }, 0 = system default (48 kHz / 2 channels)
@@ -187,6 +310,9 @@ HLE_FORCE("_ZN2nn5audio13CloseAudioOutEPNS0_8AudioOutE", "关闭音频输出", v
for (int i = 0; i < AOMAX; i++) if (g_aos[i] == a) g_aos[i] = NULL;
pthread_mutex_unlock(&g_aos_lock);
if (a->au) { AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); }
#if defined(__ANDROID__)
free(a->mix);
#endif
dispatch_release(a->notify_sem);
pthread_mutex_destroy(&a->m); free(a);
}
@@ -242,6 +368,12 @@ void dm_audio_suspend(int on) {
if (on) { AudioOutputUnitStop(a->au); atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); }
else { atomic_store_explicit(&a->null_run, 0, memory_order_release); pthread_join(a->null_th, NULL);
OSStatus st = AudioOutputUnitStart(a->au);
#if defined(__ANDROID__)
if (st) { // 后台期间流被系统收走(断开 / 起不来):关掉重开一次再起 | the stream was taken away by the system while in the background (disconnected / won't start): close, reopen once and start again
AAudioStream_close(a->au); a->au = NULL;
st = au_try_open(a) ? AudioOutputUnitStart(a->au) : -1;
LOG("AAudio 回前台重开%s", st ? "仍失败" : "后起来了"); }
#endif
if (st) { // 会话还被别人占着(通话没挂就切回游戏、打断结束时人还在别的 App):不致命,继续由静音接收端顶着,等下一次恢复再试 | The session is still held by someone else (switched back to the game with a call not yet hung up, or the user is still in another app when the interruption ends): not fatal, the silent sink keeps covering, and we retry at the next resume
LOG("【红】AudioUnit 恢复失败(状态 %d):保持静音接收端,等下次恢复重试", (int)st);
atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); failed = 1; } }
+13 -4
View File
@@ -110,7 +110,16 @@ static Result mount(const char *name, const char *dir, int ro) { return mount_ex
// APFS is case-insensitive by default, Horizon paths are case-sensitive: every component is looked up exactly by guest name.
// Ordinary host names are unchanged; only when a name collides on the host is a separate physical name chosen, with the guest name stored in an xattr.
// clonefile preserves xattr, so save Commit/remount needs no separate mapping table; enumeration must not leak physical aliases.
#if defined(__APPLE__)
#define FS_GUEST_NAME "org.d2rmobile.guest-name"
#else
// Linux:非特权进程只能写 user.* 命名空间;不跟随符号链接用 l* 版本,Darwin 的 position / options 参数丢弃
// Linux: unprivileged processes may only write the user.* namespace; not following symlinks uses the l* variants, Darwin's position / options arguments are dropped
#define FS_GUEST_NAME "user.d2rmobile.guest-name"
#define getxattr(p, k, v, n, pos, opt) lgetxattr(p, k, v, n)
#define setxattr(p, k, v, n, pos, opt) lsetxattr(p, k, v, n, 0)
#define removexattr(p, k, opt) lremovexattr(p, k)
#endif
static int guest_name(const char *parent, const char *physical, char *out, size_t n) {
char p[1280]; snprintf(p, sizeof p, "%s/%s", parent, physical);
ssize_t k = getxattr(p, FS_GUEST_NAME, out, n - 1, 0, XATTR_NOFOLLOW);
@@ -297,7 +306,7 @@ static void stash_seed_one(const char *save_dir, const char *name) {
// 标准级与专家级各一份,各判各的(游戏按角色类型选文件名,main+0x2ce1e8:DLC 类型标准 = ModernSharedStashSoftCoreV2、专家 = ModernSharedStashHardCoreV2;文件格式相同)
// One copy each for standard and hardcore, each judged on its own (the game picks the file name by character type, main+0x2ce1e8: DLC type standard = ModernSharedStashSoftCoreV2, hardcore = ModernSharedStashHardCoreV2; same file format)
static void stash_seed(const char *save_dir) {
const char *e = getenv("DM_STASH_SEED"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return; // iOS 上缺省开;Mac 宿主缺省关(对拍 / 存档事务这些闸门逐字节比存档目录,多出一个文件就红),要验时设 DM_STASH_SEED=1 | on by default on iOS; off by default on the Mac host (gate checks such as lockstep comparison / save transaction compare the save directory byte by byte, one extra file turns them red), set DM_STASH_SEED=1 to verify
const char *e = getenv("DM_STASH_SEED"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return; // iOS 上缺省开;Mac 宿主缺省关(对拍 / 存档事务这些闸门逐字节比存档目录,多出一个文件就红),要验时设 DM_STASH_SEED=1 | on by default on iOS; off by default on the Mac host (gate checks such as lockstep comparison / save transaction compare the save directory byte by byte, one extra file turns them red), set DM_STASH_SEED=1 to verify
stash_seed_one(save_dir, "ModernSharedStashSoftCoreV2"); stash_seed_one(save_dir, "ModernSharedStashHardCoreV2");
}
#else
@@ -308,7 +317,7 @@ static void stash_seed(const char *save_dir) { (void)save_dir; }
// Fallback for 「大字体」(Large Font) (settings key "Low Vision Mode"): if it is 1 in the settings file, change it back to 0. It switches the UI to the original game's low-vision layout profile, which our touch UI was never built for; it hangs after being turned on in the settings page.
// This item in the settings page is separately hidden by the UI overlay; this here guarantees that devices where it was already turned on recover on restart. Same switch as settings_seed (on by default on iOS, on the Mac host only with DM_TOUCH_DEFAULTS=1)
static void low_vision_off(const char *save_dir) {
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return;
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return;
char path[1200]; snprintf(path, sizeof path, "%s/Settings/Settings.json", save_dir); static char buf[65536]; FILE *f = fopen(path, "rb"); if (!f) return;
size_t n = fread(buf, 1, sizeof buf - 1, f); fclose(f); if (n == sizeof buf - 1) return; buf[n] = 0;
char *k = strstr(buf, "\"Low Vision Mode\""); if (!k) return; char *v = strchr(k + 17, ':'); if (!v) return; v++; while (*v == ' ' || *v == '\t') v++;
@@ -317,7 +326,7 @@ static void low_vision_off(const char *save_dir) {
if (ok && !rename(tmp, path)) LOG("设置兜底:「大字体」(Low Vision Mode)是开着的,已改回关"); else remove(tmp);
}
static void settings_seed(const char *save_dir) {
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE; if (!on) return;
const char *e = getenv("DM_TOUCH_DEFAULTS"); int on = e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT; if (!on) return;
static const char *kv[][2] = {{"\"Item Name Display\"", "1"}, {"\"Item Tooltip Hotkey Appender\"", "0"},
{"\"AutoMapMode\"", "2"}, {"\"AutoMap Open On Load\"", "1"}};
char dir[1100], path[1200]; snprintf(dir, sizeof dir, "%s/Settings", save_dir); snprintf(path, sizeof path, "%s/Settings.json", dir);
@@ -388,7 +397,7 @@ HLE_FORCE("_ZN2nn2fs13MountSaveDataEPKcRKNS_7account3UidE", "fsp-srv;存档
// iOS 上缺省写;Mac 宿主的对拍闸门(存档要和真机真值逐文件相同)不写
// Rule files for the loot filter (the game loads them at startup; dm_lootfilter.c registers this hook from a constructor; it is null in unit tests that link only hle_fs.c). Same switch as settings_seed:
// written by default on iOS; not written under the Mac host's parity gate (saves must match the device ground truth file by file)
{ const char *e = getenv("DM_TOUCH_DEFAULTS"); if (g_dm_mount_seed_hook && (e ? strcmp(e, "0") != 0 : TARGET_OS_IPHONE)) g_dm_mount_seed_hook(dd); }
{ const char *e = getenv("DM_TOUCH_DEFAULTS"); if (g_dm_mount_seed_hook && (e ? strcmp(e, "0") != 0 : DM_TOUCH_PRODUCT)) g_dm_mount_seed_hook(dd); }
return mount_ex(name, dd, 0, 1);
}
void (*g_dm_pre_commit_hook[4])(const char *workdir); // 提交前调(工作目录):宿主旁路文件按工作目录里的存档内容核对后再写([0] 个人仓库多页 dm_pages.c、[2] 百宝囊 dm_pouch.c、[1] 编年史仓库 dm_vault.c、[3] 秘境进度 dm_rift.c) | called before commit (working directory): host side files are checked against the save contents in the working directory before being written ([0] personal stash pages dm_pages.c, [2] pouch dm_pouch.c, [1] chronicle vault dm_vault.c, [3] rift progress dm_rift.c)
+34
View File
@@ -5,7 +5,30 @@
// Stop background threads (boot block prefetch), pause audio, suspend graphics (wait for in-flight NVN calls to end and drain GPU work), then _exit(0); a 1.5 s fallback goes straight to _exit(0).
// The default action also exits in about 0.08 s (exit code 143); the value of this function is stopping background threads in order, exit code 0, and giving the iOS lifecycle callback an entry.
#include "hle.h"
#if defined(__APPLE__)
#include <dispatch/dispatch.h>
#else
#include <pthread.h>
#include <time.h>
// Linux 无 GCD:兜底计时与 SIGTERM 收尾各用一个分离线程;信号处理器只往自管道写一个字节(异步信号安全)
// Linux has no GCD: the fallback timer and the SIGTERM wrap-up each use a detached thread; the signal handler only writes one byte to a self-pipe (async-signal-safe)
static void *shutdown_watchdog(void *arg) {
(void)arg; struct timespec ts = {1, 500000000}; while (nanosleep(&ts, &ts)) {}
LOG("【红】优雅退出 1.5 秒未完成,直接退出"); _exit(0);
}
static int g_term_pipe[2] = {-1, -1};
static void term_handler(int sig) { (void)sig; char c = 1; ssize_t r = write(g_term_pipe[1], &c, 1); (void)r; }
void dm_host_shutdown(const char *why);
static void *term_thread(void *arg) {
(void)arg; char c;
while (read(g_term_pipe[0], &c, 1) != 1) {}
dm_host_shutdown("SIGTERM"); return NULL;
}
static void spawn_detached(void *(*fn)(void *)) {
pthread_t t; pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
pthread_create(&t, &a, fn, NULL); pthread_attr_destroy(&a);
}
#endif
#include <stdatomic.h>
#include <signal.h>
#include <unistd.h>
@@ -15,8 +38,12 @@ void hlecount_flush(void);
void dm_host_shutdown(const char *why) {
static _Atomic int once; if (atomic_exchange(&once, 1)) return;
uint64_t t0 = now_ns(); LOG("收到 %s:优雅退出", why);
#if defined(__APPLE__)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1500 * NSEC_PER_MSEC), dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), ^{
LOG("【红】优雅退出 1.5 秒未完成,直接退出"); _exit(0); });
#else
spawn_detached(shutdown_watchdog);
#endif
tact_prefetch_stop();
granny_prof_dump();
hlecount_flush(); // DM_HLECOUNT:_exit 不走 atexit,这里写一份 | DM_HLECOUNT: _exit does not run atexit, write a copy here
@@ -26,9 +53,16 @@ void dm_host_shutdown(const char *why) {
_exit(0);
}
void dm_term_install(void) {
#if !defined(__APPLE__)
if (pipe(g_term_pipe)) return;
spawn_detached(term_thread);
struct sigaction sa = {0}; sa.sa_handler = term_handler; sa.sa_flags = SA_RESTART | SA_ONSTACK; sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, NULL);
#else
signal(SIGTERM, SIG_IGN); // 不走缺省动作:交给 GCD 信号源在普通线程上收尾 | do not take the default action: hand over to the GCD signal source to wrap up on an ordinary thread
static dispatch_source_t src;
src = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0));
dispatch_source_set_event_handler(src, ^{ dm_host_shutdown("SIGTERM"); });
dispatch_resume(src);
#endif
}
+10 -4
View File
@@ -133,7 +133,7 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
// 界面层与 Final Result 仍按输出尺寸(+0xee88 / +0xee8c)建,末端由游戏自己的放大着色器 ps_upsample_p 放回输出尺寸。
// 启动流程不调 0x8582f0,所以要主动调一次;调用点必须是游戏主线程取系统通知处——游戏自己处理模式切换的同一上下文
// (在出图 HLE 里调会自锁:渲染锁已被出图路径持有)。
// 缺省:iOS 0.75,Mac 宿主 1.0(画面闸门对 Switch 真值比);DM_3D_SCALE=0.5–1.0 覆盖。
// 缺省:iOS 0.75,安卓 0.8(3D 720 档),Mac 宿主 1.0(画面闸门对 Switch 真值比);DM_3D_SCALE=0.5–1.0 覆盖。
// 视觉尺子真值阶段(DM_NVN_RULER=1 的 A / B)强制 1.0,切到被测模式后才生效。
// 动态比例(系统降频看的是占用率,温控档位只是粗信号 → 按实际掉帧调):控制器吃出图线程报来的实际上屏间隔
// (与 perf.txt 同源),三级 配置值(0.75) → 0.72 → 0.70;下限 0.70(实看 0.65 有差别)。规则见 scale3d_ctl_step。
@@ -146,7 +146,7 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
// the UI layer and Final Result are still built at the output size (+0xee88 / +0xee8c), and at the end the game's own upscale shader ps_upsample_p brings it back to the output size.
// The boot flow does not call 0x8582f0, so it has to be called once actively; the call site must be where the game main thread fetches system notifications -- the same context in which the game itself handles mode switches
// (calling it in the present HLE self-deadlocks: the render lock is already held by the present path).
// Default: iOS 0.75, Mac host 1.0 (the screenshot gate compares against Switch ground truth); DM_3D_SCALE=0.5–1.0 overrides.
// Default: iOS 0.75, Android 0.8 (3D at the 720 level), Mac host 1.0 (the screenshot gate compares against Switch ground truth); DM_3D_SCALE=0.5–1.0 overrides.
// The visual ruler ground truth phase (A / B of DM_NVN_RULER=1) forces 1.0, it only takes effect after switching to the mode under test.
// Dynamic scale (system throttling looks at utilization, the thermal state is only a coarse signal → adjust by actual dropped frames): the controller consumes the actual present intervals reported by the present thread
// (same source as perf.txt), three levels configured value (0.75) → 0.72 → 0.70; lower limit 0.70 (0.65 is visibly different). For the rules see scale3d_ctl_step.
@@ -155,6 +155,12 @@ HLE_FORCE("_ZN2nn2oe20SetFocusHandlingModeENS0_17FocusHandlingModeE", "前后台
#include <TargetConditionals.h>
#define SCALE3D_MIN 0.70f
#define SCALE3D_MID 0.72f
// 安卓缺省 0.8:输出高 900 时 3D 目标高 720(掌机档),界面仍按 900 画 | Android default 0.8: with output height 900 the 3D target is 720 high (handheld level), the UI is still drawn at 900
#ifdef __ANDROID__
#define DM_3D_SCALE_ANDROID 0.8f
#else
#define DM_3D_SCALE_ANDROID 1.0f
#endif
// 纯函数控制器(单测 t_oe.c 直接喂序列):level 0 = 配置值,越大越低。安全阀:只在可感的掉帧时动。
// 窗:每累计 2 秒的上屏间隔一个窗,窗内帧率 = 上屏帧数 ÷ 间隔之和(被系统丢掉的帧不计数,那段时间落在下一张上屏帧的间隔里)。
// 降:连续两个窗的帧率都 < 目标 × 0.92(60 帧时 55.2)→ 降一级。
@@ -219,7 +225,7 @@ float dm_3d_scale_cur(void) { return atomic_load(&g_scale3d_cur); }
static void scale3d_tick(void) {
static float want_cfg = -1, cur = 1.0f; static module_t *main;
if (want_cfg < 0) {
const char *e = getenv("DM_3D_SCALE"); want_cfg = TARGET_OS_IPHONE ? 0.75f : 1.0f;
const char *e = getenv("DM_3D_SCALE"); want_cfg = TARGET_OS_IPHONE ? 0.75f : DM_3D_SCALE_ANDROID;
if (e) { char *end; float v = strtof(e, &end); if (end == e || *end || !(v >= 0.5f && v <= 1.0f)) die("DM_3D_SCALE 非法:%s(要求 0.5–1.0)", e); want_cfg = v; }
for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) main = &g_mod[i];
}
@@ -249,7 +255,7 @@ HLE_FORCE("_ZN2nn2oe25TryPopNotificationMessageEPj", "系统通知队列;前
// The resolution parameter bits live in the thread slot, and the game reads them on the thread that fetches notifications to change the render size (on receiving 31 "performance mode changed", from main+0xe10ddc; 30 only updates a flag).
// When they are read: each time the handler is entered, once after the first notification is fetched (0xe10d5c / 0xe10d60), and notifications fetched later in the loop still use the values from that read. So every time one is taken, the value due at this moment is written into the current thread's slot --
// writing only when 31 is taken is not enough: when 31 is queued behind another notification (e.g. focus 15), the parameter bits have already been read after fetching 15 (iOS app: the front end did not switch to 16:9, in the Mac host run 31 happened to be queued first).
if (ok) for (int i = 0; i < 2; i++) if (g_keyres[i]) pthread_setspecific(g_keyres[i], (void *)dm_game_res(i));
if (ok) for (int i = 0; i < 2; i++) if (g_keyres[i]) dm_slot_set(g_keyres[i], (void *)dm_game_res(i));
if (ok && *msg == MSG_PERFMODE) dm_uiscreen_res_reread();
if (ok) LOG("oe 通知被游戏取走:%u", *msg); // 状态变化很少,逐条打不刷屏 | state changes are rare, printing each one does not flood the log
return ok;
+1 -1
View File
@@ -5,7 +5,7 @@
#include <ctype.h>
#include <time.h>
typedef struct { const char *name; void *fn; } hle_ent;
#define L(n) __attribute__((used, section("__DATA,swhle"))) static const hle_ent hle_lib_##n = { #n, (void *)n };
#define L(n) __attribute__((used, DM_SECT("swhle"))) static const hle_ent hle_lib_##n = { #n, (void *)n };
L(memcpy) L(memset) L(memmove) L(memcmp) L(memchr) L(strlen) L(strnlen) L(strcmp) L(strncmp)
L(strcpy) L(strncpy) L(strcat) L(strncat) L(strchr) L(strrchr) L(strstr) L(strspn) L(strcspn)
L(strpbrk) L(strcasecmp) L(strncasecmp) L(atoi) L(atof) L(strtol) L(strtoul) L(strtoll) L(strtoull)
+54 -4
View File
@@ -28,6 +28,41 @@ static pthread_key_t key_value(unsigned i) {
case KEY_KASPECT: return g_keyaspect; default: return g_keyaspectui;
}
}
#ifndef __APPLE__
// Linux / Android:槽块挂在 tp[2](bionic TLS_SLOT_APP,留给应用、libc 不用);块随线程退出释放并清 tp[2]
// Linux / Android: the slot block hangs off tp[2] (bionic TLS_SLOT_APP, reserved for the app and unused by libc); the block is freed and tp[2] cleared when the thread exits
#define SLOT_N 16
static pthread_key_t g_slot_owner;
static pthread_once_t g_slot_once = PTHREAD_ONCE_INIT;
static void slot_free(void *p) {
uint64_t *tp = __builtin_thread_pointer();
if (tp[2] == (uint64_t)p) tp[2] = 0;
free(p);
}
static void slot_once(void) { if (pthread_key_create(&g_slot_owner, slot_free)) die("创建槽块键失败"); }
uint64_t *dm_slot_block(void) {
uint64_t *tp = __builtin_thread_pointer();
if (tp[2]) return (uint64_t *)tp[2];
pthread_once(&g_slot_once, slot_once);
uint64_t *b = calloc(SLOT_N, 8);
if (!b || pthread_setspecific(g_slot_owner, b)) die("分配槽块失败");
tp[2] = (uint64_t)b;
return b;
}
void dm_slot_set(pthread_key_t k, void *v) {
if (!k || k >= SLOT_N) die("槽号越界 %lu", (unsigned long)k);
dm_slot_block()[k] = (uint64_t)v;
}
static void create_keys(void) {
// 键号从 1 起(键页项为 0 视为没建)
// Key numbers start at 1 (a key page entry of 0 means "not created")
pthread_key_t *ks[] = {&g_key18, &g_keytls, &g_keytlr, &g_keygate, &g_keyres[0], &g_keyres[1], &g_keyaspect, &g_keyaspectui};
for (unsigned i = 0; i < 8; i++) *ks[i] = i + 1;
LOG("槽号 K18=%lu KTLS=%lu KTLR=%lu KGATE=%lu KRES0=%lu KRES1=%lu KASPECT=%lu KASPECTUI=%lu",
(unsigned long)g_key18, (unsigned long)g_keytls, (unsigned long)g_keytlr, (unsigned long)g_keygate,
(unsigned long)g_keyres[0], (unsigned long)g_keyres[1], (unsigned long)g_keyaspect, (unsigned long)g_keyaspectui);
}
#else
static void create_keys(void) {
if (pthread_key_create(&g_key18, NULL) || pthread_key_create(&g_keytls, NULL) ||
pthread_key_create(&g_keytlr, NULL) || pthread_key_create(&g_keygate, NULL)) die("创建宿主键失败");
@@ -38,15 +73,20 @@ static void create_keys(void) {
LOG("键号 K18=%lu KTLS=%lu KTLR=%lu KGATE=%lu KRES0=%lu KRES1=%lu KASPECT=%lu KASPECTUI=%lu",
g_key18, g_keytls, g_keytlr, g_keygate, g_keyres[0], g_keyres[1], g_keyaspect, g_keyaspectui);
}
#endif
// K 槽校验:pthread TSD 布局固定,槽 = tpidrro_el0 + 8*key
// K slot check: the pthread TSD layout is fixed, slot = tpidrro_el0 + 8*key
static void tsd_check(void) {
pthread_setspecific(g_key18, (void *)0x1234);
dm_slot_set(g_key18, (void *)0x1234);
#ifdef __APPLE__
uint64_t base; __asm__ volatile("mrs %0, tpidrro_el0" : "=r"(base));
#else
uint64_t base = ((uint64_t *)__builtin_thread_pointer())[2];
#endif
uint64_t off = *(uint64_t *)(g_mod[0].base + g_mod[0].key_page_off + g_mod[0].key_idx[KEY_K18] * 8);
if (((uint64_t *)(base & ~7ull))[off / 8] != 0x1234) die("TSD 布局不符");
pthread_setspecific(g_key18, 0);
dm_slot_set(g_key18, 0);
}
static void build_symhash(module_t *m);
@@ -154,8 +194,12 @@ static void read_layout(module_t *m, const char *dir) {
FILE *f = fopen(path, "r");
if (!f) die("open %s", path);
static const char *kn[8] = {"K18", "KTLS", "KTLR", "KGATE", "KRES0", "KRES1", "KASPECT", "KASPECTUI"};
char line[256], key[32]; unsigned long v; unsigned seen = 0;
char line[256], key[32], abi[32] = "apple"; unsigned long v, tp_off = 0; unsigned seen = 0;
while (fgets(line, sizeof line, f)) {
// 改写器 ABI(DM_ABI=android 出 linux-bionic,槽基址取 [tpidr_el0 + TP_SLOT_OFF]);Apple 产物没有这行
// Rewriter ABI (DM_ABI=android emits linux-bionic, slot base taken from [tpidr_el0 + TP_SLOT_OFF]); Apple outputs have no such line
if (sscanf(line, "# ABI %31s", abi) == 1) continue;
if (sscanf(line, "# TP_SLOT_OFF %lx", &tp_off) == 1) continue;
if (sscanf(line, "# %31s %lx", key, &v) != 2) die("%s: 产物是旧改写器出的,换成当前代号(dm/PRODUCT)的产物", path);
if (!strcmp(key, "PATCH_OFF")) m->patch_off = v;
else if (!strcmp(key, "KEY_PAGE_OFF")) m->key_page_off = v;
@@ -171,6 +215,11 @@ static void read_layout(module_t *m, const char *dir) {
}
}
fclose(f);
#ifdef __APPLE__
if (strcmp(abi, "apple")) die("%s: 产物 ABI 是 %s,Apple 宿主要 DM_ABI=apple 的产物", path, abi);
#else
if (strcmp(abi, "linux-bionic") || tp_off != 0x10) die("%s: 产物 ABI 是 %s(TP_SLOT_OFF %#lx),Android 宿主要 DM_ABI=android 的产物", path, abi, tp_off);
#endif
if (!m->patch_off || m->key_page_off % 0x4000 || m->key_page_size != 0x4000 || seen != 0xff)
die("%s: 产物是旧改写器出的,换成当前代号(dm/PRODUCT)的产物", path);
}
@@ -196,7 +245,8 @@ static void register_gates(module_t *m, const char *dir) {
if (sscanf(line, "%lx %15s %d %lx", &ret, kind, &arg, &orig) == 4) { gate_register((uint64_t)m->base + ret, kind, arg, orig); ng++; }
fclose(f);
}
LOG("%s: gates %d patch_off %#llx keys %lu/%lu/%lu/%lu", m->name, ng, m->patch_off, g_key18, g_keytls, g_keytlr, g_keygate);
LOG("%s: gates %d patch_off %#llx keys %lu/%lu/%lu/%lu", m->name, ng, m->patch_off,
(unsigned long)g_key18, (unsigned long)g_keytls, (unsigned long)g_keytlr, (unsigned long)g_keygate);
}
static void relocate(module_t *m) {
+16
View File
@@ -3,7 +3,9 @@
#include "dm.h"
#include "front.h"
#include <stdatomic.h>
#if defined(__APPLE__)
#include <sys/sysctl.h>
#endif
#include <sys/time.h>
#include <unistd.h>
void probe_install(void); void ticks_install(void); void hid_keys_init(void); void tact_prefetch_start(const char *outdir); void tact_chk_init(void); void stubs_report(void); void crash_install(void); void guest_thread_init(void); uint32_t svc_thread_main_init(void);
@@ -90,11 +92,25 @@ static void flags_init(void) {
// 启动时间线零点 = 进程创建时刻(sysctl KERN_PROC_PID 的 p_starttime,墙钟)换算到 now_ns 单调时基;Mac / iOS 同口径
// Zero point of the boot timeline = process creation time (p_starttime from sysctl KERN_PROC_PID, wall clock) converted to the now_ns monotonic time base; same definition on Mac / iOS
static uint64_t proc_start_mono_ns(void) {
#if !defined(__APPLE__)
// Linux:/proc/self/stat 第 22 字段 starttime(开机起的时钟滴答,含挂起)对 CLOCK_BOOTTIME 求进程年龄
// Linux: field 22 of /proc/self/stat, starttime (clock ticks since boot, including suspend), against CLOCK_BOOTTIME gives the process age
uint64_t mono = now_ns(); char b[1024] = {0};
FILE *f = fopen("/proc/self/stat", "r"); if (!f) return mono;
size_t n = fread(b, 1, sizeof b - 1, f); fclose(f); b[n] = 0;
char *p = strrchr(b, ')'); unsigned long long st = 0;
for (int i = 2; p && i < 22; i++) p = strchr(p + 1, ' '); // ')' 之后是第 3 字段 | field 3 follows ')'
if (!p || sscanf(p + 1, "%llu", &st) != 1) return mono;
struct timespec ts; clock_gettime(CLOCK_BOOTTIME, &ts);
int64_t age = (int64_t)ts.tv_sec * 1000000000ll + ts.tv_nsec - (int64_t)(st * 1000000000ull / (unsigned long long)sysconf(_SC_CLK_TCK));
return age > 0 ? mono - (uint64_t)age : mono;
#else
struct kinfo_proc kp; size_t n = sizeof kp; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
uint64_t mono = now_ns(); struct timeval tv; gettimeofday(&tv, NULL);
if (sysctl(mib, 4, &kp, &n, NULL, 0) || !n) return mono;
int64_t age = (int64_t)(tv.tv_sec - kp.kp_proc.p_starttime.tv_sec) * 1000000000ll + (tv.tv_usec - kp.kp_proc.p_starttime.tv_usec) * 1000ll;
return age > 0 ? mono - (uint64_t)age : mono;
#endif
}
// 宿主装载(与 UIKit / Metal 无关):读 NSO、重定位、强制接管、探针 / 拍门 / 按键、预取起跑。缺省在 main 里同步跑;
+6 -6
View File
@@ -132,16 +132,16 @@ $(B)/t_fs_case: t_fs_case.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B)
$(B)/t_romfs_validate: t_romfs_validate.c ../romfs_validate.c ../romfs_validate.h ../dm_i18n.c ../dm_i18n_tab.h | $(B)
clang -O1 -Wno-unused-function -I.. -o $@ t_romfs_validate.c ../romfs_validate.c ../dm_i18n.c
$(B)/t_hid_script: t_hid_script.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_script.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
$(B)/t_hid_script: t_hid_script.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../touch/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
clang -O1 -Wno-unused-function -I.. -I../../touch -o $@ t_hid_script.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../touch/dm_touch_controls.c -lm
$(B)/t_oe: t_oe.c ../hle_oe.c ../hle.h ../dm.h | $(B)
clang -O1 -Wno-unused-function -I.. -o $@ t_oe.c
$(B)/t_hid_receipt: t_hid_receipt.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../ios/Sources/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
clang -O1 -Wno-unused-function -I.. -I../../ios/Sources -o $@ t_hid_receipt.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../ios/Sources/dm_touch_controls.c -lm
$(B)/t_touch_mac: t_touch_mac.c ../touch_mac.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../../ios/Sources/dm_touch_controls.c ../../ios/Sources/dm_touch_controls.h ../../host/dm_input.h | $(B) # 测试 #include 了 touch_mac.c 与 dm_touch_controls.c,须列为依赖(漏列致改源不重编) | the test #includes touch_mac.c and dm_touch_controls.c, which must be listed as dependencies (omitting them means source changes do not trigger a rebuild)
clang -std=c11 -Wall -Wextra -Werror -I.. -I../../ios/Sources -o $@ t_touch_mac.c ../dm_cursor.c ../dm_hud.c -lm
$(B)/t_hid_receipt: t_hid_receipt.c t_touch_tick_stub.c ../hle_hid.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../touch_mac.c ../../touch/dm_touch_controls.c ../hle.h ../dm.h ../dm_input.h ../front.h | $(B)
clang -O1 -Wno-unused-function -I.. -I../../touch -o $@ t_hid_receipt.c t_touch_tick_stub.c ../dm_cursor.c ../dm_hud.c ../touch_mac.c ../../touch/dm_touch_controls.c -lm
$(B)/t_touch_mac: t_touch_mac.c ../touch_mac.c ../dm_cursor.c ../dm_hud.c ../dm_hud.h ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h ../../host/dm_input.h | $(B) # 测试 #include 了 touch_mac.c 与 dm_touch_controls.c,须列为依赖(漏列致改源不重编) | the test #includes touch_mac.c and dm_touch_controls.c, which must be listed as dependencies (omitting them means source changes do not trigger a rebuild)
clang -std=c11 -Wall -Wextra -Werror -I.. -I../../touch -o $@ t_touch_mac.c ../dm_cursor.c ../dm_hud.c -lm
$(B)/t_target_rank: t_target_rank.c ../hle_target.c ../dm.h | $(B)
clang -O1 -Wno-unused-function -I.. -o $@ t_target_rank.c ../hle_target.c
$(B)/t_rift_clock: t_rift_clock.c ../dm_rift.c ../dm_rift.h ../hle_os.c ../hle.h ../dm.h | $(B)
+1 -1
View File
@@ -2,7 +2,7 @@
#include <stdlib.h>
#include "../dm.h"
#include "../touch_mac.c"
#include "../../ios/Sources/dm_touch_controls.c"
#include "../../touch/dm_touch_controls.c"
uint64_t now_ns(void) { return 0; }
void (*dm_pad_hook)(uint64_t, uint64_t *, int32_t *, int32_t *, int32_t *, int32_t *);
+6 -6
View File
@@ -14,8 +14,8 @@ static pthread_once_t g_keyown_once = PTHREAD_ONCE_INIT;
static void own_free(void *p) { void **own = p; free(own[0]); free(own[1]); free(own); }
static void own_key_init(void) { if (pthread_key_create(&g_keyown, own_free)) die("创建线程本地块的释放键失败"); }
void guest_thread_init(void) {
pthread_setspecific(g_keygate, (void *)dm_gate);
for (int i = 0; i < 2; i++) if (g_keyres[i]) pthread_setspecific(g_keyres[i], (void *)dm_game_res(i)); // 分辨率参数位:{u32 宽, u32 高} 打包 | resolution parameter slot: {u32 width, u32 height} packed
dm_slot_set(g_keygate, (void *)dm_gate);
for (int i = 0; i < 2; i++) if (g_keyres[i]) dm_slot_set(g_keyres[i], (void *)dm_game_res(i)); // 分辨率参数位:{u32 宽, u32 高} 打包 | resolution parameter slot: {u32 width, u32 height} packed
if (g_keyaspect || g_keyaspectui) { // 宽高比上限参数位:max(19/9, 两种模式输出宽 / 高),float 位模式放低 32 位 | aspect ratio limit parameter slot: max(19/9, output width / height of the two modes), float bit pattern in the low 32 bits
float a = 19.0f / 9.0f; int wide = 0;
for (int i = 0; i < 2; i++) { uint64_t r = front_game_res(i); float w = (float)(uint32_t)r, h = (float)(uint32_t)(r >> 32); if (h > 0 && w / h > a) { a = w / h; wide = 1; } }
@@ -29,10 +29,10 @@ void guest_thread_init(void) {
// Not a magic number: when the screen height grows the margin stays proportional (delta is relative to screen height)
float ui = wide ? a + 0.15f : a;
uint32_t bits;
if (g_keyaspect) { memcpy(&bits, &a, 4); pthread_setspecific(g_keyaspect, (void *)(uintptr_t)bits); }
if (g_keyaspectui) { memcpy(&bits, &ui, 4); pthread_setspecific(g_keyaspectui, (void *)(uintptr_t)bits); }
if (g_keyaspect) { memcpy(&bits, &a, 4); dm_slot_set(g_keyaspect, (void *)(uintptr_t)bits); }
if (g_keyaspectui) { memcpy(&bits, &ui, 4); dm_slot_set(g_keyaspectui, (void *)(uintptr_t)bits); }
}
pthread_setspecific(g_key18, 0);
dm_slot_set(g_key18, 0);
// 这两块随线程退出释放。客体会改写 TLS / 线程本地区这两把键的槽(它自己设线程指针),所以不能按键里的当前值去 free:
// 申请到的原始指针另记在本文件自己的键 g_keyown 上,由它的析构放(键析构在 pthread_exit 时调用,同信号备用栈 crash.c altstack_free;
// 析构里只有 free,客体线程的小栈上也安全)。原先不放:游戏频繁起短命线程,每条漏 8192 + 0x200 + 0x400 = 9728 字节。
@@ -44,5 +44,5 @@ void guest_thread_init(void) {
void **own = calloc(2, sizeof *own); uint8_t *tlr = calloc(1, TLR_SIZE + THREAD_OBJ_SIZE);
own[0] = calloc(1, TLS_SIZE); own[1] = tlr;
*(void **)(tlr + 0x1f8) = tlr + TLR_SIZE; // 当前线程对象 | current thread object
pthread_once(&g_keyown_once, own_key_init); pthread_setspecific(g_keytls, own[0]); pthread_setspecific(g_keytlr, tlr); pthread_setspecific(g_keyown, own);
pthread_once(&g_keyown_once, own_key_init); dm_slot_set(g_keytls, own[0]); dm_slot_set(g_keytlr, tlr); pthread_setspecific(g_keyown, own);
}
+1 -1
View File
@@ -3,7 +3,7 @@
#include "dm_cursor.h"
#include "dm_actions.h"
#include "dm_hud.h"
#include "../ios/Sources/dm_touch_controls.h"
#include "../touch/dm_touch_controls.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-1
View File
@@ -7,4 +7,3 @@ RomfsDownloader/RomfsDownloader.entitlements
local.env
# 由原版图 / 表生成的(构建时从玩家自己的游戏文件生成,不进仓库;tools/gen_assets.py)
Sources/TouchArt/dm_native_*.png
Sources/dm_touch_native_art.c
+1 -1
View File
@@ -21,7 +21,7 @@ No mod is used; it goes through the overlay RomFS (a small set of assets generat
In the skill area on the right, the game's five original skill buttons still occupy their places in the layout, and the skill circles the shell draws with UIKit are stacked on top of them (`../Sources/DmTouchOverlay.m`). The experience bar, the difficulty number and the selection strip are also drawn by this layer, with art and geometry generated at build time.
What a finger tap on these widgets counts as is decided by the layout in `../Sources/dm_touch_controls.c` (`dm_tc_layout_make`): it converts the tap areas onto the same set of seven slots according to the screen height, aligned with the picture.
What a finger tap on these widgets counts as is decided by the layout in `../../touch/dm_touch_controls.c` (`dm_tc_layout_make`): it converts the tap areas onto the same set of seven slots according to the screen height, aligned with the picture.
## What is in this directory
+1 -1
View File
@@ -21,7 +21,7 @@ English: [README.md](README.md)
右侧技能区里,游戏原版的五个技能钮仍在布局里占着位置,外壳用 UIKit 画的技能圈叠在它们上面(`../Sources/DmTouchOverlay.m`)。经验条、难度数字和选择条也由这一层画,素材与几何在构建时生成。
手指点在这些部件上算什么,由 `../Sources/dm_touch_controls.c` 的布局决定(`dm_tc_layout_make`):它按屏幕高度把点击区换算到同一组七格上,和画面对齐。
手指点在这些部件上算什么,由 `../../touch/dm_touch_controls.c` 的布局决定(`dm_tc_layout_make`):它按屏幕高度把点击区换算到同一组七格上,和画面对齐。
## 这个目录里有什么
+5 -5
View File
@@ -66,7 +66,7 @@ Only those 18 archive files are checked: the configuration file used is the one
The Switch version of the game only recognizes two kinds of input, the gamepad and the touch screen. The shell translates finger actions into these two, plus direct clicks on the game UI.
- **Collection**: `DmMetalView` in `front_ios.m` receives all `UITouch` objects in one place.
- **Classification**: `Sources/dm_touch_controls.c` is a pure C state machine with no dependency on UIKit (`dm_tc_*`): which finger belongs to the stick, a skill button, a belt slot or the UI, what a tap / double tap / long press / drag and drop each count as, and as output the gamepad buttons that should currently be pressed and the values of the left and right sticks. It can be unit-tested without a device (see "Unit tests").
- **Classification**: `../touch/dm_touch_controls.c` is a pure C state machine with no dependency on UIKit (`dm_tc_*`): which finger belongs to the stick, a skill button, a belt slot or the UI, what a tap / double tap / long press / drag and drop each count as, and as output the gamepad buttons that should currently be pressed and the values of the left and right sticks. It can be unit-tested without a device (see "Unit tests").
- **Publication**: on every state change, `pushFrom:phase:` of `DmMetalView` hands the results to the host together: `dm_touch_set` (raw touch points, for the game to read as the touch screen), `dm_cursor_set_screen` (UI cursor position), `dm_input_set` (gamepad buttons and sticks). The host applies them when the game reads the gamepad (`dm/host/hle_hid.c`, `dm/host/dm_cursor.c`).
There are three cases depending on which UI the game is currently in. Switching between them is driven by the UI messages the game itself emits (`dm_tc_navigation`), not by guessing:
@@ -82,7 +82,7 @@ There are three cases depending on which UI the game is currently in. Switching
The principle is to use the game's own UI widgets as far as possible; the shell only adds the layer the game does not have:
- The life orb, mana orb, belt, town portal and feature entry of the **bottom bar** are the game's original HUD widgets; only their positions and scale are changed, through a layout file in the overlay. The experience bar and the numbers on the slots are drawn by the shell. See [NativeHUD/README.md](NativeHUD/README.md) for details.
- The **stick and skill buttons** are drawn on top of the game picture with UIKit by `Sources/DmTouchOverlay.m`. This layer only draws and does not receive touches. The icons on the skill buttons come from the game's skill atlas, and which skill is currently bound is read, read-only, from the running game by `Sources/dm_touch_game_bridge.c`.
- The **stick and skill buttons** are drawn on top of the game picture with UIKit by `Sources/DmTouchOverlay.m`. This layer only draws and does not receive touches. The icons on the skill buttons come from the game's skill atlas, and which skill is currently bound is read, read-only, from the running game by `../touch/dm_touch_game_bridge.c`.
- The **panels** are all the game's original panels. The overlay moves the gamepad button hints of the original layout off screen, adds a close button to the panels, and replaces gamepad wording in hint texts with touch wording (`tools/touch_layout.py`, `tools/touch_strings.py`).
### Overlay RomFS
@@ -116,9 +116,9 @@ The GPUs of these models do not support the BC compression formats the game's te
| `local.env.example` | Sample local configuration |
| `Sources/main.m` | App entry point: modes, logging, locating assets, starting the host, lifecycle |
| `Sources/front_ios.m` | iOS implementation of the host front end: Metal view, touch collection and publication, touch scripts, test switches such as screenshots |
| `Sources/dm_touch_controls.[ch]` | Touch classification state machine (pure C) |
| `../touch/dm_touch_controls.[ch]` | Touch classification state machine (pure C) |
| `Sources/DmTouchOverlay.[hm]` | Self-drawn controls such as the stick and skill buttons |
| `Sources/dm_touch_game_*.c` | Reads the skill bindings from the running game (read-only) |
| `../touch/dm_touch_game_*.c` | Reads the skill bindings from the running game (read-only) |
| `Sources/asset_dl.[hm]`, `cloud_ios.m`, `dm_update.m`, `dm_sharelog.m` | Asset download, iCloud save sync, version notice, sharing the diagnostic log |
| `Sources/TouchArt/` | Art for the self-drawn controls. The repository holds only the stick image and the source manifest of the skill atlas (original paths and checksums); the skill atlas itself is generated from the game files at build time |
| `NativeHUD/` | Bottom bar documentation and the self-drawn close button image |
@@ -263,7 +263,7 @@ No device is needed, and the app is not launched. Contents:
- The behaviours of the touch classification state machine `dm_touch_controls.c` (`t_touch_controls.c`, `t_skill_aim.c`, `t_joy_travel.c`, `t_portal_sequence.c`).
- Parsing and reading of the skill bindings (`t_native_binding.c`, `t_game_bridge.c`, `t_binding_*.c`, `t_native_hud_*.c`), using the two fixtures in [tests/fixtures/native_binding/](tests/fixtures/native_binding/README.md). The public repository does not ship these two fixtures: without them, the three tests that read them are skipped automatically and the rest run as usual.
- The skill atlas index (`t_native_art.c`, `test_native_art_capture.py`). This item needs the game files on your machine: the skill index `Sources/dm_touch_native_art.c` is not kept in the repository, and when it is missing it is generated on the spot from `DM_ROMFS_SRC` (default `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`).
- The skill atlas index (`t_native_art.c`, `test_native_art_capture.py`). This item needs the game files on your machine: the skill index `../touch/dm_touch_native_art.c` is not kept in the repository, and when it is missing it is generated on the spot from `DM_ROMFS_SRC` (default `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`).
- A few Python scripts that check the wiring of the touch path in `front_ios.m` and the format of the diagnostic log.
Under `tools/` there are also self-tests that come with a few of the scripts: `devlock_test.sh`, `devlock_max_test.sh`, `devlock_locale_test.sh` (device lock), `devbattery_test.sh` (battery check).
+5 -5
View File
@@ -66,7 +66,7 @@ iOS 不允许普通 App 执行运行时才写进内存的代码,所以游戏
游戏的 Switch 版只认手柄和触摸屏两种输入,外壳把手指动作翻译成这两样,再加上直接对游戏界面的点击。
- **收集**:`front_ios.m` 的 `DmMetalView` 统一接收全部 `UITouch`。
- **判定**:`Sources/dm_touch_controls.c` 是一份不依赖 UIKit 的纯 C 状态机(`dm_tc_*`):哪根手指属于摇杆、技能钮、腰带格还是界面,点按 / 双击 / 长按 / 拖放各算什么,输出当前该按下的手柄键和左右摇杆的值。它可以脱离设备做单元测试(见「单测」)。
- **判定**:`../touch/dm_touch_controls.c` 是一份不依赖 UIKit 的纯 C 状态机(`dm_tc_*`):哪根手指属于摇杆、技能钮、腰带格还是界面,点按 / 双击 / 长按 / 拖放各算什么,输出当前该按下的手柄键和左右摇杆的值。它可以脱离设备做单元测试(见「单测」)。
- **发布**:每次状态变化,`DmMetalView` 的 `pushFrom:phase:` 把结果一起交给宿主:`dm_touch_set`(原始触点,供游戏读触摸屏)、`dm_cursor_set_screen`(界面光标位置)、`dm_input_set`(手柄键与摇杆)。宿主在游戏读手柄时把它们落地(`dm/host/hle_hid.c`、`dm/host/dm_cursor.c`)。
按游戏当前所处的界面分三种情况,由游戏自己发出的界面消息驱动切换(`dm_tc_navigation`),不靠猜:
@@ -82,7 +82,7 @@ iOS 不允许普通 App 执行运行时才写进内存的代码,所以游戏
原则是尽量用游戏自己的界面部件,外壳只补游戏没有的那一层:
- **底栏**的血球、蓝球、腰带、回城、功能入口是游戏原版的 HUD 部件,只通过覆盖层里的布局文件改了位置与缩放;经验条和格子上的数字由外壳画。详见 [NativeHUD/README.zh-CN.md](NativeHUD/README.zh-CN.md)。
- **摇杆与技能钮**由 `Sources/DmTouchOverlay.m` 用 UIKit 画在游戏画面上面。这一层只画不收触点。技能钮上的图标取自游戏的技能图集,当前绑的是哪个技能由 `Sources/dm_touch_game_bridge.c` 从运行中的游戏只读地取出来。
- **摇杆与技能钮**由 `Sources/DmTouchOverlay.m` 用 UIKit 画在游戏画面上面。这一层只画不收触点。技能钮上的图标取自游戏的技能图集,当前绑的是哪个技能由 `../touch/dm_touch_game_bridge.c` 从运行中的游戏只读地取出来。
- **面板**全部是游戏原版的面板。覆盖层把原版布局里的手柄键位提示挪出屏幕、给面板加上关闭按钮、把提示文字里的手柄说法换成触摸说法(`tools/touch_layout.py`、`tools/touch_strings.py`)。
### 覆盖层 RomFS
@@ -116,9 +116,9 @@ iOS 不允许普通 App 执行运行时才写进内存的代码,所以游戏
| `local.env.example` | 本机配置样例 |
| `Sources/main.m` | App 入口:模式、日志、找资源、启动宿主、生命周期 |
| `Sources/front_ios.m` | 宿主前端的 iOS 实现:Metal 视图、触摸收集与发布、触点脚本、截图等测试开关 |
| `Sources/dm_touch_controls.[ch]` | 触摸判定状态机(纯 C) |
| `../touch/dm_touch_controls.[ch]` | 触摸判定状态机(纯 C) |
| `Sources/DmTouchOverlay.[hm]` | 摇杆、技能钮等自绘控件 |
| `Sources/dm_touch_game_*.c` | 从运行中的游戏读取技能绑定(只读) |
| `../touch/dm_touch_game_*.c` | 从运行中的游戏读取技能绑定(只读) |
| `Sources/asset_dl.[hm]`、`cloud_ios.m`、`dm_update.m`、`dm_sharelog.m` | 资源下载、iCloud 存档同步、版本提示、分享诊断日志 |
| `Sources/TouchArt/` | 自绘控件的素材。仓库里只有摇杆图和技能图集的来源清单(原版路径与校验值);技能图集本身在构建时从游戏文件生成 |
| `NativeHUD/` | 底栏说明与自己画的关闭按钮图 |
@@ -263,7 +263,7 @@ make -C dm/ios/tests test
- 触摸判定状态机 `dm_touch_controls.c` 的各项行为(`t_touch_controls.c`、`t_skill_aim.c`、`t_joy_travel.c`、`t_portal_sequence.c`)。
- 技能绑定的解析与读取(`t_native_binding.c`、`t_game_bridge.c`、`t_binding_*.c`、`t_native_hud_*.c`),用到 [tests/fixtures/native_binding/](tests/fixtures/native_binding/README.zh-CN.md) 里的两份夹具。公开仓库不带这两份夹具:缺了的话,读它们的三个测试自动跳过,其余照常。
- 技能图集索引(`t_native_art.c`、`test_native_art_capture.py`)。这一项需要本机有游戏文件:技能索引 `Sources/dm_touch_native_art.c` 不进仓库,缺了会从 `DM_ROMFS_SRC`(缺省 `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`)现生成。
- 技能图集索引(`t_native_art.c`、`test_native_art_capture.py`)。这一项需要本机有游戏文件:技能索引 `../touch/dm_touch_native_art.c` 不进仓库,缺了会从 `DM_ROMFS_SRC`(缺省 `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`)现生成。
- 几份 Python 脚本,核对 `front_ios.m` 里触摸通路的接线和诊断日志格式。
`tools/` 下还有几个脚本自带的自测:`devlock_test.sh`、`devlock_max_test.sh`、`devlock_locale_test.sh`(设备锁)、`devbattery_test.sh`(电量检查)。
+2 -1
View File
@@ -14,9 +14,10 @@ targets:
- name: 从游戏文件生成资源
basedOnDependencyAnalysis: false
script: |
[ -f "$SRCROOT/Gen/assets/NativeHUD/v4/hud.json" ] && [ -f "$SRCROOT/Sources/dm_touch_native_art.c" ] || python3 "$SRCROOT/tools/gen_assets.py"
[ -f "$SRCROOT/Gen/assets/NativeHUD/v4/hud.json" ] && [ -f "$SRCROOT/../touch/dm_touch_native_art.c" ] || python3 "$SRCROOT/tools/gen_assets.py"
sources:
- Sources
- ../touch # 跨平台触控模块(纯 C,Android 共用) | Cross-platform touch module (pure C, shared with Android)
- Assets.xcassets # App 图标(1024²、不透明;TestFlight 上传必需) | App icon (1024², opaque; required for TestFlight upload)
- path: Gen/assets/NativeHUD/v4/hud_v4_ui # 底部 UI v4 的 UIKit 素材(run.sh build 由 tools/gen_hud_v4.py 从游戏文件生成:几何、字形、难度数字、选择条格子) | UIKit art for bottom UI v4 (generated from game files by tools/gen_hud_v4.py during run.sh build: geometry, glyphs, difficulty digits, selection bar cells)
type: folder
+24 -24
View File
@@ -13,35 +13,35 @@ fixture_test = $(if $(HAVE_BINDING_FIXTURES),./$(1) $(BINDING_FIXTURES),@echo "
.PHONY: all run test clean
all: $(TARGET) $(BINDING_TARGETS) t_native_art t_skill_aim t_joy_travel $(METAL_CACHE_TARGET)
run: test
$(TARGET): t_touch_controls.c $(wildcard ../Sources/dm_touch_controls.[ch]) ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_touch_controls.c ../Sources/dm_touch_controls.c -lm -o $@
t_native_binding: t_native_binding.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_native_binding.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_controls.c -lm -o $@
t_game_bridge: t_game_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -DDM_TG_TEST_SYNTHETIC_IDENTITY -I../Sources t_game_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_state.c -lpthread -o $@
t_binding_freshness: t_binding_freshness.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_binding_freshness.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_controls.c -lm -o $@
t_portal_sequence: t_portal_sequence.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_portal_sequence.c ../Sources/dm_touch_controls.c -lm -o $@
t_binding_group: t_binding_group.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../Sources t_binding_group.c ../Sources/dm_touch_game_state.c -o $@
t_native_hud_identity: t_native_hud_identity.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../Sources t_native_hud_identity.c ../Sources/dm_touch_game_identity.c -o $@
t_native_hud_bridge: t_native_hud_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -I../Sources t_native_hud_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_state.c -lpthread -o $@
$(TARGET): t_touch_controls.c $(wildcard ../../touch/dm_touch_controls.[ch]) ../../host/dm_input.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_touch_controls.c ../../touch/dm_touch_controls.c -lm -o $@
t_native_binding: t_native_binding.c ../../touch/dm_touch_game_state.c ../../touch/dm_touch_game_state.h ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_native_binding.c ../../touch/dm_touch_game_state.c ../../touch/dm_touch_controls.c -lm -o $@
t_game_bridge: t_game_bridge.c ../../touch/dm_touch_game_bridge.c ../../touch/dm_touch_game_identity.c ../../touch/dm_touch_game_identity.h ../../touch/dm_touch_game_state.c ../../touch/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -DDM_TG_TEST_SYNTHETIC_IDENTITY -I../../touch -I../Sources t_game_bridge.c ../../touch/dm_touch_game_bridge.c ../../touch/dm_touch_game_identity.c ../../touch/dm_touch_game_state.c -lpthread -o $@
t_binding_freshness: t_binding_freshness.c ../../touch/dm_touch_game_state.c ../../touch/dm_touch_game_state.h ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_binding_freshness.c ../../touch/dm_touch_game_state.c ../../touch/dm_touch_controls.c -lm -o $@
t_portal_sequence: t_portal_sequence.c ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_portal_sequence.c ../../touch/dm_touch_controls.c -lm -o $@
t_binding_group: t_binding_group.c ../../touch/dm_touch_game_state.c ../../touch/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_binding_group.c ../../touch/dm_touch_game_state.c -o $@
t_native_hud_identity: t_native_hud_identity.c ../../touch/dm_touch_game_identity.c ../../touch/dm_touch_game_identity.h ../../touch/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_native_hud_identity.c ../../touch/dm_touch_game_identity.c -o $@
t_native_hud_bridge: t_native_hud_bridge.c ../../touch/dm_touch_game_bridge.c ../../touch/dm_touch_game_identity.c ../../touch/dm_touch_game_identity.h ../../touch/dm_touch_game_state.c ../../touch/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_native_hud_bridge.c ../../touch/dm_touch_game_bridge.c ../../touch/dm_touch_game_identity.c ../../touch/dm_touch_game_state.c -lpthread -o $@
# 技能图集 / 技能索引由原版表生成、不进仓库(tools/native_art/generate.py;dm/README.md「从你的游戏文件生成资源」)
# The skill atlas / skill index are generated from the original game's tables and are not kept in the repository (tools/native_art/generate.py; dm/README.md 「从你的游戏文件生成资源」(Generating assets from your game files))
ROMFS?=$(or $(DM_ROMFS_SRC),$(DM_ROOT)/data/switch/3.3.94012/Update/RomFS)
../Sources/dm_touch_native_art.c: ../tools/native_art/generate.py ../tools/native_art/implementation.c.inc ../Sources/TouchArt/native_art_manifest.json
../../touch/dm_touch_native_art.c: ../tools/native_art/generate.py ../tools/native_art/implementation.c.inc ../Sources/TouchArt/native_art_manifest.json
python3 ../tools/native_art/generate.py "$(ROMFS)"
t_native_art: t_native_art.c ../Sources/dm_touch_native_art.c ../Sources/dm_touch_native_art.h
$(CC) $(CFLAGS) -I../Sources t_native_art.c ../Sources/dm_touch_native_art.c -o $@
t_skill_aim: t_skill_aim.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_skill_aim.c ../Sources/dm_touch_controls.c -lm -o $@
t_joy_travel: t_joy_travel.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_joy_travel.c ../Sources/dm_touch_controls.c -lm -o $@
t_native_art: t_native_art.c ../../touch/dm_touch_native_art.c ../../touch/dm_touch_native_art.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_native_art.c ../../touch/dm_touch_native_art.c -o $@
t_skill_aim: t_skill_aim.c ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_skill_aim.c ../../touch/dm_touch_controls.c -lm -o $@
t_joy_travel: t_joy_travel.c ../../touch/dm_touch_controls.c ../../touch/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../../touch -I../Sources t_joy_travel.c ../../touch/dm_touch_controls.c -lm -o $@
t_metal_cache_guard: t_metal_cache_guard.c ../Sources/dm_metal_cache_guard.c ../Sources/dm_metal_cache_guard.h
$(CC) $(CFLAGS) -I../Sources t_metal_cache_guard.c ../Sources/dm_metal_cache_guard.c -o $@
$(CC) $(CFLAGS) -I../../touch -I../Sources t_metal_cache_guard.c ../Sources/dm_metal_cache_guard.c -o $@
test: $(TARGET) $(BINDING_TARGETS) t_native_art t_skill_aim t_joy_travel $(METAL_CACHE_TARGET)
./$(METAL_CACHE_TARGET)
./$(TARGET)
+1 -1
View File
@@ -8,7 +8,7 @@ For unit tests only. The app does not read these two files at run time, and the
## Background
The skill buttons on the right need to show "which skill this button is bound to right now". In the memory of the running game this information is two tables, which the shell fetches read-only and then parses (`../../../Sources/dm_touch_game_bridge.c` does the fetching, and `dm_tg_parse` in `../../../Sources/dm_touch_game_state.c` does the parsing):
The skill buttons on the right need to show "which skill this button is bound to right now". In the memory of the running game this information is two tables, which the shell fetches read-only and then parses (`../../../../touch/dm_touch_game_bridge.c` does the fetching, and `dm_tg_parse` in `../../../../touch/dm_touch_game_state.c` does the parsing):
- **Button mapping table**: for each of the six gamepad buttons (B, A, Y, X, R, ZR), which normal skill slot and which alternate skill slot it corresponds to. The alternate slots are the set used while ZL is held.
- **Binding table**: the skill ID bound in each skill slot; an empty slot is `0xFFFFFFFF`.
+1 -1
View File
@@ -8,7 +8,7 @@ English: [README.md](README.md)
## 背景
右侧技能钮上要显示「这个键现在绑着哪个技能」。这份信息在运行中的游戏内存里是两张表,外壳只读地取出来再解析(`../../../Sources/dm_touch_game_bridge.c` 负责取,`../../../Sources/dm_touch_game_state.c` 的 `dm_tg_parse` 负责解析):
右侧技能钮上要显示「这个键现在绑着哪个技能」。这份信息在运行中的游戏内存里是两张表,外壳只读地取出来再解析(`../../../../touch/dm_touch_game_bridge.c` 负责取,`../../../../touch/dm_touch_game_state.c` 的 `dm_tg_parse` 负责解析):
- **键位表**:六个手柄键(B、A、Y、X、R、ZR)各对应哪个普通技能槽、哪个替代技能槽。替代槽是按住 ZL 时用的那一套。
- **绑定表**:每个技能槽里绑着的技能编号,空槽是 `0xFFFFFFFF`。
+1 -1
View File
@@ -13,7 +13,7 @@ try:
# They guarded how the implementation is written, not behavior: who draws the bottom bar is guarded by the UI screenshots of the full regression table, and the touch-to-game protocol behavior is guarded by the C unit tests in this directory (t_native_binding / t_game_bridge / t_native_hud_bridge etc.) - deleted, not chasing the source text with edits.
# What remains is data consistency: the three hash constants compiled into the program, the manifest, the 12 textures and the two skill tables match the actual files.
manifest=json.loads((IOS/'Sources/TouchArt/native_art_manifest.json').read_text())
compiled=(IOS/'Sources/dm_touch_native_art.c').read_text()
compiled=(IOS.parent/'touch'/'dm_touch_native_art.c').read_text()
for name,target in [('dm_ta_manifest_sha',IOS/'Sources/TouchArt/native_art_manifest.json'),
('dm_ta_geometry_sha',IOS/'docs/native_art_v1_geometry.json'),
('dm_ta_binding_sha',IOS/'docs/touch_layout_spec_native_binding_v5.json')]:
+1 -1
View File
@@ -18,5 +18,5 @@ previous4=root/'docs/touch_layout_spec_native_binding_v4.json'
assert hashlib.sha256(previous4.read_bytes()).hexdigest()=='048ee8bfffa348d6a6829feb394ce723ad6acf892447d051eb7073b863a32d2f'
new=root/'docs/touch_layout_spec_native_binding_v5.json'
data=json.loads(new.read_text());assert data['profile_id']=='touch_native_binding_v5'
assert hashlib.sha256(new.read_bytes()).hexdigest() in (root/'Sources/dm_touch_native_art.c').read_text()
assert hashlib.sha256(new.read_bytes()).hexdigest() in (root.parent/'touch'/'dm_touch_native_art.c').read_text()
print('PASS frozen v1/v2/v3/v4 spec hashes; v5 profile/spec hash matches compiled constant')
+1 -1
View File
@@ -13,5 +13,5 @@ assert '@"touch_native_binding_v5"' in m
assert 's->map_cancel_active' in m and '@"right_aim"' in m
d=ios/'docs/touch_layout_spec_native_binding_v5.json'
assert json.loads(d.read_text())['profile_id']=='touch_native_binding_v5'
assert hashlib.sha256(d.read_bytes()).hexdigest() in (ios/'Sources/dm_touch_native_art.c').read_text()
assert hashlib.sha256(d.read_bytes()).hexdigest() in (ios.parent/'touch'/'dm_touch_native_art.c').read_text()
print('PASS v5 source seam: full five-axis publish; real rx/ry receipts; navigation/cancel metadata; v5 spec SHA; runtime/phone UNRUN')
+1 -1
View File
@@ -8,7 +8,7 @@
set -uo pipefail
I="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; W="$(cd "$I/../.." && pwd)"
BAD=$(git -C "$W" ls-files -- dm/ios/NativeHUD/v4 dm/ios/NativeHUD/mapgoal dm/ios/NativeHUD/widestash dm/ios/NativeHUD/pouch dm/ios/NativeHUD/touch/fe_rightpanel.* \
'dm/ios/Sources/TouchArt/dm_native_*' dm/ios/Sources/dm_touch_native_art.c dm/host/dm_vault_tab.h dm/host/dm_hud_exp.h dm/host/dm_bright_levels.inc dm/ios/tools/touchrectv1_HUDPanelHD.json dm/ios/tools/native_art/skills.txt dm/ios/tools/native_art/skilldesc.txt)
'dm/ios/Sources/TouchArt/dm_native_*' dm/touch/dm_touch_native_art.c dm/host/dm_vault_tab.h dm/host/dm_hud_exp.h dm/host/dm_bright_levels.inc dm/ios/tools/touchrectv1_HUDPanelHD.json dm/ios/tools/native_art/skills.txt dm/ios/tools/native_art/skilldesc.txt)
[ -z "$BAD" ] || { echo "HUDGEN 红:原版衍生的生成物进了仓库(应该构建时从游戏文件生成):"; echo "$BAD" | sed 's/^/ /'; exit 1; }
R=${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}
[ -f "$R/data/build_manifest.psv" ] || { echo "HUDGEN OK(入库检查);生成检查跳过:这台机器没有游戏文件 $R"; exit 0; }
+3 -3
View File
@@ -3,7 +3,7 @@
输入:Switch 版 3.3.94012 的 Update/RomFS(参数或环境变量 DM_ROMFS_SRC);可选 PC 版 D2R 的解包目录(DM_PC_DATA,底栏出原版 2 倍图用,没有就用 Switch 素材放大)。
产物(不进 git):
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} 加宽储藏箱 / 编年史盖板 / 百宝囊框 / 选角右侧面板 / 小地图终点 / 底部 UI v4
Sources/TouchArt/dm_native_*.png、Sources/dm_touch_native_art.c 原版技能图集与技能索引(生成在原位置,dm/ios/.gitignore 忽略)
Sources/TouchArt/dm_native_*.png、../touch/dm_touch_native_art.c 原版技能图集与技能索引(生成在原位置,dm/ios/.gitignore 忽略)
宿主的三张表(dm_vault_tab.h、dm_hud_exp.h、dm_bright_levels.inc)由 dm/host/Makefile 生成。
用法:gen_assets.py [<原版 RomFS(Update)>]
输入没变就不重出(指纹 = 游戏文件清单 + dm/ios/tools 下全部文件 + PC 素材开关;写在产物根目录 .stamp);同一棵树里同时只许一个进程在生成(锁目录 .gen_lock)——
@@ -12,7 +12,7 @@ Generate the assets derived from the original game that the App uses, from the p
Input: Update/RomFS of Switch version 3.3.94012 (argument or environment variable DM_ROMFS_SRC); optionally the unpacked directory of PC D2R (DM_PC_DATA, used to produce the original game's 2x art for the bottom bar; without it, Switch art is upscaled).
Build output (not in git):
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} widened stash / chronicle cover plate / pouch frame / character select right panel / minimap goal / bottom UI v4
Sources/TouchArt/dm_native_*.png, Sources/dm_touch_native_art.c the original game's skill atlas and skill index (generated in place, ignored by dm/ios/.gitignore)
Sources/TouchArt/dm_native_*.png, ../touch/dm_touch_native_art.c the original game's skill atlas and skill index (generated in place, ignored by dm/ios/.gitignore)
The host's three tables (dm_vault_tab.h, dm_hud_exp.h, dm_bright_levels.inc) are generated by dm/host/Makefile.
Usage: gen_assets.py [<original game RomFS (Update)>]
Nothing is regenerated when the input is unchanged (fingerprint = game file list + all files under dm/ios/tools + the PC art switch; written to .stamp in the build output root); only one process may generate at a time in the same tree (lock directory .gen_lock) --
@@ -39,7 +39,7 @@ def stamp(R):
def ensure(R):
"""产物齐、指纹没变就直接返回;否则拿锁生成。返回 True = 这次重出了。 | If the build output is complete and the fingerprint unchanged, return directly; otherwise take the lock and generate. Returns True = regenerated this time."""
root = gen_paths.gen_dir(); st = os.path.join(root, '.stamp'); lock = os.path.join(root, '.gen_lock')
outs = [os.path.join(root, 'NativeHUD', 'v4', 'base.png'), os.path.join(HERE, '..', 'Sources', 'TouchArt', 'dm_native_skill_0.png'), os.path.join(HERE, '..', 'Sources', 'dm_touch_native_art.c')]
outs = [os.path.join(root, 'NativeHUD', 'v4', 'base.png'), os.path.join(HERE, '..', 'Sources', 'TouchArt', 'dm_native_skill_0.png'), os.path.join(HERE, '..', '..', 'touch', 'dm_touch_native_art.c')]
want = stamp(R); fresh = lambda: all(map(os.path.isfile, outs)) and os.path.isfile(st) and open(st).read() == want
if fresh(): return False
t0 = time.time()
+1 -1
View File
@@ -33,7 +33,7 @@ for s in srcs:
if d not in dirs: dirs.append(d)
b = os.path.basename(s)
if os.path.splitext(b)[0].endswith('_mac'): continue # Mac 专用源按 _mac 命名约定不进 iOS(front_mac.m 由 front_ios.m 实现 front.h;touch_mac.c 是 Mac 触点脚本) | Mac-only sources are kept out of iOS by the _mac naming convention (for front_mac.m, front_ios.m implements front.h; touch_mac.c is the Mac touch point script)
if os.path.dirname(s) == os.path.normpath(os.path.join(host, '../ios/Sources')): continue # 宿主借用的 iOS 源(如触屏模块)iOS 工程本身已编,再收一份会重复链接 | iOS sources borrowed by the host (e.g. the touch module) are already compiled by the iOS project itself; collecting another copy would link them twice
if os.path.dirname(s) == os.path.normpath(os.path.join(host, '../touch')): continue # 跨平台触控模块(dm/touch)iOS 工程按目录整体编,再收一份会重复链接 | The cross-platform touch module (dm/touch) is compiled as a whole directory by the iOS project; collecting another copy would link it twice
if s == os.path.join(host, 'main.c'): os.symlink(s, f'{gen}/main/main.c'); continue
flat = os.path.relpath(s, os.path.dirname(host)).replace('/', '__') # 不同目录同名文件不冲突 | Same-named files in different directories do not collide
os.symlink(s, f'{gen}/src/{flat}')
+1
View File
@@ -20,6 +20,7 @@ asm = ['// 由 dm/ios/tools/gen_embed.py 生成,勿手改']
flags = []
for n in names:
hdr = dict(l[2:].split() for l in open(f'{out}/{n}.fixups.tsv'))
assert hdr.get('ABI', 'apple') == 'apple', f'{n}: 非苹果 ABI 产物({hdr["ABI"]}),不能打进苹果包 | non-Apple ABI build output, cannot go into an Apple package'
te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16)
ko, ks = int(hdr['KEY_PAGE_OFF'], 16), int(hdr['KEY_PAGE_SIZE'], 16)
bin_ = os.path.abspath(f'{out}/{n}.patched.bin'); sz = os.path.getsize(bin_)
+4 -4
View File
@@ -2,12 +2,12 @@
"""原版技能图集 / HUD 小图 → TouchArt PNG,原版 Skills / Skilldesc → 纯 C 索引 dm_touch_native_art.c。构建时从玩家自己的游戏文件生成,不进仓库。
来源与指纹冻结在仓库里的 Sources/TouchArt/native_art_manifest.json(只有原版路径与哈希):读包后先核原件 SHA-256 / MD5 与两张表的 SHA-256,
解码后核 PNG 的 SHA-256(解码只解块、不重绘像素);对不上就报错(游戏版本不对)。
用法:generate.py <原版 RomFS(Update)> 产物生成在原位置、git 忽略(dm/ios/.gitignore):Sources/TouchArt/dm_native_*.png、Sources/dm_touch_native_art.c
用法:generate.py <原版 RomFS(Update)> 产物生成在原位置、git 忽略(dm/ios/.gitignore):Sources/TouchArt/dm_native_*.png、../touch/dm_touch_native_art.c
(.c 里按 Sources/ 写了相对 include,PNG 由 DmTouchOverlay.m / 工程 / 测试按 Sources/TouchArt 引用,所以不挪目录)
Original game skill atlas / HUD small images → TouchArt PNG, original game Skills / Skilldesc → pure C index dm_touch_native_art.c. Generated at build time from the player's own game files, not kept in the repository.
Sources and fingerprints are frozen in Sources/TouchArt/native_art_manifest.json in the repository (only original game paths and hashes): after reading the package, first verify the SHA-256 / MD5 of the original files and the SHA-256 of the two tables,
after decoding verify the SHA-256 of the PNGs (decoding only decodes blocks, it does not redraw pixels); on a mismatch report an error (wrong game version).
Usage: generate.py <original game RomFS (Update)> The build output is generated in place and git-ignored (dm/ios/.gitignore): Sources/TouchArt/dm_native_*.png, Sources/dm_touch_native_art.c
Usage: generate.py <original game RomFS (Update)> The build output is generated in place and git-ignored (dm/ios/.gitignore): Sources/TouchArt/dm_native_*.png, ../touch/dm_touch_native_art.c
(the .c has a relative include written against Sources/, and the PNGs are referenced by DmTouchOverlay.m / the project / the tests via Sources/TouchArt, so the directory is not moved)"""
import csv, hashlib, io, json, sys
from pathlib import Path
@@ -52,14 +52,14 @@ def main(romfs):
assert len({r[0] for r in rows}) == len(rows)
if sha(canonical(rows)) != man['descriptor_index_sha256']: raise SystemExit('native_art:技能索引和冻结的不一致')
gpath = IOS / 'docs/native_art_v1_geometry.json'; binding = IOS / 'docs/touch_layout_spec_native_binding_v5.json'
out = ['/* Generated from frozen official Skills/Skilldesc; do not hand-edit rows. */', '#include "dm_touch_native_art.h"', '#include "../../host/dm_input.h"', '#include <stddef.h>',
out = ['/* Generated from frozen official Skills/Skilldesc; do not hand-edit rows. */', '#include "dm_touch_native_art.h"', '#include "../host/dm_input.h"', '#include <stddef.h>',
'const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES]={']
for a in atl: out.append(' {"%s",%d,%d,%d,%d,%d},' % (a['asset'][:-4], *a['atlas_px'], a['frame_width'], a['frame_pitch'], a['frame_count']))
out += ['};', f'const char dm_ta_manifest_sha[]="{sha(mpath.read_bytes())}";', f'const char dm_ta_geometry_sha[]="{sha(gpath.read_bytes())}";',
f'const char dm_ta_binding_sha[]="{sha(binding.read_bytes())}";', 'static const struct { uint32_t id; int atlas,frame; } rows[]={']
out += [' {%d,%d,%d},' % tuple(row) for row in rows]; out += ['};']
out += [(HERE / 'implementation.c.inc').read_text()]
(IOS / 'Sources/dm_touch_native_art.c').write_text('\n'.join(out) + '\n')
(IOS.parent / 'touch' / 'dm_touch_native_art.c').write_text('\n'.join(out) + '\n')
print(f'native_art:{len(rows)} 条技能索引、{len(atlases)} 张 PNG(原件 SHA256 + MD5、PNG SHA256 都核过)→ {art}')
+21 -7
View File
@@ -6,6 +6,7 @@
# 表的条数会写进替身(数组大小):条数随游戏版本固定,不是游戏内容。
# 用法:shell_stubs.py data <dm 目录> <输出 derived.tsv> 读真实的三份生成文件,写数据(d2rm_pack.py 与 shell_build.sh 都用)
# shell_stubs.py stubs <dm 目录> 把三份生成文件原地换成替身(只在 shell_build.sh 的临时副本里做)
# shell_stubs.py host-stubs <dm 目录> <derived.tsv> 只写宿主的两份替身(经验 / 仓库),条数取自 derived.tsv(Android 无界面宿主,不需要 RomFS)
# For the shell: split the three files "generated from the game files and compiled into the code" into two halves --
# data → one derived.tsv (generated from the user's own game files, placed in dm/ of the install package)
# stubs → three source files of the same names, with no data inside, only fixed-size empty tables and the few lines that fill the tables from derived.tsv at startup (host/dm_derived_rt.h)
@@ -13,6 +14,7 @@
# The entry counts of the tables are written into the stubs (array sizes): the counts are fixed by the game version and are not game content.
# Usage: shell_stubs.py data <dm directory> <output derived.tsv> read the three real generated files and write the data (used by both d2rm_pack.py and shell_build.sh)
# shell_stubs.py stubs <dm directory> replace the three generated files in place with stubs (done only in shell_build.sh's temporary copy)
# shell_stubs.py host-stubs <dm directory> <derived.tsv> write only the host's two stubs (experience / vault), counts taken from derived.tsv (Android headless host, no RomFS)
import os, re, sys
CSTR = r'"((?:[^"\\]|\\.)*)"'
@@ -22,7 +24,7 @@ def unq(s): return bytes(s, 'utf-8').decode('unicode_escape').encode('latin-1').
def paths(dm):
return (os.path.join(dm, 'host', 'dm_hud_exp.h'), os.path.join(dm, 'host', 'dm_vault_tab.h'), os.path.join(dm, 'ios', 'Sources', 'dm_touch_native_art.c'))
return (os.path.join(dm, 'host', 'dm_hud_exp.h'), os.path.join(dm, 'host', 'dm_vault_tab.h'), os.path.join(dm, 'touch', 'dm_touch_native_art.c'))
def parse(dm):
@@ -52,9 +54,8 @@ def data(dm, dst):
return len(exp), len(parts), len(rows), len(sets), len(trows)
def stubs(dm):
exp, parts, rows, sets, trows, (hud, vault, art, m) = parse(dm)
p_hud, p_vault, p_art = paths(dm)
def host_stubs(dm, nparts, nrows, nsets):
p_hud, p_vault, _ = paths(dm)
open(p_hud, 'w', encoding='utf-8').write('''// 壳的替身(ios/tools/shell_stubs.py 生成):经验表不编进代码,启动时从安装包的 dm/derived.tsv 读(标签 EXP,每行 10 个)
#pragma once
#include <stdint.h>
@@ -82,14 +83,20 @@ __attribute__((constructor)) static void vt_load(void) { int a = 0, b = 0, c = 0
for (int i = a; i < VT_NPART; i++) vt_part_name[i] = ""; for (int i = c; i < VT_NSET; i++) vt_set_key[i] = "";
for (int i = b; i < VT_NROW; i++) vt_rows[i] = (vt_row){ .set = -1, .key = "", .icon = "" };
if (a != VT_NPART || b != VT_NROW || c != VT_NSET) fprintf(stderr, "[dm] 【红】编年史仓库表没读全:部位 %%d / %%d、条目 %%d / %%d、套装 %%d / %%d\\n", a, VT_NPART, b, VT_NROW, c, VT_NSET); }
''' % (len(parts), len(rows), len(sets)))
''' % (nparts, nrows, nsets))
def stubs(dm):
exp, parts, rows, sets, trows, (hud, vault, art, m) = parse(dm)
p_hud, p_vault, p_art = paths(dm)
host_stubs(dm, len(parts), len(rows), len(sets))
stub = art[:m.start()] + '''static struct { uint32_t id; int atlas,frame; } rows[%d]; /* 壳的替身:技能索引不编进代码,启动时从安装包的 dm/derived.tsv 读(标签 TAROW) */
static void ta_row_cb(char **f, int n, void *ctx) { int *i = ctx; if (n < 3 || *i >= (int)(sizeof rows / sizeof rows[0])) return;
rows[*i].id = (uint32_t)strtoul(f[0], NULL, 10); rows[*i].atlas = atoi(f[1]); rows[*i].frame = atoi(f[2]); (*i)++; }
__attribute__((constructor)) static void ta_load(void) { int i = 0; dm_derived_each("TAROW", ta_row_cb, &i);
for (int k = i; k < (int)(sizeof rows / sizeof rows[0]); k++) { rows[k].id = UINT32_MAX - 1; rows[k].atlas = rows[k].frame = -1; }
if (i != (int)(sizeof rows / sizeof rows[0])) fprintf(stderr, "[dm] 【红】技能图标索引没读全:%%d / %%d\\n", i, (int)(sizeof rows / sizeof rows[0])); }''' % len(trows) + art[m.end():]
stub = stub.replace('#include <stddef.h>', '#include <stddef.h>\n#include "../../host/dm_derived_rt.h"', 1); assert 'dm_derived_rt.h' in stub
stub = stub.replace('#include <stddef.h>', '#include <stddef.h>\n#include "../host/dm_derived_rt.h"', 1); assert 'dm_derived_rt.h' in stub
open(p_art, 'w', encoding='utf-8').write(stub)
return len(parts), len(rows), len(sets), len(trows)
@@ -97,4 +104,11 @@ __attribute__((constructor)) static void ta_load(void) { int i = 0; dm_derived_e
if __name__ == '__main__':
if len(sys.argv) == 4 and sys.argv[1] == 'data': print('derived.tsv:经验 %d、部位 %d、仓库条目 %d、套装 %d、技能索引 %d' % data(sys.argv[2], sys.argv[3]))
elif len(sys.argv) == 3 and sys.argv[1] == 'stubs': print('替身已写:部位 %d、仓库条目 %d、套装 %d、技能索引 %d' % stubs(sys.argv[2]))
else: sys.exit('用法:shell_stubs.py data <dm 目录> <输出 derived.tsv> | shell_stubs.py stubs <dm 目录>')
elif len(sys.argv) == 4 and sys.argv[1] == 'host-stubs':
# 只写宿主用的两份替身(经验表、编年史仓库表),条数取自现成的 derived.tsv(如安装包里的 dm/derived.tsv):没有原版 RomFS 也能编宿主(Android 无界面宿主)
# Write only the two stubs the host uses (experience table, chronicle vault table), with counts taken from an existing derived.tsv (e.g. dm/derived.tsv in an install package): the host builds without the original RomFS (Android headless host)
tags = [l.split('\t', 1)[0] for l in open(sys.argv[3], encoding='utf-8')]
assert tags.count('EXP') == 10, '经验表应是 10 行'
n = tags.count('VTPART'), tags.count('VTROW'), tags.count('VTSET'); assert all(n), n
host_stubs(sys.argv[2], *n); print('宿主替身已写:部位 %d、仓库条目 %d、套装 %d' % n)
else: sys.exit('用法:shell_stubs.py data <dm 目录> <输出 derived.tsv> | shell_stubs.py stubs <dm 目录> | shell_stubs.py host-stubs <dm 目录> <derived.tsv>')
+2 -2
View File
@@ -40,7 +40,7 @@ TABLE = {
'ui.json': {
# 通知里不写怎么操作(界面更简洁;十字按钮变红已表达)
# Notifications do not say how to operate (the UI is cleaner; the cross button turning red already conveys it)
'LevelUpStatsNotificationController': ('7854f598', '你升级了。'),
'LevelUpStatsNotificationController': ('7854f598', '有新的属性点和技能点可以分配。'), # 与下一句同时弹出,写成同一句会显示两遍 | Pops up together with the next one; identical text would show twice
'LevelUpNotificationController': ('7ba311c9', '你升级了。'),
'QuestLogNotificationController': ('7b65d87d', '任务已更新。'),
'MoviePlaybackHoldToSkip': ('f3a05873', ''),
@@ -85,7 +85,7 @@ EN = {
'MoviePlaybackHoldToSkip_switch': ('dab56a9e', ''),
},
'ui.json': {
'LevelUpStatsNotificationController': ('525fb31a', "You've leveled up."),
'LevelUpStatsNotificationController': ('525fb31a', 'You have new Stat and Skill Points to spend.'),
'LevelUpNotificationController': ('1e4882b2', "You've leveled up."),
'QuestLogNotificationController': ('94d110a8', 'Quest has been updated.'),
'MoviePlaybackHoldToSkip': ('dab56a9e', ''),
+1
View File
@@ -55,6 +55,7 @@ def build(out, names):
text, wsegs = [], []
for n in names:
hdr = dict(l[2:].split() for l in open(os.path.join(out, n + '.fixups.tsv')) if l.startswith('# '))
assert hdr.get('ABI', 'apple') == 'apple', f'{n}: 非苹果 ABI 产物({hdr["ABI"]}),不能打进苹果包 | non-Apple ABI build output, cannot go into an Apple package'
te, po = int(hdr['TEXT_END'], 16), int(hdr['PATCH_OFF'], 16)
img = open(os.path.join(out, n + '.patched.bin'), 'rb').read(); sz = len(img); a, end = r16(te), r16(sz)
assert po % PG == 0 and a <= po <= end, (n, hex(te), hex(po), hex(sz))
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
# 从苹果包(IPA)里的 Guest.framework 反推改写前的模块映像,写成未压缩 NSO:给拿不到原 ExeFS、只有可运行 IPA 的场合重出别的 ABI(如 DM_ABI=android)。
# 做法:按 guest_dylib.py 的节布局拼回 patched.bin;text 里每条跳进补丁区的 b 按补丁块形态还原原指令(patch_nso.py 各 site_* 的逆);
# 参数位按 patch_nso.py 的 PARAMS 表还原两条原字;最后按包内 <名>.cuts.tsv 把剪口(含代码 / 数据)还原成原字节。
# 判据:用同一规则域(IPA 为 touch:DM_RULESET=touch-run-v4)苹果 ABI 重新改写,patched.bin / fixups / gates / cuts 须与包内逐字节一致(--check 自动做)。
# 局限:NSO 文件本身(lz4 压缩、表头校验值)复原不出,extract_game.sh 里的原文件 SHA256 对不上;包里没有 subsdk0(视频库,宿主不加载);
# sdk 的构建号包里没有,写全 0(改写器只按构建号查 main 的登记表)。
# 用法:ipa_unpatch.py <IPA 或解开的 DmIOS.app 目录> <输出目录> [--check] 输出 <输出目录>/{main,sdk}
# Reconstruct the pre-rewrite module images from Guest.framework inside an Apple package (IPA) and write them as uncompressed NSOs: for when the original ExeFS is unavailable and only a runnable IPA is, so another ABI (e.g. DM_ABI=android) can be built.
# Method: reassemble patched.bin from the section layout of guest_dylib.py; for every b in text that jumps into the patch area, restore the original instruction from the patch block's shape (the inverse of each site_* in patch_nso.py);
# parameter slots get both original words back from patch_nso.py's PARAMS table; finally the package's <name>.cuts.tsv restores cuts (code / data) to their original bytes.
# Criterion: rewriting again with the same rule domain (the IPA is touch: DM_RULESET=touch-run-v4) and the Apple ABI must reproduce patched.bin / fixups / gates / cuts byte for byte (--check does this).
# Limits: the NSO file itself (lz4 compression, header hashes) cannot be recovered, so the original-file SHA256 in extract_game.sh will not match; the package has no subsdk0 (video library, not loaded by the host);
# the package does not carry sdk's build ID, so it is written as all zeros (the rewriter only looks up main's registries by build ID).
# Usage: ipa_unpatch.py <IPA or unpacked DmIOS.app directory> <output dir> [--check] writes <output dir>/{main,sdk}
import os, re, struct, subprocess, sys, tempfile, zipfile
from itertools import combinations
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM
HERE = os.path.dirname(os.path.abspath(__file__))
MODS = ('main', 'sdk')
BUILD_IDS = {'main': 'db0507f36b84200ac05f75d76ed5026f'}
PG = 0x4000
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM); md.detail = True
W = lambda b, o: struct.unpack_from('<I', b, o)[0]
r16 = lambda x: (x + PG - 1) & ~(PG - 1)
def dis(w, pc):
l = list(md.disasm(struct.pack('<I', w), pc)); assert l, f'{pc:#x} {w:08x}'; return l[0]
def bt(w, pc):
"""b / bl 目标;不是 b 返回 None。 | Target of a b; None if not a b."""
if w & 0xFC000000 != 0x14000000: return None
return pc + 4 * (((w & 0x3FFFFFF) ^ 0x2000000) - 0x2000000)
def read_app(src):
"""{相对路径: 字节},只取 dm/ 与 Guest。 | {relative path: bytes}, dm/ and Guest only."""
want = lambda p: p.startswith('dm/') or p == 'Frameworks/Guest.framework/Guest'
out = {}
if os.path.isdir(src):
for p in ['Frameworks/Guest.framework/Guest'] + ['dm/' + f for f in os.listdir(os.path.join(src, 'dm'))]:
out[p] = open(os.path.join(src, p), 'rb').read()
else:
with zipfile.ZipFile(src) as z:
for n in z.namelist():
m = re.match(r'Payload/[^/]+\.app/(.*)$', n)
if m and want(m.group(1)) and not n.endswith('/'): out[m.group(1)] = z.read(n)
return out
def sections(guest):
"""Mach-O 节 → {节名: 字节}(guest_dylib.py 写法:文件偏移 = 地址)。 | Mach-O sections → {name: bytes} (guest_dylib.py layout: file offset = address)."""
assert W(guest, 0) == 0xFEEDFACF
ncmds = W(guest, 16); o = 32; out = {}
for _ in range(ncmds):
cmd, sz = struct.unpack_from('<II', guest, o)
if cmd == 0x19:
seg = guest[o + 8:o + 24].rstrip(b'\0').decode(); ns = W(guest, o + 64)
for i in range(ns):
so = o + 72 + 80 * i
sn = guest[so:so + 16].rstrip(b'\0').decode()
addr, size = struct.unpack_from('<QQ', guest, so + 32)
out[sn if sn != '__img' else seg] = guest[addr:addr + size]
o += sz
return out
def header(txt):
return {k: int(v, 0) for k, v in (l[2:].split() for l in txt.splitlines() if l.startswith('# ') and l.split()[1] != 'BUILD_ID')}
def params_table():
"""patch_nso.py 的 PARAMS:[(A, 原字 A, B, 原字 B)]。 | patch_nso.py's PARAMS: [(A, word A, B, word B)]."""
s = open(os.path.join(HERE, 'patch_nso.py'), encoding='utf-8').read()
body = s[s.index('PARAMS = {'):s.index('params = PARAMS.get')]
return [(int(a, 16), int(wa, 16), int(b, 16), int(wb, 16)) for a, wa, b, wb in re.findall(r"\((0x[0-9a-f]+), '([0-9a-f]{8})', (0x[0-9a-f]+), '([0-9a-f]{8})'", body)]
def regs_in(ins):
"""与 patch_nso.regs_in 同。 | Same as patch_nso.regs_in."""
s = {int(n) for n in re.findall(r'\b[xw](\d+)\b', ins.op_str)}
try:
r, w = ins.regs_access()
s |= {int(m.group(1)) for m in (re.fullmatch(r'[xw](\d+)', ins.reg_name(x) or '') for x in r + w) if m}
except Exception: pass
return s
def unsubst(nw, S, pc, T=None):
"""patch_nso.subst 的逆:xS/wS → x18/w18,只在 4 个寄存器字段里找,再用 subst 的判据正向核对。
S、T 是改写器 pick() 挑的「原指令没用到的最小两个寄存器」:候选不得用到 S / T;给了 T(单条指令的块)时还须 pick(候选) == (S, T)。
Inverse of patch_nso.subst. S, T are the two lowest registers unused by the original instruction (patch_nso pick()): a candidate must not use S / T,
and when T is given (single-instruction block) pick(candidate) must equal (S, T)."""
pos = [p for p in (0, 5, 10, 16) if (nw >> p) & 31 == S]
got = []
for k in range(len(pos), 0, -1):
for c in combinations(pos, k):
w = nw
for p in c: w = (w & ~(31 << p)) | (18 << p)
try: ins = dis(w, pc)
except AssertionError: continue
if not re.search(r'\b[xw]18\b', ins.op_str): continue
want = re.sub(r'\b([xw])18\b', lambda m: f'{m.group(1)}{S}', ins.op_str)
if dis(nw, pc).mnemonic != ins.mnemonic or dis(nw, pc).op_str != want: continue
used = regs_in(ins)
if S in used or (T is not None and (T in used or [r for r in range(16) if r not in used and r != 18][:2] != [S, T])): continue
got.append((k, w))
if not got: return None
# 多个候选正向改写都得 nw 时(立即数字段恰为 S,如逻辑立即数的 immr)取替换字段最少的:编码器给的规范编码;--check 的重改写仍须逐字节一致
# When several candidates all rewrite forward to nw (an immediate field happens to equal S, e.g. immr of a logical immediate), take the one with the fewest
# substituted fields: the canonical encoding an assembler emits; --check still requires the re-rewrite to match byte for byte
kmin = min(k for k, _ in got); best = {w for k, w in got if k == kmin}
assert len(best) == 1, f'{pc:#x} {nw:08x} S=x{S}:候选 {[hex(x) for x in best]}'
if len(got) > 1: AMBIG.append(pc)
return best.pop()
AMBIG = []
class Block:
"""补丁块读取器:跳过槽块基址前缀(apple:mrs tpidrro)+ 键页三条,返回 (基址寄存器, 键下标, 后续偏移)。 | Patch block reader."""
def __init__(self, pat, key_idx): self.pat, self.kv = pat, {v: k for k, v in key_idx.items()}
def w(self, o): return W(self.pat, o)
def slot(self, o):
w = self.w(o); assert w & 0xFFFFFFE0 == 0xD53BD060, f'{o:#x} 不是 mrs tpidrro:{w:08x}'
T = w & 31; ldr = self.w(o + 8)
assert self.w(o + 4) & 0x9F000000 == 0x90000000 and ldr & 0xFFC00000 == 0xF9400000 and self.w(o + 12) & 0xFFE0FFFF == 0x8B000000 | (T << 5) | T, f'{o:#x} 键页序列不符'
return T, self.kv[(ldr >> 10) & 0xFFF], o + 16
def restore(name, app, gates):
hdr = header(app[f'dm/{name}.fixups.tsv'].decode())
se = sections(app['Frameworks/Guest.framework/Guest'])
te, po, ko = hdr['TEXT_END'], hdr['PATCH_OFF'], hdr['KEY_PAGE_OFF']
pat = bytearray(se[f'__dm{name}x0'] + se[f'__DM{name}W'] + se[f'__dm{name}x1'])
assert len(se[f'__dm{name}x0']) == r16(te) and len(se[f'__dm{name}x0']) + len(se[f'__DM{name}W']) == po
assert pat[ko:ko + PG] == bytes(PG), '键页不是全 0'
key_idx = {k[4:-4]: v for k, v in hdr.items() if k.startswith('KEY_') and k.endswith('_IDX')}
B = Block(pat, key_idx)
img = bytearray(pat[:ko])
gate_at = {orig: (k, arg) for ret, k, arg, orig in gates}
params = {a: (wa, b, wb) for a, wa, b, wb in params_table()} if name in BUILD_IDS else {}
cuts = []
if f'dm/{name}.cuts.tsv' in app:
for l in app[f'dm/{name}.cuts.tsv'].decode().splitlines():
if l.startswith('#') or not l.strip(): continue
f = l.split('\t'); cuts.append((int(f[0], 16), bytes.fromhex(f[1]), bytes.fromhex(f[2])))
cut_b = {off: nb for off, ob, nb in cuts if len(nb) == 4 and bt(W(nb, 0), off) is not None and bt(W(nb, 0), off) >= po}
st = {}
def put(o, w, kind): struct.pack_into('<I', img, o, w); st[kind] = st.get(kind, 0) + 1
for o in range(0, te & ~3, 4):
w = W(img, o); s = bt(w, o)
if s is None or s < po: continue
if o in cut_b and cut_b[o] == struct.pack('<I', w): st['cut_b'] = st.get('cut_b', 0) + 1; continue # 剪口自带的跳板:最后按 cuts.tsv 还原 | trampoline belonging to a cut: restored from cuts.tsv at the end
if o in params:
wa, b, wb = params[o]; assert W(img, b) == 0xD503201F, f'参数位 B {b:#x} 不是 nop'
put(o, wa, 'param'); struct.pack_into('<I', img, b, wb); continue
h = B.w(s)
if h == 0xA9BF7FE8 or h == 0xA9BF7BFD: # 分支门 / 门 / 观测门 | branch gate / gate / observation gate
q = s + (4 if h == 0xA9BF7FE8 else 0)
assert B.w(q) == 0xA9BF7BFD
T, key, n = B.slot(q + 4); assert T == 30 and key == 'KGATE'
assert B.w(n) == 0xF94003DE and B.w(n + 4) == 0xF94003FD and B.w(n + 8) == 0xD63F03C0 and B.w(n + 12) == 0xA8C17BFD
n += 16
if h == 0xA9BF7FE8: # cbz w8; ldp; b 目标; ldp; 原字; b o+4
assert B.w(n) == 0x34000068 and bt(B.w(n + 20), n + 20) == o + 4; put(o, B.w(n + 16), 'branch_gate')
elif bt(B.w(n), n) == o + 4: # 宿主门:svc / cntpct / cntvct
k, arg = gate_at[o]
put(o, {'svc': 0xD4000001 | arg << 5, 'cntpct': 0xD53BE020 | arg, 'cntvct': 0xD53BE040 | arg}[k], k)
else:
assert bt(B.w(n + 4), n + 4) == o + 4; put(o, B.w(n), 'obs')
continue
if h & 0xFFFFFFE0 == 0xF81F03E0: # stur xR,[sp,#-16]
R = h & 31; h2 = B.w(s + 4)
if R == 16 and h2 == 0xF81E83F1: # 跳转表 br x18
put(o, 0xD61F0240, 'br'); continue
if h2 & 0xFFFFFFE0 == 0xF81E83E0: # msr tpidr_el0, xN:stur T / stur tmp / 基址 T / str N,[T]
T, key, n = B.slot(s + 8); assert key == 'KTLS' and B.w(n) & 0xFFFFFFE0 == 0xF9000000 | (T << 5)
put(o, 0xD51BD040 | (B.w(n) & 31), 'tpidr_w'); continue
N, key, n = B.slot(s + 4) # mrs xN, tpidr_el0 / tpidrro_el0
put(o, {'KTLS': 0xD53BD040, 'KTLR': 0xD53BD060}[key] | N, 'sysreg_r'); continue
assert h & 0xFFC003E0 == 0xA90003E0, f'{o:#x} → {s:#x} 未知块头 {h:08x}' # stp xS, xT, [sp, #save]
S = h & 31; T, key, n = B.slot(s + 4); assert key == 'K18' and T == (h >> 10) & 31
w1 = B.w(n)
if w1 & 0x9F00001F == 0x90000000 | S: # adrp xS → adr / adrp x18
tgt = (n & ~0xFFF) + (((((w1 >> 5) & 0x7FFFF) << 2 | (w1 >> 29) & 3) ^ 0x100000) - 0x100000 << 12)
if B.w(n + 4) & 0xFFC003FF == 0x91000000 | (S << 5) | S:
tgt += (B.w(n + 4) >> 10) & 0xFFF; d = tgt - o
put(o, 0x10000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adr')
else:
d = (tgt >> 12) - (o >> 12)
put(o, 0x90000000 | ((d & 3) << 29) | (((d >> 2) & 0x7FFFF) << 5) | 18, 'adrp')
continue
assert w1 == 0xF9400000 | (T << 5) | S, f'{s:#x} 读槽不符'
n += 4; w2 = B.w(n); m = dis(w2, n).mnemonic
if B.w(n + 4) == 0xF9000000 | (T << 5) | S and B.w(n + 8) & 0xFFC07FFF == 0xA9400000 | (T << 10) | (31 << 5) | S and bt(B.w(n + 12), n + 12) == o + 4:
w0 = unsubst(w2, S, o, T); assert w0 is not None, f'{o:#x} 普通块还原不出 x18'
put(o, w0, 'plain'); continue
if m in ('cbz', 'cbnz', 'tbz', 'tbnz') and w2 & 31 == S and bt(B.w(n + 8), n + 8) == o + 4:
tgt = bt(B.w(n + 16), n + 16); off = (tgt - o) >> 2
nw = ((w2 & 0xFF000000) | ((off & 0x7FFFF) << 5) | 18) if m in ('cbz', 'cbnz') else ((w2 & 0xFFF80000) | ((off & 0x3FFF) << 5) | 18)
put(o, nw, 'cond'); continue
# 独占窗口:块里依次是窗口指令的拷贝,首条即原处那条(窗口首条是独占读,不是分支)
# Exclusive window: the block holds copies of the window instructions in order; the first is the one at the original site (an exclusive load, not a branch)
assert dis(w2, o).mnemonic.startswith(('ldxr', 'ldaxr', 'ldxp', 'ldaxp')), f'{o:#x} 窗口首条 {dis(w2, o).mnemonic}'
w0 = unsubst(w2, S, o); put(o, w2 if w0 is None else w0, 'window')
for off, ob, nb in cuts:
assert bytes(img[off:off + len(nb)]) == nb, f'剪口 {off:#x} 现值 {bytes(img[off:off + len(nb)]).hex()} ≠ 新字节 {nb.hex()}'
img[off:off + len(ob)] = ob
st['cut'] = len(cuts)
return img, hdr, st, pat
def write_nso(path, img, hdr, build_id):
te, ro, da, ko = hdr['TEXT_END'], hdr['RO_OFF'], hdr['DATA_OFF'], hdr['KEY_PAGE_OFF']
segs = [(0, te), (ro, da - ro), (da, ko - da)] # data 拉到键页前、bss 0:映像长 = KEY_PAGE_OFF,改写器算出同一 KEY_PAGE_OFF / PATCH_OFF
h = bytearray(0x100); h[0:4] = b'NSO0'
off = 0x100
for i, (mo, sz) in enumerate(segs): struct.pack_into('<III', h, 0x10 + 0x10 * i, off, mo, sz); off += sz
h[0x40:0x50] = bytes.fromhex(build_id)
struct.pack_into('<III', h, 0x60, *(sz for _, sz in segs))
with open(path, 'wb') as f:
f.write(h)
for mo, sz in segs: f.write(img[mo:mo + sz])
def check(name, out, app, pat):
with tempfile.TemporaryDirectory() as td:
env = dict(os.environ, DM_RULESET='touch-run-v4', DM_ABI='apple'); env.pop('DM_PRIVATE_GATES', None)
r = subprocess.run([sys.executable, os.path.join(HERE, 'patch_nso.py'), os.path.join(out, name), td, name], env=env, capture_output=True, text=True)
if r.returncode: print(r.stdout, r.stderr); return False
got = open(os.path.join(td, f'{name}.patched.bin'), 'rb').read()
ok = got.rstrip(b'\0') == bytes(pat).rstrip(b'\0')
if not ok:
n = min(len(got), len(pat)); bad = [o for o in range(0, n, 4) if got[o:o + 4] != pat[o:o + 4]]
print(f' patched.bin 不一致:{len(bad)} 字,首个 {[hex(x) for x in bad[:8]]}')
for t in ('fixups', 'gates', 'cuts'):
if f'dm/{name}.{t}.tsv' not in app: continue
same = open(os.path.join(td, f'{name}.{t}.tsv'), 'rb').read() == app[f'dm/{name}.{t}.tsv']
print(f' {t}.tsv {"一致" if same else "不一致"}'); ok &= same
return ok
def main():
a = [x for x in sys.argv[1:] if not x.startswith('--')]
if len(a) != 2: sys.exit('用法:ipa_unpatch.py <IPA 或 DmIOS.app 目录> <输出目录> [--check]')
app = read_app(a[0]); os.makedirs(a[1], exist_ok=True); ok = True
for name in MODS:
gates = []
for l in app[f'dm/{name}.gates.tsv'].decode().splitlines():
r, k, arg, orig = l.split(); gates.append((int(r, 16), k, int(arg), int(orig, 16)))
img, hdr, st, pat = restore(name, app, gates)
write_nso(os.path.join(a[1], name), img, hdr, BUILD_IDS.get(name, '00' * 16))
print(name, st, '多候选取规范编码', len(AMBIG)); AMBIG.clear()
if '--check' in sys.argv:
c = check(name, a[1], app, pat); ok &= c; print(f' {name} 苹果 ABI 重改写 {"与包内逐字节一致" if c else "不一致"}')
sys.exit(0 if ok else 1)
if __name__ == '__main__':
main()
+156 -19
View File
@@ -7,6 +7,7 @@
# svc #n、mrs cntpct_el0 → 宿主门(门地址取自线程槽 KGATE,进 C 后按返回点查 gates.tsv)
# 已登记剪口(CUTS,按 NSO 构建号限定):改写前逐条断言原字节,不符即中止;结果列在 <名>.cuts.tsv
# 已登记观测门(OBS,按构建号限定):入口一条指令换成「进宿主观测回调 → 执行原指令 → 跳回」,诊断零运行时改代码;列在 <名>.obs.tsv
# DM_ABI=android:槽块基址改经 Bionic 线程指针取(mrs tpidr_el0 + ldr [tp,#DM_ANDROID_TP_OFF],Linux 把用户态 tpidrro_el0 清零),fixups.tsv 表头多 ABI / TP_SLOT_OFF 两行。
# 键页只在数据段末尾保存“实际键号 × 8”,补丁代码通过键页间接取线程槽:装载器可使用任意键号。
# 输出:<名>.patched.bin(键页与补丁区接在映像后 PATCH_OFF)、<名>.fixups.tsv(布局与键页下标表头)、<名>.gates.tsv、<名>.sites.tsv、<名>.cuts.tsv、<名>.obs.tsv
# Generic NSO rewriter: Switch aarch64 module → an image that can execute natively on Apple systems.
@@ -18,6 +19,7 @@
# svc #n, mrs cntpct_el0 → host gate (gate address taken from thread slot KGATE; once in C, gates.tsv is looked up by return point)
# Registered cuts (CUTS, restricted by NSO build ID): before rewriting, the original bytes are asserted one by one and any mismatch aborts; results are listed in <name>.cuts.tsv
# Registered observation gates (OBS, restricted by build ID): one instruction at the entry is replaced with "enter the host observation callback → execute the original instruction → jump back", so diagnostics modify zero code at runtime; listed in <name>.obs.tsv
# DM_ABI=android: the slot block base is fetched via the Bionic thread pointer instead (mrs tpidr_el0 + ldr [tp,#DM_ANDROID_TP_OFF]; Linux zeroes user tpidrro_el0), and the fixups.tsv header gains two lines, ABI / TP_SLOT_OFF.
# The key page only stores "actual key number × 8" at the end of the data segment, and patch code fetches thread slots indirectly through the key page: the loader may use any key number.
# Output: <name>.patched.bin (key page and patch area appended after the image at PATCH_OFF), <name>.fixups.tsv (layout and key page index header), <name>.gates.tsv, <name>.sites.tsv, <name>.cuts.tsv, <name>.obs.tsv
import struct, re, sys, os
@@ -178,6 +180,12 @@ cuts = list(CUTS.get(BUILD_ID, []))
# 触屏版规则域默认同时带宿主私有门;规则闸门可显式关闭,保留同一出包入口和规则域。
# The touchscreen rule domain by default also carries the host-private gates; the rule gate check can turn them off explicitly, keeping the same packaging entry point and rule domain.
PRIVATE_GATES = os.environ.get("DM_PRIVATE_GATES", "1") != "0"
# 目标 ABI:apple(iOS/macOS,默认,产物逐字节不变)/ android(Linux Bionic,槽块基址经 tpidr_el0 的 TLS 槽)。
# Target ABI: apple (iOS/macOS, default, output byte-identical) / android (Linux Bionic, slot block base via a TLS slot of tpidr_el0).
ABI = os.environ.get('DM_ABI', 'apple')
assert ABI in ('apple', 'android'), f'未知 ABI {ABI}'
ANDROID_TP_OFF = int(os.environ.get('DM_ANDROID_TP_OFF', '0x10'), 0) # Bionic TLS_SLOT_APP(tp[2])
assert ANDROID_TP_OFF % 8 == 0 and 0 <= ANDROID_TP_OFF < 0x8000, f'DM_ANDROID_TP_OFF {ANDROID_TP_OFF:#x}'
PRIVATE_AIM = RULE_RUN and PRIVATE_GATES
if PRIVATE_AIM:
cuts.append((0x2faf04, 'fde7fe97', 'c11000d4',
@@ -256,6 +264,16 @@ def emit(w, kind=None):
def emit_key_addr(reg, kind):
fix.append((len(patch), kind)); emit(ADRP(reg, here(), KEY_PAGE_OFF)); emit(LDRX(reg, reg, KEY_INDEX[kind]))
def emit_slot_base(reg):
"""reg = 本线程槽块基址。apple:tpidrro_el0 即基址(宿主每线程写入);android:Linux 把用户态 tpidrro_el0 清零,
改从 Bionic 线程指针取:reg = [tpidr_el0 + ANDROID_TP_OFF](宿主在该 TLS 槽放槽块指针)。客体自己的 tpidr_el0 读写已改写成槽 KTLS,
真 tpidr_el0 始终是 Bionic 的。
reg = base of this thread's slot block. apple: tpidrro_el0 is the base (written per thread by the host); android: Linux zeroes user tpidrro_el0,
so take it from the Bionic thread pointer instead: reg = [tpidr_el0 + ANDROID_TP_OFF] (the host stores the slot block pointer in that TLS slot). The guest's own tpidr_el0
reads/writes are already rewritten to slot KTLS, so the real tpidr_el0 is always Bionic's."""
if ABI == 'apple': emit(MRS_TPIDRRO(reg))
else: emit(MRS_TPIDR(reg)); emit(LDRX(reg, reg, ANDROID_TP_OFF // 8))
def emit_slot_addr(base, key_reg, kind):
emit_key_addr(key_reg, kind); emit(ADDR(base, base, key_reg))
@@ -273,6 +291,7 @@ def LDUR(t, n, off): return 0xF8400000 | ((off & 0x1FF) << 12) | (n << 5) | t
def LDRX(t, n, imm12=0): return 0xF9400000 | (imm12 << 10) | (n << 5) | t
def STRX(t, n, imm12=0): return 0xF9000000 | (imm12 << 10) | (n << 5) | t
def MRS_TPIDRRO(t): return 0xD53BD060 | t
def MRS_TPIDR(t): return 0xD53BD040 | t
def ADRP(dd, pc, target):
imm = ((target & ~0xFFF) - (pc & ~0xFFF)) >> 12; assert -(1 << 20) <= imm < (1 << 20)
return 0x90000000 | ((imm & 3) << 29) | (((imm >> 2) & 0x7FFFF) << 5) | dd
@@ -326,13 +345,87 @@ def sp_delta(ins):
assert not re.match(r'(sp|wsp),', ins.op_str), f'writes sp: {ins.address:x} {ins.op_str}'
return 0
# ---- android:没有红区 ----
# Linux / Bionic 不保留 sp 下方:信号(含 ART / 系统发来的、不走 sigaltstack 的)随时可能落在当前栈上把 sp 下方写坏。
# 所以 android 的跳板一律先减 sp 再存借用的寄存器,用完加回;被搬进跳板、又引用 sp 的原指令改用一个存着原 sp 的寄存器 U。
# apple 走原来的红区写法,产物逐字节不变。思路来自 dodola/d2r-mobile 的 Android 移植(MIT)。
# ---- android: no red zone ----
# Linux / Bionic does not reserve the area below sp: a signal (including ones from ART / the system that do not go through sigaltstack) may land on
# the current stack at any time and overwrite what is below sp. So android trampolines always lower sp first, store the borrowed registers, and
# add it back afterwards; an original instruction moved into a trampoline that references sp uses a register U holding the original sp instead.
# apple keeps the original red-zone form, output byte-identical. The approach comes from the Android port in dodola/d2r-mobile (MIT).
def save_pair(S, T):
emit(STP_PRE(S, T, 31, -16) if ABI == 'android' else STP(S, T, 31, -16))
def restore_pair(S, T):
emit(LDP_POST(S, T, 31, 16) if ABI == 'android' else LDP(S, T, 31, -16))
def uses_sp(ins): return re.search(r'\bw?sp\b', ins.op_str) is not None
def subst_sp(ins, w, reg):
"""把原指令里的 sp / wsp 操作数换成寄存器 reg。寄存器号 31 也编码 xzr / wzr,所以逐个组合反汇编核对,只换真正是 sp 的字段。
Replace the sp / wsp operand of the original instruction with register reg. Register number 31 also encodes xzr / wzr, so disassemble every
combination and check it, replacing only the fields that really are sp."""
orig = dis(w, ins.address)
if orig.mnemonic == 'mov' and orig.op_str.endswith(', sp'): # mov xd, sp = add xd, sp, #0;换基址后 capstone 不再写成 mov,改用寄存器 mov | mov xd, sp = add xd, sp, #0; with the base replaced capstone no longer prints mov, use the register mov
assert w & 0xFFC003E0 == 0x910003E0 and (w >> 10) & 0xFFF == 0, hex(ins.address)
return 0xAA0003E0 | (reg << 16) | (w & 31)
want = re.sub(r'\b(w?sp)\b', lambda m: ('w' if m.group(1) == 'wsp' else 'x') + str(reg), orig.op_str)
pos = [p for p in (0, 5, 10, 16) if (w >> p) & 31 == 31]
for k in range(1, len(pos) + 1):
for c in combinations(pos, k):
nw = w
for p in c: nw = (nw & ~(31 << p)) | (reg << p)
try: dd = dis(nw, ins.address)
except AssertionError: continue
if dd.mnemonic == orig.mnemonic and dd.op_str == want: return nw
raise RuntimeError(f'android sp 替换失败 {ins.address:x} {orig.mnemonic} {orig.op_str}')
def android_frame(ins, scratch=32):
"""借用寄存器的暂存区放在原指令所有静态 sp 访问(含负偏移、前变址写回)之下。
Place the scratch area for borrowed registers below every static sp access of the original instruction (including negative offsets and pre-index writeback)."""
from capstone.arm64 import ARM64_OP_MEM, ARM64_REG_SP, ARM64_REG_INVALID
floor = min(0, sp_delta(ins))
for op in ins.operands:
if op.type == ARM64_OP_MEM and op.mem.base == ARM64_REG_SP:
assert op.mem.index == ARM64_REG_INVALID, f'android 不支持 sp 加寄存器下标 {ins.address:x} {ins.op_str}'
floor = min(floor, op.mem.disp)
frame = (scratch - floor + 15) & ~15
assert frame <= 0xFFF, f'android 暂存帧过大 {ins.address:x} {frame}'
return frame
def site_plain_android(ins):
S, T = pick(regs_in(ins))
dlt = sp_delta(ins)
assert dlt % 16 == 0, f'android sp 写回破坏 16 字节对齐 {ins.address:x} {dlt}'
start = here()
w = subst(ins, S)
if uses_sp(ins):
(U,) = pick(regs_in(ins) | {S, T}, 1)
frame = android_frame(ins)
emit(SUBI(31, 31, frame)); emit(STP(S, T, 31, 0)); emit(STRX(U, 31, 2)); emit(ADDI(U, 31, frame))
emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(subst_sp(ins, w, U))
emit(STRX(S, T))
emit(LDRX(U, 31, 2)); emit(LDP(S, T, 31, 0))
assert 0 <= frame + dlt <= 0xFFF, f'android sp 收尾超范围 {ins.address:x} {frame + dlt}'
if frame + dlt: emit(ADDI(31, 31, frame + dlt))
else:
assert dlt == 0
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(w); emit(STRX(S, T))
restore_pair(S, T)
emit(B(here(), ins.address + 4))
return start
def site_plain(ins):
if ABI == 'android': return site_plain_android(ins)
S, T = pick(regs_in(ins))
dlt = sp_delta(ins)
save = -16 if dlt == 0 else -112 # 改 sp 的指令会写到 sp 下方,暂存放到保留区深处 | Instructions that modify sp write below sp, so the scratch save is placed deep in the reserved area
assert dlt == 0 or dlt >= -96, f'sp delta {dlt} at {ins.address:x}'
start = here()
emit(STP(S, T, 31, save)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(STP(S, T, 31, save)); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
emit(subst(ins, S))
emit(STRX(S, T)) # 一律写回:capstone 会漏报写入(adds w18 实例) | Always write back: capstone can miss reporting a write (the adds w18 instance)
emit(LDP(S, T, 31, save - dlt)); emit(B(here(), ins.address + 4))
@@ -343,34 +436,35 @@ def site_cond(ins):
S, T = pick(regs_in(ins))
tgt = ins.operands[-1].imm
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
m = ins.mnemonic
taken = here() + 4 * 3
off = (taken - here()) >> 2
nw = ((w & 0xFF000000) | ((off & 0x7FFFF) << 5) | S) if m in ('cbz', 'cbnz') else ((w & 0xFFF80000) | ((off & 0x3FFF) << 5) | S)
pc = here(); emit(nw)
dd = dis(nw, pc); assert dd.mnemonic == m and dd.operands[-1].imm == taken
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
restore_pair(S, T); emit(B(here(), ins.address + 4))
assert here() == taken
emit(LDP(S, T, 31, -16)); emit(B(here(), tgt))
restore_pair(S, T); emit(B(here(), tgt))
return start
def site_pcrel(ins):
tgt = ins.operands[1].imm
S, T = pick(set())
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18') # S 先作键页偏移暂存,下一条再装目标值 | S first serves as a temporary for the key page offset; the next instruction then loads the target value
save_pair(S, T); emit_slot_base(T); emit_slot_addr(T, S, 'K18') # S 先作键页偏移暂存,下一条再装目标值 | S first serves as a temporary for the key page offset; the next instruction then loads the target value
pc = here(); emit(ADRP(S, pc, tgt))
if ins.mnemonic == 'adr': emit(ADDI(S, S, tgt & 0xFFF))
emit(STRX(S, T))
emit(LDP(S, T, 31, -16)); emit(B(here(), ins.address + 4))
restore_pair(S, T); emit(B(here(), ins.address + 4))
return start
def site_br(ins, base, count):
"""跳转表 br x18:目标 = base + 4i。x16 暂存红区 → 等距落地垫 → 恢复 x16 → 原目标。 | Jump table br x18: target = base + 4i. Stash x16 in the red zone → equally spaced landing pads → restore x16 → original target."""
start = here()
emit(STUR(16, 31, -16)); emit(STUR(17, 31, -24)) # x16 / x17 是函数内可存活的临时寄存器,借用前存红区 | x16 / x17 are temporary registers that can stay live within a function; save them to the red zone before borrowing
emit(MRS_TPIDRRO(16)); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(LDUR(17, 31, -24))
if ABI == 'android': emit(STP_PRE(16, 17, 31, -16)) # 没有红区:先减 sp 再存 | No red zone: lower sp first, then store
else: emit(STUR(16, 31, -16)); emit(STUR(17, 31, -24)) # x16 / x17 是函数内可存活的临时寄存器,借用前存红区 | x16 / x17 are temporary registers that can stay live within a function; save them to the red zone before borrowing
emit_slot_base(16); emit_slot_addr(16, 17, 'K18'); emit(LDRX(16, 16)); emit(LDRX(17, 31, 1) if ABI == 'android' else LDUR(17, 31, -24))
padbase = start + 4 * 24
delta = padbase - base
op = ADDI if delta >= 0 else SUBI; dl = abs(delta)
@@ -380,20 +474,37 @@ def site_br(ins, base, count):
assert len(ops) <= 12
for o in ops: emit(o)
emit(BR(16))
assert here() <= padbase, f'跳转表块超出落地垫基址 {base:#x}'
while here() < padbase: emit(NOP)
tails = padbase + 4 * count
for i in range(count): emit(B(here(), tails + 8 * i))
for i in range(count):
emit(0xF85F0000 | (31 << 5) | 16) # ldur x16,[sp,#-16]
emit(LDP_POST(16, 17, 31, 16) if ABI == 'android' else 0xF85F0000 | (31 << 5) | 16) # android ldp x16,x17,[sp],#16 / apple ldur x16,[sp,#-16]
emit(B(here(), base + 4 * i))
return start
def emit_slot_read(N, tmp, kind):
"""xN = 线程槽 kind 的值,借 tmp。apple:tmp 存红区;android:先减 sp 存 tmp(与 xzr 成对保持 16 字节)。
xN = value of thread slot kind, borrowing tmp. apple: tmp is saved in the red zone; android: lower sp first and store tmp (paired with xzr to keep 16 bytes)."""
if ABI == 'android':
assert N not in (18, 31) and tmp != N
emit(STP_PRE(tmp, 31, 31, -16)); emit_slot_base(N); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDP_POST(tmp, 31, 31, 16))
else:
emit(STUR(tmp, 31, -16)); emit_slot_base(N); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp 存红区借用 | tmp is saved by borrowing the red zone
def site_sysreg_read(ins, kind):
"""mrs xN, tpidr_el0 / tpidrro_el0 → xN = 线程槽值。 | mrs xN, tpidr_el0 / tpidrro_el0 → xN = thread slot value."""
N = ins.bytes[0] & 31
tmp = 16 if N != 16 else 17
start = here()
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(N)); emit_slot_addr(N, tmp, kind); emit(LDRX(N, N)); emit(LDUR(tmp, 31, -16)) # tmp 存红区借用 | tmp is saved by borrowing the red zone
if ABI == 'android' and N == 31: pass # mrs xzr:无副作用 | mrs xzr: no effect
elif ABI == 'android' and N == 18:
# x18 是虚拟寄存器(槽 K18),不碰硬件 x18:槽 kind → 槽 K18 | x18 is virtual (slot K18), never touch hardware x18: slot kind -> slot K18
emit(SUBI(31, 31, 32)); emit(STP(16, 17, 31, 0)); emit(STRX(15, 31, 2))
emit_slot_base(17); emit_slot_addr(17, 16, kind); emit(LDRX(15, 17))
emit_slot_base(17); emit_slot_addr(17, 16, 'K18'); emit(STRX(15, 17))
emit(LDRX(15, 31, 2)); emit(LDP(16, 17, 31, 0)); emit(ADDI(31, 31, 32))
else: emit_slot_read(N, tmp, kind)
emit(B(here(), ins.address + 4))
return start
@@ -401,10 +512,19 @@ def site_tpidr_write(ins):
N = struct.unpack('<I', ins.bytes)[0] & 31
(T,) = pick({N}, 1)
start = here()
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
tmp = next(x for x in (16, 17) if x not in (N, T))
emit(STUR(tmp, 31, -24)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDUR(tmp, 31, -24))
emit(0xF85F0000 | (31 << 5) | T) # ldur xT,[sp,#-16]
if ABI == 'android' and N == 18:
# msr tpidr_el0, x18:x18 的值在槽 K18 | msr tpidr_el0, x18: the value of x18 lives in slot K18
emit(SUBI(31, 31, 32)); emit(STP(16, 17, 31, 0)); emit(STRX(15, 31, 2))
emit_slot_base(17); emit_slot_addr(17, 16, 'K18'); emit(LDRX(15, 17))
emit_slot_base(17); emit_slot_addr(17, 16, 'KTLS'); emit(STRX(15, 17))
emit(LDRX(15, 31, 2)); emit(LDP(16, 17, 31, 0)); emit(ADDI(31, 31, 32))
elif ABI == 'android':
emit(STP_PRE(T, tmp, 31, -16)); emit_slot_base(T); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDP_POST(T, tmp, 31, 16))
else:
emit(0xF81F0000 | (31 << 5) | T) # stur xT,[sp,#-16]
emit(STUR(tmp, 31, -24)); emit_slot_base(T); emit_slot_addr(T, tmp, 'KTLS'); emit(STRX(N, T)); emit(LDUR(tmp, 31, -24))
emit(0xF85F0000 | (31 << 5) | T) # ldur xT,[sp,#-16]
emit(B(here(), ins.address + 4))
return start
@@ -417,7 +537,7 @@ def emit_gate_call():
Fetching the slot through the key page needs a second register to be borrowed; x29 is borrowed and then immediately restored from the stack: the x29 saved by _dm_gate must be the guest's original value --
the host identifies the caller by [x29+8] (skill binding observation gate 6, private aiming gate svc86), and the crash backtrace also walks the x29 chain
(since r24 plan C it was borrowed and not returned, the x29 the host got was the slot offset from the key page, and skill icons fell back to placeholder text)."""
emit(MRS_TPIDRRO(30)); emit_slot_addr(30, 29, 'KGATE'); emit(LDRX(30, 30)); emit(LDRX(29, 31))
emit_slot_base(30); emit_slot_addr(30, 29, 'KGATE'); emit(LDRX(30, 30)); emit(LDRX(29, 31))
def site_gate(ins, kind, arg):
"""svc / mrs cntpct_el0 → 宿主门。门地址取自线程槽 KGATE;门按返回点(本块 ldp 的地址)查 gates.tsv。 | svc / mrs cntpct_el0 → host gate. The gate address is taken from thread slot KGATE; the gate looks up gates.tsv by return point (the address of this block's ldp)."""
@@ -472,18 +592,30 @@ def site_window(seg):
S, T = pick(used)
lo, hi = seg[0].address, seg[-1].address + 4
start = here()
emit(STP(S, T, 31, -16)); emit(MRS_TPIDRRO(T)); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
# android 没有红区:先减 sp 再存借用寄存器;窗口里有引用 sp 的指令时,sp 换成 U(= 原 sp),暂存帧放在它们的访问范围之下
# android has no red zone: lower sp first, then save the borrowed registers; when the window references sp, sp is replaced by U (= original sp) and the scratch frame goes below their accesses
U = frame = None
if ABI == 'android' and any(uses_sp(x) for x in seg):
assert all(sp_delta(x) == 0 for x in seg), f'android 独占窗口里改 sp {lo:#x}'
(U,) = pick(used | {S, T}, 1)
frame = max(android_frame(x) for x in seg)
emit(SUBI(31, 31, frame)); emit(STP(S, T, 31, 0)); emit(STRX(U, 31, 2)); emit(ADDI(U, 31, frame))
else:
save_pair(S, T)
emit_slot_base(T); emit_slot_addr(T, S, 'K18'); emit(LDRX(S, T))
copy0 = here(); n = len(seg)
exits = copy0 + 4 * n
stride = 32 if U is not None else 16
ex_targets = []; words = []
for k, x in enumerate(seg):
w = struct.unpack('<I', x.bytes)[0]
if has18(x): w = subst(x, S)
if U is not None and uses_sp(x): w = subst_sp(x, w, U)
m = x.mnemonic
if m in ('cbz', 'cbnz', 'tbz', 'tbnz') or m.startswith('b.'):
tgt = x.operands[-1].imm
if lo <= tgt < hi: newt = copy0 + (tgt - lo)
else: ex_targets.append(tgt); newt = exits + 16 * len(ex_targets) # 出口桩第 0 个留给顺序落出(见下),窗口外的目标从第 1 个起 | Exit stub 0 is reserved for the sequential fall-out (see below); targets outside the window start from stub 1
else: ex_targets.append(tgt); newt = exits + stride * len(ex_targets) # 出口桩第 0 个留给顺序落出(见下),窗口外的目标从第 1 个起 | Exit stub 0 is reserved for the sequential fall-out (see below); targets outside the window start from stub 1
pc = copy0 + 4 * k; off = (newt - pc) >> 2
if m in ('tbz', 'tbnz'): w = (w & 0xFFF8001F) | ((off & 0x3FFF) << 5)
else: w = (w & 0xFF00001F) | ((off & 0x7FFFF) << 5)
@@ -501,7 +633,12 @@ def site_window(seg):
# (one operation done twice / a lock-free list popped more than once). The game has 6 such windows (main 0x1848eb8 / 0x1848f28 / 0x1848f84, sdk 0x2ea0fc / 0x2ea4cc / 0x2ea644);
# windows whose only branch is a cbnz back into the window are not affected. The equivalence check used to never draw the "compare equal" direction at random, so it stayed green (equiv.py now forces both directions of window branches).
for t in [hi] + ex_targets:
emit(STRX(S, T)); emit(LDP(S, T, 31, -16)); emit(B(here(), t)); emit(NOP)
e0 = here()
emit(STRX(S, T))
if U is not None: emit(LDRX(U, 31, 2)); emit(LDP(S, T, 31, 0)); emit(ADDI(31, 31, frame))
else: restore_pair(S, T)
emit(B(here(), t))
while here() < e0 + stride: emit(NOP)
return start, lo, hi
# ---- 函数边界(eh_frame_hdr)----
@@ -788,8 +925,7 @@ for oa, wa, ob_, wb, r, key, why in params:
ins = dis(struct.unpack_from('<I', IMG, o)[0], o)
assert r not in regs_in(ins), f'参数位中间用到 x{r}:{o:#x} {ins.mnemonic} {ins.op_str}'
start = here()
tmp = 16 if r != 16 else 17
emit(STUR(tmp, 31, -16)); emit(MRS_TPIDRRO(r)); emit_slot_addr(r, tmp, key); emit(LDRX(r, r)); emit(LDUR(tmp, 31, -16)); emit(B(here(), oa + 4))
emit_slot_read(r, 16 if r != 16 else 17, key); emit(B(here(), oa + 4))
struct.pack_into('<I', IMG, oa, B(oa, start)); struct.pack_into('<I', IMG, ob_, NOP); stat('param')
# 既有三块原生规则跳板均只使用后继覆盖的死临时w8,不改w0/stat返回、sp或NZCV。
@@ -852,6 +988,7 @@ elif os.path.exists(P('rules.tsv')):
with open(P('fixups.tsv'), 'w') as f:
f.write(f'# PATCH_OFF\t{PATCH_OFF:#x}\n# KEY_PAGE_OFF\t{KEY_PAGE_OFF:#x}\n# KEY_PAGE_SIZE\t0x4000\n# TEXT_END\t{TEXT_END:#x}\n# RO_OFF\t{RO_OFF:#x}\n# DATA_OFF\t{DATA_OFF:#x}\n')
for k in KEY_INDEX: f.write(f'# KEY_{k}_IDX\t{KEY_INDEX[k]}\n')
if ABI == 'android': f.write(f'# ABI\tlinux-bionic\n# TP_SLOT_OFF\t{ANDROID_TP_OFF:#x}\n') # 苹果宿主读到非数值行即拒载 | the Apple host refuses to load on a non-numeric line
with open(P('gates.tsv'), 'w') as f:
for ret, k, arg, orig in gates: f.write(f'{ret:#x}\t{k}\t{arg}\t{orig:#x}\n')
with open(P('sites.tsv'), 'w') as f:
+7 -4
View File
@@ -4,23 +4,26 @@
# product.sh path <种类> → 本机缺省产物目录 $DM_ROOT/build/cache/dm/out/<name>
# product.sh rev → r28
# product.sh build → 重出三种产物(keypage / rules / touch)到本机缺省目录
# DM_ABI=android(缺省 apple)→ 以上名字 / 目录都带 -android 后缀,改写器出 Linux Bionic 版
# The codename of the current rewrite build output is written in exactly one place: dm/PRODUCT (one line, e.g. 3.3.94012-r28). A revision bump changes only that line.
# Usage: product.sh name <kind> → 3.3.94012-r28-<kind> (kind: touch / rules / keypage)
# product.sh path <kind> → local default build output directory $DM_ROOT/build/cache/dm/out/<name>
# product.sh rev → r28
# product.sh build → rebuild the three kinds of build output (keypage / rules / touch) into the local default directory
# DM_ABI=android (default apple) → the names / directories above get an -android suffix and the rewriter emits the Linux Bionic variant
set -u
P=$(head -1 "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/PRODUCT") || exit 2
[ -n "$P" ] || { echo "dm/PRODUCT 为空" >&2; exit 2; }
case "${DM_ABI:=apple}" in apple) X=;; android) X=-android;; *) echo "未知 DM_ABI=$DM_ABI" >&2; exit 2;; esac; export DM_ABI
case "${1:-}" in
name) echo "$P-${2:?种类}";;
path) echo "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-${2:?种类}";;
name) echo "$P-${2:?种类}$X";;
path) echo "${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-${2:?种类}$X";;
rev) echo "${P##*-}";;
build) # 用本工作树的改写器重出三种产物到本机缺省目录(换代 / 改了 patch_nso.py 之后跑)。种类 → 规则集:keypage = 原生;rules = 触屏规则、不带宿主私有门;touch = 触屏规则 + 私有门 | Rebuild the three kinds of build output with this worktree's rewriter into the local default directory (run after a revision bump / after changing patch_nso.py). Kind → rule set: keypage = native; rules = touchscreen rules, without host-private gates; touch = touchscreen rules + private gates
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); PY=${DM_PY:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/venv/bin/python3}; NSO=${DM_NSO_DIR:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/ExeFS}
for k in keypage rules touch; do O=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-$k; mkdir -p "$O"
for k in keypage rules touch; do O=${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/$P-$k$X; mkdir -p "$O"
case $k in keypage) E=(DM_RULESET=native);; rules) E=(DM_RULESET=touch-run-v4 DM_PRIVATE_GATES=0);; touch) E=(DM_RULESET=touch-run-v4);; esac
for m in main sdk subsdk0; do env "${E[@]}" "$PY" "$HERE/patch_nso.py" "$NSO/$m" "$O" "$m" > "$O/$m.patch.log" 2>&1 || { echo "🔴 $k $m 改写失败:$(tail -2 "$O/$m.patch.log")" >&2; exit 1; }; done
echo "$P-$k 已出:$(ls "$O" | wc -l | tr -d ' ') 个文件"; done;;
echo "$P-$k$X 已出:$(ls "$O" | wc -l | tr -d ' ') 个文件"; done;;
*) echo "用法:product.sh name|path <种类> | rev | build" >&2; exit 2;;
esac
+2
View File
@@ -0,0 +1,2 @@
# 由原版技能表生成(构建时从玩家自己的游戏文件生成,不进仓库;ios/tools/gen_assets.py) | Generated from the original skill tables at build time, not committed
dm_touch_native_art.c
@@ -1,5 +1,5 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include "../host/dm_input.h"
#include <math.h>
#include <string.h>
@@ -1,6 +1,6 @@
#include "dm_touch_game_state.h"
#include "dm_touch_game_identity.h"
#include "../../host/dm.h"
#include "../host/dm.h"
enum { OBS_BINDING_GETTER=6, MAPPING_OFFSET=0x2d13cbc, BINDING_OFFSET=0x2d5f0c0 };
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static dm_tg_snapshot latest;
@@ -3,6 +3,9 @@
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/vm_map.h>
#elif defined(__linux__)
#include <sys/uio.h>
#include <unistd.h>
#endif
int dm_tg_vm_read(uint64_t address,void *out,size_t bytes) {
if(!out || !bytes || !address || address>UINT64_MAX-bytes)return 0;
@@ -10,6 +13,10 @@ int dm_tg_vm_read(uint64_t address,void *out,size_t bytes) {
vm_size_t copied=0;
kern_return_t rc=vm_read_overwrite(mach_task_self(),(vm_address_t)address,(vm_size_t)bytes,(vm_address_t)out,&copied);
return rc==KERN_SUCCESS && copied==bytes;
#elif defined(__linux__)
/* 读自己进程:process_vm_readv 读不到的页返回短读 / -1,不触发 SIGSEGV(同 vm_read_overwrite) | Read our own process: process_vm_readv returns a short read / -1 on unreadable pages instead of raising SIGSEGV (same as vm_read_overwrite) */
struct iovec l={out,bytes},r={(void*)(uintptr_t)address,bytes};
return process_vm_readv(getpid(),&l,1,&r,1,0)==(ssize_t)bytes;
#else
(void)address;return 0;
#endif
@@ -1,5 +1,5 @@
#include "dm_touch_game_state.h"
#include "../../host/dm_input.h"
#include "../host/dm_input.h"
#include <string.h>
static uint32_t u32(const unsigned char *p) {
return (uint32_t)p[0]|(uint32_t)p[1]<<8|(uint32_t)p[2]<<16|(uint32_t)p[3]<<24;

Some files were not shown because too many files have changed in this diff Show More