diff --git a/README.md b/README.md index ac33cb7..1c83858 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ This is not a tech demo that "sort of runs". It is a mobile version polished for daily play, from your first character all the way through the endgame. -Platforms: iPhone / iPad (iOS 26 and later) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 · License: MIT · **Bring your own game files** +Platforms: iPhone / iPad (iOS 26 and later) · Mac (Apple silicon, macOS 13 and later, first version) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 · License: MIT · **Bring your own game files** 中文: [README.zh-CN.md](README.zh-CN.md) @@ -231,6 +231,17 @@ The first time you open the app on your phone, it asks for the "game resource fo `./setup.sh check` is a health check: it reports the state of this computer, the tools, the game files and the signing configuration item by item, and for everything missing it says where to get it and which command to run next; it changes nothing. If what you have is a whole game package (`.xci` / `.nsp`), `./setup.sh ` first extracts the game files into place and then carries on (install hactool first). Run `./setup.sh` again after every update to a new commit: it rebuilds the patched binaries and the shader library for the current sources (steps that are already up to date are skipped). It also rewrites three files in the repository that change with your local tool fingerprints (`dm/gfx/tools/dmsh_chain.lock`, `dm/gfx/nvn/dmsh_chain.h`, `dm/gfx/nvn/c1_full.tsv`); that is expected, do not commit them. +### Playing directly on a Mac + +After the same `./setup.sh`, one more command produces a native macOS App that starts on double-click and works with keyboard, mouse and gamepad, with no developer account needed: + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +dm/tools/mac_app.sh # produces ~/dm-work/out/macapp/D2R Mobile.app +``` + +This is a first version: it uses the original gamepad UI, with the keyboard mapped to the full set of gamepad buttons. Nobody has actually sat down and played it yet — the key mapping, the known gaps and what to do on first launch are in [docs/MAC.md](docs/MAC.md). + ### Without a Mac: the shell plus the packaging tool Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md). @@ -264,6 +275,7 @@ Download our prebuilt "shell" package (`D2RMobile-shell.ipa`), which contains no | [docs/GAME_FILES.md](docs/GAME_FILES.md) | Game files: which ones you need, how to get them from your own console, where to put them | | [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md) | Dependencies and third-party licenses | | [docs/NO_XCODE.md](docs/NO_XCODE.md) | Building without Xcode and without a Mac | +| [docs/MAC.md](docs/MAC.md) | Playing on a Mac: building the macOS App, key mapping, known gaps | | [docs/DERIVED.md](docs/DERIVED.md) | Game-related material in this repository: what is here, what is not, and why | ## Legal diff --git a/README.zh-CN.md b/README.zh-CN.md index 5f71c05..1f6fb96 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -4,7 +4,7 @@ 这不是一个「勉强能跑」的技术演示,而是一个打磨到可以天天玩、从开荒一路玩到终局的移动版。 -平台:iPhone / iPad(iOS 26 起)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English · 许可证:MIT · **需要自备游戏文件** +平台:iPhone / iPad(iOS 26 起)· Mac(Apple 芯片,macOS 13 起,第一版)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English · 许可证:MIT · **需要自备游戏文件** English: [README.md](README.md) @@ -231,6 +231,17 @@ flowchart LR `./setup.sh check` 是体检:逐项报告这台电脑、工具、游戏文件、签名配置的状态,缺的每一项都给出去哪拿和下一步命令,不做任何改动。手上是一整个游戏包(`.xci` / `.nsp`)时,`./setup.sh <游戏包> ` 会先把游戏文件取出来放到位再接着准备(要先装 hactool)。每次更新到新的提交之后都要再跑一遍 `./setup.sh`:它会按当前源码重出改写产物与着色器库(已是最新的步骤会跳过)。它还会改写仓库里三个随工具指纹变化的文件(`dm/gfx/tools/dmsh_chain.lock`、`dm/gfx/nvn/dmsh_chain.h`、`dm/gfx/nvn/c1_full.tsv`),这是预期的,不要提交它们。 +### 在 Mac 上直接玩 + +同一份 `./setup.sh` 做完之后,再跑一条命令就能出一个原生的 macOS App,双击启动,键盘、鼠标、手柄都能用,不需要开发者账号: + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +dm/tools/mac_app.sh # 产出 ~/dm-work/out/macapp/D2R Mobile.app +``` + +这是第一版:界面用原版的手柄版界面,键盘对应整套手柄键位。它还没有人真的坐下来玩过——键位、已知的不足和第一次打开时要做的事,见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md)。 + ### 没有 Mac:壳 + 做包工具 从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell.ipa`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。 @@ -264,6 +275,7 @@ flowchart LR | [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md) | 游戏文件:要哪些、怎么从自己的主机取、放到哪 | | [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md) | 依赖清单与第三方许可证 | | [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md) | 不用 Xcode、不用 Mac 的做法 | +| [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 在 Mac 上玩:构建 macOS App、键位、已知不足 | | [docs/DERIVED.zh-CN.md](docs/DERIVED.zh-CN.md) | 仓库里与游戏有关的东西:有什么、没有什么、为什么 | ## 声明 diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index e4679c3..156a3ca 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -99,12 +99,19 @@ static _Atomic int g_up_pending; static pthread_mutex_t g_res_mu = PTHREAD_MUTEX_INITIALIZER; // 驻留集专用锁:res_add 会在持 g_mu 的路径里调用(arena_new),不能共用 g_mu | Dedicated lock for the residency set: res_add is called on paths that hold g_mu (arena_new), so it cannot share g_mu static NSHashTable *g_res_objects; +// 测试开关 DM_RES_CENSUS=1(不常开):记下进过驻留集的全部对象(弱引用),内存读数行那一拍按「还在驻留集里 / 已移出驻留集却还没销毁」各报个数与占用。 +// 后一类 = 我们已经不用、但还有人攥着引用(例如客体线程上从不排空的自动释放池)的显卡内存 +// Test switch DM_RES_CENSUS=1 (not normally on): records every object that has entered the residency set (weak references); on the tick of the memory readout line it reports the count and size of those "still in the residency set" and those "removed from the residency set but not yet destroyed". +// The latter = GPU memory we no longer use but someone still holds a reference to (for example an autorelease pool on a guest thread that is never drained) +static NSHashTable *g_res_ever; static int g_res_census = -1; static void res_add(id r) { if (!r) return; pthread_mutex_lock(&g_res_mu); [g_res addAllocation:(id)r]; if (!g_res_objects) g_res_objects = [NSHashTable weakObjectsHashTable]; [g_res_objects addObject:r]; + if (g_res_census < 0) g_res_census = getenv("DM_RES_CENSUS") != NULL; + if (g_res_census > 0) { if (!g_res_ever) g_res_ever = [NSHashTable weakObjectsHashTable]; [g_res_ever addObject:r]; } g_res_dirty = 1; pthread_mutex_unlock(&g_res_mu); } @@ -1225,7 +1232,19 @@ static id tex_mtl(const tex_t *ct) { // Memory readout line (always on, low frequency, capped): resident memory, GPU allocated, deferred release queue, residency set object count, registered memory pool count / peak / tracking table capacity, cumulative texture re-uploads, game heap total / free / largest allocatable block (host dm_guest_heap_stat), and how far from the system memory limit (iOS only). // Purpose: to pin down "crashes with no log" -- the system gives no notice before killing a process for memory, and only readouts left beforehand can show which number kept climbing. // Called by the frame hook every 300 frames; printed when resident or GPU allocated changed by >= 64 MB, or game heap free space or largest allocatable block changed by >= 16 MB (the main heap normally has only about 100 MB left), otherwise one line every 3000 frames; capped at 400 lines per run. All integers (the frame hook runs on the small stack of a guest thread, so no floating-point formatting) +static void res_census(unsigned long long frame, unsigned long long rss_mb) { + @autoreleasepool { + unsigned long nl[2] = {0, 0}, nr[2] = {0, 0}; unsigned long long bl[2] = {0, 0}, br[2] = {0, 0}; // [0] 贴图 [1] 缓冲;l = 在驻留集里,r = 已退役未销毁 | [0] textures [1] buffers; l = in the residency set, r = retired but not destroyed + pthread_mutex_lock(&g_res_mu); + for (id o in g_res_ever.allObjects) { int k = [o conformsToProtocol:@protocol(MTLBuffer)] ? 1 : 0; unsigned long long b = (unsigned long long)[(id)o allocatedSize]; + if ([g_res_objects containsObject:o]) { nl[k]++; bl[k] += b; } else { nr[k]++; br[k] += b; } } + pthread_mutex_unlock(&g_res_mu); + MLOG("驻留普查 至帧 %llu:常驻 %llu MB,显卡已分配 %llu MB;驻留集里 贴图 %lu 个 %llu MB、缓冲 %lu 个 %llu MB;已退役未销毁 贴图 %lu 个 %llu MB、缓冲 %lu 个 %llu MB", frame, rss_mb, (unsigned long long)(g_dev.currentAllocatedSize >> 20), + nl[0], bl[0] >> 20, nl[1], bl[1] >> 20, nr[0], br[0] >> 20, nr[1], br[1] >> 20); + } +} void mtl_mem_stat(unsigned long long frame, unsigned long long rss_mb, int heap_ok, unsigned long long heap_mb, unsigned long long heap_free_mb, unsigned long long heap_maxblk_kb) { + if (g_res_census > 0) res_census(frame, rss_mb); static unsigned long long last_rss, last_gpu, last_frame, last_hfree, last_hmax; static int lines; unsigned long long gpu = (unsigned long long)(g_dev.currentAllocatedSize >> 20); unsigned long long dr = rss_mb > last_rss ? rss_mb - last_rss : last_rss - rss_mb, dg = gpu > last_gpu ? gpu - last_gpu : last_gpu - gpu; unsigned long long dh = heap_free_mb > last_hfree ? heap_free_mb - last_hfree : last_hfree - heap_free_mb, hmax_mb = heap_maxblk_kb >> 10, dm = hmax_mb > last_hmax ? hmax_mb - last_hmax : last_hmax - hmax_mb; diff --git a/dm/host/Makefile b/dm/host/Makefile index d12f5c1..2279f0b 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -2,7 +2,7 @@ DM_ROOT ?= $(HOME)/dm-work CFLAGS=-O1 -g -Wall -Wno-unused-function # 服务层接管 hle_*.c 按通配纳入:新增文件不改这一行(免合并冲突) # Service-layer takeover hle_*.c files are included by wildcard: adding a file does not touch this line (avoids merge conflicts) -SRC=main.c loader.c hle.c crash.c diag.c thread.c memstat.m dm_cursor.c dm_cursor_item.c dm_world.c dm_textinput.c dm_update.c dm_actions.c dm_namegen.c dm_cloudsync.c dm_custom.c dm_elysium.c dm_bossrush.c dm_pages.c dm_vault.c dm_vault_ui.c dm_kills.c dm_textbox.c dm_textbox_core.c dm_potpick.c dm_lootfilter.c dm_autobuff.c dm_beltauto.c dm_padmode.c dm_pouch.c dm_drophaptic.c dm_freetp.c dm_townwp.c dm_shoprefresh.c dm_runeword.c dm_uiscreen.c dm_dropfilter.c dm_hud.c dm_rift.c dm_rift_ui.c dm_bright.c touch_mac.c romfs_validate.c ../ios/Sources/dm_touch_controls.c $(sort $(wildcard hle_*.c)) front_mac.m entry.S dm_i18n.c +SRC=main.c loader.c hle.c crash.c diag.c thread.c memstat.m dm_cursor.c dm_cursor_item.c dm_world.c dm_textinput.c dm_update.c dm_actions.c dm_namegen.c dm_cloudsync.c dm_custom.c dm_elysium.c dm_bossrush.c dm_pages.c dm_vault.c dm_vault_ui.c dm_kills.c dm_textbox.c dm_textbox_core.c dm_potpick.c dm_lootfilter.c dm_autobuff.c dm_beltauto.c dm_padmode.c dm_pouch.c dm_drophaptic.c dm_freetp.c dm_townwp.c dm_shoprefresh.c dm_runeword.c dm_uiscreen.c dm_dropfilter.c dm_hud.c dm_rift.c dm_rift_ui.c dm_bright.c touch_mac.c romfs_validate.c ../ios/Sources/dm_touch_controls.c $(sort $(wildcard hle_*.c)) front_mac.m app_mac.m ../ios/Sources/dm_gamepad.m entry.S dm_i18n.c # NVN 空设备 + nn::vi(dm/gfx/) # 按通配纳入 dm/gfx 与 dm/gfx/nvn 下的源(tests/ metal/ 不进宿主):新增文件不改这一行 # NVN null device + nn::vi (dm/gfx/) @@ -27,5 +27,5 @@ dm_hud_exp.h: ../ios/tools/gen_hud_exp.py ../ios/tools/romfs_art.py dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py $(NEED_ROMFS) python3 ../tools/gen_bright_levels.py "$(ROMFS)" > $@.tmp && mv $@.tmp $@ -dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH) - clang $(CFLAGS) -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers +dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH) + clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController diff --git a/dm/host/app_mac.m b/dm/host/app_mac.m new file mode 100644 index 0000000..551682c --- /dev/null +++ b/dm/host/app_mac.m @@ -0,0 +1,117 @@ +// macOS App 形态(双击起):宿主被包成 <名>.app 时,启动最前面替玩家把命令行那套准备好—— +// 窗口开着;存档放 ~/Library/Application Support/D2R Mobile/save(与开发用的工作区、测试存档都不相干); +// 游戏资源文件夹第一次启动时请玩家选(记在偏好里,下次不再问;选的不是资源文件夹给明确报错、重选); +// 程序文件(改写后的游戏程序,产物目录)随包放在 Contents/Resources/product;日志写到 ~/Library/Logs/D2R Mobile/host.log。 +// 命令行起(闸门、截图、脚本)不走这里:不在 .app 包里,或带了参数,一律原样。打包脚本 dm/tools/mac_app.sh。 +// macOS App form (started by double-click): when the host is packaged as .app, the very first thing at startup is to prepare the command-line setup on the player's behalf -- +// the window is on; saves go to ~/Library/Application Support/D2R Mobile/save (unrelated to the development workspace and to test saves); +// the game resource folder is chosen by the player on first launch (remembered in preferences and not asked again; choosing something that is not a resource folder gives a clear error and another try); +// the program files (the rewritten game program, the build output directory) are in Contents/Resources/product inside the package; the log is written to ~/Library/Logs/D2R Mobile/host.log. +// Command-line starts (gates, screenshots, scripts) do not come here: not inside an .app package, or with arguments, everything stays as it was. Packaging script: dm/tools/mac_app.sh. +#import +#include +#include "hle.h" +#include "dm_i18n.h" +#define T(k) (@(dm_ui(k))) + +#define APP_NAME "D2R Mobile" +static NSString *const kRomfsKey = @"RomfsDir"; + +// 这个文件夹是不是游戏资源:认 data/build_manifest.psv。选到上一两层(解包目录的根、Update)也认,往里找一层 +// Whether this folder is the game resources: recognized by data/build_manifest.psv. Choosing one or two levels up (the root of the unpacked directory, Update) is accepted too, looking one level in +static NSString *romfs_root(NSString *dir, NSString **why) { + NSFileManager *fm = NSFileManager.defaultManager; + for (NSString *sub in @[@"", @"RomFS", @"romfs", @"Update/RomFS"]) { + NSString *d = sub.length ? [dir stringByAppendingPathComponent:sub] : dir; + if ([fm fileExistsAtPath:[d stringByAppendingPathComponent:@"data/build_manifest.psv"]]) { + if (![fm isReadableFileAtPath:[d stringByAppendingPathComponent:@"data/build_manifest.psv"]]) { if (why) *why = T("dmAppNoRead"); return nil; } + return d; + } + } + if (why) *why = [NSString stringWithFormat:T("dmAppNotRomfs"), dir.lastPathComponent.UTF8String]; + return nil; +} +static void alert(NSString *title, NSString *text) { + NSAlert *a = [NSAlert new]; a.messageText = title; a.informativeText = text; [a addButtonWithTitle:T("dmAppOK")]; [a runModal]; +} +// 请玩家选资源文件夹,直到选对或取消。返回资源根目录,取消返回 nil +// Ask the player to choose the resource folder until it is right or cancelled. Returns the resource root, or nil on cancel +static NSString *pick_romfs(NSString *first_why) { + NSString *why = first_why; + for (;;) { + NSOpenPanel *p = [NSOpenPanel openPanel]; + p.canChooseDirectories = YES; p.canChooseFiles = NO; p.allowsMultipleSelection = NO; p.prompt = T("dmAppPickUse"); + p.message = why ? [NSString stringWithFormat:T("dmAppPickAgain"), why.UTF8String] : T("dmAppPickMsg"); + if ([p runModal] != NSModalResponseOK) return nil; + NSString *w = nil, *r = romfs_root(p.URL.path, &w); + if (r) return r; + alert(T("dmAppNotRomfsTitle"), w); why = w; + } +} + +// 包里的一项(product / msl / romfs_overlay):实物在 Contents/Resources/<名> 就用它;没有就看 Resources/paths.txt 里「名=本机路径」那一行 +// (mac_app.sh 的「不带派生物」出法:改写后的游戏程序、着色器库、界面覆盖层都从游戏内容派生,公开发布的包不带,指向本机自己构建出来的) +// One item of the package (product / msl / romfs_overlay): if the real thing is in Contents/Resources/ it is used; otherwise the line "name=local path" in Resources/paths.txt is consulted +// (the "without derived content" build of mac_app.sh: the rewritten game program, the shader library and the UI overlay are all derived from game content, a publicly released package does not carry them and points at what this machine built itself) +static NSString *res_item(NSString *name) { + NSFileManager *fm = NSFileManager.defaultManager; NSString *rp = NSBundle.mainBundle.resourcePath, *d = [rp stringByAppendingPathComponent:name]; + if ([fm fileExistsAtPath:d]) return d; + NSString *txt = [NSString stringWithContentsOfFile:[rp stringByAppendingPathComponent:@"paths.txt"] encoding:NSUTF8StringEncoding error:nil]; + for (NSString *ln in [txt componentsSeparatedByString:@"\n"]) { NSString *pre = [name stringByAppendingString:@"="]; if ([ln hasPrefix:pre]) { d = [ln substringFromIndex:pre.length]; return [fm fileExistsAtPath:d] ? d : nil; } } + return nil; +} +// main() 最前面调。是 App 形态就把环境与参数备好并返回 1;不是返回 0、什么都不动 +// Called at the very start of main(). In App form it prepares the environment and arguments and returns 1; otherwise it returns 0 and touches nothing +int dm_app_bootstrap(int *argc, char ***argv) { + @autoreleasepool { + NSString *bp = NSBundle.mainBundle.bundlePath; + if (*argc > 1 || ![bp.pathExtension isEqualToString:@"app"]) return 0; + NSFileManager *fm = NSFileManager.defaultManager; + if (!getenv("DM_LANG")) setenv("DM_LANG", [NSLocale.preferredLanguages.firstObject hasPrefix:@"zh"] ? "zh-Hans" : "en", 1); // 命令行宿主一律简中;App 形态跟系统首选语言(提示框与游戏内同一个开关) | The command-line host is always Simplified Chinese; the App form follows the system's preferred language (dialogs and in-game text use the same switch) + NSString *sup = [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@APP_NAME] copy]; + if (getenv("DM_APP_SUPPORT")) sup = @(getenv("DM_APP_SUPPORT")); // 测试:存档等放到指定目录,不碰玩家那份 | Test: put saves and the rest in a given directory, leaving the player's own untouched + NSString *logd = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"Logs/" APP_NAME] copy]; + NSString *save = [sup stringByAppendingPathComponent:@"save"], *temp = [sup stringByAppendingPathComponent:@"temp"]; + for (NSString *d in @[sup, logd, save, temp]) [fm createDirectoryAtPath:d withIntermediateDirectories:YES attributes:nil error:nil]; + // 双击起没有终端:日志落文件,上一次的留一份 + // A double-click start has no terminal: the log goes to a file, and the previous one is kept + NSString *lf = [logd stringByAppendingPathComponent:@"host.log"]; + [fm removeItemAtPath:[logd stringByAppendingPathComponent:@"host.prev.log"] error:nil]; + [fm moveItemAtPath:lf toPath:[logd stringByAppendingPathComponent:@"host.prev.log"] error:nil]; + if (!isatty(2)) { freopen(lf.fileSystemRepresentation, "w", stderr); setvbuf(stderr, NULL, _IOLBF, 0); } + [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; [NSApp activateIgnoringOtherApps:YES]; + NSString *prod = res_item(@"product"); + if (!prod || ![fm fileExistsAtPath:[prod stringByAppendingPathComponent:@"main.patched.bin"]]) { + alert(T("dmAppBrokenTitle"), T("dmAppBroken")); exit(1); + } + NSUserDefaults *ud = NSUserDefaults.standardUserDefaults; + NSString *saved = [ud stringForKey:kRomfsKey], *why = nil, *rom = saved ? romfs_root(saved, &why) : nil; + if (getenv("DM_APP_ROMFS")) { // 测试(没人点对话框时用):直接给资源文件夹;不对就把同一句报错写进日志并退出,不弹框、不记进偏好 | Test (for when nobody is there to click the dialog): give the resource folder directly; if it is wrong, write the same error sentence to the log and exit, with no dialog and nothing saved to preferences + rom = romfs_root(@(getenv("DM_APP_ROMFS")), &why); + if (!rom) { LOG("【红】App:DM_APP_ROMFS 给的不是游戏资源文件夹:%s", why.UTF8String); exit(2); } + } else if (!rom) { + rom = pick_romfs(saved ? [NSString stringWithFormat:T("dmAppRomfsGone"), why.UTF8String] : nil); + if (!rom) { LOG("App:没有选资源文件夹,退出"); exit(0); } + [ud setObject:rom forKey:kRomfsKey]; + } + setenv("DM_WINDOW", "1", 1); setenv("DM_APP", "1", 1); + setenv("DM_SAVE", save.fileSystemRepresentation, 1); setenv("DM_TEMP", temp.fileSystemRepresentation, 1); + setenv("DM_ROMFS", rom.fileSystemRepresentation, 1); setenv("DM_ROOT", sup.fileSystemRepresentation, 1); + NSString *shmap = [NSBundle.mainBundle.resourcePath stringByAppendingPathComponent:@"shader_map.tsv"]; // 图形后端的着色器映射表:命令行起时按可执行文件旁的源码树找,包里放在 Resources | The graphics backend's shader mapping table: when started from the command line it is found via the source tree next to the executable; in the package it is in Resources + if ([fm fileExistsAtPath:shmap]) setenv("DM_NVN_SHMAP", shmap.fileSystemRepresentation, 1); + NSString *msl = res_item(@"msl"); // 编好的着色器库(msl/b-<翻译链版本>/) | The compiled shader library (msl/b-/) + if (msl) setenv("DM_MSL_DIR", msl.fileSystemRepresentation, 1); + NSString *ov = res_item(@"romfs_overlay"); + if (ov) setenv("DM_ROMFS_OVERLAY", ov.fileSystemRepresentation, 1); + static char *av[5]; av[0] = (*argv)[0]; av[1] = strdup(prod.fileSystemRepresentation); av[2] = "main"; av[3] = "sdk"; av[4] = NULL; + *argv = av; *argc = 4; + LOG("App:存档 %s;资源 %s;程序文件 %s;界面覆盖层 %s;日志 %s", save.UTF8String, rom.UTF8String, prod.UTF8String, getenv("DM_ROMFS_OVERLAY") ?: "(没有,原版界面)", lf.UTF8String); + return 1; + } +} + +// 手柄代码(ios/Sources/dm_gamepad.m,两边共用)问「现在是不是面板 / 读取画面开着」:只用来决定空着的 ZR 格要不要当免费回城。 +// 宿主没有 iOS 壳那套面板栈;一律答「是」= ZR 整颗交给原版(面板里它是翻页签键),手柄上的免费回城这一版没有(记在已知不足里) +// The gamepad code (ios/Sources/dm_gamepad.m, shared by both sides) asks "is a panel / loading screen open right now": used only to decide whether the empty ZR slot should act as the free town portal. +// The host has no panel stack like the iOS shell; it always answers "yes" = ZR is handed entirely to the original game (in panels it is the tab-switch key), so the free town portal on the gamepad is absent in this version (listed under known gaps) +int dm_front_navigation(void) { return 1; } diff --git a/dm/host/diag.c b/dm/host/diag.c index fd377e9..5e2657a 100644 --- a/dm/host/diag.c +++ b/dm/host/diag.c @@ -1183,6 +1183,15 @@ int dm_request_save(void) { *(volatile uint64_t *)(uintptr_t)(g_lastG + 0x5800) = 1; return 1; } +// 退出前存盘用(Mac App):单机暂停着(暂停菜单 / 大秘境面板开着,原版界面状态字节 [main+0x2d5ff51] | [main+0x2d5ff67] 非 0,见 dm_rift_ui.c)时游戏不跑拍, +// 上面拨的那次存盘等不到。把这两个字节清掉让拍接着走;只在进程马上要退出时调(不写回)。返回清之前是否暂停着 +// For saving before exit (Mac App): while single-player is paused (pause menu / rift panel open, original UI state bytes [main+0x2d5ff51] | [main+0x2d5ff67] non-zero, see dm_rift_ui.c) the game does not tick, +// so the save requested above would never happen. Clear these two bytes so the ticks continue; called only when the process is about to exit (not written back). Returns whether it was paused before clearing +int dm_unpause_for_exit(void) { + uint8_t *b = NULL; for (int i = 0; i < g_nmod; i++) if (!strcmp(g_mod[i].name, "main")) b = (uint8_t *)g_mod[i].base; + if (!b || !in_game()) return 0; + volatile uint8_t *f = b + 0x2d5ff51, *g = b + 0x2d5ff67; int was = *f || *g; *f = 0; *g = 0; return was; +} // 测试用:按 id 取服务端物品单位(物品表 G+0x2e30,128 桶、next=+0x158);不在局内 / 没找到返回 0 // For tests: get a server item unit by id (item table G+0x2e30, 128 buckets, next=+0x158); returns 0 when not in a run / not found uint64_t dm_diag_srv_item(uint32_t id) { if (!in_game()) return 0; uint64_t u = 0; tk_rd(g_lastG + 0x2e30 + 8 * (id & 0x7f), &u, 8); for (int k = 0; u && k < 4096; k++) { uint32_t ty = 0, uid = 0; if (!tk_rd(u, &ty, 4) || !tk_rd(u + 8, &uid, 4)) return 0; if (ty == 4 && uid == id) return u; if (!tk_rd(u + 0x158, &u, 8)) return 0; } return 0; } diff --git a/dm/host/dm_i18n_tab.h b/dm/host/dm_i18n_tab.h index 59c5e8d..a180f4b 100644 --- a/dm/host/dm_i18n_tab.h +++ b/dm/host/dm_i18n_tab.h @@ -302,4 +302,20 @@ static const struct { const char *k, *zh, *en; } k_dm_i18n[] = { { "dmPadDiffLine", "游戏难度:%d", "Game Difficulty: %d" }, { "dmRiftGamAfterEn", "通关本层后", "After This Level" }, { "dmRiftMsNEn", "每档另得 符文 · 赦免之证 · 打孔", "+ Rune, Token of Absolution, Sockets" }, + { "dmAppQuit", "退出 D2R Mobile", "Quit D2R Mobile" }, + { "dmAppOK", "好", "OK" }, + { "dmAppPickUse", "用这个文件夹", "Use This Folder" }, + { "dmAppPickMsg", "请选择游戏资源文件夹(里面有 data 文件夹)。只需要选这一次。", "Choose the game data folder (the one that contains a “data” folder). You only need to do this once." }, + { "dmAppPickAgain", "%s\n\n请重新选择游戏资源文件夹。", "%s\n\nPlease choose the game data folder again." }, + { "dmAppNotRomfsTitle", "这不是游戏资源文件夹", "This is not the game data folder" }, + { "dmAppNotRomfs", "「%s」里没有 data/build_manifest.psv。\n要选的是游戏资源文件夹:里面有一个 data 文件夹,data 里有 build_manifest.psv 和若干很大的数据文件。", "“%s” has no data/build_manifest.psv.\nChoose the game data folder: it contains a “data” folder with build_manifest.psv and several very large data files." }, + { "dmAppNoRead", "找到了资源清单,但没有读取权限。", "The data manifest was found but cannot be read." }, + { "dmAppRomfsGone", "上次选的资源文件夹用不了了:\n%s", "The data folder chosen last time can no longer be used:\n%s" }, + { "dmAppBrokenTitle", "这个 App 不完整", "This app is incomplete" }, + { "dmAppBroken", "包里没有程序文件(Contents/Resources/product)。请重新构建或重新下载。", "The app bundle has no program files (Contents/Resources/product). Rebuild it or download it again." }, + { "dmAppMenuView", "显示", "View" }, + { "dmAppFullscreen", "全屏", "Toggle Full Screen" }, + { "dmAppMenuHelp", "帮助", "Help" }, + { "dmAppKeysTitle", "键盘与手柄按键对照", "Keyboard and Controller Buttons" }, + { "dmAppKeysText", "界面上的按键提示是手柄字母,键盘这样对应:\n\n移动:W A S D(左摇杆)\n十字键:方向键\nA 确认:J  B 返回:K  X:U  Y:I\nL:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n+(菜单):回车  −(地图):Tab\n\n鼠标:左键点目标或界面,右键 = B,滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。", "On-screen button hints use controller letters. Keyboard mapping:\n\nMove: W A S D (left stick)\nD-pad: arrow keys\nA confirm: J B back: K X: U Y: I\nL: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n+ (menu): Return − (map): Tab\n\nMouse: left click a target or the interface, right click = B, wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu." }, }; diff --git a/dm/host/dm_padmode.c b/dm/host/dm_padmode.c index 7dfb37c..807f174 100644 --- a/dm/host/dm_padmode.c +++ b/dm/host/dm_padmode.c @@ -125,7 +125,8 @@ void dm_padmode_boot(void) { // 开机:游戏建面板之前(main.c,nnMa module_t *m = NULL; for (int i = 0; i < g_nmod; ++i) if (!strcmp(g_mod[i].name, "main")) m = &g_mod[i]; char mk[1100]; if (!m || !getenv("DM_ROMFS_OVERLAY")) return; if (!dm_overlay_file("ctrl_touch", mk, sizeof mk)) { LOG("手柄 / 触屏布局:覆盖层没有 ctrl_touch 标记,照原版布局"); return; } - if (pfx_write((uint8_t *)m->base, 0)) { g_have = 1; g_cur = 0; g_b = (uint8_t *)m->base; str_load(); LOG("手柄 / 触屏布局:开机用触屏版(layouts/xtouch_lay 等三个目录)"); } + int pad = getenv("DM_APP") != NULL; // Mac App:没有触屏圆钮与底栏的绘制层,开机就用原版手柄版(我们的功能页在手柄版布局里同样有),之后也不切 | Mac App: there is no drawing layer for the touch buttons and bottom bar, so it starts in the original gamepad UI (our feature pages exist in the gamepad layout as well) and never switches afterwards + if (pfx_write((uint8_t *)m->base, pad)) { g_have = 1; g_cur = pad; atomic_store(&g_want, pad); g_b = (uint8_t *)m->base; str_load(); LOG("手柄 / 触屏布局:开机用%s", pad ? "原版手柄版(Mac App)" : "触屏版(layouts/xtouch_lay 等三个目录)"); } } void dm_padmode_request(int pad) { pad = pad ? 1 : 0; atomic_store(&g_want, pad); if (g_have && pad != g_cur) atomic_store(&g_freeze, 1); } // 前端(任意线程):从这一刻起输入就不再交给游戏 | Front end (any thread): from this moment on input is no longer handed to the game int dm_padmode_current(void) { return g_cur; } diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m index bbada47..b462d9a 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -5,7 +5,7 @@ // Without DM_WINDOW: the guest runs directly on the current thread, behaving the same as with no front end (windowless tests use this). // Key map (Nintendo layout): WASD left stick, arrow keys D-pad, J=A K=B U=X I=Y, Q=L E=R, Z=ZL C=ZR, F=press left stick G=press right stick, Return=+ Tab=−. #import -#import +#import #import #include "dm.h" #include "dm_input.h" @@ -17,7 +17,51 @@ __attribute__((constructor)) static void ui_shift_reg(void) { mtl_set_ui_rect_fn #include "hle.h" #include +void dm_touch_host_live_enable(void); void dm_touch_host_live(int op, float nx, float ny); // touch_mac.c +static int g_live; // App 形态(或 DM_TOUCH_LIVE=1):鼠标进我们的触屏状态机;否则照旧当原版触摸屏的一个触点 | App form (or DM_TOUCH_LIVE=1): the mouse goes into our touch state machine; otherwise it stays a single touch point of the original touch screen as before static CAMetalLayer *g_layer; +static NSView *g_view; +// 窗口不是 16:9(拉伸窗口、全屏到 16:10 的屏):游戏画面保持 16:9 居中,四周留黑边;鼠标位置按游戏画面这一块算 +// The window is not 16:9 (stretched window, full screen on a 16:10 display): the game picture stays 16:9 and centred with black bars around it; the mouse position is computed against the game picture +static NSRect game_rect(void) { + NSSize b = g_view.bounds.size; CGFloat w = b.width, h = b.height; + if (w * 9 > h * 16) w = floor(h * 16 / 9); else h = floor(w * 9 / 16); + return NSMakeRect(floor((b.width - w) / 2), floor((b.height - h) / 2), w, h); +} +static void layout_game(void) { + NSRect r = game_rect(); if (NSEqualRects(r, g_layer.frame)) return; + [CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = g_view.window.backingScaleFactor; [CATransaction commit]; + LOG("窗口:内容区 %.0f×%.0f,游戏画面 %.0f×%.0f 放在 (%.0f,%.0f)", g_view.bounds.size.width, g_view.bounds.size.height, r.size.width, r.size.height, r.origin.x, r.origin.y); +} +// 退出(关窗口 / ⌘Q / 菜单):有局在就先请游戏走一次它自己的存盘并等存档提交(做法同 iOS 壳进后台),最多 3 秒,再有序收尾。 +// 暂停菜单 / 大秘境面板开着时游戏停拍:先放开暂停让拍走起来;读取画面里等它进到局内再请。3 秒到了还没有提交就照实记「未存盘退出」 +// Quit (closing the window / ⌘Q / menu): if a game is in progress, first ask the game to do its own save and wait for the save to be committed (the same way the iOS shell does when going to the background), for at most 3 seconds, then shut down in order. +// With the pause menu / rift panel open the game is not ticking: release the pause first so the ticks run; in a loading screen wait until it is in the game, then ask. If nothing is committed when the 3 seconds are up, truthfully log "quit without saving" +static void app_quit(const char *why) { + static int once; if (once++) return; + int dm_ingame_now(void); int dm_request_save(void); int dm_unpause_for_exit(void); uint64_t dm_fs_commit_count(void); uint64_t now_ns(void); + if (!dm_ingame_now() && !dm_uiscreen_ingame()) { LOG("窗口:退出(不在局内,没有待存的进度)"); dm_host_shutdown(why); return; } + uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0; int asked = 0, paused = 0; + for (;;) { + paused |= dm_unpause_for_exit(); if (!asked) asked = dm_request_save(); + usleep(20000); uint64_t c = dm_fs_commit_count(), t = now_ns(); + if (c != last) { last = c; last_t = t; } + if ((asked && last_t && t - last_t >= 200000000ull) || t - t0 >= 3000000000ull) break; + } + if (last != c0 && asked) LOG("窗口:退出前等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), paused ? "(原先停在暂停菜单 / 面板,已放开)" : ""); + else LOG("【红】窗口:未存盘退出——3 秒内没等到存档提交(%s%s)", asked ? "已请游戏存盘" : "一直没到能请存盘的状态(读取画面?)", paused ? ",原先暂停着、已放开" : ""); + dm_host_shutdown(why); +} +static const char *ui(const char *k) { const char *dm_ui(const char *key); return dm_ui(k); } +static void show_keys(void) { NSAlert *a = [NSAlert new]; a.messageText = @(ui("dmAppKeysTitle")); a.informativeText = @(ui("dmAppKeysText")); [a addButtonWithTitle:@(ui("dmAppOK"))]; [a runModal]; } +@interface DmWinCtl : NSObject @end +@implementation DmWinCtl +- (BOOL)windowShouldClose:(NSWindow *)w { (void)w; app_quit("关窗口"); return NO; } +- (void)windowDidResize:(NSNotification *)n { (void)n; layout_game(); } +- (void)windowDidChangeBackingProperties:(NSNotification *)n { (void)n; layout_game(); } +- (void)quit:(id)s { (void)s; app_quit("菜单退出"); } +- (void)keys:(id)s { (void)s; show_keys(); } +@end static uint64_t g_btn; static int g_w, g_a, g_s, g_d; @@ -30,9 +74,10 @@ uint64_t front_game_res(int docked) { return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; } +static int g_wheel; // 滚轮:+1 / −1 = 右摇杆向上 / 向下推一小会儿(原版手柄版用右摇杆滚列表) | Wheel: +1 / -1 = push the right stick up / down for a short while (the original gamepad UI scrolls lists with the right stick) static void push(void) { int32_t lx = (g_d - g_a) * 32767, ly = (g_w - g_s) * 32767; - dm_input_set(g_btn, lx, ly, 0, 0); + dm_input_set(g_btn, lx, ly, 0, g_wheel * 32767); } static int key_bit(unsigned short code) { switch (code) { @@ -69,18 +114,30 @@ void front_run(void (*guest)(void)) { styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; win.title = @"D2R Mobile"; - NSView *v = win.contentView; - v.wantsLayer = YES; + NSView *v = win.contentView; g_view = v; + v.wantsLayer = YES; v.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); + win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, 360); + static DmWinCtl *ctl; ctl = [DmWinCtl new]; win.delegate = ctl; g_layer = [CAMetalLayer layer]; g_layer.device = MTLCreateSystemDefaultDevice(); g_layer.pixelFormat = MTLPixelFormatBGRA8Unorm; g_layer.contentsScale = win.backingScaleFactor; - v.layer = g_layer; + [v.layer addSublayer:g_layer]; layout_game(); [win center]; + g_live = getenv("DM_APP") || getenv("DM_TOUCH_LIVE"); if (g_live) dm_touch_host_live_enable(); + { // 菜单栏:应用(退出 ⌘Q)/ 显示(全屏 ⌃⌘F)/ 帮助(键位对照) | Menu bar: application (Quit ⌘Q) / View (Full Screen ⌃⌘F) / Help (key mapping) + NSMenu *bar = [NSMenu new]; + NSMenu *(^add)(const char *) = ^NSMenu *(const char *t) { NSMenuItem *it = [NSMenuItem new]; [bar addItem:it]; NSMenu *m = [[NSMenu alloc] initWithTitle:@(t)]; it.submenu = m; return m; }; + [[add("") addItemWithTitle:@(ui("dmAppQuit")) action:@selector(quit:) keyEquivalent:@"q"] setTarget:ctl]; + NSMenuItem *fs = [add(ui("dmAppMenuView")) addItemWithTitle:@(ui("dmAppFullscreen")) action:@selector(toggleFullScreen:) keyEquivalent:@"f"]; fs.keyEquivalentModifierMask = NSEventModifierFlagControl | NSEventModifierFlagCommand; + [[add(ui("dmAppMenuHelp")) addItemWithTitle:@(ui("dmAppKeysTitle")) action:@selector(keys:) keyEquivalent:@""] setTarget:ctl]; + NSApp.mainMenu = bar; } + { void dm_gamepad_start(void (*on_mode)(int pad)); dm_gamepad_start(NULL); } // 手柄(与 iOS 壳共用 ios/Sources/dm_gamepad.m):连上即用,与键盘并存 | Gamepad (ios/Sources/dm_gamepad.m, shared with the iOS shell): works as soon as it is connected, alongside the keyboard [win makeKeyAndOrderFront:nil]; [NSApp activateIgnoringOtherApps:YES]; [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown | NSEventMaskKeyUp handler:^NSEvent *(NSEvent *e) { if (e.window != win) return e; // 只吃游戏窗口的键;软键盘输入框等其他窗口照常收字 | Only swallow keys for the game window; other windows such as the software keyboard input box receive typing as usual + if (e.modifierFlags & NSEventModifierFlagCommand) return e; // 带 ⌘ 的留给菜单(⌘Q、⌃⌘F) | Keys with ⌘ are left to the menu (⌘Q, ⌃⌘F) if (!e.isARepeat) on_key(e, e.type == NSEventTypeKeyDown); return nil; // 吃掉,免得系统提示音 | Swallow it to avoid the system beep }]; @@ -88,18 +145,39 @@ void front_run(void (*guest)(void)) { // Mouse as a single-point touchscreen (for testing touch on the local machine, front.h dm_touch_set): left button down / drag = finger 0 at the normalized coordinates, release = lifted [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskLeftMouseDown | NSEventMaskLeftMouseDragged | NSEventMaskLeftMouseUp handler:^NSEvent *(NSEvent *e) { if (e.window != win) return e; - if (e.type == NSEventTypeLeftMouseUp) { dm_touch_set(NULL, 0); return nil; } - NSPoint p = [v convertPoint:e.locationInWindow fromView:nil]; NSSize sz = v.bounds.size; - if (sz.width <= 0 || sz.height <= 0) return e; - dm_touch t = {0, (float)(p.x / sz.width), (float)(1.0 - p.y / sz.height)}; // AppKit 视图原点在左下,触屏原点在左上 | The AppKit view origin is at bottom left, the touchscreen origin is at top left + if (e.type == NSEventTypeLeftMouseUp) { if (g_live) dm_touch_host_live(2, 0, 0); else dm_touch_set(NULL, 0); return nil; } + NSPoint p = [v convertPoint:e.locationInWindow fromView:nil]; NSRect gr = game_rect(); + if (gr.size.width <= 0 || gr.size.height <= 0) return e; + float nx = (float)((p.x - gr.origin.x) / gr.size.width), ny = (float)(1.0 - (p.y - gr.origin.y) / gr.size.height); // AppKit 视图原点在左下,触屏原点在左上 | The AppKit view origin is at bottom left, the touchscreen origin is at top left + if (e.type == NSEventTypeLeftMouseDown && (nx < 0 || nx > 1 || ny < 0 || ny > 1)) return nil; // 按在黑边上:不算点 | Pressed on the black bars: not a click + dm_touch t = {0, nx < 0 ? 0 : nx > 1 ? 1 : nx, ny < 0 ? 0 : ny > 1 ? 1 : ny}; + if (g_live) { dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, t.x, t.y); return nil; } dm_touch_set(&t, 1); return nil; }]; - [[NSNotificationCenter defaultCenter] addObserverForName:NSWindowWillCloseNotification object:win queue:nil - usingBlock:^(NSNotification *n) { (void)n; exit(0); }]; + // 右键 = 手柄 B(返回 / 关面板);滚轮 = 右摇杆上下推 0.12 秒(滚列表)。只在 App 形态接(命令行宿主的测试不受影响) + // Right click = gamepad B (back / close panel); wheel = push the right stick up or down for 0.12 s (scroll lists). Only wired in App form (tests of the command-line host are unaffected) + if (g_live) { + [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskRightMouseDown | NSEventMaskRightMouseUp handler:^NSEvent *(NSEvent *e) { + if (e.window != win) return e; + if (e.type == NSEventTypeRightMouseDown) g_btn |= DM_BTN_B; else g_btn &= ~(uint64_t)DM_BTN_B; + push(); return nil; + }]; + [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^NSEvent *(NSEvent *e) { + if (e.window != win || e.scrollingDeltaY == 0) return e; + static int gen; int my = ++gen; g_wheel = e.scrollingDeltaY > 0 ? 1 : -1; push(); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.12 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ if (my == gen) { g_wheel = 0; push(); } }); + return nil; + }]; + } + if (getenv("DM_APP") && !getenv("DM_APP_ROMFS") && ![NSUserDefaults.standardUserDefaults boolForKey:@"KeysShown"]) { show_keys(); [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"KeysShown"]; } // 第一次启动给一次键位对照(界面上的按键提示是手柄字母);以后在「帮助」菜单里 | Show the key mapping once on first launch (button prompts on screen are gamepad letters); afterwards it is in the Help menu + { const char *e; // 测试(没人点窗口时用):DM_TEST_WINSIZE=宽x高 设内容区大小;DM_TEST_FULLSCREEN_AT=<秒> 进全屏;DM_TEST_QUIT_AT=<秒> 走一次退出 | Tests (for when nobody is there to click the window): DM_TEST_WINSIZE=WxH sets the content size; DM_TEST_FULLSCREEN_AT= enters full screen; DM_TEST_QUIT_AT= goes through one quit + int w, h; if ((e = getenv("DM_TEST_WINSIZE")) && sscanf(e, "%dx%d", &w, &h) == 2) { [win setContentSize:NSMakeSize(w, h)]; layout_game(); } + if ((e = getenv("DM_TEST_FULLSCREEN_AT"))) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(e) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; }); + if ((e = getenv("DM_TEST_QUIT_AT"))) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(e) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ app_quit("DM_TEST_QUIT_AT"); }); } // 生命周期(hle.h / dm.h):失焦 → 2、拿回焦点 → 1;最小化 → 3 + 音频暂停 + GPU 挂起,还原 → 恢复(随后拿回焦点 → 1) // Lifecycle (hle.h / dm.h): focus lost → 2, focus regained → 1; minimized → 3 + audio paused + GPU suspended, restored → resume (followed by focus regained → 1) NSNotificationCenter *nc = NSNotificationCenter.defaultCenter; - [nc addObserverForName:NSWindowDidResignKeyNotification object:win queue:nil usingBlock:^(NSNotification *n) { (void)n; if (!win.miniaturized) dm_focus_set(2); }]; + [nc addObserverForName:NSWindowDidResignKeyNotification object:win queue:nil usingBlock:^(NSNotification *n) { (void)n; if (!win.miniaturized) dm_focus_set(2); g_btn = 0; g_w = g_a = g_s = g_d = 0; push(); { void dm_gamepad_reset(void); dm_gamepad_reset(); } }]; // 失焦:键盘和手柄按着的键清掉(松开事件收不到) | Focus lost: clear the keys held on keyboard and gamepad (their release events will not arrive) [nc addObserverForName:NSWindowDidBecomeKeyNotification object:win queue:nil usingBlock:^(NSNotification *n) { (void)n; dm_focus_set(1); }]; [nc addObserverForName:NSWindowDidMiniaturizeNotification object:win queue:nil usingBlock:^(NSNotification *n) { (void)n; dm_focus_set(3); dm_audio_suspend(1); dm_gfx_suspend(1); }]; [nc addObserverForName:NSWindowDidDeminiaturizeNotification object:win queue:nil usingBlock:^(NSNotification *n) { (void)n; dm_gfx_suspend(0); dm_audio_suspend(0); dm_focus_set(2); }]; diff --git a/dm/host/main.c b/dm/host/main.c index e5202ef..5291f97 100644 --- a/dm/host/main.c +++ b/dm/host/main.c @@ -167,7 +167,12 @@ void dm_host_preload_start(int argc, char **argv) { pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstacksize(&a, 8 << 20); if (pthread_create(&g_pre.th, &a, preload_thread, NULL)) die("dm_host_preload_start:起线程失败"); } +#include +int dm_app_bootstrap(int *argc, char ***argv); // app_mac.m:包成 .app 双击起时备好环境与参数;命令行起原样 | app_mac.m: when packaged as an .app and started by double-click, prepare the environment and arguments; command-line starts are unchanged int main(int argc, char **argv) { +#if TARGET_OS_OSX // iOS 包也编这个文件(入口由外壳调),那边没有 app_mac.m | The iOS package compiles this file too (the entry is called by the shell); there is no app_mac.m on that side + dm_app_bootstrap(&argc, &argv); +#endif if (getenv("DM_PRELOAD")) dm_host_preload_start(argc, argv); // Mac 上验证提前起跑的路径(iOS 由 App 的 main() 调) | Exercise the early-start path on Mac (on iOS it is called from the App's main()) if (atomic_load(&g_pre.started)) { pthread_join(g_pre.th, NULL); diff --git a/dm/host/touch_mac.c b/dm/host/touch_mac.c index be0db0c..27ac027 100644 --- a/dm/host/touch_mac.c +++ b/dm/host/touch_mac.c @@ -28,6 +28,19 @@ static struct { dm_tc_state state; } g_touch; +// ---- 真鼠标(Mac App,front_mac.m):事件来自前端而不是脚本表,进同一套状态机。界面用原版手柄 HUD,屏上没有触屏圆钮与摇杆: +// 非面板态一个按钮目标都不开、左下角不起摇杆(点哪里都只是「点世界」:点到目标走过去交互,点空地不动);面板态照旧(点控件、页签、物品格)。 +// 前端页(主菜单 / 选角 / 建角,不在局内)不经状态机,触点直接当界面点击(同 iOS 前端的 frontendMode)。 +// ---- Real mouse (Mac App, front_mac.m): events come from the front end rather than the script table and enter the same state machine. The UI is the original gamepad HUD, with no touch buttons or stick on screen: +// outside panels no button target is opened and no stick is raised at the bottom left (a click anywhere is just "click the world": clicking a target walks over and interacts, clicking empty ground does nothing); in panels it works as before (clicking controls, tabs, item cells). +// Front-end pages (main menu / character select / character creation, not in a game) bypass the state machine and the touch point is taken directly as a UI click (same as frontendMode in the iOS front end). +#include +static int g_live_on; static uint32_t g_live_tick0; static int g_live_based; +static struct { _Atomic unsigned head, tail; struct { int op; float nx, ny; } q[64]; } g_live; +void dm_touch_host_live(int op, float nx, float ny) { // 前端线程:op 0 按下 1 移动 2 抬起;坐标 = 游戏画面归一化 [0,1] | Front-end thread: op 0 down, 1 move, 2 up; coordinates = normalized to the game picture [0,1] + if (!g_live_on) return; unsigned t = atomic_load(&g_live.tail); if (t - atomic_load(&g_live.head) >= 64) return; + g_live.q[t % 64].op = op; g_live.q[t % 64].nx = nx; g_live.q[t % 64].ny = ny; atomic_store(&g_live.tail, t + 1); +} static void touch_uimsg(const char *cat, const char *act, const char *arg) { static dm_tc_scene scene; if (!strcmp(cat, "DM") && !strcmp(act, "ReplayDone") && g_touch.prefix) @@ -37,7 +50,7 @@ static void touch_uimsg(const char *cat, const char *act, const char *arg) { if (g_touch.enabled) { dm_tc_set_navigation_mode(&g_touch.state, navigation); static int pad = -1; if (pad < 0) { const char *e = getenv("DM_TOUCH_NAV_PAD"); pad = e && e[0] == '1'; } // 缺省不给圆钮(同 front_ios.m) | no round button by default (same as front_ios.m) - uint32_t mask = navigation ? (dm_tc_nav_mask(pad && !dm_tc_scene_dead()) | (dm_tc_scene_dialog_only(&scene) ? 1u << DM_TC_MENU : 0)) : ((1u << DM_TC_COUNT) - 1); + uint32_t mask = navigation ? (dm_tc_nav_mask(pad && !dm_tc_scene_dead()) | (dm_tc_scene_dialog_only(&scene) ? 1u << DM_TC_MENU : 0)) : g_live_on ? 0 : ((1u << DM_TC_COUNT) - 1); dm_tc_enable_targets(&g_touch.state, mask); } if (!strcmp(cat, "DM") && !strcmp(act, "ReplayDone") && g_touch.prefix && !g_touch.started) { @@ -108,6 +121,30 @@ static void touch_init(uint64_t now) { fprintf(stderr, "[dm] DM_TOUCH_SCRIPT ← %s:%d 条,按服务端游戏拍推进(脚本 25 拍/秒)%s\n", path, g_touch.count, g_touch.drop ? "(测试丢弃输出)" : ""); } +#include +#include +static void *live_test_thread(void *arg) { + FILE *f = fopen((const char *)arg, "r"); if (!f) { fprintf(stderr, "[dm] 【红】DM_TEST_LIVE 打不开 %s\n", (const char *)arg); return NULL; } + char line[160]; double t0 = (double)now_ns() / 1e9; int n = 0; + while (fgets(line, sizeof line, f)) { double sec; char op[8]; float x = 0, y = 0; if (line[0] == '#' || sscanf(line, "%lf %7s %f,%f", &sec, op, &x, &y) < 2) continue; + double wait = sec - ((double)now_ns() / 1e9 - t0); if (wait > 0) usleep((useconds_t)(wait * 1e6)); + dm_touch_host_live(!strcmp(op, "down") ? 0 : !strcmp(op, "move") ? 1 : 2, x / 2868, y / 1320); n++; } + fclose(f); fprintf(stderr, "[dm] DM_TEST_LIVE:%d 条发完\n", n); return NULL; +} +void dm_touch_host_step(uint64_t now, uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry); +void dm_touch_host_live_enable(void) { // 前端开窗后、客体线程起来之前调一次 | Called once after the front end opens the window and before the guest threads start + if (g_live_on) return; + if (!g_touch.ready) touch_init(0); // 同时带了触点脚本(测试)就照常装载 | If a touch script (test) is given as well, it is loaded as usual + if (!g_touch.enabled) { dm_tc_init(&g_touch.state, 2868, 1320); g_touch.state.mouse_click_mode = 1; g_touch.enabled = 1; + void uimsg_subscribe(void (*fn)(const char *, const char *, const char *)); uimsg_subscribe(touch_uimsg); } + dm_tc_set_joy_block(&g_touch.state, 1); dm_tc_enable_targets(&g_touch.state, 0); + g_live_on = 1; dm_pad_hook = dm_touch_host_step; fprintf(stderr, "[dm] 鼠标:接到触屏状态机(点目标 / 点界面;没有触屏圆钮与摇杆)\n"); + // 测试开关 DM_TEST_LIVE=<文件>(没人操作窗口时验这条路):每行「秒 down|move|up x,y」,坐标按 2868×1320,秒 = 从这里起的墙钟;到点调上面的 dm_touch_host_live, + // 与真鼠标只差「系统鼠标事件 → 归一化坐标」那三行 + // Test switch DM_TEST_LIVE= (to verify this path when nobody operates the window): each line is "seconds down|move|up x,y", coordinates on a 2868×1320 basis, seconds = wall clock from here; at that time the dm_touch_host_live above is called, + // differing from a real mouse only by the three lines "system mouse event -> normalized coordinates" + if (getenv("DM_TEST_LIVE")) { pthread_t th; pthread_create(&th, NULL, live_test_thread, strdup(getenv("DM_TEST_LIVE"))); pthread_detach(th); } +} int dm_touch_host_enabled(void) { return getenv("DM_TOUCH_SCRIPT") && *getenv("DM_TOUCH_SCRIPT"); } @@ -119,6 +156,19 @@ void dm_touch_host_game_start(uint64_t now) { void dm_touch_host_step(uint64_t now, uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) { if (!g_touch.ready) touch_init(now); + if (g_live_on) { // 真鼠标:前端页直通界面点击;局内并进事件表(拍 = 此刻),与脚本事件同一段处理 | Real mouse: on front-end pages it goes straight to a UI click; in game it joins the event table (tick = now) and is handled in the same pass as script events + int dm_uiscreen_ingame(void); int in = dm_uiscreen_ingame(); static float px, py; unsigned h; + if (in && !g_live_based) { g_live_based = 1; g_live_tick0 = touch_cur_tick(); if (!g_touch.based) { g_touch.started = 1; g_touch.based = 1; g_touch.loaded = 1; g_touch.tick_set = 1; g_touch.start_tick = g_live_tick0; g_touch.to_game_tick = g_live_tick0; } } + if (!in) g_live_based = 0; + while ((h = atomic_load(&g_live.head)) != atomic_load(&g_live.tail)) { + int op = g_live.q[h % 64].op; float nx = g_live.q[h % 64].nx, ny = g_live.q[h % 64].ny; if (op != 2) { px = nx; py = ny; } + if (!in) { dm_ui_touch(op, px, py); atomic_store(&g_live.head, h + 1); continue; } + if (g_touch.next == g_touch.count) g_touch.next = g_touch.count = 0; // 表里的都处理完了:从头复用 | Everything in the table has been handled: reuse from the start + if (g_touch.count >= 256) break; + touch_event *e = &g_touch.event[g_touch.count++]; e->beat = 0; e->slot = 0; e->op = op == 0 ? TOUCH_DOWN : op == 1 ? TOUCH_MOVE : TOUCH_UP; e->x = px * 2868; e->y = py * 1320; + atomic_store(&g_live.head, h + 1); + } + } if (!g_touch.enabled || !g_touch.started) return; uint32_t tick = touch_cur_tick(); if (!g_touch.prefix && !g_touch.tick_set) { g_touch.to_game_tick = tick; g_touch.tick_set = 1; } diff --git a/dm/i18n/ui_text.tsv b/dm/i18n/ui_text.tsv index eead8b6..37ba95e 100644 --- a/dm/i18n/ui_text.tsv +++ b/dm/i18n/ui_text.tsv @@ -300,3 +300,19 @@ dmPadLegIdentify 捡起(按住鉴定) Pick Up (Hold to Identify) 手柄模 dmPadDiffLine 游戏难度:%d Game Difficulty: %d 手柄版暂停菜单的难度行(dm_padmode.c);英文 = 原版 ui[OptionsMenuGameDifficulty]「Game Difficulty」 dmRiftGamAfterEn 通关本层后 After This Level 大秘境面板赌博区英文版的小标题行(中文界面不用:中文是「通关后暗金 / 通关后套装」两行) dmRiftMsNEn 每档另得 符文 · 赦免之证 · 打孔 + Rune, Token of Absolution, Sockets 大秘境面板右上那句的英文版控件(物品名 = 暗黑 2 原版 item-modifiers[toa]「Token of Absolution」、ui[Addsocketsui]「Add sockets」) +dmAppQuit 退出 D2R Mobile Quit D2R Mobile Mac App 菜单栏(host/front_mac.m) +dmAppOK 好 OK Mac App 提示框的按钮(host/app_mac.m,下同) +dmAppPickUse 用这个文件夹 Use This Folder 选资源文件夹对话框的确认按钮 +dmAppPickMsg 请选择游戏资源文件夹(里面有 data 文件夹)。只需要选这一次。 Choose the game data folder (the one that contains a “data” folder). You only need to do this once. 第一次启动选资源文件夹时对话框上的说明 +dmAppPickAgain %s\n\n请重新选择游戏资源文件夹。 %s\n\nPlease choose the game data folder again. 选错后再弹对话框时的说明(%s = 上一次的原因) +dmAppNotRomfsTitle 这不是游戏资源文件夹 This is not the game data folder 选错文件夹的提示框标题 +dmAppNotRomfs 「%s」里没有 data/build_manifest.psv。\n要选的是游戏资源文件夹:里面有一个 data 文件夹,data 里有 build_manifest.psv 和若干很大的数据文件。 “%s” has no data/build_manifest.psv.\nChoose the game data folder: it contains a “data” folder with build_manifest.psv and several very large data files. 选错文件夹的原因(%s = 所选文件夹名) +dmAppNoRead 找到了资源清单,但没有读取权限。 The data manifest was found but cannot be read. 资源清单读不了 +dmAppRomfsGone 上次选的资源文件夹用不了了:\n%s The data folder chosen last time can no longer be used:\n%s 上次选的文件夹失效(挪走 / 删了 / 外接盘没插) +dmAppBrokenTitle 这个 App 不完整 This app is incomplete 包里缺程序文件 +dmAppBroken 包里没有程序文件(Contents/Resources/product)。请重新构建或重新下载。 The app bundle has no program files (Contents/Resources/product). Rebuild it or download it again. 同上的正文 +dmAppMenuView 显示 View Mac App 菜单栏(host/front_mac.m,下同) +dmAppFullscreen 全屏 Toggle Full Screen 显示菜单的全屏项 +dmAppMenuHelp 帮助 Help 帮助菜单 +dmAppKeysTitle 键盘与手柄按键对照 Keyboard and Controller Buttons 帮助菜单的键位对照项,也是那一页的标题 +dmAppKeysText 界面上的按键提示是手柄字母,键盘这样对应:\n\n移动:W A S D(左摇杆)\n十字键:方向键\nA 确认:J  B 返回:K  X:U  Y:I\nL:Q  R:E  ZL:Z  ZR:C\n按左摇杆:F  按右摇杆:G\n+(菜单):回车  −(地图):Tab\n\n鼠标:左键点目标或界面,右键 = B,滚轮滚列表。\n接上手柄可以直接用。这一页以后在「帮助」菜单里。 On-screen button hints use controller letters. Keyboard mapping:\n\nMove: W A S D (left stick)\nD-pad: arrow keys\nA confirm: J B back: K X: U Y: I\nL: Q R: E ZL: Z ZR: C\nPress left stick: F Press right stick: G\n+ (menu): Return − (map): Tab\n\nMouse: left click a target or the interface, right click = B, wheel scrolls lists.\nA connected controller works right away. This page stays in the Help menu. 键位对照正文(首次启动弹一次) diff --git a/dm/ios/tools/gen_romfs_overlay.py b/dm/ios/tools/gen_romfs_overlay.py index 398cf7d..87bd8ee 100644 --- a/dm/ios/tools/gen_romfs_overlay.py +++ b/dm/ios/tools/gen_romfs_overlay.py @@ -64,7 +64,7 @@ with tempfile.TemporaryDirectory() as t: tpad=os.path.join(t,'pad'); os.makedirs(tpad); PR={} lp,lt=touch_layout.read_layout(romfs,pouch_layout.INV); o=os.path.join(tpad,'pad_inv.json'); open(o,'w',encoding='utf-8').write(touch_layout.pad_inv_rw(lt)); PR[lp.lower()]=o for rel,gd in (('controller/pauselayoutgardenhd.json',1),('controller/pauselayouthd.json',0)): # 手柄版暂停菜单:一键重开 / 切换难度 / 存放 / 分享诊断日志 | Controller pause menu: one-tap restart / change difficulty / Deposit / Share Diagnostics - lp,lt=touch_layout.read_layout(romfs,rel); o=os.path.join(tpad,'pad_pause%d.json'%gd); open(o,'w',encoding='utf-8').write(touch_layout.pad_pause(lt,gd)); PR[lp.lower()]=o + lp,lt=touch_layout.read_layout(romfs,rel); o=os.path.join(tpad,'pad_pause%d.json'%gd); open(o,'w',encoding='utf-8').write(touch_layout.pad_pause(lt,gd,share=not os.environ.get('DM_OVERLAY_MAC'))); PR[lp.lower()]=o # 大秘境面板(借「消息记录」面板外壳,touch_layout._rift_panel):手柄版同一份。少了它手柄模式点秘境门开出来的是空的原版消息记录面板、进不了秘境;手柄键在 dm_rift_ui.c # Greater Rift panel (borrows the shell of the "Message Log" panel, touch_layout._rift_panel): the controller version uses the same one. Without it, # tapping the Rift portal in controller mode opens an empty original Message Log panel and the Rift cannot be entered; the controller keys are in diff --git a/dm/ios/tools/touch_layout.py b/dm/ios/tools/touch_layout.py index e14b66e..86ebe96 100644 --- a/dm/ios/tools/touch_layout.py +++ b/dm/ios/tools/touch_layout.py @@ -623,12 +623,13 @@ def _pause_no_help(ys, hide=('Help',), restart_y=None, extra=()): # "Options" is fixed on the fourth row (y 653): when the original gamepad UI opens the pause menu the free cursor is at the centre of the screen and highlights whichever row it rests on, and pressing confirm straight away activates it -- the centre row may only be one whose press has no consequence. # "Game Difficulty: N" = one press raises the player-count setting by 1 (back to 1 after 8), with the current setting shown on this row; "Deposit" = the same thing as the "Deposit" button of the inventory (the gamepad focus cannot reach that button), using the original string @strGoldDeposit. # Button image height is 120 units: in the version with the Chronicle, seven rows are spaced evenly by 125 between the original first and last rows (278–1028); the classic version's own background only fits four rows, so the background of the Chronicle version (same size) is used and the first six rows are laid out with the same spacing (without the Chronicle row, the following row moves up) -def pad_pause(s, garden): +def pad_pause(s, garden, share=True): # share=False(Mac App):没有系统分享面板,「分享诊断日志」行不放 | share=False (Mac App): there is no system share sheet, so the "Share Diagnostics" row is left out ex = (('TouchPadDiff', '', 278), ('TouchPadStore', '@strGoldDeposit', 778)); y = 278 - if garden: s = _pause_no_help({'Settings': (428, 653), 'Exit': (728, 403), 'Chronicle': (1028, 903), 'MessageLog': (278, 1028)}, hide=('Help', 'LootFilter'), restart_y=528, extra=ex)(s)[0] + sh = lambda y0, y1: {'MessageLog': (y0, y1)} if share else {}; hs = () if share else ('MessageLog',) + if garden: s = _pause_no_help({'Settings': (428, 653), 'Exit': (728, 403), 'Chronicle': (1028, 903), **sh(278, 1028)}, hide=('Help', 'LootFilter') + hs, restart_y=528, extra=ex)(s)[0] else: s = _sub1(s, '"filename": "Controller/Panel/EscapeMenu/EscapeOptionsBGClassic"', '"filename": "Controller/Panel/EscapeMenu/EscapeOptionsBG"') - s = _pause_no_help({'Settings': (578, 653), 'Exit': (878, 403), 'MessageLog': (428, 903)}, hide=('Help',), restart_y=528, extra=ex)(s)[0] + s = _pause_no_help({'Settings': (578, 653), 'Exit': (878, 403), **sh(428, 903)}, hide=('Help',) + hs, restart_y=528, extra=ex)(s)[0] # 「游戏难度:N」的字:菜单开着时游戏停拍、原版系统通知要关了菜单才出,所以当前档位直接写在这一行上——按钮自己不带字,上面叠一个同字体的文字控件,宿主写(dm_padmode.c) # Text of "Game Difficulty: N": while the menu is open the game stops ticking and the original system notification only appears once the menu is closed, # so the current setting is written directly on this row. The button itself carries no text; a text widget with the same font is stacked on top and diff --git a/dm/tools/mac_app.sh b/dm/tools/mac_app.sh new file mode 100755 index 0000000..2d1a587 --- /dev/null +++ b/dm/tools/mac_app.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# 把 Mac 宿主包成能双击起的 macOS App:mac_app.sh [输出目录] 产出 <输出目录>/D2R Mobile.app(缺省 $DM_ROOT/out/macapp) +# 包里有:宿主程序、改写后的游戏程序(产物目录,种类 DM_MAC_PRODUCT,缺省 touch)、有界面覆盖层就带上(DM_MAC_OVERLAY=<目录>)。 +# DM_MAC_LINK=1:不带派生物的出法——改写后的游戏程序、着色器库、界面覆盖层都是从游戏内容派生的,公开发布的包不能带; +# 这样出的包里只有宿主程序和 Resources/paths.txt(三项各指向本机构建产物的路径),只在构建它的这台机器上能跑。 +# 游戏资源不进包:第一次启动请玩家选资源文件夹(host/app_mac.m)。签名用本地临时签名,本机直接能跑。 +# Package the Mac host as a macOS App that starts on double-click: mac_app.sh [output dir] produces /D2R Mobile.app (default $DM_ROOT/out/macapp) +# The package holds: the host program, the rewritten game program (build output directory, kind DM_MAC_PRODUCT, default touch), and the UI overlay when there is one (DM_MAC_OVERLAY=). +# DM_MAC_LINK=1: the build without derived content -- the rewritten game program, the shader library and the UI overlay are all derived from game content and must not be in a publicly released package; +# a package built this way holds only the host program and Resources/paths.txt (three entries, each pointing at a build output on this machine) and runs only on the machine that built it. +# Game resources never go into the package: on first launch the player is asked to choose the resource folder (host/app_mac.m). Signing is local ad-hoc signing, which runs on this machine directly. +set -eu +HERE=$(cd "$(dirname "$0")" && pwd); DM=$HERE/..; ROOT=${DM_ROOT:-$HOME/dm-work} +OUT=${1:-$ROOT/out/macapp}; KIND=${DM_MAC_PRODUCT:-touch}; BID=${DM_MAC_BUNDLE_ID:-org.d2rmobile.mac} +P=$(bash "$HERE/product.sh" path "$KIND"); [ -f "$P/main.patched.bin" ] || { echo "🔴 没有产物 ${P}(先跑 product.sh build)"; exit 2; } +make -C "$DM/host" > /dev/null +APP="$OUT/D2R Mobile.app"; rm -rf "$APP"; mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources" +cp "$DM/host/dmhost" "$APP/Contents/MacOS/D2RMobile" +LINK=${DM_MAC_LINK-1}; [ "$LINK" != 0 ] || LINK=; RES="$APP/Contents/Resources"; : > "$RES/paths.txt" +if [ -n "$LINK" ]; then echo "product=$P" >> "$RES/paths.txt"; else cp -R "$P" "$RES/product"; fi +cp "$DM/gfx/nvn/shader_map.tsv" "$APP/Contents/Resources/shader_map.tsv" +[ ! -f "$DM/gfx/nvn/c1_full.tsv" ] || cp "$DM/gfx/nvn/c1_full.tsv" "$APP/Contents/Resources/c1_full.tsv" # 图形后端按「与映射表同目录」找它 | The graphics backend looks for it "in the same directory as the mapping table" +# 编好的着色器库(Mac 版,dmsh_build.py 出的):只带运行要用的 .metallib 与反射 .json,源码 .metal 不带 +# The compiled shader library (Mac variant, produced by dmsh_build.py): only the .metallib and reflection .json needed at run time are included, not the .metal sources +V=$(sed -n 's/.*DMSH_CHAIN "\(.*\)".*/\1/p' "$DM/gfx/nvn/dmsh_chain.h"); MSL=${DM_MSL_DIR:-$ROOT/build/cache/metal_shader_cache}/b-$V +[ -d "$MSL" ] || { echo "🔴 没有着色器库 ${MSL}(先跑 dm/gfx/tools/dmsh_build.py)"; exit 2; } +if [ -n "$LINK" ]; then echo "msl=$(dirname "$MSL")" >> "$RES/paths.txt" +else mkdir -p "$RES/msl/b-$V"; rsync -a --include='*.metallib' --include='*.json' --exclude='*' "$MSL/" "$RES/msl/b-$V/"; fi +# 界面覆盖层(自定义页、珍宝匣、秘境等我们的页面都在里面):从游戏资源现生成(约 3 秒);DM_MAC_OVERLAY=<目录> 用现成的,=none 不带(原版界面) +# UI overlay (the Custom page, the trove, rifts and our other pages all live in it): generated on the spot from the game resources (about 3 seconds); DM_MAC_OVERLAY= uses an existing one, =none leaves it out (original UI) +if [ "${DM_MAC_OVERLAY:-}" != none ]; then + OVD="$RES/romfs_overlay"; [ -z "$LINK" ] || { OVD="$OUT/romfs_overlay.local"; rm -rf "$OVD"; echo "romfs_overlay=$OVD" >> "$RES/paths.txt"; } + if [ -n "${DM_MAC_OVERLAY:-}" ]; then cp -R "$DM_MAC_OVERLAY" "$OVD" + else DM_OVERLAY_MAC=1 python3 "$DM/ios/tools/gen_romfs_overlay.py" "${DM_ROMFS_SRC:-$ROOT/data/switch/3.3.94012/Update/RomFS}" "$OVD" > /dev/null || { echo "🔴 界面覆盖层生成失败"; exit 2; }; fi +fi +[ -s "$RES/paths.txt" ] || rm -f "$RES/paths.txt" +VER=$(cat "$DM/PRODUCT") +cat > "$APP/Contents/Info.plist" < + + +CFBundleNameD2R Mobile +CFBundleDisplayNameD2R Mobile +CFBundleIdentifier$BID +CFBundleExecutableD2RMobile +CFBundlePackageTypeAPPL +CFBundleShortVersionString$VER +CFBundleVersion$(git -C "$DM" rev-parse --short HEAD 2>/dev/null || echo 0) +LSMinimumSystemVersion13.0 +NSHighResolutionCapable +LSApplicationCategoryTypepublic.app-category.role-playing-games +GCSupportsControllerUserInteraction + +PL +codesign --force -s - "$APP" > /dev/null 2>&1 || { echo "🔴 本地签名失败"; exit 3; } +echo "MACAPP ${APP}(产物 $(basename "$P"),$(du -sh "$APP" | cut -f1)${LINK:+,不带派生物:只能在本机跑})" diff --git a/docs/MAC.md b/docs/MAC.md new file mode 100644 index 0000000..f7a77f9 --- /dev/null +++ b/docs/MAC.md @@ -0,0 +1,66 @@ +# Playing on a Mac (macOS App, first version) + +中文:[MAC.zh-CN.md](MAC.zh-CN.md) + +On an Apple silicon Mac this project can be built into a native macOS App, `D2R Mobile.app`: double-click to start, with keyboard, mouse and gamepad all working. It runs the same game and the same features we added (rifts, the trove, the chronicle, the Custom page and so on), using the original game's gamepad UI. + +**Up front: nobody has actually sat down and played this version yet.** Keyboard keys, a physical gamepad, the resource-folder dialog, ⌘Q and menu clicks, and how it feels in the hand — none of these five has been operated by a person. Everything described as "verified" below was run unattended: keys injected by a test script, the mouse through a test entry point, quit / full screen / window resizing through test switches. If you are among the first to try it, please open an issue and tell us how it went. + +## Build + +The prerequisites are the same as for the iOS route: your game files in place and `./setup.sh` finished (see "Getting started" on the front page). Then: + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +dm/tools/mac_app.sh +``` + +It takes a dozen seconds or so and produces `~/dm-work/out/macapp/D2R Mobile.app` (about 3 MB). To put it elsewhere: `dm/tools/mac_app.sh `. + +The App contains only our own program. The rewritten game program, the shader library and the UI overlay are made from your game files; they stay in your workspace (`~/dm-work`) and the App only records where they are — so **this App runs only on the Mac that built it**. Please do not copy it to anyone else, and do not delete the workspace. It is signed with a local ad-hoc signature: no developer account and no device registration are needed. + +## First launch + +Double-click `D2R Mobile.app`. The first launch asks you to choose the **game resource folder**: pick `~/dm-work/data/switch/3.3.94012/Update` (or the `RomFS` inside it); it must contain a `data` folder. A wrong choice is explained and you can pick again; a right one is remembered and not asked for again. + +The key mapping is then shown once; afterwards it is always available under Help in the menu bar. + +## Where things are + +- Saves: `~/Library/Application Support/D2R Mobile/save` +- Log: `~/Library/Logs/D2R Mobile/host.log` (the previous run is `host.prev.log`). Please attach it when reporting a problem. + +## Keyboard ↔ gamepad + +Button prompts on screen show gamepad letters; the keyboard keys are: + +| Gamepad | Keyboard | +|---|---| +| Left stick (move) | W A S D | +| D-pad | Arrow keys | +| A confirm / B back / X / Y | J / K / U / I | +| L / R | Q / E | +| ZL / ZR | Z / C | +| Left stick press / right stick press | F / G | +| + (menu) / − (map) | Return / Tab | + +Mouse: left click on a target or on the UI, right click = B (back / close panel), wheel scrolls lists. A gamepad works as soon as it is connected, alongside the keyboard. + +The menu bar has View → Full Screen (⌃⌘F) and Quit (⌘Q). The window can be resized freely; the game picture stays 16:9 and centred. + +## Quitting and saving + +Closing the window, ⌘Q and Quit in the menu all save first and then quit, in any state: in game, with the pause menu open, with a panel open, in a loading screen and with the rift panel open were each verified once. It waits at most 3 seconds; if the save has not completed by then, the log records "quit without saving". + +## How this version is operated + +- **Move** with W A S D or the gamepad stick. A mouse click on a monster, NPC or object walks over and interacts; a click on empty ground does not move. +- **Items** — sorting, equipping, buying and selling — are handled with the keyboard or gamepad cursor: move the cursor onto the item with W A S D and press the key shown in the bottom bar. For example, buying from a vendor: cursor onto the goods (the bottom bar shows "A Buy") → press J → press J again in the confirmation. +- **The UI** is the original gamepad UI, and the pages we added (the Custom page, the trove, the chronicle, rift floor selection and so on) are all in it. + +## Not in this version yet + +- Mouse click-to-move on the ground, and long-press / double-click / drag-and-drop on items with the mouse. +- The free town portal on the empty ZR slot of the gamepad. +- The rift task list on the left. +- iCloud save sync, update checks, sharing the diagnostic log. diff --git a/docs/MAC.zh-CN.md b/docs/MAC.zh-CN.md new file mode 100644 index 0000000..b38a853 --- /dev/null +++ b/docs/MAC.zh-CN.md @@ -0,0 +1,66 @@ +# 在 Mac 上玩(macOS App,第一版) + +English: [MAC.md](MAC.md) + +Apple 芯片的 Mac 可以把本项目构建成一个原生的 macOS App:`D2R Mobile.app`,双击启动,键盘、鼠标、手柄都能用。它跑的是同一份游戏、同一套我们加的功能(秘境、珍宝匣、编年史、自定义页等),界面用的是原版的手柄版界面。 + +**先说在前面:这一版还没有人真的坐下来玩过。**键盘按键、实体手柄、选资源文件夹的对话框、⌘Q 与菜单点击、真人手感——这五项都没有人实际操作过。下面写「验过」的,都是无人值守跑出来的:按键用测试脚本注入,鼠标用测试入口注入,退出、全屏、改窗口大小用测试开关。欢迎第一批试用的人把结果开 Issue 告诉我们。 + +## 构建 + +前提与 iOS 那条路相同:游戏文件放到位,`./setup.sh` 跑完(见首页「开始使用」)。然后: + +```bash +source ~/dm-work/build/cache/dm/venv/bin/activate +dm/tools/mac_app.sh +``` + +约十几秒,产出 `~/dm-work/out/macapp/D2R Mobile.app`(约 3 MB)。想放到别处:`dm/tools/mac_app.sh <输出目录>`。 + +这个 App 里只有我们自己的程序。改写后的游戏程序、着色器库、界面覆盖层都是从你的游戏文件做出来的,它们留在你的工作区(`~/dm-work`)里,App 只记着它们的位置——所以**这个 App 只能在构建它的这台 Mac 上跑**,请不要拷给别人,也不要删掉工作区。签名用的是本机临时签名,不需要开发者账号,也不需要登记设备。 + +## 第一次打开 + +双击 `D2R Mobile.app`。第一次启动会请你选**游戏资源文件夹**:选 `~/dm-work/data/switch/3.3.94012/Update`(或它里面的 `RomFS`)即可,里面要有 `data` 文件夹。选错了会说明原因并让你重选;选对之后会记住,下次不再问。 + +接着会弹一次键位对照表,之后在菜单栏「帮助」里随时能看。 + +## 东西放在哪 + +- 存档:`~/Library/Application Support/D2R Mobile/save` +- 日志:`~/Library/Logs/D2R Mobile/host.log`(上一次运行的是 `host.prev.log`)。报问题时请附上它。 + +## 键盘 ↔ 手柄 + +界面上的按键提示显示的是手柄字母,对应的键盘按键如下: + +| 手柄 | 键盘 | +|---|---| +| 左摇杆(移动) | W A S D | +| 十字键 | 方向键 | +| A 确认 / B 返回 / X / Y | J / K / U / I | +| L / R | Q / E | +| ZL / ZR | Z / C | +| 按左摇杆 / 按右摇杆 | F / G | +| +(菜单)/ −(地图) | 回车 / Tab | + +鼠标:左键点目标或界面,右键 = B(返回 / 关面板),滚轮滚列表。接上手柄直接可用,与键盘并存。 + +菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小,游戏画面保持 16:9 居中。 + +## 退出与存盘 + +关窗口、⌘Q、菜单里点退出,在任何状态下都会先存盘再退:局内、暂停菜单开着、面板开着、读取画面、秘境面板开着各验过一局。最多等 3 秒;到点还没存成,会在日志里记一行「未存盘退出」。 + +## 这一版的操作方式 + +- **移动**用 W A S D 或手柄摇杆。鼠标点到怪物、NPC、物件会走过去交互;点空地不会走。 +- **物品**的整理、穿脱、买卖用键盘或手柄的光标操作:W A S D 把光标移到物品上,按底栏提示的键。例如在商人处买东西:光标移到货物上(底栏出现「A 购买」)→ 按 J → 确认框里再按 J。 +- **界面**是原版的手柄版界面,我们加的页面(自定义页、珍宝匣、编年史、秘境选层等)都在里面。 + +## 这一版还没有的 + +- 鼠标点地面走路、鼠标对物品的长按 / 双击 / 拖放。 +- 手柄上 ZR 空格的免费回城。 +- 秘境左侧的任务栏。 +- iCloud 存档同步、更新检查、分享诊断日志。 diff --git a/setup.sh b/setup.sh index aaaa635..2636ee7 100755 --- a/setup.sh +++ b/setup.sh @@ -181,3 +181,4 @@ echo " source $DM_ROOT/build/cache/dm/venv/bin/activate" echo " 然后出 App:cd dm/ios && ./run.sh build(先在 dm/ios/local.env 里填 DM_TEAM_ID 与 DM_BUNDLE_ID;缺省同时面向 iPhone 与 iPad,只要 iPhone 加 DM_DEVICE_FAMILY=1)" echo " Next, enter the Python environment setup prepared (the build and test scripts need the packages in it): source $DM_ROOT/build/cache/dm/venv/bin/activate" echo " Then build the app: cd dm/ios && ./run.sh build (fill DM_TEAM_ID and DM_BUNDLE_ID in dm/ios/local.env first; it targets both iPhone and iPad by default, add DM_DEVICE_FAMILY=1 for iPhone only)" +echo " $(m "想在这台 Mac 上直接玩:dm/tools/mac_app.sh 出一个 macOS App(见 docs/MAC.zh-CN.md)" "To play on this Mac directly: dm/tools/mac_app.sh builds a macOS App (see docs/MAC.md)")"