From e2a0c9a9b5d65f6cd505e967e4760e2745e90ca8 Mon Sep 17 00:00:00 2001 From: jhaizhou <258432107+jhaizhou-ops@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:46:55 +0800 Subject: [PATCH] NPC speech restored (explicit 5.1 to stereo downmix); graphics memory pools made resident only on first GPU use (about 0.5 GB less held); render targets written through a format-changing view attached with that format, sRGB swapchain presented through a non-sRGB view (#36); bloom / FXAA texture-slot rewrites mark bindings dirty; Mac App plays sound and fills 16:10 screens The render-target view issue (#36) was found and diagnosed by seedds on another port built from this repository, who also proposed the fix direction. Co-authored-by: seedds <3463322+seedds@users.noreply.github.com> --- dm/gfx/nvn/nvn_mtl.m | 99 ++++++++++++++++++++++++++----- dm/gfx/tests/.gitignore | 2 + dm/gfx/tests/Makefile | 4 ++ dm/gfx/tests/t_rt_srgb_view.m | 58 ++++++++++++++++++ dm/host/Makefile | 4 +- dm/host/app_mac.m | 1 + dm/host/front_mac.m | 65 +++++++++++++++++--- dm/host/hle_audio.c | 74 ++++++++++++++++++----- dm/host/tests/Makefile | 6 +- dm/host/tests/t_audio.c | 12 ++++ dm/host/tests/t_touch_mac.c | 1 + dm/host/tests/t_touch_tick_stub.c | 1 + dm/host/touch_mac.c | 15 ++++- docs/MAC.md | 3 +- docs/MAC.zh-CN.md | 3 +- 15 files changed, 301 insertions(+), 47 deletions(-) create mode 100644 dm/gfx/tests/t_rt_srgb_view.m diff --git a/dm/gfx/nvn/nvn_mtl.m b/dm/gfx/nvn/nvn_mtl.m index 78e37d0..f93defe 100644 --- a/dm/gfx/nvn/nvn_mtl.m +++ b/dm/gfx/nvn/nvn_mtl.m @@ -273,7 +273,7 @@ void bf_want_note(const char *key) { // ---------- 内存池 ---------- // ---------- Memory pools ---------- -typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; } pool_ent; +typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id buf; uint64_t gpu; const void *key; int res; } pool_ent; // res:已放进驻留集(按需,见 pool_res) | res: already put in the residency set (on demand, see pool_res) static pool_ent *g_pools; static int g_npool, g_cap; static NSMutableArray *g_keep; // 持有缓冲引用(pool_ent 里是不持有的指针) | Holds the buffer references (pool_ent has non-owning pointers) static uint64_t g_pool_adds; @@ -407,16 +407,34 @@ uint64_t dm_mtl_l3_sample(uint32_t tick) { } static _Atomic uint64_t g_reg_gen = 1; // 内存池 / 贴图 / 采样器登记的变更代号:参数缓冲复用以它为失效条件之一 | Change generation of memory pool / texture / sampler registration: one of the invalidation conditions for argument buffer reuse +// 内存池按需驻留:零拷贝缓冲放进驻留集,iOS 会把整个池读进内存并钉成 wired(不计入 footprint,也不能被换出),游戏从没用过的池也一样—— +// 真机 17 Pro Max 实测 512 MB 的渲染目标池一局取址 0 次,放进驻留集整机 wired 高约 530 MB;A14 4 GB 机因此启动几秒就被系统按整机缺页结束(公开仓库 #37)。 +// 所以池建好时不放进驻留集,GPU 第一次经 mtl_addr / mtl_gpu_addr 取到它的地址时才放进去,并当场提交驻留集 +// (GPU 拿池地址只有这两个口子;当场提交 = 早于用到它的任何命令缓冲提交,不依赖各提交口自己调 res_commit)。调用方持 g_mu +// On-demand residency of memory pools: putting a zero-copy buffer into the residency set makes iOS read the whole pool into memory and pin it as wired (not counted in footprint and never paged out), even a pool the game never uses - +// measured on a 17 Pro Max: the 512 MB render-target pool is addressed 0 times in a run, and putting it into the residency set raises device wired memory by about 530 MB; this is why an A14 4 GB device was ended by the system for running out of memory within seconds of launch (public repository #37). +// So a pool is not put into the residency set when created; it is put in, and the residency set committed on the spot, the first time the GPU gets its address through mtl_addr / mtl_gpu_addr +// (these are the only two ways the GPU gets pool addresses; committing on the spot = earlier than any command buffer commit that uses it, without relying on each commit point calling res_commit). Caller holds g_mu +static uint64_t g_cb_commits, g_pool_res_at; // 已提交的命令缓冲个数(主提交 + 上传);最近一次按需驻留时的这个数(0 = 没有待核的) | number of command buffers committed (main + upload); this number at the last on-demand residency (0 = nothing pending to check) +static void pool_res(int i) { + if (g_pools[i].res) return; + res_add(g_pools[i].buf); res_commit(); g_pools[i].res = 1; g_pool_res_at = g_cb_commits + 1; + MLOG("内存池按需驻留:%llu MB 的池第一次被取址,已放进驻留集并提交(此时已提交命令缓冲 %llu 个)", + (unsigned long long)((g_pools[i].hi - g_pools[i].lo) >> 20), (unsigned long long)g_cb_commits); +} +static void cb_committed(void) { // 主提交 / 上传提交之后调:核「驻留集提交早于用到它的第一个命令缓冲提交」,每次按需驻留后记一行 | called after the main submission / upload submission: checks that "the residency set commit is earlier than the first command buffer commit that uses it", one line after each on-demand residency + pthread_mutex_lock(&g_mu); uint64_t n = ++g_cb_commits, at = g_pool_res_at; if (at) g_pool_res_at = 0; pthread_mutex_unlock(&g_mu); + if (at) MLOG("内存池按需驻留:其后第一个命令缓冲提交是第 %llu 个(驻留集在第 %llu 个之前已提交)", (unsigned long long)n, (unsigned long long)at); +} void mtl_pool_add(const void *mem, uint64_t size) { mtl_init(); g_reg_gen++; uintptr_t pg = (uintptr_t)getpagesize(), lo = (uintptr_t)mem, hi = lo + size; uintptr_t a = lo & ~(pg - 1), b = (hi + pg - 1) & ~(pg - 1); id buf = [g_dev newBufferWithBytesNoCopy:(void *)a length:b - a options:MTLResourceStorageModeShared deallocator:nil]; if (!buf) MDIE("内存池 %p+%#llx 建零拷贝缓冲失败", mem, (unsigned long long)size); - res_add(buf); pthread_mutex_lock(&g_mu); if (g_npool == g_cap) { g_cap = g_cap ? g_cap * 2 : 64; g_pools = realloc(g_pools, g_cap * sizeof *g_pools); } - g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem}; + g_pools[g_npool++] = (pool_ent){lo, hi, a, buf, buf.gpuAddress, mem, 0}; // 先不进驻留集:第一次被取址时才放进去(pool_res) | not in the residency set yet: put in the first time it is addressed (pool_res) g_pool_adds++; [g_keep addObject:buf]; pthread_mutex_unlock(&g_mu); @@ -437,7 +455,7 @@ int mtl_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off) { pthread_mutex_lock(&g_mu); for (int i = 0; i < g_npool; i++) if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) { - *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break; + pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; ok = 1; break; } pthread_mutex_unlock(&g_mu); return ok; @@ -447,7 +465,7 @@ int mtl_gpu_addr(uint64_t addr, uint64_t len, void **buf, uint64_t *off, uint64_ pthread_mutex_lock(&g_mu); for (int i = 0; i < g_npool; i++) if (addr >= g_pools[i].lo && addr + len <= g_pools[i].hi) { - *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break; + pool_res(i); *buf = (__bridge void *)g_pools[i].buf; *off = addr - g_pools[i].base; *gpu = g_pools[i].gpu + *off; ok = 1; break; } pthread_mutex_unlock(&g_mu); return ok; @@ -845,6 +863,7 @@ uint64_t mtl_sub_commit(void) { [g_q4 commit:buffers count:1 options:o]; [g_q4 signalEvent:g_ev value:fence]; #endif + cb_committed(); g_alloc_fence[g_alloc_cur] = fence; g_cb = nil; g_commit_blocks = nil; @@ -1137,6 +1156,7 @@ static void up_flush(void) { CBUF buffers[] = {cb}; [g_q4 commit:buffers count:1 options:o]; #endif + cb_committed(); g_up_cb = nil; if (g_up_block) { defer_obj_release(g_up_block); g_up_block = nil; } g_up_block_off = g_up_block_size = 0; for (id obj in g_up_keep) defer_obj_release(obj); [g_up_keep removeAllObjects]; @@ -1827,10 +1847,34 @@ static void rp_end(void) { if (g_enc) { } } void pg_sub_begin_ext(uint64_t fence) { pg_sub_begin(fence); } void pg_commit_ext(id cb) { pg_commit(cb); } -static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v) { - a.texture = tex_mtl(t); +// 颜色附件实际挂上的格式:视图换了格式且挂得上就是视图格式,否则底图格式(挂附件与管线预测共用,口径一致)。warn:挂不上时报红 +// The format a colour attachment is actually attached with: the view's format if the view changes the format and it can be attached, otherwise the base texture's format (shared by attaching and pipeline prediction, so both agree). warn: log red when it cannot be attached +static MTLPixelFormat rt_color_fmt(id base, const view_t *v, int has_v, int warn) { + if (!base || !has_v || !v->set_format) return base.pixelFormat; + uint32_t pf = 0; uint8_t swz[4]; + if (!nvn_fmt_to_mtl(v->format, &pf, swz) || !pf) return base.pixelFormat; + if (pf != (uint32_t)base.pixelFormat && tex_need_pfv(base.pixelFormat, (MTLPixelFormat)pf) && !(base.usage & MTLTextureUsagePixelFormatView)) { + if (warn) RED_ONCE(48, "渲染目标视图格式 %#x 挂不上(底图 %lu 没有换格式用途),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat); + return base.pixelFormat; } + return (MTLPixelFormat)pf; +} +// color:颜色附件的视图换了格式(如 RGBA8 底图经 RGBA8_SRGB 视图写)就挂该格式的 Metal 视图——Switch 上写入与清除按视图格式编码, +// 只挂底图则 sRGB 编码整个丢掉、画面偏暗(公开仓库 #36,seedds 在另一款游戏上实测);管线颜色格式取挂上的贴图格式(g_pass.cfmt),随之一致。 +// 视图只活到本次提交跑完(Metal 4 不持有资源;视图与底图同一份存储,不单独驻留)。深度 / 模板附件不换格式 +// color: when the view of a colour attachment changes the format (e.g. an RGBA8 base texture written through an RGBA8_SRGB view), attach a Metal view of that format - on the Switch writes and clears are encoded by the view's format, +// and attaching only the base texture drops the sRGB encoding entirely, making the picture too dark (public repository #36, measured by seedds on another game); the pipeline colour formats take the attached texture's format (g_pass.cfmt), so they follow. +// The view lives only until this submission completes (Metal 4 does not retain resources; the view shares storage with the base texture and is not made resident separately). Depth / stencil attachments do not change format +static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const view_t *v, int has_v, int color) { + id base = tex_mtl(t); a.texture = base; if (has_v && v->set_levels) a.level = v->base_level; if (has_v && v->set_layers) { if (t->d.target == 2) a.depthPlane = v->min_layer; else a.slice = v->min_layer; } + if (!color || !base) return; + MTLPixelFormat pf = rt_color_fmt(base, v, has_v, 1); + if (pf == base.pixelFormat) return; + id vw = [base newTextureViewWithPixelFormat:pf]; + if (!vw) { RED_ONCE(49, "渲染目标视图建不出:格式 %#x(底图 %lu),按底图格式画(首例)", v->format, (unsigned long)base.pixelFormat); return; } + a.texture = vw; defer_obj_unref(vw); + { static int once; if (!once++) MLOG("渲染目标经换格式的视图挂上:视图格式 %#x,底图 %lu → 挂 %lu(首例)", v->format, (unsigned long)base.pixelFormat, (unsigned long)pf); } } // mode 1(clear_only):只为落地挂起的清除而开的通道,只挂有清除的附件;mode 2:前瞻证明本通道不用深度模板,不挂深度。 // clear_only:只为落地挂起的清除而开的通道,只挂有清除的附件——其余附件本通道不碰,挂上去在 TBDR 上平白一读一写 @@ -1855,7 +1899,7 @@ static RENC rp_begin_ex(int clear_only) { int any = 0; for (int i = 0; i < R.rt.n; i++) { if (!R.rt.color[i] || (clear_only == 1 && !R.clear_c[i])) continue; - attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i]); + attach(pd.colorAttachments[i], R.rt.color[i], &R.rt.cview[i], R.rt.has_cview[i], 1); if (!pd.colorAttachments[i].texture) continue; any = 1; pd.colorAttachments[i].loadAction = R.clear_c[i] ? MTLLoadActionClear : MTLLoadActionLoad; @@ -1880,14 +1924,14 @@ static RENC rp_begin_ex(int clear_only) { // clear_only:0 全挂 1 只为清除 2 深度模板都不挂 3 只挂模板 4 只挂深度(3 / 4 由 pass_ds_need 前瞻证明整通道只用那一项) // clear_only: 0 attach all 1 only for clears 2 neither depth nor stencil attached 3 stencil only 4 depth only (3 / 4: the pass_ds_need lookahead proves the whole pass uses only that one) if (R.rt.depth && clear_only == 3) { // 只挂模板:合一格式的深度平面不进 tile、不读不写(Metal 允许深度附件空、模板附件挂合一贴图) | Stencil only: the depth plane of the combined format does not enter the tile and is neither read nor written (Metal allows an empty depth attachment with the combined texture on the stencil attachment) - attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview); + attach(pd.stencilAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0); MTLPixelFormat pf = pd.stencilAttachment.texture.pixelFormat; if (pf == MTLPixelFormatDepth32Float_Stencil8 || pf == MTLPixelFormatStencil8) { any = 1; pd.stencilAttachment.loadAction = R.clear_s ? MTLLoadActionClear : MTLLoadActionLoad; pd.stencilAttachment.clearStencil = R.cs; pd.stencilAttachment.storeAction = MTLStoreActionStore; } else pd.stencilAttachment.texture = nil; // 没有模板平面:模板测试恒过,什么都不挂 | No stencil plane: the stencil test always passes, attach nothing } else if (R.rt.depth && clear_only != 2 && !(clear_only == 1 && !R.clear_d && !R.clear_s)) { - attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview); + attach(pd.depthAttachment, R.rt.depth, &R.rt.dview, R.rt.has_dview, 0); if (pd.depthAttachment.texture) { any = 1; pd.depthAttachment.loadAction = R.clear_d ? MTLLoadActionClear : MTLLoadActionLoad; @@ -3283,7 +3327,7 @@ static void pso_predict_rest(void) { if (!fz_next(&cur, &q, &hq, &aq)) break; if (hq.op == OP_SET_RT) { const p_set_rt *r = aq; memset(cf, 0, sizeof cf); dfull = sfull = 0; samples = 1; - for (int i = 0; i < r->n && i < 8; i++) { id t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)t.pixelFormat; samples = (uint32_t)t.sampleCount; } } + for (int i = 0; i < r->n && i < 8; i++) { id t = r->color[i] ? tex_mtl(r->color[i]) : nil; if (t) { cf[i] = (uint32_t)rt_color_fmt(t, &r->cview[i], r->has_cview[i], 0); samples = (uint32_t)t.sampleCount; } } id dt = r->depth ? tex_mtl(r->depth) : nil; if (dt) { MTLPixelFormat f = dt.pixelFormat; samples = (uint32_t)dt.sampleCount; dfull = f != MTLPixelFormatStencil8 ? (uint32_t)f : 0; sfull = (f == MTLPixelFormatStencil8 || f == MTLPixelFormatDepth32Float_Stencil8) ? (uint32_t)f : 0; } @@ -4472,7 +4516,7 @@ static void draw(const p_draw *dw, const p_draw_idx *di) { if (!strncmp(f->key, "ebcfcd1fa0a77dbc", 16) && !g_enc && R.rt.n == 1 && R.rt.color[0] && !R.clear_c[0]) { uint64_t h = 0; for (int i = 0; i < f->rf.nb && !h; i++) if (f->rf.b[i].kind == NVN_RB_TEX && f->rf.b[i].reg < 128) h = S.tex[1][f->rf.b[i].reg]; if (h) { fx_from = R.rt.color[0]->serial; fx_to = h; PD("N %llu 跳过 FXAA:ser=%llu 的读者改读 ser=%llu", g_stat_pass, (unsigned long long)fx_from, (unsigned long long)h_ser(h)); return; } } - else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) S.tex[1][r] = fx_to; fx_from = 0; } } } + else if (fx_from && !strncmp(f->key, "52aac1f2306b8fc5", 16)) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == fx_from) { S.tex[1][r] = fx_to; g_args_dirty[1] = 1; } fx_from = 0; } } } { static uint64_t bloomq_frame; if (bloomq_frame != atomic_load(&g_cur_frame)) { bloomq_frame = atomic_load(&g_cur_frame); bloomq_reset(); } if (bloomq_enabled() && tbdr_on() && !g_defer_replaying && pr->sh[1]) { NvShader *f = pr->sh[1]; uint64_t tgt = 0; int lv, sl; @@ -4501,14 +4545,14 @@ static void draw(const p_draw *dw, const p_draw_idx *di) { } else if (g_bloomq.state == 2 && !strncmp(f->key, "cc264583f2000c81", 16)) { if (bloomq_target(&tgt, &lv, &sl) && tgt == g_bloomq.b0_ser) { g_bloomq.state = 3; PD("C %llu 泛光 1/4 跳过 B0 上采样", g_stat_pass); return; } } else if (g_bloomq.state == 3 && !strncmp(f->key, "2e2d6700a2569795", 16)) { - if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) S.tex[1][r] = g_bloomq.b1_h; PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); } + if (g_bloomq.b1_h) { for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq.b0_ser) { S.tex[1][r] = g_bloomq.b1_h; g_args_dirty[1] = 1; } PD("D %llu 泛光 1/4 叠加改读 B1", g_stat_pass); g_bloomq_last_b0 = g_bloomq.b0_ser; g_bloomq_last_b1h = g_bloomq.b1_h; g_bloomq_last_b1s = g_bloomq.b1_ser; bloomq_reset(); } else { RED_ONCE(63, "泛光 1/4 状态缺少 B1 句柄"); bloomq_reset(); } } else if (!g_bloomq.state && g_bloomq_last_b1h && h_ser(g_bloomq_last_b1h) == g_bloomq_last_b1s && !strncmp(f->key, "2e2d6700a2569795", 16)) { // B1 句柄仍指同一张贴图(换分辨率重建后不认) | The B1 handle still points to the same texture (not recognized after a rebuild on resolution change) // 本帧泛光链没跑(运行时外推的外推帧跳过了它:输入 469 区域外是上一帧 LDR,不能跑)就到了泛光叠加:照最近一次改读 B1,叠上一帧的泛光。 // 不改读就读 B0——开了泛光 1/4 的话 B0 的上采样一直被跳过、从没写过,读到的是未初始化显存(M4 Pro 上区域里的单位整个发绿,别处多半是 0、缺泛光) // The bloom overlay is reached without the bloom chain having run this frame (the extrapolated frame of runtime extrapolation skipped it: outside the region the input 469 is the previous frame's LDR, so it cannot run): redirect the read to B1 as last time, overlaying the previous frame's bloom. // Without the redirect it would read B0 -- with bloom 1/4 on, B0's upsample is always skipped and never written, so what is read is uninitialized video memory (on M4 Pro the units in the region turn entirely green; elsewhere it is mostly 0, i.e. missing bloom) - int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; } + int hit = 0; for (int r = 0; r < 128; r++) if (S.tex[1][r] && h_ser(S.tex[1][r]) == g_bloomq_last_b0) { S.tex[1][r] = g_bloomq_last_b1h; hit = 1; g_args_dirty[1] = 1; } if (hit) { PD("D %llu 泛光链没跑:叠加沿用上一帧 B1", g_stat_pass); static uint64_t n; if (n++ % 600 == 0) MLOG("泛光 1/4:泛光链没跑的帧叠加沿用上一帧 B1(第 %llu 次)", (unsigned long long)n); } } else if (g_bloomq.state) { RED_ONCE(61, "泛光 1/4 起点:链中途出现别的绘制,本帧泛光不完整"); bloomq_reset(); } } @@ -5678,9 +5722,31 @@ static void present_pipeline(MTLPixelFormat format) { g_blit_samp = [g_dev newSamplerStateWithDescriptor:sd]; } } +// 呈现采样的源:交换链贴图是 sRGB 格式(游戏把交换链建成 RGBA8_SRGB)时经它的非 sRGB 视图采样,屏上显示存的字节,与 Switch 扫描输出一致; +// 直接采样会先解成线性,呈现层(BGRA8Unorm)不再编码,整幅偏暗(公开仓库 #36)。截图读的是原始字节,看不出这一处。 +// 视图按源贴图缓存 4 张、换掉最久没用的:呈现走自己的队列,不能挂主提交的延迟释放;同时在跑的呈现最多 3 帧,被换掉的那张已经用完 +// Source for presentation sampling: when the swapchain texture has an sRGB format (the game created the swapchain as RGBA8_SRGB), sample through its non-sRGB view so the screen shows the stored bytes, as the Switch's scan-out does; +// sampling it directly decodes to linear first, and the present layer (BGRA8Unorm) does not encode again, so the whole picture is too dark (public repository #36). Screenshots read the raw bytes and cannot see this. +// Views are cached per source texture, 4 of them, replacing the least recently used: presentation runs on its own queue and cannot use the deferred release of the main submission; at most 3 presents are in flight, so the replaced one is already done +static id present_src(id src) { + MTLPixelFormat raw = MTLPixelFormatInvalid; + for (size_t i = 0; i < sizeof g_pfv_srgb / sizeof *g_pfv_srgb; i++) if (src.pixelFormat == g_pfv_srgb[i].b) raw = g_pfv_srgb[i].a; + if (raw == MTLPixelFormatInvalid) return src; + static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER; static id cs[4], cv[4]; static uint64_t used[4], tick; + pthread_mutex_lock(&mu); + int k = -1, old = 0; + for (int i = 0; i < 4; i++) { if (cs[i] == src) k = i; if (used[i] < used[old]) old = i; } + if (k < 0) { k = old; cs[k] = src; cv[k] = [src newTextureViewWithPixelFormat:raw]; + if (!cv[k]) RED_ONCE(50, "出图:sRGB 交换链贴图(格式 %lu)的非 sRGB 视图建不出,直接采样(画面会偏暗,首例)", (unsigned long)src.pixelFormat); + else MLOG("出图:交换链贴图是 sRGB 格式 %lu,经格式 %lu 的视图采样", (unsigned long)src.pixelFormat, (unsigned long)raw); } + used[k] = ++tick; id v = cv[k] ?: src; + pthread_mutex_unlock(&mu); + return v; +} // 出图仅采NVN声明的有效源矩形;与原始交换链读回截图分开。边缘钳到有效区纹素中心,双线性不读外侧黑纹素。 // Present samples only the valid source rectangle declared by NVN; kept separate from the raw swapchain readback screenshot. Edges are clamped to the texel centers of the valid area, so bilinear does not read the black texels outside. -static int present_encode(id cb, id src, id dst, const int crop[4]) { +static int present_encode(id cb, id src0, id dst, const int crop[4]) { + id src = present_src(src0); NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height; if (crop && (crop[2] || crop[3])) { if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 || @@ -5719,7 +5785,8 @@ static int present_encode(id cb, id src, id src, id dst, const int crop[4], int uv_i) { +static int present_encode_m4(CBUF cb, id src0, id dst, const int crop[4], int uv_i) { + id src = present_src(src0); NSUInteger cx = 0, cy = 0, cw = src.width, ch = src.height; if (crop && (crop[2] || crop[3])) { if (crop[0] < 0 || crop[1] < 0 || crop[2] <= 0 || crop[3] <= 0 || diff --git a/dm/gfx/tests/.gitignore b/dm/gfx/tests/.gitignore index 4502c8f..cc294b5 100644 --- a/dm/gfx/tests/.gitignore +++ b/dm/gfx/tests/.gitignore @@ -43,3 +43,5 @@ t_xv t_xv.dSYM/ t_ub t_ub.dSYM/ +t_rt_srgb_view +t_rt_srgb_view.dSYM/ diff --git a/dm/gfx/tests/Makefile b/dm/gfx/tests/Makefile index 175e135..b066bee 100644 --- a/dm/gfx/tests/Makefile +++ b/dm/gfx/tests/Makefile @@ -28,6 +28,8 @@ t_pace: t_pace.c ../nvn/nvn_pace.h clang -O1 -Wall -o $@ t_pace.c t_fuse_check: t_fuse_check.m ../../host/crash.c $(GFX) $(GFX_H) clang $(CFLAGS) -fobjc-arc -o $@ t_fuse_check.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW) +t_rt_srgb_view: t_rt_srgb_view.m ../../host/crash.c $(GFX) $(GFX_H) + clang $(CFLAGS) -fobjc-arc -o $@ t_rt_srgb_view.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW) t_present_crop: t_present_crop.m ../nvn/hle_nvn.c ../../host/crash.c $(GFX) $(GFX_H) clang $(CFLAGS) -fobjc-arc -o $@ t_present_crop.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m,$(GFX)) $(FW) t_reorder_chain: t_reorder_chain.m ../../host/crash.c $(GFX) $(GFX_H) @@ -77,6 +79,7 @@ run: \ t_rt_range \ t_rt_range_ro \ t_rt_range_shape \ + t_rt_srgb_view \ t_ub \ t_xv \ t_zskip @@ -108,6 +111,7 @@ run: \ DM_NVN_UNWRITTEN_DC=0 MTL_DEBUG_LAYER=1 ./t_rt_range --sample-attachment --both-flags ./t_pso_skey MTL_DEBUG_LAYER=1 ./t_pfv + MTL_DEBUG_LAYER=1 ./t_rt_srgb_view python3 test_tbdr_budget.py .PHONY: run # 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。 diff --git a/dm/gfx/tests/t_rt_srgb_view.m b/dm/gfx/tests/t_rt_srgb_view.m new file mode 100644 index 0000000..4e8b815 --- /dev/null +++ b/dm/gfx/tests/t_rt_srgb_view.m @@ -0,0 +1,58 @@ +// 换格式的渲染目标视图(公开仓库 #36):RGBA8 底图经 RGBA8_SRGB 视图当颜色附件,清成 0.5 要按 sRGB 编码落进底图; +// 呈现采样 sRGB 交换链贴图要经非 sRGB 视图(读出存的字节)。走生产 rp_begin_ex / rp_end / present_src,4×4 真 Metal 附件。 +// 期望值由常量算,不借被测实现:sRGB 编码 0.5 = 1.055 × 0.5^(1/2.4) − 0.055 = 0.7354 → ×255 = 187.5,硬件取 188;不经视图 = 0.5 × 255 → 128 +// Render-target views that change the format (public repository #36): an RGBA8 base texture used as a colour attachment through an RGBA8_SRGB view must store the sRGB-encoded value when cleared to 0.5; +// presenting from an sRGB swapchain texture must sample through a non-sRGB view (reading the stored bytes). Goes through the production rp_begin_ex / rp_end / present_src with a real 4x4 Metal attachment. +// Expected values come from constants, not from the code under test: sRGB encoding of 0.5 = 1.055 x 0.5^(1/2.4) - 0.055 = 0.7354 -> x255 = 187.5, the hardware gives 188; without the view = 0.5 x 255 -> 128 +#include "../nvn/nvn_mtl.m" +void *front_metal_layer(void) { return NULL; } +module_t *module_of(const void *p) { (void)p; return NULL; } +module_t g_mod[MAX_MOD]; int g_nmod; +void svc_thread_dump(void) {} +uint64_t now_ns(void) { return bp_now(); } + +static int fail, count; +#define EXPECT(name, want, got) do { long long w_ = (want), g_ = (got); count++; \ + printf("%s 期望 %lld → 真结果 %lld %s\n", name, w_, g_, w_ == g_ ? "✓" : "✗"); fail += w_ != g_; } while (0) + +// 清成 0.5 后读回第一个像素的 R 字节;view = 1:经 RGBA8_SRGB 视图挂附件 +// after clearing to 0.5, read back the R byte of the first pixel; view = 1: the attachment goes through an RGBA8_SRGB view +static int clear_and_read(tex_t *t, int view, uint32_t *cfmt) { + memset(&R, 0, sizeof R); R.has_rt = 1; R.rt.n = 1; R.rt.color[0] = t; + if (view) { R.rt.has_cview[0] = 1; R.rt.cview[0].set_format = 1; R.rt.cview[0].format = NVN_FORMAT_RGBA8_SRGB; } + R.clear_c[0] = 1; R.cc[0] = MTLClearColorMake(0.5, 0.5, 0.5, 1); + mtl_sub_begin(); rp_begin_ex(1); *cfmt = g_pass.cfmt[0]; rp_end(); + id b = [g_dev newBufferWithLength:64 options:MTLResourceStorageModeShared]; res_add(b); + [blit() copyFromTexture:tex_mtl(t) sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0, 0, 0) sourceSize:MTLSizeMake(4, 4, 1) + toBuffer:b destinationOffset:0 destinationBytesPerRow:16 destinationBytesPerImage:64]; + enc_b_end(g_blit); g_blit = nil; + uint64_t f = mtl_sub_commit(); + EXPECT("提交完成", 1, mtl_wait(f, 5000000000ull)); + EXPECT("提交反馈无错误", 0, mtl_last_commit_error()); + return ((uint8_t *)b.contents)[0]; +} + +int main(void) { @autoreleasepool { + mtl_init(); + tex_t t = {.serial = 3601}; + t.d.width = t.d.height = 4; t.d.depth = t.d.levels = t.d.samples = 1; t.d.target = NVN_TEXTURE_TARGET_2D; t.d.format = NVN_FORMAT_RGBA8; + uint32_t cf = 0; + EXPECT("负对照:不带视图清 0.5,底图存线性值", 128, clear_and_read(&t, 0, &cf)); + EXPECT("负对照:管线颜色格式 = 底图 RGBA8Unorm", MTLPixelFormatRGBA8Unorm, cf); + EXPECT("经 RGBA8_SRGB 视图清 0.5,底图存 sRGB 编码值", 188, clear_and_read(&t, 1, &cf)); + EXPECT("管线颜色格式跟着视图 = RGBA8Unorm_sRGB", MTLPixelFormatRGBA8Unorm_sRGB, cf); + + MTLTextureDescriptor *d = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm_sRGB width:4 height:4 mipmapped:NO]; + d.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget; d.storageMode = MTLStorageModePrivate; + id s = [g_dev newTextureWithDescriptor:d], s2 = [g_dev newTextureWithDescriptor:d]; + id v = present_src(s); + EXPECT("呈现:sRGB 交换链经 RGBA8Unorm 视图采样", MTLPixelFormatRGBA8Unorm, v.pixelFormat); + EXPECT("呈现:视图的底图就是交换链贴图", 1, v.parentTexture == s); + EXPECT("呈现:同一张交换链贴图第二次取到同一个视图(缓存)", 1, present_src(s) == v); + id v2 = present_src(s2); + EXPECT("呈现:另一张交换链贴图各自一个视图", 1, v2 != v && v2.parentTexture == s2); + id plain = tex_mtl(&t); + EXPECT("呈现:非 sRGB 交换链原样采样", 1, present_src(plain) == plain); + EXPECT("全程没有报红", 0, g_red_once[48] + g_red_once[49] + g_red_once[50]); + printf("== %d 项,失败 %d ==\n", count, fail); return fail != 0; +} } diff --git a/dm/host/Makefile b/dm/host/Makefile index 643e6e6..3ba9260 100644 --- a/dm/host/Makefile +++ b/dm/host/Makefile @@ -96,8 +96,8 @@ dm_bright_levels.inc: ../tools/gen_bright_levels.py ../ios/tools/touch_layout.py $(NEED_ROMFS) python3 ../tools/gen_bright_levels.py "$(ROMFS)" > $@.tmp && mv $@.tmp $@ dmhost: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH) - 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 -framework Network + clang $(CFLAGS) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network # 老接口版宿主(图形后端不用 Metal 4,目标 macOS 15.0):同一棵树、同一份源码,只多一个编译开关;不在缺省目标里,要用时 make dmhost_m3 # Older-API host (graphics backend without Metal 4, target macOS 15.0): the same tree and the same source, with just one more compile switch; not in the default targets, run make dmhost_m3 when needed dmhost_m3: $(SRC) $(GFX) $(LIBDEFLATE) dm.h hle.h dm_input.h front.h touch_mac.h dm_cursor.h dm_i18n_tab.h ../ios/Sources/dm_touch_controls.[ch] $(GFX_H) $(GENH) - clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network + clang $(CFLAGS_M3) -I. -I../gfx/nvn/include -fobjc-arc -o $@ $(SRC) $(GFX) $(LIBDEFLATE) -framework Cocoa -framework QuartzCore -framework Metal -framework AudioToolbox -framework CoreAudio -framework ImageIO -framework UniformTypeIdentifiers -framework GameController -framework Network diff --git a/dm/host/app_mac.m b/dm/host/app_mac.m index 19ca632..6b689c9 100644 --- a/dm/host/app_mac.m +++ b/dm/host/app_mac.m @@ -110,6 +110,7 @@ int dm_app_bootstrap(int *argc, char ***argv) { if (!getenv("DM_TOUCH_DEFAULTS")) setenv("DM_TOUCH_DEFAULTS", "1", 1); // 产品缺省同 iOS 包(hle_fs.c settings_seed:玩家没碰过的设置键补上——小地图放右上角、进局自动打开、显示物品用开关式等;已有的键不动)。命令行宿主缺省不做,那边要对 Switch 真值比图 | product defaults same as the iOS package (hle_fs.c settings_seed: fills in settings keys the player has never touched - minimap in the top-right corner, opened automatically on entering a game, show-items as a toggle, and so on; existing keys are left alone). The command-line host does not do this by default, since it has to be compared against Switch ground-truth images if (!getenv("DM_APP_SUPPORT")) setenv("DM_CLOUD_REAL", "1", 1); // iCloud 同步(ios/Sources/cloud_ios.m,两端共用)只认玩家真实的存档目录;测试用的支持目录一律不同步 | iCloud sync (ios/Sources/cloud_ios.m, shared by both platforms) only recognises the player's real save directory; a support directory used for testing is never synced setenv("DM_WINDOW", "1", 1); setenv("DM_APP", "1", 1); + if (!getenv("DM_AUDIO")) setenv("DM_AUDIO", "1", 1); // 产品要出声(hle_audio.c 在 Mac 上的缺省是给命令行回放 / 闸门的静音接收端);无人值守测试显式 DM_AUDIO=0 | the product must play sound (on the Mac, hle_audio.c defaults to the silent sink used for command-line replays / gates); unattended tests set DM_AUDIO=0 explicitly 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 diff --git a/dm/host/front_mac.m b/dm/host/front_mac.m index 5ab983e..06d1810 100644 --- a/dm/host/front_mac.m +++ b/dm/host/front_mac.m @@ -8,6 +8,7 @@ #include #import #import +#import #include "dm.h" #include "dm_input.h" #include "dm_uiscreen.h" @@ -23,16 +24,36 @@ static int g_live; // App 形态(或 DM_TOUCH_LIVE=1):鼠标进我们的 static CAMetalLayer *g_layer; static NSWindow *g_win; 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 +// 真全屏(App 形态,屏幕比 16:9 窄——16:10 的 MacBook,「不能全屏」:全屏后上下各 56 点黑边):照 iPad 那套(front_ios.m、dm_uiscreen.c)—— +// 启动时按屏幕比例(全屏时的内容区:屏幕扣掉刘海安全区)定游戏分辨率,局内 3D 铺满、界面按 16:9 贴底(开大面板居中),前端各页与读取画面游戏自己按 16:9 出、上下留边。 +// 窗口锁成同一比例,窗口态与全屏态都铺满。屏幕不比 16:9 窄(外接 16:9 / 更宽的屏):照旧全程 16:9。比例在启动时按主屏定,之后挪到别的屏不重算(游戏分辨率只在启动时定)。 +// 测试开关 DM_TEST_SCREEN_ASPECT=<宽>x<高>:当作主屏是这个比例(16x9 = 外接 16:9 屏的口径) +// True full screen (App form, screen narrower than 16:9 - a 16:10 MacBook, "cannot go full screen": 56 points of black bar above and below in full screen): the iPad approach (front_ios.m, dm_uiscreen.c) - +// at launch the game resolution is set from the screen's aspect ratio (the full-screen content area: the screen minus the notch safe area); in game the 3D fills the screen, the interface is 16:9 along the bottom (centred with a large panel open), and the front-end pages and the loading screen are drawn by the game at 16:9 with bars above and below. +// The window is locked to the same ratio, so both windowed and full screen are filled. Screens not narrower than 16:9 (external 16:9 / wider screens): 16:9 throughout as before. The ratio is set from the main screen at launch and not recomputed when moved to another screen (the game resolution is only set at launch). +// Test switch DM_TEST_SCREEN_ASPECT=x: treat the main screen as this ratio (16x9 = the external 16:9 screen case) +static double g_aspect = 16.0 / 9; // 游戏画面比例(宽 ÷ 高) | aspect ratio of the game picture (width / height) +static int g_full; // 1 = 真全屏已开 | 1 = true full screen is on +static void full_setup(void) { + if (!getenv("DM_APP") || getenv("DM_GAME_RES")) return; + NSScreen *sc = NSScreen.mainScreen; double w = sc.frame.size.width, h = sc.frame.size.height - sc.safeAreaInsets.top; const char *e = getenv("DM_TEST_SCREEN_ASPECT"); unsigned tw, th; + if (e && sscanf(e, "%ux%u", &tw, &th) == 2 && tw && th) { w = tw; h = th; } + if (h <= 0 || w / h >= 16.0 / 9 - 0.01) { LOG("画面:主屏 %.0fx%.0f 不比 16:9 窄 → 全程 16:9", w, h); return; } + g_aspect = w / h; g_full = 1; dm_uiscreen_enable(DM_UISCREEN_BOTTOM); + LOG("画面:主屏全屏内容区 %.0fx%.0f(比例 %.3f)比 16:9 窄 → 真全屏:窗口锁这个比例,局内铺满、界面贴底,前端 16:9 留边", w, h, g_aspect); +} +// 游戏画面在视图里的位置:按游戏画面比例放进视图(比例对得上就是整个视图;对不上的四周留黑边) +// Where the game picture sits in the view: fitted into the view by the picture's aspect ratio (if the ratios match, the whole view; otherwise black bars around) 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); + if (fabs(w / h / g_aspect - 1) < 0.003) { } // 比例差 0.3% 以内(窗口高取整的零头、全屏内容区比按刘海安全区算的少 1 点)当对得上,铺满 | within 0.3% (the remainder from rounding the window height, and the full-screen content area being 1 point less than computed from the notch safe area) counts as matching, and it fills + else if (w > h * g_aspect) w = round(h * g_aspect); else h = round(w / g_aspect); 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]; + CGFloat sc = g_view.window.backingScaleFactor ?: 2; // 画布跟着改:作为子层的 CAMetalLayer 改 frame 不会自己改 drawableSize,原先进全屏后一直用窗口态的画布放大显示(发糊) | the canvas follows: a CAMetalLayer used as a sublayer does not change its drawableSize when its frame changes, so after going full screen it used to keep the windowed canvas and scale it up (blurry) + [CATransaction begin]; [CATransaction setDisableActions:YES]; g_layer.frame = r; g_layer.contentsScale = sc; g_layer.drawableSize = CGSizeMake(round(r.size.width * sc), round(r.size.height * sc)); [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 秒,再有序收尾。 @@ -41,6 +62,7 @@ static void layout_game(void) { // 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; + { uint64_t dm_audio_render_calls(void); LOG("窗口:退出(%s);声卡回调累计 %llu(0 = 这次没出声)", why, (unsigned long long)dm_audio_render_calls()); } 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; @@ -112,6 +134,7 @@ void *front_metal_layer(void) { return (__bridge void *)g_layer; } uint64_t front_game_res(int docked) { unsigned w, h; const char *e = getenv("DM_GAME_RES"); if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4; + if (g_full) return docked ? (uint64_t)(llround(1600 / g_aspect / 2) * 2) << 32 | 1600 : 720ull << 32 | (uint64_t)(llround(720 * g_aspect / 8) * 8); // 真全屏:宽 1600、高按屏幕比例(16:10 → 1600x1004) | true full screen: width 1600, height by the screen's aspect ratio (16:10 -> 1600x1004) return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280; } @@ -155,14 +178,15 @@ void front_run(void (*guest)(void)) { @autoreleasepool { [NSApplication sharedApplication]; [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular]; - NSRect r = NSMakeRect(0, 0, 1280, 720); + full_setup(); + NSRect r = NSMakeRect(0, 0, 1280, floor(1280 / g_aspect)); NSWindow *win = [[NSWindow alloc] initWithContentRect:r styleMask:NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable backing:NSBackingStoreBuffered defer:NO]; win.title = @"D2R Mobile"; win.restorable = NO; g_win = win; NSView *v = win.contentView; g_view = v; v.wantsLayer = YES; v.layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack); - win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, 360); + win.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary; win.contentMinSize = NSMakeSize(640, floor(640 / g_aspect)); if (g_full) win.contentAspectRatio = NSMakeSize(1280, 1280 / g_aspect); static DmWinCtl *ctl; ctl = [DmWinCtl new]; win.delegate = ctl; g_layer = [CAMetalLayer layer]; g_layer.device = MTLCreateSystemDefaultDevice(); @@ -196,6 +220,18 @@ void front_run(void (*guest)(void)) { 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 + if (g_full && g_live) { // 真全屏:状态机吃界面矩形里的归一化坐标(同 iOS 的游戏视图)。两步: | true full screen: the state machine takes normalised coordinates inside the interface rectangle (like the iOS game view). Two steps: + // ① 先换到「实际显示的那块」:游戏当前分辨率(前端 16:9、局内整屏)按比例居中放进游戏画面,与上屏同一口径(nvn_mtl.m present_encode:比例差 1% 内铺满); + // ② 再换到界面矩形(局内贴底)。局内界面矩形外是 3D 世界,带符号交下去(点世界换回整屏,touch_mac.c);不在局内时显示块外是黑边,不算点 + // (1) First map to "the block actually shown": the game's current resolution (16:9 in the front end, the whole screen in game) placed centred in the game picture by aspect ratio, the same measure as presentation (nvn_mtl.m present_encode: fill when the aspect ratios differ by less than 1%); + // (2) then map to the interface rectangle (along the bottom in game). In game, outside the interface rectangle is the 3D world, passed down with a sign (tapping the world maps back to the whole screen, touch_mac.c); outside the game the area beyond the shown block is the black bars, not counted as a tap + int rw = 0, rh = 0; double cx = 0, cy = 0, cw = 1, ch = 1; + if (dm_screen_real(&rw, &rh) && rw > 0 && rh > 0) { double ca = (double)rw / rh, ga = gr.size.width / gr.size.height; + if (fabs(ga / ca - 1) >= 0.01) { if (ga > ca) { cw = ca / ga; cx = (1 - cw) / 2; } else { ch = ga / ca; cy = (1 - ch) / 2; } } } + float vx = (float)((nx - cx) / cw), vy = (float)((ny - cy) / ch); + double fy = 0, fh = 1; ui_rect_frac(&fy, &fh); float uy = fh > 0 ? (float)((vy - fy) / fh) : vy; + if (e.type == NSEventTypeLeftMouseDown && !dm_uiscreen_ingame() && (vx < 0 || vx > 1 || uy < 0 || uy > 1)) return nil; + dm_touch_host_live(e.type == NSEventTypeLeftMouseDown ? 0 : 1, vx, uy); return nil; } 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; @@ -218,7 +254,22 @@ void front_run(void (*guest)(void)) { 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_FULLSCREEN_AT"))) for (const char *q = e; q && *q; q = strchr(q, ';') ? strchr(q, ';') + 1 : NULL) // 「秒[;秒…]」:每个时刻切一次全屏(来回切) | "seconds[;seconds...]": toggle full screen at each time (back and forth) + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(atof(q) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [win toggleFullScreen:nil]; }); + // DM_TEST_PRESENT_SHOT=<秒>:<路径>[;<秒>:<路径>…]:到点取下一次上屏的画面(图形层与上屏同一套编码,见 nvn_mtl.m mtl_grab_next_present)写成 PNG—— + // 看的是玩家真看到的(含留边位置),不是游戏出图贴图(DM_NVN_SHOT_UI 取的那张,裁切区不居中) + // DM_TEST_PRESENT_SHOT=:[;:...]: at the given time, grab the next presented picture (the graphics layer uses the same encoding as presentation, see nvn_mtl.m mtl_grab_next_present) and write it as PNG - + // this is what the player actually sees (including where the bars are), not the game's output texture (the one DM_NVN_SHOT_UI takes, whose crop is not centred) + if ((e = getenv("DM_TEST_PRESENT_SHOT"))) { void mtl_grab_next_present(void (^cb)(CGImageRef img)); + for (NSString *it in [@(e) componentsSeparatedByString:@";"]) { NSRange c = [it rangeOfString:@":"]; if (c.location == NSNotFound) continue; + double at = [it substringToIndex:c.location].doubleValue; NSString *path = [it substringFromIndex:c.location + 1]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(at * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ + NSSize vb = v.bounds.size; NSRect gr = game_rect(); double fy = 0, fh = 1; ui_rect_frac(&fy, &fh); + mtl_grab_next_present(^(CGImageRef img) { if (!img) { LOG("【红】DM_TEST_PRESENT_SHOT:%s 没取到", path.UTF8String); return; } + CGImageDestinationRef d = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:path], (__bridge CFStringRef)@"public.png", 1, NULL); + if (d) { CGImageDestinationAddImage(d, img, NULL); CGImageDestinationFinalize(d); CFRelease(d); } + LOG("DM_TEST_PRESENT_SHOT:%s %zux%zu(内容区 %.0fx%.0f,游戏画面 %.0fx%.0f 在 (%.0f,%.0f),界面矩形纵向 %.3f 高 %.3f,%s)", path.UTF8String, CGImageGetWidth(img), CGImageGetHeight(img), + vb.width, vb.height, gr.size.width, gr.size.height, gr.origin.x, gr.origin.y, fy, fh, dm_uiscreen_ingame() ? "局内" : "局外"); }); }); } } // DM_TEST_NSMOUSE=<文件>:合成真正的系统鼠标事件(NSEvent)投进 App 的事件队列,走与真人点击同一条分发路(事件监视器 → 换算 → 状态机),不经测试入口。 // 每行「秒 down|move|up x,y」,x,y 是内容区里的点(左上角为原点;窗口缺省 1280×720),时刻自窗口建好起算 // DM_TEST_NSMOUSE=: synthesise real system mouse events (NSEvent) and post them to the App's event queue, going through the same dispatch path as a person clicking (event monitor -> conversion -> state machine), not through the test entry. diff --git a/dm/host/hle_audio.c b/dm/host/hle_audio.c index 8c3eed0..83ff303 100644 --- a/dm/host/hle_audio.c +++ b/dm/host/hle_audio.c @@ -1,11 +1,15 @@ // nn::audio AudioOut:游戏(FMOD nx 输出层)按块追加 PCM 缓冲,播完由系统放回「已释放」队列并触发事件。 // 宿主:真出声 = CoreAudio AudioUnit(Mac DefaultOutput / iOS RemoteIO);静音接收端 = 按真实时间消耗缓冲(不出声,节奏与真机一致)。 -// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声。 +// iOS 缺省真出声(产品必须有声音),测试要静音显式 DM_AUDIO=0;Mac 命令行宿主缺省静音接收端(回放 / 闸门不出声),DM_AUDIO=1 真出声; +// Mac App(app_mac.m)是产品,启动时设 DM_AUDIO=1(「没有声音」:之前 App 也走了命令行的缺省,从来不出声)。 +// 声卡打不开(没有输出设备等)不再退出:记红,这一路改由静音接收端按实时消耗,游戏照常跑。 // AudioOut / AudioOutBuffer / AudioOutParameter 的内容只经下列接口读写,宿主自定内部布局,只写结构体前部。 -// nn::audio AudioOut: the game (FMOD nx output layer) appends PCM buffers block by block; once played the system puts them back on the "released" queue and signals the event. -// Host: real audio output = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = consumes buffers in real time (no sound, pacing matches the real device). -// iOS defaults to real audio output (the product must have sound), tests that want silence set DM_AUDIO=0 explicitly; Mac defaults to the silent sink (replay / gate checks are silent), DM_AUDIO=1 for real audio output. -// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and only writes the front part of the structs. +// nn::audio AudioOut: the game (FMOD's nx output layer) appends PCM buffers in blocks; once played the system puts them back on the "released" queue and signals an event. +// Host: real sound = CoreAudio AudioUnit (Mac DefaultOutput / iOS RemoteIO); silent sink = buffers consumed in real time (no sound, same pacing as the device). +// iOS plays real sound by default (the product must have sound), tests set DM_AUDIO=0 explicitly for silence; the Mac command-line host defaults to the silent sink (replays / gates are silent), DM_AUDIO=1 for real sound; +// the Mac App (app_mac.m) is the product and sets DM_AUDIO=1 at launch ("no sound": the App used to take the command-line default and never played sound). +// If the sound card cannot be opened (no output device etc.) it no longer exits: logs red, and this channel is consumed in real time by the silent sink while the game runs on. +// The contents of AudioOut / AudioOutBuffer / AudioOutParameter are read and written only through the interfaces below; the host defines its own internal layout and writes only the front part of each struct. #include "hle.h" #include #include @@ -27,6 +31,8 @@ typedef struct { gbuf *rel[RELMAX]; _Atomic uint32_t rel_head, rel_tail; // 已释放:出声端写,游戏侧读 | Released: written by the output side, read by the game side uint64_t pos; // 当前块已播字节 | Bytes already played of the current block AudioUnit au; + int mix; // 1 = 游戏给 5.1(6 声道),交给 CoreAudio 前我们自己下混成双声道(au_render) | 1 = the game gives 5.1 (6 channels), downmixed to stereo by us before handing to CoreAudio (au_render) + int16_t *mixbuf; // 下混用的 6 声道暂存(MIXMAX 帧) | 6-channel staging for the downmix (MIXMAX frames) pthread_t null_th; _Atomic int null_run; dispatch_semaphore_t notify_sem; pthread_t notify_th; _Atomic int notify_run, notify_pending, notify_armed; @@ -89,14 +95,39 @@ static void pull(aout *a, uint8_t *dst, uint64_t n) { static _Atomic uint64_t g_render_calls; // 声卡回调累计(生命周期验证:恢复后须继续增长) | Cumulative sound card callbacks (lifecycle verification: must keep growing after resume) uint64_t dm_audio_render_calls(void) { return atomic_load_explicit(&g_render_calls, memory_order_relaxed); } +// 5.1 → 双声道(公开 的:原先把游戏的 6 声道原样交给 AudioUnit、不设声道布局,系统隐式转换只取前两路,中置——NPC 对白——整路丢掉)。 +// 游戏的声道顺序(Mac App 走到阿卡拉跟前、对白开口那半秒按声道量能量实测:只有第 3 路跳起来):左前、右前、中置、低音、左后、右后。 +// 系数照 ITU-R BS.775 的 Lo/Ro:L = 左前 + 0.707·中置 + 0.707·左后,R 对称;低音不并入(标准下混不含 LFE,并进去会让低频发闷); +// 整体再乘 0.707 留 3 dB 余量,仍超出 16 位的饱和截断。Q15 定点:0.707 = 23170,0.707 × 0.707 = 16384 +// 5.1 -> stereo (previously: the game's 6 channels were handed to the AudioUnit as is without a channel layout; the system's implicit conversion took only the first two, and the centre - NPC dialogue - was dropped entirely). +// The game's channel order (measured in the Mac App by per-channel energy during the half second Akara starts speaking: only channel 3 jumps): front left, front right, centre, LFE, rear left, rear right. +// Coefficients from the ITU-R BS.775 Lo/Ro downmix: L = front left + 0.707*centre + 0.707*rear left, R symmetric; LFE is not mixed in (the standard downmix excludes LFE, and mixing it in muddies the low end); +// the whole is multiplied by 0.707 again for 3 dB of headroom, and anything still beyond 16 bits is saturated. Q15 fixed point: 0.707 = 23170, 0.707 x 0.707 = 16384 +#define MIXMAX 4096 +static void downmix51(const int16_t *in, int16_t *out, unsigned frames) { + for (unsigned i = 0; i < frames; i++, in += 6, out += 2) { + int32_t l = (23170 * in[0] + 16384 * in[2] + 16384 * in[4]) >> 15, r = (23170 * in[1] + 16384 * in[2] + 16384 * in[5]) >> 15; + out[0] = (int16_t)(l > 32767 ? 32767 : l < -32768 ? -32768 : l); out[1] = (int16_t)(r > 32767 ? 32767 : r < -32768 ? -32768 : r); } +} static OSStatus au_render(void *ctx, AudioUnitRenderActionFlags *f, const AudioTimeStamp *ts, UInt32 bus, UInt32 frames, AudioBufferList *bl) { (void)f; (void)ts; (void)bus; (void)frames; aout *a = ctx; atomic_fetch_add_explicit(&g_render_calls, 1, memory_order_relaxed); - pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize); + if (!a->mix) pull(a, bl->mBuffers[0].mData, bl->mBuffers[0].mDataByteSize); + else { int16_t *o = bl->mBuffers[0].mData; unsigned left = bl->mBuffers[0].mDataByteSize / 4; // 双声道 16 位:每帧 4 字节 | stereo 16-bit: 4 bytes per frame + while (left) { unsigned k = left < MIXMAX ? left : MIXMAX; pull(a, (uint8_t *)a->mixbuf, (uint64_t)k * 12); downmix51(a->mixbuf, o, k); o += 2 * k; left -= k; } } + // 诊断开关 DM_AUDIO_OUT_DUMP=<文件>:交给 CoreAudio 的那份数据原样续写(下混后是双声道)。本机没有回环设备录不到系统输出,判「对白有没有交出去」看这份 + // Diagnostic switch DM_AUDIO_OUT_DUMP=: append the data handed to CoreAudio as is (stereo after the downmix). This machine has no loopback device and cannot record the system output; to tell whether the dialogue was handed over, look at this file + { static FILE *df; static int on = -1; if (on < 0) { const char *e = getenv("DM_AUDIO_OUT_DUMP"); on = e != NULL; if (on && !(df = fopen(e, "wb"))) LOG("【红】DM_AUDIO_OUT_DUMP 打不开 %s", e); } + if (df) fwrite(bl->mBuffers[0].mData, 1, bl->mBuffers[0].mDataByteSize, df); } return noErr; } -static void au_open(aout *a) { +#if !TARGET_OS_IPHONE +static void dev_name(AudioObjectID id, char *o, size_t n) { // 输出设备名(日志用) | output device name (for the log) + CFStringRef nm = NULL; UInt32 sz = sizeof nm; AudioObjectPropertyAddress pa = { kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; + o[0] = 0; if (!AudioObjectGetPropertyData(id, &pa, 0, NULL, &sz, &nm) && nm) { CFStringGetCString(nm, o, (CFIndex)n, kCFStringEncodingUTF8); CFRelease(nm); } } +#endif +static int au_open(aout *a) { // 0 = 声卡开好了;-1 = 开不了(a->au 置空,调用方走静音接收端) | 0 = the sound card is open; -1 = it cannot be opened (a->au set to null, the caller uses the silent sink) AudioComponentDescription d = {.componentType = kAudioUnitType_Output, #if TARGET_OS_IPHONE .componentSubType = kAudioUnitSubType_RemoteIO, @@ -105,15 +136,28 @@ static void au_open(aout *a) { #endif .componentManufacturer = kAudioUnitManufacturer_Apple}; AudioComponent c = AudioComponentFindNext(NULL, &d); - if (!c || AudioComponentInstanceNew(c, &a->au)) die("AudioUnit 建不出来"); + if (!c || AudioComponentInstanceNew(c, &a->au)) { a->au = NULL; LOG("【红】AudioUnit 建不出来:这一路改用静音接收端(不出声)"); return -1; } + a->mix = a->ch == 6; if (a->mix && !a->mixbuf) a->mixbuf = malloc(MIXMAX * 12); // 5.1:我们自己下混,AudioUnit 只收双声道(单 / 双声道照旧原样交) | 5.1: we downmix ourselves and the AudioUnit only takes stereo (mono / stereo are passed through as before) + if (a->mix && !a->mixbuf) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】下混暂存申请不到:这一路改用静音接收端(不出声)"); return -1; } + int och = a->mix ? 2 : a->ch; AudioStreamBasicDescription f = {.mSampleRate = RATE, .mFormatID = kAudioFormatLinearPCM, .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, - .mBytesPerPacket = 2u * a->ch, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * a->ch, - .mChannelsPerFrame = (UInt32)a->ch, .mBitsPerChannel = 16}; + .mBytesPerPacket = 2u * och, .mFramesPerPacket = 1, .mBytesPerFrame = 2u * och, + .mChannelsPerFrame = (UInt32)och, .mBitsPerChannel = 16}; + if (a->mix) LOG("audio:游戏给 6 声道(5.1)→ 交给声卡前自己下混成双声道(中置 / 后环绕 ×0.707 并入左右,低音不并入,整体 −3 dB、饱和截断)"); AURenderCallbackStruct cb = {au_render, a}; if (AudioUnitSetProperty(a->au, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &f, sizeof f) || AudioUnitSetProperty(a->au, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &cb, sizeof cb) || - AudioUnitInitialize(a->au)) die("AudioUnit 设置失败"); + AudioUnitInitialize(a->au)) { AudioComponentInstanceDispose(a->au); a->au = NULL; LOG("【红】AudioUnit 设置失败(没有输出设备?):这一路改用静音接收端(不出声)"); return -1; } +#if !TARGET_OS_IPHONE + { // 缺省输出单元跟随系统缺省输出设备:两个都记下来,核「声音从系统选的那个设备出」 | the default output unit follows the system default output device: record both, to check that "the sound comes out of the device the system chose" + AudioObjectID cur = 0, def = 0; UInt32 sz = sizeof cur; char cn[128], dn[128]; + AudioUnitGetProperty(a->au, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &cur, &sz); + AudioObjectPropertyAddress pa = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain }; sz = sizeof def; + AudioObjectGetPropertyData(kAudioObjectSystemObject, &pa, 0, NULL, &sz, &def); dev_name(cur, cn, sizeof cn); dev_name(def, dn, sizeof dn); + LOG("audio:输出设备「%s」(%u),系统缺省输出「%s」(%u)%s", cn, (unsigned)cur, dn, (unsigned)def, cur == def ? ",一致" : "【红】不一致"); } +#endif + return 0; } // 静音接收端:每 5 ms 按 48 kHz 实时消耗 // Silent sink: consumes in real time at 48 kHz every 5 ms @@ -158,15 +202,15 @@ HLE_FORCE("_ZN2nn5audio12OpenAudioOutEPNS0_8AudioOutEPNS_2os11SystemEventEPKcRKN g_aos[slot] = a; pthread_mutex_unlock(&g_aos_lock); LOG("audio::OpenAudioOut %s 声道 %d %s", name ? name : "(默认)", ch, real_audio() ? "真出声" : "静音接收端"); - if (real_audio()) au_open(a); + if (real_audio()) au_open(a); // 开不了就 a->au 为空,开始播放时走静音接收端 | if it cannot be opened, a->au is null, and playback goes to the silent sink when it starts return RES_OK; } HLE_FORCE("_ZN2nn5audio13StartAudioOutEPNS0_8AudioOutE", "开始播放", Result, h_au_Start, void *g) { aout *a = ao(g); pthread_mutex_lock(&a->m); int was = atomic_load_explicit(&a->state, memory_order_relaxed); atomic_store_explicit(&a->state, STATE_STARTED, memory_order_release); pthread_mutex_unlock(&a->m); if (was == STATE_STARTED) return RES_OK; - if (a->au && !g_suspended) { if (AudioOutputUnitStart(a->au)) die("AudioUnit 启动失败"); } - else { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); } + if (a->au && !g_suspended && AudioOutputUnitStart(a->au)) { LOG("【红】AudioUnit 启动失败:这一路改用静音接收端(不出声)"); AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); a->au = NULL; } + if (!a->au || g_suspended) { atomic_store_explicit(&a->null_run, 1, memory_order_release); pthread_create(&a->null_th, NULL, null_sink, a); } return RES_OK; } HLE_FORCE("_ZN2nn5audio12StopAudioOutEPNS0_8AudioOutE", "停止播放", void, h_au_Stop, void *g) { @@ -188,7 +232,7 @@ HLE_FORCE("_ZN2nn5audio13CloseAudioOutEPNS0_8AudioOutE", "关闭音频输出", v pthread_mutex_unlock(&g_aos_lock); if (a->au) { AudioUnitUninitialize(a->au); AudioComponentInstanceDispose(a->au); } dispatch_release(a->notify_sem); - pthread_mutex_destroy(&a->m); free(a); + free(a->mixbuf); pthread_mutex_destroy(&a->m); free(a); } HLE_FORCE("_ZN2nn5audio16GetAudioOutStateEPKNS0_8AudioOutE", "播放状态", int, h_au_State, const void *g) { return atomic_load_explicit(&ao(g)->state, memory_order_acquire); } HLE_FORCE("_ZN2nn5audio21GetAudioOutSampleRateEPKNS0_8AudioOutE", "采样率", int, h_au_Rate, const void *g) { (void)ao(g); return RATE; } diff --git a/dm/host/tests/Makefile b/dm/host/tests/Makefile index a37e854..fbc5380 100644 --- a/dm/host/tests/Makefile +++ b/dm/host/tests/Makefile @@ -104,11 +104,11 @@ $(B)/t_touch: t_touch.c ../hle_touch.c ../front.h ../dm.h | $(B) $(B)/t_fs: t_fs.c t_fs_stub.c ../hle_fs.c ../hle.h ../dm.h ../dm_i18n.c | $(B) clang -O1 -Wno-unused-function -I.. -o $@ t_fs.c t_fs_stub.c ../dm_i18n.c $(B)/t_audio: t_audio.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox + clang -O1 -Wno-unused-function -I.. -o $@ t_audio.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_audio_spsc: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox + clang -O1 -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_audio_spsc_tsan: t_audio_spsc.c ../hle_audio.c ../hle.h ../dm.h | $(B) - clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox + clang -O1 -g -O1 -fsanitize=thread -Wno-unused-function -I.. -o $@ t_audio_spsc.c -framework AudioToolbox -framework CoreAudio -framework CoreFoundation $(B)/t_swkbd: t_swkbd.c ../hle_swkbd.c ../hle.h ../dm.h | $(B) clang -O1 -Wno-unused-function -I.. -o $@ t_swkbd.c ../hle_swkbd.c $(B)/t_movie: t_movie.c ../hle_movie.c ../hle.h ../dm.h | $(B) diff --git a/dm/host/tests/t_audio.c b/dm/host/tests/t_audio.c index cfac9a0..f030808 100644 --- a/dm/host/tests/t_audio.c +++ b/dm/host/tests/t_audio.c @@ -13,6 +13,18 @@ static _Atomic int g_sig; void hle_signal_system_event(void *g) { (void)g; atomic_fetch_add_explicit(&g_sig, 1, memory_order_seq_cst); } void hle_bind_system_event(void *g, int autoclear) { (void)g; (void)autoclear; } // 真实现要客体线程 + SDK 内核事件;单测只数触发次数 | the real implementation needs a guest thread + SDK kernel event; the unit test only counts triggers int main(void) { + { // 5.1 下混(期望按 Q15 系数手算:0.707·0.707 = 16384/32768 = 0.5,0.707 = 23170/32768):顺序 左前 右前 中置 低音 左后 右后 | 5.1 downmix (expected values worked out by hand from the Q15 coefficients: 0.707*0.707 = 16384/32768 = 0.5, 0.707 = 23170/32768): order front left, front right, centre, LFE, rear left, rear right + static const struct { int16_t in[6]; int16_t l, r; const char *what; } c[] = { + { { 0, 0, 10000, 0, 0, 0 }, 5000, 5000, "只有中置(对白)→ 左右各 5000" }, + { { 0, 0, 0, 0, 10000, 0 }, 5000, 0, "只有左后 → 左 5000、右 0" }, + { { 10000, 0, 0, 0, 0, 0 }, 7070, 0, "只有左前 → 左 7070(−3 dB)" }, + { { 0, 0, 0, 30000, 0, 0 }, 0, 0, "只有低音 → 不并入,0" }, + { { 32767, 32767, 32767, 0, 32767, 32767 }, 32767, 32767, "满幅叠加 → 饱和到 32767" }, + { { -32768, -32768, -32768, 0, -32768, -32768 }, -32768, -32768, "负满幅叠加 → 饱和到 −32768" } }; + int bad = 0; + for (unsigned i = 0; i < sizeof c / sizeof *c; i++) { int16_t o[2]; downmix51(c[i].in, o, 1); int ok = o[0] == c[i].l && o[1] == c[i].r; bad |= !ok; + printf("下混:%s:期望 (%d,%d) → 真结果 (%d,%d) %s\n", c[i].what, c[i].l, c[i].r, o[0], o[1], ok ? "✓" : "✗"); } + if (bad) return 1; } char out[64], ev[64]; uint8_t prm[16]; gbuf b[3]; static int16_t pcm[3][4800 * 2]; h_au_InitParam(prm); if (h_au_Open(out, ev, NULL, prm)) return 1; diff --git a/dm/host/tests/t_touch_mac.c b/dm/host/tests/t_touch_mac.c index 6aeb7b3..2dad65b 100644 --- a/dm/host/tests/t_touch_mac.c +++ b/dm/host/tests/t_touch_mac.c @@ -33,6 +33,7 @@ void dm_elysium_arm(int on) { (void)on; } // 极乐世界勾选(dm_elysium.c void dm_custom_on_uimsg(const char *cat, const char *act, const char *arg) { (void)cat; (void)act; (void)arg; } // 「自定义」设置(dm_custom.c)的桩 | stub for the "Custom" settings (dm_custom.c) void dm_belt_put(unsigned id) { (void)id; } void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; } +void dm_uiscreen_set_panel(int on) { (void)on; } int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; } int dm_uiscreen_ingame(void) { return 0; } void dm_uiscreen_set_ingame(int on) { (void)on; } // 界面矩形(dm_uiscreen.c)的桩:没开真全屏 | stub for the UI rectangle (dm_uiscreen.c): true full screen not enabled diff --git a/dm/host/tests/t_touch_tick_stub.c b/dm/host/tests/t_touch_tick_stub.c index d8d1f4d..b5ec6af 100644 --- a/dm/host/tests/t_touch_tick_stub.c +++ b/dm/host/tests/t_touch_tick_stub.c @@ -79,6 +79,7 @@ float dm_ui_ny(float ny) { return ny; } int dm_screen_real(int *w, int *h) { (void)w; (void)h; return 0; } void dm_uiscreen_enable(int m) { (void)m; } void dm_ui_rect(int *x, int *y, int *w, int *h) { *x = *y = *w = *h = 0; } +void dm_uiscreen_set_panel(int on) { (void)on; } int dm_uiscreen_ingame(void) { return 0; } void dm_uiscreen_set_ingame(int on) { (void)on; } void dm_held_stow(void) {} diff --git a/dm/host/touch_mac.c b/dm/host/touch_mac.c index df8bffe..666e241 100644 --- a/dm/host/touch_mac.c +++ b/dm/host/touch_mac.c @@ -4,11 +4,17 @@ #include "dm_actions.h" #include "dm_hud.h" #include "../ios/Sources/dm_touch_controls.h" +#include "dm_uiscreen.h" #include #include #include uint64_t now_ns(void); +// 手势层的坐标是「界面矩形里的归一化」(同 iOS 的游戏视图);点世界 / 点地走要的是「整屏归一化」。16:9 时两者一样; +// 真全屏(界面按 16:9 贴底、画面更高)下纵向要换:整屏 y = (界面 y × 界面高 + 界面矩形顶边) ÷ 画面高(iOS 前端在点世界前做的同一步,front_ios.m world_norm) +// Gesture-layer coordinates are "normalised within the interface rectangle" (like the iOS game view); tapping the world / tap-to-walk needs "normalised to the whole screen". At 16:9 the two are the same; +// with true full screen (interface 16:9 along the bottom, picture taller) the vertical needs converting: screen y = (interface y x interface height + interface rectangle top) / picture height (the same step the iOS front end does before tapping the world, front_ios.m world_norm) +static float ui_y_to_screen(float uy) { int x, y, w, h, rw = 0, rh = 0; dm_ui_rect(&x, &y, &w, &h); return dm_screen_real(&rw, &rh) && rh > 0 && h > 0 ? (uy * h + y) / rh : uy; } uint64_t guest_ns(void); uint32_t dm_cur_tick(void); int dm_loadscreen_down(void); @@ -54,6 +60,11 @@ static void touch_uimsg(const char *cat, const char *act, const char *arg) { scene.game = 1; dm_tc_set_panel_state(dm_ui_panel_state()); int navigation = dm_tc_navigation(&scene, cat, act, arg); + // 真全屏(16:10 的 Mac,front_mac.m):局内开大面板时界面整块移到正中、上下留同样宽的边,关掉回落贴底——iPad 的做法,判据同 front_ios.m 的 nmode == 1: + // 面板模式,且不是只开着 NPC 对话菜单(菜单跟着 NPC 摆,留在贴底)、不是死亡页。没开真全屏时宿主不动 + // True full screen (16:10 Mac, front_mac.m): in game with a large panel open the interface moves as a block to the centre with equal bars above and below, and drops back to the bottom when closed - the iPad approach, same criterion as nmode == 1 in front_ios.m: + // panel mode, and not only the NPC dialogue menu open (the menu follows the NPC and stays at the bottom), and not the death page. Without true full screen the host does nothing + dm_uiscreen_set_panel(navigation && !dm_tc_scene_dead() && !dm_tc_scene_dialog_only(&scene)); 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) @@ -217,7 +228,7 @@ void dm_touch_host_step(uint64_t now, uint64_t *buttons, int32_t *lx, int32_t *l { void dm_world_walk(float, float); int dm_world_tap_result(unsigned), dm_game_paused(void); uint32_t tk = touch_cur_tick(); dm_tc_set_joy_block(&g_touch.state, 1); // 鼠标不起触屏那个浮动摇杆(左下那片按住拖动原先会变成推摇杆) | the mouse does not start the touch layout's floating stick (holding and dragging in the bottom-left area used to turn into pushing the stick) if (g_lm.tap_seq) { int r = dm_world_tap_result(g_lm.tap_seq); if (r >= 0) { if (r == 0 && in && !dm_game_paused()) dm_world_walk(g_lm.tap_x, g_lm.tap_y); g_lm.tap_seq = 0; } } - if (g_lm.down && in && !g_touch.state.navigation_mode && !dm_game_paused() && (int32_t)(tk - g_lm.t0) >= 9 && (!g_lm.last || (int32_t)(tk - g_lm.last) >= 6) && dm_ui_item_at_now(g_lm.x, g_lm.y) != 0) { g_lm.last = tk; dm_world_walk(g_lm.x, g_lm.y); } + if (g_lm.down && in && !g_touch.state.navigation_mode && !dm_game_paused() && (int32_t)(tk - g_lm.t0) >= 9 && (!g_lm.last || (int32_t)(tk - g_lm.last) >= 6) && dm_ui_item_at_now(g_lm.x, g_lm.y) != 0) { g_lm.last = tk; dm_world_walk(g_lm.x, ui_y_to_screen(g_lm.y)); } if (!in) g_lm.down = 0; } } if (g_live_btn) { if ((int32_t)(g_live_btn_until - touch_cur_tick()) > 0) *buttons |= g_live_btn; else g_live_btn = 0; } @@ -299,7 +310,7 @@ apply_input: // 真鼠标:手势层认为没有面板开着(它按名单认面板,大秘境选层页这类借壳的面板不在名单里),这一下却落在某个面板里 → 发界面点击,不当点世界 // Real mouse: the gesture layer believes no panel is open (it recognises panels by a list, and panels that borrow another shell, such as the Greater Rift level-selection page, are not on it), yet this click lands inside some panel -> send a UI click instead of a world click if (g_live_on && dm_ui_item_at_now(wx, wy) == 0) { dm_ui_touch(0, wx, wy); dm_ui_touch(2, wx, wy); } - else if (g_live_on) { unsigned dm_world_click(float, float); g_lm.tap_seq = dm_world_click(wx, wy); g_lm.tap_x = wx; g_lm.tap_y = wy; } else dm_world_tap(wx, wy); } // 真鼠标:记下这一笔,答案是「没有目标」就改成走到那一点 | real mouse: remember this click, and if the answer is "no target" turn it into walking to that point + else if (g_live_on) { unsigned dm_world_click(float, float); float sy = ui_y_to_screen(wy); g_lm.tap_seq = dm_world_click(wx, sy); g_lm.tap_x = wx; g_lm.tap_y = sy; } else dm_world_tap(wx, ui_y_to_screen(wy)); } // 真鼠标:记下这一笔,答案是「没有目标」就改成走到那一点 | real mouse: remember this click, and if the answer is "no target" turn it into walking to that point if (g_touch.state.mouse_click_seq != mc) { float nx = g_touch.state.mouse_click_x / 2868, ny = g_touch.state.mouse_click_y / 1320; dm_ui_touch(0, nx, ny); dm_ui_touch(2, nx, ny); } } } diff --git a/docs/MAC.md b/docs/MAC.md index 1a0b7c7..b42b582 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -61,7 +61,7 @@ With a keyboard, the button prompts on screen (the hint bar at the bottom, skill **Creating a character, start to finish**: on the main menu press `=` (or click "New Character") → choose a class with the arrow keys and press Return (or click that class's figure) → on the mode page press Return or Space → on the naming page press Return to open the input box, type, Return → press Return once more to create. -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. +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. In game the picture fills the window or screen at its own aspect ratio (on a 16:10 MacBook both windowed and full screen are filled, with the interface along the bottom, centred while a large panel is open); the front-end pages such as the main menu and character select stay 16:9 with bars above and below. ## Mouse @@ -91,6 +91,7 @@ What it cannot do yet: - Saves: `~/Library/Application Support/D2R Mobile/save` - Log: `~/Library/Logs/D2R Mobile/host.log` (the previous run is `host.prev.log`). When reporting a problem use Help → Share Log… in the menu bar: it packs these two logs and a version-information file into one archive and lets you choose where to save it; nothing is uploaded, no saves are included, and the user name in the logs is replaced with `~`. +- No sound: at launch the log has a line `audio:输出设备「…」…,系统缺省输出「…」…` (the output device in use and the system default output; a mismatch is marked red), and on exit a line `声卡回调累计 N` — N = 0 means no sound was played this time. (These log lines are in Chinese.) - The older-API build (`D2R Mobile M3.app`) uses a separate pair of directories with M3 in the name. **iCloud save sync: not available in an App you build from this repository.** The program has the same sync as on iPhone / iPad wired in, but it needs the App to carry the iCloud signing entitlement; an App you build yourself is signed locally without it, so saves stay on this Mac, the log records one line saying iCloud is unavailable and only local saves are used, and the game runs as usual. To bring your phone's progress over, import it by hand as below. diff --git a/docs/MAC.zh-CN.md b/docs/MAC.zh-CN.md index 37e9985..b2b6f89 100644 --- a/docs/MAC.zh-CN.md +++ b/docs/MAC.zh-CN.md @@ -61,7 +61,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 **建一个角色,从头到尾这样按**:主菜单按 `=`(或鼠标点「新角色」)→ 用方向键选职业再按回车(或直接点那个职业的人物)→ 模式页按回车或空格 → 起名页按回车弹出输入框,直接打字,回车 → 再按一次回车创建。 -接上手柄直接可用,与键盘并存。菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小,游戏画面保持 16:9 居中。 +接上手柄直接可用,与键盘并存。菜单栏有「显示 → 全屏(⌃⌘F)」和「退出(⌘Q)」。窗口可以随意拉大小。进游戏后画面按窗口 / 屏幕的比例铺满(16:10 的 MacBook 上窗口态和全屏态都铺满,界面贴底,开着大面板时界面居中);主菜单、选角等前端页仍是 16:9、上下留边。 ## 鼠标 @@ -91,6 +91,7 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25 - 存档:`~/Library/Application Support/D2R Mobile/save` - 日志:`~/Library/Logs/D2R Mobile/host.log`(上一次运行的是 `host.prev.log`)。报问题时用菜单栏「帮助 → 分享日志…」:它把这两份日志和一份版本信息打成一个压缩包,让你选保存位置;不上传、不带存档,日志里的用户名会换成 `~`。 +- 没有声音时看日志:启动时有一行「audio:输出设备「…」,系统缺省输出「…」」,两者不一致会标红;退出时有一行「声卡回调累计 N」,N 为 0 表示这次没有出声。 - 老接口版(`D2R Mobile M3.app`)用的是名字里带 M3 的另一对目录。 **iCloud 存档同步:从本仓库自己构建的 App 没有。**程序里接了与 iPhone / iPad 相同的同步,但它需要 App 带着 iCloud 的签名权限;自己构建的 App 用的是本机临时签名,没有这项权限,所以存档只留在这台 Mac 上,日志里会记一行「iCloud 不可用…只用本地存档」,游戏照常。要把手机上的进度带过来,用下面的手工导入。