Initial public release

This commit is contained in:
jhaizhou
2026-10-12 16:51:08 +08:00
commit 46578a2b5d
997 changed files with 218713 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
DmIOS.xcodeproj/
Sources/Info.plist
Sources/DmIOS.entitlements
Gen/
RomfsDownloader/Info.plist
RomfsDownloader/RomfsDownloader.entitlements
local.env
# 由原版图 / 表生成的(构建时从玩家自己的游戏文件生成,不进仓库;tools/gen_assets.py)
Sources/TouchArt/dm_native_*.png
Sources/dm_touch_native_art.c
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

@@ -0,0 +1,4 @@
{
"images" : [ { "filename" : "AppIcon1024.png", "idiom" : "universal", "platform" : "ios", "size" : "1024x1024" } ],
"info" : { "author" : "xcode", "version" : 1 }
}
+1
View File
@@ -0,0 +1 @@
{ "info" : { "author" : "xcode", "version" : 1 } }
+52
View File
@@ -0,0 +1,52 @@
# NativeHUD — bottom bar
中文:[README.zh-CN.md](README.zh-CN.md)
The strip at the bottom of the screen in game: life orb, mana orb, belt, town portal, feature entry, experience bar. Most of it is not UI drawn by the shell itself but widgets of the game's original HUD (the always-present in-game UI), rearranged.
## Arrangement
From left to right:
Stick area → statue holding the life orb → seven slots → statue holding the mana orb → skill area
The seven slots in the middle are, in order: difficulty (tapping it opens a selection strip of 1–8), four belt slots, town portal, feature entry (opens feature pages such as the inventory). Above the seven slots is the experience bar.
## How it is done
No mod is used; it goes through the overlay RomFS (a small set of assets generated at build time and shipped with the app, which the game checks first when reading files; see "Overlay RomFS" in [../README.md](../README.md)). Two things are replaced in the overlay:
- **The gamepad HUD layout**. The original layout has the structural patch kept in the repository, `../tools/touchrectv1_patch.json`, applied to it (for the patch format see `../tools/layout_patch.py`), and is then arranged into the layout above by `../tools/gen_hud_v4.py`. For the original widgets only position and scale are changed: the life orb, mana orb and belt are as before; town portal uses the original sixth skill button, and the feature entry uses the original `升级` (Level Up) button. The original experience bar is moved off screen and is instead drawn by the shell according to the new geometry.
- **One base image**: the stone strip, the seven slot frames and the statues on both sides, with the orb centres cut out so that the orb liquid the game itself draws shows through. The base image is written to an old texture path the game no longer reads, registered in `dm/data/casc_overlay/borrowed_paths.tsv`.
In the skill area on the right, the game's five original skill buttons still occupy their places in the layout, and the skill circles the shell draws with UIKit are stacked on top of them (`../Sources/DmTouchOverlay.m`). The experience bar, the difficulty number and the selection strip are also drawn by this layer, with art and geometry generated at build time.
What a finger tap on these widgets counts as is decided by the layout in `../Sources/dm_touch_controls.c` (`dm_tc_layout_make`): it converts the tap areas onto the same set of seven slots according to the screen height, aligned with the picture.
## What is in this directory
The repository holds only what we drew ourselves:
| File | Contents |
|---|---|
| `touch/close.png` | The close button image for the top-right corner of the panel frame, drawn by `../tools/gen_close_btn.py` |
The base image, layout and glyphs derived from the original are not kept in the repository. At `../run.sh build` time they are generated by `../tools/gen_assets.py` from your game files into `../Gen/assets/NativeHUD/`:
| Output | Contents | Generation script |
|---|---|---|
| `v4/base.png` | Base image | `../tools/gen_hud_v4.py` (geometry and art sources are in `../tools/hud_v4_design.py`) |
| `v4/hud.json` | The modified gamepad HUD layout | Same as above |
| `v4/hud_v4_ui/` | Art and geometry used by the UIKit layer | Same as above |
After that, `../tools/gen_romfs_overlay.py` writes the base image and the layout into the overlay `../Gen/romfs_overlay`.
The art for the base image has two sources: when an unpacked directory of the PC version of the game is available (environment variable `DM_PC_DATA`), its 2x originals are used; otherwise the same-named art from the Switch version is upscaled, which is slightly blurry. For where to put it and how to set it, see "Generating assets from your game files" in [../../README.md](../../README.md).
## How to check after making changes
```bash
dm/ios/tools/check_hud_gen.sh
```
It checks two things: that these generated files have not been committed to the repository; and, when the game files are present on your machine, it actually generates the bottom bar once and reports red if that fails. When your machine has no game files, the second item is skipped.
+52
View File
@@ -0,0 +1,52 @@
# NativeHUD — 底栏
English: [README.md](README.md)
局内屏幕底部那一条:血球、蓝球、腰带、回城、功能入口、经验条。其中大部分不是外壳自己画的界面,而是游戏原版的 HUD(局内常驻界面)部件,重新排了位置。
## 排布
从左到右:
摇杆区 → 抱着血球的雕像 → 七格 → 抱着蓝球的雕像 → 技能区
中间七格依次是:难度(点开是 1–8 的选择条)、四格腰带、回城、功能入口(开背包等功能页)。七格上方是经验条。
## 怎么做到的
不用 mod,走覆盖层 RomFS(构建时生成、App 自带的一小份资源,游戏读文件时先查它,见 [../README.zh-CN.md](../README.zh-CN.md)「覆盖层 RomFS」)。覆盖层里替换两样东西:
- **手柄版 HUD 布局**。原版布局套上仓库里的结构补丁 `../tools/touchrectv1_patch.json`(补丁格式见 `../tools/layout_patch.py`),再由 `../tools/gen_hud_v4.py` 摆成上面的排布。原版部件只改位置与缩放:血球、蓝球、腰带照旧;回城用的是原版第六个技能钮,功能入口用的是原版「升级」按钮。原版的经验条被挪出屏幕,改由外壳按新的几何来画。
- **一张底图**:石条、七个格框、两侧雕像,球心挖空,让游戏自己画的球液透出来。底图写在一个游戏不再读取的旧贴图路径上,登记在 `dm/data/casc_overlay/borrowed_paths.tsv`。
右侧技能区里,游戏原版的五个技能钮仍在布局里占着位置,外壳用 UIKit 画的技能圈叠在它们上面(`../Sources/DmTouchOverlay.m`)。经验条、难度数字和选择条也由这一层画,素材与几何在构建时生成。
手指点在这些部件上算什么,由 `../Sources/dm_touch_controls.c` 的布局决定(`dm_tc_layout_make`):它按屏幕高度把点击区换算到同一组七格上,和画面对齐。
## 这个目录里有什么
仓库里只放自己画的东西:
| 文件 | 内容 |
|---|---|
| `touch/close.png` | 面板外框右上角的关闭按钮图,由 `../tools/gen_close_btn.py` 画出 |
从原版衍生的底图、布局、字形都不进仓库。`../run.sh build` 时由 `../tools/gen_assets.py` 从你的游戏文件生成到 `../Gen/assets/NativeHUD/`:
| 产物 | 内容 | 生成脚本 |
|---|---|---|
| `v4/base.png` | 底图 | `../tools/gen_hud_v4.py`(几何与素材来源在 `../tools/hud_v4_design.py`) |
| `v4/hud.json` | 改好的手柄版 HUD 布局 | 同上 |
| `v4/hud_v4_ui/` | UIKit 那一层用的素材与几何 | 同上 |
之后 `../tools/gen_romfs_overlay.py` 把底图和布局写进覆盖层 `../Gen/romfs_overlay`。
底图的素材有两个来源:有 PC 版游戏的解包目录时(环境变量 `DM_PC_DATA`)用它的 2 倍原图;没有就把 Switch 版的同名素材放大,会略糊。放哪、怎么设见 [../../README.zh-CN.md](../../README.zh-CN.md)「从你的游戏文件生成资源」。
## 改了之后怎么检查
```bash
dm/ios/tools/check_hud_gen.sh
```
它检查两件事:这些生成物没有被提交进仓库;本机有游戏文件时,把底栏实际生成一遍,跑不通就报红。本机没有游戏文件时第二项跳过。
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

+283
View File
@@ -0,0 +1,283 @@
# dm/ios — iOS shell
中文:[README.zh-CN.md](README.zh-CN.md)
The iOS app of D2R Mobile: it packs the host (`dm/host`), the graphics layer (`dm/gfx`) and the rewritten game program into one app, and is responsible for starting up, locating the game assets, turning touches into input the game understands, and laying touch controls over the original UI.
Read these first; this document does not repeat them:
- What you need and how to build from scratch: [../../README.md](../../README.md), [../../setup.sh](../../setup.sh)
- Dependencies and versions: [../../docs/DEPENDENCIES.md](../../docs/DEPENDENCIES.md)
- How to prepare the game files and where to put them: [../../docs/GAME_FILES.md](../../docs/GAME_FILES.md)
- The rewriter, the host, the graphics layer, and "Generating assets from your game files": [../README.md](../README.md)
In this document `$DM_ROOT` means the workspace root (default `~/dm-work`). Relative paths in commands are relative to `dm/ios` unless stated otherwise.
## How it works
### What gets packed into the app at build time
iOS does not allow an ordinary app to execute code that was written into memory at run time, so the game program cannot be loaded at startup the way it is on the Mac host. Instead it is compiled into the app's executable at build time:
- `tools/gen_embed.py` turns the rewritten module images (`main`, `sdk`) into an embedded assembly file `Gen/embed.S`, which places them into segments of the executable in their original relative layout. On iOS the host's loader only takes the addresses of these segments and checks the layout; it does not copy code and does not change page permissions.
- `tools/gen_build.py` takes the host's source files, header paths and frameworks from the compile commands that `dm/host/Makefile` actually expands to, and generates `Gen/dm.xcconfig` and `Gen/src/`. The host's `main.c` is compiled in with `-Dmain=dm_main` and is called by the app on its own thread.
- The shader libraries (the iOS versions translated by `setup.sh`), the shader mapping table, the relocation table and gate table used for loading, and the overlay RomFS (see below) ship with the app as resources.
The project file is not kept in the repository: `project.yml` is the input to XcodeGen (a tool that generates an Xcode project from a YAML file), and `run.sh build` regenerates `DmIOS.xcodeproj` and `Gen/` every time.
### Startup
The entry point is in `Sources/main.m`. The app uses the launch argument `-mode <name>` to choose what to run; the default is `boot` (start the game). The sequence in `boot` mode:
1. Raise the process's soft limit on file descriptors to 4096 (once in a game, the number of files the game has open at the same time comes close to the iOS default limit).
2. Open the log: `Documents/boot.txt`, flushed to disk line by line; the log of the previous launch is renamed to `Documents/boot.previous.txt`. What the host writes to standard error also goes into this file.
3. Check whether the GPU supports BC-compressed textures. Models that do not support them need the matching ASTC supplement pack (produced by `dm/tools/astc_pack.py`); if it cannot be found, a dialog explains this and the game is not started. How to make the supplement pack and get it onto the phone is in "Models without BC texture support" below.
4. Locate the game assets (next section). If found, prepare the environment: `boot_prepare` sets the environment variables the host reads, such as `DM_ROMFS` (asset root), `DM_ROMFS_OVERLAY` (overlay), `DM_SAVE` (save directory `Documents/save`), `DM_TEMP` and `DM_MSL_DIR` (shader libraries), changes the working directory to `Documents`, and calls `dm_host_preload_start` so that the host starts loading on a background thread, in parallel with UIKit's startup.
5. Once the scene is set up, the root view is replaced with the Metal view returned by `front_ios_view` (`Sources/front_ios.m`, the iOS implementation of the host's front-end interface `dm/host/front.h`).
6. `boot_thread`, on a thread with a 64 MB stack, first does the iCloud save sync (`Sources/cloud_ios.m`) and then calls `dm_main` to enter the host; from then on the game is running.
Lifecycle events such as going to the background, returning to the foreground and scene disconnection are forwarded by the `SceneDelegate` in `main.m` to `front_ios.m`; when the app terminates, `dm_host_shutdown` is called so the host can shut down in order.
The remaining modes are for diagnostics: the three probes `anon`, `mapjit` and `file` try "execute an anonymous page after writing to it", "MAP_JIT mapping" and "map a file inside the sandbox as executable" respectively, to confirm the restriction described above; the `tsd` probe tries the fixed slots of thread-local storage; `msl` loads the shader libraries inside the app one by one; `blank` runs only a blank Metal clear-screen page (a heat baseline); `thermal` reads the system thermal level once and exits.
### Locating the game assets
`romfs_locate` in `main.m` searches in the order below, and the first match wins; every location is checked with `dm_romfs_validate` (`dm/host/romfs_validate.c`) to confirm that all 18 archive files are present and that their byte counts match:
1. `Library/Application Support/romfs` in the app container. This is the location used during development; push the files in from the Mac:
```bash
xcrun devicectl device copy to --device <device identifier> \
--domain-type appDataContainer --domain-identifier <bundle ID> \
--source $DM_ROOT/data/switch/3.3.94012/Update/RomFS \
--destination 'Library/Application Support/romfs'
```
2. A folder inside the app's `Documents` (visible in the Files app) that directly contains the archive files. The folder can have any name and can be nested a few levels deep (up to 4); if it is incomplete, the missing files are listed on screen.
3. An Apple-hosted asset pack (Background Assets, large file packs downloaded along with the app install), with the pack name `romfs`. `RomfsDownloader/` is the download extension it requires.
4. None of the above: the host is not started, and the asset screen (`AssetVC` in `main.m`) is shown with the progress or the reason; once the assets are in place, tapping retry enters the game on the spot.
Only those 18 archive files are checked: the configuration file used is the one in the overlay bundled with the app, and the game does not read the keys or the archive list, so none of them need to be copied.
`Sources/asset_dl.m` implements a path that downloads the assets directly from an HTTP address (the manifest is generated by `tools/asset_manifest.py`). The `asset_pointers.txt` in the repository registers no address, so unless `DM_ASSET_BASE` is also passed at build time, this path does not take effect.
### Turning touches into input
The Switch version of the game only recognizes two kinds of input, the gamepad and the touch screen. The shell translates finger actions into these two, plus direct clicks on the game UI.
- **Collection**: `DmMetalView` in `front_ios.m` receives all `UITouch` objects in one place.
- **Classification**: `Sources/dm_touch_controls.c` is a pure C state machine with no dependency on UIKit (`dm_tc_*`): which finger belongs to the stick, a skill button, a belt slot or the UI, what a tap / double tap / long press / drag and drop each count as, and as output the gamepad buttons that should currently be pressed and the values of the left and right sticks. It can be unit-tested without a device (see "Unit tests").
- **Publication**: on every state change, `pushFrom:phase:` of `DmMetalView` hands the results to the host together: `dm_touch_set` (raw touch points, for the game to read as the touch screen), `dm_cursor_set_screen` (UI cursor position), `dm_input_set` (gamepad buttons and sticks). The host applies them when the game reads the gamepad (`dm/host/hle_hid.c`, `dm/host/dm_cursor.c`).
There are three cases depending on which UI the game is currently in. Switching between them is driven by the UI messages the game itself emits (`dm_tc_navigation`), not by guessing:
| Case | How the shell handles touches |
|---|---|
| Front-end pages (main menu, character select, character creation) | The stick and skill buttons are not shown; touch points become mouse clicks on the game UI through `dm_ui_touch` |
| In game, no panel open | The stick on the left, the skill buttons on the right and the bottom bar buttons each become gamepad buttons and stick values; a tap in the world (a monster, an item name, an NPC, a chest) is handed to the host through `dm_ui_world_tap` to resolve the target, and a tap on empty ground sends no input at all |
| In game, with a panel or dialogue open | The finger taps the UI directly: on an item slot, single tap to see the description, double tap to use, long press, drag and drop; tabs, buttons, and tapping outside a panel to close it. What was hit is answered by the host according to the game's own panel tree, and the front end decides from that whether to send a mouse click or a gamepad button |
### How the touch controls relate to the original UI
The principle is to use the game's own UI widgets as far as possible; the shell only adds the layer the game does not have:
- The life orb, mana orb, belt, town portal and feature entry of the **bottom bar** are the game's original HUD widgets; only their positions and scale are changed, through a layout file in the overlay. The experience bar and the numbers on the slots are drawn by the shell. See [NativeHUD/README.md](NativeHUD/README.md) for details.
- The **stick and skill buttons** are drawn on top of the game picture with UIKit by `Sources/DmTouchOverlay.m`. This layer only draws and does not receive touches. The icons on the skill buttons come from the game's skill atlas, and which skill is currently bound is read, read-only, from the running game by `Sources/dm_touch_game_bridge.c`.
- The **panels** are all the game's original panels. The overlay moves the gamepad button hints of the original layout off screen, adds a close button to the panels, and replaces gamepad wording in hint texts with touch wording (`tools/touch_layout.py`, `tools/touch_strings.py`).
### Overlay RomFS
The overlay is a small RomFS that ships with the app: when the host reads a game file it looks in the overlay first, and only if the file is not there does it read the full game assets (`DM_ROMFS_OVERLAY`, `dm/host/hle_fs.c`, `dm/host/hle_tact.c`). This way UI layouts and textures can be changed without touching the player's game files.
`run.sh build` generates it by calling `tools/gen_romfs_overlay.py <original RomFS> Gen/romfs_overlay`: it reads the original layouts and strings from your game files, applies the changes kept in the repository, and writes a new `.build.config` plus one new data archive.
- The repository stores only "what was changed", not the original content: layouts use structural patches (`tools/layout_patch.py`), and string tables are replaced by key name, with the checksum of the original text used to verify the version.
- New textures are written to a few old texture paths the game no longer reads, registered in `dm/data/casc_overlay/borrowed_paths.tsv`.
- Some feature switches only take effect with a different overlay: the script produces one overlay for each combination of these switches under `Gen/romfs_overlay_variants/`, and at launch the app picks the one matching the switches the player has turned on.
- `Gen/romfs_overlay_astc*` is additionally produced only when `DM_ASTC_PACK` (the ASTC supplement pack directory) is set at build time, for models that do not support BC textures.
### Models without BC texture support (A16 and earlier chips)
The GPUs of these models do not support the BC compression formats the game's textures use. They need a separate ASTC supplement pack, the matching overlay included when the app is built, and the pack copied onto the phone. The pack is generated on a Mac from your own game files and is not in the repository. The full procedure is in the header of `dm/tools/astc_pack.py`; these are its steps (run from the repository root; `D` is an output directory of your choice):
1. Get the encoder astcenc (ARM's open-source encoder, built from source) and give its path with `--astcenc` or the environment variable `ASTCENC`.
2. Transcode: `python3 dm/tools/astc_pack.py <Update/RomFS directory> D/work`.
3. Write the data archive: `python3 dm/tools/casc_overlay.py pack <Update/RomFS directory> D/pack D/work/repl.tsv 0-8`.
4. Finalize: `python3 dm/tools/astc_pack.py finalize D/pack`. It computes sizes and checksums and creates, under `D/pack`, the folder meant for the phone (containing `manifest.json` and `data/`).
5. Build the app: set `DM_ASTC_PACK` to the absolute path of `D/pack`, then run `cd dm/ios && ./run.sh build` as usual.
6. Copy the whole folder created in step 4 into this app's folder on the phone (with the Files app or Finder, next to the game asset folder).
## Directory layout
| Path | Contents |
|---|---|
| `run.sh` | Build, install to device, launch by mode (see below) |
| `project.yml` | XcodeGen project definition: three targets (the app, the asset download extension, the UI tests) and the signing capabilities |
| `local.env.example` | Sample local configuration |
| `Sources/main.m` | App entry point: modes, logging, locating assets, starting the host, lifecycle |
| `Sources/front_ios.m` | iOS implementation of the host front end: Metal view, touch collection and publication, touch scripts, test switches such as screenshots |
| `Sources/dm_touch_controls.[ch]` | Touch classification state machine (pure C) |
| `Sources/DmTouchOverlay.[hm]` | Self-drawn controls such as the stick and skill buttons |
| `Sources/dm_touch_game_*.c` | Reads the skill bindings from the running game (read-only) |
| `Sources/asset_dl.[hm]`, `cloud_ios.m`, `dm_update.m`, `dm_sharelog.m` | Asset download, iCloud save sync, version notice, sharing the diagnostic log |
| `Sources/TouchArt/` | Art for the self-drawn controls. The repository holds only the stick image and the source manifest of the skill atlas (original paths and checksums); the skill atlas itself is generated from the game files at build time |
| `NativeHUD/` | Bottom bar documentation and the self-drawn close button image |
| `RomfsDownloader/` | Download extension for the Apple-hosted asset pack |
| `TouchSmokeTests/` | XCTest UI tests (real touches, lifecycle) |
| `docs/` | Specification files (JSON) for the touch layout and skill bindings. The generation scripts and unit tests reference them by checksum; do not modify them |
| `tests/` | Unit tests (see below) |
| `tools/` | Build-time generation scripts (`gen_*.py`), smoke test, regression and measurement tools |
| `tools/uireg/` | Scripted regression of the touch UI, see [tools/uireg/usage.md](tools/uireg/usage.md) |
| `Gen/`, `DmIOS.xcodeproj/` | Generated at build time, not kept in the repository |
## Local configuration: local.env
Signing information and device IDs are not kept in the repository; they go in a local configuration file:
```bash
cp local.env.example local.env
```
| Variable | Meaning | When it is needed |
|---|---|---|
| `DM_TEAM_ID` | Developer team ID | Building the app |
| `DM_BUNDLE_ID` | The app's bundle ID, which you choose yourself (reverse-domain style). The app group and iCloud container are derived from it: `group.<bundle ID>`, `iCloud.<bundle ID>` | Building the app, all smoke test and regression scripts |
| `DM_DEVICE` | The real device's devicectl device identifier (the Identifier column of `xcrun devicectl list devices`) | Installing to the device and the real-device scripts |
| `DM_IOS_UDID` | The real device's hardware UDID | The battery check of the real-device smoke test, `tools/lifecycle.sh`, `tools/xtrace.sh` |
| `MINI_SSH` | The ssh target of a second Mac dedicated to running tests | Only used by `dm/tools/l3run.sh` and `dm/tools/mini_sync.sh`; leave it empty if you have no second Mac |
The scripts read the configuration through `tools/local_env.sh`, searching in this order and **reading only the first file that exists, without merging**: the file pointed to by the environment variable `DM_LOCAL_ENV` → `dm/ios/local.env` → `~/.config/dm-ios/local.env`. The last location is convenient for sharing between several worktrees on the same machine; note that once a worktree has a `local.env`, the shared one is not read at all.
## run.sh
```bash
./run.sh build # generate Gen/ and the project, compile, sign; does not touch the device
./run.sh install # install the app from the last build to DM_DEVICE
./run.sh <mode> [limit_seconds=60] # launch on the real device with -mode <mode>, pull back Documents/<mode>.txt and print it
```
Prerequisites: `../../setup.sh` has finished (the rewritten program and the iOS shader libraries are ready), and `DM_TEAM_ID` and `DM_BUNDLE_ID` are filled in in the local configuration.
`build` does the following in order: generate the assets derived from the original from the game files (`tools/gen_assets.py`, skipped if the inputs have not changed) → generate the host's three table files (`dm_vault_tab.h`, `dm_hud_exp.h`, `dm_bright_levels.inc`) → `gen_build.py`, `gen_embed.py` → copy the shader libraries and the various manifests into `Gen/` → generate the overlay → `xcodegen generate` → `xcodebuild` (Release, automatic signing). These steps call `python3` and must be run inside the Python environment created by `setup.sh` (Pillow, numpy and the rest are installed there): run `source ~/dm-work/build/cache/dm/venv/bin/activate` first (if you set `DM_ROOT`, use it in place of `~/dm-work`). The build log is at `$DM_ROOT/run/ios/build.log`, and the app is at `<derived data directory>/Build/Products/Release-iphoneos/DmIOS.app`.
`install` and launching by mode first take the device lock (`tools/devlock.sh`, lock directory `$DM_ROOT/run/ios/device.lock`), which guarantees that only one script is operating the phone at any moment.
Commonly used environment variables:
| Variable | Purpose | Default |
|---|---|---|
| `DM_OUT` | Directory of the rewrite output | The output of `../tools/product.sh path touch` |
| `DM_IOS_DD` | Xcode derived data directory | `$DM_ROOT/run/ios/dd` |
| `DM_ROMFS_SRC` | Original RomFS (`Update/RomFS`) | `$DM_ROOT/data/switch/3.3.94012/Update/RomFS` |
| `DM_GEN_ONLY=1` | Only generate `Gen/` and the project, do not compile | Unset |
| `DM_ASTC_PACK` | ASTC supplement pack directory; the matching overlay is produced only when it is set | Unset |
The test save inside the app is also brought in at `build` time: if `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/` exists, it is copied into the app. When launched with the environment variable `DM_SAVE_FRESH=warlock`, that run uses a fresh copy of it, placed in `Documents/save.test`, and does not touch the real save in `Documents/save`. `DM_SAVE_FRESH=empty` starts from an empty save; `DM_SAVE_TEST=1` keeps using the `Documents/save.test` left by the previous run.
## Smoke test
A smoke test really launches the app and goes through a short stretch, to confirm that it starts, can enter a game, and has sound. The repository has two sets with the same criteria: one runs the iOS package directly on a Mac, the other runs on a real device.
### Step one: generate the smoke test save
```bash
tools/make_fixture.sh
```
The first stage of the smoke test is "load a save and enter the game", which needs a save. This script launches the iOS package on the Mac from an empty save, uses touch scripts to create two characters one after the other, enters the camp once with each and saves and exits, then collects the result into `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/`. After that, apps built by `run.sh build` include it.
- It only needs to be done once; if the target directory already exists it is not overwritten, so delete that directory first if you want to redo it.
- Along the way it clones your game assets into this app's container on the Mac (an APFS clone, taking no extra space), so the Mac smoke test afterwards can use them directly.
- The save exists only in your workspace and is not kept in the repository.
### Running the iOS package on a Mac
```bash
tools/smoke_mac.sh 1 # the argument is how many times "load a save and enter the game" is repeated
```
An Apple silicon Mac can run an iOS arm64 package as is. What the script does:
1. Build: `run.sh build` only does the generation, then it compiles with "Designed for iPad" as the destination, with the derived data placed in `.iosdd_mac/` at the repository root (if the source was not obtained with git clone, in the directory the script is run from).
2. Wrap: opening the build product directly reports a wrong format, so it has to be wrapped as `.iosdd_mac/DmMacSmoke.app/Wrapper/DmIOS.app`, plus a `WrappedBundle` symlink.
3. Load a save and enter the game N times: each time it launches with `DM_SAVE_FRESH=warlock` and a key script (main menu → character select → enter the game), and through the app's test log port (`DM_LOG_PORT`, read by `tools/logport.py`) waits in turn for the main menu, entering the game, and the loading screen being taken down.
4. One player-path run: without `-mode`, without the watchdog and the save variables, equivalent to the player tapping the icon; after entering the game it opens the pause menu and then sits idle. It requires that, in the log, the audio output is really producing sound, the player state can be read, and there are no lines containing `【红】` (red).
5. One touch player-path run: starting from an empty save, using only the touch script `tools/smoke_touch.txt` to create a character and enter the game; tapping empty ground three times does not move the character, and tapping the waypoint underfoot opens the waypoint panel.
The last line is `SMOKE-MAC OK <passes>/<count> 用时 … 秒` (`用时 … 秒` = took … seconds) or `SMOKE-MAC RED …`. The result directory is `$DM_ROOT/run/ios/smoke_mac/<time>_<pid>/`, and every run also appends one record line to `$DM_ROOT/run/ios/smoke_ledger.tsv`.
Key points:
- The game assets are read from this app's container on the Mac (`Library/Application Support/romfs`). When the container has none, the script clones them from the directory `SMOKE_MAC_ROMFS` points to; this variable must point to the `data` directory of the RomFS, for example `SMOKE_MAC_ROMFS=$DM_ROOT/data/switch/3.3.94012/Update/RomFS/data`. If you have run `make_fixture.sh` first, you can ignore this item.
- A given bundle ID can have only one instance on one Mac. If the script finds an existing instance before starting, it reports red and does not terminate it for you. On the same Mac, the Mac smoke test, the touch-screen cases and the UI regression share one lock, `$DM_ROOT/run/ios/macsmoke.lock`, and queue automatically.
- By default a set of "real-device profile" parameters is applied (screen resolution and left/right safe areas), so that layout and touch-point conversion match the phone; `DM_MAC_DEVICE_PROFILE=0` switches back to running as is in the Mac window.
- While the package is running, the system mounts its `Wrapper` directory. Deleting this directory or replacing it wholesale at that time leaves a stale mount point that cannot be unmounted; that path can no longer be opened from then on, and only a reboot clears it. So do not touch the package while it is running.
Tunables:
| Variable | Purpose |
|---|---|
| `SMOKE_MAC_HOST` | Default `local`, everything is done on this machine. When set to an ssh target (`user@host`), this machine builds and wraps, transfers the package to that Mac to run, and pulls the results back. This is intended for a second Mac dedicated to running tests; without one there is no need to set it |
| `SMOKE_MAC_PKG_ONLY=1` | Only build and wrap, do not run; the last line prints the path of the package |
| `SMOKE_PLAYER=0`, `SMOKE_TOUCH=0` | Skip the player path / the touch player path |
| `SMOKE_KEYS` | Use a different key script. Such a run is marked `反例` (counterexample) in the record, and the last two stages are not run |
| `SMOKE_MAIN_MENU_TIMEOUT`, `SMOKE_GAME_SCREEN_TIMEOUT` | Limit in seconds for waiting for the main menu / waiting for the loading screen to be taken down, default 40 / 30 |
| `SMOKE_UIREG=1` | After the smoke test passes, additionally run one UI regression run in the background, see [tools/uireg/usage.md](tools/uireg/usage.md) |
| `SMOKE_OWNER` | The name shown in the queue and in the record |
What the Mac smoke test can verify: the shell starts, asset location, entering a game, lifecycle, sound output. What it cannot verify: installation and signing, real fingers, the phone's heat and GPU time.
### Real-device smoke test
```bash
# run from the repository root
dm/ios/tools/smoke.sh 3
```
Prerequisites, in addition to those of the Mac smoke test:
- The local configuration has `DM_DEVICE` and `DM_IOS_UDID`, and the phone is connected by cable and has trusted this Mac.
- The command-line tools `timeout` (GNU coreutils) and `iproxy`, `ideviceinfo` (libimobiledevice) are in `PATH`.
- The game assets have already been pushed to the phone (the command in case 1 of "Locating the game assets").
- A smoke test save already exists (`make_fixture.sh`).
The script first reads the phone's battery level (below 30% it refuses to start and leaves a pause marker, and only lets runs through again once charged to 60%), takes the device lock, then builds (derived data in `.iosdd/` at the repository root; if the source was not obtained with git clone, in the directory the script is run from), installs to the device, and launches the given number of times. The log likewise goes through the app's test log port and is read back through `iproxy`'s USB port mapping. The criteria are the same as the first two stages on the Mac (load a save and enter the game N times + one player-path run), and the last line is `SMOKE OK <passes>/<count> 用时 … 秒` (`用时 … 秒` = took … seconds) or `SMOKE RED …`. The result directory is `$DM_ROOT/run/ios/smoke/<time>/`, and the record is written to the same `smoke_ledger.tsv`.
## Touch scripts
The "touch script" used in the smoke tests and the regression is a text file in which every line is "seconds action arguments", executed by the app according to time. Scripted fingers go through the same `touchesBegan / Moved / Ended` path as real fingers, and the classification and publication afterwards are exactly the same.
- Usage: put the script into the app's `Documents` and launch with `DM_TOUCH_SCRIPT=<file name>`. By default timing starts from first entering a game; with `DM_TOUCH_SCRIPT_START=menu` timing starts from when the main menu appears.
- The actions include `down` / `move` / `up` (finger), `tap_ui` (tap by UI widget name), `tap_unit` (tap a certain kind of unit in the world), `walk_to`, `type`, `shot` (screenshot), `note`, `pos`, `await` and others; for the full format see `touch_script_start` in `Sources/front_ios.m`.
- A position can be written as point coordinates or as `@widget name`. With `DM_TOUCH_REF=<width>x<height>`, bare coordinates are converted from that reference screen to the current screen.
To run a single touch script on its own: on a Mac use `tools/touch_e2e_mac.sh <script> <result directory> [seconds]`, on a real device use `tools/touch_e2e.sh` (same arguments).
## Unit tests
```bash
make -C dm/ios/tests test
```
No device is needed, and the app is not launched. Contents:
- The behaviours of the touch classification state machine `dm_touch_controls.c` (`t_touch_controls.c`, `t_skill_aim.c`, `t_joy_travel.c`, `t_portal_sequence.c`).
- Parsing and reading of the skill bindings (`t_native_binding.c`, `t_game_bridge.c`, `t_binding_*.c`, `t_native_hud_*.c`), using the two fixtures in [tests/fixtures/native_binding/](tests/fixtures/native_binding/README.md). The public repository does not ship these two fixtures: without them, the three tests that read them are skipped automatically and the rest run as usual.
- The skill atlas index (`t_native_art.c`, `test_native_art_capture.py`). This item needs the game files on your machine: the skill index `Sources/dm_touch_native_art.c` is not kept in the repository, and when it is missing it is generated on the spot from `DM_ROMFS_SRC` (default `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`).
- A few Python scripts that check the wiring of the touch path in `front_ios.m` and the format of the diagnostic log.
Under `tools/` there are also self-tests that come with a few of the scripts: `devlock_test.sh`, `devlock_max_test.sh`, `devlock_locale_test.sh` (device lock), `devbattery_test.sh` (battery check).
## Other scripts in tools/
| Script | Purpose |
|---|---|
| `gen_assets.py` and the `gen_*.py` and `native_art/generate.py` it calls | Generate the assets derived from the original from the game files, described in [../README.md](../README.md) |
| `check_hud_gen.sh` | Checks that generated files have not been committed to the repository; when the game files are present on your machine, actually generates the bottom bar once |
| `devlock.sh`, `devbattery.sh`, `local_env.sh`, `logport.py` | Common parts referenced by other scripts: device lock, battery check, local configuration, log port |
| `touch_e2e.sh`, `touch_e2e_mac.sh` | Run one touch script and collect the log and screenshots |
| `charsel_retap.sh` | Touch regression of the character select page (iOS package on a Mac) |
| `lifecycle.sh` | One round of lifecycle testing on a real device: go to the background and come back to the foreground |
| `screen_check.py`, `fullscreen_check.py` | Check orientation, black borders and stretching from whole-window screenshots |
| `bootprof.sh`, `heat_ab.sh`, `gpu_read.sh`, `xtrace.sh` | Real-device measurements: startup timeline, heat comparison, GPU time, Instruments command-line recording |
| `asset_manifest.py` | Generates the manifest for the direct asset download path |
+283
View File
@@ -0,0 +1,283 @@
# dm/ios — iOS 外壳
English: [README.md](README.md)
D2R Mobile 的 iOS App:把宿主(`dm/host`)、图形层(`dm/gfx`)和改写后的游戏程序装进一个 App,负责启动、找游戏资源、把触摸变成游戏能懂的输入,并在原版界面上摆出触摸控件。
先读这几份,本文不重复它们:
- 需要什么、怎么从零构建:[../../README.zh-CN.md](../../README.zh-CN.md)、[../../setup.sh](../../setup.sh)
- 依赖与版本:[../../docs/DEPENDENCIES.zh-CN.md](../../docs/DEPENDENCIES.zh-CN.md)
- 游戏文件怎么准备、放哪:[../../docs/GAME_FILES.zh-CN.md](../../docs/GAME_FILES.zh-CN.md)
- 改写器、宿主、图形层,以及「从你的游戏文件生成资源」:[../README.zh-CN.md](../README.zh-CN.md)
文中 `$DM_ROOT` 指工作区根目录(缺省 `~/dm-work`)。命令里的相对路径以 `dm/ios` 为准,除非另有说明。
## 怎么工作
### 构建时把什么装进 App
iOS 不允许普通 App 执行运行时才写进内存的代码,所以游戏程序不能像在 Mac 宿主上那样启动时再装载,而是在构建时就编进 App 的可执行文件:
- `tools/gen_embed.py` 把改写后的模块映像(`main`、`sdk`)生成一份内嵌汇编 `Gen/embed.S`,按原来的相对布局放进可执行文件的段里。宿主的装载器在 iOS 上只取这些段的地址并核对布局,不拷贝代码、不改页权限。
- `tools/gen_build.py` 从 `dm/host/Makefile` 实际展开的编译命令里取宿主的源文件、头文件路径和框架,生成 `Gen/dm.xcconfig` 与 `Gen/src/`。宿主的 `main.c` 以 `-Dmain=dm_main` 编入,由 App 在自己的线程上调用。
- 着色器库(`setup.sh` 翻译好的 iOS 版)、着色器映射表、装载用的重定位表与门表、覆盖层 RomFS(见下)作为资源随 App 走。
工程文件不进仓库:`project.yml` 是 XcodeGen(由一份 YAML 生成 Xcode 工程的工具)的输入,`run.sh build` 每次重新生成 `DmIOS.xcodeproj` 和 `Gen/`。
### 启动
入口在 `Sources/main.m`。App 用启动参数 `-mode <名>` 选要跑的内容,缺省是 `boot`(起游戏)。`boot` 模式的顺序:
1. 把进程的文件描述符软上限提到 4096(游戏进局后同时打开的文件数接近 iOS 的缺省上限)。
2. 开日志:`Documents/boot.txt`,逐行落盘;上一轮的日志改名成 `Documents/boot.previous.txt`。宿主写到标准错误的内容也进这个文件。
3. 查显卡是否支持 BC 压缩贴图。不支持的机型需要配套的 ASTC 补充包(`dm/tools/astc_pack.py` 的产物),找不到就弹框说明,不起游戏。补充包怎么做、怎么放进手机,见下文「不支持 BC 贴图的机型」。
4. 找游戏资源(下一节)。找到就准备环境:`boot_prepare` 设好 `DM_ROMFS`(资源根)、`DM_ROMFS_OVERLAY`(覆盖层)、`DM_SAVE`(存档目录 `Documents/save`)、`DM_TEMP`、`DM_MSL_DIR`(着色器库)等宿主要读的环境变量,把工作目录切到 `Documents`,并调 `dm_host_preload_start` 让宿主在后台线程先开始装载,与 UIKit 的启动并行。
5. 场景建好后,根视图换成 `front_ios_view` 返回的 Metal 视图(`Sources/front_ios.m`,宿主前端接口 `dm/host/front.h` 的 iOS 实现)。
6. `boot_thread` 在一条 64 MB 栈的线程上先做 iCloud 存档同步(`Sources/cloud_ios.m`),再调 `dm_main` 进入宿主,从此游戏开始运行。
切后台、回前台、场景断开等生命周期事件由 `main.m` 的 `SceneDelegate` 转给 `front_ios.m`;App 终止时调 `dm_host_shutdown` 让宿主有序收尾。
其余模式是诊断用的:`anon`、`mapjit`、`file` 三个探针分别试「匿名页写入后执行」「MAP_JIT 映射」「沙箱内文件映射成可执行」,用来确认上面那条限制;`tsd` 探针试线程局部存储的固定槽位;`msl` 逐个加载 App 内的着色器库;`blank` 只跑一个空白 Metal 清屏页(发热对照);`thermal` 读一次系统温控档位就退出。
### 找游戏资源
`main.m` 的 `romfs_locate` 按下面的顺序找,先到先得;每一处都用 `dm_romfs_validate`(`dm/host/romfs_validate.c`)核对 18 个档案文件齐全、字节数对得上:
1. App 容器的 `Library/Application Support/romfs`。开发时用这一处,从 Mac 推进去:
```bash
xcrun devicectl device copy to --device <设备标识> \
--domain-type appDataContainer --domain-identifier <包名> \
--source $DM_ROOT/data/switch/3.3.94012/Update/RomFS \
--destination 'Library/Application Support/romfs'
```
2. App 的 `Documents`(在「文件」App 里可见)里直接放着档案文件的文件夹。文件夹叫什么都行,外面多套几层也认(4 层以内);不完整时把缺的文件列在屏上。
3. 苹果托管资源包(Background Assets,随 App 安装下载的大文件包),包名 `romfs`。`RomfsDownloader/` 是它要求的下载扩展。
4. 都没有:不起宿主,显示资源界面(`main.m` 的 `AssetVC`),给出进度或原因,资源到位后点重试就地进游戏。
资源只核那 18 个档案文件:配置文件用 App 里覆盖层自带的那份,密钥与档案清单游戏不读,都不用拷。
`Sources/asset_dl.m` 实现了从一个 HTTP 地址直接下载资源的通路(清单由 `tools/asset_manifest.py` 生成)。仓库里的 `asset_pointers.txt` 没有登记任何地址,构建时也不传 `DM_ASSET_BASE` 的话,这条通路不会生效。
### 把触摸变成输入
游戏的 Switch 版只认手柄和触摸屏两种输入,外壳把手指动作翻译成这两样,再加上直接对游戏界面的点击。
- **收集**:`front_ios.m` 的 `DmMetalView` 统一接收全部 `UITouch`。
- **判定**:`Sources/dm_touch_controls.c` 是一份不依赖 UIKit 的纯 C 状态机(`dm_tc_*`):哪根手指属于摇杆、技能钮、腰带格还是界面,点按 / 双击 / 长按 / 拖放各算什么,输出当前该按下的手柄键和左右摇杆的值。它可以脱离设备做单元测试(见「单测」)。
- **发布**:每次状态变化,`DmMetalView` 的 `pushFrom:phase:` 把结果一起交给宿主:`dm_touch_set`(原始触点,供游戏读触摸屏)、`dm_cursor_set_screen`(界面光标位置)、`dm_input_set`(手柄键与摇杆)。宿主在游戏读手柄时把它们落地(`dm/host/hle_hid.c`、`dm/host/dm_cursor.c`)。
按游戏当前所处的界面分三种情况,由游戏自己发出的界面消息驱动切换(`dm_tc_navigation`),不靠猜:
| 情况 | 外壳怎么处理触摸 |
|---|---|
| 前端页面(主菜单、选角、建角) | 不显示摇杆和技能钮;触点经 `dm_ui_touch` 变成对游戏界面的鼠标点击 |
| 局内、没开面板 | 左侧摇杆、右侧技能钮、底栏按钮各自变成手柄键与摇杆;点在世界里(怪、物品名、NPC、箱子)经 `dm_ui_world_tap` 交给宿主解析目标,点空地不发任何输入 |
| 局内、开着面板或对话 | 手指直接点界面:物品格上单击看说明、双击使用、长按、拖放;页签、按钮、面板外点按关面板。命中的是什么由宿主按游戏自己的面板树回答,前端据此决定发鼠标点击还是手柄键 |
### 触摸控件与原版界面的关系
原则是尽量用游戏自己的界面部件,外壳只补游戏没有的那一层:
- **底栏**的血球、蓝球、腰带、回城、功能入口是游戏原版的 HUD 部件,只通过覆盖层里的布局文件改了位置与缩放;经验条和格子上的数字由外壳画。详见 [NativeHUD/README.zh-CN.md](NativeHUD/README.zh-CN.md)。
- **摇杆与技能钮**由 `Sources/DmTouchOverlay.m` 用 UIKit 画在游戏画面上面。这一层只画不收触点。技能钮上的图标取自游戏的技能图集,当前绑的是哪个技能由 `Sources/dm_touch_game_bridge.c` 从运行中的游戏只读地取出来。
- **面板**全部是游戏原版的面板。覆盖层把原版布局里的手柄键位提示挪出屏幕、给面板加上关闭按钮、把提示文字里的手柄说法换成触摸说法(`tools/touch_layout.py`、`tools/touch_strings.py`)。
### 覆盖层 RomFS
覆盖层是 App 自带的一小份 RomFS:宿主读游戏文件时先查它,查不到再读完整的游戏资源(`DM_ROMFS_OVERLAY`,`dm/host/hle_fs.c`、`dm/host/hle_tact.c`)。这样改界面布局和贴图不用动玩家的游戏文件。
`run.sh build` 调 `tools/gen_romfs_overlay.py <原版 RomFS> Gen/romfs_overlay` 生成它:读你的游戏文件里的原版布局与字符串,套上仓库里的改动,写成一份新的 `.build.config` 加一个新数据档。
- 仓库里只存「改了什么」,不存原版内容:布局用结构补丁(`tools/layout_patch.py`),字符串表按键名替换并用原文的校验值核对版本。
- 新贴图写在几个游戏不再读取的旧贴图路径上,登记在 `dm/data/casc_overlay/borrowed_paths.tsv`。
- 有些功能开关要换一份覆盖层才生效:脚本会把这些开关的各种组合各出一份到 `Gen/romfs_overlay_variants/`,App 启动时按玩家已打开的开关挑对应的那份。
- 构建时设了 `DM_ASTC_PACK`(ASTC 补充包目录)才会另出 `Gen/romfs_overlay_astc*`,给不支持 BC 贴图的机型用。
### 不支持 BC 贴图的机型(A16 及更早的芯片)
这些机型的显卡不支持游戏贴图用的 BC 压缩格式,要另做一份 ASTC 补充包,出包时带上配套的覆盖层,再把补充包放进手机。补充包用你自己的游戏文件在 Mac 上生成,仓库里不带。完整流程写在 `dm/tools/astc_pack.py` 的文件头,下面是它的步骤(在仓库根目录执行,`D` 是你选的输出目录):
1. 准备编码器 astcenc(ARM 的开源编码器,从源码编),路径用 `--astcenc` 或环境变量 `ASTCENC` 给。
2. 转码:`python3 dm/tools/astc_pack.py <Update/RomFS 目录> D/work`。
3. 写成数据档:`python3 dm/tools/casc_overlay.py pack <Update/RomFS 目录> D/pack D/work/repl.tsv 0-8`。
4. 收尾:`python3 dm/tools/astc_pack.py finalize D/pack`。它算出大小与校验值,并在 `D/pack` 下生成给手机用的那个文件夹(里面是 `manifest.json` 与 `data/`)。
5. 出包:把 `DM_ASTC_PACK` 设成 `D/pack` 的绝对路径,再照常 `cd dm/ios && ./run.sh build`。
6. 把第 4 步生成的那个文件夹整个拷进手机上这个 App 的文件夹(用「文件」App 或 Finder,和游戏资源文件夹放在一起)。
## 目录结构
| 路径 | 内容 |
|---|---|
| `run.sh` | 构建、装机、按模式启动(见下) |
| `project.yml` | XcodeGen 工程定义:App、资源下载扩展、界面测试三个目标,以及签名能力 |
| `local.env.example` | 本机配置样例 |
| `Sources/main.m` | App 入口:模式、日志、找资源、启动宿主、生命周期 |
| `Sources/front_ios.m` | 宿主前端的 iOS 实现:Metal 视图、触摸收集与发布、触点脚本、截图等测试开关 |
| `Sources/dm_touch_controls.[ch]` | 触摸判定状态机(纯 C) |
| `Sources/DmTouchOverlay.[hm]` | 摇杆、技能钮等自绘控件 |
| `Sources/dm_touch_game_*.c` | 从运行中的游戏读取技能绑定(只读) |
| `Sources/asset_dl.[hm]`、`cloud_ios.m`、`dm_update.m`、`dm_sharelog.m` | 资源下载、iCloud 存档同步、版本提示、分享诊断日志 |
| `Sources/TouchArt/` | 自绘控件的素材。仓库里只有摇杆图和技能图集的来源清单(原版路径与校验值);技能图集本身在构建时从游戏文件生成 |
| `NativeHUD/` | 底栏说明与自己画的关闭按钮图 |
| `RomfsDownloader/` | 苹果托管资源包的下载扩展 |
| `TouchSmokeTests/` | XCTest 界面测试(真实触点、生命周期) |
| `docs/` | 触摸布局与技能绑定的规格文件(JSON)。生成脚本和单测按校验值引用它们,不要改 |
| `tests/` | 单元测试(见下) |
| `tools/` | 构建期生成脚本(`gen_*.py`)、冒烟、回归、测量工具 |
| `tools/uireg/` | 触摸界面脚本化回归,见 [tools/uireg/usage.zh-CN.md](tools/uireg/usage.zh-CN.md) |
| `Gen/`、`DmIOS.xcodeproj/` | 构建时生成,不进仓库 |
## 本机配置:local.env
签名信息和设备号不进仓库,放在本机配置文件里:
```bash
cp local.env.example local.env
```
| 变量 | 含义 | 什么时候要 |
|---|---|---|
| `DM_TEAM_ID` | 开发者团队号 | 出 App |
| `DM_BUNDLE_ID` | App 包名,自己起(反域名写法)。App 组与 iCloud 容器由它派生:`group.<包名>`、`iCloud.<包名>` | 出 App、所有冒烟与回归脚本 |
| `DM_DEVICE` | 真机的 devicectl 设备标识(`xcrun devicectl list devices` 的 Identifier 列) | 装机与真机脚本 |
| `DM_IOS_UDID` | 真机的硬件 UDID | 真机冒烟的电量检查、`tools/lifecycle.sh`、`tools/xtrace.sh` |
| `MINI_SSH` | 第二台 Mac(专门用来跑测试)的 ssh 目标 | 只有 `dm/tools/l3run.sh`、`dm/tools/mini_sync.sh` 用;没有第二台 Mac 就留空 |
脚本通过 `tools/local_env.sh` 读配置,按这个顺序找,**只读第一个存在的文件,不合并**:环境变量 `DM_LOCAL_ENV` 指的文件 → `dm/ios/local.env` → `~/.config/dm-ios/local.env`。后一个位置方便同一台机器上的多个工作树共用;注意工作树里一旦有了 `local.env`,共用的那份就整份不读了。
## run.sh
```bash
./run.sh build # 生成 Gen/ 与工程,编译、签名;不碰设备
./run.sh install # 把上一次 build 的 App 装到 DM_DEVICE
./run.sh <模式> [上限秒=60] # 在真机上以 -mode <模式> 启动,拉回 Documents/<模式>.txt 并打印
```
前提:`../../setup.sh` 已跑完(改写后的程序与 iOS 版着色器库就绪),本机配置里填了 `DM_TEAM_ID` 与 `DM_BUNDLE_ID`。
`build` 依次做:从游戏文件生成原版衍生资源(`tools/gen_assets.py`,输入没变就跳过)→ 生成宿主的三个表文件(`dm_vault_tab.h`、`dm_hud_exp.h`、`dm_bright_levels.inc`) → `gen_build.py`、`gen_embed.py` → 拷着色器库与各张清单进 `Gen/` → 生成覆盖层 → `xcodegen generate` → `xcodebuild`(Release,自动签名)。这些步骤调用 `python3`,要在 `setup.sh` 建的 Python 环境里跑(Pillow、numpy 等装在里面):先执行 `source ~/dm-work/build/cache/dm/venv/bin/activate`(设了 `DM_ROOT` 就把 `~/dm-work` 换成它)。构建日志在 `$DM_ROOT/run/ios/build.log`,App 在 `<派生数据目录>/Build/Products/Release-iphoneos/DmIOS.app`。
`install` 与按模式启动会先取设备锁(`tools/devlock.sh`,锁目录 `$DM_ROOT/run/ios/device.lock`),保证同一时刻只有一个脚本在操作手机。
常用的环境变量:
| 变量 | 作用 | 缺省 |
|---|---|---|
| `DM_OUT` | 改写产物目录 | `../tools/product.sh path touch` 的输出 |
| `DM_IOS_DD` | Xcode 派生数据目录 | `$DM_ROOT/run/ios/dd` |
| `DM_ROMFS_SRC` | 原版 RomFS(`Update/RomFS`) | `$DM_ROOT/data/switch/3.3.94012/Update/RomFS` |
| `DM_GEN_ONLY=1` | 只生成 `Gen/` 与工程,不编译 | 不设 |
| `DM_ASTC_PACK` | ASTC 补充包目录,设了才出配套的覆盖层 | 不设 |
App 里的测试存档也在 `build` 时带上:`$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/` 存在就拷进 App。启动时带环境变量 `DM_SAVE_FRESH=warlock`,这一局就用它的新副本,放在 `Documents/save.test`,不碰 `Documents/save` 里的真实存档。`DM_SAVE_FRESH=empty` 从空存档起;`DM_SAVE_TEST=1` 沿用上一局留下的 `Documents/save.test`。
## 冒烟
冒烟是把 App 真的起起来走一小段,确认它起得来、进得了局、有声音。仓库里有两套,判据相同:一套把 iOS 包直接放在 Mac 上跑,一套在真机上跑。
### 第一步:生成冒烟存档
```bash
tools/make_fixture.sh
```
冒烟的第一段是「读档进局」,要一份存档。这个脚本在 Mac 上把 iOS 包从空存档起一局,用触点脚本先后建两个角色、各进一次营地并保存退出,再把结果收到 `$DM_ROOT/data/switch/save_ref_warlock/0000000000000001/0/`。之后 `run.sh build` 出的 App 就会带上它。
- 只需做一次;目标目录已存在时不覆盖,要重做先删掉那个目录。
- 它顺带把你的游戏资源克隆进 Mac 上这个 App 的容器(APFS 克隆,不另占空间),后面的 Mac 冒烟直接可用。
- 存档只在你的工作区里,不进仓库。
### 在 Mac 上跑 iOS 包
```bash
tools/smoke_mac.sh 1 # 参数是「读档进局」重复的次数
```
Apple 芯片的 Mac 可以原样运行 iOS 的 arm64 包。脚本做的事:
1. 构建:`run.sh build` 只做生成,再以「Designed for iPad」为目标编译,派生数据放在仓库根目录的 `.iosdd_mac/`(源码不是用 git 克隆来的话,是运行脚本时所在的目录)。
2. 包装:直接打开构建产物会报格式不对,要包成 `.iosdd_mac/DmMacSmoke.app/Wrapper/DmIOS.app`,外加一个 `WrappedBundle` 软链。
3. 读档进局 N 次:每次带 `DM_SAVE_FRESH=warlock` 和一段按键脚本(主菜单 → 选角 → 进局)启动,通过 App 的测试日志端口(`DM_LOG_PORT`,由 `tools/logport.py` 读)依次等到主菜单、进局、读取画面撤下。
4. 玩家路径一局:不带 `-mode`、不带看门狗和存档变量,等同于玩家点图标;进局后开暂停菜单再静置。要求日志里音频输出是真出声的、读得到玩家状态、没有带「【红】」的行。
5. 触摸玩家路径一局:从空存档起,只用触点脚本 `tools/smoke_touch.txt` 建角进局,点三下空地人不动,点脚下的小站能开小站面板。
末行是 `SMOKE-MAC OK <成功数>/<次数> 用时 … 秒` 或 `SMOKE-MAC RED …`。结果目录 `$DM_ROOT/run/ios/smoke_mac/<时间>_<进程号>/`,每次运行还往 `$DM_ROOT/run/ios/smoke_ledger.tsv` 追加一行记录。
要点:
- 游戏资源从 Mac 上这个 App 的容器里读(`Library/Application Support/romfs`)。容器里没有时,脚本从 `SMOKE_MAC_ROMFS` 指的目录克隆;这个变量要指到 RomFS 的 `data` 目录,例如 `SMOKE_MAC_ROMFS=$DM_ROOT/data/switch/3.3.94012/Update/RomFS/data`。先跑过 `make_fixture.sh` 就不用管这一条。
- 同一个包名在一台 Mac 上只能有一个实例。脚本开跑前发现已有实例就报红,不替你结束它。同一台 Mac 上的 Mac 冒烟、触屏用例、界面回归共用一把锁 `$DM_ROOT/run/ios/macsmoke.lock`,自动排队。
- 缺省带上一组「真机档位」参数(画面分辨率与左右安全区),让布局和触点换算与手机一致;`DM_MAC_DEVICE_PROFILE=0` 改回按 Mac 窗口原样跑。
- 包在运行时,系统把它的 `Wrapper` 目录挂载出去。这时删掉或整体替换这层目录会留下卸不掉的失效挂载点,那个路径从此打不开,只有重启能清。所以包在跑的时候不要动它。
可调项:
| 变量 | 作用 |
|---|---|
| `SMOKE_MAC_HOST` | 缺省 `local`,全部在本机做。设成 ssh 目标(`用户名@主机`)时,本机构建并包装,把包传到那台 Mac 上跑,结果拉回本机。这是给第二台专门跑测试的 Mac 准备的,没有就不用设 |
| `SMOKE_MAC_PKG_ONLY=1` | 只构建和包装,不跑;末行打印包的路径 |
| `SMOKE_PLAYER=0`、`SMOKE_TOUCH=0` | 跳过玩家路径 / 触摸玩家路径 |
| `SMOKE_KEYS` | 换一段按键脚本。这样的运行在记录里标成「反例」,并且不跑后两段 |
| `SMOKE_MAIN_MENU_TIMEOUT`、`SMOKE_GAME_SCREEN_TIMEOUT` | 等主菜单 / 等读取画面撤下的上限秒,缺省 40 / 30 |
| `SMOKE_UIREG=1` | 冒烟通过后在后台加跑一局界面回归,见 [tools/uireg/usage.zh-CN.md](tools/uireg/usage.zh-CN.md) |
| `SMOKE_OWNER` | 排队和记录里显示的名字 |
Mac 冒烟能验的是:外壳起得来、资源定位、进局、生命周期、出声。验不了的是:安装与签名、真实手指、手机的发热与 GPU 时间。
### 真机冒烟
```bash
# 在仓库根目录执行
dm/ios/tools/smoke.sh 3
```
前提,比 Mac 冒烟多这些:
- 本机配置里有 `DM_DEVICE` 与 `DM_IOS_UDID`,手机用线连着并已信任这台 Mac。
- 命令行工具 `timeout`(GNU coreutils)与 `iproxy`、`ideviceinfo`(libimobiledevice)在 `PATH` 里。
- 游戏资源已经推到手机上(「找游戏资源」第 1 种的那条命令)。
- 已有冒烟存档(`make_fixture.sh`)。
脚本先读手机电量(低于 30% 拒绝开跑,并留下暂停标记,充到 60% 才放行),取设备锁,然后构建(派生数据在仓库根目录的 `.iosdd/`;源码不是用 git 克隆来的话,是运行脚本时所在的目录)、装机、按次数启动。日志同样走 App 的测试日志端口,经 `iproxy` 的 USB 端口映射读回。判据与 Mac 上的前两段相同(读档进局 N 次 + 玩家路径一局),末行 `SMOKE OK <成功数>/<次数> 用时 … 秒` 或 `SMOKE RED …`。结果目录 `$DM_ROOT/run/ios/smoke/<时间>/`,记录写进同一份 `smoke_ledger.tsv`。
## 触点脚本
冒烟和回归里的「触点脚本」是一份文本,每行「秒 动作 参数」,由 App 按时间执行。脚本手指走的是和真手指相同的 `touchesBegan / Moved / Ended` 路径,之后的判定与发布完全一样。
- 用法:把脚本放进 App 的 `Documents`,启动时带 `DM_TOUCH_SCRIPT=<文件名>`。缺省从首次进局起计时,带 `DM_TOUCH_SCRIPT_START=menu` 则从主菜单出现起计时。
- 动作有 `down` / `move` / `up`(手指)、`tap_ui`(按界面控件名点)、`tap_unit`(点世界里的某类单位)、`walk_to`、`type`、`shot`(截图)、`note`、`pos`、`await` 等,完整格式见 `Sources/front_ios.m` 的 `touch_script_start`。
- 位置可以写点数坐标,也可以写 `@控件名`。带 `DM_TOUCH_REF=<宽>x<高>` 时,裸坐标按这块参考画面换算到当前屏幕。
单独跑一份触点脚本:Mac 上用 `tools/touch_e2e_mac.sh <脚本> <结果目录> [秒]`,真机用 `tools/touch_e2e.sh`(同参数)。
## 单测
```bash
make -C dm/ios/tests test
```
不需要设备,也不启动 App。内容:
- 触摸判定状态机 `dm_touch_controls.c` 的各项行为(`t_touch_controls.c`、`t_skill_aim.c`、`t_joy_travel.c`、`t_portal_sequence.c`)。
- 技能绑定的解析与读取(`t_native_binding.c`、`t_game_bridge.c`、`t_binding_*.c`、`t_native_hud_*.c`),用到 [tests/fixtures/native_binding/](tests/fixtures/native_binding/README.zh-CN.md) 里的两份夹具。公开仓库不带这两份夹具:缺了的话,读它们的三个测试自动跳过,其余照常。
- 技能图集索引(`t_native_art.c`、`test_native_art_capture.py`)。这一项需要本机有游戏文件:技能索引 `Sources/dm_touch_native_art.c` 不进仓库,缺了会从 `DM_ROMFS_SRC`(缺省 `$DM_ROOT/data/switch/3.3.94012/Update/RomFS`)现生成。
- 几份 Python 脚本,核对 `front_ios.m` 里触摸通路的接线和诊断日志格式。
`tools/` 下还有几个脚本自带的自测:`devlock_test.sh`、`devlock_max_test.sh`、`devlock_locale_test.sh`(设备锁)、`devbattery_test.sh`(电量检查)。
## tools/ 里的其它脚本
| 脚本 | 用途 |
|---|---|
| `gen_assets.py` 及它调用的 `gen_*.py`、`native_art/generate.py` | 从游戏文件生成原版衍生资源,说明在 [../README.zh-CN.md](../README.zh-CN.md) |
| `check_hud_gen.sh` | 检查生成物没有被提交进仓库;本机有游戏文件时把底栏实际生成一遍 |
| `devlock.sh`、`devbattery.sh`、`local_env.sh`、`logport.py` | 被其它脚本引用的公共部分:设备锁、电量检查、本机配置、日志端口 |
| `touch_e2e.sh`、`touch_e2e_mac.sh` | 跑一份触点脚本并收回日志与截图 |
| `charsel_retap.sh` | 选角页的触点回归(Mac 上的 iOS 包) |
| `lifecycle.sh` | 真机上切后台再回前台的一轮生命周期测试 |
| `screen_check.py`、`fullscreen_check.py` | 按整窗截图核对方向、黑边、拉伸 |
| `bootprof.sh`、`heat_ab.sh`、`gpu_read.sh`、`xtrace.sh` | 真机测量:启动时间线、发热对照、GPU 时间、Instruments 命令行录制 |
| `asset_manifest.py` | 给资源直接下载通路生成清单 |
@@ -0,0 +1,8 @@
// 苹果托管资源包的下载扩展:系统缺省实现即可,资源包 romfs 按 essential 策略在安装时下载完。
// Download extension for Apple-hosted asset packs: the system default implementation is enough, the asset pack romfs is fully downloaded at install time under the essential policy.
import BackgroundAssets
import ExtensionFoundation
import StoreKit
@main
struct RomfsDownloader: StoreDownloaderExtension {}
+16
View File
@@ -0,0 +1,16 @@
#import <UIKit/UIKit.h>
#include "dm_touch_controls.h"
#include "dm_touch_game_state.h"
#include "../../host/dm_hud.h"
// 绘制层不吃触点;真实事件由DmMetalView统一收集并保留dm_touch_set通路。
// The drawing layer does not consume touch points; real events are collected in one place by DmMetalView, keeping the dm_touch_set path.
@interface DmTouchOverlay : UIView
@property(nonatomic, assign) const dm_tc_state *controls;
@property(nonatomic, assign) BOOL navigationMode;
@property(nonatomic, assign) dm_tg_snapshot nativeMapping;
@property(nonatomic, assign) dm_hud_info hud;
@property(nonatomic, assign) BOOL dialogOnly; // 只开着 NPC 对话菜单:底栏照常画 | only the NPC dialog menu is open: the bottom bar is drawn as usual
@property(nonatomic, assign) BOOL hudBlocked; // 面板栈里有非常驻面板:UIKit 底栏让开(front_ios.m hud_stack_message) // 宿主每拍发布的 HUD 数字(底部 UI v4:经验条、角标、难度) | the panel stack has a non-persistent panel: the UIKit bottom bar gets out of the way (front_ios.m hud_stack_message) // HUD numbers published by the host every tick (bottom UI v4: experience bar, badges, difficulty)
- (NSDictionary *)controlMetadata;
@end
+315
View File
@@ -0,0 +1,315 @@
#import "DmTouchOverlay.h"
#include <math.h>
#include <TargetConditionals.h>
#include "dm_touch_native_art.h"
#include "hle.h"
#include "dm_input.h"
#include "../../host/dm_i18n.h"
#define DM_SKILL_IDLE_ALPHA .6 // 五个技能钮、回城钮、技能组切换钮没按着时的不透明度(底圈、圆环、图标同乘;要调浓淡只改这一处) | opacity of the five skill buttons, town portal button and skill set switch button when not held (base circle, ring and icon are all multiplied; this is the one place to tune it)
static UIColor *bronze(CGFloat a) { return [UIColor colorWithRed:.66 green:.53 blue:.32 alpha:a]; }
static void caption(NSString *s, CGRect rect, CGFloat size, CGFloat alpha) {
NSMutableParagraphStyle *p = [NSMutableParagraphStyle new]; p.alignment = NSTextAlignmentCenter;
UIFont *f = [UIFont fontWithName:@"Palatino" size:size];
[s drawInRect:rect withAttributes:@{NSFontAttributeName:f ?: [UIFont systemFontOfSize:size],
NSForegroundColorAttributeName:[UIColor colorWithRed:.85 green:.79 blue:.65 alpha:alpha],NSParagraphStyleAttributeName:p}];
}
// 技能钮上画哪个图标:读数入口与输入层相同(dm_ta_current_set),只多一条「旧了照旧画」。
// 测试注入 DM_TEST_OVERLAY_STALE_MS=<毫秒>:绘制时把「现在」往后拨这么多,等于技能快照已经这么旧(造「游戏停拍」时覆盖层的样子,不影响输入判定)
// Which icon to draw on a skill button: same reading entry as the input layer (dm_ta_current_set), with just one extra rule: "if stale, draw as before".
// Test injection DM_TEST_OVERLAY_STALE_MS=<ms>: when drawing, push "now" forward by this much, as if the skill snapshot were already this old (reproduces how the overlay looks when game ticks stall; does not affect input decisions)
static dm_ta_glyph shown_glyph(const dm_tg_snapshot *n, uint64_t button, uint64_t now, int set) {
static int64_t stale = -1; if (stale < 0) { const char *e = getenv("DM_TEST_OVERLAY_STALE_MS"); stale = e ? atoll(e) * 1000000ll : 0; }
now += (uint64_t)stale;
dm_ta_glyph g = dm_ta_current_set(n, button, now, set);
// 快照只是旧了(超过 250 毫秒没更新:游戏停拍、切后台那一瞬、长卡顿)→ 照它被取到那一刻的内容画,不退回 F 标签 / 十字——
// 绑定没变,只是暂时没人刷新;换场景时桥会把快照清空(dm_touch_game_bridge.c),那时取到时刻为 0,仍画占位。输入层的同一读数(front_ios.m)不走这里,照旧只认新鲜的
// The snapshot is merely stale (not updated for over 250 ms: game ticks stalled, the instant of going to background, a long hitch) → draw the content it had at the moment it was captured, do not fall back to the F label / cross --
// the binding has not changed, nobody is refreshing it for the moment; on scene change the bridge clears the snapshot (dm_touch_game_bridge.c), then the capture time is 0 and the placeholder is still drawn. The same reading in the input layer (front_ios.m) does not go through here and still accepts only fresh ones
if (g.status == DM_TA_UNKNOWN && n && n->captured_ns && now > n->captured_ns && now - n->captured_ns > DM_TG_MAX_AGE_NS) g = dm_ta_current_set(n, button, n->captured_ns, set);
return g;
}
@implementation DmTouchOverlay {
UIImage *_circle, *_joy, *_map, *_menu, *_nativeAtlases[DM_TA_ATLASES], *_silAtlases[DM_TA_ATLASES]; // _sil:同帧位的银色剪影图集(gen_hud_v4.py) | _sil: silver silhouette atlas at the same frame positions (gen_hud_v4.py)
NSMutableDictionary<NSString *,UIImage *> *_glyphFrames;
dm_ta_glyph _nativeVisualGlyphs[5];
}
- (instancetype)initWithFrame:(CGRect)f {
if (!(self = [super initWithFrame:f])) return nil;
self.backgroundColor = UIColor.clearColor; self.opaque = NO; self.userInteractionEnabled = NO;
_circle=[UIImage imageNamed:@"dm_native_circle"]; _joy=[UIImage imageNamed:@"dm_touch_joy"];
_map=[UIImage imageNamed:@"dm_native_map"]; _menu=[UIImage imageNamed:@"dm_native_menu"];
_glyphFrames=[NSMutableDictionary dictionary];
for(int i=0;i<DM_TA_ATLASES;i++) _nativeAtlases[i]=[UIImage imageNamed:[NSString stringWithUTF8String:dm_ta_atlases[i].asset]];
for(int i=0;i<DM_TA_ATLASES;i++) _silAtlases[i]=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:
[@"hud_v4_ui/sil_" stringByAppendingString:[NSString stringWithUTF8String:dm_ta_atlases[i].asset]]]];
return self;
}
- (void)setNativeMapping:(dm_tg_snapshot)n {
_nativeMapping=n;
uint64_t buttons[5]={DM_BTN_A,DM_BTN_B,DM_BTN_X,DM_BTN_Y,DM_BTN_R};
uint64_t hostNow=now_ns(); BOOL dirty=NO;
for(int i=0;i<5;i++) {
dm_ta_glyph next=shown_glyph(&n,buttons[i],hostNow,self.controls?self.controls->skill_set:0),previous=_nativeVisualGlyphs[i];
if(next.status!=previous.status || next.raw_skill_id!=previous.raw_skill_id || next.atlas!=previous.atlas ||
next.normal_frame!=previous.normal_frame || next.slot!=previous.slot || next.effective_slot!=previous.effective_slot)dirty=YES;
_nativeVisualGlyphs[i]=next;
}
// 复用现有front CADisplayLink赋快照:只在图或新鲜性改变时重绘,不另开timer。
// Reuse the existing front CADisplayLink to assign the snapshot: redraw only when the image or freshness changes, no extra timer.
if(dirty)[self setNeedsDisplay];
}
- (UIImage *)frameImage:(UIImage *)atlas key:(NSString *)key rect:(CGRect)rect {
if(!atlas) return nil;
UIImage *image=_glyphFrames[key]; if(image) return image;
CGImageRef crop=CGImageCreateWithImageInRect(atlas.CGImage,rect); if(!crop) return nil;
image=[UIImage imageWithCGImage:crop]; CGImageRelease(crop); _glyphFrames[key]=image; return image;
}
- (UIImage *)skillImage:(dm_ta_glyph)g held:(BOOL)held {
if(g.status!=DM_TA_GLYPH)return nil;
int frame=held?g.pressed_frame:g.normal_frame;dm_ta_frame f;
if(!dm_ta_frame_at(g.atlas,frame,&f))return nil;
UIImage *sil=_silAtlases[g.atlas]; // 优先剪影(技能键是圆形,PC 定稿演示图只放剪影) | Prefer the silhouette (skill buttons are round; the finalized PC demo image uses silhouettes only)
return [self frameImage:sil?sil:_nativeAtlases[g.atlas] key:[NSString stringWithFormat:@"%@:%d:%d",sil?@"sil":@"skill",g.atlas,frame] rect:CGRectMake(f.x,f.y,f.width,f.height)];
}
- (void)setNavigationMode:(BOOL)n { _navigationMode = n; [self setNeedsDisplay]; }
// ---- 底部 UI v4:UIKit 部分(经验条、「Lv · %」、角标、难度数字与 1–8 选择条),素材与几何由 tools/gen_hud_v4.py 生成(App 内 hud_v4_ui/)----
// 几何单位 = 2868×1320 效果图像素:点 = (像素 − 1434) × 屏高/1320 + 屏宽/2(x),像素 × 屏高/1320(y)——与原生 HUD 同样按屏高缩放、以屏幕中线居中
// ---- Bottom UI v4: UIKit part (experience bar, "Lv · %", badges, difficulty number and the 1–8 selector strip); assets and geometry are generated by tools/gen_hud_v4.py (hud_v4_ui/ inside the App) ----
// Geometry unit = pixels of the 2868×1320 mockup: point = (pixel − 1434) × screen height/1320 + screen width/2 (x), pixel × screen height/1320 (y) -- scaled by screen height and centered on the screen's center line, same as the native HUD
static NSDictionary *v4ui(void) {
static NSDictionary *ui; static dispatch_once_t once;
dispatch_once(&once, ^{ NSString *p=[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"hud_v4_ui/ui.json"];
NSData *d=[NSData dataWithContentsOfFile:p]; ui=d?[NSJSONSerialization JSONObjectWithData:d options:0 error:nil]:nil;
if(!ui) NSLog(@"【红】底部 UI v4:App 内缺 hud_v4_ui/ui.json"); });
return ui;
}
static UIImage *v4img(NSString *name) {
static NSMutableDictionary *cache; if(!cache) cache=[NSMutableDictionary dictionary];
UIImage *im=cache[name]; if(im) return im;
im=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:[@"hud_v4_ui" stringByAppendingPathComponent:name]]];
if(im) cache[name]=im; return im;
}
// 逐字贴预渲染字形(字效与效果图同源);align:0 居中、1 右对齐;(x, baseline) 为效果图像素
// Blit pre-rendered glyphs character by character (text effect from the same source as the mockup); align: 0 centered, 1 right-aligned; (x, baseline) are in mockup pixels
static void v4text(NSString *str, NSDictionary *glyphs, CGFloat x, CGFloat baseline, int align, CGFloat W, CGFloat u) {
CGFloat adv=0; for(NSUInteger i=0;i<str.length;i++) adv+=[glyphs[[str substringWithRange:NSMakeRange(i,1)]][@"adv"] doubleValue];
CGFloat pen=align==1?x-adv:x-adv/2;
for(NSUInteger i=0;i<str.length;i++) {
NSDictionary *gm=glyphs[[str substringWithRange:NSMakeRange(i,1)]]; if(!gm) continue;
UIImage *im=[gm[@"file"] isKindOfClass:NSString.class]?v4img(gm[@"file"]):nil;
if(im) [im drawInRect:CGRectMake((pen+[gm[@"dx"] doubleValue]-1434)*u+W/2,(baseline+[gm[@"dy"] doubleValue])*u,im.size.width*u,im.size.height*u)];
pen+=[gm[@"adv"] doubleValue];
}
}
- (void)drawV4:(CGContextRef)c {
NSDictionary *ui=v4ui(); const dm_hud_info h=self.hud; const dm_tc_state *s=self.controls;
if(!ui || !dm_hud_bar_visible(&h,self.navigationMode && !self.dialogOnly,self.hudBlocked)) return; // 只在局内常态显示:面板 / 读取画面 / 过场(导航态)与死亡时让开,不挡游戏自己的画面(dm_hud.h) | Shown only in the normal in-run state: yields during panels / loading screen / cutscenes (navigation mode) and on death, so it does not cover the game's own picture (dm_hud.h)
CGFloat W=self.bounds.size.width, u=self.bounds.size.height/1320.0;
CGFloat (^X)(CGFloat)=^(CGFloat px){ return (px-1434)*u+W/2; };
// 底栏静态美术:效果图原生分辨率直接贴(不经游戏 1568×720 渲染再放大);腰带格内挖空透出游戏画的药水、球心挖空透出球液
// Bottom bar static art: blit the mockup directly at native resolution (not rendered by the game at 1568×720 and then upscaled); the belt cells are cut out to show the potions drawn by the game, and the orb centers are cut out to show the orb liquid
UIImage *full=v4img(@"base_full.png"); NSDictionary *bo=ui[@"base"];
if(full) [full drawInRect:CGRectMake(X([bo[@"x"] doubleValue]),[bo[@"y"] doubleValue]*u,full.size.width*u,full.size.height*u)];
// 第 5 格(现为六格布局;原第 6 格)= 原版十字按钮整格替换(含边框);按住第 1 帧。两态:有未分配点数时红色 + 外圈金光(原版「有点可加」提示),否则默认色(暗底金十字)
// Cell 5 (now a six-cell layout; formerly cell 6) = the original game's cross button replacing the whole cell (border included); frame 1 while held. Two states: with unspent points it is red + an outer gold glow (the original game's "points available" hint), otherwise the default color (gold cross on dark base)
{ NSArray *s6=ui[@"slots"][5]; BOOL held=s && (s->buttons & DM_BTN_PLUS), alert=h.points>0 || h.quest_unread;
UIImage *btn=v4img(alert?(held?@"lvl_1.png":@"lvl_0.png"):(held?@"lvl_d1.png":@"lvl_d0.png")); CGRect r=CGRectMake(X([s6[0] doubleValue]),[s6[1] doubleValue]*u,([s6[2] doubleValue]-[s6[0] doubleValue])*u,([s6[3] doubleValue]-[s6[1] doubleValue])*u);
if(h.points>0) { CGContextSaveGState(c); CGContextSetShadowWithColor(c,CGSizeZero,10*u,[UIColor colorWithRed:1 green:.82 blue:.35 alpha:.95].CGColor); [btn drawInRect:r]; CGContextRestoreGState(c); }
if(btn) [btn drawInRect:r]; }
// 经验条:底槽 + 描边 + 填充(本级‰)+ 20 等分刻度,同效果图
// Experience bar: base groove + outline + fill (‰ of the current level) + 20 equal tick marks, same as the mockup
NSDictionary *e=ui[@"exp"]; CGFloat x0=[e[@"x0"] doubleValue], x1=[e[@"x1"] doubleValue], y=[e[@"y"] doubleValue], eh=[e[@"h"] doubleValue];
UIColor *(^rgb)(NSArray *)=^(NSArray *a){ return [UIColor colorWithRed:[a[0] doubleValue]/255 green:[a[1] doubleValue]/255 blue:[a[2] doubleValue]/255 alpha:1]; };
CGContextSetFillColorWithColor(c,rgb(e[@"track"]).CGColor); CGContextFillRect(c,CGRectMake(X(x0),y*u,(x1-x0)*u,eh*u));
CGContextSetStrokeColorWithColor(c,rgb(e[@"edge"]).CGColor); CGContextSetLineWidth(c,u); CGContextStrokeRect(c,CGRectMake(X(x0)+u/2,y*u+u/2,(x1-x0-1)*u,(eh-1)*u));
CGContextSetFillColorWithColor(c,rgb(e[@"fill"]).CGColor); CGContextFillRect(c,CGRectMake(X(x0+1),(y+1)*u,(x1-x0-2)*u*h.exp_permille/1000.0,(eh-2)*u));
int ticks=[e[@"ticks"] intValue]; CGContextSetFillColorWithColor(c,rgb(e[@"track"]).CGColor);
for(int t=1;t<ticks;t++) CGContextFillRect(c,CGRectMake(X(x0+round((x1-x0)*t/(double)ticks)),(y+1)*u,u,(eh-2)*u));
NSDictionary *vt=ui[@"vital"]; // 生命 / 法力:球顶上方居中,效果图字形原生分辨率(原生数值文字已挪出屏幕) | Life / mana: centered above the top of the orb, mockup glyphs at native resolution (the native numeric text has been moved off screen)
v4text([NSString stringWithFormat:@(dm_ui("dmHudLife")),h.hp,h.hp_max],vt[@"glyphs"],[vt[@"left_x"] doubleValue],[vt[@"baseline"] doubleValue],0,W,u);
v4text([NSString stringWithFormat:@(dm_ui("dmHudMana")),h.mp,h.mp_max],vt[@"glyphs"],[vt[@"right_x"] doubleValue],[vt[@"baseline"] doubleValue],0,W,u);
NSDictionary *lv=ui[@"lv"];
v4text([NSString stringWithFormat:@"Lv %d · %d%%",h.level,h.exp_permille/10],lv[@"glyphs"],[lv[@"x"] doubleValue],[lv[@"baseline"] doubleValue],0,W,u);
// 角标:腰带四列件数(第 1–4 格),右下内角右对齐(回城不要书 / 卷轴、不显示次数,第 5 格是十字)
// Badges: item counts of the four belt columns (cells 1–4), right-aligned at the inner bottom-right corner (town portal needs no tome / scroll and shows no count; cell 5 is the cross)
NSArray *slots=ui[@"slots"], *in=ui[@"inner"]; NSDictionary *bd=ui[@"badge"];
int counts[5]={0,h.belt[0],h.belt[1],h.belt[2],h.belt[3]};
for(int i=1;i<=4;i++) { if(!counts[i]) continue;
v4text([NSString stringWithFormat:@"%d",counts[i]],bd[@"glyphs"],[slots[i][0] doubleValue]+[in[2] doubleValue]+[bd[@"dx"] doubleValue],[slots[i][1] doubleValue]+[in[3] doubleValue]+[bd[@"dy"] doubleValue],1,W,u); }
// 难度:第 0 格当前档数字;选择条展开时画 8 格(当前档不透明、其余略淡)
// Difficulty: cell 0 shows the current level number; when the selector strip is expanded, draw 8 cells (current level opaque, the rest slightly faded)
void (^digit)(int,CGFloat,CGFloat,CGFloat)=^(int n,CGFloat cx,CGFloat cy,CGFloat alpha){ UIImage *d=v4img([NSString stringWithFormat:@"diff_%d.png",n]);
if(d) [d drawInRect:CGRectMake(X(cx)-d.size.width*u/2,cy*u-d.size.height*u/2,d.size.width*u,d.size.height*u) blendMode:kCGBlendModeNormal alpha:alpha]; };
CGFloat icx=([in[0] doubleValue]+[in[2] doubleValue]+1)/2, icy=([in[1] doubleValue]+[in[3] doubleValue]+1)/2;
if(h.players>=1 && h.players<=8) digit(h.players,[slots[0][0] doubleValue]+icx,[slots[0][1] doubleValue]+icy,1);
if(s && s->diff_open) {
NSDictionary *pk=ui[@"pick"]; UIImage *tile=v4img(@"slot.png");
for(int i=0;i<8;i++) {
CGFloat cx=[pk[@"center_x"] doubleValue]+(i-3.5)*[pk[@"pitch"] doubleValue], cy=[pk[@"y"] doubleValue];
CGFloat tw=tile.size.width, th=tile.size.height, a=(i+1==h.players)?1:.82;
if(tile) [tile drawInRect:CGRectMake(X(cx-tw/2),(cy-th/2)*u,tw*u,th*u) blendMode:kCGBlendModeNormal alpha:a];
digit(i+1,cx,cy,a);
}
}
}
- (void)drawRect:(CGRect)rect {
(void)rect;
const dm_tc_state *s = self.controls; if (!s) return;
const dm_tc_layout *l = &s->layout;
CGFloat k = l->joy_radius / 60;
if (k <= 0) return;
CGContextRef c = UIGraphicsGetCurrentContext();
uint64_t hostNow=now_ns(); dm_tg_snapshot native=self.nativeMapping;
NSString *labels[DM_TC_COUNT] = {@"主技能",@"技能一",@"技能二",@"技能三",@"技能四",@"回城",@"药剂",@"药剂",@"药剂",@"药剂",@"功能",@"地图"};
if (self.navigationMode) { labels[0]=@"确认/交换"; labels[1]=@"返回"; labels[2]=@"操作"; labels[3]=@"绑定"; labels[4]=@"下一页"; } // 底栏十字位置的「关闭」已去:关闭入口只留外框右上角那一个(dm_tc_nav_mask) | The 「关闭」(Close) at the bottom bar cross position has been removed: the only close entry left is the one at the top-right corner of the outer frame (dm_tc_nav_mask)
for (int i=0;i<DM_TC_COUNT;i++) {
if (!(s->enabled_targets & (1u<<i))) continue;
if(!self.navigationMode && i>DM_TC_PORTAL && i<=DM_TC_MENU) continue; // 底部 UI v4:腰带 / 功能入口(LevelUpButton)由原生 HUD 画;宿主只保 hit-test。回城(技能弧上方圆钮)照技能钮画 | Bottom UI v4: belt / function entry (LevelUpButton) are drawn by the native HUD; the host only keeps hit-test. Town portal (round button above the skill arc) is drawn like a skill button
const dm_tc_target *t = &l->target[i]; CGRect b = CGRectMake(t->x-t->r,t->y-t->r,t->r*2,t->r*2);
BOOL 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; // 回城钮不出按键(宿主施放回城技能),按住态看手指 | The town portal button emits no key (the host casts the town portal skill); the held state is read from the fingers
CGFloat opacity = held ? .6 : .28;
if(!self.navigationMode && i==DM_TC_MAP && s->map_cancel_active) {
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.55 green:.05 blue:.04 alpha:.36].CGColor); CGContextFillRect(c,b); labels[i]=@"取消";
}
BOOL skillKey=!self.navigationMode && (i<=DM_TC_SKILL4 || i==DM_TC_PORTAL); // 回城钮(圆形、和技能图标一样) | Town portal button (round, same as the skill icons)
if (skillKey) { // PC 定稿演示图同款:深色圆底 + 古铜圆环(外亮内暗两道) | Same as the finalized PC demo image: dark round base + bronze ring (two strokes, bright outside and dark inside)
CGFloat lw=MAX(1.5,t->r*0.075);
// 五个技能钮与回城钮平时淡一些(DM_SKILL_IDLE_ALPHA,少挡画面),按住时恢复原样给手感;角标、标签、充能用完的灰态不跟着变
// The five skill buttons and the town portal button are faded when idle (DM_SKILL_IDLE_ALPHA, to block less of the view) and return to normal while held for feedback; badges, labels and the grey out-of-charges state do not change
CGFloat fr=held?1:DM_SKILL_IDLE_ALPHA;
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.086 green:.067 blue:.047 alpha:held?.92:.80*fr].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetLineWidth(c,lw); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:held?1:.9*fr].CGColor);
CGContextStrokeEllipseInRect(c,CGRectInset(b,lw/2,lw/2));
CGContextSetLineWidth(c,lw*.5); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.12 green:.09 blue:.05 alpha:.9*fr].CGColor);
CGContextStrokeEllipseInRect(c,CGRectInset(b,lw*1.3,lw*1.3));
} else if (_circle) [_circle drawInRect:b blendMode:kCGBlendModeNormal alpha:opacity];
else {
CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:.02 alpha:.16].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetStrokeColorWithColor(c,bronze(.28).CGColor); CGContextSetLineWidth(c,k); CGContextStrokeEllipseInRect(c,b);
}
UIImage *icon=nil; BOOL showCaption=YES; int ssKind=0, ssCharges=0;
if(!self.navigationMode && i<=DM_TC_SKILL4) {
dm_ta_glyph g=shown_glyph(&native,t->button,hostNow,s->skill_set);
if(g.status!=DM_TA_EMPTY && g.status!=DM_TA_UNKNOWN) { int dm_swapskill_slot(int,int*); ssKind=dm_swapskill_slot(g.slot,&ssCharges); }
icon=[self skillImage:g held:held];
showCaption=g.status!=DM_TA_EMPTY && !icon;
} else if(!self.navigationMode && i==DM_TC_PORTAL) {
icon=[self skillImage:dm_ta_skill(359) held:held]; // 原版回城技能图(技能描述表 Town Portal:通用技能页第 18 格,219 / 220 / 411 同一张),不显示次数 | the original game's town portal skill image (skill description table Town Portal: cell 18 of the generic skill page, 219 / 220 / 411 share one image), count not shown
} else if(!self.navigationMode && (i==DM_TC_MENU || i==DM_TC_MAP)) {
icon=[self frameImage:i==DM_TC_MAP?_map:_menu key:[NSString stringWithFormat:@"fixed:%d:%d",i,held] rect:CGRectMake(held?36:0,0,36,36)];
}
if(!self.navigationMode && i==DM_TC_MAP && s->map_cancel_active) {icon=nil;showCaption=YES;}
if(skillKey && !icon && (!showCaption || i==DM_TC_MAIN)) { // 主钮取不到图标(如第二套里这一格没绑)也画十字、不写「攻击」:空格按下去不出普通攻击,画攻击图标或写字都会骗人 // 空技能位:圆底圆环里一个单色十字,不写 F 标签;点它进绑定技能(行为由输入层接) | when the main button cannot get an icon (e.g. this cell is not bound in the second set) it also draws the cross and does not say 「攻击」(Attack): pressing an empty cell does not produce a normal attack, so drawing the attack icon or the text would both be misleading // empty skill slot: a single-color cross inside the round base and ring, no F label; tapping it goes to skill binding (the behavior is wired by the input layer)
CGFloat a_=t->r*.30, w_=MAX(1.5,t->r*.085);
CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:held?1:.9].CGColor); CGContextSetLineWidth(c,w_); CGContextSetLineCap(c,kCGLineCapButt);
CGContextMoveToPoint(c,t->x-a_,t->y); CGContextAddLineToPoint(c,t->x+a_,t->y); CGContextMoveToPoint(c,t->x,t->y-a_); CGContextAddLineToPoint(c,t->x,t->y+a_); CGContextStrokePath(c);
continue;
}
if(skillKey) { // 剪影居中略偏上,下方标签:主键「攻击」,其余 F1–F4(第二套 F5–F8);空槽只有圆底、圆环与标签 | silhouette centered and slightly high, label below: main button 「攻击」(Attack), the others F1–F4 (second set F5–F8); an empty slot has only the round base, the ring and the label
BOOL bare=icon!=nil; // 有图标的技能钮不写字(最大的钮是「主技能 / 交互」、可绑任意技能,钮上只画所绑技能的图标,不写「攻击」):图标放大并居中。取不到图标时主钮仍落回「攻击」字样 | skill buttons that have an icon carry no text (the largest button is "main skill / interact" and can be bound to any skill, so the button draws only the bound skill's icon and does not say 「攻击」(Attack)): the icon is enlarged and centered. When no icon can be obtained the main button still falls back to the 「攻击」(Attack) text
BOOL spent=(ssKind&2) && ssCharges<=0; // 充能用完:钮变灰(灰底上按亮度贴图标 = 去色),按下也不换武器(dm_actions.c) | charges used up: the button turns gray (the icon applied by luminance on a gray base = desaturated), and pressing does not swap weapons either (dm_actions.c)
if(icon) { CGFloat size=b.size.width*(bare?.64:.56); CGSize in_=icon.size; CGFloat fit=size/MAX(in_.width,in_.height);
CGRect ir=CGRectMake(t->x-in_.width*fit/2,t->y-(bare?0:t->r*.12)-in_.height*fit/2,in_.width*fit,in_.height*fit);
if(spent) { CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:.30 alpha:1].CGColor); CGContextFillEllipseInRect(c,CGRectInset(b,t->r*.14,t->r*.14));
[icon drawInRect:ir blendMode:kCGBlendModeLuminosity alpha:.55];
CGContextSetFillColorWithColor(c,[UIColor colorWithWhite:0 alpha:.35].CGColor); CGContextFillEllipseInRect(c,b); }
else [icon drawInRect:ir blendMode:kCGBlendModeNormal alpha:held?1:.92*DM_SKILL_IDLE_ALPHA]; }
// 副手组技能角标:右上「Ⅱ」= 技能在另一组武器上,按下先换武器;右下剩余次数 = 充能技能,字用腰带药水件数那套(ui.json badge)
// Secondary weapon set skill badges: top right "Ⅱ" = the skill is on the other weapon set, pressing swaps weapons first; bottom right remaining count = charged skill, the text uses the same style as the belt potion count (ui.json badge)
if(ssKind&1) { CGFloat br=t->r*.30, bx=t->x+t->r*.74, by=t->y-t->r*.74; CGRect bb=CGRectMake(bx-br,by-br,br*2,br*2), lw2=CGRectInset(bb,MAX(1,br*.08),MAX(1,br*.08));
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.11 green:.094 blue:.078 alpha:.95].CGColor); CGContextFillEllipseInRect(c,bb);
CGContextSetLineWidth(c,MAX(1,br*.14)); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.63 green:.50 blue:.27 alpha:1].CGColor); CGContextStrokeEllipseInRect(c,lw2);
CGFloat ts=br*1.15; caption(@"Ⅱ",CGRectMake(bx-br,by-ts*.62,br*2,ts*1.4),ts,1); }
if(ssKind&2) { NSDictionary *ui=v4ui(); CGFloat W=self.bounds.size.width, u=self.bounds.size.height/1320.0; NSDictionary *bd=ui[@"badge"];
if(bd && u>0) v4text([NSString stringWithFormat:@"%d",ssCharges<0?0:ssCharges],bd[@"glyphs"],(t->x+t->r*.66-W/2)/u+1434,(t->y+t->r*.42)/u,1,W,u); }
if(bare) continue;
NSString *ln=i==DM_TC_MAIN?@"lbl_main.png":[NSString stringWithFormat:@"lbl_f%d.png",i-DM_TC_SKILL1+1+(s->skill_set?4:0)];
UIImage *lbl=[UIImage imageWithContentsOfFile:[NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:[@"hud_v4_ui" stringByAppendingPathComponent:ln]]];
if(lbl) { CGFloat lh=t->r*(i==DM_TC_MAIN?.30:.36), lw_=lbl.size.width*lh/lbl.size.height;
[lbl drawInRect:CGRectMake(t->x-lw_/2,t->y+t->r*.50-lh/2,lw_,lh)]; }
continue;
}
if(icon) {
CGFloat size=b.size.width*(i==DM_TC_MAIN?.55:.62);
CGSize intrinsic=icon.size;CGFloat fit=size/MAX(intrinsic.width,intrinsic.height);
CGRect glyph=CGRectMake(t->x-intrinsic.width*fit/2,t->y-intrinsic.height*fit/2,intrinsic.width*fit,intrinsic.height*fit);
[icon drawInRect:glyph blendMode:kCGBlendModeNormal alpha:held?1:.82];showCaption=NO;
}
CGFloat textSize = (i==DM_TC_MAIN ? 13 : 10)*k;
if(showCaption) caption(labels[i],CGRectMake(b.origin.x,t->y-textSize*.6,b.size.width,textSize*1.6),textSize,held ? 1 : .84);
if (i>=DM_TC_BELT1 && i<=DM_TC_BELT4) caption([NSString stringWithFormat:@"%d",i-DM_TC_BELT1+1],CGRectMake(t->x-10*k,t->y+8*k,20*k,12*k),8*k,.65);
}
if (!self.navigationMode && l->swap.r > 0) { // 技能组切换键:显示当前第几套 | skill set switch button: shows which set is current
CGRect b = CGRectMake(l->swap.x-l->swap.r,l->swap.y-l->swap.r,l->swap.r*2,l->swap.r*2);
// 与技能键同一套:深色圆底 + 古铜圆环(外亮内暗两道);上面「Ⅰ / Ⅱ」、下面小字「换组」
// Same scheme as the skill buttons: dark round base + bronze ring (two strokes, bright outside and dark inside); "Ⅰ / Ⅱ" on top, small text 「换组」(switch set) below
CGFloat lw=MAX(1.5,l->swap.r*0.075);
BOOL sheld=NO; for(int f=0;f<DM_TC_MAX_TOUCH;f++) sheld|=s->finger[f].active && hypot(s->finger[f].x-l->swap.x,s->finger[f].y-l->swap.y)<=l->swap.r; // 手指按在这颗上 | a finger is on this button
CGFloat fs=sheld?1:DM_SKILL_IDLE_ALPHA; // 同技能钮:平时淡、按住变实;「Ⅰ / Ⅱ」是状态指示,不淡 | same as skill buttons: faded normally, solid while held; "Ⅰ / Ⅱ" is a state indicator and is not faded
CGContextSetFillColorWithColor(c,[UIColor colorWithRed:.086 green:.067 blue:.047 alpha:sheld?.92:.80*fs].CGColor); CGContextFillEllipseInRect(c,b);
CGContextSetLineWidth(c,lw); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.60 green:.47 blue:.28 alpha:sheld?1:.9*fs].CGColor); CGContextStrokeEllipseInRect(c,CGRectInset(b,lw/2,lw/2));
CGContextSetLineWidth(c,lw*.5); CGContextSetStrokeColorWithColor(c,[UIColor colorWithRed:.12 green:.09 blue:.05 alpha:.9*fs].CGColor); CGContextStrokeEllipseInRect(c,CGRectInset(b,lw*1.3,lw*1.3));
CGFloat ts = 14*k; caption(s->skill_set ? @"Ⅱ" : @"Ⅰ",CGRectMake(b.origin.x,l->swap.y-ts*.8,b.size.width,ts*1.6),ts,1); // 只留 Ⅰ / Ⅱ、居中(「换组」小字去掉) | keep only Ⅰ / Ⅱ, centered (the small 「换组」(switch set) text is removed)
}
if (self.hud.valid && self.hud.dead) return; // 死亡画面:右侧圆钮已由掩码收起,左侧摇杆圈也不画(截图:死后摇杆圈还在) | death screen: the round buttons on the right are already hidden by the mask, and the stick ring on the left is not drawn either (screenshot: the stick ring was still there after death)
if (s->navigation_mode) return; // 面板开着(与起摇杆同一个判定:dm_touch_controls.c 起摇杆的条件带 !navigation_mode):摇杆起不来,静止淡影只会压在面板上(iPad 上双面板占满整宽)——不画 | a panel is open (the same check as starting the stick: the stick-start condition in dm_touch_controls.c includes !navigation_mode): the stick cannot start, and the idle faint shadow would only sit on top of the panel (on iPad the dual panels fill the whole width) - not drawn
BOOL moving = s->joy_slot >= 0;
CGPoint o = moving ? CGPointMake(s->joy_origin_x,s->joy_origin_y) : CGPointMake(l->joy_x,l->joy_y);
CGFloat radius=l->joy_radius;
CGRect base=CGRectMake(o.x-radius,o.y-radius,radius*2,radius*2);
CGContextSetLineWidth(c,k); CGContextSetStrokeColorWithColor(c,bronze(moving ?.32:.12).CGColor); CGContextStrokeEllipseInRect(c,base);
CGFloat dx=s->lx/32767.0*radius,dy=-s->ly/32767.0*radius;
CGRect thumb=CGRectMake(o.x+dx-23*k,o.y+dy-23*k,46*k,46*k);
if (_joy) [_joy drawInRect:thumb blendMode:kCGBlendModeNormal alpha:moving ?.8:.18];
if (moving && (s->lx || s->ly)) {
CGFloat angle=atan2(dy,dx);
CGContextSetStrokeColorWithColor(c,bronze(.7).CGColor); CGContextSetLineWidth(c,2*k);
CGContextAddArc(c,o.x,o.y,radius+3*k,angle-M_PI/6,angle+M_PI/6,0); CGContextStrokePath(c);
}
[self drawV4:c];
}
- (NSDictionary *)controlMetadata {
const dm_tc_state *s=self.controls; if (!s) return @{};
NSMutableArray *a=[NSMutableArray array];
dm_tg_snapshot visualNative=self.nativeMapping; uint64_t hostNow=now_ns();
NSString *names[DM_TC_COUNT]={@"main",@"skill1",@"skill2",@"skill3",@"skill4",@"portal",@"belt1",@"belt2",@"belt3",@"belt4",@"menu",@"map"};
for(int i=0;i<DM_TC_COUNT;i++) {
const dm_tc_target *t=&s->layout.target[i];
NSMutableDictionary *entry=[@{@"id":names[i],@"rect_pt":@[@(t->x-t->r),@(t->y-t->r),@(t->r*2),@(t->r*2)],@"npad_button":@(t->button),@"visible":@((s->enabled_targets&(1u<<i))!=0)} mutableCopy];
if(!self.navigationMode && i>=DM_TC_PORTAL && i<=DM_TC_MENU) {
entry[@"visual_owner"]=i==DM_TC_PORTAL?@"overlay_portal_skill":(i==DM_TC_MENU?@"native_levelup_button":@"native_game_belt"); entry[@"host_drawn"]=@NO;
entry[@"touch_enabled"]=@((s->enabled_targets&(1u<<i))!=0);
}
if(i<=DM_TC_SKILL4) {
dm_ta_glyph g=shown_glyph(&visualNative,t->button,hostNow,s->skill_set);
BOOL held=t->button && (s->buttons&t->button)==t->button;
BOOL drawn=!self.navigationMode && [self skillImage:g held:held]!=nil;
NSString *status=self.navigationMode?@"navigation_label":(g.status==DM_TA_EMPTY?@"empty_slot":(drawn?@"current_skill":@"empty_unknown"));
entry[@"currentSkill"]=@{@"schema":@"dm-current-skill-visual-1",@"status":status,@"reason":[NSString stringWithUTF8String:g.reason],@"raw_skill_id":@(g.raw_skill_id),@"slot":@(g.slot),@"effective_slot":@(g.effective_slot),@"atlas":@(g.atlas),@"normal_frame":@(g.normal_frame),@"pressed_frame":@(g.pressed_frame),@"display_frame":@(held?g.pressed_frame:g.normal_frame),@"glyph_drawn":@(drawn),@"icon_diameter_ratio":@(i==DM_TC_MAIN?.55:.62)};
}
[a addObject:entry];
}
[a addObject:@{@"id":@"swap",@"rect_pt":@[@(s->layout.swap.x-s->layout.swap.r),@(s->layout.swap.y-s->layout.swap.r),@(s->layout.swap.r*2),@(s->layout.swap.r*2)],@"skill_set":@(s->skill_set),@"visible":@(!self.navigationMode)}];
BOOL moving=s->joy_slot>=0; CGFloat k=s->layout.joy_radius/60;
CGFloat jx=moving?s->joy_origin_x:s->layout.joy_x,jy=moving?s->joy_origin_y:s->layout.joy_y,r=s->layout.joy_radius;
CGFloat tx=jx+s->lx/32767.0*r,ty=jy-s->ly/32767.0*r;
NSDictionary *joystick=@{@"id":@"joystick",@"active":@(moving),@"base_rect_pt":@[@(jx-r),@(jy-r),@(2*r),@(2*r)],@"thumb_rect_pt":@[@(tx-23*k),@(ty-23*k),@(46*k),@(46*k)]};
dm_tg_snapshot native=self.nativeMapping;
NSMutableArray *mapping=[NSMutableArray array],*ids=[NSMutableArray array];
for(int i=0;i<DM_TG_FACETS;i++) [mapping addObject:@{@"logical":@(native.mapping[i].logical),@"normal":@(native.mapping[i].normal),@"alt":@(native.mapping[i].alt)}];
for(int i=0;i<DM_TG_SLOTS;i++) [ids addObject:@(native.raw_skill_id[i])];
NSDictionary *nativeInfo=@{@"schema":@"dm-native-binding-4",@"source_id":@(native.source),@"source":native.source==DM_TG_SOURCE_NATIVE_GETTER?@"native_getter":@"none",
@"supported":@(native.supported),@"valid":@(native.valid),@"ready":@(native.ready),@"secondary_group":@(native.secondary_group),@"group_seen":@(native.group_seen),@"group_started_ns":@(native.group_started_ns),@"binding_identity":@(native.binding_identity),@"scene_epoch":@(native.scene_epoch),@"world_epoch":@(native.world_epoch),@"identity_kind":native.identity_scope==DM_TG_IDENTITY_NATIVE?@"fixed_native_hud_updater_cohort":(native.identity_scope==DM_TG_IDENTITY_SYNTHETIC?@"synthetic_stub":@"unconfirmed"),@"caller_identity":@(native.caller_identity),@"hud_identity":@(native.hud_identity),@"identity_scope":@(native.identity_scope),@"captured_ns":@(native.captured_ns),@"selected_bank":@(native.selected_bank),@"getter_input_slot":@(native.getter_input_slot),@"valid_scope":@"table_parse_only",@"observed_index":@(native.observed_index),@"mapping":mapping,@"raw_skill_ids":ids,
@"portal":@{@"valid":@(native.portal.valid),@"slot":@(native.portal.slot),@"raw_skill_id":@(native.portal.raw_skill_id),@"buttons":@(native.portal.buttons)}};
// capture版本与布局版本分开;期望state由测试输入提供,不用visible反推。
// The capture version and the layout version are separate; the expected state is supplied by the test input, not inferred back from visible.
return @{@"capture_schema":@"dm-touch-capture-2",@"profile_id":@"native_art_v1",@"binding_profile_id":@"touch_native_binding_v5",@"input_schema":@"dm-touch-input-5",@"native_mapping":nativeInfo,
@"layout_sha256":[NSString stringWithUTF8String:dm_ta_geometry_sha],@"geometry_sha256":[NSString stringWithUTF8String:dm_ta_geometry_sha],@"binding_protocol_sha256":[NSString stringWithUTF8String:dm_ta_binding_sha],
@"art_provenance":@{@"schema":@"dm-native-art-provenance-1",@"manifest":@"native_art_manifest.json",@"manifest_sha256":[NSString stringWithUTF8String:dm_ta_manifest_sha],@"shell_idle_alpha":@.28,@"shell_held_alpha":@.6,@"fixed_functions":@[@"portal",@"map",@"menu"],@"unsupported_state":@"no ammo/cooldown/mana tint"},
@"source":TARGET_OS_SIMULATOR?@"uikit_simulator_overlay":@"uikit_device_overlay",
@"right_aim":@{@"rx":@(s->rx),@"ry":@(s->ry),@"owner_slot":@(s->aim_slot),@"map_cancel_active":@(s->map_cancel_active),@"navigation_suppressed":@(s->navigation_mode),@"mapping":@"UIKit dx/r, -dy/r; independent clamped SDK axes"},
@"state":self.navigationMode?@"navigation":@"game",@"joystick":joystick,@"coordinate_space":@"UIKit points",@"view_size_pt":@[@(s->layout.width),@(s->layout.height)],@"navigation":@(self.navigationMode),@"controls":a,@"portal_request":@{@"gesture_epoch":@(s->gesture_epoch),@"binding_identity":@(s->portal_binding_identity),@"scene_epoch":@(s->portal_scene_epoch),@"phase":@(s->portal_phase),@"pending":@(s->portal_pending)},@"portal_binding_verified":@NO,@"game_hud_relayout_verified":@NO};
}
@end
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

File diff suppressed because one or more lines are too long
+17
View File
@@ -0,0 +1,17 @@
// 直装包的游戏资源下载(实现与下载站约定见 asset_dl.m)
// Game asset download for the direct-install build (implementation and the download-site conventions: see asset_dl.m)
#import <Foundation/Foundation.h>
@interface DmAssetDL : NSObject
+ (instancetype)shared;
+ (instancetype)astcPack; // 老机型补充包:下到 Documents/Legacy Device Pack/data(地址见 asset_dl.m 文件头) | Legacy Device Pack: downloaded to Documents/Legacy Device Pack/data (address: see the asset_dl.m file header)
// 定下载地址、取清单、盘点本地已有的。回调在主线程:err 非空 = 走不了直接下载(原因);remain / total = 还要下 / 总字节数;cellular = 当前是按流量计费的网络
// Determine the download address, fetch the manifest, take stock of what is already local. Callback on the main thread: err non-nil = direct download not possible (reason); remain / total = bytes still to download / total bytes; cellular = the current network is metered
- (void)prepare:(void (^)(NSString *err, int64_t remain, int64_t total, BOOL cellular))done;
// 上一次 prepare 判出手机空间不够时:还差多少字节(含 200 MB 余量)与手机可用字节;空间够 = 0
// When the last prepare found the phone short of space: how many bytes are still missing (including a 200 MB margin) and the phone's available bytes; enough space = 0
@property (atomic) int64_t shortBytes, freeBytes;
// 开始(或接着)下载。progress(已到手字节数, 总字节数, 附注或 nil) 与 done(失败原因或 nil) 都在主线程
// Start (or resume) downloading. progress(bytes received, total bytes, note or nil) and done(failure reason or nil) are both on the main thread
- (void)run:(void (^)(int64_t done, int64_t total, NSString *note))progress done:(void (^)(NSString *err))done;
@end
void dm_asset_dl_bg_events(NSString *ident, void (^done)(void)); // App 委托的 handleEventsForBackgroundURLSession 转来(按会话标识分给资源 / 补充包) | Forwarded from the App delegate's handleEventsForBackgroundURLSession (dispatched to assets / Legacy Device Pack by session identifier)
+262
View File
@@ -0,0 +1,262 @@
// 直装包的游戏资源下载(直装包没有苹果托管资源包,也用不了开发者账号的 iCloud)。
// 从我们自己的下载站把资源文件逐个拉到 Documents/D2R Mobile Resources/data,全部到齐后由 main.m 的 romfs_locate 照常校验、就地进游戏。
// 下载站目录:<根>/manifest.json({"files":[{"name","size","sha256"}…]},tools/asset_manifest.py 生成)+ <根>/data/<文件名>。
// 根地址怎么定(隧道换域名时不用重出包):环境变量 DM_ASSET_BASE(测试)→ 包内 dm/asset_pointers.txt 里的每个「地址文件」网址
// (取回的正文第一行就是根地址)→ 上次成功用过的根地址 → 包内 dm/asset_base.txt(出包时写进去的缺省根地址)。逐个试,谁的清单取得到用谁。
// 传输:后台会话(URLSession background),一次一个任务,每个任务取一个文件的一段(≤16 MB,Range),取完追加到 <文件名>.part;
// .part 的长度就是这个文件已到手的字节数——杀进程重开 / 断网重连都从这里接着取,不重头。整个文件到齐后核字节数与 SHA-256,
// 对了才改成正式文件名;不对就删掉重下(同一文件最多 3 次)。网络出错自动重试(间隔 2 → 30 秒),不用玩家点。
// 已经在目录里且字节数对的文件不重下(玩家用「文件」拷进来的那些)。
// 老机型补充包(显卡不支持 BC 的机型)走同一套:DmAssetDL.astcPack 下到 Documents/Legacy Device Pack/data,根地址只认
// 环境变量 DM_ASTC_PACK_BASE(测试)→ 上次用过的 → 包内 dm/astc_pack_base.txt(出包时写进去;空 = 没配自动下载,只能玩家用「文件」拷),后台会话标识另起一个。
// Game asset download for the direct-install build (a direct-install build has no Apple-hosted asset packs and cannot use the developer account's iCloud).
// Pull the asset files one by one from our own download site into Documents/D2R Mobile Resources/data; once all have arrived, romfs_locate in main.m verifies them as usual and enters the game in place.
// Download site layout: <root>/manifest.json ({"files":[{"name","size","sha256"}…]}, generated by tools/asset_manifest.py) + <root>/data/<file name>.
// How the root address is determined (no need to rebuild the package when the tunnel changes domain): environment variable DM_ASSET_BASE (test) → each "address file" URL in the bundled dm/asset_pointers.txt
// (the first line of the fetched body is the root address) → the last root address that worked → the bundled dm/asset_base.txt (default root address written at packaging time). Try them one by one; use whichever one's manifest can be fetched.
// Transfer: background session (URLSession background), one task at a time, each task fetches one range of one file (≤16 MB, Range) and appends it to <file name>.part when done;
// the length of .part is the number of bytes of this file already received -- killing and relaunching the process / reconnecting after a network drop both resume from here, not from the start. Once the whole file has arrived, verify the byte count and SHA-256,
// rename to the final file name only if they match; if not, delete and re-download (at most 3 times per file). Network errors retry automatically (interval 2 → 30 s), no player tap needed.
// Files already in the directory with the right byte count are not re-downloaded (those the player copied in with the Files app).
// The Legacy Device Pack (models whose GPU does not support BC) uses the same mechanism: DmAssetDL.astcPack downloads to Documents/Legacy Device Pack/data; the root address only accepts
// environment variable DM_ASTC_PACK_BASE (test) → the last one used → the bundled dm/astc_pack_base.txt (written at packaging time; empty = auto-download not configured, the player can only copy it in with the Files app); it gets a separate background session identifier.
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonDigest.h>
#import <Network/Network.h>
#import "asset_dl.h"
#include "../../host/dm_i18n.h"
void plog(const char *fmt, ...);
#define DL_CHUNK (16ll << 20)
static NSString *dm_dl_sid(NSString *suffix) { return [NSBundle.mainBundle.bundleIdentifier stringByAppendingString:suffix]; } // 后台会话标识 = 包名 + 后缀 | Background session identifier = bundle ID + suffix
@interface DmAssetDL () <NSURLSessionDownloadDelegate>
@property (strong) NSURLSession *session; @property (strong) dispatch_queue_t q;
@property (copy) NSString *base, *dir; @property (strong) NSArray<NSDictionary *> *files;
@property (assign) int64_t total, settled; // 清单总字节数;已落盘的字节数(正式文件 + 各 .part) | Total bytes in the manifest; bytes already on disk (final files + all .part)
@property (assign) int running, retry, cellular; @property (strong) NSMutableDictionary<NSString *, NSNumber *> *redo;
@property (copy) void (^onProgress)(int64_t, int64_t, NSString *); @property (copy) void (^onDone)(NSString *);
@property (copy) NSString *sid, *envBase, *ptrFile, *baseFile, *defKey; // 后台会话标识、测试用环境变量、包内地址文件 / 缺省根地址文件、记住上次根地址的键 | Background session identifier, test environment variable, bundled address file / default root address file, key that remembers the last root address
@property (copy) void (^bgDone)(void); // 系统为后台会话唤醒 App 时给的收尾回调 | Completion callback given by the system when it wakes the App for the background session
// 卡住自救:盯当前这一片的吞吐,明显掉速就取消它、换一个全新的进程内会话(= 全新连接)从 .part 的长度接着取。
// 起因:系统的后台会话会一直复用同一条连接,那条连接塌了(丢包 / 被限速)之后每一片都慢,结束 App 重开也接回同一条。
// Stall self-healing: watch the throughput of the current chunk; on a clear slowdown, cancel it and continue from the length of the .part file on a brand-new in-process session (= a brand-new connection).
// Why: the system background session keeps reusing the same connection; once that connection degrades (packet loss / throttling) every chunk is slow, and quitting and reopening the app re-attaches to the same one.
@property (strong) NSURLSession *fg; // 自救用的进程内会话;每次自救新建一个 | In-process session used for self-healing; a new one is created each time
@property (assign) int useFg, heal, skipWin; // 现在是否走进程内会话;本轮已自救几次;自救后先放过几个窗口再判(给新连接起速的时间,也防来回折腾) | Whether the in-process session is in use now; how many times this round has self-healed; how many windows to skip after a self-heal before judging again (gives the new connection time to ramp up and avoids flapping)
@property (assign) int64_t curBytes, winBytes; // 当前这一片已收字节;本窗口起点时的已收字节 | Bytes received for the current chunk; bytes received at the start of this window
@property (assign) CFAbsoluteTime winT; @property (assign) double best; // 本窗口起点时刻;本轮见过的最高窗口吞吐(字节 / 秒) | Start time of this window; best window throughput seen this round (bytes / second)
@property (strong) dispatch_source_t watch;
- (NSURLSession *)bg;
@end
@implementation DmAssetDL
+ (instancetype)shared { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"D2R Mobile Resources/data" sid:dm_dl_sid(@".assets") env:@"DM_ASSET_BASE" ptr:@"asset_pointers.txt" base:@"asset_base.txt" key:@"dm_asset_base"]; }); return s; }
+ (instancetype)astcPack { static DmAssetDL *s; static dispatch_once_t once; dispatch_once(&once, ^{ s = [[DmAssetDL alloc] initDir:@"Legacy Device Pack/data" sid:dm_dl_sid(@".astcpack") env:@"DM_ASTC_PACK_BASE" ptr:nil base:@"astc_pack_base.txt" key:@"dm_astc_pack_base"]; }); return s; }
- (instancetype)initDir:(NSString *)dir sid:(NSString *)sid env:(NSString *)env ptr:(NSString *)ptr base:(NSString *)base key:(NSString *)key {
if ((self = [super init])) {
self.q = dispatch_queue_create("dm.assetdl", DISPATCH_QUEUE_SERIAL); self.redo = [NSMutableDictionary new];
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
{ const char *td = getenv("DM_ROMFS_TEST_DOC"); if (td && *td && !strchr(td, '/')) doc = [doc stringByAppendingPathComponent:@(td)]; } // 只测试用:与 main.m romfs_locate 同一个开关,下到被当成「D2R Mobile」的那个文件夹里 | test only: the same switch as romfs_locate in main.m; downloads into the folder that is treated as "D2R Mobile"
__weak DmAssetDL *w = self; // 切到后台:进程内会话在后台不保活,把在途这一片交还给系统的后台会话接着取 | Going to the background: an in-process session is not kept alive there, so hand the chunk in flight back to the system background session to carry on
[NSNotificationCenter.defaultCenter addObserverForName:@"UIApplicationDidEnterBackgroundNotification" object:nil queue:nil usingBlock:^(NSNotification *n) { DmAssetDL *d = w; if (d) dispatch_async(d.q, ^{
if (d.running && d.useFg) { plog("assets: 进后台,在途这一片交还给系统的后台会话"); d.useFg = 0; [d.fg invalidateAndCancel]; d.fg = nil; [d pump]; } }); }];
self.dir = [doc stringByAppendingPathComponent:dir]; self.sid = sid; self.envBase = env; self.ptrFile = ptr; self.baseFile = base; self.defKey = key;
}
return self;
}
void dm_asset_dl_bg_events(NSString *ident, void (^done)(void)) { DmAssetDL *d = [ident isEqualToString:dm_dl_sid(@".astcpack")] ? DmAssetDL.astcPack : DmAssetDL.shared; d.bgDone = done; dispatch_async(d.q, ^{ (void)[d bg]; }); } // 接回同标识的后台会话,事件才送得到 | Reattach the background session with the same identifier, otherwise the events cannot be delivered
- (NSURLSession *)bg { // 后台会话:同一个标识全进程只建一次;杀进程后重开用同一标识接回系统手里没做完的任务 | Background session: one identifier is created only once per process; after the process is killed and relaunched, the same identifier reattaches the unfinished tasks held by the system
if (!self.session) {
NSURLSessionConfiguration *c = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:self.sid];
c.sessionSendsLaunchEvents = YES; c.discretionary = NO; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 60; c.timeoutIntervalForResource = 7 * 24 * 3600;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.session = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq];
}
return self.session;
}
- (NSURLSession *)fgNew { // 新建一个进程内会话:不沿用任何已有连接 | Create a new in-process session: reuses no existing connection
[self.fg invalidateAndCancel];
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.allowsCellularAccess = YES; c.HTTPMaximumConnectionsPerHost = 2;
c.timeoutIntervalForRequest = 30; c.timeoutIntervalForResource = 3600; c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSOperationQueue *oq = [NSOperationQueue new]; oq.underlyingQueue = self.q; oq.maxConcurrentOperationCount = 1;
self.fg = [NSURLSession sessionWithConfiguration:c delegate:self delegateQueue:oq]; return self.fg;
}
// 每 5 秒看一次当前这一片的吞吐(只在 self.q 上跑)。判掉速:一个窗口(缺省 20 秒)的平均吞吐低于 24 KB/s,
// 或低于本轮见过的最高窗口吞吐的四分之一且低于 512 KB/s。测试开关:DM_ASSET_STALL_MIN=<字节/秒>(低于它就算掉速)、DM_ASSET_STALL_WIN=<秒>
// Every 5 seconds, look at the throughput of the current chunk (runs only on self.q). Slowdown rule: the average throughput over one window (20 seconds by default) is below 24 KB/s,
// or below a quarter of the best window throughput seen this round and below 512 KB/s. Test switches: DM_ASSET_STALL_MIN=<bytes/second> (anything below counts as a slowdown), DM_ASSET_STALL_WIN=<seconds>
- (void)watchTick {
if (!self.running) return;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); const char *ew = getenv("DM_ASSET_STALL_WIN"), *em = getenv("DM_ASSET_STALL_MIN"); double win = ew ? atof(ew) : 20;
if (!self.winT) { self.winT = now; self.winBytes = self.curBytes; return; }
if (now - self.winT < win) return;
double rate = MAX(0, self.curBytes - self.winBytes) / (now - self.winT); self.winT = now; self.winBytes = self.curBytes;
if (self.skipWin > 0) { self.skipWin--; if (rate > self.best) self.best = rate; return; }
BOOL slow = em ? rate < atof(em) : (rate < 24 * 1024 || (rate * 4 < self.best && rate < 512 * 1024));
if (rate > self.best) self.best = rate;
if (!slow) return;
self.heal++; self.skipWin = MIN(self.heal, 6); self.useFg = 1; self.winT = 0; self.curBytes = 0;
plog("assets: 这一片掉速(%.0f KB/s,本轮最高 %.0f KB/s):取消、换新连接从已下的地方接着取(第 %d 次)", rate / 1024, self.best / 1024, self.heal);
(void)[self fgNew];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) { for (NSURLSessionTask *t in tasks) if (t.state != NSURLSessionTaskStateCompleted) [t cancel];
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlReconnect")), self.heal]]; [self pump]; }];
}
static NSData *dl_get(NSString *url, NSTimeInterval timeout) { // 小文件(地址文件、清单)同步取,不走缓存 | Small files (address file, manifest) are fetched synchronously, bypassing the cache
NSURL *u = [NSURL URLWithString:url]; if (!u) return nil;
NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.timeoutIntervalForRequest = timeout; c.timeoutIntervalForResource = timeout * 2;
c.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSession *s = [NSURLSession sessionWithConfiguration:c]; dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block NSData *out = nil;
[[s dataTaskWithURL:u completionHandler:^(NSData *d, NSURLResponse *r, NSError *e) {
if (!e && [(NSHTTPURLResponse *)r statusCode] == 200) out = d; else plog("assets: 取 %s 失败:%s", url.UTF8String, e ? e.localizedDescription.UTF8String : [NSString stringWithFormat:@"HTTP %ld", (long)[(NSHTTPURLResponse *)r statusCode]].UTF8String);
dispatch_semaphore_signal(sem); }] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); [s finishTasksAndInvalidate]; return out;
}
static NSString *dl_trim(NSString *s) { s = [s stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; while ([s hasSuffix:@"/"]) s = [s substringToIndex:s.length - 1]; return s; }
static NSArray<NSString *> *dl_lines(NSString *path) { // 包内文本:一行一项,# 开头是注释 | Bundled text: one item per line; lines starting with # are comments
NSMutableArray *a = [NSMutableArray new]; NSString *t = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { NSString *v = dl_trim(l); if (v.length && ![v hasPrefix:@"#"]) [a addObject:v]; }
return a;
}
// 定根地址并取清单。成功返回 nil,失败返回原因
// Determine the root address and fetch the manifest. Returns nil on success, the reason on failure
- (NSString *)resolve {
NSString *res = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"dm"]; NSMutableArray<NSString *> *cand = [NSMutableArray new];
if (getenv("DM_TEST_NO_DL_BASE")) return @(dm_ui("dmDlNoBase")); // 只测试用:同 main.m res_dl_configured | Test only: same as res_dl_configured in main.m
const char *e = getenv(self.envBase.UTF8String); if (e && *e) [cand addObject:dl_trim(@(e))];
else {
for (NSString *p in self.ptrFile ? dl_lines([res stringByAppendingPathComponent:self.ptrFile]) : @[]) {
NSData *d = dl_get(p, 8); NSString *t = d ? [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding] : nil;
NSString *first = dl_trim([t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet].firstObject ?: @"");
if ([first hasPrefix:@"https://"]) { plog("assets: 地址文件 %s → %s", p.UTF8String, first.UTF8String); [cand addObject:first]; }
}
NSString *last = [NSUserDefaults.standardUserDefaults stringForKey:self.defKey]; if (last.length) [cand addObject:last];
[cand addObjectsFromArray:dl_lines([res stringByAppendingPathComponent:self.baseFile])];
}
if (!cand.count) return @(dm_ui("dmDlNoBase"));
for (NSString *b in cand) {
NSData *d = dl_get([b stringByAppendingString:@"/manifest.json"], 15); if (!d) continue;
NSDictionary *j = [NSJSONSerialization JSONObjectWithData:d options:0 error:nil]; NSArray *fs = [j isKindOfClass:NSDictionary.class] ? j[@"files"] : nil;
int64_t tot = 0; BOOL ok = [fs isKindOfClass:NSArray.class] && fs.count;
for (NSDictionary *f in (ok ? fs : @[])) {
NSString *nm = [f isKindOfClass:NSDictionary.class] ? f[@"name"] : nil, *sha = [f isKindOfClass:NSDictionary.class] ? f[@"sha256"] : nil; NSNumber *sz = [f isKindOfClass:NSDictionary.class] ? f[@"size"] : nil;
if (![nm isKindOfClass:NSString.class] || !nm.length || [nm containsString:@"/"] || [nm hasPrefix:@"."] || ![sha isKindOfClass:NSString.class] || sha.length != 64 || ![sz isKindOfClass:NSNumber.class] || sz.longLongValue < 0) { ok = NO; break; }
}
if (!ok) { plog("assets: %s 的清单格式不对,换下一个地址", b.UTF8String); continue; }
// 只下档案文件与它的区段表:清单里别的(配置、密钥、提取工具的各张清单)游戏用不着(见 host/romfs_validate.c),不下、也就不会因为它们下不动
// Download only the archive files and their extent tables: the rest of the manifest (config, key, the extraction tool's manifests) is not needed by the
// game (see host/romfs_validate.c), so it is not downloaded and the download cannot get stuck on it
fs = [fs filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary *f, id _) { return [f[@"name"] hasSuffix:@".data"] || [f[@"name"] hasSuffix:@".data.holes"]; }]];
for (NSDictionary *f in fs) tot += [f[@"size"] longLongValue];
if (!fs.count) { plog("assets: %s 的清单里没有档案文件,换下一个地址", b.UTF8String); continue; }
self.base = b; self.files = fs; self.total = tot; [NSUserDefaults.standardUserDefaults setObject:b forKey:self.defKey];
plog("assets: 下载地址 %s,清单 %lu 个文件共 %lld 字节", b.UTF8String, (unsigned long)fs.count, tot); return nil;
}
return @(dm_ui("dmDlNoServer"));
}
static int64_t dl_size(NSString *p) { NSDictionary *a = [NSFileManager.defaultManager attributesOfItemAtPath:p error:nil]; return a ? (int64_t)[a fileSize] : -1; }
- (NSString *)final:(NSString *)nm { return [self.dir stringByAppendingPathComponent:nm]; }
- (NSString *)part:(NSString *)nm { return [self.dir stringByAppendingPathComponent:[nm stringByAppendingString:@".part"]]; }
- (BOOL)have:(NSDictionary *)f { return dl_size([self final:f[@"name"]]) == [f[@"size"] longLongValue]; } // 正式文件在且字节数对 | The final file exists and its byte count is right
- (int64_t)scan { int64_t n = 0; for (NSDictionary *f in self.files) { if ([self have:f]) n += [f[@"size"] longLongValue]; else { int64_t p = dl_size([self part:f[@"name"]]); if (p > 0) n += MIN(p, [f[@"size"] longLongValue]); } } return n; }
static NSString *dl_sha256(NSString *path) {
NSFileHandle *h = [NSFileHandle fileHandleForReadingAtPath:path]; if (!h) return nil; CC_SHA256_CTX c; CC_SHA256_Init(&c);
for (;;) { @autoreleasepool { NSData *d = [h readDataOfLength:1 << 20]; if (!d.length) break; CC_SHA256_Update(&c, d.bytes, (CC_LONG)d.length); } }
unsigned char dg[32]; CC_SHA256_Final(dg, &c); NSMutableString *s = [NSMutableString new]; for (int i = 0; i < 32; i++) [s appendFormat:@"%02x", dg[i]]; return s;
}
- (void)prepare:(void (^)(NSString *err, int64_t remain, int64_t total, BOOL cellular))done {
self.shortBytes = 0; self.freeBytes = 0; // 每次先清:更早一步失败(取清单断网等)时不留上一轮「空间不够」 | Clear first every time: when an earlier step fails (manifest fetch with no network, etc.), do not keep the previous round's "not enough space"
dispatch_async(self.q, ^{
NSString *err = getenv("DM_ASSET_DL_OFF") ? @"测试开关 DM_ASSET_DL_OFF:下载站当作走不通" : [self resolve]; if (err) { dispatch_async(dispatch_get_main_queue(), ^{ done(err, 0, 0, NO); }); return; }
NSFileManager *fm = NSFileManager.defaultManager; [fm createDirectoryAtPath:self.dir withIntermediateDirectories:YES attributes:nil error:nil];
[[NSURL fileURLWithPath:self.dir.stringByDeletingLastPathComponent] setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:nil]; // 4 GB 资源不进 iCloud 备份 | The 4 GB of assets do not go into iCloud backup
self.settled = [self scan]; int64_t remain = self.total - self.settled;
NSNumber *freeb = nil; [[NSURL fileURLWithPath:self.dir] getResourceValue:&freeb forKey:NSURLVolumeAvailableCapacityForImportantUsageKey error:nil];
{ const char *ft = getenv("DM_ASSET_FREE_TEST"); if (ft) freeb = @((long long)(atof(ft) * 1e9)); } // 测试开关:把手机可用空间当成这么多 GB(造「空间不够」现场) | Test switch: treat the phone's free space as this many GB (reproduces the "not enough space" scenario)
self.freeBytes = freeb ? freeb.longLongValue : 0;
if (freeb && freeb.longLongValue < remain + (200ll << 20)) { self.shortBytes = remain + (200ll << 20) - freeb.longLongValue; NSString *m = [NSString stringWithFormat:@"手机剩余空间不够:还要下 %.2f GB,可用 %.2f GB", remain / 1e9, freeb.longLongValue / 1e9]; dispatch_async(dispatch_get_main_queue(), ^{ done(m, remain, self.total, NO); }); return; }
// 当前网络是不是按流量计费的(蜂窝 / 个人热点):是的话由界面先问玩家
// Whether the current network is metered (cellular / personal hotspot): if so, the UI asks the player first
nw_path_monitor_t mon = nw_path_monitor_create(); dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block BOOL exp = NO; __block int got = 0;
nw_path_monitor_set_queue(mon, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
nw_path_monitor_set_update_handler(mon, ^(nw_path_t p) { if (!got) { got = 1; exp = nw_path_is_expensive(p); dispatch_semaphore_signal(sem); } });
nw_path_monitor_start(mon); dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC)); nw_path_monitor_cancel(mon);
if (getenv("DM_ASSET_CELL_TEST")) exp = YES;
plog("assets: 已有 %lld / %lld 字节,还要下 %lld;%s", self.settled, self.total, remain, exp ? "当前是按流量计费的网络" : "当前不是按流量计费的网络");
dispatch_async(dispatch_get_main_queue(), ^{ done(nil, remain, self.total, exp); });
});
}
- (void)run:(void (^)(int64_t, int64_t, NSString *))progress done:(void (^)(NSString *))done {
dispatch_async(self.q, ^{ self.onProgress = progress; self.onDone = done; self.running = 1; self.retry = 0; self.heal = 0; self.skipWin = 0; self.best = 0; self.winT = 0; self.curBytes = 0;
if (!self.watch) { self.watch = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, self.q); dispatch_source_set_timer(self.watch, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC);
__weak DmAssetDL *w = self; dispatch_source_set_event_handler(self.watch, ^{ [w watchTick]; }); dispatch_resume(self.watch); }
[self pump]; });
}
- (void)report:(int64_t)done note:(NSString *)note { void (^p)(int64_t, int64_t, NSString *) = self.onProgress; int64_t t = self.total; if (p) dispatch_async(dispatch_get_main_queue(), ^{ p(done, t, note); }); }
- (void)finish:(NSString *)err { self.running = 0; void (^d)(NSString *) = self.onDone; self.onDone = nil; plog("assets: 直接下载结束:%s", err ? err.UTF8String : "全部到齐"); if (d) dispatch_async(dispatch_get_main_queue(), ^{ d(err); }); }
// 找到第一个没到齐的文件,给它起(或接回)一个分段任务。只在 self.q 上跑
// Find the first incomplete file and start (or reattach) a ranged task for it. Runs only on self.q
- (void)pump {
if (!self.running) return;
self.settled = [self scan];
for (NSDictionary *f in self.files) {
if ([self have:f]) continue;
NSString *nm = f[@"name"], *part = [self part:nm]; int64_t size = [f[@"size"] longLongValue], p = MAX(dl_size(part), 0);
if (p > size) { [NSFileManager.defaultManager removeItemAtPath:part error:nil]; p = 0; }
if (p == size) { // 到齐:核校验值,对了才改成正式名 | All received: verify the checksum; rename to the final name only if it matches
[self report:self.settled note:[NSString stringWithFormat:@(dm_ui("dmDlVerifying")), nm]];
if (!size) [NSFileManager.defaultManager createFileAtPath:part contents:NSData.data attributes:nil];
NSString *sha = dl_sha256(part);
if ([sha isEqualToString:f[@"sha256"]]) { NSError *e = nil; [NSFileManager.defaultManager removeItemAtPath:[self final:nm] error:nil];
if (![NSFileManager.defaultManager moveItemAtPath:part toPath:[self final:nm] error:&e]) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlWriteFail")), nm, e.localizedDescription]]; return; }
plog("assets: %s 到齐(%lld 字节,校验值对)", nm.UTF8String, size); continue; }
int n = self.redo[nm].intValue + 1; self.redo[nm] = @(n); [NSFileManager.defaultManager removeItemAtPath:part error:nil];
plog("assets: 🔴 %s 校验值不对(得 %s,应 %s),删掉重下(第 %d 次)", nm.UTF8String, sha.UTF8String, [f[@"sha256"] UTF8String], n);
if (n >= 3) { [self finish:[NSString stringWithFormat:@(dm_ui("dmDlBad3")), nm]]; return; }
p = 0; self.settled = [self scan];
}
int64_t end = MIN(p + DL_CHUNK, size) - 1; NSString *desc = [NSString stringWithFormat:@"%@\t%lld\t%lld", nm, p, end];
[[self bg] getTasksWithCompletionHandler:^(NSArray *d0, NSArray *u0, NSArray<NSURLSessionDownloadTask *> *tasks) {
BOOL alive = NO;
for (NSURLSessionTask *t in tasks) { if (t.state == NSURLSessionTaskStateCompleted) continue; if (!self.useFg && !alive && [t.taskDescription isEqualToString:desc]) { alive = YES; if (t.state == NSURLSessionTaskStateSuspended) [t resume]; } else [t cancel]; }
self.winT = 0; self.curBytes = 0; // 新的一片(或刚接回的一片):吞吐窗口从头量。接回的旧任务若是僵死的,一个窗口后照掉速处理 | A new chunk (or one just re-attached): measure the throughput window from scratch. If a re-attached old task is dead, it is treated as a slowdown after one window
if (alive) { plog("assets: 接回系统手里没做完的任务:%s 字节 %lld–%lld", nm.UTF8String, p, end); return; }
NSString *enc = [nm stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/data/%@", self.base, enc]]];
[rq setValue:[NSString stringWithFormat:@"bytes=%lld-%lld", p, end] forHTTPHeaderField:@"Range"]; rq.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSessionDownloadTask *t = [(self.useFg ? (self.fg ?: [self fgNew]) : [self bg]) downloadTaskWithRequest:rq]; t.taskDescription = desc; [t resume];
}];
[self report:self.settled note:nil];
return;
}
[self finish:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didWriteData:(int64_t)n totalBytesWritten:(int64_t)w totalBytesExpectedToWrite:(int64_t)x {
self.curBytes = w;
if (self.running) [self report:self.settled + w note:nil];
}
- (void)URLSession:(NSURLSession *)s downloadTask:(NSURLSessionDownloadTask *)t didFinishDownloadingToURL:(NSURL *)loc {
NSArray<NSString *> *d = [t.taskDescription componentsSeparatedByString:@"\t"]; if (d.count != 3) return;
NSString *nm = d[0], *part = [self part:nm]; int64_t off = d[1].longLongValue, end = d[2].longLongValue, got = dl_size(loc.path), have = MAX(dl_size(part), 0);
NSHTTPURLResponse *r = (NSHTTPURLResponse *)t.response; NSString *cr = [r valueForHTTPHeaderField:@"Content-Range"]; NSString *wantcr = [NSString stringWithFormat:@"bytes %lld-%lld/", off, end];
if (r.statusCode != 206 || ![cr hasPrefix:wantcr] || got != end - off + 1 || have != off) { // 不是要的那一段(服务器不认 Range / 中间页 / 重复送达):丢掉,pump 会按 .part 的实际长度重新要 | Not the range we asked for (server ignores Range / interstitial page / duplicate delivery): discard; pump will ask again based on the actual length of .part
plog("assets: 丢弃一段 %s 字节 %lld–%lld:HTTP %ld,Content-Range %s,收到 %lld 字节,.part 现有 %lld", nm.UTF8String, off, end, (long)r.statusCode, cr.UTF8String ?: "无", got, have); return; }
NSFileHandle *in = [NSFileHandle fileHandleForReadingAtPath:loc.path]; if (![NSFileManager.defaultManager fileExistsAtPath:part]) [NSFileManager.defaultManager createFileAtPath:part contents:nil attributes:nil];
NSFileHandle *out = [NSFileHandle fileHandleForWritingAtPath:part]; if (!in || !out) { plog("assets: 🔴 打不开 %s", part.UTF8String); return; }
@try { [out seekToEndOfFile]; for (;;) { @autoreleasepool { NSData *b = [in readDataOfLength:1 << 20]; if (!b.length) break; [out writeData:b]; } } [out synchronizeFile]; }
@catch (NSException *ex) { plog("assets: 🔴 写 %s 出错:%s", part.UTF8String, ex.reason.UTF8String); [out truncateFileAtOffset:(unsigned long long)off]; }
[out closeFile]; [in closeFile];
}
- (void)URLSession:(NSURLSession *)s task:(NSURLSessionTask *)t didCompleteWithError:(NSError *)e {
if (e && e.code == NSURLErrorCancelled) return; // 我们自己取消的多余任务 | Surplus tasks that we cancelled ourselves
if (!self.running) return; // 进程刚被系统唤醒、界面还没来要:落盘已在上面做完,等 run 时再接着 | The process was just woken by the system and the UI has not asked yet: writing to disk is already done above; resume when run is called
if (e) { int wait = MIN(30, 2 << MIN(self.retry, 4)); self.retry++;
plog("assets: 一段没取成(%s),%d 秒后自动重试(第 %d 次)", e.localizedDescription.UTF8String, wait, self.retry);
[self report:[self scan] note:[NSString stringWithFormat:@(dm_ui("dmDlNetRetry")), wait]];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, wait * NSEC_PER_SEC), self.q, ^{ [self pump]; }); return; }
self.retry = 0; [self pump];
}
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)s { void (^d)(void) = self.bgDone; self.bgDone = nil; if (d) dispatch_async(dispatch_get_main_queue(), d); }
@end
+44
View File
@@ -0,0 +1,44 @@
// iOS 启动 I/O 采样(DM_BOOTPROF=1 时生效;分段表 ⓪–⑥ 由宿主 diag.c 出,零点同为进程创建):
// 每 100 ms 一行 Documents/bootprof.tsv:t(秒,零点 = 进程创建,内核 p_starttime)、
// ri_pageins(缺页读入次数:内嵌代码段等文件页首次触达)、ri_diskio_bytesread(真读盘字节:RomFS 首读 + 代码页)、phys_footprint
// iOS startup I/O sampling (active when DM_BOOTPROF=1; the phase table ⓪–⑥ is produced by the host's diag.c, with the same zero point = process creation):
// one line every 100 ms to Documents/bootprof.tsv: t (seconds, zero point = process creation, kernel p_starttime),
// ri_pageins (page-in count: first touch of file pages such as the embedded code segment), ri_diskio_bytesread (bytes actually read from disk: first RomFS reads + code pages), phys_footprint
#import <Foundation/Foundation.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <mach/mach.h>
#include <pthread.h>
#include <unistd.h>
int proc_pid_rusage(int pid, int flavor, rusage_info_t *buffer); // libproc(iOS SDK 无头文件,符号在 libsystem) | libproc (no header in the iOS SDK; the symbol is in libsystem)
uint64_t now_ns(void); // 宿主时钟(hle_os.c) | Host clock (hle_os.c)
static uint64_t g_t0; // 本构造函数时刻 | Time of this constructor
static double g_pre_s; // 进程创建 → 本构造函数(秒) | Process creation → this constructor (seconds)
static void *sampler(void *p) {
FILE *f = fopen((const char *)p, "w"); if (!f) return NULL;
fprintf(f, "t_since_spawn\tpageins\tdisk_read_MiB\tfootprint_MiB\n");
for (int i = 0; i < 300; i++) { // 30 秒 | 30 seconds
struct rusage_info_v4 ri; task_vm_info_data_t vi; mach_msg_type_number_t n = TASK_VM_INFO_COUNT;
proc_pid_rusage(getpid(), RUSAGE_INFO_V4, (rusage_info_t *)&ri);
task_info(mach_task_self(), TASK_VM_INFO, (task_info_t)&vi, &n);
fprintf(f, "%.2f\t%llu\t%.1f\t%llu\n", g_pre_s + (now_ns() - g_t0) / 1e9, ri.ri_pageins, ri.ri_diskio_bytesread / 1048576.0, vi.phys_footprint >> 20);
fflush(f);
usleep(100000);
}
fclose(f); return NULL;
}
__attribute__((constructor)) static void bootprof_ios(void) {
g_t0 = now_ns();
if (!getenv("DM_BOOTPROF")) return;
struct kinfo_proc kp; size_t len = sizeof kp; int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()};
struct timeval now; gettimeofday(&now, NULL);
if (!sysctl(mib, 4, &kp, &len, NULL, 0))
g_pre_s = (now.tv_sec - kp.kp_proc.p_starttime.tv_sec) + (now.tv_usec - kp.kp_proc.p_starttime.tv_usec) / 1e6;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
char *path = strdup([doc stringByAppendingPathComponent:@"bootprof.tsv"].fileSystemRepresentation);
pthread_t th; pthread_create(&th, NULL, sampler, path); pthread_detach(th);
}
+202
View File
@@ -0,0 +1,202 @@
// iCloud 存档同步的 iOS 一侧:拿 iCloud 容器目录、让云端的包先下载好,再调共用核心 dm_cloud_sync(dm/host/dm_cloudsync.c)。
// 启动:dm_cloud_boot 在 boot_thread 里、dm_main 挂存档之前调,最多等 5 秒,拉云端各包、按「后写覆盖先写」换进本地存档,之后游戏照常读存档列表。
// 运行中:存档每提交成功一次(hle_fs.c 的 Commit),提交钩子先把已提交目录 clonefile 成快照(写时复制,近乎零成本);局内只记成待传,出局 / 切后台时在串行队列里把快照与云端对比、只上传(allow_down = 0);不在局内的提交当场传。
// 只同步玩家真实存档 Documents/save;测试存档(save.test 等)缺省不同步。测试开关 DM_TEST_ICLOUD_SUB=<子目录名>:测试存档也同步,云端用容器里的这个子目录(与真实存档的 saves 隔开,不会把测试角色传到玩家设备上)。
// 测试开关 DM_TEST_ICLOUD_DIR=<本地目录>:用本地目录当云端(不碰 iCloud),测试存档也同步。不以 / 开头的路径拼到 App 的 Documents 下(下同)。
// 测试开关 DM_TEST_ICLOUD_ROOT=<本地目录>:用本地目录当 iCloud 容器的 Documents(下有 saves / saves_v2),验目录换代与一次性迁移;测试存档也同步。
// 开关:「自定义」页 icloud(缺省开)。没登录 iCloud / 本 App 的 iCloud 被关:取不到容器,整套跳过,日志记一行。
// iOS side of iCloud save sync: get the iCloud container directory, let the cloud packages download first, then call the shared core dm_cloud_sync (dm/host/dm_cloudsync.c).
// Startup: dm_cloud_boot is called in boot_thread before dm_main mounts the save; waits at most 5 seconds, pulls each cloud package and swaps it into the local save under "later write overwrites earlier write"; after that the game reads the save list as usual.
// While running: each time a save commit succeeds (Commit in hle_fs.c), the commit hook first clonefiles the committed directory into a snapshot (copy-on-write, nearly free); in a run it is only marked pending, and on leaving the run / going to background the snapshot is compared with the cloud on a serial queue, upload only (allow_down = 0); commits outside a run are uploaded on the spot.
// Only the player's real save Documents/save is synced; test saves (save.test etc.) are not synced by default. Test switch DM_TEST_ICLOUD_SUB=<subdirectory name>: test saves are synced too, and the cloud uses this subdirectory of the container (kept apart from the real save's saves, so test characters are not uploaded to the player's devices).
// Test switch DM_TEST_ICLOUD_DIR=<local directory>: use a local directory as the cloud (iCloud untouched); test saves are synced too. Paths not starting with / are joined under the App's Documents (same below).
// Test switch DM_TEST_ICLOUD_ROOT=<local directory>: use a local directory as the iCloud container's Documents (containing saves / saves_v2), to verify the directory generation change and the one-time migration; test saves are synced too.
// Switch: icloud on the 「自定义」(Custom) page (on by default). Not signed in to iCloud / iCloud turned off for this App: the container cannot be obtained, the whole thing is skipped and one log line is written.
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <signal.h>
#include <sys/clonefile.h>
#include <stdatomic.h>
#include "front.h"
#include "hle.h"
int dm_cloud_sync(const char *save, const char *cloud, const char *bak, const char *statef, int allow_down, uint64_t now_ms, int (*ready)(const char *unit));
int dm_custom_get(const char *key);
extern void (*g_dm_save_commit_hook)(const char *commit_dir);
static NSString *g_cloud, *g_save, *g_bak, *g_state; // 云端目录 / 本地存档 / 备份 / 状态文件 | Cloud directory / local save / backup / state file
static dispatch_queue_t g_q;
static uint64_t now_ms(void) { return (uint64_t)([NSDate date].timeIntervalSince1970 * 1000); }
// 云端某个单位的包是否已在本机(iCloud 里没下载的文件是占位:旧系统是「.<名>.icloud」,新系统是同名但下载状态不是「最新」)
// Whether a given unit's package in the cloud is already on this device (undownloaded files in iCloud are placeholders: on older systems ".<name>.icloud", on newer systems the same name with a download status other than "current")
static int pack_ready(const char *unit) {
NSString *nm = [NSString stringWithFormat:@"%s.pack", unit];
if ([NSFileManager.defaultManager fileExistsAtPath:[g_cloud stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", nm]]]) return 0;
NSURL *u = [NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:nm]]; NSString *st = nil;
if (![u getResourceValue:&st forKey:NSURLUbiquitousItemDownloadingStatusKey error:nil] || !st) return 1; // 不是 iCloud 管的文件(或没有这个包):按已在本机 | Not an iCloud-managed file (or no such package): treated as already on this device
return [st isEqualToString:NSURLUbiquitousItemDownloadingStatusCurrent];
}
static int pending_downloads(int start) { // 还没下载好的包数;start = 1 时顺手请系统开始下载 | Number of packages not yet downloaded; with start = 1 also ask the system to start downloading
int n = 0; NSFileManager *fm = NSFileManager.defaultManager;
for (NSString *f in [fm contentsOfDirectoryAtPath:g_cloud error:nil] ?: @[]) {
NSString *nm = f; if ([f hasPrefix:@"."] && [f hasSuffix:@".icloud"]) nm = [f substringWithRange:NSMakeRange(1, f.length - 8)];
if (![nm hasSuffix:@".pack"]) continue;
if (pack_ready([nm substringToIndex:nm.length - 5].UTF8String)) continue;
n++; if (start) [fm startDownloadingUbiquitousItemAtURL:[NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:nm]] error:nil];
}
return n;
}
static int run_sync(NSString *save, int down) { // 在文件协调里做:iCloud 守护进程同时在写这个目录时不会读到半个文件 | Done inside file coordination: half-written files are not read while the iCloud daemon is writing this directory at the same time
__block int r = -1; NSError *err = nil;
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateWritingItemAtURL:[NSURL fileURLWithPath:g_cloud] options:NSFileCoordinatorWritingForMerging error:&err byAccessor:^(NSURL *u) {
(void)u; r = dm_cloud_sync(save.fileSystemRepresentation, g_cloud.fileSystemRepresentation, g_bak.fileSystemRepresentation, g_state.fileSystemRepresentation, down, now_ms(), pack_ready); }];
if (err) LOG("【红】iCloud 同步:文件协调失败 %s", err.localizedDescription.UTF8String);
return r;
}
// 存档提交钩子(hle_fs.c,持着存档锁调):只做快照,其余放队列。
// 局内(58 分钟提交 127 次、上传 97 次,平均 35 秒碰一次网):只留最新那份快照记成「待传」,不上传;
// 退出这一局回到前端(主菜单 / 选角页)、切到后台时各传一次(dm_cloud_flush)。不在局内(选角 / 建角 / 删角色)的提交照旧当场传——
// 删角色只在选角页发生,拖到以后传的话被强杀后再启动会把删掉的角色从云端拉回来(启动同步把「本地没了」当丢失、从云端拿回)。
// 被强杀 / 崩溃没来得及传:待传快照随之作废(启动时清掉),启动那次同步看到本地自上次同步后改过、云端没变,照常补传(dm_cloudsync.c lchg && !cchg → UP)
// Save commit hook (hle_fs.c, called while holding the save lock): only takes a snapshot, the rest goes to the queue.
// In a run (127 commits and 97 uploads in 58 minutes, touching the network every 35 seconds on average): keep only the newest snapshot marked as "pending upload", do not upload;
// upload once each when leaving the run back to the front end (main menu / character select page) and when going to background (dm_cloud_flush). Commits outside a run (character select / create / delete character) are still uploaded on the spot --
// character deletion only happens on the character select page; if deferred, a force-kill followed by a relaunch would pull the deleted character back from the cloud (startup sync treats "missing locally" as lost and restores it from the cloud).
// Force-killed / crashed before uploading: the pending snapshot is voided with it (cleared at startup), and the startup sync sees local changed since the last sync and cloud unchanged, so it uploads as usual (dm_cloudsync.c lchg && !cchg → UP)
static NSString *g_pend; // 局内最新一次提交的快照(只在 g_q 上读写) | Snapshot of the newest commit in the run (read and written only on g_q)
static _Atomic int g_bg; // App 在后台:此时的提交(失活时请求的那次存盘)当场传 | App in background: a commit at this time (the save requested on resign active) is uploaded on the spot
static _Atomic int g_session; // 在一局里:进局(第一次出现局内画面)起,到游戏发「回到前端」(FrontEndNavigation:ToFrontEnd)为止——中间的读取画面(切幕 / 传送点)不算出局 | In a run: from entering the run (first appearance of the in-run picture) until the game sends "back to front end" (FrontEndNavigation:ToFrontEnd) -- loading screens in between (act change / waypoint) do not count as leaving the run
static void upload_snap(NSString *snap, const char *why) { // 在 g_q 上调 | Called on g_q
if (dm_custom_get("icloud")) { int n = run_sync(snap, 0); LOG("iCloud 同步:%s上传 %d 个", why, n); }
[NSFileManager.defaultManager removeItemAtPath:snap error:nil];
}
static void on_commit(const char *commit_dir) {
static unsigned seq; NSString *snap = [NSString stringWithFormat:@"%@.cloudsnap%u", g_save, ++seq];
[NSFileManager.defaultManager removeItemAtPath:snap error:nil];
if (clonefile(commit_dir, snap.fileSystemRepresentation, 0)) { LOG("【红】iCloud 同步:存档快照失败 errno=%d,这次提交不上传", errno); return; }
int defer = atomic_load(&g_session) && !atomic_load(&g_bg);
dispatch_async(g_q, ^{
if (defer) { if (g_pend) [NSFileManager.defaultManager removeItemAtPath:g_pend error:nil]; g_pend = snap; return; } // 局内:换成这一份,等出局 / 切后台 | In a run: replace with this copy and wait for leaving the run / going to background
if (g_pend) { [NSFileManager.defaultManager removeItemAtPath:g_pend error:nil]; g_pend = nil; } // 这一份更新,旧的待传作废 | This copy is newer; the old pending upload is voided
upload_snap(snap, atomic_load(&g_bg) ? "后台存档提交后" : "存档提交后(不在局内)");
});
}
// 出局 / 切后台:把局内攒下的最新一份传掉。切后台用系统给的后台收尾时间,传完才结束(最多约 30 秒,系统到点前会叫停)
// Leaving a run / going to background: upload the newest copy accumulated during the run. Going to background uses the background completion time granted by the system and ends only after the upload finishes (about 30 seconds at most; the system calls a stop before time is up)
void dm_cloud_flush(int background) {
if (!g_q) return; // 没开同步(测试存档 / 没登录 iCloud / 自定义页关了) | Sync not enabled (test save / not signed in to iCloud / turned off on the Custom page)
if (background) atomic_store(&g_bg, 1);
__block UIBackgroundTaskIdentifier tk = UIBackgroundTaskInvalid;
if (background) tk = [UIApplication.sharedApplication beginBackgroundTaskWithName:@"dm.cloud" expirationHandler:^{ LOG("【红】iCloud 同步:后台收尾时间到,系统叫停(没传完的下次启动补传)"); [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; }];
dispatch_async(g_q, ^{
NSString *p = g_pend; g_pend = nil;
if (p) upload_snap(p, background ? "切到后台," : "退出这一局回到前端,");
else LOG("iCloud 同步:%s,局内没有待传的存档", background ? "切到后台" : "退出这一局回到前端");
if (tk != UIBackgroundTaskInvalid) dispatch_async(dispatch_get_main_queue(), ^{ if (tk != UIBackgroundTaskInvalid) { [UIApplication.sharedApplication endBackgroundTask:tk]; tk = UIBackgroundTaskInvalid; } });
});
}
void dm_cloud_foreground(void) { atomic_store(&g_bg, 0); }
static void cloud_ingame(int on) { if (on) atomic_store(&g_session, 1); }
static void cloud_charsel(void) { if (atomic_exchange(&g_session, 0)) dm_cloud_flush(0); } // 退出这一局回到前端(主菜单 / 选角页):这一局结束 | Left this run back to the front end (main menu / character select page): this run has ended
static NSURL *container(double limit) { // 取 iCloud 容器:要在主线程以外调,第一次可能要等系统建目录;取不到返回 nil 并记原因 | Get the iCloud container: must be called off the main thread; the first time may have to wait for the system to create the directory; returns nil and logs the reason if it cannot be obtained
__block NSURL *ct = nil; dispatch_semaphore_t got = dispatch_semaphore_create(0);
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ ct = [NSFileManager.defaultManager URLForUbiquityContainerIdentifier:nil]; dispatch_semaphore_signal(got); });
if (dispatch_semaphore_wait(got, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(limit * NSEC_PER_SEC)))) { LOG("iCloud 不可用:取容器超过 %.0f 秒,本次只用本地存档", limit); return nil; }
if (!ct) LOG("iCloud 不可用:没登录 iCloud 或本 App 的 iCloud 被关,只用本地存档");
return ct;
}
// 云端目录换代(编年史仓库第 5 步;旧版本是覆盖更新的):本版起存档格式变了(储藏箱 14 列),旧包读新档会静默删掉新列里的物品。
// 云端改用 Documents/saves_v2,旧包仍用 Documents/saves,两边互不覆盖。新包第一次启动(saves_v2 还没有)把 saves 复制过去一次——只读旧目录,旧目录一个字节都不改、不删:
// 先等旧目录里的包全部下载到本机(占位文件复制过去是空的);逐个文件复制到 saves_v2.tmp,最后写完成清单 sw_migrated.txt(迁移时的全部包名),
// 再把 saves_v2.tmp 整个改名成 saves_v2——改名是最后一步,有 saves_v2 就一定是写完清单的整套。中途被杀:下次启动先删掉残留的 .tmp 从头再来。
// 没等到下载完 / 复制失败 = 本次不迁移也不同步,下次启动再试(先同步会建出空的 saves_v2,之后再也不迁移,别的设备在旧目录里的新档就漏了)。
// 用之前查齐(所有设备,含迁移的那台):saves_v2 里有清单、清单上的包都到了本机目录(已下载或是 iCloud 占位)才同步。另一台设备上 iCloud 是一个文件一个文件
// 下来的:没查齐就同步,本机较旧的那份会按「云端没有包 → 上传」传上去,后写覆盖掉迁移过来的新进度。查齐过一次就在本地记一笔(<存档>.cloudv2ok),以后不再查
// (之后角色删了包会少,不能一直按清单卡)。返回 0 = 本次跳过同步
// Cloud directory generation change (chronicle vault step 5; older versions were updated by overwrite): from this version the save format changed (stash has 14 columns); an old build reading a new save silently deletes the items in the new columns.
// The cloud now uses Documents/saves_v2 while old builds keep using Documents/saves, so neither overwrites the other. On its first launch (saves_v2 does not exist yet) the new build copies saves over once -- the old directory is only read, not one byte of it is changed or deleted:
// first wait until all packages in the old directory are downloaded to this device (a placeholder file would copy over as empty); copy file by file into saves_v2.tmp, and finally write the completion manifest sw_migrated.txt (all package names at migration time),
// then rename saves_v2.tmp as a whole to saves_v2 -- the rename is the last step, so if saves_v2 exists it is always a complete set with the manifest written. Killed midway: on the next launch delete the leftover .tmp first and start over.
// Download not finished in time / copy failed = no migration and no sync this time, retry on the next launch (syncing first would create an empty saves_v2, after which migration never happens again and new saves from other devices in the old directory would be missed).
// Check completeness before use (all devices, including the one that migrated): sync only when saves_v2 contains the manifest and every package on the manifest has reached this device's directory (downloaded, or present as an iCloud placeholder). On another device iCloud brings files down one
// at a time: syncing before the check passes, this device's older copy would be uploaded under "no package in the cloud → upload", and the later write would overwrite the newer migrated progress. Once the check has passed, record it locally (<save>.cloudv2ok) and never check again
// (later, deleting a character removes packages, so we cannot keep blocking on the manifest forever). Returns 0 = skip sync this time
static NSString *test_path(const char *e) { // 测试开关里的路径:不以 / 开头的拼到 App 的 Documents 下(真机容器路径每次装包都变) | Paths in test switches: those not starting with / are joined under the App's Documents (the real-device container path changes on every install)
if (!e) return nil; if (e[0] == '/') return @(e);
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@(e)];
}
static int v2_ready(NSString *nw, NSString *okf) { // 迁移过来的整套是否都到了本机 | Whether the whole migrated set has arrived on this device
NSFileManager *fm = NSFileManager.defaultManager; if ([fm fileExistsAtPath:okf]) return 1;
NSString *ls = [NSString stringWithContentsOfFile:[nw stringByAppendingPathComponent:@"sw_migrated.txt"] encoding:NSUTF8StringEncoding error:nil];
if (!ls) { LOG("iCloud 同步:saves_v2 里还没有完成清单(别的设备的迁移还没传完?),本次不同步"); return 0; }
int miss = 0, n = 0; for (NSString *f in [ls componentsSeparatedByString:@"\n"]) { if (!f.length) continue; n++;
if (![fm fileExistsAtPath:[nw stringByAppendingPathComponent:f]] && ![fm fileExistsAtPath:[nw stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", f]]]) miss++; }
if (miss) { LOG("iCloud 同步:saves_v2 清单 %d 项还缺 %d 项没到本机,本次不同步", n, miss); return 0; }
[@"" writeToFile:okf atomically:YES encoding:NSUTF8StringEncoding error:nil]; LOG("iCloud 同步:saves_v2 清单 %d 项都已到本机", n); return 1;
}
static int migrate_v2(NSString *docs, double deadline) {
NSFileManager *fm = NSFileManager.defaultManager; NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"], *old = [docs stringByAppendingPathComponent:@"saves"], *tmp = [nw stringByAppendingString:@".tmp"];
if ([fm fileExistsAtPath:nw]) return 1;
if (![fm fileExistsAtPath:old]) { LOG("iCloud 同步:云端没有旧目录 saves,直接用 saves_v2"); [fm createDirectoryAtPath:nw withIntermediateDirectories:YES attributes:nil error:nil];
[@"" writeToFile:[nw stringByAppendingPathComponent:@"sw_migrated.txt"] atomically:YES encoding:NSUTF8StringEncoding error:nil]; return 1; } // 空清单:没有要等的包 | Empty manifest: no packages to wait for
g_cloud = old; int pend = pending_downloads(1);
while (pend && CFAbsoluteTimeGetCurrent() < deadline) { usleep(100000); pend = pending_downloads(0); }
g_cloud = nil;
if (pend) { LOG("iCloud 同步:旧目录 saves 还有 %d 个包没下载完,本次不迁移、不同步,下次启动再试", pend); return 0; }
const char *kill_at = getenv("DM_TEST_ICLOUD_MIGRATE_KILL"); // 测试:复制完第 N 个文件后自杀(N = marker:写完清单、改名之前),验中途被杀 | Test: kill self after copying the Nth file (N = marker: after writing the manifest, before the rename), to verify being killed midway
__block BOOL ok = YES; __block NSError *e2 = nil; __block NSMutableString *list = [NSMutableString string]; __block int copied = 0; NSError *err = nil;
[[[NSFileCoordinator alloc] initWithFilePresenter:nil] coordinateReadingItemAtURL:[NSURL fileURLWithPath:old] options:0 error:&err byAccessor:^(NSURL *u) {
if ([fm fileExistsAtPath:tmp]) { LOG("iCloud 同步:上次迁移没做完(有 saves_v2.tmp),删掉重来"); [fm removeItemAtPath:tmp error:nil]; }
ok = [fm createDirectoryAtPath:tmp withIntermediateDirectories:NO attributes:nil error:&e2];
for (NSString *f in [fm contentsOfDirectoryAtPath:u.path error:nil] ?: @[]) { if (!ok) break; if ([f hasPrefix:@"."]) continue; // 隐藏文件(系统的)不带 | Hidden files (the system's) are not carried over
ok = [fm copyItemAtPath:[u.path stringByAppendingPathComponent:f] toPath:[tmp stringByAppendingPathComponent:f] error:&e2]; if (!ok) break;
if ([f hasSuffix:@".pack"]) [list appendFormat:@"%@\n", f]; copied++;
if (kill_at && atoi(kill_at) == copied) { LOG("DM_TEST_ICLOUD_MIGRATE_KILL:复制完第 %d 个文件,自杀", copied); kill(getpid(), SIGKILL); } }
if (ok) ok = [list writeToFile:[tmp stringByAppendingPathComponent:@"sw_migrated.txt"] atomically:YES encoding:NSUTF8StringEncoding error:&e2];
if (ok && kill_at && !strcmp(kill_at, "marker")) { LOG("DM_TEST_ICLOUD_MIGRATE_KILL:清单已写、改名之前自杀"); kill(getpid(), SIGKILL); }
if (ok) ok = [fm moveItemAtPath:tmp toPath:nw error:&e2]; }];
if (!ok || err) { [fm removeItemAtPath:tmp error:nil];
if ([fm fileExistsAtPath:nw]) { LOG("iCloud 同步:saves_v2 已由别的设备建好,用它"); return 1; } // 两台同时迁:后改名的那台失败,用先到的那套 | Two devices migrating at once: the one that renames later fails and uses the set that arrived first
LOG("【红】iCloud 同步:旧目录 saves 复制到 saves_v2 失败(%s),本次不同步", (err ?: e2).localizedDescription.UTF8String ?: "?"); return 0; }
LOG("iCloud 同步:旧目录 saves 已复制到 saves_v2(%d 个文件,清单 %lu 个包),旧目录留给旧包用", copied, (unsigned long)[list componentsSeparatedByString:@"\n"].count - 1); return 1;
}
void dm_cloud_boot(void) {
const char *sv = getenv("DM_SAVE"), *sub = getenv("DM_TEST_ICLOUD_SUB"), *ldir = getenv("DM_TEST_ICLOUD_DIR"), *lroot = getenv("DM_TEST_ICLOUD_ROOT"); if (!sv) return;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *save = @(sv); int real = [save.stringByStandardizingPath isEqualToString:[doc stringByAppendingPathComponent:@"save"].stringByStandardizingPath];
int off = getenv("DM_TEST_ICLOUD_OFF") != NULL; // 测试总闸:脚本起的局一律带它(tools/cloud_guard.sh),整局不同步 | Test master gate: runs launched by scripts always carry it (tools/cloud_guard.sh), and the whole run does not sync
if (!real && !sub && !ldir && !lroot) { if (off) LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); return; } // 测试存档:不同步 | Test save: not synced
// Mac 上跑的 iOS 包:缺省整个不连真实 iCloud。这个包只发 iPhone / iPad,Mac 上跑的全是开发与测试;开发机登着真实账号时,
// 它就是那个账号的又一台设备,任何脚本、手点图标都会和真实云端双向同步(出过把测试存档传进真实云端)。本地测试云端(DIR / ROOT)不受影响;
// 真要在 Mac 上连真实云端:同时给 DM_REAL_ICLOUD=1 与 DM_REAL_ICLOUD_CONFIRM=写入真实云端。真机不走这一支。
// iOS app running on a Mac: by default it does not connect to real iCloud at all. This package ships only for iPhone / iPad, and everything run on a Mac is development and testing; when the development machine is signed in to a real account,
// it is one more device of that account, and any script or a tap on the icon would sync both ways with the real cloud (test saves have been uploaded to the real cloud before). The local test cloud (DIR / ROOT) is unaffected;
// to really connect to the real cloud on a Mac: give both DM_REAL_ICLOUD=1 and DM_REAL_ICLOUD_CONFIRM=写入真实云端. Real devices do not take this branch.
if (NSProcessInfo.processInfo.isiOSAppOnMac && !ldir && !lroot) { const char *r1 = getenv("DM_REAL_ICLOUD"), *r2 = getenv("DM_REAL_ICLOUD_CONFIRM");
if (!(r1 && !strcmp(r1, "1") && r2 && !strcmp(r2, "写入真实云端"))) { LOG("iCloud 同步:Mac 上运行:缺省不同步 iCloud"); return; }
LOG("【红】iCloud 同步:Mac 上运行,已显式放开(DM_REAL_ICLOUD):本局连真实云端"); }
if (off) { LOG("iCloud 同步:测试开关 DM_TEST_ICLOUD_OFF,本局不同步"); return; }
if (!dm_custom_get("icloud")) { LOG("iCloud 同步:自定义页已关,不同步"); return; }
double t0 = CFAbsoluteTimeGetCurrent(), limit = 5.0;
if (ldir) g_cloud = test_path(ldir); // 测试:本地目录当云端(没有 iCloud 权限的开发包也能验整条链) | Test: use a local directory as the cloud (a dev build without iCloud entitlement can also verify the whole chain)
else if (sub) { NSURL *ct = container(limit); if (!ct) return; g_cloud = [[ct.path stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@(sub)]; }
else { NSString *docs = test_path(lroot); if (!lroot) { NSURL *ct = container(limit); if (!ct) return; docs = [ct.path stringByAppendingPathComponent:@"Documents"]; }
if (!migrate_v2(docs, t0 + limit)) return;
NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"]; if (!v2_ready(nw, [save stringByAppendingString:@".cloudv2ok"])) return;
g_cloud = nw; }
[NSFileManager.defaultManager createDirectoryAtPath:g_cloud withIntermediateDirectories:YES attributes:nil error:nil];
g_save = save; g_bak = [save stringByAppendingString:@".cloudbak"]; g_state = [save stringByAppendingString:@".cloudstate"];
if (ldir) { g_bak = [g_cloud stringByAppendingString:@".cloudbak"]; g_state = [g_cloud stringByAppendingString:@".cloudstate"]; } // 测试的本地云端:状态与备份跟云端目录走,不与真存档(同一路径、连真实 iCloud 时)共用——共用的话测试局会改写真存档的同步状态 | Local cloud for tests: state and backup follow the cloud directory and are not shared with the real save (same path, when connected to real iCloud) -- if shared, test runs would rewrite the real save's sync state
g_q = dispatch_queue_create("dm.cloud", DISPATCH_QUEUE_SERIAL);
for (NSString *f in [NSFileManager.defaultManager contentsOfDirectoryAtPath:save.stringByDeletingLastPathComponent error:nil] ?: @[]) // 上次被杀时没删掉的提交快照 | Commit snapshots not deleted when we were last killed
if ([f hasPrefix:[save.lastPathComponent stringByAppendingString:@".cloudsnap"]]) [NSFileManager.defaultManager removeItemAtPath:[save.stringByDeletingLastPathComponent stringByAppendingPathComponent:f] error:nil];
int pend = pending_downloads(1);
while (pend && CFAbsoluteTimeGetCurrent() - t0 < limit) { usleep(100000); pend = pending_downloads(0); }
int n = run_sync(save, 1);
LOG("iCloud 同步:启动 %.0f ms,动作 %d 个%s(云端目录 %s)", (CFAbsoluteTimeGetCurrent() - t0) * 1000, n, pend ? [NSString stringWithFormat:@",%d 个包没等到下载完、本次跳过", pend].UTF8String : "", ldir ? "本地测试目录" : sub ? sub : "saves_v2");
g_dm_save_commit_hook = on_commit;
{ extern void (*g_dm_ingame_hook)(int); extern void (*g_dm_charsel_hook)(void); g_dm_ingame_hook = cloud_ingame; g_dm_charsel_hook = cloud_charsel; } // 进局记一局开始;回到前端 = 这一局结束,传一次 | Entering a run marks the start of a run; returning to the front end = this run has ended, upload once
}
+147
View File
@@ -0,0 +1,147 @@
// 手柄接入(原版 Switch 本来就是手柄操作,恢复手柄支持;复用原版手柄交互,不自己设计)。
// iOS GameController(MFi / Xbox / PS / Switch Pro)的扩展手柄 → 原版手柄输入(宿主 dm_pad_set,与触屏输入在游戏取手柄时合并)。
// 四个面键按键帽上印的字母对应:提示条写哪个字母,就按手柄上印着那个字母的键(提示条画的是 Switch 键帽,不跟手柄型号换图)。
// 任天堂手柄(Switch Pro、Joy-Con)与 Switch 原样一致;Xbox 手柄 = 下 A、右 B、左 X、上 Y;没有字母的(PS 等)和认不出类型的按 Xbox 的位置排(下方键 = 确认)。
// 规则与认手柄类型的办法在 host/dm_padmap.h(纯函数,宿主单测 t_padmap 核);连接时记一行日志写明这个手柄用哪种排法。
// (先前一律按 Switch 的位置排——右键确认——Xbox 手柄玩家照提示条「A 选择」按印着 A 的下方键,实际发的是 B,选角页选不了人。)
// 系统给的面键是按位置定的、不看键帽上的字(GCExtendedGamepad.h:buttonA 下、buttonB 右、buttonX 左、buttonY 上);玩家在系统设置里改过键位的,系统已先换好再给我们。
// 任天堂手柄上系统给的是不是同样按位置(印 A 的右键 = buttonB),没有实体手柄实测过,依据只有头文件的约定。
// 肩键 L/R、扳机 ZL/ZR、摇杆按下 LS/RS、十字键、菜单键→+、选项键→-。
// 选项键(buttonOptions)有的手柄没有,那时减号没有来源:不拿 Home 键顶(头文件:系统不吃才轮到 App,靠不住),留空。Xbox 的视图键、PS 的分享 / 创建键、Switch Pro 的 − 都是选项键。
// 摇杆照原值换成 ±32767(GameController 与原版都是上为正)。
//
// 谁接管(谁有明确输入谁接管,不因漂移来回切):
// · 手柄「明确输入」= 按下任何一颗键,或把摇杆从中位推出来。摇杆带迟滞:推过 25% 才算推出,回到 15% 以内才算回中——停在阈值附近的漂移不会一会儿算一会儿不算。
// · 手柄有明确输入 → 手柄模式(布局换原版手柄版);碰屏幕 → 触屏模式(前端调 dm_gamepad_touched)。
// · 碰过屏幕之后,摇杆要先回中、再推出来才重新接管:一直偏着的摇杆(漂移大的手柄)不会把布局又切回手柄版。按键随时接管。
// · 触屏模式下手柄摇杆的值不交给游戏(手柄连着放在一边、摇杆有点漂移,不该盖掉触屏摇杆);手柄模式下没推出来的摇杆给 0、推出来的给原值。
// · 游戏取手柄处(hle_hid.c fill):触屏摇杆有值就用触屏的,否则用手柄的。
// 多个手柄:每个手柄各存各的键和摇杆,交给游戏的是合起来的——键取或、每根摇杆取推得最远的那个。断开一个只拿掉它那一份,别的手柄按着的键不丢。
// 失活 / 进后台 / 来电(前端 front_ios_focus_event → dm_gamepad_reset):所有手柄的键和摇杆清零。回调只在值变化时来,按着键切走、在后台松开,回来不会补一次「松开」。
// Controller support (the original Switch game is controller-driven to begin with, so controller support is restored; the original controller
// interaction is reused, nothing is designed from scratch).
// The extended gamepad of iOS GameController (MFi / Xbox / PS / Switch Pro) -> the original controller input (host dm_pad_set, merged with
// touch input when the game reads the controller).
// The four face buttons are mapped by the letter printed on the button glyph: whichever letter the button legend shows, press the button
// with that letter printed on the controller (the button legend draws Switch glyphs and does not change images per controller model).
// Nintendo controllers (Switch Pro, Joy-Con) are identical to the Switch as is; Xbox controllers = bottom A, right B, left X, top Y;
// controllers with no letters (PS etc.) and unrecognized types are laid out by the Xbox positions (bottom button = confirm).
// The rule and the way the controller type is recognized are in host/dm_padmap.h (pure function, checked by the host unit test t_padmap);
// on connect one log line states which layout this controller uses.
// (Previously everything was laid out by the Switch positions -- right button confirms -- so an Xbox controller player following the legend
// bar's "A Select" pressed the bottom button printed A, B was actually sent, and no character could be selected on the character select page.)
// The face buttons given by the system are defined by position, not by the letter on the glyph (GCExtendedGamepad.h: buttonA bottom,
// buttonB right, buttonX left, buttonY top); if the player has remapped buttons in system settings, the system has already applied that
// before handing them to us.
// Whether the system also reports Nintendo controllers by position (the right button printed A = buttonB) has not been measured on a
// physical controller; the only basis is the convention in the header file.
// Shoulder buttons L/R, triggers ZL/ZR, stick clicks LS/RS, D-pad, menu button -> +, options button -> -.
// Some controllers have no options button (buttonOptions), and then minus has no source: the Home button is not used as a substitute
// (header file: the app only gets it when the system does not consume it, which is unreliable), so it is left empty. The Xbox view button,
// the PS share / create button and the Switch Pro - button are all the options button.
// Sticks are converted from their raw values to +/-32767 (up is positive in both GameController and the original game).
// Who takes over (whoever has explicit input takes over; no flipping back and forth because of drift):
// - Controller "explicit input" = pressing any button, or pushing a stick out of center. Sticks have hysteresis: only past 25% counts as
// pushed out, and only back within 15% counts as centered -- drift sitting near the threshold does not count one moment and not the next.
// - The controller has explicit input -> controller mode (the layout switches to the original controller layout); touching the screen ->
// touch mode (the front end calls dm_gamepad_touched).
// - After the screen has been touched, a stick must return to center and then be pushed out before it takes over again: a stick that stays
// deflected (a controller with heavy drift) will not flip the layout back to the controller layout. Buttons take over at any time.
// - In touch mode the controller stick values are not handed to the game (a connected controller lying aside with slight stick drift
// should not override the touch stick); in controller mode a stick that is not pushed out gives 0 and one that is pushed out gives the
// raw value.
// - Where the game reads the controller (hle_hid.c fill): if the touch stick has a value the touch one is used, otherwise the controller's.
// Multiple controllers: each controller keeps its own buttons and sticks, and what the game gets is the combination -- buttons are ORed, and
// for each stick the one pushed furthest wins. Disconnecting one removes only its share; buttons held on other controllers are not lost.
// Resign active / entering background / incoming call (front end front_ios_focus_event -> dm_gamepad_reset): buttons and sticks of all
// controllers are zeroed. Callbacks only arrive when a value changes, so after switching away with a button held and releasing it in the
// background, no "release" is delivered on return.
#import <GameController/GameController.h>
#include "dm_input.h"
#include "dm_padmap.h"
#include "hle.h"
static void (*g_on_mode)(int pad);
static int g_pad_mode, g_need_center;
void dm_padmode_request(int pad); // 宿主 dm_padmode.c:布局换成原版手柄版 / 触屏版 | Host dm_padmode.c: switch the layouts to the original controller version / the touch version
static void set_mode(int pad) { if (g_pad_mode == pad) return; g_pad_mode = pad; dm_padmode_request(pad); LOG("手柄:%s", pad ? "手柄有输入 → 手柄模式" : "碰了屏幕 / 手柄断开 → 触屏模式"); if (g_on_mode) g_on_mode(pad); }
int dm_gamepad_mode(void) { return g_pad_mode; }
// 各手柄各存各的(槽 0、1 留给触点脚本的两个虚拟手柄,其余给实体手柄)
// Each controller is stored separately (slots 0 and 1 are reserved for the touch script's two virtual controllers, the rest are for physical controllers)
enum { NSLOT = 6 };
static struct { const void *who; uint64_t b; int32_t ax[4]; } g_s[NSLOT];
static int slot_of(const void *who, int make) { int fr = -1; for (int i = 0; i < NSLOT; i++) { if (g_s[i].who == who) return i; if (fr < 0 && !g_s[i].who) fr = i; }
if (make && fr >= 0) { memset(&g_s[fr], 0, sizeof g_s[fr]); g_s[fr].who = who; return fr; } return -1; }
static int32_t axis(float v) { if (v > 1) v = 1; if (v < -1) v = -1; return (int32_t)lroundf(v * DM_STICK_MAX); }
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; } // 迟滞:推过 25% 算推出,回到 15% 内算回中 | Hysteresis: past 25% counts as pushed out, back within 15% counts as centered
// 把各手柄合起来、定模式、交给宿主。任何一份变了都重算一遍
// Merge all controllers, decide the mode and hand the result to the host. Recompute whenever any one of them changes
static void apply(void) {
uint64_t b = 0; int32_t ax[4] = {0}; double best[2] = {0};
for (int i = 0; i < NSLOT; i++) { if (!g_s[i].who) continue; b |= g_s[i].b;
for (int k = 0; k < 2; k++) { double m = hypot(g_s[i].ax[2 * k], g_s[i].ax[2 * k + 1]); if (m > best[k]) { best[k] = m; ax[2 * k] = g_s[i].ax[2 * k]; ax[2 * k + 1] = g_s[i].ax[2 * k + 1]; } } }
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; // 碰过屏幕后摇杆回过中了:之后再推出来算数 | The stick has returned to center since the screen was touched: pushing it out again from now on counts
if ((b & ~prev_b) || ((on[0] || on[1]) && !g_need_center)) set_mode(1);
prev_b = b;
if (!g_pad_mode || !on[0]) ax[0] = ax[1] = 0; if (!g_pad_mode || !on[1]) ax[2] = ax[3] = 0; // 触屏模式不交摇杆;手柄模式下没推出来的给 0 | Sticks are not delivered in touch mode; in controller mode a stick that is not pushed out gives 0
// ZR:原版六个技能格之一。这一格空着(没绑技能)时按它 = 免费回城(手柄玩家也免费回城,与触屏回城钮一致);绑了技能就整颗交还原版(不再整颗占用)。
// 想把回城放在别的键上:原版选技能界面「综合技能」里有回城技能可绑(宿主进局时挂上的,dm_freetp.c),那条走原版自己的施放,不经这里。
// 只在游戏态接管:面板开着时 ZR 照常交给原版(储藏箱 / 编年史用 ZL / ZR 翻页签);按下时在游戏态接管的那一下,到松开前都不交给游戏
// ZR: one of the six original skill slots. While this slot is empty (no skill bound), pressing it = free town portal (controller players get
// the free town portal too, consistent with the touch town portal button); once a skill is bound the whole button is handed back to the
// original game (we no longer claim the whole button).
// To put town portal on another key: the original skill selection screen has a town portal skill under "General Skills" that can be bound
// (attached by the host on joining a run, dm_freetp.c); that one goes through the original game's own cast and does not pass through here.
// Taken over only in game state: with a panel open ZR goes to the original game as usual (the stash / Chronicle use ZL / ZR to switch tabs);
// a press that was taken over in game state is not handed to the game until it is released
{ static uint64_t prev; static int mine; void dm_tp_request(void); int dm_front_navigation(void), dm_freetp_zr_free(int zl);
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]);
}
static void put(const void *who, uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) {
int i = slot_of(who, 1); if (i < 0) return; g_s[i].b = b; g_s[i].ax[0] = lx; g_s[i].ax[1] = ly; g_s[i].ax[2] = rx; g_s[i].ax[3] = ry; apply();
}
static void drop(const void *who) { // 这个手柄没了:只拿掉它那一份;一个手柄都不剩才回触屏模式 | This controller is gone: remove only its share; return to touch mode only when no controller is left
int i = slot_of(who, 0); if (i < 0) return; memset(&g_s[i], 0, sizeof g_s[i]); apply();
for (int k = 0; k < NSLOT; k++) if (g_s[k].who) return;
set_mode(0);
}
void dm_gamepad_touched(void) { if (g_pad_mode) { g_need_center = 1; set_mode(0); apply(); } } // 前端:碰了屏幕。摇杆此刻偏着的话要先回中才重新接管 | Front end: the screen was touched. If a stick is deflected right now it must return to center before taking over again
void dm_gamepad_reset(void) { // 前端:失活 / 进后台 / 来电 | Front end: resign active / enter background / incoming call
int any = 0; for (int i = 0; i < NSLOT; i++) if (g_s[i].who) { any |= g_s[i].b != 0 || g_s[i].ax[0] || g_s[i].ax[1] || g_s[i].ax[2] || g_s[i].ax[3]; g_s[i].b = 0; memset(g_s[i].ax, 0, sizeof g_s[i].ax); }
if (any) { LOG("手柄:失活,手柄的键和摇杆清零"); apply(); }
}
// 测试(触点脚本 pad / pad2 / padoff / padoff2 步):没有实体手柄时走同一条路,只少了 GameController 回调那一层。n = 1 或 2:两个虚拟手柄
// Test (touch script pad / pad2 / padoff / padoff2 steps): without a physical controller the same path is taken, minus only the GameController callback
// layer. n = 1 or 2: two virtual controllers
void dm_gamepad_inject_n(int n, uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { put((const void *)(intptr_t)(n == 2 ? 2 : 1), b, lx, ly, rx, ry); }
void dm_gamepad_drop_n(int n) { LOG("手柄:断开(虚拟手柄 %d)", n == 2 ? 2 : 1); drop((const void *)(intptr_t)(n == 2 ? 2 : 1)); }
void dm_gamepad_inject(uint64_t b, int32_t lx, int32_t ly, int32_t rx, int32_t ry) { dm_gamepad_inject_n(1, b, lx, ly, rx, ry); }
static void publish(GCController *c, GCExtendedGamepad *g) {
uint64_t b = 0;
b |= dm_padmap_face(dm_padmap_kind(c.productCategory.UTF8String, c.vendorName.UTF8String), g.buttonA.pressed, g.buttonB.pressed, g.buttonX.pressed, g.buttonY.pressed); // 按键帽上的字母(dm_padmap.h) | By the letter on the button glyph (dm_padmap.h)
if (g.leftShoulder.pressed) b |= DM_BTN_L; if (g.rightShoulder.pressed) b |= DM_BTN_R; if (g.leftTrigger.pressed) b |= DM_BTN_ZL; if (g.rightTrigger.pressed) b |= DM_BTN_ZR;
if (g.leftThumbstickButton.pressed) b |= DM_BTN_LS; if (g.rightThumbstickButton.pressed) b |= DM_BTN_RS;
if (g.buttonMenu.pressed) b |= DM_BTN_PLUS; if (g.buttonOptions.pressed) b |= DM_BTN_MINUS;
if (g.dpad.left.pressed) b |= DM_BTN_LEFT; if (g.dpad.up.pressed) b |= DM_BTN_UP; if (g.dpad.right.pressed) b |= DM_BTN_RIGHT; if (g.dpad.down.pressed) b |= DM_BTN_DOWN;
put((__bridge const void *)c, b, axis(g.leftThumbstick.xAxis.value), axis(g.leftThumbstick.yAxis.value), axis(g.rightThumbstick.xAxis.value), axis(g.rightThumbstick.yAxis.value));
}
static void attach(GCController *c) {
GCExtendedGamepad *g = c.extendedGamepad; if (!g) { LOG("手柄:%s 不是扩展手柄,不接", c.vendorName.UTF8String ?: "?"); return; }
LOG("手柄:连上 %s,类别 %s → 面键用 %s 排法", c.vendorName.UTF8String ?: "?", c.productCategory.UTF8String ?: "?", dm_padmap_kind(c.productCategory.UTF8String, c.vendorName.UTF8String) == DM_PADKIND_NINTENDO ? "任天堂(右 A、下 B、上 X、左 Y)" : "Xbox(下 A、右 B、左 X、上 Y)");
__weak GCController *wc = c;
g.valueChangedHandler = ^(GCExtendedGamepad *gp, GCControllerElement *el) { (void)el; GCController *sc = wc; if (sc) publish(sc, gp); };
}
void dm_gamepad_start(void (*on_mode)(int pad)) {
g_on_mode = on_mode;
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserverForName:GCControllerDidConnectNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n) { attach(n.object); }];
[nc addObserverForName:GCControllerDidDisconnectNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *n) {
LOG("手柄:断开 %s", ((GCController *)n.object).vendorName.UTF8String ?: "?"); drop((__bridge const void *)n.object); }];
for (GCController *c in GCController.controllers) attach(c);
}
+41
View File
@@ -0,0 +1,41 @@
#include "dm_metal_cache_guard.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int has_parent_component(const char *path) {
const char *cursor = path;
while (*cursor) {
while (*cursor == '/') cursor++;
const char *start = cursor;
while (*cursor && *cursor != '/') cursor++;
if ((size_t)(cursor - start) == 2 && !strncmp(start, "..", 2)) return 1;
}
return 0;
}
static int under(const char *path, const char *directory) {
size_t length = strlen(directory);
return strlen(path) > length && !strncmp(path, directory, length) && path[length] == '/';
}
int dm_metal_cache_path_allowed(const char *container_root, const char *target_path) {
char root[PATH_MAX], target[PATH_MAX], caches[PATH_MAX], temporary[PATH_MAX];
if (!container_root || !target_path || container_root[0] != '/' || target_path[0] != '/' ||
has_parent_component(container_root) || has_parent_component(target_path)) return 0;
if (!realpath(container_root, root) || !realpath(target_path, target)) return 0;
if (!strcmp(root, target)) return 0;
size_t prefix_length = strlen(container_root);
while (prefix_length > 1 && container_root[prefix_length - 1] == '/') prefix_length--;
if (strlen(target_path) <= prefix_length || strncmp(target_path, container_root, prefix_length)) return 0;
const char *relative = target_path + prefix_length;
if (strncmp(relative, "/Library/Caches/", strlen("/Library/Caches/")) &&
strncmp(relative, "/tmp/", strlen("/tmp/"))) return 0;
int caches_length = snprintf(caches, sizeof caches, "%s/Library/Caches", root);
int temporary_length = snprintf(temporary, sizeof temporary, "%s/tmp", root);
if (caches_length < 0 || (size_t)caches_length >= sizeof caches ||
temporary_length < 0 || (size_t)temporary_length >= sizeof temporary) return 0;
return under(target, caches) || under(target, temporary);
}
+6
View File
@@ -0,0 +1,6 @@
#ifndef DM_METAL_CACHE_GUARD_H
#define DM_METAL_CACHE_GUARD_H
int dm_metal_cache_path_allowed(const char *container_root, const char *target_path);
#endif
+89
View File
@@ -0,0 +1,89 @@
// 秘境爬塔左侧任务栏:放在左边并缩小,布局参考暗黑 3 右侧任务栏,倒计时条和整体风格按暗黑 2。
// 尺寸数字照设计稿:设计稿按 Mac 窗口 2 倍像素画(游戏区 1334×614),
// 这里以 u = 游戏区高 / 614 为单位换算。数据由 dm/host/dm_rift.c 出(dm_rift_hud),前端每帧调(front_ios.m tickTouchControls)。
// 字:原版 BlizzardGlobal——运行时从资源包读出来注册(不进仓库、不进 App 包);读不到就用系统粗体。
// 资源包读法同 dm/ios/tools/touch_layout.py read_layout:data/build_manifest.psv 按路径后缀找行 → 第 7 列编码键(第 10、11 字节 = 数据档号,12–16 = 偏移)、
// 第 8 列原始长度、第 9 列编码(n 原样 / z 整块 zlib / 其余 BLTE 分块:每块首字节 N 原样、Z = zlib)。
// Left-side quest bar for the rift tower climb: placed on the left and shrunk; the layout follows Diablo 3's right-side quest bar, the countdown bar and overall style follow Diablo 2.
// Size numbers follow the design mock: the mock is drawn at 2x pixels of the Mac window (game area 1334×614),
// and here everything is converted with u = game area height / 614 as the unit. Data comes from dm/host/dm_rift.c (dm_rift_hud); the front end calls it every frame (front_ios.m tickTouchControls).
// Font: the original game's BlizzardGlobal -- read from the asset pack at runtime and registered (not in the repository, not in the App bundle); if it cannot be read, use the system bold font.
// The asset pack is read the same way as dm/ios/tools/touch_layout.py read_layout: find the row in data/build_manifest.psv by path suffix → column 7 is the encoding key (bytes 10 and 11 = data archive number, 12–16 = offset),
// column 8 the raw length, column 9 the encoding (n as-is / z whole-block zlib / otherwise BLTE chunks: first byte of each chunk N as-is, Z = zlib).
#import <UIKit/UIKit.h>
#include "dm_i18n.h"
#import <CoreText/CoreText.h>
#include "../../host/dm_rift.h"
static NSData *zinflate(const uint8_t *p, size_t n, size_t cap) { // zlib(带 2 字节头)→ 原文;Foundation 的 Zlib 算法是裸 deflate,跳过头 | zlib (with 2-byte header) → plaintext; Foundation's Zlib algorithm is raw deflate, so skip the header
(void)cap; if (n < 2) return nil; return [[NSData dataWithBytes:p + 2 length:n - 2] decompressedDataUsingAlgorithm:NSDataCompressionAlgorithmZlib error:nil];
}
static NSData *romfs_file(NSString *suffix) {
const char *root = getenv("DM_ROMFS"); if (!root) return nil;
NSString *data = [@(root) stringByAppendingPathComponent:@"data"], *psv = [NSString stringWithContentsOfFile:[data stringByAppendingPathComponent:@"build_manifest.psv"] encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [psv componentsSeparatedByString:@"\n"]) { NSArray<NSString *> *f = [line componentsSeparatedByString:@"|"];
if (f.count < 11 || [line hasPrefix:@"#"] || ![f[9].lowercaseString hasSuffix:suffix]) continue;
NSString *ek = f[6]; if (ek.length < 32) return nil; uint8_t k[16]; for (int i = 0; i < 16; i++) k[i] = (uint8_t)strtol([[ek substringWithRange:NSMakeRange(i * 2, 2)] UTF8String], NULL, 16);
uint64_t off = 0; for (int i = 11; i < 16; i++) off = off << 8 | k[i]; long rawlen = f[7].longLongValue;
NSFileHandle *h = [NSFileHandle fileHandleForReadingAtPath:[data stringByAppendingPathComponent:[NSString stringWithFormat:@"%02d-%08d.data", k[9], k[10]]]]; if (!h) return nil;
[h seekToFileOffset:off]; NSData *raw = [h readDataOfLength:rawlen]; [h closeFile]; const uint8_t *r = raw.bytes; if ((long)raw.length != rawlen) return nil;
if ([f[8] isEqualToString:@"n"]) return raw;
if ([f[8] isEqualToString:@"z"]) return zinflate(r, raw.length, 64 << 20);
uint32_t hs = (uint32_t)r[4] << 24 | r[5] << 16 | r[6] << 8 | r[7], nch = (uint32_t)r[9] << 16 | r[10] << 8 | r[11], pos = hs; NSMutableData *o = [NSMutableData data];
for (uint32_t i = 0; i < nch; i++) { const uint8_t *e = r + 12 + i * 24; uint32_t es = (uint32_t)e[0] << 24 | e[1] << 16 | e[2] << 8 | e[3], ds = (uint32_t)e[4] << 24 | e[5] << 16 | e[6] << 8 | e[7];
if (pos + es > raw.length) return nil; const uint8_t *b = r + pos;
if (b[0] == 'N') [o appendBytes:b + 1 length:es - 1]; else { NSData *d = zinflate(b + 1, es - 1, ds); if (!d) return nil; [o appendData:d]; } pos += es; }
return o; }
return nil;
}
static UIFont *d2font(CGFloat size) { // 原版 BlizzardGlobal(中文、数字都是它) | The original game's BlizzardGlobal (used for both Chinese text and digits)
static NSString *name; static int tried;
if (!tried) { tried = 1; NSData *d = romfs_file(@"/hd/ui/fonts/blizzardglobal-v5_81.ttf");
CGDataProviderRef p = d ? CGDataProviderCreateWithCFData((__bridge CFDataRef)d) : NULL; CGFontRef f = p ? CGFontCreateWithDataProvider(p) : NULL;
if (f && CTFontManagerRegisterGraphicsFont(f, NULL)) name = (__bridge_transfer NSString *)CGFontCopyPostScriptName(f);
if (f) CGFontRelease(f); if (p) CGDataProviderRelease(p);
NSLog(@"[秘境] 任务栏字体:%@", name ?: @"读不到原版 BlizzardGlobal,用系统粗体"); }
return (name ? [UIFont fontWithName:name size:size] : nil) ?: [UIFont boldSystemFontOfSize:size];
}
static UIColor *rgb(int r, int g, int b, CGFloat a) { return [UIColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:a]; }
static CATextLayer *text_layer(void) { CATextLayer *t = [CATextLayer layer]; t.contentsScale = UIScreen.mainScreen.scale; t.shadowOpacity = 0.86; t.shadowOffset = CGSizeMake(1, 1); t.shadowRadius = 0; t.shadowColor = UIColor.blackColor.CGColor; return t; }
static void set_text(CATextLayer *t, NSString *s, UIFont *f, UIColor *c, CGRect fr, NSString *align) {
t.frame = fr; t.alignmentMode = align; t.foregroundColor = c.CGColor; t.font = (__bridge CFTypeRef)f; t.fontSize = f.pointSize;
if (![t.string isEqual:s]) t.string = s;
}
void dm_rift_hud_draw(UIView *host, CGRect wr, BOOL hide) {
static CALayer *box, *lineT, *lineB, *lineL, *track, *ticks[9]; static CAGradientLayer *fill; static CAShapeLayer *pin[2]; static CATextLayer *title, *sub, *timer, *goal;
dm_rift_hud_t h; int on = !hide && dm_rift_hud(&h);
if (!box) { if (!on) return;
box = [CALayer layer]; box.backgroundColor = rgb(0, 0, 0, 170 / 255.0).CGColor;
lineT = [CALayer layer]; lineB = [CALayer layer]; lineL = [CALayer layer]; track = [CALayer layer]; fill = [CAGradientLayer layer];
title = text_layer(); sub = text_layer(); timer = text_layer(); goal = text_layer();
for (CALayer *l in @[lineT, lineB, lineL, title, sub, timer, goal, track]) [box addSublayer:l];
[track addSublayer:fill]; for (int i = 0; i < 9; i++) { ticks[i] = [CALayer layer]; ticks[i].backgroundColor = rgb(0, 0, 0, 110 / 255.0).CGColor; [track addSublayer:ticks[i]]; }
for (int i = 0; i < 2; i++) { pin[i] = [CAShapeLayer layer]; pin[i].fillColor = rgb(160, 135, 80, 1).CGColor; pin[i].strokeColor = rgb(60, 48, 30, 1).CGColor; [box addSublayer:pin[i]]; }
[host.layer addSublayer:box]; }
[CATransaction begin]; [CATransaction setDisableActions:YES];
box.hidden = !on;
if (on) {
CGFloat u = wr.size.height / 614, W = 250 * u, H = 78 * u;
box.frame = CGRectMake(wr.origin.x + 28 * u, wr.origin.y + 150 * u, W, H);
lineT.frame = CGRectMake(0, 0, W, MAX(1, u)); lineB.frame = CGRectMake(0, H - MAX(1, u), W, MAX(1, u)); lineL.frame = CGRectMake(0, 0, 2 * u, H);
lineT.backgroundColor = lineB.backgroundColor = rgb(120, 100, 60, 0.9).CGColor; lineL.backgroundColor = rgb(150, 125, 75, 1).CGColor;
int g = h.guardian, s = h.secs_left < 0 ? 0 : h.secs_left; UIColor *gold = rgb(199, 179, 119, 1), *red = rgb(200, 50, 40, 1), *white = rgb(215, 210, 200, 1), *grey = rgb(150, 145, 135, 1);
set_text(title, @(dm_ui("dmRiftHudTitle")), d2font(17 * u), g ? red : gold, CGRectMake(10 * u, 6 * u, 40 * u, 22 * u), kCAAlignmentLeft);
NSString *st = h.done ? (h.inc ? [NSString stringWithFormat:@(dm_ui("dmRiftHudDone")), h.tier] : [NSString stringWithFormat:@(dm_ui("dmRiftHudLate")), h.tier]) : g ? @(dm_ui("dmRiftHudGuard")) : [NSString stringWithFormat:@(dm_ui("dmRiftTierN")), h.tier];
set_text(sub, st, d2font(14 * u), white, CGRectMake(48 * u, 9 * u, 130 * u, 19 * u), kCAAlignmentLeft);
set_text(timer, [NSString stringWithFormat:@"%d:%02d", s / 60, s % 60], d2font(17 * u), (s <= 60 && !h.done) ? red : gold, CGRectMake(W - 90 * u, 6 * u, 80 * u, 22 * u), kCAAlignmentRight);
NSString *gl = h.done ? (h.inc ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.tier + h.inc] : @(dm_ui("dmRiftHudSame"))) : g ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)];
set_text(goal, gl, d2font(12 * u), grey, CGRectMake(10 * u, 32 * u, W - 20 * u, 17 * u), kCAAlignmentLeft);
CGRect tr = CGRectMake(11 * u, 55 * u, W - 22 * u, 10 * u); // 含 1 单位外框(条 8 + 外框各 1) // 进度条:外框暗边 + 深底,填充金褐(守护者转暗红),每 10% 一道刻痕,两端菱形钉 | Includes the 1-unit outer frame (bar 8 + frame 1 on each side) // Progress bar: dark-edged outer frame + deep background, golden-brown fill (turns dark red for the guardian), a notch every 10%, diamond studs at both ends
track.frame = tr; track.backgroundColor = rgb(25, 20, 14, 1).CGColor; track.borderColor = rgb(95, 78, 48, 1).CGColor; track.borderWidth = MAX(1, u);
CGFloat bw = MAX(1, u); fill.frame = CGRectMake(bw, bw, (tr.size.width - 2 * bw) * (h.done ? 1 : h.progress), tr.size.height - 2 * bw);
fill.colors = g ? @[(id)rgb(190, 50, 40, 1).CGColor, (id)rgb(110, 20, 15, 1).CGColor] : @[(id)rgb(205, 160, 80, 1).CGColor, (id)rgb(140, 100, 40, 1).CGColor];
for (int i = 0; i < 9; i++) ticks[i].frame = CGRectMake(bw + (tr.size.width - 2 * bw) * (i + 1) / 10, bw, MAX(1, u), tr.size.height - 2 * bw);
for (int i = 0; i < 2; i++) { CGFloat cx = i ? tr.origin.x + tr.size.width + 4 * u : tr.origin.x - 4 * u, cy = CGRectGetMidY(tr), r = 4 * u; UIBezierPath *p = [UIBezierPath bezierPath];
[p moveToPoint:CGPointMake(cx, cy - r)]; [p addLineToPoint:CGPointMake(cx + r, cy)]; [p addLineToPoint:CGPointMake(cx, cy + r)]; [p addLineToPoint:CGPointMake(cx - r, cy)]; [p closePath]; pin[i].path = p.CGPath; pin[i].lineWidth = MAX(1, u * 0.8); }
}
[CATransaction commit];
}
+90
View File
@@ -0,0 +1,90 @@
// 壳专用(不含游戏内容的公开版安装包,tools/shell_build.sh):首次启动把全部着色器一次编完,带进度。内测 / 自己用 Xcode 构建的包不编这个文件的内容。
// 为什么要有:使用者的电脑上没有苹果的着色器编译器时,着色器是以源码放进安装包的(tools/d2rm_pack.py、gfx/tools/nometal_run.py),
// 设备上用到哪个现编哪个。真机实测:平均约 80 毫秒一个、单个最长约 450 毫秒;边玩边编的话第一次进一个新场景会顿约 0.8 秒
// (编好的库同一处是 0.12 秒)。所以改成进主菜单之前一次编完——系统会把编好的结果缓存,之后游戏里再建同一个库不花时间。
// 做完的记号放在 Library/Caches(和系统的着色器缓存在同一处,系统清缓存时一起没,下次启动自动重做一遍)。
// 中途切到后台 / 被杀:已编的在系统缓存里,回来从头数一遍,已编的每个只要不到 1 毫秒,等于接着做。
// Shell only (the public install package with no game content, tools/shell_build.sh): on first launch compile all shaders in one go, with progress. Beta packages / packages you build yourself with Xcode do not compile this file's contents.
// Why it exists: when the user's computer has no Apple shader compiler, the shaders are put into the install package as source (tools/d2rm_pack.py, gfx/tools/nometal_run.py),
// and each is compiled on the device when it is first used. Measured on a real device: about 80 ms each on average, about 450 ms for the longest single one; compiling while playing, the first entry into a new scene stutters for about 0.8 seconds
// (0.12 seconds at the same spot with compiled libraries). So it is changed to compiling everything once before entering the main menu -- the system caches the compiled results, and building the same library again in the game afterwards takes no time.
// The completion marker is placed in Library/Caches (the same place as the system's shader cache, so it goes away together when the system clears caches, and the next launch automatically redoes it once).
// Sent to the background / killed midway: what was compiled is in the system cache; on return it counts from the start, each already compiled one taking less than 1 ms, which amounts to resuming.
#ifdef DM_SHELL
#import <Metal/Metal.h>
#import <UIKit/UIKit.h>
#include <stdatomic.h>
#include <stdio.h>
#include <string.h>
static void pl(NSString *s) { fprintf(stderr, "[dm] %s\n", s.UTF8String); }
static BOOL zh(void) { return [NSLocale.preferredLanguages.firstObject hasPrefix:@"zh"]; }
static NSString *libdir(void) { // <包>/msl/b-<链版本>:壳里只有一个版本目录 | <package>/msl/b-<chain version>: the shell has only one version directory
NSString *msl = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"msl"];
for (NSString *d in [NSFileManager.defaultManager contentsOfDirectoryAtPath:msl error:nil] ?: @[]) if ([d hasPrefix:@"b-"]) return [msl stringByAppendingPathComponent:d];
return nil;
}
static NSString *marker(NSString *dir) {
NSString *c = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
return [c stringByAppendingPathComponent:[NSString stringWithFormat:@"dm_shader_prep_%@_%@.done", dir.lastPathComponent, NSProcessInfo.processInfo.operatingSystemVersionString.length ? @(NSProcessInfo.processInfo.operatingSystemVersion.majorVersion * 100 + NSProcessInfo.processInfo.operatingSystemVersion.minorVersion).stringValue : @"0"]];
}
static BOOL is_source(NSString *path) { // 编好的库以 MTLB 开头;不是的就是源码 | a compiled library starts with MTLB; anything else is source
FILE *f = fopen(path.fileSystemRepresentation, "rb"); if (!f) return NO; char h[4] = {0}; size_t n = fread(h, 1, 4, f); fclose(f);
return n == 4 && memcmp(h, "MTLB", 4) != 0;
}
// 要不要做:返回 1 = 已接手(显示进度页,做完调 done);0 = 不用做(没有源码着色器,或上次已经做完)
// Whether it needs to run: returns 1 = taken over (shows the progress page, calls done when finished); 0 = nothing to do (no source shaders, or already finished last time)
int dm_shader_prep_begin(void (^done)(void)) {
NSString *dir = libdir(); if (!dir) return 0;
NSString *mk = marker(dir); if ([NSFileManager.defaultManager fileExistsAtPath:mk]) return 0;
NSMutableArray<NSString *> *src = [NSMutableArray array];
for (NSString *f in [[NSFileManager.defaultManager contentsOfDirectoryAtPath:dir error:nil] sortedArrayUsingSelector:@selector(compare:)] ?: @[])
if ([f hasSuffix:@".metallib"] && is_source([dir stringByAppendingPathComponent:f])) [src addObject:[dir stringByAppendingPathComponent:f]];
if (!src.count) return 0;
UIWindow *win = nil;
for (UIScene *s in UIApplication.sharedApplication.connectedScenes) if ([s isKindOfClass:UIWindowScene.class]) for (UIWindow *w in ((UIWindowScene *)s).windows) if (!win || w.isKeyWindow) win = w;
UIView *host = win.rootViewController.view ?: win; if (!host) { pl(@"【红】着色器准备:没有窗口可放进度页,跳过(进游戏后会边玩边编,第一次进新场景会顿)"); return 0; }
UIView *v = [[UIView alloc] initWithFrame:host.bounds]; v.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; v.backgroundColor = UIColor.blackColor;
UILabel *title = [UILabel new], *sub = [UILabel new], *note = [UILabel new]; UIProgressView *bar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
for (UILabel *l in @[title, sub, note]) { l.textColor = [UIColor colorWithWhite:0.85 alpha:1]; l.textAlignment = NSTextAlignmentCenter; l.numberOfLines = 0; l.translatesAutoresizingMaskIntoConstraints = NO; [v addSubview:l]; }
title.font = [UIFont systemFontOfSize:20 weight:UIFontWeightSemibold]; sub.font = [UIFont monospacedDigitSystemFontOfSize:15 weight:UIFontWeightRegular]; note.font = [UIFont systemFontOfSize:13]; note.textColor = [UIColor colorWithWhite:0.6 alpha:1];
bar.translatesAutoresizingMaskIntoConstraints = NO; bar.progressTintColor = [UIColor colorWithRed:0.78 green:0.36 blue:0.16 alpha:1]; [v addSubview:bar];
title.text = zh() ? @"首次启动:正在准备着色器" : @"First launch: preparing shaders";
note.text = zh() ? @"只需要做这一次,做完以后游戏里不会因为着色器卡顿。\n系统更新或重装之后会再做一次。可以切到后台,回来接着做。"
: @"This is only needed once; afterwards the game will not stutter because of shaders.\nIt runs again after a system update or a reinstall. You can switch away and it continues when you come back.";
[NSLayoutConstraint activateConstraints:@[
[title.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [title.bottomAnchor constraintEqualToAnchor:bar.topAnchor constant:-22],
[bar.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [bar.centerYAnchor constraintEqualToAnchor:v.centerYAnchor], [bar.widthAnchor constraintEqualToAnchor:v.widthAnchor multiplier:0.5],
[sub.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [sub.topAnchor constraintEqualToAnchor:bar.bottomAnchor constant:14],
[note.centerXAnchor constraintEqualToAnchor:v.centerXAnchor], [note.topAnchor constraintEqualToAnchor:sub.bottomAnchor constant:22], [note.widthAnchor constraintLessThanOrEqualToAnchor:v.widthAnchor multiplier:0.8]]];
[host addSubview:v];
UIApplication.sharedApplication.idleTimerDisabled = YES; // 这几分钟别自动锁屏 | do not auto-lock the screen during these few minutes
int total = (int)src.count, threads = (int)MAX(2, MIN(6, (NSInteger)NSProcessInfo.processInfo.activeProcessorCount - 2));
const char *te = getenv("DM_SHADER_PREP_THREADS"); if (te && atoi(te) > 0) threads = atoi(te); // 测试开关:指定并行数 | test switch: set the degree of parallelism
pl([NSString stringWithFormat:@"着色器准备:开始,共 %d 个,%d 线程", total, threads]);
CFAbsoluteTime t0 = CFAbsoluteTimeGetCurrent(); __block _Atomic int fin = 0, bad = 0;
void (^tick)(void) = ^{ int n = atomic_load(&fin); double el = CFAbsoluteTimeGetCurrent() - t0, left = n > 20 ? el / n * (total - n) : -1;
bar.progress = (float)n / total;
NSString *eta = left < 0 ? (zh() ? @"正在估算剩余时间" : @"estimating time left") : left >= 90 ? [NSString stringWithFormat:zh() ? @"预计还要 %.0f 分钟" : @"about %.0f min left", ceil(left / 60)] : [NSString stringWithFormat:zh() ? @"预计还要 %.0f 秒" : @"about %.0f s left", ceil(left / 5) * 5];
sub.text = [NSString stringWithFormat:@"%d / %d · %@", n, total, eta]; };
tick();
NSTimer *tm = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer *t) { tick(); }];
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
id<MTLDevice> dev = MTLCreateSystemDefaultDevice(); dispatch_semaphore_t sem = dispatch_semaphore_create(threads); dispatch_group_t g = dispatch_group_create();
for (NSString *p in src) { dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_group_async(g, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ @autoreleasepool {
NSString *txt = [NSString stringWithContentsOfFile:p encoding:NSUTF8StringEncoding error:nil]; NSError *e = nil;
id<MTLLibrary> l = txt ? [dev newLibraryWithSource:txt options:nil error:&e] : nil; // 与游戏里建库用的是同一个调用、同样的参数:缓存才对得上 | the same call with the same arguments as the game uses to build the library: only then does the cache match
if (!l && atomic_fetch_add(&bad, 1) < 5) pl([NSString stringWithFormat:@"【红】着色器准备:%@ 编不过:%@", p.lastPathComponent, e.localizedDescription ?: @"读不了"]);
int n = atomic_fetch_add(&fin, 1) + 1; if (n % 500 == 0) pl([NSString stringWithFormat:@"着色器准备:%d / %d,已用 %.0f 秒,温控档位 %ld", n, total, CFAbsoluteTimeGetCurrent() - t0, (long)NSProcessInfo.processInfo.thermalState]);
dispatch_semaphore_signal(sem); } }); }
dispatch_group_wait(g, DISPATCH_TIME_FOREVER);
double el = CFAbsoluteTimeGetCurrent() - t0; int nb = atomic_load(&bad);
pl([NSString stringWithFormat:@"着色器准备:完成 %d 个,编不过 %d 个,用时 %.1f 秒,%d 线程,结束时温控档位 %ld", total, nb, el, threads, (long)NSProcessInfo.processInfo.thermalState]);
if (!nb) [@"ok" writeToFile:mk atomically:YES encoding:NSUTF8StringEncoding error:nil]; // 有编不过的就不记完成:下次启动再来一遍(已编的很快) | if any failed to compile, do not record completion: run it again at the next launch (the already compiled ones are fast)
dispatch_async(dispatch_get_main_queue(), ^{ [tm invalidate]; [v removeFromSuperview]; UIApplication.sharedApplication.idleTimerDisabled = NO; done(); });
});
return 1;
}
#endif
+117
View File
@@ -0,0 +1,117 @@
// 暂停菜单「分享诊断日志」的 iOS 侧。
// 按钮是游戏自己的控件(布局 tools/touch_layout.py 的 _pause_no_help:借原版「消息记录」按钮,换字、改发 PanelManager:ClosePanel:TouchShareLog),
// 宿主收到这条空操作消息后调这里登记的回调(dm/host/diag.c)。这里做两件:
// ① 打一个文件:头部(构建号、机型、系统版本、温控 / 电量 / 内存 / 存储、本局与上一局的关键性能读数)+ 本局 boot.txt + 上一局 boot.previous.txt(main.m 每次启动前改名留下);
// ② 弹系统分享面板(UIActivityViewController),玩家自己选发到哪;iPad / Mac 上分享面板是弹出框,必须给锚点,否则一弹就崩。
// 隐私:只放这两份日志(游戏与宿主自己写的)和上面那几项机器读数;不取设备名、不取任何账号 / 位置 / 通讯录类信息。
// 测试开关 DM_TEST_SHARELOG_CLOSE=<秒>:分享面板照常弹出,过这么多秒自动收起;导出的文件另拷一份到 Documents/sharelog_test.txt 供回归核内容。
// iOS side of the pause menu's 「分享诊断日志」(Share Diagnostics).
// The button is the game's own widget (layout: _pause_no_help in tools/touch_layout.py: borrows the original game's 「消息记录」(Message Log) button, changes the text, and makes it send PanelManager:ClosePanel:TouchShareLog instead),
// and on receiving this no-op message the host calls the callback registered here (dm/host/diag.c). Two things are done here:
// ① Build one file: header (build number, device model, OS version, thermal / battery / memory / storage, key performance readings of this run and the previous run) + this run's boot.txt + the previous run's boot.previous.txt (left by main.m's rename before each launch);
// ② Present the system share sheet (UIActivityViewController), and the player chooses where to send it; on iPad / Mac the share sheet is a popover and must be given an anchor, otherwise it crashes as soon as it is presented.
// Privacy: only these two logs (written by the game and the host themselves) and the machine readings listed above are included; no device name, no account / location / contacts information of any kind.
// Test switch DM_TEST_SHARELOG_CLOSE=<seconds>: the share sheet is presented as usual and dismissed automatically after that many seconds; the exported file is also copied to Documents/sharelog_test.txt so regression can check its content.
#import <UIKit/UIKit.h>
#include <stdatomic.h>
#include <sys/sysctl.h>
#include <pwd.h>
#include <unistd.h>
#include "../../host/dm_i18n.h"
void plog(const char *fmt, ...);
void dm_sharelog_init(void (*cb)(void)); // dm/host/diag.c
// 日志里最后一条含 key 的行(不含行尾换行);没有返回 nil
// The last line in the log containing key (without the trailing newline); returns nil if none
static NSString *last_line(NSData *d, const char *key) {
if (!d.length) return nil;
NSData *k = [NSData dataWithBytes:key length:strlen(key)];
NSRange r = [d rangeOfData:k options:NSDataSearchBackwards range:NSMakeRange(0, d.length)]; if (r.location == NSNotFound) return nil;
const char *b = d.bytes; NSUInteger s = r.location, e = r.location;
while (s > 0 && b[s - 1] != '\n') s--;
while (e < d.length && b[e] != '\n') e++;
return [[NSString alloc] initWithBytes:b + s length:e - s encoding:NSUTF8StringEncoding] ?: @"(这一行不是合法 UTF-8)";
}
static void perf_block(NSMutableString *h, NSString *title, NSData *d) {
[h appendFormat:@"\n—— %@ ——\n", title];
if (!d) { [h appendString:@"(没有这份日志)\n"]; return; }
static const char *keys[] = { "boot: 版本", "[诊断]", "[perf]", "[nvn] 上屏", "温控档位" };
for (size_t i = 0; i < sizeof keys / sizeof *keys; i++) { NSString *l = last_line(d, keys[i]); [h appendFormat:@"%@\n", l ?: [NSString stringWithFormat:@"(没有「%@」行)", @(keys[i])]]; }
}
// 日志里的路径会带系统用户主目录(Mac 上是 /Users/<用户名>,iPhone 上是 /var/mobile):导出时一律换成 ~,不把用户名带出去
// Paths in the log carry the system user's home directory (/Users/<username> on Mac, /var/mobile on iPhone): on export always replace it with ~ so the username does not leak out
static NSData *scrub_home(NSData *d) {
struct passwd *pw = getpwuid(getuid()); const char *h = pw ? pw->pw_dir : NULL; size_t hn = h ? strlen(h) : 0;
if (!d || hn < 2) return d;
NSMutableData *o = [NSMutableData dataWithCapacity:d.length]; const uint8_t *b = d.bytes; size_t n = d.length, i = 0, from = 0;
while (i + hn <= n) { if (b[i] == (uint8_t)h[0] && !memcmp(b + i, h, hn)) { [o appendBytes:b + from length:i - from]; [o appendBytes:"~" length:1]; i += hn; from = i; } else i++; }
[o appendBytes:b + from length:n - from]; return o;
}
static NSDate *g_t0; // 本次启动时刻(dm_sharelog_boot) | Time of this launch (dm_sharelog_boot)
static NSURL *build_file(void) {
NSFileManager *fm = NSFileManager.defaultManager;
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSData *cur = [NSData dataWithContentsOfFile:[doc stringByAppendingPathComponent:@"boot.txt"]], *prev = [NSData dataWithContentsOfFile:[doc stringByAppendingPathComponent:@"boot.previous.txt"]];
NSDictionary *inf = NSBundle.mainBundle.infoDictionary; NSString *build = [inf[@"CFBundleVersion"] description] ?: @"未知";
NSDateFormatter *df = [NSDateFormatter new]; df.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZ";
char hw[64] = "未知"; size_t hn = sizeof hw; sysctlbyname("hw.machine", hw, &hn, NULL, 0);
UIDevice *dev = UIDevice.currentDevice; dev.batteryMonitoringEnabled = YES;
NSArray<NSString *> *bst = @[ @"未知", @"放电", @"充电中", @"已充满" ]; int bs = (int)dev.batteryState;
NSDictionary *fsa = [fm attributesOfFileSystemForPath:doc error:nil]; NSProcessInfo *pi = NSProcessInfo.processInfo;
NSMutableString *h = [NSMutableString string];
[h appendFormat:@"D2R Mobile Diagnostics\n导出时间 %@\n版本 %@ 构建 %@\n机型 %s 系统 %@\n", [df stringFromDate:NSDate.date], [inf[@"CFBundleShortVersionString"] description] ?: @"未知", build, hw, pi.operatingSystemVersionString];
[h appendFormat:@"温控档位 %ld 低电量模式 %@ 电量 %.0f%% %@\n", (long)pi.thermalState, pi.lowPowerModeEnabled ? @"开" : @"关", dev.batteryLevel < 0 ? -1.0 : dev.batteryLevel * 100, bs >= 0 && bs <= 3 ? bst[bs] : @"未知"]; // 中文一律走 %@:NSString 的 %s 不按 UTF-8 解 | Chinese always goes through %@: NSString's %s does not decode as UTF-8
[h appendFormat:@"物理内存 %.1f GB 可用存储 %.1f GB 本次已运行 %.0f 分钟\n", pi.physicalMemory / 1073741824.0, [fsa[NSFileSystemFreeSize] doubleValue] / 1073741824.0, -g_t0.timeIntervalSinceNow / 60];
perf_block(h, @"本局关键读数(各取最后一条)", cur);
perf_block(h, @"上一局关键读数(各取最后一条)", prev);
NSMutableData *out = [[h dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
void (^part)(NSString *, NSData *) = ^(NSString *t, NSData *d) {
[out appendData:[[NSString stringWithFormat:@"\n\n===== %@(%@)=====\n", t, d ? [NSString stringWithFormat:@"%lu 字节", (unsigned long)d.length] : @"没有这份日志"] dataUsingEncoding:NSUTF8StringEncoding]];
if (d) [out appendData:d]; };
part(@"本局日志 boot.txt", cur); part(@"上一局日志 boot.previous.txt", prev);
NSString *dir = [NSTemporaryDirectory() stringByAppendingPathComponent:@"sharelog"]; // 只放这一份导出:每次重建这个目录(我们自己的,不碰别的) | Hold only this one export: rebuild this directory every time (it is our own; nothing else is touched)
[fm removeItemAtPath:dir error:nil]; [fm createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
df.dateFormat = @"yyyyMMdd_HHmmss";
NSString *p = [dir stringByAppendingPathComponent:[NSString stringWithFormat:@(dm_ui("dmShareLogFile")), build, [df stringFromDate:NSDate.date]]];
out = [scrub_home(out) mutableCopy];
if (![out writeToFile:p atomically:YES]) { plog("诊断日志:【红】导出文件写不进 %s", p.UTF8String); return nil; }
plog("诊断日志:已打包 %s(%lu 字节:本局 %lu、上一局 %s)", p.lastPathComponent.UTF8String, (unsigned long)out.length, (unsigned long)cur.length,
prev ? [NSString stringWithFormat:@"%lu", (unsigned long)prev.length].UTF8String : "没有");
if (getenv("DM_TEST_SHARELOG_CLOSE")) [out writeToFile:[doc stringByAppendingPathComponent:@"sharelog_test.txt"] atomically:YES];
return [NSURL fileURLWithPath:p];
}
static UIViewController *top_vc(void) { // 同 front_ios.m 系统输入框找宿主的顺序:主窗口 → 前台活跃场景的窗口 → 任一窗口,再顺着已弹出的往上找 | Same order as front_ios.m's system input box uses to find its host: main window → a window of the foreground active scene → any window, then walk up through what is already presented
UIViewController *vc = nil, *alt = nil, *any = nil;
for (UIScene *s in UIApplication.sharedApplication.connectedScenes)
if ([s isKindOfClass:UIWindowScene.class]) for (UIWindow *w in ((UIWindowScene *)s).windows) {
if (!w.rootViewController) continue;
if (w.isKeyWindow) vc = w.rootViewController;
else if (s.activationState == UISceneActivationStateForegroundActive && !alt) alt = w.rootViewController;
else if (!any) any = w.rootViewController; }
vc = vc ?: alt ?: any; while (vc.presentedViewController) vc = vc.presentedViewController;
return vc;
}
static _Atomic int g_busy; // 打包 / 分享面板开着时再点不叠第二个 | Tapping again while packaging / the share sheet is open does not stack a second one
static void on_click(void) { // 宿主在游戏主线程调:玩家点了「分享诊断日志」 | Called by the host on the game main thread: the player tapped 「分享诊断日志」(Share Diagnostics)
if (atomic_exchange(&g_busy, 1)) { plog("诊断日志:分享面板还开着,这次点击不再弹"); return; }
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
NSURL *u = build_file();
dispatch_async(dispatch_get_main_queue(), ^{
UIViewController *vc = u ? top_vc() : nil;
if (!vc) { if (u) plog("诊断日志:【红】没找到可弹分享面板的界面"); atomic_store(&g_busy, 0); return; }
UIActivityViewController *a = [[UIActivityViewController alloc] initWithActivityItems:@[u] applicationActivities:nil];
a.completionWithItemsHandler = ^(UIActivityType t, BOOL done, NSArray *items, NSError *e) { (void)items;
plog("诊断日志:分享面板收起(%s%s%s)", done ? "已发到 " : "没发", done ? (t ?: @"未知").UTF8String : "", e ? [NSString stringWithFormat:@",错误 %@", e.localizedDescription].UTF8String : "");
atomic_store(&g_busy, 0); };
UIPopoverPresentationController *pp = a.popoverPresentationController; // iPad / Mac 上是弹出框:锚在画面正中(暂停菜单所在处),不画箭头 | On iPad / Mac it is a popover: anchored at the center of the picture (where the pause menu is), no arrow drawn
if (pp) { pp.sourceView = vc.view; pp.sourceRect = CGRectMake(CGRectGetMidX(vc.view.bounds), CGRectGetMidY(vc.view.bounds), 1, 1); pp.permittedArrowDirections = 0; }
[vc presentViewController:a animated:YES completion:^{
plog("诊断日志:分享面板已弹出(%s,%s)", pp ? "弹出框" : "底部面板", NSStringFromCGRect(a.view.frame).UTF8String);
const char *tc = getenv("DM_TEST_SHARELOG_CLOSE"); if (!tc) return;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(tc) * 1e9)), dispatch_get_main_queue(), ^{
[a dismissViewControllerAnimated:NO completion:^{ plog("诊断日志:测试开关 DM_TEST_SHARELOG_CLOSE 到点收起分享面板"); atomic_store(&g_busy, 0); }]; });
}];
});
});
}
void dm_sharelog_boot(void) { g_t0 = NSDate.date; dm_sharelog_init(on_click); } // main.m 起宿主前调一次 | main.m calls this once before starting the host
+698
View File
@@ -0,0 +1,698 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <math.h>
#include <string.h>
#include <stdatomic.h>
#define DM_TC_POINTER_MOVE_PT 10.0f
#define DM_TC_POINTER_HOLD_S 0.5
#define DM_TC_POINTER_TAP_S 0.35
/* 控件缩放。手机(画面高 ≤ 440 点,最大的 iPhone 横屏就是 440):min(1, 宽/667, 高/375),与原来一字不差。
比手机高的画面(iPad 上居中的 16:9 那块,13 寸是 1366×768 点):按画面高度等比放大(高/440),否则摇杆与技能钮还是手机的点数大小,
在大画面里只剩一小簇(Mac 上按 iPad 尺寸出图所见),而底栏与游戏界面都是按画面高度缩放的。
这条放大只在前端显式打开时生效(dm_tc_set_tall_scale,front_ios.m 建视图时开):Mac 宿主的触屏用例通路(dm/host/touch_mac.c)是把像素数
(2868×1320)当点数传进来的,13 个用例的坐标按「缩放 = 1」写;不加这道开关,1320 > 440 会把它们的控件放大 3 倍、主钮挪位(skill_main 红)。
Widget scale. Phone (picture height ≤ 440 points; the largest iPhone in landscape is exactly 440): min(1, width/667, height/375), identical to before to the letter.
Pictures taller than the phone's (the centered 16:9 block on iPad; 13-inch is 1366×768 points): scale up proportionally by picture height (height/440), otherwise the stick and skill buttons keep the phone's point size
and are just a small cluster in the large picture (as seen when rendering at iPad size on Mac), while the bottom bar and the game UI both scale by picture height.
This enlargement takes effect only when the front end turns it on explicitly (dm_tc_set_tall_scale, turned on when front_ios.m creates the view): the Mac host's touch test-case path (dm/host/touch_mac.c) passes pixel counts
(2868×1320) in as points, and the coordinates of the 13 test cases are written for "scale = 1"; without this switch, 1320 > 440 would enlarge their widgets 3x and move the main button (skill_main red). */
static int g_tall_scale;
void dm_tc_set_tall_scale(int on) { g_tall_scale = !!on; }
float dm_tc_scale_for_size(float width, float height) { float k = fminf(1.0f, fminf(width / 667.0f, height / 375.0f)); return g_tall_scale && k >= 1.0f && height > 440.0f ? height / 440.0f : k; }
static float scale_for(const dm_tc_layout *l) { return dm_tc_scale_for_size(l->width, l->height); }
/* 安全区(iPhone 横屏左右各有一条让给灵动岛 / 圆角的区域,17 Pro Max 实读各 62 点):右侧技能键整组、左侧摇杆按最小位移平移到全部落在安全区内,
组内相对排布不变。岛在哪一侧取决于玩家怎么拿,两侧都内缩。缺省 0(Mac 宿主、单测不设 = 原布局)。
Safe area (in iPhone landscape there is a strip on each of the left and right yielded to the Dynamic Island / rounded corners; read as 62 points each on a 17 Pro Max): the whole right-side skill key group and the left stick are translated by the minimum displacement so that they lie entirely inside the safe area,
with the relative arrangement within the group unchanged. Which side the island is on depends on how the player holds the device, so both sides are inset. Default 0 (Mac host and unit tests do not set it = original layout). */
static float g_safe_l, g_safe_r;
/* 屏幕底边归系统的那一条(点):从这里起手往上划会被系统当成底边手势(iPad 上连着两次就拉出程序坞),而移动恰好是同一处反复起手往上推。
这一条里起手不当摇杆、松手也不当点地;从上面起手的摇杆拖进来照常持有。只有 iPad 的前端会给非零值,手机恒为 0。
The strip along the bottom edge of the screen that belongs to the system (points): a swipe up starting here is taken by the system as a bottom-edge gesture (on iPad two in a row pull out the Dock), and movement is exactly a repeated push upward starting from the same place.
A touch starting in this strip is not treated as the stick, and its release is not treated as a ground tap; a stick drag that started above and moves in keeps its hold as usual. Only the iPad front end passes a non-zero value; on phones it is always 0. */
static float g_edge_b;
void dm_tc_set_edge_bottom(float bottom) { g_edge_b = isfinite(bottom) && bottom > 0 ? bottom : 0; }
void dm_tc_set_safe_insets(float left, float right) { g_safe_l = isfinite(left) && left > 0 ? left : 0; g_safe_r = isfinite(right) && right > 0 ? right : 0; }
void dm_tc_layout_make(dm_tc_layout *l, float width, float height) {
memset(l, 0, sizeof(*l));
l->width = isfinite(width) && width > 0 ? width : 0;
l->height = isfinite(height) && height > 0 ? height : 0;
float k = scale_for(l);
float main_x = l->width - 56 * k, main_y = l->height - 82 * k;
{ float over = main_x + 40*k - (l->width - g_safe_r); if (over > 0) main_x -= over; } /* 右侧一组里最靠右的是主技能键(半径 40) | The rightmost one in the right-side group is the main skill key (radius 40) */
l->target[DM_TC_MAIN] = (dm_tc_target){ main_x, main_y, 40*k, DM_BTN_A };
/* 四分之一弧的单位向量:180°、150°、120°、90°。 | Unit vectors of the quarter arc: 180°, 150°, 120°, 90°. */
const float dx[4] = {-1, -0.8660254038f, -0.5f, 0};
const float dy[4] = {0, -0.5f, -0.8660254038f, -1};
const uint64_t skill[4] = {DM_BTN_B, DM_BTN_X, DM_BTN_Y, DM_BTN_R};
for (int i = 0; i < 4; ++i)
l->target[DM_TC_SKILL1+i] = (dm_tc_target){main_x+112*k*dx[i], main_y+112*k*dy[i], 26*k, skill[i]};
/* 底栏 = 底部 UI v4 六格(NativeHUD/v4,游戏 HUD 按屏高缩放、以屏幕中线居中,所以按屏高换算):
效果图 2868×1320 里格心 x = 1090 + 120×格号、y = 1241.5、格宽 114;第 0 格难度,1–4 腰带四列,5 功能入口(PLUS)。
回城不在底栏(离药水太近易误触):改为技能弧最上面那颗(技能四)正上方的圆钮,同半径、间距 12,点下由宿主施放原版回城技能(dm_freetp.c),不出按键。
Bottom bar = the six cells of bottom UI v4 (NativeHUD/v4; the game HUD scales by screen height and is centered on the screen centerline, so convert by screen height):
in the 2868×1320 mock, cell center x = 1090 + 120×cell index, y = 1241.5, cell width 114; cell 0 difficulty, 1–4 the four belt columns, 5 the function entry (PLUS).
Town portal is not in the bottom bar (too close to the potions, easy to hit by mistake): it is instead a round button directly above the topmost one on the skill arc (skill four), same radius, gap 12; on tap the host casts the original game's town portal skill (dm_freetp.c), with no key press. */
/* 腰带四列对十字键:左 = 第 1 列、上 = 第 2 列、下 = 第 3 列、右 = 第 4 列(原版实测:按「右」第 4 列减、按「下」第 3 列减;首版把后两个写反了,真机才撞到) | The four belt columns map to the D-pad: left = column 1, up = column 2, down = column 3, right = column 4 (measured in the original game: pressing "right" decrements column 4, pressing "down" decrements column 3; the first version had the last two swapped, which was only hit on a real device) */
const uint64_t bottom[5] = {DM_BTN_LEFT, DM_BTN_UP, DM_BTN_DOWN, DM_BTN_RIGHT, DM_BTN_PLUS};
const int cell[5] = {1, 2, 3, 4, 5};
float u = l->height / 1320.0f;
for (int i = 0; i < 5; ++i)
l->target[DM_TC_BELT1+i] = (dm_tc_target){l->width/2+(1090+120*cell[i]-1434)*u, 1241.5f*u, 57*u, bottom[i]};
{ const dm_tc_target *s4 = &l->target[DM_TC_SKILL4]; l->target[DM_TC_PORTAL] = (dm_tc_target){s4->x, s4->y-s4->r-12*k-26*k, 26*k, 0}; }
/* 第 0 格难度与选择条:选择条 8 格同格宽、格距 120,中线对齐两球中线(效果图 1390),格心 y = 1051.5(七格之上、避开数值文字) | Cell 0 difficulty and the selector bar: the selector bar has 8 cells of the same cell width, cell pitch 120, centerline aligned with the centerline between the two orbs (mock 1390), cell center y = 1051.5 (above the seven cells, clear of the value text) */
l->diff = (dm_tc_target){l->width/2+(1090-1434)*u, 1241.5f*u, 57*u, 0};
for (int i = 0; i < 8; ++i) l->pick[i] = (dm_tc_target){l->width/2+(1390+(i-3.5f)*120-1434)*u, 1051.5f*u, 57*u, 0};
l->target[DM_TC_MAP] = (dm_tc_target){l->width-30*k, 30*k, 22*k, DM_BTN_MINUS};
/* 技能组切换:主技能左下、技能一下方,避开主技能与弧上四键 | Skill set switch: lower-left of the main skill, below skill one, clear of the main skill and the four keys on the arc */
/* 位置与大小:技能一正下方,半径 22(直径 44 点 ≈ 7.3 毫米);上沿离技能一下沿 4 点、下沿离屏幕底 10 点(956×440) | Position and size: directly below skill one, radius 22 (diameter 44 points ≈ 7.3 mm); top edge 4 points from the bottom edge of skill one, bottom edge 10 points from the bottom of the screen (956×440) */
/* 比手机窄的画面(16:9:iPad 留边 / 真全屏的游戏视图、667×375)底栏按屏高缩放、右端雕像翼尖(效果图 x 2075)会伸到换组键底下:
键向右让到离翼尖 8 点以外,大小不变(量:1366×768 下原位重叠 21 点;956×440 下本来就隔着 28 点,不动)
On pictures narrower than the phone's (16:9: iPad letterboxed / true full-screen game view, 667×375) the bottom bar scales by screen height and the right-end statue wing tip (mock x 2075) would extend under the set-switch key:
the key moves right to at least 8 points away from the wing tip, size unchanged (measured: at 1366×768 the original position overlaps by 21 points; at 956×440 it is already 28 points apart and is not moved) */
{ float sx = main_x-112*k, bar_r = l->width/2+(2015-1434)*u+8*k+22*k; /* 右雕像翼尖:七格时 2075,六格石条右端收进 60 | Right statue wing tip: 2075 with seven cells; with six cells the right end of the stone bar is pulled in by 60 */ if (sx < bar_r) sx = bar_r;
l->swap = (dm_tc_target){sx, main_y+52*k, 22*k, 0}; }
/* 底栏外侧是血 / 蓝球;球不是输入目标。 | Outside the bottom bar are the life / mana orbs; the orbs are not input targets. */
l->joy_x = fmaxf(90*k, g_safe_l + 60*k); /* 摇杆底盘(半径 60)左沿不越过安全区左界 | The left edge of the stick base (radius 60) does not cross the left boundary of the safe area */
l->joy_y = l->height - 100*k;
l->joy_radius = 60*k;
}
int dm_tc_hit(const dm_tc_layout *l, float x, float y) {
if (!isfinite(x) || !isfinite(y) || x < 0 || y < 0 || x > l->width || y > l->height)
return DM_TC_NONE;
for (int i = 0; i < DM_TC_COUNT; ++i) {
const dm_tc_target *t = &l->target[i];
float dx = x-t->x, dy = y-t->y;
if (t->r > 0 && dx*dx+dy*dy <= t->r*t->r) return i;
}
float sx = x-l->swap.x, sy = y-l->swap.y;
if (l->swap.r > 0 && sx*sx+sy*sy <= l->swap.r*l->swap.r) return DM_TC_SWAP;
return DM_TC_NONE;
}
static int skill_target(int target) {
return target >= DM_TC_MAIN && target <= DM_TC_SKILL4;
}
/* 拖动方向(单位向量,屏幕坐标):拖动不过 10 点死区 = 没有方向 | Drag direction (unit vector, screen coordinates): a drag that does not pass the 10-point dead zone = no direction */
static int aim_dir(const dm_tc_state *s, const dm_tc_finger *f, float *ux, float *uy) {
float dx = f->x-f->aim_origin_x, dy = f->y-f->aim_origin_y, d = hypotf(dx, dy);
if (!(d > 10 * scale_for(&s->layout))) return 0;
*ux = dx/d; *uy = dy/d; return 1;
}
static int inside_map_cancel(const dm_tc_state *s, const dm_tc_finger *f) {
const dm_tc_target *map = &s->layout.target[DM_TC_MAP];
return map->r > 0 && fabsf(f->x-map->x) <= map->r && fabsf(f->y-map->y) <= map->r;
}
static int g_iso_fix = 1;
void dm_tc_set_iso_fix(int on) { g_iso_fix = !!on; }
static void update_aim(dm_tc_state *s) {
s->rx = s->ry = 0;
s->aim_slot = DM_TC_NONE;
s->map_cancel_active = 0;
if (s->navigation_mode) return;
uint64_t latest = 0;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
const dm_tc_finger *f = &s->finger[i];
if (!f->active || !skill_target(f->target)) continue;
if (inside_map_cancel(s, f)) s->map_cancel_active = 1;
if (!f->aim_cancelled && f->aim_move_sequence > latest) {
latest = f->aim_move_sequence;
s->aim_slot = i;
}
}
if (s->pulse_button) { s->rx = s->pulse_rx; s->ry = s->pulse_ry; return; }
float radius = 60 * scale_for(&s->layout);
if (s->aim_slot == DM_TC_NONE || radius <= 0) return;
const dm_tc_finger *f = &s->finger[s->aim_slot];
if (f->target != DM_TC_MAIN && hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y) <= 10 * scale_for(&s->layout)) return; /* 技能钮:拖动不过 10 点 = 点按,不给方向,原版自动选目标 | Skill button: a drag of no more than 10 points = tap, no direction given, the original game auto-targets */
float dx = (f->x-f->aim_origin_x)/radius;
float dy = (f->aim_origin_y-f->y)/radius;
s->rx = (int32_t)lroundf(fmaxf(-1, fminf(1, dx))*DM_STICK_MAX);
s->ry = (int32_t)lroundf(fmaxf(-1, fminf(1, dy))*DM_STICK_MAX);
}
static void update(dm_tc_state *s) {
s->buttons = 0;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
dm_tc_finger *f = &s->finger[i];
if (f->active && !f->aim_cancelled && f->target >= 0 && f->target < DM_TC_COUNT) {
uint64_t b = f->target==DM_TC_PORTAL && s->portal_pending ? DM_BTN_ZL : s->layout.target[f->target].button;
/* 拖动定方向(核心手势)。技能钮:按下后先等 DM_TC_AIM_SETTLE_S 看是点按还是拖动——拖过死区就带着右轴方向立刻键下,
没拖到点也键下(点按 = 原版自动选目标 / 朝向);否则键先下、右轴后偏,按下那一发朝的是旧朝向。
主钮:按下即键下,不等(它是最高频的键,点按不该多等;按下就拖的第一发是原生朝向,第二发起跟手)。
按住期间方向再变由宿主的瞄准适配每拍重取,这里不做「松—按」;判定时间不为「按下稍停再拖」加长。
Drag to set direction (the core gesture). Skill button: after press, first wait DM_TC_AIM_SETTLE_S to see whether it is a tap or a drag -- once dragged past the dead zone, key down immediately with the right-axis direction,
and key down too if the time is reached without dragging (tap = the original game's auto target / facing); otherwise the key would go down first and the right axis deflect later, and the shot at press would aim at the old facing.
Main button: key down on press, no wait (it is the most frequent key and a tap should not wait longer; with press-then-drag the first shot uses the native facing, and from the second shot on it follows the finger).
Direction changes while held are re-read every tick by the host's aim adapter, so no "release-press" is done here; the decision time is not lengthened for "press, pause, then drag". */
if (!s->navigation_mode && f->target >= DM_TC_SKILL1 && f->target <= DM_TC_SKILL4) {
float ux, uy;
if (!f->key_down && !aim_dir(s, f, &ux, &uy) && s->last_time_s - f->start_time_s < DM_TC_AIM_SETTLE_S) b = 0;
else if (!f->key_down) { f->key_down = 1; f->key_down_s = s->last_time_s; }
}
/* 多排腰带:腰带格上滑 = 展开、下滑 = 收起,所以键不在按下时发;一律等松手那一刻按位移判(dm_tc_end_at)。不设「按住到点就喝」的计时:
手慢一点的上滑 / 下滑会先被它判成喝药(真机与 mini 各撞一次)。只有 1 排时照旧按下即喝
Multi-row belt: swiping up on a belt cell = expand, swiping down = collapse, so the key is not sent on press; always wait for the moment of release and decide by displacement (dm_tc_end_at). No "drink once held long enough" timer:
a slightly slow swipe up / down would first be judged by it as drinking a potion (hit once each on a real device and on the second Mac). With only 1 row, still drink on press as before */
/* 只有 1 排时也一律松手那一刻喝(和多排同一条路) | with only 1 row, also always drink at the moment of release (same path as multiple rows) */
if (!s->navigation_mode && f->target >= DM_TC_BELT1 && f->target <= DM_TC_BELT4) b = 0;
s->buttons |= b;
}
}
s->buttons |= s->pulse_button;
/* 第二套技能:ZL 是原版的换组修饰键。只在用技能的那一刻带上——手指按着主钮 / 技能钮、或技能脉冲在发(含等着发)时;
其余时候不按:一直按着会让十字(+)、腰带、回城都变成「ZL + 键」的组合(Ⅱ 态下十字开不了面板)。
ZL 先下、主钮的键晚 DM_TC_ZL_LEAD_S 再下(同一帧按下游戏只认主键 = 放成第一组的技能)。
Second skill set: ZL is the original game's set-switch modifier. It is added only at the moment a skill is used -- while a finger is on the main button / a skill button, or a skill pulse is being sent (including waiting to be sent);
it is not pressed the rest of the time: holding it all the time would turn the cross (+), the belt and town portal all into "ZL + key" combos (in state Ⅱ the cross could not open the panel).
ZL goes down first, and the main button's key goes down DM_TC_ZL_LEAD_S later (pressed in the same frame, the game only recognizes the main key = casts the first set's skill). */
if (s->skill_set && !s->navigation_mode) {
/* 在发的脉冲只有是技能键(主钮 / 技能钮补的那一下)才带 ZL:多排腰带松手补的喝药脉冲带上 ZL 就成了原版「ZL + 腰带键 = 喂佣兵」
(本机 实跑:第二组下点腰带,0x26 包目标字节 = 1、佣兵生命 642 → 762 涨、玩家不变)
The pulse being sent carries ZL only if it is a skill button (the make-up press of the main button / a skill button): a drink pulse made up on release of a multi-row belt, if it carried ZL, would become the original game's "ZL + belt key = feed the mercenary"
(actual run on the local machine: tapping the belt under the second set, 0x26 packet target byte = 1, mercenary life rose 642 → 762, player unchanged) */
/* 等着补发的技能也要 ZL 领先——但只在没有别的脉冲在发时:腰带脉冲在发时带上 ZL 同样成了「喂佣兵」(单测探针读到 0x1100) | A skill waiting for a make-up send also needs ZL to lead -- but only when no other pulse is being sent: adding ZL while a belt pulse is being sent likewise becomes "feed the mercenary" (the unit-test probe read 0x1100) */
int use = s->defer_button != 0 && !s->pulse_button;
for (int t = DM_TC_MAIN; t <= DM_TC_SKILL4 && !use; ++t) if (s->pulse_button && s->pulse_button == s->layout.target[t].button) use = 1;
/* 手指按着第二组技能时发「给玩家喝」的腰带脉冲:ZL 还按着就成了原版「ZL + 腰带键 = 喂佣兵」。ZL 和按着的技能键要一起让开
(只松 ZL 不松技能键 = 放成第一组的技能),而且要先让开、隔一段再按腰带键:同一拍里「松 ZL + 按腰带键」游戏仍按 ZL 还在算
(真局实测:发出的还是喂佣兵包——宿主取手柄处对按下沿做锁存,这一拍采到的是 ZL 与腰带键都在)。所以分三段:
等着发(belt_gap_cell)→ 脉冲在发 → 收回后 ZL 先回来、领先满 DM_TC_ZL_LEAD_S 技能键再回来(同一帧按下游戏只认主键)
The "drink for the player" belt pulse sent while a finger holds a skill of the second skill set: with ZL still held it becomes the original game's "ZL + belt key = feed the mercenary". ZL and the held skill key have to get out of the way together
(releasing only ZL and not the skill key = casting the first set's skill), and they have to get out of the way first, with the belt key pressed after a gap: with "release ZL + press belt key" in the same tick the game still counts ZL as held
(measured in a real run: what went out was still the feed-the-mercenary packet -- where the host fetches the controller it latches the press edge, and what was sampled this tick was both ZL and the belt key down). So there are three stages:
waiting to send (belt_gap_cell) → the pulse is being sent → after it is withdrawn ZL comes back first, and the skill key comes back once ZL has led by a full DM_TC_ZL_LEAD_S (pressed in the same frame, the game only recognizes the main key) */
int belt_pulse = s->belt_gap_cell != 0;
for (int t = DM_TC_BELT1; t <= DM_TC_BELT4; ++t) if (s->pulse_button && s->pulse_button == s->layout.target[t].button) belt_pulse = 1;
if (belt_pulse) s->belt_pulse_s = s->last_time_s;
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) {
const dm_tc_finger *f = &s->finger[i];
if (!f->active || f->aim_cancelled || f->target < DM_TC_MAIN || f->target > DM_TC_SKILL4) continue;
if (!belt_pulse) use = 1;
if (belt_pulse || s->last_time_s - f->start_time_s < DM_TC_ZL_LEAD_S || (s->belt_pulse_s > 0 && s->last_time_s - s->belt_pulse_s < DM_TC_ZL_LEAD_S)) s->buttons &= ~s->layout.target[f->target].button;
}
if (use) s->buttons |= DM_BTN_ZL;
}
update_aim(s);
s->lx = s->ly = 0;
if (s->joy_slot < 0) return;
dm_tc_finger *f = &s->finger[s->joy_slot];
float dx = f->x-s->joy_origin_x, dy = s->joy_origin_y-f->y;
/* 输入行程不跟大屏的视觉放大走:拇指不随屏幕变大。满偏 60 点、死区 6 点,手机与 iPad 一致
(原先乘视觉倍数,12.9 寸 iPad 要推 105 点 ≈ 20 mm 才满偏,是手机的两倍)。底盘和摇杆头的大小仍按视觉倍数画。
Input travel does not follow the visual enlargement on large screens: the thumb does not grow with the screen. Full deflection 60 points, dead zone 6 points, same on phone and iPad
(it used to be multiplied by the visual factor, so a 12.9-inch iPad needed a 105-point ≈ 20 mm push for full deflection, twice the phone's). The size of the base and the stick head is still drawn by the visual factor. */
float in_k = fminf(1.0f, scale_for(&s->layout));
float distance = hypotf(dx, dy), radius = 60 * in_k;
float dead = 6 * in_k;
if (distance <= dead || radius <= dead) return;
float strength = fminf(1, (distance-dead)/(radius-dead));
/* 斜向预修正:原版把摇杆做纯 45° 旋转成世界方向、不补偿等距画面的 2:1,人实际走的屏幕角 = atan(tan(摇杆角) / 2)(推 45° 走 26.6°)。
手柄玩家看不见摇杆和画面的对应,触屏上手指画的就是屏幕方向,所以送值前把纵向放大 2 倍再缩回原幅度:屏幕角 = 手指角,推多深不变。
只动游戏态的移动摇杆(导航态没有摇杆值;技能方向走右轴,不经这里)
Diagonal pre-correction: the original game turns the stick into a world direction by a pure 45° rotation and does not compensate for the 2:1 of the isometric view, so the screen angle the character actually walks = atan(tan(stick angle) / 2) (push 45°, walk 26.6°).
Controller players do not see the mapping between stick and picture, but on a touchscreen what the finger draws is the screen direction, so before sending the value the vertical component is doubled and then scaled back to the original magnitude: screen angle = finger angle, push depth unchanged.
Only the movement stick in game state is affected (navigation state has no stick value; skill direction goes through the right axis and does not pass here) */
float ex = dx/distance, ey = dy/distance;
if (g_iso_fix) { float n = hypotf(ex, 2*ey); ex /= n; ey = 2*ey/n; }
s->lx = (int32_t)lroundf(ex * strength * DM_STICK_MAX);
s->ly = (int32_t)lroundf(ey * strength * DM_STICK_MAX);
}
static int pointer_finger(const dm_tc_state *s, const dm_tc_finger *f) {
return s->navigation_mode && f->active && s->pointer_slot >= 0 &&
&s->finger[s->pointer_slot] == f;
}
static void update_pointer(dm_tc_state *s) {
if (!s->pointer_valid || s->pointer_slot < 0 || s->pointer_slot >= DM_TC_MAX_TOUCH) return;
dm_tc_finger *f = &s->finger[s->pointer_slot];
if (f->pointer_dragged && s->pointer_pickup_done && !f->shop_drag && !f->locked_drag) {
s->pointer_x = f->x;
s->pointer_y = f->y - DM_TC_POINTER_LIFT_PT * scale_for(&s->layout);
}
}
/* 指针脉冲(kind 1 = 拖放的拿起,2 = 放下 / 点按):指针先落到 (x,y) 再按 A。上一个脉冲还没收(游戏还没取走)时不动指针、只记下,
等前端在上一个收回且游戏已看到一次「A 松开」之后调 dm_tc_pulse_resume 才开始——否则两下 A 连成一下、或拿起落在放下的位置
Pointer pulse (kind 1 = pick-up of a drag-and-drop, 2 = put-down / tap): the pointer first lands at (x,y), then A is pressed. While the previous pulse has not been released (the game has not consumed it yet) the pointer is not moved and the request is only recorded,
and it starts only when the front end calls dm_tc_pulse_resume, after the previous one is released and the game has seen "A released" once -- otherwise two A presses merge into one, or the pick-up lands at the put-down position */
static void pointer_pulse_btn(dm_tc_state *s, float x, float y, int kind, uint64_t button, double hold_s) {
if (!s->pulse_button) {
s->pointer_x = x; s->pointer_y = y;
s->pulse_button = button;
s->pulse_hold_s = hold_s;
s->pulse_rx = s->pulse_ry = 0;
s->pointer_pulse_active = kind;
++s->pulse_epoch;
} else {
s->pointer_pulse_pending = kind;
s->pointer_pending_x = x;
s->pointer_pending_y = y;
s->pointer_pending_button = button; s->pointer_pending_hold = hold_s;
}
}
static void pointer_pulse_start(dm_tc_state *s, float x, float y, int kind) { pointer_pulse_btn(s, x, y, kind, DM_BTN_A, 0); }
void dm_tc_pointer_release(dm_tc_state *s, int kind) { s->pointer_release_item = kind == 1 || kind == 3 || kind == 4 || kind == 8 ? kind : 0; }
void dm_tc_pointer_release_at(dm_tc_state *s, float x, float y) { s->pointer_release_item = 5; s->release_x = x; s->release_y = y; }
void dm_tc_set_holding(dm_tc_state *s, int holding) { s->holding = !!holding; }
void dm_tc_pointer_item(dm_tc_state *s, int kind) {
if (kind == 7) { s->pointer_shop = 1; kind = 1; }
s->pointer_lock = kind == 10; if (kind == 10) kind = 1;
s->pointer_stack = kind == 8; if (kind == 8) kind = 1; /* 8 = 高级仓库的成叠格:照物品区,只有双击不同 | 8 = stacked cell of the advanced stash: follows the item area, only double tap differs */ /* 7 = 商人货架上的货:别的都照物品区,只有起拖不同 | 7 = goods on the vendor shelf: everything else follows the item area, only drag start differs */
s->pointer_item = (kind >= 1 && kind <= 3) || kind == 6 || kind == 11 ? kind : 0; /* 11 = 这一下不点(底下是被盖住的按钮),但可以起滚动手势(设置页列表里的文字 / 空处) | 11 = this tap does not click (a covered button is underneath), but it may start a scroll gesture (text / empty space in the settings page list) */
if (s->mouse_click_mode && s->pointer_slot >= 0 && s->pointer_slot < DM_TC_MAX_TOUCH && s->finger[s->pointer_slot].active && !s->finger[s->pointer_slot].pointer_dragged) {
if (kind == 1) { if (!s->pulse_button) { s->pointer_valid = 1; s->pointer_x = s->finger[s->pointer_slot].aim_origin_x; s->pointer_y = s->finger[s->pointer_slot].aim_origin_y; } }
else s->pointer_valid = 0; /* 不在物品区:放开手柄光标(前端据此清掉光标请求,不再推摇杆) | Not in the item area: release the controller cursor (based on this the front end clears the cursor request and stops pushing the stick) */
}
} /* 1 物品区 2 页签(点按不发键也不发鼠标,前端另调宿主切页) | 1 item area, 2 tab (a tap sends neither a key nor a mouse click; the front end separately calls the host to switch pages) */
static _Atomic int g_dead_modal;
static _Atomic int g_vendor_open; /* 商人交易页开着:ZL 是切货架页签,「再点同一处 = 比较」不发 | Vendor trade page open: ZL switches shelf tabs, so "tap the same spot again = compare" is not sent */
static _Atomic int g_close_stop; /* 「面板外点按 = 按返回到面板关掉」途中弹出了确认框(名字以 Modal 结尾的面板打开):后面的返回键不再按 | A confirmation box popped up (a panel whose name ends in Modal opened) in the middle of "tap outside the panel = press back until the panel closes": stop pressing the remaining back presses */
static _Atomic int g_tap_box; /* 最近一次单击的物品是魔盒(前端每拍从宿主同步) | The most recently single-tapped item is the cube (synced by the front end from the host every tick) */
void dm_tc_set_tap_box(int on) { atomic_store(&g_tap_box, on != 0); }
static _Atomic unsigned g_cur_stack;
void dm_tc_set_cur_stack(unsigned id) { atomic_store(&g_cur_stack, id); }
static _Atomic unsigned g_hover_unid;
void dm_tc_set_hover_unid(unsigned id) { atomic_store(&g_hover_unid, id); }
static _Atomic int g_imbue_open; /* 单件任务槽面板开着(灌魔 / 打孔 / 个性化 / 古墓底座,同一个 ImbueItemsPanel) | Single-item quest slot panel open (imbue / socket / personalize / tomb pedestal, all the same ImbueItemsPanel) */
static _Atomic int g_cube_open; /* 赫拉迪克方块页开着:双击 = 按住 Y(原版「移到另一侧」:背包 → 方块 / 方块 → 背包),不是「使用 / 装备」 | Horadric Cube page open: double tap = hold Y (the original game's "move to the other side": inventory → cube / cube → inventory), not "use / equip" */
static _Atomic int g_vault_open; /* 储藏箱开在第六页「编年史」:双击背包物品 = 存进编年史仓库(走 use_seq,宿主 ui_use_pump 判页),不发原版「按住 Y」——那一页游戏当魔盒页 | Stash open on page six 「编年史」(Chronicle): double-tapping an inventory item = store it in the Chronicle vault (goes through use_seq; the host's ui_use_pump determines the page); do not send the original game's "hold Y" -- the game treats that page as the cube page */
static _Atomic int g_bank_open; /* 储藏箱开着(前端从宿主读游戏面板树的结果设进来,不靠开关消息):双击 = 按住 Y(移到另一侧) | Stash open (set by the front end from the host's reading of the game panel tree, not from open/close messages): double tap = hold Y (move to the other side) */
void dm_tc_set_panel_state(int bits) { atomic_store(&g_bank_open, (bits & 1) != 0); atomic_store(&g_vendor_open, (bits & 2) != 0); atomic_store(&g_dead_modal, (bits & 4) != 0); atomic_store(&g_imbue_open, (bits & 16) != 0); atomic_store(&g_cube_open, (bits & 32) != 0); atomic_store(&g_vault_open, (bits & 64) != 0); } /* 位同 dm_cursor.h 的 DM_PS_*;宿主读游戏状态得来 | Bits are the same as DM_PS_* in dm_cursor.h; obtained by the host reading the game state */
static void pointer_drag_begin(dm_tc_state *s, dm_tc_finger *f) {
f->pointer_dragged = 1;
if (s->pointer_lock) { f->locked_drag = 1; return; } /* 单件槽占用时从别的物品上起拖:不拿起,这次拖动什么都不做 | Drag starting from another item while the single-item slot is occupied: do not pick up; this drag does nothing */
if (s->pointer_shop || s->pointer_stack) { f->shop_drag = 1; s->pointer_x = 2; s->pointer_y = 2; update(s); return; } /* 从货架上的货起拖:不拿起;光标挪到屏幕角上,让货上的说明框收掉(买的时候宿主再把光标放回这件货上) | Drag starting from goods on the shelf: do not pick up; move the cursor to a screen corner so the tooltip on the goods closes (at purchase time the host puts the cursor back on that item) */
s->pointer_pickup_done = 0;
pointer_pulse_start(s, f->aim_origin_x, f->aim_origin_y, 1);
}
void dm_tc_cancel_all(dm_tc_state *s) {
++s->gesture_epoch; s->portal_pending=s->portal_phase=0; s->diff_open=0;
memset(s->finger, 0, sizeof(s->finger));
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) s->finger[i].target = DM_TC_NONE;
s->joy_slot = DM_TC_NONE;
s->joy_origin_x = s->joy_origin_y = 0;
s->buttons = 0;
s->lx = s->ly = s->rx = s->ry = 0;
s->aim_slot = DM_TC_NONE;
s->aim_move_sequence = 0;
s->map_cancel_active = 0;
s->pulse_button = 0; s->pulse_rx = s->pulse_ry = 0;
s->belt_q = 0; s->belt_gap_cell = 0; /* 排着的、等着发的喝药一起作废 | queued and pending drinks are voided as well */ /* 等着判单双击的腰带格、等着发的喂雇佣兵一起作废 | The belt cell waiting for single/double tap decision and the pending mercenary feed are voided together */
s->defer_button = 0; /* 等着补发的那下技能也作废:原先取消后 0.2 秒照样放出来 | The skill press waiting for a make-up send is voided as well: previously it was still cast 0.2 seconds after the cancel */
s->pointer_slot = DM_TC_NONE;
s->pointer_valid = 0; s->pointer_x = s->pointer_y = 0;
s->pointer_pickup_done = 0;
s->pointer_pulse_active = s->pointer_pulse_pending = 0;
s->pointer_pending_x = s->pointer_pending_y = 0;
}
int dm_tc_pulse_end(dm_tc_state *s, uint64_t epoch) {
if (!s->pulse_button || s->pulse_epoch != epoch) return 0;
int ended_pointer = s->pointer_pulse_active;
if (s->defer_button && s->defer_at_s < s->last_time_s + DM_TC_ZL_LEAD_S) s->defer_at_s = s->last_time_s + DM_TC_ZL_LEAD_S; /* 等着补发的技能:从这一刻起 ZL 才能领先(见 dm_tc_tick) | Skill waiting for a make-up send: ZL can start leading only from this moment (see dm_tc_tick) */
s->pulse_button = 0; s->pulse_rx = s->pulse_ry = 0; s->pulse_hold_s = 0;
s->pointer_pulse_active = 0;
if (ended_pointer == 1) {
s->pointer_pickup_done = 1;
update_pointer(s);
}
update(s);
return 1;
}
int dm_tc_pulse_pending(const dm_tc_state *s) { return !s->pulse_button && s->pointer_pulse_pending; }
int dm_tc_pulse_resume(dm_tc_state *s) {
if (s->pulse_button || !s->pointer_pulse_pending) return 0;
int kind = s->pointer_pulse_pending;
s->pointer_pulse_pending = 0;
pointer_pulse_btn(s, s->pointer_pending_x, s->pointer_pending_y, kind, s->pointer_pending_button ? s->pointer_pending_button : DM_BTN_A, s->pointer_pending_hold);
s->pointer_pending_button = 0; s->pointer_pending_hold = 0;
update(s);
return 1;
}
void dm_tc_init(dm_tc_state *s, float width, float height) {
memset(s, 0, sizeof(*s));
s->pointer_release_item = 1;
dm_tc_layout_make(&s->layout, width, height);
s->enabled_targets = (1u << DM_TC_COUNT) - 1;
dm_tc_cancel_all(s);
}
void dm_tc_resize(dm_tc_state *s, float width, float height) {
uint64_t portal = s->layout.target[DM_TC_PORTAL].button;
dm_tc_cancel_all(s);
dm_tc_layout_make(&s->layout, width, height);
s->layout.target[DM_TC_PORTAL].button = portal;
}
void dm_tc_enable_targets(dm_tc_state *s, uint32_t mask) {
mask &= (1u << DM_TC_COUNT) - 1;
if (mask == s->enabled_targets) return;
dm_tc_cancel_all(s);
s->enabled_targets = mask;
}
void dm_tc_set_joy_block(dm_tc_state *s, int block) { s->joy_block = block != 0; }
void dm_tc_set_navigation_mode(dm_tc_state *s, int navigation_mode) {
navigation_mode = !!navigation_mode;
if (navigation_mode == s->navigation_mode) return;
dm_tc_cancel_all(s);
s->navigation_mode = navigation_mode;
}
/* 系统取消了这根手指(通知横幅、系统手势):不当松手——不补脉冲、不点世界、不点界面;只把它按着的键、摇杆、光标放掉 | The system cancelled this finger (notification banner, system gesture): do not treat it as a release -- no make-up pulse, no world tap, no UI click; only let go of the keys, stick and cursor it was holding */
void dm_tc_cancel_finger(dm_tc_state *s, int slot) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH) return;
++s->gesture_epoch;
if (s->finger[slot].active && s->finger[slot].target == DM_TC_PORTAL) { dm_tc_cancel_portal(s); }
if (slot == s->joy_slot && s->finger[slot].active) { s->joy_lost_s = s->last_time_s; s->joy_lost_x = s->finger[slot].x; s->joy_lost_y = s->finger[slot].y; } /* 系统取消了摇杆那根手指:记下,紧接着在附近重新落下的接着当摇杆 | the system cancelled the joystick finger: record it, and a finger landing again nearby right afterwards continues as the joystick */
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
if (slot == s->joy_slot) { s->joy_slot = DM_TC_NONE; s->joy_origin_x = s->joy_origin_y = 0; }
if (slot == s->aim_slot) s->aim_slot = DM_TC_NONE;
if (slot == s->pointer_slot) { s->pointer_item = 0; s->pointer_shop = 0; s->pointer_stack = 0; s->pointer_lock = 0; s->pointer_slot = DM_TC_NONE; s->pointer_valid = 0; }
update(s);
}
void dm_tc_cancel_portal(dm_tc_state *s) {
++s->gesture_epoch; s->portal_pending=s->portal_phase=0;
for (int i=0;i<DM_TC_MAX_TOUCH;++i)
if(s->finger[i].active && s->finger[i].target==DM_TC_PORTAL)
s->finger[i]=(dm_tc_finger){.target=DM_TC_NONE};
update(s);
}
void dm_tc_set_portal_binding(dm_tc_state *s,uint64_t mask,uint64_t identity,uint64_t scene) {
if(s->layout.target[DM_TC_PORTAL].button==mask && s->portal_binding_identity==identity && s->portal_scene_epoch==scene)return;
dm_tc_cancel_portal(s);
s->portal_binding_identity=identity;s->portal_scene_epoch=scene;
s->layout.target[DM_TC_PORTAL].button=mask;update(s);
}
void dm_tc_set_portal_button(dm_tc_state *s,uint64_t mask) {
dm_tc_set_portal_binding(s,mask,s->portal_binding_identity,s->portal_scene_epoch);
}
int dm_tc_portal_ack(dm_tc_state *s,uint64_t epoch,uint64_t identity,uint64_t scene) {
if(!s->portal_pending || s->gesture_epoch!=epoch || s->portal_binding_identity!=identity || s->portal_scene_epoch!=scene)return 0;
int active=0;for(int i=0;i<DM_TC_MAX_TOUCH;i++)active|=s->finger[i].active && s->finger[i].target==DM_TC_PORTAL;
if(!active)return 0;
s->portal_pending=0;s->portal_phase=2;update(s);return 1;
}
/* 腰带展开着、这一点不在腰带上(底排四格与展开的几排之外):前端据此在自己的手势(小地图块、空位十字)之前先收腰带并吃掉这一下 | Belt expanded and this point is not on the belt (outside the four bottom-row cells and the expanded rows): based on this the front end collapses the belt and consumes this tap before its own gestures (minimap block, empty-slot cross) */
int dm_tc_belt_outside(const dm_tc_state *s, float x, float y) {
if (s->navigation_mode || !s->belt_open || s->belt_rows <= 1) return 0;
int hit = dm_tc_hit(&s->layout, x, y); if (hit >= DM_TC_BELT1 && hit <= DM_TC_BELT4) return 0;
float u = s->layout.height / 1320.0f;
for (int r = 1; r < s->belt_rows && r < 4; ++r) for (int c = 0; c < 4; ++c) {
const dm_tc_target *t = &s->layout.target[DM_TC_BELT1+c];
if (fabsf(x - t->x) <= 60*u && fabsf(y - (t->y - (165.0f + 162.0f*(r-1))*u)) <= 53.75f*u) return 0;
}
return 1;
}
/* 腰带点一下 = 自己喝,点几下喝几瓶(原版手感,不判双击)。底排 = 补一个腰带键脉冲(不带 ZL,第二组下也不带);上面几排手柄没有键 = belt_request 交宿主喝那一格。
喂雇佣兵不在腰带上做手势:佣兵面板里的原版入口和「自动给佣兵喝药」设置照旧
One tap on the belt = the player drinks, several taps drink several (original feel, no double-tap detection). Bottom row = one belt key pulse (without ZL, also under the second set); upper rows have no controller key = belt_request asks the host to drink that cell.
Feeding the mercenary has no gesture on the belt: the game's own entry in the mercenary panel and the "auto-feed mercenary" setting are unchanged */
static void belt_fire(dm_tc_state *s, int cell) {
if (cell >= 0x100) { s->belt_request = cell; return; }
uint64_t btn = s->layout.target[DM_TC_BELT1 + (cell & 0xf)].button; if (!btn) return;
if (s->pulse_button || s->defer_button || s->belt_gap_cell) { s->belt_q = cell; return; } /* 有脉冲在发 / 有补发在等:排着(dm_tc_tick 空了再发) | A pulse is being sent / a make-up send is waiting: queue it (dm_tc_tick sends it when free) */
if (s->skill_set && !s->navigation_mode) for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) { /* 按着第二组技能:先松 ZL 和技能键,隔 DM_TC_ZL_LEAD_S 再按腰带键(见 update) | a skill of the second skill set is held: first release ZL and the skill key, and press the belt key after DM_TC_ZL_LEAD_S (see update) */
const dm_tc_finger *f = &s->finger[i]; if (!f->active || f->aim_cancelled || f->target < DM_TC_MAIN || f->target > DM_TC_SKILL4) continue;
s->belt_gap_cell = 0x1000 | cell; s->belt_gap_at = s->last_time_s + DM_TC_ZL_LEAD_S; update(s); return; }
s->pulse_rx = s->pulse_ry = 0; s->pulse_button = btn; ++s->pulse_epoch;
update(s);
}
void dm_tc_begin_at(dm_tc_state *s, int slot, float x, float y, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH || s->finger[slot].active || !isfinite(x) || !isfinite(y)) return;
s->last_time_s = now_s;
dm_tc_finger *f = &s->finger[slot];
if (!s->navigation_mode) { /* 难度:点第 0 格开 / 收选择条;展开时点某格 = 选档并收起,点别处只收起、照常处理 | Difficulty: tapping cell 0 opens / collapses the selector bar; when expanded, tapping a cell = select that level and collapse; tapping elsewhere only collapses and is then handled as usual */
const dm_tc_target *d = &s->layout.diff;
int on_diff = d->r > 0 && hypotf(x-d->x, y-d->y) <= d->r, pick = -1;
for (int i = 0; s->diff_open && i < 8; ++i) if (hypotf(x-s->layout.pick[i].x, y-s->layout.pick[i].y) <= s->layout.pick[i].r) pick = i;
if (on_diff || pick >= 0) {
if (pick >= 0) s->diff_request = pick + 1;
s->diff_open = on_diff ? !s->diff_open : 0;
*f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
s->diff_open = 0;
}
int hit = dm_tc_hit(&s->layout, x, y);
if (!s->navigation_mode && s->belt_open && s->belt_rows > 1) { /* 腰带展开着:点上面几排 = 喝那一格;点腰带以外 = 只收起 | Belt expanded: tapping the upper rows = drink that cell; tapping outside the belt = only collapse */
float u = s->layout.height / 1320.0f; /* 展开的几排是游戏自己画的:列与底排对齐,排距 162、第一排比底排高 165(效果图单位;真机 2868×1320 实量,行距由 gen_hud_v4.py 的 bpy 定,改那边要一起改) | The expanded rows are drawn by the game itself: columns align with the bottom row, row pitch 162, the first row is 165 above the bottom row (mock units; measured on a real device at 2868×1320; the row spacing is set by bpy in gen_hud_v4.py, and changing it there requires changing it here too) */
for (int r = 1; r < s->belt_rows && r < 4; ++r) for (int c = 0; c < 4; ++c) {
const dm_tc_target *t = &s->layout.target[DM_TC_BELT1+c];
if (fabsf(x - t->x) <= 60*u && fabsf(y - (t->y - (165.0f + 162.0f*(r-1))*u)) <= 53.75f*u) {
belt_fire(s, 0x100 | r << 4 | c); /* 按下就喝那一格 | drink that cell on press */
*f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
}
if (hit < DM_TC_BELT1 || hit > DM_TC_BELT4) { /* 点别处:只收腰带,这一下不再做别的(不走路、不点世界、不按键) | Tap elsewhere: only collapse the belt; this tap does nothing else (no walking, no world tap, no key press) */
s->belt_request = 2; *f = (dm_tc_finger){.active=1, .target=DM_TC_DIFF, .x=x, .y=y}; update(s); return;
}
}
if (hit == DM_TC_SWAP) {
if (s->navigation_mode) hit = DM_TC_NONE;
else { s->skill_set = !s->skill_set; *f = (dm_tc_finger){.active=1, .target=DM_TC_SWAP, .x=x, .y=y}; update(s); return; }
}
int enabled = hit >= 0 && (s->enabled_targets & (1u << hit));
/* 面板态:被禁用的目标(底栏腰带 / 功能键 / 回城、圆钮收起后的技能钮位置)不占手指——它们压着的地方可能正是面板的按钮
(设置页「应用」在屏幕底部,落在禁用的底栏目标上,既不判类也不点击)。游戏态仍占着(防隐藏的回城触点变成摇杆)
Panel state: disabled targets (bottom-bar belt / function key / town portal, and the skill button positions after the round buttons are hidden) do not capture fingers -- the place they cover may be exactly a panel button
(「应用」(Apply) on the settings page is at the bottom of the screen and landed on a disabled bottom-bar target, getting neither classified nor clicked). In game state they still capture (preventing a hidden town-portal touch point from turning into the stick) */
if (s->navigation_mode && hit >= 0 && !enabled) hit = DM_TC_NONE;
if(enabled && hit==DM_TC_PORTAL && s->layout.target[hit].button && s->portal_phase==0) {
++s->gesture_epoch;
uint64_t mask=s->layout.target[hit].button;
s->portal_pending=(mask&DM_BTN_ZL) && (mask&~DM_BTN_ZL);
s->portal_phase=s->portal_pending?1:2;
}
*f = (dm_tc_finger){.active=1, .target=enabled ? hit : DM_TC_NONE, .x=x, .y=y,
.aim_origin_x=x, .aim_origin_y=y,
.start_time_s=now_s};
/* 禁用圆仍阻止落入左摇杆区,防止隐藏回城触点变成移动。 | A disabled circle still blocks falling through into the left stick area, preventing a hidden town-portal touch point from turning into movement. */
if (s->navigation_mode && hit == DM_TC_NONE && s->pointer_slot == DM_TC_NONE) {
s->pointer_slot = slot;
s->pointer_item = 0;
/* 鼠标点击模式下,手柄光标只跟「落在物品区的手指」走(前端答出命中后调 dm_tc_pointer_item):
光标是靠推摇杆走的,在没有自由光标的页面(选项、暂停菜单、小站)推摇杆 = 改当前选项 / 挪焦点(点页签顺带改了「显示物品」)
In mouse click mode the controller cursor follows only "a finger that landed in the item area" (the front end calls dm_tc_pointer_item once it has the hit answer):
the cursor moves by pushing the stick, and on pages without a free cursor (options, pause menu, waypoint) pushing the stick = changing the current option / moving the focus (tapping a tab changed 「显示物品」(Show Items) as a side effect) */
if (!s->mouse_click_mode) { s->pointer_valid = 1; s->pointer_x = x; s->pointer_y = y; }
} else if (!s->navigation_mode && hit == DM_TC_NONE && g_edge_b > 0 && x >= 0 && x < s->layout.width*0.43f && y > s->layout.height - g_edge_b) {
f->target = DM_TC_EDGE;
} else if (!s->navigation_mode && !s->joy_block && hit == DM_TC_NONE && s->joy_slot == DM_TC_NONE &&
x >= 0 && y <= s->layout.height && x < s->layout.width*0.43f && y > s->layout.height*0.25f &&
(hypotf(x - s->layout.joy_x, y - s->layout.joy_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius ||
(s->joy_lost_s > 0 && now_s - s->joy_lost_s <= DM_TC_JOY_RESUME_S && hypotf(x - s->joy_lost_x, y - s->joy_lost_y) <= DM_TC_JOY_GRAB_K * s->layout.joy_radius))) {
/* 摇杆底座固定在左下角原位:手指落在底座附近(DM_TC_JOY_GRAB_K 倍半径内)才起摇杆,方向与幅度按「手指相对底座中心」算,
按住后拖到多远都照样识别;落在左侧别处不起摇杆(照旧是点地)。原先是浮动摇杆:落在左侧区域哪里,底座就出在哪里、松手回原位。
例外:摇杆那根手指刚被系统取消(通知横幅、系统手势;dm_tc_cancel_finger 记下时刻与位置),DM_TC_JOY_RESUME_S 内在原处附近重新落下的手指接着当摇杆——
拖远了的摇杆被系统打断一下不该就此断掉;浮动摇杆时这种情形表现为底座追着手指重起
The joystick base is fixed at its home position in the lower left: the joystick starts only when a finger lands near the base (within DM_TC_JOY_GRAB_K × radius), and direction and magnitude are computed as "finger relative to the base center";
once held it is still recognized however far it is dragged; landing elsewhere on the left does not start the joystick (it is a ground tap as before). Previously it was a floating joystick: wherever in the left area the finger landed, the base appeared there, returning to its home position on release.
Exception: when the joystick finger has just been cancelled by the system (notification banner, system gesture; dm_tc_cancel_finger records the time and position), a finger landing again near the same spot within DM_TC_JOY_RESUME_S continues as the joystick --
a joystick dragged far away should not be cut off for good by a brief system interruption; with the floating joystick this case showed up as the base restarting under the finger */
s->joy_lost_s = 0;
f->target = DM_TC_JOYSTICK;
s->joy_slot = slot;
s->joy_origin_x = s->layout.joy_x;
s->joy_origin_y = s->layout.joy_y;
}
update(s);
}
void dm_tc_move_at(dm_tc_state *s, int slot, float x, float y, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH || !s->finger[slot].active || !isfinite(x) || !isfinite(y)) return;
s->last_time_s = now_s;
dm_tc_finger *f = &s->finger[slot];
f->x = x;
f->y = y;
if (pointer_finger(s, f)) {
float distance = hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y);
if (!f->pointer_dragged && distance > DM_TC_POINTER_MOVE_PT * scale_for(&s->layout) && (!s->mouse_click_mode || s->pointer_item == 1))
pointer_drag_begin(s, f); /* 鼠标点击模式:只有从物品区起手才是拖放;别处的滑动不发键。按住不动超过长按时长再拖也算拖放(真人「按住停一下再拖」,z4:0.5 秒后才动的拖放拿不起来) | Mouse click mode: only a gesture starting in the item area is a drag-and-drop; swipes elsewhere send no key. Holding still longer than the long-press duration and then dragging also counts as drag-and-drop (a real person "holds for a moment and then drags"; z4: a drag that started moving only after 0.5 seconds could not pick the item up) */
/* 起手在模态框外 / 被上层盖住(类 6 = 这一下不点)也不起滚动 / 滑块手势:原先模态框开着时框外上下滑照样给底下发滚轮 | A gesture starting outside the modal box / covered by an upper layer (class 6 = this tap does not click) does not start a scroll / slider gesture either: previously, with a modal box open, swiping up and down outside it still sent wheel events to what was underneath */
else if (s->mouse_click_mode && s->pointer_item != 1 && s->pointer_item != 3 && s->pointer_item != 6 && !f->ui_drag && !f->pointer_dragged && distance > DM_TC_POINTER_MOVE_PT * scale_for(&s->layout))
f->ui_drag = fabsf(f->x - f->aim_origin_x) > fabsf(f->y - f->aim_origin_y) ? 2 : 1; /* 界面连续手势:过阈值那一刻按方向定型(纵 = 滚动,横 = 滑块) | Continuous UI gesture: the type is fixed by direction at the moment the threshold is crossed (vertical = scroll, horizontal = slider) */
update_pointer(s);
} else if (!s->navigation_mode && skill_target(f->target)) {
if (inside_map_cancel(s, f)) f->aim_cancelled = 1;
if (!f->aim_cancelled) f->aim_move_sequence = ++s->aim_move_sequence;
}
update(s);
}
void dm_tc_end_at(dm_tc_state *s, int slot, double now_s) {
if (slot < 0 || slot >= DM_TC_MAX_TOUCH) return;
s->last_time_s = now_s;
if(s->finger[slot].active && s->finger[slot].target==DM_TC_PORTAL) {
s->finger[slot]=(dm_tc_finger){.target=DM_TC_NONE};
for(int i=0;i<DM_TC_MAX_TOUCH;i++)if(s->finger[i].active && s->finger[i].target==DM_TC_PORTAL) {update(s);return;}
dm_tc_cancel_portal(s);return;
}
dm_tc_finger done = s->finger[slot];
if (s->navigation_mode && slot == s->pointer_slot) {
float distance = hypotf(done.x-done.aim_origin_x, done.y-done.aim_origin_y);
double elapsed = now_s - done.start_time_s;
/* 商人货架上的货长按 = 原版的「按住 Y 大量购买」(提示条原文;宿主读数:约 1.3 秒):背包里有没满的卷轴书 / 同类叠时买满,没有就和买 1 份一样;买多少、钱够不够都由游戏定,这里只替玩家按键 | Long press on goods on the vendor shelf = the original game's 「按住 Y 大量购买」(Hold Y to buy in bulk) (button legend text; host reading: about 1.3 seconds): when the inventory has a non-full scroll tome / stack of the same kind it buys until full, otherwise it is the same as buying 1; how many to buy and whether there is enough gold are decided by the game, and here we only press the key for the player */
if (done.pointer_long && !done.pointer_dragged && !done.shop_drag && s->pointer_item == 1 && s->pointer_shop) pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 1.3);
else if (done.pointer_long && !done.pointer_dragged && !done.shop_drag && s->pointer_item == 1 && !s->pointer_lock) ++s->long_press_seq; /* 长按在松手时才算(按住没动):按住到点就算的话,「按住停一下再拖」的药水会先被放进腰带(mini 药拖腰带脚本里多出 2 次) | Long press counts only at release (held without moving): if it counted as soon as the hold time was reached, a potion that is "held for a moment and then dragged" would first be put into the belt (2 extra occurrences in the potion-drag-to-belt script on the second Mac) */
if (done.locked_drag) { } /* 单件槽占用时拖别的物品:不发任何键 | Dragging another item while the single-item slot is occupied: send no key */
else if (done.shop_drag) { ++s->shop_drop_seq; } /* 买不买由前端按落点定;这里不发任何键 | Whether to buy is decided by the front end from the drop point; no key is sent here */
else if (done.pointer_dragged) {
if (s->pointer_release_item == 1) pointer_pulse_start(s, done.x, done.y - DM_TC_POINTER_LIFT_PT * scale_for(&s->layout), 2); /* 放在抬起点(物品显示的位置) | Place at the lifted point (where the item is displayed) */
else if (s->pointer_release_item == 5) pointer_pulse_start(s, s->release_x, s->release_y, 2); /* 宿主给的放下位置(装备槽 = 槽心) | Drop position given by the host (equipment slot = slot center) */
else if (s->pointer_release_item == 4) pointer_pulse_start(s, done.x, done.y, 2); /* 放在手指点(玩家对着手指放) | Place at the finger point (the player aims with the finger) */
else if (s->pointer_release_item == 3) pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 0.15); /* 手指在面板外 = 丢弃:指针回原处、到位后按 Y | Finger outside the panel = discard: pointer returns to the original spot and presses Y once in place */
else if (s->pointer_release_item == 8) { /* 松在单件任务槽上:按原版走法重做——先放回原格,再对它按住 Y(原版的「放进槽」)。只把物品拿在手上停在槽上方不算进槽:槽会显示它,但点确认不成交(本机 实测没有成交包) | Released on the single-item quest slot: redo it the original game's way -- first put it back in its original cell, then hold Y on it (the original game's "put into slot"). Merely holding the item and hovering over the slot does not count as entering the slot: the slot shows it, but tapping confirm does not complete the transaction (measured on the local machine: no transaction packet) */
pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2); pointer_pulse_btn(s, done.aim_origin_x, done.aim_origin_y, 2, DM_BTN_Y, 1.3); }
else pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2); /* 面板里的空白处:放回原处 | Blank area inside the panel: put it back where it was */
} else if (!done.ui_drag && !done.pointer_long && elapsed < DM_TC_POINTER_TAP_S && distance <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) { /* 拖出去又拖回原处不算点按 | Dragging out and back to the original spot does not count as a tap */
/* 单件任务槽面板开着时,手上那件就是「槽里那件」:点背包格仍是放回去,点别处按没拿着处理——确认 / 关闭按钮要能点,点面板外 = 关面板(不是把槽里那件丢到地上) | While the single-item quest slot panel is open, the held item is "the one in the slot": tapping an inventory cell still puts it back, tapping elsewhere is handled as if nothing were held -- the confirm / close buttons must be tappable, and tapping outside the panel = close the panel (not drop the slot's item on the ground) */
if (s->pointer_lock) { s->pointer_x = done.aim_origin_x; s->pointer_y = done.aim_origin_y; } /* 单件槽占用时点别的物品:只移光标出说明,单击 / 双击都不动它 | Tapping another item while the single-item slot is occupied: only move the cursor to show the tooltip; neither single nor double tap moves it */
else if (s->holding && s->pointer_item != 0 && !(atomic_load(&g_imbue_open) && s->pointer_item != 1)) { if (s->pointer_item == 1) pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2);
else if (s->pointer_item == 3) pointer_pulse_btn(s, s->pointer_x, s->pointer_y, 2, DM_BTN_Y, 0.15); } /* 手上还拿着物品(上次没放成):点物品区 = 放下;点面板外 / 两侧黑网格 = 丢(Y);点页签等别处不动。
点按钮(类 0)不在这里吞掉、照常发鼠标点击:原先连合成钮也吞,手上有东西时点合成什么都不发;合成钮由宿主先收手上那件再按,见 dm_cursor.c
Still holding an item (the last drop did not succeed): tap the item area = put down; tap outside the panel / the black grid on either side = drop (Y); tapping tabs or elsewhere does nothing.
Tapping a button (class 0) is not swallowed here and sends a mouse click as usual: previously even the transmute button was swallowed, and tapping transmute with something in hand sent nothing; for the transmute button the host first stows the held item and then presses, see dm_cursor.c */
else if (s->pointer_item == 2) { ++s->tab_tap_seq; }
else if (s->pointer_item == 6 || s->pointer_item == 11) { } /* 压着被上层面板盖住的按钮:不点、不发键 | Pressing on a button covered by an upper panel: no click, no key */
else if (s->pointer_item == 3) { if (!atomic_load(&g_dead_modal)) { s->close_left = 3; s->close_next_s = now_s; atomic_store(&g_close_stop, 0); } } /* 面板外:不发鼠标点击(会落到游戏世界 = 点地走路),按 B 关面板——子菜单里一下 B 只退一级,所以按到面板关掉为止(至多 3 下,见 dm_tc_tick);死亡弹窗开着时不动 | Outside the panel: do not send a mouse click (it would land in the game world = tap ground to walk); press B to close the panel -- in a submenu one B only goes back one level, so press until the panel is closed (at most 3 presses, see dm_tc_tick); do nothing while the death popup is open */
else if (s->pointer_item) { /* 物品区:单击只移光标(游戏自己出说明);紧接着在同一处再点一下 = 按住 A / Y | Item area: a single tap only moves the cursor (the game shows the tooltip itself); another tap at the same spot right after = hold A / Y */
float ox = done.aim_origin_x, oy = done.aim_origin_y;
int dbl = now_s - s->last_tap_s < DM_TC_DOUBLE_TAP_S && hypotf(ox - s->last_tap_x, oy - s->last_tap_y) <= 2 * DM_TC_POINTER_MOVE_PT * scale_for(&s->layout);
if (dbl) { if (atomic_load(&g_hover_unid) && !s->pointer_stack && !s->pointer_shop) ++s->ident_seq; /* 未鉴定物品:双击 = 免费鉴定(各页都先判;商人货架上的货不算我方物品,宿主也不发布) | Unidentified item: double tap = free identify (checked first on every page; goods on the vendor shelf are not our items, and the host does not publish them either) */
else if (s->pointer_stack) ++s->stack_take_seq; /* 成叠格:取 1 件(原版短按 Y;这里不按键,按住 0.6 秒会变成「移动 3 个」) | Stacked cell: take 1 (short press Y in the original game; no key is pressed here, since holding for 0.6 seconds would become "move 3") */
else if (atomic_load(&g_imbue_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, 1.3); /* 单件任务槽面板:原版对背包物品按住 Y = 放进槽(宿主读数:约 1.3 秒);不能当「使用」——否则在古墓底座前双击法杖会被装到手上 | Single-item quest slot panel: in the original game holding Y on an inventory item = put it into the slot (host reading: about 1.3 seconds); it must not be treated as "use" -- otherwise double-tapping the staff in front of the tomb pedestal would equip it in hand */
else if (atomic_load(&g_bank_open) && !atomic_load(&g_tap_box) && !atomic_load(&g_vault_open)) {
/* 背包里的物品:先发原版的 X(移动到堆叠栏)。能堆叠的(符文 / 宝石 / 材料)游戏收下、进堆叠格;不能堆叠的游戏对 X 不做任何事,0.4 秒后它还在光标下就退回按住 Y。
不直接按住 Y:那是「到仓库当前这一页」,在符文 / 宝石页且背包带着魔盒时会进页里嵌的魔盒格。仓库一侧的物品不走这里,仍是按住 Y 取回
Item in the inventory: first send the original game's X (move to the stacking tab). Stackable ones (runes / gems / materials) are accepted by the game and go into a stack cell; for non-stackable ones the game does nothing on X, and if it is still under the cursor after 0.4 seconds, fall back to hold Y.
Do not hold Y directly: that means "to the stash's current page", and on the rune / gem page with a cube in the inventory it would go into the cube cell embedded in the page. Items on the stash side do not go through here; they are still retrieved by holding Y */
if (atomic_load(&g_cur_stack)) { pointer_pulse_btn(s, ox, oy, 2, DM_BTN_X, 0.15); s->stash_x_check_s = now_s + 0.4; s->stash_x_x = ox; s->stash_x_y = oy; s->stash_x_id = atomic_load(&g_cur_stack); }
else pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); }
else if (atomic_load(&g_cube_open) && !atomic_load(&g_bank_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); /* 方块页(不是箱子里嵌的那格):原版按住 Y 一步送进 / 送出方块;与箱子页双击同一条规则 | Cube page (not the cell embedded in the stash): in the original game holding Y sends the item into / out of the cube in one step; same rule as double tap on the stash page */
else ++s->use_seq; /* 开着箱子:按住 Y = 移到另一侧(魔盒除外:原版开箱时按住 A 仍是打开魔盒,读码);否则交给宿主当场使用(原先按住 A 0.6 秒,约 0.4 秒后才生效) | Stash open: hold Y = move to the other side (except the cube: in the original game holding A with the stash open still opens the cube, per the code); otherwise hand it to the host to use on the spot (it used to hold A for 0.6 seconds and took effect only after about 0.4 seconds) */
s->last_tap_s = -1e9; }
else { /* 单击:移光标。隔了一会儿(不算双击)又点同一处 = 与另一件已装备的比较(原版按 ZL 循环;说明框文案「再点一次与另一件比较」) | Single tap: move the cursor. Tapping the same spot again after a while (not a double tap) = compare with the other equipped item (the original game cycles with ZL; tooltip text 「再点一次与另一件比较」(Tap again to compare with the other one)) */
int again = now_s - s->last_tap_s < 8.0 && hypotf(ox - s->last_tap_x, oy - s->last_tap_y) <= 2 * DM_TC_POINTER_MOVE_PT * scale_for(&s->layout);
if (again && !atomic_load(&g_bank_open) && !atomic_load(&g_vendor_open)) pointer_pulse_btn(s, ox, oy, 2, DM_BTN_ZL, 0); /* 开着箱子 / 商人页时 ZL 是切页签,不发(货上点第二下把货架翻到了下一页) | With the stash / vendor page open ZL switches tabs, so do not send it (a second tap on goods flipped the shelf to the next page) */
else if (!s->pulse_button) { s->pointer_x = ox; s->pointer_y = oy; }
++s->item_tap_seq; s->last_tap_s = now_s; s->last_tap_x = ox; s->last_tap_y = oy; }
} else if (s->tap_button) {
s->pointer_valid = 1; pointer_pulse_btn(s, s->tap_x, s->tap_y, 2, s->tap_button, 0); /* 前端改写:光标到点 + 按键(技能绑定里点技能) | Front-end rewrite: cursor to the point + key press (tapping a skill in skill binding) */
} else if (s->tap_move) {
s->pointer_valid = 1; s->pointer_x = s->tap_x; s->pointer_y = s->tap_y; ++s->tap_move_seq;
} else if (s->mouse_click_mode) {
s->mouse_click_x = done.aim_origin_x; s->mouse_click_y = done.aim_origin_y; ++s->mouse_click_seq;
} else pointer_pulse_start(s, done.aim_origin_x, done.aim_origin_y, 2);
}
s->pointer_item = 0; s->pointer_release_item = 1; s->pointer_shop = 0; s->pointer_stack = 0; s->pointer_lock = 0;
s->pointer_slot = DM_TC_NONE;
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
update(s);
return;
}
/* 技能钮:按住 = 持续施放、拖动定方向、松手键起,不再是「按住瞄准、松手放一下」。
唯一要补的:点得太短,键还没来得及按下手就松了(不到点按 / 拖动的判定时间,或第二组里 ZL 还没领先够)——补成一个带方向的脉冲;
第二组里 ZL 还没领先够时,这个脉冲延到够了再发(dm_tc_tick)。
Skill button: hold = continuous cast, drag sets the direction, release lifts the key; no longer "hold to aim, release to cast once".
The only thing to make up: the tap was too short and the finger lifted before the key could go down (shorter than the tap / drag decision time, or in the second set ZL has not led long enough) -- make it up as one pulse with direction;
in the second set, when ZL has not led long enough, this pulse is delayed until it has (dm_tc_tick). */
if (done.active && done.target >= DM_TC_SKILL1 && done.target <= DM_TC_SKILL4 && !done.aim_cancelled && !s->navigation_mode
&& (!done.key_down || now_s - done.key_down_s < DM_TC_KEY_MIN_S || (s->skill_set && now_s - done.start_time_s < DM_TC_ZL_LEAD_S))) { /* 键没按下过,或按下不到 2 帧(游戏可能漏读):补成脉冲 | The key was never pressed, or was pressed for less than 2 frames (the game may miss it): make it up as a pulse */
float ux = 0, uy = 0; int has = aim_dir(s, &done, &ux, &uy);
s->pulse_rx = has ? (int32_t)lroundf(ux*DM_STICK_MAX) : 0; s->pulse_ry = has ? (int32_t)lroundf(-uy*DM_STICK_MAX) : 0;
if (s->skill_set && now_s - done.start_time_s < DM_TC_ZL_LEAD_S) { s->defer_button = s->layout.target[done.target].button; s->defer_at_s = done.start_time_s + DM_TC_ZL_LEAD_S; }
else { s->pulse_button = s->layout.target[done.target].button; ++s->pulse_epoch; }
}
if (done.active && !s->navigation_mode && done.target >= DM_TC_BELT1 && done.target <= DM_TC_BELT4) {
/* 腰带格松手这一刻判:多排时上移过阈值 = 展开,下移过阈值 = 收起;几乎没动 = 点了一下,这一刻就喝;横着滑走了什么都不做 | decided when a belt cell is released: with multiple rows, moved up past the threshold = expand, down past the threshold = collapse; barely moved = a tap, drink right then; slid away sideways = do nothing */
float th = DM_TC_BELT_SWIPE_PT * scale_for(&s->layout), up = done.aim_origin_y - done.y, dx = done.x - done.aim_origin_x;
if (s->belt_rows > 1 && up > th) s->belt_request = 1;
else if (s->belt_rows > 1 && up < -th) s->belt_request = 2;
else if (fabsf(dx) <= th && fabsf(up) <= th) belt_fire(s, 0x10 | (done.target - DM_TC_BELT1));
}
if (done.active && !s->navigation_mode && done.target == DM_TC_NONE && now_s - done.start_time_s < DM_TC_POINTER_TAP_S && /* 落在摇杆底座上的那一下是摇杆(一按就有方向),不再兼作点地 | the tap that lands on the joystick base is the joystick (direction as soon as pressed) and no longer doubles as a ground tap */
hypotf(done.x - done.aim_origin_x, done.y - done.aim_origin_y) <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) {
s->world_tap_x = done.aim_origin_x; s->world_tap_y = done.aim_origin_y; ++s->world_tap_seq; /* 点游戏世界 | Tap the game world */
}
s->finger[slot] = (dm_tc_finger){.target=DM_TC_NONE};
if (slot == s->joy_slot) {
s->joy_slot = DM_TC_NONE;
s->joy_origin_x = s->joy_origin_y = 0;
}
update(s);
}
void dm_tc_begin(dm_tc_state *s, int slot, float x, float y) { dm_tc_begin_at(s, slot, x, y, s->last_time_s); }
void dm_tc_move(dm_tc_state *s, int slot, float x, float y) { dm_tc_move_at(s, slot, x, y, s->last_time_s); }
void dm_tc_end(dm_tc_state *s, int slot) { dm_tc_end_at(s, slot, s->last_time_s); }
void dm_tc_pointer_press(dm_tc_state *s, float x, float y, uint64_t button) {
if (s->pointer_slot >= 0 && s->pointer_slot < DM_TC_MAX_TOUCH) s->finger[s->pointer_slot].pointer_long = 1;
s->pointer_valid = 1; pointer_pulse_btn(s, x, y, 2, button, 0); update(s);
}
void dm_tc_tick(dm_tc_state *s, double now_s) {
s->last_time_s = now_s;
/* 补发不许盖掉在发的脉冲(腰带喝药等):在发就等;那个脉冲收回时(dm_tc_pulse_end)把补发时刻推到 ZL 再领先满 DM_TC_ZL_LEAD_S 之后(原先到点直接覆盖,腰带那下没了) | The make-up send must not overwrite a pulse being sent (belt potion, etc.): wait while one is being sent; when that pulse is released (dm_tc_pulse_end), push the make-up time to after ZL has again led for a full DM_TC_ZL_LEAD_S (it used to overwrite directly when due, and the belt press was lost) */
if (s->belt_gap_cell && now_s >= s->belt_gap_at && !s->pulse_button) { uint64_t btn = s->layout.target[DM_TC_BELT1 + (s->belt_gap_cell & 0xf)].button; s->belt_gap_cell = 0;
if (btn && !s->navigation_mode) { s->pulse_rx = s->pulse_ry = 0; s->pulse_button = btn; ++s->pulse_epoch; } update(s); }
if (s->belt_q && !s->pulse_button && !s->defer_button && !s->belt_gap_cell) { int q = s->belt_q; s->belt_q = 0; if (!s->navigation_mode) belt_fire(s, q); }
if (s->defer_button && !s->pulse_button && now_s >= s->defer_at_s) { s->pulse_button = s->defer_button; s->defer_button = 0; ++s->pulse_epoch; update(s); }
else if (!s->navigation_mode) { /* 主钮 / 技能钮上有手指:判定时间、ZL 领先这两个时刻要按时刷新键值 | A finger is on the main button / a skill button: the key values must be refreshed on time at two moments, the decision time and the ZL lead */
for (int i = 0; i < DM_TC_MAX_TOUCH; ++i) if (s->finger[i].active && (s->finger[i].target >= DM_TC_MAIN && s->finger[i].target <= DM_TC_SKILL4)) { update(s); break; }
}
if (s->stash_x_check_s > 0 && now_s >= s->stash_x_check_s) { /* 发过 X 的那件还在光标下(不能堆叠 / 这个存档没有堆叠栏 / 那一叠满了):退回按住 Y,移到仓库当前页。核的是同一个物品 id,X 已经把它移走就什么都不做 | The item that X was sent for is still under the cursor (not stackable / this save has no stacking tab / that stack is full): fall back to hold Y, moving it to the stash's current page. The check is on the same item id; if X has already moved it away, do nothing */
s->stash_x_check_s = 0;
if (atomic_load(&g_bank_open) && atomic_load(&g_cur_stack) == s->stash_x_id && !s->holding && !s->pulse_button) { pointer_pulse_btn(s, s->stash_x_x, s->stash_x_y, 2, DM_BTN_Y, DM_TC_HOLD_USE_S); update(s); }
}
if (s->close_left > 0 && atomic_exchange(&g_close_stop, 0)) s->close_left = 0; /* 返回键引出了确认框(设置页有未应用的改动):停手,让玩家自己答——再按一下就成了替他选「放弃」(改动丢失) | The back button brought up a confirmation box (the settings page has unapplied changes): stop and let the player answer -- one more press would choose 「放弃」(Discard) on their behalf (changes lost) */
if (s->close_left > 0) { /* 面板外点按 = 关到底:面板还开着、上一下 B 已收回,就隔 0.3 秒再按一下 | Tap outside the panel = close all the way: if the panel is still open and the previous B has been released, press once more after 0.3 seconds */
if (!s->navigation_mode) s->close_left = 0;
else if (!s->pulse_button && now_s >= s->close_next_s) { s->pulse_button = DM_BTN_B; s->pulse_hold_s = 0; s->pulse_rx = s->pulse_ry = 0; s->pointer_pulse_active = 2; ++s->pulse_epoch; --s->close_left; s->close_next_s = now_s + 0.3; update(s); }
}
if (s->pointer_slot < 0 || s->pointer_slot >= DM_TC_MAX_TOUCH) return;
dm_tc_finger *f = &s->finger[s->pointer_slot];
if (!f->active || f->pointer_dragged || f->pointer_long) return;
if (s->mouse_click_mode && s->pointer_item != 1) return;
if (now_s - f->start_time_s >= DM_TC_POINTER_HOLD_S &&
hypotf(f->x-f->aim_origin_x, f->y-f->aim_origin_y) <= DM_TC_POINTER_MOVE_PT * scale_for(&s->layout)) {
f->pointer_long = 1;
s->pointer_x = f->aim_origin_x;
s->pointer_y = f->aim_origin_y;
update(s);
}
}
int dm_tc_navigation(dm_tc_scene *s, const char *cat, const char *act, const char *arg) {
static const char *names[]={"PlayerInventoryExpansionLayout","SkillsTreePanel","PauseLayout","PauseLayoutGarden","CharacterStatsPanel","QuestLogPanelExpansion","BankExpansionLayout","HoradricCubeLayout","WaypointsPanelExpansion","NpcDialogPanel","NpcTradePanel","ButtonBindingModal","SkillSelect","YouDiedModal"};
if(!strcmp(cat,"FrontEndNavigation")&&!strcmp(act,"ToFrontEnd")) { s->game=0;s->panels=0; }
if(!strcmp(cat,"PanelManager")) {
if(!strcmp(arg,"LoadScreenPanel")&&!strcmp(act,"OpenPanel"))s->game=0;
if(!strcmp(arg,"LoadScreenPanel")&&!strcmp(act,"UnloadPanel"))s->game=1;
if(!strcmp(act,"UnloadAll"))s->panels=0;
{ size_t al=strlen(arg); if((!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"))&&al>5&&!strcmp(arg+al-5,"Modal"))atomic_store(&g_close_stop,1); }
for(unsigned i=0;i<sizeof(names)/sizeof(*names);i++)if(!strcmp(arg,names[i])) {
if(!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"))s->panels|=1ull<<i;
if(!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel"))s->panels&=~(1ull<<i);
}
}
return !s->game||s->panels!=0;
}
/* 死亡弹窗开着:也算导航态(触点走界面点击,能点到「继续」),但五个手柄圆钮不给——死后点技能钮位置会触发复活,容易误触 | Death popup open: also counts as navigation state (touch points go through UI clicks, so 「继续」(Continue) can be tapped), but the five controller round buttons are not offered -- after death a tap at a skill button position triggers resurrection, which is easy to hit by mistake */
int dm_tc_scene_dead(void) { return atomic_load(&g_dead_modal); }
int dm_tc_scene_dialog_only(const dm_tc_scene *s) { return s->game && s->panels == (1ull << 9); } /* 面板表第 9 项 = NpcDialogPanel(见 dm_tc_navigation 的 names) | Entry 9 of the panel table = NpcDialogPanel (see names in dm_tc_navigation) */
+204
View File
@@ -0,0 +1,204 @@
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { DM_TC_MAX_TOUCH = 16, DM_TC_COUNT = 12 };
enum {
DM_TC_NONE = -1, DM_TC_JOYSTICK = -2, DM_TC_SWAP = -3, DM_TC_DIFF = -4, /* DIFF:难度格 / 选择条占用的手指,不发按键 | DIFF: a finger captured by the difficulty cell / selector bar; sends no key */
DM_TC_EDGE = -5, /* 屏幕底边归系统的那一条里起手的手指:不当摇杆,松手也不当点地 | A finger that started in the strip along the bottom edge of the screen that belongs to the system: not treated as the stick, and its release is not treated as a ground tap */
DM_TC_MAIN = 0,
DM_TC_SKILL1, DM_TC_SKILL2, DM_TC_SKILL3, DM_TC_SKILL4,
DM_TC_PORTAL, DM_TC_BELT1, DM_TC_BELT2, DM_TC_BELT3, DM_TC_BELT4,
DM_TC_MENU, DM_TC_MAP
};
typedef struct { float x, y, r; uint64_t button; } dm_tc_target;
typedef struct {
float width, height;
dm_tc_target target[DM_TC_COUNT];
float joy_x, joy_y, joy_radius;
dm_tc_target swap; /* 技能组切换键:本地开关,不直接发按键 | Skill set switch key: a local toggle; does not send a key directly */
dm_tc_target diff; /* 底部 UI v4 第 0 格难度:点开 / 收起 1–8 选择条,不发按键 | Bottom UI v4 cell 0 difficulty: tap to open / collapse the 1–8 selector bar; sends no key */
dm_tc_target pick[8]; /* 选择条 8 格(第 i 格 = 人数档 i+1),在七格上方 | The selector bar's 8 cells (cell i = player-count level i+1), above the seven cells */
} dm_tc_layout;
typedef struct {
int active, target;
float x, y;
float aim_origin_x, aim_origin_y;
uint64_t aim_move_sequence;
int aim_cancelled;
int key_down; double key_down_s; /* 技能钮:键是否已按下过、几时按下的(按下后先等判定时间,见 update) | Skill button: whether the key has gone down and when (after press, first wait the decision time, see update) */
double start_time_s;
int pointer_dragged, pointer_long;
/* 界面连续手势(鼠标点击模式、起手不在物品区也不在面板外、位移过阈值时按起始方向定型,定型后不变):1 = 纵向拖(滚动),2 = 横向拖(滑块)。
手势层只定型,前端看到后把起手点与当前点转给宿主(dm_ui_drag_*),滚动 / 滑块由宿主按游戏自己的命中去做
Continuous UI gesture (mouse click mode, started neither in the item area nor outside the panel; when displacement crosses the threshold the type is fixed by the initial direction and does not change afterwards): 1 = vertical drag (scroll), 2 = horizontal drag (slider).
The gesture layer only fixes the type; on seeing it the front end forwards the start point and current point to the host (dm_ui_drag_*), and the scroll / slider is done by the host according to the game's own hit testing */
int ui_drag;
int shop_drag; /* 从商人货架的货上起拖(不拿起):松手按落点买 / 不买 | Drag starting from goods on the vendor shelf (not picked up): on release, buy / do not buy by the drop point */
int locked_drag; /* 单件任务槽占用时从别的物品上起拖:不拿起,松手不发任何键 | Drag starting from another item while the single-item quest slot is occupied: do not pick up, and send no key on release */
} dm_tc_finger;
typedef struct {
dm_tc_layout layout;
dm_tc_finger finger[DM_TC_MAX_TOUCH];
int joy_slot;
float joy_origin_x, joy_origin_y;
uint32_t enabled_targets;
uint64_t buttons;
int32_t lx, ly, rx, ry;
int aim_slot, navigation_mode, map_cancel_active;
uint64_t aim_move_sequence;
int portal_pending, portal_phase; // 0idle / 1modifier-pending / 2armed
uint64_t gesture_epoch, portal_binding_identity, portal_scene_epoch;
/* 松手施放的短按脉冲:按键与右轴方向同时发布,前端到时调 dm_tc_pulse_end 收回 | Short-press pulse for release-to-cast: the key and the right-axis direction are published together, and the front end calls dm_tc_pulse_end to release it when due */
uint64_t pulse_button, pulse_epoch;
int32_t pulse_rx, pulse_ry;
uint64_t defer_button; double defer_at_s; /* 第二组里点得太短的那一下:等 ZL 领先够了再补发 | The too-short tap in the second set: make it up once ZL has led long enough */
/* 技能组:0 = 第一套;1 = 第二套(原版 Switch 按住 ZL 用 alt 槽)。是模式,不随取消/尺寸变化清零 | Skill set: 0 = first set; 1 = second set (on the original Switch game, holding ZL uses the alt slots). It is a mode and is not cleared on cancel/size change */
int skill_set;
/* 第二组技能(ZL 修饰):ZL 只在手指按着主钮 / 技能钮、或技能脉冲在发时按着,且先于技能键 DM_TC_ZL_LEAD_S 按下。
松手施放按得太短时,这一下脉冲延到 ZL 领先够了再发(dm_tc_tick 到点起)。
Second skill set (ZL modifier): ZL is held only while a finger is on the main button / a skill button or a skill pulse is being sent, and goes down DM_TC_ZL_LEAD_S before the skill button.
When a release-to-cast press is too short, that pulse is delayed until ZL has led long enough (dm_tc_tick starts it when due). */
int pointer_slot;
double last_time_s;
int pointer_pickup_done;
int pointer_pulse_active, pointer_pulse_pending;
float pointer_pending_x, pointer_pending_y;
int pointer_valid;
float pointer_x, pointer_y;
/* 物品手势:pointer_item = 当前指针手指落在物品区(前端在松手前按宿主命中结果置位)。物品区单击只移光标(出说明)、
双击 = 按住 A(游戏提示:按住 = 打开 / 使用 / 装备;开着箱子时按住 Y = 移到另一侧);非物品区单击照旧 = 移光标 + 按 A。
pulse_hold_s > 0 = 这个脉冲要按住这么久,前端在「游戏已取走」之外再等满它才收
Item gestures: pointer_item = the current pointer finger landed in the item area (set by the front end before release from the host's hit result). A single tap in the item area only moves the cursor (shows the tooltip),
double tap = hold A (game hint: hold = open / use / equip; with the stash open, hold Y = move to the other side); a single tap outside the item area is as before = move the cursor + press A.
pulse_hold_s > 0 = this pulse must be held this long, and the front end waits it out in full in addition to "the game has consumed it" before releasing */
int pointer_item;
/* 非物品区的点按走鼠标点击(暂停菜单按钮、布局里插回的关闭 / 修理等按钮只认鼠标):mouse_click_mode 由前端打开;
每次这样的点按 mouse_click_seq 加一,前端看到变化就在 (mouse_click_x, mouse_click_y) 发一次界面鼠标点击,不再按 A
Taps outside the item area go through mouse clicks (pause menu buttons and the close / repair buttons inserted back into the layout only respond to the mouse): mouse_click_mode is turned on by the front end;
each such tap increments mouse_click_seq, and on seeing a change the front end sends one UI mouse click at (mouse_click_x, mouse_click_y) and no longer presses A */
/* 拖放松手处(物品抬在手指上方的那个落点)是不是物品区:前端松手前置位。不是 = 拖到面板外 = 丢弃(指针回原处、到位后按 Y)。
holding = 光标上还拿着物品(上一次没放成):这时点物品区 = 放下(A),点别处不动
Whether the drag-and-drop release spot (the drop point where the item is lifted above the finger) is the item area: set by the front end before release. If not = dragged outside the panel = discard (pointer returns to the original spot and presses Y once in place).
holding = the cursor is still holding an item (the last drop did not succeed): then tapping the item area = put down (A), tapping elsewhere does nothing */
int pointer_release_item, holding; float release_x, release_y;
/* 游戏态(没开面板)的点按 = 点游戏世界:手指没落在任何控件目标上(含落在摇杆区但没拖动)、按下到抬起不到 0.35 秒、位移不超过点按阈值
→ world_tap_seq 加一,前端看到变化调宿主 dm_world_tap(点物品名拾取 / 点 NPC 对话 / 点箱子,点空地什么都不发)。
A tap in game state (no panel open) = tap the game world: the finger did not land on any widget target (including landing in the stick area without dragging), less than 0.35 seconds from press to lift, displacement within the tap threshold
→ world_tap_seq is incremented, and on seeing a change the front end calls the host's dm_world_tap (tap an item name to pick up / tap an NPC to talk / tap a chest; tapping empty ground sends nothing). */
unsigned world_tap_seq; float world_tap_x, world_tap_y;
int close_left; double close_next_s; /* 面板外点按后还要按几下 B、下一下最早什么时候(按到面板关掉为止) | After a tap outside the panel, how many more B presses remain and the earliest time of the next one (press until the panel is closed) */
/* 商人页:这次按下落在货架的货上(前端按宿主命中结果 7 置位)。从货上起拖 = 想买:不发「拿起」、光标留在那件货上(宿主买的是光标选中的那件);
松手时 shop_drop_seq 加一,前端按落点决定——落在背包类物品区 = 买,拖回货架 / 面板外 / 别处 = 不买
Vendor page: this press landed on goods on the shelf (set by the front end on host hit result 7). A drag starting from goods = intent to buy: do not send "pick up", and the cursor stays on that item (the host buys the item the cursor has selected);
on release shop_drop_seq is incremented and the front end decides by the drop point -- landing in an inventory-type item area = buy; dragged back to the shelf / outside the panel / elsewhere = do not buy */
int pointer_shop; unsigned shop_drop_seq;
int pointer_lock; /* 单件任务槽里有东西时按在别的物品上(宿主命中结果 10):照物品区移光标出说明,但不拿起、双击 / 长按 / 单击都不动它,也不把槽里那件放过来 | Pressing on another item while the single-item quest slot holds something (host hit result 10): move the cursor and show the tooltip as in the item area, but do not pick it up; double tap / long press / single tap do not move it, and the item in the slot is not placed here either */
/* 高级仓库的成叠格(前端按宿主命中结果 8 置位):别的都照物品区,只有双击不同——stack_take_seq 加一,前端调宿主 dm_stash_take(1) 取 1 件到背包 | Stacked cell of the advanced stash (set by the front end on host hit result 8): everything else follows the item area, only double tap differs -- stack_take_seq is incremented and the front end calls the host's dm_stash_take(1) to take 1 into the inventory */
int pointer_stack; unsigned stack_take_seq;
unsigned ident_seq; /* 物品区双击了一件未鉴定物品的次数(只有未鉴定时双击 = 免费鉴定,各页都先判这一条):前端看到变化调宿主 dm_ui_identify_hovered | Number of double taps on an unidentified item in the item area (only when unidentified does double tap = free identify, and this rule is checked first on every page): on seeing a change the front end calls the host's dm_ui_identify_hovered */
unsigned use_seq; /* 物品区双击的次数(没开箱子时):前端看到变化调宿主 dm_ui_use_item——按光标下物品走原生的使用 / 购买 / 装备,不等「按住 A」的门槛 | Number of double taps in the item area (when no stash is open): on seeing a change the front end calls the host's dm_ui_use_item -- performs the native use / buy / equip on the item under the cursor without waiting for the "hold A" threshold */
unsigned item_tap_seq; /* 物品区单击的次数(前端看到变化调宿主 dm_ui_item_tap:鉴定态下单击物品 = 鉴定它) | Number of single taps in the item area (on seeing a change the front end calls the host's dm_ui_item_tap: in identify state, single-tapping an item = identify it) */
unsigned long_press_seq; /* 物品区按住不动满长按时长的次数(前端看到变化调宿主 dm_ui_long_press:背包药水 → 腰带) | Number of times the item area was held still for the full long-press duration (on seeing a change the front end calls the host's dm_ui_long_press: inventory potion → belt) */
unsigned tab_tap_seq; /* 点按落在页签上的次数(前端看到变化调宿主 dm_ui_tab_go) | Number of taps that landed on a tab (on seeing a change the front end calls the host's dm_ui_tab_go) */
int mouse_click_mode; unsigned mouse_click_seq; float mouse_click_x, mouse_click_y;
/* 前端临时改写「面板内非物品区的点按」:非 0 = 不发鼠标点击,改成手柄光标走到触点、到位后按这个键(技能绑定流程里点技能 = 光标到它身上按 Y)。页签 / 面板外照旧 | Temporary front-end rewrite of "taps inside a panel outside the item area": non-zero = send no mouse click; instead the controller cursor walks to the touch point and presses this key on arrival (tapping a skill in the skill binding flow = cursor onto it and press Y). Tabs / outside the panel behave as before */
uint64_t tap_button; float tap_x, tap_y; int tap_move; unsigned tap_move_seq; /* tap_move:本次点按只把光标移到 tap_x / tap_y,不发点击(技能图标 / 属性「+」:先选中、再确认) | tap_move: this tap only moves the cursor to tap_x / tap_y and sends no click (skill icon / attribute "+": select first, then confirm) */
double pulse_hold_s;
double last_tap_s; float last_tap_x, last_tap_y;
double stash_x_check_s; float stash_x_x, stash_x_y; unsigned stash_x_id; /* 开着箱子双击背包物品先发了 X:到这个时刻那件还在光标下(游戏没收这下 X)就退回按住 Y | With the stash open, double-tapping an inventory item sent X first: if at this time the item is still under the cursor (the game did not accept that X), fall back to hold Y */
uint64_t pointer_pending_button; double pointer_pending_hold;
/* 难度:diff_open = 选择条展开;diff_request = 刚选中的人数档(1–8),前端交给宿主 dm_hud_request_players 后清零 | Difficulty: diff_open = selector bar expanded; diff_request = the player-count level just selected (1–8), cleared after the front end hands it to the host's dm_hud_request_players */
int diff_open, diff_request;
/* 腰带展开(原版键鼠「显示腰带」的那几排,手柄版没有入口):身上的腰带多于 1 排时,在腰带格上向上滑 = 展开、向下滑 / 点别处 = 收起,
展开后点上面几排的药 = 喝。belt_rows / belt_open 由前端每次触摸前按宿主读数写入;belt_request 前端取走后清零:
1 展开,2 收起,0x100 | 排 << 4 | 列 = 喝那一格(排 1–3 = 底排之上第几排)
Belt expansion (the rows of the original game's keyboard-and-mouse "show belt"; the controller version has no entry for it): when the worn belt has more than 1 row, swiping up on a belt cell = expand, swiping down / tapping elsewhere = collapse,
and after expansion tapping a potion in the upper rows = drink. belt_rows / belt_open are written by the front end from host readings before each touch; belt_request is cleared after the front end takes it:
1 expand, 2 collapse, 0x100 | row << 4 | column = drink that cell (row 1–3 = which row above the bottom row) */
int belt_rows, belt_open, belt_request;
/* 腰带点一下 = 自己喝,松手那一刻就喝,点几下喝几瓶;不判双击、腰带上不做喂雇佣兵的手势 | one tap on the belt = the player drinks, at the moment of release, several taps drink several; no double-tap detection, no mercenary feeding gesture on the belt */
int belt_gap_cell; double belt_gap_at; /* 按着第二组技能时要喝药:先把 ZL 和技能键松开、空出 DM_TC_ZL_LEAD_S,到 belt_gap_at 才按腰带键(belt_gap_cell = 等着的那一格,0 = 没有) | to drink a potion while a skill of the second skill set is held: first release ZL and the skill key and leave a gap of DM_TC_ZL_LEAD_S, and only at belt_gap_at press the belt key (belt_gap_cell = the cell that is waiting, 0 = none) */
double joy_lost_s; float joy_lost_x, joy_lost_y; /* 摇杆手指被系统取消的时刻与当时的位置(0 = 没有):紧接着在附近重新落下的手指接着当摇杆 | time and position at which the joystick finger was cancelled by the system (0 = none): a finger landing again nearby right afterwards continues as the joystick */
int joy_block; /* 讲话文字框单独开着(前端不进面板态):这时落在底座上的手指不起摇杆,照旧只当一次点击(关讲话框)。前端按面板栈写 | speech text box open on its own (the front end does not enter panel state): a finger on the base starts no stick and is still just one click (closes the speech box). Written by the front end from the panel stack */
double belt_pulse_s; /* 最近一次「给玩家喝」的腰带脉冲还在发的时刻:其间按着的第二组技能连同 ZL 一起让开,收回后 ZL 重新领先 DM_TC_ZL_LEAD_S 技能键才回来 | Time until which the most recent "player drinks" belt pulse is still being sent: during it the held second-set skill gives way together with ZL, and after the release ZL again leads by DM_TC_ZL_LEAD_S before the skill key comes back */
int belt_q; /* 此刻有别的脉冲在发 / 别的补发在等:排着,空了再落地(不互相盖掉)。值 = 格 | another pulse is being sent / another resend is pending: queue and fire when free (they never overwrite each other). Value = cell */
} dm_tc_state;
/* 原版UI消息驱动,不根据输入键猜面板。AutoMap是战斗叠加,不切导航。 | Driven by the original game's UI messages; panels are not guessed from input keys. AutoMap is a combat overlay and does not switch to navigation. */
typedef struct { int game; uint64_t panels; } dm_tc_scene;
int dm_tc_navigation(dm_tc_scene *scene, const char *cat, const char *act, const char *arg);
int dm_tc_scene_dialog_only(const dm_tc_scene *scene); /* 只开着 NPC 对话菜单 | Only the NPC dialog menu is open */
int dm_tc_scene_dead(void); /* 死亡弹窗开着(导航态,但不给手柄圆钮) | Death popup open (navigation state, but no controller round buttons) */
/* 坐标使用 UIKit 点;布局本身不画球、不声称游戏已绑定回城/腰带。 | Coordinates use UIKit points; the layout itself does not draw the orbs and does not claim the game has bound town portal/belt. */
/* 安全区左右内缩(点);在 init / resize 之前设,之后的布局按它把右侧技能键组与左摇杆移进安全区。缺省 0。 | Left/right safe-area insets (points); set before init / resize, and the layout afterwards uses them to move the right-side skill key group and the left stick into the safe area. Default 0. */
void dm_tc_set_safe_insets(float left, float right);
void dm_tc_set_edge_bottom(float bottom); /* 屏幕底边归系统的那一条的高度(点);0 = 没有。只约束移动摇杆的起手 | Height (points) of the strip along the bottom edge of the screen that belongs to the system; 0 = none. Constrains only where the movement stick may start */
void dm_tc_layout_make(dm_tc_layout *layout, float width, float height);
int dm_tc_hit(const dm_tc_layout *layout, float x, float y);
#define DM_TC_POINTER_LIFT_PT 40.0f // 功能页拖动时物品抬在手指上方的点数(× 控件缩放) | Number of points the item is lifted above the finger while dragging on function pages (× widget scale)
void dm_tc_set_tall_scale(int on); // 画面高 > 440 点时按 高/440 放大的开关;缺省关(Mac 宿主触屏用例传的是像素数,不能放大),iOS 前端建视图时开 | Switch for scaling up by height/440 when picture height > 440 points; default off (the Mac host touch test cases pass pixel counts and must not be scaled up); the iOS front end turns it on when creating the view
float dm_tc_scale_for_size(float width, float height); // 控件缩放:手机 min(1, 宽/667, 高/375);画面高 > 440 点(iPad)时按 高/440 等比放大 | Widget scale: phone min(1, width/667, height/375); when picture height > 440 points (iPad), scale up proportionally by height/440
void dm_tc_init(dm_tc_state *state, float width, float height);
/* 尺寸变更会取消全部触点,调用者随后推送归零状态。 | A size change cancels all touch points, and the caller then pushes the zeroed state. */
void dm_tc_resize(dm_tc_state *state, float width, float height);
/* 控件开关不改变布局;切换有效位时取消已有触点。 | Widget switches do not change the layout; existing touch points are cancelled when the valid bits are toggled. */
void dm_tc_enable_targets(dm_tc_state *state, uint32_t mask);
/* 导航模式(面板 / 对话 / 前端页开着)下可用的控件:右侧五个虚拟手柄圆钮(确认 / 返回 / 操作 / 绑定 / 下一页 = A B X Y R)。
底栏十字位置的「关闭」不再给:面板的关闭入口只留一个(外框右上角的关闭按钮;圆钮还在时另有「返回」)。
pad = 0:五个圆钮也不给(局内手指直接点界面接上之后用,开关 DM_TOUCH_NAV_PAD=0,缺省 1)。两个前端共用这一处,不各写各的。
Widgets available in navigation mode (a panel / dialog / front-end page is open): the five virtual controller round buttons on the right (confirm / back / action / bind / next page = A B X Y R).
The "close" at the bottom bar's cross position is no longer offered: only one close entry for panels remains (the close button at the top-right corner of the frame; while the round buttons are present there is also "back").
pad = 0: the five round buttons are not offered either (used once in-run fingers tapping the UI directly is hooked up; switch DM_TOUCH_NAV_PAD=0, default 1). Both front ends share this one place and do not each write their own. */
static inline uint32_t dm_tc_nav_mask(int pad) { return pad ? ((1u<<DM_TC_MAIN)|(1u<<DM_TC_SKILL1)|(1u<<DM_TC_SKILL2)|(1u<<DM_TC_SKILL3)|(1u<<DM_TC_SKILL4)) : 0; }
/* 模式变化释放全部手势;导航模式只按键,不启用技能拖拽和地图取消区。 | A mode change releases all gestures; navigation mode only presses keys and does not enable skill dragging or the map cancel area. */
void dm_tc_set_navigation_mode(dm_tc_state *state, int navigation_mode);
void dm_tc_set_joy_block(dm_tc_state *state, int block); /* 讲话文字框 / 对话菜单单独开着:落在底座上的手指不起摇杆、只当一次点击 | speech text box / dialogue menu open on its own: a finger on the base starts no stick and is just one click */
/* 只取消回城控件拥有的core触点;物理触点由前端保留。 | Cancel only the core touch point owned by the town-portal widget; the physical touch point is kept by the front end. */
void dm_tc_set_portal_button(dm_tc_state *state, uint64_t mask);
void dm_tc_set_portal_binding(dm_tc_state *state, uint64_t mask, uint64_t binding_identity, uint64_t scene_epoch);
/* 反馈确认仅作用于仍持有且身份/场景/请求一致的pending手势;返回是否首次armed。 | Feedback confirmation applies only to a pending gesture that is still held and whose identity/scene/request match; returns whether it was armed for the first time. */
int dm_tc_portal_ack(dm_tc_state *state, uint64_t gesture_epoch, uint64_t binding_identity, uint64_t scene_epoch);
void dm_tc_cancel_portal(dm_tc_state *state);
void dm_tc_begin(dm_tc_state *state, int slot, float x, float y);
void dm_tc_move(dm_tc_state *state, int slot, float x, float y);
void dm_tc_end(dm_tc_state *state, int slot);
void dm_tc_begin_at(dm_tc_state *state, int slot, float x, float y, double now_s);
void dm_tc_move_at(dm_tc_state *state, int slot, float x, float y, double now_s);
void dm_tc_end_at(dm_tc_state *state, int slot, double now_s);
void dm_tc_tick(dm_tc_state *state, double now_s);
void dm_tc_cancel_all(dm_tc_state *state);
void dm_tc_cancel_finger(dm_tc_state *state, int slot); /* 系统取消这根手指:不当松手,只放掉它按着的东西 | The system cancels this finger: do not treat it as a release, only let go of what it was holding */
/* 结束 epoch 对应的施放脉冲;返回是否有变化(调用者随后推送) | End the cast pulse corresponding to epoch; returns whether anything changed (the caller then pushes) */
int dm_tc_pulse_end(dm_tc_state *state, uint64_t pulse_epoch);
// 收回后还有排着的指针脉冲(拖放的「放下」在「拿起」没收时就到了):前端等游戏看到一次松开后调 resume 开始它
// After release there is still a queued pointer pulse (the "put-down" of a drag-and-drop arrived before the "pick-up" was released): the front end waits until the game has seen a release once, then calls resume to start it
int dm_tc_pulse_pending(const dm_tc_state *state);
void dm_tc_pointer_press(dm_tc_state *state, float x, float y, uint64_t button); /* 光标到 (x, y) 再按一下 button;当前指针手指记为「长按已处理」,松手不再算点按 | Cursor to (x, y), then press button once; the current pointer finger is marked "long press handled" and its release no longer counts as a tap */
void dm_tc_pointer_item(dm_tc_state *state, int kind); /* 指针手指的命中结果一出来就调(最晚松手前):1 = 物品区,2 = 页签,3 = 面板外(点按 = 关面板),其余 = 面板内别处(点按 = 鼠标点击) | Called as soon as the pointer finger's hit result is available (before release at the latest): 1 = item area, 2 = tab, 3 = outside the panel (tap = close the panel), anything else = elsewhere inside the panel (tap = mouse click) */
void dm_tc_pointer_release(dm_tc_state *state, int kind); /* 拖放松手前调:宿主的落点判定(1 放在抬起点 / 4 放在手指点 / 3 丢弃 / 0 放回原处) | Called before a drag-and-drop release: the host's drop decision (1 place at the lifted point / 4 place at the finger point / 3 discard / 0 put back where it was) */
void dm_tc_pointer_release_at(dm_tc_state *state, float x, float y); /* 拖放松手前调:放在这个位置(宿主算的,装备槽 = 槽心) | Called before a drag-and-drop release: place at this position (computed by the host; equipment slot = slot center) */
void dm_tc_set_holding(dm_tc_state *state, int holding);
void dm_tc_set_cur_stack(unsigned id); /* 仓库开着时光标此刻指着的背包物品的 id(指着仓库一侧 / 没指着 = 0) | id of the inventory item the cursor is pointing at right now while the stash is open (pointing at the stash side / pointing at nothing = 0) */
void dm_tc_set_hover_unid(unsigned id); /* 光标此刻指着的我方未鉴定物品 id(宿主 dm_ui_hover_unid):物品区双击先判它——非 0 = 鉴定(ident_seq 加一),不走各页原来的双击 | id of our unidentified item the cursor is pointing at right now (host dm_ui_hover_unid): an item-area double tap checks it first -- non-zero = identify (ident_seq incremented), skipping each page's original double tap */
void dm_tc_set_tap_box(int on); /* 最近一次单击的物品是不是魔盒(开着箱子时双击魔盒 = 打开) | Whether the most recently single-tapped item is the cube (with the stash open, double-tapping the cube = open) */
void dm_tc_set_panel_state(int bits); /* 宿主读游戏面板树得到的状态位(1 储藏箱开着 / 2 商人页 / 4 死亡弹窗);界面消息 DM:PanelState 到来时前端调 | State bits the host obtains by reading the game panel tree (1 stash open / 2 vendor page / 4 death popup); the front end calls this when the UI message DM:PanelState arrives */
void dm_tc_set_iso_fix(int on); /* 移动摇杆斜向预修正开关(缺省开;测量改前改后用) | Switch for the movement stick's diagonal pre-correction (default on; used to measure before and after the change) */
int dm_tc_belt_outside(const dm_tc_state *state, float x, float y);
#define DM_TC_AIM_SETTLE_S 0.08 /* 技能钮按下后等这么久判定是点按还是拖动(拖过死区就提前键下) | After a skill button is pressed, wait this long to decide tap versus drag (dragging past the dead zone puts the key down early) */
#define DM_TC_BELT_SWIPE_PT 24 /* 腰带格上松手时纵向位移过这么多点 = 展开 / 收起;不到 = 点按(喝) | On release over a belt cell, vertical displacement beyond this many points = expand / collapse; less = tap (drink) */
#define DM_TC_KEY_MIN_S 0.035 /* 技能键至少按住这么久(约 2 帧);不够的松手时补成脉冲,保证游戏读到 | A skill button is held at least this long (about 2 frames); a shorter one is made up as a pulse on release to guarantee the game reads it */
#define DM_TC_JOY_RESUME_S 0.35 /* 摇杆那根手指被系统取消后,这么久之内在原处附近重新落下的手指接着当摇杆(不要求落在底座附近) | after the joystick finger is cancelled by the system, a finger landing again near the same spot within this long continues as the joystick (landing near the base is not required) */
#define DM_TC_JOY_GRAB_K 1.5f /* 手指落在离摇杆底座中心这么多倍半径之内才起摇杆(底座固定,不跟落指点) | the joystick starts only when a finger lands within this many radii of the joystick base center (the base is fixed and does not follow the touch-down point) */
#define DM_TC_ZL_LEAD_S 0.17 /* 修饰键领先主键的时间(约 10 帧;同一帧按下游戏只认主键) | Time the modifier key leads the main key (about 10 frames; pressed in the same frame, the game only recognizes the main key) */
#define DM_TC_DOUBLE_TAP_S 0.40 /* 两次单击间隔上限 | Upper limit of the interval between two single taps */
#define DM_TC_HOLD_USE_S 0.60 /* 「按住」动作的按住时长:Mac 宿主实测 0.25 s 只捡起、0.45 s 打开魔盒 | Hold duration of the "hold" action: measured on the Mac host, 0.25 s only picks up, 0.45 s opens the cube */
int dm_tc_pulse_resume(dm_tc_state *state);
#ifdef __cplusplus
}
#endif
+125
View File
@@ -0,0 +1,125 @@
#include "dm_touch_game_state.h"
#include "dm_touch_game_identity.h"
#include "../../host/dm.h"
enum { OBS_BINDING_GETTER=6, MAPPING_OFFSET=0x2d13cbc, BINDING_OFFSET=0x2d5f0c0 };
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static dm_tg_snapshot latest;
static dm_tg_group group;
static dm_tg_hud_cohort hud_cohort;
static int scene_game;
static uint64_t scene_epoch,world_epoch;
static const module_t *main_module;
void dm_touch_game_set_scene(int game,uint64_t scene,uint64_t world) {
pthread_mutex_lock(&lock);
if(world_epoch!=world)dm_tg_hud_reset(&hud_cohort,world);
if(scene_game!=game || scene_epoch!=scene || world_epoch!=world) {
scene_game=game;scene_epoch=scene;world_epoch=world;memset(&group,0,sizeof group);
int supported=latest.supported;memset(&latest,0,sizeof latest);latest.supported=supported;
latest.scene_epoch=scene;latest.world_epoch=world;latest.portal.slot=-1;
}
pthread_mutex_unlock(&lock);
}
int dm_touch_game_snapshot(dm_tg_snapshot *out) {
if(!out)return 0;
pthread_mutex_lock(&lock);*out=latest;pthread_mutex_unlock(&lock);return out->valid;
}
/* 只读render实例门;不学习cohort,不续反馈TTL,不写客体。未知一律原render。 | Read-only render instance gate; does not learn the cohort, does not extend the feedback TTL, does not write to the guest. Anything unknown gets the original render. */
int dm_touch_game_hide_own_glyph(uint64_t widget) {
int match=0;pthread_mutex_lock(&lock);
const module_t *m=main_module;uint64_t t=now_ns();
if(m && scene_game && scene_epoch && world_epoch && hud_cohort.confirmed && hud_cohort.seen==63 &&
hud_cohort.world_epoch==world_epoch && latest.supported && latest.valid && latest.ready &&
latest.identity_scope==DM_TG_IDENTITY_NATIVE && latest.source==DM_TG_SOURCE_NATIVE_GETTER &&
latest.scene_epoch==scene_epoch && latest.world_epoch==world_epoch &&
latest.hud_identity==hud_cohort.hud_identity && latest.group_seen==63 &&
latest.captured_ns && t>=latest.captured_ns && t-latest.captured_ns<=DM_TG_MAX_AGE_NS) {
for(unsigned i=0;i<6;i++)if(widget && widget==hud_cohort.widget[i]) {
/* 一次读完[widget,widget+c91):VT、enum(+b18)、alwaysGetAlt(+c90)。读失败=原render。object是静态的(在lock内),不占客体线程的栈。 | Read [widget,widget+c91) in one go: VT, enum (+b18), alwaysGetAlt (+c90). Read failure = original render. object is static (inside the lock) and does not use the guest thread's stack. */
static unsigned char object[0xc91];uint64_t vt=0;uint32_t slot=UINT32_MAX;
if(widget<=UINT64_MAX-0xc90 && dm_tg_vm_read(widget,object,sizeof object)) {
memcpy(&vt,object,8);memcpy(&slot,object+0xb18,4);
if(vt==(uint64_t)m->base+0x208a5f8 && slot==i && !object[0xc90])match=1;
}
break;
}
}
pthread_mutex_unlock(&lock);return match;
}
/* 诊断(DM_BINDING_DIAG=1):各返回点计数,每 3 秒一行;身份确认失败再按原因码细分(identity.c) | Diagnostic (DM_BINDING_DIAG=1): counts per return point, one line every 3 seconds; identity confirmation failures are further broken down by reason code (identity.c) */
static unsigned dg[8], dg_id[8]; static uint64_t dg_last;
static void diag_tick(void) {
static int on=-1; if(on<0) on=getenv("DM_BINDING_DIAG")!=NULL; if(!on) return;
uint64_t t=now_ns(); if(t-dg_last<3000000000ull) return; dg_last=t;
LOG("绑定诊断:调用 %u|寄存器不符 %u|槽越界 %u|组不符 %u|不在局内 %u|身份未确认 %u(原因 3:%u 4:%u 5:%u 6:%u 7:%u,LR 偏移 %#llx 槽 %u)|成功 %u|scene_game %d world %llu",
dg[0],dg[1],dg[2],dg[3],dg[4],dg[5],dg_id[3],dg_id[4],dg_id[5],dg_id[6],dg_id[7],(unsigned long long)dm_tg_identity_lr,dm_tg_identity_slot,dg[6],scene_game,(unsigned long long)world_epoch);
}
static int live_check; /* 真游戏里才开(要调游戏函数);单测的假模块上不开 | Turned on only in the real game (it calls game functions); not turned on for the unit tests' fake module */
void dm_touch_game_live_check(int on) { live_check=on; }
/* 槽里绑的技能玩家现在还有没有(摘掉给技能的装备后,那颗钮回到空位;装备穿回来原版把绑定接回、钮自己回来——所以不清原版绑定表,只在快照里按空位报)。
判法照原版选用技能时那段 main+0x43f1ac–0x43f23c:技能链表 [玩家+0x100] 里找「技能号、物品号(槽 +4;-1 = 自己学的)都相同」的节点,
等级 = 节点 +0x38(自己学的再加装备加成 0x5b1710),夹到版本上限后 > 0 才算有。读不到玩家 / 版本不认 = 不改判。只在游戏线程调(观测门里)
Whether the player still has the skill bound in the slot (after taking off the gear that grants the skill, that button goes back to an empty slot; when the gear is put back on, the original game reconnects the binding and the button comes back by itself -- so the original binding table is not cleared, and the slot is only reported as empty in the snapshot).
The check follows the original game's code for selecting a skill at main+0x43f1ac–0x43f23c: in the skill linked list [player+0x100], find the node whose "skill number and item number (slot +4; -1 = self-learned) are both the same",
level = node +0x38 (for a self-learned one, plus the gear bonus 0x5b1710), and it counts as owned only if > 0 after clamping to the version cap. Player unreadable / version not recognized = verdict unchanged. Called only on the game thread (inside the observation gate) */
static int skill_live(const unsigned char *b,uint32_t id,int32_t item) {
if(id==UINT32_MAX || id==359 || id==219 || id==220)return 1; /* 空位、回城卷轴 / 书(原版取槽时自己换号,按数量判)不归这里 | Empty slots and town portal scrolls / tomes (the original game swaps the number itself when fetching the slot, judged by quantity) are not handled here */
uint64_t pl=((uint64_t(*)(uint32_t))(b+0x45f9d0))(*(const uint32_t*)(b+0x2d20e4c)); if(!pl)return 1;
uint8_t ver=*(uint8_t*)(pl+0x1bd); if(ver<1 || ver>3)return 1;
uint64_t l=*(uint64_t*)(pl+0x100),n=l?*(uint64_t*)l:0;
for(int k=0;n && k<1024;k++,n=*(uint64_t*)(n+8)) { uint64_t r=*(uint64_t*)n;
if(!r || *(int16_t*)r!=(int16_t)id || *(int32_t*)(n+0x44)!=item)continue;
int lv=*(int32_t*)(n+0x38); if(item==-1)lv+=((int(*)(uint64_t,uint64_t,int))(b+0x5b1710))(pl,n,0);
int cap=**(int32_t**)(*(uint64_t*)(b+0x2d64a18+(uint64_t)ver*16)+0x1500); if(lv<0)lv=0; if(lv>cap)lv=cap;
return lv>0; }
{ int dm_swapskill_equipped(int32_t); return item!=-1 && dm_swapskill_equipped(item); } /* 副手组技能:物品还穿在换手那组上 = 按下会先换武器再放(dm_actions.c),照常显示、角标「II」 | Off-hand set skill: the item is still worn on the weapon-swap set = pressing will swap weapons first and then cast (dm_actions.c); shown as usual, with corner badge "II" */
}
static void binding_getter(const uint64_t *regs) {
const module_t *m=main_module;
dg[0]++; diag_tick();
if(!m || !regs || regs[10]!=(uint64_t)(m->base+BINDING_OFFSET) || regs[8]%DM_TG_STRIDE){dg[1]++;return;}
uint64_t effective=regs[8]/DM_TG_STRIDE;
uint32_t input_slot=(uint32_t)regs[19]; // PRE-ldr原getter arg,不是ID。 | PRE-ldr arg of the original getter, not an ID.
if(input_slot>=DM_TG_SLOTS || effective>=28 || effective<input_slot){dg[2]++;return;}
uint64_t selected_bank=effective-input_slot;
if(selected_bank!=0 && selected_bank!=16){dg[3]++;return;}
unsigned dead=0; /* 绑着但玩家现在没有的技能(位 = 槽)。要调游戏函数,放在取锁之前 | Skills that are bound but the player does not currently have (bit = slot). This calls a game function, so it is placed before taking the lock */
for(int i=0;live_check && i<DM_TG_SLOTS;i++) { uint32_t id;int32_t item;const unsigned char *e=(const unsigned char*)m->base+BINDING_OFFSET+(selected_bank+i)*DM_TG_STRIDE;memcpy(&id,e,4);memcpy(&item,e+4,4);
static uint32_t gone[32]; int live=skill_live((const unsigned char*)m->base,id,item); if(!live)dead|=1u<<i;
if(gone[selected_bank+i]!=(live?UINT32_MAX:id)) { gone[selected_bank+i]=live?UINT32_MAX:id; if(!live)LOG("技能钮:槽 %d 绑的技能 %u(物品 %d)玩家现在没有,按空位显示",(int)selected_bank+i,id,item); else LOG("技能钮:槽 %d 的技能回来了,照常显示",(int)selected_bank+i); } }
pthread_mutex_lock(&lock);
if(!scene_game || !world_epoch) {dg[4]++;pthread_mutex_unlock(&lock);return;} // menu/nav不学cohort。 | menu/nav do not learn the cohort.
uint64_t caller=0,hud=0;
#ifndef DM_TG_TEST_SYNTHETIC_IDENTITY
/* 不读内存的前置筛:HUD updater在main3e2f68把arg放进w23、3e2f6c再mov w0,w23后BL原Get;原Get只动x19-x21,
被调函数按AAPCS保x23,所以HUD这条调用到门时必有x23==x19(arg)。不等=不是HUD updater,同「savedLR不符」一样IGNORE,省掉读栈。
Pre-filter that reads no memory: at main3e2f68 the HUD updater puts arg into w23, at 3e2f6c it does mov w0,w23 and then BL to the original Get; the original Get only touches x19-x21,
and the callee preserves x23 per AAPCS, so when this HUD call reaches the gate x23==x19 (arg) must hold. Not equal = not the HUD updater; IGNORE just like "savedLR mismatch", saving the stack read. */
if(regs[23]!=regs[19]) {dg[5]++;dg_id[4]++;pthread_mutex_unlock(&lock);return;}
#endif
#ifdef DM_TG_TEST_SYNTHETIC_IDENTITY
int scope=dm_touch_game_test_identity(regs,&caller,&hud); // 仅独立SDK_STUB构建;不与生产符号碰撞。 | Only for the standalone SDK_STUB build; does not collide with production symbols.
#else
int scope=dm_tg_hud_identity(&hud_cohort,regs,(uint64_t)m->base,scene_game,world_epoch,dm_tg_vm_read,&caller,&hud);
#endif
if(scope==DM_TG_IDENTITY_UNCONFIRMED) {dg[5]++;if(dm_tg_identity_reason>=0&&dm_tg_identity_reason<8)dg_id[dm_tg_identity_reason]++;pthread_mutex_unlock(&lock);return;} // cache/unknown/readFail全IGNORE,不清HUD快照/不续时。 | cache/unknown/readFail are all IGNORE; do not clear the HUD snapshot / do not extend the time.
unsigned char mapping[72],bindings[DM_TG_SLOTS*DM_TG_STRIDE]={0};
memcpy(mapping,m->base+MAPPING_OFFSET,sizeof mapping);
for(int i=0;i<DM_TG_SLOTS;i++)memcpy(bindings+i*DM_TG_STRIDE,m->base+BINDING_OFFSET+(selected_bank+i)*DM_TG_STRIDE,4);
uint32_t observed_id;memcpy(&observed_id,m->base+BINDING_OFFSET+regs[8],4);
dm_tg_snapshot s;
dm_tg_parse(&s,mapping,sizeof mapping,bindings,sizeof bindings,(int)selected_bank,(int)input_slot,(int)effective,observed_id,now_ns());
for(int i=0;i<DM_TG_SLOTS;i++)if(s.valid && (dead>>i&1) && !(s.portal.valid && s.portal.slot==i))s.raw_skill_id[i]=UINT32_MAX;
s.scene_epoch=scene_epoch;s.world_epoch=world_epoch;
dm_tg_group_observe(&group,&s,scene_game,scene_epoch,caller,hud,scope);latest=group.completed;dg[6]++;
pthread_mutex_unlock(&lock);
}
int dm_touch_game_attach(void) {
main_module=NULL;
pthread_mutex_lock(&lock);int supported=gate_obs_present(OBS_BINDING_GETTER);memset(&latest,0,sizeof latest);
latest.supported=supported;latest.scene_epoch=scene_epoch;latest.world_epoch=world_epoch;latest.portal.slot=-1;memset(&group,0,sizeof group);
pthread_mutex_unlock(&lock);
if(!supported)return 0;
if(g_nmod<1 || strcmp(g_mod[0].name,"main") || !g_mod[0].base ||
g_mod[0].size<BINDING_OFFSET+32*DM_TG_STRIDE || g_mod[0].size<MAPPING_OFFSET+72)return 0;
main_module=&g_mod[0];gate_obs_set(OBS_BINDING_GETTER,binding_getter);return 1;
}
+56
View File
@@ -0,0 +1,56 @@
#include "dm_touch_game_identity.h"
#include <string.h>
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/vm_map.h>
#endif
int dm_tg_vm_read(uint64_t address,void *out,size_t bytes) {
if(!out || !bytes || !address || address>UINT64_MAX-bytes)return 0;
#ifdef __APPLE__
vm_size_t copied=0;
kern_return_t rc=vm_read_overwrite(mach_task_self(),(vm_address_t)address,(vm_size_t)bytes,(vm_address_t)out,&copied);
return rc==KERN_SUCCESS && copied==bytes;
#else
(void)address;return 0;
#endif
}
/* 诊断(DM_BINDING_DIAG):最近一次的返回原因码与读到的 LR / 槽号,供 bridge 计数(v4 后快照全空,查卡在哪个返回点) | Diagnostic (DM_BINDING_DIAG): the most recent return reason code and the LR / slot number read, for bridge to count (after v4 the snapshot is entirely empty; find which return point it is stuck at) */
int dm_tg_identity_reason; uint64_t dm_tg_identity_lr; uint32_t dm_tg_identity_slot;
void dm_tg_hud_reset(dm_tg_hud_cohort *c,uint64_t world) {memset(c,0,sizeof(*c));c->world_epoch=world;}
static uint64_t add(uint64_t h,uint64_t v) {
for(int i=0;i<8;i++){h^=(unsigned char)(v>>(i*8));h*=1099511628211ull;}return h;
}
int dm_tg_hud_identity(dm_tg_hud_cohort *c,const uint64_t *regs,uint64_t base,int game,uint64_t world,
dm_tg_read_fn read_fn,uint64_t *caller,uint64_t *hud) {
dm_tg_identity_reason=1;
if(!caller || !hud)return DM_TG_IDENTITY_UNCONFIRMED;
*caller=*hud=0;
if(!c || !regs || !read_fn)return DM_TG_IDENTITY_UNCONFIRMED;
if(c->world_epoch!=world)dm_tg_hud_reset(c,world);
uint32_t arg=(uint32_t)regs[19];
dm_tg_identity_reason=3;
if(!game || !world || arg>=12 || base>UINT64_MAX-0x3e2f74)return DM_TG_IDENTITY_UNCONFIRMED;
dm_tg_identity_reason=4;
/* 原Get栈帧一次读完:fp-8=调用者x19(widget)、fp=上一帧fp、fp+8=savedLR;三者同在原Get序言刚写下的0x30字节帧里。 | Read the original Get's stack frame in one go: fp-8 = caller's x19 (widget), fp = previous frame's fp, fp+8 = savedLR; all three are in the 0x30-byte frame the original Get's prologue has just written. */
uint64_t fp=regs[29],frame[3]={0},lr=0,widget=0;
if(fp<8 || fp>UINT64_MAX-16 || !read_fn(fp-8,frame,sizeof frame))return DM_TG_IDENTITY_UNCONFIRMED;
widget=frame[0];lr=frame[2];dm_tg_identity_lr=lr-base;
if(lr!=base+0x3e2f74 || !widget || widget>UINT64_MAX-0xc90)return DM_TG_IDENTITY_UNCONFIRMED;
/* widget的enum(+b18)与alwaysGetAlt(+c90)同一对象内,一次读[+b18,+c91)。 | The widget's enum (+b18) and alwaysGetAlt (+c90) are inside the same object; read [+b18,+c91) in one go. */
uint32_t slot=UINT32_MAX;unsigned char always_alt=255;static unsigned char span[0xc91-0xb18]; /* 调用方(bridge 的门回调)持锁;不占客体线程的栈 | The caller (bridge's gate callback) holds the lock; does not use the guest thread's stack */ dm_tg_identity_reason=5;
if(read_fn(widget+0xb18,span,sizeof span)){memcpy(&slot,span,4);always_alt=span[0xc90-0xb18];}
if(slot>=6 || always_alt ||
(arg!=slot && arg!=slot+6)) { dm_tg_identity_slot=slot; return DM_TG_IDENTITY_UNCONFIRMED; }
dm_tg_identity_reason=6; dm_tg_identity_slot=slot;
if(c->widget[slot] && c->widget[slot]!=widget)return DM_TG_IDENTITY_UNCONFIRMED;
for(unsigned i=0;i<6;i++)if(i!=slot && c->widget[i]==widget)return DM_TG_IDENTITY_UNCONFIRMED;
if(c->confirmed){*caller=lr;*hud=c->hud_identity;dm_tg_identity_reason=0;return DM_TG_IDENTITY_NATIVE;}
dm_tg_identity_reason=7; /* 学习中:六槽未齐 | Learning: the six slots are not all filled yet */
c->widget[slot]=widget;c->seen|=1u<<slot;
if(c->seen==63) {
uint64_t h=add(1469598103934665603ull,world);for(int i=0;i<6;i++)h=add(h,c->widget[i]);
c->hud_identity=h?h:1;c->confirmed=1;
}
/* 首组六体只确认cohort,不把第六体借给反馈组;下一个原frame完整六组才ready。 | The first group of six only confirms the cohort and does not lend the sixth one to the feedback group; ready only once the next original frame has the complete six groups. */
return DM_TG_IDENTITY_UNCONFIRMED;
}
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "dm_touch_game_state.h"
typedef struct {
uint64_t world_epoch, widget[6], hud_identity;
uint32_t seen;
int confirmed;
} dm_tg_hud_cohort;
typedef int (*dm_tg_read_fn)(uint64_t address, void *out, size_t bytes);
/* 同进程Mach只读,不直接解引用未知FramePointer或widget堆地址。 | Same-process Mach read-only; never dereference an unknown FramePointer or widget heap address directly. */
int dm_tg_vm_read(uint64_t address, void *out, size_t bytes);
void dm_tg_hud_reset(dm_tg_hud_cohort *cohort, uint64_t world_epoch);
/* 首组六指针只确认cohort;返回身份从下一帧六组开始,不追认替换指针。 | The first group of six pointers only confirms the cohort; identity is returned starting from the next frame's six groups, and replaced pointers are not recognized retroactively. */
extern int dm_tg_identity_reason; extern uint64_t dm_tg_identity_lr; extern uint32_t dm_tg_identity_slot; /* 诊断用 | For diagnostics */
int dm_tg_hud_identity(dm_tg_hud_cohort *cohort, const uint64_t *regs,
uint64_t main_base, int game_no_panel, uint64_t world_epoch,
dm_tg_read_fn read_fn, uint64_t *caller, uint64_t *hud);
+83
View File
@@ -0,0 +1,83 @@
#include "dm_touch_game_state.h"
#include "../../host/dm_input.h"
#include <string.h>
static uint32_t u32(const unsigned char *p) {
return (uint32_t)p[0]|(uint32_t)p[1]<<8|(uint32_t)p[2]<<16|(uint32_t)p[3]<<24;
}
static uint64_t sdk(uint32_t logical) {
switch(logical) {
case 0x1000:return DM_BTN_B; case 0x2000:return DM_BTN_A;
case 0x4000:return DM_BTN_Y; case 0x8000:return DM_BTN_X;
case 0x200:return DM_BTN_R; case 0x800:return DM_BTN_ZR;
default:return 0;
}
}
static int portal(uint32_t id) { return id==359 || id==219 || id==220; }
int dm_tg_parse(dm_tg_snapshot *out,const void *mapping,size_t mapping_bytes,
const void *bank,size_t bank_bytes,int selected_bank,int getter_input_slot,
int observed_index,uint32_t observed_id,uint64_t captured_ns) {
if(!out)return 0;
memset(out,0,sizeof(*out)); out->supported=1;out->portal.slot=-1;
if(!mapping || !bank || mapping_bytes<DM_TG_FACETS*12 || bank_bytes<DM_TG_SLOTS*DM_TG_STRIDE ||
(selected_bank!=0 && selected_bank!=16) || getter_input_slot<0 || getter_input_slot>=DM_TG_SLOTS ||
observed_index!=selected_bank+getter_input_slot) return 0;
dm_tg_snapshot s=*out; unsigned normals=0,alts=0; uint64_t logicals=0;
const unsigned char *m=mapping,*b=bank;
for(int i=0;i<DM_TG_FACETS;i++) {
dm_tg_mapping *t=&s.mapping[i]; t->logical=u32(m+i*12);t->normal=u32(m+i*12+4);t->alt=u32(m+i*12+8);
uint64_t bit=sdk(t->logical);
if(!bit || (logicals&bit) || t->normal>=6 || t->alt<6 || t->alt>=12 ||
(normals&(1u<<t->normal)) || (alts&(1u<<(t->alt-6))))return 0;
logicals|=bit;normals|=1u<<t->normal;alts|=1u<<(t->alt-6);
}
for(int i=0;i<DM_TG_SLOTS;i++)s.raw_skill_id[i]=u32(b+i*DM_TG_STRIDE);
if(s.raw_skill_id[observed_index-selected_bank]!=observed_id)return 0;
/* 先替代栏,再普通栏;每栏按原slot顺序确定唯一入口。 | Alternate bar first, then the normal bar; within each bar the unique entry is determined in the original slot order. */
for(int pass=0;pass<2 && !s.portal.valid;pass++)for(int slot=pass?0:6;slot<(pass?6:12);slot++) {
if(!portal(s.raw_skill_id[slot]))continue;
for(int i=0;i<DM_TG_FACETS;i++)if((pass?s.mapping[i].normal:s.mapping[i].alt)==(uint32_t)slot) {
s.portal=(dm_tg_portal){sdk(s.mapping[i].logical)|(pass?0:DM_BTN_ZL),s.raw_skill_id[slot],slot,1};break;
}
if(s.portal.valid)break;
}
s.valid=1;s.source=DM_TG_SOURCE_NATIVE_GETTER;s.selected_bank=selected_bank;s.getter_input_slot=getter_input_slot;
s.observed_index=observed_index;s.captured_ns=captured_ns;*out=s;return 1;
}
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *s,uint64_t host_now_ns) {
if(!s || !s->supported || !s->valid || !s->ready || !s->portal.valid || !s->captured_ns ||
host_now_ns<s->captured_ns || host_now_ns-s->captured_ns>DM_TG_MAX_AGE_NS)return 0;
return s->portal.buttons;
}
static uint64_t identity_add(uint64_t h,uint64_t value) {
for(int i=0;i<8;i++) { h^=(unsigned char)(value>>(i*8)); h*=1099511628211ull; }
return h;
}
static uint64_t binding_identity(const dm_tg_snapshot *s,uint64_t caller,uint64_t hud,int scope) {
uint64_t h=identity_add(1469598103934665603ull,(uint64_t)s->selected_bank);
h=identity_add(h,s->world_epoch);h=identity_add(h,caller);h=identity_add(h,hud);h=identity_add(h,(uint64_t)scope);
for(int i=0;i<DM_TG_FACETS;i++) {h=identity_add(h,s->mapping[i].logical);h=identity_add(h,s->mapping[i].normal);h=identity_add(h,s->mapping[i].alt);}
for(int i=0;i<DM_TG_SLOTS;i++)h=identity_add(h,s->raw_skill_id[i]);
return h?h:1;
}
int dm_tg_group_observe(dm_tg_group *g,const dm_tg_snapshot *table,int game,uint64_t scene,
uint64_t caller,uint64_t hud,int scope) {
if(!g || !table)return 0;
dm_tg_snapshot s=*table;s.ready=0;s.scene_epoch=scene;s.caller_identity=caller;s.hud_identity=hud;s.identity_scope=scope;
if(!s.valid || !game || !scene || !caller || !hud ||
(scope!=DM_TG_IDENTITY_NATIVE && scope!=DM_TG_IDENTITY_SYNTHETIC) ||
s.getter_input_slot<0 || s.getter_input_slot>=DM_TG_SLOTS) {
memset(g,0,sizeof(*g));g->completed=s;return 0;
}
s.binding_identity=binding_identity(&s,caller,hud,scope);s.secondary_group=s.getter_input_slot>=6;
int same=g->pending.binding_identity==s.binding_identity && g->pending.scene_epoch==scene &&
g->pending.world_epoch==s.world_epoch && g->pending.selected_bank==s.selected_bank && g->pending.caller_identity==caller && g->pending.hud_identity==hud && g->pending.identity_scope==scope &&
!memcmp(g->pending.mapping,s.mapping,sizeof s.mapping) && !memcmp(g->pending.raw_skill_id,s.raw_skill_id,sizeof s.raw_skill_id);
if(!same) { memset(g,0,sizeof(*g));g->completed=s; }
uint32_t bit=1u<<(s.getter_input_slot%6);
if(!same || g->pending.secondary_group!=s.secondary_group || (g->seen&bit)) {g->seen=0;g->started_ns=s.captured_ns;}
g->seen|=bit;s.group_seen=g->seen;s.group_started_ns=g->started_ns;g->pending=s;
if(g->seen!=63)return 0;
s.ready=1;g->completed=s;return 1;
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
enum { DM_TG_FACETS=6, DM_TG_SLOTS=12, DM_TG_STRIDE=28,
DM_TG_MAX_AGE_NS=250000000,
DM_TG_IDENTITY_UNCONFIRMED=0, DM_TG_IDENTITY_NATIVE=1, DM_TG_IDENTITY_SYNTHETIC=2,
DM_TG_SOURCE_NONE=0, DM_TG_SOURCE_NATIVE_GETTER=1 };
typedef struct { uint32_t logical, normal, alt; } dm_tg_mapping;
typedef struct {
uint64_t buttons;
uint32_t raw_skill_id;
int slot, valid;
} dm_tg_portal;
typedef struct {
uint64_t captured_ns, group_started_ns, scene_epoch, world_epoch, binding_identity, caller_identity, hud_identity;
int ready, secondary_group, identity_scope;
uint32_t group_seen;
/* valid只证明捕获表解析完整,不证明当前武器bank、ammo或游戏施法状态。 | valid only proves the captured table parsed completely; it does not prove the current weapon bank, ammo or the game's casting state. */
int supported, valid, source, selected_bank, getter_input_slot, observed_index;
dm_tg_mapping mapping[DM_TG_FACETS];
uint32_t raw_skill_id[DM_TG_SLOTS];
dm_tg_portal portal;
} dm_tg_snapshot;
/* 只解析已复制的32位小端原表;不读取客体内存、不调用客体getter。 | Parses only the already-copied 32-bit little-endian original table; does not read guest memory and does not call guest getters. */
int dm_tg_parse(dm_tg_snapshot *out, const void *mapping, size_t mapping_bytes,
const void *bank, size_t bank_bytes, int selected_bank, int getter_input_slot,
int observed_index, uint32_t observed_id, uint64_t captured_ns);
typedef struct { dm_tg_snapshot pending, completed; uint32_t seen; uint64_t started_ns; } dm_tg_group;
/* 单normal/alt组的六facet完整且身份/scene一致才ready。身份未知则不ready。 | ready only when the six facets of a single normal/alt group are complete and identity/scene match. If identity is unknown, not ready. */
int dm_tg_group_observe(dm_tg_group *group, const dm_tg_snapshot *table, int game,
uint64_t scene_epoch, uint64_t caller_identity, uint64_t hud_identity, int identity_scope);
/* host now_ns时间域;未来/零时间戳及年龄>250ms时Portal输入归零。 | host now_ns time domain; for future/zero timestamps and age >250ms the Portal input is zeroed. */
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *snapshot, uint64_t host_now_ns);
/* 生产桥:load_modules完成后的客体线程attach;UI只取锁内快照副本。 | Production bridge: attach on the guest thread after load_modules completes; the UI only takes a copy of the snapshot inside the lock. */
int dm_touch_game_attach(void);
/* 开:快照里把「绑着但玩家现在没有的技能」(如摘掉给技能的装备)按空位报;要调游戏函数,只在真游戏里开。 | On: in the snapshot, report "skills that are bound but the player does not currently have" (e.g. after taking off the gear that grants the skill) as empty slots; this calls game functions, so turn it on only in the real game. */
void dm_touch_game_live_check(int on);
int dm_touch_game_snapshot(dm_tg_snapshot *out);
void dm_touch_game_set_scene(int game_no_panel, uint64_t scene_epoch, uint64_t world_epoch);
#ifdef DM_TG_TEST_SYNTHETIC_IDENTITY
/* 仅SDK_STUB显式条件构建可提供此opaque seam;生产走strong Mach原HUD cohort。 | Only an explicitly conditional SDK_STUB build may provide this opaque seam; production uses the strong Mach original HUD cohort. */
int dm_touch_game_test_identity(const uint64_t *regs, uint64_t *caller_identity, uint64_t *hud_identity);
#endif
#ifdef __cplusplus
}
#endif
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "dm_touch_game_state.h"
enum { DM_TA_UNKNOWN=0, DM_TA_EMPTY=1, DM_TA_GLYPH=2, DM_TA_ATLASES=9 };
typedef struct { const char *asset; int width,height,frame_width,pitch,count; } dm_ta_atlas;
typedef struct { int x,y,width,height; } dm_ta_frame;
typedef struct { int status,atlas,normal_frame,pressed_frame,slot,effective_slot; uint32_t raw_skill_id; const char *reason; } dm_ta_glyph;
extern const dm_ta_atlas dm_ta_atlases[DM_TA_ATLASES];
extern const char dm_ta_manifest_sha[],dm_ta_geometry_sha[],dm_ta_binding_sha[];
dm_ta_glyph dm_ta_skill(uint32_t raw_skill_id);
dm_ta_glyph dm_ta_current(const dm_tg_snapshot *s,uint64_t sdk_button,uint64_t host_now_ns);
/* 同上,skill_set=1 取第二套(alt 槽,原版按住 ZL) | Same as above; skill_set=1 takes the second set (alt slots, hold ZL in the original game) */
dm_ta_glyph dm_ta_current_set(const dm_tg_snapshot *s,uint64_t sdk_button,uint64_t host_now_ns,int skill_set);
int dm_ta_frame_at(int atlas,int frame,dm_ta_frame *out);
+142
View File
@@ -0,0 +1,142 @@
// 构建号 + 新版本提示的 iOS 侧。
// 画面上的字和按钮是游戏自己的控件(布局 tools/touch_layout.py,写字与显隐 dm/host/dm_update.c);这里只管三件:
// ① 把自己的构建号(CFBundleVersion,与日志头「构建」同一个数)交给宿主,选角页左下角常显;
// ② 每次选角页出现(启动、从局里退回来)都在后台取一次版本文件(这是我们自己加的唯一一处联网,只读一个小文件,单次 10 秒超时、失败隔几秒重试共 3 次,不挡启动与进局;同一时刻只有一个查询在途);
// ③ 玩家点了「更新」→ 把版本文件里的安装链接交给系统打开(系统安装,整包覆盖,存档与资源不动)。
// 版本文件地址不在仓库里:出包脚本写进 Info.plist 的 SWUpdateURL(tools/adhoc.sh 传 DM_UPDATE_URL)。没有这个键、或构建号不是大于 1 的整数
// (开发签名包是 1)→ 不联网、不提示。不比自己新:画面上什么都不出;没网 / 超时 / 地址失效 / 格式不对:选角页构建号右边出一行失败提示(dm_update_fail:没有无线数据许可 → 提示去设置里允许;其余 → 提示去浏览器打开版本文件所在的站点),这次启动取到了就撤掉。
// 版本文件 latest.json(UTF-8)四个字段:{"build": 10051432, "note": "一句话 ≤ 24 个汉字", "urgent": false, "install_url": "…"},缺字段或类型不对 = 格式不对。
// 每次查完按新结果处理(不限一天一次,进首页就查、有新的就提示):比自己新 → 显示 / 换成这次的;不比自己新 → 撤掉已有提示;
// 取不到 / 格式不对 → 已有的提示留着不动(一次网络抖动不该把确实存在的新版本提示抹掉;这次启动还没提示过的话照旧什么都不出)。
// 测试注入(只影响这三件的输入,不设就是产品行为):DM_TEST_UPDATE_URL 换版本文件地址(可用 file://),DM_TEST_UPDATE_BUILD 换自己的构建号,
// DM_TEST_UPDATE_OPEN=0 点「更新」只记日志不真打开链接;DM_TEST_UPDATE_DENY=1 把取不到当成「无线数据许可被拒」。
// iOS side of the build number + new-version notice.
// The text and button on screen are the game's own widgets (layout in tools/touch_layout.py, text writing and show/hide in dm/host/dm_update.c); only three things are handled here:
// ① Hand our own build number (CFBundleVersion, the same number as 「构建」(Build) in the log header) to the host, always shown at the bottom-left of the character select page;
// ② Each time the character select page appears (launch, returning from a run), fetch the version file once in the background (this is the only network access we added ourselves; it reads one small file, 10-second timeout per attempt, retries a few seconds after a failure for 3 attempts in total, does not block launch or entering a run; only one query is in flight at any moment);
// ③ The player tapped 「更新」(Update) → hand the install link from the version file to the system to open (system install, whole-package overwrite, saves and assets untouched).
// The version file address is not in the repository: the packaging script writes it into SWUpdateURL in Info.plist (tools/adhoc.sh passes DM_UPDATE_URL). Without this key, or when the build number is not an integer greater than 1
// (dev-signed builds are 1) → no network access, no notice. Not newer than ours: nothing appears on screen; no network / timeout / dead address / bad format: a failure notice line appears to the right of the build number on the character select page (dm_update_fail: no wireless data permission → tell the player to allow it in Settings; otherwise → tell the player to open in a browser the site that serves the version file), removed once a fetch succeeds during this launch.
// The version file latest.json (UTF-8) has four fields: {"build": 10051432, "note": "one sentence, ≤ 24 Chinese characters", "urgent": false, "install_url": "..."}; a missing field or wrong type = bad format.
// After each query, act on the new result (not limited to once a day; query on entering the home page and show a notice if there is a new one): newer than ours → show / replace with this one; not newer than ours → remove the existing notice;
// fetch failed / bad format → leave the existing notice untouched (one network glitch should not erase a notice for a new version that really exists; if nothing has been shown yet during this launch, still show nothing as before).
// Test injection (affects only the inputs of these three things; unset = product behavior): DM_TEST_UPDATE_URL replaces the version file address (file:// is allowed), DM_TEST_UPDATE_BUILD replaces our own build number,
// DM_TEST_UPDATE_OPEN=0 makes tapping 「更新」(Update) only log without actually opening the link; DM_TEST_UPDATE_DENY=1 treats a failed fetch as "wireless data permission denied".
#import <UIKit/UIKit.h>
#import <Network/Network.h>
#include <stdatomic.h>
void plog(const char *fmt, ...);
void dm_update_init(int own_build, void (*on_select)(void), void (*on_click)(void)); // dm/host/dm_update.c
void dm_update_offer(int new_build, const char *note, int urgent);
void dm_update_safe_left(int units);
void dm_update_fail(int kind);
void dm_update_site(const char *host);
static NSString *g_url, *g_install; static int g_own; static _Atomic int g_inflight;
// 取不到时补一行系统眼里的网络状态:分清「手机没连网」和「这个 App 没拿到无线数据许可」(两种情况请求报的都是「没有网络」)。只读,不弹框
// When the fetch fails, add one line with the network state as the system sees it: tell apart "the phone is not connected" and "this App has not been granted wireless data permission" (in both cases the request reports "no network"). Read-only, no alert
static void upd_net_why(void) {
nw_path_monitor_t m = nw_path_monitor_create(); nw_path_monitor_set_queue(m, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
nw_path_monitor_set_update_handler(m, ^(nw_path_t p) {
static const char *st[] = { "无效", "通", "不通", "要先建连接" }, *why[] = { "系统没给原因", "蜂窝数据许可被拒", "无线局域网数据许可被拒", "本地网络许可被拒", "要先开 VPN" };
nw_path_status_t s = nw_path_get_status(p); nw_path_unsatisfied_reason_t r = nw_path_get_unsatisfied_reason(p);
plog("更新:系统网络路径 %s%s%s;无线局域网 %s、蜂窝 %s", s <= 3 ? st[s] : "未知", s == nw_path_status_satisfied ? "" : ",原因:", s == nw_path_status_satisfied ? "" : r <= 4 ? why[r] : "未知",
nw_path_uses_interface_type(p, nw_interface_type_wifi) ? "在用" : "没用上", nw_path_uses_interface_type(p, nw_interface_type_cellular) ? "在用" : "没用上");
// 选角页失败提示:系统说「数据许可被拒」= 玩家自己能在设置里开;其余 = 让玩家去浏览器手动更新
// Failure notice on the character select page: the system says "data permission denied" = the player can turn it on in Settings themselves; anything else = have the player update manually in a browser
const char *td = getenv("DM_TEST_UPDATE_DENY"); // 测试:=1 当成系统说「数据许可被拒」(Mac 上造不出这种现场) | Test: =1 behaves as if the system said "data permission denied" (this situation cannot be created on Mac)
int denied = (td && atoi(td)) || (s != nw_path_status_satisfied && (r == nw_path_unsatisfied_reason_cellular_denied || r == nw_path_unsatisfied_reason_wifi_denied));
dm_update_fail(denied ? 1 : 2); plog("更新:选角页显示%s", denied ? "「无法联网检查更新 · 请在设置里允许无线数据」" : "「检查更新失败 · 浏览器手动更新」");
nw_path_monitor_cancel(m);
});
nw_path_monitor_start(m);
}
// 版本文件 → 要不要提示。返回 nil = 提示(out 填好),否则是不提示的原因(进日志)
// Version file → whether to show a notice. Returns nil = show it (out is filled in); otherwise the reason for not showing it (goes to the log)
static NSString *upd_parse(NSData *d, int *build, NSString **note, int *urgent, NSString **install) {
NSDictionary *j = d ? [NSJSONSerialization JSONObjectWithData:d options:0 error:nil] : nil;
if (![j isKindOfClass:NSDictionary.class]) return @"格式不对:不是 JSON 对象";
NSNumber *b = j[@"build"], *u = j[@"urgent"]; NSString *n = j[@"note"], *i = j[@"install_url"];
if (![b isKindOfClass:NSNumber.class] || ![u isKindOfClass:NSNumber.class] || ![n isKindOfClass:NSString.class] || ![i isKindOfClass:NSString.class]) return @"格式不对:四个字段缺了或类型不对";
if (!(b.doubleValue >= 1 && b.doubleValue < 2e9) || b.doubleValue != b.intValue) return @"格式不对:build 不是正整数";
NSString *sch = [NSURL URLWithString:i].scheme.lowercaseString;
if (![sch isEqualToString:@"https"] && ![sch isEqualToString:@"itms-services"]) return @"格式不对:install_url 不是 https / itms-services 链接";
n = [[n componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet] componentsJoinedByString:@" "];
if (n.length > 24) n = [n substringWithRange:[n rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 24)]]; // 说明只有一行的位置:超过 24 个字截掉 | The note has room for only one line: truncate beyond 24 characters
*build = b.intValue; *note = n; *urgent = u.boolValue; *install = i; return nil;
}
static void upd_fetch(int n);
static void on_select(void) { // 宿主在游戏主线程调:选角页每出现一次调一次 | Called by the host on the game main thread: once each time the character select page appears
dispatch_async(dispatch_get_main_queue(), ^{ // 左安全区换成布局单位(2160 高)交给宿主,算法同 front_ios.m 给佣兵头像用的那处 | Convert the left safe area into layout units (2160 high) and hand it to the host; same algorithm as the place in front_ios.m used for the mercenary portrait
UIWindow *w = nil; for (UIScene *s in UIApplication.sharedApplication.connectedScenes) if ([s isKindOfClass:UIWindowScene.class]) { w = ((UIWindowScene *)s).windows.firstObject; if (w) break; }
const char *tl = getenv("DM_TEST_SAFE_L"); CGFloat l = tl ? atof(tl) : w.safeAreaInsets.left, hh = w.bounds.size.height; if (hh > 0) dm_update_safe_left((int)lround(l / hh * 2160));
});
if (!g_url) return;
if (atomic_exchange(&g_inflight, 1)) { plog("更新:上一次查询还没回来,这次不再发"); return; } // 同一时刻只有一个查询(含重试)在途 | Only one query (including retries) is in flight at any moment
upd_fetch(1);
}
// 一次查询最多试 UPD_TRIES 次(首页出过一次「检查更新失败」,服务端那段时间全是 200,请求多半没出手机)。
// 读代码能列出的客户端一次性失败:① 刚启动 / 刚回前台时系统网络路径还没就绪,waitsForConnectivity = NO 时立刻报 -1009;② 冷连接 DNS + TCP + TLS
// 在蜂窝上超过原先 5 秒的总时限(-1001);③ 每次新建会话、不复用连接,次次都是冷连接;④ DNS 首查失败(-1003)/ 连接中途丢(-1005)。
// 改:请求 10 秒、整体 15 秒;会话全程复用一个;失败隔 3 秒、6 秒再试,三次都失败才出失败提示(一次失败不出字);每次都记第几次、错误码。
// 不开 waitsForConnectivity:数据许可被拒时它会一直等到整体时限,玩家要多等十几秒才看到「去设置里允许」。
// 测试:DM_TEST_UPDATE_FAIL_FIRST=N 前 N 次故意查一个不存在的域名(造「一次失败、再试成功」)
// One query tries at most UPD_TRIES times (the home page once showed 「检查更新失败」(Update check failed) while the server returned all 200s during that period, so the request most likely never left the phone).
// One-off client failures that can be listed by reading the code: ① right after launch / returning to the foreground the system network path is not ready yet, and with waitsForConnectivity = NO it reports -1009 immediately; ② cold-connection DNS + TCP + TLS
// on cellular exceeds the former 5-second total limit (-1001); ③ a new session was created every time with no connection reuse, so every attempt was a cold connection; ④ the first DNS lookup fails (-1003) / the connection drops midway (-1005).
// Changes: request 10 seconds, overall 15 seconds; one session reused throughout; retry 3 seconds and 6 seconds after a failure, and show the failure notice only after all three fail (a single failure shows no text); log the attempt number and error code every time.
// waitsForConnectivity is not turned on: when the data permission is denied it waits until the overall limit, and the player would wait ten-odd more seconds before seeing 「去设置里允许」(Allow it in Settings).
// Test: DM_TEST_UPDATE_FAIL_FIRST=N deliberately queries a non-existent domain for the first N attempts (to create "fail once, succeed on retry")
#define UPD_TRIES 3
static void upd_fetch(int n) {
static NSURLSession *ses; static dispatch_once_t once;
dispatch_once(&once, ^{ NSURLSessionConfiguration *c = NSURLSessionConfiguration.ephemeralSessionConfiguration; c.timeoutIntervalForRequest = 10; c.timeoutIntervalForResource = 15;
c.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; c.waitsForConnectivity = NO; ses = [NSURLSession sessionWithConfiguration:c]; });
const char *tf = getenv("DM_TEST_UPDATE_FAIL_FIRST"); NSString *us = tf && n <= atoi(tf) ? @"https://nonexistent-dm.invalid/latest.json" : g_url;
NSURL *url = [NSURL URLWithString:us]; if (!url) { plog("更新:版本文件地址 %s 不是合法地址,不查", us.UTF8String); g_url = nil; atomic_store(&g_inflight, 0); return; }
[[ses dataTaskWithURL:url completionHandler:^(NSData *d, NSURLResponse *r, NSError *e) {
int build = 0, urgent = 0; NSString *note = nil, *install = nil, *why = nil;
if (e) why = [NSString stringWithFormat:@"取不到:%@", e.localizedDescription];
else if ([r isKindOfClass:NSHTTPURLResponse.class] && [(NSHTTPURLResponse *)r statusCode] != 200) why = [NSString stringWithFormat:@"取不到:HTTP %ld", (long)[(NSHTTPURLResponse *)r statusCode]];
else if (d.length > 4096) why = @"格式不对:超过 4096 字节";
else why = upd_parse(d, &build, &note, &urgent, &install);
if (!e && d.length && d.length <= 4096) { // 远程退回画法:版本文件里 "render_safe": true → 本局退回原画法;没有这个字段 = 新画法 | Remote fallback of the drawing method: "render_safe": true in the version file → this run falls back to the old drawing method; without this field = the new drawing method
NSDictionary *j = [NSJSONSerialization JSONObjectWithData:d options:0 error:nil]; NSNumber *rs = [j isKindOfClass:NSDictionary.class] ? j[@"render_safe"] : nil;
extern int g_dm_rt_ab; if ([rs isKindOfClass:NSNumber.class] && rs.boolValue) { if (g_dm_rt_ab) { g_dm_rt_ab = 0; plog("画法:版本文件 render_safe = true → 本局退回原画法"); } }
else plog("画法:版本文件没有 render_safe(或为 false)→ 新画法照常"); }
if (why) {
plog("更新:查 %s(第 %d / %d 次)→ %s%s", us.UTF8String, n, UPD_TRIES, why.UTF8String, n < UPD_TRIES ? ",稍后再试" : ",已有的提示不动");
if (e) plog("更新:第 %d 次取不到的错误码 %s %ld", n, e.domain.UTF8String, (long)e.code);
if (n < UPD_TRIES) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * n) * NSEC_PER_SEC), dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ upd_fetch(n + 1); }); return; }
atomic_store(&g_inflight, 0);
if (e) upd_net_why(); else dm_update_fail(2); // 三次都失败才出字:网络错误由系统网络路径定原因(upd_net_why 里设),HTTP 非 200 / 格式不对 = 其余失败 | Text appears only after all three attempts fail: for a network error the reason is determined by the system network path (set in upd_net_why); HTTP non-200 / bad format = other failures
return; }
atomic_store(&g_inflight, 0);
if (n > 1) plog("更新:第 %d 次取到了(前面 %d 次失败)", n, n - 1);
dm_update_fail(0); // 这次取到了:撤掉失败提示 | Fetched successfully this time: remove the failure notice
if (build <= g_own) { plog("更新:查 %s → 最新构建 %d,不比自己(%d)新,不提示(已有的提示撤掉)", us.UTF8String, build, g_own); dm_update_offer(0, "", 0); return; }
plog("更新:查 %s → 有新构建 %d(%s,自己 %d):%s", us.UTF8String, build, urgent ? "建议立即更新" : "普通", g_own, note.UTF8String);
dispatch_async(dispatch_get_main_queue(), ^{ g_install = install; });
dm_update_offer(build, note.UTF8String, urgent);
}] resume];
}
static void on_click(void) { // 宿主在游戏主线程调:玩家点了「更新」 | Called by the host on the game main thread: the player tapped 「更新」(Update)
dispatch_async(dispatch_get_main_queue(), ^{
NSURL *u = g_install ? [NSURL URLWithString:g_install] : nil; if (!u) { plog("更新:点了「更新」但没有安装链接"); return; }
const char *to = getenv("DM_TEST_UPDATE_OPEN"); if (to && !atoi(to)) { plog("更新:点了「更新」→ 安装链接 %s(DM_TEST_UPDATE_OPEN=0,不真打开)", g_install.UTF8String); return; }
plog("更新:点了「更新」→ 交系统打开安装链接");
[UIApplication.sharedApplication openURL:u options:@{} completionHandler:^(BOOL ok) { plog("更新:系统%s安装链接", ok ? "已接手" : "没能打开"); }];
});
}
void dm_update_boot(void) { // main.m 起宿主前调一次 | main.m calls this once before starting the host
const char *tb = getenv("DM_TEST_UPDATE_BUILD"), *tu = getenv("DM_TEST_UPDATE_URL");
NSString *v = tb ? @(tb) : [NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"] description]; g_own = v.intValue;
if (![v isEqualToString:[NSString stringWithFormat:@"%d", g_own]] || g_own < 0) g_own = 0;
NSString *url = tu ? @(tu) : NSBundle.mainBundle.infoDictionary[@"SWUpdateURL"];
if ([url isKindOfClass:NSString.class] && url.length && g_own > 1) g_url = url;
if (g_url) dm_update_site([NSURL URLWithString:g_url].host.UTF8String); // 检查失败时提示玩家去浏览器打开的站点 = 版本文件所在的主机 | The site the player is told to open in a browser when the check fails = the host that serves the version file
plog("更新:自己的构建 %d,%s", g_own, g_url ? "到选角页后查一次新版本" : g_own > 1 ? "包里没有版本文件地址,不查新版本" : "开发包,不查新版本");
dm_update_init(g_own, on_select, on_click);
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+106
View File
@@ -0,0 +1,106 @@
// 宿主堆增长定位(诊断,DM_MALLOCDIAG=起始秒,结束秒 时生效;零点 = 本构造函数):
// 起始秒挂 libmalloc 的 malloc_logger 回调,逐次记分配 → 调用点(帧指针回溯 10 帧)、释放即销账;结束秒摘钩,
// 按「窗口内分配、到结束仍活着」的字节数给调用点排序,写 Documents/mallocdiag.txt(前 40 个,模块+偏移)。
// 为什么不用 xctrace Allocations:它的记录库跑在当前栈上,HLE 在客体线程的小栈上调 malloc 时探栈越过保护页(真机两次 sig=10 ___chkstk_darwin)。
// 约束:回调里不分配内存、栈帧小(可能跑在客体栈上);表满即停记并在报告里标红。
// Locating host heap growth (diagnostic; active when DM_MALLOCDIAG=start_seconds,end_seconds; zero point = this constructor):
// at the start second, hook libmalloc's malloc_logger callback and record each allocation → call site (frame-pointer backtrace of 10 frames), cancelling the entry on free; at the end second, unhook,
// sort call sites by the bytes "allocated inside the window and still live at the end", and write Documents/mallocdiag.txt (top 40, module+offset).
// Why not xctrace Allocations: its recording library runs on the current stack, and when HLE calls malloc on a guest thread's small stack the stack probe crosses the guard page (twice on a real device: sig=10 ___chkstk_darwin).
// Constraints: no memory allocation inside the callback, small stack frame (it may run on a guest stack); when a table fills up, stop recording and mark it as failed in the report.
#import <Foundation/Foundation.h>
#include <dlfcn.h>
#include <os/lock.h>
#include <pthread.h>
#include <stdatomic.h>
#include <unistd.h>
#include "dm.h"
typedef void(malloc_logger_t)(uint32_t type, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t result, uint32_t skip);
extern malloc_logger_t *malloc_logger; // libsystem_malloc 导出(MallocStackLogging / Instruments 用的同一挂点) | Exported by libsystem_malloc (the same hook point used by MallocStackLogging / Instruments)
enum { T_ALLOC = 2, T_DEALLOC = 4, T_ZONE = 8 };
#define NF 10
#define LIVE_BITS 22 // 活块表 4M 项 × 24 B = 96 MiB(只记窗口内分配) | Live-block table 4M entries × 24 B = 96 MiB (records only allocations inside the window)
#define SITE_BITS 16
typedef struct { uintptr_t p; uint32_t size, site; } live_t;
typedef struct { uintptr_t f[NF]; uint64_t bytes, n, total_n; } site_t;
static live_t *g_live; static site_t *g_site;
static os_unfair_lock g_lk = OS_UNFAIR_LOCK_INIT;
static int g_full;
static uint32_t hsite(const uintptr_t *f) { uint64_t h = 1469598103934665603ull; for (int i = 0; i < NF; i++) h = (h ^ f[i]) * 1099511628211ull; return (uint32_t)(h ^ h >> 32); }
static uint32_t hptr(uintptr_t p) { return (uint32_t)((p >> 4) * 0x9E3779B97F4A7C15ull >> (64 - LIVE_BITS)); }
static void on_alloc(uintptr_t p, uintptr_t size) {
uintptr_t f[NF] = {0}; uintptr_t *fp = __builtin_frame_address(0);
for (int i = 0, k = 0; fp && k < NF && i < NF + 1; i++) { // 跳过本函数自己的返回地址 | Skip this function's own return address
uintptr_t *nx = (uintptr_t *)fp[0]; uintptr_t lr = fp[1] & 0x0000ffffffffffffull;
if (i >= 1) f[k++] = lr;
if (!nx || nx <= fp || (uintptr_t)nx - (uintptr_t)fp > (1u << 20) || ((uintptr_t)nx & 7)) break;
fp = nx;
}
uint32_t s = hsite(f) & ((1u << SITE_BITS) - 1);
os_unfair_lock_lock(&g_lk);
for (uint32_t i = 0; i < (1u << SITE_BITS); i++, s = (s + 1) & ((1u << SITE_BITS) - 1)) {
site_t *e = &g_site[s];
if (!e->total_n) { memcpy(e->f, f, sizeof f); break; }
if (!memcmp(e->f, f, sizeof f)) break;
if (i == (1u << SITE_BITS) - 1) { g_full = 1; os_unfair_lock_unlock(&g_lk); return; }
}
g_site[s].bytes += size; g_site[s].n++; g_site[s].total_n++;
uint32_t h = hptr(p);
for (uint32_t i = 0; i < (1u << LIVE_BITS); i++, h = (h + 1) & ((1u << LIVE_BITS) - 1))
if (!g_live[h].p || g_live[h].p == 1) { g_live[h] = (live_t){p, (uint32_t)size, s}; os_unfair_lock_unlock(&g_lk); return; }
g_full = 1; os_unfair_lock_unlock(&g_lk);
}
static void on_free(uintptr_t p) {
uint32_t h = hptr(p);
os_unfair_lock_lock(&g_lk);
for (uint32_t i = 0; i < (1u << LIVE_BITS) && g_live[h].p; i++, h = (h + 1) & ((1u << LIVE_BITS) - 1))
if (g_live[h].p == p) { site_t *e = &g_site[g_live[h].site]; e->bytes -= g_live[h].size; e->n--; g_live[h].p = 1; break; } // 1 = 墓碑 | 1 = tombstone
os_unfair_lock_unlock(&g_lk);
}
static void logger(uint32_t type, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t result, uint32_t skip) {
(void)a1; (void)skip;
if ((type & (T_ALLOC | T_DEALLOC)) == (T_ALLOC | T_DEALLOC)) { // realloc:a2 = 旧块,a3 = 新长,result = 新块 | realloc: a2 = old block, a3 = new length, result = new block
if (a2) on_free(a2);
if (result) on_alloc(result, a3);
} else if (type & T_ALLOC) { if (result) on_alloc(result, a2); }
else if (type & T_DEALLOC) on_free(a2);
}
static void sym(char *o, size_t n, uintptr_t a) {
for (int i = 0; i < g_nmod; i++)
if (a >= (uintptr_t)g_mod[i].base && a < (uintptr_t)g_mod[i].base + g_mod[i].size) { snprintf(o, n, "%s+%#lx", g_mod[i].name, a - (uintptr_t)g_mod[i].base); return; }
Dl_info d; if (dladdr((void *)a, &d) && d.dli_sname) { snprintf(o, n, "%s+%#lx", d.dli_sname, a - (uintptr_t)d.dli_saddr); return; }
if (dladdr((void *)a, &d) && d.dli_fname) { const char *b = strrchr(d.dli_fname, '/'); snprintf(o, n, "%s+%#lx", b ? b + 1 : d.dli_fname, a - (uintptr_t)d.dli_fbase); return; }
snprintf(o, n, "%#lx", a);
}
static int by_bytes(const void *a, const void *b) { uint64_t x = (*(site_t *const *)a)->bytes, y = (*(site_t *const *)b)->bytes; return (x < y) - (x > y); }
static void *diag(void *arg) {
int *w = arg; sleep((unsigned)w[0]);
malloc_logger = logger;
sleep((unsigned)(w[1] - w[0]));
malloc_logger = NULL; usleep(200000); // 摘钩后等在途回调走完 | After unhooking, wait for in-flight callbacks to finish
static site_t *top[1u << SITE_BITS]; int nt = 0; uint64_t sum = 0, sumn = 0;
for (uint32_t i = 0; i < (1u << SITE_BITS); i++) if (g_site[i].total_n && g_site[i].bytes) { top[nt++] = &g_site[i]; sum += g_site[i].bytes; sumn += g_site[i].n; }
qsort(top, nt, sizeof *top, by_bytes);
NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
FILE *f = fopen([doc stringByAppendingPathComponent:@"mallocdiag.txt"].fileSystemRepresentation, "w"); if (!f) return NULL;
fprintf(f, "窗口 %d–%d 秒:窗口内分配、到结束仍活着 %.2f MiB / %llu 块,调用点 %d 个%s\n", w[0], w[1], sum / 1048576.0, sumn, nt, g_full ? "(【红】表满,有漏记)" : "");
for (int i = 0; i < nt && i < 40; i++) {
fprintf(f, "%8.1f KiB %7llu 块(窗口内共分配 %llu 次)", top[i]->bytes / 1024.0, top[i]->n, top[i]->total_n);
for (int k = 0; k < NF && top[i]->f[k]; k++) { char s[160]; sym(s, sizeof s, top[i]->f[k]); fprintf(f, " ← %s", s); }
fputc('\n', f);
}
fclose(f); return NULL;
}
__attribute__((constructor)) static void mallocdiag_ios(void) {
const char *e = getenv("DM_MALLOCDIAG"); if (!e) return;
static int w[2]; if (sscanf(e, "%d,%d", &w[0], &w[1]) != 2 || w[1] <= w[0]) return;
g_live = calloc(1u << LIVE_BITS, sizeof *g_live); g_site = calloc(1u << SITE_BITS, sizeof *g_site);
pthread_t th; pthread_create(&th, NULL, diag, w); pthread_detach(th);
}
+58
View File
@@ -0,0 +1,58 @@
import XCTest
// 生命周期:进局 → 按主屏键回桌面 30 秒 → 把同一个进程激活回来 → 再跑 20 秒。
// 判据不在这里断言(界面测试看不到游戏内部):跑完由 tools/lifecycle.sh 拉回 Documents/boot.txt 按日志判
//(同一份日志里前后台事件齐、回来后上屏恢复、客体时钟相接、声卡回调继续涨、红行 0)。这里只保证动作序列做完、进程回到前台。
// Lifecycle: enter the run → press the home button to go to the home screen for 30 seconds → activate the same process back → run another 20 seconds.
// The criterion is not asserted here (UI tests cannot see inside the game): after the run tools/lifecycle.sh pulls back Documents/boot.txt and judges by the log
// (in the same log the foreground / background events are all there, present resumes after returning, the guest clock is continuous, the audio callback count keeps rising, 0 failure lines). Here we only guarantee that the action sequence completes and the process returns to the foreground.
final class LifecycleSmoke: XCTestCase {
func testBackgroundAndReturn() throws {
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["-mode", "boot"]
app.launchEnvironment = ["DM_SAVE_FRESH":"warlock", "DM_UIMSG":"1", "DM_AUDIO":"1",
"DM_KEYS":"X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame"]
app.launch()
defer { app.terminate() }
sleep(25) // 进局并在营地站定 | enter the run and settle in the camp
XCTAssertEqual(app.state, .runningForeground)
XCUIDevice.shared.press(.home)
sleep(30) // 后台 30 秒 | 30 seconds in the background
XCTAssertNotEqual(app.state, .notRunning, "后台期间进程被系统结束")
app.activate() // 激活同一个进程,不重开 | activate the same process, do not relaunch
XCTAssertTrue(app.wait(for: .runningForeground, timeout: 10))
sleep(20) // 回前台后再跑 20 秒 | run another 20 seconds after returning to the foreground
XCTAssertEqual(app.state, .runningForeground)
}
// 多任务界面里划掉:进局后第 8 秒左右替玩家捡一枚 r30 进背包(DM_TEST_GIVE_INV)→ 第 25 秒从底边慢拖上来停住 = 多任务界面 →
// 停 3 秒 → 结束进程(等同在多任务界面划掉:系统直接杀进程)。判据由 tools/lifecycle.sh switcher 读这一局的 boot.txt 与下一局(testReenter)的物品表
// Swipe away in the app switcher: around second 8 after entering the run pick up one r30 into the inventory for the player (DM_TEST_GIVE_INV) → at second 25 drag slowly up from the bottom edge and hold = app switcher →
// pause 3 seconds → terminate the process (equivalent to swiping away in the app switcher: the system kills the process directly). The criterion is judged by tools/lifecycle.sh switcher reading this run's boot.txt and the item table of the next run (testReenter)
private static let enterKeys = "X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,DOWN@OpenPanel:CharacterSelectPanel>UpdateCharacterInfo,A@UpdateCharacterInfo%1>CharacterSelect:SelectCharacter,A@CharacterSelect:SelectCharacter>FrontEndNavigation:ToGame"
func testSwitcherKill() throws {
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["-mode", "boot"]
app.launchEnvironment = ["DM_SAVE_FRESH":"warlock", "DM_UIMSG":"1", "DM_KEYS":Self.enterKeys, "DM_TEST_GIVE":"r30@200", "DM_TEST_GIVE_INV":"1"]
app.launch()
sleep(25)
XCTAssertEqual(app.state, .runningForeground)
let from = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.998)), to = app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.55))
from.press(forDuration: 0.05, thenDragTo: to, withVelocity: .slow, thenHoldForDuration: 1.0) // 底边慢拖上来停住:进多任务界面(快甩是回桌面) | drag slowly up from the bottom edge and hold: enters the app switcher (a quick flick goes to the home screen)
sleep(3)
app.terminate()
}
// 下一局:不换存档,进同一个角色,记物品表(DM_STATE)15 秒
// Next run: no save swap, enter the same character, record the item table (DM_STATE) for 15 seconds
func testReenter() throws {
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["-mode", "boot"]
app.launchEnvironment = ["DM_UIMSG":"1", "DM_KEYS":Self.enterKeys, "DM_STATE":"lc_state.jsonl"]
app.launch()
sleep(30)
app.terminate()
}
}
+59
View File
@@ -0,0 +1,59 @@
import XCTest
// Apple UI测试实际生成UITouch,贯穿DmMetalView→纯C归属→dm_input_set→原版UI消息。
// The Apple UI test actually generates a UITouch, passing through DmMetalView → pure C ownership → dm_input_set → the original game's UI message.
final class TouchSmoke: XCTestCase {
func testJoystickAndPanelRoundTrip() throws {
continueAfterFailure = false
let app = XCUIApplication()
app.launchArguments = ["-mode", "boot"]
app.launchEnvironment = ["DM_SAVE_FRESH":"warlock", "DM_WATCH":"50", "DM_OPMODE":"0",
"DM_KEYS":"A@OpenPanel:MainMenuButtonRibbon%0.7>FrontEndNavigation:ToGame",
"DM_TOUCH_CONTROL_LOG":"1", "DM_UIMSG":"touch_uimsg.jsonl", "DM_C2S_LOG":"touch_c2s.jsonl",
"DM_TICKS":"touch_ticks.jsonl", "DM_TICKS_FULL":"1",
"DM_TOUCH_SHOT":"22:touch_overlay.png", "DM_SCREEN_SHOT":"22:touch_window.png"]
app.launch()
defer { app.terminate() }
let surface = app.otherElements["dm_touch_surface"]
XCTAssertTrue(surface.waitForExistence(timeout:15))
XCTAssertTrue(XCTNSPredicateExpectation(predicate:NSPredicate(format:"value BEGINSWITH %@", "game|"), object:surface).wait(25))
// 期望位置由已批准的控件点尺寸与固定弧距算,不读实际rect作为期望。
// Expected positions are computed from the approved widget point sizes and the fixed arc spacing, not by reading the actual rect as the expectation.
let box = surface.frame
let w = box.width, h = box.height
func at(_ x:CGFloat,_ y:CGFloat) -> XCUICoordinate {
return surface.coordinate(withNormalizedOffset:CGVector(dx:x/w,dy:y/h))
}
at(90,h-100).press(forDuration:0.15, thenDragTo:at(150,h-100))
at(90,h-100).press(forDuration:0.15, thenDragTo:at(30,h-100))
// 空白右侧不该变成A,不改变game模式。
// The blank area on the right should not become A, and does not change the game mode.
at(w*0.55,h*0.25).tap()
let sample = (surface.value as? String) ?? ""
XCTAssertTrue(sample.hasPrefix("game|"))
let fields = Dictionary(uniqueKeysWithValues:sample.split(separator:"|").dropFirst().map { part -> (String,String) in
let pair=part.split(separator:"=",maxSplits:1);return (String(pair[0]),String(pair[1]))
})
XCTAssertGreaterThanOrEqual(Int(fields["max"] ?? "0") ?? 0,32000)
XCTAssertLessThanOrEqual(Int(fields["min"] ?? "0") ?? 0,-32000)
XCTAssertEqual(fields["buttons"],"0");XCTAssertEqual(fields["lx"],"0");XCTAssertEqual(fields["ly"],"0")
XCTAssertEqual(fields["a"],"0", "空白触点不得生成主技能A")
// 底部功能PLUS必须经真实触摸打开原版物品栏。
// The bottom function PLUS must open the original game's inventory panel through a real touch.
at(w/2+120,h-30).tap()
XCTAssertTrue(XCTNSPredicateExpectation(predicate:NSPredicate(format:"value BEGINSWITH %@", "navigation|"), object:surface).wait(5))
let panel = XCTAttachment(screenshot:app.screenshot()); panel.name="touch_inventory";panel.lifetime = .keepAlways;add(panel)
// 左下第一个技能位在导航态为B返回,必须恢复game。
// The first skill slot at the bottom left is B (Back) in navigation state, and must restore game.
at(w-56-112,h-82).tap()
XCTAssertTrue(XCTNSPredicateExpectation(predicate:NSPredicate(format:"value BEGINSWITH %@", "game|"), object:surface).wait(5))
let world = XCTAttachment(screenshot:app.screenshot());world.name="touch_game";world.lifetime = .keepAlways;add(world)
// 留够本次透明层/整窗诊断输出的22秒触发时刻;上限仍受DM_WATCH保护。
// Leave enough for the 22-second trigger moment of this run's transparent layer / whole-window diagnostic output; the limit is still protected by DM_WATCH.
XCTAssertTrue(XCTNSPredicateExpectation(predicate:NSPredicate(format:"value CONTAINS %@", "|shot=1"), object:surface).wait(25), "透明操作层写盘完成才结束")
app.terminate()
}
}
private extension XCTestExpectation {
func wait(_ seconds:TimeInterval) -> Bool { XCTWaiter.wait(for:[self],timeout:seconds) == .completed }
}
+3
View File
@@ -0,0 +1,3 @@
# 资源直接下载的「地址文件」网址,一行一个(Sources/asset_dl.m)。App 启动下载前逐个取,取回正文的第一行 = 下载站根地址
# (根地址下须有 manifest.json 与 data/)。放在不会变的地方(下载站换域名时只改那个文件的内容,不用重出包)。
# 现在还没有固定的存放处:留空时用上次成功的地址 / 出包时写进包里的缺省地址(asset_base.txt)。
+1
View File
@@ -0,0 +1 @@
{"bottom":{"center_y":"height-30*k","diameter":"44*k","first_center_x":"width/2-120*k","order":["portal","belt1","belt2","belt3","belt4","menu"],"pitch":"48*k"},"joystick":{"center":["90*k","height-100*k"],"radius":"60*k","thumb_diameter":"46*k"},"main":{"center":["width-56*k","height-82*k"],"diameter":"80*k"},"map":{"center":["width-30*k","30*k"],"diameter":"44*k"},"scaling":"k=min(1,width/667,height/375)","skills":{"angles_degrees":[180,210,240,270],"count":4,"diameter":"52*k","main_distance":"112*k"},"unit":"UIKit points"}
+116
View File
@@ -0,0 +1,116 @@
{
"unit": "UIKit points",
"scaling": "k=min(1,width/667,height/375)",
"main": {
"center": [
"width-56*k",
"height-82*k"
],
"diameter": "80*k",
"binding": "A",
"use": "主技能/交互/交换共用"
},
"skills": {
"count": 4,
"diameter": "52*k",
"main_distance": "112*k",
"angles_degrees": [
180,
210,
240,
270
],
"bindings": [
"B",
"X",
"Y",
"R"
]
},
"bottom_controls": {
"ids": [
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu"
],
"first_center_x": "width/2-120*k",
"pitch": "48*k",
"center_y": "height-30*k",
"diameter": "44*k"
},
"full_hud_order": [
"原版血球",
"回城",
"腰带1",
"腰带2",
"腰带3",
"腰带4",
"功能",
"原版蓝球"
],
"joystick": {
"idle_center": [
"90*k",
"height-100*k"
],
"radius": "60*k",
"thumb_diameter": "46*k",
"deadzone": "6*k",
"zone": "x<width*.43,y>height*.25",
"axes": "left only, ±32767"
},
"map": {
"center": [
"width-30*k",
"30*k"
],
"diameter": "44*k",
"binding": "MINUS"
},
"game_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map",
"joystick"
],
"navigation_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"menu",
"joystick"
],
"not_yet_verified": [
"回城实际绑定与生效",
"原版HUD资源重排",
"强制跑步与取消精力机制",
"功能菜单难度首屏",
"真实触摸和手柄全局存档等价"
],
"captured_device": {
"view_size_pt": [
956,
440
],
"pixel_size": [
2868,
1320
],
"scale": 3
},
"viewport_issue": "DM_OPMODE=0原生截图游戏内容未铺满,右/底黑区;触屏层真实铺满,不作为宽屏通过"
}
@@ -0,0 +1,135 @@
{
"unit": "UIKit points",
"scaling": "k=min(1,width/667,height/375)",
"main": {
"center": [
"width-56*k",
"height-82*k"
],
"diameter": "80*k",
"binding": "A",
"use": "主技能/交互/交换共用"
},
"skills": {
"count": 4,
"diameter": "52*k",
"main_distance": "112*k",
"angles_degrees": [
180,
210,
240,
270
],
"bindings": [
"B",
"X",
"Y",
"R"
]
},
"bottom_controls": {
"ids": [
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu"
],
"first_center_x": "width/2-120*k",
"pitch": "48*k",
"center_y": "height-30*k",
"diameter": "44*k",
"portal_binding": "runtime native_mapping.portal.buttons"
},
"full_hud_order": [
"原版血球",
"回城",
"腰带1",
"腰带2",
"腰带3",
"腰带4",
"功能",
"原版蓝球"
],
"joystick": {
"idle_center": [
"90*k",
"height-100*k"
],
"radius": "60*k",
"thumb_diameter": "46*k",
"deadzone": "6*k",
"zone": "x<width*.43,y>height*.25",
"axes": "left only, ±32767"
},
"map": {
"center": [
"width-30*k",
"30*k"
],
"diameter": "44*k",
"binding": "MINUS"
},
"game_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map",
"joystick"
],
"navigation_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"menu",
"joystick"
],
"not_yet_verified": [
"回城实际绑定与生效",
"原版HUD资源重排",
"强制跑步与取消精力机制",
"功能菜单难度首屏",
"真实触摸和手柄全局存档等价"
],
"captured_device": {
"view_size_pt": [
956,
440
],
"pixel_size": [
2868,
1320
],
"scale": 3
},
"viewport_issue": "DM_OPMODE=0原生截图游戏内容未铺满,右/底黑区;触屏层真实铺满,不作为宽屏通过",
"profile_id": "touch_native_binding_v2",
"supersedes": "touch_m1_v1",
"native_mapping": {
"schema": "dm-native-binding-2",
"getter_obs": 6,
"source": "native_getter",
"portal": "alt slot6..11 first, then normal slot0..5; raw marker359/219/220; original logical facet -> SDK (+ZL for alt)",
"unsupported": "OBS6 absent preserves old ZR verified domain only",
"supported_not_ready": "mask0",
"write_original_memory": false,
"verified": false,
"getter_phase": "pre_ldr_main_43ecc8",
"selected_bank": "effectiveIndex - original getter_input_slot; only0/16; not active_weapon_bank",
"valid_scope": "table_parse_only; not ammo or gameplay proof",
"max_age_ns": 250000000,
"cadence": "existing DmRateHint CADisplayLink; no additional timer",
"navigation": "no Portal bindings publish while disabled"
}
}
@@ -0,0 +1,141 @@
{
"unit": "UIKit points",
"scaling": "k=min(1,width/667,height/375)",
"main": {
"center": [
"width-56*k",
"height-82*k"
],
"diameter": "80*k",
"binding": "A",
"use": "主技能/交互/交换共用"
},
"skills": {
"count": 4,
"diameter": "52*k",
"main_distance": "112*k",
"angles_degrees": [
180,
210,
240,
270
],
"bindings": [
"B",
"X",
"Y",
"R"
]
},
"bottom_controls": {
"ids": [
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu"
],
"first_center_x": "width/2-120*k",
"pitch": "48*k",
"center_y": "height-30*k",
"diameter": "44*k",
"portal_binding": "runtime native_mapping.portal.buttons"
},
"full_hud_order": [
"原版血球",
"回城",
"腰带1",
"腰带2",
"腰带3",
"腰带4",
"功能",
"原版蓝球"
],
"joystick": {
"idle_center": [
"90*k",
"height-100*k"
],
"radius": "60*k",
"thumb_diameter": "46*k",
"deadzone": "6*k",
"zone": "x<width*.43,y>height*.25",
"axes": "left only, ±32767"
},
"map": {
"center": [
"width-30*k",
"30*k"
],
"diameter": "44*k",
"binding": "MINUS"
},
"game_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map",
"joystick"
],
"navigation_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"menu",
"joystick"
],
"not_yet_verified": [
"回城实际绑定与生效",
"原版HUD资源重排",
"强制跑步与取消精力机制",
"功能菜单难度首屏",
"真实触摸和手柄全局存档等价"
],
"captured_device": {
"view_size_pt": [
956,
440
],
"pixel_size": [
2868,
1320
],
"scale": 3
},
"viewport_issue": "DM_OPMODE=0原生截图游戏内容未铺满,右/底黑区;触屏层真实铺满,不作为宽屏通过",
"profile_id": "touch_native_binding_v3",
"supersedes": "touch_native_binding_v2",
"native_mapping": {
"schema": "dm-native-binding-3",
"getter_obs": 6,
"source": "native_getter",
"portal": "alt slot6..11 first, then normal slot0..5; raw marker359/219/220; original logical facet -> SDK (+ZL for alt)",
"unsupported": "OBS6 absent preserves old ZR verified domain only",
"supported_not_ready": "mask0",
"write_original_memory": false,
"verified": false,
"getter_phase": "pre_ldr_main_43ecc8",
"selected_bank": "effectiveIndex - original getter_input_slot; only0/16; not active_weapon_bank",
"valid_scope": "table_parse_only; not ammo or gameplay proof",
"max_age_ns": 250000000,
"cadence": "existing DmRateHint CADisplayLink; no additional timer",
"navigation": "no Portal bindings publish while disabled",
"ready": "same original synchronous scene, selected_bank, map+IDs, confirmed HUD/caller; six normal or six alt facets complete; no mixing",
"identity_scope": "UNCONFIRMED=0 -> never ready; NATIVE=1 only confirmed root ABI; SYNTHETIC=2 SDK_STUB tests only",
"portal_sequence": "alt begin modifier-only ZL; complete secondary group started/captured after actual modifier publish -> epoch/identity/scene ACK -> facet|ZL; normal instant",
"last_finger_end": "last Portal-owned finger cancels request; second finger never restarts epoch",
"cancel": "focus/layout/scene/identity/mask/staleness cancels all Portal ownership; no late ACK or blind timer",
"publish": "source=portal_sequence phase=none eventseq unchanged; pending modifier publish host timestamp independent of diagnostics"
}
}
@@ -0,0 +1,146 @@
{
"unit": "UIKit points",
"scaling": "k=min(1,width/667,height/375)",
"main": {
"center": [
"width-56*k",
"height-82*k"
],
"diameter": "80*k",
"binding": "A",
"use": "主技能/交互/交换共用"
},
"skills": {
"count": 4,
"diameter": "52*k",
"main_distance": "112*k",
"angles_degrees": [
180,
210,
240,
270
],
"bindings": [
"B",
"X",
"Y",
"R"
]
},
"bottom_controls": {
"ids": [
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu"
],
"first_center_x": "width/2-120*k",
"pitch": "48*k",
"center_y": "height-30*k",
"diameter": "44*k",
"portal_binding": "runtime native_mapping.portal.buttons"
},
"full_hud_order": [
"原版血球",
"回城",
"腰带1",
"腰带2",
"腰带3",
"腰带4",
"功能",
"原版蓝球"
],
"joystick": {
"idle_center": [
"90*k",
"height-100*k"
],
"radius": "60*k",
"thumb_diameter": "46*k",
"deadzone": "6*k",
"zone": "x<width*.43,y>height*.25",
"axes": "left only, ±32767"
},
"map": {
"center": [
"width-30*k",
"30*k"
],
"diameter": "44*k",
"binding": "MINUS"
},
"game_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map",
"joystick"
],
"navigation_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"menu",
"joystick"
],
"not_yet_verified": [
"回城实际绑定与生效",
"原版HUD资源重排",
"强制跑步与取消精力机制",
"功能菜单难度首屏",
"真实触摸和手柄全局存档等价"
],
"captured_device": {
"view_size_pt": [
956,
440
],
"pixel_size": [
2868,
1320
],
"scale": 3
},
"viewport_issue": "DM_OPMODE=0原生截图游戏内容未铺满,右/底黑区;触屏层真实铺满,不作为宽屏通过",
"profile_id": "touch_native_binding_v4",
"supersedes": "touch_native_binding_v3",
"native_mapping": {
"schema": "dm-native-binding-4",
"getter_obs": 6,
"source": "native_getter",
"portal": "alt slot6..11 first, then normal slot0..5; raw marker359/219/220; original logical facet -> SDK (+ZL for alt)",
"unsupported": "OBS6 absent preserves old ZR verified domain only",
"supported_not_ready": "mask0",
"write_original_memory": false,
"verified": false,
"getter_phase": "pre_ldr_main_43ecc8",
"selected_bank": "effectiveIndex - original getter_input_slot; only0/16; not active_weapon_bank",
"valid_scope": "table_parse_only; not ammo or gameplay proof",
"max_age_ns": 250000000,
"cadence": "existing DmRateHint CADisplayLink; no additional timer",
"navigation": "no Portal bindings publish while disabled",
"ready": "same original synchronous scene, selected_bank, map+IDs, confirmed HUD/caller; six normal or six alt facets complete; no mixing",
"identity_scope": "strong production Mach resolver: savedLR(fp+8)=main+3e2f74, saved widget(fp-8), enum(widget+b18)0..5, alwaysGetAlt(widget+c90)=0, arg=enum or enum+6",
"portal_sequence": "alt begin modifier-only ZL; complete secondary group started/captured after actual modifier publish -> epoch/identity/scene ACK -> facet|ZL; normal instant",
"last_finger_end": "last Portal-owned finger cancels request; second finger never restarts epoch",
"cancel": "focus/layout/scene/identity/mask/staleness cancels all Portal ownership; no late ACK or blind timer",
"publish": "source=portal_sequence phase=none eventseq unchanged; pending modifier publish host timestamp independent of diagnostics",
"identity_kind": "fixed six-widget HUD updater cohort hash; not HUDPanel root pointer",
"world_epoch": "increments only original scene.game changes; world change resets cohort; mode changes update scene_epoch",
"cohort": "first live game/no-panel distinct6 enum widgets fixed; sixth confirms only, next complete native six group ready; never replace until world reload",
"non_hud": "IGNORE cache/readFail/bad arg/widget/alwaysAlt; do not clear confirmed snapshot or renew freshness",
"synthetic": "conditional DM_TG_TEST_SYNTHETIC_IDENTITY opaque dm_touch_game_test_identity only; no production weak identity"
}
}
@@ -0,0 +1,161 @@
{
"unit": "UIKit points",
"scaling": "k=min(1,width/667,height/375)",
"main": {
"center": [
"width-56*k",
"height-82*k"
],
"diameter": "80*k",
"binding": "A",
"use": "主技能/交互/交换共用"
},
"skills": {
"count": 4,
"diameter": "52*k",
"main_distance": "112*k",
"angles_degrees": [
180,
210,
240,
270
],
"bindings": [
"B",
"X",
"Y",
"R"
]
},
"bottom_controls": {
"ids": [
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu"
],
"first_center_x": "width/2-120*k",
"pitch": "48*k",
"center_y": "height-30*k",
"diameter": "44*k",
"portal_binding": "runtime native_mapping.portal.buttons"
},
"full_hud_order": [
"原版血球",
"回城",
"腰带1",
"腰带2",
"腰带3",
"腰带4",
"功能",
"原版蓝球"
],
"joystick": {
"idle_center": [
"90*k",
"height-100*k"
],
"radius": "60*k",
"thumb_diameter": "46*k",
"deadzone": "6*k",
"zone": "x<width*.43,y>height*.25",
"axes": "left only, ±32767"
},
"map": {
"center": [
"width-30*k",
"30*k"
],
"diameter": "44*k",
"binding": "MINUS"
},
"game_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"portal",
"belt1",
"belt2",
"belt3",
"belt4",
"menu",
"map",
"joystick"
],
"navigation_visible": [
"main",
"skill1",
"skill2",
"skill3",
"skill4",
"menu",
"joystick"
],
"not_yet_verified": [
"回城实际绑定与生效",
"原版HUD资源重排",
"强制跑步与取消精力机制",
"功能菜单难度首屏",
"真实触摸和手柄全局存档等价"
],
"captured_device": {
"view_size_pt": [
956,
440
],
"pixel_size": [
2868,
1320
],
"scale": 3
},
"viewport_issue": "DM_OPMODE=0原生截图游戏内容未铺满,右/底黑区;触屏层真实铺满,不作为宽屏通过",
"profile_id": "touch_native_binding_v5",
"supersedes": "touch_native_binding_v4",
"native_mapping": {
"schema": "dm-native-binding-4",
"getter_obs": 6,
"source": "native_getter",
"portal": "alt slot6..11 first, then normal slot0..5; raw marker359/219/220; original logical facet -> SDK (+ZL for alt)",
"unsupported": "OBS6 absent preserves old ZR verified domain only",
"supported_not_ready": "mask0",
"write_original_memory": false,
"verified": false,
"getter_phase": "pre_ldr_main_43ecc8",
"selected_bank": "effectiveIndex - original getter_input_slot; only0/16; not active_weapon_bank",
"valid_scope": "table_parse_only; not ammo or gameplay proof",
"max_age_ns": 250000000,
"cadence": "existing DmRateHint CADisplayLink; no additional timer",
"navigation": "no Portal bindings publish while disabled",
"ready": "same original synchronous scene, selected_bank, map+IDs, confirmed HUD/caller; six normal or six alt facets complete; no mixing",
"identity_scope": "strong production Mach resolver: savedLR(fp+8)=main+3e2f74, saved widget(fp-8), enum(widget+b18)0..5, alwaysGetAlt(widget+c90)=0, arg=enum or enum+6",
"portal_sequence": "alt begin modifier-only ZL; complete secondary group started/captured after actual modifier publish -> epoch/identity/scene ACK -> facet|ZL; normal instant",
"last_finger_end": "last Portal-owned finger cancels request; second finger never restarts epoch",
"cancel": "focus/layout/scene/identity/mask/staleness cancels all Portal ownership; no late ACK or blind timer",
"publish": "source=portal_sequence phase=none eventseq unchanged; pending modifier publish host timestamp independent of diagnostics",
"identity_kind": "fixed six-widget HUD updater cohort hash; not HUDPanel root pointer",
"world_epoch": "increments only original scene.game changes; world change resets cohort; mode changes update scene_epoch",
"cohort": "first live game/no-panel distinct6 enum widgets fixed; sixth confirms only, next complete native six group ready; never replace until world reload",
"non_hud": "IGNORE cache/readFail/bad arg/widget/alwaysAlt; do not clear confirmed snapshot or renew freshness",
"synthetic": "conditional DM_TG_TEST_SYNTHETIC_IDENTITY opaque dm_touch_game_test_identity only; no production weak identity"
},
"extends_binding_profile": "touch_native_binding_v4",
"input_schema": "dm-touch-input-5",
"skill_drag": {
"origin": "actual began point",
"radius": "60*k",
"rx": "round(clamp((x-origin_x)/radius,-1,1)*32767)",
"ry": "round(-clamp((y-origin_y)/radius,-1,1)*32767)",
"ownership": "last active noncancelled skill moved sample; no sum; neutral is neutral",
"navigation": "never interpret item or menu touch as skill aim",
"cancel_region": "map target bounding rectangle; affected finger latched cancelled until end",
"left_axis": "unchanged; never selects aim direction",
"platform_scope": "skill-aim-v1-private 0x86, main917e4e61feb22471354973edadbeea23b692408ce5227839b1e7621ac5d3b1cf; actual current Swap0 only; Swap1/phoneHandheld32 unverified",
"continuous_hold": "existing button begins/held unchanged; no weapon or skill group exchange gesture added",
"tap_target_priority": "not implemented or proven by right-axis mapping"
}
}
+26
View File
@@ -0,0 +1,26 @@
# 本机设备配置样例。复制成 dm/ios/local.env(已在 .gitignore 里,不进仓)再填;也可放 ~/.config/dm-ios/local.env 供多个工作树共用。
# 真机的 devicectl 设备标识:xcrun devicectl list devices 的 Identifier 列(装机 / 真机脚本用)
# Sample local device configuration. Copy to dm/ios/local.env (already in .gitignore, not committed) and fill it in; it can also go in ~/.config/dm-ios/local.env to be shared by multiple working trees.
# devicectl device identifier of the real device: the Identifier column of xcrun devicectl list devices (used by the install / real-device scripts)
DM_DEVICE=
# 真机的硬件 UDID:Xcode → Devices and Simulators → Identifier。tools/lifecycle.sh、tools/xtrace.sh 用;
# 用免费账号(DM_FREE_ACCOUNT=1)出包时也要填:构建以这台手机为目标,苹果才肯给免费团队生成描述文件(构建时手机要连着)
# Hardware UDID of the real device: Xcode → Devices and Simulators → Identifier. Used by tools/lifecycle.sh, tools/xtrace.sh;
# it must also be filled in when building with a free account (DM_FREE_ACCOUNT=1): the build targets this phone, and only then will Apple generate a provisioning profile for a free team (the phone must be connected during the build)
DM_IOS_UDID=
# 第二台 Mac 的 ssh 目标(只有 dm/tools/l3run.sh、mini_sync.sh 用),如 用户名@主机
# ssh target of the second Mac (only used by dm/tools/l3run.sh and mini_sync.sh), e.g. user@host
MINI_SSH=
# 签名:开发者团队号(Xcode → Settings → Accounts 里团队的 Team ID)与 App 包名(自己起,反域名写法,如 org.example.d2rmobile)。
# App 组、iCloud 容器由包名派生(group.<包名>、iCloud.<包名>)。出 App 与装机脚本都要这两项。
# Signing: developer team ID (the Team ID of the team under Xcode → Settings → Accounts) and the App bundle ID (your own choice, reverse-domain style, e.g. org.example.d2rmobile).
# The App group and iCloud container are derived from the bundle ID (group.<bundle ID>, iCloud.<bundle ID>). Both the App build and the install scripts need these two.
DM_TEAM_ID=
DM_BUNDLE_ID=
# 用免费的开发者账号(个人团队)时设成 1:出包时不带它签不了的权限(iCloud 存档同步、持续执行、增加内存上限、扩展虚拟寻址)。
# 免费账号另有苹果的限制:描述文件 7 天过期(要重新构建重装)、最多 3 台设备、每台最多 3 个 App。付费账号留空。
# 用免费账号时:上面的 DM_IOS_UDID 也要填,构建时把手机连上;装好后第一次打开前,到手机「设置 → 通用 → VPN 与设备管理」里信任你的开发者账号。
# Set to 1 when using a free developer account (personal team): the build then leaves out the entitlements it cannot sign (iCloud save sync, sustained execution, increased memory limit, extended virtual addressing).
# Free accounts also have Apple's own limits: the provisioning profile expires after 7 days (rebuild and reinstall needed), at most 3 devices, at most 3 apps per device. Leave empty for a paid account.
# When using a free account: DM_IOS_UDID above must also be filled in, and the phone must be connected during the build; after installing and before the first launch, trust your developer account on the phone under 「设置 → 通用 → VPN 与设备管理」(Settings → General → VPN & Device Management).
DM_FREE_ACCOUNT=
+162
View File
@@ -0,0 +1,162 @@
name: DmIOS
options:
bundleIdPrefix: ${DM_BUNDLE_ID}
deploymentTarget:
iOS: "26.0" # 命令翻译层走 Metal 4(MTL4CommandQueue 等,iOS 26 起);着色器编译的最低版本(tools/ios_metal.py)不动,免得缓存全量失效 | The command translation layer uses Metal 4 (MTL4CommandQueue etc., from iOS 26); the minimum version for shader compilation (tools/ios_metal.py) is left unchanged, to avoid invalidating the whole cache
configFiles: # run.sh build 生成:内嵌段链接参数 + 从 dm/host/Makefile 取的头文件路径与框架 | Generated by run.sh build: embedded-segment link flags + header paths and frameworks taken from dm/host/Makefile
Release: Gen/dm.xcconfig
Debug: Gen/dm.xcconfig
targets:
DmIOS:
type: application
platform: iOS
preBuildScripts: # 直接在 Xcode 里构建时:原版衍生资源不在就先从游戏文件生成(run.sh build 已生成过就跳过;dm/README.md「从你的游戏文件生成资源」) | When building directly in Xcode: if the assets derived from the original game are missing, generate them from game files first (skipped if run.sh build already generated them; see dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files))
- name: 从游戏文件生成资源
basedOnDependencyAnalysis: false
script: |
[ -f "$SRCROOT/Gen/assets/NativeHUD/v4/hud.json" ] && [ -f "$SRCROOT/Sources/dm_touch_native_art.c" ] || python3 "$SRCROOT/tools/gen_assets.py"
sources:
- Sources
- Assets.xcassets # App 图标(1024²、不透明;TestFlight 上传必需) | App icon (1024², opaque; required for TestFlight upload)
- path: Gen/assets/NativeHUD/v4/hud_v4_ui # 底部 UI v4 的 UIKit 素材(run.sh build 由 tools/gen_hud_v4.py 从游戏文件生成:几何、字形、难度数字、选择条格子) | UIKit art for bottom UI v4 (generated from game files by tools/gen_hud_v4.py during run.sh build: geometry, glyphs, difficulty digits, selection bar cells)
type: folder
buildPhase: resources
- path: Gen/assets/NativeHUD/mapgoal # 小地图任务终点的素材(run.sh build 由 tools/gen_map_goal_art.py 从游戏文件生成:塔拉夏符号、地图十字、原版名牌) | Art for the minimap quest goal (generated from game files by tools/gen_map_goal_art.py during run.sh build: Tal Rasha symbols, map cross, the original game's nameplate)
type: folder
buildPhase: resources
- path: Gen/romfs_overlay # RomFS 覆盖层(run.sh build 由 tools/gen_romfs_overlay.py 生成;main.m 设 DM_ROMFS_OVERLAY) | RomFS overlay (generated by tools/gen_romfs_overlay.py during run.sh build; main.m sets DM_ROMFS_OVERLAY)
type: folder
buildPhase: resources
- path: Gen/romfs_overlay_variants # 覆盖层的开关组合(物品注释…,同一脚本生成;main.m 按自定义开关挑一份) | Overlay switch combinations (item annotations..., generated by the same script; main.m picks one according to the custom switches)
type: folder
buildPhase: resources
- path: Gen/romfs_overlay_astc # 老机型补充包配套的 ASTC 版覆盖层与 pack.json(设了 DM_ASTC_PACK 才有内容;main.m 在不支持 BC 且补充包校验通过时用) | ASTC overlay and pack.json that go with the Legacy Device Pack (has content only when DM_ASTC_PACK is set; main.m uses it when BC is unsupported and the Legacy Device Pack passes verification)
type: folder
buildPhase: resources
- path: Gen/romfs_overlay_astc_variants
type: folder
buildPhase: resources
- path: Gen/embed.S
- path: Gen/dm
type: folder
buildPhase: resources
- path: Gen/msl # iOS 版 metallib + 反射 json(DM_MSL_DIR) | iOS metallib + reflection json (DM_MSL_DIR)
type: folder
buildPhase: resources
- path: Gen/save_ref # 标准存档 save_ref(DM_SAVE_FRESH 时换进 Documents/save) | Standard save save_ref (swapped into Documents/save when DM_SAVE_FRESH is set)
type: folder
buildPhase: resources
- path: Gen/save_ref_warlock # 术士存档(DM_SAVE_FRESH=warlock) | Warlock save (DM_SAVE_FRESH=warlock)
type: folder
buildPhase: resources
- path: Gen/src # dm/host/Makefile 编译命令里的源文件(gen_build.py 链入) | Source files from the compile commands of dm/host/Makefile (linked in by gen_build.py)
- path: Gen/main/main.c
compilerFlags: "-Dmain=dm_main"
info:
path: Sources/Info.plist
properties:
CFBundleDisplayName: D2R Mobile
CFBundleVersion: $(CURRENT_PROJECT_VERSION) # 构建号(testflight.sh 传月日时分);xcodegen 缺省写死 1,TestFlight 会当重复构建 | Build number (testflight.sh passes month-day-hour-minute); xcodegen hardcodes 1 by default, which TestFlight treats as a duplicate build
CFBundleShortVersionString: $(MARKETING_VERSION)
SWUpdateURL: $(DM_UPDATE_URL) # 新版本提示查的版本文件地址(Sources/dm_update.m);出包脚本传,地址不进仓库。空 = 不查不提示 | URL of the version file checked for the new-version prompt (Sources/dm_update.m); passed by the packaging script, the URL is not committed to the repository. Empty = no check, no prompt
UILaunchStoryboardName: ""
UIFileSharingEnabled: true
LSSupportsOpeningDocumentsInPlace: true
UISupportedInterfaceOrientations: # 游戏画面 16:9 横屏(1600x900),只允许横屏两向 | The game picture is 16:9 landscape (1600x900); only the two landscape orientations are allowed
- UIInterfaceOrientationLandscapeRight
- UIInterfaceOrientationLandscapeLeft
UIRequiresFullScreen: true
UIStatusBarHidden: true
UIViewControllerBasedStatusBarAppearance: false
LSApplicationCategoryType: public.app-category.role-playing-games # 声明为游戏:iOS 游戏模式(压后台活动、保持续性能)只对游戏类目的 App 自动开(此前没声明类目) | Declare as a game: iOS Game Mode (suppresses background activity, preserves sustained performance) turns on automatically only for Apps in a game category (no category was declared before)
LSSupportsGameMode: true # iOS 游戏模式的键(WWDC25 209)。先前误写成 GCSupportsGameMode(macOS 旧键),iOS 不认 | Key for iOS Game Mode (WWDC25 209). Previously miswritten as GCSupportsGameMode (the old macOS key), which iOS does not recognize
ITSAppUsesNonExemptEncryption: false # TestFlight 上传免出口合规问答(只用系统加密) | Skips the export compliance questionnaire on TestFlight upload (only system encryption is used)
BAAppGroupID: group.${DM_BUNDLE_ID} # 游戏资源(RomFS 9 GB,超安装包 4 GB 上限)走苹果托管资源包 romfs:TestFlight / 商店安装时随包下载 | Game assets (RomFS is 9 GB, over the 4 GB install package limit) go through the Apple-hosted asset pack romfs: downloaded with the package on TestFlight / Store install
BAHasManagedAssetPacks: true
BAUsesAppleHosting: true
CADisableMinimumFrameDurationOnPhone: true # iPhone 缺省把 App 限在 60 Hz;不设这个键,ProMotion 120 Hz 拿不到(画布每 16.6 ms 才给一张) | By default iPhone caps Apps at 60 Hz; without this key ProMotion 120 Hz is unavailable (the canvas hands out a drawable only every 16.6 ms)
UIApplicationSceneManifest:
UIApplicationSupportsMultipleScenes: false
UISceneConfigurations:
UIWindowSceneSessionRoleApplication:
- UISceneConfigurationName: Default
UISceneDelegateClassName: SceneDelegate
entitlements:
path: Sources/DmIOS.entitlements
properties:
com.apple.developer.kernel.increased-memory-limit: true
com.apple.developer.kernel.extended-virtual-addressing: true
com.apple.developer.sustained-execution: true # 持续执行模式:系统从启动起就按稳态功率给性能,凉机与热机表现一致(启动日志「持续执行档」核对是否生效) | Sustained execution mode: from launch the system grants performance at steady-state power, so a cold device and a hot device behave the same (check the startup log line 「持续执行档」(sustained execution tier) to see whether it took effect)
com.apple.security.application-groups: ["group.${DM_BUNDLE_ID}"]
com.apple.developer.icloud-container-identifiers: ["iCloud.${DM_BUNDLE_ID}"] # iCloud 同步存档(cloud_ios.m):App 私有的 iCloud Drive 容器,不在「文件」App 里露出 | iCloud save sync (cloud_ios.m): the App's private iCloud Drive container, not exposed in the Files app
com.apple.developer.icloud-services: [CloudDocuments]
com.apple.developer.ubiquity-container-identifiers: ["iCloud.${DM_BUNDLE_ID}"]
dependencies:
- target: RomfsDownloader # 苹果托管资源包要求的下载扩展(系统缺省实现) | Download extension required by Apple-hosted asset packs (system default implementation)
- sdk: BackgroundAssets.framework
settings:
PRODUCT_BUNDLE_IDENTIFIER: ${DM_BUNDLE_ID}
ENABLE_USER_SCRIPT_SANDBOXING: NO # 构建前脚本「从游戏文件生成资源」要读工程外的 RomFS(沙盒里读不到) | The pre-build script 「从游戏文件生成资源」(Generate assets from game files) needs to read the RomFS outside the project (unreadable inside the sandbox)
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
MARKETING_VERSION: "1.0"
CURRENT_PROJECT_VERSION: $(DM_BUILD_NUMBER) # TestFlight 每次上传须递增;tools/testflight.sh 传入,本地构建缺省 1 | Must be incremented for every TestFlight upload; passed in by tools/testflight.sh, defaults to 1 for local builds
DM_BUILD_NUMBER: "1"
DM_UPDATE_URL: "" # tools/adhoc.sh 在环境里有 DM_UPDATE_URL 时传入;本地构建缺省空 | Passed in by tools/adhoc.sh when DM_UPDATE_URL is in the environment; empty by default for local builds
DEVELOPMENT_TEAM: ${DM_TEAM_ID}
CODE_SIGN_STYLE: Automatic
TARGETED_DEVICE_FAMILY: $(DM_DEVICE_FAMILY) # 设备族:缺省只面向 iPhone("1");给 iPad 用的直装包出包时传 DM_DEVICE_FAMILY=1,2。Mac 冒烟 / 开发包不传,窗口与坐标换算不变 | Device family: defaults to iPhone only ("1"); pass DM_DEVICE_FAMILY=1,2 when building the direct-install package for iPad. Mac smoke test / development builds do not pass it; window and coordinate conversion are unchanged
DM_DEVICE_FAMILY: "1"
ENABLE_BITCODE: NO
GCC_C_LANGUAGE_STANDARD: gnu11
OTHER_CFLAGS: $(inherited) -mcpu=apple-a18 # 只给 iPhone 17 Pro Max(A19)用;宿主汇编里有 LSE 原子指令,默认 a10 基线不认 | Only for iPhone 17 Pro Max (A19); the host assembly contains LSE atomic instructions, which the default a10 baseline does not accept
CLANG_ENABLE_OBJC_ARC: YES
DEBUG_INFORMATION_FORMAT: dwarf
RomfsDownloader:
type: extensionkit-extension
platform: iOS
sources:
- RomfsDownloader
info:
path: RomfsDownloader/Info.plist
properties:
CFBundleDisplayName: RomfsDownloader
CFBundleVersion: $(CURRENT_PROJECT_VERSION)
CFBundleShortVersionString: $(MARKETING_VERSION)
EXAppExtensionAttributes:
EXExtensionPointIdentifier: com.apple.background-asset-downloader-extension
entitlements:
path: RomfsDownloader/RomfsDownloader.entitlements
properties:
com.apple.security.application-groups: ["group.${DM_BUNDLE_ID}"]
settings:
PRODUCT_BUNDLE_IDENTIFIER: ${DM_BUNDLE_ID}.romfs-downloader
DEVELOPMENT_TEAM: ${DM_TEAM_ID}
CODE_SIGN_STYLE: Automatic
TARGETED_DEVICE_FAMILY: $(DM_DEVICE_FAMILY) # 设备族:缺省只面向 iPhone("1");给 iPad 用的直装包出包时传 DM_DEVICE_FAMILY=1,2。Mac 冒烟 / 开发包不传,窗口与坐标换算不变 | Device family: defaults to iPhone only ("1"); pass DM_DEVICE_FAMILY=1,2 when building the direct-install package for iPad. Mac smoke test / development builds do not pass it; window and coordinate conversion are unchanged
DM_DEVICE_FAMILY: "1"
IPHONEOS_DEPLOYMENT_TARGET: "26.4"
SWIFT_VERSION: "6.0"
MARKETING_VERSION: "1.0"
CURRENT_PROJECT_VERSION: $(DM_BUILD_NUMBER)
DM_BUILD_NUMBER: "1"
TouchSmokeTests:
type: bundle.ui-testing
platform: iOS
sources:
- TouchSmokeTests
dependencies:
- target: DmIOS
settings:
DEVELOPMENT_TEAM: ${DM_TEAM_ID}
CODE_SIGN_STYLE: Automatic
GENERATE_INFOPLIST_FILE: YES
TEST_TARGET_NAME: DmIOS
schemes:
DmIOS:
build:
targets:
DmIOS: all
TouchSmokeTests: [test]
test:
targets:
- TouchSmokeTests
Executable
+136
View File
@@ -0,0 +1,136 @@
#!/bin/bash
# 构建、显式装机、按模式启动并拉回 Documents/<mode>.txt。用法:[DM_OUT=产物目录] [DM_NOINSTALL=1] run.sh build | run.sh install | run.sh <mode> [上限秒]
# 包缺省只面向 iPhone;要同时面向 iPad:DM_DEVICE_FAMILY=1,2 ./run.sh build(设备族是构建设置,这里替你传给 xcodebuild)
# 产物与日志在 $DM_ROOT/run/ios/(不进仓)。真机按 bundle 停:--terminate-existing 只停本 App。
# Build, explicitly install, launch by mode and pull back Documents/<mode>.txt. Usage: [DM_OUT=output dir] [DM_NOINSTALL=1] run.sh build | run.sh install | run.sh <mode> [timeout seconds]
# The app targets iPhone only by default; to target iPad as well: DM_DEVICE_FAMILY=1,2 ./run.sh build (device family is a build setting; this passes it to xcodebuild for you)
# Outputs and logs go to $DM_ROOT/run/ios/ (not in the repo). On device, stopping is by bundle: --terminate-existing stops only this App.
set -u
cd "$(dirname "$0")"
source tools/devlock.sh
source tools/asc_env.sh
source tools/local_env.sh # 本机设备配置(不进仓,见 local.env.example);出包不需要设备号,装机 / 启动时才核 | Local device configuration (not committed, see local.env.example); packaging does not need a device ID, it is only checked at install / launch
D=${DM_DEVICE:-}; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
R=${DM_ROOT:-$HOME/dm-work}/run/ios; mkdir -p "$R/out"
DD=${DM_IOS_DD:-$R/dd}
APP=$DD/Build/Products/Release-iphoneos/DmIOS.app
t(){ echo "[$(date +%T)] $*"; }
OUT=${DM_OUT:-$(bash "../tools/product.sh" path touch)}; MODS="main sdk"
if [ "$1" = build ]; then
# 生成:宿主源文件/头路径/框架(取自 dm/host/Makefile)+ 映像三段内嵌汇编与 -segprot + 装载表头/门表进 App 资源 dm/
# Generate: host source files/header paths/frameworks (taken from dm/host/Makefile) + embedded assembly for the three image segments and -segprot + load table header/gate table into the App resources dm/
mkdir -p Gen; for x in Gen/* Gen/.[!.]*; do [ -e "$x" ] && [ "$x" != Gen/assets ] && rm -rf "$x"; done; mkdir -p Gen/dm # 每次重建 Gen,但留着 Gen/assets:原版衍生资源有自己的输入指纹与锁(tools/gen_assets.py),删了会和并行读它的功能用例撞(accept 红) | Rebuild Gen every time but keep Gen/assets: assets derived from the original game have their own input fingerprint and lock (tools/gen_assets.py); deleting them would collide with functional cases reading them in parallel (accept fails)
# 产品包不监听任何端口:`listen(` 全库只许 main.m 日志端口一处,且监听线程只在 DM_LOG_PORT 测试开关下起
# The product package listens on no port: across the whole codebase `listen(` is allowed only at the log port in main.m, and the listening thread only starts under the DM_LOG_PORT test switch
nl=$(grep -rn 'listen(' Sources ../host --include='*.c' --include='*.m' | grep -v '^[^:]*:[0-9]*:\s*//' | wc -l | tr -d ' ')
gl=$(grep -c 'if (log_port && !pthread_create(&lp, NULL, log_port_main' Sources/main.m)
[ "$nl" = 1 ] && [ "$gl" = 1 ] || { t "🔴 端口监听核对失败:listen( 共 $nl 处(只许 1),开关守卫 $gl 处(须 1)"; exit 1; }
# 原版衍生资源(加宽储藏箱、百宝囊框、选角面板、小地图终点、技能图集、底部 UI v4 …)不进仓库,每次从游戏文件生成(tools/gen_assets.py;dm/README.md「从你的游戏文件生成资源」)
# Assets derived from the original game (widened stash, pouch frame, character select panel, minimap goal, skill atlas, bottom UI v4 ...) are not committed to the repository and are generated from game files every time (tools/gen_assets.py; dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files))
python3 tools/gen_assets.py "${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}" || { t "🔴 gen_assets 失败(见上)"; exit 1; }
make -s -C ../host dm_vault_tab.h dm_hud_exp.h dm_bright_levels.inc ROMFS="${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}" || { t "🔴 宿主表头生成失败(见上)"; exit 1; }
python3 tools/gen_build.py ../host Gen > Gen/dm.xcconfig || { t "🔴 gen_build 失败"; exit 1; }
F=$(python3 tools/gen_embed.py $OUT Gen/embed.S $MODS) || { t "🔴 gen_embed 失败"; exit 1; }
echo "OTHER_LDFLAGS = \$(inherited) \$(DM_FRAMEWORKS) $F" >> Gen/dm.xcconfig
for m in $MODS; do cp $OUT/$m.fixups.tsv $OUT/$m.gates.tsv Gen/dm/; done
# 启动块清单(缺省开预取:宿主到产物目录 = App 内 dm/ 找 bootlist.tsv)+ main.cuts.tsv(宿主据此核清单构建号);产物没有就不带
# Boot block list (prefetch on by default: the host looks for bootlist.tsv in the build output directory = dm/ inside the App) + main.cuts.tsv (the host uses it to check the list's build ID); not included if the build output lacks them
for f in bootlist.tsv main.cuts.tsv; do [ -f $OUT/$f ] && cp $OUT/$f Gen/dm/; done
# 图形:着色器映射表(与 Mac 同一份)+ iOS 版 metallib 缓存(PC 链 iphoneos 目标,已编,覆盖映射表 6,938/6,938;APFS 克隆不占空间)
# Graphics: shader mapping table (the same copy as on Mac) + iOS metallib cache (PC chain iphoneos target, already compiled, covers 6,938/6,938 of the mapping table; APFS clones take no space)
cp ../gfx/nvn/shader_map.tsv Gen/dm/ # 映射表(B 路线只用来查阶段) | Mapping table (route B only uses it to look up the stage)
cp ../gfx/nvn/pso_manifest.tsv Gen/dm/ # 预热种子清单(与映射表同目录) | Warm-up seed list (same directory as the mapping table)
cp ../gfx/nvn/c1_full.tsv Gen/dm/ # c1 运行时下标未证有界的着色器清单(与映射表同目录;缺失则全部 c1 独占 64 KiB 并报红) | List of shaders whose c1 runtime index is not proven bounded (same directory as the mapping table; if missing, every c1 gets an exclusive 64 KiB and a failure is reported)
# 着色器:B 路线(Switch 原版翻译)iOS 版 <键>_b.metallib + <键>_b.json,缺失回放层报红、不回退。
# 出包:J=10 IOSOUT=<本目录> python3 ../gfx/tools/dmsh_build.py $DM_ROOT/build/cache/dm/dmsh <Mac 缓存目录>(编译口径 tools/ios_metal.py)
# 宿主只从 DM_MSL_DIR/b-<V>/ 加载(V = dm/gfx/nvn/dmsh_chain.h 的翻译链版本),App 内放成 msl/b-<V>/,只带当前版本
# Shaders: route B (translated from the Switch original) iOS <key>_b.metallib + <key>_b.json; if missing, the replay layer reports a failure and does not fall back.
# To build: J=10 IOSOUT=<this directory> python3 ../gfx/tools/dmsh_build.py $DM_ROOT/build/cache/dm/dmsh <Mac cache dir> (compile settings in tools/ios_metal.py)
# The host loads only from DM_MSL_DIR/b-<V>/ (V = the translation chain version in dm/gfx/nvn/dmsh_chain.h); inside the App it is placed as msl/b-<V>/, carrying only the current version
MSL=${DM_MSL_IOS:-${DM_ROOT:-$HOME/dm-work}/build/ios/dmsh_b}; V=$(sed -n 's/^#define DMSH_CHAIN "\(.*\)"/\1/p' ../gfx/nvn/dmsh_chain.h)
[ -n "$V" ] && [ -d "$MSL/b-$V" ] && ls "$MSL/b-$V" | grep -q "_b.metallib$" || { t "🔴 缺 iOS 版 B 着色器 $MSL/b-$V(见上一行出包命令;V=$V)"; exit 1; }
mkdir -p Gen/msl && cp -cR "$MSL/b-$V" Gen/msl/
# 资源直接下载(直装包,Sources/asset_dl.m):地址文件列表(仓库里的 asset_pointers.txt)+ 出包时的缺省下载根地址(DM_ASSET_BASE,tools/adhoc.sh 传隧道地址;没传就不带)
# Direct asset download (direct-install package, Sources/asset_dl.m): URL file list (asset_pointers.txt in the repository) + the default download root URL at packaging time (DM_ASSET_BASE; tools/adhoc.sh passes the tunnel URL; omitted if not passed)
cp asset_pointers.txt Gen/dm/; [ -n "${DM_ASSET_BASE:-}" ] && echo "$DM_ASSET_BASE" > Gen/dm/asset_base.txt
# 老机型补充包的自动下载根地址(DM_ASTC_PACK_BASE,<根>/manifest.json + <根>/data/…;没传 = 只能玩家用「文件」拷,见 Sources/asset_dl.m)
# Root URL for automatic download of the Legacy Device Pack (DM_ASTC_PACK_BASE, <root>/manifest.json + <root>/data/...; not passed = players can only copy it with the Files app, see Sources/asset_dl.m)
rm -f Gen/dm/astc_pack_base.txt; [ -n "${DM_ASTC_PACK_BASE:-}" ] && echo "$DM_ASTC_PACK_BASE" > Gen/dm/astc_pack_base.txt
rm -rf Gen/save_ref; mkdir -p Gen/save_ref; if [ -d "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0" ]; then cp -R "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0/." Gen/save_ref/ && chmod -R u+w Gen/save_ref; elif [ "${DM_REQUIRE_SAVES:-0}" = 1 ]; then t "🔴 正式出包要带标准存档(DM_REQUIRE_SAVES=1),但 ${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0 不在"; exit 1; fi # 标准存档(DM_SAVE_FRESH=1 用,80 KB) | Standard save (used with DM_SAVE_FRESH=1, 80 KB)
rm -rf Gen/save_ref_warlock; mkdir -p Gen/save_ref_warlock; if [ -d "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001/0" ]; then cp -R "${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001/0/." Gen/save_ref_warlock/ && chmod -R u+w Gen/save_ref_warlock; elif [ "${DM_REQUIRE_SAVES:-0}" = 1 ]; then t "🔴 正式出包要带标准存档(DM_REQUIRE_SAVES=1),但 ${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref_warlock/0000000000000001/0 不在"; exit 1; fi # 术士存档(DM_SAVE_FRESH=warlock,浸泡 / cvd 回放用,92 KB) | Warlock save (DM_SAVE_FRESH=warlock, used for soak / cvd replay, 92 KB)
# RomFS 覆盖层(底部 UI v4:Gen/assets/NativeHUD/v4 → 借用路径底图 + 手柄 HUD 布局),App 启动按 DM_ROMFS_OVERLAY 先查本层
# 老机型补充包(DM_ASTC_PACK = 补充包目录,dm/tools/astc_pack.py 的产物):设了才另出一套 ASTC 版覆盖层(Gen/romfs_overlay_astc*),不支持 BC 的机型用;没设(如 TestFlight)这两个目录为空
# RomFS overlay (bottom UI v4: Gen/assets/NativeHUD/v4 → base image at the borrowed path + controller HUD layout); at App launch this layer is looked up first according to DM_ROMFS_OVERLAY
# Legacy Device Pack (DM_ASTC_PACK = Legacy Device Pack directory, the build output of dm/tools/astc_pack.py): only when set is an additional ASTC overlay produced (Gen/romfs_overlay_astc*), used by devices that do not support BC; when unset (e.g. TestFlight) these two directories are empty
python3 tools/gen_romfs_overlay.py "${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}" Gen/romfs_overlay > /dev/null || { t "🔴 gen_romfs_overlay 失败"; exit 1; }
# 游戏的配置文件只认 App 自带的这份(玩家那边的资源只核档案文件,见 host/romfs_validate.c):每一套覆盖层里都得有,缺一套出包失败
# The game only accepts the config file bundled with the App (on the player's side only the archive files of the resources are checked, see
# host/romfs_validate.c): every overlay set must contain one, and packaging fails if any set lacks it
for o in Gen/romfs_overlay Gen/romfs_overlay_variants/* Gen/romfs_overlay_astc Gen/romfs_overlay_astc_variants/*; do
[ -d "$o/data" ] || continue; grep -q '^vfs-root = ' "$o/data/.build.config" 2>/dev/null || { t "🔴 覆盖层 $o 里没有可用的配置文件 data/.build.config"; exit 1; }
done
[ -f Gen/romfs_overlay/data/.build.config ] || { t "🔴 没生成覆盖层 Gen/romfs_overlay"; exit 1; }
# 免费的开发者账号(个人团队)签不了这几项权限:DM_FREE_ACCOUNT=1 时从工程描述里去掉再生成。去掉后少的是 iCloud 存档同步、
# 持续执行模式与更高的内存上限;游戏照常运行(地址预留已按不带扩展虚拟寻址也放得下来定,见 host/hle_svc.c)
# A free developer account (personal team) cannot sign these entitlements: with DM_FREE_ACCOUNT=1 they are removed from the project
# description before generating. What is lost is iCloud save sync,
# sustained execution mode and the higher memory limit; the game runs as usual (the address reservation is already sized to fit without
# extended virtual addressing, see host/hle_svc.c)
if [ "${DM_FREE_ACCOUNT:-0}" = 1 ]; then
python3 tools/project_free.py project.yml project_free.yml || { t "🔴 DM_FREE_ACCOUNT:免费档的工程描述没生成(见上)"; exit 1; } # 去掉签不了的六行权限与用不上的资源下载扩展 | remove the six entitlement lines it cannot sign and the asset download extension it has no use for
xcodegen generate -q --spec project_free.yml >/dev/null || { t "🔴 xcodegen 失败"; exit 1; }; rm -f project_free.yml; t "按免费账号生成:不带 iCloud / 持续执行 / 增加内存上限 / 扩展虚拟寻址,也不带资源下载扩展(只占一个应用标识)"
else
xcodegen generate -q >/dev/null || { t "🔴 xcodegen 失败"; exit 1; }
fi
[ "${DM_GEN_ONLY:-}" = 1 ] && { t "生成完成(DM_GEN_ONLY)"; exit 0; } # tools/testflight.sh 只要生成,自己 archive | tools/testflight.sh only needs the generation step and does the archive itself
asc_auth # App Store Connect API 密钥(有就带上,供签名自动注册 App Group 等能力;见 tools/asc_env.sh) | App Store Connect API key (included if present, so signing can auto-register capabilities such as the App Group; see tools/asc_env.sh)
# 开发包带上被测提交的标识(真机收数时把包里的标识读出来核对,不靠「锁内装过包」推断):构建号 = HEAD 的提交时间戳,
# 启动日志首行「boot: 版本 … 构建 N」原样打出来,tools/uireg/run_dev.sh 收数时核。工作区有未提交改动 = 认不出是哪个提交 → 构建号留 1,这种包不能用于放行。
# 只影响这条开发包构建命令:正式包(tools/testflight.sh、tools/adhoc.sh)与 Mac 包(tools/smoke_mac.sh)带 DM_GEN_ONLY=1 进来,上面一行就退出了,各自的构建号不经过这里。
# Development packages carry the identity of the commit under test (when collecting results from a real device, the identity is read out of the package
# and checked, rather than inferred from "a package was installed while holding the lock"): build number = the commit timestamp of HEAD,
# printed verbatim in the first line of the boot log ("boot: version ... build N") and checked by tools/uireg/run_dev.sh when collecting results.
# Uncommitted changes in the working tree = the commit cannot be identified → the build number stays 1, and such a package cannot be used for release
# sign-off.
# This affects only this development package build command: release packages (tools/testflight.sh, tools/adhoc.sh) and the Mac package
# (tools/smoke_mac.sh) come in with DM_GEN_ONLY=1 and exit on the line above, so their build numbers do not pass through here.
BN=$(git log -1 --format=%ct 2>/dev/null); [ -n "$(git status --porcelain --untracked-files=no 2>/dev/null)" ] && BN=1; BN=${BN:-1}
[ "$BN" = 1 ] && t "⚠ 工作区有未提交改动(或读不到提交):开发包构建号 = 1,不能用于放行" || t "开发包构建号 $BN(提交 $(git log -1 --format=%h | cut -c1-9) 的提交时间戳)"
# 构建目标:平常是「通用 iOS 设备」。免费账号(个人团队)名下起初没有任何设备,苹果不给生成描述文件
# (「Your team has no devices from which to generate a provisioning profile」,真拿免费账号签时实测撞到)——
# 所以免费档改用连着的那台手机做目标(DM_IOS_UDID),构建时 Xcode 会把它登记到团队名下。付费账号不受影响,照旧用通用目标。
# Build destination: normally "generic iOS device". A free account (personal team) initially has no devices under its name, and Apple will not generate a provisioning profile
# ("Your team has no devices from which to generate a provisioning profile", hit when actually signing with a free account) --
# so the free mode uses the connected phone as the destination instead (DM_IOS_UDID), and during the build Xcode registers it under the team. Paid accounts are unaffected and keep using the generic destination.
DEST='generic/platform=iOS'
if [ "${DM_FREE_ACCOUNT:-0}" = 1 ]; then
if [ -n "${DM_IOS_UDID:-}" ]; then DEST="id=$DM_IOS_UDID"; t "免费账号:用已连接的设备做构建目标(先把手机用数据线连上并解锁)"
else t "⚠ 免费账号第一次构建要把手机连上,并在本机配置里填 DM_IOS_UDID(见 local.env.example);没填,先按通用目标试"; fi
fi
xcodebuild -project DmIOS.xcodeproj -scheme DmIOS -configuration Release -destination "$DEST" \
-derivedDataPath "$DD" -allowProvisioningUpdates ${ASC_AUTH[@]+"${ASC_AUTH[@]}"} DM_BUILD_NUMBER=$BN ${DM_DEVICE_FAMILY:+DM_DEVICE_FAMILY=$DM_DEVICE_FAMILY} build > "$R/build.log" 2>&1 || { t "🔴 构建失败"; grep -E "error:" "$R/build.log" | head -5
grep -q 'no devices from which to generate a provisioning profile' "$R/build.log" && t "原因:这个团队名下还没有设备。把手机用数据线连上并解锁,在本机配置里填 DM_IOS_UDID、DM_FREE_ACCOUNT=1,再构建一次"; exit 1; }
codesign -d --entitlements :- $APP 2>/dev/null | plutil -p - ; t "构建完成"
# DM_NOINSTALL 保持兼容;build 现在本来就只编译,不触碰设备。
# DM_NOINSTALL is kept for compatibility; build now only compiles anyway and does not touch the device.
t "构建完成"; exit 0
fi
if [ "$1" = install ]; then
local_env_need DM_DEVICE || exit 1
devlock_acquire "${SMOKE_OWNER:-${ACCEPT_OWNER:-run.sh install}}"
trap devlock_release EXIT
xcrun devicectl device install app --device $D "$APP" > $R/install.log 2>&1 || { t "🔴 装机失败"; tail -5 $R/install.log; exit 1; }
t "装机完成"; exit 0
fi
local_env_need DM_DEVICE || exit 1
M=$1; CAP=${2:-60}; O=$R/out/$M.txt; rm -f $O
devlock_acquire "${SMOKE_OWNER:-${ACCEPT_OWNER:-run.sh $M}}"
trap devlock_release EXIT
xcrun devicectl device process launch --device $D --terminate-existing $B -mode $M > $R/launch_$M.log 2>&1
grep -q Launched $R/launch_$M.log || { t "🔴 启动失败"; tail -8 $R/launch_$M.log; exit 1; }
pull(){ xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source Documents/$M.txt --destination $O >/dev/null 2>&1; }
alive(){ xcrun devicectl device info processes --device $D 2>/dev/null | grep -q "DmIOS.app/DmIOS"; }
s=$SECONDS; sleep 3
while :; do pull; grep -q DONE $O 2>/dev/null && { t "$M 完成"; cat $O; exit 0; }
alive || { sleep 1; pull; t "$M 进程已退出"; cat $O 2>/dev/null; exit 0; }
[ $((SECONDS - s)) -gt $CAP ] && { t "🔴 $M 超 ${CAP}s"; cat $O 2>/dev/null; exit 1; }; sleep 3; done
+19
View File
@@ -0,0 +1,19 @@
t_touch_controls
*.dSYM/
/t_native_binding
/t_game_bridge
/t_binding_freshness
/t_portal_sequence
/t_binding_group
/t_native_hud_identity
/t_native_hud_bridge
/t_native_art
/t_skill_aim
/t_metal_cache_guard
/t_joy_travel
+64
View File
@@ -0,0 +1,64 @@
DM_ROOT ?= $(HOME)/dm-work
CC ?= cc
CFLAGS ?= -std=c11 -Wall -Wextra -Werror -pedantic -O2
TARGET = t_touch_controls
METAL_CACHE_TARGET = t_metal_cache_guard
BINDING_TARGETS = t_native_binding t_game_bridge t_binding_freshness t_portal_sequence t_binding_group t_native_hud_identity t_native_hud_bridge
BINDING_FIXTURES = fixtures/native_binding/mapping.bin fixtures/native_binding/bindings.bin
# 这两份夹具是从运行中的游戏内存抓下来的两张表,公开仓库不带(见 fixtures/native_binding/README)。不在就跳过要读它们的三个测试并说明,别的照跑
# These two fixtures are tables captured from the memory of the running game, and the public repository does not ship them (see fixtures/native_binding/README). When they are absent, the three tests that read them are skipped with an explanation, and everything else still runs
HAVE_BINDING_FIXTURES := $(and $(wildcard fixtures/native_binding/mapping.bin),$(wildcard fixtures/native_binding/bindings.bin))
fixture_test = $(if $(HAVE_BINDING_FIXTURES),./$(1) $(BINDING_FIXTURES),@echo "跳过 $(1):没有夹具 $(BINDING_FIXTURES)(公开仓库不带,要自己从运行中的游戏抓,见 fixtures/native_binding/README)")
.PHONY: all run test clean
all: $(TARGET) $(BINDING_TARGETS) t_native_art t_skill_aim t_joy_travel $(METAL_CACHE_TARGET)
run: test
$(TARGET): t_touch_controls.c $(wildcard ../Sources/dm_touch_controls.[ch]) ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_touch_controls.c ../Sources/dm_touch_controls.c -lm -o $@
t_native_binding: t_native_binding.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_native_binding.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_controls.c -lm -o $@
t_game_bridge: t_game_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -DDM_TG_TEST_SYNTHETIC_IDENTITY -I../Sources t_game_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_state.c -lpthread -o $@
t_binding_freshness: t_binding_freshness.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_binding_freshness.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_controls.c -lm -o $@
t_portal_sequence: t_portal_sequence.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h
$(CC) $(CFLAGS) -I../Sources t_portal_sequence.c ../Sources/dm_touch_controls.c -lm -o $@
t_binding_group: t_binding_group.c ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../Sources t_binding_group.c ../Sources/dm_touch_game_state.c -o $@
t_native_hud_identity: t_native_hud_identity.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.h
$(CC) $(CFLAGS) -I../Sources t_native_hud_identity.c ../Sources/dm_touch_game_identity.c -o $@
t_native_hud_bridge: t_native_hud_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_identity.h ../Sources/dm_touch_game_state.c ../Sources/dm_touch_game_state.h ../../host/dm.h
$(CC) $(CFLAGS) -I../Sources t_native_hud_bridge.c ../Sources/dm_touch_game_bridge.c ../Sources/dm_touch_game_identity.c ../Sources/dm_touch_game_state.c -lpthread -o $@
# 技能图集 / 技能索引由原版表生成、不进仓库(tools/native_art/generate.py;dm/README.md「从你的游戏文件生成资源」)
# The skill atlas / skill index are generated from the original game's tables and are not kept in the repository (tools/native_art/generate.py; dm/README.md 「从你的游戏文件生成资源」(Generating assets from your game files))
ROMFS?=$(or $(DM_ROMFS_SRC),$(DM_ROOT)/data/switch/3.3.94012/Update/RomFS)
../Sources/dm_touch_native_art.c: ../tools/native_art/generate.py ../tools/native_art/implementation.c.inc ../Sources/TouchArt/native_art_manifest.json
python3 ../tools/native_art/generate.py "$(ROMFS)"
t_native_art: t_native_art.c ../Sources/dm_touch_native_art.c ../Sources/dm_touch_native_art.h
$(CC) $(CFLAGS) -I../Sources t_native_art.c ../Sources/dm_touch_native_art.c -o $@
t_skill_aim: t_skill_aim.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_skill_aim.c ../Sources/dm_touch_controls.c -lm -o $@
t_joy_travel: t_joy_travel.c ../Sources/dm_touch_controls.c ../Sources/dm_touch_controls.h ../../host/dm_input.h
$(CC) $(CFLAGS) -I../Sources t_joy_travel.c ../Sources/dm_touch_controls.c -lm -o $@
t_metal_cache_guard: t_metal_cache_guard.c ../Sources/dm_metal_cache_guard.c ../Sources/dm_metal_cache_guard.h
$(CC) $(CFLAGS) -I../Sources t_metal_cache_guard.c ../Sources/dm_metal_cache_guard.c -o $@
test: $(TARGET) $(BINDING_TARGETS) t_native_art t_skill_aim t_joy_travel $(METAL_CACHE_TARGET)
./$(METAL_CACHE_TARGET)
./$(TARGET)
./t_skill_aim
./t_joy_travel
./t_native_art
python3 test_native_art_capture.py
$(call fixture_test,t_native_binding)
$(call fixture_test,t_game_bridge)
./t_binding_freshness
./t_portal_sequence
./t_binding_group
./t_native_hud_identity
$(call fixture_test,t_native_hud_bridge)
python3 test_portal_receipt.py
python3 test_native_binding_seam.py
python3 test_skill_aim_front.py
python3 test_touch_receipt.py --source ../Sources/front_ios.m
clean:
rm -f $(TARGET) $(BINDING_TARGETS) t_native_art t_skill_aim t_joy_travel $(METAL_CACHE_TARGET)
@@ -0,0 +1 @@
!*.bin
+45
View File
@@ -0,0 +1,45 @@
# native_binding — test fixtures for skill binding parsing
中文:[README.zh-CN.md](README.zh-CN.md)
For unit tests only. The app does not read these two files at run time, and the tests do not modify them.
**The public repository does not ship these two fixtures**: they are two tables captured from the memory of the running game. Without them, the three tests below that read the fixtures are skipped automatically with a one-line notice, and the other tests run as usual. To run those three tests you have to capture the two tables from the running game yourself and put them in this directory under the file names below; the assertions in the tests are written against the contents of the snapshot described below, so with different contents the assertions have to be changed accordingly.
## Background
The skill buttons on the right need to show "which skill this button is bound to right now". In the memory of the running game this information is two tables, which the shell fetches read-only and then parses (`../../../Sources/dm_touch_game_bridge.c` does the fetching, and `dm_tg_parse` in `../../../Sources/dm_touch_game_state.c` does the parsing):
- **Button mapping table**: for each of the six gamepad buttons (B, A, Y, X, R, ZR), which normal skill slot and which alternate skill slot it corresponds to. The alternate slots are the set used while ZL is held.
- **Binding table**: the skill ID bound in each skill slot; an empty slot is `0xFFFFFFFF`.
## Files
| File | Size | Contents |
|---|---|---|
| `mapping.bin` | 114 bytes | A snapshot of the button mapping table. Parsing uses only the first 72 bytes: 6 entries, each of 3 32-bit little-endian integers (logical button, normal slot, alternate slot) |
| `bindings.bin` | 896 bytes | A snapshot of the binding table: 32 entries of 28 bytes each; the 32-bit little-endian integer at the start of each entry is the skill ID |
The contents of this snapshot, which the assertions in the tests are written against:
- Button mapping: B → normal slot 1 / alternate slot 7, A → 0 / 6, Y → 2 / 8, X → 3 / 9, R → 4 / 10, ZR → 5 / 11.
- Bindings: slots 0, 2 and 7 of the first group have skills, the rest are empty; the second group, starting from entry 16, is entirely empty. Slot 7 is the town portal skill, so in the parse result the way to press town portal is ZL + B.
Checksums (SHA-256):
```
b9777515f225f235ac1223dd04bf15db250f1240f893511737ceecf357367362 mapping.bin
4d4f4cde5d08f35f9a988ac61aff54913499d32322ac95fa3ce7763c16a11262 bindings.bin
```
## Who uses them
The `test` target of `dm/ios/tests/Makefile` passes these two files as arguments to three tests (when the files are absent, these three tests are skipped):
| Test | What it verifies with them |
|---|---|
| `t_native_binding` | Parsing: in the normal case it reads out the button mapping and the town portal button combination above; when the length is too short, a slot number is out of range, a button is duplicated, or the observed skill ID does not match, it rejects in every case |
| `t_game_bridge` | Puts the two tables into a block of simulated game memory and verifies the whole path from reading memory to producing a snapshot: reading does not modify registers or the tables; no snapshot is produced when not in a game |
| `t_native_hud_bridge` | Same as above, and additionally verifies that a snapshot is produced only after confirming that the call comes from the HUD of the current game, and that after switching to another game it has to be confirmed again |
To run: `make -C dm/ios/tests test`.
+45
View File
@@ -0,0 +1,45 @@
# native_binding — 技能绑定解析的测试夹具
English: [README.md](README.md)
只给单元测试用。App 运行时不读这两个文件,测试也不会改它们。
**公开仓库不带这两份夹具**:它们是从运行中的游戏内存抓下来的两张表。缺了它们,下面三个要读夹具的测试自动跳过并打印一行说明,其余测试照常。要跑这三个测试,得自己从运行中的游戏抓这两张表,照下面的文件名放到本目录;测试里的断言是按下面这份快照的内容写的,内容不同就要相应改断言。
## 背景
右侧技能钮上要显示「这个键现在绑着哪个技能」。这份信息在运行中的游戏内存里是两张表,外壳只读地取出来再解析(`../../../Sources/dm_touch_game_bridge.c` 负责取,`../../../Sources/dm_touch_game_state.c` 的 `dm_tg_parse` 负责解析):
- **键位表**:六个手柄键(B、A、Y、X、R、ZR)各对应哪个普通技能槽、哪个替代技能槽。替代槽是按住 ZL 时用的那一套。
- **绑定表**:每个技能槽里绑着的技能编号,空槽是 `0xFFFFFFFF`。
## 文件
| 文件 | 大小 | 内容 |
|---|---|---|
| `mapping.bin` | 114 字节 | 键位表的一份快照。解析只用前 72 字节:6 项,每项 3 个 32 位小端整数(逻辑键、普通槽、替代槽) |
| `bindings.bin` | 896 字节 | 绑定表的一份快照:32 项,每项 28 字节,每项开头的 32 位小端整数是技能编号 |
这份快照里的内容,测试里的断言按它写:
- 键位:B → 普通槽 1 / 替代槽 7,A → 0 / 6,Y → 2 / 8,X → 3 / 9,R → 4 / 10,ZR → 5 / 11。
- 绑定:第一组的 0、2、7 号槽有技能,其余为空;从第 16 项起的第二组全空。7 号槽是回城技能,所以解析结果里回城的按法是 ZL + B。
校验值(SHA-256):
```
b9777515f225f235ac1223dd04bf15db250f1240f893511737ceecf357367362 mapping.bin
4d4f4cde5d08f35f9a988ac61aff54913499d32322ac95fa3ce7763c16a11262 bindings.bin
```
## 谁在用
`dm/ios/tests/Makefile` 的 `test` 目标把这两个文件作为参数传给三个测试(文件不在时这三个测试跳过):
| 测试 | 用它验什么 |
|---|---|
| `t_native_binding` | 解析:正常情况读出上面的键位与回城按法;长度不够、槽号越界、键位重复、观察到的技能编号对不上时一律拒绝 |
| `t_game_bridge` | 把两张表放进一块模拟的游戏内存,验从内存读取到产出快照的整条通路:读取不改寄存器、不改表;不在局内时不出快照 |
| `t_native_hud_bridge` | 同上,另验要先确认调用来自当前这一局的 HUD 才出快照,换了一局要重新确认 |
运行:`make -C dm/ios/tests test`。
+79
View File
@@ -0,0 +1,79 @@
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static int log_fd;
static int stderr_copy;
static int tee_pipe[2];
static void write_all(int fd, const char *p, size_t n) {
while (n) {
ssize_t w = write(fd, p, n);
if (w > 0) { p += w; n -= (size_t)w; }
else if (w < 0 && errno == EINTR) continue;
else abort();
}
}
static void *tee_main(void *unused) {
(void)unused;
char buf[128], line[256];
size_t used = 0;
for (;;) {
ssize_t n = read(tee_pipe[0], buf, sizeof buf);
if (n == 0) break;
if (n < 0 && errno == EINTR) continue;
if (n < 0) abort();
for (ssize_t i = 0; i < n; i++) {
line[used++] = buf[i];
if (buf[i] == '\n') {
write_all(log_fd, line, used);
if (fsync(log_fd)) abort();
write_all(stderr_copy, line, used);
used = 0;
}
}
}
if (used) {
write_all(log_fd, line, used);
if (fsync(log_fd)) abort();
write_all(stderr_copy, line, used);
}
return NULL;
}
int main(void) {
char path[] = "dm/ios/tests/.log_tee_test.XXXXXX";
int capture[2];
pthread_t thread;
char expected[] = "LOG one\nUIMSG two\n";
char actual[sizeof expected] = {0};
char console[sizeof expected] = {0};
int fd;
log_fd = mkstemp(path);
if (log_fd < 0 || pipe(tee_pipe) || pipe(capture)) return 1;
stderr_copy = capture[1];
if (pthread_create(&thread, NULL, tee_main, NULL)) return 1;
if (dup2(tee_pipe[1], STDERR_FILENO) < 0) return 1;
write_all(STDERR_FILENO, expected, sizeof expected - 1);
close(tee_pipe[1]);
close(STDERR_FILENO);
if (pthread_join(thread, NULL)) return 1;
close(capture[1]);
if (read(capture[0], console, sizeof console - 1) != (ssize_t)(sizeof expected - 1)) return 1;
if (memcmp(console, expected, sizeof expected - 1)) return 1;
fd = open(path, O_RDONLY);
if (fd < 0 || read(fd, actual + 0, sizeof actual - 1) != (ssize_t)(sizeof expected - 1)) return 1;
lseek(fd, 0, SEEK_SET);
memset(actual, 0, sizeof actual);
if (read(fd, actual, sizeof actual - 1) != (ssize_t)(sizeof expected - 1)) return 1;
if (memcmp(actual, expected, sizeof expected - 1)) return 1;
unlink(path);
puts("log tee: file lines and stderr lines match; fsync per line passed");
return 0;
}
+32
View File
@@ -0,0 +1,32 @@
#include "dm_touch_game_state.h"
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <stdlib.h>
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *,uint64_t);
#ifdef RED_BASELINE
/* v1旧策略的测试替身:valid永久复用,故意不检查时间。 | Test double for the old v1 policy: valid is reused forever, deliberately not checking time. */
uint64_t dm_tg_portal_mask(const dm_tg_snapshot *s,uint64_t n){(void)n;return s->valid?s->portal.buttons:0;}
#endif
static int checks;
#define CHECK(x) do{checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);exit(1);}}while(0)
static void press(dm_tc_state *c,int n,int t){dm_tc_begin(c,n,c->layout.target[t].x,c->layout.target[t].y); if(t>=DM_TC_MAIN && t<=DM_TC_SKILL4) dm_tc_tick(c,c->last_time_s+0.1); /* 已过点按 / 拖动的判定时间 | The tap / drag decision time has passed */}
int main(void){
dm_tg_snapshot s={.supported=1,.valid=1,.ready=1,.captured_ns=1000000000,.portal={.valid=1,.buttons=258}};
CHECK(dm_tg_portal_mask(&s,1250000001)==0);
CHECK(dm_tg_portal_mask(&s,1250000000)==258);CHECK(dm_tg_portal_mask(&s,1000000000)==258);
CHECK(dm_tg_portal_mask(&s,999999999)==0);s.captured_ns=0;CHECK(dm_tg_portal_mask(&s,1)==0);
s.captured_ns=1000000000;s.valid=0;CHECK(dm_tg_portal_mask(&s,1000000000)==0);
s.valid=1;s.supported=0;CHECK(dm_tg_portal_mask(&s,1000000000)==0);
s.supported=1;s.portal.valid=0;CHECK(dm_tg_portal_mask(&s,1000000000)==0);s.portal.valid=1;
dm_tc_state c;dm_tc_init(&c,667,375);dm_tc_set_portal_button(&c,dm_tg_portal_mask(&s,1000000000));
press(&c,0,DM_TC_PORTAL);press(&c,1,DM_TC_MAIN);dm_tc_begin(&c,2,90,275);dm_tc_move(&c,2,150,275);int32_t lx=c.lx;
CHECK(c.buttons==257 && c.portal_pending && lx==32767);
CHECK(dm_tc_portal_ack(&c,c.gesture_epoch,0,0));CHECK(c.buttons==259 && lx==32767);
dm_tc_set_portal_button(&c,dm_tg_portal_mask(&s,1250000001));
CHECK(!c.finger[0].active && c.finger[1].active && c.finger[2].active && c.buttons==1 && c.lx==lx);
s.portal.buttons=257;dm_tc_set_portal_button(&c,dm_tg_portal_mask(&s,1000000000));
CHECK(c.buttons==1 && c.lx==lx);press(&c,3,DM_TC_PORTAL);CHECK(c.buttons==257 && c.portal_pending);
s.portal.buttons=264;dm_tc_set_portal_button(&c,dm_tg_portal_mask(&s,1000000000));CHECK(!c.finger[3].active && c.buttons==1 && c.lx==lx);
printf("PASS synthetic host-clock freshness+held-map-change %d/%d checks\n",checks,checks);return 0;
}
+38
View File
@@ -0,0 +1,38 @@
#include "dm_touch_game_state.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef RED_BASELINE
int dm_tg_group_observe(dm_tg_group *g,const dm_tg_snapshot *s,int game,uint64_t scene,uint64_t caller,uint64_t hud,int scope){(void)game;(void)scene;(void)caller;(void)hud;(void)scope;g->completed=*s;g->completed.ready=1;return 1;}
#endif
static int checks;
#define CHECK(x) do{checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);exit(1);}}while(0)
static int feed(dm_tg_group *g,dm_tg_snapshot *s,int arg,int game,int scope,uint64_t scene,uint64_t caller,uint64_t hud){s->getter_input_slot=arg;s->observed_index=s->selected_bank+arg;s->captured_ns++;return dm_tg_group_observe(g,s,game,scene,caller,hud,scope);}
int main(void){
dm_tg_snapshot s={.supported=1,.valid=1,.captured_ns=100,.portal={.valid=1,.buttons=258}};dm_tg_group g={0};
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));CHECK(!g.completed.ready && g.seen==1);
for(int i=7;i<11;i++)CHECK(!feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));
CHECK(feed(&g,&s,11,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));CHECK(g.completed.ready && g.completed.secondary_group==1 && g.completed.group_seen==63 && g.completed.group_started_ns==101);
uint64_t identity=g.completed.binding_identity;CHECK(identity!=0);
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_UNCONFIRMED,1,77,88));CHECK(!g.completed.ready);
for(int i=0;i<6;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88);CHECK(g.completed.ready && !g.completed.secondary_group);
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));CHECK(g.completed.ready && !g.completed.secondary_group); // 旧完整normal暂留,不能单alt伪ACK | the old complete normal is kept for now; a lone alt must not fake an ACK
for(int i=0;i<6;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88);
CHECK(!g.completed.secondary_group); // normal/alt不混群 | normal/alt are not mixed into one group
s.selected_bank=16;CHECK(!feed(&g,&s,7,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));CHECK(!g.completed.ready);
s.selected_bank=0;for(int i=6;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88);CHECK(g.completed.ready);
s.raw_skill_id[3]++;CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88));CHECK(!g.completed.ready);
for(int i=7;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,1,77,88);CHECK(g.completed.ready && g.completed.binding_identity!=identity);
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,2,77,88));CHECK(!g.completed.ready);
for(int i=7;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,2,77,88);CHECK(g.completed.ready && g.completed.scene_epoch==2);
CHECK(!feed(&g,&s,6,0,DM_TG_IDENTITY_SYNTHETIC,2,77,88));CHECK(!g.completed.ready);
for(int i=6;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,2,77,88);CHECK(g.completed.ready);
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,2,99,88));CHECK(!g.completed.ready);
for(int i=7;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,2,99,88);CHECK(g.completed.ready);
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,2,99,0));CHECK(!g.completed.ready);
for(int i=6;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,2,99,88);CHECK(g.completed.ready);
uint64_t world_identity=g.completed.binding_identity;s.world_epoch=1;
CHECK(!feed(&g,&s,6,1,DM_TG_IDENTITY_SYNTHETIC,2,99,88));CHECK(!g.completed.ready);
for(int i=7;i<12;i++)feed(&g,&s,i,1,DM_TG_IDENTITY_SYNTHETIC,2,99,88);CHECK(g.completed.ready && g.completed.binding_identity!=world_identity);
printf("PASS six-facet group+scope/scene/bank/map-ID identity %d/%d checks\n",checks,checks);return 0;
}
+50
View File
@@ -0,0 +1,50 @@
#include "dm_touch_game_state.h"
#include "../../host/dm.h"
#include "../../host/dm_input.h"
#include <assert.h>
module_t g_mod[MAX_MOD];int g_nmod;
static int present,checks,identity_scope=DM_TG_IDENTITY_UNCONFIRMED;
int dm_touch_game_test_identity(const uint64_t *regs,uint64_t *caller,uint64_t *hud) {(void)regs;*caller=77;*hud=88;return identity_scope;}
static void (*hook)(const uint64_t *);
int gate_obs_present(int id) {assert(id==6);return present;}
void gate_obs_set(int id,void (*fn)(const uint64_t *)) {assert(id==6);hook=fn;}
uint64_t now_ns(void) {return 123456;}
#define CHECK(x) do {checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);return 1;}}while(0)
#ifdef RED_BASELINE
int dm_touch_game_attach(void){return 0;}
int dm_touch_game_snapshot(dm_tg_snapshot *out){memset(out,0,sizeof(*out));return 0;}
#endif
int main(int argc,char **argv) {
CHECK(argc==3);dm_tg_snapshot s;CHECK(dm_touch_game_attach()==0);CHECK(!dm_touch_game_snapshot(&s) && !s.supported);
size_t size=0x2d5f0c0+32*28;unsigned char *mem=calloc(1,size);CHECK(mem!=NULL);
g_mod[0].base=mem;g_mod[0].size=size;strcpy(g_mod[0].name,"main");g_nmod=1;present=1;
CHECK(dm_touch_game_attach()==1);CHECK(hook!=NULL);CHECK(!dm_touch_game_snapshot(&s) && s.supported);
FILE *f=fopen(argv[1],"rb");CHECK(f!=NULL);CHECK(fread(mem+0x2d13cbc,1,72,f)==72);fclose(f);
f=fopen(argv[2],"rb");CHECK(f!=NULL);CHECK(fread(mem+0x2d5f0c0,1,896,f)==896);fclose(f);
uint64_t regs[31]={0};regs[10]=(uint64_t)(mem+0x2d5f0c0);regs[8]=7*28;regs[19]=7;
uint64_t saved[31];memcpy(saved,regs,sizeof regs);unsigned char table[896];memcpy(table,mem+0x2d5f0c0,896);
hook(regs);CHECK(!memcmp(saved,regs,sizeof regs));CHECK(!memcmp(table,mem+0x2d5f0c0,896));
CHECK(!dm_touch_game_snapshot(&s) && !s.valid && !s.ready);
CHECK(!s.ready && s.identity_scope==DM_TG_IDENTITY_UNCONFIRMED);
dm_touch_game_set_scene(1,3,1);identity_scope=DM_TG_IDENTITY_SYNTHETIC;
regs[8]=6*28;regs[19]=6;hook(regs);CHECK(dm_touch_game_snapshot(&s) && !s.ready);
for(int i=7;i<12;i++) {regs[8]=i*28;regs[19]=i;hook(regs);}
CHECK(dm_touch_game_snapshot(&s) && s.ready && s.secondary_group && s.group_seen==63 && s.scene_epoch==3);
s.portal.buttons=0;CHECK(dm_touch_game_snapshot(&s) && s.portal.buttons==258);
regs[8]=16*28;regs[19]=0;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.selected_bank==16 && !s.portal.buttons);
regs[8]=16*28;regs[19]=16;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.selected_bank==16 && !s.portal.buttons); // otherbank显式arg16反例 | counterexample: otherbank with explicit arg16
regs[8]=23*28;regs[19]=7;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.selected_bank==16 && !s.portal.buttons);
regs[8]=7*28;regs[19]=7;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.selected_bank==0 && s.portal.buttons==258);
regs[8]=7*28;regs[19]=6;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.selected_bank==0 && s.portal.buttons==258); // offset-arg=1 IGNORE
const uint64_t bad[]={1,12*28,15*28,28*28,UINT64_MAX};
for(unsigned i=0;i<sizeof bad/sizeof *bad;i++){regs[8]=bad[i];hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.supported && s.portal.buttons==258);}
regs[8]=7*28;regs[19]=7;regs[10]++;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.portal.buttons==258);
regs[10]--;regs[19]=6;hook(regs);CHECK(dm_touch_game_snapshot(&s) && s.portal.buttons==258);
dm_touch_game_set_scene(0,4,1);CHECK(!dm_touch_game_snapshot(&s) && !s.ready && s.scene_epoch==4);
regs[8]=7*28;regs[19]=7;hook(regs);CHECK(!dm_touch_game_snapshot(&s) && !s.ready);
g_mod[0].size=size-1;CHECK(dm_touch_game_attach()==0);CHECK(!dm_touch_game_snapshot(&s) && s.supported);
g_mod[0].size=size;strcpy(g_mod[0].name,"sdk");CHECK(dm_touch_game_attach()==0);
free(mem);printf("PASS adapter synthetic ABI+read-only+negative %d/%d checks\n",checks,checks);return 0;
}
int dm_swapskill_equipped(int32_t item) { (void)item; return 0; } /* 副手组技能(宿主 dm_actions.c):单测里没有穿着的物品 | Secondary weapon set skills (host dm_actions.c): there are no worn items in the unit test */
+42
View File
@@ -0,0 +1,42 @@
/* 移动摇杆:输入行程不跟大屏视觉放大走;iPad 屏幕底边归系统的那一条不起摇杆。期望值按公式手算:幅度 = (位移 − 6) / (60 − 6),满幅 32767。 | Movement stick: the input travel does not follow the visual scale-up on large screens; the strip at the iPad screen bottom edge that belongs to the system does not start the stick. Expected values are hand-computed from the formula: magnitude = (displacement − 6) / (60 − 6), full scale 32767. */
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <stdlib.h>
static int checks;
#define CHECK(x) do { ++checks; if (!(x)) { fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x); exit(1); } } while (0)
static int push(dm_tc_state *s, float w, float h, float d) { /* 在底座圆心起手(底座固定),向右推 d 点,返回横轴输出 | start on the base center (the base is fixed), push d points to the right, return the horizontal axis output */
dm_tc_init(s, w, h); float cx = s->layout.joy_x, cy = s->layout.joy_y; dm_tc_begin(s, 0, cx, cy); CHECK(s->joy_slot == 0);
dm_tc_move(s, 0, cx + d, cy); return s->lx;
}
int main(void) {
dm_tc_state s; dm_tc_set_tall_scale(1); /* 前端的口径:比手机高的画面控件按 高 / 440 放大(1366×768 → 1.745 倍) | The front end's convention: on displays taller than a phone, widgets are scaled up by height / 440 (1366×768 → 1.745×) */
static const float size[][2] = {{956, 440}, {1194, 672}, {1366, 768}}; /* 手机、11 寸 iPad 的 16:9 视图、12.9 寸 iPad 的 16:9 视图 | Phone, the 16:9 view on the 11-inch iPad, the 16:9 view on the 12.9-inch iPad */
for (int i = 0; i < 3; ++i) {
float w = size[i][0], h = size[i][1];
CHECK(push(&s, w, h, 6) == 0); /* 死区 6 点 | Dead zone 6 points */
CHECK(abs(push(&s, w, h, 20) - 8495) <= 1); /* 14 / 54 × 32767 = 8495.1 */
CHECK(abs(push(&s, w, h, 33) - 16384) <= 1); /* 27 / 54 = 一半 | 27 / 54 = half */
CHECK(push(&s, w, h, 60) == DM_STICK_MAX); /* 60 点满偏 | 60 points for full deflection */
CHECK(push(&s, w, h, 105) == DM_STICK_MAX);
CHECK(abs(push(&s, w, h, -20) + 8495) <= 1);
}
dm_tc_init(&s, 1366, 768); CHECK(s.layout.joy_radius > 104 && s.layout.joy_radius < 105); /* 画出来的底盘仍按视觉倍数:60 × 1.745 | The drawn base still follows the visual multiplier: 60 × 1.745 */
/* 底边那一条:手机(没设)照旧能在最底起摇杆 | Bottom-edge strip: a phone (not set) can still start the stick at the very bottom as before */
dm_tc_init(&s, 956, 440); dm_tc_begin(&s, 0, 90, 425); CHECK(s.joy_slot == 0); dm_tc_cancel_all(&s); /* 圆心 90,340、可起手半径 90:(90,425) 在内 | center 90,340, grab radius 90: (90,425) is inside */
/* iPad:底部 20 点里起手不当摇杆、松手不当点地 | iPad: a touch starting in the bottom 20 points is not treated as the stick, and its release is not treated as a ground tap */
dm_tc_set_edge_bottom(20); dm_tc_init(&s, 1366, 768);
dm_tc_begin(&s, 0, 100, 760); CHECK(s.joy_slot == DM_TC_NONE && s.finger[0].target == DM_TC_EDGE);
dm_tc_move(&s, 0, 100, 700); CHECK(s.lx == 0 && s.ly == 0 && s.joy_slot == DM_TC_NONE); /* 划上去也不变成摇杆 | Swiping upward does not turn into the stick either */
dm_tc_end(&s, 0); CHECK(s.world_tap_seq == 0 && s.buttons == 0);
dm_tc_begin(&s, 0, 100, 762); dm_tc_end(&s, 0); CHECK(s.world_tap_seq == 0); /* 原地点一下也不当点地 | A tap in place is not treated as a ground tap either */
dm_tc_begin(&s, 0, 150, 745); CHECK(s.joy_slot == 0); /* 这一条的上沿(768 − 20)不算在内 | The top edge of this strip (768 − 20) is not included */
dm_tc_move(&s, 0, 160, 766); CHECK(s.joy_slot == 0 && s.lx > 0 && s.ly < 0); /* 已起手的摇杆拖进这一条照常持有 | A stick already started is still held as usual when dragged into this strip */
dm_tc_begin(&s, 1, 200, 765); CHECK(s.joy_slot == 0 && s.finger[1].target == DM_TC_EDGE); /* 另一根手指落在这一条:不抢摇杆 | Another finger lands in this strip: it does not grab the stick */
dm_tc_end(&s, 1); CHECK(s.joy_slot == 0 && s.lx > 0);
dm_tc_end(&s, 0); CHECK(s.lx == 0 && s.ly == 0 && s.joy_slot == DM_TC_NONE);
dm_tc_begin(&s, 0, 800, 760); CHECK(s.finger[0].target != DM_TC_EDGE); dm_tc_cancel_all(&s); /* 右半屏不受影响 | The right half of the screen is unaffected */
dm_tc_set_edge_bottom(0);
printf("JOY_TRAVEL OK %d 项\n", checks); return 0;
}
+71
View File
@@ -0,0 +1,71 @@
#include "../Sources/dm_metal_cache_guard.h"
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static void expect(int condition, const char *label) {
if (!condition) {
fprintf(stderr, "FAIL: %s\n", label);
exit(1);
}
}
static void make_directory(const char *path) {
expect(!mkdir(path, 0755) || errno == EEXIST, path);
}
int main(void) {
char root_template[] = "./dm-metal-guard-XXXXXX";
char *root = mkdtemp(root_template);
char absolute_root[PATH_MAX];
char path[PATH_MAX];
expect(root != NULL, "mkdtemp");
expect(realpath(root, absolute_root) != NULL, "realpath fixture");
root = absolute_root;
snprintf(path, sizeof path, "%s/Library", root); make_directory(path);
snprintf(path, sizeof path, "%s/Library/Caches", root); make_directory(path);
snprintf(path, sizeof path, "%s/Library/Caches/com.apple.metal", root); make_directory(path);
snprintf(path, sizeof path, "%s/tmp", root); make_directory(path);
snprintf(path, sizeof path, "%s/Documents", root); make_directory(path);
snprintf(path, sizeof path, "%s/Documents/romfs", root); make_directory(path);
snprintf(path, sizeof path, "%s/Documents/romfs/file", root);
FILE *file = fopen(path, "w"); expect(file != NULL, "fixture file"); fclose(file);
char metal[PATH_MAX], documents[PATH_MAX], romfs[PATH_MAX], parent[PATH_MAX], link_path[PATH_MAX];
snprintf(metal, sizeof metal, "%s/Library/Caches/com.apple.metal", root);
snprintf(documents, sizeof documents, "%s/Documents", root);
snprintf(romfs, sizeof romfs, "%s/Documents/romfs", root);
snprintf(parent, sizeof parent, "%s/..", root);
snprintf(link_path, sizeof link_path, "%s/Library/Caches/metal-link", root);
expect(!symlink(documents, link_path), "symlink fixture");
expect(dm_metal_cache_path_allowed(root, metal), "Caches/com.apple.metal allowed");
expect(!dm_metal_cache_path_allowed(root, romfs), "Documents/romfs rejected");
expect(!dm_metal_cache_path_allowed(root, documents), "Documents rejected");
expect(!dm_metal_cache_path_allowed(root, root), "container root rejected");
expect(!dm_metal_cache_path_allowed(root, parent), "parent component rejected");
expect(!dm_metal_cache_path_allowed(root, link_path), "symlink to Documents rejected");
char appsup[PATH_MAX]; // iOS RomFS 基底在 Library/Application Support/romfs | the iOS RomFS base is at Library/Application Support/romfs
snprintf(appsup, sizeof appsup, "%s/Library/Application Support", root); make_directory(appsup);
snprintf(appsup, sizeof appsup, "%s/Library/Application Support/romfs", root); make_directory(appsup);
expect(!dm_metal_cache_path_allowed(root, appsup), "Application Support/romfs rejected");
puts("metal cache guard: PASS (7 cases)");
expect(!unlink(link_path), "remove fixture symlink");
expect(!unlink(path), "remove fixture file");
expect(!rmdir(romfs), "remove fixture romfs");
expect(!rmdir(documents), "remove fixture Documents");
expect(!rmdir(metal), "remove fixture metal");
expect(!rmdir(appsup), "remove fixture appsup romfs");
snprintf(path, sizeof path, "%s/Library/Application Support", root); expect(!rmdir(path), "remove fixture Application Support");
snprintf(path, sizeof path, "%s/Library/Caches", root); expect(!rmdir(path), "remove fixture Caches");
snprintf(path, sizeof path, "%s/Library", root); expect(!rmdir(path), "remove fixture Library");
snprintf(path, sizeof path, "%s/tmp", root); expect(!rmdir(path), "remove fixture tmp");
expect(!rmdir(root), "remove fixture container");
return 0;
}
+46
View File
@@ -0,0 +1,46 @@
#include "dm_touch_native_art.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <string.h>
static unsigned checks;
#define CHECK(x) do { checks++; if(!(x)){fprintf(stderr,"FAIL line %d: %s\n",__LINE__,#x);return 1;} } while(0)
int main(void) {
dm_ta_glyph g;
const uint32_t ids[]={0,115,219,220,359,395};
const int classes[]={8,3,8,8,8,7},frames[]={2,26,18,18,18,46};
for(unsigned i=0;i<6;i++) {
g=dm_ta_skill(ids[i]);CHECK(g.status==DM_TA_GLYPH);CHECK(g.raw_skill_id==ids[i]);
CHECK(g.atlas==classes[i]);CHECK(g.normal_frame==frames[i]);CHECK(g.pressed_frame==frames[i]+1);
}
CHECK(dm_ta_skill(UINT32_MAX).status==DM_TA_EMPTY);
CHECK(dm_ta_skill(1000000).status==DM_TA_UNKNOWN);
dm_ta_frame f;CHECK(dm_ta_frame_at(8,18,&f));CHECK(f.x==1224&&f.y==0&&f.width==65&&f.height==65);
CHECK(dm_ta_frame_at(8,39,&f));CHECK(!dm_ta_frame_at(8,40,&f));CHECK(!dm_ta_frame_at(9,0,&f));CHECK(!dm_ta_frame_at(0,-1,&f));
CHECK(dm_ta_frame_at(7,59,&f));CHECK(!dm_ta_frame_at(7,60,&f));
dm_tg_snapshot s={0};s.supported=s.valid=s.ready=1;s.source=1;s.identity_scope=1;s.captured_ns=1000;s.selected_bank=0;
const uint32_t logicals[]={0x1000,0x2000,0x4000,0x8000,0x200,0x800};
for(int i=0;i<6;i++){s.mapping[i]=(dm_tg_mapping){logicals[i],(uint32_t)i,(uint32_t)(i+6)};s.raw_skill_id[i]=ids[i];}
/* 按原runtime tuple而非数组顺序:A normal0/B1/X3/Y2/R4。 | By the original runtime tuple rather than array order: A normal0/B1/X3/Y2/R4. */
s.mapping[0].normal=1;s.mapping[1].normal=0;
const uint64_t buttons[]={DM_BTN_A,DM_BTN_B,DM_BTN_X,DM_BTN_Y,DM_BTN_R};
const int slots[]={0,1,3,2,4};
for(int i=0;i<5;i++){g=dm_ta_current(&s,buttons[i],1000);CHECK(g.status==DM_TA_GLYPH);CHECK(g.slot==slots[i]);CHECK(g.raw_skill_id==ids[slots[i]]);CHECK(g.effective_slot==slots[i]);}
/* 银行16所复制的12 ID数组独立,不能退回银行0图。 | The 12-ID array copied by bank 16 is independent and must not fall back to the bank 0 image. */
s.selected_bank=16;for(int i=0;i<12;i++)s.raw_skill_id[i]=UINT32_MAX;
g=dm_ta_current(&s,DM_BTN_A,1000);CHECK(g.status==DM_TA_EMPTY);CHECK(g.slot==0&&g.effective_slot==16);
s.raw_skill_id[0]=395;g=dm_ta_current(&s,DM_BTN_A,1000);CHECK(g.atlas==7&&g.normal_frame==46&&g.effective_slot==16);
s.raw_skill_id[0]=1000000;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);
s.raw_skill_id[0]=0;
CHECK(dm_ta_current(&s,DM_BTN_A,1000+DM_TG_MAX_AGE_NS).status==DM_TA_GLYPH);
CHECK(dm_ta_current(&s,DM_BTN_A,1001+DM_TG_MAX_AGE_NS).status==DM_TA_UNKNOWN);
CHECK(dm_ta_current(&s,DM_BTN_A,999).status==DM_TA_UNKNOWN);
s.ready=0;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.ready=1;
s.valid=0;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.valid=1;
s.supported=0;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.supported=1;
s.source=0;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.source=1;
s.identity_scope=2;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.identity_scope=1;
s.captured_ns=0;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.captured_ns=1000;
s.selected_bank=1;CHECK(dm_ta_current(&s,DM_BTN_A,1000).status==DM_TA_UNKNOWN);s.selected_bank=0;
CHECK(dm_ta_current(&s,DM_BTN_A|DM_BTN_B,1000).status==DM_TA_UNKNOWN);
printf("PASS native_art: %u/%u checks; official IDs6; tuple facets5; banks0/16; frame bounds; freshness/source/identity gates\n",checks,checks);return 0;
}
+65
View File
@@ -0,0 +1,65 @@
#include "dm_touch_game_state.h"
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int checks;
#define CHECK(x) do { ++checks; if(!(x)) { fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x); exit(1); } } while(0)
#ifdef RED_BASELINE
/* 测试专用缺失功能基线,不进入Sources。 | Test-only missing-feature baseline, does not go into Sources. */
int dm_tg_parse(dm_tg_snapshot *o,const void *m,size_t ml,const void *b,size_t bl,int k,int input,int i,uint32_t id,uint64_t n) {(void)m;(void)ml;(void)b;(void)bl;(void)k;(void)input;(void)i;(void)id;(void)n;memset(o,0,sizeof(*o));return 0;}
void dm_tc_set_portal_button(dm_tc_state *s,uint64_t b) {(void)s;(void)b;}
#endif
void dm_tc_set_portal_button(dm_tc_state *,uint64_t);
static void put(unsigned char *p,uint32_t v) { for(int i=0;i<4;i++)p[i]=(unsigned char)(v>>(i*8)); }
static void press(dm_tc_state *s,int n,int t) { dm_tc_begin(s,n,s->layout.target[t].x,s->layout.target[t].y); }
int main(int argc,char **argv) {
CHECK(argc==3); unsigned char map[114],table[896];
FILE *f=fopen(argv[1],"rb"); CHECK(f!=NULL);CHECK(fread(map,1,sizeof map,f)==sizeof map);fclose(f);
f=fopen(argv[2],"rb");CHECK(f!=NULL);CHECK(fread(table,1,sizeof table,f)==sizeof table);fclose(f);
dm_tg_snapshot s;
CHECK(dm_tg_parse(&s,map,sizeof map,table,12*28,0,(7-0),7,359,99));
CHECK(s.valid && s.source==DM_TG_SOURCE_NATIVE_GETTER && s.selected_bank==0 && s.captured_ns==99);
CHECK(s.mapping[0].logical==0x1000 && s.mapping[0].normal==1 && s.mapping[0].alt==7);
CHECK(s.portal.valid && s.portal.slot==7 && s.portal.raw_skill_id==359 && s.portal.buttons==(DM_BTN_ZL|DM_BTN_B));
unsigned char changed[896]; memcpy(changed,table,sizeof changed);
put(changed+7*28,UINT32_MAX);put(changed+6*28,220);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(6-0),6,220,100));CHECK(s.portal.buttons==(DM_BTN_ZL|DM_BTN_A));
put(changed+6*28,UINT32_MAX);put(changed+5*28,219);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(5-0),5,219,101));CHECK(s.portal.buttons==DM_BTN_ZR);
put(changed+5*28,UINT32_MAX);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(0-0),0,0,102));CHECK(s.valid && !s.portal.valid && s.portal.buttons==0);
CHECK(dm_tg_parse(&s,map,72,table+16*28,336,16,(16-16),16,UINT32_MAX,103));CHECK(s.selected_bank==16 && !s.portal.valid);
CHECK(!dm_tg_parse(&s,map,71,table,336,0,(7-0),7,359,1));CHECK(!s.valid && !s.portal.buttons);
CHECK(!dm_tg_parse(&s,map,72,table,335,0,(7-0),7,359,1));
CHECK(!dm_tg_parse(&s,map,72,table,336,0,(12-0),12,359,1));
CHECK(!dm_tg_parse(&s,map,72,table,336,16,(7-16),7,359,1));
CHECK(!dm_tg_parse(&s,map,72,table,336,0,(7-0),7,220,1));
unsigned char badmap[72];memcpy(badmap,map,72);put(badmap+12,0x1000);
CHECK(!dm_tg_parse(&s,badmap,72,table,336,0,(7-0),7,359,1));
memcpy(badmap,map,72);put(badmap+16,1);CHECK(!dm_tg_parse(&s,badmap,72,table,336,0,(7-0),7,359,1));
memcpy(badmap,map,72);put(badmap+20,7);CHECK(!dm_tg_parse(&s,badmap,72,table,336,0,(7-0),7,359,1));
memcpy(badmap,map,72);put(badmap,0xDEAD);CHECK(!dm_tg_parse(&s,badmap,72,table,336,0,(7-0),7,359,1));
const uint64_t facets[6]={DM_BTN_B,DM_BTN_A,DM_BTN_Y,DM_BTN_X,DM_BTN_R,DM_BTN_ZR};
for(int alt=0;alt<2;alt++)for(int facet=0;facet<6;facet++) {
memset(changed,255,sizeof changed);int slot=map[facet*12+(alt?8:4)];put(changed+slot*28,359);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(slot-0),slot,359,104));
CHECK(s.portal.buttons==(facets[facet]|(alt?DM_BTN_ZL:0)) && s.portal.slot==slot);
}
memset(changed,255,sizeof changed);put(changed,219);put(changed+7*28,359);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(0-0),0,219,105));CHECK(s.portal.slot==7);
put(changed+7*28,360);put(changed,UINT32_MAX);
CHECK(dm_tg_parse(&s,map,72,changed,336,0,(7-0),7,360,106));CHECK(!s.portal.valid && !s.portal.buttons);
dm_tc_state c;dm_tc_init(&c,667,375);dm_tc_set_portal_button(&c,DM_BTN_ZL|DM_BTN_B);
press(&c,0,DM_TC_PORTAL);press(&c,1,DM_TC_MAIN);dm_tc_begin(&c,2,100,200);dm_tc_move(&c,2,150,200);
CHECK(c.buttons==(DM_BTN_ZL|DM_BTN_A) && c.portal_pending);
CHECK(dm_tc_portal_ack(&c,c.gesture_epoch,0,0));
CHECK(c.buttons==(DM_BTN_ZL|DM_BTN_B|DM_BTN_A));int32_t lx=c.lx;
dm_tc_set_portal_button(&c,DM_BTN_ZL|DM_BTN_B);CHECK(c.finger[0].active);
dm_tc_set_portal_button(&c,DM_BTN_ZL|DM_BTN_A);
CHECK(!c.finger[0].active && c.finger[1].active && c.finger[2].active && c.lx==lx && c.buttons==DM_BTN_A);
dm_tc_resize(&c,812,375);CHECK(c.layout.target[DM_TC_PORTAL].button==(DM_BTN_ZL|DM_BTN_A));
dm_tc_set_portal_button(&c,0);press(&c,0,DM_TC_PORTAL);CHECK(c.buttons==0 && c.joy_slot==-1);
printf("PASS native binding fixture+negative+ownership %d/%d checks\n",checks,checks);return 0;
}
+52
View File
@@ -0,0 +1,52 @@
#include "dm_touch_game_state.h"
#include "../../host/dm.h"
#ifdef RED_BASELINE
#define SCENE(g,s,w) dm_touch_game_set_scene(g,s)
#define WORLD(s) 0
#else
#define SCENE(g,s,w) dm_touch_game_set_scene(g,s,w)
#define WORLD(s) ((s).world_epoch)
#endif
module_t g_mod[MAX_MOD];int g_nmod;
static void (*hook)(const uint64_t *);
static int checks,clock_reads,x23_off; /* x23_off!=0:让到门时 x23 != x19(不是 HUD updater 那条调用) | x23_off!=0: make x23 != x19 on reaching the gate (not the HUD updater call path) */static uint64_t clock_ns=1000;
int gate_obs_present(int id){return id==6;}
void gate_obs_set(int id,void (*fn)(const uint64_t *)){if(id==6)hook=fn;}
uint64_t now_ns(void){clock_reads++;return ++clock_ns;}
#define CHECK(x) do{checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);exit(1);}}while(0)
static void emit(uint64_t *regs,uint64_t *frame,unsigned char widget[7][0xc98],int slot,int arg,uint64_t caller){frame[1]=(uint64_t)widget[slot];frame[3]=caller;regs[19]=(uint64_t)arg;regs[23]=(uint64_t)arg+(uint64_t)x23_off;regs[8]=(uint64_t)arg*28;uint64_t before[31],stack_before[8];unsigned char widgets_before[7][0xc98];memcpy(before,regs,sizeof before);memcpy(stack_before,frame,sizeof stack_before);memcpy(widgets_before,widget,sizeof widgets_before);hook(regs);CHECK(!memcmp(before,regs,sizeof before) && !memcmp(stack_before,frame,sizeof stack_before) && !memcmp(widgets_before,widget,sizeof widgets_before));}
int main(int argc,char **argv){
CHECK(argc==3);size_t size=0x2d5f0c0+896;unsigned char *mem=calloc(1,size);CHECK(mem!=NULL);g_nmod=1;g_mod[0].base=mem;g_mod[0].size=size;strcpy(g_mod[0].name,"main");
FILE *f=fopen(argv[1],"rb");CHECK(f!=NULL);CHECK(fread(mem+0x2d13cbc,1,72,f)==72);fclose(f);f=fopen(argv[2],"rb");CHECK(f!=NULL);CHECK(fread(mem+0x2d5f0c0,1,896,f)==896);fclose(f);
unsigned char original_mapping[72],original_table[896];memcpy(original_mapping,mem+0x2d13cbc,72);memcpy(original_table,mem+0x2d5f0c0,896);
unsigned char widget[7][0xc98]={{0}};for(uint32_t i=0;i<7;i++){uint32_t slot=i<6?i:5;memcpy(widget[i]+0xb18,&slot,4);}
uint64_t regs[31]={0},frame[8]={0};regs[29]=(uint64_t)&frame[2];regs[10]=(uint64_t)(mem+0x2d5f0c0);uint64_t hud_lr=(uint64_t)mem+0x3e2f74;dm_tg_snapshot s,before;
CHECK(dm_touch_game_attach() && hook!=NULL);SCENE(1,2,1);
for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);
CHECK(!dm_touch_game_snapshot(&s) && !s.ready && clock_reads==0); // 首cohort不借第六体变ready。 | the first cohort does not borrow the sixth body to become ready.
for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);
CHECK(dm_touch_game_snapshot(&s) && s.ready && s.identity_scope==DM_TG_IDENTITY_NATIVE && s.group_seen==63 && s.portal.buttons==258 && WORLD(s)==1);
before=s;int reads=clock_reads;
for(int i=0;i<12;i++)emit(regs,frame,widget,i%6,i,(uint64_t)mem+0x2fa1d0);
CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s) && clock_reads==reads); // cache不撤、不续时。 | cache is not revoked and its time is not extended.
x23_off=1;for(int i=0;i<6;i++)emit(regs,frame,widget,i,i+6,hud_lr);x23_off=0;
CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s) && clock_reads==reads); // 前置筛:栈帧里的返回地址与控件都对、只有 x23 != x19,也当非 HUD 调用忽略——不切组、不续时。 | pre-filter: the return address in the stack frame and the widget are both right and only x23 != x19, still ignored as a non-HUD call - no set switch, no time extension.
emit(regs,frame,widget,5,16,hud_lr);CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s));
emit(regs,frame,widget,5,0,hud_lr);CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s));
widget[5][0xc90]=1;emit(regs,frame,widget,5,11,hud_lr);widget[5][0xc90]=0;CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s));
uint64_t fp=regs[29];regs[29]=1;emit(regs,frame,widget,5,11,hud_lr);regs[29]=fp;CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s));
emit(regs,frame,widget,6,11,hud_lr);CHECK(dm_touch_game_snapshot(&s) && !memcmp(&s,&before,sizeof s));
CHECK(dm_tg_portal_mask(&s,s.captured_ns+250000001)==0); // cache不能延长fresh窗口。 | cache must not extend the fresh window.
for(int i=0;i<6;i++)emit(regs,frame,widget,i,i+6,hud_lr);
CHECK(dm_touch_game_snapshot(&s) && s.ready && s.secondary_group && s.group_started_ns>before.captured_ns && s.hud_identity==before.hud_identity);
uint64_t cohort=s.hud_identity;SCENE(0,3,1);emit(regs,frame,widget,6,11,hud_lr);CHECK(!dm_touch_game_snapshot(&s));
SCENE(1,4,1);emit(regs,frame,widget,6,11,hud_lr);CHECK(!dm_touch_game_snapshot(&s)); // 菜单六体不追认/回game不重学。 | the six menu bodies are not retroactively accepted / returning to game does not relearn.
for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);CHECK(dm_touch_game_snapshot(&s) && s.ready && s.hud_identity==cohort);
SCENE(0,5,2);for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);CHECK(!dm_touch_game_snapshot(&s));
SCENE(1,6,3);for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);CHECK(!dm_touch_game_snapshot(&s));
for(int i=0;i<6;i++)emit(regs,frame,widget,i,i,hud_lr);CHECK(dm_touch_game_snapshot(&s) && s.ready && WORLD(s)==3 && s.hud_identity!=cohort);
CHECK(!memcmp(original_mapping,mem+0x2d13cbc,72) && !memcmp(original_table,mem+0x2d5f0c0,896));
free(mem);printf("PASS production strong HUD Mach ABI -> group/ignore/world bridge %d/%d checks\n",checks,checks);return 0;
}
int dm_swapskill_equipped(int32_t item) { (void)item; return 0; } /* 副手组技能(宿主 dm_actions.c):单测里没有穿着的物品 | Secondary weapon set skills (host dm_actions.c): there are no worn items in the unit test */
+44
View File
@@ -0,0 +1,44 @@
#include "dm_touch_game_identity.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef RED_BASELINE
int dm_tg_hud_identity(dm_tg_hud_cohort *c,const uint64_t *r,uint64_t b,int g,uint64_t w,dm_tg_read_fn f,uint64_t *l,uint64_t *h){(void)c;(void)r;(void)b;(void)g;(void)w;(void)f;*l=*h=0;return 0;}
void dm_tg_hud_reset(dm_tg_hud_cohort *c,uint64_t w){memset(c,0,sizeof(*c));c->world_epoch=w;}
int dm_tg_vm_read(uint64_t a,void *o,size_t n){memcpy(o,(const void *)a,n);return 1;}
#endif
static int checks,readonly_calls;
static int observed(dm_tg_hud_cohort *c,const uint64_t *r,uint64_t b,int game,uint64_t world,dm_tg_read_fn read_fn,uint64_t *caller,uint64_t *hud) {
uint64_t before[31];memcpy(before,r,sizeof before);
int result=dm_tg_hud_identity(c,r,b,game,world,read_fn,caller,hud);
if(memcmp(before,r,sizeof before)){fprintf(stderr,"FAIL native resolver changed regs\n");exit(1);}++readonly_calls;return result;
}
#define dm_tg_hud_identity observed
#define CHECK(x) do{checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);exit(1);}}while(0)
static int failed_read(uint64_t a,void *o,size_t n){(void)a;(void)o;(void)n;return 0;}
static void put32(unsigned char *p,uint32_t n){memcpy(p,&n,4);}
int main(void){
const uint64_t base=0x123000000;unsigned char widget[7][0xc98]={{0}};uint64_t frame[8]={0},regs[31]={0},caller=0,hud=0;
regs[29]=(uint64_t)&frame[2];frame[3]=base+0x3e2f74;dm_tg_hud_cohort c;dm_tg_hud_reset(&c,1);
for(int i=0;i<6;i++) {put32(widget[i]+0xb18,(uint32_t)i);frame[1]=(uint64_t)widget[i];regs[19]=(uint64_t)i;CHECK(dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud)==0);}
CHECK(c.confirmed && c.seen==63 && c.hud_identity!=0);uint64_t identity=c.hud_identity;
for(int i=0;i<6;i++){frame[1]=(uint64_t)widget[i];regs[19]=(uint64_t)(i+6);CHECK(dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud)==DM_TG_IDENTITY_NATIVE);CHECK(caller==base+0x3e2f74 && hud==identity);}
unsigned char original[sizeof widget];memcpy(original,widget,sizeof widget);
frame[3]=base+0x2fa1d0;for(int i=0;i<12;i++){regs[19]=(uint64_t)i;CHECK(dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud)==0);}CHECK(c.hud_identity==identity && c.confirmed);
frame[3]=base+0x3e2f74;regs[19]=16;CHECK(!dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud));
regs[19]=0;frame[1]=(uint64_t)widget[5];CHECK(!dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud)); // widget enum5 versus arg0
regs[19]=11;widget[5][0xc90]=1;CHECK(!dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud));widget[5][0xc90]=0;
CHECK(!dm_tg_hud_identity(&c,regs,base,1,1,failed_read,&caller,&hud));
CHECK(!dm_tg_hud_identity(&c,regs,base,0,1,dm_tg_vm_read,&caller,&hud));CHECK(c.hud_identity==identity && c.confirmed);
put32(widget[6]+0xb18,5);frame[1]=(uint64_t)widget[6];CHECK(!dm_tg_hud_identity(&c,regs,base,1,1,dm_tg_vm_read,&caller,&hud));CHECK(c.widget[5]==(uint64_t)widget[5] && c.hud_identity==identity);
dm_tg_hud_reset(&c,2);CHECK(!c.confirmed && !c.seen);
for(int i=0;i<6;i++){frame[1]=(uint64_t)widget[i];regs[19]=(uint64_t)i;CHECK(!dm_tg_hud_identity(&c,regs,base,0,2,dm_tg_vm_read,&caller,&hud));}CHECK(!c.seen && !c.confirmed);
for(int i=0;i<6;i++){frame[1]=(uint64_t)widget[i];regs[19]=(uint64_t)i;CHECK(!dm_tg_hud_identity(&c,regs,base,1,2,dm_tg_vm_read,&caller,&hud));}CHECK(c.confirmed && c.hud_identity!=identity);
frame[1]=(uint64_t)widget[5];regs[19]=5;CHECK(dm_tg_hud_identity(&c,regs,base,1,2,dm_tg_vm_read,&caller,&hud)==1);
frame[1]=1;regs[19]=5;CHECK(!dm_tg_hud_identity(&c,regs,base,1,2,dm_tg_vm_read,&caller,&hud)); // 真Mach读取坏堆指针。 | a real Mach read of a bad heap pointer.
dm_tg_hud_reset(&c,3);frame[1]=(uint64_t)widget[0];regs[19]=0;CHECK(!dm_tg_hud_identity(&c,regs,base,1,3,dm_tg_vm_read,&caller,&hud));
put32(widget[0]+0xb18,1);regs[19]=1;CHECK(!dm_tg_hud_identity(&c,regs,base,1,3,dm_tg_vm_read,&caller,&hud));CHECK(c.seen==1 && !c.widget[1]);put32(widget[0]+0xb18,0);
CHECK(!dm_tg_vm_read(1,&caller,8));CHECK(!dm_tg_vm_read(UINT64_MAX,&caller,8));
CHECK(!memcmp(widget,original,6*sizeof widget[0])); // 原six widget无写入;第七是测试替身。 | no writes to the original six widgets; the seventh is a test double.
printf("PASS native Mach FramePointer/HUD cohort/cache/world negative %d/%d checks; %d/%d calls regs read-only\n",checks,checks,readonly_calls,readonly_calls);return 0;
}
+37
View File
@@ -0,0 +1,37 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <stdlib.h>
#ifdef RED_BASELINE
/* v2测试替身:旧直接组合与缺失ACK。 | v2 test double: old direct combination and missing ACK. */
static int dm_tc_portal_ack(dm_tc_state *s,uint64_t e,uint64_t b,uint64_t c){(void)s;(void)e;(void)b;(void)c;return 0;}
static void dm_tc_set_portal_binding(dm_tc_state *s,uint64_t mask,uint64_t b,uint64_t c){(void)b;(void)c;dm_tc_set_portal_button(s,mask);}
#define EPOCH(s) 0
#else
#define EPOCH(s) ((s).gesture_epoch)
#endif
static int checks;
#define CHECK(x) do{checks++;if(!(x)){fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x);exit(1);}}while(0)
static void press(dm_tc_state *s,int n,int target){dm_tc_begin(s,n,s->layout.target[target].x,s->layout.target[target].y); if(target>=DM_TC_MAIN && target<=DM_TC_SKILL4) dm_tc_tick(s,s->last_time_s+0.1); /* 主钮 / 技能钮按下后有判定时间(点按还是拖动),这里的「按下」= 已过判定时间 | After the main button / a skill button is pressed there is a decision time (tap or drag); here "pressed" = the decision time has passed */}
int main(void){
dm_tc_state s;dm_tc_init(&s,667,375);dm_tc_set_portal_binding(&s,258,77,3);press(&s,0,DM_TC_PORTAL);
CHECK(s.buttons==256);uint64_t epoch=EPOCH(s);
press(&s,1,DM_TC_MAIN);dm_tc_begin(&s,2,90,275);dm_tc_move(&s,2,150,275);CHECK(s.buttons==257 && s.lx==32767);
CHECK(!dm_tc_portal_ack(&s,epoch+1,77,3));CHECK(!dm_tc_portal_ack(&s,epoch,78,3));CHECK(!dm_tc_portal_ack(&s,epoch,77,4));CHECK(s.buttons==257);
press(&s,3,DM_TC_PORTAL);CHECK(EPOCH(s)==epoch && s.buttons==257);
CHECK(dm_tc_portal_ack(&s,epoch,77,3));CHECK(s.buttons==259 && s.lx==32767);CHECK(!dm_tc_portal_ack(&s,epoch,77,3));
press(&s,4,DM_TC_PORTAL);CHECK(EPOCH(s)==epoch && s.buttons==259);
dm_tc_end(&s,0);CHECK(s.buttons==259 && s.lx==32767 && s.finger[3].active && s.finger[4].active && EPOCH(s)==epoch);
dm_tc_end(&s,3);CHECK(s.buttons==259 && EPOCH(s)==epoch);dm_tc_end(&s,4);CHECK(s.buttons==1 && s.lx==32767);CHECK(!dm_tc_portal_ack(&s,epoch,77,3));
press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);CHECK(s.buttons==257);dm_tc_set_portal_binding(&s,258,78,3);CHECK(s.buttons==1 && s.lx==32767);CHECK(!dm_tc_portal_ack(&s,epoch,77,3));
press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);dm_tc_set_portal_binding(&s,258,78,4);CHECK(s.buttons==1);CHECK(!dm_tc_portal_ack(&s,epoch,78,3));
press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);dm_tc_set_portal_button(&s,0);CHECK(s.buttons==1 && s.lx==32767);CHECK(!dm_tc_portal_ack(&s,epoch,78,4));
dm_tc_set_portal_binding(&s,258,79,4);press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);dm_tc_end(&s,0);CHECK(s.buttons==1);CHECK(!dm_tc_portal_ack(&s,epoch,79,4));
press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);dm_tc_cancel_all(&s);CHECK(s.buttons==0 && s.lx==0);CHECK(!dm_tc_portal_ack(&s,epoch,79,4));
press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);dm_tc_resize(&s,812,375);CHECK(s.buttons==0);CHECK(!dm_tc_portal_ack(&s,epoch,79,4));
dm_tc_set_portal_binding(&s,512,80,5);press(&s,0,DM_TC_PORTAL);CHECK(s.buttons==512);dm_tc_end(&s,0);CHECK(s.buttons==0);
dm_tc_set_portal_binding(&s,258,81,6);press(&s,0,DM_TC_PORTAL);epoch=EPOCH(s);press(&s,1,DM_TC_PORTAL);
CHECK(s.buttons==256 && EPOCH(s)==epoch);dm_tc_end(&s,0);CHECK(s.buttons==256 && EPOCH(s)==epoch);
CHECK(dm_tc_portal_ack(&s,epoch,81,6));CHECK(s.buttons==258);dm_tc_end(&s,1);CHECK(s.buttons==0);CHECK(!dm_tc_portal_ack(&s,epoch,81,6));
printf("PASS portal two-stage+epoch+end/cancel/identity/scene %d/%d checks\n",checks,checks);return 0;
}
+108
View File
@@ -0,0 +1,108 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
static int checks;
#define CHECK(x) do { ++checks; if (!(x)) { fprintf(stderr,"FAIL line=%d %s\n",__LINE__,#x); exit(1); } } while (0)
static void begin(dm_tc_state *s,int n,int target) { dm_tc_begin(s,n,s->layout.target[target].x,s->layout.target[target].y); if(target>=DM_TC_MAIN && target<=DM_TC_SKILL4) dm_tc_tick(s,s->last_time_s+0.1); /* 主钮 / 技能钮按下后有判定时间(点按还是拖动),这里的「按下」= 已过判定时间 | After the main button / a skill button is pressed there is a decision time (tap or drag); here "pressed" = the decision time has passed */ }
static void drag(dm_tc_state *s,int n,int target,float dx,float dy) { dm_tc_move(s,n,s->layout.target[target].x+dx,s->layout.target[target].y+dy); }
int main(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
CHECK(s.rx==0 && s.ry==0 && s.aim_slot==DM_TC_NONE && !s.navigation_mode && !s.map_cancel_active);
begin(&s,0,DM_TC_MAIN); CHECK(s.buttons==DM_BTN_A && s.rx==0 && s.ry==0);
drag(&s,0,DM_TC_MAIN,60,0); CHECK(s.rx==32767 && s.ry==0 && s.aim_slot==0);
drag(&s,0,DM_TC_MAIN,0,60); CHECK(s.rx==0 && s.ry==-32767);
drag(&s,0,DM_TC_MAIN,30,-30); CHECK(s.rx==16384 && s.ry==16384);
drag(&s,0,DM_TC_MAIN,120,-120); CHECK(s.rx==32767 && s.ry==32767);
drag(&s,0,DM_TC_MAIN,0,0); CHECK(s.rx==0 && s.ry==0 && s.aim_slot==0);
dm_tc_begin(&s,1,90,275); dm_tc_move(&s,1,150,275);
drag(&s,0,DM_TC_MAIN,60,0); CHECK(s.lx==32767 && s.ly==0 && s.rx==32767 && s.ry==0);
/* 技能钮与主钮同一套:按下即键下、按住 = 持续施放,后拖动的那根手指定方向,松手键起、不发脉冲 | On-screen skill buttons use the same scheme as the main button: key down on press, hold = continuous cast, the finger that dragged later sets the direction, on release the key goes up, no pulse sent */
begin(&s,2,DM_TC_SKILL1); CHECK(s.buttons==(DM_BTN_A|DM_BTN_B));
drag(&s,2,DM_TC_SKILL1,0,60); CHECK(s.lx==32767 && s.rx==0 && s.ry==-32767 && s.aim_slot==2 && s.buttons==(DM_BTN_A|DM_BTN_B));
dm_tc_tick(&s,s.last_time_s+0.1); dm_tc_end(&s,2); CHECK(s.buttons==DM_BTN_A && s.rx==32767 && s.ry==0 && s.aim_slot==0 && !s.pulse_button); /* 键已按住够久:松手键起,不补脉冲 | The key has been held long enough: on release the key goes up, no make-up pulse */
begin(&s,2,DM_TC_MAIN);
dm_tc_target map=s.layout.target[DM_TC_MAP];
dm_tc_move(&s,2,map.x+map.r,map.y-map.r);
CHECK(s.map_cancel_active && s.buttons==DM_BTN_A && s.rx==32767 && s.lx==32767);
dm_tc_move(&s,2,map.x-map.r-1,map.y); CHECK(!s.map_cancel_active && s.buttons==DM_BTN_A && s.aim_slot==0);
dm_tc_end(&s,0); CHECK(s.buttons==0 && s.rx==0 && s.ry==0 && s.aim_slot==DM_TC_NONE && s.lx==32767);
drag(&s,2,DM_TC_MAIN,60,0); CHECK(s.buttons==0 && s.rx==0 && s.ry==0);
dm_tc_end(&s,2); CHECK(!s.map_cancel_active);
begin(&s,0,DM_TC_SKILL2); drag(&s,0,DM_TC_SKILL2,60,0);
dm_tc_move(&s,0,map.x,map.y); CHECK(s.map_cancel_active && s.buttons==0 && s.rx==0 && s.ry==0 && s.lx==32767);
dm_tc_end(&s,0); CHECK(!s.map_cancel_active && s.lx==32767 && s.buttons==0 && !s.pulse_button); /* 取消区松手不放 | Releasing in the cancel zone does not cast */
begin(&s,0,DM_TC_MAIN); drag(&s,0,DM_TC_MAIN,60,0);
dm_tc_set_navigation_mode(&s,1); CHECK(s.navigation_mode && s.buttons==0 && s.lx==0 && s.rx==0 && s.ry==0);
begin(&s,0,DM_TC_MAIN); drag(&s,0,DM_TC_MAIN,60,0); CHECK(s.buttons==DM_BTN_A && s.rx==0 && s.ry==0);
dm_tc_move(&s,0,map.x,map.y); CHECK(!s.map_cancel_active && s.buttons==DM_BTN_A);
dm_tc_set_navigation_mode(&s,1); CHECK(s.buttons==DM_BTN_A); /* identical mode does not cancel */
dm_tc_set_navigation_mode(&s,0); CHECK(!s.navigation_mode && s.buttons==0 && s.rx==0 && s.ry==0);
begin(&s,0,DM_TC_SKILL3); drag(&s,0,DM_TC_SKILL3,-60,0); CHECK(s.buttons==DM_BTN_Y && s.rx==-32767 && s.ry==0); /* 按住技能钮拖动:键一直按着,朝拖动方向 | Hold an on-screen skill button and drag: the key stays down, facing the drag direction */
dm_tc_move(&s,0,NAN,0); CHECK(s.buttons==DM_BTN_Y && s.rx==-32767); dm_tc_tick(&s,s.last_time_s+0.1); dm_tc_end(&s,0); CHECK(s.buttons==0 && s.rx==0 && s.ry==0 && !s.pulse_button); /* 坏坐标不动;松手键起 | Bad coordinates do nothing; on release the key goes up */
dm_tc_cancel_all(&s); CHECK(s.buttons==0 && s.rx==0 && s.ry==0 && s.aim_slot==DM_TC_NONE && !s.map_cancel_active && !s.pulse_button);
begin(&s,0,DM_TC_SKILL4); drag(&s,0,DM_TC_SKILL4,5,-5);
CHECK(s.buttons==DM_BTN_R && s.rx==0 && s.ry==0); /* 拖动不过 10 点死区 = 点按:不给方向,原版自动选目标 | A drag that does not pass the 10-point dead zone = a tap: no direction given, the original game auto-selects the target */
dm_tc_tick(&s,s.last_time_s+0.1); dm_tc_end(&s,0); CHECK(s.buttons==0);
begin(&s,0,DM_TC_SKILL4); drag(&s,0,DM_TC_SKILL4,0,-60);
dm_tc_resize(&s,333.5f,187.5f); CHECK(s.rx==0 && s.ry==0 && s.buttons==0 && s.aim_slot==DM_TC_NONE && !s.pulse_button);
begin(&s,0,DM_TC_MAIN); drag(&s,0,DM_TC_MAIN,15,-15); CHECK(s.rx==16384 && s.ry==16384);
dm_tc_enable_targets(&s,0); CHECK(s.rx==0 && s.ry==0 && s.buttons==0);
dm_tc_enable_targets(&s,(1u<<DM_TC_COUNT)-1);
const int non_skill[]={DM_TC_PORTAL,DM_TC_BELT1,DM_TC_MENU,DM_TC_MAP};
for(unsigned i=0;i<sizeof(non_skill)/sizeof(*non_skill);i++) {
begin(&s,0,non_skill[i]); drag(&s,0,non_skill[i],30,-30); CHECK(s.rx==0 && s.ry==0 && s.aim_slot==DM_TC_NONE); dm_tc_end(&s,0);
}
dm_tc_resize(&s,667,375); dm_tc_set_portal_binding(&s,DM_BTN_ZL|DM_BTN_B,77,3); begin(&s,3,DM_TC_PORTAL);
begin(&s,0,DM_TC_MAIN); drag(&s,0,DM_TC_MAIN,60,0);
CHECK(s.buttons==(DM_BTN_ZL|DM_BTN_A) && s.rx==32767);
CHECK(dm_tc_portal_ack(&s,s.gesture_epoch,77,3)); CHECK(s.buttons==(DM_BTN_ZL|DM_BTN_B|DM_BTN_A) && s.rx==32767);
dm_tc_end(&s,0); CHECK(s.buttons==(DM_BTN_ZL|DM_BTN_B) && s.rx==0); dm_tc_end(&s,3); CHECK(s.buttons==0);
dm_tc_target main=s.layout.target[DM_TC_MAIN];
dm_tc_begin(&s,0,main.x+10,main.y+10);
dm_tc_move(&s,0,main.x+40,main.y-20); CHECK(s.rx==16384 && s.ry==16384);
dm_tc_move(&s,0,map.x,map.y); CHECK(s.map_cancel_active);
dm_tc_cancel_all(&s); CHECK(!s.map_cancel_active && s.rx==0 && s.ry==0 && s.aim_slot==DM_TC_NONE);
{ /* 拖动定方向:技能钮按下后先等判定时间;拖过死区带着方向立刻键下;按住中改方向键不动(右轴跟着变,宿主每拍重取);点得太短补一个带方向的脉冲 | Drag to set direction: after an on-screen skill button is pressed, first wait for the decision time; dragging past the dead zone presses the key immediately with the direction; changing direction while holding leaves the key untouched (the right axis follows, the host re-reads it every tick); a tap that is too short gets one make-up pulse with the direction */
dm_tc_state t; dm_tc_init(&t,667,375); dm_tc_target k=t.layout.target[DM_TC_SKILL2];
dm_tc_tick(&t,1.00); dm_tc_begin_at(&t,0,k.x,k.y,1.00); CHECK(t.buttons==0); /* 刚按下:等判定 | Just pressed: waiting for the decision */
dm_tc_move_at(&t,0,k.x+60,k.y,1.03); CHECK(t.buttons==DM_BTN_X && t.rx==32767 && t.ry==0); /* 0.03 秒就拖过死区:带着方向键下 | Dragged past the dead zone in just 0.03 seconds: key down carrying the direction */
dm_tc_tick(&t,1.40); dm_tc_move_at(&t,0,k.x,k.y-60,1.40); CHECK(t.buttons==DM_BTN_X && t.rx==0 && t.ry==32767); /* 改成朝上:键一直按着,右轴是新方向 | Changed to upward: the key stays down, and the right axis is the new direction */
dm_tc_end_at(&t,0,2.00); CHECK(t.buttons==0 && !t.pulse_button); /* 键按下过:松手键起,不发脉冲 | The key had been pressed: on release the key goes up, no pulse sent */
dm_tc_tick(&t,3.00); dm_tc_begin_at(&t,0,k.x,k.y,3.00); dm_tc_end_at(&t,0,3.05); CHECK(t.pulse_button==DM_BTN_X && t.buttons==DM_BTN_X && t.rx==0); /* 点得比判定时间短、没拖:补一个不带方向的脉冲 | Tapped shorter than the decision time, no drag: send one make-up pulse with no direction */
CHECK(dm_tc_pulse_end(&t,t.pulse_epoch) && t.buttons==0);
dm_tc_tick(&t,4.00); dm_tc_begin_at(&t,0,k.x,k.y,4.00); dm_tc_tick(&t,4.10); CHECK(t.buttons==DM_BTN_X && t.rx==0); /* 没拖、过了判定时间:键下,不带方向 | No drag and the decision time has passed: key down, with no direction */
dm_tc_end_at(&t,0,4.30); CHECK(t.buttons==0 && !t.pulse_button);
dm_tc_target mn=t.layout.target[DM_TC_MAIN];
dm_tc_tick(&t,5.00); dm_tc_begin_at(&t,0,mn.x,mn.y,5.00); CHECK(t.buttons==DM_BTN_A); dm_tc_end_at(&t,0,5.03); CHECK(t.buttons==0 && !t.pulse_button); /* 主钮:按下即键下,点按不等 | Main button: key down on press, a tap does not wait */
dm_tc_tick(&t,6.00); dm_tc_begin_at(&t,0,k.x,k.y,6.00); dm_tc_tick(&t,6.09); CHECK(t.buttons==DM_BTN_X); dm_tc_end_at(&t,0,6.10); CHECK(t.pulse_button==DM_BTN_X && t.buttons==DM_BTN_X); /* 技能钮点 0.10 秒:键才按下 0.01 秒就松手 → 补成脉冲,不让游戏漏读 | On-screen skill button tapped for 0.10 seconds: released when the key had been down only 0.01 seconds → made up into a pulse so the game does not miss the read */
CHECK(dm_tc_pulse_end(&t,t.pulse_epoch) && t.buttons==0);
}
{ /* 技能组切换:点一下进第二套。ZL 只在用技能时带(手指按着主钮 / 技能钮、技能脉冲在发),且先于技能键 0.17 秒;十字 / 腰带等不带;导航态不按;取消/改尺寸不丢模式 | Skill set switch: one tap enters the second set. ZL is held only while a skill is in use (a finger is on the main button / an on-screen skill button and the skill pulse is being sent), and leads the skill button key by 0.17 seconds; D-pad / belt etc. do not carry it; not pressed in navigation state; cancel/resize does not lose the mode */
dm_tc_state t; dm_tc_init(&t,667,375); dm_tc_target w=t.layout.swap;
CHECK(dm_tc_hit(&t.layout,w.x,w.y)==DM_TC_SWAP && t.skill_set==0);
dm_tc_begin(&t,0,w.x,w.y); CHECK(t.skill_set==1 && t.buttons==0); dm_tc_end(&t,0); CHECK(t.buttons==0);
dm_tc_target k=t.layout.target[DM_TC_SKILL3], mn=t.layout.target[DM_TC_MAIN], mu=t.layout.target[DM_TC_MENU];
dm_tc_tick(&t,10.0); dm_tc_begin_at(&t,1,k.x,k.y,10.0); CHECK(t.buttons==DM_BTN_ZL); /* 刚按下技能钮:ZL 先下 | On-screen skill button just pressed: ZL goes down first */
dm_tc_tick(&t,10.3); CHECK(t.buttons==(DM_BTN_ZL|DM_BTN_Y)); /* ZL 领先够了:技能键下,按住期间一直按着 | ZL has led long enough: the skill button key goes down and stays down for as long as the hold lasts */
dm_tc_end_at(&t,1,10.4); CHECK(t.buttons==0 && t.pulse_button==0); /* 松手:一起放,不发脉冲 | Release: let go together, no pulse sent */
dm_tc_tick(&t,11.0); dm_tc_begin_at(&t,1,k.x,k.y,11.0); dm_tc_end_at(&t,1,11.05); CHECK(t.buttons==DM_BTN_ZL && t.pulse_button==0); /* 点得太短:先只按 ZL | Tapped too briefly: press only ZL first */
dm_tc_tick(&t,11.1); CHECK(t.buttons==DM_BTN_ZL); dm_tc_tick(&t,11.18); CHECK(t.buttons==(DM_BTN_ZL|DM_BTN_Y));
dm_tc_pulse_end(&t,t.pulse_epoch); CHECK(t.buttons==0);
dm_tc_tick(&t,12.0); dm_tc_begin_at(&t,1,mn.x,mn.y,12.0); CHECK(t.buttons==DM_BTN_ZL); /* 主钮:ZL 先下 | Main button: ZL goes down first */
dm_tc_tick(&t,12.1); CHECK(t.buttons==DM_BTN_ZL); dm_tc_tick(&t,12.2); CHECK(t.buttons==(DM_BTN_ZL|DM_BTN_A)); /* 0.17 秒后 A 下,按住期间一直按着 | A goes down 0.17 seconds later and stays down for as long as the hold lasts */
dm_tc_tick(&t,13.0); CHECK(t.buttons==(DM_BTN_ZL|DM_BTN_A)); dm_tc_end_at(&t,1,13.1); CHECK(t.buttons==0);
dm_tc_begin_at(&t,1,mu.x,mu.y,14.0); CHECK(t.buttons==DM_BTN_PLUS); dm_tc_end_at(&t,1,14.1); CHECK(t.buttons==0); /* 十字:不带 ZL | D-pad: without ZL */
{ dm_tc_target bl=t.layout.target[DM_TC_BELT1]; dm_tc_tick(&t,15.0); dm_tc_begin_at(&t,1,bl.x,bl.y,15.0); CHECK(t.buttons==0); dm_tc_end_at(&t,1,15.05); /* 腰带:松手即喝,不带 ZL(带了 = 喂佣兵) | belt: drink on release, without ZL (with it = feed mercenary) */
dm_tc_tick(&t,15.05+0.01); CHECK(t.buttons==DM_BTN_LEFT); dm_tc_pulse_end(&t,t.pulse_epoch); CHECK(t.buttons==0); }
dm_tc_cancel_all(&t); CHECK(t.skill_set==1 && t.buttons==0);
dm_tc_resize(&t,812,375); CHECK(t.skill_set==1);
dm_tc_set_navigation_mode(&t,1); begin(&t,0,DM_TC_MAIN); CHECK(t.buttons==DM_BTN_A); dm_tc_end(&t,0);
dm_tc_begin(&t,0,t.layout.swap.x,t.layout.swap.y); CHECK(t.skill_set==1 && t.buttons==0); dm_tc_end(&t,0);
dm_tc_set_navigation_mode(&t,0); w=t.layout.swap;
dm_tc_begin(&t,0,w.x,w.y); dm_tc_end(&t,0); CHECK(t.skill_set==0 && t.buttons==0);
}
printf("PASS skill drag axes/ownership/map-lock/navigation/resize/Portal coexistence/skill-set swap %d/%d checks\n",checks,checks);
return 0;
}
+552
View File
@@ -0,0 +1,552 @@
#include "dm_touch_controls.h"
#include "../../host/dm_input.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
static int checks, cases;
#define CHECK(expr) do { ++checks; if (!(expr)) { fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #expr); exit(1); } } while (0)
#define NEAR(a,b,e) CHECK(fabs((double)(a)-(double)(b)) <= (e))
#define RUN(f) do { int before = checks; f(); ++cases; printf("PASS %s (%d checks)\n", #f, checks-before); } while (0)
static const uint64_t keys[DM_TC_COUNT] = {
DM_BTN_A, DM_BTN_B, DM_BTN_X, DM_BTN_Y, DM_BTN_R, 0, /* 回城钮不出按键:点下由宿主施放回城 | The town portal button emits no key: on tap the host casts town portal */
DM_BTN_LEFT, DM_BTN_UP, DM_BTN_DOWN, DM_BTN_RIGHT, DM_BTN_PLUS, DM_BTN_MINUS
};
static void press(dm_tc_state *s, int slot, int target) {
dm_tc_target t = s->layout.target[target];
dm_tc_begin(s, slot, t.x, t.y);
if (target >= DM_TC_MAIN && target <= DM_TC_SKILL4) dm_tc_tick(s, s->last_time_s + 0.1); /* 主钮 / 技能钮按下后有判定时间(点按还是拖动),这里的「按下」= 已过判定时间 | After the main button / a skill button is pressed there is a decision time (tap or drag); here "pressed" = the decision time has passed */
}
static int g_tall; /* 本文件里跟着 dm_tc_set_tall_scale 一起设 | Set together with dm_tc_set_tall_scale in this file */
static void layout_at(float w, float h) {
dm_tc_layout l; dm_tc_layout_make(&l, w, h);
NEAR(l.width,w,0); NEAR(l.height,h,0);
for (int i=0; i<DM_TC_COUNT; ++i) {
dm_tc_target a=l.target[i];
CHECK(a.r>0 && isfinite(a.r));
CHECK(a.x-a.r>=0 && a.x+a.r<=w);
CHECK(a.y-a.r>=0 && a.y+a.r<=h);
CHECK(a.button==keys[i]);
CHECK(dm_tc_hit(&l,a.x,a.y)==i);
for (int j=i+1; j<DM_TC_COUNT; ++j) {
dm_tc_target b=l.target[j];
CHECK(hypotf(a.x-b.x,a.y-b.y)>a.r+b.r);
}
}
float k = g_tall && h > 440 ? h/440 : 1; /* 缺省 1;前端开了大画面放大(g_tall)且画面比手机高(iPad 的 16:9 块)时技能钮按画面高度等比放大 | Default 1; when the front end has large-display scale-up on (g_tall) and the display is taller than a phone (the iPad 16:9 block), skill buttons scale up proportionally with display height */
NEAR(l.target[DM_TC_MAIN].r,40*k,0.001);
for (int i=DM_TC_SKILL1; i<=DM_TC_SKILL4; ++i) {
NEAR(l.target[i].r,26*k,0.001);
NEAR(hypotf(l.target[i].x-l.target[0].x,l.target[i].y-l.target[0].y),112*k,0.001);
}
/* 底部 UI v4 六格(第 0 格难度):腰带四列 → 第 1–4 格,功能入口 → 第 5 格;效果图 2868×1320 里格心 x = 1090 + 120×格号、y = 1241.5、
格半宽 57,按屏高换算、以屏宽中线(效果图 1434)居中。
Bottom UI v4 six cells (cell 0 is difficulty): the four belt columns → cells 1–4, function entry → cell 5; in the 2868×1320 mockup the cell center x = 1090 + 120 × cell number, y = 1241.5,
cell half-width 57, converted by screen height and centered on the screen-width center line (mockup 1434). */
const int order[5] = {DM_TC_BELT1, DM_TC_BELT2, DM_TC_BELT3, DM_TC_BELT4, DM_TC_MENU};
float u = h/1320;
for (int c=0; c<5; ++c) {
dm_tc_target t=l.target[order[c]];
NEAR(t.r,57*u,0.001);
NEAR(t.y,1241.5*u,0.001);
NEAR(t.x,w/2+(1090+120*(c+1)-1434)*u,0.01);
}
/* 回城钮(不在底栏):技能弧最上面那颗(技能四)正上方的圆钮,同半径、间距 12 | Town portal button (not in the bottom bar): the round button directly above the topmost one on the skill arc (skill four), same radius, gap 12 */
{ dm_tc_target p=l.target[DM_TC_PORTAL], s4=l.target[DM_TC_SKILL4];
NEAR(p.r,26*k,0.001); NEAR(p.x,s4.x,0.001); NEAR(p.y,s4.y-s4.r-12*k-p.r,0.001); }
}
/* 难度格:第 0 格 = 腰带第 1 格左邻一个格距;点开选择条,选第 8 格 → diff_request=8 并收起;选择期间不发任何按键 | Difficulty cell: cell 0 = one cell pitch to the left of belt cell 1; tap to open the selector strip, select cell 8 → diff_request=8 and collapse; no key is sent during selection */
static void difficulty_picker(void) {
dm_tc_state s; dm_tc_init(&s,956,440);
dm_tc_layout *l=&s.layout; float pitch=440.0f*120/1320;
NEAR(l->diff.x,l->target[DM_TC_BELT1].x-pitch,0.01); NEAR(l->diff.y,l->target[DM_TC_BELT1].y,0.01);
NEAR(l->pick[7].x-l->pick[0].x,7*pitch,0.01); CHECK(l->pick[0].y+l->pick[0].r<l->diff.y-l->diff.r);
NEAR((l->pick[3].x+l->pick[4].x)/2,l->width/2+(1390-1434)*440.0f/1320,0.01); /* 选择条中线 = 两球中线(效果图 1390) | Selector strip center line = the center line between the two orbs (mockup 1390) */
dm_tc_begin(&s,0,l->diff.x,l->diff.y); CHECK(s.diff_open==1 && s.buttons==0); dm_tc_end(&s,0); CHECK(s.buttons==0);
dm_tc_begin(&s,0,l->pick[7].x,l->pick[7].y); CHECK(s.diff_request==8 && s.diff_open==0 && s.buttons==0); dm_tc_end(&s,0);
s.diff_request=0;
dm_tc_begin(&s,0,l->diff.x,l->diff.y); dm_tc_end(&s,0); CHECK(s.diff_open==1);
press(&s,0,DM_TC_BELT2); CHECK(s.diff_open==0 && s.diff_request==0 && s.buttons==0); dm_tc_end(&s,0); /* 点别处:收起并照常处理(腰带按下不再即喝,松手后等单双击,见 belt_tap) | Tap elsewhere: collapses and is handled as usual (a belt press no longer drinks immediately; it waits for single / double tap after release, see belt_tap) */
dm_tc_begin(&s,0,l->diff.x,l->diff.y); dm_tc_end(&s,0); dm_tc_set_navigation_mode(&s,1); CHECK(s.diff_open==0);
dm_tc_begin(&s,0,l->diff.x,l->diff.y); CHECK(s.diff_open==0); /* 导航模式(功能页)不理难度格 | Navigation mode (function page) ignores the difficulty cell */
}
static void layout_667(void) { layout_at(667,375); }
static void layout_812(void) { layout_at(812,375); }
static void layout_956(void) { layout_at(956,440); }
static void layout_1024(void) { layout_at(1024,768); }
static void layout_ipad169(void) { dm_tc_set_tall_scale(g_tall = 1); layout_at(1366,768); dm_tc_set_tall_scale(g_tall = 0); } /* 13 寸 iPad 上居中的 16:9 块:开了放大 | The centered 16:9 block on the 13-inch iPad: scale-up is on */
static void layout_pixels(void) { layout_at(2868,1320); } /* Mac 宿主触屏用例通路把像素数当点数传:没开放大,主钮半径仍是 40、位置不变 | The Mac host touch-case path passes pixel counts as point counts: scale-up is not on, the main button radius is still 40 and its position is unchanged */
static void small_layout(void) {
dm_tc_layout l; dm_tc_layout_make(&l,333.5f,187.5f);
NEAR(l.target[0].r,20,0.001); NEAR(l.joy_radius,30,0.001);
for(int i=0;i<DM_TC_COUNT;i++) {
CHECK(l.target[i].x>=l.target[i].r && l.target[i].x+l.target[i].r<=l.width);
CHECK(l.target[i].y>=l.target[i].r && l.target[i].y+l.target[i].r<=l.height);
for(int j=i+1;j<DM_TC_COUNT;j++) CHECK(hypotf(l.target[i].x-l.target[j].x,l.target[i].y-l.target[j].y)>l.target[i].r+l.target[j].r);
}
}
static void hit_edges(void) {
dm_tc_layout l; dm_tc_layout_make(&l,667,375);
for(int i=0;i<DM_TC_COUNT;i++) {
dm_tc_target t=l.target[i];
CHECK(dm_tc_hit(&l,t.x+t.r,t.y)==i);
CHECK(dm_tc_hit(&l,t.x+t.r+0.01f,t.y)==DM_TC_NONE);
}
CHECK(dm_tc_hit(&l,-1,50)==DM_TC_NONE);
CHECK(dm_tc_hit(&l,800,50)==DM_TC_NONE);
CHECK(dm_tc_hit(&l,NAN,50)==DM_TC_NONE);
}
static void key_hold_and_ownership(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
for(int i=0;i<DM_TC_COUNT;i++) {
if(i>=DM_TC_BELT1&&i<=DM_TC_BELT4) continue; /* 腰带格松手后等单双击,见 belt_single_double | A belt slot waits for single / double tap after release, see belt_single_double */
int release=0; /* 技能钮与主钮同一套:按下即键下、松手键起(按住 = 持续施放) | Skill buttons use the same scheme as the main button: key down on press, key up on release (hold = continuous cast) */
press(&s,0,i);
CHECK(s.buttons==(release?0:keys[i]));
dm_tc_move(&s,0,350,100); CHECK(s.buttons==(release?0:keys[i]));
dm_tc_move(&s,0,s.layout.target[0].x,s.layout.target[0].y); CHECK(s.buttons==(release?0:keys[i]));
dm_tc_tick(&s,s.last_time_s+0.1); dm_tc_end(&s,0); CHECK(s.buttons==(release?keys[i]:0));
if(release) { CHECK(dm_tc_pulse_end(&s,s.pulse_epoch)); CHECK(s.buttons==0); }
}
}
static void two_fingers_same_key(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
press(&s,0,DM_TC_MAIN); press(&s,1,DM_TC_MAIN);
CHECK(s.buttons==DM_BTN_A); dm_tc_end(&s,0); CHECK(s.buttons==DM_BTN_A);
dm_tc_end(&s,1); CHECK(s.buttons==0);
}
static void joystick_deadzone(void) {
/* 底座固定在静止位(667×375:圆心 90,275、半径 60):落在圆心上起手,原点 = 圆心 | the base is fixed at its rest position (667×375: center 90,275, radius 60): starting on the center, origin = center */
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275);
CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,90,0); NEAR(s.joy_origin_y,275,0);
CHECK(s.lx==0 && s.ly==0);
dm_tc_move(&s,0,96,275); CHECK(s.lx==0 && s.ly==0);
dm_tc_move(&s,0,96.1f,275); CHECK(s.lx>0 && s.lx<100 && s.ly==0);
dm_tc_move(&s,0,123,275); CHECK(abs(s.lx-16384)<=1 && s.ly==0);
dm_tc_end(&s,0);
/* 落在底座附近(离圆心不超过 1.5 倍半径 = 90 点):起摇杆,原点仍是圆心,一按下就按「手指相对圆心」出方向((150,275) 在圆心右 60 = 满偏) | landing near the base (no more than 1.5 × radius = 90 points from the center): the joystick starts, the origin is still the center, and from the moment of pressing the direction is "finger relative to the center" ((150,275) is 60 to the right of the center = full deflection) */
dm_tc_begin(&s,0,150,275); CHECK(s.joy_slot==0); NEAR(s.joy_origin_x,90,0); NEAR(s.joy_origin_y,275,0); CHECK(s.lx==DM_STICK_MAX && s.ly==0);
dm_tc_move(&s,0,600,275); CHECK(s.lx==DM_STICK_MAX && s.ly==0); NEAR(s.joy_origin_x,90,0); /* 拖到很远:照样识别,底座不动 | dragged very far: still recognized, the base does not move */
dm_tc_move(&s,0,90,100); CHECK(s.lx==0 && s.ly==DM_STICK_MAX); NEAR(s.joy_origin_y,275,0);
dm_tc_end(&s,0); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0);
dm_tc_begin(&s,0,90,365); CHECK(s.joy_slot==0); dm_tc_end(&s,0); /* 正下方 90 点:刚好在内 | 90 points straight down: just inside */
dm_tc_begin(&s,0,181,275); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); /* 右边 91 点:不起摇杆 | 91 points to the right: no joystick started */
dm_tc_begin(&s,0,250,150); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_move(&s,0,300,150); CHECK(s.joy_slot==-1 && s.lx==0); dm_tc_end(&s,0); /* 左侧别处:不起摇杆,拖也不变成摇杆 | elsewhere on the left: no joystick started, and dragging does not turn into a joystick either */
/* 拖远了的摇杆手指被系统取消,0.35 秒内在原处附近重新落下:接着当摇杆(原点仍是圆心);超时或离得远:不接 | a joystick finger dragged far away is cancelled by the system and lands again near the same spot within 0.35 seconds: it continues as the joystick (the origin is still the center); timed out or too far away: not picked up */
dm_tc_begin_at(&s,0,90,275,50.0); dm_tc_move_at(&s,0,260,160,50.2); CHECK(s.lx>0 && s.ly>0); dm_tc_cancel_finger(&s,0); CHECK(s.joy_slot==-1 && s.lx==0);
dm_tc_begin_at(&s,1,265,165,50.4); CHECK(s.joy_slot==1 && s.lx>0 && s.ly>0); NEAR(s.joy_origin_x,90,0); dm_tc_cancel_finger(&s,1);
dm_tc_begin_at(&s,2,265,165,50.4+0.36); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,2,51.5); /* 超过 0.35 秒 | more than 0.35 seconds */
dm_tc_begin_at(&s,0,90,275,52.0); dm_tc_move_at(&s,0,260,160,52.2); dm_tc_cancel_finger(&s,0);
dm_tc_begin_at(&s,1,265,300,52.3); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,1,53.5); /* 离取消时的位置 140 点:不接 | 140 points from the position at cancellation: not picked up */
}
static void joystick_axes(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275); /* 圆心 90,275;下面各点 = 原用例整体平移 (−10, +75) | center 90,275; the points below = the original cases shifted as a whole by (−10, +75) */
dm_tc_move(&s,0,150,275); CHECK(s.lx==DM_STICK_MAX && s.ly==0);
dm_tc_move(&s,0,30,275); CHECK(s.lx==-DM_STICK_MAX && s.ly==0);
dm_tc_move(&s,0,90,215); CHECK(s.lx==0 && s.ly==DM_STICK_MAX);
dm_tc_move(&s,0,90,335); CHECK(s.lx==0 && s.ly==-DM_STICK_MAX);
dm_tc_move(&s,0,690,275); CHECK(s.lx==DM_STICK_MAX && s.ly==0);
dm_tc_move(&s,0,150,215); CHECK(abs(s.lx-14654)<=1 && abs(s.ly-29308)<=1); /* 手指 45°:斜向预修正后 (1,2)/√5 × 32767 = (14654, 29308),幅度不变 | Finger at 45°: after diagonal pre-correction (1,2)/√5 × 32767 = (14654, 29308), magnitude unchanged */
dm_tc_move(&s,0,90+60*0.8660254f,275-30); CHECK(abs(s.lx-21451)<=2 && abs(s.ly-24769)<=2); /* 手指 30°:(cos30, 2 sin30)/√(0.75+1) × 32767 = (21451, 24769) | Finger at 30°: (cos30, 2 sin30)/√(0.75+1) × 32767 = (21451, 24769) */
dm_tc_set_iso_fix(0); dm_tc_move(&s,0,150,215); CHECK(abs(s.lx-23170)<=1 && abs(s.ly-23170)<=1); dm_tc_set_iso_fix(1);
dm_tc_end(&s,0); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0);
}
static void joystick_plus_skills(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275); dm_tc_move(&s,0,150,275);
for(int i=0;i<5;i++) press(&s,i+1,i);
uint64_t all=keys[0]|keys[1]|keys[2]|keys[3]|keys[4];
CHECK(s.buttons==all); CHECK(s.lx==DM_STICK_MAX); /* 主钮与四个技能钮:按着的键都按着(按住 = 持续施放) | Main button and the four skill buttons: every pressed key stays down (hold = continuous cast) */
dm_tc_end(&s,3); CHECK(s.buttons==(all&~keys[2]) && s.lx==DM_STICK_MAX); /* 移动中松开一个:只有它的键起 | Release one while moving: only its key goes up */
dm_tc_end(&s,0); CHECK(s.lx==0 && s.ly==0); CHECK(s.buttons==(all&~keys[2]));
}
static void no_auto_handoff(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,90,275); dm_tc_begin(&s,1,150,295); /* 第二根手指也落在底座附近:摇杆已有主,它不接手 | a second finger also lands near the base: the joystick already has an owner, so it does not take over */
dm_tc_end(&s,0); dm_tc_move(&s,1,210,295);
CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0 && s.buttons==0);
dm_tc_begin(&s,2,90,275); CHECK(s.joy_slot==2);
}
static void background_no_key(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,400,100);
CHECK(s.buttons==0 && s.joy_slot==-1);
dm_tc_move(&s,0,s.layout.target[0].x,s.layout.target[0].y); CHECK(s.buttons==0);
dm_tc_begin(&s,1,10,10); dm_tc_move(&s,1,100,200); CHECK(s.joy_slot==-1 && s.buttons==0);
dm_tc_begin(&s,2,667*0.43f,200); CHECK(s.joy_slot==-1);
dm_tc_begin(&s,3,100,375*0.25f); CHECK(s.joy_slot==-1);
}
static void circles_before_joystick(void) {
dm_tc_state s; dm_tc_init(&s,667,375); press(&s,0,DM_TC_PORTAL);
CHECK(s.buttons==0 && s.joy_slot==-1); CHECK(s.finger[0].target==DM_TC_PORTAL); /* 圆钮先于摇杆认领这根手指;回城钮自己不出按键 | Round buttons claim this finger before the stick does; the town portal button itself emits no key */
}
static void cancel_and_resize(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_begin(&s,0,100,200); dm_tc_move(&s,0,160,200); press(&s,1,DM_TC_MAIN);
dm_tc_cancel_all(&s); CHECK(s.buttons==0 && s.lx==0 && s.ly==0 && s.joy_slot==-1);
for(int i=0;i<DM_TC_MAX_TOUCH;i++) CHECK(!s.finger[i].active);
dm_tc_begin(&s,0,100,200); press(&s,1,DM_TC_MAIN); dm_tc_resize(&s,812,375);
CHECK(s.buttons==0 && s.lx==0 && s.ly==0 && s.joy_slot==-1); NEAR(s.layout.width,812,0);
for(int i=0;i<DM_TC_MAX_TOUCH;i++) CHECK(!s.finger[i].active);
dm_tc_move(&s,1,s.layout.target[0].x,s.layout.target[0].y); CHECK(s.buttons==0);
}
static void invalid_slots_and_repeated_begin(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
press(&s,-1,0); press(&s,DM_TC_MAX_TOUCH,0); dm_tc_move(&s,-1,1,1); dm_tc_end(&s,DM_TC_MAX_TOUCH);
CHECK(s.buttons==0); dm_tc_begin(&s,0,NAN,10); CHECK(!s.finger[0].active);
press(&s,0,DM_TC_MAIN); press(&s,0,DM_TC_SKILL1); CHECK(s.buttons==DM_BTN_A);
dm_tc_move(&s,0,NAN,INFINITY); CHECK(s.buttons==DM_BTN_A);
dm_tc_end(&s,0); CHECK(s.buttons==0);
dm_tc_begin(&s,0,-1,200); dm_tc_begin(&s,1,100,500); CHECK(s.joy_slot==-1);
}
static void all_slots_hold(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
for(int i=0;i<DM_TC_MAX_TOUCH;i++) press(&s,i,DM_TC_MAIN);
for(int i=0;i<DM_TC_MAX_TOUCH-1;i++) { dm_tc_end(&s,i); CHECK(s.buttons==DM_BTN_A); }
dm_tc_end(&s,DM_TC_MAX_TOUCH-1); CHECK(s.buttons==0);
}
static void enabled_targets(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
CHECK(s.enabled_targets == ((1u<<DM_TC_COUNT)-1));
dm_tc_begin(&s,0,100,200); dm_tc_move(&s,0,160,200); press(&s,1,DM_TC_MAIN);
uint32_t ui = (1u<<DM_TC_MAIN)|(1u<<DM_TC_SKILL1)|(1u<<DM_TC_SKILL2)|
(1u<<DM_TC_SKILL3)|(1u<<DM_TC_SKILL4)|(1u<<DM_TC_MENU);
dm_tc_enable_targets(&s,ui);
CHECK(s.enabled_targets==ui); CHECK(s.buttons==0 && s.lx==0 && s.ly==0 && s.joy_slot==-1);
for(int i=0;i<DM_TC_COUNT;i++) {
press(&s,0,i);
CHECK(s.buttons==((ui&(1u<<i))?keys[i]:0));
CHECK(s.joy_slot==-1); dm_tc_end(&s,0); dm_tc_pulse_end(&s,s.pulse_epoch);
}
press(&s,0,DM_TC_MAIN); dm_tc_enable_targets(&s,ui); CHECK(s.buttons==DM_BTN_A);
dm_tc_enable_targets(&s,0); CHECK(s.buttons==0);
press(&s,0,DM_TC_SKILL1); CHECK(s.buttons==0 && s.joy_slot==-1); /* 全禁用时点钮不出键、也不落进摇杆;重新启用后照常出键(原先用回城钮验,它 不出按键,换成技能一) | When everything is disabled, tapping a button emits no key and does not fall through to the stick either; after re-enabling, keys are emitted as usual (this used to be verified with the town portal button, which emits no key, so it was changed to skill one) */
dm_tc_end(&s,0); dm_tc_enable_targets(&s,(1u<<DM_TC_COUNT)-1); press(&s,0,DM_TC_SKILL1); CHECK(s.buttons==DM_BTN_B);
}
static void ui_scene_messages(void) {
dm_tc_scene scene={0};
CHECK(dm_tc_navigation(&scene,"FrontEndNavigation","ToFrontEnd","")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","LoadScreenPanel")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","UnloadPanel","LoadScreenPanel")==0);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","PauseLayoutGarden")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","ClosePanel","PauseLayoutGarden")==0);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","AutoMap")==0);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenExclusivePanel","BankExpansionLayout")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","PlayerInventoryExpansionLayout")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","ClosePanel","BankExpansionLayout")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","ClosePanel","PlayerInventoryExpansionLayout")==0);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","HUDPanel")==0);
CHECK(dm_tc_navigation(&scene,"PanelManager","OpenPanel","SkillsTreePanel")==1);
CHECK(dm_tc_navigation(&scene,"PanelManager","UnloadAll","")==0);
CHECK(dm_tc_navigation(&scene,"FrontEndNavigation","ToFrontEnd","")==1);
}
static void pointer_tap(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_end_at(&s,0,10.2);
CHECK(s.pointer_valid); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001);
CHECK(s.pulse_button==DM_BTN_A); CHECK(s.buttons==DM_BTN_A);
}
/* 物品区(前端松手前置 pointer_item):单击只移光标不发键;0.4 秒内同处再点 = 按住 A 0.6 秒;开着储藏箱时 = 按住 Y;隔久了再点仍是单击 | Item area (the front end sets pointer_item before release): a single tap only moves the cursor and sends no key; another tap at the same spot within 0.4 seconds = hold A for 0.6 seconds; with the stash open = hold Y; a tap after a long gap is still a single tap */
/* 高级仓库的成叠格(命中类 8):单击只移光标;双击 = stack_take_seq 加一(取 1 件),不按住 Y、不计「使用」;开着箱子也一样;长按照物品区计 long_press_seq(宿主取 3 件) | Stack cells of the advanced stash (hit class 8): a single tap only moves the cursor; double tap = stack_take_seq plus one (take 1 item), no hold-Y and no "use" count; the same with the stash open; a long press counts long_press_seq as in the item area (the host takes 3 items) */
static void pointer_stack_tap(void) {
dm_tc_scene scene={0}; dm_tc_navigation(&scene,"PanelManager","UnloadAll",""); dm_tc_navigation(&scene,"PanelManager","OpenPanel","BankExpansionLayout"); dm_tc_set_panel_state(1);
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1); s.mouse_click_mode=1;
dm_tc_begin_at(&s,0,104,91,10.0); dm_tc_pointer_item(&s,8); dm_tc_end_at(&s,0,10.1);
CHECK(s.pointer_valid); NEAR(s.pointer_x,104,0.001); CHECK(s.stack_take_seq==0); CHECK(s.pulse_button==0);
dm_tc_begin_at(&s,0,104,91,10.3); dm_tc_pointer_item(&s,8); dm_tc_end_at(&s,0,10.4);
CHECK(s.stack_take_seq==1); CHECK(s.pulse_button==0); CHECK(s.use_seq==0); CHECK(s.buttons==0);
dm_tc_begin_at(&s,0,104,91,12.0); dm_tc_pointer_item(&s,8); dm_tc_tick(&s,12.9); dm_tc_end_at(&s,0,12.9);
CHECK(s.long_press_seq==1); CHECK(s.stack_take_seq==1);
dm_tc_begin_at(&s,0,104,91,14.0); dm_tc_pointer_item(&s,8); dm_tc_move_at(&s,0,200,150,14.1); CHECK(s.finger[0].shop_drag); CHECK(s.pulse_button==0); CHECK(s.buttons==0); /* 从一叠上拖出:不拿起(不发键),松手由前端按落点取 1 件 | Dragging out from a stack: no pick up (no key sent), on release the front end takes 1 item according to the drop point */
dm_tc_end_at(&s,0,14.5); CHECK(s.pulse_button==0); CHECK(s.stack_take_seq==1);
dm_tc_navigation(&scene,"PanelManager","UnloadAll","");
}
static void pointer_item_tap(void) {
dm_tc_scene scene={0}; dm_tc_navigation(&scene,"PanelManager","UnloadAll","");
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,10.1);
CHECK(s.pointer_valid); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001); CHECK(s.pulse_button==0); CHECK(s.buttons==0);
dm_tc_begin_at(&s,0,302,181,10.3); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,10.4);
CHECK(s.pulse_button==0); CHECK(s.use_seq==1); /* 双击:不发按住 A,计一次交给宿主当场使用 | Double tap: does not send hold-A, counts once and hands it to the host to use on the spot */
dm_tc_begin_at(&s,0,302,181,10.6); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,10.7); CHECK(s.pulse_button==0); /* 双击之后的第三下重新算单击 | The third tap after a double tap counts as a single tap again */
dm_tc_begin_at(&s,0,302,181,12.0); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,12.1); CHECK(s.pulse_button==DM_BTN_ZL); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch)); /* 隔 1.3 秒又点同一处:换一件比较(ZL) | Tapped the same spot again 1.3 seconds later: compare against another item (ZL) */
dm_tc_begin_at(&s,0,400,181,12.2); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,12.3); CHECK(s.pulse_button==0); /* 换了位置:单击 | Position changed: single tap */
dm_tc_navigation(&scene,"PanelManager","OpenPanel","BankExpansionLayout"); dm_tc_set_panel_state(1); /* 储藏箱开着 = 宿主读面板树设进来的位,不靠消息 | Stash open = a bit the host sets from reading the panel tree, not relying on messages */
dm_tc_begin_at(&s,0,400,181,12.5); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,12.6);
CHECK(s.pulse_button==DM_BTN_Y); NEAR(s.pulse_hold_s,0.6,0.001); dm_tc_pulse_end(&s,s.pulse_epoch);
dm_tc_navigation(&scene,"PanelManager","ClosePanel","BankExpansionLayout"); dm_tc_set_panel_state(0);
dm_tc_begin_at(&s,0,100,100,13.5); dm_tc_end_at(&s,0,13.6); CHECK(s.pulse_button==DM_BTN_A); NEAR(s.pulse_hold_s,0,0.001); /* 非物品区:照旧点 = A | Outside the item area: tap = A as before */
dm_tc_pulse_end(&s,s.pulse_epoch); s.mouse_click_mode=1; /* 前端开了鼠标点击:非物品区点按不按 A,改记一次鼠标点击 | The front end turned on mouse click: a tap outside the item area does not press A, and one mouse click is recorded instead */
dm_tc_begin_at(&s,0,120,90,14.5); dm_tc_end_at(&s,0,14.6); CHECK(s.pulse_button==0); CHECK(s.mouse_click_seq==1); NEAR(s.mouse_click_x,120,0.001); NEAR(s.mouse_click_y,90,0.001);
dm_tc_begin_at(&s,0,300,180,15.5); dm_tc_pointer_item(&s,1); dm_tc_end_at(&s,0,15.6); CHECK(s.mouse_click_seq==1); CHECK(s.pulse_button==0); /* 物品区单击不算鼠标点击 | A single tap in the item area does not count as a mouse click */
}
/* 界面连续手势:鼠标点击模式下起手不在物品区 / 面板外、位移过 10 点阈值 → 按那一刻的方向定型(纵 1 = 滚动,横 2 = 滑块),定型后不变;
不发任何键、不记鼠标点击(拖出去又拖回原处也不算点按);物品区起手照旧是拖放;面板外起手不定型;没开鼠标点击模式不定型
UI continuous gesture: in mouse click mode, when the touch does not start in the item area / outside the panel and the displacement passes the 10-point threshold → the type is fixed by the direction at that moment (vertical 1 = scroll, horizontal 2 = slider), and does not change once fixed;
no key is sent and no mouse click is recorded (dragging out and back to the original spot does not count as a tap either); a touch starting in the item area is drag-and-drop as before; a touch starting outside the panel fixes no type; with mouse click mode off no type is fixed */
static void ui_drag_typing(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1); s.mouse_click_mode=1;
dm_tc_begin_at(&s,0,300,200,1.0); dm_tc_move_at(&s,0,302,209,1.1); CHECK(s.finger[0].ui_drag==0); /* 位移 9.2 点:没过阈值 | Displacement 9.2 points: threshold not passed */
dm_tc_move_at(&s,0,303,212,1.2); CHECK(s.finger[0].ui_drag==1); /* 过阈值,纵向为主 → 滚动 | Past the threshold, mainly vertical → scroll */
dm_tc_move_at(&s,0,400,214,1.3); CHECK(s.finger[0].ui_drag==1); CHECK(s.buttons==0); CHECK(s.pulse_button==0); /* 之后横着走也不改型,不发键 | Moving sideways afterward does not change the type either, no key sent */
dm_tc_move_at(&s,0,300,200,1.4); dm_tc_end_at(&s,0,1.45); CHECK(s.mouse_click_seq==0); CHECK(s.pulse_button==0); /* 拖回原处松手:不算点按 | Dragged back to the original spot and released: does not count as a tap */
dm_tc_begin_at(&s,0,300,200,2.0); dm_tc_move_at(&s,0,312,204,2.1); CHECK(s.finger[0].ui_drag==2); /* 横向为主 → 滑块 | Mainly horizontal → slider */
dm_tc_end_at(&s,0,2.2); CHECK(s.mouse_click_seq==0); CHECK(s.pulse_button==0);
dm_tc_begin_at(&s,0,300,200,3.0); dm_tc_pointer_item(&s,1); dm_tc_move_at(&s,0,300,230,3.1); CHECK(s.finger[0].ui_drag==0); CHECK(s.finger[0].pointer_dragged); /* 物品区起手:照旧拖放 | Touch starting in the item area: drag-and-drop as before */
dm_tc_pointer_release(&s,1); dm_tc_end_at(&s,0,3.2); if (s.pulse_button) dm_tc_pulse_end(&s,s.pulse_epoch);
dm_tc_begin_at(&s,0,300,200,4.0); dm_tc_pointer_item(&s,3); dm_tc_move_at(&s,0,300,240,4.1); CHECK(s.finger[0].ui_drag==0); /* 面板外起手:不当滚动 | Touch starting outside the panel: not treated as a scroll */
dm_tc_end_at(&s,0,4.2); if (s.pulse_button) dm_tc_pulse_end(&s,s.pulse_epoch);
s.mouse_click_mode=0;
dm_tc_begin_at(&s,0,300,200,5.0); dm_tc_move_at(&s,0,300,240,5.1); CHECK(s.finger[0].ui_drag==0); /* 没开鼠标点击模式(手柄光标拖放那条老路):不定型 | Mouse click mode not on (the old controller-cursor drag-and-drop path): no type is fixed */
dm_tc_end_at(&s,0,5.2);
}
/* 拖放松手:落点是物品区 = 在落点按 A 放下;不是(拖到面板外)= 指针回起点、按 Y 丢弃(按住 0.15 秒) | Drag-and-drop release: the drop point is the item area = press A at the drop point to put down; it is not (dragged outside the panel) = the pointer returns to the start point and Y is pressed to discard (held 0.15 seconds) */
/* 面板态:手指落在被禁用的目标上(底栏腰带格)照样当指针用——面板的按钮可能就在那下面 | Panel state: a finger landing on a disabled target (bottom bar belt slot) is still used as a pointer - the panel's button may be right under it */
static void pointer_over_disabled_target(void) {
dm_tc_state s; dm_tc_init(&s,667,375); s.mouse_click_mode=1; dm_tc_set_navigation_mode(&s,1); dm_tc_enable_targets(&s,dm_tc_nav_mask(1));
const dm_tc_target *b=&s.layout.target[DM_TC_BELT1];
dm_tc_begin_at(&s,0,b->x,b->y,10.0); CHECK(s.pointer_slot==0); dm_tc_end_at(&s,0,10.1); CHECK(s.mouse_click_seq==1); CHECK(s.buttons==0);
}
/* 游戏态点按 = 点世界:空处短按记一笔;按住拖动(摇杆)、点技能钮、面板态都不记。城里没目标时主按钮不发键 | Tap in game state = world tap: a short press on empty space records one; hold-and-drag (stick), tapping a skill button, and panel state do not record. The main button sends no key when there is no target in town */
static void world_tap(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_enable_targets(&s,(1u<<DM_TC_COUNT)-1);
dm_tc_begin_at(&s,0,400,120,10.0); dm_tc_end_at(&s,0,10.1); CHECK(s.world_tap_seq==1); NEAR(s.world_tap_x,400,0.001); NEAR(s.world_tap_y,120,0.001);
dm_tc_begin_at(&s,0,250,150,11.0); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,0,11.1); CHECK(s.world_tap_seq==2); NEAR(s.world_tap_x,250,0.001); /* 左侧区域、底座以外点一下:点世界(不起摇杆) | a tap in the left area outside the base: world tap (no joystick started) */
dm_tc_begin_at(&s,0,120,250,11.5); CHECK(s.joy_slot==0); dm_tc_end_at(&s,0,11.6); CHECK(s.world_tap_seq==2); /* 落在底座上点一下:是摇杆(一按就有方向),不兼作点世界 | a tap landing on the base: it is the joystick (direction as soon as pressed), and does not double as a world tap */
dm_tc_begin_at(&s,0,120,250,12.0); dm_tc_move_at(&s,0,170,250,12.1); dm_tc_end_at(&s,0,12.2); CHECK(s.world_tap_seq==2); /* 拖了 = 摇杆 | Dragged = stick */
dm_tc_begin_at(&s,0,400,120,13.0); dm_tc_end_at(&s,0,13.6); CHECK(s.world_tap_seq==2); /* 按了 0.6 秒:不算点按 | Held for 0.6 seconds: does not count as a tap */
const dm_tc_target *m=&s.layout.target[DM_TC_MAIN];
dm_tc_begin_at(&s,0,m->x,m->y,14.0); CHECK(s.buttons==m->button); dm_tc_end_at(&s,0,14.1); CHECK(s.world_tap_seq==2); /* 点主按钮:发键,不算点世界 | Tapping the main button: sends the key, does not count as a world tap */
dm_tc_set_joy_block(&s,1); dm_tc_begin_at(&s,0,120,250,20.5); CHECK(s.joy_slot==-1 && s.lx==0 && s.ly==0); dm_tc_end_at(&s,0,20.6); CHECK(s.world_tap_seq==3); NEAR(s.world_tap_x,120,0.001); /* 讲话文字框单独开着:同一处点一下不起摇杆、没有方向,只当一次点击 | speech text box open on its own: a tap in the same place starts no stick and gives no direction, it is just one click */
dm_tc_set_joy_block(&s,0); dm_tc_begin_at(&s,0,120,250,21.5); CHECK(s.joy_slot==0); dm_tc_end_at(&s,0,21.6); CHECK(s.world_tap_seq==3); /* 文字框关了:照旧是摇杆 | text box closed: stick as usual */
dm_tc_set_navigation_mode(&s,1); dm_tc_begin_at(&s,0,400,120,16.0); dm_tc_end_at(&s,0,16.1); CHECK(s.world_tap_seq==3); /* 面板态不记 | Not recorded in panel state */
}
/* 面板外点按 = 按 B 到面板关掉为止:第一下在 tick 里发;面板还开着,0.3 秒后再发;面板关了就不再发;至多 3 下 | Tap outside the panel = press B until the panel closes: the first press is sent in tick; if the panel is still open, send again 0.3 seconds later; once the panel is closed no more are sent; at most 3 presses */
static void pointer_outside_close(void) {
dm_tc_state s; dm_tc_init(&s,667,375); s.mouse_click_mode=1; dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,330,60,10.0); dm_tc_pointer_item(&s,3); dm_tc_end_at(&s,0,10.1); CHECK(s.pulse_button==0);
dm_tc_tick(&s,10.12); CHECK(s.pulse_button==DM_BTN_B); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_tick(&s,10.2); CHECK(s.pulse_button==0); /* 不到 0.3 秒 | Less than 0.3 seconds */
dm_tc_tick(&s,10.45); CHECK(s.pulse_button==DM_BTN_B); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch)); /* 面板还开着:再按 | Panel still open: press again */
dm_tc_set_navigation_mode(&s,0); dm_tc_tick(&s,10.8); CHECK(s.pulse_button==0); CHECK(s.close_left==0); /* 面板关了:停 | Panel closed: stop */ dm_tc_set_navigation_mode(&s,1); /* 第一下返回引出了确认框:后面不再按 | The first Back brought up a confirmation box: no more presses after that */
dm_tc_begin_at(&s,0,330,60,20.0); dm_tc_pointer_item(&s,3); dm_tc_end_at(&s,0,20.1); dm_tc_tick(&s,20.12); CHECK(s.pulse_button==DM_BTN_B); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
{ dm_tc_scene sc={0}; dm_tc_navigation(&sc,"PanelManager","OpenPanel","ConfirmationModal"); }
dm_tc_tick(&s,20.5); CHECK(s.pulse_button==0); CHECK(s.close_left==0);
}
static void scene_dialog_only(void) { /* 只开着 NPC 对话菜单 = 底栏十字可点的那个状态 | Only the NPC dialog menu is open = the state in which the bottom bar D-pad is tappable */
dm_tc_scene sc={0};
dm_tc_navigation(&sc,"PanelManager","UnloadPanel","LoadScreenPanel"); CHECK(!dm_tc_scene_dialog_only(&sc));
CHECK(dm_tc_navigation(&sc,"PanelManager","OpenPanel","NpcDialogPanel")); CHECK(dm_tc_scene_dialog_only(&sc));
dm_tc_navigation(&sc,"PanelManager","OpenPanel","NpcTradePanel"); CHECK(!dm_tc_scene_dialog_only(&sc));
dm_tc_navigation(&sc,"PanelManager","ClosePanel","NpcTradePanel"); dm_tc_navigation(&sc,"PanelManager","ClosePanel","NpcDialogPanel"); CHECK(!dm_tc_scene_dialog_only(&sc));
}
static void pointer_drag_out(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_move_at(&s,0,320,180,10.1); CHECK(s.pulse_button==DM_BTN_A); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_move_at(&s,0,20,300,10.5); dm_tc_pointer_release(&s,3); dm_tc_end_at(&s,0,10.6); /* 3 = 手指在面板外 | 3 = the finger is outside the panel */
CHECK(s.pulse_button==DM_BTN_Y); NEAR(s.pulse_hold_s,0.15,0.001); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001);
CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_begin_at(&s,0,300,180,11.0); dm_tc_move_at(&s,0,320,180,11.1); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_move_at(&s,0,340,200,11.5); dm_tc_end_at(&s,0,11.6); CHECK(s.pulse_button==DM_BTN_A); /* 没置位 = 缺省按物品区:照旧放下 | Not set = defaults to item area: put down as before */
CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_begin_at(&s,0,300,180,12.0); dm_tc_move_at(&s,0,320,180,12.1); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_move_at(&s,0,400,120,12.5); dm_tc_pointer_release(&s,4); dm_tc_end_at(&s,0,12.6); /* 4 = 抬起点不在物品区、手指点在:放在手指点 | 4 = the lift point is not in the item area but the finger point is: put down at the finger point */
CHECK(s.pulse_button==DM_BTN_A); NEAR(s.pointer_x,400,0.001); NEAR(s.pointer_y,120,0.001); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_begin_at(&s,0,300,180,13.0); dm_tc_move_at(&s,0,320,180,13.1); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_move_at(&s,0,400,120,13.5); dm_tc_pointer_release(&s,0); dm_tc_end_at(&s,0,13.6); /* 0 = 面板里的空白处:放回原处,不丢 | 0 = blank area inside the panel: put back in place, not discarded */
CHECK(s.pulse_button==DM_BTN_A); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001);
}
static void pointer_drag(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_move_at(&s,0,320,180,10.1);
CHECK(s.pointer_valid); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001);
CHECK(s.pulse_button==DM_BTN_A); uint64_t first=s.pulse_epoch;
CHECK(dm_tc_pulse_end(&s,first));
dm_tc_move_at(&s,0,340,200,10.2);
NEAR(s.pointer_x,340,0.001); NEAR(s.pointer_y,160,0.001);
dm_tc_end_at(&s,0,10.3); NEAR(s.pointer_x,340,0.001); NEAR(s.pointer_y,160,0.001);
CHECK(s.pulse_button==DM_BTN_A); CHECK(s.pulse_epoch!=first);
}
static void pointer_long(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_tick(&s,10.5);
CHECK(s.pointer_valid); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001);
CHECK(s.pulse_button==0); dm_tc_end_at(&s,0,10.6); CHECK(s.pulse_button==0);
}
static void pointer_shop_drag(void) { /* 从商人货架的货上起拖:不发「拿起」、光标留在货上;松手不发任何键、只计一次(买不买由前端按落点定) | Starting a drag on goods on the vendor shelf: no "pick up" is sent and the cursor stays on the goods; on release no key is sent, only one count is made (whether to buy is decided by the front end from the drop point) */
dm_tc_state s; dm_tc_init(&s,667,375); s.mouse_click_mode=1; dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,150,200,10.0); dm_tc_pointer_item(&s,7); CHECK(s.pointer_item==1); CHECK(s.pointer_shop==1);
dm_tc_move_at(&s,0,300,220,10.3); CHECK(s.pulse_button==0); CHECK(s.finger[0].shop_drag); NEAR(s.pointer_x,2,0.001); NEAR(s.pointer_y,2,0.001); /* 光标挪到角上(收说明框),不跟手指 | The cursor moves to the corner (dismissing the tooltip) and does not follow the finger */
dm_tc_move_at(&s,0,480,280,10.8); NEAR(s.pointer_x,2,0.001); NEAR(s.finger[0].aim_origin_x,150,0.001);
dm_tc_end_at(&s,0,11.0); CHECK(s.pulse_button==0); CHECK(s.shop_drop_seq==1); CHECK(s.pointer_shop==0);
dm_tc_begin_at(&s,0,150,200,12.0); dm_tc_pointer_item(&s,7); dm_tc_end_at(&s,0,12.1); CHECK(s.shop_drop_seq==1); /* 点货不买 | Tapping goods does not buy */
}
static void pointer_long_seq(void) { /* 物品区按住不动满长按时长、松手时计一次(前端据此调宿主「补充到腰带」);按住后又拖走的不计;别处的长按不计 | In the item area, holding still for the full long-press duration counts once on release (the front end calls the host's "refill to belt" based on this); holding and then dragging away does not count; long presses elsewhere do not count */
dm_tc_state s; dm_tc_init(&s,667,375); s.mouse_click_mode=1; dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_pointer_item(&s,1); dm_tc_tick(&s,10.6); CHECK(s.long_press_seq==0);
dm_tc_end_at(&s,0,11.6); CHECK(s.long_press_seq==1); CHECK(s.pulse_button==0);
dm_tc_begin_at(&s,0,300,180,12.0); dm_tc_pointer_item(&s,1); dm_tc_tick(&s,12.6); dm_tc_move_at(&s,0,360,220,12.8); dm_tc_end_at(&s,0,13.2); CHECK(s.long_press_seq==1);
dm_tc_pulse_end(&s,s.pulse_epoch);
dm_tc_begin_at(&s,0,300,180,14.0); dm_tc_pointer_item(&s,0); dm_tc_tick(&s,15.0); dm_tc_end_at(&s,0,15.1); CHECK(s.long_press_seq==1);
}
static void pointer_long_then_drag(void) { /* 按住停 0.5 秒再拖:照样拿起、松手放下 | Hold for 0.5 seconds and then drag: still picks up, and puts down on release */
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_tick(&s,10.5); CHECK(s.pulse_button==0);
dm_tc_move_at(&s,0,340,200,10.6); CHECK(s.pulse_button==DM_BTN_A); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch));
dm_tc_move_at(&s,0,400,240,11.0); dm_tc_end_at(&s,0,11.1); CHECK(s.pulse_button==DM_BTN_A);
}
static void pointer_control_hit(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
press(&s,0,DM_TC_MAIN); CHECK(!s.pointer_valid); CHECK(s.buttons==DM_BTN_A);
}
static void pointer_game_mode(void) {
dm_tc_state s; dm_tc_init(&s,667,375);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_move_at(&s,0,340,200,10.1);
CHECK(!s.pointer_valid); CHECK(s.joy_slot==-1); dm_tc_end_at(&s,0,10.2); CHECK(!s.pointer_valid);
}
static void pointer_pulse_queue(void) {
dm_tc_state s; dm_tc_init(&s,667,375); dm_tc_set_navigation_mode(&s,1);
dm_tc_begin_at(&s,0,300,180,10.0); dm_tc_move_at(&s,0,320,180,10.1);
// 「拿起」还没收手指就抬了:指针留在起点(游戏还没取走这下 A),「放下」只排着
// The finger lifted before "pick up" was withdrawn: the pointer stays at the start point (the game has not yet taken this A), and "put down" is only queued
dm_tc_end_at(&s,0,10.2); CHECK(s.pulse_button==DM_BTN_A); NEAR(s.pointer_x,300,0.001); NEAR(s.pointer_y,180,0.001); CHECK(!dm_tc_pulse_pending(&s));
uint64_t first=s.pulse_epoch; CHECK(dm_tc_pulse_end(&s,first));
// 收回后 A 松开、指针仍在起点,等前端 resume(中间留一次松开给游戏看)
// After the withdrawal A is released and the pointer is still at the start point, waiting for the front end's resume (one release is left in between for the game to see)
CHECK(s.pulse_button==0); CHECK(s.buttons==0); CHECK(dm_tc_pulse_pending(&s)); NEAR(s.pointer_y,180,0.001);
CHECK(dm_tc_pulse_resume(&s)); CHECK(s.pulse_button==DM_BTN_A); CHECK(s.pulse_epoch!=first); NEAR(s.pointer_x,320,0.001); NEAR(s.pointer_y,140,0.001);
CHECK(!dm_tc_pulse_resume(&s)); CHECK(dm_tc_pulse_end(&s,s.pulse_epoch)); CHECK(!dm_tc_pulse_pending(&s));
}
/* 安全区内缩:956×440、左右各 62 点。期望手算:主键右沿 = 956−62 = 894 → 主键中心 x = 854(原 900,移 46);弧上四键与换组键同移 46;
摇杆中心 x = 62+60 = 122(原 90);y 都不变。设回 0 后恢复原布局。
Safe area inset: 956×440, 62 points on each of left and right. Expected values hand-computed: main button right edge = 956−62 = 894 → main button center x = 854 (was 900, moved 46); the four buttons on the arc and the set-switch button move the same 46;
stick center x = 62+60 = 122 (was 90); all y unchanged. After setting back to 0 the original layout is restored. */
static void safe_insets(void) {
dm_tc_layout a, b; dm_tc_layout_make(&a, 956, 440);
dm_tc_set_safe_insets(62, 62); dm_tc_layout_make(&b, 956, 440); dm_tc_set_safe_insets(0, 0);
NEAR(a.target[DM_TC_MAIN].x, 900, 0.001); NEAR(b.target[DM_TC_MAIN].x, 854, 0.001); NEAR(b.target[DM_TC_MAIN].y, a.target[DM_TC_MAIN].y, 0.001);
for (int i = DM_TC_SKILL1; i <= DM_TC_SKILL4; ++i) { NEAR(a.target[i].x - b.target[i].x, 46, 0.001); NEAR(a.target[i].y, b.target[i].y, 0.001); CHECK(b.target[i].x + b.target[i].r <= 894.001f); }
NEAR(a.swap.x - b.swap.x, 46, 0.001); NEAR(a.joy_x, 90, 0.001); NEAR(b.joy_x, 122, 0.001); CHECK(b.joy_x - b.joy_radius >= 61.999f);
dm_tc_layout c; dm_tc_layout_make(&c, 956, 440); NEAR(c.target[DM_TC_MAIN].x, 900, 0.001);
}
/* 换组键:956×440 下主键中心 (900,358),换组键在技能一正下方 (900−112, 358+52) = (788,410),半径 22;不与技能一(中心 (788,358) 半径 26)重叠、不出屏 | Set-switch button: at 956×440 the main button center is (900,358), the set-switch button is directly below skill one at (900−112, 358+52) = (788,410), radius 22; it does not overlap skill one (center (788,358), radius 26) and does not go off screen */
static void swap_key(void) {
dm_tc_layout l; dm_tc_layout_make(&l, 956, 440);
NEAR(l.swap.x, 788, 0.001); NEAR(l.swap.y, 410, 0.001); NEAR(l.swap.r, 22, 0.001);
CHECK(l.swap.y - l.swap.r >= l.target[DM_TC_SKILL1].y + l.target[DM_TC_SKILL1].r); CHECK(l.swap.y + l.swap.r <= 440);
CHECK(dm_tc_hit(&l, 788, 410) == DM_TC_SWAP);
}
/* 腰带展开手势(956×440,u = 440/1320 = 1/3:腰带第 1 列格心 x = 478 + (1210−1434)/3 = 403.33、y = 1241.5/3 = 413.83)。
(腰带一律松手后等过双击窗才喝。)只有 1 排:按下不发键、松手过窗 → 一个脉冲。4 排:按下不发键;松手没滑 → 过窗一个脉冲;上滑过 24 点 → 请求 1(展开)且不发键;下滑 → 请求 2。
展开着:点上一排(y 高 165/3 = 55)同列 → 请求 0x100 | 1<<4 | 0,不发键;点世界别处 → 请求 2(收起)。
Belt expand gesture (956×440, u = 440/1320 = 1/3: belt column 1 cell center x = 478 + (1210−1434)/3 = 403.33, y = 1241.5/3 = 413.83).
(The belt always drinks only after release and once the double-tap window has passed.) Only 1 row: no key on press, release and window passed → one pulse. 4 rows: no key on press; release without sliding → one pulse after the window; slide up past 24 points → request 1 (expand) and no key; slide down → request 2.
While expanded: tap the same column one row up (y higher by 165/3 = 55) → request 0x100 | 1<<4 | 0, no key; tap elsewhere in the world → request 2 (collapse). */
static void belt_expand(void) {
dm_tc_state s; dm_tc_init(&s, 956, 440); float bx = s.layout.target[DM_TC_BELT1].x, by = s.layout.target[DM_TC_BELT1].y;
NEAR(bx, 403.333f, 0.01); NEAR(by, 413.833f, 0.01);
dm_tc_begin_at(&s, 0, bx, by, 1.0); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, 1.05); CHECK(!s.belt_request); dm_tc_tick(&s, 1.05 + 0.01); CHECK(s.pulse_button == DM_BTN_LEFT); dm_tc_pulse_end(&s, s.pulse_epoch);
s.belt_rows = 4; s.pulse_button = 0;
dm_tc_begin_at(&s, 0, bx, by, 2.0); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, 2.05); dm_tc_tick(&s, 2.05 + 0.01); CHECK(s.pulse_button == DM_BTN_LEFT); CHECK(!s.belt_request); s.pulse_button = 0;
dm_tc_begin_at(&s, 0, bx, by, 3.0); dm_tc_tick(&s, 3.4); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, 3.5); dm_tc_tick(&s, 3.5 + 0.01); CHECK(s.pulse_button == DM_BTN_LEFT); s.pulse_button = 0; /* 按住半秒不动:按住期间不发键,松手才喝 | Hold for half a second without moving: no key is sent while holding, drinks only on release */
dm_tc_begin_at(&s, 0, bx, by, 4.0); dm_tc_move_at(&s, 0, bx, by - 30, 4.05); CHECK(s.belt_request == 0); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, 4.1); CHECK(s.belt_request == 1); CHECK(s.pulse_button == 0); s.belt_request = 0;
dm_tc_begin_at(&s, 0, bx, by, 5.0); dm_tc_move_at(&s, 0, bx, by + 25, 5.05); dm_tc_end_at(&s, 0, 5.1); CHECK(s.belt_request == 2); CHECK(s.pulse_button == 0); s.belt_request = 0;
dm_tc_begin_at(&s, 0, bx, by, 5.2); dm_tc_tick(&s, 5.4); dm_tc_move_at(&s, 0, bx, by - 30, 5.5); dm_tc_end_at(&s, 0, 5.55); CHECK(s.belt_request == 1); CHECK(s.pulse_button == 0); CHECK(s.buttons == 0); s.belt_request = 0; /* 按下停 0.2 秒再上滑:展开,不喝(实测撞到过) | Press, stay 0.2 seconds, then slide up: expands, does not drink (hit in actual testing) */
dm_tc_begin_at(&s, 0, bx, by, 5.6); dm_tc_tick(&s, 5.8); dm_tc_move_at(&s, 0, bx, by + 36, 5.95); dm_tc_end_at(&s, 0, 5.95); CHECK(s.belt_request == 2); CHECK(s.pulse_button == 0); s.belt_request = 0; /* 0.35 秒慢慢下滑 36 点:收起,不喝(真机撞到过) | Slowly sliding down 36 points over 0.35 seconds: collapses, does not drink (hit on a real device) */
dm_tc_begin_at(&s, 0, bx, by, 5.96); dm_tc_move_at(&s, 0, bx + 40, by, 5.97); dm_tc_end_at(&s, 0, 5.98); CHECK(!s.belt_request); CHECK(s.pulse_button == 0); /* 横着滑走:什么都不做 | Sliding away sideways: does nothing */
CHECK(s.layout.target[DM_TC_BELT3].button == DM_BTN_DOWN && s.layout.target[DM_TC_BELT4].button == DM_BTN_RIGHT); /* 第 3 列 = 下、第 4 列 = 右(原版实测) | Column 3 = down, column 4 = right (measured in the original game) */
s.belt_open = 1;
dm_tc_begin_at(&s, 0, bx, by - 55.0f, 6.0); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, 6.05); dm_tc_tick(&s, 6.05 + 0.01); CHECK(s.belt_request == (0x100 | 1 << 4)); CHECK(s.pulse_button == 0); CHECK(s.world_tap_seq == 0); s.belt_request = 0;
dm_tc_begin_at(&s, 0, bx + 40*3, by - (165.0f + 2*162.0f)/3, 7.0); dm_tc_end_at(&s, 0, 7.05); dm_tc_tick(&s, 7.05 + 0.01); CHECK(s.belt_request == (0x100 | 3 << 4 | 3)); s.belt_request = 0;
dm_tc_begin_at(&s, 0, bx, by, 8.0); CHECK(!s.belt_request); dm_tc_end_at(&s, 0, 8.05); dm_tc_tick(&s, 8.05 + 0.01); CHECK(s.pulse_button == DM_BTN_LEFT); s.pulse_button = 0;
CHECK(dm_tc_belt_outside(&s, 600, 150)); CHECK(!dm_tc_belt_outside(&s, bx, by)); CHECK(!dm_tc_belt_outside(&s, bx, by - 165.0f/3)); s.belt_open = 0; CHECK(!dm_tc_belt_outside(&s, 600, 150)); s.belt_open = 1;
dm_tc_begin_at(&s, 0, 100, 250, 9.0); CHECK(s.belt_request == 2); CHECK(s.joy_slot == DM_TC_NONE); dm_tc_end_at(&s, 0, 9.05); CHECK(s.world_tap_seq == 0); CHECK(s.buttons == 0); /* 点别处(摇杆区):只收起,不成摇杆、不点世界 | Tap elsewhere (stick zone): only collapses, does not become the stick, does not tap the world */
}
/* 第二组里点得太短的技能等 ZL 领先再补发。等的时候点了多排腰带:腰带那下不许带 ZL(ZL + 腰带 = 喂佣兵)、
不许被补发盖掉;腰带脉冲收回后 ZL 再领先满 DM_TC_ZL_LEAD_S 才补技能;全取消把等着的补发一起作废
A skill tapped too briefly in the second set waits for ZL to lead before the make-up send. A multi-row belt is tapped while waiting: the belt tap must not carry ZL (ZL + belt = feed the mercenary) and
must not be overwritten by the make-up send; after the belt pulse is withdrawn, ZL leads for a full DM_TC_ZL_LEAD_S again before the skill is made up; cancel-all voids the pending make-up send as well */
static void deferred_skill_vs_belt(void) {
/* 技能在等补发时点腰带:腰带那下排着,技能先按时补发(ZL 领先),等它收回后腰带再发、不带 ZL | tapping the belt while a skill awaits resend: the belt tap queues, the skill resends on time first (ZL leading), and after it is released the belt key is sent, without ZL */
dm_tc_state s; dm_tc_init(&s, 667, 375); s.skill_set = 1; s.belt_rows = 4; s.last_time_s = 10.0;
dm_tc_target k = s.layout.target[DM_TC_SKILL1], b = s.layout.target[DM_TC_BELT1];
dm_tc_begin_at(&s, 0, k.x, k.y, 10.000); dm_tc_end_at(&s, 0, 10.050); CHECK(s.defer_button == k.button);
dm_tc_begin_at(&s, 1, b.x, b.y, 10.080); dm_tc_end_at(&s, 1, 10.120);
double skill = -1, belt = -1; int belt_zl = 0, zl_gap = 0; /* ZL 从技能松手(10.050)起就按着,补发前一直不断 | ZL is held from the skill release (10.050) onward, with no break until the make-up send */
for (double t = 10.13; t < 11.0; t += 0.01) { dm_tc_tick(&s, t);
if (skill < 0 && !(s.buttons & DM_BTN_ZL)) zl_gap = 1;
if (s.pulse_button == k.button && skill < 0) { skill = t; dm_tc_tick(&s, t + 0.03); s.last_time_s = t + 0.03; CHECK(dm_tc_pulse_end(&s, s.pulse_epoch)); }
else if (s.pulse_button == b.button && belt < 0) { belt = t; belt_zl = (s.buttons & DM_BTN_ZL) != 0; CHECK(dm_tc_pulse_end(&s, s.pulse_epoch)); } }
CHECK(skill >= 10.000 + DM_TC_ZL_LEAD_S - 1e-9 && !zl_gap); /* 技能补发:ZL 领先够、中间不断 | Skill make-up send: ZL leads long enough, with no break in between */
CHECK(belt > skill && belt >= 10.120 && !belt_zl); /* 腰带那下没丢、没被盖、不带 ZL(不变成喂佣兵) | The belt tap was not lost, not overwritten, and carries no ZL (does not turn into feeding the mercenary) */
dm_tc_state c; dm_tc_init(&c, 667, 375); c.skill_set = 1; c.last_time_s = 20.0;
dm_tc_begin_at(&c, 0, k.x, k.y, 20.000); dm_tc_end_at(&c, 0, 20.050); CHECK(c.defer_button);
dm_tc_cancel_all(&c); dm_tc_tick(&c, 20.30); CHECK(c.defer_button == 0 && c.pulse_button == 0 && c.buttons == 0);
}
/* 手指一直按着第二组技能时点腰带:喝药那一脉冲期间不许有 ZL(ZL + 腰带键 = 喂佣兵)、也不许剩下不带 ZL 的技能键(= 放成第一组技能);
脉冲收回后 ZL 先回来,技能键晚 DM_TC_ZL_LEAD_S 再回来。期望按规则手算
Tapping the belt while a finger keeps holding a second-set skill: during the potion pulse there must be no ZL (ZL + belt key = feed the mercenary), nor a leftover skill key without ZL (= cast as the first-set skill);
after the pulse is released ZL comes back first, and the skill key comes back DM_TC_ZL_LEAD_S later. Expectations computed by hand from the rule */
static void held_skill2_vs_belt(void) {
dm_tc_state s; dm_tc_init(&s, 667, 375); s.skill_set = 1; s.last_time_s = 30.0;
dm_tc_target k = s.layout.target[DM_TC_SKILL1], b = s.layout.target[DM_TC_BELT1];
dm_tc_begin_at(&s, 0, k.x, k.y, 30.000); for (double t = 30.01; t < 30.60; t += 0.01) dm_tc_tick(&s, t);
CHECK((s.buttons & DM_BTN_ZL) && (s.buttons & k.button)); /* 按住半秒多:ZL + 技能键都在 | Held for a bit over half a second: ZL + the skill key are both present */
dm_tc_begin_at(&s, 1, b.x, b.y, 30.600); dm_tc_end_at(&s, 1, 30.640);
double belt = -1, back = -1, zl_back = -1, zl_off = -1; int bad_zl = 0, bad_key = 0;
for (double t = 30.65; t < 31.60; t += 0.01) { dm_tc_tick(&s, t);
if (belt < 0 && zl_off < 0 && !(s.buttons & DM_BTN_ZL)) { zl_off = t; CHECK(!(s.buttons & k.button)); } /* ZL 先松(技能键同时松),这时腰带键还没按 | ZL is released first (the skill key is released at the same time), and at this point the belt key is not pressed yet */
if (s.pulse_button == b.button) { if (belt < 0) belt = t; if (s.buttons & DM_BTN_ZL) bad_zl = 1; if (s.buttons & k.button) bad_key = 1;
if (t - belt > 0.025) { CHECK(dm_tc_pulse_end(&s, s.pulse_epoch)); dm_tc_tick(&s, t); } }
else if (belt >= 0) { if (zl_back < 0 && (s.buttons & DM_BTN_ZL)) zl_back = t; if (back < 0 && (s.buttons & k.button)) { back = t; CHECK(s.buttons & DM_BTN_ZL); } } }
CHECK(belt >= 30.640 && !bad_zl && !bad_key); /* 喝药脉冲发了、期间没有 ZL、没有技能键 | The potion pulse was sent, with no ZL and no skill key during it */
CHECK(zl_off > 0 && belt - zl_off >= DM_TC_ZL_LEAD_S - 0.011); /* ZL 松开后空够一个领先时间腰带键才按(同一拍松 ZL + 按腰带键,游戏仍当 ZL 在) | the belt key is pressed only after a full lead time has gone by since ZL was released (releasing ZL + pressing the belt key in the same tick, the game still takes ZL as held) */
CHECK(zl_back > belt && back - zl_back >= DM_TC_ZL_LEAD_S - 0.011); /* 收回后 ZL 先回、技能键晚一个领先时间回 | After the release ZL comes back first, and the skill key comes back one lead time later */
dm_tc_end_at(&s, 0, 31.60);
}
/* 起手落在模态框外 / 被上层盖住(宿主判类 6)时,上下滑不起界面滚动手势;面板里其它地方(类 0)照旧起 | When the touch starts outside a modal box / covered by an upper layer (host hit class 6), sliding up or down does not start the UI scroll gesture; elsewhere in the panel (class 0) it starts as before */
static void no_ui_drag_outside_modal(void) {
for (int kind = 0; kind <= 6; kind += 6) {
dm_tc_state s; dm_tc_init(&s, 667, 375); dm_tc_set_navigation_mode(&s, 1); s.mouse_click_mode = 1; s.last_time_s = 1.0;
dm_tc_begin_at(&s, 0, 300, 100, 1.0); dm_tc_pointer_item(&s, kind);
dm_tc_move_at(&s, 0, 300, 140, 1.05); dm_tc_move_at(&s, 0, 300, 200, 1.10);
CHECK(s.finger[0].ui_drag == (kind == 6 ? 0 : 1));
}
}
/* 腰带点一下 = 自己喝,松手那一刻就出腰带键(不带 ZL,第二组技能下也不带);不判双击:连点两下 = 两个腰带键脉冲,哪一下都不带 ZL(不喂雇佣兵)。
展开后的上面几排按下就出 belt_request 0x1rc,点两下两次。期望按规则手算
One tap on the belt = the player drinks; the belt key fires at the moment of release (without ZL, also under the second skill set); no double-tap detection: two quick taps = two belt key pulses, neither with ZL (no mercenary feeding).
Upper rows when expanded send belt_request 0x1rc on press, two taps send two. Expected values are computed by hand from the rules */
static void tap_belt(dm_tc_state *s, int slot, int target, double t0) {
dm_tc_target t = s->layout.target[target]; dm_tc_begin_at(s, slot, t.x, t.y, t0); dm_tc_end_at(s, slot, t0 + 0.08);
}
static void belt_single_double(void) {
for (int set = 0; set < 2; ++set) {
dm_tc_state s; dm_tc_init(&s, 956, 440); s.skill_set = set; uint64_t k = s.layout.target[DM_TC_BELT2].button;
/* 点一下:按着不出键,松手即出 | single tap: no key while held, key on release */
double t = 10; dm_tc_tick(&s, t); dm_tc_begin_at(&s, 0, s.layout.target[DM_TC_BELT2].x, s.layout.target[DM_TC_BELT2].y, t); CHECK(s.buttons == 0);
dm_tc_end_at(&s, 0, t + 0.08); CHECK(s.buttons == k); /* 不带 ZL | Without ZL */
CHECK(dm_tc_pulse_end(&s, s.pulse_epoch)); CHECK(s.buttons == 0);
/* 0.12 秒内连点两下,第一下的脉冲已收回:两个脉冲,都不带 ZL | two taps within 0.12 s, the first pulse already released: two pulses, neither with ZL */
t = 20; dm_tc_tick(&s, t); tap_belt(&s, 0, DM_TC_BELT2, t); CHECK(s.buttons == k); unsigned e1 = s.pulse_epoch; CHECK(dm_tc_pulse_end(&s, e1));
tap_belt(&s, 1, DM_TC_BELT2, t + 0.12); CHECK(s.buttons == k && s.pulse_epoch != e1); CHECK(dm_tc_pulse_end(&s, s.pulse_epoch)); CHECK(s.buttons == 0);
/* 连点两下,第一下的脉冲还在发:第二下排着,收回后的下一拍补发,仍不带 ZL,一共两个 | two quick taps while the first pulse is still being sent: the second queues and is sent on the tick after release, still without ZL, two in total */
t = 30; dm_tc_tick(&s, t); tap_belt(&s, 0, DM_TC_BELT2, t); e1 = s.pulse_epoch; tap_belt(&s, 1, DM_TC_BELT2, t + 0.10); CHECK(s.pulse_epoch == e1 && s.buttons == k);
CHECK(dm_tc_pulse_end(&s, e1)); CHECK(s.buttons == 0); dm_tc_tick(&s, t + 0.20); CHECK(s.buttons == k && s.pulse_epoch != e1); CHECK(dm_tc_pulse_end(&s, s.pulse_epoch));
dm_tc_tick(&s, t + 1.0); CHECK(s.buttons == 0 && !s.pulse_button); /* 不多喝 | no extra drink */
/* 换一格 | switch to another slot */
t = 40; dm_tc_tick(&s, t); tap_belt(&s, 0, DM_TC_BELT3, t); CHECK(s.buttons == s.layout.target[DM_TC_BELT3].button); dm_tc_pulse_end(&s, s.pulse_epoch);
/* 展开的上面几排(第 1 排第 2 列):按下就请求,点两下请求两次 | upper rows when expanded (row 1, column 2): request on press, two taps make two requests */
s.belt_rows = 3; s.belt_open = 1; float u = s.layout.height / 1320.0f, x = s.layout.target[DM_TC_BELT2].x, y = s.layout.target[DM_TC_BELT2].y - 165 * u;
t = 60; dm_tc_tick(&s, t); dm_tc_begin_at(&s, 0, x, y, t); CHECK(s.belt_request == (0x100 | 1 << 4 | 1)); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, t + 0.08); s.belt_request = 0;
dm_tc_begin_at(&s, 0, x, y, t + 0.2); CHECK(s.belt_request == (0x100 | 1 << 4 | 1)); CHECK(s.buttons == 0); dm_tc_end_at(&s, 0, t + 0.3); s.belt_request = 0;
dm_tc_tick(&s, t + 1); CHECK(s.belt_request == 0);
}
}
int main(void) {
RUN(layout_667); RUN(layout_812); RUN(layout_956); RUN(layout_1024); RUN(layout_ipad169); RUN(layout_pixels); RUN(small_layout); RUN(difficulty_picker);
RUN(hit_edges); RUN(key_hold_and_ownership); RUN(two_fingers_same_key); RUN(joystick_deadzone);
RUN(joystick_axes); RUN(joystick_plus_skills); RUN(no_auto_handoff); RUN(background_no_key);
RUN(circles_before_joystick); RUN(cancel_and_resize); RUN(deferred_skill_vs_belt); RUN(held_skill2_vs_belt); RUN(belt_single_double); RUN(no_ui_drag_outside_modal); RUN(invalid_slots_and_repeated_begin); RUN(all_slots_hold); RUN(enabled_targets); RUN(ui_scene_messages);
RUN(pointer_tap); RUN(world_tap); RUN(pointer_outside_close); RUN(scene_dialog_only); RUN(pointer_item_tap); RUN(pointer_stack_tap); RUN(pointer_over_disabled_target); RUN(ui_drag_typing); RUN(pointer_drag_out); RUN(pointer_drag); RUN(pointer_long); RUN(pointer_long_then_drag); RUN(pointer_long_seq); RUN(pointer_shop_drag); RUN(pointer_control_hit); RUN(pointer_game_mode); RUN(pointer_pulse_queue); RUN(safe_insets); RUN(swap_key);
RUN(belt_expand);
printf("PASS %d/%d cases; %d/%d checks\n",cases,cases,checks,checks); return 0;
}
+169
View File
@@ -0,0 +1,169 @@
import importlib.util,unittest,os
from pathlib import Path
P=Path(os.environ.get('PAIR_SOURCE',str(Path(__file__).resolve().parents[1]/'tools/input_pair_check.py')))
spec=importlib.util.spec_from_file_location('pair',P);pair=importlib.util.module_from_spec(spec);spec.loader.exec_module(pair)
def state(lx=0):return dict(buttons=0,lx=lx,ly=0,rx=0,ry=0)
def trace(axis=32767):
ui=[];hid=[]
for i,(phase,value) in enumerate([('began',0),('moved',axis),('ended',0)],1):
n=i*100;v=state(value)
ui.append(dict(stage='event',eventseq=i,mono_ns=n,source='uitouch',phase=phase,slot=0,touch='0x1',x=90+value/32767*60,y=200,touch_timestamp_s=42.125,mode='game',**v))
ui.append(dict(stage='output',receiptseq=i,eventseq=i,event_first_seq=i,event_last_seq=i,mono_ns=n+10,publish_end_ns=n+20,source='uitouch',phase=phase,mode='game',**v))
hid.append(dict(event='npad_return',read_start_ns=n+25,time_ns=n+30,sampling=i,id=32,style=2,attributes=1,script_mask=0,**v))
return ui,hid
class PairFixtureTests(unittest.TestCase):
def case(self,f,status,reason=None):
u,h=trace();f(u,h);g=pair.analyze(u,h,domain='synthetic')
self.assertEqual(g['status'],status,g);self.assertFalse(g['physical_pass_claimed'],g)
if reason:self.assertIn(reason,g['reasons'],g)
def test_01_positive_right(self):self.case(lambda u,h:None,'protocol_pass')
def test_02_positive_left(self):
u,h=trace(-32767);g=pair.analyze(u,h);self.assertEqual(g['status'],'protocol_pass');self.assertFalse(g['physical_pass_claimed'])
def test_03_release(self):
u,h=trace();g=pair.analyze(u,h);self.assertEqual(g['status'],'protocol_pass');self.assertTrue(g['release_received'])
def test_04_stale_equal(self):self.case(lambda u,h:h[1].update(read_start_ns=1,time_ns=2),'incomplete','missing_receipt')
def test_05_invalid_controller_zero(self):self.case(lambda u,h:h[-1].update(id=99,style=0,attributes=0),'incomplete','invalid_controller')
def test_06_non_touch_output(self):
def f(u,h):
u[:]=[dict(stage='output',receiptseq=1,eventseq=0,event_first_seq=0,event_last_seq=0,mono_ns=110,publish_end_ns=120,source='layout',phase='none',mode='game',**state(32767))]
h[:]=[dict(event='npad_return',read_start_ns=125,time_ns=130,sampling=1,id=32,style=2,attributes=1,script_mask=0,**state(32767))]
self.case(f,'incomplete','no_touch_pairs')
def test_07_blank_no_receipt(self):self.case(lambda u,h:h.clear(),'incomplete','missing_receipt')
def test_08_missing_release(self):self.case(lambda u,h:(u.__delitem__(slice(-2,None)),h.pop()),'incomplete','lifecycle_unclosed')
def test_09_blank_activity_witness(self):
u,h=trace(0);u[0]['blank']=True;h[1].update(sampling=26);h[2].update(sampling=27);g=pair.analyze(u,h);self.assertEqual(g['status'],'protocol_pass');self.assertTrue(g['blank_activity_received'])
def test_10_script_confounded(self):self.case(lambda u,h:h[1].update(script_mask=33554432),'incomplete','script_confounded')
def test_11_cap_reached(self):self.case(lambda u,h:h.append(dict(event='limit_reached',limit=1024)),'incomplete','limit_reached')
def test_12_read_crosses_publish(self):self.case(lambda u,h:h[1].update(read_start_ns=215,time_ns=225),'incomplete','concurrent_undetermined')
def test_13_stable_read_after_publish(self):self.case(lambda u,h:h[1].update(read_start_ns=230,time_ns=250),'protocol_pass')
def test_14_duplicate_sampling(self):self.case(lambda u,h:h[1].update(sampling=1),'incomplete','sampling_not_forward')
def test_15_fractional_integer(self):self.case(lambda u,h:h[1].update(lx=32767.9),'invalid_trace','bad_integer')
def test_16_group_tail(self):self.case(lambda u,h:u[3].update(event_last_seq=1),'invalid_trace','event_group_not_closed')
def test_17_no_dual_stream(self):
u,h=trace();g=pair.analyze(u,None);self.assertEqual(g['status'],'pair_not_executed');self.assertFalse(g['physical_pass_claimed'])
def test_18_state_mismatch(self):self.case(lambda u,h:h[1].update(lx=100),'incomplete','returned_state_mismatch')
def test_19_device_domain_not_physical(self):
u,h=trace();g=pair.analyze(u,h,domain='device');self.assertEqual(g['status'],'protocol_pass');self.assertFalse(g['physical_pass_claimed'])
def test_20_slot_transition(self):self.case(lambda u,h:u[2].update(slot=1),'invalid_trace','slot_transition')
def test_21_touch_timestamp_not_clock(self):
u,h=trace();u[2]['touch_timestamp_s']=1e20;g=pair.analyze(u,h);self.assertEqual(g['status'],'protocol_pass')
def test_22_release_not_neutral(self):
def f(u,h):u[-1]['lx']=100;h[-1]['lx']=100
self.case(f,'incomplete','release_not_neutral')
def test_23_blank_unwanted_A(self):
def f(u,h):u[0]['blank']=True;u[1]['buttons']=1;h[0]['buttons']=1
self.case(f,'incomplete','blank_unwanted_A')
def test_24_read_crosses_next_publish(self):self.case(lambda u,h:h[1].update(read_start_ns=250,time_ns=315),'incomplete','concurrent_undetermined')
def test_25_unsigned_attribute_corruption(self):self.case(lambda u,h:h[1].update(attributes=-1),'invalid_trace','unsigned_range')
def test_26_read_start_equals_publish_end(self):
self.case(lambda u,h:h[1].update(read_start_ns=u[3]['publish_end_ns']),'incomplete','concurrent_undetermined')
def test_27_matched_int32_overflow(self):
def f(u,h):u[3]['lx']=2**31;h[1]['lx']=2**31
self.case(f,'invalid_trace','int32_range')
def binding_trace(self):
u,h=trace();v=dict(buttons=256,lx=0,ly=0,rx=0,ry=0)
u.insert(4,dict(stage='output',receiptseq=3,eventseq=2,event_first_seq=0,event_last_seq=2,mono_ns=260,publish_end_ns=270,source='bindings',phase='none',mode='game',**v))
u[-1]['receiptseq']=4
h.insert(2,dict(event='npad_return',read_start_ns=275,time_ns=280,sampling=3,id=32,style=2,attributes=1,script_mask=0,**v));h[-1]['sampling']=4
return u,h
def test_28_bindings_output_not_new_touch(self):
u,h=self.binding_trace();g=pair.analyze(u,h)
self.assertEqual(g['status'],'protocol_pass',g);self.assertEqual(g['touch_output_pairs'],3)
self.assertEqual(g['pairs'][2]['attribution'],'output_only_not_new_touch')
self.assertEqual(g['pairs'][2]['matched_sampling'],[3]);self.assertFalse(g['physical_pass_claimed'])
def test_29_bindings_only_cannot_claim_touch(self):
u,h=self.binding_trace();u=[u[4]];u[0].update(receiptseq=1,eventseq=0,event_first_seq=0,event_last_seq=0);h=[h[2]]
g=pair.analyze(u,h);self.assertEqual(g['status'],'incomplete',g);self.assertIn('no_touch_pairs',g['reasons'])
def test_30_bindings_cannot_be_touch_event(self):
u,h=trace();u[0]['source']='bindings';g=pair.analyze(u,h)
self.assertEqual(g['status'],'invalid_trace');self.assertIn('bad_event_source_phase',g['reasons'])
def test_31_bindings_must_use_none_phase(self):
u,h=self.binding_trace();u[4]['phase']='began';g=pair.analyze(u,h)
self.assertEqual(g['status'],'invalid_trace');self.assertIn('bad_output_phase',g['reasons'])
def test_32_unknown_program_source_still_rejected(self):
u,h=self.binding_trace();u[4]['source']='unfrozen_future_source';g=pair.analyze(u,h)
self.assertEqual(g['status'],'invalid_trace');self.assertIn('bad_source_or_mode',g['reasons'])
def portal_trace(self,scope=2):
base=dict(portal_request=7,portal_binding=8,portal_scene=9,portal_phase=1,portal_pending=1,modifier_publish_end_ns=120,feedback_group_start_ns=50,feedback_captured_ns=80,feedback_secondary=0,feedback_seen=63,feedback_identity_scope=scope)
def ev(i,n,phase,buttons):return dict(stage='event',eventseq=i,mono_ns=n,source='uitouch',phase=phase,slot=0,touch='0x1',x=300,y=150,touch_timestamp_s=42,mode='game',**dict(state(),buttons=buttons))
def out(i,e,n,phase,source,buttons,first,extra):return dict(stage='output',receiptseq=i,eventseq=e,event_first_seq=first,event_last_seq=e,mono_ns=n,publish_end_ns=n+10,source=source,phase=phase,mode='game',**dict(state(),buttons=buttons),**dict(base,**extra))
u=[ev(1,100,'began',256),out(1,1,110,'began','uitouch',256,1,{}),out(2,1,200,'none','portal_sequence',258,0,dict(portal_phase=2,portal_pending=0,feedback_group_start_ns=150,feedback_captured_ns=180,feedback_secondary=1)),ev(2,300,'ended',0),out(3,2,310,'ended','uitouch',0,2,dict(portal_request=8,portal_phase=0,portal_pending=0,modifier_publish_end_ns=0))]
h=[dict(event='npad_return',read_start_ns=n+15,time_ns=n+20,sampling=i,id=32,style=2,attributes=1,script_mask=0,**dict(state(),buttons=b))for i,n,b in [(1,110,256),(2,210,258),(3,310,0)]]
return u,h
def portal_case(self,change,status,reason,domain='synthetic'):
u,h=self.portal_trace();change(u,h);g=pair.analyze(u,h,domain)
self.assertEqual(g['status'],status,g);self.assertIn(reason,g['reasons'],g);self.assertFalse(g['physical_pass_claimed'])
def test_33_portal_combo_actual_two_receipts(self):
u,h=self.portal_trace();g=pair.analyze(u,h);self.assertEqual(g['status'],'protocol_pass',g)
self.assertTrue(g['combo_received']);self.assertEqual(g['portal_combo_pairs'],1);self.assertEqual(g['touch_output_pairs'],2)
self.assertEqual(g['pairs'][1]['attribution'],'output_only_not_new_touch');self.assertTrue(g['release_received']);self.assertFalse(g['physical_pass_claimed'])
def test_34_portal_no_combo_read(self):self.portal_case(lambda u,h:h.pop(1),'incomplete','missing_combo_receipt')
def test_35_portal_no_modifier_read(self):self.portal_case(lambda u,h:h.pop(0),'incomplete','missing_modifier_receipt')
def test_36_portal_tied_combo_read(self):self.portal_case(lambda u,h:h[1].update(read_start_ns=210),'incomplete','concurrent_undetermined')
def test_37_portal_old_group_start(self):self.portal_case(lambda u,h:u[2].update(feedback_group_start_ns=120),'invalid_trace','portal_feedback_time')
def test_38_portal_future_feedback(self):self.portal_case(lambda u,h:u[2].update(feedback_captured_ns=200),'invalid_trace','portal_feedback_time')
def test_39_portal_incomplete_group(self):self.portal_case(lambda u,h:u[2].update(feedback_seen=31),'invalid_trace','portal_feedback_identity')
def test_40_portal_unknown_identity(self):self.portal_case(lambda u,h:u[2].update(feedback_identity_scope=0),'invalid_trace','portal_feedback_identity')
def test_41_portal_synthetic_identity_device(self):self.portal_case(lambda u,h:None,'invalid_trace','synthetic_identity_on_device',domain='device')
def test_42_portal_ack_after_release(self):
def change(u,h):
ack=u.pop(2);ack.update(mono_ns=400,publish_end_ns=410,receiptseq=3,eventseq=2,event_first_seq=0,event_last_seq=2);u[-1]['receiptseq']=2;u.append(ack)
self.portal_case(change,'invalid_trace','portal_request_not_pending')
def test_43_portal_binding_changed(self):self.portal_case(lambda u,h:u[2].update(portal_binding=10),'invalid_trace','portal_request_identity')
def test_44_portal_scene_changed(self):self.portal_case(lambda u,h:u[2].update(portal_scene=10),'invalid_trace','portal_request_identity')
def test_45_portal_request_changed(self):self.portal_case(lambda u,h:u[2].update(portal_request=10),'invalid_trace','portal_request_identity')
def test_46_portal_duplicate_ack(self):
def change(u,h):
ack=dict(u[2],mono_ns=250,publish_end_ns=260,receiptseq=3);u.insert(3,ack);u[-1]['receiptseq']=4
self.portal_case(change,'invalid_trace','portal_request_not_pending')
def test_47_portal_source_is_not_event(self):self.portal_case(lambda u,h:u[0].update(source='portal_sequence'),'invalid_trace','bad_event_source_phase')
def test_48_portal_field_fraction(self):self.portal_case(lambda u,h:u[2].update(portal_scene=9.5),'invalid_trace','bad_integer')
def test_49_portal_field_negative(self):self.portal_case(lambda u,h:u[2].update(portal_binding=-1),'invalid_trace','portal_unsigned_range')
def test_50_portal_missing_feedback_field(self):self.portal_case(lambda u,h:u[2].pop('feedback_captured_ns'),'invalid_trace','missing_fields:feedback_captured_ns')
def test_51_portal_wrong_modifier_publication(self):self.portal_case(lambda u,h:u[1].update(modifier_publish_end_ns=121),'invalid_trace','portal_modifier_publication')
def test_52_portal_not_ZL_prefix(self):self.portal_case(lambda u,h:u[1].update(buttons=2),'invalid_trace','portal_modifier_publication')
def test_53_portal_no_action_edge(self):self.portal_case(lambda u,h:u[2].update(buttons=256),'invalid_trace','portal_action_edge')
def test_54_portal_wrong_action_phase(self):self.portal_case(lambda u,h:u[2].update(portal_pending=1),'invalid_trace','portal_request_not_pending')
def test_55_portal_navigation_ack(self):self.portal_case(lambda u,h:u[2].update(mode='navigation'),'invalid_trace','portal_request_not_pending')
def test_56_portal_stale_feedback(self):self.portal_case(lambda u,h:u[2].update(mono_ns=250000181,publish_end_ns=250000191),'invalid_trace','portal_feedback_time')
def test_57_portal_single_ui_still_not_executed(self):
u,h=self.portal_trace();g=pair.analyze(u,None);self.assertEqual(g['status'],'pair_not_executed',g);self.assertFalse(g['combo_received'])
def test_58_portal_native_identity_still_not_physical(self):
u,h=self.portal_trace(scope=1);g=pair.analyze(u,h,domain='device');self.assertEqual(g['status'],'protocol_pass',g);self.assertTrue(g['combo_received']);self.assertFalse(g['physical_pass_claimed'])
def test_59_portal_action_without_ack(self):
def change(u,h):
row=dict(u[1],receiptseq=2,event_first_seq=0,mono_ns=160,publish_end_ns=170,source='screenshot',phase='none',portal_phase=2,portal_pending=0,buttons=258);u.insert(2,row);u[3]['receiptseq']=3;u[-1]['receiptseq']=4
self.portal_case(change,'invalid_trace','portal_action_without_ack')
def test_60_portal_touch_cleared_before_ack(self):
def change(u,h):
row=dict(u[1],receiptseq=2,event_first_seq=0,mono_ns=160,publish_end_ns=170,source='layout',phase='none');u.insert(2,row);u[3]['receiptseq']=3;u[-1]['receiptseq']=4;u[-2]['slot']=-1
self.portal_case(change,'invalid_trace','portal_touch_not_active')
def test_61_portal_boolean_identity(self):self.portal_case(lambda u,h:u[2].update(portal_binding=True),'invalid_trace','boolean_not_integer')
def test_62_portal_combo_drops_modifier(self):self.portal_case(lambda u,h:u[2].update(buttons=2),'invalid_trace','portal_action_edge')
def test_63_portal_combo_ambiguous_edge(self):self.portal_case(lambda u,h:u[2].update(buttons=259),'invalid_trace','portal_action_edge')
def test_64_modifier_read_after_feedback_is_not_causal(self):
u,h=self.portal_trace();h[0].update(read_start_ns=185,time_ns=190);g=pair.analyze(u,h)
self.assertEqual(g['status'],'incomplete',g);self.assertIn('modifier_not_before_feedback',g['reasons']);self.assertFalse(g['combo_received'])
def test_65_modifier_read_equal_feedback_start_undetermined(self):
u,h=self.portal_trace();h[0].update(read_start_ns=145,time_ns=150);g=pair.analyze(u,h)
self.assertEqual(g['status'],'incomplete',g);self.assertIn('modifier_not_before_feedback',g['reasons']);self.assertFalse(g['combo_received'])
def two_portal_requests(self,second):
u,h=self.portal_trace();u2,h2=self.portal_trace()
for row in u2:
row['mono_ns']+=300;row['eventseq']+=2
if row['stage']=='event':row['touch']='0x2'
else:
row['receiptseq']+=3;row['publish_end_ns']+=300;row['event_last_seq']+=2
if row['event_first_seq']:row['event_first_seq']+=2
row['portal_request']=second+(row['portal_phase']==0)
for k in ['modifier_publish_end_ns','feedback_group_start_ns','feedback_captured_ns']:
if row[k]:row[k]+=300
for row in h2:row['read_start_ns']+=300;row['time_ns']+=300;row['sampling']+=3
return u+u2,h+h2
def test_66_two_requests_reuse_old_epoch_rejected(self):
u,h=self.two_portal_requests(7);g=pair.analyze(u,h)
self.assertEqual(g['status'],'invalid_trace',g);self.assertIn('portal_request_regression',g['reasons']);self.assertFalse(g['combo_received'])
def test_67_two_requests_forward_epoch_valid(self):
u,h=self.two_portal_requests(9);g=pair.analyze(u,h)
self.assertEqual(g['status'],'protocol_pass',g);self.assertEqual(g['portal_combo_pairs'],2);self.assertTrue(g['combo_received']);self.assertFalse(g['physical_pass_claimed'])
if __name__=='__main__':unittest.main()
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""素材采图契约与原素材哈希;不把synthetic snapshot当游戏身份。 | Asset capture contract and original asset hashes; a synthetic snapshot is not treated as game identity."""
import argparse,hashlib,json,re
from pathlib import Path
import os; DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
IOS=Path(__file__).resolve().parent.parent
sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
try:
# 这里原有一组「在 DmTouchOverlay.m 里找某段源码文字」的断言(底栏跳过宿主绘制、元数据字段、重画入口等),回城钮改版后对不上。
# 它们守的是实现写法不是行为:底栏谁来画由回归整表的界面截图守,触摸到游戏的协议行为由本目录的 C 单测(t_native_binding / t_game_bridge / t_native_hud_bridge 等)守——删掉,不追着源码文字改。
# 留下的是数据一致性:编进程序的三个哈希常量、清单、12 张贴图、两张技能表与实际文件一致。
# There used to be a group of assertions here that "look for a piece of source text in DmTouchOverlay.m" (bottom bar skips host drawing, metadata fields, redraw entry, etc.), which no longer matched after the town portal button redesign.
# They guarded how the implementation is written, not behavior: who draws the bottom bar is guarded by the UI screenshots of the full regression table, and the touch-to-game protocol behavior is guarded by the C unit tests in this directory (t_native_binding / t_game_bridge / t_native_hud_bridge etc.) - deleted, not chasing the source text with edits.
# What remains is data consistency: the three hash constants compiled into the program, the manifest, the 12 textures and the two skill tables match the actual files.
manifest=json.loads((IOS/'Sources/TouchArt/native_art_manifest.json').read_text())
compiled=(IOS/'Sources/dm_touch_native_art.c').read_text()
for name,target in [('dm_ta_manifest_sha',IOS/'Sources/TouchArt/native_art_manifest.json'),
('dm_ta_geometry_sha',IOS/'docs/native_art_v1_geometry.json'),
('dm_ta_binding_sha',IOS/'docs/touch_layout_spec_native_binding_v5.json')]:
values=re.findall(r'\bconst\s+char\s+'+name+r'\s*\[\s*\]\s*=\s*"([^"\n]*)"\s*;',compiled)
assert len(values)==1, f'{name} declaration must occur exactly once'
assert values[0]==sha(target), f'{name} differs from actual file SHA256'
assert manifest['geometry_sha256']==sha(IOS/'docs/native_art_v1_geometry.json')
assert manifest['binding_protocol_sha256']==sha(IOS/'docs/touch_layout_spec_native_binding_v5.json')
for a in manifest['assets']:
assert sha(IOS/'Sources/TouchArt'/a['asset'])==a['derived_png_sha256']==a['decoded_png_sha256']
assert a['pixel_format_code']==61 and len(a['official_sprite_md5'])==32 and len(a['official_sprite_sha256'])==64
import os,sys
romfs=os.environ.get('DM_ROMFS_SRC') or os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS') # 两张技能表不进仓库,从游戏文件现读核哈希 | the two skill tables are not kept in the repository; read fresh from the game files and verify the hashes
if os.path.isfile(os.path.join(romfs,'data','build_manifest.psv')):
sys.path.insert(0,str(IOS/'tools')); import romfs_art
for table in manifest['official_tables']:
raw=romfs_art.read(romfs,'global/excel/'+table['file'])
assert hashlib.sha256(raw).hexdigest()==table['sha256']==table['official']['sha256']
assert hashlib.md5(raw).hexdigest()==table['official']['ckey_md5']
else: print('(这台机器没有游戏文件,跳过两张技能表的哈希核对)')
assert len(manifest['assets'])==12
print('PASS native_art_capture: 3/3 real C hash constants match actual files; geometry+binding hashes distinct; 12/12 decoded PNG hashes; 2/2 frozen official tables SHA+MD5')
except AssertionError as e:
print(f'FAIL: {e}');raise SystemExit(1)
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python3
from pathlib import Path
import hashlib,json
root=Path(__file__).resolve().parents[1]
# 这里原有 10 条「在 front_ios.m / DmTouchOverlay.m 里找某段源码文字」的断言(回城键绑定的刷新时机、字段名等),产品重构后对不上。
# 它们守的协议行为现在由 C 单测 t_binding_freshness / t_portal_sequence / t_binding_group / t_native_binding 守,端到端由冒烟的触摸玩家路径和回归整表守——删掉。
# 留下的是数据一致性:历版触屏布局规格文档冻结不动、现行版的哈希与编进程序的常量一致。
# There used to be 10 assertions here that "look for a piece of source text in front_ios.m / DmTouchOverlay.m" (refresh timing of the town portal key binding, field names, etc.), which no longer matched after the product refactor.
# The protocol behavior they guarded is now guarded by the C unit tests t_binding_freshness / t_portal_sequence / t_binding_group / t_native_binding, and end to end by the smoke test's touch player path and the full regression table - deleted.
# What remains is data consistency: the touch layout spec documents of past versions stay frozen, and the current version's hash matches the constant compiled into the program.
old=root/'docs/touch_layout_spec.json'
assert hashlib.sha256(old.read_bytes()).hexdigest()=='38f3fed9acc16276ce278ae1b05ea7dad979e19cac53c447c4b73f014c3cb606'
previous=root/'docs/touch_layout_spec_native_binding_v2.json'
assert hashlib.sha256(previous.read_bytes()).hexdigest()=='2209cb320184d9ed58cd9fbee72dac734333773ff3332882405dba889749b13b'
previous3=root/'docs/touch_layout_spec_native_binding_v3.json'
assert hashlib.sha256(previous3.read_bytes()).hexdigest()=='c2921d0ef1bba260c30134603d4c2cbee50235483fa4b261e62069ef5cf9e3bb'
previous4=root/'docs/touch_layout_spec_native_binding_v4.json'
assert hashlib.sha256(previous4.read_bytes()).hexdigest()=='048ee8bfffa348d6a6829feb394ce723ad6acf892447d051eb7073b863a32d2f'
new=root/'docs/touch_layout_spec_native_binding_v5.json'
data=json.loads(new.read_text());assert data['profile_id']=='touch_native_binding_v5'
assert hashlib.sha256(new.read_bytes()).hexdigest() in (root/'Sources/dm_touch_native_art.c').read_text()
print('PASS frozen v1/v2/v3/v4 spec hashes; v5 profile/spec hash matches compiled constant')
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import tempfile
from test_touch_receipt import check_log
base='[touch-receipt] stage=output receiptseq=1 eventseq=0 event_first_seq=0 event_last_seq=0 mono_ns=200 publish_end_ns=201 source=portal_sequence phase=none buttons=0x102 lx=0 ly=0 rx=0 ry=0 mode=game'
checks=0
with tempfile.TemporaryDirectory() as d:
p=Path(d)/'receipt.log'
p.write_text(base+'\n')
try:check_log(p)
except AssertionError:checks+=1
else:raise AssertionError('portal_sequence must carry request/binding/scene/phase/pending/modifier timestamp')
good=base+' portal_request=5 portal_binding=77 portal_scene=3 portal_phase=2 portal_pending=0 modifier_publish_end_ns=100 feedback_group_start_ns=110 feedback_captured_ns=180 feedback_secondary=1 feedback_seen=63 feedback_identity_scope=2'
p.write_text(good+'\n');check_log(p);checks+=1
for old,new in [('portal_request=5','portal_request=0'),('portal_pending=0','portal_pending=1'),('portal_phase=2','portal_phase=1'),('modifier_publish_end_ns=100 feedback_group_start_ns=110 feedback_captured_ns=180 feedback_secondary=1 feedback_seen=63 feedback_identity_scope=2','modifier_publish_end_ns=200'),('buttons=0x102','buttons=0x100'),('feedback_seen=63','feedback_seen=1'),('feedback_identity_scope=2','feedback_identity_scope=0'),('feedback_group_start_ns=110','feedback_group_start_ns=99')]:
p.write_text(good.replace(old,new)+'\n')
try:check_log(p)
except AssertionError:checks+=1
else:raise AssertionError('negative accepted: '+new)
print(f'PASS portal_sequence receipt typed-phase/time/request negative {checks}/{checks} checks')
+17
View File
@@ -0,0 +1,17 @@
"""最小真实源接线约束;不声称UIImage/物理输入/原施法效果。 | Minimal real-source wiring constraints; makes no claim about UIImage / physical input / the original cast effect."""
from pathlib import Path
import argparse,hashlib,json
p=argparse.ArgumentParser();p.add_argument('--ios-root',type=Path,default=Path(__file__).resolve().parents[1]);args=p.parse_args()
ios=args.ios_root
f=(ios/'Sources/front_ios.m').read_text()
assert 'dm_input_set(_controls.buttons,_controls.lx,_controls.ly,_controls.rx,_controls.ry)' in f, 'front still drops right axis'
assert f.count('rx=%d ry=%d')>=2, 'both UITouch and output must report actual right axes'
assert f.count('_controls.lx,_controls.ly,_controls.rx,_controls.ry')>=3
assert 'dm_tc_set_navigation_mode(&_controls,n)' in f, 'navigation must suppress combat aim'
m=(ios/'Sources/DmTouchOverlay.m').read_text()
assert '@"touch_native_binding_v5"' in m
assert 's->map_cancel_active' in m and '@"right_aim"' in m
d=ios/'docs/touch_layout_spec_native_binding_v5.json'
assert json.loads(d.read_text())['profile_id']=='touch_native_binding_v5'
assert hashlib.sha256(d.read_bytes()).hexdigest() in (ios/'Sources/dm_touch_native_art.c').read_text()
print('PASS v5 source seam: full five-axis publish; real rx/ry receipts; navigation/cancel metadata; v5 spec SHA; runtime/phone UNRUN')
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""诊断收据契约:源接线检查及独立 transcript 判据,不把 STUB 当 HLE。 | Diagnostic receipt contract: source wiring checks and an independent transcript criterion, STUB is not treated as HLE."""
import argparse
import math
import re
from pathlib import Path
SOURCES = {'uitouch', 'navigation', 'layout', 'focus_cancel', 'screenshot', 'bindings', 'portal_sequence'}
TOUCH_PHASES = {'began', 'moved', 'ended', 'cancelled'}
def check_source(path):
s = Path(path).read_text()
assert '[touch-receipt]' in s, 'missing touch-receipt diagnostic records'
assert 'getenv("DM_TOUCH_CONTROL_LOG")' in s, 'missing environment gate'
assert '"cancelled"' in s, 'cancelled must not be mislabeled ended'
for source in ('uitouch', 'layout', 'navigation', 'focus_cancel', 'screenshot', 'bindings', 'portal_sequence'):
assert f'"{source}"' in s, f'missing source={source}'
assert s.count('++_touchEventSeq') == 1, 'event sequence has one UIKit-only increment site'
assert 'slot=-1' in s or 'int slot=-1' in s, 'unowned physical touch must remain observable'
assert 'touch_timestamp_s=' in s and 'touch.timestamp' in s, 'missing original UITouch timestamp'
assert 'event_first_seq=' in s and 'event_last_seq=' in s, 'missing publication event group'
print('SOURCE PASS: env gate + 4 phases + 7 sources + UIKit-only eventseq + unowned physical point + raw timestamp + publication event group')
def check_log(path):
records = []
for line in Path(path).read_text(errors='replace').splitlines():
if '[touch-receipt]' not in line:
continue
pairs = dict(re.findall(r'(\w+)=([^\s]+)', line))
records.append(pairs)
assert records, 'missing touch-receipt diagnostic records'
last_event = last_receipt = last_time = published_event = 0
phases, sources = set(), set()
pending_phases = []
previous_publish_end = 0
for r in records:
for key in ('stage', 'eventseq', 'mono_ns', 'buttons', 'lx', 'ly', 'rx', 'ry', 'mode', 'source', 'phase'):
assert key in r, f'missing {key}: {r}'
assert r['source'] in SOURCES, f'unknown source={r["source"]}'
assert r['phase'] in TOUCH_PHASES | {'none'}, f'unknown phase={r["phase"]}'
event = int(r['eventseq'])
mono = int(r['mono_ns'])
assert mono >= last_time and mono > 0, 'nonmonotonic clock'
assert mono >= previous_publish_end, 'record precedes previous publication end'
last_time = mono
if r['stage'] == 'event':
assert event == last_event + 1, f'nonphysical or lost eventseq {last_event}->{event}'
assert r['source'] == 'uitouch'
assert r['phase'] in TOUCH_PHASES, 'event cannot use none phase'
for key in ('slot', 'x', 'y', 'touch', 'touch_timestamp_s'):
assert key in r
assert math.isfinite(float(r['touch_timestamp_s'])) and float(r['touch_timestamp_s']) >= 0
phases.add(r['phase'])
pending_phases.append(r['phase'])
last_event = event
elif r['stage'] == 'output':
assert event == last_event, f'program push changed eventseq {last_event}->{event}'
for key in ('event_first_seq', 'event_last_seq'):
assert key in r, f'missing publication {key}'
first, last = int(r['event_first_seq']), int(r['event_last_seq'])
assert last == event, 'publication group tail must match current eventseq'
assert first == (published_event + 1 if event > published_event else 0), 'publication group must contain all and only newly received events'
if first:
assert r['source'] == 'uitouch', 'program source must not claim new physical events'
assert all(phase == r['phase'] for phase in pending_phases), 'event group phase differs from output phase'
pending_phases.clear()
published_event = event
receipt = int(r['receiptseq'])
assert receipt == last_receipt + 1
last_receipt = receipt
previous_publish_end = int(r['publish_end_ns'])
assert previous_publish_end >= mono, 'publication end precedes start'
if r['source'] == 'portal_sequence':
for key in ('portal_request','portal_binding','portal_scene','portal_phase','portal_pending','modifier_publish_end_ns','feedback_group_start_ns','feedback_captured_ns','feedback_secondary','feedback_seen','feedback_identity_scope'):
assert key in r, f'missing portal_sequence {key}'
assert all(int(r[key]) > 0 for key in ('portal_request','portal_binding','portal_scene'))
assert int(r['portal_phase']) == 2 and int(r['portal_pending']) == 0
assert 0 < int(r['modifier_publish_end_ns']) < mono, 'ACK must follow actual modifier publication'
assert int(r['feedback_secondary']) == 1 and int(r['feedback_seen']) == 63
assert int(r['feedback_identity_scope']) in {1, 2}, 'unconfirmed HUD identity cannot ACK'
assert int(r['modifier_publish_end_ns']) < int(r['feedback_group_start_ns']) <= int(r['feedback_captured_ns']) <= mono
mask = int(r['buttons'], 0)
assert mask & 256 and mask & (1|2|4|8|128|512), 'ACK must publish modifier plus facet'
sources.add(r['source'])
assert (r['phase'] != 'none') == (r['source'] == 'uitouch')
else:
raise AssertionError(r)
assert published_event == last_event, 'trailing physical events were not published'
print(f'LOG PASS: records={len(records)} events={last_event} outputs={last_receipt} phases={",".join(sorted(phases))} sources={",".join(sorted(sources))}')
return records, phases, sources
if __name__ == '__main__':
p = argparse.ArgumentParser()
p.add_argument('--source')
p.add_argument('--log')
p.add_argument('--probe', action='store_true', help='要求确定性 FakeTouch 探针的13事件和全部取消来源')
args = p.parse_args()
try:
if args.source:
check_source(args.source)
if args.log:
records, phases, sources = check_log(args.log)
if args.probe:
assert phases == {'began', 'moved', 'ended', 'cancelled'}
assert sources == {'uitouch', 'layout', 'navigation', 'focus_cancel', 'screenshot'}
events = [r for r in records if r['stage'] == 'event']
assert len(events) == 13, f'expected 13 independent probe events, got {len(events)}'
assert [r['phase'] for r in events[:9]] == ['began','moved','moved','ended','began','cancelled','began','moved','ended']
assert int(events[1]['lx']) == 32767, '60pt displacement must produce max left x'
assert int(events[2]['slot']) == 0 and int(events[2]['lx']) == 0, 'navigation cancellation must keep physical slot but zero controls'
assert int(events[7]['slot']) == -1 and float(events[7]['x']) == 147.0 and int(events[7]['lx']) == 0, 'focus cancellation must still record unowned physical point'
assert int(events[8]['slot']) == -1 and events[8]['phase'] == 'ended'
assert all(int(events[i]['buttons'], 0) == 0 for i in range(9))
outputs = [r for r in records if r['stage'] == 'output']
expected_sources = ['navigation', 'navigation', 'uitouch', 'uitouch', 'navigation',
'uitouch', 'uitouch', 'navigation', 'uitouch', 'uitouch', 'uitouch',
'focus_cancel', 'uitouch', 'uitouch', 'layout', 'screenshot', 'uitouch', 'uitouch']
assert [r['source'] for r in outputs] == expected_sources, 'probe publication source order mismatch'
groups = [(int(r['event_first_seq']), int(r['event_last_seq'])) for r in outputs if int(r['event_first_seq'])]
assert groups == [(i, i) for i in range(1, 10)] + [(10, 11), (12, 13)], 'two-touch batches must publish both events'
assert {int(r['slot']) for r in events[9:11]} == {0, 1}
assert {int(r['slot']) for r in events[11:13]} == {0, 1}
assert all(float(r['touch_timestamp_s']) == 42.125 for r in events), 'FakeTouch timestamp must stay unconverted'
print('PROBE PASS: 13/13 events; 4/4 phases; 5/5 sources; navigation slot kept; focus point kept; cancel axis reset; 11/11 event groups; raw timestamp=42.125')
except AssertionError as e:
print(f'FAIL: {e}')
raise SystemExit(1)
+34
View File
@@ -0,0 +1,34 @@
# Tables used by item annotations
| File | Contents | In the public repository? |
|---|---|---|
| `comments.tsv` | A one-line comment for each unique item, set item and runeword (rewritten entry by entry from the comments of a third-party mod) | **No.** It is an adaptation and the public repository does not ship it; without this table no comments are added, and the rest of the annotations work as usual |
| `oldnames.tsv` | Old-translation table: changes some names back to the older Chinese translations that long-time players know | **No.** It is a complete set of someone else's translated names and the public repository does not ship it; without this table the "change back to old names" step is skipped automatically, and the rest of the annotations work as usual |
## Supplying your own old-translation table
Put an `oldnames.tsv` in this directory to enable it. Tab-separated, UTF-8, first line is the header (the column names are in Chinese; keep them as shown):
```
文件 键 原文校验 旧译名
item-names KhalimFlail 2717cc0f (the name you want instead)
```
- `文件` (file): the name of the game string file, without `.json` (under `data/local/lng/strings/` in the game resources)
- `键` (key): the `Key` of that entry in the file
- `原文校验` (checksum of the original text): the first 8 hex digits of the SHA-1 of the entry's current Simplified Chinese text (UTF-8). Every entry is checked at build time, and a changed original (the game was updated) is reported as an error, so that nothing is replaced by mistake
- `旧译名` (old name): the name to use instead; write a line break as `\n`
## Supplying your own comment table
Put a `comments.tsv` in this directory to enable it. Tab-separated, UTF-8, first line is the header; the columns are the ones read by `comments()` in `annot_strings.py`:
```
文件 键 名字颜色 点评
item-names (the Key of the string) unique (your one-line comment)
```
- `文件` (file): `item-names` (unique and set items) or `item-runes` (runewords)
- `键` (key): the `Key` of that string; a key in the table that cannot be found in the game's string tables is reported as an error
- `名字颜色` (name color): `set` = set item (green); anything else is treated as unique (gold)
- `点评` (comment): one line shown below the name. Skill names mentioned in it must be the names after the change back to old names (if you also supply the old-translation table)
+34
View File
@@ -0,0 +1,34 @@
# 物品注释用的表
| 文件 | 内容 | 进不进公开仓库 |
|---|---|---|
| `comments.tsv` | 暗金 / 套装 / 符文之语的一句点评(按一个第三方模组的点评逐条改写的) | **不进**。属于改编,公开仓库不带;没有这份表时不加点评,其余注释照常 |
| `oldnames.tsv` | 旧译名对照表:把一部分名字换回老玩家熟悉的旧版中文译名 | **不进**。它是成套的他人译名,公开仓库不带;没有这份表时「换回旧译名」这一步自动不做,其余注释照常 |
## 自备旧译名对照表
放一份 `oldnames.tsv` 到本目录即启用。制表符分隔、UTF-8、首行是表头:
```
文件 键 原文校验 旧译名
item-names KhalimFlail 2717cc0f (你要换成的名字)
```
- `文件`:游戏字符串文件名,不带 `.json`(在游戏资源的 `data/local/lng/strings/` 下)
- `键`:该文件里那一条的 `Key`
- `原文校验`:这一条现行简体中文原文(UTF-8)的 SHA-1 前 8 位十六进制——构建时逐条核对,原文变了(游戏换了版本)会报错,免得换错
- `旧译名`:换成的名字;要换行写 `\n`
## 自备点评表
放一份 `comments.tsv` 到本目录即启用。制表符分隔、UTF-8、首行是表头;看 `annot_strings.py` 的 `comments()` 用到的列:
```
文件 键 名字颜色 点评
item-names (字符串的 Key) unique (你写的一句话)
```
- `文件`:`item-names`(暗金、套装件)或 `item-runes`(符文之语)
- `键`:该条字符串的 `Key`;表里的键在游戏字符串表里找不到会报错
- `名字颜色`:`set` = 套装(绿),其余按暗金(金)
- `点评`:显示在名字下面的一行。里面提到的技能名要用换回旧译名之后的名字(如果你同时带了旧译名对照表)
+221
View File
@@ -0,0 +1,221 @@
"""地上掉落名(筛选逻辑和规则复刻红叶;不抄红叶的字,信息一条不少,全从游戏表算,用我们自己的措辞)。
红叶的「筛选」就是改名字(它什么都不藏):低价值消耗品缩短、值钱 / 要用的加色、加来源与用途、底材加档次与价值。逐类对应如下:
药水:治疗 / 法力 1–5 级缩成 微 / 小 / 中 / 大 / 超 + 红 / 蓝(超级加色);复苏 小紫 / 大紫;解毒药水去「药水」。
卷轴:回城、鉴定两种常掉的缩短;箭矢 / 弩矢缩成「箭」「弩矢」。
宝石 / 骷髅:缩成「档-颜色」;碎裂 / 有瑕疵 / 标准三档加「合 N」= 这颗在魔盒里升级符文时合出第几号(cubemain.txt 的符文升级配方)。
符文:现行名「中文 英文 #号」上色,24 号起加框线、27 号起多空行、28 号起框线加长(越值钱越显眼)。
钥匙 / 首领器官 / 精华:来源首领由掉落表反查(treasureclassex.txt 逐层往上找,到 monstats / superuniques 的地狱掉落列),名字取字符串表;
钥匙另标首领所在幕,任务物品(ua1–ua5)按 misc.txt 英文名里的 Act 号标幕。
底材(武器 / 护甲):档次与轻中重由前面的「底材档次」步骤写好;这里加 ★(值得留的底材,名单与理由见 VALUE_BASES)、价值数字、顶级符文之语、
职业标枪的魔法词缀上限、合成手套的标志属性(cubemain.txt 的手套合成配方)。
名字一律取字符串表的现行值(已做过旧译名 / 符文序号)。游戏把多行名字倒着画(最后一行在最上面),所以「说明\\n名字」画出来是名字在上、说明在下。
Ground drop names (the filter logic and rules replicate the Hongye community mod; its wording is not copied, no piece of information is left out, everything is computed from the game tables, in our own wording).
Hongye's "filter" is just renaming (it hides nothing): low-value consumables are shortened, valuable / needed items get color, source and use are added, bases get tier and value. Category by category:
Potions: healing / mana levels 1–5 are shortened to 「微 / 小 / 中 / 大 / 超」(minor / light / medium / greater / super) + 「红 / 蓝」(red / blue) (super gets color); rejuvenation becomes 「小紫 / 大紫」(small purple / large purple); antidote potion drops 「药水」(potion).
Scrolls: the two commonly dropped ones, town portal and identify, are shortened; arrows / bolts are shortened to 「箭」(arrows) and 「弩矢」(bolts).
Gems / skulls: shortened to "grade-color"; the chipped / flawed / standard grades get 「合 N」(combine N) = which rune number this one produces when upgrading runes in the Horadric Cube (rune upgrade recipes in cubemain.txt).
Runes: the current name "Chinese English #number" is colored; frame lines from 24 on, extra blank lines from 27 on, longer frame lines from 28 on (the more valuable, the more conspicuous).
Keys / boss organs / essences: the source boss is reverse-looked-up from the treasure classes (search upward level by level in treasureclassex.txt, up to the Hell drop columns of monstats / superuniques); names come from the string table;
keys also get the act the boss is in, and quest items (ua1–ua5) get the act from the Act number in the English name in misc.txt.
Bases (weapons / armor): tier and light/medium/heavy are written by the earlier "base tier" step; here we add ★ (base worth keeping; list and reasons in VALUE_BASES), the value number, top runewords,
the magic affix cap for class javelins, and the signature property for crafted gloves (glove crafting recipes in cubemain.txt).
Names always use the current value in the string table (old translated names / rune numbers already applied). The game draws multi-line names in reverse (last line on top), so "description\\\\\\
name" is drawn with the name on top and the description below."""
import math, re
FILES = ('item-names.json', 'item-runes.json', 'chinese-overlay.json') # 加载顺序:后加载的同键覆盖前面的 | Load order: a later-loaded file overrides earlier ones for the same key
NAME_FILES = FILES + ('monsters.json', 'npcs.json')
RED, BLUE, BLUE2, PURPLE, ORANGE, GREEN = 'ÿc1', 'ÿc3', 'ÿc5', 'ÿc;', 'ÿc8', 'ÿc2'
SIZE = ('微', '小', '中', '大', '超') # 药水 1–5 级 | Potion levels 1–5
SHORT = {'tsc': '回城', 'aqv': '箭', 'cqv': '弩矢', 'rvs': PURPLE + '小紫', 'rvl': PURPLE + '大紫'}
STRIP = {'isc': '卷轴', 'yps': '药水'} # 常掉的低价值件:去掉后缀 | Commonly dropped low-value items: strip the suffix
GEM_COLOR = {'gema': '紫', 'gemt': '黄', 'gems': '蓝', 'geme': '绿', 'gemr': '红', 'gemd': '钻', 'gemz': '骷髅'}
GEM_GRADE = (('碎裂', ''), ('裂开', ''), ('', ''), ('无瑕', RED), ('完美', RED)) # 档:碎裂 / 有瑕疵 / 标准 / 无瑕 / 完美 | Grades: chipped / flawed / standard / flawless / perfect
GEM_GRADE_CH = {'c': 0, 'f': 1, 's': 2, 'l': 3, 'z': 3, 'p': 4} # 宝石码第 2 字(gzv:紫宝石的无瑕用 z) | 2nd character of the gem code (gzv: amethyst uses z for flawless)
SKULL_GRADE_CH = {'c': 0, 'f': 1, 'u': 2, 'l': 3, 'z': 4} # 骷髅码第 3 字(skl 无瑕、skz 完美) | 3rd character of the skull code (skl flawless, skz perfect)
HIGH_RUNE = 24 # 从这一号起加上下框线(值钱的高级符文);27 号起上下多空两行、28 号起框线加长 | From this number on, add frame lines above and below (valuable high runes); from 27 on, two extra blank lines above and below; from 28 on, longer frame lines
SOURCE_NOTE = {'pk1': '火炬钥匙', 'pk2': '火炬钥匙', 'pk3': '火炬钥匙', 'dhn': '地狱火炬材料', 'bey': '地狱火炬材料', 'mbr': '地狱火炬材料',
'tes': '合成赦免勋章', 'ceh': '合成赦免勋章', 'bet': '合成赦免勋章', 'fed': '合成赦免勋章'}
SOURCE_COLOR = {'pk1': RED, 'pk2': ORANGE, 'pk3': GREEN}
BOSS_ACT = {'The Countess': 1, 'The Summoner': 2, 'Nihlathak Boss': 5} # 首领所在幕(地图事实) | Act the boss is in (map fact)
# 值得留的底材(我们自己的判据,按用途分组):
# 法珠(法师专用、可 4 孔、自带法术词缀);刺客高阶爪(3 孔做混沌 / 狂怒、或高技能魔法爪);头环(可出 +2 技能 / 3 孔);
# 精英头盔里出顶级暗金 / 符文之语的三顶;4 孔精英身甲与力量需求最低的扩展身甲(做谜团 / 刚毅);6 孔女族长之矛;4 孔圣骑士皇家盾牌。
# 「值」= 这件做卓越品质(+1 最大值后 ×1.15)时的上限;身甲做谜团不做无形,头盔 / 武器给佣兵用按无形(再 ×1.5)算。武器给伤害、护甲给防御。
# Bases worth keeping (our own criteria, grouped by use):
# orbs (sorceress-only, can have 4 sockets, come with spell automods); high-tier assassin claws (3 sockets for Chaos / Fury, or high-skill magic claws); circlets (can roll +2 skills / 3 sockets);
# the three elite helms that yield top uniques / runewords; 4-socket elite body armor and the exceptional body armor with the lowest strength requirement (for Enigma / Fortitude); 6-socket Matriarchal Spear; 4-socket paladin Royal Shield.
# "Value" = the cap when this piece is superior quality (+1 max, then ×1.15); body armor is for Enigma and not ethereal, helms / weapons are for the mercenary and computed as ethereal (a further ×1.5). Weapons give damage, armor gives defense.
VALUE_BASES = {
**{c: {} for c in ('ob1', 'ob2', 'ob3', 'ob4', 'ob5', 'ob6', 'ob7', 'ob8', 'ob9', 'oba', 'obb', 'obc', 'obd', 'obe', 'obf')},
**{c: {} for c in ('9lw', '9tw', '7lw', '7tw', 'ci1', 'ci2', 'ci3', 'uhm', 'usk', 'utu', 'upl', 'uth', 'uul', 'uar', 'utp', 'amd', 'paa')},
'xtp': {'value': 'range'},
'urn': {'value': 'max', 'eth': True},
}
# 顶级符文之语:每件底材列出我们认为值得为它留底的几个(runes.txt 核过底材类型,能做才写)
# Top runewords: for each base, list the few we consider worth keeping the base for (base types checked against runes.txt; only written if it can be made)
TOP_RUNEWORDS = {'7wa': ('Oath', 'Death', 'Breath of the Dying')}
WEAPON_VALUE = {'7wa': {'value': 'range', 'eth': True}}
FRAMED = ('ci3',) # 头环里最高阶的权冠:可出 +2 技能 + 2 孔以上的顶级头环底 | The highest-tier circlet, the Diadem: a top circlet base that can roll +2 skills + 2 or more sockets
CLASS_MAGIC = ('ama', 'amf') # 职业标枪里扩展 / 精英最高阶的两把:标出魔法件能出的最高技能与攻速 | The two highest-tier exceptional / elite class javelins: mark the highest skill and attack speed a magic one can roll
CRAFT_GLOVE_MODS = {'crush': '压碎', 'mana-kill': '杀敌回蓝'} # 手套合成配方的标志属性里值得标的两种(鲜血 / 施法者合成) | The two signature properties of glove crafting recipes that are worth marking (Blood / Caster crafts)
def _strings_get(s, key):
v = [s.get(f, key) for f in NAME_FILES if s.has(f, key)]
return v[-1] if v else None
class Tables:
"""一次性读好要用的游戏表。 | Read all the game tables that are needed, once."""
def __init__(self, romfs):
from annot_strings import excel
self.misc = {r['code']: r for r in excel(romfs, 'misc.txt') if r.get('code')}
self.weap = {r['code']: r for r in excel(romfs, 'weapons.txt') if r.get('code')}
self.armor = {r['code']: r for r in excel(romfs, 'armor.txt') if r.get('code')}
self.types = {r['Code']: r for r in excel(romfs, 'itemtypes.txt') if r.get('Code')}
self.cube = excel(romfs, 'cubemain.txt')
self.runes = {r['*Rune Name']: r for r in excel(romfs, 'runes.txt') if r.get('*Rune Name')}
self.tc = excel(romfs, 'treasureclassex.txt')
self.monstats = excel(romfs, 'monstats.txt'); self.superuniques = excel(romfs, 'superuniques.txt')
self.automagic = excel(romfs, 'automagic.txt'); self.prefix = excel(romfs, 'magicprefix.txt'); self.suffix = excel(romfs, 'magicsuffix.txt')
self.parents = {}
for r in self.tc:
for k in range(1, 11):
i = r.get('Item%d' % k, '')
if i: self.parents.setdefault(i, set()).add(r['Treasure Class'])
def ancestors(self, t):
out, st = set(), [t]
while st:
x = st.pop()
if x and x not in out:
out.add(x); st += [self.types.get(x, {}).get('Equiv1', ''), self.types.get(x, {}).get('Equiv2', '')]
return out
def gem_rune(self, code):
"""这颗宝石在哪条符文升级配方里当辅料:返回合出的符文号。 | Which rune upgrade recipe uses this gem as the secondary ingredient: returns the number of the resulting rune."""
for r in self.cube:
ins = [(r.get('input %d' % k, '') or '').split(',')[0] for k in range(1, 8)]; out = r.get('output', '')
if code in ins and re.fullmatch(r'r\d\d', out) and any(re.fullmatch(r'r\d\d', i) for i in ins): return int(out[1:])
return None
def sources(self, code):
"""掉这件的首领 [(表, 内部名, 名字键)](地狱难度):从直接列出它的掉落表逐层往上找,再找哪个超级独特怪 / 怪的地狱掉落表在里面。 | Bosses that drop this piece [(table, internal name, name key)] (Hell difficulty): starting from the treasure class that lists it directly, search upward level by level, then find which super unique / monster has its Hell treasure class in there."""
seen, st = set(), [code]
while st:
for p in self.parents.get(st.pop(), ()):
if p not in seen: seen.add(p); st.append(p)
out = []
for r in self.superuniques:
if any(r.get(c) in seen for c in r if c.startswith('TC') and '(H)' in c): out.append(('su', r['Superunique'], r.get('Name')))
if out: return out
for r in self.monstats:
if any(r.get(c) in seen for c in r if c.startswith('TreasureClass') and '(H)' in c): out.append(('mon', r.get('Id'), r.get('NameStr')))
return out
def class_magic(self, code):
"""职业物品魔法件能出的最高技能(自动词缀 + 前缀的技能页加成)与最高攻速(后缀)。 | Highest skill a magic class item can roll (skill-tab bonus from automod + prefix) and highest attack speed (suffix)."""
a = self.ancestors(self.weap[code]['type'])
def best(tab, mods, spawn):
v = 0
for r in tab:
if spawn and r.get('spawnable') != '1': continue
its = {r.get('itype%d' % k, '') for k in range(1, 8)}; ex = {r.get('etype%d' % k, '') for k in range(1, 6)}
if not (its & a) or (ex & a): continue
for k in range(1, 4):
if r.get('mod%dcode' % k) in mods: v = max(v, int(r.get('mod%dmax' % k) or 0))
return v
return best(self.automagic, ('skilltab',), False) + best(self.prefix, ('skilltab',), True), best(self.suffix, ('swing1', 'swing2', 'swing3'), True)
def craft_glove(self, code):
"""这双手套所在的一族(普 / 扩 / 精)是哪条手套合成配方的底材:返回配方标志属性里值得标的那一个(CRAFT_GLOVE_MODS)。 | Which glove crafting recipe the family (normal / exceptional / elite) of this pair of gloves is the base for: returns the one worth marking among the recipe's signature properties (CRAFT_GLOVE_MODS)."""
r = self.armor[code]; fam = {r.get('normcode'), r.get('ubercode'), r.get('ultracode')}
for c in self.cube:
if (c.get('input 1', '') or '').split(',')[0] in fam:
for k in range(1, 6):
if c.get('mod %d' % k) in CRAFT_GLOVE_MODS: return CRAFT_GLOVE_MODS[c.get('mod %d' % k)]
return None
def _rune_line(code, name):
m = re.fullmatch(r"(.+) ([A-Za-z']+) (#\d+)", name)
if not m: return None
i, txt = int(code[1:]), ORANGE + m.group(1) + ' ' + BLUE2 + m.group(2) + GREEN + m.group(3)
if i < HIGH_RUNE: return txt
bar, gap = ORANGE + '—' * (13 if i >= 28 else 9), '\n' * (4 if i >= 27 else 2)
return bar + gap + txt + gap + bar
def misc_rule(T, s, code, name):
"""杂物类一个物品码的掉落名;None = 不改。 | Drop name for one miscellaneous item code; None = no change."""
row = T.misc[code]; t = row.get('type', '')
if code in SHORT: return SHORT[code]
if code in STRIP and name.endswith(STRIP[code]): return name[:-len(STRIP[code])]
if t in ('hpot', 'mpot') and code[-1:].isdigit():
i = int(code[-1]) - 1; w = SIZE[i] + ('红' if t == 'hpot' else '蓝')
return (RED if t == 'hpot' else BLUE) + w if i == 4 else w
if t in GEM_COLOR:
g = SKULL_GRADE_CH.get(code[2]) if t == 'gemz' else GEM_GRADE_CH.get(code[1])
if g is None: return None
word, color = GEM_GRADE[g]
base = color + word + '-' + GEM_COLOR[t] if word else name
n = T.gem_rune(code) if g <= 2 else None
return base + (' (合%d)' % n if n else '')
if t == 'rune' and re.fullmatch(r'r\d\d', code): return _rune_line(code, name)
if code in SOURCE_NOTE:
src = T.sources(code)
if not src: raise SystemExit('annot_drop:%s 在掉落表里找不到来源首领' % code)
who = '或'.join(dict.fromkeys(_strings_get(s, key) or key for _, _, key in src))
act = next((BOSS_ACT[x[1]] for x in src if x[1] in BOSS_ACT), None)
color = SOURCE_COLOR.get(code, GREEN)
return color + '[' + who + ' · ' + SOURCE_NOTE[code] + ']\n' + color + name + (' 第%d幕' % act if act else '')
m = re.search(r'Act ?(\d)', row.get('name', ''))
if m and t == 'ques' and code.startswith('ua'): return '%s 第%s幕' % (name, m.group(1))
return None
def base_rule(T, s, code, name):
"""武器 / 护甲一个物品码的掉落名(在底材档次之后);None = 不改。 | Drop name for one weapon / armor item code (after the base tier); None = no change."""
parts = []
w, a = T.weap.get(code), T.armor.get(code)
if code in CLASS_MAGIC:
sk, ias = T.class_magic(code); parts.append('魔法 技能+%d 攻速+%d' % (sk, ias))
vb = VALUE_BASES.get(code) or WEAPON_VALUE.get(code)
if vb and vb.get('value'):
k = 1.5 if vb.get('eth') else 1.0
if w:
lo, hi = int(w['mindam'] or w['2handmindam']), int(w['maxdam'] or w['2handmaxdam'])
parts.append('攻速 %s · 伤害 %d-%d' % (w.get('speed') or '0', lo, math.floor(math.ceil(hi * k) * 1.15)))
else:
lo, hi = int(a['minac']), int(a['maxac']); top = math.floor(math.floor((hi + 1) * k) * 1.15)
parts.append(('防御 %d-%d' % (lo, top)) if vb['value'] == 'range' else '防御 %d' % top)
if code in TOP_RUNEWORDS:
names = []
for rw in TOP_RUNEWORDS[code]:
r = T.runes[rw]; its = {r.get('itype%d' % k, '') for k in range(1, 7)}
if not (its & T.ancestors((w or a)['type'])): raise SystemExit('annot_drop:%s 做不了 %s' % (code, rw))
nm = (_strings_get(s, r['Name']) or rw).split('\n')[-1] # 前面的注释步骤给符文之语名加了范围 / 点评行:只取名字那一行 | Earlier annotation steps added range / review lines to the runeword name: take only the name line
names.append(re.sub(r'\u00ffc.', '', nm))
parts.append('可做 ' + ' / '.join(names))
glove = T.craft_glove(code) if a and a.get('type') == 'glov' else None
out = name
if code in VALUE_BASES: out = '★' + out
if glove: out += ' 〈合成·%s〉' % glove
if parts: out = '[' + ' · '.join(parts) + ']\n' + out
if code in FRAMED: out = '—' * 7 + '\n' + out + '\n' + '—' * 7 # 最顶级的几件上下加框线 | Add frame lines above and below the few top-tier pieces
return out if out != name else None
def ann_drop(s, romfs):
"""s = 已做完前面步骤的 Strings。返回改写条数。 | s = Strings with the earlier steps already applied. Returns the number of rewritten entries."""
T = Tables(romfs); n = 0
for tab, rule in ((T.misc, misc_rule), (T.weap, base_rule), (T.armor, base_rule)):
for code, row in tab.items():
key = row.get('namestr') or code
cur = [s.get(f, key) for f in FILES if s.has(f, key)]
if not cur: continue
new = rule(T, s, code, cur[-1]) # 最后一份才是游戏里显示的 | The last one is what the game displays
if new is None or new == cur[-1]: continue
n += sum(s.set(f, key, lambda _t, v=new: v) for f in FILES)
return n
+117
View File
@@ -0,0 +1,117 @@
"""给暗金、套装和符文之语名称加关键可变属性范围。 | Add key variable-property ranges to unique, set and runeword names."""
ITEM_FILES = ('item-names.json', 'chinese-overlay.json')
def _excel(romfs, name):
from annot_strings import excel
return excel(romfs, name)
STAT_NAMES = {
'abs-cold': '吸收冰伤', 'abs-cold%': '吸冰伤', 'abs-fire': '吸收火伤', 'abs-fire%': '吸火伤',
'abs-ltng': '吸电伤', 'abs-ltng%': '吸电伤', 'abs-mag': '吸收魔伤', 'ac': '防御', 'ac%': '强防',
'ac-miss': '防御', 'addxp': '经验', 'all-stats': '全属性', 'allskills': '全技能', 'ama': '亚马逊',
'att': '命中', 'att%': '命中', 'att-demon': '对恶魔命中', 'att-skill': '命中技能', 'att-undead': '对亡灵命中',
'aura': '光环', 'balance1': '打击恢复', 'balance2': '打击恢复', 'balance3': '打击恢复', 'block': '格挡',
'bloody': '撕裂', 'cast1': '施法速度', 'cast2': '施法速度', 'cast3': '施法速度', 'cheap': '商店折扣',
'cold-len': '冰冻时长', 'cold-max': '冰伤上限', 'cold-min': '冰伤下限', 'crush': '压碎打击',
'death-skill': '死亡技能', 'demon-heal': '对恶魔回复', 'dex': '敏捷', 'dmg': '伤害', 'dmg%': '强伤',
'dmg-cold': '冰伤', 'dmg-demon': '对恶魔伤', 'dmg-elem': '元素伤', 'dmg-fire': '火伤', 'dmg-ltng': '电伤',
'dmg-mag': '魔伤', 'dmg-max': '伤害上限', 'dmg-min': '伤害下限', 'dmg-norm': '伤害', 'dmg-undead': '对亡灵伤',
'dmg-pois': '毒伤', 'dru': '德鲁伊', 'dur': '耐久', 'enr': '精力', 'extra-cold': '冰伤加成',
'extra-fire': '火伤加成', 'extra-ltng': '电伤加成', 'extra-mag': '魔伤加成', 'extra-pois': '毒伤加成',
'fire-max': '火伤上限', 'fire-min': '火伤下限', 'freeze': '冻结', 'gold%': '金币', 'gethit-skill': '受击技能',
'heal-kill': '击杀回复', 'hit-skill': '击中技能', 'hp': '生命', 'hp%': '生命', 'kill-skill': '击杀技能',
'levelup-skill': '升级技能', 'lifesteal': '吸血', 'light': '照亮范围', 'light-thorns': '荆棘', 'ltng-max': '电伤上限',
'mag%': '寻宝', 'mana': '法力', 'mana%': '法力', 'mana-kill': '击杀回蓝', 'manasteal': '吸蓝',
'move1': '跑速', 'move2': '跑速', 'move3': '跑速', 'nec': '死灵法师', 'oskill': '技能',
'pal': '圣骑士', 'pierce-cold': '冰抗穿透', 'pierce-fire': '火抗穿透', 'pierce-ltng': '电抗穿透',
'pierce-mag': '魔抗穿透', 'pierce-pois': '毒抗穿透', 'randclassskill': '随机技能', 'red-dmg': '减伤',
'red-dmg%': '减伤', 'red-mag': '魔法减伤', 'regen': '生命回复', 'regen-mana': '法力回复', 'res-all': '全抗',
'res-cold': '冰抗', 'res-fire': '火抗', 'res-ltng': '电抗', 'res-mag': '魔抗', 'res-pois': '毒抗',
'skill': '技能', 'skill-rand': '随机技能', 'skilltab': '技能页', 'sock': '孔', 'sor': '女巫', 'stam': '耐力',
'str': '力量', 'swing1': '攻速', 'swing2': '攻速', 'swing3': '攻速', 'thorns': '荆棘', 'vit': '体力',
'charged': '技能', '*charged': '技能',
}
# 只有「min..max 里随机取一个值」的属性才是可变范围:看 properties.txt 的 func1。
# 1 / 2 / 5 / 6 / 7 / 8 / 10 / 14 / 22 = 随机取值(数值、伤害下限 / 上限 / 百分比、速度、技能页、孔数、单个技能等级);
# 15 = min 给下限属性、max 给上限属性(如「冰伤 15-45」是固定的伤害区间);11 / 19 = 触发 / 充能(几率或次数 + 技能等级);17 / 18 = 按等级 / 按时间。这些都不写。
# Only properties that "pick a random value within min..max" are variable ranges: look at func1 in properties.txt.
# 1 / 2 / 5 / 6 / 7 / 8 / 10 / 14 / 22 = random value (number, damage min / max / percent, speed, skill tab, socket count, single skill level);
# 15 = min goes to the minimum property and max to the maximum property (e.g. 「冰伤 15-45」(cold damage 15-45) is a fixed damage range); 11 / 19 = proc / charges (chance or count + skill level); 17 / 18 = per level / per time. None of these are written.
RANDOM_FUNCS = {'1', '2', '5', '6', '7', '8', '10', '14', '22'}
SKILL_CODES = {'skill', 'oskill', 'aura', 'skilltab', 'charged', '*charged', 'hit-skill', 'gethit-skill',
'kill-skill', 'death-skill', 'levelup-skill', 'att-skill', 'skill-rand'}
def _skill_names(s, romfs):
names = {}
for row in _excel(romfs, 'skills.txt'):
skill_id = row.get('*Id', '').strip()
skill = row.get('skill', '').strip()
if skill_id and skill:
value = s.get('skills.json', 'skillname' + skill_id)
names[skill] = value if value and len(value) <= 4 else '技能'
return names
def _label(code, param, skills):
label = STAT_NAMES.get(code, STAT_NAMES.get(code.lstrip('*')))
if code in SKILL_CODES or code.lstrip('*') in SKILL_CODES:
if param:
return skills.get(param, '技能') + '+'
return '技能'
return label or code
def _range_line(rows, code_prefix, min_prefix, max_prefix, slots, skills, props):
parts = []
for i in slots:
code = rows.get(code_prefix.format(i), '').strip()
if not code:
continue
minimum = rows.get(min_prefix.format(i), '').strip()
maximum = rows.get(max_prefix.format(i), '').strip()
if props.get(code.lstrip('*'), {}).get('func1') not in RANDOM_FUNCS or minimum == maximum or not minimum or not maximum:
continue
label = _label(code, rows.get(('par' + str(i)) if code_prefix.startswith('prop') else ('T1Param' + str(i)), '').strip(), skills)
suffix = '%' if '%' in code else ''
prefix = '+' if code == 'ac' else ''
parts.append('%s%s%s-%s%s' % (label, prefix, minimum, maximum, suffix))
if len(parts) == 3:
break
return '/'.join(parts)
def _annotate(s, key, line, color, files=ITEM_FILES):
"""名字下方加灰色范围行。串里的颜色码从写下处一直生效到被下一个码改掉(只在前面加 ÿc5 时名字也变灰),
所以名字行前补回它本来的颜色:暗金 / 符文之语 ÿc4、套装 ÿc2。
Add a gray range line below the name. A color code in the string stays in effect from where it is written until the next code changes it (adding only ÿc5 in front would turn the name gray too),
so the name line gets its original color restored in front: unique / runeword ÿc4, set ÿc2."""
if not line:
return 0
def add(text):
return text if text.startswith('\u00ffc5[') else '\u00ffc5[%s]\n%s%s' % (line, color, text)
n = 0
for filename in files:
n += s.set(filename, key, add)
return n
def ann_ranges(s, romfs):
"""按表中原顺序给可变属性加范围,返回改写条数。 | Add ranges to variable properties in the table's original order; returns the number of rewritten entries."""
skills = _skill_names(s, romfs)
props = {r['code']: r for r in _excel(romfs, 'properties.txt') if r.get('code')}
changed = 0
for row in _excel(romfs, 'uniqueitems.txt'):
if row.get('disabled') == '1' or row.get('spawnable') != '1':
continue
changed += _annotate(s, row.get('index', ''), _range_line(row, 'prop{}', 'min{}', 'max{}', range(1, 13), skills, props), '\u00ffc4')
for row in _excel(romfs, 'setitems.txt'):
changed += _annotate(s, row.get('index', ''), _range_line(row, 'prop{}', 'min{}', 'max{}', range(1, 9), skills, props), '\u00ffc2')
for row in _excel(romfs, 'runes.txt'):
if row.get('complete') != '1':
continue
changed += _annotate(s, row.get('Name', ''), _range_line(row, 'T1Code{}', 'T1Min{}', 'T1Max{}', range(1, 8), skills, props), '\u00ffc4', ('item-runes.json', 'chinese-overlay.json'))
return changed
+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env python3
"""物品 / 符文 / 区域 / 怪物 / 神殿的注释与旧译名(注释要、旧译名整体换回、不加英文缩写)。
做法 = RomFS 覆盖层换字符串文件(与 touch_strings 同一套机制),只改 zhCN 一列、按键名定位、原文不符即报错。
注释的数字一律从我们 3.3 包里的 excel 表算(不拷红叶的表);旧译名表 annot/oldnames.tsv 是从红叶 mod 的名字部分抽出、
逐条与 3.3 原文对过的。
Annotations and old translated names for items / runes / areas / monsters / shrines (annotations wanted, old translated names restored wholesale, no English abbreviations added).
Method = replace the string files via the RomFS overlay (same mechanism as touch_strings); only the zhCN column is changed, located by key name, and an error is raised if the source text does not match.
Annotation numbers are always computed from the excel tables in our 3.3 package (the Hongye community mod's tables are not copied); the old-name table annot/oldnames.tsv was extracted from the name part of the Hongye mod and
checked entry by entry against the 3.3 source text."""
import csv, hashlib, io, os, re, sys
import touch_layout
HERE = os.path.dirname(os.path.abspath(__file__))
STR = '/lng/strings/'
class Strings:
"""字符串文件的按键改写:保留原文件排版,只换 zhCN 的值。 | Per-key rewrite of a strings file: keep the original file's formatting and replace only the zhCN value."""
def __init__(self, romfs, repl):
self.romfs, self.repl, self.text, self.path, self.dirty = romfs, repl, {}, {}, set()
def _load(self, name):
if name in self.text: return
path, text = touch_layout.read_layout(self.romfs, None, suffix=STR + name)
prev = self.repl.get(path.lower()) # 前面的步骤(touch_strings)已经换过这份就在它的结果上改 | If an earlier step (touch_strings) has already replaced this file, modify on top of its result
if prev: text = open(prev, encoding='utf-8-sig').read()
self.text[name], self.path[name] = text, path
def _iter(self, name, key):
self._load(name)
return list(re.finditer(r'"Key":\s*"%s",.*?"zhCN":\s*("(?:[^"\\]|\\.)*")' % re.escape(key.replace('"', '\\"')), self.text[name], re.S))
def has(self, name, key): return bool(self._iter(name, key))
def keys(self, name):
self._load(name)
return re.findall(r'"Key":\s*"((?:[^"\\]|\\.)*)"', self.text[name])
def get(self, name, key):
import json
m = self._iter(name, key)
return json.loads(m[0].group(1)) if m else None
def get_lang(self, name, key, lang):
"""同一条目里别的语言列(如 enUS)。 | Other language columns in the same entry (e.g. enUS)."""
import json
self._load(name)
m = re.search(r'"Key":\s*"%s",.*?"%s":\s*("(?:[^"\\]|\\.)*")' % (re.escape(key), lang), self.text[name], re.S)
return json.loads(m.group(1)) if m else None
def set(self, name, key, fn):
"""fn(原文) → 新文;同一文件里同键多处一起改。返回改了几处。 | fn(original text) → new text; multiple occurrences of the same key in one file are changed together. Returns the number of changes."""
import json
ms = self._iter(name, key)
t = self.text[name]
for m in reversed(ms):
t = t[:m.start(1)] + json.dumps(fn(json.loads(m.group(1))), ensure_ascii=False) + t[m.end(1):]
if ms: self.text[name] = t; self.dirty.add(name)
return len(ms)
def write(self, outdir):
out = {}
for name in sorted(self.dirty):
o = os.path.join(outdir, 'annot_' + name)
open(o, 'w', encoding='utf-8-sig', newline='').write(self.text[name]); out[self.path[name].lower()] = o
return out
def excel(romfs, name):
_, text = touch_layout.read_layout(romfs, None, suffix='/global/excel/' + name)
return list(csv.DictReader(io.StringIO(text), delimiter='\t'))
# 物品名的键可能同时出现在 chinese-overlay.json(它后加载、同键覆盖),两处都改
# An item name key may also appear in chinese-overlay.json (it loads later and overrides the same key); change both places
ITEM_FILES = ('item-names.json', 'chinese-overlay.json')
def text_hash(t):
"""原文校验:游戏现行文字的 SHA-1 前 8 位(表里不存原文,只存这个,防原包换版本后照旧改)。 | Source-text check: first 8 characters of the SHA-1 of the game's current text (the table does not store the source text, only this, to prevent applying the same change after the original package changes version)."""
return hashlib.sha1(t.encode('utf-8')).hexdigest()[:8]
OLDNAMES = os.path.join(HERE, 'annot', 'oldnames.tsv')
def old_rows():
"""旧译名对照表的各行。表可以没有:公开仓库不带这份表(它是成套的他人译名),没有时「换回旧译名」这一步什么都不做,
注释、点评、符文序号等其余步骤照常。自备一份放到 annot/oldnames.tsv 即启用,格式见该目录下的 README。
Rows of the old-name table. The table may be absent: the public repository does not carry it (it is a complete set of someone else's translated names); without it the "switch back to old translated names" step does nothing,
and the other steps (annotations, comments, rune numbers, etc.) run as usual. Put your own copy at annot/oldnames.tsv to enable it; for the format see the README in that directory."""
if not os.path.isfile(OLDNAMES):
if not getattr(old_rows, 'said', 0): old_rows.said = 1; print('annot_strings:没有旧译名对照表 %s,不换旧译名(其余注释照常)' % OLDNAMES, file=sys.stderr)
return []
return list(csv.DictReader(open(OLDNAMES, encoding='utf-8'), delimiter='\t'))
def old_names(s):
n = 0
for row in old_rows():
f, k = row['文件'] + '.json', row['键']
new = row['旧译名'].replace('\\n', '\n')
cur = s.get(f, k)
if cur is None: raise SystemExit('annot_strings:%s 里没有键 %s' % (f, k))
if text_hash(cur) != row['原文校验']: raise SystemExit('annot_strings:%s / %s 的原文变了(校验 %s,现行「%s」)——原包换了版本,核过再改表' % (f, k, row['原文校验'], cur))
n += s.set(f, k, lambda _: new)
return n
def rune_numbers(s):
"""符文名 = 中文短名 + 原版英文名 + 序号:r30 → 「贝 Ber #30」。背包说明与地上标签都用这个键;
中文取符文之语配方里的短名 rNNL(已换旧译),英文取 rNNL 的 enUS 列。
Rune name = Chinese short name + the original game's English name + number: r30 → 「贝 Ber #30」(Chinese short name, Ber, #30). The inventory description and the ground label both use this key;
the Chinese comes from the short name rNNL in the runeword recipe (old translation already restored), the English from the enUS column of rNNL."""
n = 0
for i in range(1, 34):
zh, en = s.get('item-runes.json', 'r%02dL' % i), s.get_lang('item-runes.json', 'r%02dL' % i, 'enUS')
if not zh or not en or not re.fullmatch(r"[A-Za-z']+", en): raise SystemExit('annot_strings:r%02dL 的中 / 英短名不对:%r %r' % (i, zh, en))
n += s.set('item-runes.json', 'r%02d' % i, lambda _, i=i, zh=zh, en=en: '%s %s #%d' % (zh, en, i))
# 配方短名也带序号:rNNL 只被 gems.txt 的 letter 列引用,用在符文之语装备说明框的配方行,
# 游戏把各符文短名直接拼进一对引号(实测「'奈夫提尔'」),所以序号后留一个空格分隔:「'乔#31 伊斯特#24 贝#30 '」
# Recipe short names also carry the number: rNNL is referenced only by the letter column of gems.txt and is used in the recipe line of the runeword item tooltip;
# the game concatenates the rune short names directly inside one pair of quotes (measured: 「'奈夫提尔'」('NefTir')), so one space is left after the number as a separator: 「'乔#31 伊斯特#24 贝#30 '」('Jah#31 Ist#24 Ber#30 ')
n += s.set('item-runes.json', 'r%02dL' % i, lambda _, i=i, zh=zh: '%s#%d ' % (zh, i))
return n
def is_shield(code, types):
seen = set()
while code and code not in seen:
if code == 'shld': return True
seen.add(code); code = types.get(code, {}).get('Equiv1', '')
return False
def base_tiers(s, romfs):
"""底材名后标档次:普 / 扩 / 精 = 该行 code 等于同行 normcode / ubercode / ultracode;
身甲与盾类再标轻 / 中 / 重 = armor.txt 的 speed 列 0 / 5 / 10(跑步减速档)。例「神圣铠甲[精·中]」。
Mark the tier after the base name: 「普 / 扩 / 精」(normal / exceptional / elite) = the row's code equals the same row's normcode / ubercode / ultracode;
body armor and shields additionally get 「轻 / 中 / 重」(light / medium / heavy) = 0 / 5 / 10 in the speed column of armor.txt (run slowdown tier). Example: 「神圣铠甲[精·中]」(Sacred Armor [elite, medium])."""
types = {r['Code']: r for r in excel(romfs, 'itemtypes.txt') if r.get('Code')}
n = 0
for tab in ('weapons.txt', 'armor.txt'):
for r in excel(romfs, tab):
c = r.get('code')
if not c or r.get('spawnable') != '1' or r.get('quest') not in ('', '0') or r.get('type') == 'tpot': continue
tier = '普' if c == r['normcode'] else '扩' if c == r['ubercode'] else '精' if c == r['ultracode'] else None
if not tier: continue
if tab == 'armor.txt' and (r['type'] == 'tors' or is_shield(r['type'], types)):
tier += '·' + {'0': '轻', '5': '中', '10': '重'}[r['speed']]
key = r['namestr'] or c
for f in ITEM_FILES:
n += s.set(f, key, lambda t, tier=tier: '%s[%s]' % (t, tier))
return n
def comments(s):
"""暗金 / 套装 / 符文之语的一句点评(我们自己写的,按红叶点评的意思逐条重写、字面不照搬)。绿色一行,显示在名字下面、范围行上面:
串 = [范围行\n]ÿc2点评\n<名字色>名字(游戏把多行名字倒着画,最后一行在最上面)。
核对:点评里不许出现「已换回旧译名的技能」的 3.3 现行名(点评用换回后的名字),有就报错。
A one-sentence review for uniques / sets / runewords (written by ourselves, rewritten entry by entry after the meaning of the Hongye community mod's reviews, wording not copied). One green line, shown below the name and above the range line:
string = [range line\\
]ÿc2review\\
<name color>name (the game draws multi-line names in reverse, last line on top).
Check: a review must not contain the 3.3 current name of "a skill already switched back to its old translated name" (reviews use the restored names); raise an error if it does."""
renamed, orig = {}, Strings(s.romfs, s.repl) # orig:没改过的那份,取技能现行名 | orig: the unmodified copy, used to get the skills' current names
for row in old_rows():
if row['文件'] == 'skills' and row['键'].lower().startswith('skillname'):
cur = orig.get('skills.json', row['键'])
if cur and cur != row['旧译名']: renamed[cur] = row['旧译名']
kept = {s.get('skills.json', k) for k in s.keys('skills.json') if k.lower().startswith('skillname')} # 换名后仍在用的名字(两个技能同名、只改了一个,如「专注」)不算错 | A name still in use after the rename (two skills shared a name and only one was changed, e.g. 「专注」(Concentration)) is not an error
renamed = {a: b for a, b in renamed.items() if a not in kept}
n = 0
cp = os.path.join(HERE, 'annot', 'comments.tsv')
if not os.path.isfile(cp): # 点评表可以没有(公开仓库不带:它是照别人的点评逐条改写的):没有就不加点评,其余注释照常。自备格式见 annot/README.md | the comments table may be absent (the public repository does not carry it: it was rewritten entry by entry from someone else's comments): without it no comments are added, and the other annotations are produced as usual. For the format of your own copy see annot/README.md
print('annot_strings:没有点评表 %s,不加点评(其余注释照常)' % cp, file=sys.stderr); return 0
for row in csv.DictReader(open(cp, encoding='utf-8'), delimiter='\t'):
c, color = row['点评'], '\u00ffc2' if row['名字颜色'] == 'set' else '\u00ffc4'
bad = [a for a in renamed if a in c and renamed[a] not in c]
if bad: raise SystemExit('annot_strings:%s 的点评「%s」里有 3.3 现行技能名 %s(应写旧译名 %s)' % (row['键'], c, bad, [renamed[a] for a in bad]))
def add(t, c=c, color=color):
if '\n' in t: head, name = t.rsplit('\n', 1); return '%s\n\u00ffc2%s\n%s' % (head, c, name)
return '\u00ffc2%s\n%s%s' % (c, color, t)
files = ('item-runes.json', 'chinese-overlay.json') if row['文件'] == 'item-runes' else ITEM_FILES
k = sum(s.set(f, row['键'], add) for f in files)
if not k: raise SystemExit('annot_strings:点评的键 %s 在字符串表里没有' % row['键'])
n += k
return n
def apply_all(s, romfs):
"""全部步骤按次序做在同一个 Strings 上;返回 {步骤: 改了几处}。旧译名在前(后面的注释挂在换回后的名字上);
掉落名最后(杂物类按规则表缩短 / 加色 / 加说明,在旧译名与符文序号之后)。
All steps are applied in order to the same Strings; returns {step: number of changes}. Old translated names come first (later annotations attach to the restored names);
drop names come last (miscellaneous items are shortened / colored / given descriptions by the rule table, after old translated names and rune numbers)."""
from annot_ranges import ann_ranges
from annot_world import ann_levels, ann_shrines
from annot_drop import ann_drop
return {'旧译名': old_names(s), '可变范围': ann_ranges(s, romfs), '点评': comments(s), '符文序号': rune_numbers(s), '底材档次': base_tiers(s, romfs),
'区域等级': ann_levels(s, romfs), '神殿效果': ann_shrines(s, romfs),
'掉落名': ann_drop(s, romfs)}
# 普通文字框(TextBoxWidget)不认颜色码:游戏加载时把 ÿc 换成私用区字符 U+E07E,文字框原样画成「*5」、换行画成空格
# (真机上编年史列表所见)。说明框(TooltipsPanel)、聊天(ChatListWidget)认。所以除了写进字符串表的注释版,再出一份「文字框版」:
# 同一条流水线只做改名类步骤(旧译名、符文序号、底材档次、区域等级),不做装饰类步骤(可变范围行、点评行、神殿效果行、掉落名的缩写 / 颜色 / 说明行)。
# 两份逐键对照,凡注释版带颜色码且与文字框版不同的,记一行「注释版 → 文字框版」(都换成运行时的 U+E07E 写法)。
# 宿主在文字框写字入口(观测门 14,dm_textbox.c)只按这张表整串 / 子串替换:原版自带的串不在表里、一个字节都不动;注释开关关掉时没有这张表
# Ordinary text boxes (TextBoxWidget) do not understand color codes: at load time the game replaces ÿc with the private-use character U+E07E, and the text box draws it verbatim as "*5" and draws newlines as spaces
# (as seen in the chronicle list on a real device). The tooltip box (TooltipsPanel) and chat (ChatListWidget) do understand them. So besides the annotated version written into the string table, a "text-box version" is also produced:
# the same pipeline does only the renaming steps (old translated names, rune numbers, base tiers, area levels) and not the decorative steps (variable range lines, review lines, shrine effect lines, and the abbreviations / colors / description lines of drop names).
# The two are compared key by key; wherever the annotated version has color codes and differs from the text-box version, one line "annotated version → text-box version" is recorded (both converted to the runtime U+E07E form).
# At the text-box write entry (observation gate 14, dm_textbox.c) the host only does whole-string / substring replacement by this table: the original game's own strings are not in the table and not a single byte of them is touched; when the annotation switch is off this table does not exist
TEXTBOX_TABLE = 'dm_textbox_plain.tsv'
TEXTBOX_STEPS = ('旧译名', '符文序号', '底材档次', '区域等级')
_last_table = None
def apply_textbox(s, romfs):
from annot_world import ann_levels
steps = {'旧译名': lambda: old_names(s), '符文序号': lambda: rune_numbers(s), '底材档次': lambda: base_tiers(s, romfs), '区域等级': lambda: ann_levels(s, romfs)}
return {k: steps[k]() for k in TEXTBOX_STEPS}
def textbox_table(full, plain):
"""full / plain:同一组文件、同一组键的两份 Strings。返回 {运行时注释版: 运行时文字框版};同一注释版对到两种文字框版 = 生成器自相矛盾,报错。 | full / plain: two Strings over the same set of files and the same set of keys. Returns {runtime annotated version: runtime text-box version}; the same annotated version mapping to two different text-box versions = the generator contradicts itself, raise an error."""
rt = lambda t: t.replace('\u00ffc', '\ue07e')
# 同一个键在几份表里都有时,后加载的覆盖前面的(同 annot_drop:最后一份才是游戏里显示的):先按加载顺序取每个键的生效值
# When the same key exists in several tables, the later-loaded one overrides the earlier ones (same as annot_drop: the last one is what the game displays): first take each key's effective value in load order
from annot_drop import FILES as LOAD_ORDER
order = [n for n in LOAD_ORDER if n in full.dirty] + sorted(n for n in full.dirty if n not in LOAD_ORDER)
eff = {}
for name in order:
for key in full.keys(name):
a, b = full.get(name, key), plain.get(name, key)
if a is not None and b is not None: eff[(name if name not in LOAD_ORDER else '*', key)] = (a, b)
tab, src = {}, {}
for k, (a, b) in eff.items():
if 'ÿc' not in a or a == b: continue
ra, rb = rt(a), rt(b)
if tab.get(ra, rb) != rb: raise SystemExit('annot_strings:注释版 %r 对到两种文字框版 %r(%s)/ %r(%s)' % (a, tab[ra], src[ra], rb, k))
tab[ra] = rb; src[ra] = k
return tab
def write_textbox_table(dst):
"""gen_romfs_overlay 写完带本特性的变体后调:把最近一次 build 算出的对照表写进变体目录(一行一条,键与值里的 \\ / 换行 / 制表转义)。 | Called by gen_romfs_overlay after it writes a variant with this feature: writes the mapping table computed by the most recent build into the variant directory (one entry per line; \\\\ / newline / tab in keys and values are escaped)."""
if _last_table is None: raise SystemExit('annot_strings:还没 build 就写文字框对照表')
esc = lambda t: t.replace('\\', '\\\\').replace('\n', '\\n').replace('\t', '\\t')
with open(os.path.join(dst, TEXTBOX_TABLE), 'w', encoding='utf-8', newline='\n') as f:
f.write('# 注释版\t文字框版(annot_strings.py 生成,宿主 dm_textbox.c 读)\n')
for a in sorted(_last_table): f.write('%s\t%s\n' % (esc(a), esc(_last_table[a])))
return len(_last_table)
def build(romfs, outdir, repl):
"""repl:前面步骤已换的 {包内逻辑路径: 本地文件}。返回 ({包内逻辑路径: 本地文件}, {步骤: 改了几处})。 | repl: {in-package logical path: local file} already replaced by earlier steps. Returns ({in-package logical path: local file}, {step: number of changes})."""
global _last_table
s = Strings(romfs, repl)
stat = apply_all(s, romfs)
p = Strings(romfs, repl); apply_textbox(p, romfs)
_last_table = textbox_table(s, p); stat['文字框对照'] = len(_last_table)
return s.write(outdir), stat
if __name__ == '__main__': # 单独跑:python3 annot_strings.py <RomFS> <输出目录> → 打印统计 | Standalone run: python3 annot_strings.py <RomFS> <output dir> → prints statistics
import sys
os.makedirs(sys.argv[2], exist_ok=True)
r, st = build(sys.argv[1], sys.argv[2], {})
print(st); [print(k, '→', v) for k, v in r.items()]
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""区域、怪物、神殿名称注释。 | Annotations for area, monster and shrine names."""
from collections import defaultdict
def _number(row, key):
value = row.get(key, '')
return int(value or 0)
def _groups(rows, key, fields):
groups = defaultdict(list)
for row in rows:
if row.get(key):
groups[row[key]].append(tuple(row.get(field, '') for field in fields))
return groups
def ann_levels(s, romfs):
from annot_strings import excel
fields = ('MonLvlEx', 'MonLvlEx(N)', 'MonLvlEx(H)')
groups = _groups(excel(romfs, 'levels.txt'), 'LevelName', fields)
skipped = []
changed = 0
for key, values in groups.items():
unique = set(values)
if len(unique) > 1:
skipped.append(key)
continue
levels = tuple(_number(dict(zip(fields, values[0])), field) for field in fields)
if levels == (0, 0, 0):
continue
changed += s.set('levels.json', key, lambda text, levels=levels: '%s[%d/%d/%d]' % (text, *levels))
if skipped:
print('ann_levels:同键多值,跳过:%s' % '、'.join(sorted(skipped)))
return changed
def _duration(row):
frames = _number(row, 'Duration in frames')
return '%d 秒' % (frames // 25) if frames else ''
def _reset(row):
value = row.get('reset time in minutes', '')
return '刷新时间 %s 分钟' % value if value else '不会刷新'
def _shrine_effect(row):
code = row['Code']
arg0, arg1 = row.get('Arg0', ''), row.get('Arg1', '')
duration, reset = _duration(row), _reset(row)
if code == '1':
effect = '生命和法力全满'
elif code == '2':
effect = '生命全满'
elif code == '3':
effect = '法力全满'
elif code == '4':
effect = '用当前生命的 %s%% 恢复法力,最多 %s' % (arg0, arg1)
elif code == '5':
effect = '用当前法力的 %s%% 恢复生命,最多 %s' % (arg0, arg1)
elif code == '6':
effect = '+%s%% 防御' % arg0
elif code == '7':
effect = '+%s%% 准确率,+%s%% 伤害' % (arg0, arg1)
elif code in ('8', '9', '10', '11'):
effect = '+%s%% %s' % (arg0, {'8': '抗火', '9': '抗冰', '10': '抗电', '11': '抗毒'}[code])
elif code == '12':
effect = '+%s 所有技能' % arg0
elif code == '13':
effect = '+%s%% 法力重生' % arg0
elif code == '14':
effect = '无限耐力'
elif code == '15':
effect = '经验+%s%%' % arg0
elif code == '16':
effect = '颠倒角色名称'
elif code == '17':
effect = '生成一个回家的传送门'
elif code == '18':
effect = '随机把背包中的一颗宝石提升一级;没有宝石则生成一颗最低级宝石'
elif code == '19':
effect = '爆发火焰,使周围所有单位失去 %s%% 生命' % arg0
elif code == '20':
effect = '使最近的怪物升级为精英或冠军怪'
elif code == '21':
effect = '获得 %s-%s 个爆炸药剂,并使周围产生爆炸' % (arg0, arg1)
elif code == '22':
effect = '获得 %s-%s 个窒息气体药剂,并在周围产生毒雾' % (arg0, arg1)
else:
effect = row['*Effect']
details = [effect]
if reset:
details.append(reset)
if duration:
details.append('持续 %s' % duration)
return ','.join(details)
def ann_shrines(s, romfs):
from annot_strings import excel
changed = 0
for row in excel(romfs, 'shrines.txt'):
key = row.get('StringName')
if not key or key == 'ShrId0' or '(Not Used)' in row.get('*Effect', ''): # 表里标了不用的(生命 / 法力交换、颠倒名字)游戏不生成,不加 | Those marked unused in the table (life / mana exchange, reversed names) are not generated by the game; not added
continue
effect = _shrine_effect(row)
changed += s.set('shrines.json', key, lambda text, effect=effect: 'ÿc5%s\nÿc0%s' % (effect, text))
return changed
+17
View File
@@ -0,0 +1,17 @@
# App Store Connect API 密钥口径(TestFlight 用)。只放编号,不放密钥:
# ~/.appstoreconnect/dm.env:ASC_KEY_ID=… ASC_ISSUER=… ASC_APP_ID=…(App 的数字编号)
# 密钥文件:~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8(600;altool 缺省也在这里找)
# asc_auth:有密钥就把 xcodebuild 的 API 认证参数放进数组 ASC_AUTH,没有就留空(开发机照旧用本地描述文件)
# App Store Connect API key conventions (for TestFlight). Only IDs go here, not the key:
# ~/.appstoreconnect/dm.env: ASC_KEY_ID=... ASC_ISSUER=... ASC_APP_ID=... (the App's numeric ID)
# Key file: ~/.appstoreconnect/private_keys/AuthKey_<ASC_KEY_ID>.p8 (600; altool also looks here by default)
# asc_auth: if a key exists, put the xcodebuild API authentication arguments into the array ASC_AUTH; otherwise leave it empty (development machines keep using local provisioning profiles)
ASC_ENV=${DM_ASC_ENV:-$HOME/.appstoreconnect/dm.env}
asc_auth() {
ASC_AUTH=()
[ -f "$ASC_ENV" ] || return 0
source "$ASC_ENV"
ASC_KEY=$HOME/.appstoreconnect/private_keys/AuthKey_${ASC_KEY_ID}.p8
[ -f "$ASC_KEY" ] || { echo "🔴 缺 API 密钥文件 $ASC_KEY"; return 1; }
ASC_AUTH=(-authenticationKeyPath "$ASC_KEY" -authenticationKeyID "$ASC_KEY_ID" -authenticationKeyIssuerID "$ASC_ISSUER")
}
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""给资源直接下载(Sources/asset_dl.m)出下载站目录:asset_manifest.py <资源文件夹(含 data/)> <下载站里的 assets 目录>
生成 <assets>/manifest.json(每个文件的名字、字节数、SHA-256;.holes 区段表当普通文件一起列)并把 <assets>/data 软链到资源正本(不拷第二份)。
校验值按(字节数, 修改时刻)缓存在 <assets> 旁的 .asset_sha.json,资源没变时重出清单不重算 4 GB。
Produce the download-site directory for direct asset download (Sources/asset_dl.m): asset_manifest.py <asset folder (containing data/)> <assets directory in the download site>
Generates <assets>/manifest.json (each file's name, byte count, SHA-256; the .holes extent table is listed as an ordinary file) and symlinks <assets>/data to the master copy of the assets (no second copy).
Checksums are cached by (byte count, modification time) in .asset_sha.json next to <assets>, so regenerating the manifest when the assets are unchanged does not recompute 4 GB."""
import hashlib, json, os, sys
src, out = os.path.realpath(os.path.join(sys.argv[1], "data")), sys.argv[2]
os.makedirs(out, exist_ok=True)
cache_p = os.path.join(os.path.dirname(os.path.abspath(out)), ".asset_sha.json")
try: cache = json.load(open(cache_p))
except Exception: cache = {}
files, total = [], 0
for nm in sorted(os.listdir(src)):
p = os.path.join(src, nm)
if nm.startswith(".") or not os.path.isfile(p): continue
st = os.stat(p); key = f"{p}|{st.st_size}|{st.st_mtime_ns}"
if key not in cache:
h = hashlib.sha256()
with open(p, "rb") as f:
while b := f.read(1 << 22): h.update(b)
cache[key] = h.hexdigest()
files.append({"name": nm, "size": st.st_size, "sha256": cache[key]}); total += st.st_size
json.dump({k: v for k, v in cache.items() if k.split("|")[0].startswith(src)}, open(cache_p, "w"))
json.dump({"version": 1, "total": total, "files": files}, open(os.path.join(out, "manifest.json"), "w"), indent=0)
link = os.path.join(out, "data")
if os.path.islink(link): os.unlink(link)
os.symlink(src, link)
print(f"清单 {len(files)} 个文件共 {total} 字节 → {out}/manifest.json;data → {src}")
+99
View File
@@ -0,0 +1,99 @@
#!/bin/bash
# 真机启动时间线(DM_BOOTPROF ⓪–⑥ 分段):冷启动 1 局(重装后首启:代码页冷;RomFS 可能仍在系统文件缓存里——真冷要重启手机,不做)+ 热启动 N 局。
# 用法:[DM_OUT=产物] dm/ios/tools/bootprof.sh [热局数=3] 或 --metal-cold [局数=3]
# Real-device boot timeline (DM_BOOTPROF segments ⓪–⑥): 1 cold-start run (first launch after reinstall: code pages cold; the RomFS may still be in the system file cache - truly cold needs a phone reboot, not done) + N warm-start runs.
# Usage: [DM_OUT=build output] dm/ios/tools/bootprof.sh [warm runs=3] or --metal-cold [runs=3]
set -u
cd "$(dirname "$0")/.."
METAL_COLD=0
if [ "${1:-}" = "--metal-cold" ]; then METAL_COLD=1; N=${2:-3}; else N=${1:-3}; fi
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}; RUN_ROOT=${DM_ROOT:-$HOME/dm-work}/run/ios; R=$RUN_ROOT/bootprof; mkdir -p $R; rm -f $R/*.log
t(){ echo "[$(date +%T)] $*"; }
INGAME_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,C0.84:0.208@OpenPanel:CharacterSelectPanel%1>UpdateCharacterInfo,MSG:CharacterSelect:LoadCharacter:0@UpdateCharacterInfo%0.3>FrontEndNavigation:ToGame' # 同 smoke.sh | Same as smoke.sh
if [ "$METAL_COLD" -eq 1 ]; then
case "$N" in ''|*[!0-9]*|0) t "🔴 局数必须是正整数"; exit 1;; esac
fi
source tools/devlock.sh
devlock_acquire "bootprof"
trap devlock_release EXIT
./run.sh build > $R/build.log 2>&1 || { t "🔴 构建失败"; tail -5 $R/build.log; exit 1; }
./run.sh install >> $R/build.log 2>&1 || { t "🔴 装机失败"; tail -5 $R/build.log; exit 1; }
if [ "$METAL_COLD" -eq 1 ]; then
for kind in cold hot; do
for k in $(seq 1 $N); do
name=${kind}${k}; cold_env=()
[ "$kind" = cold ] && cold_env=(DEVICECTL_CHILD_DM_METAL_COLD=1)
# 冷 / 热都按冒烟同一键序进局(标准存档新副本),量「进局读取」= ToGame → 读取画面撤下(冷缓存下预热编管线会不会拉长读取)
# Cold / warm both enter the run with the same key sequence as the smoke test (fresh copy of the standard save), measuring "run-entry loading" = ToGame → loading screen removed (whether warm-up pipeline compilation under a cold cache lengthens loading)
env -u DEVICECTL_CHILD_DM_METAL_COLD "${cold_env[@]}" DEVICECTL_CHILD_DM_SAVE_FRESH=warlock DEVICECTL_CHILD_DM_KEYS="$INGAME_KEYS" DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_BOOTPROF=1 DEVICECTL_CHILD_DM_WATCH=40 ./run.sh boot 60 > $R/$name.run 2>&1 || { t "🔴 $name 启动失败"; exit 1; }
cp $RUN_ROOT/out/boot.txt $R/$name.log || { t "🔴 $name 日志读取失败"; exit 1; }
grep -q "⑥" $R/$name.log || t "🔴 $name 没出分段表(看 $R/$name.log)"
done
done
else
for k in $(seq 0 $N); do
name=hot$k; [ $k = 0 ] && name=cold
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_UIMSG=1 DEVICECTL_CHILD_DM_BOOTPROF=1 DEVICECTL_CHILD_DM_WATCH=8 ./run.sh boot 40 > $R/$name.run 2>&1
cp $RUN_ROOT/out/boot.txt $R/$name.log
grep -q "⑥" $R/$name.log || t "🔴 $name 没出分段表(看 $R/$name.log)"
done
fi
python3 - $R $N $METAL_COLD <<'PY'
import sys, re, statistics
R, N, metal_flag = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
metal_cold = metal_flag == 1
names = ([f'cold{k}' for k in range(1, N + 1)] + [f'hot{k}' for k in range(1, N + 1)]) if metal_cold else ['cold'] + [f'hot{k}' for k in range(1, N + 1)]
seg = {}
metal = {}
cleared = set()
errors = []
togame = {}; ingame = {}
for n in names:
for l in open(f'{R}/{n}.log', errors='replace'):
m = re.match(r'\[dm\] ([⓪①②③④⑤⑥]b?) (.+?)\s{2,}([\d.]+)\s+([\d.]+)', l)
if m: seg.setdefault((m[1], m[2].strip()), {})[n] = (float(m[3]), float(m[4]))
m = re.search(r'METALCACHE 现存 (\d+) 个 (\d+) 字节', l) # 每个目标目录一行,按局加总(只取最后一行会把旧位置的 0 当成全量,热局误报 0)
if m and n not in cleared: f0, b0 = metal.get(n, (0, 0)); metal[n] = (f0 + int(m[1]), b0 + int(m[2]))
m = re.search(r'METALCACHE 已清 (\d+) 个 (\d+) 字节 → 现存 (\d+) 个', l)
if m:
metal[n] = (int(m[1]), int(m[2]))
if int(m[3]) == 0: cleared.add(n)
else: errors.append(f'{n} 清后文件数 {m[3]} 越线(要求 0)')
if metal_cold and 'METALCACHE 【红】' in l: errors.append(f'{n}: {l.strip()}')
m = re.search(r'UIMSG \[([\d.]+)s\] FrontEndNavigation ToGame', l)
if m and n not in togame: togame[n] = float(m[1])
m = re.search(r'UIMSG \[([\d.]+)s\] PanelManager (?:UnloadPanel|ClosePanel) LoadScreenPanel', l)
if m and n in togame and n not in ingame: ingame[n] = float(m[1]) - togame[n]
print('段 | ' + ' | '.join(names) + '(各段用时 s,括号内累计)')
for (k, name), v in seg.items():
print(f'{k} {name} | ' + ' | '.join(f'{v[n][0]:.3f}({v[n][1]:.3f})' if n in v else '—' for n in names))
for n in names:
tot = max((v[n][1] for v in seg.values() if n in v), default=0)
d4 = next((v[n][0] for (k, _), v in seg.items() if k == '④' and n in v), 0); d5 = next((v[n][0] for (k, _), v in seg.items() if k == '⑤' and n in v), 0)
print(f'{n}:到 Ribbon {tot:.3f} s;④ {d4:.3f} s({d4 / tot * 100 if tot else 0:.0f}%)⑤ {d5:.3f} s({d5 / tot * 100 if tot else 0:.0f}%)')
if metal_cold:
for n in names:
present = {k for (k, _), values in seg.items() if n in values}
missing = set('⓪①②③④⑤⑥') - present
if missing: errors.append(f'{n} 缺分段:{"".join(sorted(missing))}')
if n not in metal: errors.append(f'{n} 缺 METALCACHE 读数')
else: print(f'{n} METALCACHE 删前/启动前:{metal[n][0]} 个 {metal[n][1]} 字节')
if n.startswith('cold') and n not in cleared: errors.append(f'{n} 未确认清零')
if n not in ingame: errors.append(f'{n} 缺进局读取读数(ToGame / 读取画面撤下)')
else: print(f'{n} 进局读取(ToGame → 读取画面撤下){ingame[n]:.2f} s')
if errors:
for error in errors: print(f'🔴 {error}', file=sys.stderr)
sys.exit(1)
for kind in ('cold', 'hot'):
group = [n for n in names if n.startswith(kind)]
totals = [max((v[n][1] for v in seg.values() if n in v), default=0) for n in group]
print(f'{kind} 进局读取中位数:{statistics.median([ingame[n] for n in group]):.2f} s')
print(f'{kind} 中位数({len(group)}/{N} 局):总用时 {statistics.median(totals):.3f} s;METALCACHE 删前/启动前 {statistics.median([metal[n][0] for n in group]):g} 个 {statistics.median([metal[n][1] for n in group]):g} 字节')
for (key, label), values in seg.items():
duration = [values[n][0] for n in group if n in values]
cumulative = [values[n][1] for n in group if n in values]
if len(duration) != N:
print(f'🔴 {kind} {key} 分段覆盖 {len(duration)}/{N}', file=sys.stderr); sys.exit(1)
print(f'{kind} {key} {label} 中位数:{statistics.median(duration):.3f}({statistics.median(cumulative):.3f})')
PY
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# 选角页回归(Mac 上的 iOS 包,真实触点路径):四行各「点一次 → 再点两次 → 进入游戏」,核进的是该行的角色、期间没有发 CharacterSelect:SelectCharacter。
# 来由:换成键鼠版选角页后,再点已高亮的行会发「确认选择」、列表收起重开后高亮换了人,「进入游戏」进错角色。
# 认角色用进局后读到的等级:标准存档 save_ref_warlock 里四个角色等级各不相同(列表顺序 joe 76 / Warlock 1 / joebao 9 / 法师 88);换存档要改 WANT。
# 用法:charsel_retap.sh <结果目录>。先跑过 smoke_mac.sh(要有包好的 .iosdd_mac/DmMacSmoke.app)。全过返回 0。
# Character select page regression (iOS app on Mac, real touch point path): for each of the four rows, "tap once → tap twice more → enter game", check that the character entered is that row's and that no CharacterSelect:SelectCharacter was sent in between.
# Background: after switching to the keyboard-and-mouse character select page, tapping an already highlighted row again sends 「确认选择」(confirm selection), the list collapses and reopens with the highlight on someone else, and 「进入游戏」(Play) enters the wrong character.
# Characters are identified by the level read after entering the run: the four characters in the standard save save_ref_warlock all have different levels (list order joe 76 / Warlock 1 / joebao 9 / 「法师」(Mage) 88); change WANT when changing the save.
# Usage: charsel_retap.sh <result dir>. Run smoke_mac.sh first (the packaged .iosdd_mac/DmMacSmoke.app must exist). Returns 0 if all pass.
set -u
OUT=${1:?用法:charsel_retap.sh <结果目录>}; TOOLS=$(cd "$(dirname "$0")" && pwd); mkdir -p "$OUT"; WANT=(76 1 9 88); YS=(47 92 128 165); bad=0
for r in 0 1 2 3; do y=${YS[$r]}
printf '4.0 down 0 803,%s\n4.1 up 0\n5.8 down 0 803,%s\n5.9 up 0\n7.6 down 0 803,%s\n7.7 up 0\n10.0 down 0 478,395\n10.1 up 0\n12.0 down 0 478,163\n12.1 up 0\n' $y $y $y > "$OUT/t$r.txt"
E2E_REF=956x440 E2E_KEYS='B@OpenPanel:NoSuchPanelEver' E2E_ENV='{"DM_TOUCH_SCRIPT_START":"menu","DM_FE_AUTO":"1"}' bash "$TOOLS/touch_e2e_mac.sh" "$OUT/t$r.txt" "$OUT/r$r" 26 > "$OUT/r$r.out" 2>&1
sel=$(LC_ALL=C grep -a -c 'UIMSG.*CharacterSelect SelectCharacter' "$OUT/r$r/boot.txt" 2>/dev/null); lv=$(LC_ALL=C grep -a 'dm_hud' "$OUT/r$r/boot.txt" 2>/dev/null | LC_ALL=C grep -a -o 'Lv [0-9]*' | awk '$2>0{print $2; exit}')
if [ "${sel:-1}" = 0 ] && [ "${lv:-}" = "${WANT[$r]}" ]; then echo "第 $((r+1)) 行 OK:进局等级 ${lv},SelectCharacter 0 条"; else echo "【红】第 $((r+1)) 行:进局等级「${lv:-没进局}」(应为 ${WANT[$r]}),SelectCharacter ${sel:-?} 条"; bad=1; fi
done
[ $bad = 0 ] && echo "CHARSEL-RETAP OK 4/4" || echo "CHARSEL-RETAP RED"; exit $bad
+19
View File
@@ -0,0 +1,19 @@
#!/bin/bash
# 原版衍生物不入库(凡由原版表或图生成的都不进仓库,构建时从玩家自己的游戏文件生成,见 dm/README.md「从你的游戏文件生成资源」):
# ① git 里不许再出现这些生成物(被人手动加回来就红);② 本机有游戏文件时把底部 UI v4 实际生成一遍,跑不通就红(生成链最长的一条)。
# 用法:check_hud_gen.sh 退出 0 = 通过或跳过 ②,1 = 有生成物入库 / 生成失败
# Derivatives of the original game are not checked in (anything generated from the original game's tables or images stays out of the repository and is generated at build time from the player's own game files, see dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files)):
# ① these generated files must not reappear in git (fails if someone manually adds them back); ② when the local machine has game files, actually generate bottom UI v4 once, and fail if that fails (the longest generation chain).
# Usage: check_hud_gen.sh exit 0 = passed or ② skipped, 1 = generated files checked in / generation failed
set -uo pipefail
I="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; W="$(cd "$I/../.." && pwd)"
BAD=$(git -C "$W" ls-files -- dm/ios/NativeHUD/v4 dm/ios/NativeHUD/mapgoal dm/ios/NativeHUD/widestash dm/ios/NativeHUD/pouch dm/ios/NativeHUD/touch/fe_rightpanel.* \
'dm/ios/Sources/TouchArt/dm_native_*' dm/ios/Sources/dm_touch_native_art.c dm/host/dm_vault_tab.h dm/host/dm_hud_exp.h dm/host/dm_bright_levels.inc dm/ios/tools/touchrectv1_HUDPanelHD.json dm/ios/tools/native_art/skills.txt dm/ios/tools/native_art/skilldesc.txt)
[ -z "$BAD" ] || { echo "HUDGEN 红:原版衍生的生成物进了仓库(应该构建时从游戏文件生成):"; echo "$BAD" | sed 's/^/ /'; exit 1; }
R=${DM_ROMFS_SRC:-${DM_ROOT:-$HOME/dm-work}/data/switch/3.3.94012/Update/RomFS}
[ -f "$R/data/build_manifest.psv" ] || { echo "HUDGEN OK(入库检查);生成检查跳过:这台机器没有游戏文件 $R"; exit 0; }
T=$(mktemp -d); trap 'rm -rf "$T"' EXIT
python3 "$I/tools/native_art/generate.py" "$R" > "$T.art.log" 2>&1 || { echo "HUDGEN 红:技能图集生成不通(底栏要用它)"; tail -3 "$T.art.log"; exit 1; } # 底栏的技能图标取自技能图集(Sources/TouchArt,git 忽略);干净的树里没有,先生成 | The bottom bar's skill icons come from the skill atlas (Sources/TouchArt, git-ignored); a clean tree has none, so generate it first
python3 "$I/tools/gen_hud_v4.py" "$R" "$T" > "$T.log" 2>&1 || { echo "HUDGEN 红:gen_hud_v4.py 跑不通"; tail -3 "$T.log"; exit 1; }
n=$(find "$T" -type f | wc -l | tr -d ' '); [ "$n" -ge 79 ] || { echo "HUDGEN 红:底部 UI v4 只生成了 $n 个文件(应 79)"; exit 1; }
echo "HUDGEN OK:生成物没有入库;底部 UI v4 从游戏文件生成 $n 个文件$(grep -q '^没找到 PC' "$T.log" && echo '(Switch 素材放大版)')"
+40
View File
@@ -0,0 +1,40 @@
# 本机起 iOS 包的总闸:不许连真实 iCloud。被 smoke_mac.sh、touch_e2e_mac.sh、uireg/run_mac.sh source。
# 为什么要有:iCloud 同步只按路径认「真存档」(DM_SAVE == Documents/save,cloud_ios.m 的 dm_cloud_boot)。开发机登着真实账号时,
# Mac 上跑的 iOS 包就是那个账号的又一台设备——测试存档换到这个路径、或者测试局改了这个路径下的角色,都会被传进真实云端。
# 做法:每一局都带 DM_TEST_ICLOUD_OFF=1(cloud_ios.m:整个不同步);跑完再核启动日志,出现任何同步动作就报红。
# 不用「指到一次性本地目录」的办法:那会让本来不同步的测试存档开始同步,同一脚本里前一个实例传上去的角色会被后一个空存档实例下载回来。
# cloud_guard_env <Documents 目录> [调用方已带的环境,空格分隔的 K=V]
# 设好 CG_ENV(要加给 open 的那一条 K=V;调用方自己指了本地云端目录——iCloud 用例——时为空)。返回非零 = 这一局不许起(已打印红字)。
# cloud_guard_check <启动日志> 本该不同步的局出现了同步动作 → 返回非零并打印红字
# cloud_guard_clean <Documents 目录> 留给调用方收尾时调(现在没有要清的东西)
# 真要测真实 iCloud:DM_REAL_ICLOUD=1 且 DM_REAL_ICLOUD_CONFIRM=写入真实云端 两个都给才放开,放开时每局打印红字提醒。
# Master gate for launching the iOS app on this Mac: connecting to real iCloud is not allowed. Sourced by smoke_mac.sh, touch_e2e_mac.sh and uireg/run_mac.sh.
# Why it exists: iCloud sync recognizes the "real save" by path only (DM_SAVE == Documents/save, dm_cloud_boot in cloud_ios.m). When the development machine is signed in to a real account,
# the iOS app running on the Mac is one more device of that account -- a test save swapped into this path, or a test run modifying a character under this path, gets uploaded to the real cloud.
# What it does: every run carries DM_TEST_ICLOUD_OFF=1 (cloud_ios.m: no sync at all); after the run the launch log is checked, and any sync action is reported as a failure.
# The "point it at a one-off local directory" approach is not used: that would make test saves that otherwise do not sync start syncing, and a character uploaded by an earlier instance in the same script would be downloaded back by a later empty-save instance.
# cloud_guard_env <Documents directory> [environment the caller already carries, space-separated K=V]
# Sets CG_ENV (the K=V to add to open; empty when the caller specified a local cloud directory itself -- iCloud cases). Non-zero return = this run must not start (red text already printed).
# cloud_guard_check <launch log> a sync action appeared in a run that should not sync → returns non-zero and prints red text
# cloud_guard_clean <Documents directory> for the caller to call at wrap-up (currently there is nothing to clean)
# To really test real iCloud: it is opened up only when both DM_REAL_ICLOUD=1 and DM_REAL_ICLOUD_CONFIRM=写入真实云端 are given, and when opened up a red reminder is printed for every run.
CG_ENV=; CG_REAL=; CG_LOCAL=
cloud_guard_env() {
CG_ENV=; CG_REAL=; CG_LOCAL=
if [ "${DM_REAL_ICLOUD:-}" = 1 ]; then
[ "${DM_REAL_ICLOUD_CONFIRM:-}" = "写入真实云端" ] || { echo "【红】DM_REAL_ICLOUD=1 还要同时给 DM_REAL_ICLOUD_CONFIRM=写入真实云端 才放开;这一局不起" >&2; return 1; }
echo "【红】本局连的是真实 iCloud(DM_REAL_ICLOUD=1):Documents/save 里的改动会同步到这个账号的所有设备" >&2; CG_REAL=1; return 0
fi
case " ${2:-} " in
*" DM_TEST_ICLOUD_SUB="*) echo "【红】DM_TEST_ICLOUD_SUB 走的是真实 iCloud 容器,没有显式放开(DM_REAL_ICLOUD)不许带;这一局不起" >&2; return 1;;
*" DM_TEST_ICLOUD_DIR="*|*" DM_TEST_ICLOUD_ROOT="*) CG_LOCAL=1; return 0;; # 调用方自己指了本地目录(iCloud 用例) | The caller specified a local directory itself (iCloud cases)
esac
CG_ENV="DM_TEST_ICLOUD_OFF=1"
}
cloud_guard_check() {
[ "$CG_REAL" = 1 ] || [ "$CG_LOCAL" = 1 ] && return 0 # 显式放开的、调用方自己指了本地目录的:不核 | Explicitly opened up, or the caller specified a local directory itself: not checked
local bad; bad=$(LC_ALL=C grep -a -E 'iCloud 同步:(启动 |.* 上传(|.* 下载(|.*记删除标记)' "$1" 2>/dev/null | head -1)
[ -z "$bad" ] && return 0
echo "【红】这一局本该不同步,却出现了 iCloud 同步动作:$(echo "$bad" | cut -c1-160)。可能已写进真实云端,立刻停下报告,别再起局" >&2; return 1
}
cloud_guard_clean() { return 0; }
+58
View File
@@ -0,0 +1,58 @@
# 测试机电量闸(测试 iPhone 01:46 没电关机、断到 09:26——插在 Mac 上供电跟不上,屏幕常亮 10 小时电量一路掉到 1%)。
# 用法:source 本文件后 devbattery_gate || exit 1(真机局取设备锁之前调)。读法:ideviceinfo 电池域(USB 不通再走网络 -n)。
# 电量 < 30%:落暂停标记 $DM_ROOT/run/ios/device_low_battery、记【红】、记进 $DM_ROOT/run/ios/device_alert.txt,拒绝开跑(返回 1),之后所有真机局都拒绝;
# 有暂停标记时电量 ≥ 60% 才撤标记放行(充电中途 30%–60% 一律拒绝,免得刚过线又跑没电);
# 插着电却没在充、且电量低于 90% 才记【红】提醒(供电跟不上),但不拦——系统在高电量下会自己停充(全天停在 99–100%、「充电=0」,旧判据「低于 100%」整下午误报);读不到电量记【红】并拒绝(多半设备已离线)。
# 放行时把「电量 N%(充电 / 未充电,电源 有 / 无)」写进 DEVBATTERY_LINE,调用方记进表头 / 日志;每次读数追加到 $DM_ROOT/run/ios/battery.log。
# 测试开关:DEVBATTERY_FAKE="<电量> <充电 0/1> <电源 0/1>" 不读设备,直接用这组数(单测 devbattery_test.sh 用)。
# Battery gate for the test device (the test iPhone ran out of power and shut down at 01:46 and stayed offline until 09:26: power from the Mac it was
# plugged into could not keep up, and with the screen always on for 10 hours the charge fell all the way to 1%).
# Usage: after sourcing this file, devbattery_gate || exit 1 (call it before taking the device lock for a real-device run). How it reads: the
# ideviceinfo battery domain (falls back to network -n if USB is unavailable).
# Charge < 30%: drops the pause marker $DM_ROOT/run/ios/device_low_battery, logs [RED], records it in $DM_ROOT/run/ios/device_alert.txt, and refuses
# to start (returns 1); every real-device run after that is refused too;
# with the pause marker present, the marker is removed and runs are allowed only at charge ≥ 60% (30%–60% in the middle of charging is always refused,
# so a run does not drain the device again right after crossing the line);
# plugged in but not charging, and charge below 90%: only then log [RED] as a warning (power cannot keep up), without blocking. The system stops
# charging by itself at high charge (sitting at 99–100% all day with "charging=0"; the old criterion "below 100%" raised false alarms all afternoon).
# If the charge cannot be read, log [RED] and refuse (most likely the device is offline).
# When a run is allowed, "charge N% (charging / not charging, power present / absent)" is written into DEVBATTERY_LINE for the caller to put in the
# table header / log; every reading is appended to $DM_ROOT/run/ios/battery.log.
# Test switch: DEVBATTERY_FAKE="<charge> <charging 0/1> <power 0/1>" does not read the device and uses these values directly (used by the unit test
# devbattery_test.sh).
DEVBATTERY_LOW=${DEVBATTERY_LOW:-30}; DEVBATTERY_RESUME=${DEVBATTERY_RESUME:-60}
DEVBATTERY_DIR=${DEVBATTERY_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios}
devbattery_read() { # 输出「电量 充电 电源」三个数(0/1),读不到返回 1 | Outputs three numbers "battery level, charging, power source" (0/1); returns 1 if they cannot be read
if [ -n "${DEVBATTERY_FAKE:-}" ]; then echo "$DEVBATTERY_FAKE"; return 0; fi
local u=${DM_IOS_UDID:-} out
[ -n "$u" ] || { source "$(dirname "${BASH_SOURCE[0]}")/local_env.sh" 2>/dev/null; u=${DM_IOS_UDID:-}; } # 调用方没 source 本机配置时自己取 | Fetch it ourselves when the caller has not sourced the local configuration
[ -n "$u" ] || return 2 # 没配 UDID(与「读不到」分开报) | UDID not configured (reported separately from "unreadable")
out=$(timeout 20 ideviceinfo -u "$u" -q com.apple.mobile.battery 2>/dev/null) || out=$(timeout 20 ideviceinfo -n -u "$u" -q com.apple.mobile.battery 2>/dev/null) || return 1
awk '/^BatteryCurrentCapacity:/{p=$2} /^BatteryIsCharging:/{c=($2=="true")} /^ExternalConnected:/{e=($2=="true")} /^FullyCharged:/{f=($2=="true")} END{ if (p=="") exit 1; print p, c+0, e+0, f+0 }' <<<"$out"
}
devbattery_gate() {
mkdir -p "$DEVBATTERY_DIR"; local flag=$DEVBATTERY_DIR/device_low_battery log=$DEVBATTERY_DIR/battery.log r p c e f now; now=$(date '+%m-%d %H:%M:%S')
r=$(devbattery_read); local rc=$?
if [ $rc = 2 ]; then
echo "$now 没配 UDID" >> "$log"; DEVBATTERY_LINE="电量 没配 UDID"
echo "【红】没配测试机 UDID(本机配置 ~/.config/dm-ios/local.env 的 DM_IOS_UDID 为空),读不了电量,这局不跑" >&2; devbattery_notify "没配测试机 UDID,真机局已拒绝"; return 1; fi
if [ $rc != 0 ]; then
echo "$now 读不到" >> "$log"; DEVBATTERY_LINE="电量 读不到"
echo "【红】测试机电量读不到(ideviceinfo 不通,设备多半离线或没电关机),这局不跑" >&2; devbattery_notify "测试机电量读不到,真机局已拒绝"; return 1; fi
read -r p c e f <<<"$r"; f=${f:-0}
DEVBATTERY_LINE="电量 ${p}%($([ "$c" = 1 ] && echo 充电 || echo 未充电),电源 $([ "$e" = 1 ] && echo 有 || echo 无))"
echo "$now $p% 充电=$c 电源=$e 充满=$f" >> "$log"
if [ -f "$flag" ]; then
if [ "$p" -ge "$DEVBATTERY_RESUME" ]; then rm -f "$flag"; echo "测试机电量回到 ${p}%(≥ ${DEVBATTERY_RESUME}%),撤掉暂停标记,真机局放行" >&2
else echo "【红】测试机电量暂停中:现 ${p}%,充到 ${DEVBATTERY_RESUME}% 才放行(标记 $flag:$(head -1 "$flag"))" >&2; return 1; fi
elif [ "$p" -lt "$DEVBATTERY_LOW" ]; then
echo "$now 电量 ${p}% 充电=$c 电源=$e" > "$flag"
echo "【红】测试机电量 ${p}% 低于 ${DEVBATTERY_LOW}%:暂停全部真机局,充到 ${DEVBATTERY_RESUME}% 再放行(标记 $flag)" >&2
devbattery_notify "测试机电量 ${p}%,真机局已暂停,充到 ${DEVBATTERY_RESUME}% 放行"; return 1
fi
[ "$e" = 1 ] && [ "$c" = 0 ] && [ "$f" = 0 ] && [ "$p" -lt "${DEVBATTERY_NOCHARGE:-90}" ] && echo "【红】测试机插着电源却没在充(${p}%):供电跟不上,局照跑,请换充电头 / 线" >&2
return 0
}
devbattery_notify() { # 记进 battery.log 与 device_alert.txt(巡检读这个文件;不用系统通知:osascript 首次会弹权限框) | Record into battery.log and device_alert.txt (the patrol reads this file; system notifications are not used: osascript pops a permission dialog the first time)
echo "$(date '+%m-%d %H:%M:%S') 通知:$1" | tee -a "$DEVBATTERY_DIR/battery.log" >> "$DEVBATTERY_DIR/device_alert.txt"
}
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# devbattery.sh 单测:假读数(DEVBATTERY_FAKE)+ 临时目录,不碰设备。期望值按规则手算:< 30 拒并落标记、标记在时 < 60 拒、≥ 60 撤标记放行、读不到拒
# Unit test for devbattery.sh: fake readings (DEVBATTERY_FAKE) + temporary directory, no device touched. Expected values are computed by hand from the rules: < 30 refuse and drop the marker; with the marker present, < 60 refuse; ≥ 60 remove the marker and pass; unreadable refuse
cd "$(dirname "$0")"; T=$(mktemp -d); export DEVBATTERY_DIR=$T; # 单测一律写临时目录,不碰 $DM_ROOT/run/ios 的真日志与告警 | Unit tests always write to a temporary directory and never touch the real logs and alerts in $DM_ROOT/run/ios
source ./devbattery.sh; bad=0
ck() { local want=$1 got; shift; DEVBATTERY_FAKE="$*" devbattery_gate 2>/dev/null; got=$?; [ "$got" = "$want" ] && echo "通 $* → $got" || { echo "不通 $* → $got(期望 $want)"; bad=1; }; }
ck 0 80 0 1 1 # 80%:放行 | 80%: pass
ck 1 25 1 1 0 # 25%:拒,落标记 | 25%: refuse, drop the marker
[ -f $T/device_low_battery ] && echo "通 低电落标记" || { echo "不通 低电没落标记"; bad=1; }
ck 1 45 1 1 0 # 标记在、45%:拒 | Marker present, 45%: refuse
ck 0 60 1 1 0 # 60%:撤标记放行 | 60%: remove the marker and pass
[ ! -f $T/device_low_battery ] && echo "通 撤标记" || { echo "不通 标记没撤"; bad=1; }
ck 0 45 1 1 0 # 没标记、45%:放行 | No marker, 45%: pass
out=$(DEVBATTERY_FAKE="50 0 1 0" devbattery_gate 2>&1); case "$out" in *供电跟不上*) echo "通 插电不充记红";; *) echo "不通 插电不充没记红"; bad=1;; esac
out=$(DEVBATTERY_FAKE="99 0 1 0" devbattery_gate 2>&1); case "$out" in *供电跟不上*) echo "不通 99% 停充被当成供电跟不上"; bad=1;; *) echo "通 99% 停充不记红";; esac
DEVBATTERY_FAKE= DM_IOS_UDID=00000000-0000000000000000 devbattery_gate 2>/dev/null && { echo "不通 读不到却放行"; bad=1; } || echo "通 读不到拒"
grep -q '读不到' $T/battery.log && echo "通 读不到记「读不到」" || { echo "不通 读不到没记对"; bad=1; }
DEVBATTERY_FAKE= DM_IOS_UDID= DM_LOCAL_ENV=/dev/null HOME=$T devbattery_gate 2>/dev/null && { echo "不通 没配 UDID 却放行"; bad=1; } || echo "通 没配 UDID 拒"
grep -q '没配 UDID' $T/battery.log && echo "通 没配 UDID 记「没配 UDID」" || { echo "不通 没配 UDID 没分开记"; bad=1; }
grep -q 通知 $T/device_alert.txt && echo "通 告警文件有记录" || { echo "不通 告警文件没记录"; bad=1; }
# devlock 接入:device.lock 目录取锁前过闸——电量够直接取到;电量低等满上限退出 4、不取锁
# devlock integration: go through the gate before taking the device.lock directory lock - with enough battery the lock is taken directly; with low battery it waits out the full limit, exits 4 and does not take the lock
L=$T/device.lock; export DEVBATTERY_DIR=$T
DM_DEVBATTERY=1 DEVBATTERY_FAKE="80 0 1 0" DM_DEVLOCK_DIR=$L bash -c 'source ./devlock.sh; devlock_acquire 单测 2>/dev/null; [ -d "$DEVLOCK_DIR" ] && devlock_release' && echo "通 devlock 电量够取到锁" || { echo "不通 devlock 电量够没取到"; bad=1; }
DM_DEVBATTERY=1 DEVBATTERY_FAKE="10 0 1 0" DM_DEVBATTERY_WAIT_S=2 DM_DEVBATTERY_POLL_S=1 DM_DEVLOCK_DIR=$L bash -c 'source ./devlock.sh; devlock_acquire 单测 2>/dev/null; echo 不该走到这' >/dev/null; r=$?
[ $r = 4 ] && [ ! -d $L ] && echo "通 devlock 电量低退出 4 且没取锁" || { echo "不通 devlock 电量低 → $r"; bad=1; }
rm -rf "$T"; [ $bad = 0 ] && echo "devbattery 单测全过" || { echo "devbattery 单测有不通"; exit 1; }
+229
View File
@@ -0,0 +1,229 @@
#!/bin/bash
DEVLOCK_DIR=${DM_DEVLOCK_DIR:-${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock}
DEVLOCK_DEPTH=${DEVLOCK_DEPTH:-0}
DEVLOCK_QUEUE=${DM_DEVLOCK_QUEUE:-${DEVLOCK_DIR%.lock}.queue} # 拿号排队(抢锁无序,后到的可能先拿,曾饿 20 分钟) | Queue with tickets (lock grabbing is unordered; a later arrival may get it first, and one once starved for 20 minutes)
DEVLOCK_TICKET=
# 持锁上限(曾有手写脚本用 devicectl copy from 轮询日志,申报约 100 秒、实占 17 分钟,后面排队的各等 13–15 分钟;以前只要持有者活着就一直等)。
# devlock_acquire <owner> [上限秒],或环境变量 DM_DEVLOCK_MAX_S;都没给时设备锁按类别取缺省:冒烟 / 合入 / 一般真机局 600 秒(冒烟台账 1338 次用时 p99 385 秒),
# 测量(DM_DEVLOCK_CLASS=measure)1200 秒。别的锁目录(mini 的 macsmoke 锁、自测的临时锁)没有缺省、不设上限,显式给了才管。
# 拿到锁后持锁者这一侧起看门狗:超过上限仍持锁 = 记【红】(owner、已持有秒数)→ 向持锁进程及其全部子孙(devicectl、iproxy、sleep…)发 TERM,5 秒后还在的 KILL → 释放锁。
# 只动持锁者自己的进程树(看门狗自己除外),不碰别人。可重入(嵌套 acquire / 子进程沿用 DM_DEVLOCK_HELD)不另起看门狗、不改上限
# Lock hold limit (a hand-written script once polled logs with devicectl copy from, declared about 100 seconds and actually held 17 minutes, and those queued behind each waited 13–15 minutes; previously, as long as the holder was alive everyone just kept waiting).
# devlock_acquire <owner> [limit seconds], or the environment variable DM_DEVLOCK_MAX_S; when neither is given, the device lock takes a default by class: smoke test / merge / ordinary real-device run 600 seconds (p99 duration over 1338 smoke test ledger entries is 385 seconds),
# measurement (DM_DEVLOCK_CLASS=measure) 1200 seconds. Other lock directories (the second Mac's macsmoke lock, temporary locks of self-tests) have no default and no limit; they are enforced only when one is given explicitly.
# After the lock is obtained, a watchdog starts on the holder's side: still holding past the limit = log 【红】(red) (owner, seconds held) → send TERM to the holding process and all its descendants (devicectl, iproxy, sleep...), KILL those still alive after 5 seconds → release the lock.
# Only the holder's own process tree is touched (except the watchdog itself), nobody else's. Reentrant cases (nested acquire / child processes inheriting DM_DEVLOCK_HELD) start no extra watchdog and do not change the limit
DEVLOCK_WD_PID=
DEVLOCK_WD_LOG=${DM_DEVLOCK_WD_LOG:-${DM_ROOT:-$HOME/dm-work}/run/ios/devlock_watchdog.log}
devlock_default_max() {
[ "$DEVLOCK_DIR" = "${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock" ] || { echo 0; return; }
[ "${DM_DEVLOCK_CLASS:-}" = measure ] && echo 1200 || echo 600
}
# 某进程的全部子孙(不含自己),子孙先于祖先列出
# All descendants of a process (excluding itself), descendants listed before ancestors
devlock_descendants() {
local root=$1 kids k
kids=$(ps -axo pid=,ppid= 2>/dev/null | awk -v p="$root" '$2==p{print $1}')
for k in $kids; do devlock_descendants "$k"; echo "$k"; done
}
devlock_watchdog() { # 在后台跑:$1 持锁 pid,$2 其启动时刻,$3 上限秒,$4 owner | Runs in the background: $1 holder pid, $2 its start time, $3 limit in seconds, $4 owner
local holder=$1 lst=$2 max=$3 owner=$4 me=${BASHPID:-$$} now started held victims v
trap '' HUP
while sleep 2; do
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$holder" ] || exit 0 # 已放锁 / 锁被换主 | Lock already released / lock changed owner
[ "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)" = "$lst" ] || exit 0
kill -0 "$holder" 2>/dev/null || exit 0
started=$(cat "$DEVLOCK_DIR/started" 2>/dev/null || echo 0); now=$(date +%s); held=$((now - started))
[ "$held" -ge "$max" ] || continue
local msg="【红】设备锁看门狗:持有者「$owner」(pid $holder)已持有 ${held} 秒,超过上限 ${max} 秒 → 终止持锁进程树、释放锁"
echo "$msg" >&2; mkdir -p "$(dirname "$DEVLOCK_WD_LOG")"; echo "$(date '+%F %T') $msg(锁 $DEVLOCK_DIR)" >> "$DEVLOCK_WD_LOG"
victims=$(devlock_descendants "$holder" | grep -v -x -e "$me" $(devlock_descendants "$me" | sed 's/^/-e /'))
for v in $victims "$holder"; do kill -TERM "$v" 2>/dev/null; done
sleep 5
for v in $victims "$holder"; do kill -0 "$v" 2>/dev/null && kill -KILL "$v" 2>/dev/null; done
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$holder" ] && rm -rf "$DEVLOCK_DIR"
exit 0
done
}
# 取号:<类别>_<到达纳秒>_<pid>,名字按(类别, 到达先后)排序;持号进程已死的号作废。
# 类别(排队超过五分钟都太久):0 = 冒烟 / 合入(缺省),1 = 测量(DM_DEVLOCK_CLASS=measure)。
# 冒烟 / 合入的号排在所有测量号前面,先到先得只在同类内部——任何冒烟最多等正在持锁的那一轮测量(测量单轮持锁 ≤ 4 分钟)。
# 旧版脚本取的号(<到达纳秒>_<pid>,无类别)按字节序落在两类之间,新旧混用期间不乱序。
# Take a ticket: <class>_<arrival nanoseconds>_<pid>; names sort by (class, arrival order); a ticket whose holding process is dead is void.
# Classes (queuing for more than five minutes is too long in any case): 0 = smoke test / merge (default), 1 = measurement (DM_DEVLOCK_CLASS=measure).
# Smoke test / merge tickets rank ahead of all measurement tickets, and first-come-first-served applies only within a class - any smoke test waits at most for the measurement round currently holding the lock (a single measurement round holds the lock ≤ 4 minutes).
# Tickets taken by old scripts (<arrival nanoseconds>_<pid>, no class) fall between the two classes in byte order, so the order is not scrambled while old and new are mixed.
devlock_ticket_take() {
mkdir -p "$DEVLOCK_QUEUE"
local cls=0; [ "${DM_DEVLOCK_CLASS:-}" = measure ] && cls=1
DEVLOCK_TICKET="$DEVLOCK_QUEUE/${cls}_$(python3 -c 'import time;print(time.time_ns())')_$$"
mkdir "$DEVLOCK_TICKET"; printf "%s\n" "${1:-unknown}" > "$DEVLOCK_TICKET/owner"
}
devlock_ticket_drop() { [ -n "$DEVLOCK_TICKET" ] && rm -rf "$DEVLOCK_TICKET"; DEVLOCK_TICKET=; }
# 前面还有几个存活的号(顺手清掉死号);标准输出:个数<TAB>下一个的 owner
# How many live tickets are ahead (dead tickets are cleaned up along the way); stdout: count<TAB>owner of the next one
devlock_ahead() {
local d n=0 first="" mine; mine=$(basename "$DEVLOCK_TICKET")
# 调用处写的是 IFS=$'\t' read … < <(devlock_ahead):那个临时 IFS 会带进本函数,下面的 $(ls) 就不按换行拆——队列里有 ≥2 个号时
# 每个人都把整张队列当成「排在前面的一个号」,全体永远等(曾有四个任务互等 11–20 分钟,锁本身没人持有)。这里钉回缺省。
# The call site is written as IFS=$'\t' read ... < <(devlock_ahead): that temporary IFS carries into this function, so the $(ls) below is not split on newlines - with ≥2 tickets in the queue
# everyone takes the whole queue as "one ticket ahead" and all wait forever (four tasks once waited on each other for 11–20 minutes while nobody held the lock). Pin it back to the default here.
local IFS=$' \t\n'
for d in $(ls "$DEVLOCK_QUEUE" 2>/dev/null | LC_ALL=C sort); do
kill -0 "${d##*_}" 2>/dev/null || { rm -rf "$DEVLOCK_QUEUE/$d"; continue; }
[ "$d" != "$mine" ] || break # 已按字节序排好:排在自己前面的都算(不用 [ \< ],它按区域设置比较) | Already sorted in byte order: everything ranked before our own counts (do not use [ \< ], which compares by locale)
n=$((n + 1)); [ -n "$first" ] || first=$(cat "$DEVLOCK_QUEUE/$d/owner" 2>/dev/null)
done
printf "%s\t%s\n" "$n" "$first"
}
# 进程启动时刻(判锁的持有者还在不在、防 pid 复用)。ps -o lstart 的字符串跟语言环境走:中文环境是「四 10月/ 8 18:51:58 2026」,
# C / 英文环境是「Thu Oct 8 18:51:58 2026」。取锁方与抢锁方环境不同时,活着的持有者永远对不上、被当无主锁拆掉,两边同时用手机
# (两路真机局曾因此撞车)。写入一律 LC_ALL=C;比对时按锁里那条记录的格式取(记录含非 ASCII = 中文环境写的)
# Process start time (to judge whether the lock holder is still there, guards against pid reuse). The ps -o lstart string follows the locale: in a Chinese locale it is 「四 10月/ 8 18:51:58 2026」,
# in a C / English locale it is "Thu Oct 8 18:51:58 2026". When the lock taker and the lock grabber have different locales, a live holder never matches and is torn down as an ownerless lock, and both sides use the phone at once
# (two real-device runs once collided because of this). Writes always use LC_ALL=C; comparison uses the format of the record in the lock (a record containing non-ASCII = written in a Chinese locale)
devlock_lstart() { # $1 pid,$2 参照串(缺省 = C 格式) | $1 pid, $2 reference string (default = C format)
local loc=C; printf %s "${2:-}" | LC_ALL=C grep -q '[^ -~]' && loc=zh_CN.UTF-8
# 进程已不在时 ps 返回非零:这里一律回 0、只打空串——调用方开着 set -e + pipefail(touch_e2e.sh)时,$(devlock_lstart 死pid) 的赋值会让整个脚本当场静默退出,
# 走不到「持有者已死 → 收回锁」那个分支(实例:j 局留下死锁后 k pk sb rf2 pg2 vt1 六局 0 秒退、日志只有电量闸一行)
# ps returns non-zero when the process is gone: here always return 0 and print only an empty string - when the caller has set -e + pipefail (touch_e2e.sh), the assignment $(devlock_lstart <dead pid>) would make the whole script exit silently on the spot,
# never reaching the "holder is dead → reclaim the lock" branch (instance: after run j left a dead lock, the six runs k pk sb rf2 pg2 vt1 exited at 0 seconds with only the battery gate line in the log)
LC_ALL=$loc ps -o lstart= -p "$1" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' || true
}
devlock_is_descendant() {
local child=$1 ancestor=$2 parent depth=0
while [ "$depth" -lt 64 ]; do
[ "$child" = "$ancestor" ] && return 0
parent=$(ps -o ppid= -p "$child" 2>/dev/null | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
[ -n "$parent" ] || return 1
[ "$parent" = "$child" ] && return 1
child=$parent
depth=$((depth + 1))
done
return 1
}
# 取锁必须响亮:里面任何一步意外失败、或走完了锁却不在自己(或可重入的祖先)手里,都打【红】并返回非零——set -e 的调用方随之退出,不许静默退。
# 函数体放在 || 的左边执行,调用方的 set -e 在里面不生效:没开 set -e 的调用方(冒烟、合入)一直是这样跑的,两种调用方从此同一条路径
# Taking the lock must be loud: if any step inside fails unexpectedly, or it finishes with the lock not held by itself (or a reentrant ancestor), print 【红】(red) and return non-zero - a set -e caller then exits; silent exit is not allowed.
# The function body runs on the left side of ||, so the caller's set -e has no effect inside: callers without set -e (smoke test, merge) have always run this way, and from now on both kinds of caller take the same path
devlock_acquire() {
local rc=0; _devlock_acquire "$@" || rc=$?
if [ "$rc" = 0 ] && [ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" != "${DM_DEVLOCK_HELD:-}" ]; then rc=97; fi
[ "$rc" = 0 ] && return 0
echo "【红】设备锁:${1:-unknown} 没取到锁(返回 $rc;锁 $DEVLOCK_DIR 现在的持有者「$(cat "$DEVLOCK_DIR/owner" 2>/dev/null || echo 无)」pid $(cat "$DEVLOCK_DIR/pid" 2>/dev/null || echo 无))" >&2
return "$rc"
}
_devlock_acquire() {
local owner=${1:-unknown} max=${2:-${DM_DEVLOCK_MAX_S:-}} held_lstart pid lock_owner started now held lock_lstart self_lstart lock_pid_lstart current_pid last_notice=0 lock_max over_notice=0
[ -n "$max" ] || max=$(devlock_default_max)
mkdir -p "$(dirname "$DEVLOCK_DIR")" 2>/dev/null && [ -w "$(dirname "$DEVLOCK_DIR")" ] || return 98 # 锁的父目录建不出 / 写不了:下面的抢锁循环会空转,直接报失败 | The lock's parent directory cannot be created / written: the lock-grabbing loop below would spin, so report failure directly
current_pid=${BASHPID:-$$}
self_lstart=$(devlock_lstart $$)
if [ -n "${DM_DEVLOCK_HELD:-}" ] && [ -f "$DEVLOCK_DIR/pid" ] &&
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$DM_DEVLOCK_HELD" ] &&
# 比的是「持锁进程 DM_DEVLOCK_HELD」现在的启动时刻与锁内记录是否一致(防 pid 复用),不是当前进程自己的——
# 比自己的会让持锁者的子进程(启动时刻必然不同)判不可复用、排队等自己的父进程,死锁
# What is compared is whether the current start time of the "lock-holding process DM_DEVLOCK_HELD" matches the record inside the lock (guards against pid reuse), not that of the current process itself -
# comparing its own would make a child of the holder (whose start time necessarily differs) be judged non-reentrant and queue up waiting for its own parent: deadlock
held_lstart=$(devlock_lstart "$DM_DEVLOCK_HELD" "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)") &&
[ -n "$held_lstart" ] &&
[ "$held_lstart" = "$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null)" ] &&
kill -0 "$DM_DEVLOCK_HELD" 2>/dev/null &&
devlock_is_descendant "$current_pid" "$DM_DEVLOCK_HELD"; then
DEVLOCK_DEPTH=$((DEVLOCK_DEPTH + 1))
return 0
fi
# 电量闸:取真机锁 device.lock 前过 devbattery.sh——低于 30% 暂停、充到 60% 放行;拒绝时每分钟重读,
# 一直不放行等满 DM_DEVBATTERY_WAIT_S(缺省 3600)秒就记【红】退出调用脚本(退出码 4)。只管真机锁 $DM_ROOT/run/ios/device.lock(单测的临时锁目录不过闸);DM_DEVBATTERY=0 跳过、=1 强制过闸
# Battery gate: before taking the real-device lock device.lock, go through devbattery.sh - below 30% pause, charged to 60% pass; when refused, re-read every minute,
# and if it never passes after waiting the full DM_DEVBATTERY_WAIT_S (default 3600) seconds, log 【红】(red) and exit the calling script (exit code 4). Applies only to the real-device lock $DM_ROOT/run/ios/device.lock (temporary lock directories of unit tests do not go through the gate); DM_DEVBATTERY=0 skips, =1 forces the gate
if { [ "$DEVLOCK_DIR" = "${DM_ROOT:-$HOME/dm-work}/run/ios/device.lock" ] && [ "${DM_DEVBATTERY:-1}" != 0 ]; } || [ "${DM_DEVBATTERY:-}" = 1 ]; then
source "$(dirname "${BASH_SOURCE[0]}")/devbattery.sh"
local bw0=$SECONDS bwmax=${DM_DEVBATTERY_WAIT_S:-3600}
until devbattery_gate; do
[ $((SECONDS - bw0)) -ge "$bwmax" ] && { echo "【红】电量闸等了 $((SECONDS - bw0)) 秒仍不放行(${DEVBATTERY_LINE:-}),$owner 不取锁、退出" >&2; exit 4; }
sleep "${DM_DEVBATTERY_POLL_S:-60}"
done
echo "电量闸放行:${DEVBATTERY_LINE:-}($owner)" >&2
fi
devlock_ticket_take "$owner"
local ahead first q_notice=0
while :; do
IFS=$'\t' read -r ahead first < <(devlock_ahead)
[ "$ahead" = 0 ] && break
now=$(date +%s); [ $((now - q_notice)) -ge 30 ] && { echo "排队等设备锁:前面还有 $ahead 个(下一个:${first:-?})" >&2; q_notice=$now; }
sleep 1
done
while :; do
# 每次抢锁前重看队列:等锁期间来了更优先的号(冒烟 / 合入排在测量前)就让它先抢
# Re-check the queue before every lock attempt: if a higher-priority ticket arrived while waiting (smoke test / merge rank ahead of measurement), let it grab first
IFS=$'\t' read -r ahead first < <(devlock_ahead)
if [ "$ahead" != 0 ]; then sleep 1; continue; fi
mkdir "$DEVLOCK_DIR" 2>/dev/null && break
pid=$(cat "$DEVLOCK_DIR/pid" 2>/dev/null || true)
lock_owner=$(cat "$DEVLOCK_DIR/owner" 2>/dev/null || echo unknown)
started=$(cat "$DEVLOCK_DIR/started" 2>/dev/null || date +%s)
lock_lstart=$(cat "$DEVLOCK_DIR/lstart" 2>/dev/null || true)
now=$(date +%s)
held=$((now - started))
lock_pid_lstart=$(devlock_lstart "$pid" "$lock_lstart")
# 旧格式锁(只有 pid / owner、没有 lstart 文件,如旧版 ios_smoke.sh 或手写的 mkdir 锁):pid 活着就尊重,不判陈旧
# Old-format lock (only pid / owner, no lstart file, e.g. an old ios_smoke.sh or a hand-written mkdir lock): if the pid is alive, respect it and do not judge it stale
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null && { [ ! -f "$DEVLOCK_DIR/lstart" ] || [ "$lock_pid_lstart" = "$lock_lstart" ]; }; then
lock_max=$(cat "$DEVLOCK_DIR/max" 2>/dev/null || echo 0)
if [ "$last_notice" -eq 0 ] || [ $((now - last_notice)) -ge 30 ]; then
if [ "${lock_max:-0}" -gt 0 ]; then echo "等待设备锁:持有者 ${lock_owner},已持有 ${held} 秒 / 上限 ${lock_max} 秒" >&2
else echo "等待设备锁:持有者 ${lock_owner},已持有 ${held} 秒(未申报上限)" >&2; fi
last_notice=$now
fi
# 超过上限 30 秒还没放(持锁者的看门狗也没管用):记红,但不碰别人的进程
# Still not released 30 seconds past the limit (the holder's watchdog did not work either): log a failure line, but do not touch other people's processes
if [ "${lock_max:-0}" -gt 0 ] && [ "$held" -gt $((lock_max + 30)) ] && [ $((now - over_notice)) -ge 60 ]; then
echo "【红】设备锁:持有者 ${lock_owner}(pid $pid)已持有 ${held} 秒,超过上限 ${lock_max} 秒仍未释放(看门狗没起作用),不代为终止,请找持有者" >&2
mkdir -p "$(dirname "$DEVLOCK_WD_LOG")"; echo "$(date '+%F %T') 等锁方:持有者「${lock_owner}」pid $pid 已持有 ${held} 秒、上限 ${lock_max} 秒仍未释放(锁 $DEVLOCK_DIR)" >> "$DEVLOCK_WD_LOG"
over_notice=$now
fi
sleep 1
elif [ -z "$pid" ] && [ $((now - $(stat -f %m "$DEVLOCK_DIR" 2>/dev/null || echo 0))) -lt 10 ]; then
sleep 1 # 别人刚 mkdir、还没写 pid:正在创建,不是陈旧锁 | Someone else just did mkdir and has not written the pid yet: it is being created, not a stale lock
else
rm -rf "$DEVLOCK_DIR"
fi
done
printf "%s\n" "$$" > "$DEVLOCK_DIR/pid"
printf "%s\n" "$owner" > "$DEVLOCK_DIR/owner"
date +%s > "$DEVLOCK_DIR/started"
printf "%s\n" "$self_lstart" > "$DEVLOCK_DIR/lstart"
printf "%s\n" "${max:-0}" > "$DEVLOCK_DIR/max"
export DM_DEVLOCK_HELD=$$
devlock_ticket_drop
DEVLOCK_DEPTH=1
if [ "${max:-0}" -gt 0 ]; then
devlock_watchdog "$$" "$self_lstart" "$max" "$owner" </dev/null >/dev/null &
DEVLOCK_WD_PID=$!; disown "$DEVLOCK_WD_PID" 2>/dev/null || true
fi
}
devlock_release() {
[ "$DEVLOCK_DEPTH" -gt 0 ] || return 0
if [ "$DEVLOCK_DEPTH" -gt 1 ]; then
DEVLOCK_DEPTH=$((DEVLOCK_DEPTH - 1))
return 0
fi
# 看门狗连同它正在 sleep 的子进程一起收掉(KILL:它的 stdout / stderr 可能连着调用方的管道,拖着不退会让 `… | tail` 多等)
# 先记下它的子进程、先杀看门狗本身再杀子进程:反过来的话看门狗会替被杀的 sleep 打一行「Killed: 9」到调用方的输出里
# 每一步都带 || true:看门狗正好在两次 sleep 之间(没有子进程)时 pgrep 返回 1,set -e 的调用方在 EXIT 钩子里跑到这就当场退出、走不到下面删锁,
# 留下一把持有者已死的锁(j 局出现过;离线复现:持锁 2 秒放锁,退出码 1、锁目录还在)
# Reap the watchdog together with the child it is currently sleeping in (KILL: its stdout / stderr may be attached to the caller's pipe, and lingering would make `... | tail` wait longer)
# Record its children first, then kill the watchdog itself before the children: the other way round, the watchdog would print a line "Killed: 9" for the killed sleep into the caller's output
# Every step carries || true: when the watchdog happens to be between two sleeps (no child), pgrep returns 1, and a set -e caller running this in its EXIT hook would exit on the spot and never reach the lock removal below,
# leaving a lock whose holder is dead (seen in run j; offline reproduction: hold the lock 2 seconds then release, exit code 1, lock directory still there)
if [ -n "$DEVLOCK_WD_PID" ]; then local wk; wk=$(pgrep -P "$DEVLOCK_WD_PID" 2>/dev/null) || true; kill -KILL "$DEVLOCK_WD_PID" 2>/dev/null || true; [ -z "$wk" ] || kill -KILL $wk 2>/dev/null || true; DEVLOCK_WD_PID=; fi
[ "$(cat "$DEVLOCK_DIR/pid" 2>/dev/null)" = "$$" ] || return 0
rm -rf "$DEVLOCK_DIR"
DEVLOCK_DEPTH=0
}
+25
View File
@@ -0,0 +1,25 @@
#!/bin/bash
# devlock.sh 跨语言环境自测(不碰手机):ps -o lstart 的字符串跟语言环境走,持有者与抢锁者环境不同时,活着的持有者不能被当无主锁拆掉。
# 三格:① 中文环境持锁、C 环境来抢 → 等持有者放锁;② 修正前在中文环境写的旧锁(lstart 是中文串)、持有者活着 → 等;③ 持有者已死 → 收回。
# Cross-locale self-test for devlock.sh (does not touch the phone): the ps -o lstart string follows the locale; when holder and grabber have different locales, a live holder must not be torn down as an ownerless lock.
# Three cells: ① Chinese-locale holder, C-locale grabber → wait for the holder to release; ② an old lock written in a Chinese locale before the fix (lstart is a Chinese string), holder alive → wait; ③ holder dead → reclaim.
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue; bad=0
ok(){ echo " ✓ $1"; }; no(){ echo " 🔴 $1"; bad=1; }
# ① 中文环境持锁 4 秒,1 秒后 C 环境来抢:抢到的时刻必须在持有者放锁之后
# ① A Chinese-locale process holds the lock for 4 seconds and a C-locale one comes to grab 1 second later: the moment it gets the lock must be after the holder releases
( unset DM_DEVLOCK_HELD; export LC_ALL=zh_CN.UTF-8; source $H/devlock.sh; devlock_acquire 甲 2>/dev/null; sleep 4; date +%s > $T/a_rel; devlock_release ) &
sleep 1
( unset DM_DEVLOCK_HELD; export LC_ALL=C; source $H/devlock.sh; devlock_acquire 乙 2>/dev/null; date +%s > $T/b_got; devlock_release )
wait; [ "$(cat $T/b_got)" -ge "$(cat $T/a_rel)" ] && ok "① 中文环境持锁时 C 环境的等到放锁才拿到" || no "① C 环境的在中文环境持有者还活着时拿到了锁"
# ② 旧锁:持有者活着、lstart 是中文环境写的串(修正前的写法),C 环境来抢 → 不能拆
# ② Old lock: holder alive, lstart is a string written in a Chinese locale (the pre-fix way), a C-locale process comes to grab → must not be torn down
sleep 30 & P=$!; mkdir -p $DM_DEVLOCK_DIR; echo $P > $DM_DEVLOCK_DIR/pid; echo 旧锁 > $DM_DEVLOCK_DIR/owner; date +%s > $DM_DEVLOCK_DIR/started
LC_ALL=zh_CN.UTF-8 ps -o lstart= -p $P | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' > $DM_DEVLOCK_DIR/lstart
( sleep 3; date +%s > $T/p_kill; kill $P ) &
( unset DM_DEVLOCK_HELD; export LC_ALL=C; source $H/devlock.sh; devlock_acquire 丙 2>/dev/null; date +%s > $T/c_got; devlock_release )
wait; [ "$(cat $T/c_got)" -ge "$(cat $T/p_kill)" ] && ok "② 中文串旧锁的持有者活着时没被拆,死了才收回" || no "② 中文串旧锁在持有者活着时被拆了"
# ③ 持有者已死(pid 不在)→ 立即收回
# ③ Holder is dead (pid gone) → reclaim immediately
mkdir -p $DM_DEVLOCK_DIR; echo 999999 > $DM_DEVLOCK_DIR/pid; echo 死锁 > $DM_DEVLOCK_DIR/owner; echo "Thu Jan 1 00:00:00 2026" > $DM_DEVLOCK_DIR/lstart
t0=$(date +%s); ( unset DM_DEVLOCK_HELD; source $H/devlock.sh; devlock_acquire 丁 2>/dev/null; devlock_release ); [ $(( $(date +%s) - t0 )) -le 3 ] && ok "③ 死持有者的锁 3 秒内收回" || no "③ 死持有者的锁没及时收回"
rm -rf $T; [ $bad = 0 ] && echo "devlock_locale_test 通过 3/3" || { echo "🔴 devlock_locale_test 有不过的"; exit 1; }
+46
View File
@@ -0,0 +1,46 @@
#!/bin/bash
export DM_DEVBATTERY=0 DEVBATTERY_DIR=$(mktemp -d) # 锁单测不过电量闸、不写真电量日志(一次挂住的锁单测往真告警文件写了 18 条「读不到」) | Lock unit tests do not go through the battery gate and do not write the real battery log (a hung lock unit test once wrote 18 「读不到」(unreadable) entries into the real alert file)
# devlock.sh 持锁上限自测(不碰手机,用临时锁目录):
# 1. 故意不放锁的持锁者(上限 6 秒,里面挂 sleep 子孙)→ 到点被自己的看门狗终止、子孙清干净、锁释放;排在后面的号随后拿到锁
# 2. 正常持锁 3 秒就放(上限 6 秒)→ 不被终止,看门狗随之退出
# 3. 嵌套 acquire(同进程两层 + 子进程沿用)→ 不另起看门狗、不误杀,上限到点前放锁
# Lock hold limit self-test for devlock.sh (does not touch the phone, uses a temporary lock directory):
# 1. A holder that deliberately does not release (limit 6 seconds, with sleep descendants hanging inside) → terminated on time by its own watchdog, descendants cleaned up, lock released; the ticket queued behind then gets the lock
# 2. A normal hold released after 3 seconds (limit 6 seconds) → not terminated, and the watchdog exits along with it
# 3. Nested acquire (two levels in the same process + inherited by a child process) → no extra watchdog, no wrongful kill, lock released before the limit is reached
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue DM_DEVLOCK_WD_LOG=$T/wd.log
fail=0; ok(){ echo " 通:$*"; }; bad(){ echo " 🔴 不通:$*"; fail=1; }
echo "1. 不放锁的持锁者"
# 持锁者用独立的 bash 进程(devlock 按 $$ 认持锁者:子 shell 的 $$ 是外层脚本,那样看门狗会把整个自测连根终止)
# The holder uses a separate bash process (devlock identifies the holder by $$: a subshell's $$ is the outer script, in which case the watchdog would terminate the whole self-test, root and all)
bash -c 'source $0/devlock.sh; devlock_acquire 赖着不走 6; sleep 300 & echo $! > $1/kid; sleep 300; echo 不该走到这 > $1/h1.reach' $H $T 2>>$T/h1.err & H1=$!
sleep 1; bash -c 'unset DM_DEVLOCK_HELD; source $0/devlock.sh; t0=$(date +%s); devlock_acquire 后面排队的 2>>$1/w.err; echo $(( $(date +%s) - t0 )) > $1/wait; devlock_release' $H $T & W=$!
wait $W; waited=$(cat $T/wait); sleep 1
kill -0 $H1 2>/dev/null && bad "持锁者没被终止" || ok "持锁者被终止"
kill -0 "$(cat $T/kid)" 2>/dev/null && { bad "子孙 sleep 还活着"; kill "$(cat $T/kid)"; } || ok "子孙清干净"
[ ! -e $T/h1.reach ] && ok "持锁者没继续往下跑" || bad "持锁者继续往下跑了"
[ "$waited" -ge 4 ] && [ "$waited" -le 10 ] && ok "后面的号等了 ${waited} 秒(上限 6 秒)就拿到锁" || bad "后面的号等了 ${waited} 秒"
grep -q '【红】设备锁看门狗:持有者「赖着不走」' $T/h1.err && grep -q '已持有' $T/wd.log && ok "记了红:$(head -1 $T/wd.log | cut -c1-80)…" || bad "没记红"
grep -q '上限 6 秒' $T/w.err && ok "等锁方提示带上限:$(grep -m1 上限 $T/w.err)" || bad "等锁方提示没有上限:$(cat $T/w.err)"
[ ! -d $DM_DEVLOCK_DIR ] && ok "锁目录已清" || bad "锁目录还在"
echo "2. 正常持锁 3 秒"
bash -c 'source $0/devlock.sh; devlock_acquire 正常 6 2>/dev/null; sleep 3; devlock_release; sleep 6; echo 活着 > $1/h2.alive' $H $T; [ -e $T/h2.alive ] && ok "放锁后进程照常走完,没被杀" || bad "被误杀"
echo "3. 嵌套"
bash -c 'source $0/devlock.sh; devlock_acquire 外层 8 2>/dev/null; devlock_acquire 内层 2 2>/dev/null; bash -c "source $0/devlock.sh; devlock_acquire 子进程 2 2>/dev/null; sleep 4; devlock_release"; sleep 2; devlock_release; devlock_release; echo 走完 > $1/h3.done' $H $T
[ -e $T/h3.done ] && ok "嵌套 6 秒(内层上限 2 秒不生效,外层 8 秒)没被误杀" || bad "嵌套被误杀"
[ ! -d $DM_DEVLOCK_DIR ] && ok "锁已释放" || bad "锁没释放"
echo "4. set -e 的调用方(touch_e2e.sh 的写法):持锁几秒后靠 EXIT 钩子放锁,锁必须放掉"
for hold in 0 1 2 3; do
bash -c 'set -euo pipefail; source $0/devlock.sh; devlock_acquire "钩子放锁 $2" 60 2>/dev/null; trap devlock_release EXIT; sleep $2' $H $T $hold; rc=$?
[ $rc = 0 ] && [ ! -d $DM_DEVLOCK_DIR ] && ok "持锁 $hold 秒:退出码 0、锁已放" || { bad "持锁 $hold 秒:退出码 $rc、锁目录$([ -d $DM_DEVLOCK_DIR ] && echo 还在 || echo 已放)"; rm -rf $DM_DEVLOCK_DIR; }
done
echo "5. 持有者已死的锁:set -e 的后来者要收回并拿到"
mkdir $DM_DEVLOCK_DIR; echo 999999 > $DM_DEVLOCK_DIR/pid; echo 死掉的持有者 > $DM_DEVLOCK_DIR/owner; date +%s > $DM_DEVLOCK_DIR/started; echo "Sun Oct 11 01:06:01 2026" > $DM_DEVLOCK_DIR/lstart; echo 600 > $DM_DEVLOCK_DIR/max
bash -c 'set -euo pipefail; unset DM_DEVLOCK_HELD; source $0/devlock.sh; devlock_acquire 后来者 60 2>$1/s5.err; trap devlock_release EXIT; cat $DM_DEVLOCK_DIR/owner > $1/s5.owner' $H $T; rc=$?
[ $rc = 0 ] && [ "$(cat $T/s5.owner 2>/dev/null)" = 后来者 ] && ok "死锁被收回,后来者拿到锁" || bad "退出码 $rc,锁内 owner「$(cat $DM_DEVLOCK_DIR/owner 2>/dev/null)」,输出:$(cat $T/s5.err)"
[ ! -d $DM_DEVLOCK_DIR ] && ok "后来者退出后锁已放" || { bad "后来者退出后锁还在"; rm -rf $DM_DEVLOCK_DIR; }
echo "6. 取不到锁要响亮:锁目录建不出来(父目录是个文件)→ 打【红】+ 非零退出"
: > $T/notdir; DM_DEVLOCK_DIR=$T/notdir/device.lock DM_DEVLOCK_QUEUE=$T/q6 bash -c 'set -euo pipefail; unset DM_DEVLOCK_HELD; source $0/devlock.sh; devlock_acquire 取不到的 5 2>$1/s6.err; echo 不该走到这 > $1/s6.reach' $H $T & P6=$!
( sleep 8; kill -KILL $P6 2>/dev/null ) & K6=$!; wait $P6 2>/dev/null; rc=$?; kill $K6 2>/dev/null
[ $rc != 0 ] && [ $rc != 137 ] && grep -q '【红】设备锁:取不到的 没取到锁' $T/s6.err && [ ! -e $T/s6.reach ] && ok "退出码 $rc:$(grep -m1 【红】 $T/s6.err | cut -c1-60)…" || bad "退出码 $rc(137 = 挂住被本测试杀掉),输出:$(head -2 $T/s6.err)"
rm -rf $T; [ $fail = 0 ] && echo "devlock_max_test 通过" || { echo "🔴 devlock_max_test 有不通"; exit 1; }
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash
export DM_DEVBATTERY=0 DEVBATTERY_DIR=$(mktemp -d) # 锁单测不过电量闸、不写真电量日志(一次挂住的锁单测往真告警文件写了 18 条「读不到」) | Lock unit tests do not go through the battery gate and do not write the real battery log (a hung lock unit test once wrote 18 「读不到」(unreadable) entries into the real alert file)
# devlock.sh 排队次序自测(不碰手机):持锁者在跑时,先到的测量号、后到的冒烟号、再后到的旧版无类别号——放锁后的拿锁次序应为 冒烟 → 旧版 → 测量。
# Queue-order self-test for devlock.sh (does not touch the phone): while a holder is running, a measurement ticket arrives first, then a smoke test ticket, then an old-style classless ticket - after release the lock should be obtained in the order smoke test → old-style → measurement.
set -u; H=$(cd "$(dirname "$0")" && pwd); T=$(mktemp -d); export DM_DEVLOCK_DIR=$T/device.lock DM_DEVLOCK_QUEUE=$T/device.queue
w(){ ( unset DM_DEVLOCK_HELD; [ "$2" = measure ] && export DM_DEVLOCK_CLASS=measure; source $H/devlock.sh; devlock_acquire "$1" 2>/dev/null; echo "$1" >> $T/order; sleep 0.3; devlock_release ) & }
( source $H/devlock.sh; devlock_acquire 持锁者 2>/dev/null; sleep 4; devlock_release ) &
sleep 1; w 测量 measure; sleep 0.5; w 冒烟 smoke; sleep 0.5
( mkdir -p $DM_DEVLOCK_QUEUE; sleep 30 & P=$!; K=$DM_DEVLOCK_QUEUE/$(python3 -c 'import time;print(time.time_ns())')_$P; mkdir $K; echo 旧版 > $K/owner
until [ "$(ls $DM_DEVLOCK_QUEUE | LC_ALL=C sort | head -1 | sed 's/.*_//')" = $P ] && [ ! -d $DM_DEVLOCK_DIR ]; do sleep 0.1; done; echo 旧版 >> $T/order; kill $P; rm -rf $DM_DEVLOCK_QUEUE/*_$P ) &
wait; got=$(tr '\n' ' ' < $T/order); rm -rf $T
[ "$got" = "冒烟 旧版 测量 " ] && echo "devlock_test 通过:$got" || { echo "🔴 devlock_test 次序不对:期望「冒烟 旧版 测量」,实际「$got」"; exit 1; }
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""我们自己加的界面文字的中英表(英文版):唯一来源 dm/i18n/ui_text.tsv(键 / 中文 / English / 用在哪)。
做法 = 把每一行作为新条目追加进原版字符串表 ui.json(RomFS 覆盖层,与 touch_strings 同一套机制):zhCN / zhTW 列 = 中文(繁体玩家读简体比读英文顺),其余 11 种语言列 = English。
这样布局里写「@键」、宿主用原版取串 main+0x7f5630 取,语言切换由原版自己重装字符串表完成(SetLanguage,r34 起不剪),不用我们另跟语言。
Chinese-English string table for the UI text we added ourselves (English version): single source dm/i18n/ui_text.tsv (key / Chinese / English / where used).
Approach = append each row as a new entry to the original string table ui.json (RomFS overlay, same mechanism as touch_strings): zhCN / zhTW columns = Chinese (Traditional Chinese players read Simplified more easily than English), the other 11 language columns = English.
This way layouts write "@key", the host fetches through the original string lookup at main+0x7f5630, and language switching is done by the original game reloading its string tables itself (SetLanguage, no longer patched out as of r34), so we do not have to follow the language separately."""
import csv, json, os, re
HERE = os.path.dirname(os.path.abspath(__file__))
TABLE = os.path.join(HERE, '..', '..', 'i18n', 'ui_text.tsv')
LANGS = ('enUS', 'zhTW', 'deDE', 'esES', 'frFR', 'itIT', 'koKR', 'plPL', 'esMX', 'jaJP', 'ptBR', 'ruRU', 'zhCN') # 原版条目的列序 | column order of the original entries
ID0 = 300000 # 原版全部字符串表最大 id 251780;我们的条目从这里起按表序编号 | the largest id across all original string tables is 251780; our entries are numbered from here in table order
PROPER = '老机型补充包|D2R Mobile Resources|D2R Mobile' # 英文里唯一许可的中文:App 显示名与资源文件夹名(玩家在桌面 /「文件」里看到的就是这几个字,改名另案,见盘点待定 6、7) | the only Chinese allowed in English text: the App display name and the asset folder name (these are the very characters the player sees on the home screen / in "Files"; renaming is a separate matter, see open items 6 and 7 of the inventory)
FMT = re.compile(r'%[-+ #0-9.]*(?:ll|l|h|z)?[a-zA-Z@%]') # printf / strftime / NSString 占位符:中英两列必须同序同类(运行时拿英文串当格式串用) | printf / strftime / NSString placeholders: the Chinese and English columns must match in order and type (at run time the English string is used as a format string)
# 英文字数闸(进行中页「This Rift will be lost」被截断出框,靠人眼看图没拦住):大秘境面板 / 秘境提示各栏的英文上限(字符数,占位符按 3 个字符算)。
# 数是按 Mac 截图量出来的每栏像素宽 ÷ 该栏字号下英文每字符平均宽度、再留一个字符余量——是按字数的近似,不是按字形逐个量宽;
# 全是窄字母(i、l、1)的串实际更短,全是宽字母(M、W)的会更长,所以新词进表后仍要出图看一眼
# English length gate (on the in-progress page "This Rift will be lost" was truncated and ran out of its box, and looking at screenshots by eye did not
# catch it): English limits for each field of the Greater Rift panel / Rift messages (in characters, with a placeholder counted as 3 characters).
# The numbers are each field's pixel width measured from Mac screenshots ÷ the average English character width at that field's font size, less one
# character of margin. This is an approximation by character count, not a glyph-by-glyph width measurement;
# a string made of narrow letters only (i, l, 1) is actually shorter and one made of wide letters only (M, W) is longer, so new wording added to the
# table still needs a look at a screenshot
EN_LIMITS = (
(r'dmRiftSay(?!Prefix).*', 31),
(r'dmRiftPtsGot', 62), (r'dmRiftPtsHeld', 33), # 通关点数两句:第一句中文就占两行(提示框自动换行),英文同样两行、不缩写;第二句一行 # 系统提示:前缀「Rift 」6 个字符 + 正文,提示框一行约 37 个字符 | the two clear-points sentences: the first already takes two lines in Chinese (the message box wraps automatically), so English is likewise two lines, unabbreviated; the second is one line # system messages: the prefix "Rift " is 6 characters plus the body, and one message box line holds about 37 characters
(r'dmRift(Range|Best|Str|Lvl|Time)', 13), # 左栏「标签 + 值」的标签(英文专用小字号控件,值最长 7 个字符) | labels of the left column's "label + value" rows (English-only small-font widget; values are at most 7 characters)
(r'dmRiftGam(Uni|Set)', 8), (r'dmRiftGamAfterEn', 17),
(r'dmRift(SelT|InfT|GamT|TitleRun|TitleDone|TitleLate)', 16), # 左栏小标题(中号字,栏宽约 160 像素) | left column small headings (medium font, column about 160 pixels wide)
(r'dmRift(GuardDown|NextOpen|Saved|RetryOpen|NotCounted)', 16), # 已完成页那三行(整行,中号字) | the three lines on the completed page (full lines, medium font)
(r'dmRiftCap.*', 20), # 按钮上方的说明(英文专用小字号控件) | caption above the buttons (English-only small-font widget)
(r'dmRiftBtn.*', 12), # 按钮上的字 | text on the buttons
(r'dmRiftMsItem\d+', 15), (r'dmRiftMsSub\d+', 19), (r'dmRiftMsTier\d+', 4), (r'dmRiftMs(Got|Next|No)', 7), (r'dmRiftMsT', 12), (r'dmRiftMsNEn', 38),
(r'dmRiftHud(Title)', 4), (r'dmRiftHud(Done|Late|Guard)', 18), (r'dmRiftHud(Next|Same|Kill|Goal)', 26),
(r'dmKbRiftUnlock', 9), (r'dmKbRift(Best|Total)', 16),
)
# 键只许字母数字:布局里「@键」的解析遇到 _ 就断(@dmCustom_auto_mana 显示成「丢失字符串_auto_mana」,Mac 上的 iOS 包实测)
# Keys may contain only letters and digits: parsing of "@key" in layouts stops at _ (@dmCustom_auto_mana is displayed as "<missing string>_auto_mana",
# measured on the iOS app on Mac)
def rows():
out = []
with open(TABLE, encoding='utf-8') as f:
for r in csv.DictReader(f, delimiter='\t'):
k, zh, en = r['键'], r['中文'].replace('\\n', '\n'), r['English'].replace('\\n', '\n')
if not re.fullmatch(r'dm[A-Za-z0-9]+', k) or not zh or not en: raise SystemExit('dm_i18n:表里这一行不对:%r' % r)
if re.search(r'[ -鿿＀-￯]', re.sub(PROPER, '', en)): raise SystemExit('dm_i18n:%s 的英文里有中文字符:%r' % (k, en))
if FMT.findall(zh) != FMT.findall(en): raise SystemExit('dm_i18n:%s 的中英占位符不一致:%s / %s' % (k, FMT.findall(zh), FMT.findall(en)))
lim = next((n for pat, n in EN_LIMITS if re.fullmatch(pat, k)), None) # 英文字数闸(见 EN_LIMITS) | English length gate (see EN_LIMITS)
if lim is not None and len(FMT.sub('000', en).split('\n')[0]) > lim: raise SystemExit('dm_i18n:%s 的英文「%s」%d 个字符,超过这一栏的上限 %d(会顶框 / 被截断;压短,或给这一栏做英文专用的小字号控件后再改上限)' % (k, en, len(FMT.sub('000', en)), lim))
out.append((k, zh, en))
ks = [k for k, _, _ in out]
if len(set(ks)) != len(ks): raise SystemExit('dm_i18n:键重复:%s' % sorted({k for k in ks if ks.count(k) > 1}))
return out
def build(romfs, outdir, repl):
"""repl:前面步骤已换的 {包内逻辑路径: 本地文件}。返回 ({包内逻辑路径: 本地文件}, 条数)。 | repl: {logical path in the package: local file} already replaced by earlier steps. Returns ({logical path in the package: local file}, entry count)."""
import touch_layout # 用时再导:touch_layout 自己在模块层要读本表(自定义页行数),顶层互导会半初始化 | imported at use time: touch_layout itself reads this table at module level (row count of the Custom page), and a top-level mutual import would leave it half-initialized
path, text = touch_layout.read_layout(romfs, None, suffix='/lng/strings/ui.json')
prev = repl.get(path.lower())
if prev: text = open(prev, encoding='utf-8-sig').read()
have = set(re.findall(r'"Key":\s*"((?:[^"\\]|\\.)*)"', text))
rs = rows()
clash = [k for k, _, _ in rs if k in have]
if clash: raise SystemExit('dm_i18n:键和原版重名:%s' % clash)
add = [{'id': ID0 + i, 'Key': k, **{l: (zh if l in ('zhCN', 'zhTW') else en) for l in LANGS}} for i, (k, zh, en) in enumerate(rs)]
end = text.rstrip().rindex(']')
body = ',\n'.join(' ' + json.dumps(e, ensure_ascii=False) for e in add)
text = text[:end].rstrip() + ',\n' + body + '\n' + text[end:]
json.loads(text) # 拼完还是合法 JSON | still valid JSON after assembly
o = os.path.join(outdir, 'i18n_ui.json'); open(o, 'w', encoding='utf-8-sig', newline='').write(text)
return {path.lower(): o}, len(add)
def header():
"""dm/host/dm_i18n_tab.h 的内容(游戏外画的字用的编译期表)。 | Contents of dm/host/dm_i18n_tab.h (the compile-time table for text drawn outside the game)."""
c = lambda s: json.dumps(s, ensure_ascii=False) # JSON 串的转义在 C 里同样成立(\n \" \\) | JSON string escapes are equally valid in C (newline, double quote, backslash)
out = ['// 生成文件,勿手改:python3 dm/ios/tools/dm_i18n.py --header > dm/host/dm_i18n_tab.h(表 dm/i18n/ui_text.tsv)', '#pragma once',
'static const struct { const char *k, *zh, *en; } k_dm_i18n[] = {']
out += [' { %s, %s, %s },' % (c(k), c(zh), c(en)) for k, zh, en in rows()]
return '\n'.join(out + ['};', ''])
if __name__ == '__main__':
import sys
if sys.argv[1:] == ['--header']: sys.stdout.write(header())
elif sys.argv[1:] == ['--check']: # 单测:表与入库的头文件一致 | unit test: the table matches the checked-in header file
h = os.path.join(HERE, '..', '..', 'host', 'dm_i18n_tab.h')
if open(h, encoding='utf-8').read() != header(): raise SystemExit('dm_i18n:dm/host/dm_i18n_tab.h 过期,重跑 python3 dm/ios/tools/dm_i18n.py --header > dm/host/dm_i18n_tab.h')
print('dm_i18n OK %d 条' % len(rows()))
else: raise SystemExit('用法:dm_i18n.py --header | --check')
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
# 高价值掉落的光(第二批):覆盖层里给物品的「地面模型定义」json 出两档带光变体,
# 由宿主在「地上物品取模型路径」那一刻按规则改指过去(dm/host/dm_dropfilter.c,剪口 svc #0x87 落在 main+0x8fa590)。
# 变体常驻覆盖层(不进开关组合份数):开关、档位、筛选都由宿主运行时决定,没被改指的变体游戏不会去读。
# 变体 = 原模型定义 + 一个原版特效实体:一档 = 原版赫拉迪克光(白色竖光柱),二档 = 原版迪亚波罗光柱(橙色斜光束)。
# 不加贴图、不加着色器、不放大模型、不加爆闪 / 头顶感叹号。路径:data/hd/items/<类别>/zswg/<档>__<模型名,/ 换成 __>.json(新增路径,casc_overlay「+」)。
# 覆盖哪些模型:items.json / uniques.json / sets.json 指向的、在武器 / 盔甲两类下的全部模型(暗金 / 套装可以是任何底材),
# 加上杂项里会发光的几类(符文、戒指、项链、护身符、钥匙、任务道具)。原版表里指向包里不存在模型的条目跳过(宿主改指前不核存在性:
# 那些条目原本就画不出来)。
# Light on high-value drops (second batch): in the overlay, produce two tiers of lit variants of the items' "ground model definition" json,
# and the host redirects to them by rule at the moment of "ground item fetches its model path" (dm/host/dm_dropfilter.c, cut svc #0x87 lands at main+0x8fa590).
# Variants live permanently in the overlay (not counted in the number of switch-combination copies): switch, tier and filter are all decided by the host at run time, and the game never reads a variant that is not redirected to.
# Variant = original model definition + one effect entity from the original game: tier 1 = the original game's Horadric light (white vertical light shaft), tier 2 = the original game's Diablo light shaft (orange slanted beam).
# No textures added, no shaders added, no model enlargement, no flash burst / overhead exclamation mark. Path: data/hd/items/<category>/zswg/<tier>__<model name, / replaced by __>.json (new path, casc_overlay "+").
# Which models are covered: all models pointed to by items.json / uniques.json / sets.json under the weapon / armor categories (uniques / sets can be any base),
# plus the few glowing kinds among misc (runes, rings, amulets, charms, keys, quest items). Entries in the original tables that point to models missing from the package are skipped (the host does not check existence before redirecting:
# those entries could not be drawn in the first place).
import hashlib, json, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import touch_layout
GLOW = 'data/hd/vfx/particles/overlays/object/horadric_light/fx_horadric_light.particles' # 一档 | Tier 1
SHAFT = 'data/hd/vfx/particles/missiles/diablo_light_shaft/fx_diablo_light_shaft.particles' # 二档 | Tier 2
TIERS = {'1': GLOW, '2': SHAFT}
ROOTS = ('weapon', 'armor', 'misc')
MISC_LIT = ('rune/', 'ring/', 'amulet/', 'charm/', 'key/', 'quest/')
def add_light(text, fx, name):
"""地面模型定义 → 挂上特效的新文本。实体 id 由文件名定(同一输入同一输出)。 | Ground model definition → new text with the effect attached. The entity id is determined by the file name (same input, same output)."""
d = json.loads(text); assert d.get('type') == 'UnitDefinition', name
deps = d['dependencies'].setdefault('particles', [])
if not any(p.get('path', '').lower() == fx for p in deps): deps.append({'path': fx})
eid = int.from_bytes(hashlib.md5(('droplight:' + name).encode()).digest()[:4], 'little') | 1
d['entities'].append({'type': 'Entity', 'name': 'droplight', 'id': eid, 'components': [
{'type': 'TransformDefinitionComponent', 'name': 'component_transform_droplight', 'position': {'x': 0.0, 'y': 0.0, 'z': 0.0},
'orientation': {'x': 0.0, 'y': 0.0, 'z': 0.0, 'w': 1.0}, 'scale': {'x': 1.0, 'y': 1.0, 'z': 1.0}, 'inheritOnlyPosition': False},
{'type': 'VfxDefinitionComponent', 'name': 'component_vfx_droplight', 'filename': fx, 'hardKillOnDestroy': False}]})
return json.dumps(d, separators=(',', ':'))
def variant_path(root, asset, tier):
"""宿主改写规则的离线一份(两边必须一致):data/hd/items/<root>/<asset>.json → data/hd/items/<root>/zswg/<tier>__<asset 里 / 换 __>.json | Offline copy of the host's rewrite rule (the two sides must match): data/hd/items/<root>/<asset>.json → data/hd/items/<root>/zswg/<tier>__<asset with / replaced by __>.json"""
return f'data/hd/items/{root}/zswg/{tier}__' + asset.lower().replace('/', '__') + '.json'
def build(romfs, outdir, repl):
"""返回 ({逻辑路径: 文件}(新增路径带「+」前缀), 统计)。repl 里已有同一原模型时在那份上叠加。 | Returns ({logical path: file} (new paths carry a "+" prefix), statistics). If repl already has the same original model, layer on top of that copy."""
manifest = set()
for line in open(os.path.join(romfs, 'data', 'build_manifest.psv'), encoding='utf-8'):
f = line.rstrip('\n').split('|')
if len(f) >= 11 and not line.startswith('#'): manifest.add(f[9].split(':', 1)[-1].lower())
assets = set()
for table in ('items.json', 'uniques.json', 'sets.json'):
for row in json.loads(touch_layout.read_layout(romfs, None, suffix='/hd/items/' + table)[1]):
(_, v), = row.items()
assets.update(x.lower() for x in ([v['asset']] if 'asset' in v else [v[k] for k in ('normal', 'uber', 'ultra')]))
out, skipped = {}, 0
for asset in sorted(assets):
root = next((r for r in ROOTS if f'data/hd/items/{r}/{asset}.json' in manifest), None)
if root is None: skipped += 1; continue
if root == 'misc' and not asset.startswith(MISC_LIT): continue
src = f'data/hd/items/{root}/{asset}.json'
text = open(repl[src], encoding='utf-8').read() if src in repl else touch_layout.read_layout(romfs, None, suffix='/' + src.split('/', 1)[1])[1]
for tier, fx in TIERS.items():
dst = variant_path(root, asset, tier)
o = os.path.join(outdir, 'droplight_' + dst.replace('/', '_')); open(o, 'w').write(add_light(text, fx, dst)); out['+' + dst] = o
return out, f'掉落光变体:{len(out) // 2} 个模型 × 2 档(原表指向不存在模型、跳过 {skipped} 个)'
if __name__ == '__main__': # 试验:drop_light.py <RomFS> <输出目录> → 只含本模块改动的 repl.tsv(casc_overlay.py 直接吃) | Trial: drop_light.py <RomFS> <output dir> → a repl.tsv containing only this module's changes (consumed directly by casc_overlay.py)
romfs, out = sys.argv[1:3]; os.makedirs(out, exist_ok=True)
r, stat = build(romfs, out, {})
with open(os.path.join(out, 'repl.tsv'), 'w') as f:
for k, v in r.items(): f.write(f'{k}\t{v}\n')
print(stat)
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
# 「重场面」触点脚本:亡者大殿二层(第二幕,区域号 57,levels.txt 怪物密度最高一档 2200,Lv76 角色 joe 的存档自带这个小站)。真机 touch_e2e.sh / Mac touch_e2e_mac.sh 通用。
# 用法:gen_heavy.py <总秒数> [到达后开始秒=17] > 脚本.txt,配套环境见同目录 heavy.env.sh(小站回放 + 键序传送 + 起局人数档 8)。
# 动作:先推摇杆离开小站(站在小站上按攻击键是「再开小站页」),之后摇杆每 4 秒左右换向来回走(边走边拉怪),攻击键每 0.5 秒点一下。
# 证据:perf.txt 场景列「区域57」、e2e_state.jsonl 的怪物表计数、boot.txt 的「每帧绘制」。
# "Heavy scene" touch point script: Halls of the Dead Level 2 (Act 2, area number 57, the highest monster density tier 2200 in levels.txt, the save of the Lv76 character joe already has this waypoint). Works for both real device touch_e2e.sh / Mac touch_e2e_mac.sh.
# Usage: gen_heavy.py <total seconds> [start second after arrival=17] > script.txt, the matching environment is in heavy.env.sh in the same directory (waypoint replay + key-sequence teleport + run-start /players setting 8).
# Actions: first push the stick to leave the waypoint (pressing the attack key while standing on the waypoint is "open the waypoint page again"), after that the stick changes direction about every 4 seconds, walking back and forth (pulling monsters while walking), and the attack key is tapped every 0.5 seconds.
# Evidence: 「区域57」(area 57) in the scene column of perf.txt, the monster table count in e2e_state.jsonl, 「每帧绘制」(draws per frame) in boot.txt.
import sys
total = float(sys.argv[1]); t0 = float(sys.argv[2]) if len(sys.argv) > 2 else 17.0
ev = [(t0, "down 0 @joy"), (t0 + 0.1, "move 0 @joy+40,0")]
t = t0 + 2.0; left = True
while t < total - 1.0:
ev.append((t, f"move 0 @joy+{-40 if left else 40},0")); left = not left; t += 4.0
ev.append((total - 0.5, "up 0"))
t = t0 + 2.2
while t < total - 1.0:
ev.append((t, "down 1 @main")); ev.append((t + 0.15, "up 1")); t += 0.5
for t, s in sorted(ev, key=lambda e: e[0]): print(f"{t:.2f} {s}")
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
# 生成「进野外后向左走 + 连续攻击」的触点脚本(真机 touch_e2e.sh / Mac touch_e2e_mac.sh 通用,只用 @名字 目标,不依赖屏幕尺寸)。
# 用法:gen_wild.py <总秒数> [起始秒=18] > 脚本.txt;配 PREFIX=<wild_prefix_original_warlock>/c2s.jsonl(前缀回放约 16 s 把角色带到营地门外、区域 2 鲜血荒地)。
# 摇杆(触点 0)全程向左推满;攻击键(触点 1)每 0.6 秒点一下(按 0.15 秒)。证据:perf.txt 场景列的区域号 / 坐标在变,dm_hud 行的经验 ‰ 在涨。
# 出处:在 Mac 上试出的走法(进鲜血荒地打到沉沦魔,经验 0 → 108‰)。
# Generates the touch point script for "walk left after entering the wilderness + continuous attack" (works for both real device touch_e2e.sh / Mac touch_e2e_mac.sh, uses only @name targets, independent of screen size).
# Usage: gen_wild.py <total seconds> [start second=18] > script.txt; pair with PREFIX=<wild_prefix_original_warlock>/c2s.jsonl (the prefix replay takes about 16 s to bring the character outside the camp gate, area 2 Blood Moor).
# The stick (touch point 0) is pushed fully left the whole time; the attack key (touch point 1) is tapped every 0.6 seconds (held 0.15 seconds). Evidence: the area number / coordinates in the scene column of perf.txt are changing, and the experience ‰ on the dm_hud line is rising.
# Source: a route worked out by trial on Mac (entering the Blood Moor and fighting Fallen, experience 0 → 108‰).
import sys
total = float(sys.argv[1]); t0 = float(sys.argv[2]) if len(sys.argv) > 2 else 18.0
print(f"{t0:.2f} down 0 @joy"); print(f"{t0 + 0.1:.2f} move 0 @joy+-40,0")
t = t0 + 0.5
while t < total - 1.0:
print(f"{t:.2f} down 1 @main"); print(f"{t + 0.15:.2f} up 1"); t += 0.6
print(f"{total - 0.5:.2f} up 0")
+5
View File
@@ -0,0 +1,5 @@
# 重场面起局环境(source 后再调 touch_e2e.sh / touch_e2e_mac.sh):小站回放把 joe 带到营地小站 → 拍 135 开小站页 → ZR 切第二幕 → 下 ×3 → A 传到亡者大殿二层;起局人数档 8(怪更耐打,场面不会越打越轻)
# Heavy scene run-start environment (source it, then call touch_e2e.sh / touch_e2e_mac.sh): the waypoint replay brings joe to the camp waypoint → at tick 135 open the waypoint page → ZR switches to Act 2 → down ×3 → A teleports to Halls of the Dead Level 2; run-start /players setting 8 (monsters take more hits, so the scene does not get lighter as the fight goes on)
export PREFIX=${DM_ROOT:-$HOME/dm-work}/data/switch/truth_runs/wp1/c2s_to_E.jsonl
export E2E_KEYS='X@OpenPanel:MainMenuButtonRibbon>OpenPanel:CharacterSelectPanel,MSG:CharacterSelect:LoadCharacter:0@OpenPanel:CharacterSelectPanel%1>FrontEndNavigation:ToGame,A@DM:Tick:135#>OpenPanel:WaypointsPanelExpansion,ZR@OpenPanel:WaypointsPanelExpansion%1,DOWN@%0.5,DOWN@%0.5,DOWN@%0.5,A@%0.6'
export E2E_ENV='{"DM_FIXED_TIME":"1790000000","DM_PLAYERS":"8"}'
+50
View File
@@ -0,0 +1,50 @@
# 帧对拍:iPhone 截帧 vs Mac 截帧,遮罩外逐位全等才算过。
# 遮罩 = Mac 自身两次运行有差异的区域(按墙钟推进的动画等非确定区,自动取)∪ --rect 给的固定矩形。
# 自动区按 16×16 块取:块内有任一自身差异像素即整块遮掉,再外扩 1 块——动画区里两次 Mac 碰巧相同的像素
# 照样随机变(实测逐像素遮罩漏掉 365 个),所以遮的是区域不是像素。
# 用法:frame_cmp.py <mac_a.png> <mac_b.png> <ios.png> [--rect x0,y0,x1,y1 ...] [--mask-out mask.png]
# 退出码 0 = 遮罩外全等;1 = 有差(打印差异区)。整块动画区两次 Mac 恰好全同时会漏遮 → 报红而不是放过。
# Frame comparison: iPhone captured frame vs Mac captured frame; passes only if bit-identical outside the mask.
# Mask = regions that differ between two runs of Mac itself (non-deterministic regions such as wall-clock-driven animation, taken automatically) ∪ fixed rectangles given by --rect.
# The automatic region is taken in 16×16 tiles: a tile with any self-difference pixel is masked entirely, then grown by 1 tile - pixels inside an animated region that happened to match between the two Mac runs
# still vary randomly (measured: a per-pixel mask missed 365), so what is masked is regions, not pixels.
# Usage: frame_cmp.py <mac_a.png> <mac_b.png> <ios.png> [--rect x0,y0,x1,y1 ...] [--mask-out mask.png]
# Exit code 0 = identical outside the mask; 1 = differences (prints the differing regions). If an entire animated region happens to be fully identical between the two Mac runs it will be under-masked → reports a failure rather than letting it through.
import argparse, sys
import numpy as np
from PIL import Image
ap = argparse.ArgumentParser()
ap.add_argument('mac_a'); ap.add_argument('mac_b'); ap.add_argument('ios')
ap.add_argument('--rect', action='append', default=[], help='x0,y0,x1,y1(含端点)')
ap.add_argument('--mask-out')
o = ap.parse_args()
paths, mask_out = (o.mac_a, o.mac_b, o.ios), o.mask_out
rects = [tuple(map(int, r.split(','))) for r in o.rect]
a, b, c = (np.asarray(Image.open(p).convert('RGBA')).astype(np.int16) for p in paths)
if not (a.shape == b.shape == c.shape): sys.exit(f'【红】尺寸不一:{a.shape} {b.shape} {c.shape}')
H, W = a.shape[:2]
T = 16
self_px = np.abs(a - b).max(axis=2) > 0 # Mac 自身非确定像素 | Mac's own non-deterministic pixels
th, tw = (H + T - 1) // T, (W + T - 1) // T
tiles = np.zeros((th, tw), bool)
ys, xs = np.nonzero(self_px); tiles[ys // T, xs // T] = True
grown = tiles.copy() # 外扩 1 块 | Grow by 1 tile
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
grown |= np.pad(tiles, 1)[1 + dy:1 + dy + th, 1 + dx:1 + dx + tw]
mask = np.kron(grown, np.ones((T, T), bool))[:H, :W]
auto_n = int(mask.sum())
for x0, y0, x1, y1 in rects: mask[y0:y1 + 1, x0:x1 + 1] = True
diff = np.abs(c - a).max(axis=2)
bad = (diff > 0) & ~mask
inside = int(((diff > 0) & mask).sum())
print(f'尺寸 {W}×{H};Mac 自身差异 {int(self_px.sum())} 像素 → 自动遮罩 {int(grown.sum())} 块 {auto_n} 像素;矩形 {len(rects)} 个;遮罩合计占 {mask.sum() / mask.size:.2%}')
if not self_px.any(): print('【警告】Mac 两次无自身差异:按墙钟变化的区域没暴露出来,遮罩可能不全,下方的红可能是误报')
print(f'遮罩外:比对 {int((~mask).sum())} 像素,不同 {int(bad.sum())};遮罩内不同 {inside}(不计)')
if mask_out: Image.fromarray((mask * 255).astype(np.uint8)).save(mask_out)
if bad.any():
ys, xs = np.nonzero(bad)
print(f'【红】遮罩外有差:x {xs.min()}–{xs.max()} y {ys.min()}–{ys.max()},最大分量差 {int(diff[bad].max())}')
sys.exit(1)
print('全过:遮罩外逐位全等')
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# 真机 vs Mac 第 N 帧逐像素对拍(每次 main 更新后跑):Mac 截两次(取自身非确定区作遮罩)→ 真机截一次 → frame_cmp.py。
# 用法:dm/ios/tools/frame_cmp.sh [帧号=300] [--rect x0,y0,x1,y1 ...] 产物与日志在 $DM_ROOT/run/ios/cmp/(每次清空重来)
# 退出码 0 = 遮罩外逐位全等且屏幕级三项全过。宽屏产物对拍:DM_GAME_RES=宽x高 让 Mac 按同分辨率出图(front_mac.m)。Mac 截到图即停该进程(按自记 pid);真机按看门狗 DM_WATCH 收尾。
# 帧号与时间:两端出图节拍同为 60 Hz、游戏出图间隔 2(约 30 帧/秒,窗口与无窗口一致),第 N 帧约在 N/30 秒;
# 缺省 300(约 10 秒)落在选角页稳态(r5 起打开即选角,约 2.4 秒到主菜单)。
# Per-pixel comparison of frame N, real device vs Mac (run after every main update): Mac captures twice (its own non-deterministic regions become the mask) → the real device captures once → frame_cmp.py.
# Usage: dm/ios/tools/frame_cmp.sh [frame=300] [--rect x0,y0,x1,y1 ...] Build output and logs are in $DM_ROOT/run/ios/cmp/ (cleared and redone every time)
# Exit code 0 = bit-identical outside the mask and all three screen-level checks pass. Widescreen build output comparison: DM_GAME_RES=WxH makes Mac output frames at the same resolution (front_mac.m). The Mac process is stopped as soon as its image is captured (by the self-recorded pid); the real device is wound up by the watchdog DM_WATCH.
# Frame number and time: both ends present frames at a 60 Hz cadence with a game present interval of 2 (about 30 frames/second, the same with and without a window), so frame N is at about N/30 seconds;
# the default 300 (about 10 seconds) lands in the steady state of the character select page (since r5 it opens straight to character select, about 2.4 seconds to the main menu).
set -u
cd "$(dirname "$0")/.."
N=300; case "${1:-}" in [0-9]*) N=$1; shift ;; esac
OUT=${DM_OUT:-${DM_ROOT:-$HOME/dm-work}/build/cache/dm/out/3.3.94012-r10}
C=${DM_ROOT:-$HOME/dm-work}/run/ios/cmp; rm -rf "$C"; mkdir -p "$C"
source tools/local_env.sh && local_env_need DM_DEVICE || exit 1 # 本机设备配置(不进仓,见 dm/ios/local.env.example) | Local device configuration (not committed, see dm/ios/local.env.example)
D=$DM_DEVICE; B=${DM_BUNDLE_ID:?先在本机配置里设 DM_BUNDLE_ID(App 包名,见 dm/ios/local.env.example)}
SAVE_REF=${DM_ROOT:-$HOME/dm-work}/data/switch/save_ref/0000000000000001/0 # 标准存档:每局拷新副本(两端起始状态一致) | Standard save: a fresh copy per run (same starting state on both ends)
t(){ echo "[$(date +%T)] $*"; }
# 前置:真机 RomFS 完整(46 个文件)。缺了游戏会在 nnMain 早退,症状只是「没截到帧」,在这里直接报根因
# Precondition: the real device's RomFS is complete (46 files). If any is missing the game exits early in nnMain and the only symptom is "no frame captured"; report the root cause directly here
xcrun devicectl device info files --device $D --domain-type appDataContainer --domain-identifier $B --subdirectory Documents/romfs/data --json-output "$C/romfs_ls.json" > /dev/null 2>&1
nf=$(python3 -c "import json; d=json.load(open('$C/romfs_ls.json')); print(sum(not f['resources']['isDirectory'] for f in d['result']['files']))" 2>/dev/null)
[ "${nf:-0}" = 46 ] || { t "🔴 真机 Documents/romfs/data 文件数 ${nf:-0} ≠ 46:RomFS 不全,先推送(见 dm/ios/README.md 推送一节)"; exit 1; }
make -s -C ../host || { t "🔴 Mac 宿主编译失败"; exit 1; }
# Mac 两次:第二次压到后台 QoS(能效核)跑慢,使到第 N 帧时墙钟不同,按墙钟推进的动画才会在两次间露出差异
# (两次全速连跑到第 300 帧同为 1–3 秒,动画相位相同、自身差异 0;慢跑 3/3 次露出约 6,600 像素)
# Mac twice: the second run is pushed to background QoS (efficiency cores) to run slow, so the wall clock at frame N differs and wall-clock-driven animation shows differences between the two runs
# (two back-to-back full-speed runs both reach frame 300 in 1–3 seconds, with the same animation phase and 0 self-difference; the slow run exposed about 6,600 pixels in 3/3 tries)
for k in a b; do
POL=""; [ $k = b ] && POL="taskpolicy -c background"
rm -rf "$C/save_$k"; cp -R "$SAVE_REF" "$C/save_$k" && chmod -R u+w "$C/save_$k" || { t "🔴 拷标准存档失败"; exit 1; }
DM_SAVE="$C/save_$k" DM_NVN_SHOT="$N:$C/mac_$k.png" DM_WATCH=120 $POL ../host/dmhost "$OUT" main sdk > "$C/mac_$k.log" 2>&1 & pid=$!
s=$SECONDS
until grep -q "截图.*$C/mac_$k.png" "$C/mac_$k.log" 2>/dev/null; do
kill -0 $pid 2>/dev/null || { t "🔴 Mac 第 $k 次在截到第 $N 帧前退出"; tail -3 "$C/mac_$k.log"; exit 1; }
[ $((SECONDS - s)) -gt 120 ] && { kill $pid; t "🔴 Mac 第 $k 次 120 秒未到第 $N 帧"; exit 1; }
sleep 1
done
kill $pid 2>/dev/null; wait $pid 2>/dev/null
t "Mac 第 $k 次截到($((SECONDS - s)) 秒)"
done
./run.sh build > "$C/ios_build.log" 2>&1 || { t "🔴 真机构建失败"; tail -5 "$C/ios_build.log"; exit 1; }
./run.sh install >> "$C/ios_build.log" 2>&1 || { t "🔴 真机装机失败"; tail -5 "$C/ios_build.log"; exit 1; }
# 真机存档:App 自己把 Documents/save 换成资源里的 save_ref 新副本(DM_SAVE_FRESH)。勿用 devicectl --remove-existing-content:它会清掉整个 Documents
# Real-device save: the App itself replaces Documents/save with a fresh copy of save_ref from its resources (DM_SAVE_FRESH). Do not use devicectl --remove-existing-content: it wipes the entire Documents
DEVICECTL_CHILD_DM_SAVE_FRESH=1 DEVICECTL_CHILD_DM_NVN_SHOT="$N:cmp_$N.png" DEVICECTL_CHILD_DM_SCREEN_SHOT="$((N / 30 + 3)):screen.png" DEVICECTL_CHILD_DM_WATCH=${DM_IOS_WATCH:-45} ./run.sh boot 120 > "$C/ios_run.log" 2>&1
cp "${DM_ROOT:-$HOME/dm-work}/run/ios/out/boot.txt" "$C/ios.log" 2>/dev/null
grep -q "截图.*cmp_$N.png 成功" "$C/ios.log" || { t "🔴 真机没截到第 $N 帧(看 $C/ios.log;可加大 DM_IOS_WATCH)"; exit 1; }
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B \
--source "Documents/cmp_$N.png" --destination "$C/ios.png" > /dev/null 2>&1 || { t "🔴 拉回真机截图失败"; exit 1; }
t "真机截到并拉回"
# 屏幕级截图(整个窗口:方向、黑边、实际显示):在第 N 帧之后约 3 秒截;三项自动核见 screen_check.py(DM_SCREEN_WANT=full | 16:9,缺省 full)
# Screen-level screenshot (the whole window: orientation, black bars, what is actually displayed): taken about 3 seconds after frame N; for the three automatic checks see screen_check.py (DM_SCREEN_WANT=full | 16:9, default full)
for f in screen.png screen.png.txt; do
xcrun devicectl device copy from --device $D --domain-type appDataContainer --domain-identifier $B --source "Documents/$f" --destination "$C/$f" > /dev/null 2>&1 || { t "🔴 拉回屏幕级截图 $f 失败"; exit 1; }
done
python3 tools/screen_check.py "$C/screen.png" "$C/screen.png.txt" "$C/ios.log" --want "${DM_SCREEN_WANT:-full}"; SC=$?
python3 tools/frame_cmp.py "$C/mac_a.png" "$C/mac_b.png" "$C/ios.png" --mask-out "$C/mask.png" "$@"; FC=$?
exit $(( FC || SC ))
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
# iOS 全屏验收(屏幕级截图):② 不拉伸、④ 游戏输出分辨率 = 前端给的值;①(铺满无黑边)见 screen_check.py --want full。
# 全屏不留安全区(界面按游戏原样铺满,不为灵动岛 / 圆角往里收)→ ③ 只出参考数据与叠线图,不判红。
# 用法:fullscreen_check.py <页 sel|cls|game> <screen.png> <screen.png.txt> <boot.log> [16:9 负对照屏幕截图.png]
# ② 不拉伸:(a) 出图横纵缩放差(闭式,三页);(b) 局内页 HUD 中段对 16:9 负对照截图的横纵缩放比(图像);均 ≤ 1%
# ③(参考,不判):选角页左侧菜单面板左缘对安全区左边距;三页都出叠了安全区框线的图 <screen>_安全区.png
# ④ 日志「前端给游戏的输出分辨率 主机 WxH」== 「WindowInitialize 交换链 … 首张 WxH」
# iOS full-screen acceptance (screen-level screenshots): ② no stretching, ④ game output resolution = the value given by the front end; for ① (fills the screen with no black bars) see screen_check.py --want full.
# Full screen keeps no safe area (the UI fills the screen exactly as the game draws it, not inset for the Dynamic Island / rounded corners) → ③ only produces reference data and an overlaid-line image, and never fails anything.
# Usage: fullscreen_check.py <page sel|cls|game> <screen.png> <screen.png.txt> <boot.log> [16:9 negative-control screenshot.png]
# ② No stretching: (a) difference between horizontal and vertical output scale (closed form, three pages); (b) on the in-run page, horizontal/vertical scale ratio of the HUD middle section against the 16:9 negative-control screenshot (image); both ≤ 1%
# ③ (reference, not judged): left edge of the left menu panel on the character select page versus the safe-area left margin; all three pages produce an image with the safe-area frame lines overlaid, <screen>_安全区.png
# ④ Log 「前端给游戏的输出分辨率 主机 WxH」(output resolution the front end gives the game, console WxH) == 「WindowInitialize 交换链 … 首张 WxH」(WindowInitialize swapchain ... first image WxH)
import sys, re
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage
page, png, meta, log = sys.argv[1:5]; ref = sys.argv[5] if len(sys.argv) > 5 else None # ref = 16:9 负对照的屏幕截图(同页) | ref = screenshot of the 16:9 negative control (same page)
img = np.asarray(Image.open(png).convert('RGB')).astype(int); H, W = img.shape[:2]
M = {l.split('\t')[0]: l.split('\t')[1:] for l in open(meta).read().splitlines() if '\t' in l}
scale = float(M['scale'][0]); top, left, bottom, right = (float(x) * scale for x in M['safe_pt']) # 像素 | Pixels
L = open(log, errors='replace').read(); bad = 0
def res(ok, msg):
global bad; print(('过 ' if ok else '【红】') + msg); bad += not ok
def ed(a): return np.abs(np.diff(a, axis=1))[:-1, :] + np.abs(np.diff(a, axis=0))[:, :-1]
# ② 不拉伸,两道:(a) 闭式:游戏画面 WxH 对出图视口的横纵缩放之差(日志「出图视口 … (游戏画面 WxH)」);
# (b) 图像:16:9 负对照屏幕截图(DM_GAME_RES=1600x900,同页同高度)的 HUD 中段作模板,在本截图上搜横 / 纵缩放,横纵比差 ≤ 1%。
# (HUD 球不用:底部被 HUD 框遮住、液面与动画干扰,真值上也量不出正圆;人为横拉 2% 时本法测得 1.0226)
# ② No stretching, two checks: (a) closed form: the difference between the horizontal and vertical scale of the game picture WxH to the output viewport (log 「出图视口 … (游戏画面 WxH)」(output viewport ... (game picture WxH)));
# (b) image: use the middle section of the HUD from the 16:9 negative-control screenshot (DM_GAME_RES=1600x900, same page, same height) as a template and search for the horizontal / vertical scale on this screenshot; aspect difference ≤ 1%.
# (the HUD orbs are not used: the bottom is covered by the HUD frame, the liquid surface and animation interfere, and even on ground truth a perfect circle cannot be measured; with an artificial 2% horizontal stretch this method measured 1.0226)
vp = re.findall(r'出图视口 (\d+),(\d+) (\d+)x(\d+) / 画布 \d+x\d+(游戏画面 (\d+)x(\d+))', L)
if vp:
_, _, vw, vh, gw, gh = map(int, vp[-1]); d = (vw / gw) / (vh / gh) - 1
res(abs(d) <= 0.01, f'② (a) 出图横纵缩放:{vw}/{gw} 对 {vh}/{gh},横纵比差 {d * 100:+.2f}%(判据 ≤ 1%)')
else: res(False, '② (a) 日志里没有「出图视口」行')
if page == 'game' and ref:
F = np.asarray(Image.open(png).convert('L')).astype(float); N = np.asarray(Image.open(ref).convert('L')).astype(float); Hn, Wn = N.shape
tpl = N[int(Hn * 0.87):Hn, Wn // 2 - 420:Wn // 2 + 420]; best = (-1,)
for sx in np.arange(0.985, 1.0151, 0.0025):
for sy in np.arange(0.985, 1.0151, 0.0025):
t = np.asarray(Image.fromarray(tpl).resize((int(round(tpl.shape[1] * sx)), int(round(tpl.shape[0] * sy))), Image.BILINEAR)).astype(float)
te = ed(t); te = (te - te.mean()) / (te.std() + 1e-9); th, tw = te.shape
for dy in range(-6, 7, 2):
for dx in range(-12, 13, 2):
yy, xx = H - th - 1 + dy, W // 2 - tw // 2 + dx
if yy < 0 or yy + th + 1 > H: continue
f = ed(F[yy:yy + th + 1, xx:xx + tw + 1]); f = (f - f.mean()) / (f.std() + 1e-9); c = float((f * te).mean())
if c > best[0]: best = (c, sx, sy)
c, sx, sy = best
res(c > 0.8 and abs(sx / sy - 1) <= 0.01, f'② (b) HUD 中段对 16:9 负对照:横 {sx:.4f} 纵 {sy:.4f},横纵比差 {(sx / sy - 1) * 100:+.2f}%(相关 {c:.3f},步长 0.25%,判据 ≤ 1%)')
elif page == 'game': print(' ② (b) 没给 16:9 负对照截图,跳过图像核对')
# ③
if page == 'sel':
lum = img.mean(axis=2); sat = img.max(axis=2) - img.min(axis=2)
band = (lum > 95) & (sat < 40); band[: int(H * 0.1)] = False; band[int(H * 0.9):] = False
frac = band.mean(axis=0); cols = np.nonzero(frac[: W // 3] > 0.35)[0]
if cols.size: print(f' ③(参考)左侧菜单左缘 x={cols[0]} px({cols[0] / scale:.1f} pt),安全区左边距 {left:.0f} px({left / scale:.1f} pt)')
else: print(' ③(参考)没找到左侧菜单面板')
o = Image.open(png).convert('RGB'); d = ImageDraw.Draw(o)
d.rectangle((left, top, W - 1 - right, H - 1 - bottom), outline=(255, 0, 255), width=4); o.save(png.replace('.png', '_安全区.png'))
print(f' ③ 安全区(像素)上 {top:.0f} 左 {left:.0f} 下 {bottom:.0f} 右 {right:.0f};叠线图 {png.replace(".png", "_安全区.png")}')
# ④
f = re.search(r'前端给游戏的输出分辨率 主机 (\d+)x(\d+)', L); w = re.search(r'WindowInitialize 交换链 \d+ 张 间隔 \d+ 首张 (\d+)x(\d+)', L)
res(bool(f and w and f.groups() == w.groups()), f'④ 前端给 {f.groups() if f else "?"},游戏交换链 {w.groups() if w else "?"}')
sys.exit(1 if bad else 0)
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""从玩家自己的游戏文件生成 App 用的原版衍生资源(仓库里不放原版的图和字,见 dm/README.md「从你的游戏文件生成资源」)。run.sh build 先跑这里。
输入:Switch 版 3.3.94012 的 Update/RomFS(参数或环境变量 DM_ROMFS_SRC);可选 PC 版 D2R 的解包目录(DM_PC_DATA,底栏出原版 2 倍图用,没有就用 Switch 素材放大)。
产物(不进 git):
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} 加宽储藏箱 / 编年史盖板 / 百宝囊框 / 选角右侧面板 / 小地图终点 / 底部 UI v4
Sources/TouchArt/dm_native_*.png、Sources/dm_touch_native_art.c 原版技能图集与技能索引(生成在原位置,dm/ios/.gitignore 忽略)
宿主的三张表(dm_vault_tab.h、dm_hud_exp.h、dm_bright_levels.inc)由 dm/host/Makefile 生成。
用法:gen_assets.py [<原版 RomFS(Update)>]
输入没变就不重出(指纹 = 游戏文件清单 + dm/ios/tools 下全部文件 + PC 素材开关;写在产物根目录 .stamp);同一棵树里同时只许一个进程在生成(锁目录 .gen_lock)——
accept 里 iOS 构建与功能用例并行,后者读产物、前者原先每次重写产物,读到一半被删过(base.png 找不到)。gen_romfs_overlay.py 开头也调 ensure()。
Generate the assets derived from the original game that the App uses, from the player's own game files (the repository holds none of the original game's images or text, see dm/README.md 「从你的游戏文件生成资源」(Generate assets from your game files)). run.sh build runs this first.
Input: Update/RomFS of Switch version 3.3.94012 (argument or environment variable DM_ROMFS_SRC); optionally the unpacked directory of PC D2R (DM_PC_DATA, used to produce the original game's 2x art for the bottom bar; without it, Switch art is upscaled).
Build output (not in git):
Gen/assets/NativeHUD/{widestash, pouch, touch, mapgoal, v4} widened stash / chronicle cover plate / pouch frame / character select right panel / minimap goal / bottom UI v4
Sources/TouchArt/dm_native_*.png, Sources/dm_touch_native_art.c the original game's skill atlas and skill index (generated in place, ignored by dm/ios/.gitignore)
The host's three tables (dm_vault_tab.h, dm_hud_exp.h, dm_bright_levels.inc) are generated by dm/host/Makefile.
Usage: gen_assets.py [<original game RomFS (Update)>]
Nothing is regenerated when the input is unchanged (fingerprint = game file list + all files under dm/ios/tools + the PC art switch; written to .stamp in the build output root); only one process may generate at a time in the same tree (lock directory .gen_lock) --
in accept the iOS build and the functional cases run in parallel; the latter read the build output while the former used to rewrite it every time, and files were deleted mid-read (base.png not found). The start of gen_romfs_overlay.py also calls ensure()."""
import hashlib, os, shutil, subprocess, sys, time
import gen_paths
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work') # 工作区根目录(游戏文件、产物、运行现场都在它下面) | Workspace root (game files, build outputs and run artifacts are all under it)
HERE = os.path.dirname(os.path.abspath(__file__))
STEPS = [('加宽储藏箱', ['gen_widestash_art.py', '{R}']), ('编年史盖板', ['gen_vault_cover.py']), ('百宝囊框', ['gen_pouch_art.py', '{R}']),
('选角右侧面板', ['gen_fe_rightpanel.py', '{R}']), ('小地图终点', ['gen_map_goal_art.py', '{R}']), ('佣兵面板底图', ['gen_merc_art.py', '{R}']),
('技能图集与索引', ['native_art/generate.py', '{R}']), ('底部 UI v4', ['gen_hud_v4.py', '{R}'])]
def stamp(R):
h = hashlib.sha256(open(os.path.join(R, 'data', 'build_manifest.psv'), 'rb').read())
for d, ds, fs in sorted(os.walk(HERE)):
ds[:] = sorted(x for x in ds if x != '__pycache__')
for f in sorted(fs): h.update(os.path.relpath(os.path.join(d, f), HERE).encode()); h.update(open(os.path.join(d, f), 'rb').read())
pc = os.environ.get('DM_PC_DATA') or os.path.join(DM_ROOT, 'data/assets-src/raw')
h.update(('%s|%s|%s' % (pc, os.path.isdir(pc), os.environ.get('DM_REQUIRE_PC_ART', ''))).encode())
return h.hexdigest()
def ensure(R):
"""产物齐、指纹没变就直接返回;否则拿锁生成。返回 True = 这次重出了。 | If the build output is complete and the fingerprint unchanged, return directly; otherwise take the lock and generate. Returns True = regenerated this time."""
root = gen_paths.gen_dir(); st = os.path.join(root, '.stamp'); lock = os.path.join(root, '.gen_lock')
outs = [os.path.join(root, 'NativeHUD', 'v4', 'base.png'), os.path.join(HERE, '..', 'Sources', 'TouchArt', 'dm_native_skill_0.png'), os.path.join(HERE, '..', 'Sources', 'dm_touch_native_art.c')]
want = stamp(R); fresh = lambda: all(map(os.path.isfile, outs)) and os.path.isfile(st) and open(st).read() == want
if fresh(): return False
t0 = time.time()
while True:
try: os.mkdir(lock); break
except FileExistsError:
try: pid = int(open(os.path.join(lock, 'pid')).read())
except (OSError, ValueError): pid = 0
if pid:
try: os.kill(pid, 0)
except ProcessLookupError: shutil.rmtree(lock, ignore_errors=True); continue # 持锁进程已经不在:接管 | The lock-holding process is gone: take over
if time.time() - t0 > 600: sys.exit('🔴 gen_assets:等别的进程生成等了 10 分钟(锁 %s,pid %s)' % (lock, pid))
time.sleep(0.5)
try:
open(os.path.join(lock, 'pid'), 'w').write(str(os.getpid()))
if fresh(): return False # 等锁期间别人已经生成好了 | Someone else already generated it while we waited for the lock
if os.path.exists(st): os.remove(st)
run_steps(R); open(st, 'w').write(want); return True
finally: shutil.rmtree(lock, ignore_errors=True)
def run_steps(R):
for name, cmd in STEPS:
t0 = time.time(); r = subprocess.run([sys.executable] + [os.path.join(HERE, c) if i == 0 else c.replace('{R}', R) for i, c in enumerate(cmd)],
capture_output=True, text=True)
if r.returncode: sys.exit('🔴 生成「%s」失败:\n%s%s' % (name, r.stdout[-1500:], r.stderr[-1500:]))
tip = [l for l in r.stdout.splitlines() if l.startswith(('没找到', '底栏素材'))]
print('%s:%.1f 秒%s' % (name, time.time() - t0, ('(' + tip[0] + ')') if tip else ''))
def main():
R = sys.argv[1] if len(sys.argv) > 1 else os.environ.get('DM_ROMFS_SRC') or os.path.join(DM_ROOT, 'data/switch/3.3.94012/Update/RomFS')
if not os.path.isfile(os.path.join(R, 'data', 'build_manifest.psv')):
sys.exit('🔴 没找到游戏文件:%s/data/build_manifest.psv。把 Switch 版 3.3.94012 的 Update/RomFS 放到这里,或用环境变量 DM_ROMFS_SRC 指过去'
'(见 dm/README.md「从你的游戏文件生成资源」)' % R)
if not ensure(R): print('原版衍生资源:输入没变,沿用 %s' % gen_paths.gen_dir())
if __name__ == '__main__':
main()
+42
View File
@@ -0,0 +1,42 @@
# 从 dm/host/Makefile 实际展开的编译命令(make -n -B dmhost)取宿主的源文件 / 头文件路径 / 框架,生成 iOS 工程的构建输入,
# 不手抄列表:Makefile 一改,iOS 下次构建自动跟上。
# Gen/src/<扁平名> 源文件符号链接(排除 main.c 与 front_mac.m;main.c 另链到 Gen/main/main.c,以 -Dmain=dm_main 编)
# stdout xcconfig 行:HEADER_SEARCH_PATHS(-I 目录 + 每个源文件所在目录,保证相对 include 照常解析)、
# OTHER_CFLAGS(-D)、框架(Cocoa 换成 UIKit 侧已有,跳过)
# 用法:gen_build.py <dm/host 目录> <Gen 目录>
# Take the host's source files / header paths / frameworks from the actually expanded compile commands of dm/host/Makefile (make -n -B dmhost) and generate the iOS project's build inputs,
# without hand-copying lists: when the Makefile changes, the next iOS build follows automatically.
# Gen/src/<flat name> symlinks to source files (excluding main.c and front_mac.m; main.c is linked separately to Gen/main/main.c and compiled with -Dmain=dm_main)
# stdout xcconfig lines: HEADER_SEARCH_PATHS (-I directories + the directory of every source file, so relative includes resolve as usual),
# OTHER_CFLAGS (-D), frameworks (Cocoa is replaced by what the UIKit side already has, skipped)
# Usage: gen_build.py <dm/host dir> <Gen dir>
import os, shlex, subprocess, sys
host, gen = os.path.abspath(sys.argv[1]), os.path.abspath(sys.argv[2])
cmd = subprocess.run(['make', '-s', '-n', '-B', '-C', host, 'dmhost'], capture_output=True, text=True, check=True).stdout
toks = shlex.split(next(l for l in cmd.splitlines() if l.lstrip().startswith('clang')))
srcs, incs, defs, fws = [], [], [], []
i = 0
while i < len(toks):
t = toks[i]
if t == '-framework': fws.append(toks[i + 1]); i += 2; continue
if t.startswith('-I'): incs.append(os.path.normpath(os.path.join(host, t[2:])))
elif t.startswith('-D'): defs.append(t)
elif t.endswith(('.c', '.m', '.S')): srcs.append(os.path.normpath(os.path.join(host, t)))
i += 1
assert srcs, '编译命令里没有源文件'
dup = sorted({s for s in srcs if srcs.count(s) > 1})
if dup: sys.exit('编译命令里源文件重复(Makefile 显式列与通配重叠?):' + ' '.join(dup))
os.makedirs(f'{gen}/src'); os.makedirs(f'{gen}/main')
dirs = []
for s in srcs:
d = os.path.dirname(s)
if d not in dirs: dirs.append(d)
b = os.path.basename(s)
if os.path.splitext(b)[0].endswith('_mac'): continue # Mac 专用源按 _mac 命名约定不进 iOS(front_mac.m 由 front_ios.m 实现 front.h;touch_mac.c 是 Mac 触点脚本) | Mac-only sources are kept out of iOS by the _mac naming convention (for front_mac.m, front_ios.m implements front.h; touch_mac.c is the Mac touch point script)
if os.path.dirname(s) == os.path.normpath(os.path.join(host, '../ios/Sources')): continue # 宿主借用的 iOS 源(如触屏模块)iOS 工程本身已编,再收一份会重复链接 | iOS sources borrowed by the host (e.g. the touch module) are already compiled by the iOS project itself; collecting another copy would link them twice
if s == os.path.join(host, 'main.c'): os.symlink(s, f'{gen}/main/main.c'); continue
flat = os.path.relpath(s, os.path.dirname(host)).replace('/', '__') # 不同目录同名文件不冲突 | Same-named files in different directories do not collide
os.symlink(s, f'{gen}/src/{flat}')
print('HEADER_SEARCH_PATHS = $(inherited) ' + ' '.join(f'"{d}"' for d in incs + dirs))
print('OTHER_CFLAGS = $(inherited) ' + ' '.join(defs))
print('DM_FRAMEWORKS = ' + ' '.join(f'-framework {f}' for f in fws if f != 'Cocoa'))

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