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
+221 -45
View File
@@ -246,6 +246,76 @@ NVN(nvnTextureBuilderGetStorageAlignment, size_t, const NVNtextureBuilder *b) {
}
#define TX(t) ((tex_t *)(t))
#define CTX(t) ((const tex_t *)(t))
// ---------- 对象副本:录制时按序号留一份贴图 / 程序对象,命令载荷存副本地址 ----------
// 同一序号的对象内容不变(Initialize / SetShaders 才换序号),游戏提交后可以改写或重建自己的对象(真机上 GPU 只看录进命令内存的值),
// 回放层读副本就不受影响。游戏对象里记着副本地址,按值拷来的对象序号相同、直接共用。副本在对象 Finalize / 换序号后再过 SNAP_KEEP 次提交才回收;
// 槽位内存只增不还给系统,回收时清零(序号 0 不与任何有效序号相等),过期的副本地址只会读到不相等的序号、重新取副本。
// ---------- Object snapshots: when recording, keep one copy of each texture / program object per serial; command payloads store the snapshot address ----------
// An object with the same serial has the same content (only Initialize / SetShaders change the serial); after submitting, the game may rewrite or rebuild its own objects (on the real device the GPU only sees the values recorded into command memory),
// and the replay layer reading snapshots is unaffected. The game object records the snapshot address, and objects copied by value have the same serial and share it directly. A snapshot is reclaimed only SNAP_KEEP submits after the object is Finalized / changes serial;
// slot memory only grows and is never returned to the system; reclaimed slots are zeroed (serial 0 never equals a valid serial), so a stale snapshot address only reads a non-matching serial and takes a new snapshot.
typedef union snap_slot { tex_t t; prog_t p; union snap_slot *next; } snap_slot;
#define SNAP_KEEP 8
static pthread_mutex_t g_snap_mu = PTHREAD_MUTEX_INITIALIZER;
static snap_slot *g_snap_free;
static struct { snap_slot *s; uint64_t at; } *g_snap_ret; static size_t g_snap_nret, g_snap_capret, g_snap_live, g_snap_slots;
static uint64_t g_snap_sub; // 已执行(翻译完)的提交数:回收时刻 | Number of submits executed (translated): the reclaim clock
static _Atomic uint64_t g_x_subs; // 已入队的提交数(翻译队列,见 nvnQueueSubmitCommands 前):退役盖戳用它,回收按已执行数,翻译线程落后时副本不会提前回收 | Number of submits enqueued (translation queue, see before nvnQueueSubmitCommands): used for the retire stamp, while reclaim goes by the number executed, so snapshots are not reclaimed early when the translation thread falls behind
static snap_slot *snap_alloc(void) { // 持 g_snap_mu | Holds g_snap_mu
if (!g_snap_free) {
snap_slot *c = calloc(256, sizeof *c); if (!c) { LOG("【红】对象副本分配失败"); abort(); }
for (int i = 255; i >= 0; i--) { c[i].next = g_snap_free; g_snap_free = &c[i]; }
g_snap_slots += 256; // 读数:槽位只在在用 + 待回收占满时才扩,扩槽停住即有上界 | Reading: slots grow only when in-use + pending-reclaim fill them all; slot growth stops, so there is an upper bound
LOG("[nvn] 对象副本槽位扩到 %zu 个(%zu KB):在用 %zu,其中待回收 %zu,第 %llu 次提交", g_snap_slots, g_snap_slots * sizeof *c >> 10, g_snap_live, g_snap_nret, (unsigned long long)g_snap_sub);
}
snap_slot *n = g_snap_free; g_snap_free = n->next; memset(n, 0, sizeof *n); g_snap_live++;
return n;
}
static void snap_retire(const void *s) { // 持 g_snap_mu | Holds g_snap_mu
if (g_snap_nret == g_snap_capret) { g_snap_capret = g_snap_capret ? g_snap_capret * 2 : 256; g_snap_ret = realloc(g_snap_ret, g_snap_capret * sizeof *g_snap_ret); }
g_snap_ret[g_snap_nret].s = (snap_slot *)s; g_snap_ret[g_snap_nret++].at = atomic_load(&g_x_subs);
}
static void snap_tick(uint64_t done) { // 翻译线程每执行完一次提交:回收退役时已入队的提交都执行完、且又过了 SNAP_KEEP 次提交的副本 | Each time the translation thread finishes a submit: reclaim snapshots whose submits enqueued at retirement have all executed and that have passed SNAP_KEEP more submits
pthread_mutex_lock(&g_snap_mu);
g_snap_sub = done; size_t k = 0;
for (size_t i = 0; i < g_snap_nret; i++) {
if (g_snap_ret[i].at + SNAP_KEEP <= g_snap_sub) { snap_slot *n = g_snap_ret[i].s; memset(n, 0, sizeof *n); n->next = g_snap_free; g_snap_free = n; g_snap_live--; }
else g_snap_ret[k++] = g_snap_ret[i];
}
g_snap_nret = k;
pthread_mutex_unlock(&g_snap_mu);
}
static const tex_t *snap_tex(const NVNtexture *t) {
tex_t *o = TX(t); if (!o || !o->serial) return o; // 没初始化过的对象没有可留的内容,照旧存原址 | An object that was never initialized has no content to keep; store the original address as before
const tex_t *s = __atomic_load_n((const tex_t **)&o->snap, __ATOMIC_ACQUIRE);
if (s && s->serial == o->serial) return s;
pthread_mutex_lock(&g_snap_mu);
s = o->snap;
if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->t = *o; n->t.snap = NULL; s = &n->t; __atomic_store_n((const tex_t **)&o->snap, s, __ATOMIC_RELEASE); }
pthread_mutex_unlock(&g_snap_mu);
return s;
}
static const prog_t *snap_prog(const NVNprogram *p) {
prog_t *o = (prog_t *)p; if (!o || !o->serial) return o;
const prog_t *s = __atomic_load_n((const prog_t **)&o->snap, __ATOMIC_ACQUIRE);
if (s && s->serial == o->serial) return s;
pthread_mutex_lock(&g_snap_mu);
s = o->snap;
if (!s || s->serial != o->serial) { snap_slot *n = snap_alloc(); n->p = *o; n->p.snap = NULL; s = &n->p; __atomic_store_n((const prog_t **)&o->snap, s, __ATOMIC_RELEASE); }
pthread_mutex_unlock(&g_snap_mu);
return s;
}
static void x_drain(void);
static uint64_t x_fence(void);
// 对象 Finalize / 换序号前调:本序号的副本退役(按值拷来的同序号对象之后再录会重新取副本)
// Called before an object is Finalized / changes serial: retire this serial's snapshot (an object with the same serial copied by value takes a new snapshot when recorded later)
static void snap_drop(const void **pp, uint64_t ser, uint64_t snap_ser_off) {
pthread_mutex_lock(&g_snap_mu);
const uint8_t *s = *pp; uint64_t ss; if (s) memcpy(&ss, s + snap_ser_off, 8);
if (s && ser && ss == ser) snap_retire(s);
*pp = NULL;
pthread_mutex_unlock(&g_snap_mu);
}
NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b) {
const tex_builder_t *s = (const tex_builder_t *)b; tex_t *o = TX(t);
memset(o, 0, sizeof *o);
@@ -258,7 +328,7 @@ NVN(nvnTextureInitialize, NVNboolean, NVNtexture *t, const NVNtextureBuilder *b)
o->d.levels, o->d.format, o->d.target, o->d.flags, o->L.size);
return 1;
}
NVN(nvnTextureFinalize, void, NVNtexture *t) { mtl_tex_release(TX(t)); TX(t)->magic = 0; }
NVN(nvnTextureFinalize, void, NVNtexture *t) { snap_drop(&TX(t)->snap, TX(t)->serial, offsetof(tex_t, serial)); mtl_tex_release(TX(t)); TX(t)->magic = 0; }
NVN(nvnTextureGetFlags, NVNtextureFlags, const NVNtexture *t) { return (NVNtextureFlags)CTX(t)->d.flags; }
NVN(nvnTextureGetWidth, int, const NVNtexture *t) { return (int)CTX(t)->d.width; }
NVN(nvnTextureGetHeight, int, const NVNtexture *t) { return (int)CTX(t)->d.height; }
@@ -295,6 +365,7 @@ static void read_texels(const tex_t *o, const view_t *v, const NVNcopyRegion *r,
if (!row) row = wb;
if (!img) img = row * hb;
unsigned level = v && v->set_levels ? (unsigned)v->base_level : 0, layer0 = v && v->set_layers ? (unsigned)v->min_layer : 0;
x_drain(); // CPU 读贴图:已入队的提交先翻译完 | CPU texture read: submits already enqueued are translated first
mtl_read_texels(o, level, layer0, r, dst, (size_t)row, (size_t)img);
}
NVN(nvnTextureReadTexels, void, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, void *dst) {
@@ -340,11 +411,11 @@ NVN(nvnSamplerFinalize, void, NVNsampler *s) { ((samp_t *)s)->magic = 0; }
NVN(nvnProgramInitialize, NVNboolean, NVNprogram *p, NVNdevice *d) {
(void)d; memset(p, 0, sizeof(prog_t)); ((prog_t *)p)->magic = MAGIC('P', 'R', 'O', 'G'); return 1;
}
NVN(nvnProgramFinalize, void, NVNprogram *p) { mtl_prog_release((prog_t *)p); ((prog_t *)p)->magic = 0; }
NVN(nvnProgramFinalize, void, NVNprogram *p) { prog_t *o = (prog_t *)p; snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->magic = 0; }
NVN(nvnProgramSetShaders, NVNboolean, NVNprogram *p, int n, const NVNshaderData *sd) {
prog_t *o = (prog_t *)p;
if (n < 0 || n > 6) { LOG("【红】ProgramSetShaders 阶段数 %d", n); return 0; }
mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
snap_drop(&o->snap, o->serial, offsetof(prog_t, serial)); mtl_prog_release(o); o->nstage = n; memcpy(o->sd, sd, n * sizeof *sd); o->serial = nvn_new_serial();
OLOG("ProgramSetShaders %p n=%d data0=%#llx", (void *)p, n, n ? (unsigned long long)sd[0].data : 0ull);
return 1;
}
@@ -355,7 +426,7 @@ NVN(nvnSyncInitialize, NVNboolean, NVNsync *s, NVNdevice *d) { (void)d; *(sync_t
NVN(nvnSyncFinalize, void, NVNsync *s) { ((sync_t *)s)->magic = 0; }
// 围栏 = 「此前提交到队列的命令全部完成」:记下最近一次提交的栅栏值
// Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); }
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); }
// 没围栏过的同步对象按真机行为等到超时;已围栏的只在 GPU 真正完成到该栅栏值后放行
// A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
@@ -406,10 +477,10 @@ NVN(nvnQueueGetError, NVNqueueGetErrorResult, NVNqueue *q, NVNqueueErrorInfo *in
}
NVN(nvnQueueFlush, void, NVNqueue *q) { (void)q;
#ifdef __ANDROID__
mtl_queue_flush();
x_drain(); mtl_queue_flush();
#endif
}
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; mtl_finish(); }
NVN(nvnQueueFinish, void, NVNqueue *q) { (void)q; x_drain(); mtl_finish(); }
// ---------- 命令缓冲:录进游戏的命令内存,提交时执行 CPU 可见副作用 ----------
// ---------- Command buffer: record into the game's command memory, perform CPU-visible side effects at submit ----------
@@ -578,8 +649,8 @@ NVN(nvnCommandBufferSetRenderTargets, void, NVNcommandBuffer *c, int n, const NV
const NVNtexture *dt, const NVNtextureView *dv) {
if (n < 0 || n > 8) { LOG("【红】SetRenderTargets 数量 %d", n); n = n < 0 ? 0 : 8; }
p_set_rt *r = REC(c, OP_SET_RT, p_set_rt); r->n = n;
for (int i = 0; i < n; i++) { r->color[i] = ct ? (const tex_t *)ct[i] : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); }
r->depth = (const tex_t *)dt; copy_view(&r->dview, &r->has_dview, dv);
for (int i = 0; i < n; i++) { r->color[i] = ct ? snap_tex(ct[i]) : NULL; copy_view(&r->cview[i], &r->has_cview[i], cv ? cv[i] : NULL); }
r->depth = snap_tex(dt); copy_view(&r->dview, &r->has_dview, dv);
}
NVN(nvnCommandBufferClearColor, void, NVNcommandBuffer *c, int index, const float *rgba, int mask) {
p_clear_color *r = REC(c, OP_CLEAR_COLOR, p_clear_color); r->index = index; r->mask = mask; memcpy(r->rgba, rgba, 16);
@@ -595,7 +666,7 @@ NVN(nvnCommandBufferSetViewports, void, NVNcommandBuffer *c, int first, int n, c
NVN(nvnCommandBufferSetScissor, void, NVNcommandBuffer *c, int x, int y, int w, int h) { *REC(c, OP_SCISSOR, p_scissor) = (p_scissor){x, y, w, h}; }
NVN(nvnCommandBufferSetDepthRange, void, NVNcommandBuffer *c, float n, float f) { *REC(c, OP_DEPTH_RANGE, p_depth_range) = (p_depth_range){n, f}; }
NVN(nvnCommandBufferBindProgram, void, NVNcommandBuffer *c, const NVNprogram *p, int stages) {
*REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){(const prog_t *)p, stages};
*REC(c, OP_BIND_PROGRAM, p_bind_program) = (p_bind_program){snap_prog(p), stages};
}
static void bind_state(NVNcommandBuffer *c, int kind, const void *st, size_t n) { p_bind_state *r = REC(c, OP_BIND_STATE, p_bind_state); r->kind = kind; memcpy(r->bytes, st, n); }
NVN(nvnCommandBufferBindBlendState, void, NVNcommandBuffer *c, const NVNblendState *st) { bind_state(c, 0, st, sizeof(blend_st)); }
@@ -668,23 +739,23 @@ NVN(nvnCommandBufferSetSamplerPool, void, NVNcommandBuffer *c, const NVNsamplerP
NVN(nvnCommandBufferCopyBufferToTexture, void, NVNcommandBuffer *c, NVNbufferAddress src, const NVNtexture *t, const NVNtextureView *v,
const NVNcopyRegion *r, int flags) {
p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
p_copy_b2t *o = REC(c, OP_COPY_B2T, p_copy_b2t); o->src = src; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
}
NVN(nvnCommandBufferCopyTextureToBuffer, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r,
NVNbufferAddress dst, int flags) {
p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
p_copy_b2t *o = REC(c, OP_COPY_T2B, p_copy_b2t); o->src = dst; o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->flags = flags;
}
// 用给定值清贴图区域(浮点 / 无符号整数两版;mask = 通道写掩码)
// Clear a texture region with the given value (float / unsigned integer versions; mask = channel write mask)
NVN(nvnCommandBufferClearTexture, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const float *rgba, int mask) {
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16);
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 0; memcpy(o->c.f, rgba, 16);
}
NVN(nvnCommandBufferClearTextureui, void, NVNcommandBuffer *c, const NVNtexture *t, const NVNtextureView *v, const NVNcopyRegion *r, const uint32_t *rgba, int mask) {
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = (const tex_t *)t; copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16);
p_clear_tex *o = REC(c, OP_CLEAR_TEX, p_clear_tex); o->tex = snap_tex(t); copy_view(&o->view, &o->has_view, v); o->r = *r; o->mask = mask; o->is_uint = 1; memcpy(o->c.u, rgba, 16);
}
NVN(nvnCommandBufferCopyTextureToTexture, void, NVNcommandBuffer *c, const NVNtexture *s, const NVNtextureView *sv, const NVNcopyRegion *sr,
const NVNtexture *d, const NVNtextureView *dv, const NVNcopyRegion *dr, int flags) {
p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = (const tex_t *)s; o->dst = (const tex_t *)d;
p_copy_t2t *o = REC(c, OP_COPY_T2T, p_copy_t2t); o->src = snap_tex(s); o->dst = snap_tex(d);
copy_view(&o->sv, &o->has_sv, sv); copy_view(&o->dv, &o->has_dv, dv); o->sr = *sr; o->dr = *dr; o->flags = flags;
}
NVN(nvnCommandBufferSetCopyRowStride, void, NVNcommandBuffer *c, ptrdiff_t st) { REC(c, OP_COPY_STRIDE, p_copy_stride)->stride = st; }
@@ -780,23 +851,123 @@ void dm_gfx_suspend(int on) {
if (on) while (g_inflight_api) pthread_cond_wait(&g_susp_cv, &g_susp_mu);
else pthread_cond_broadcast(&g_susp_cv);
pthread_mutex_unlock(&g_susp_mu);
if (on) { mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复");
if (on) { x_drain(); mtl_drain(); LOG("[nvn] 图形挂起:在途 GPU 工作已清空"); } else LOG("[nvn] 图形恢复");
}
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
gfx_enter();
// 一条实时线程的声明状态:游戏主线程(取图处)与翻译线程(帧边界)各一份,按各自每帧 CPU 自动调整(见 set_time_constraint_comp)
// Declaration state of one real-time thread: one each for the game main thread (at acquire) and the translation thread (at frame boundaries), each adjusted automatically from its own per-frame CPU (see set_time_constraint_comp)
typedef struct { const char *who; double comp_ms, period_ms; uint64_t last; double win[120]; int n; } rt_decl; // comp_ms:当前声明的计算量(0 = 未声明) | comp_ms: currently declared computation (0 = not declared)
static rt_decl g_rt_main = {"出图线程"}, g_rt_xlat = {"翻译线程"};
static void set_time_constraint(rt_decl *d, uint64_t period_ns);
static void rt_comp_tick(rt_decl *d, uint64_t period_ns);
// ---------- 翻译队列(B 方案第二期):提交 / 出图 / 设帧号按序排给翻译线程,游戏线程只登记、立刻返回 ----------
// 游戏逻辑与上一帧的翻译(回放 + Metal 编码)重叠。栅栏值 = 已入队的提交数:Metal 层每次提交恰好 ++g_fence、g_done 只在已提交的命令缓冲
// 完成时推进,所以等栅栏 f 就是等「f 翻译完且 GPU 做完」——游戏按栅栏回收命令内存、改写对象时翻译线程早已读完。
// 出图票号换成本队列的任务号:取图处先等该任务执行完,再按它换来的出图线程票号等。设帧号也排队:回放按帧号重置泛光取样等状态,
// 不能在翻译途中被游戏线程改掉。DM_NVN_SYNC=1:任务在调用线程上当场执行(同一个执行函数),作对照与量测基准。
// ---------- Translation queue (plan B, phase 2): submit / present / set-frame-number are queued in order to the translation thread; the game thread only records them and returns at once ----------
// Game logic overlaps the previous frame's translation (replay + Metal encoding). Fence value = number of submits enqueued: the Metal layer does ++g_fence exactly once per submit and g_done advances only when a committed command buffer
// completes, so waiting for fence f means waiting until "f is translated and the GPU is done"; by the time the game reclaims command memory or rewrites objects by fence, the translation thread has long finished reading them.
// Present tickets become this queue's job numbers: acquire first waits for that job to run, then waits on the present thread ticket it was swapped for. Setting the frame number is queued too: replay resets bloom sampling and other state by frame number,
// which must not be changed by the game thread in the middle of translation. DM_NVN_SYNC=1: jobs run in place on the calling thread (the same execution function), as the control and measurement baseline.
enum { XJ_SUBMIT, XJ_PRESENT, XJ_FRAME };
typedef struct { int kind, n; uint64_t *h; const tex_t *tex; double period; int crop[4]; uint64_t frame, sub, host; } xjob; // host:入队时锁存的宿主画法开关 | host: host drawing switches latched at enqueue
#define XQ 32
#define XTK 1024
static xjob g_xq[XQ]; static uint64_t g_xq_in, g_xq_done; // 入队任务数 / 已执行任务数(任务号从 1 计) | Jobs enqueued / jobs executed (job numbers start at 1)
static struct { uint64_t job, tk; } g_xtk[XTK]; // 出图任务号 → 出图线程票号 | Present job number -> present thread ticket
static pthread_mutex_t g_xmu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_xcv = PTHREAD_COND_INITIALIZER;
static int g_x_sync; static pthread_t g_x_thr; static mach_port_t g_x_port; // 翻译线程(策略读数用) | Translation thread (for policy readings)
#ifdef __ANDROID__
#define ANDROID_SYNC_FENCE 1 // Vulkan 后端的栅栏还计读回等内部提交,不与提交数对齐 | the Vulkan backend's fence also counts internal commits such as readbacks and is not aligned with the submit count
#else
#define ANDROID_SYNC_FENCE 0
#endif
static void x_submit(const uint64_t *h, int n, uint64_t sub, uint64_t host) {
mtl_host_apply(host);
uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0);
((queue_t *)q)->submits++;
mtl_sub_begin();
mtl_sub_index((const uint64_t *)h, n);
for (int i = 0; i < n; i++) { mtl_exec_rest((const uint64_t *)h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); }
mtl_sub_index(h, n);
for (int i = 0; i < n; i++) { mtl_exec_rest(h + i + 1, n - i - 1); mtl_exec((const uint8_t *)h[i]); }
mtl_exec_rest(NULL, 0);
mtl_sub_commit();
uint64_t f = mtl_sub_commit();
if (f != sub && !ANDROID_SYNC_FENCE) { static int red; if (!red++) LOG("【红】翻译队列:第 %llu 次提交的 Metal 栅栏是 %llu,栅栏与提交数对不上,游戏等同步会提前 / 推迟放行", (unsigned long long)sub, (unsigned long long)f); }
snap_tick(sub);
uint64_t dw = now_ns() - t0;
atomic_fetch_add(&g_nvn_ns, dw); atomic_fetch_add(&g_sub_wall_ns, dw);
uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t dc = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - c0, di = i1 - i0;
atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw);
atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc);
atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di);
}
static void x_run(const xjob *j, uint64_t job) {
if (j->kind == XJ_SUBMIT) { x_submit(j->h, j->n, j->sub, j->host); free(j->h); }
else if (j->kind == XJ_PRESENT) { uint64_t tk = mtl_present(j->tex, j->period, j->crop); pthread_mutex_lock(&g_xmu); g_xtk[job % XTK].job = job; g_xtk[job % XTK].tk = tk; pthread_mutex_unlock(&g_xmu); }
else {
mtl_set_frame(j->frame);
// 翻译线程与游戏主线程同级:时间约束(实时)线程,周期 = 出图周期,计算量按本线程每帧 CPU 的 p90 自动声明(同取图处的主线程;确定性时钟下不声明)
// The translation thread has the same standing as the game main thread: a time-constraint (real-time) thread, period = present period, computation declared automatically from the p90 of this thread's per-frame CPU (same as the main thread at acquire; not declared under the deterministic clock)
uint64_t pn = (uint64_t)(j->period * 1e9); static uint64_t rt_p;
if (!g_x_sync && !dm_detclock_enabled()) { if (pn && rt_p != pn) { rt_p = pn; set_time_constraint(&g_rt_xlat, pn); } rt_comp_tick(&g_rt_xlat, pn); }
}
}
static void *x_thread(void *a) {
(void)a; pthread_setname_np("nvn-translate"); g_x_port = pthread_mach_thread_np(pthread_self());
pthread_mutex_lock(&g_xmu);
for (;;) {
while (g_xq_done == g_xq_in) pthread_cond_wait(&g_xcv, &g_xmu);
uint64_t job = g_xq_done + 1; xjob j = g_xq[job % XQ];
pthread_mutex_unlock(&g_xmu);
x_run(&j, job);
pthread_mutex_lock(&g_xmu);
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
}
return NULL;
}
static void x_start(void) {
#ifdef __ANDROID__
// Vulkan 后端还没按翻译线程改:提交线程上同步翻译(读回贴图等也会提交,栅栏不等于提交数,见 x_fence)
// The Vulkan backend has not been adapted to the translation thread yet: translate synchronously on the submit thread (texture readbacks also commit, so the fence is not the submit count, see x_fence)
g_x_sync = 1; LOG("[nvn] 安卓:翻译在提交线程上同步做"); return;
#endif
const char *e = getenv("DM_NVN_SYNC"); g_x_sync = e && atoi(e);
if (g_x_sync) { LOG("[nvn] DM_NVN_SYNC=1:翻译在提交线程上同步做(对照档)"); return; }
pthread_attr_t at; pthread_attr_init(&at); pthread_attr_set_qos_class_np(&at, QOS_CLASS_USER_INTERACTIVE, 0); pthread_attr_setstacksize(&at, 8 << 20);
pthread_t t; if (pthread_create(&g_x_thr, &at, x_thread, NULL)) { LOG("【红】翻译线程起不来,改为同步翻译"); g_x_sync = 1; } else LOG("[nvn] 翻译线程已起:提交 / 出图在翻译线程上按序执行(队列 %d 项)", XQ);
pthread_attr_destroy(&at);
}
static uint64_t x_push(xjob *j) { // 返回任务号 | Returns the job number
static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, x_start);
pthread_mutex_lock(&g_xmu);
while (g_xq_in - g_xq_done >= XQ) pthread_cond_wait(&g_xcv, &g_xmu);
if (j->kind == XJ_SUBMIT) j->sub = atomic_fetch_add(&g_x_subs, 1) + 1;
uint64_t job = ++g_xq_in;
if (g_x_sync) { // 当场执行:单线程提交时与旧路径同序 | Run in place: with single-thread submission the order is the same as the old path
pthread_mutex_unlock(&g_xmu); x_run(j, job); pthread_mutex_lock(&g_xmu);
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
} else { g_xq[job % XQ] = *j; pthread_cond_broadcast(&g_xcv); }
pthread_mutex_unlock(&g_xmu);
return job;
}
static void x_wait(uint64_t job) { pthread_mutex_lock(&g_xmu); while (g_xq_done < job) pthread_cond_wait(&g_xcv, &g_xmu); pthread_mutex_unlock(&g_xmu); }
static void x_drain(void) { pthread_mutex_lock(&g_xmu); uint64_t job = g_xq_in; pthread_mutex_unlock(&g_xmu); x_wait(job); }
#ifdef __ANDROID__
static uint64_t x_fence(void) { return mtl_last_fence(); } // 同步翻译:Vulkan 后端的最近栅栏(含读回等内部提交) | synchronous translation: the Vulkan backend's latest fence (including internal commits such as readbacks)
#else
static uint64_t x_fence(void) { return atomic_load(&g_x_subs); }
#endif
static uint64_t x_present_ticket(uint64_t job) { // 出图任务执行完后换来的出图线程票号(0 = 那次出图被丢弃,不用等) | Present thread ticket obtained after the present job runs (0 = that present was dropped, nothing to wait for)
x_wait(job);
pthread_mutex_lock(&g_xmu); uint64_t tk = g_xtk[job % XTK].job == job ? g_xtk[job % XTK].tk : 0; int lost = g_xtk[job % XTK].job != job; pthread_mutex_unlock(&g_xmu);
if (lost) { static int red; if (!red++) LOG("【红】翻译队列:出图任务 %llu 的票号已被覆盖(票号表 %d 项不够),这次取图不等出图线程", (unsigned long long)job, XTK); }
return tk;
}
NVN(nvnQueueSubmitCommands, void, NVNqueue *q, int n, const NVNcommandHandle *h) {
gfx_enter();
((queue_t *)q)->submits++;
xjob j = {XJ_SUBMIT, n, n > 0 ? malloc((size_t)n * sizeof *h) : NULL}; // 句柄数组是游戏的,入队时拷一份 | The handle array belongs to the game; copy it when enqueuing
if (n > 0) memcpy(j.h, h, (size_t)n * sizeof *h);
j.host = mtl_host_latch();
x_push(&j);
gfx_leave();
}
@@ -872,10 +1043,6 @@ NVN(nvnWindowSetCrop, void, NVNwindow *w, int x, int y, int ww, int hh) {
memcpy(o->crop, v, sizeof v);
}
static void trow(uint64_t f, const char *name, double v);
static void set_time_constraint(uint64_t period_ns);
static void rt_comp_tick(uint64_t period_ns);
static double g_rt_comp_ms; // 当前声明的实时计算量(ms;0 = 未声明) | Currently declared real-time computation amount (ms; 0 = not declared)
static double g_rt_period_ms;
static void sleep_until_ns(uint64_t dl);
static uint64_t present_period(const win_t *o);
__attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests
@@ -894,8 +1061,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
uint64_t at = *idx < 4 ? o->avail[*idx] : 0, now = dm_detclock_enabled() ? guest_ns() : now_ns(), wait = at > now ? at - now : 0;
if (!dm_detclock_enabled()) { // 取图线程登记为时间约束线程(不再只在「来早了」时才登记:热态一直落后时也要声明) | Register the acquire thread as a time-constraint thread (no longer registered only when it "arrived early": it must also declare itself when it is constantly behind in the hot state)
static uint64_t rt_period; uint64_t period = present_period(o);
if (period && rt_period != period) { rt_period = period; set_time_constraint(period); }
rt_comp_tick(period);
if (period && rt_period != period) { rt_period = period; set_time_constraint(&g_rt_main, period); }
rt_comp_tick(&g_rt_main, period);
uint64_t pace_t0 = now_ns();
if (mtl_link_active()) { if (!mtl_link_wait_tick(period ? 2 * period : 33333333ull) && wait) sleep_until_ns(at); } // DM_PRESENT_LINK:节拍完全跟显示节拍(跑得快就等下一拍,落后立刻走);自己的 60 Hz 时钟只作等不到节拍时的兜底 | DM_PRESENT_LINK: pacing fully follows the display link (wait for the next display-link tick when running fast, go immediately when behind); our own 60 Hz clock is only the fallback when no display-link tick arrives
else if (wait) sleep_until_ns(at);
@@ -911,8 +1078,8 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
// 该张上一次出图还没被出图线程处理完(显示跟不上、落后一整轮交换链):等它归还,再交给游戏画
// The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
if (tk) { uint64_t w0 = now_ns(); mtl_present_wait(tk); g_pq_wait_ns += now_ns() - w0; }
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = mtl_last_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
if (tk) { uint64_t w0 = now_ns(), rt = x_present_ticket(tk); if (rt) mtl_present_wait(rt); g_pq_wait_ns += now_ns() - w0; } // tk 是翻译队列的出图任务号 | tk is the translation queue's present job number
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
}
@@ -1010,10 +1177,16 @@ static void tsummary(uint64_t frame) {
uint64_t aw = 0, ag = 0; int an = 0; void mtl_alloc_stats(uint64_t *, uint64_t *, int *); mtl_alloc_stats(&aw, &ag, &an);
static uint64_t pyn, pyns; uint64_t yn = 0, yns = 0; dm_main_yield_stats(&yn, &yns);
LOG("[nvn] 翻译细项 至帧 %llu:每帧提交 周期 %.2f M(每条指令 %.2f 周期)、CPU %.3f ms 其中内核态 %.3f ms、墙钟 %.3f ms;平均主频 %.2f GHz(周期 / CPU 时间);本线程 QoS %#x;分配器池 %d 个、累计等 GPU %llu 次;实时声明计算 %.2f ms;主线程让出 每帧 %.0f 次 / %.3f ms", frame,
cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; }
cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_main.comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; }
if (frame % 300 == 0) { unsigned wn = 0; uint32_t wq = dm_guest_work_qos(&wn); thread_extended_info_data_t xi; mach_msg_type_number_t xc = THREAD_EXTENDED_INFO_COUNT; int okx = thread_info(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_INFO, (thread_info_t)&xi, &xc) == KERN_SUCCESS;
thread_time_constraint_policy_data_t tp; mach_msg_type_number_t tc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t def = 0; int rt_live = thread_policy_get(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&tp, &tc, &def) == KERN_SUCCESS && !def; // def = 1:实时策略没在生效(没设上 / 被撤) | def = 1: the real-time policy is not in effect (never set / revoked)
LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_comp_ms, g_rt_period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos()); }
LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_main.comp_ms, g_rt_main.period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos());
if (g_x_port) { // 翻译线程:声明、实时策略在不在生效、当前 / 基础优先级、QoS(降级看这几项;在不在大核看「翻译细项」行的平均主频) | Translation thread: declaration, whether the real-time policy is in effect, current / base priority, QoS (check these for demotion; for whether it is on a performance core, see the average clock on the "translation detail" line)
thread_extended_info_data_t yi; mach_msg_type_number_t yc = THREAD_EXTENDED_INFO_COUNT; int oky = thread_info(g_x_port, THREAD_EXTENDED_INFO, (thread_info_t)&yi, &yc) == KERN_SUCCESS;
thread_time_constraint_policy_data_t yp; mach_msg_type_number_t ytc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t ydef = 0; int y_live = thread_policy_get(g_x_port, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&yp, &ytc, &ydef) == KERN_SUCCESS && !ydef;
qos_class_t yq = QOS_CLASS_UNSPECIFIED; int yr = 0; pthread_get_qos_class_np(g_x_thr, &yq, &yr);
LOG("[nvn] 线程策略:翻译线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);QoS %#x", g_rt_xlat.comp_ms, g_rt_xlat.period_ms, y_live ? "在生效" : "未生效",
oky ? yi.pth_curpri : -1, oky ? yi.pth_priority : -1, oky ? yi.pth_policy : -1, (unsigned)yq); } }
py = cy; pk = ck; pw = cw; }
pi = ci; pc = cc; pd = dr_; pf = frame; }
uint64_t up, re, fa, pr; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr);
@@ -1068,29 +1241,28 @@ static void slow_emit(uint64_t f) {
// The computation used to be hard-coded at 2 ms, while the game main thread (game logic + recording + submit replay) takes about 10 ms per frame when hot - a 5× gap between declared and actual:
// a real-time thread that exceeds its declared computation gets demoted by the system, and the performance controller also sets frequency from the declaration (this declaration is how the system learns the frame deadline and the workload).
// DM_RT_COMP=<ms> fixes the declaration; default auto = every 120 frames take the p90 of this thread's per-frame CPU time and re-declare if it differs from the declared value by > 15% (capped at 0.9 × period).
static void set_time_constraint_comp(uint64_t period_ns, uint64_t comp_ns) {
static void set_time_constraint_comp(rt_decl *d, uint64_t period_ns, uint64_t comp_ns) {
static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);
if (comp_ns < 1000000ull) comp_ns = 1000000ull; if (comp_ns > period_ns * 9 / 10) comp_ns = period_ns * 9 / 10;
thread_time_constraint_policy_data_t p = {
.period = (uint32_t)(period_ns * tb.denom / tb.numer), .computation = (uint32_t)(comp_ns * tb.denom / tb.numer),
.constraint = (uint32_t)(period_ns * tb.denom / tb.numer), .preemptible = 1};
kern_return_t kr = thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&p, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
if (kr == KERN_SUCCESS) { g_rt_comp_ms = comp_ns / 1e6; g_rt_period_ms = period_ns / 1e6; }
LOG("[nvn] 出图线程时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败");
if (kr == KERN_SUCCESS) { d->comp_ms = comp_ns / 1e6; d->period_ms = period_ns / 1e6; }
LOG("[nvn] %s时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", d->who, period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败");
}
static int rt_comp_fixed_ms(void) { static int v = -2; if (v == -2) { const char *e = getenv("DM_RT_COMP"); v = e && *e && strcmp(e, "auto") ? atoi(e) : -1; } return v; } // −1 = auto
static void set_time_constraint(uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms
static void set_time_constraint(rt_decl *d, uint64_t period_ns) { int f = rt_comp_fixed_ms(); set_time_constraint_comp(d, period_ns, f > 0 ? (uint64_t)f * 1000000ull : 2000000ull); } // 首次:固定值,或 auto 的起始值 2 ms | first time: the fixed value, or auto's starting value of 2 ms
// 每帧在取图处调:记本线程自上次以来的 CPU 时间;auto 模式下按 p90 重新声明
// Called every frame at acquire: records this thread's CPU time since the last call; in auto mode re-declares based on p90
static void rt_comp_tick(uint64_t period_ns) {
if (rt_comp_fixed_ms() > 0 || !period_ns || !g_rt_comp_ms) return;
static uint64_t last; static double win[120]; static int n;
uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!last) { last = c; return; }
win[n++] = (double)(c - last) / 1e6; last = c;
if (n < 120) return;
double v[120]; memcpy(v, win, sizeof v); qsort(v, 120, sizeof *v, dcmp); n = 0;
static void rt_comp_tick(rt_decl *d, uint64_t period_ns) { // 在被声明的那条线程上调(读本线程 CPU 时钟) | Call on the thread being declared (reads this thread's CPU clock)
if (rt_comp_fixed_ms() > 0 || !period_ns || !d->comp_ms) return;
uint64_t c = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); if (!d->last) { d->last = c; return; }
d->win[d->n++] = (double)(c - d->last) / 1e6; d->last = c;
if (d->n < 120) return;
double v[120]; memcpy(v, d->win, sizeof v); qsort(v, 120, sizeof *v, dcmp); d->n = 0;
double p90 = v[107], comp = p90 * 1.25, cap = period_ns * 0.9 / 1e6; if (comp > cap) comp = cap; if (comp < 1) comp = 1;
if (comp > g_rt_comp_ms * 1.15 || comp < g_rt_comp_ms * 0.85) set_time_constraint_comp(period_ns, (uint64_t)(comp * 1e6));
if (comp > d->comp_ms * 1.15 || comp < d->comp_ms * 0.85) set_time_constraint_comp(d, period_ns, (uint64_t)(comp * 1e6));
}
static void sleep_until_ns(uint64_t dl) { // 单调时钟上的绝对时刻 | absolute time on the monotonic clock
static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);
@@ -1140,7 +1312,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
present_cfg(o);
gfx_enter();
uint64_t t0 = now_ns();
if (idx >= 0 && idx < o->ntex && idx < 4) o->ticket[idx] = mtl_present(CTX(o->tex[idx]), present_period(o) / 1e9, o->crop); // 只入队,立即返回 | enqueue only, return immediately
if (idx >= 0 && idx < o->ntex && idx < 4) { // 只入队,立即返回;ticket 存翻译队列的任务号 | Enqueue only and return at once; ticket holds the translation queue's job number
xjob j = {XJ_PRESENT, 0, NULL, snap_tex(o->tex[idx]), present_period(o) / 1e9}; memcpy(j.crop, o->crop, sizeof j.crop);
o->ticket[idx] = x_push(&j); }
gfx_leave();
atomic_fetch_add(&g_nvn_ns, now_ns() - t0);
uint64_t f = g_frame, ps, dr; mtl_stats(&ps, &dr);
@@ -1226,7 +1400,9 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
prev_in = t0; prev_pass = ps; prev_draw = dr;
dump_frame();
if (g_frame % TWIN == 0) tsummary(g_frame);
mtl_set_frame(g_frame);
{ static uint64_t pc, py, pf; uint64_t i_, y_, c_ = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); thr_counts(&i_, &y_); // 主线程(游戏线程)的每帧 CPU 与平均主频:与「翻译细项」行的翻译线程对照,分「整机降频」还是「翻译线程被放小核」 | Per-frame CPU and average clock of the main (game) thread: compared with the translation thread on the "translation detail" line, to tell "whole-chip downclocking" from "translation thread placed on an efficiency core"
if (g_frame % TWIN == 0) { if (pf && g_frame > pf && c_ > pc) LOG("[nvn] 主线程 至帧 %llu:每帧 CPU %.2f ms,平均主频 %.2f GHz(周期 / CPU 时间)", g_frame, (c_ - pc) / 1e6 / (double)(g_frame - pf), (double)(y_ - py) / (double)(c_ - pc)); pc = c_; py = y_; pf = g_frame; } }
{ xjob j = {XJ_FRAME}; j.frame = g_frame; j.period = present_period(o) / 1e9; x_push(&j); } // 帧号随队列生效(见翻译队列说明) | The frame number takes effect in queue order (see the translation queue notes)
// 真机语义:出图只入队、立即返回;本帧显示时刻按节拍器排,该贴图到「显示时刻 + 一个周期」才可再获取(阻塞在 AcquireTexture)
// Real-device semantics: present only enqueues and returns immediately; this frame's display time is scheduled by the pacer, and the texture can be acquired again only at "display time + one period" (blocking in AcquireTexture)
uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns();
+100 -25
View File
@@ -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<MTLBuffer> buf; uint64_t gpu; const void *key; } pool_ent;
typedef struct { uintptr_t lo, hi; uintptr_t base; __unsafe_unretained id<MTLBuffer> 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<MTLBuffer> 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<MTLCommandBuffer> 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<MTLTexture> 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<MTLTexture> 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<MTLTexture> 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;
@@ -2061,7 +2105,7 @@ static void shmap_load(void) {
// Warm-up entry: built in the background, waiting to be taken by the submit thread. vs / fs are strong references (in pso they are only raw pointers, and the background dictionary is released when the task ends)
@interface WarmItem : NSObject { @public int kind; NSString *key, *vs_key, *fs_key; NvShader *shader, *vs, *fs; pso_key pso; id<MTLFunction> fsfn; id object; } @end
@implementation WarmItem @end
static NSMutableDictionary<NSString *, NvShader *> *g_shcache;
static NSMutableDictionary<NSString *, NvShader *> *g_shcache; static _Atomic uint32_t g_shcache_n; // 表只在提交线程上读写;条数另记一份原子数给别的线程读(资源计数) | The tables are read and written only on the submit thread; a separate atomic count is kept for other threads to read (resource counts)
static void c1_store(NvShader *o) {
size_t len = o->rf.c1_len;
@@ -2242,7 +2286,7 @@ static NvShader *shader_get(NSString *pc, int stage) {
if (o) return o;
uint64_t bt = bp_now(); o = shader_load(pc, stage);
if (!o) return nil;
g_shcache[pc] = o;
g_shcache[pc] = o; atomic_fetch_add(&g_shcache_n, 1);
pso_record("S\t%s\t%d\n", pc.UTF8String, stage);
pso_user_record("S\t%s\t%d\n", pc.UTF8String, stage);
g_bp_lib_n++; g_bp_lib_ns += bp_now() - bt;
@@ -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<MTLTexture> 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<MTLTexture> 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<MTLTexture> 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(); }
}
@@ -4707,17 +4751,17 @@ static void warm_claim(void) {
for (WarmItem *item in items) {
if (item->kind == 0) {
if (!g_shcache) g_shcache = [NSMutableDictionary dictionary];
if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; g_warm_claim_shaders++; }
if (!g_shcache[item->key]) { g_shcache[item->key] = item->shader; atomic_fetch_add(&g_shcache_n, 1); g_warm_claim_shaders++; }
} else if (item->kind == 1) {
if (!g_shcache) g_shcache = [NSMutableDictionary dictionary];
NvShader *vs = g_shcache[item->vs_key], *fs = item->fs_key.length ? g_shcache[item->fs_key] : nil;
if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; }
if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; }
if (!vs) { vs = item->vs; g_shcache[item->vs_key] = vs; atomic_fetch_add(&g_shcache_n, 1); }
if (item->fs_key.length && !fs) { fs = item->fs; g_shcache[item->fs_key] = fs; atomic_fetch_add(&g_shcache_n, 1); }
item->pso.vs = (__bridge void *)vs; item->pso.fs = (__bridge void *)fs;
if (!hm_get_id(&g_pso, &item->pso)) { hm_put_id(&g_pso, &item->pso, item->object); g_warm_claim_rps++; }
} else {
NvShader *cs = g_shcache[item->key];
if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; }
if (!cs) { cs = item->shader; if (!g_shcache) g_shcache = [NSMutableDictionary dictionary]; g_shcache[item->key] = cs; atomic_fetch_add(&g_shcache_n, 1); }
const void *key = (__bridge const void *)cs;
if (!hm_get_id(&g_cps, &key)) { hm_put_id(&g_cps, &key, item->object); g_warm_claim_cps++; }
}
@@ -4844,6 +4888,7 @@ static void copy_t2b(const p_copy_b2t *c) {
// CPU 读贴图(ReadTexels):预排布贴图以池内存为真值,解排布直读;其余从 MTLTexture blit 读回(调用方已按 NVN 规矩等过 GPU)
// CPU texture read (ReadTexels): for packaged textures the pool memory is the ground truth, de-layout and read directly; the rest are read back from the MTLTexture by blit (the caller has already waited for the GPU per NVN rules)
void mtl_read_texels(const tex_t *t, unsigned level, unsigned layer0, const NVNcopyRegion *r, uint8_t *dst, size_t row, size_t img) {
if (!on_sub_thread()) while (atomic_load(&g_up_pending)) usleep(200); // 翻译在翻译线程:调用方已排空队列(批已随提交冲刷),这里只等上传在 GPU 上做完(提交线程上由 q_cb 冲刷并等) | Translation runs on the translation thread: the caller has already drained the queue (batches were flushed with the submit), so here we only wait for uploads to finish on the GPU (on the submit thread q_cb flushes and waits)
xv_check(t->serial, level, layer0, "CPU读回");
PD("U cpu_read ser=%llu lv%u sl%u xyz=%d,%d,%d size=%d,%d,%d dst=%p row=%lu img=%lu", t->serial, level, layer0, r->xoffset, r->yoffset, r->zoffset, r->width, r->height, r->depth, dst, (unsigned long)row, (unsigned long)img);
int bw, bh, bpb = nvn_fmt_bpb(t->d.format, &bw, &bh);
@@ -5062,7 +5107,13 @@ static const char *cctx_snap(void) {
// State constants / buffer updates / events / counters / texture uploads execute as usual (the UI pass needs them, the game is waiting).
int g_frz_on = -1;
static int g_frz_phase = 2, g_frz_drop, g_frz_seen_ds; static uint64_t g_frz_full_n, g_frz_skip_n;
void mtl_world_frozen(int on) { g_frz_on = on != 0; }
// 宿主在游戏线程上写的两个画法开关(冻结位、强制全画)先记成请求,提交入队时锁存进任务(mtl_host_latch),翻译线程执行那次提交前生效(mtl_host_apply):
// 生效时机与同步翻译时一样落在两次提交之间,不会在翻译途中翻转(回放每条操作都读冻结位;强制全画计数回放里自减,宿主直接写会丢)
// The two drawing switches the host writes on the game thread (freeze bit, force full draw) are first recorded as requests, latched into the job when the submit is enqueued (mtl_host_latch), and take effect before the translation thread runs that submit (mtl_host_apply):
// they take effect between two submits just as with synchronous translation and never flip in the middle of translation (replay reads the freeze bit for every operation; the force-full-draw counter is decremented in replay, and a direct write by the host would lose one)
static _Atomic int g_frz_req = -1, g_force_req;
void mtl_world_frozen(int on) { atomic_store(&g_frz_req, on != 0); }
uint64_t mtl_host_latch(void) { return (uint64_t)(uint32_t)(atomic_load(&g_frz_req) + 1) | (uint64_t)(uint32_t)atomic_exchange(&g_force_req, 0) << 32; }
static int frz_wanted(void) { if (g_frz_on < 0) { const char *e = getenv("DM_NVN_TEST_FRZ"); g_frz_on = e && atoi(e); if (g_frz_on) MLOG("DM_NVN_TEST_FRZ:世界冻结状态位由测试开关顶替(常开)"); } tbdr_on(); return g_frz_on > 0 && tbdr_on() && g_ruler_truth <= 0; }
// ---------- 运行时外推(省电画法;不给玩家开关;线上出过卡顿缺陷,现缺省关,A17 上有不卡的证据再开)----------
// 3D 隔帧:全画帧照常画,并在附件被挪作他用之前拷下不透明 HDR(468)、主深度模板、色调映射后的 468、FXAA 后的 469;
@@ -5091,7 +5142,8 @@ static struct { int env, frame, filt, first, hdrp, mainp_seen, skipall, oit_seen
static int rt_want(void);
static void rt_toggle_poll(void) { static int tg = -1; if (tg < 0) { const char *e = getenv("DM_RT_AB_TOGGLE"); tg = e ? atoi(e) : 0; (void)rt_want(); } // 首次顺带读 DM_RT_AB(真机上世界冻结位早早置 0,frz_op 不一定被调到) // 测试:每 tg 秒按墙钟在 A / B 之间来回切 | On first call also read DM_RT_AB (on a real device the world-freeze bit is set to 0 very early, so frz_op is not necessarily called) // test: switch back and forth between A / B every tg seconds by wall clock
if (tg > 0) { int v = (int)((time(NULL) / tg) & 1); if (v != g_dm_rt_ab) { g_dm_rt_ab = v; MLOG("DM_RT_AB_TOGGLE:画法切到 %s", v ? "B" : "A"); } } }
void mtl_rt_force_full(int n) { g_rt.force_full = n; } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画 | Called by the host: before an overall picture change such as switching the 3D render scale, the following n frames are all fully drawn
void mtl_rt_force_full(int n) { atomic_store(&g_force_req, n); } // 宿主调:要换 3D 渲染比例等画面整体变化前,之后 n 帧一律全画(随下一次提交生效) | Called by the host: before a change to the whole picture such as switching the 3D render scale, draw everything for the next n frames (takes effect with the next submit)
void mtl_host_apply(uint64_t v) { int frz = (int)(uint32_t)v - 1, force = (int)(v >> 32); if (frz >= 0) g_frz_on = frz; if (force) g_rt.force_full = force; }
// ---------- 省电模式(30 帧)----------
// 开:显示节拍对象改 30 Hz(帧率范围 30–30,ProMotion 屏跟着降刷新率;front_ios.m 的帧率提示一起降),游戏每拍出一帧;运行时外推关(每帧真画)。
// 游戏逻辑本来就按 25 拍 / 秒走、单位位置按时间插值,30 帧下没有重复帧(真机实测:每帧镜头位移的变异系数 30 帧 0.292、60 帧 0.296)。
@@ -5358,7 +5410,7 @@ void mtl_res_snapshot(mtl_res_count *out) {
out->pso = g_pso.n;
out->cps = g_cps.n;
out->dss = g_dss.n;
out->shaders = (uint32_t)(g_shcache ? g_shcache.count : 0);
out->shaders = atomic_load(&g_shcache_n); // 资源计数在宿主线程上取,回放在翻译线程上改表 | Resource counts are taken on the host thread while replay changes the tables on the translation thread
os_unfair_lock_lock(&g_c1_lock);
out->c1_bufs = (uint32_t)(g_c1_banks.count + g_c1_exclusive); out->c1_alloc = g_c1_alloc_bytes; out->c1_data = g_c1_data_bytes;
os_unfair_lock_unlock(&g_c1_lock);
@@ -5678,9 +5730,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<MTLTexture> present_src(id<MTLTexture> 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<MTLTexture> 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<MTLTexture> 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<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4]) {
static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src0, id<MTLTexture> dst, const int crop[4]) {
id<MTLTexture> 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 +5793,8 @@ static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTex
[en endEncoding];
return 1;
}
static int present_encode_m4(CBUF cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i) {
static int present_encode_m4(CBUF cb, id<MTLTexture> src0, id<MTLTexture> dst, const int crop[4], int uv_i) {
id<MTLTexture> 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 ||
+6 -3
View File
@@ -33,6 +33,7 @@ typedef struct {
typedef struct {
uint32_t magic; nvn_texdesc d; nvn_texlayout L; uint8_t *mem; pool_t *pool; int64_t off; uint8_t has_layout, layout[8];
uint64_t serial; // 初始化序号:回放层按它在宿主表里找 MTLTexture(游戏可能按值拷贝对象,不能存对象指针) | Initialization serial: the replay layer uses it to find the MTLTexture in the host table (the game may copy the object by value, so object pointers cannot be stored)
const void *snap; // 本序号的不可变副本(hle_nvn.c snap_tex):命令载荷存它,不存游戏对象地址 | This serial's immutable snapshot (hle_nvn.c snap_tex): command payloads store it, not the game object's address
} tex_t; FITS(tex_t, NVNtexture);
typedef struct { uint8_t set_levels, set_layers, set_format, set_target; int32_t base_level, nlevels, min_layer, nlayers, format, target; } view_t;
FITS(view_t, NVNtextureView);
@@ -43,7 +44,7 @@ typedef struct { uint8_t minf, magf, ws, wt, wr, cmp_mode, cmp_func; float lod_m
typedef struct { NVNdevice *dev; samp_par p; } samp_builder_t; FITS(samp_builder_t, NVNsamplerBuilder);
typedef struct { uint32_t magic; samp_par p; } samp_t; FITS(samp_t, NVNsampler);
typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键 | serial: table key for the replay layer's resolved result
typedef struct { uint32_t magic, nstage; NVNshaderData sd[6]; uint64_t serial; const void *snap; } prog_t; FITS(prog_t, NVNprogram); // serial:回放层解析结果的表键;snap:本序号的不可变副本(同 tex_t) | serial: table key for the replay layer's resolved results; snap: this serial's immutable snapshot (same as tex_t)
typedef struct { uint32_t magic, fenced; uint64_t fence; } sync_t; FITS(sync_t, NVNsync);
typedef struct { const pool_t *pool; int64_t off; } ev_builder_t; FITS(ev_builder_t, NVNeventBuilder);
@@ -94,8 +95,8 @@ enum {
OP_STENCIL, OP_POLY_OFFSET, OP_DRAW, OP_DRAW_IDX, OP_DISPATCH, OP_BARRIER,
OP_SET_TEX_POOL, OP_SET_SAMP_POOL, OP_COPY_B2T, OP_COPY_STRIDE, OP_BLEND_COLOR, OP_COPY_T2B, OP_BIND_IMG, OP_COPY_T2T, OP_RESET_COUNTER, OP_CLEAR_TEX, OP_SHADER_SCRATCH, OP_WAIT_SYNC, OP_FENCE_SYNC, OP_WAIT_EVENT, OP_COUNT_
};
// 载荷(紧跟 op_hdr)
// Payload (immediately follows op_hdr)
// 载荷(紧跟 op_hdr)。贴图 / 程序指针都指向录制时按序号留下的不可变副本(snap_tex / snap_prog),游戏之后改写或重建对象不影响已录的命令
// Payload (right after op_hdr). Texture / program pointers point to the immutable snapshots kept by serial at record time (snap_tex / snap_prog); later rewrites or rebuilds of the object by the game do not affect recorded commands
typedef struct { int32_t n; const tex_t *color[8]; view_t cview[8]; uint8_t has_cview[8]; const tex_t *depth; view_t dview; uint8_t has_dview; } p_set_rt;
typedef struct { int32_t index, mask; float rgba[4]; } p_clear_color;
typedef struct { float depth; int32_t depth_mask, stencil, stencil_mask; } p_clear_ds;
@@ -137,6 +138,8 @@ void mtl_set_tex_pool_n(int n); // 贴图描述符池
// 计时埋点(Mac / iOS 共用):提交按帧号打标;GPU 时间 = 该帧全部命令缓冲 GPUEnd−GPUStart 之和,全部完成后才可读(否则 −1)
// Timing instrumentation (shared by Mac / iOS): submissions are tagged with the frame number; GPU time = sum of GPUEnd−GPUStart over all of that frame's command buffers, readable only after all complete (otherwise −1)
void mtl_set_frame(uint64_t f);
uint64_t mtl_host_latch(void); // 游戏线程提交入队时锁存宿主写的画法开关(冻结位 / 强制全画),随任务带到翻译线程 | When the game thread enqueues a submit it latches the host-written drawing switches (freeze bit / force full draw), carried with the job to the translation thread
void mtl_host_apply(uint64_t v); // 翻译线程执行那次提交前生效 | Takes effect before the translation thread runs that submit
void mtl_ub_present(double iv_ms); // 同进程交替测量(DM_NVN_UB):出图线程每帧报实际上屏间隔 | Same-process alternating measurement (DM_NVN_UB): the present thread reports the actual present interval every frame
double mtl_gpu_ms(uint64_t f);
void mtl_sub_index(const uint64_t *h, int n); // 提交开始:按回放顺序建写回前瞻索引(nvn_mtl.m) | Start of submission: build the store lookahead index in replay order (nvn_mtl.m)
+2
View File
@@ -43,3 +43,5 @@ t_xv
t_xv.dSYM/
t_ub
t_ub.dSYM/
t_rt_srgb_view
t_rt_srgb_view.dSYM/
+4
View File
@@ -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 目录里用同一份测试源码另编另跑,不动这里的缺省产物。
+47 -1
View File
@@ -302,7 +302,7 @@ int main(void) {
for (int i = 0; i < 24; i++) P(nvnCommandBufferCopyBufferToBuffer)(&cb, (NVNbufferAddress)heap, (NVNbufferAddress)(heap + big), big, 0);
NVNcommandHandle hbusy = P(nvnCommandBufferEndRecording)(&cb);
P(nvnQueueSubmitCommands)(&q, 1, &hbusy);
uint64_t f = mtl_last_fence();
uint64_t f = x_fence(); // 游戏经 FenceSync 拿到的栅栏值(翻译异步:可能还没翻译到) | Fence value the game gets from FenceSync (translation is asynchronous: it may not have been translated yet)
int busy_before = !mtl_wait(f, 0);
dm_gfx_suspend(1);
EXPECT("挂起前 GPU 确实在忙(零超时等待未完成)", 1, busy_before);
@@ -359,6 +359,52 @@ int main(void) {
mtl_present_test_stall(0); mtl_present_flush();
}
// 8. 对象副本:录完命令后游戏 Finalize 并在同址重建贴图 / 换程序着色器,已录命令里读到的仍是录制时的内容;退役副本过 SNAP_KEEP 次提交才回收
// 8. Object snapshots: after commands are recorded the game Finalizes and rebuilds a texture at the same address / swaps a program's shaders; recorded commands still read what was there at record time; retired snapshots are reclaimed only after SNAP_KEEP submits
{
NVNtextureBuilder b; NVNtexture tx; P(nvnTextureBuilderSetDevice)(&b, &dev); P(nvnTextureBuilderSetDefaults)(&b);
P(nvnTextureBuilderSetWidth)(&b, 8); P(nvnTextureBuilderSetHeight)(&b, 4); P(nvnTextureBuilderSetFormat)(&b, NVN_FORMAT_RGBA8); P(nvnTextureInitialize)(&tx, &b);
NVNprogram pg; NVNshaderData sd[2]; memset(sd, 0, sizeof sd); P(nvnProgramInitialize)(&pg, &dev); P(nvnProgramSetShaders)(&pg, 1, sd);
const NVNtexture *ct[1] = {&tx};
P(nvnCommandBufferBeginRecording)(&cb);
P(nvnCommandBufferSetRenderTargets)(&cb, 1, ct, NULL, NULL, NULL);
P(nvnCommandBufferBindProgram)(&cb, &pg, NVN_SHADER_STAGE_VERTEX_BIT);
NVNcommandHandle hs = P(nvnCommandBufferEndRecording)(&cb);
const p_set_rt *rt = NULL; const p_bind_program *bp = NULL;
for (const uint8_t *p = (const uint8_t *)hs; p;) { // 按记录格式走:JUMP 跟到下一段,END 结束 | Walk the record format: follow JUMP to the next segment, stop at END
op_hdr h; memcpy(&h, p, sizeof h);
if (h.op == OP_END) break;
if (h.op == OP_JUMP) { memcpy(&p, p + 8, 8); continue; }
if (h.op == OP_SET_RT) rt = (const p_set_rt *)(p + 8);
if (h.op == OP_BIND_PROGRAM) bp = (const p_bind_program *)(p + 8);
p += h.size;
}
EXPECT("录到 SET_RT 与 BIND_PROGRAM", 2, (rt != NULL) + (bp != NULL));
if (rt && bp) {
const tex_t *s0 = rt->color[0];
EXPECT("SET_RT 存的不是游戏对象地址", 1, (const void *)s0 != (const void *)&tx);
EXPECT("副本宽 8", 8, s0->d.width);
NVNtexture cp; memcpy(&cp, &tx, sizeof cp);
EXPECT("按值拷来的同序号对象共用同一副本", 1, snap_tex(&cp) == s0);
uint64_t ser0 = s0->serial;
P(nvnTextureFinalize)(&tx); P(nvnTextureBuilderSetWidth)(&b, 16); P(nvnTextureBuilderSetHeight)(&b, 16); P(nvnTextureInitialize)(&tx, &b);
EXPECT("同址重建后已录命令仍读到宽 8", 8, rt->color[0]->d.width);
EXPECT("同址重建后已录命令仍是旧序号", 1, rt->color[0]->serial == ser0);
const tex_t *s1 = snap_tex(&tx);
EXPECT("重建后再录取到新副本、宽 16", 16, s1 != s0 ? (long long)s1->d.width : -1);
P(nvnProgramSetShaders)(&pg, 2, sd);
EXPECT("换着色器后已录命令的程序仍是 1 段", 1, bp->prog->nstage);
x_drain(); uint64_t s_at = atomic_load(&g_x_subs); // 退役盖戳 = 当时已入队的提交数;回收按已执行数 | Retire stamp = number of submits enqueued at that time; reclaim goes by the number executed
for (int k = 1; k < SNAP_KEEP; k++) snap_tick(s_at + k);
EXPECT("退役后 SNAP_KEEP−1 次提交:副本还在", 8, s0->d.width);
snap_tick(s_at + SNAP_KEEP);
EXPECT("退役后 SNAP_KEEP 次提交:副本已回收(序号清零)", 0, s0->serial);
const tex_t *s2 = snap_tex(&cp);
EXPECT("回收后旧拷贝对象再取副本:宽 8、序号是它自己的", 8, s2->serial == ((const tex_t *)&cp)->serial ? (long long)s2->d.width : -1);
}
P(nvnTextureFinalize)(&tx); P(nvnProgramFinalize)(&pg);
}
// 7. 未实现函数:返回 0、报红、只报一次
// 7. Unimplemented functions: return 0, report a failure, report only once
unsigned ui = 0; while (strcmp(nvn_names[ui], "nvnBufferBuilderSetDefaults")) ui++;
+1 -1
View File
@@ -71,7 +71,7 @@ int main(void) { @autoreleasepool {
NVNT_nvnQueuePresentTexture present=(NVNT_nvnQueuePresentTexture)get(NULL,"nvnQueuePresentTexture");
tex_t tex={.serial=10001};tex.d.width=tex.d.height=8;tex.d.depth=tex.d.levels=1;tex.d.format=NVN_FORMAT_RGBA8;tex.d.target=NVN_TEXTURE_TARGET_2D;serial_put(tex.serial,src);
win_t win={.ntex=1};win.tex[0]=(NVNtexture *)&tex;set((NVNwindow *)&win,4,4,4,4);
mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);uint64_t tk=win.ticket[0];set((NVNwindow *)&win,0,0,8,8);
mtl_present_test_stall(100000000);present(NULL,(NVNwindow *)&win,0);set((NVNwindow *)&win,0,0,8,8);uint64_t tk=x_present_ticket(win.ticket[0]); // ticket 存翻译队列任务号,换成出图线程票号 | ticket holds the translation queue's job number; swap it for the present thread's ticket
#ifdef CROP_LEGACY_HEADER
EXPECT("旧队列结构没有四参数副本空间(结构检查)",1,sizeof(pq_item)>=sizeof(tex_t)+sizeof(double)+sizeof(uint64_t)+sizeof br);
#else
+58
View File
@@ -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<MTLBuffer> 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<MTLTexture> s = [g_dev newTextureWithDescriptor:d], s2 = [g_dev newTextureWithDescriptor:d];
id<MTLTexture> v = present_src(s);
EXPECT("呈现:sRGB 交换链经 RGBA8Unorm 视图采样", MTLPixelFormatRGBA8Unorm, v.pixelFormat);
EXPECT("呈现:视图的底图就是交换链贴图", 1, v.parentTexture == s);
EXPECT("呈现:同一张交换链贴图第二次取到同一个视图(缓存)", 1, present_src(s) == v);
id<MTLTexture> v2 = present_src(s2);
EXPECT("呈现:另一张交换链贴图各自一个视图", 1, v2 != v && v2.parentTexture == s2);
id<MTLTexture> 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;
} }
+3
View File
@@ -2948,6 +2948,9 @@ void dm_vk_copy_test_read(const tex_t *source,unsigned level,unsigned layer,uint
void mtl_stats(uint64_t *passes,uint64_t *draws) { *passes=G.pass_count;*draws=G.draws; }
void mtl_pkg_stats(uint64_t *uploads,uint64_t *reuploads) { *uploads=G.uploads;*reuploads=0; }
void mtl_set_frame(uint64_t frame) { G.frame=frame; }
// 宿主画法开关(冻结位 / 强制全画):Vulkan 后端没有这两种画法,锁存值恒 0 | host drawing switches (freeze bit / force full draw): the Vulkan backend has neither, the latched value is always 0
uint64_t mtl_host_latch(void) { return 0; }
void mtl_host_apply(uint64_t v) { (void)v; }
double mtl_gpu_ms(uint64_t frame) { (void)frame;return -1; }
int mtl_gpu_span(uint64_t frame,uint64_t *a,uint64_t *b) { (void)frame;(void)a;(void)b;return 0; }
int mtl_warm_wait(int timeout) { (void)timeout;return 0; } /* No asynchronous pipeline warm-up job exists. */