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
@@ -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>