Merge upstream v1.0.15 into android-port

Conflicts resolved: hle_audio.c keeps the AAudio downmix on Android and takes
upstream's 5.1 downmix on Apple; hle_nvn.c keeps mtl_queue_flush / ADPF pacing
on Android. Android translates synchronously on the submit thread for now (the
Vulkan backend's fence also counts readback commits); Vulkan gets no-op
mtl_host_latch / mtl_host_apply; compat adds pthread_attr_set_qos_class_np.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 10:07:20 +09:00
co-authored by Claude Opus 5.5
57 changed files with 2003 additions and 396 deletions
+79 -1
View File
@@ -21,6 +21,7 @@
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#endif
#import <Network/Network.h>
#include <signal.h>
#include <sys/clonefile.h>
#include <stdatomic.h>
@@ -28,6 +29,8 @@
#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_cloud_inbox_add(const char *save, const char *statef, const char *pack); uint64_t dm_cloud_pack_stamp(const char *pack);
int dm_cloud_bak_pack(const char *bak, const char *unit, const char *pack, const char *why); void dm_cloud_char_conflict_note(const char *unit);
int dm_custom_get(const char *key);
extern void (*g_dm_save_commit_hook)(const char *commit_dir);
@@ -54,10 +57,39 @@ static int pending_downloads(int start) { // 还没下载好的包数;start
}
return n;
}
// iCloud 自己的同名文件冲突(两台各写了一份同名包、系统挑了一份当现行版,其余成「未解决的冲突版本」;iCloud 离线冲突第 1 条)。启动同步前在文件协调里做:
// 共享仓库:每个冲突版本收进待合并收件箱(dm_cloud_inbox_add,现行版照常走同步);
// 角色:包头时刻(游戏最后写它的时刻)最新的那份当现行版(不是系统挑的就换上去),其余整份进备份,记名进局提示。
// 全部收好才把冲突标成已解决并删掉其余版本;有一份收不进就都留着,下次启动再来(宁可多留不丢)。
// iCloud's own same-name file conflict (two devices each wrote a same-name pack, the system picked one as the current version and the rest became "unresolved conflict versions"; iCloud offline conflict item 1). Done inside file coordination before the launch sync:
// shared stash: each conflict version is stored in the to-merge inbox (dm_cloud_inbox_add; the current version goes through sync as usual);
// character: the copy with the newest pack header timestamp (the moment the game last wrote it) becomes the current version (swapped in if it is not the one the system picked), the rest go into the backup whole, and the name is recorded for a notice after entering a run.
// Only once everything is stored are the conflicts marked resolved and the other versions deleted; if any one cannot be stored, all are kept and tried again at the next launch (better keep extra than lose any).
static void take_conflicts(NSString *save) {
NSFileManager *fm = NSFileManager.defaultManager;
for (NSString *f in [fm contentsOfDirectoryAtPath:g_cloud error:nil] ?: @[]) {
if ([f hasPrefix:@"."] || ![f hasSuffix:@".pack"]) continue;
NSURL *u = [NSURL fileURLWithPath:[g_cloud stringByAppendingPathComponent:f]]; NSArray<NSFileVersion *> *vs = [NSFileVersion unresolvedConflictVersionsOfItemAtURL:u];
if (!vs.count) continue;
NSString *unit = f.stringByDeletingPathExtension; int bad = 0;
if ([unit isEqualToString:@"_stash"]) { for (NSFileVersion *v in vs) bad |= dm_cloud_inbox_add(save.fileSystemRepresentation, g_state.fileSystemRepresentation, v.URL.fileSystemRepresentation) != 0; }
else { uint64_t best = dm_cloud_pack_stamp(u.fileSystemRepresentation); NSFileVersion *win = nil;
for (NSFileVersion *v in vs) { uint64_t t = dm_cloud_pack_stamp(v.URL.fileSystemRepresentation); if (t > best) { best = t; win = v; } }
if (win) { NSError *e = nil; bad |= dm_cloud_bak_pack(g_bak.fileSystemRepresentation, unit.UTF8String, u.fileSystemRepresentation, "iCloud 冲突里较旧的现行版") != 0;
if (!bad && ![win replaceItemAtURL:u options:0 error:&e]) { bad = 1; LOG("【红】iCloud 同步:%s 换上较新的冲突版本失败 %s", unit.UTF8String, e.localizedDescription.UTF8String ?: "?"); } }
for (NSFileVersion *v in vs) if (v != win) bad |= dm_cloud_bak_pack(g_bak.fileSystemRepresentation, unit.UTF8String, v.URL.fileSystemRepresentation, "iCloud 冲突版本") != 0;
if (!bad) dm_cloud_char_conflict_note(unit.UTF8String); }
if (bad) { LOG("【红】iCloud 同步:%s 有 %lu 个冲突版本没收好,留着下次启动再来", unit.UTF8String, (unsigned long)vs.count); continue; }
for (NSFileVersion *v in vs) v.resolved = YES;
NSError *e = nil; if (![NSFileVersion removeOtherVersionsOfItemAtURL:u error:&e]) LOG("iCloud 同步:%s 冲突已标解决,删其余版本没成(%s),不影响", unit.UTF8String, e.localizedDescription.UTF8String ?: "?");
LOG("iCloud 同步:%s 的 %lu 个 iCloud 冲突版本已收好(%s)", unit.UTF8String, (unsigned long)vs.count, [unit isEqualToString:@"_stash"] ? "进待合并收件箱" : "最新的当现行版、其余进备份");
}
}
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); }];
(void)u; if (down) take_conflicts(save); // 只在启动那次(运行中 save 是提交快照目录,不放收件箱) | only at launch (while running, save is the commit snapshot directory; nothing goes into the inbox)
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;
}
@@ -187,6 +219,51 @@ static int migrate_v2(NSString *docs, double deadline) {
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;
}
// 从没同步成功过的设备先看清云端再同步(iCloud 离线冲突第 2 条):新设备断网首启时,系统还没把云端条目列到本机,云端目录看着是空的——
// 照常同步会把本机全部当「云端没有」上传(离线时新建的穷共享仓库联网后与云端同名包冲突、盖掉云端),迁移那步还会新建一个空的 saves_v2。
// 所以状态文件里一条记录都没有(从没同步成功过)时,先问系统的云端条目列表(NSMetadataQuery,收集完成才算数):
// 列出了包 → 这些包都已出现在本机目录(下好的或 iCloud 占位)才同步;列表是空的 → 网络通才同步(世界上第一台设备就是这种)。都不满足 = 本次整套跳过,下次启动再看。
// 列表收集完成在断网时怎么表现、联网时空列表会不会滞后,要真机断网跑才知道(排给池);滞后漏过去的那种由冲突版本合并兜住(第 1 条)。
// 测试开关 DM_TEST_ICLOUD_FIRST=<收集完成>,<列出几个>,<到本机几个>,<网络通>:不问系统,按给的值判(Mac 宿主 / 本地测试云端验分支用)
// A device that has never synced successfully first gets a clear view of the cloud before syncing (iCloud offline conflict item 2): on a new device's first launch without network, the system has not yet listed the cloud entries locally, so the cloud directory looks empty -
// a normal sync would upload everything local as "not in the cloud" (a poor shared stash newly created offline conflicts with the cloud's same-name pack once online and overwrites the cloud), and the migration step would also create an empty saves_v2.
// So when the state file has no record at all (never synced successfully), first ask the system for its list of cloud entries (NSMetadataQuery, counted only once gathering has finished):
// packs are listed -> sync only once all of them have appeared in the local directory (downloaded or as iCloud placeholders); the list is empty -> sync only if the network is reachable (the very first device in the world is like this). Neither = skip the whole thing this time and look again at the next launch.
// How gathering completes with no network, and whether an empty list can lag behind when online, can only be known by running on a device with the network cut (queued for the pool); the lagging case that slips through is covered by merging conflict versions (item 1).
// Test switch DM_TEST_ICLOUD_FIRST=<gathering done>,<how many listed>,<how many local>,<network reachable>: does not ask the system and decides by the given values (for verifying the branches on the Mac host / a local test cloud)
static int never_synced(NSString *statef) {
NSString *t = [NSString stringWithContentsOfFile:statef encoding:NSUTF8StringEncoding error:nil];
return !t || [t rangeOfString:@"\t"].location == NSNotFound;
}
static int first_listing_ok(double deadline) {
int got = 0, listed = 0, present = 0, net = 0; const char *e = getenv("DM_TEST_ICLOUD_FIRST");
if (e) { sscanf(e, "%d,%d,%d,%d", &got, &listed, &present, &net); }
else {
__block int g = 0, n = 0, pr = 0; dispatch_semaphore_t sem = dispatch_semaphore_create(0); __block NSMetadataQuery *q = nil; __block id obs = nil;
dispatch_async(dispatch_get_main_queue(), ^{ // 元数据查询要挂在有运行循环的线程上 | the metadata query has to be attached to a thread with a run loop
q = [NSMetadataQuery new]; q.searchScopes = @[NSMetadataQueryUbiquitousDocumentsScope];
q.predicate = [NSPredicate predicateWithFormat:@"%K LIKE '*.pack'", NSMetadataItemFSNameKey];
obs = [NSNotificationCenter.defaultCenter addObserverForName:NSMetadataQueryDidFinishGatheringNotification object:q queue:nil usingBlock:^(NSNotification *note) { (void)note;
[q disableUpdates]; n = (int)q.resultCount; NSFileManager *fm = NSFileManager.defaultManager;
for (NSUInteger i = 0; i < q.resultCount; i++) { NSURL *u = [[q resultAtIndex:i] valueForAttribute:NSMetadataItemURLKey]; if (!u) continue;
NSString *ph = [u.path.stringByDeletingLastPathComponent stringByAppendingPathComponent:[NSString stringWithFormat:@".%@.icloud", u.lastPathComponent]];
if ([fm fileExistsAtPath:u.path] || [fm fileExistsAtPath:ph]) pr++; }
g = 1; [q stopQuery]; [NSNotificationCenter.defaultCenter removeObserver:obs]; dispatch_semaphore_signal(sem); }];
if (![q startQuery]) { [NSNotificationCenter.defaultCenter removeObserver:obs]; dispatch_semaphore_signal(sem); } });
double left = deadline - CFAbsoluteTimeGetCurrent(); if (left < 0.5) left = 0.5;
if (dispatch_semaphore_wait(sem, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(left * NSEC_PER_SEC))))
dispatch_async(dispatch_get_main_queue(), ^{ if (q) { [q stopQuery]; if (obs) [NSNotificationCenter.defaultCenter removeObserver:obs]; } });
got = g; listed = n; present = pr;
__block int ns = 0; dispatch_semaphore_t ps = dispatch_semaphore_create(0); nw_path_monitor_t m = nw_path_monitor_create();
nw_path_monitor_set_queue(m, dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0));
nw_path_monitor_set_update_handler(m, ^(nw_path_t path) { if (!ns) { ns = nw_path_get_status(path) == nw_path_status_satisfied ? 1 : 2; dispatch_semaphore_signal(ps); } });
nw_path_monitor_start(m); dispatch_semaphore_wait(ps, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(NSEC_PER_SEC))); nw_path_monitor_cancel(m); net = ns == 1;
}
int ok = got && (listed ? present >= listed : net);
LOG("iCloud 同步:本机从没同步成功过,先看云端条目列表:收集%s、列出 %d 个包、已到本机 %d 个、网络%s → %s", got ? "完成" : "未完成", listed, present, net ? "通" : "不通",
ok ? "看清了,同步" : "没看清,本次不同步(不上传、不建 saves_v2),下次启动再看");
return ok;
}
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;
@@ -215,6 +292,7 @@ void dm_cloud_boot(void) {
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 (never_synced([save stringByAppendingString:@".cloudstate"]) && (!lroot || getenv("DM_TEST_ICLOUD_FIRST")) && !first_listing_ok(t0 + limit)) return;
if (!migrate_v2(docs, t0 + limit)) return;
NSString *nw = [docs stringByAppendingPathComponent:@"saves_v2"]; if (!v2_ready(nw, [save stringByAppendingString:@".cloudv2ok"])) return;
g_cloud = nw; }
+2 -1
View File
@@ -75,7 +75,8 @@ void dm_rift_hud_draw(UIView *host, CGRect wr, BOOL hide) {
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 ? @(dm_ui("dmRiftHudSame")) : h.next > h.tier ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.next] : @(dm_ui("dmRiftHudTop"))) : h.overtime ? @(dm_ui("dmRiftHudOver")) : g ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)]; // 已超时:第二行换成这一句,优先于「击败守护者」/ 进度目标(第一行照旧写第几层 / 守护者现身) | overtime: the second line becomes this sentence, taking priority over "Slay the Rift Guardian" / the progress goal (the first line still says which level / that the Guardian has appeared)
NSString *gl = h.done ? (!h.inc ? @(dm_ui("dmRiftHudSame")) : h.next > h.tier ? [NSString stringWithFormat:@(dm_ui("dmRiftHudNext")), h.next] : @(dm_ui("dmRiftHudTop"))) : h.goal == 5 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudOverKillN")), h.gdead, h.gtotal] : h.goal == 4 ? @(dm_ui("dmRiftHudOverKill")) : h.goal == 3 ? @(dm_ui("dmRiftHudOver"))
: (h.goal == 1 || h.goal == 2) && h.nwave > 1 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudKillWave")), h.wave, h.nwave, h.gdead, h.gtotal] : h.goal == 2 ? [NSString stringWithFormat:@(dm_ui("dmRiftHudKillN")), h.gdead, h.gtotal] : h.goal == 1 ? @(dm_ui("dmRiftHudKill")) : [NSString stringWithFormat:@(dm_ui("dmRiftHudGoal")), (int)(h.progress * 100)]; // 已超时:第二行换成这一句,优先于「击败守护者」/ 进度目标(第一行照旧写第几层 / 守护者现身) | overtime: the second line becomes this sentence, taking priority over "Slay the Rift Guardian" / the progress goal (the first line still says which level / that the Guardian has appeared)
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);
+1
View File
@@ -116,3 +116,4 @@ static void on_click(void) { // 宿主在游戏主线程调:玩家点了「
});
}
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
void dm_sharelog_share(void) { on_click(); } // 游戏外的界面直接调(资源下载页的「分享诊断日志」按钮,main.m AssetVC) | called directly from screens outside the game (the "Share diagnostic log" button on the asset download page, main.m AssetVC)
+16 -72
View File
@@ -750,65 +750,16 @@ static BOOL touch_done(UITouch *t) { UITouchPhase ph=t.phase; return ph==UITouch
// 底部 UI v4 的 UIKit 底栏只在「局内常态」画:维护面板开合栈,常驻 HUD 层之外任何面板开着就不画(未知面板默认让开,免挡游戏自己的画面)。
// 常驻层 = 营地无操作时 OpenPanel 后一直不关的 13 个(实测 UI 消息流)+ 存档提示 / 通知 / 组队消息 / 帮助按钮 / 手柄提示层 / 自动地图(战斗叠加)
// 名单在宿主 dm_cursor.c 的 dm_ui_panel_resident(面板状态安全阀同用一份)
// The UIKit bottom bar of bottom UI v4 is drawn only in the "normal in-run state": maintain a panel open / close stack, and do not draw when any panel other than the always-on HUD layers is open (unknown panels yield by default, to avoid covering the game's own picture).
// Always-on layers = the 13 that stay open after OpenPanel when idle in camp (measured UI message stream) + save hint / notification / party message / help button / controller hint layer / automap (combat overlay)
// The list is in the host's dm_cursor.c dm_ui_panel_resident (shared with the panel state safety valve)
enum { HUD_STACK_MAX=64 };
static struct { char name[64]; int open; } g_hud_stack[HUD_STACK_MAX];
static _Atomic int g_hud_blocked; // 栈里还开着的非常驻面板数 | Number of panels other than the always-on layers still open in the stack
// 面板开合栈搬到宿主 dm_cursor.c(dm_hud_stack_msg,Mac touch_mac.c 共用同一份);这里只记「连续多久非零」并通知 UIKit 底栏让开
// The UIKit bottom bar of bottom UI v4 is only drawn in the normal in-game state: maintain the panel stack; whenever any panel other than the resident HUD layers is open, it is not drawn (unknown panels make way by default so they do not cover the game's own picture).
// Resident layers = the 13 panels that are opened and never closed in camp when idle (measured from the UI message stream) + save notice / notifications / party messages / help button / gamepad hint layer / automap (combat overlay).
// The list is dm_ui_panel_resident in the host's dm_cursor.c (shared with the panel state safety valve).
// The panel stack moved to the host's dm_cursor.c (dm_hud_stack_msg, shared with Mac touch_mac.c); here we only track how long it has been non-zero and tell the UIKit bottom bar to make way
int dm_hud_stack_msg(const char *act, const char *arg); void dm_hud_stack_dump(void);
static _Atomic int g_hud_blocked; // 栈读数:开着的非常驻面板数(只开着 NPC 对话菜单时 -1) | Stack reading: number of open non-resident panels (-1 when only the NPC dialog menu is open)
static uint64_t g_hud_blocked_since;
static void hud_stack_message(const char *act,const char *arg) {
// 读取画面撤下:清掉此刻在游戏面板树里已经看不见的记录(防只开不关的漏配),屏上还在的照记——
// 通关页是读取画面撤下前 0.5 秒开的(OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel),原先整栈清零把它也清了:
// 底栏和技能钮盖在通关页上、点「好」变成点世界
// Loading screen removed: clear the records no longer visible in the game's panel tree at this moment (guards against open-without-close mismatches), and keep those still on screen --
// the game-completion page is opened 0.5 seconds before the loading screen is removed (OpenExclusivePanel EndScreenPanelExpansion → UnloadPanel LoadScreenPanel); previously the whole stack was zeroed, clearing it too:
// the bottom bar and skill buttons covered the game-completion page, and tapping 「好」(OK) became a world tap
if(!strcmp(act,"UnloadPanel") && !strcmp(arg,"LoadScreenPanel")) {
for(int i=0;i<HUD_STACK_MAX;i++) {
if(g_hud_stack[i].open>0 && strcmp(g_hud_stack[i].name,"LoadScreenPanel") && dm_ui_panel_shown(g_hud_stack[i].name)) fprintf(stderr,"[hud] 面板栈 读取画面撤下:%s 屏上还在,照记\n",g_hud_stack[i].name);
else memset(&g_hud_stack[i],0,sizeof g_hud_stack[i]);
}
}
else if(!strcmp(act,"UnloadAll")) memset(g_hud_stack,0,sizeof g_hud_stack);
else {
// PanelManager 的面板动作全集(读码:它的消息分发 main+0xb1dc60 只认这 8 个,与全部日志里出现过的一致):
// OpenPanel / OpenExclusivePanel = 开;ClosePanel / UnloadPanel = 关(读取画面那条见上);TogglePanel = 按当前记录翻转(高级属性页走它);
// UnloadAll = 全清(见上);LoadPanel = 预载、不上屏,不算开关;HideGameInfo = 隐藏游戏信息层,与面板开关无关
// Full set of PanelManager panel actions (from reading the code: its message dispatch main+0xb1dc60 only recognizes these 8, matching what has appeared across all logs):
// OpenPanel / OpenExclusivePanel = open; ClosePanel / UnloadPanel = close (for the loading screen one see above); TogglePanel = flip according to the current record (the advanced stats page uses it);
// UnloadAll = clear all (see above); LoadPanel = preload without showing, not counted as open or close; HideGameInfo = hide the game info layer, unrelated to panel open / close
int tog=!strcmp(act,"TogglePanel");
int open=!strcmp(act,"OpenPanel")||!strcmp(act,"OpenExclusivePanel"), close=!strcmp(act,"ClosePanel")||!strcmp(act,"UnloadPanel");
if(!open && !close && !tog) return;
if(dm_ui_panel_resident(arg)) return;
int slot=-1; for(int i=0;i<HUD_STACK_MAX;i++) if(!strcmp(g_hud_stack[i].name,arg)) { slot=i; break; }
if(slot<0) for(int i=0;i<HUD_STACK_MAX;i++) if(!g_hud_stack[i].name[0]) { slot=i; strlcpy(g_hud_stack[i].name,arg,sizeof g_hud_stack[i].name); break; }
if(slot<0) return;
if(tog) { open=g_hud_stack[slot].open<=0; close=!open; }
// 没开着就收到关闭 = 空操作,不是漏配:游戏开功能页 / 切页签时对一批互斥面板(仓库、方块、商店、小站、对话…)统一发 ClosePanel,不管开没开;
// 启动时选角页也是先关再开(读界面消息流水;之前记成红,玩家路径每次启动 14 条假红)。真漏接了打开的后果是底栏不让开,由下面 60 秒巡检兜
// A close received while not open = no-op, not a missing mapping: when opening a function page / switching tabs the game sends ClosePanel to a batch of mutually exclusive panels (storage, cube, shop, waypoint, dialog…) regardless of whether they are open;
// at launch the character select page is also closed first and then opened (from reading the UI message log; previously logged as a failure, 14 false failures per launch on the player path). The consequence of really missing an open is the bottom bar not yielding, which the 60-second patrol below covers
if(close && g_hud_stack[slot].open<=0) return;
// 按「开 / 没开」记,不按次数累加:游戏对已经开着的面板再发一次 OpenPanel 是常态——雇佣列表上的替换确认框每被关掉一次,
// 就重发一次 OpenPanel HireMenuPanel(中间没有关闭),而整段对话结束时只发固定次数的关闭。按次数加的话多出确认框两回再雇成,计数留在 1:
// 屏上已没有面板,前端却一直按面板态(没摇杆、没技能钮、点哪里都是「面板外」)。809 份日志里计数到过 2 以上的只有 4 个面板
// (主菜单链接、选角页、起名候选栏、雇佣列表),没有一个是真叠两层要关两次的。dm_tc_navigation 那一路本来就是幂等位图,两路口径一致了
// Recorded as "open / not open", not accumulated by count: the game sending OpenPanel again for an already open panel is normal -- each time the replacement confirmation box on the hire list is dismissed,
// OpenPanel HireMenuPanel is sent again (with no close in between), while at the end of the whole dialog only a fixed number of closes is sent. Adding by count, when the confirmation box comes up two extra times and the hire then succeeds, leaves the count at 1:
// no panel left on screen, yet the front end stays in panel mode (no stick, no skill buttons, every tap is "outside the panel"). Across 809 logs only 4 panels ever reached a count of 2 or more
// (main menu links, character select page, naming candidate bar, hire list), and none of them was a real two-layer stack needing two closes. The dm_tc_navigation path was already an idempotent bitmap, so the two paths now agree
if(open && g_hud_stack[slot].open>0) { fprintf(stderr,"[hud] 面板栈 %s %s:已经开着,不重复计\n",act,arg); return; }
g_hud_stack[slot].open=open?1:0;
fprintf(stderr,"[hud] 面板栈 %s %s → %d\n",act,arg,g_hud_stack[slot].open);
}
// NPC 对话菜单(交谈 / 交易…那一小列)不挡底栏:只开着它时底栏照常显示(否则 UIKit 层让开、露出游戏层那份底栏,难度格和回城书不见、腰带样子也变)。
// 编码进同一个数:对话菜单开着且没有别的面板 → -1(底栏不让开、且免除导航态的隐藏)
// The NPC dialog menu (the small column of Talk / Trade…) does not block the bottom bar: with only it open the bottom bar shows as usual (otherwise the UIKit layer yields and exposes the game layer's bottom bar; the difficulty cell and Tome of Town Portal disappear and the belt looks different too).
// Encoded into the same number: dialog menu open with no other panel → -1 (the bottom bar does not yield, and navigation-mode hiding is waived)
int n=0, dlg=0; for(int i=0;i<HUD_STACK_MAX;i++) { if(!strcmp(g_hud_stack[i].name,"NpcDialogPanel")||!strcmp(g_hud_stack[i].name,"ScrollSpeechPanel")) dlg|=g_hud_stack[i].open>0; else n+=g_hud_stack[i].open; } // ScrollSpeechPanel = NPC 说话的滚动文字框(屏幕上方一小块),同样不挡底栏 | ScrollSpeechPanel = the scrolling text box of NPC speech (a small block at the top of the screen); it likewise does not block the bottom bar
if(!n && dlg) n=-1;
int n=dm_hud_stack_msg(act,arg);
uint64_t t=now_ns();
if(n>0 && !g_hud_blocked_since) g_hud_blocked_since=t;
if(n<=0) g_hud_blocked_since=0;
@@ -823,7 +774,7 @@ static void hud_stack_message(const char *act,const char *arg) {
static void hud_stack_watch(void) {
if(g_hud_blocked_since && now_ns()-g_hud_blocked_since>60000000000ull) {
fprintf(stderr,"[hud] 面板栈已连续 60 秒非零(线索,非缺陷):");
for(int i=0;i<HUD_STACK_MAX;i++) if(g_hud_stack[i].open) fprintf(stderr,"%s×%d ",g_hud_stack[i].name,g_hud_stack[i].open);
dm_hud_stack_dump();
fprintf(stderr,"\n"); g_hud_blocked_since=now_ns();
}
}
@@ -855,7 +806,7 @@ static void touch_ui_message(const char *cat,const char *act,const char *arg) {
// 测试:DM_TOUCH_SCRIPT_START=menu 时触点脚本从主菜单出现起计时(缺省从首次进局起),前端页面的玩家路径用例用
// Test: with DM_TOUCH_SCRIPT_START=menu the touch script times from when the main menu appears (default: from first entering a run); used by player-path cases on front-end pages
if(getenv("DM_TOUCH_SCRIPT_START") && !strcmp(cat,"PanelManager") && !strcmp(act,"OpenPanel") && !strcmp(arg,"MainMenuButtonRibbon")) dispatch_async(dispatch_get_main_queue(),^{ touch_script_start(); });
int nmode=mode ? (dm_tc_scene_dead() ? 2 : dm_tc_scene_dialog_only(&scene) && atomic_load(&g_hud_blocked)<=0 ? 3 : 1) : 0; // 3 = 只开着 NPC 对话菜单(面板栈读数 -1);菜单上又开了雇佣列表这类不在名单里的页就不算(那时底栏十字不该露出来) | 3 = only the NPC dialog menu is open (panel stack reading -1); if a page not on the list such as the hire list is opened on top of the menu, it does not count (the bottom bar cross should not show then)
int nmode=dm_tc_panel_mode(mode,&scene,atomic_load(&g_hud_blocked)); // 3 = 只开着 NPC 对话菜单(面板栈读数 -1);菜单上又开了雇佣列表这类不在名单里的页就不算(那时底栏十字不该露出来) | 3 = only the NPC dialog menu is open (panel stack reading -1); if a page not on the list such as the hire list is opened on top of the menu, it does not count (the bottom bar cross should not show then)
if(atomic_exchange(&g_touch_navigation,nmode)!=nmode) dispatch_async(dispatch_get_main_queue(),^{ [g_touch_view navigationMode:nmode]; });
dm_uiscreen_set_panel(nmode==1); // iPad 真全屏:面板模式下界面移到正中;没开真全屏时宿主不动 | iPad true fullscreen: in panel mode the UI moves to the center; without true fullscreen the host does nothing
}
@@ -1177,20 +1128,13 @@ static void audio_apply(void) { dm_audio_suspend(g_audio_bg || g_audio_intr); }
// In the enter-background callback (the system gives this callback 10 seconds): wait only in a run. Wait until "a save commit has appeared after sending the background focus, and no new commit for 0.2 seconds after that" (character and shared stash are two containers and may commit separately), at most 2.5 seconds.
// During this time the game main loop runs as usual and presented frames are simply dropped. Outside a run (main menu / character select) do not wait: there is no unsaved progress there
static void background_wait_save(void) {
int dm_ingame_now(void); uint64_t dm_fs_commit_count(void); void mtl_present_discard(int on); uint64_t now_ns(void);
int dm_request_save(void);
if (!dm_ingame_now() || !dm_request_save()) return; // 让游戏下一拍走它自己的定时自动存盘(diag.c) | Let the game run its own timed auto-save on the next tick (diag.c)
uint64_t c0 = dm_fs_commit_count(), t0 = now_ns(), last = c0, last_t = 0;
int dm_ingame_now(void); void mtl_present_discard(int on); int dm_save_wait(double max_s, uint64_t *commits, int *froze, double *ms);
if (!dm_ingame_now()) return;
uint64_t n = 0; int froze = 0; double ms = 0;
mtl_present_discard(1);
for (;;) {
usleep(20000);
uint64_t c = dm_fs_commit_count(), t = now_ns();
if (c != last) { last = c; last_t = t; }
if (last_t && t - last_t >= 200000000ull) break;
if (t - t0 >= 2500000000ull) break;
}
dm_save_wait(2.5, &n, &froze, &ms); // 游戏停着(暂停菜单开着)时冻住世界、临时放开暂停存这一次,存完写回(diag.c) | If the game is stopped (pause menu open), freeze the world and temporarily release the pause for this one save, then write it back (diag.c)
mtl_present_discard(0);
LOG("前端:进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s", (now_ns() - t0) / 1e6, (unsigned long long)(last - c0), last == c0 ? "【红】(2.5 秒内没等到)" : "");
LOG("前端:进后台等游戏存盘 %.0f ms,期间存档提交 %llu 次%s%s", ms, (unsigned long long)n, froze ? "(原先暂停着:冻结世界存盘、已恢复暂停)" : "", n ? "" : "【红】(2.5 秒内没等到)");
}
// 失活时也请游戏存一次盘(查 #22 发现的缺口):上划进多任务界面时 App 多半只「失活」、不进后台,在那里直接划掉进程
// 走不到进后台的存盘,丢掉距上次定时存盘(游戏 5 分钟一次)以来的进度。只置游戏「下一拍就自动存盘」的计时(同 dm_request_save),不等提交、不挡主线程;
@@ -1479,7 +1423,7 @@ void front_ios_lifecycle_install(void) {
LOG("前端:测试回前台(DM_TEST_BG)"); mtl_link_pause(0); front_ios_focus_event(2); front_ios_focus_event(3);
uint64_t c0 = dm_audio_render_calls();
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2000000000), dispatch_get_main_queue(), ^{
LOG("前端:测试回前台后 2 s 声卡回调 +%llu(客体时钟 %.3f s)", (unsigned long long)(dm_audio_render_calls() - c0), guest_ns() / 1e9); }); });
int dm_game_paused(void); LOG("前端:测试回前台后 2 s 声卡回调 +%llu(客体时钟 %.3f s;原版暂停 %d)", (unsigned long long)(dm_audio_render_calls() - c0), guest_ns() / 1e9, dm_game_paused()); }); });
}
// 测试开关 DM_TEST_RESIGN=秒:到点只发「失活」(sceneWillResignActive),不进后台——模仿上划停在多任务界面;配合测试脚本随后 kill -9 = 在多任务界面里划掉
// Test switch DM_TEST_RESIGN=seconds: at that time send only "resign active" (sceneWillResignActive) without going to background -- mimics swiping up and stopping in the app switcher; combined with the test script's subsequent kill -9 = swiping it away in the app switcher
+203 -28
View File
@@ -365,11 +365,20 @@ static int g_pack_wait; // 托管资源包的目录已经在、系统还没说
static int g_doc_stray; // 另一条附带结论:「D2R Mobile」里有文件夹但没有一个是资源(why = 现有哪些文件夹),托管资源包也没到——照常去试托管下载,下载站也走不通时把 why 给玩家看 | The other side conclusion: 「D2R Mobile」 has folders but none of them is assets (why = which folders exist now), and the hosted asset pack has not arrived either -- try the hosted download as usual, and show why to the player when the download site is unreachable too
// 本包有没有配置苹果的托管资源包(Info.plist 的 BAHasManagedAssetPacks)。没配置的包(免费账号档、不带游戏内容的壳:tools/project_free.py、
// tools/shell_build.sh 把那几项去掉了)一碰 BAAssetPackManager,系统接口内部断言直接让进程退出——真机实测:没有资源的第一次启动必崩。
// 所以凡是要问那个接口的地方先问这里。
// Whether this bundle is configured with Apple managed asset packs (BAHasManagedAssetPacks in Info.plist). In a bundle without it (the free-account build and the shell with no game content: tools/project_free.py and
// tools/shell_build.sh remove those keys), merely touching BAAssetPackManager trips an assertion inside the system framework and the process exits -- measured on a device: the first launch with no resources always crashed.
// So every place that is about to ask that framework asks here first.
static BOOL ba_configured(void) { return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"BAHasManagedAssetPacks"] boolValue]; }
// 所以凡是要问那个接口的地方先问这里。另一种同样会崩的包:Info.plist 还声明着,但签名里没有它要的 app group(用自己的 Apple ID / 自签工具重签的
// 包——描述文件里没有我们的 app group):系统 Swift 层报「app group … is inaccessible」致命错误。所以还要核声明的 app group 拿得到容器目录(拿不到 = 签名没带这项权限)
// Whether this package configures Apple's managed asset packs (BAHasManagedAssetPacks in Info.plist). In packages without it (the free-account build, and the shell without game content: tools/project_free.py and
// tools/shell_build.sh remove those entries), touching BAAssetPackManager makes an assertion inside the system interface terminate the process; measured on a device, the first launch without resources always crashed.
// So every place that would ask that interface asks here first. Another kind of package crashes the same way: Info.plist still declares it, but the signature lacks the app group it needs (packages re-signed with your own Apple ID / a sideloading tool,
// whose provisioning profile does not include our app group): the system Swift layer raises a fatal "app group ... is inaccessible" error. So we also check that the declared app group returns a container directory (none = the signature does not carry that entitlement)
static BOOL ba_configured(void) {
static int v = -1; if (v >= 0) return v;
NSString *g = [NSBundle.mainBundle objectForInfoDictionaryKey:@"BAAppGroupID"];
if (![[NSBundle.mainBundle objectForInfoDictionaryKey:@"BAHasManagedAssetPacks"] boolValue]) v = 0;
else if (!g.length || ![NSFileManager.defaultManager containerURLForSecurityApplicationGroupIdentifier:g]) { v = 0; plog("boot: 本包声明了托管资源包,但签名里没有它要的 app group「%s」(自签 / 重签的包),不走托管资源包", g.UTF8String ?: "未声明"); }
else v = 1;
return v;
}
static NSString *romfs_locate(char *why, size_t n) {
g_doc_bad = 0; g_doc_stray = 0;
@@ -507,6 +516,51 @@ static BOOL astc_dl_configured(void) { // 自动下载地址配了没有:测
for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) { NSString *v = [l stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; if (v.length && ![v hasPrefix:@"#"]) return YES; }
return NO;
}
// 安装包自检(只查从发布页的壳做出来的包:壳带着 dm/shell_manifest.txt;Xcode 出的包没有它,不查)。壳清单里每一项都要由 d2rm_pack.py 做进来,
// 缺 = 装的是没做过第一步的壳(或拼装的包)——起宿主会在装载器读 dm/main.fixups.tsv 处退出(线上闪退)。另比产物代号:打包记录 dm/pack_info.txt 与壳的
// dm/shell_info.txt(两份都在才比,旧版打包工具不写打包记录)。不过就不起宿主,弹框说明缺什么、该做哪一步
// Install package self-check (only for packages made from the shell on the releases page: the shell carries dm/shell_manifest.txt; packages built with Xcode do not have it and are not checked). Every item in the shell manifest must have been built in by d2rm_pack.py;
// missing = the shell was installed without doing step 1 (or the package was assembled), and starting the host would exit where the loader reads dm/main.fixups.tsv (a crash for players). The product generation is also compared: the pack record dm/pack_info.txt against the shell's
// dm/shell_info.txt (only when both exist; older pack tools did not write a pack record). If the check fails, do not start the host; show a message saying what is missing and which step to do
static NSString *g_block_title, *g_block_msg, *g_block_why; // 非空 = 这台设备 / 这个安装包起不了游戏:不起宿主,场景里弹框(BlockVC)说明;why 进日志 | Non-empty = this device / this install package cannot start the game: do not start the host, show a message in the scene (BlockVC); why goes to the log
static NSString *g_romfs; static char g_romfs_why[2048]; // 起宿主前那次资源校验的结果(host_start 写,boot_prepare 用) | Result of the resource check before starting the host (written by host_start, used by boot_prepare)
static UIWindow *g_window;
static NSString *kv_file(NSString *path, NSString *key) {
NSString *t = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
for (NSString *l in [t componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) if ([l hasPrefix:[key stringByAppendingString:@"="]]) return [l substringFromIndex:key.length + 1];
return nil;
}
static NSString *pack_check(void) {
NSString *app = NSBundle.mainBundle.resourcePath; NSFileManager *fm = NSFileManager.defaultManager;
// 只测试用:DM_TEST_PACK_MANIFEST=<文件,相对 Documents> 换一份壳清单、DM_TEST_PACK_INFO=<文件> 换一份打包记录(Xcode 包里没有壳信息时,同一文件的 SHELL_PRODUCT= 充当壳的代号;造「缺项」「代号不一致」现场,不动包内文件、不破签名)
// Test only: DM_TEST_PACK_MANIFEST=<file, relative to Documents> substitutes the shell manifest and DM_TEST_PACK_INFO=<file> substitutes the pack record (in an Xcode package, which has no shell info, SHELL_PRODUCT= in the same file stands in for the shell's generation), to create "missing item" and "generation mismatch" cases without touching files in the package or breaking the signature
NSString *(^tpath)(const char *) = ^NSString *(const char *e) { if (!e) return nil; NSString *p = @(e); return [p hasPrefix:@"/"] ? p : // 相对路径按 Documents 解析(沙盒读不到容器外;真机容器路径每次变) | Relative paths are resolved against Documents (the sandbox cannot read outside the container, and the device container path changes every time)
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:p]; };
NSString *tm = tpath(getenv("DM_TEST_PACK_MANIFEST")), *ti = tpath(getenv("DM_TEST_PACK_INFO"));
NSString *man = [NSString stringWithContentsOfFile:tm ?: [app stringByAppendingPathComponent:@"dm/shell_manifest.txt"] encoding:NSUTF8StringEncoding error:nil];
if (!man) { plog("boot: 安装包自检:没有壳清单(Xcode 出的包),不查"); return nil; }
NSMutableArray<NSString *> *miss = [NSMutableArray array]; int total = 0;
for (NSString *l in [man componentsSeparatedByCharactersInSet:NSCharacterSet.newlineCharacterSet]) {
NSString *m = [l stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; if (!m.length) continue; total++;
BOOL dir = NO; if (![fm fileExistsAtPath:[app stringByAppendingPathComponent:m] isDirectory:&dir] || dir != [m hasSuffix:@"/"]) [miss addObject:m]; }
if (miss.count) {
plog("boot: 🔴 安装包自检:壳清单 %d 项缺 %lu 项:%s", total, (unsigned long)miss.count, [miss componentsJoinedByString:@", "].UTF8String);
return [NSString stringWithFormat:T("dmPackBadMiss"), (int)miss.count, [[miss subarrayWithRange:NSMakeRange(0, MIN(miss.count, (NSUInteger)3))] componentsJoinedByString:@", "]]; }
NSString *sp = kv_file([app stringByAppendingPathComponent:@"dm/shell_info.txt"], @"PRODUCT") ?: (ti ? kv_file(ti, @"SHELL_PRODUCT") : nil), *pp = kv_file(ti ?: [app stringByAppendingPathComponent:@"dm/pack_info.txt"], @"PRODUCT");
if (sp && pp && ![sp isEqualToString:pp]) { plog("boot: 🔴 安装包自检:壳的产物代号 %s,打包记录 %s,不一致", sp.UTF8String, pp.UTF8String); return [NSString stringWithFormat:T("dmPackBadProd"), sp, pp]; }
plog("boot: 安装包自检通过:壳清单 %d 项齐全;产物代号 壳 %s / 打包记录 %s", total, sp.UTF8String ?: "无", pp.UTF8String ?: "无(旧版打包工具)");
return nil;
}
@interface BlockVC : UIViewController @end
@implementation BlockVC
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated]; static int shown; if (shown++) return;
UIAlertController *a = [UIAlertController alertControllerWithTitle:g_block_title message:g_block_msg preferredStyle:UIAlertControllerStyleAlert];
[a addAction:[UIAlertAction actionWithTitle:T("dmOldQuit") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { plog("boot: 玩家点了「退出」(%s)", g_block_why.UTF8String); exit(0); }]];
[self presentViewController:a animated:YES completion:nil];
plog("boot: 已弹框(%s)|屏上标题:%s|正文:%s", g_block_why.UTF8String, a.title.UTF8String, [a.message stringByReplacingOccurrencesOfString:@"\n" withString:@" ⏎ "].UTF8String);
}
@end
@interface NoBcVC : UIViewController @property (strong) UILabel *label; @property (strong) UIProgressView *bar; @property (assign) BOOL shown; @end
@implementation NoBcVC
- (void)viewDidLoad {
@@ -561,10 +615,10 @@ static void boot_prepare(void) {
NSFileManager *fm = NSFileManager.defaultManager;
[fm createDirectoryAtPath:romfs withIntermediateDirectories:YES attributes:nil error:nil];
NSURL *romURL = [NSURL fileURLWithPath:romfs]; NSNumber *excluded = @YES; [romURL setResourceValue:excluded forKey:NSURLIsExcludedFromBackupKey error:nil];
char romwhy[2048];
NSString *found = romfs_locate(romwhy, sizeof romwhy);
const char *romwhy = g_romfs_why;
NSString *found = g_romfs; // host_start 起宿主前刚校验过(唯一一次);没过的不会走到这里 | host_start checked right before starting the host (the only time); failures never reach here
if (!found) {
plog("boot: 🔴 RomFS 校验失败:%s", romwhy);
plog("boot: 🔴 RomFS 没经过起宿主前的校验(不应发生):%s", romwhy);
plog("boot: 请推送原版 RomFS: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'");
abort();
}
@@ -685,6 +739,9 @@ static void log_promote(void) { // 场景第一次到前台:这一轮是玩
static void host_start(void) {
if (g_host_up) return;
if (getenv("DM_TEST_BG_RELAUNCH")) return; // 这次启动只为造后台拉起(见 bg_relaunch_test),马上自己退出 | this launch exists only to stage a background relaunch (see bg_relaunch_test) and exits by itself right away
{ NSString *r = romfs_locate(g_romfs_why, sizeof g_romfs_why); // 资源校验:起宿主前只在这里做一次(boot_prepare 用这次结果)。没过(启动判定之后资源被挪 / 删)就回资源界面,不闪退 | Resource check: done only once, here, before starting the host (boot_prepare uses this result). If it fails (resources moved / deleted after the launch decision), go back to the resources screen instead of crashing
if (!r) { plog("boot: 起宿主前资源校验没过(%s),回到资源界面", g_romfs_why); if (g_window) astc_handoff(g_window); return; }
g_romfs = r; }
#ifdef DM_SHELL
// 壳:着色器是以源码进包的话,进游戏之前先一次编完(dm_shader_prep.m,带进度页);做完它回头再调这里
// Shell: if the shaders are shipped as source in the package, compile them all in one go before entering the game (dm_shader_prep.m, with a progress page); when done it calls back here
@@ -739,6 +796,14 @@ static void run_boot(void);
@property (strong) UILabel *label; @property (strong) UIProgressView *bar; @property (strong) UIButton *retry;
@property (assign) int64_t last; @property (assign) CFAbsoluteTime lastT; @property (assign) double rate;
@property (strong) nw_path_monitor_t netmon; @property (assign) int netDown, stopped; // 守着网络:停在「下载没开始」那一页时,网络从不通变成通就自己重试 | network watch: while sitting on the "download did not start" page, retry automatically when the network goes from down to up
// 托管下载(TestFlight):进度到 100% 之后系统还要把资源包装进本地(头文件:完成通知 = 下完且本地可用),这段不给进度;完成回调 / 通知不来就会一直停在进度字上(线上玩家卡 10 分钟)。
// 所以守着系统的「本地可用」状态自己轮询(5 秒一次、30 秒记一行日志),到了就进游戏,不只等回调;100% 后屏上说明在安装、空间不够写清差多少;
// 安装超时 / 暂停 / 报错时给「改用直接下载」(走下载站那条路,包里配了下载地址才给)。packFull = 进度到 100% 的时刻,gone = 已改走直接下载(之后托管的回调只记日志)
// Hosted download (TestFlight): after progress reaches 100% the system still has to install the asset pack locally (header: completion notification = downloaded and available locally), and gives no progress for that part; if the completion callback / notification does not come, the screen stays on the progress text forever (players in the field were stuck for 10 minutes).
// So we watch the system's "available locally" state and poll it ourselves (every 5 seconds, a log line every 30 seconds) and enter the game when it is reached, instead of only waiting for the callback; after 100% the screen explains that it is installing, and if space is short it says by how much;
// on install timeout / pause / error it offers "Use direct download" (the download-site path, only offered if the package has a download address configured). packFull = the moment progress reached 100%, gone = already switched to direct download (after that, callbacks from the hosted download are only logged)
@property (strong) UIButton *useDirect, *share; @property (strong) dispatch_source_t poll; @property (assign) CFAbsoluteTime packT, packFull, logT, testAvailAt;
@property (assign) int64_t packBytes, packDone; @property (assign) int gone, slowShown, finished, textKind, packStop; // packStop:系统报了暂停 / 失败,屏上留那条说明,不再换回「正在安装」 | packStop: the system reported paused / failed; the screen keeps that explanation and does not switch back to "Installing"
@end
@implementation AssetVC
- (void)netUp { if (self.netDown && self.stopped) { plog("assets: 网络通了,自动重试"); self.netDown = 0; [self start]; } else self.netDown = 0; }
@@ -765,24 +830,108 @@ static void run_boot(void);
self.retry = [UIButton buttonWithType:UIButtonTypeSystem]; self.retry.frame = CGRectMake(b.size.width / 2 - 60, b.size.height / 2 + 50, 120, 44);
[self.retry setTitle:T("dmDlRetry") forState:UIControlStateNormal]; self.retry.hidden = YES; self.retry.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
[self.retry addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.label]; [self.view addSubview:self.bar]; [self.view addSubview:self.retry];
self.useDirect = [UIButton buttonWithType:UIButtonTypeSystem]; [self.useDirect setTitle:T("dmDlUseDirect") forState:UIControlStateNormal]; self.useDirect.hidden = YES;
[self.useDirect addTarget:self action:@selector(useDirectTap) forControlEvents:UIControlEventTouchUpInside];
self.share = [UIButton buttonWithType:UIButtonTypeSystem]; [self.share setTitle:T("dmPauseShareLog") forState:UIControlStateNormal]; self.share.hidden = YES;
[self.share addTarget:self action:@selector(shareTap) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.label]; [self.view addSubview:self.bar]; [self.view addSubview:self.retry]; [self.view addSubview:self.useDirect]; [self.view addSubview:self.share];
UIApplication.sharedApplication.idleTimerDisabled = YES;
[self watchNet];
[self start];
}
- (void)viewDidLayoutSubviews { // 按钮一行居中排:重试 / 改用直接下载 / 分享诊断日志,只排露出来的 | buttons centred in one row: Retry / Use direct download / Share diagnostic log, only the ones showing
[super viewDidLayoutSubviews]; CGRect b = self.view.bounds; NSMutableArray<UIButton *> *row = [NSMutableArray array]; CGFloat w = 0;
for (UIButton *x in @[self.retry, self.useDirect, self.share]) if (!x.hidden) { [x sizeToFit]; [row addObject:x]; w += MAX(120, x.bounds.size.width + 24) + (row.count > 1 ? 16 : 0); }
CGFloat x0 = (b.size.width - w) / 2;
for (UIButton *x in row) { CGFloat bw = MAX(120, x.bounds.size.width + 24); x.frame = CGRectMake(x0, b.size.height / 2 + 50, bw, 44); x0 += bw + 16; }
}
- (void)showBtn:(UIButton *)x { dispatch_async(dispatch_get_main_queue(), ^{ x.hidden = NO; [self.view setNeedsLayout]; }); }
- (void)shareTap { plog("assets: 玩家点了分享诊断日志"); void dm_sharelog_share(void); dm_sharelog_share(); }
- (void)useDirectTap {
plog("assets: 玩家点了改用直接下载(托管已等 %.0f 秒,进度 %.2f / %.2f GB%s)", CFAbsoluteTimeGetCurrent() - self.packT, self.packDone / 1e9, self.packBytes / 1e9, self.packFull ? ",已到 100%" : "");
self.gone = 1; if (self.poll) { dispatch_source_cancel(self.poll); self.poll = nil; }
self.useDirect.hidden = YES; [self.view setNeedsLayout]; [self direct:nil];
}
- (void)offerDirect:(int)why { // 托管那条路走不下去时给玩家另一条(why:1 安装超时、2 暂停、3 报错):包里没配下载地址(照公开仓库出的包)就不给,只记日志 | when the hosted path cannot go on, give the player another path (why: 1 install timeout, 2 paused, 3 error): if the package has no download address configured (packages built from the public repository), it is not offered, only logged
if (self.gone) return;
if (!res_dl_configured()) { static int lg; if (!lg++) plog("assets: 托管走不下去(%d:1 安装超时 2 暂停 3 报错),但本包没配资源下载地址,不给「改用直接下载」", why); return; }
plog("assets: 托管走不下去(%d:1 安装超时 2 暂停 3 报错)→ 露出「改用直接下载」", why); [self showBtn:self.useDirect]; [self showBtn:self.share];
}
static double slow_s(void) { const char *t = getenv("DM_TEST_BA_SLOW"); return t ? atof(t) : 300; } // 100% 后等系统装进本地多久算慢(头文件只说完成通知 = 本地可用,中间要多久没写;给 5 分钟);测试开关缩短 | how long to wait after 100% for the system to install it locally before it counts as slow (the header only says the completion notification = available locally, not how long it takes in between; 5 minutes is given); a test switch shortens it
static int64_t free_bytes(void) { // 给 App 用的可用空间(系统「重要用途」口径,同设置里显示的);测试开关 DM_TEST_BA_FREE=<GB> 造空间不够 | free space available to the App (the system's "important usage" measure, the same as shown in Settings); test switch DM_TEST_BA_FREE=<GB> stages not enough space
const char *t = getenv("DM_TEST_BA_FREE"); if (t) return (int64_t)(atof(t) * 1e9);
NSURL *u = [NSURL fileURLWithPath:NSHomeDirectory()]; NSNumber *v = nil; [u getResourceValue:&v forKey:NSURLVolumeAvailableCapacityForImportantUsageKey error:nil]; return v.longLongValue;
}
- (BOOL)packAvail {
if (getenv("DM_TEST_BA")) return self.testAvailAt > 0 && CFAbsoluteTimeGetCurrent() >= self.testAvailAt;
if (@available(iOS 26.4, *)) return [BAAssetPackManager.sharedManager assetPackIsAvailableLocallyWithIdentifier:@"romfs"];
return NO;
}
- (void)logPack:(BOOL)avail free:(int64_t)fr {
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); double w = now - self.packT, f = self.packFull ? now - self.packFull : -1, d = self.packDone / 1e9, t = self.packBytes / 1e9, g = fr / 1e9; int a = avail;
if (getenv("DM_TEST_BA")) { plog("assets: 托管状态(测试现场):已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB", w, d, t, f, a, g); return; }
if (@available(iOS 26.4, *)) {
[BAAssetPackManager.sharedManager getLocalStatusOfAssetPackWithIdentifier:@"romfs" completionHandler:^(BAAssetPackStatus st) {
plog("assets: 托管状态:已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB;系统状态位 0x%lx(1 可下载 2 有更新 4 最新 8 过期 0x10 已撤 0x20 下载中 0x40 已下完)",
w, d, t, f, a, g, (unsigned long)st); }];
} else plog("assets: 托管状态:已等 %.0f 秒,进度 %.2f / %.2f GB(100%% 后 %.0f 秒,-1 = 没到),系统说本地可用 %d,可用空间 %.2f GB", w, d, t, f, a, g);
}
- (void)packText:(int64_t)fr { // 100% 之后屏上那段:空间不够 > 超时 > 正在安装 | the passage on screen after 100%: not enough space > timeout > installing
NSString *dev = UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone";
int k = self.packBytes > 0 && fr < self.packBytes ? 3 : self.slowShown ? 2 : 1;
NSString *t = k == 3 ? [NSString stringWithFormat:T("dmDlInstallSpace"), self.packBytes / 1e9, dev, fr / 1e9, (self.packBytes - fr) / 1e9, dev]
: k == 2 ? [NSString stringWithFormat:T(res_dl_configured() ? "dmDlPackSlow" : "dmDlPackSlowNoDl"), (int)MAX(1, lround(slow_s() / 60))] // 没配下载地址就没有「改用直接下载」按钮,文字不提它 | with no download address configured there is no "Use direct download" button, and the text does not mention it
: [NSString stringWithFormat:T("dmDlInstalling"), self.packBytes / 1e9, fr / 1e9];
if (k != self.textKind) { self.textKind = k; [self say:t]; } // 换了一种说法才进日志;只是空间数字变了就只改屏上的字 | only goes into the log when the wording changes; if only the space numbers changed, just update the text on screen
else if (![self.label.text isEqualToString:t]) dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; });
}
- (void)pollPack {
if (self.gone) return;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); BOOL avail = [self packAvail]; int64_t fr = free_bytes();
if (now - self.logT >= 30) { self.logT = now; [self logPack:avail free:fr]; }
if (avail) { plog("assets: 轮询:系统说资源包本地可用(完成回调%s)→ 进游戏", self.finished ? "也到了" : "没到"); [self ready]; return; }
if (!self.packFull || self.packStop) return;
if (!self.slowShown && now - self.packFull >= slow_s()) { self.slowShown = 1; plog("assets: 进度 100%% 后 %.0f 秒系统仍没装好", now - self.packFull); [self offerDirect:1]; }
[self packText:fr];
}
- (void)watchPack { // 托管下载开始后:守着系统状态(主线程定时器) | after the hosted download starts: watch the system state (main-thread timer)
if (self.poll) return; self.packT = CFAbsoluteTimeGetCurrent(); self.logT = 0;
dispatch_source_t s = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); self.poll = s; __weak AssetVC *w = self;
dispatch_source_set_timer(s, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), 5 * NSEC_PER_SEC, NSEC_PER_SEC / 2);
dispatch_source_set_event_handler(s, ^{ [w pollPack]; }); dispatch_resume(s);
}
// 测试开关 DM_TEST_BA=finish|late|silent|fail(Mac 上的 iOS 包造托管下载现场,资源其实在本地):3 秒内假进度走到 100%,之后——
// finish 再 3 秒送完成通知;late 什么都不来(配 DM_TEST_BA_SLOW=<秒> 看超时);silent 不送通知、8 秒后「系统说本地可用」(看轮询自愈);fail 送下载失败。
// DM_TEST_BA_TAP=<秒>:到点替玩家点「改用直接下载」(按钮没露出来就报红)
// Test switch DM_TEST_BA=finish|late|silent|fail (stages a hosted download scene for the iOS package on the Mac, the resources are actually local): fake progress goes to 100% within 3 seconds, then -
// finish sends the completion notification 3 seconds later; late sends nothing (with DM_TEST_BA_SLOW=<seconds> to see the timeout); silent sends no notification and "the system says it is available locally" after 8 seconds (to see polling recover); fail sends a download failure.
// DM_TEST_BA_TAP=<seconds>: at that time, taps "Use direct download" for the player (reports red if the button is not showing)
- (void)fakeBA:(NSString *)sc API_AVAILABLE(ios(26.0)) {
plog("assets: 测试现场 DM_TEST_BA=%s", sc.UTF8String); self.packBytes = 4130000000LL; [self watchPack]; [self say:T("dmDlDownloading")];
NSProgress *g = [NSProgress progressWithTotalUnitCount:self.packBytes]; BAAssetPack *np = nil;
for (int i = 1; i <= 10; i++) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(i * 0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ g.completedUnitCount = self.packBytes * i / 10; [self downloadOfAssetPack:np hasProgress:g]; });
if ([sc isEqualToString:@"silent"]) self.testAvailAt = CFAbsoluteTimeGetCurrent() + 11;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 6 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
if ([sc isEqualToString:@"finish"]) [self downloadOfAssetPackFinished:np];
if ([sc isEqualToString:@"fail"]) [self downloadOfAssetPack:np failedWithError:[NSError errorWithDomain:@"DmTestBA" code:1 userInfo:@{NSLocalizedDescriptionKey: @"test failure"}]]; });
const char *tp = getenv("DM_TEST_BA_TAP"); if (tp) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(tp) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
if (self.useDirect.hidden) plog("【红】DM_TEST_BA_TAP:「改用直接下载」没露出来"); else [self useDirectTap]; });
}
- (void)say:(NSString *)t { plog("assets: %s", t.UTF8String); dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; }); }
- (void)fail:(NSString *)what error:(NSError *)e {
// 直装包没有托管资源,这条路必然失败:报错只进日志,界面给玩家能照做的指引
// A direct-install build has no hosted assets, so this path always fails: the error goes only to the log, and the screen gives the player instructions they can follow
plog("assets: %s失败:%s(%s %ld)", what.UTF8String, e.localizedDescription.UTF8String, e.domain.UTF8String, (long)e.code);
[self say:no_assets_text()];
dispatch_async(dispatch_get_main_queue(), ^{ self.retry.hidden = NO; });
[self showBtn:self.retry];
}
- (void)start {
self.retry.hidden = YES; self.stopped = 0; self.last = 0; self.lastT = CFAbsoluteTimeGetCurrent();
self.retry.hidden = YES; self.stopped = 0; self.last = 0; self.lastT = CFAbsoluteTimeGetCurrent(); self.packStop = 0; self.textKind = 0;
char why[2048];
if (getenv("DM_TEST_BA") && !self.gone) { if (@available(iOS 26.0, *)) [self fakeBA:@(getenv("DM_TEST_BA"))]; return; } // 测试:造托管下载现场(fakeBA) | test: stage a hosted download scene (fakeBA)
if (!getenv("DM_ASSETS_TEST") && romfs_locate(why, sizeof why)) { [self ready]; return; } // 重试时资源已到(如刚在「文件」里拷完) | Assets have already arrived on retry (e.g. just finished copying in the Files app)
if (!getenv("DM_ASSETS_TEST") && g_doc_bad) { [self direct:@(why)]; return; } // 有文件夹但不完整(拷到一半 / 下到一半):不试托管下载,直接从下载站补齐;下载站走不通才报原因 | A folder exists but is incomplete (half copied / half downloaded): do not try the hosted download, fill in the rest straight from the download site; report the reason only if the download site is unreachable
if (self.gone) { [self direct:nil]; return; } // 玩家已选「改用直接下载」:重试仍走这条(托管的回调此后不接,回到托管会停在「正在下载」) | the player chose "Use direct download": retries keep going this way (callbacks from the hosted download are not taken from now on; going back to hosted would stay stuck at "Downloading")
NSString *stray = !getenv("DM_ASSETS_TEST") && g_doc_stray ? @(why) : nil; // 「D2R Mobile」里有文件夹但都不是资源:托管下载、下载站都走不通时给玩家看这条 | 「D2R Mobile」 has folders but none of them is assets: show the player this message when neither the hosted download nor the download site works
if (getenv("DM_ROMFS_TEST_PACK")) { [self ready]; return; } // 只测试用:托管资源包「下完了」但不合格的现场 | Test only: the scenario where the managed asset pack has "finished downloading" but does not pass validation
if (getenv("DM_ASSETS_TEST") && !strcmp(getenv("DM_ASSETS_TEST"), "direct")) { [self direct:nil]; return; } // 测试:资源在本地也走真正的直接下载准备(联网取清单、盘点、查空间),配 DM_ASSET_FREE_TEST 造空间不够 | Test: with assets local, still go through the real direct-download preparation (fetch the manifest over the network, take inventory, check space); pair with DM_ASSET_FREE_TEST to fake insufficient space
@@ -798,8 +947,11 @@ static void run_boot(void);
[m getAssetPackWithIdentifier:@"romfs" completionHandler:^(BAAssetPack *pack, NSError *e) {
if (!pack) { plog("assets: 没有托管资源包(%s),改从下载站直接下", e.localizedDescription.UTF8String); dispatch_async(dispatch_get_main_queue(), ^{ [self direct:stray]; }); return; } // 直装包走到这里必然失败 | A direct-install build always fails when it gets here
[self say:T("dmDlDownloading")];
plog("assets: 托管资源包 版本 %ld、%.2f GB,请系统确保本地可用(可用空间 %.2f GB)", (long)pack.version, pack.downloadSize / 1e9, free_bytes() / 1e9);
dispatch_async(dispatch_get_main_queue(), ^{ self.packBytes = pack.downloadSize; [self watchPack]; });
[m ensureLocalAvailabilityOfAssetPack:pack completionHandler:^(NSError *e2) {
if (e2) { [self fail:@"下载游戏资源" error:e2]; return; }
if (e2) { self.packStop = 1; [self fail:@"下载游戏资源" error:e2]; [self offerDirect:3]; return; }
plog("assets: 系统「确保本地可用」完成回调到了");
dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; });
}];
}];
@@ -809,7 +961,7 @@ static void run_boot(void);
// Direct-install build: download the assets straight from our own download site into Documents/D2R Mobile Resources (asset_dl.m). When the download site is unreachable the screen falls back to the original instructions (or the reason given by fallback)
- (void)direct:(NSString *)fallback {
if (!res_dl_configured()) { // 这个包没配下载地址(照公开仓库自己出的包):不去连、不说「下载没开始」,只讲把资源拷进来 | This build has no download address configured (a build made by yourself from the public repository): do not connect, do not say "the download has not started", only explain how to copy the resources in
plog("assets: 本包没配资源下载地址,不走下载"); [self say:fallback ? [NSString stringWithFormat:@"%@\n%@", fallback, T("dmDlCopyInShort")] : no_assets_text()]; self.bar.hidden = YES; self.retry.hidden = NO; self.stopped = 1; return; } // 这条路没有进度可报:不留一条空的进度条 | nothing to report progress on along this path: do not leave an empty progress bar
plog("assets: 本包没配资源下载地址,不走下载"); [self say:fallback ? [NSString stringWithFormat:@"%@\n%@", fallback, T("dmDlCopyInShort")] : no_assets_text()]; self.bar.hidden = YES; [self showBtn:self.retry]; self.stopped = 1; return; } // 这条路没有进度可报:不留一条空的进度条 | nothing to report progress on along this path: do not leave an empty progress bar
[self say:T("dmDlConnecting")];
[DmAssetDL.shared prepare:^(NSString *err, int64_t remain, int64_t total, BOOL cellular) {
if (err && DmAssetDL.shared.shortBytes > 0) { // 设备空间不够(原先只进日志、界面显示的是「先从内测页下载资源包」,跟真实原因无关):系统提示写清还差多少 | Not enough space on the device (previously this only went to the log and the screen showed 「先从内测页下载资源包」(First download the asset pack from the beta page), unrelated to the real cause): the system prompt states exactly how much is missing
@@ -817,7 +969,7 @@ static void run_boot(void);
NSString *dev = UIDevice.currentDevice.userInterfaceIdiom == UIUserInterfaceIdiomPad ? @"iPad" : @"iPhone"; // 按设备写 | Wording depends on the device
NSString *m = [NSString stringWithFormat:T("dmDlSpaceMsg"), DmAssetDL.shared.shortBytes / 1e9, remain / 1e9, dev, DmAssetDL.shared.freeBytes / 1e9, dev];
NSString *title = [NSString stringWithFormat:T("dmDlSpaceTitle"), dev];
[self say:[[title stringByAppendingString:@"\n"] stringByAppendingString:m]]; self.retry.hidden = NO;
[self say:[[title stringByAppendingString:@"\n"] stringByAppendingString:m]]; [self showBtn:self.retry];
UIAlertController *a = [UIAlertController alertControllerWithTitle:title message:m preferredStyle:UIAlertControllerStyleAlert];
[a addAction:[UIAlertAction actionWithTitle:T("dmOk") style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:a animated:YES completion:^{ plog("assets: 已弹系统提示「%s」|正文:%s", title.UTF8String, [m stringByReplacingOccurrencesOfString:@"\n" withString:@" ⏎ "].UTF8String); }]; return; }
@@ -829,7 +981,7 @@ static void run_boot(void);
if (err) { // 下载没开始:屏上写真实原因和下一步,不落回「还没有游戏资源」(没网时玩家看到的是「没有资源」,不知道是网络、也不知道能重试) | download did not start: show the real reason and the next step on screen instead of falling back to "no game assets yet" (with no network the player saw "no assets", not knowing it was the network or that a retry was possible)
plog("assets: 直接下载走不了:%s", err.UTF8String);
[self say:[NSString stringWithFormat:T("dmDlNotStarted"), fallback ? [fallback stringByAppendingString:@"\n"] : @"", self.netDown ? T("dmDlNetDown") : err, self.netDown ? T("dmDlNextAuto") : T("dmDlNextRetry")]];
self.retry.hidden = NO; self.stopped = 1; return; }
[self showBtn:self.retry]; self.stopped = 1; return; }
void (^go)(void) = ^{
[self say:[NSString stringWithFormat:T("dmDlWill"), remain < 100000000 ? [NSString stringWithFormat:@"%.0f MB", remain / 1e6] : [NSString stringWithFormat:@"%.1f GB", remain / 1e9], total / 1e9]]; // 自动开始的大下载,开始前先把要下多少写在屏上 | A large download that starts automatically: show on screen how much will be downloaded before it starts
self.last = total - remain; self.lastT = CFAbsoluteTimeGetCurrent(); self.rate = 0;
@@ -839,33 +991,45 @@ static void run_boot(void);
self.label.text = [NSString stringWithFormat:@"正在下载游戏资源(共 %.1f GB)\n%.2f / %.2f GB(%.0f%%) %.1f MB/s%@", tot / 1e9, done / 1e9, tot / 1e9, tot ? 100.0 * done / tot : 0, self.rate / 1e6, note ? [@"\n" stringByAppendingString:note] : @""];
self.bar.progress = tot ? (float)done / tot : 0;
} done:^(NSString *e2) {
if (e2) { [self say:[NSString stringWithFormat:T("dmDlStopped"), e2, self.last / 1e9, total / 1e9]]; self.retry.hidden = NO; self.stopped = 1; return; }
if (e2) { [self say:[NSString stringWithFormat:T("dmDlStopped"), e2, self.last / 1e9, total / 1e9]]; [self showBtn:self.retry]; self.stopped = 1; return; }
[self ready];
}];
};
if (!cellular || remain <= 0) { go(); return; }
UIAlertController *a = [UIAlertController alertControllerWithTitle:T("dmDlCellTitle") message:[NSString stringWithFormat:T("dmDlCellMsg"), remain / 1e9] preferredStyle:UIAlertControllerStyleAlert];
[a addAction:[UIAlertAction actionWithTitle:T("dmDlCellLater") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { [self say:T("dmDlCellWait")]; self.retry.hidden = NO; }]];
[a addAction:[UIAlertAction actionWithTitle:T("dmDlCellLater") style:UIAlertActionStyleCancel handler:^(UIAlertAction *x) { [self say:T("dmDlCellWait")]; [self showBtn:self.retry]; }]];
[a addAction:[UIAlertAction actionWithTitle:T("dmDlCellGo") style:UIAlertActionStyleDefault handler:^(UIAlertAction *x) { plog("assets: 玩家同意用流量下载"); go(); }]];
[self presentViewController:a animated:YES completion:nil];
}];
}
- (void)downloadOfAssetPack:(BAAssetPack *)p hasProgress:(NSProgress *)g API_AVAILABLE(ios(26.0)) {
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); int64_t done = g.completedUnitCount, total = g.totalUnitCount;
if (self.gone) return; // 已改走直接下载:屏上是那条路的进度 | already switched to direct download: the screen shows that path's progress
self.packDone = done; if (total > 0) self.packBytes = total;
if (total > 0 && done >= total) { // 到 100%:之后是系统装包,屏上改说明(进度字不再刷) | reached 100%: from here the system installs the pack, the screen switches to an explanation (the progress text is no longer updated)
if (!self.packFull) { self.packFull = now; plog("assets: 托管下载进度到 100%%(%.2f GB),等系统装进本地;可用空间 %.2f GB", total / 1e9, free_bytes() / 1e9);
dispatch_async(dispatch_get_main_queue(), ^{ self.bar.progress = 1; [self packText:free_bytes()]; [self showBtn:self.share]; }); }
return; }
if (now - self.lastT >= 1.0) { self.rate = (done - self.last) / (now - self.lastT); self.last = done; self.lastT = now; }
NSString *t = [NSString stringWithFormat:T("dmDlProgress"), done / 1e9, total / 1e9, total ? 100.0 * done / total : 0, self.rate / 1e6];
dispatch_async(dispatch_get_main_queue(), ^{ self.label.text = t; self.bar.progress = total ? (float)done / total : 0; });
}
- (void)downloadOfAssetPackFinished:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { plog("assets: 系统通知资源包下载完成"); dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); }
- (void)downloadOfAssetPackPaused:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { [self say:T("dmDlPaused")]; }
- (void)downloadOfAssetPack:(BAAssetPack *)p failedWithError:(NSError *)e API_AVAILABLE(ios(26.0)) { [self fail:@"下载游戏资源" error:e]; }
- (void)downloadOfAssetPackBegan:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) { plog("assets: 系统通知托管下载开始 / 继续"); self.packStop = 0; self.textKind = 0; }
- (void)downloadOfAssetPackFinished:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) {
plog("assets: 系统通知资源包下载完成%s", self.gone ? "(已改走直接下载,不接)" : ""); if (self.gone) return; self.finished = 1; dispatch_async(dispatch_get_main_queue(), ^{ [self ready]; }); }
- (void)downloadOfAssetPackPaused:(BAAssetPack *)p API_AVAILABLE(ios(26.0)) {
plog("assets: 系统通知托管下载暂停%s", self.gone ? "(已改走直接下载)" : ""); if (self.gone) return; self.packStop = 1; [self say:T("dmDlPaused")]; [self offerDirect:2]; }
- (void)downloadOfAssetPack:(BAAssetPack *)p failedWithError:(NSError *)e API_AVAILABLE(ios(26.0)) {
if (self.gone) { plog("assets: 托管下载失败(已改走直接下载):%s", e.localizedDescription.UTF8String); return; }
self.packStop = 1; [self fail:@"下载游戏资源" error:e]; [self offerDirect:3]; }
- (void)ready {
char why[2048];
static int started; if (started) return; // 完成回调与系统的完成通知都会走到这里:只起一次 | Both the completion callback and the system's completion notification end up here: start only once
if (!romfs_locate(why, sizeof why)) {
if (g_pack_wait) { [self say:T("dmDlPackWait")]; return; } // 等系统的完成通知(downloadOfAssetPackFinished)再来,不按时间等 | Come back when the system's completion notification (downloadOfAssetPackFinished) arrives; do not wait by time
[self say:[NSString stringWithFormat:T("dmDlNotReady"), @(why)]]; self.retry.hidden = NO; return; }
started = 1;
if (g_pack_wait) { if (!self.packFull) [self say:T("dmDlPackWait")]; return; } // 等系统说本地可用(完成通知或 pollPack 轮询到);100% 后屏上是 packText 那段 | waiting for the system to say it is available locally (the completion notification, or found by pollPack's polling); after 100% the screen shows the packText passage
if (self.poll) { plog("assets: 系统说可用但校验没过:%s", why); }
[self say:[NSString stringWithFormat:T("dmDlNotReady"), @(why)]]; [self showBtn:self.retry]; return; }
started = 1; if (self.poll) { dispatch_source_cancel(self.poll); self.poll = nil; }
plog("assets: 资源就绪,就地起宿主");
g_need_assets = 0;
self.view = front_ios_view(self.view.window.windowScene.coordinateSpace.bounds);
@@ -902,10 +1066,11 @@ static void astc_handoff(UIWindow *w) { // 补充包到位(玩家刚拷好 /
@implementation SceneDelegate
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)s options:(UISceneConnectionOptions *)o {
UIWindowScene *ws = (UIWindowScene *)scene;
self.window = [[UIWindow alloc] initWithWindowScene:ws];
self.window = [[UIWindow alloc] initWithWindowScene:ws]; g_window = self.window;
UIViewController *vc = [DmGameVC new];
vc.view.backgroundColor = UIColor.blackColor;
if ([g_mode isEqualToString:@"boot"] && g_no_bc) { vc = [NoBcVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 本机型不支持:只弹框 | This device model is not supported: only show an alert
if ([g_mode isEqualToString:@"boot"] && g_block_title) { vc = [BlockVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 图形芯片不支持 / 安装包不完整:只弹框 | Graphics chip not supported / install package incomplete: only show the message
else if ([g_mode isEqualToString:@"boot"] && g_no_bc) { vc = [NoBcVC new]; vc.view.backgroundColor = UIColor.blackColor; } // 本机型不支持:只弹框 | This device model is not supported: only show an alert
else if ([g_mode isEqualToString:@"boot"] && g_need_assets) vc = [AssetVC new]; // 资源包没到:下载界面 | Asset pack not here yet: download screen
else if ([g_mode isEqualToString:@"boot"]) vc.view = front_ios_view(ws.coordinateSpace.bounds); // 图形后端出图的层(不叠任何控件) | The layer the graphics backend presents into (no widgets stacked on it)
else if ([g_mode isEqualToString:@"blank"]) { UIView *front_ios_blank_view(CGRect); vc.view = front_ios_blank_view(ws.coordinateSpace.bounds); } // 发热负对照 | Heat negative control
@@ -920,7 +1085,7 @@ static void astc_handoff(UIWindow *w) { // 补充包到位(玩家刚拷好 /
}
- (void)sceneWillResignActive:(UIScene *)s { if (g_host_up) front_ios_focus_event(0); }
- (void)sceneDidEnterBackground:(UIScene *)s { if (g_host_up) front_ios_focus_event(1); }
- (void)sceneWillEnterForeground:(UIScene *)s { log_promote(); if ([g_mode isEqualToString:@"boot"] && !g_need_assets && !g_no_bc) { host_start(); if (g_host_up) front_ios_focus_event(2); } }
- (void)sceneWillEnterForeground:(UIScene *)s { log_promote(); if ([g_mode isEqualToString:@"boot"] && !g_need_assets && !g_no_bc && !g_block_title) { host_start(); if (g_host_up) front_ios_focus_event(2); } }
- (void)sceneDidBecomeActive:(UIScene *)s { if (g_host_up) front_ios_focus_event(3); }
// 场景断开 / App 终止:宿主有序收尾后 _exit(hle_lifecycle.c)。注意:用户在多任务界面划掉一个已在后台挂起的 App 时,系统直接 SIGKILL,不走这两个回调
// Scene disconnect / App termination: the host shuts down in order, then _exit (hle_lifecycle.c). Note: when the user swipes away an App already suspended in the background from the multitasking screen, the system sends SIGKILL directly and neither of these two callbacks runs
@@ -1064,14 +1229,24 @@ int main(int argc, char *argv[]) {
metal_cache_report_and_clean();
char why[2048];
{ id<MTLDevice> dev = MTLCreateSystemDefaultDevice(); g_no_bc = !dev.supportsBCTextureCompression || getenv("DM_TEST_NO_BC");
// 图形层要 Metal 3(参数缓冲里直接写 gpuAddress 的无绑定用法):A14 / M1(Apple7 家族)起才有,A13 及更早不支持。不支持就不起游戏、弹框说明(不再走到解包 / 建管线时闪退)。
// 测试开关 DM_TEST_NO_METAL3=1 当成不支持
// The graphics layer needs Metal 3 (bindless use that writes gpuAddress directly into argument buffers): available from A14 / M1 (the Apple7 family); A13 and earlier do not support it. If unsupported, do not start the game and show a message (instead of crashing later while unpacking / building pipelines).
// Test switch DM_TEST_NO_METAL3=1 treats the device as unsupported
if (![dev supportsFamily:MTLGPUFamilyMetal3] || getenv("DM_TEST_NO_METAL3")) {
g_block_title = T("dmGpuOldTitle"); g_block_msg = T("dmGpuOldMsg"); g_block_why = @"图形芯片不支持 Metal 3";
plog("boot: 🔴 显卡 %s 不支持 Metal 3%s——不起游戏,弹框说明", dev.name.UTF8String, getenv("DM_TEST_NO_METAL3") ? "(测试开关 DM_TEST_NO_METAL3)" : ""); }
plog("boot: 显卡 %s,BC 压缩格式%s", dev.name.UTF8String, g_no_bc ? (getenv("DM_TEST_NO_BC") ? "按测试开关 DM_TEST_NO_BC 当成不支持" : "不支持——不起游戏,弹框说明后退出") : "支持"); }
if (g_no_bc) { // 不支持 BC:有配套的老机型补充包就照常起(覆盖层换 ASTC 版,见 boot_prepare),没有就弹框 | BC not supported: if the matching Legacy Device Pack is present, start as usual (the overlay switches to the ASTC version, see boot_prepare); otherwise show an alert
NSString *d = astc_pack_locate(g_astc_why, sizeof g_astc_why);
if (d) { g_astc_dir = d; g_no_bc = 0; plog("boot: 用老机型补充包 %s", d.UTF8String); }
else plog("boot: 老机型补充包未就绪:%s", g_astc_why);
}
if (g_no_bc) {}
else if (getenv("DM_ASSETS_TEST")) { g_need_assets = 1; plog("boot: DM_ASSETS_TEST——强制走资源下载界面再就地起宿主(测这条路径)"); }
NSString *pb = g_block_title ? nil : pack_check();
if (pb) { g_block_title = T("dmPackBadTitle"); g_block_msg = [NSString stringWithFormat:@"%@\n\n%@", pb, T("dmPackBadHow")]; g_block_why = @"安装包自检没过"; }
if (g_block_title) {} // 起不了游戏:不起宿主,场景里弹框(BlockVC) | The game cannot start: do not start the host; show a message in the scene (BlockVC)
else if (g_no_bc) {}
else if (getenv("DM_ASSETS_TEST") || getenv("DM_TEST_BA")) { g_need_assets = 1; plog("boot: DM_ASSETS_TEST——强制走资源下载界面再就地起宿主(测这条路径)"); }
else if (romfs_locate(why, sizeof why)) plog("boot: 游戏资源就绪,宿主等场景到前台再装载");
else { g_need_assets = 1; plog("boot: 游戏资源还没到(%s),先显示资源下载界面", why); }
} else metal_cache_report_and_clean();