@@ -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 400 x225 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 ;