Older systems: iOS 18+ / macOS 15+ via the older-API build; floating left stick; runeword required level; Mac keyboard, mouse and docs; clearer older-device dialog

This commit is contained in:
jhaizhou
2026-10-14 01:49:25 +08:00
parent 2eb5758771
commit d9e95c3381
52 changed files with 1325 additions and 274 deletions
+1
View File
@@ -0,0 +1 @@
tests_m3/
+293 -69
View File
@@ -14,6 +14,36 @@
#include <sys/mman.h>
#include <fcntl.h>
#include "nvn_mtl.h"
// 编译期开关 DM_NVN_M3=1:图形后端走老接口(普通命令队列 / 命令缓冲 / 渲染与计算与拷贝编码器,逐槽绑定缓冲,对参数块引用的资源逐个声明),
// 目标 macOS 15 / iOS 18。缺省 0 = Metal 4(macOS 26 / iOS 26)。两支共用同一份回放逻辑,分叉处都在 #if DM_NVN_M3 里
// Compile-time switch DM_NVN_M3=1: the graphics backend uses the older API (ordinary command queue / command buffers / render, compute and copy encoders, buffers bound per slot, each resource referenced by an argument block declared individually),
// target macOS 15 / iOS 18. Default 0 = Metal 4 (macOS 26 / iOS 26). Both branches share the same replay logic, and every divergence is inside #if DM_NVN_M3
#ifndef DM_NVN_M3
#define DM_NVN_M3 0
#endif
#if DM_NVN_M3
#define RENC id<MTLRenderCommandEncoder>
#define CENC id<MTLComputeCommandEncoder>
#define BENC id<MTLBlitCommandEncoder>
#define CBUF id<MTLCommandBuffer>
#define RPD MTLRenderPassDescriptor
#define FB_ON(o, cb) cb
#define M4_ONLY(...)
#define M3_PRESENT(cb, dr) [cb presentDrawable:dr]
#define FB_SEL addCompletedHandler
#define FB_ARG id<MTLCommandBuffer>
#else
#define RENC id<MTL4RenderCommandEncoder>
#define CENC id<MTL4ComputeCommandEncoder>
#define BENC id<MTL4ComputeCommandEncoder>
#define CBUF id<MTL4CommandBuffer>
#define RPD MTL4RenderPassDescriptor
#define FB_ON(o, cb) o
#define M4_ONLY(...) __VA_ARGS__
#define M3_PRESENT(cb, dr) [dr present]
#define FB_SEL addFeedbackHandler
#define FB_ARG id<MTL4CommitFeedback>
#endif
#include "nvn_obj.h"
#include "../tex/nvn_fmt_mtl.h"
#include "../tex/nvn_deswizzle.h"
@@ -54,19 +84,26 @@ static id<MTLDevice> g_dev;
static NSMutableArray *g_l3_gpu_leaks;
static int g_nvn_deswz_gpu;
static id<MTLCommandQueue> g_q;
#if !DM_NVN_M3
static id<MTL4CommandQueue> g_q4;
static dispatch_queue_t g_feedback_q;
#endif
static _Atomic uint32_t g_present_qos;
#define ALLOC_MAX 8
static id<MTL4CommandAllocator> g_alloc4[ALLOC_MAX]; static int g_alloc_n, g_alloc_cur; // 主提交的命令分配器池:开工时挑一个 GPU 已用完的,没有就新建(到上限才等) | Command allocator pool of the main submission: at start pick one the GPU has finished with, create a new one if there is none (wait only at the cap)
static int g_alloc_n, g_alloc_cur; // 主提交的在途槽(Metal 4:每槽一个命令分配器;老接口:只用来限制在途提交数) | in-flight slots of the main submission (Metal 4: one command allocator per slot; older API: used only to limit the number of in-flight submissions)
#if !DM_NVN_M3
static id<MTL4CommandAllocator> g_alloc4[ALLOC_MAX]; // 主提交的命令分配器池:开工时挑一个 GPU 已用完的,没有就新建(到上限才等) | Command allocator pool of the main submission: at start pick one the GPU has finished with, create a new one if there is none (wait only at the cap)
static id<MTL4CommandAllocator> g_up_alloc4[3];
static id<MTL4CommandAllocator> g_present_alloc4[3];
static id<MTL4CommandBuffer> g_present_cb[3];
static CBUF g_present_cb[3];
static id<MTL4ArgumentTable> g_vt, g_ft, g_ct, g_up_ct;
static id<MTL4ArgumentTable> g_present_args;
#endif
static id<MTLBuffer> g_present_uv[3];
int g_bloom_q = -1; // 泛光 1/4 起点(非 static:真机同进程交替直接改 0 / 1) | Bloom 1/4 starting point (non-static: real-device same-process alternation sets it to 0 / 1 directly)
#if !DM_NVN_M3
static id<MTL4ArgumentTable> g_bloomq_args;
#endif
static id<MTLBuffer> g_bloomq_const[3];
static id<MTLSamplerState> g_bloomq_samp;
static id<MTLRenderPipelineState> g_bloomq_pso;
@@ -99,6 +136,25 @@ static _Atomic int g_up_pending;
static pthread_mutex_t g_res_mu = PTHREAD_MUTEX_INITIALIZER; // 驻留集专用锁:res_add 会在持 g_mu 的路径里调用(arena_new),不能共用 g_mu | Dedicated lock for the residency set: res_add is called on paths that hold g_mu (arena_new), so it cannot share g_mu
static NSHashTable *g_res_objects;
#if DM_NVN_M3
// 老接口按「缓冲对象 + 偏移」绑定,而回放层手里是显卡地址:登记过的缓冲(内存池的零拷贝缓冲、参数区块、暂存块等,几十个)按地址区间反查。
// 弱引用登记(__unsafe_unretained + 撤驻留时摘掉);最近命中的那一项先试——同一通道里的绑定几乎都落在同一两个缓冲上
// The older API binds by "buffer object + offset", while the replay layer holds GPU addresses: registered buffers (zero-copy buffers of memory pools, argument blocks, staging blocks and so on, a few dozen) are looked up by address range.
// Registered by weak reference (__unsafe_unretained, removed when residency is withdrawn); the most recently hit entry is tried first - bindings within one pass almost always land on the same one or two buffers
enum { M3_BUFS = 512 };
static struct { uint64_t gpu, len; __unsafe_unretained id<MTLBuffer> buf; } g_m3_bufs[M3_BUFS]; static int g_m3_nbufs; static os_unfair_lock g_m3_lk = OS_UNFAIR_LOCK_INIT;
static void m3_buf_add(id<MTLBuffer> b) { os_unfair_lock_lock(&g_m3_lk); if (g_m3_nbufs < M3_BUFS) { g_m3_bufs[g_m3_nbufs].gpu = b.gpuAddress; g_m3_bufs[g_m3_nbufs].len = b.length; g_m3_bufs[g_m3_nbufs++].buf = b; } os_unfair_lock_unlock(&g_m3_lk); }
static void m3_buf_del(id b) { os_unfair_lock_lock(&g_m3_lk); for (int i = 0; i < g_m3_nbufs; i++) if (g_m3_bufs[i].buf == b) { g_m3_bufs[i] = g_m3_bufs[--g_m3_nbufs]; break; } os_unfair_lock_unlock(&g_m3_lk); }
static id<MTLBuffer> m3_buf(uint64_t gpu, NSUInteger *off) {
static _Thread_local int last; id<MTLBuffer> r = nil; *off = 0; if (!gpu) return nil;
os_unfair_lock_lock(&g_m3_lk);
int i = last < g_m3_nbufs && gpu >= g_m3_bufs[last].gpu && gpu - g_m3_bufs[last].gpu < g_m3_bufs[last].len ? last : -1;
for (int k = 0; i < 0 && k < g_m3_nbufs; k++) if (gpu >= g_m3_bufs[k].gpu && gpu - g_m3_bufs[k].gpu < g_m3_bufs[k].len) i = k;
if (i >= 0) { last = i; r = g_m3_bufs[i].buf; *off = (NSUInteger)(gpu - g_m3_bufs[i].gpu); }
os_unfair_lock_unlock(&g_m3_lk);
return r;
}
#endif
// 测试开关 DM_RES_CENSUS=1(不常开):记下进过驻留集的全部对象(弱引用),内存读数行那一拍按「还在驻留集里 / 已移出驻留集却还没销毁」各报个数与占用。
// 后一类 = 我们已经不用、但还有人攥着引用(例如客体线程上从不排空的自动释放池)的显卡内存
// Test switch DM_RES_CENSUS=1 (not normally on): records every object that has entered the residency set (weak references); on the tick of the memory readout line it reports the count and size of those "still in the residency set" and those "removed from the residency set but not yet destroyed".
@@ -110,6 +166,9 @@ static void res_add(id<MTLResource> r) {
[g_res addAllocation:(id<MTLAllocation>)r];
if (!g_res_objects) g_res_objects = [NSHashTable weakObjectsHashTable];
[g_res_objects addObject:r];
#if DM_NVN_M3
if ([r conformsToProtocol:@protocol(MTLBuffer)]) m3_buf_add((id<MTLBuffer>)r);
#endif
if (g_res_census < 0) g_res_census = getenv("DM_RES_CENSUS") != NULL;
if (g_res_census > 0) { if (!g_res_ever) g_res_ever = [NSHashTable weakObjectsHashTable]; [g_res_ever addObject:r]; }
g_res_dirty = 1;
@@ -120,6 +179,9 @@ static void res_remove(id<MTLResource> r) {
pthread_mutex_lock(&g_res_mu);
[g_res removeAllocation:(id<MTLAllocation>)r];
[g_res_objects removeObject:r];
#if DM_NVN_M3
m3_buf_del(r);
#endif
g_res_dirty = 1;
pthread_mutex_unlock(&g_res_mu);
}
@@ -273,13 +335,16 @@ void mtl_init(void) {
if (!g_res) MDIE("建立 MTLResidencySet 失败");
[g_q addResidencySet:g_res];
{ void crash_set_wait_dump(void (*fn)(void)); void mtl_wait_state_dump(void); crash_set_wait_dump(mtl_wait_state_dump); }
#if !DM_NVN_M3
dispatch_queue_attr_t feedback_attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INTERACTIVE, 0);
g_feedback_q = dispatch_queue_create("dm.nvn.mtl4-feedback", feedback_attr);
MTL4CommandQueueDescriptor *q4d = [MTL4CommandQueueDescriptor new]; q4d.feedbackQueue = g_feedback_q;
g_q4 = [g_dev newMTL4CommandQueueWithDescriptor:q4d error:&re];
if (!g_q4) MDIE("建立 MTL4CommandQueue 失败");
[g_q4 addResidencySet:g_res];
#endif
g_alloc_n = 3;
#if !DM_NVN_M3
for (int i = 0; i < 3; i++) {
MTL4CommandAllocatorDescriptor *ad = [MTL4CommandAllocatorDescriptor new];
ad.label = [NSString stringWithFormat:@"nvn-mtl allocator %d", i];
@@ -308,6 +373,7 @@ void mtl_init(void) {
if (!g_present_args) MDIE("建立出图 argument table 失败:%s", ate.localizedDescription.UTF8String);
g_bloomq_args = [g_dev newArgumentTableWithDescriptor:pad error:&ate];
if (!g_bloomq_args) MDIE("建立泛光 1/4 argument table 失败:%s", ate.localizedDescription.UTF8String);
#endif
for (int i = 0; i < 3; i++) {
g_present_uv[i] = [g_dev newBufferWithLength:sizeof(float) * 8 options:MTLResourceStorageModeShared];
if (!g_present_uv[i]) MDIE("建立出图 UV 缓冲[%d] 失败", i);
@@ -428,7 +494,7 @@ static zskip_zero g_zskip_cand[8]; static uint8_t g_zskip_cand_ok[8];
static void zskip_clear(void);
static int tbdr_on(void);
static id g_cb;
static id<MTL4ComputeCommandEncoder> g_blit;
static BENC g_blit;
static NSMutableArray<dispatch_block_t> *g_commit_blocks;
static uint64_t g_alloc_fence[ALLOC_MAX]; static uint64_t g_alloc_waits, g_alloc_grown;
int mtl_wait(uint64_t fence, uint64_t timeout_ns);
@@ -476,20 +542,30 @@ void mtl_sub_begin(void) {
g_sub_thread = pthread_self(); atomic_store(&g_sub_thread_set, 1);
atomic_store(&g_last_commit_error, 0);
g_sub_pool = objc_autoreleasePoolPush();
#if DM_NVN_M3
g_cb = [g_q commandBuffer];
#else
g_cb = [g_dev newCommandBuffer];
#endif
// 不在帧中间等 GPU(真机热态:固定 3 个轮转时 GPU 跟不上就每帧在这里阻塞,提交线程睡醒后按低频跑,指令数 −18% 而 CPU 时间 +49%):
// 挑一个 GPU 已用完的分配器;都在用就新建;到上限才等最老的那个。超前量由游戏取交换链贴图处的等待约束,与旧接口相同。
// Do not wait for the GPU mid-frame (hot real device: with a fixed rotation of 3, when the GPU cannot keep up every frame blocks here, and the submit thread runs at low frequency after waking, instruction count −18% but CPU time +49%):
// pick an allocator the GPU has finished with; if all are in use create a new one; only at the cap wait for the oldest one. How far ahead it runs is bounded by the wait where the game acquires the swapchain texture, same as the old interface.
int alloc_i = -1; uint64_t done = g_done;
for (int i = 0; i < g_alloc_n; i++) if (g_alloc_fence[i] <= done) { alloc_i = i; break; }
#if DM_NVN_M3
if (alloc_i < 0 && g_alloc_n < ALLOC_MAX) { alloc_i = g_alloc_n++; g_alloc_grown++; }
#else
if (alloc_i < 0 && g_alloc_n < ALLOC_MAX) { NSError *ae = nil; MTL4CommandAllocatorDescriptor *ad = [MTL4CommandAllocatorDescriptor new];
g_alloc4[g_alloc_n] = [g_dev newCommandAllocatorWithDescriptor:ad error:&ae]; if (!g_alloc4[g_alloc_n]) MDIE("新建 MTL4CommandAllocator 失败:%s", ae.localizedDescription.UTF8String);
alloc_i = g_alloc_n++; g_alloc_grown++; }
#endif
if (alloc_i < 0) { alloc_i = 0; for (int i = 1; i < g_alloc_n; i++) if (g_alloc_fence[i] < g_alloc_fence[alloc_i]) alloc_i = i; g_alloc_waits++; mtl_wait(g_alloc_fence[alloc_i], UINT64_MAX); }
g_alloc_cur = alloc_i;
#if !DM_NVN_M3
[g_alloc4[alloc_i] reset];
[g_cb beginCommandBufferWithAllocator:g_alloc4[alloc_i]];
#endif
g_commit_blocks = [NSMutableArray array];
g_npost = 0; g_vis = nil; g_vis_n = 0; g_vis_cur = -1; g_npend = 0; g_pend_over = 0;
zskip_clear(); g_zskip_count = 0;
@@ -521,43 +597,80 @@ static void ser_gate(void) {
// 只放开头不够:t_rt_range「通道 1 → 通道 2 → 拷贝」读回黑色,补上结束处屏障后 19/19。旧队列的编码器(上传 / 诊断 / 上屏)不走这里的屏障。
// Metal 4 conservative barriers (first version): a consumer barrier at the start of an encoder (all prior work → this encoder) and a producer barrier at the end (this encoder and earlier → later encoders).
// Only the one at the start is not enough: t_rt_range 'pass 1 → pass 2 → copy' read back black, and after adding the end barrier it is 19/19. Old-queue encoders (upload / diagnostics / present) do not go through these barriers.
#if DM_NVN_M3
static inline void m4_end(id e) { [e endEncoding]; } // 老接口没有显式屏障:依赖关系由 useResource 声明 + 系统自动跟踪 | the older API has no explicit barriers: dependencies come from useResource declarations plus the system's automatic tracking
static inline void m3_rbuf(id<MTLRenderCommandEncoder> e, int vertex, NSUInteger i, uint64_t gpu) {
NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; }
if (vertex) [e setVertexBuffer:b offset:off atIndex:i]; else [e setFragmentBuffer:b offset:off atIndex:i];
}
#else
static inline void m4_end(id e) {
if ([e conformsToProtocol:@protocol(MTL4CommandEncoder)]) [(id<MTL4CommandEncoder>)e barrierAfterStages:MTLStageAll beforeQueueStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice];
[e endEncoding];
}
static inline id<MTL4RenderCommandEncoder> enc_r_begin(MTL4RenderPassDescriptor *d) { id<MTL4RenderCommandEncoder> e = [g_cb renderCommandEncoderWithDescriptor:d]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_vt atStages:MTLRenderStageVertex]; [e setArgumentTable:g_ft atStages:MTLRenderStageFragment]; return e; }
#endif
#if DM_NVN_M3
static inline RENC enc_r_begin(RPD *d) { return [g_cb renderCommandEncoderWithDescriptor:d]; }
#else
static inline RENC enc_r_begin(RPD *d) { RENC e = [g_cb renderCommandEncoderWithDescriptor:d]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_vt atStages:MTLRenderStageVertex]; [e setArgumentTable:g_ft atStages:MTLRenderStageFragment]; return e; }
#endif
static inline void enc_r_end(id e) { m4_end(e); }
static inline void enc_r_pso(id<MTL4RenderCommandEncoder> e, id<MTLRenderPipelineState> p) { [e setRenderPipelineState:p]; }
static inline void enc_r_dss(id<MTL4RenderCommandEncoder> e, id<MTLDepthStencilState> s) { [e setDepthStencilState:s]; }
static inline void enc_r_viewport(id<MTL4RenderCommandEncoder> e, MTLViewport v) { [e setViewport:v]; }
static inline void enc_r_scissor(id<MTL4RenderCommandEncoder> e, MTLScissorRect r) { [e setScissorRect:r]; }
static inline void enc_r_cull(id<MTL4RenderCommandEncoder> e, MTLCullMode m) { [e setCullMode:m]; }
static inline void enc_r_winding(id<MTL4RenderCommandEncoder> e, MTLWinding w) { [e setFrontFacingWinding:w]; }
static inline void enc_r_fill(id<MTL4RenderCommandEncoder> e, MTLTriangleFillMode m) { [e setTriangleFillMode:m]; }
static inline void enc_r_depth_bias(id<MTL4RenderCommandEncoder> e, float u, float s, float c) { [e setDepthBias:u slopeScale:s clamp:c]; }
static inline void enc_r_depth_clip(id<MTL4RenderCommandEncoder> e, BOOL v) { [e setDepthClipMode:v ? MTLDepthClipModeClip : MTLDepthClipModeClamp]; }
static inline void enc_r_stencil_ref(id<MTL4RenderCommandEncoder> e, uint32_t f, uint32_t b) { (void)b; [e setStencilReferenceValue:f]; }
static inline void enc_r_blend_color(id<MTL4RenderCommandEncoder> e, float r, float g, float b, float a) { [e setBlendColorRed:r green:g blue:b alpha:a]; }
static inline void enc_r_visibility(id<MTL4RenderCommandEncoder> e, MTLVisibilityResultMode m, NSUInteger o) { [e setVisibilityResultMode:m offset:o]; }
static inline void enc_r_vbuf(id<MTL4RenderCommandEncoder> e, NSUInteger i, uint64_t gpu) { (void)e; [g_vt setAddress:gpu atIndex:i]; }
static inline void enc_r_args(id<MTL4RenderCommandEncoder> e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { (void)e; [(s == MTLRenderStageVertex ? g_vt : g_ft) setAddress:gpu atIndex:i]; }
static inline void enc_r_draw(id<MTL4RenderCommandEncoder> e, MTLPrimitiveType p, NSUInteger v, NSUInteger n) { [e drawPrimitives:p vertexStart:v vertexCount:n]; }
static inline void enc_r_draw_instanced(id<MTL4RenderCommandEncoder> e, MTLPrimitiveType p, NSUInteger v, NSUInteger n, NSUInteger i, NSUInteger b) { [e drawPrimitives:p vertexStart:v vertexCount:n instanceCount:i baseInstance:b]; }
static inline void enc_r_draw_indexed(id<MTL4RenderCommandEncoder> e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:gpu indexBufferLength:len instanceCount:i baseVertex:bv baseInstance:bi]; }
static inline id<MTL4ComputeCommandEncoder> enc_c_begin(MTLComputePassDescriptor *d) { (void)d; id<MTL4ComputeCommandEncoder> e = [g_cb computeCommandEncoder]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_ct]; return e; }
static inline void enc_r_pso(RENC e, id<MTLRenderPipelineState> p) { [e setRenderPipelineState:p]; }
static inline void enc_r_dss(RENC e, id<MTLDepthStencilState> s) { [e setDepthStencilState:s]; }
static inline void enc_r_viewport(RENC e, MTLViewport v) { [e setViewport:v]; }
static inline void enc_r_scissor(RENC e, MTLScissorRect r) { [e setScissorRect:r]; }
static inline void enc_r_cull(RENC e, MTLCullMode m) { [e setCullMode:m]; }
static inline void enc_r_winding(RENC e, MTLWinding w) { [e setFrontFacingWinding:w]; }
static inline void enc_r_fill(RENC e, MTLTriangleFillMode m) { [e setTriangleFillMode:m]; }
static inline void enc_r_depth_bias(RENC e, float u, float s, float c) { [e setDepthBias:u slopeScale:s clamp:c]; }
static inline void enc_r_depth_clip(RENC e, BOOL v) { [e setDepthClipMode:v ? MTLDepthClipModeClip : MTLDepthClipModeClamp]; }
static inline void enc_r_stencil_ref(RENC e, uint32_t f, uint32_t b) { (void)b; [e setStencilReferenceValue:f]; }
static inline void enc_r_blend_color(RENC e, float r, float g, float b, float a) { [e setBlendColorRed:r green:g blue:b alpha:a]; }
static inline void enc_r_visibility(RENC e, MTLVisibilityResultMode m, NSUInteger o) { [e setVisibilityResultMode:m offset:o]; }
#if DM_NVN_M3
static inline void enc_r_vbuf(RENC e, NSUInteger i, uint64_t gpu) { m3_rbuf(e, 1, i, gpu); }
static inline void enc_r_args(RENC e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { m3_rbuf(e, s == MTLRenderStageVertex, i, gpu); }
#else
static inline void enc_r_vbuf(RENC e, NSUInteger i, uint64_t gpu) { (void)e; [g_vt setAddress:gpu atIndex:i]; }
static inline void enc_r_args(RENC e, MTLRenderStages s, uint64_t gpu, NSUInteger i) { (void)e; [(s == MTLRenderStageVertex ? g_vt : g_ft) setAddress:gpu atIndex:i]; }
#endif
static inline void enc_r_draw(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n) { [e drawPrimitives:p vertexStart:v vertexCount:n]; }
static inline void enc_r_draw_instanced(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n, NSUInteger i, NSUInteger b) { [e drawPrimitives:p vertexStart:v vertexCount:n instanceCount:i baseInstance:b]; }
#if DM_NVN_M3
static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { (void)len; if (!n) return; NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (!b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绘制:索引缓冲地址 %#llx 不在任何登记过的缓冲里", (unsigned long long)gpu); } return; } [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:b indexBufferOffset:off instanceCount:i baseVertex:bv baseInstance:bi]; }
#else
static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:gpu indexBufferLength:len instanceCount:i baseVertex:bv baseInstance:bi]; }
#endif
#if DM_NVN_M3
static inline CENC enc_c_begin(MTLComputePassDescriptor *d) { return d ? [g_cb computeCommandEncoderWithDescriptor:d] : [g_cb computeCommandEncoder]; }
#else
static inline CENC enc_c_begin(MTLComputePassDescriptor *d) { (void)d; CENC e = [g_cb computeCommandEncoder]; [e barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [e setArgumentTable:g_ct]; return e; }
#endif
static inline id<MTLComputeCommandEncoder> enc_c_begin_concurrent(id<MTLCommandBuffer> cb) { return [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent]; }
static inline void enc_c_end(id e) { m4_end(e); }
static inline void enc_c_pso(id e, id<MTLComputePipelineState> p) { [e setComputePipelineState:p]; }
#if DM_NVN_M3
static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口计算绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; } [(id<MTLComputeCommandEncoder>)e setBuffer:b offset:off atIndex:i]; }
#else
static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { (void)e; [g_ct setAddress:gpu atIndex:i]; }
#endif
static inline void enc_c_dispatch(id e, MTLSize n, MTLSize t) { [e dispatchThreadgroups:n threadsPerThreadgroup:t]; }
#if DM_NVN_M3
static inline id enc_b_begin(id cb) { return [cb blitCommandEncoder]; }
#else
static inline id enc_b_begin(id cb) { return [cb respondsToSelector:@selector(beginCommandBufferWithAllocator:)] ? [cb computeCommandEncoder] : [cb blitCommandEncoder]; }
#endif
static inline void enc_b_end(id e) { m4_end(e); }
static inline void enc_b_copy_buffer(id e, id<MTLBuffer> s, NSUInteger so, id<MTLBuffer> d, NSUInteger doff, NSUInteger n) { [e copyFromBuffer:s sourceOffset:so toBuffer:d destinationOffset:doff size:n]; }
static inline void enc_b_copy_buffer_texture(id e, id<MTLBuffer> s, NSUInteger so, NSUInteger row, NSUInteger img, MTLSize z, id<MTLTexture> d, NSUInteger sl, NSUInteger lv, MTLOrigin o) { [e copyFromBuffer:s sourceOffset:so sourceBytesPerRow:row sourceBytesPerImage:img sourceSize:z toTexture:d destinationSlice:sl destinationLevel:lv destinationOrigin:o]; }
static inline void enc_b_copy_texture_buffer(id e, id<MTLTexture> s, NSUInteger sl, NSUInteger lv, MTLOrigin o, MTLSize z, id<MTLBuffer> d, NSUInteger doff, NSUInteger row, NSUInteger img) { [e copyFromTexture:s sourceSlice:sl sourceLevel:lv sourceOrigin:o sourceSize:z toBuffer:d destinationOffset:doff destinationBytesPerRow:row destinationBytesPerImage:img]; }
static inline void enc_b_copy_texture(id e, id<MTLTexture> s, NSUInteger sl, NSUInteger lv, MTLOrigin so, MTLSize z, id<MTLTexture> d, NSUInteger dl, NSUInteger dv, MTLOrigin doo) { [e copyFromTexture:s sourceSlice:sl sourceLevel:lv sourceOrigin:so sourceSize:z toTexture:d destinationSlice:dl destinationLevel:dv destinationOrigin:doo]; }
static void blit_note(void); // 逐通道转储:拷贝 / 缓冲更新结束了渲染通道(定义在 PD 之后) | Per-pass dump: a copy / buffer update ended the render pass (defined after PD)
static id<MTL4ComputeCommandEncoder> blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; } return g_blit; }
#if DM_NVN_M3
static BENC blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); } return g_blit; }
#else
static BENC blit(void) { blit_note(); rp_end(); if (!g_blit) { ser_gate(); g_blit = enc_b_begin(g_cb); [g_blit barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; } return g_blit; }
#endif
void mtl_sub_copy(uint64_t src, uint64_t dst, uint64_t n) {
if (g_npend < PEND_MAX) { g_pend_lo[g_npend] = dst; g_pend_hi[g_npend++] = dst + n; } else g_pend_over = 1;
@@ -699,11 +812,13 @@ uint64_t mtl_sub_commit(void) {
int n = g_npost; post_op *ops = n ? malloc(n * sizeof *ops) : NULL;
if (n) memcpy(ops, g_post, n * sizeof *ops);
NSArray<dispatch_block_t> *commit_blocks = [g_commit_blocks copy];
#if !DM_NVN_M3
MTL4CommitOptions *o = [MTL4CommitOptions new];
[o addFeedbackHandler:^(id<MTL4CommitFeedback> f) { (void)f; for (dispatch_block_t block in commit_blocks) block(); }];
#endif
[FB_ON(o, g_cb) FB_SEL:^(FB_ARG f) { (void)f; for (dispatch_block_t block in commit_blocks) block(); }];
uint64_t gpu_f = atomic_load(&g_cur_frame); gpu_tag_begin(gpu_f);
NSString *cctx = @(cctx_snap());
[o addFeedbackHandler:^(id<MTL4CommitFeedback> cb) {
[FB_ON(o, g_cb) FB_SEL:^(FB_ARG cb) {
gpu_tag_done(gpu_f, cb.GPUStartTime, cb.GPUEndTime);
if (cb.error) { atomic_store(&g_last_commit_error, 1); static int n, nv; int victim = [cb.error.description containsString:@"InnocentVictim"]; if (victim ? nv++ < 1 : n++ < 8) MLOG("【红】命令缓冲错误详情 fence=%llu:%s | GPU %.3f→%.3f", (unsigned long long)fence, cb.error.description.UTF8String, cb.GPUStartTime, cb.GPUEndTime); if (!victim) MLOG("【红】出错那次提交的现场 fence=%llu:%s", (unsigned long long)fence, cctx.UTF8String); MLOG("【红】命令缓冲执行出错:%s", cb.error.localizedDescription.UTF8String); }
for (int i = 0; i < n; i++) {
@@ -721,10 +836,15 @@ uint64_t mtl_sub_commit(void) {
}];
void arena_commit(uint64_t fence); arena_commit(fence);
res_commit();
#if DM_NVN_M3
[g_cb encodeSignalEvent:g_ev value:fence];
[g_cb commit];
#else
[g_cb endCommandBuffer];
id<MTL4CommandBuffer> buffers[] = {g_cb};
CBUF buffers[] = {g_cb};
[g_q4 commit:buffers count:1 options:o];
[g_q4 signalEvent:g_ev value:fence];
#endif
g_alloc_fence[g_alloc_cur] = fence;
g_cb = nil;
g_commit_blocks = nil;
@@ -857,7 +977,7 @@ static id<MTLTexture> tex_upgrade_pfv(const tex_t *t, id<MTLTexture> base, MTLPi
id<MTLTexture> upgraded = [g_dev newTextureWithDescriptor:d];
if (!upgraded) { RED_ONCE(45, "贴图升级失败 ser=%llu 格式 %lu → %lu", t->serial, (unsigned long)base.pixelFormat, (unsigned long)view_pf); return base; }
res_add(upgraded);
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
NSUInteger slices = base.textureType == MTLTextureType3D ? 1 : base.arrayLength * (base.textureType == MTLTextureTypeCube || base.textureType == MTLTextureTypeCubeArray ? 6 : 1);
for (NSUInteger l = 0; l < base.mipmapLevelCount; l++) {
NSUInteger w = MAX(base.width >> l, 1u), h = MAX(base.height >> l, 1u), z = base.textureType == MTLTextureType3D ? MAX(base.depth >> l, 1u) : 1;
@@ -880,8 +1000,8 @@ static id<MTLTexture> tex_upgrade_pfv(const tex_t *t, id<MTLTexture> base, MTLPi
// the same queue executes in commit order ⇒ uploads are always finished before the first sample. Uploads outside a submission are flushed on the spot. The staging area is cut from 32 MB private blocks, held by the command buffer until completion.
static _Atomic uint64_t g_upload_ns; // 提交线程上解排布 + 上传编码的累计耗时(计时埋点) | Cumulative time of deswizzle + upload encoding on the submit thread (timing instrumentation)
static _Atomic uint64_t g_upload_gpu_ns;
static id<MTL4CommandBuffer> g_up_cb;
static id<MTL4ComputeCommandEncoder> g_up_ce;
static CBUF g_up_cb;
static CENC g_up_ce;
static _Atomic int g_up_alloc_busy[3];
static unsigned g_up_seq;
#define UP_BLOCK_SIZE (32u * 1024u * 1024u)
@@ -957,7 +1077,25 @@ static void up_flush(void) {
if (g_up_ce) {
m4_end(g_up_ce); g_up_ce = nil;
}
id<MTL4ComputeCommandEncoder> b = g_nup_blits || g_nup_decs ? g_up_ce = [g_up_cb computeCommandEncoder] : nil;
#if DM_NVN_M3
// 老接口:拷贝与计算是两种编码器——先一个拷贝编码器做「暂存块 → 贴图」,再一个计算编码器做无 BC 的 GPU 解压
// Older API: copy and compute are two kinds of encoder - first a copy encoder does "staging block -> texture", then a compute encoder does the GPU decompression for devices without BC
BENC b = g_nup_blits ? [g_up_cb blitCommandEncoder] : nil;
for (int i = 0; b && i < g_nup_blits; i++) {
up_blit *x = &g_up_blits[i];
enc_b_copy_buffer_texture(b, x->src, x->off, x->row, x->image, x->size, x->dst, x->slice, x->level, MTLOriginMake(0, 0, 0));
}
[b endEncoding];
CENC dc = g_nup_decs ? [g_up_cb computeCommandEncoder] : nil;
if (dc) {
[dc setComputePipelineState:bcd_pso()];
for (int i = 0; i < g_nup_decs; i++) { up_dec *x = &g_up_decs[i];
[dc setBuffer:x->src offset:0 atIndex:0]; [dc setBuffer:x->params offset:x->poff atIndex:1]; [dc setTexture:x->view atIndex:0];
[dc dispatchThreadgroups:MTLSizeMake((x->bw + 7) / 8, (x->bh + 7) / 8, 1) threadsPerThreadgroup:MTLSizeMake(8, 8, 1)]; }
}
[dc endEncoding]; g_up_ce = nil;
#else
CENC b = g_nup_blits || g_nup_decs ? g_up_ce = [g_up_cb computeCommandEncoder] : nil;
if (b) [b barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice];
for (int i = 0; b && i < g_nup_blits; i++) {
up_blit *x = &g_up_blits[i];
@@ -970,13 +1108,16 @@ static void up_flush(void) {
[b dispatchThreadgroups:MTLSizeMake((x->bw + 7) / 8, (x->bh + 7) / 8, 1) threadsPerThreadgroup:MTLSizeMake(8, 8, 1)]; }
}
if (b) { m4_end(b); g_up_ce = nil; }
id<MTL4CommandBuffer> cb = g_up_cb;
#endif
CBUF cb = g_up_cb;
unsigned slot = (g_up_seq - 1) % 3;
NSMutableArray *dsts = [NSMutableArray arrayWithCapacity:(NSUInteger)g_nup_blits]; for (int i = 0; i < g_nup_blits; i++) if (g_up_blits[i].dst) [dsts addObject:g_up_blits[i].dst];
static int lost_at = -2; static uint64_t batch_n; if (lost_at == -2) { const char *e = getenv("DM_TEST_UP_LOST"); lost_at = e ? atoi(e) : -1; } int fake_lost = dsts.count && lost_at > 0 && (int)++batch_n == lost_at;
#if !DM_NVN_M3
MTL4CommitOptions *o = [MTL4CommitOptions new];
#endif
atomic_fetch_add(&g_up_pending, 1);
[o addFeedbackHandler:^(id<MTL4CommitFeedback> f) {
[FB_ON(o, cb) FB_SEL:^(FB_ARG f) {
if (f.error) MLOG("【红】上传命令缓冲执行出错:%s", f.error.description.UTF8String);
if (f.error || fake_lost) {
os_unfair_lock_lock(&g_up_lost_lk); if (!g_up_lost) g_up_lost = [NSHashTable weakObjectsHashTable]; for (id d in dsts) [g_up_lost addObject:d]; int n = (int)g_up_lost.allObjects.count; atomic_store(&g_up_lost_n, n); os_unfair_lock_unlock(&g_up_lost_lk);
@@ -989,9 +1130,13 @@ static void up_flush(void) {
atomic_fetch_sub(&g_up_pending, 1);
}];
res_commit();
#if DM_NVN_M3
[cb commit];
#else
[cb endCommandBuffer];
id<MTL4CommandBuffer> buffers[] = {cb};
CBUF buffers[] = {cb};
[g_q4 commit:buffers count:1 options:o];
#endif
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];
@@ -1006,12 +1151,17 @@ static void up_begin(void) {
unsigned slot = g_up_seq++ % 3;
while (atomic_load(&g_up_alloc_busy[slot])) usleep(1000);
atomic_store(&g_up_alloc_busy[slot], 1);
#if DM_NVN_M3
g_up_cb = [g_q commandBuffer];
g_up_ce = [g_up_cb computeCommandEncoder];
#else
[g_up_alloc4[slot] reset];
g_up_cb = [g_dev newCommandBuffer];
[g_up_cb beginCommandBufferWithAllocator:g_up_alloc4[slot]];
g_up_ce = [g_up_cb computeCommandEncoder];
[g_up_ce barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice];
[g_up_ce setArgumentTable:g_up_ct];
#endif
if (!g_up_texs) g_up_texs = [NSMutableArray array];
if (!g_up_keep) g_up_keep = [NSMutableArray array];
}
@@ -1125,8 +1275,12 @@ static id<MTLTexture> pkg_upload_(const tex_t *t, uint64_t *stamp) {
uint32_t w = MAX(t->d.width >> l, 1u), h = MAX(t->d.height >> l, 1u), z = t->d.target == 2 ? MAX(t->d.depth >> l, 1u) : 1;
size_t pitch = (size_t)((w + bw - 1) / bw) * bpb, rows = (h + bh - 1) / bh;
for (unsigned y = 0; y < layers; y++) {
#if DM_NVN_M3
if (nvn_deswz_gpu_encode(g_up_ce, (__bridge id<MTLBuffer>)mb, mo, &t->d, l, y, stg, stg_off + off, pitch)) { enc_ok = 0; break; }
#else
size_t poff; id<MTLBuffer> params = up_param_alloc(&poff); // Metal 4 无 setBytes:每次解排布的参数块从共享块里切(不逐次新建 GPU 缓冲) | Metal 4 has no setBytes: the parameter block of each deswizzle is cut from a shared block (no new GPU buffer each time)
if (nvn_deswz_gpu_encode_m4(g_up_ce, g_up_ct, params, poff, (__bridge id<MTLBuffer>)mb, mo, &t->d, l, y, stg, stg_off + off, pitch)) { enc_ok = 0; break; }
#endif
if (gdec) { // 解压任务:冲刷时过了屏障再派发(见 up_flush) | Decompression job: dispatched at flush time after the barrier (see up_flush)
MTLPixelFormat vf = mt.pixelFormat == MTLPixelFormatRGBA8Unorm_sRGB ? MTLPixelFormatRGBA8Unorm : mt.pixelFormat;
id<MTLTexture> v = [mt newTextureViewWithPixelFormat:vf textureType:MTLTextureType2D levels:NSMakeRange(l, 1) slices:NSMakeRange(y, 1)];
@@ -1310,7 +1464,7 @@ static void rr_begin(void), rr_finish(int ranged);
static void rr_snap(const p_draw *, const p_draw_idx *);
static void rr_reset(void);
#endif
static id<MTL4RenderCommandEncoder> g_enc;
static RENC g_enc;
// 当前渲染通道的目标信息:rp_begin 时由附件定一次,通道内各绘制共用(管线键、深度模板、视口 / 剪裁都只依赖它)
// Target info of the current render pass: determined once from the attachments at rp_begin and shared by all draws in the pass (pipeline key, depth-stencil, viewport / scissor all depend only on it)
static struct { uint32_t cfmt[8], dfmt, sfmt, samples; int hd, hs; NSUInteger tw, th; uint64_t serial, reg_gen, ser_gen, range_dirty; int range_external, range_depth_nonro; __unsafe_unretained id<MTLTexture> range_color, range_depth; } g_pass;
@@ -1388,7 +1542,7 @@ static uint64_t att_bytes(id<MTLTexture> t, NSUInteger level) {
static NSUInteger mip_extent(NSUInteger size, NSUInteger level) {
return level < sizeof(size) * 8 ? MAX(size >> level, 1) : 1;
}
static void pass_dims(MTL4RenderPassDescriptor *pd, NSUInteger nc, NSUInteger *w, NSUInteger *h) {
static void pass_dims(RPD *pd, NSUInteger nc, NSUInteger *w, NSUInteger *h) {
*w = *h = 0;
for (NSUInteger i = 0; i < nc + 2; i++) {
MTLRenderPassAttachmentDescriptor *a = i < nc ? pd.colorAttachments[i] : i == nc ? pd.depthAttachment : pd.stencilAttachment;
@@ -1449,7 +1603,7 @@ static pg_pass *pg_new(int kind, int nslot) {
g_pg_used += nslot;
return p;
}
static void pg_render(MTL4RenderPassDescriptor *pd, NSUInteger nc) {
static void pg_render(RPD *pd, NSUInteger nc) {
(void)pd; (void)nc;
return;
#if 0
@@ -1684,9 +1838,9 @@ static void attach(MTLRenderPassAttachmentDescriptor *a, const tex_t *t, const v
// mode 1 (clear_only): a pass opened only to land pending clears, attaching only the attachments that have clears; mode 2: the lookahead proves this pass does not use depth-stencil, so depth is not attached.
// clear_only: a pass opened only to land pending clears, attaching only the attachments that have clears - the other attachments are not touched by this pass, and attaching them costs a pointless load and store on TBDR
// (Mac character select screen: the color-clear pass drags along a 400x225 depth load and store)
static id<MTL4RenderCommandEncoder> rp_begin_ex(int clear_only);
static id<MTL4RenderCommandEncoder> rp_begin(void) { return rp_begin_ex(0); }
static id<MTL4RenderCommandEncoder> rp_begin_ex(int clear_only) {
static RENC rp_begin_ex(int clear_only);
static RENC rp_begin(void) { return rp_begin_ex(0); }
static RENC rp_begin_ex(int clear_only) {
if (g_enc) return g_enc;
memset(g_zskip_cand_ok, 0, sizeof g_zskip_cand_ok);
g_enc_mode = clear_only;
@@ -1697,7 +1851,7 @@ static id<MTL4RenderCommandEncoder> rp_begin_ex(int clear_only) {
if (rt_range_on()) { reg0 = g_reg_gen; ser0 = g_ser_gen; }
if (rt_range_on()) dirty0=nvn_dirty_now();
if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
MTL4RenderPassDescriptor *pd = [MTL4RenderPassDescriptor new];
RPD *pd = [RPD new];
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;
@@ -2711,7 +2865,18 @@ static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, in
g_stat_args_reuse++;
return 1;
}
#if DM_NVN_M3
// 老接口:着色器经参数块间接访问的每个资源都要在本编码器上声明用途,系统才知道它和别的编码器(上传拷贝、别的通道)之间的先后依赖;
// 不声明的话只读贴图会和写它的拷贝乱序(迁 Metal 4 前实测过)。同一编码器内重复声明是幂等的
// Older API: every resource a shader accesses indirectly through an argument block must have its usage declared on this encoder, so that the system knows its ordering dependency against other encoders (upload copies, other passes);
// without the declaration a read-only texture gets out of order with the copy that writes it (measured before the move to Metal 4). Repeated declarations within one encoder are idempotent
#define USE(r, u) do { id<MTLResource> r_ = (id<MTLResource>)(r); if (r_) { if (nvn_stage == 5) [(id<MTLComputeCommandEncoder>)en useResource:r_ usage:(u)]; else [(id<MTLRenderCommandEncoder>)en useResource:r_ usage:(u) stages:MTLRenderStageVertex | MTLRenderStageFragment]; } \
if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0)
#define USE_SAMP(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) // 采样器不是资源,不用声明 | samplers are not resources and need no declaration
#else
#define USE(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0)
#define USE_SAMP(r, u) USE(r, u)
#endif
// DM_NVN_PASSDUMP:每通道每阶段第一次新编时记着色器键(K)与各绑定的实际来源(B:UBO 地址 / 长度 / 前 4 个浮点,贴图号与序号或「哑」)
// DM_NVN_PASSDUMP: on the first new encode per pass per stage, records the shader key (K) and the actual source of each binding (B: UBO address / length / first 4 floats, texture ID and serial, or 「哑」(dummy))
static uint64_t bl_pass[6]; static int bl_all = -1; if (bl_all < 0) bl_all = getenv("DM_NVN_PASSDUMP_ALL") != NULL; // 每次新编都记(否则只记每通道每阶段第一次) | Record on every new encode (otherwise only the first time per pass per stage)
@@ -2744,7 +2909,7 @@ static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, in
int sid = reg < 128 ? (int)((b->kind == NVN_RB_SAMPT ? S.tex[nvn_stage][reg] : S.samp[nvn_stage][reg]) >> 20) : 0;
__unsafe_unretained id<MTLSamplerState> ss = sid ? (__bridge id<MTLSamplerState>)samp_fast(sid) : nil;
slots[aid] = sid && sid < g_nsreg && g_srid[sid] ? g_srid[sid] : dummy_samp_rid();
USE(ss ? ss : dummy_samp(), MTLResourceUsageRead);
USE_SAMP(ss ? ss : dummy_samp(), MTLResourceUsageRead);
if (bl && sid > 0) { int ok = sid < g_nsreg && g_sreg_ok[sid]; samp_par sp = ok ? g_sreg[sid] : (samp_par){0}; // 本段已持 g_rmu | g_rmu is already held in this section
if (ok) PD("B %llu st%d samp reg%d sid=%d mag=%d min=%d(0 最近点 / 1 双线性;2–5 带 mip)", g_stat_pass, nvn_stage, reg, sid, (int)sp.magf, (int)sp.minf); }
} else if (b->kind == NVN_RB_TEX) {
@@ -2810,6 +2975,7 @@ static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, in
} else RED_ONCE(46, "绑定种类 %d 未实现", b->kind);
}
#undef USE
#undef USE_SAMP
pthread_mutex_unlock(&g_rmu);
NSUInteger arg_len = sh->arg_len ? sh->arg_len : sh->ae.encodedLength;
id<MTLBuffer> ab; size_t off = arena_alloc(arg_len, &ab);
@@ -2820,7 +2986,7 @@ static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, in
return 1;
}
static id<MTLBuffer> g_quad_ib; static uint64_t g_quad_gpu;
static id<MTL4RenderCommandEncoder> rp_begin(void);
static RENC rp_begin(void);
// ---------- 通道前瞻:本通道是否用到深度 / 模板 ----------
// 开通道时从当前绘制的下一条起往后扫,模拟深度模板状态的变化,直到本通道必然结束处(重设目标、拷贝、计算派发——
// 与回放里结束通道的操作一一对应)。期间没有任何绘制开深度测试 / 深度写 / 模板测试,则本通道可不挂深度附件:
@@ -3553,7 +3719,7 @@ static void fz_check_run(const fuse_t *fz) {
for (int a = 0; a < na; a++) {
id<MTLTexture> t = att[a], c = scr[a]; NSUInteger W = t.width, H = t.height, bpp = (NSUInteger)(att_bytes(t, 0) / (W * H));
id<MTLBuffer> b1 = [g_dev newBufferWithLength:W * H * bpp options:MTLResourceStorageModeShared], b2 = [g_dev newBufferWithLength:W * H * bpp options:MTLResourceStorageModeShared];
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
enc_b_copy_texture_buffer(b, c, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(W, H, 1), b1, 0, W * bpp, W * H * bpp);
enc_b_copy_texture_buffer(b, t, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(W, H, 1), b2, 0, W * bpp, W * H * bpp);
unsigned long long ser = sers[a], pass = g_stat_pass, frame = atomic_load(&g_cur_frame); NSUInteger nb = W * H * bpp;
@@ -4154,11 +4320,16 @@ static int bloomq_capture(void) {
id<MTLTexture> dst = base; if (lv || sl) { static id<MTLTexture> vb; static int vl, vs; if (vb != base || vl != lv || vs != sl) { defer_obj_release(g_bloomq_view); /* 旧视图退役(原先直接被覆盖:留在驻留集里,连带钉住旧底图) | retire the old view (it used to be overwritten directly: it stayed in the residency set and pinned the old base texture with it) */ g_bloomq_view = [base newTextureViewWithPixelFormat:base.pixelFormat textureType:base.textureType levels:NSMakeRange(lv, 1) slices:NSMakeRange(sl, 1)]; if (g_bloomq_view) res_add(g_bloomq_view); vb = base; vl = lv; vs = sl; } dst = g_bloomq_view; }
if (!dst || !bloomq_make_pipeline(dst.pixelFormat)) return 0;
rp_end();
MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new]; rp.colorAttachments[0].texture = dst; rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
id<MTL4RenderCommandEncoder> en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0;
RPD *rp = [RPD new]; rp.colorAttachments[0].texture = dst; rp.colorAttachments[0].loadAction = MTLLoadActionDontCare; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
RENC en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0;
#if DM_NVN_M3
[en setFragmentTexture:src atIndex:0]; [en setFragmentSamplerState:g_bloomq_samp atIndex:0];
float *p = g_bloomq_const[g_bloomq_i].contents; p[0] = g_bloomq.threshold; p[1] = g_bloomq.coeff_g; p[2] = g_bloomq.coeff_b; p[3] = src.width; p[4] = src.height; [en setFragmentBuffer:g_bloomq_const[g_bloomq_i] offset:0 atIndex:0];
#else
[en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice]; [en setArgumentTable:g_bloomq_args atStages:MTLRenderStageFragment];
[g_bloomq_args setTexture:src.gpuResourceID atIndex:0]; [g_bloomq_args setSamplerState:g_bloomq_samp.gpuResourceID atIndex:0];
float *p = g_bloomq_const[g_bloomq_i].contents; p[0] = g_bloomq.threshold; p[1] = g_bloomq.coeff_g; p[2] = g_bloomq.coeff_b; p[3] = src.width; p[4] = src.height; [g_bloomq_args setAddress:g_bloomq_const[g_bloomq_i].gpuAddress atIndex:0];
#endif
[en setViewport:(MTLViewport){0,0,dst.width,dst.height,0,1}]; [en setRenderPipelineState:g_bloomq_pso]; [en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; m4_end(en);
g_bloomq_i = (g_bloomq_i + 1) % 3; args_dirty_all(); g_pso_dirty = g_dss_dirty = 1; return 1;
}
@@ -4557,7 +4728,10 @@ static const char k_lut_msl[] =
" float s = smoothstep(0.65, 1.0, dot(b.rgb, float3(0.2126, 0.7152, 0.0722)));\n" // 高光保护:提亮后越接近白,越收回原值(雪、天光不糊成一片白);暗处 s = 0 照常提亮 | Highlight protection: after brightening, the closer to white, the more it is pulled back to the original value (snow and skylight do not blur into a sheet of white); in dark areas s = 0 and brightening proceeds as usual
" dst.write(float4(max(mix(b.rgb, o.rgb, s), o.rgb), b.a), g); }\n";
static void bright_lut(NvShader *cs) {
static int failed; static id<MTLComputePipelineState> ps; static id<MTL4ArgumentTable> at; static id<MTLTexture> tmp; static id<MTLBuffer> kb[3]; static int ki;
static int failed; static id<MTLComputePipelineState> ps; static id<MTLTexture> tmp; static id<MTLBuffer> kb[3]; static int ki;
#if !DM_NVN_M3
static id<MTL4ArgumentTable> at;
#endif
if (failed || strncmp(cs->key, "552f45c348a61b86", 16)) return;
float k = dm_bright_k(); if (!(k > 1.005f)) return; // k ≈ 1(局外 / 正午):表保持原版 | k ~= 1 (out of game / noon): the table stays as in the original game
if (k > 4.0f) k = 4.0f;
@@ -4566,16 +4740,23 @@ static void bright_lut(NvShader *cs) {
if (!lut || lut.textureType != MTLTextureType3D || !(lut.usage & MTLTextureUsageShaderWrite)) { static int n; if (!n++) MLOG("【红】3D 画面加亮:调色表认不出(贴图号 %d),不加亮", tid); return; }
if (!ps) { NSError *e = nil; id<MTLLibrary> lib = [g_dev newLibraryWithSource:@(k_lut_msl) options:nil error:&e]; id<MTLFunction> f = lib ? [lib newFunctionWithName:@"lutk"] : nil;
ps = f ? [g_dev newComputePipelineStateWithFunction:f error:&e] : nil;
#if !DM_NVN_M3
MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 2; ad.maxBufferBindCount = 1; at = [g_dev newArgumentTableWithDescriptor:ad error:&e];
#endif
for (int i = 0; i < 3; i++) { kb[i] = [g_dev newBufferWithLength:16 options:MTLResourceStorageModeShared]; if (kb[i]) res_add(kb[i]); }
if (!ps || !at || !kb[0] || !kb[1] || !kb[2]) { failed = 1; MLOG("【红】3D 画面加亮:计算管线建不出 %s(退回原版亮度)", e.localizedDescription.UTF8String); return; }
if (!ps || M4_ONLY(!at ||) !kb[0] || !kb[1] || !kb[2]) { failed = 1; MLOG("【红】3D 画面加亮:计算管线建不出 %s(退回原版亮度)", e.localizedDescription.UTF8String); return; }
MLOG("3D 画面加亮:建好(调色表 %lux%lux%lu,曝光每帧由 dm_bright_k 给)", (unsigned long)lut.width, (unsigned long)lut.height, (unsigned long)lut.depth); }
if (!tmp || tmp.width != lut.width || tmp.height != lut.height || tmp.depth != lut.depth || tmp.pixelFormat != lut.pixelFormat) {
MTLTextureDescriptor *d = [MTLTextureDescriptor new]; d.textureType = MTLTextureType3D; d.pixelFormat = lut.pixelFormat; d.width = lut.width; d.height = lut.height; d.depth = lut.depth;
d.usage = MTLTextureUsageShaderRead; d.storageMode = MTLStorageModePrivate; if (tmp) defer_obj_release(tmp); tmp = [g_dev newTextureWithDescriptor:d]; if (!tmp) { failed = 1; return; } res_add(tmp); }
id<MTLBuffer> b0 = kb[ki]; ki = (ki + 1) % 3; *(float *)b0.contents = k; // 三份轮换:在途的帧还在读上一份 | Three copies in rotation: in-flight frames are still reading the previous copy
id<MTL4ComputeCommandEncoder> b = blit(); enc_b_copy_texture(b, lut, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(lut.width, lut.height, lut.depth), tmp, 0, 0, MTLOriginMake(0, 0, 0)); enc_b_end(g_blit); g_blit = nil;
id<MTL4ComputeCommandEncoder> ce = (id<MTL4ComputeCommandEncoder>)enc_c_begin(NULL); [ce setArgumentTable:at]; [at setTexture:tmp.gpuResourceID atIndex:0]; [at setTexture:lut.gpuResourceID atIndex:1]; [at setAddress:b0.gpuAddress atIndex:0];
BENC b = blit(); enc_b_copy_texture(b, lut, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(lut.width, lut.height, lut.depth), tmp, 0, 0, MTLOriginMake(0, 0, 0)); enc_b_end(g_blit); g_blit = nil;
CENC ce = (CENC)enc_c_begin(NULL);
#if DM_NVN_M3
[ce setTexture:tmp atIndex:0]; [ce setTexture:lut atIndex:1]; [ce setBuffer:b0 offset:0 atIndex:0];
#else
[ce setArgumentTable:at]; [at setTexture:tmp.gpuResourceID atIndex:0]; [at setTexture:lut.gpuResourceID atIndex:1]; [at setAddress:b0.gpuAddress atIndex:0];
#endif
enc_c_pso(ce, ps); enc_c_dispatch(ce, MTLSizeMake((lut.width + 3) / 4, (lut.height + 3) / 4, (lut.depth + 3) / 4), MTLSizeMake(4, 4, 4)); enc_c_end(ce);
args_dirty_all();
}
@@ -4634,7 +4815,7 @@ static void copy_t2b(const p_copy_b2t *c) {
int is3d = c->tex->d.target == 2, nz = c->r.depth ? c->r.depth : 1;
void *mb; uint64_t mo;
if (!mtl_addr(c->src, img * nz, &mb, &mo)) { RED_ONCE(31, "贴图→缓冲拷贝的目标不在内存池里"); return; }
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
if (is3d)
enc_b_copy_texture_buffer(b, t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset), MTLSizeMake(c->r.width, c->r.height, nz), (__bridge id<MTLBuffer>)mb, mo, row, img);
else
@@ -4693,13 +4874,13 @@ static void copy_b2t(const p_copy_b2t *c) {
id<MTLBuffer> tb = [g_dev newBufferWithLength:uimg * nz ?: 16 options:MTLResourceStorageModeShared];
for (int z = 0; z < nz; z++) nvn_bc_decode(c->tex->d.format, src + mo + z * img, row, c->r.width, c->r.height, (uint8_t *)tb.contents + z * uimg, up);
res_add(tb);
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
if (is3d) enc_b_copy_buffer_texture(b, tb, 0, up, uimg, MTLSizeMake(c->r.width, c->r.height, nz), t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset));
else for (int z = 0; z < nz; z++) enc_b_copy_buffer_texture(b, tb, z * uimg, up, uimg, MTLSizeMake(c->r.width, c->r.height, 1), t, layer0 + c->r.zoffset + z, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, 0));
defer_obj_release(tb); // 本次提交跑完再放(并撤驻留) | Release after this submit has finished running (and remove from residency)
return;
}
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
if (is3d)
enc_b_copy_buffer_texture(b, (__bridge id<MTLBuffer>)mb, mo, row, img, MTLSizeMake(c->r.width, c->r.height, nz), t, 0, level, MTLOriginMake(c->r.xoffset, c->r.yoffset, c->r.zoffset));
else
@@ -4717,12 +4898,17 @@ static const char k_a2u_msl[] =
"kernel void a2u(texture2d<float> src [[texture(0)]], texture2d<float, access::write> dst [[texture(1)]], constant uint4 *p [[buffer(0)]], uint2 g [[thread_position_in_grid]]) {\n"
" if (g.x >= p[1].x || g.y >= p[1].y) return; float4 v = src.read(g + p[0].xy); if (p[1].z) v.rgb = enc(v.rgb); dst.write(v, g + p[0].zw); }\n";
static int copy_t2t_astc(id<MTLTexture> s, id<MTLTexture> d, unsigned sl, unsigned ss, unsigned dl, unsigned ds, int sx, int sy, int dx, int dy, int w, int h) {
static int failed; static id<MTLComputePipelineState> ps; static id<MTL4ArgumentTable> at;
static int failed; static id<MTLComputePipelineState> ps;
#if !DM_NVN_M3
static id<MTL4ArgumentTable> at;
#endif
if (failed) return 0;
if (!ps) { NSError *e = nil; id<MTLLibrary> lib = [g_dev newLibraryWithSource:@(k_a2u_msl) options:nil error:&e]; id<MTLFunction> f = lib ? [lib newFunctionWithName:@"a2u"] : nil;
ps = f ? [g_dev newComputePipelineStateWithFunction:f error:&e] : nil;
#if !DM_NVN_M3
MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 2; ad.maxBufferBindCount = 1; at = [g_dev newArgumentTableWithDescriptor:ad error:&e];
if (!ps || !at) { failed = 1; MLOG("【红】无 BC:ASTC → 解压格式拷贝的计算管线建不出 %s", e.localizedDescription.UTF8String); return 0; } }
#endif
if (!ps M4_ONLY(|| !at)) { failed = 1; MLOG("【红】无 BC:ASTC → 解压格式拷贝的计算管线建不出 %s", e.localizedDescription.UTF8String); return 0; } }
MTLTextureType tt = MTLTextureType2D;
id<MTLTexture> sv = [s newTextureViewWithPixelFormat:s.pixelFormat textureType:tt levels:NSMakeRange(sl, 1) slices:NSMakeRange(ss, 1)];
id<MTLTexture> dv = [d newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm textureType:tt levels:NSMakeRange(dl, 1) slices:NSMakeRange(ds, 1)];
@@ -4731,8 +4917,13 @@ static int copy_t2t_astc(id<MTLTexture> s, id<MTLTexture> d, unsigned sl, unsign
uint32_t *p = pb.contents; p[0] = sx; p[1] = sy; p[2] = dx; p[3] = dy; p[4] = w; p[5] = h; p[6] = s.pixelFormat == MTLPixelFormatASTC_4x4_sRGB; p[7] = 0;
res_add(pb);
rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
id<MTL4ComputeCommandEncoder> ce = (id<MTL4ComputeCommandEncoder>)enc_c_begin(NULL); [ce setArgumentTable:at];
CENC ce = (CENC)enc_c_begin(NULL);
#if DM_NVN_M3
[ce setTexture:sv atIndex:0]; [ce setTexture:dv atIndex:1]; [ce setBuffer:pb offset:0 atIndex:0];
#else
[ce setArgumentTable:at];
[at setTexture:sv.gpuResourceID atIndex:0]; [at setTexture:dv.gpuResourceID atIndex:1]; [at setAddress:pb.gpuAddress atIndex:0];
#endif
enc_c_pso(ce, ps); enc_c_dispatch(ce, MTLSizeMake((w + 7) / 8, (h + 7) / 8, 1), MTLSizeMake(8, 8, 1)); enc_c_end(ce);
args_dirty_all();
defer_obj_unref(sv); defer_obj_unref(dv); defer_obj_release(pb); // 本次提交跑完再放(视图不单独驻留,参数块撤驻留) | Release after this submit has finished running (views are not made resident separately; the parameter block is removed from residency)
@@ -4770,7 +4961,7 @@ static void copy_t2t(const p_copy_t2t *c) {
c->flags, (unsigned long)s.pixelFormat, (unsigned long)d.pixelFormat, s3, d3);
return;
}
id<MTL4ComputeCommandEncoder> b = blit();
BENC b = blit();
if (s3)
enc_b_copy_texture(b, s, 0, sl, MTLOriginMake(c->sr.xoffset, c->sr.yoffset, c->sr.zoffset), MTLSizeMake(c->sr.width, c->sr.height, nz), d, 0, dl, MTLOriginMake(c->dr.xoffset, c->dr.yoffset, c->dr.zoffset));
else
@@ -4813,7 +5004,7 @@ static void clear_tex(const p_clear_tex *c) {
}
rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
for (int z = 0; z < nz; z++) {
MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new];
RPD *rp = [RPD new];
MTLRenderPassAttachmentDescriptor *a = depth ? rp.depthAttachment : stencil ? rp.stencilAttachment : rp.colorAttachments[0];
a.texture = t; a.level = lv; a.loadAction = MTLLoadActionClear; a.storeAction = MTLStoreActionStore;
if (is3d) a.depthPlane = c->r.zoffset + z; else a.slice = l0 + c->r.zoffset + z;
@@ -4920,11 +5111,11 @@ static id<MTLTexture> rt_cp(id<MTLTexture> src, id<MTLTexture> dst0) {
d.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget | MTLTextureUsagePixelFormatView; d.storageMode = MTLStorageModePrivate;
if (dst0) defer_obj_release(dst0); // 换尺寸:旧副本可能还被在途的命令缓冲读着(MTL4 命令缓冲不保留资源),延迟放 | Size change: the old copy may still be read by an in-flight command buffer (MTL4 command buffers do not retain resources), so release it deferred
dst = [g_dev newTextureWithDescriptor:d]; if (!dst) return nil; res_add(dst); }
id<MTL4ComputeCommandEncoder> b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(src.width, src.height, 1), dst, 0, 0, MTLOriginMake(0, 0, 0)); return dst; }
BENC b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(0, 0, 0), MTLSizeMake(src.width, src.height, 1), dst, 0, 0, MTLOriginMake(0, 0, 0)); return dst; }
static void rt_blit_shift(id<MTLTexture> src, id<MTLTexture> dst, int dx, int dy) { // 整数偏移拷贝:dst(x + dx, y + dy) = src(x, y);搬不到的屏边一条留给区域重算(外推趟已标 0x80) | Integer-offset copy: dst(x + dx, y + dy) = src(x, y); the strip at the screen edge that cannot be moved is left for the region recompute (the extrapolation pass has already marked it 0x80)
if (!src || !dst || src.width != dst.width || src.height != dst.height) return;
int W = (int)src.width, H = (int)src.height, w = W - abs(dx), h = H - abs(dy); if (w <= 0 || h <= 0) return;
id<MTL4ComputeCommandEncoder> b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(MAX(0, -dx), MAX(0, -dy), 0), MTLSizeMake(w, h, 1), dst, 0, 0, MTLOriginMake(MAX(0, dx), MAX(0, dy), 0)); }
BENC b = blit(); enc_b_copy_texture(b, src, 0, 0, MTLOriginMake(MAX(0, -dx), MAX(0, -dy), 0), MTLSizeMake(w, h, 1), dst, 0, 0, MTLOriginMake(MAX(0, dx), MAX(0, dy), 0)); }
static void rt_copy_prev(void) { // 全画帧:不透明 HDR 与主深度模板各拷一份(GPU 内按序,在本命令缓冲里) | Fully drawn frame: copy the opaque HDR and the main depth-stencil once each (in order within the GPU, in this command buffer)
if (g_rt.copied || !g_rt.main_seen || !g_rt.hdr || !g_rt.ds) return; g_rt.copied = 1; // 本帧没认出主通道(前台 / 读取画面)不拷:上次认的贴图可能已被游戏放掉、不在驻留集里 | Do not copy when the main pass was not recognized this frame (foreground / loading screen): the textures recognized last time may already have been released by the game and not be in the residency set
if (!rx_setup(g_rt.hdr.pixelFormat, g_rt.ds.pixelFormat)) { if (!g_rt.disabled) { g_rt.disabled = 1; MLOG("【红】运行时外推:外推管线在这台设备上建不出,整局退回原画法"); } return; } // 建不出(老 GPU 不支持模板导出等):整局退回 | Cannot be built (old GPU does not support stencil export etc.): fall back for the whole run
@@ -5183,7 +5374,7 @@ void mtl_res_counts(uint32_t tick, const char *why) {
static struct { uint64_t frame; char path[1024]; } g_shotq[SHOTQ_MAX]; static int g_nshotq;
static pthread_mutex_t g_shotq_mu = PTHREAD_MUTEX_INITIALIZER;
static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4]);
static int present_encode_m4(id<MTL4CommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i);
static int present_encode_m4(CBUF cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i);
// 整窗截图要的游戏画面(前端 window_shot,不再对挂着显示节拍的 Metal 图层做 drawViewHierarchy):下一次上屏时,出图线程把同一帧
// 按上屏同一套编码(present_encode)画进一张与交换链同尺寸的离屏贴图,GPU 做完后在完成回调里交出 CGImage(回调不阻塞上屏)。g_shotq_mu 护
// Game picture needed by the whole-window screenshot (front end window_shot; no longer does drawViewHierarchy on a Metal layer with the display link attached): at the next present, the present thread draws the same frame
@@ -5306,7 +5497,7 @@ static void shot(id<MTLTexture> src, const char *path, int screen, const int cro
// Diagnostic: before the first render pass of the next frame is opened, wait for the GPU to finish, then draw each one (the mip level used by that frame) by full-screen sampling into RGBA8 and save as PNG (float formats are clamped to [0,1])
static long g_td_frame = -2; static const char *g_td_path; static NSMutableArray *g_td_list; static int g_td_done;
static void td_dump(void);
void td_note(MTL4RenderPassDescriptor *pd, NSUInteger nc) {
void td_note(RPD *pd, NSUInteger nc) {
if (g_td_frame == -2) { const char *e = getenv("DM_NVN_TEXDUMP"), *c = e ? strchr(e, ':') : NULL; g_td_frame = c ? atol(e) : -1; g_td_path = c ? c + 1 : NULL; g_td_list = [NSMutableArray array]; }
if (g_td_frame < 0 || g_td_done) return;
long f = (long)atomic_load(&g_cur_frame);
@@ -5393,7 +5584,7 @@ static void td_dump(void) {
// (the same target is often cleared and reused within a frame, so the end-of-frame state cannot reflect the output of intermediate passes); file name index = in-frame index*100000 + texture index*100 + mip level
static int g_ts_idx[64], g_ts_n = -1, g_ts_on; static uint64_t g_ts_first, g_ts_curf = ~0ull;
static __strong id<MTLTexture> g_ts_att[8]; static uint64_t g_ts_ser[8]; static NSUInteger g_ts_lv[8]; static int g_ts_na;
void ts_note(MTL4RenderPassDescriptor *pd, NSUInteger nc) {
void ts_note(RPD *pd, NSUInteger nc) {
if (g_ts_n < 0) { g_ts_n = 0; const char *e = getenv("DM_NVN_TEXSNAP");
for (const char *q = e; q && *q && g_ts_n < 64; q = strchr(q, ',') ? strchr(q, ',') + 1 : q + strlen(q)) g_ts_idx[g_ts_n++] = atoi(q); }
g_ts_on = 0; if (!g_ts_n || g_td_frame < 0 || g_td_done) return;
@@ -5443,7 +5634,9 @@ int mtl_display_hz(void) {
#endif
}
static _Atomic uint64_t g_present_stall_ns; // 单测用:出图线程每次出图前额外停顿(模拟 drawable 迟迟不可用) | For unit tests: an extra pause before each present on the present thread (simulating a drawable that stays unavailable)
#if !DM_NVN_M3
static CAMetalLayer *g_present_layer_resident;
#endif
void mtl_present_test_stall(uint64_t ns) { g_present_stall_ns = ns; }
static void present_pipeline(MTLPixelFormat format) {
if (!g_blit_pso || g_blit_fmt != format) {
@@ -5507,7 +5700,7 @@ static int present_encode(id<MTLCommandBuffer> cb, id<MTLTexture> src, id<MTLTex
[en endEncoding];
return 1;
}
static int present_encode_m4(id<MTL4CommandBuffer> cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i) {
static int present_encode_m4(CBUF cb, id<MTLTexture> src, id<MTLTexture> dst, const int crop[4], int uv_i) {
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 ||
@@ -5521,21 +5714,30 @@ static int present_encode_m4(id<MTL4CommandBuffer> cb, id<MTLTexture> src, id<MT
MTLViewport vp = {floor((dw - cw * s) / 2), floor((dh - ch * s) / 2), round(cw * s), round(ch * s), 0, 1};
if (fabs((dw / dh) / ((double)cw / ch) - 1) < 0.01) vp = (MTLViewport){0, 0, dw, dh, 0, 1};
int full = vp.originX == 0 && vp.originY == 0 && vp.width == dw && vp.height == dh;
MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new];
RPD *rp = [RPD new];
rp.colorAttachments[0].texture = dst;
rp.colorAttachments[0].loadAction = full ? MTLLoadActionDontCare : MTLLoadActionClear;
rp.colorAttachments[0].storeAction = MTLStoreActionStore;
rp.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1);
id<MTL4RenderCommandEncoder> en = [cb renderCommandEncoderWithDescriptor:rp];
RENC en = [cb renderCommandEncoderWithDescriptor:rp];
if (!en) { MLOG("【红】M4 出图渲染编码器创建失败"); return 0; }
#if DM_NVN_M3
[en setFragmentTexture:src atIndex:0];
[en setFragmentSamplerState:g_blit_samp atIndex:0];
#else
[en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice];
[en setArgumentTable:g_present_args atStages:MTLRenderStageFragment];
[g_present_args setTexture:src.gpuResourceID atIndex:0];
[g_present_args setSamplerState:g_blit_samp.gpuResourceID atIndex:0];
#endif
float *uv = g_present_uv[uv_i].contents;
uv[0] = (float)cx / src.width; uv[1] = (float)cy / src.height; uv[2] = (float)cw / src.width; uv[3] = (float)ch / src.height;
uv[4] = (cx + 0.5f) / src.width; uv[5] = (cy + 0.5f) / src.height; uv[6] = (cx + cw - 0.5f) / src.width; uv[7] = (cy + ch - 0.5f) / src.height;
#if DM_NVN_M3
[en setFragmentBuffer:g_present_uv[uv_i] offset:0 atIndex:0];
#else
[g_present_args setAddress:g_present_uv[uv_i].gpuAddress atIndex:0];
#endif
[en setViewport:vp]; [en setRenderPipelineState:g_blit_pso];
[en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
m4_end(en);
@@ -5596,7 +5798,9 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
if (g_burst_left > 0) burst_grab(src); // 测试:连拍 | test: burst capture
CAMetalLayer *layer = (__bridge CAMetalLayer *)front_metal_layer();
if (!layer) return 0;
#if !DM_NVN_M3
if (g_present_layer_resident != layer) { [g_q4 addResidencySet:layer.residencySet]; g_present_layer_resident = layer; }
#endif
#if TARGET_OS_OSX
if (!layer.displaySyncEnabled) layer.displaySyncEnabled = YES; // 窗口模式按显示器垂直同步,防撕裂 | Windowed mode follows the display's vsync to prevent tearing
#endif
@@ -5612,20 +5816,31 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
while (g_pq_done < g_present_alloc_fence[alloc_i]) pthread_cond_wait(&g_pq_cv, &g_pq_mu);
pthread_mutex_unlock(&g_pq_mu);
}
#if DM_NVN_M3
CBUF cb = [g_q commandBuffer]; // 老接口:交画面记在命令缓冲上(presentDrawable),这一帧的绘制做完才上屏 | older API: presentation is recorded on the command buffer (presentDrawable), so the frame reaches the screen only after its drawing is done
if (!present_encode_m4(cb, src, dr.texture, crop, alloc_i)) return 0;
#else
[g_present_alloc4[alloc_i] reset];
[g_q4 waitForDrawable:dr];
id<MTL4CommandBuffer> cb = g_present_cb[alloc_i];
CBUF cb = g_present_cb[alloc_i];
[cb beginCommandBufferWithAllocator:g_present_alloc4[alloc_i]];
if (!present_encode_m4(cb, src, dr.texture, crop, alloc_i)) { [cb endCommandBuffer]; [g_q4 signalDrawable:dr]; return 0; }
[cb endCommandBuffer];
#endif
#if !DM_NVN_M3
MTL4CommitOptions *o = [MTL4CommitOptions new];
[o addFeedbackHandler:^(id<MTL4CommitFeedback> f) {
#endif
[FB_ON(o, cb) FB_SEL:^(FB_ARG f) {
if (f.error) MLOG("【红】上屏命令缓冲错误:%s", f.error.description.UTF8String);
pthread_mutex_lock(&g_pq_mu); if (ticket > g_pq_done) g_pq_done = ticket; g_pq_inflight--; pthread_cond_broadcast(&g_pq_cv); pthread_mutex_unlock(&g_pq_mu);
}];
id<MTL4CommandBuffer> buffers[] = {cb};
#if !DM_NVN_M3
CBUF buffers[] = {cb};
#endif
pthread_mutex_lock(&g_pq_mu); g_pq_inflight++; pthread_mutex_unlock(&g_pq_mu);
#if !DM_NVN_M3
[g_q4 commit:buffers count:1 options:o];
#endif
if (target_ts > 0) {
static double leads[300], e2e[300]; // e2e:游戏入队 → 系统预定上屏(含在队列里等节拍回调的时间),输入延迟里我们这一侧能读到的全程 | e2e: game enqueue -> system-scheduled present (including the time waiting in the queue for the display-link callback), the full span of input latency that our side can read
static uint64_t lead_n;
@@ -5641,10 +5856,12 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
(unsigned long long)g_link_dropped, a[149], a[0], b[149], b[0], b[299]);
}
}
#if !DM_NVN_M3
[g_q4 signalDrawable:dr];
#endif
g_present_alloc_fence[alloc_i] = ticket;
#if TARGET_OS_SIMULATOR // iOS 模拟器 SDK 没有呈现时刻回调与最短显示时长(只作画面验收用,不计节拍) | The iOS simulator SDK has no presentation-time callback and no minimum display duration (used only for picture acceptance, display-link ticks are not counted)
(void)period; [dr present];
(void)period; M3_PRESENT(cb, dr);
#else
uint64_t pn = ticket; // 按游戏出图序号(票号)记上屏时刻:hle 的上屏统计按「游戏第 n 次出图」取;显示节拍路径里实际出图次数 ≠ 游戏出图次数(旧帧会被合并丢弃) | Record the present time by the game's present sequence number (ticket number): hle's present statistics are taken by "the game's nth present"; in the display link path the actual present count != the game's present count (old frames get merged and dropped)
[dr addPresentedHandler:^(id<MTLDrawable> d) { // 真实呈现时刻(屏幕上真正换上这一帧的时间,CACurrentMediaTime 基准) | Actual presentation time (the time this frame is really put on screen, CACurrentMediaTime base)
@@ -5653,8 +5870,15 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
}];
// 每张至少显示一个出图周期:GPU 完成时刻在 120 Hz 刷新边界附近抖动时,不再出现「25 ms + 8.33 ms」成对的顿挫
// Each frame is displayed for at least one present period: when the GPU completion time jitters around a 120 Hz refresh boundary, the paired "25 ms + 8.33 ms" stutter no longer appears
#if DM_NVN_M3
if (target_ts <= 0 && period > 0) [cb presentDrawable:dr afterMinimumDuration:period]; else [cb presentDrawable:dr];
#else
if (target_ts > 0) [dr present];
else if (period > 0) [dr presentAfterMinimumDuration:period]; else [dr present];
#endif
#endif
#if DM_NVN_M3
[cb commit];
#endif
(void)frame;
return 1;
+17 -3
View File
@@ -22,7 +22,12 @@
// Before and after the call: this function first calls rp_end() to close the current render pass and copy encoder; after encoding it sets args_dirty_all() / g_pso_dirty / g_dss_dirty, and the game's next draw reopens its pass with 'load'.
// Resources: src_hdr / src_ds are created and res_add'ed by the caller; src_ds must be able to open an X32_Stencil8 view (created with MTLTextureUsagePixelFormatView).
static id<MTLRenderPipelineState> g_rx_pso1; static MTLPixelFormat g_rx_fmt_c, g_rx_fmt_ds;
static id<MTLDepthStencilState> g_rx_dss; static id<MTL4ArgumentTable> g_rx_args;
static id<MTLDepthStencilState> g_rx_dss;
#if DM_NVN_M3
static int g_rx_args; // 老接口没有参数表:只当「常量缓冲建过没有」的标记 | the older API has no argument table: used only as the marker for "has the constant buffer been created"
#else
static id<MTL4ArgumentTable> g_rx_args;
#endif
static id<MTLBuffer> g_rx_const[3]; static int g_rx_ci;
static id<MTLTexture> g_rx_stv; static __unsafe_unretained id<MTLTexture> g_rx_stv_src;
static const char *k_rx_msl =
@@ -84,8 +89,12 @@ static int rx_setup(MTLPixelFormat fc, MTLPixelFormat fds) {
if (fds == MTLPixelFormatDepth32Float_Stencil8) { MTLStencilDescriptor *sd = [MTLStencilDescriptor new]; sd.stencilCompareFunction = MTLCompareFunctionEqual; sd.readMask = 0x2; sd.writeMask = 0x80; sd.depthStencilPassOperation = MTLStencilOperationReplace; // 洞 / 屏外新进来的像素由片元导出 0x80,后面 LDR 区域据此重算 // 本帧被界面挡住的像素(界面模板趟已写 0x2)不算 | Hole pixels / pixels newly entering from off-screen get 0x80 exported by the fragment, and the later LDR region is recomputed accordingly // Pixels covered by this frame's UI (the UI stencil pass already wrote 0x2) do not count
dd.frontFaceStencil = sd; dd.backFaceStencil = sd; }
g_rx_dss = [g_dev newDepthStencilStateWithDescriptor:dd];
#if DM_NVN_M3
if (!g_rx_args) { g_rx_args = 1;
#else
if (!g_rx_args) { MTL4ArgumentTableDescriptor *ad = [MTL4ArgumentTableDescriptor new]; ad.maxTextureBindCount = 3; ad.maxBufferBindCount = 1;
g_rx_args = [g_dev newArgumentTableWithDescriptor:ad error:&e];
#endif
for (int i = 0; i < 3; i++) { g_rx_const[i] = [g_dev newBufferWithLength:256 options:MTLResourceStorageModeShared]; res_add(g_rx_const[i]); } }
if (!g_rx_args || !g_rx_dss) { MLOG("【红】运行时外推:参数表 / 深度状态建不出"); g_rx_pso1 = nil; failed = 1; return 0; }
g_rx_fmt_c = fc; g_rx_fmt_ds = fds; MLOG("运行时外推:着色器建好(颜色格式 %lu,深度格式 %lu)", (unsigned long)fc, (unsigned long)fds);
@@ -143,15 +152,20 @@ int rt_ex_encode(id<MTLTexture> dst_hdr, id<MTLTexture> dst_ds, id<MTLTexture> s
rp_end(); if (g_blit) { enc_b_end(g_blit); g_blit = nil; }
// 单趟:外推 + 补洞 + 按小数相位补锐化 → dst_hdr;深度写进 dst_ds;本帧界面挡住的像素按模板跳过(模板不写)
// Single pass: extrapolation + hole filling + sharpening compensation by fractional phase → dst_hdr; depth is written into dst_ds; pixels covered by this frame's UI are skipped by stencil (stencil not written)
MTL4RenderPassDescriptor *rp = [MTL4RenderPassDescriptor new];
RPD *rp = [RPD new];
rp.colorAttachments[0].texture = dst_hdr; rp.colorAttachments[0].loadAction = MTLLoadActionLoad; rp.colorAttachments[0].storeAction = MTLStoreActionStore;
rp.depthAttachment.texture = dst_ds; rp.depthAttachment.loadAction = MTLLoadActionLoad; rp.depthAttachment.storeAction = MTLStoreActionStore;
if (dst_ds.pixelFormat == MTLPixelFormatDepth32Float_Stencil8) { rp.stencilAttachment.texture = dst_ds; rp.stencilAttachment.loadAction = MTLLoadActionLoad; rp.stencilAttachment.storeAction = MTLStoreActionStore; }
id<MTL4RenderCommandEncoder> en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0;
RENC en = [g_cb renderCommandEncoderWithDescriptor:rp]; if (!en) return 0;
#if DM_NVN_M3
[en setFragmentTexture:src_hdr atIndex:0]; [en setFragmentTexture:src_ds atIndex:1]; [en setFragmentTexture:g_rx_stv atIndex:2];
[en setFragmentBuffer:cbuf offset:0 atIndex:0];
#else
[en barrierAfterQueueStages:MTLStageAll beforeStages:MTLStageAll visibilityOptions:MTL4VisibilityOptionDevice];
[en setArgumentTable:g_rx_args atStages:MTLRenderStageFragment];
[g_rx_args setTexture:src_hdr.gpuResourceID atIndex:0]; [g_rx_args setTexture:src_ds.gpuResourceID atIndex:1]; [g_rx_args setTexture:g_rx_stv.gpuResourceID atIndex:2];
[g_rx_args setAddress:cbuf.gpuAddress atIndex:0];
#endif
[en setViewport:(MTLViewport){0, 0, W, H, 0, 1}]; [en setRenderPipelineState:g_rx_pso1]; [en setDepthStencilState:g_rx_dss]; [en setStencilReferenceValue:0];
[en drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3]; m4_end(en);
args_dirty_all(); g_pso_dirty = g_dss_dirty = 1;
+7
View File
@@ -85,3 +85,10 @@ run: t_nvn t_dirty_slots t_dirty_race t_builtin t_deswz_gpu t_pace t_refl t_hmap
MTL_DEBUG_LAYER=1 ./t_pfv
python3 test_tbdr_budget.py
.PHONY: run
# 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。
# 闸门(verify/accept.sh)两遍都跑,免得以后只测一边
# The older-API pass (compile-time switch DM_NVN_M3=1 of the graphics backend, target macOS 15.0): built and run separately from the same test sources in the sibling tests_m3 directory, leaving the default outputs here untouched.
# The gate (verify/accept.sh) runs both passes, so that only one side being tested cannot happen later
run-m3:
rm -rf ../tests_m3 && mkdir ../tests_m3 && cp Makefile *.c *.m *.py ../tests_m3/
$(MAKE) -C ../tests_m3 run CFLAGS="$(CFLAGS) -DDM_NVN_M3=1 -mmacosx-version-min=15.0"
+2 -2
View File
@@ -15,9 +15,9 @@ static tex_t color={.serial=52000},depth={.serial=52001};static prog_t pg[2]={{.
static p_set_rt rt(int levels){p_set_rt r={.n=1,.depth=&depth,.has_dview=1};r.color[0]=&color;r.has_cview[0]=1;
r.cview[0]=(view_t){.set_levels=1,.set_layers=1,.set_format=1,.set_target=1,.nlevels=levels,.nlayers=1,.format=NVN_FORMAT_RGBA8,.target=NVN_TEXTURE_TARGET_2D};
r.dview=r.cview[0];r.dview.nlevels=1;r.dview.base_level=small_depth?1:0;r.dview.format=NVN_FORMAT_DEPTH32F_STENCIL8;return r;}
static void seed(void){MTL4RenderPassDescriptor *p=[MTL4RenderPassDescriptor new];p.colorAttachments[0].texture=tex_mtl(&color);p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,1);
static void seed(void){RPD *p=[RPD new];p.colorAttachments[0].texture=tex_mtl(&color);p.colorAttachments[0].loadAction=MTLLoadActionClear;p.colorAttachments[0].storeAction=MTLStoreActionStore;p.colorAttachments[0].clearColor=MTLClearColorMake(0,0,0,1);
p.depthAttachment.texture=p.stencilAttachment.texture=tex_mtl(&depth);p.depthAttachment.loadAction=p.stencilAttachment.loadAction=MTLLoadActionClear;p.depthAttachment.storeAction=p.stencilAttachment.storeAction=MTLStoreActionStore;p.depthAttachment.clearDepth=.75;p.stencilAttachment.clearStencil=0x2d;enc_r_end(enc_r_begin(p));
if(sample_attachment){MTL4RenderPassDescriptor *q=[MTL4RenderPassDescriptor new];q.colorAttachments[0].texture=tex_mtl(&color);q.colorAttachments[0].level=1;q.colorAttachments[0].loadAction=MTLLoadActionClear;q.colorAttachments[0].storeAction=MTLStoreActionStore;q.colorAttachments[0].clearColor=MTLClearColorMake(0,1,0,0);enc_r_end(enc_r_begin(q));}
if(sample_attachment){RPD *q=[RPD new];q.colorAttachments[0].texture=tex_mtl(&color);q.colorAttachments[0].level=1;q.colorAttachments[0].loadAction=MTLLoadActionClear;q.colorAttachments[0].storeAction=MTLStoreActionStore;q.colorAttachments[0].clearColor=MTLClearColorMake(0,1,0,0);enc_r_end(enc_r_begin(q));}
if(small_depth){p.colorAttachments[0].texture=nil;p.depthAttachment.level=p.stencilAttachment.level=1;enc_r_end(enc_r_begin(p));}}
static void rr_read_planes(id<MTLBuffer> __strong *b){id<MTLTexture> t=tex_mtl(&color),d=tex_mtl(&depth);[blit()copyFromTexture:t sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[0]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256];
[blit()copyFromTexture:d sourceSlice:0 sourceLevel:0 sourceOrigin:MTLOriginMake(0,0,0)sourceSize:MTLSizeMake(8,8,1)toBuffer:b[1]destinationOffset:0 destinationBytesPerRow:32 destinationBytesPerImage:256 options:MTLBlitOptionDepthFromDepthStencil];
+5
View File
@@ -3,12 +3,17 @@
#include <stdint.h>
#import <Metal/Metal.h>
#include "nvn_deswizzle.h"
#ifndef DM_NVN_M3
#define DM_NVN_M3 0 // 见 nvn_mtl.m:1 = 图形后端走老接口 | see nvn_mtl.m: 1 = the graphics backend uses the older API
#endif
int nvn_deswz_gpu_init(id<MTLDevice> dev);
int nvn_deswz_gpu_encode(id<MTLComputeCommandEncoder> enc, id<MTLBuffer> src, uint64_t src_off,
const nvn_texdesc *d, unsigned level, unsigned layer,
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch);
#if !DM_NVN_M3
int nvn_deswz_gpu_encode_m4(id<MTL4ComputeCommandEncoder> enc, id<MTL4ArgumentTable> table,
id<MTLBuffer> params, size_t params_off, id<MTLBuffer> src, uint64_t src_off,
const nvn_texdesc *d, unsigned level, unsigned layer,
id<MTLBuffer> dst, uint64_t dst_off, size_t dst_pitch);
#endif
+2
View File
@@ -48,6 +48,7 @@ int nvn_deswz_gpu_encode(id<MTLComputeCommandEncoder> enc, id<MTLBuffer> src, ui
return 0;
}
#if !DM_NVN_M3
int nvn_deswz_gpu_encode_m4(id<MTL4ComputeCommandEncoder> enc, id<MTL4ArgumentTable> table,
id<MTLBuffer> params, size_t params_off, id<MTLBuffer> src, uint64_t src_off,
const nvn_texdesc *d, unsigned level, unsigned layer,
@@ -71,3 +72,4 @@ int nvn_deswz_gpu_encode_m4(id<MTL4ComputeCommandEncoder> enc, id<MTL4ArgumentTa
[enc dispatchThreadgroups:MTLSizeMake(gobs_x, gobs_y, slices) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
return 0;
}
#endif
+27
View File
@@ -0,0 +1,27 @@
#!/bin/bash
# 把 Mac 着色器库按指定的最低系统版本重编一份:msl_retarget.sh <最低系统,如 15.0> <输出根目录> 产出 <输出根目录>/b-<翻译链版本>/
# 为什么要有:dmsh_build.py 编库时不带最低版本参数,库里记的目标是编译这台机器的 SDK(macOS 26);老系统上加载这种库会直接失败
# (同程序本体的最低系统版本是一回事,换了个地方)。老接口版的包(tools/mac_app.sh DM_MAC_M3=1)带的是这里重编出来的库。
# 源码来源(共用缓存只读):_b 库旁边的 .metal;_bf 库(可读 tile 版本)的源码在内容寻址缓存里,按库文件内容对上。
# 编译命令与 dmsh_build.py 相同,只多一个 -mmacosx-version-min。约 7000 个库 3 分钟。
# Recompile the Mac shader libraries for a given minimum system version: msl_retarget.sh <minimum system, e.g. 15.0> <output root> produces <output root>/b-<translation chain version>/
# Why it exists: dmsh_build.py compiles the libraries without a minimum-version flag, so the target recorded in them is the SDK of the build machine (macOS 26); loading such a library on an older system simply fails
# (the same matter as the minimum system version of the executable, in a different place). The older-API package (tools/mac_app.sh DM_MAC_M3=1) carries the libraries recompiled here.
# Where the sources come from (the shared cache is read-only): the .metal next to each _b library; the sources of _bf libraries (the readable-tile variants) are in the content-addressed cache and are matched by the content of the library file.
# The compile command is the same as in dmsh_build.py with only -mmacosx-version-min added. About 7000 libraries in 3 minutes.
set -u; MIN=$1; OUTROOT=$2
HERE=$(cd "$(dirname "$0")" && pwd); ROOT=${DM_ROOT:-$HOME/dm-work}
V=$(sed -n 's/.*DMSH_CHAIN "\(.*\)".*/\1/p' "$HERE/../nvn/dmsh_chain.h"); S=$ROOT/build/cache/metal_shader_cache/b-$V; CAS=$ROOT/build/cache/metal_shader_cache/cas/variant
[ -d "$S" ] || { echo "🔴 没有着色器库 ${S}(先跑 dmsh_build.py)"; exit 2; }
D=$OUTROOT/b-$V; rm -rf "$D"; mkdir -p "$D"; cp -c "$S"/*.json "$D"/
one() { src=$1; dst=$2; t=$(mktemp -d); if xcrun -sdk macosx metal -c -mmacosx-version-min="$MIN" "$src" -o "$t/a.air" 2>"$t/err" && xcrun -sdk macosx metallib "$t/a.air" -o "$t/a.metallib" 2>>"$t/err"; then mv "$t/a.metallib" "$dst"; else echo "失败 $(basename "$dst"):$(head -1 "$t/err" | cut -c1-120)"; fi; rm -rf "$t"; }
export -f one; export MIN D S
BAD=$(ls "$S" | grep '_b\.metal$' | sed 's/\.metal$//' | xargs -P 10 -I{} bash -c 'one "$S/{}.metal" "$D/{}.metallib"')
T=$(mktemp); for r in "$CAS"/*/; do [ -f "$r/mac.metallib" ] && [ -f "$r/metal" ] && echo "$(shasum -a 256 "$r/mac.metallib" | cut -c1-64) $r"; done > "$T"
miss=0
for f in "$S"/*_bf.metallib; do [ -f "$f" ] || continue; h=$(shasum -a 256 "$f" | cut -c1-64); r=$(grep -m1 "^$h " "$T" | cut -d' ' -f2-)
if [ -n "$r" ]; then m=$D/$(basename "${f%.metallib}").metal; cp "$r/metal" "$m"; BAD="$BAD$(one "$m" "$D/$(basename "$f")")"; rm -f "$m"; else miss=$((miss+1)); fi; done
rm -f "$T"
have=$(ls "$D" | grep -c '\.metallib$'); want=$(ls "$S" | grep -c '\.metallib$')
[ -z "$BAD" ] && [ "$miss" = 0 ] && [ "$have" = "$want" ] || { echo "🔴 着色器库重编不全:产出 ${have} / ${want},_bf 源码没对上 ${miss} 个;${BAD:0:300}"; exit 3; }
echo "MSL_RETARGET ${D}(${have} 个库,目标 macOS ${MIN})"