Android: NaN-free float color outputs against the top-of-screen flicker blocks; TBDR clears; mprotect ENOMEM fix

- Shader translator (Vulkan pack only): pixel shaders store 0 instead of NaN in
  float color outputs (XLATE_NAN_OUT=0 disables). ps_foliage occasionally writes
  NaN pixels on Adreno; the downsample / bloom chain spread them into blocks.
  Float min/max/clamp use NMin/NMax/NClamp like Maxwell FMNMX / .SAT
  (XLATE_NAN_MINMAX=0 disables).
- Vulkan backend: pending full clears become loadOp=CLEAR (DM_NVN_TBDR=0
  disables); TBDR / store profile stats; per-batch command pools and query reset.
- Trace diagnostics: NaN / Inf scan of float targets (DM_VK_NANSCAN_PS,
  DM_VK_NANSCAN_BOX), burst readback of the top rows (DM_VK_BURST*).
- nvn_dirty: protection unit max(pagesize, 16K) to stay under the VMA limit
  (mprotect ENOMEM crash); log the process mapping count.
- Upload-MB stat underflow fix; t_vk_perf test fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-14 19:36:26 +09:00
co-authored by Claude Opus 5.5
parent 3c25cd89fc
commit 1ceeeaba77
12 changed files with 396 additions and 24 deletions
+1 -1
View File
@@ -1,7 +1,7 @@
NDK ?= $(or $(ANDROID_NDK_HOME),$(lastword $(sort $(wildcard $(HOME)/Library/Android/sdk/ndk/*))))
CC := $(wildcard $(NDK)/toolchains/llvm/prebuilt/*/bin)/aarch64-linux-android33-clang
OUT ?= ../build/tests
CFLAGS = -O1 -g -Wall -Wno-unused-function -ffunction-sections -fdata-sections -I../../gfx/nvn -I../../gfx/nvn/include
CFLAGS = -O1 -g -Wall -Wno-unused-function -ffunction-sections -fdata-sections -I../../gfx/nvn -I../../gfx/nvn/include -include ../../host/compat/linux/compat_linux.h -I../../host/compat/linux/include -I../../host
$(OUT)/t_vk_perf: t_vk_perf.c ../../gfx/vulkan/nvn_vk.c ../../gfx/vulkan/nvn_vk_dispatch.h
@mkdir -p $(OUT)
$(CC) $(CFLAGS) -Wl,--gc-sections -Wl,-z,max-page-size=16384 $< -o $@ -landroid -ldl -lm -lz
+1 -1
View File
@@ -126,7 +126,7 @@ int main(int argc,char **argv) {
VkDescriptorSetLayoutCreateInfo layout_info={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,.bindingCount=1,.pBindings=&binding};
VShader shader={0};shader.h.nb=1;shader.b[0].type=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
CHECK(vkCreateDescriptorSetLayout(G.device,&layout_info,NULL,&shader.layout));
mtl_sub_begin();for(unsigned i=0;i<8200;i++)assert(shader_set_allocate(&shader));assert(G.batch->nextra_descriptors==1);
mtl_sub_begin();for(unsigned i=0;i<8200;i++)assert(shader_set_allocate(&shader,0));assert(G.batch->nextra_descriptors==1);
/* Capacity splits keep the logical fence reserved for the final piece. */
uint64_t before=G.fence;G.batch->ncounter=3000;
for(int i=0;i<3000;i++)G.batch->counter_ops[i]=(CounterOp){0,0,0};
+4
View File
@@ -1017,7 +1017,11 @@ static void tsummary(uint64_t frame) {
py = cy; pk = ck; pw = cw; }
pi = ci; pc = cc; pd = dr_; pf = frame; }
uint64_t up, re, fa, pr; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr);
#ifdef __ANDROID__
{ int nvn_dirty_vma_count(void); LOG("[nvn] 预排布贴图 首传 %llu 张、池内容变化重传 %llu 次;写保护缺页 %llu 次、宿主写前解保护 %llu 页;漏检 %llu(累计);进程映射 %d 段", up, re, fa, pr, mtl_pkg_miss(), nvn_dirty_vma_count()); }
#else
LOG("[nvn] 预排布贴图 首传 %llu 张、池内容变化重传 %llu 次;写保护缺页 %llu 次、宿主写前解保护 %llu 页;漏检 %llu(累计)", up, re, fa, pr, mtl_pkg_miss());
#endif
memset(g_tn, 0, sizeof g_tn);
}
// DM_SLOWFRAME=1(测试开关,真机经日志端口读):逐帧计时先存近 16 帧环;滞后 8 帧(GPU / 上屏时刻已回)判掉帧,
+18 -1
View File
@@ -14,6 +14,7 @@
#include <unistd.h>
#include <mach/mach_time.h>
#include <sched.h>
#include <stdio.h>
// 页状态与 mprotect 的次序(改保护的一方先把状态改成 BUSY,mprotect 落地后才改成终态;别的线程见 BUSY 就等):
// 设只读:NONE → BUSY → mprotect(只读) → PROT;解保护:PROT → BUSY → mprotect(可写) → NONE。
@@ -102,9 +103,25 @@ static void prep_write(void *addr, size_t len) {
}
}
// 跟踪粒度 = 系统页、但至少 16K。安卓页 4K:逐页解保护把池的映射切成只读 / 可写交错的碎段,每段一个 VMA,
// 一局十几分钟累计十几万次缺页后进程撞上 vm.max_map_count(约 65530),之后任何 mprotect / mmap 都回 ENOMEM(MapMemory 建线程栈时中止)。
// 16K 与苹果一致:碎段数降到四分之一,代价是同一 16K 内相邻贴图互相连坐(多一次重传,内容不会错)
// Tracking granularity = the system page, but at least 16K. Android pages are 4K: unprotecting page by page cuts a pool's mapping into interleaved read-only / writable pieces, one VMA each;
// after a dozen minutes of play and over a hundred thousand faults the process hits vm.max_map_count (about 65530), and from then on every mprotect / mmap returns ENOMEM (MapMemory aborts while creating a thread stack).
// 16K matches Apple: the number of pieces drops to a quarter, at the cost of neighbouring textures within one 16K implicating each other (one more re-upload, never wrong content)
static uintptr_t unit_size(void) { uintptr_t pg = (uintptr_t)getpagesize(); return pg < 0x4000 ? 0x4000 : pg; }
#ifdef __ANDROID__
int nvn_dirty_vma_count(void) { // /proc/self/maps 行数 = 进程 VMA 数(统计行用,几十毫秒级,别放热路径) | line count of /proc/self/maps = process VMA count (for the stats line; tens of ms, keep it off hot paths)
FILE *f = fopen("/proc/self/maps", "r"); if (!f) return -1;
char buf[65536]; size_t n; int lines = 0;
while ((n = fread(buf, 1, sizeof buf, f)) > 0) for (size_t i = 0; i < n; i++) lines += buf[i] == '\n';
fclose(f); return lines;
}
#endif
void nvn_dirty_add_range(const void *mem, size_t size) {
static int inited;
if (!inited) { inited = 1; g_pg = (uintptr_t)getpagesize(); g_shift = __builtin_ctzl(g_pg); mach_timebase_info(&g_tb); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
if (!inited) { inited = 1; g_pg = unit_size(); g_shift = __builtin_ctzl(g_pg); mach_timebase_info(&g_tb); dm_fault_hook_register(on_fault); dm_guest_write_prep_register(prep_write); }
atomic_fetch_add(&g_adds_total, 1);
pthread_mutex_lock(&g_slot_mu);
int n = atomic_load(&g_nr);
+3 -1
View File
@@ -57,7 +57,9 @@ def job_for(key, name, rec, w):
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1',
'sb_align': int(os.environ.get('SB_ALIGN', '64'))} # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
'sb_align': int(os.environ.get('SB_ALIGN', '64')), # Adreno minStorageBufferOffsetAlignment;翻译器按 base & -64 求偏移 | translator takes offsets from base & -64
'nan_minmax': os.environ.get('XLATE_NAN_MINMAX', '1') != '0',
'nan_out': os.environ.get('XLATE_NAN_OUT', '1') != '0'} # 浮点颜色输出 NaN 换 0;XLATE_NAN_OUT=0 关 | NaN in float color outputs becomes 0; XLATE_NAN_OUT=0 turns it off # 浮点 min/max/clamp 用 NaN 安全版(同 Maxwell);XLATE_NAN_MINMAX=0 关 | NaN-safe float min/max/clamp (as on Maxwell); XLATE_NAN_MINMAX=0 turns it off
if key not in FACTS: j['pc_missing'] = True; return j, c1
j.update(FACTS[key])
return j, c1
+6
View File
@@ -100,6 +100,12 @@ static class SwshXlate
// 作业 reduced = true:放宽精度——翻译器只给强制精确的运算打 NoContraction(缺省全部打:保持 Maxwell 分开舍入的逐位结果,代价是 MSL 里大量禁优化的 spvFMul 等)
// Job reduced = true: relaxed precision - the translator marks NoContraction only on operations that must be exact (the default marks all: keeps the bit-exact results of Maxwell's separate rounding, at the cost of many optimization-disabled spvFMul etc. in the MSL)
public bool QueryHostReducedPrecision() => _job["reduced"] is JsonNode n && (bool)n;
// 作业 nan_minmax = true:浮点 min / max / clamp 出 NMin / NMax / NClamp(Maxwell FMNMX 与 .SAT 遇 NaN 取另一操作数;Adreno 上 FMax / FClamp 会把 NaN 传下去,bloom 链把它扩成黑块)
// Job nan_minmax = true: float min / max / clamp emit NMin / NMax / NClamp (Maxwell FMNMX and .SAT take the other operand on NaN; on Adreno FMax / FClamp pass the NaN on, and the bloom chain spreads it into a black block)
public bool QueryHostNanSafeMinMax() => _job["nan_minmax"] is JsonNode n && (bool)n;
// 作业 nan_out = true:像素着色器写浮点颜色输出时 NaN 换成 0(Adreno 上 foliage 等偶尔算出 NaN 像素,降采样 / bloom 链把它扩成闪块)
// Job nan_out = true: pixel shaders store 0 instead of NaN in float color outputs (on Adreno foliage etc. occasionally produce NaN pixels, which downsample / bloom chains spread into flickering blocks)
public bool QueryHostNanFreeColorOutput() => _job["nan_out"] is JsonNode n && (bool)n;
}
static int Main(string[] args)
+305 -19
View File
@@ -102,14 +102,14 @@ typedef struct {
} ReplayState;
typedef struct Snapshot { VPool pool; uint64_t offset,hash; struct Snapshot *next; } Snapshot;
typedef struct {
VkCommandBuffer command; VkDescriptorPool descriptors; VkFence fence; uint64_t ticket,submit_order;
VkCommandBuffer command; VkCommandPool command_pool; VkDescriptorPool descriptors; VkFence fence; uint64_t ticket,submit_order;
VkSemaphore acquire; /* 本槽出图时的取图信号量;槽位复用前已等过 fence,可直接再用 | swapchain-acquire semaphore of a present in this slot; reusable once the slot's fence was waited */
VkDescriptorPool extra_descriptors[64]; unsigned nextra_descriptors,descriptor_used[9],descriptor_sets;
int recording,pending,awaiting_publish; uint64_t last_commit_ns; uint32_t draws,sets; uint64_t upload_bytes;
Range writes[LIMIT_WRITES]; VBuffer *writebacks[LIMIT_WRITES]; int nwrites; Event events[LIMIT_WRITES]; int nevents;
VBuffer **temporaries; size_t temporary_capacity; int ntemporary;
VkImageView temporary_views[LIMIT_WRITES]; int nview; VkBufferView buffer_views[LIMIT_WRITES]; int nbuffer_view;
VkQueryPool occlusion,timestamps; uint32_t nocc,ntime; int stamped;
VkQueryPool occlusion,timestamps; uint32_t nocc,ntime,reset_occ,reset_time; int stamped,queries_reset;
CounterOp counter_ops[LIMIT_WRITES]; int ncounter;
TraceCapture trace_captures[512]; unsigned ntrace_captures;
Snapshot *snapshots[1024]; VBuffer *upload_arena; uint64_t upload_offset; Snapshot *snapshot_blocks[1024]; unsigned nsnapshot;
@@ -750,6 +750,10 @@ static VPool *input_read(uint64_t addr,uint64_t len,uint64_t *offset) {
* reset/report instead of wrapping every draw; its total joins the counter in
* command order when the segment closes. */
static void counter_op(uint32_t kind,uint32_t query,uint64_t address);
static void pending_flush(void);
static void sx_pass_end(void);
static void nan_snap(const char *tag);
static void nan_snap_box(VTexture *u,const unsigned box[4],const char *tag);
static void query_end(void) {
if(G.query_active<0)return;vkCmdEndQuery(G.batch->command,G.batch->occlusion,(uint32_t)G.query_active);
counter_op(1,(uint32_t)G.query_active,0);G.query_active=-1;
@@ -788,7 +792,7 @@ static void pp_report(void){
fprintf(stderr,"[nvn-vulkan] PASSPROF i=%u kind=%c rt=%ux%u draws=%u ps=%s us=%.1f att=%s\n",i,pp_info[i].kind,pp_info[i].w,pp_info[i].h,pp_info[i].draws,pp_info[i].ps?pp_info[i].ps:"-",us,pp_info[i].att[0]?pp_info[i].att:"-");}
fprintf(stderr,"[nvn-vulkan] PASSPROF total_us=%.1f stamps=%u\n",total,pp_n);
}
static void pass_end(void) { if(G.in_pass) { query_end(); vkCmdEndRenderPass(G.batch->command); G.in_pass=0; pp_stamp('P',G.current_fb?G.current_fb->width:0,G.current_fb?G.current_fb->height:0); } }
static void pass_end(void) { if(G.in_pass) { sx_pass_end();query_end(); vkCmdEndRenderPass(G.batch->command); G.in_pass=0; pp_stamp('P',G.current_fb?G.current_fb->width:0,G.current_fb?G.current_fb->height:0); } }
static void all_barrier(void) {
G.profile_barriers++;G.profile_pass_breaks+=G.in_pass;pass_end(); VkMemoryBarrier b={.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,
.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT,.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT};
@@ -815,16 +819,27 @@ static void recording_begin_locked(void) {
static uint64_t epochs;batch->epoch=++epochs;memset(batch->texel_views,0,sizeof(batch->texel_views));
memset(&batch->bound,0,sizeof(batch->bound));batch->recording=1;G.in_pass=0;batch->table_offset=0;memset(batch->table_last_valid,0,sizeof(batch->table_last_valid));
G.batch->nwrites=G.batch->nevents=G.batch->ntemporary=0; G.in_pass=0;
G.batch->reset_occ=G.batch->nocc;G.batch->reset_time=G.batch->ntime;
G.batch->nocc=G.batch->ntime=0;G.batch->ncounter=0;G.batch->nview=0;G.batch->nbuffer_view=0;
VkCommandBufferAllocateInfo a={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,.commandPool=G.command_pool,
.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,.commandBufferCount=1}; if(!batch->command)CHECK(vkAllocateCommandBuffers(G.device,&a,&batch->command));
else CHECK(vkResetCommandBuffer(batch->command,0));
/* 每批一个命令池:整池重置比逐个 vkResetCommandBuffer 便宜(Adreno 上后者约占回放线程 3%)
* One command pool per batch: resetting the whole pool is cheaper than vkResetCommandBuffer one by one (~3% of the replay thread on Adreno) */
if(!batch->command){VkCommandPoolCreateInfo pi={.sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,.queueFamilyIndex=G.family};
CHECK(vkCreateCommandPool(G.device,&pi,NULL,&batch->command_pool));
VkCommandBufferAllocateInfo a={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,.commandPool=batch->command_pool,
.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY,.commandBufferCount=1};CHECK(vkAllocateCommandBuffers(G.device,&a,&batch->command));}
else CHECK(vkResetCommandPool(G.device,batch->command_pool,0));
VkCommandBufferBeginInfo b={.sType=VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,.flags=VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
CHECK(vkBeginCommandBuffer(G.batch->command,&b));
VkQueryPoolCreateInfo query={.sType=VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,.queryType=VK_QUERY_TYPE_OCCLUSION,.queryCount=LIMIT_WRITES};
if(!batch->occlusion)CHECK(vkCreateQueryPool(G.device,&query,NULL,&batch->occlusion));
query.queryType=VK_QUERY_TYPE_TIMESTAMP;query.queryCount=LIMIT_WRITES+2;if(!batch->timestamps)CHECK(vkCreateQueryPool(G.device,&query,NULL,&batch->timestamps));
vkCmdResetQueryPool(G.batch->command,G.batch->occlusion,0,LIMIT_WRITES);vkCmdResetQueryPool(G.batch->command,G.batch->timestamps,0,LIMIT_WRITES+2);
/* 查询按序号顺序分配:头一次整池重置,之后只重置上一轮用过的前段(其余自上次重置后没动过),外加每批都写的首尾时间戳
* Queries are allocated in index order: reset the whole pool the first time, afterwards only the prefix the previous recording used
* (the rest has not been touched since it was last reset), plus the batch start / end timestamps written every batch */
if(!batch->queries_reset){vkCmdResetQueryPool(G.batch->command,G.batch->occlusion,0,LIMIT_WRITES);vkCmdResetQueryPool(G.batch->command,G.batch->timestamps,0,LIMIT_WRITES+2);batch->queries_reset=1;}
else {if(batch->reset_occ)vkCmdResetQueryPool(G.batch->command,G.batch->occlusion,0,batch->reset_occ);
if(batch->reset_time)vkCmdResetQueryPool(G.batch->command,G.batch->timestamps,0,batch->reset_time);
vkCmdResetQueryPool(G.batch->command,G.batch->timestamps,BATCH_STAMP,2);}
batch->stamped=0;if(G.timestamp_bits)vkCmdWriteTimestamp(G.batch->command,VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,batch->timestamps,BATCH_STAMP);
if(!batch->descriptors)batch->descriptors=descriptor_pool_create();
else CHECK(vkResetDescriptorPool(G.device,batch->descriptors,0));
@@ -954,6 +969,7 @@ static void drain_locked(void) {
}
uint64_t mtl_sub_commit(void) {
if(!G.active)die("commit without begin",0);
pending_flush();
uint64_t ticket=++G.fence;G.batch->ticket=ticket;
int publish=G.batch->nevents;
for(int i=0;i<G.batch->ncounter;i++)if(G.batch->counter_ops[i].kind>=2)publish=1;
@@ -1025,8 +1041,11 @@ static void texture_transition(VTexture *t,VkImageLayout layout) {
/* GPU transfers and CPU streaming can update different compression blocks of
* one NVN allocation. Compare actual block bytes to the last CPU snapshot so
* page-level dirtiness never overwrites unrelated GPU-owned contents. */
/* Cumulative CPU texture upload bytes (the long-frame log takes per-frame deltas). */
static _Atomic uint64_t g_upload_total;
static void refresh_compressed_cpu(VTexture *t,const tex_t *source) {
uint64_t started=dm_android_nvn_clock_ns(),stamp=nvn_dirty_now();nvn_dirty_protect(source->mem,source->L.size);
atomic_fetch_add(&g_upload_total,source->L.size);
uint8_t *snapshot=malloc(source->L.size);if(!snapshot)die("streamed BC snapshot allocation",source->L.size);
memcpy(snapshot,source->mem,source->L.size);
unsigned changed_regions=0;
@@ -1126,7 +1145,7 @@ upload_existing:
if(!source->mem || !pool_find((uint64_t)(uintptr_t)source->mem,source->L.size,NULL)) die("packaged texture storage",source->serial);
// Protect before reading and stamp before protection: any later CPU
// write is newer than this snapshot, even if it races the upload.
uint64_t stamp=nvn_dirty_now();nvn_dirty_protect(source->mem,source->L.size);
uint64_t stamp=nvn_dirty_now();nvn_dirty_protect(source->mem,source->L.size);atomic_fetch_add(&g_upload_total,source->L.size);
const uint8_t *upload_memory=source->mem;
if(upload_bc){uint8_t *snapshot=malloc(source->L.size);if(!snapshot)die("BC CPU baseline snapshot allocation",source->L.size);
memcpy(snapshot,source->mem,source->L.size);free(t->cpu_snapshot);t->cpu_snapshot=snapshot;upload_memory=snapshot;}
@@ -1731,7 +1750,7 @@ static VkDescriptorSet bind_shader(VShader *s) {
if(!(s->fetch_bindings&(1ull<<i)) || sid){fprintf(stderr,"[nvn-vulkan] unbound sampler shader=%s stage=%u slot=%d sampler=%d handle=%#llx separate=%#llx fetch_bindings=%#llx\n",s->key,s->h.stage,b->slot,b->sampler,(unsigned long long)handle,(unsigned long long)(b->sampler>=0?G.state.samp[s->h.stage][b->sampler]:0),(unsigned long long)s->fetch_bindings);die("unbound sampler descriptor",sid);}
ii[i].sampler=fetch_sampler();
}else {ii[i].sampler=G.sslot[sid].sampler;
if(G.trace_frame&&s->h.stage==1&&!strcmp(s->key,"5c1ca4e7c3e4657c")){
if(G.trace_frame&&s->h.stage==1){
samp_par *p=&G.sslot[sid].source;
fprintf(stderr,"[nvn-vulkan] TEXTURE_SAMPLER draw=%llu binding=%u slot=%d serial=%llu sampler=%u minf=%u magf=%u lod=%g,%g bias=%g compare=%u,%u view_levels=%d,%d set_levels=%u\n",(unsigned long long)G.draws,b->binding,b->slot,(unsigned long long)t->serial,sid,p->minf,p->magf,p->lod_min,p->lod_max,p->lod_bias,p->cmp_mode,p->cmp_func,slot->view.base_level,slot->view.nlevels,slot->has_view&&slot->view.set_levels);
}
@@ -1835,7 +1854,68 @@ static VkImageSubresourceRange attachment_range(const tex_t *source,const view_t
die("attachment view format/layer/mip",level);
return (VkImageSubresourceRange){aspect(format(source->d.format)),level,1,layer,1};
}
/* 全屏 clear 先挂起,等下一个以它为附件的渲染通道开始时变成 loadOp=CLEAR:tiler 上省掉一次整图写出、一次整图读入和一道全屏障。
* 其它任何会碰到它的命令之前照旧补做 vkCmdClear*Image。DM_NVN_TBDR=0 关掉,供逐像素对照。
* Full clears are held and become loadOp=CLEAR when the next pass using the image as an attachment begins: on a tiler this
* saves a whole-image write, a whole-image read and a full barrier. Any other command that may touch it first replays the
* vkCmdClear*Image as before. DM_NVN_TBDR=0 turns it off for pixel A/B comparison. */
typedef struct { VTexture *t; VkImageSubresourceRange range; } SxAtt;
static SxAtt sx_att[9];static unsigned sx_natt;
typedef struct { VTexture *t; VkImageSubresourceRange range; VkClearValue value; } PendingClear;
#define PENDING_MAX 16
static PendingClear pending[PENDING_MAX];static int npending;
static uint64_t pending_folded,pending_flushed;
static int tbdr_on(void){static int on=-1;if(on<0){const char *e=getenv("DM_NVN_TBDR");on=!(e&&*e=='0');}return on;}
static int pending_find(const VTexture *t,const VkImageSubresourceRange *r) {
for(int i=0;i<npending;i++)if(pending[i].t==t && pending[i].range.baseMipLevel==r->baseMipLevel && pending[i].range.baseArrayLayer==r->baseArrayLayer)return i;
return -1;
}
static void pending_drop(int i){pending[i]=pending[--npending];}
static void pending_flush_one(int i) {
PendingClear c=pending[i];pending_drop(i);pending_flushed++;
all_barrier();texture_transition(c.t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
if(c.range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)vkCmdClearColorImage(G.batch->command,c.t->image,c.t->layout,&c.value.color,1,&c.range);
else vkCmdClearDepthStencilImage(G.batch->command,c.t->image,c.t->layout,&c.value.depthStencil,1,&c.range);
}
static void pending_flush(void){while(npending)pending_flush_one(npending-1);}
static void pending_add(VTexture *t,VkImageSubresourceRange range,const VkClearValue *value) {
t->cpu_owned=0;t->version++;
if(!tbdr_on()){pending[npending++]=(PendingClear){t,range,*value};pending_flush_one(npending-1);return;}
int i=pending_find(t,&range);
if(i>=0 && !(range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)) {
/* 深度、模板分开清的合并成一条;后清的面覆盖先清的值 | merge separate depth / stencil clears; the later aspect's value wins */
PendingClear *c=&pending[i];
if(range.aspectMask&VK_IMAGE_ASPECT_DEPTH_BIT)c->value.depthStencil.depth=value->depthStencil.depth;
if(range.aspectMask&VK_IMAGE_ASPECT_STENCIL_BIT)c->value.depthStencil.stencil=value->depthStencil.stencil;
c->range.aspectMask|=range.aspectMask;return;
}
if(i>=0){pending[i].value=*value;return;}
if(npending==PENDING_MAX)pending_flush_one(0);
pending[npending++]=(PendingClear){t,range,*value};
}
/* 要开的渲染通道:挂起项必须是它的附件、同一子资源、整个附件就是渲染区域、本次绘制不采样它,否则先补做 |
* for the pass about to begin, a held clear must be one of its attachments, the same subresource, cover the whole render
* area, and not be sampled by this draw; otherwise replay it first */
static void pending_resolve(void) {
if(!npending)return;
p_set_rt *rt=&G.state.rt;VTexture *ts[9];VkImageSubresourceRange rs[9];unsigned ws[9],hs[9],n=0,width=0,height=0;
for(int i=0;i<rt->n+(rt->depth?1:0) && i<9;i++) {
int is_depth=i==rt->n;const tex_t *source=is_depth?rt->depth:rt->color[i];if(!source)continue;
const view_t *v=is_depth?(rt->has_dview?&rt->dview:NULL):(rt->has_cview[i]?&rt->cview[i]:NULL);
rs[n]=attachment_range(source,v);ts[n]=texture_get(source,0);
ws[n]=ts[n]->width>>rs[n].baseMipLevel;hs[n]=ts[n]->height>>rs[n].baseMipLevel;if(!ws[n])ws[n]=1;if(!hs[n])hs[n]=1;
if(!width){width=ws[n];height=hs[n];}else{if(ws[n]<width)width=ws[n];if(hs[n]<height)height=hs[n];}n++;
}
for(int i=npending-1;i>=0;i--) {
int keep=0;
for(unsigned j=0;j<n;j++)if(ts[j]==pending[i].t && rs[j].baseMipLevel==pending[i].range.baseMipLevel && rs[j].baseArrayLayer==pending[i].range.baseArrayLayer)
keep=ws[j]==width && hs[j]==height;
for(unsigned j=0;keep && j<G.nimage_uses;j++)if(G.image_uses[j].serial==pending[i].t->serial)keep=0;
if(!keep)pending_flush_one(i);
}
}
static VkRenderPass render_begin(void) {
pending_resolve();VkClearValue clears[9];memset(clears,0,sizeof(clears));int consumed[9],nconsumed=0;
p_set_rt *rt=&G.state.rt;if(rt->n<0 || rt->n>8 || (!rt->n&&!rt->depth))die("render targets",rt->n);
VkAttachmentDescription attachments[9];VkAttachmentReference color[8],depth;VkImage images[9]={0};VkImageSubresourceRange ranges[9]={0};uint32_t n=0,width=0,height=0;
memset(color,0,sizeof(color));memset(&depth,0,sizeof(depth));
@@ -1863,6 +1943,10 @@ static VkRenderPass render_begin(void) {
attachments[n]=(VkAttachmentDescription){.format=t->format,.samples=VK_SAMPLE_COUNT_1_BIT,.loadOp=VK_ATTACHMENT_LOAD_OP_LOAD,
.storeOp=VK_ATTACHMENT_STORE_OP_STORE,.stencilLoadOp=VK_ATTACHMENT_LOAD_OP_LOAD,.stencilStoreOp=VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout=layout,.finalLayout=layout};
int pc=pending_find(t,&range);
if(pc>=0){VkImageAspectFlags m=pending[pc].range.aspectMask;clears[n]=pending[pc].value;consumed[nconsumed++]=pc;
if(m&(VK_IMAGE_ASPECT_COLOR_BIT|VK_IMAGE_ASPECT_DEPTH_BIT))attachments[n].loadOp=VK_ATTACHMENT_LOAD_OP_CLEAR;
if(m&VK_IMAGE_ASPECT_STENCIL_BIT)attachments[n].stencilLoadOp=VK_ATTACHMENT_LOAD_OP_CLEAR;}
images[n]=t->image;ranges[n]=range;
if(is_depth)depth=(VkAttachmentReference){n,layout};else color[i]=(VkAttachmentReference){n,layout};n++;
}
@@ -1901,9 +1985,15 @@ static VkRenderPass render_begin(void) {
fb->next=G.framebuffers;G.framebuffers=fb;}else G.fb_hits++;
/* Feedback draws retain a pass boundary: its external dependency orders
* prior attachment writes before ordinary sampled-image reads on Adreno. */
if(G.in_pass && G.current_fb==fb && !key.feedback)return pass->pass;
if(G.in_pass && G.current_fb==fb && !key.feedback && !nconsumed)return pass->pass;
pass_end();VkRenderPassBeginInfo begin={.sType=VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,.renderPass=pass->pass,.framebuffer=fb->framebuffer,
.renderArea={{0,0},{width,height}}};vkCmdBeginRenderPass(G.batch->command,&begin,VK_SUBPASS_CONTENTS_INLINE);
.renderArea={{0,0},{width,height}},.clearValueCount=nconsumed?n:0,.pClearValues=clears};vkCmdBeginRenderPass(G.batch->command,&begin,VK_SUBPASS_CONTENTS_INLINE);
/* 下标从大到小删,前面的下标不受交换影响 | drop highest index first so the swap-remove keeps lower indices valid */
for(int a=0;a<nconsumed;a++)for(int b=a+1;b<nconsumed;b++)if(consumed[b]>consumed[a]){int x=consumed[a];consumed[a]=consumed[b];consumed[b]=x;}
for(int a=0;a<nconsumed;a++)pending_drop(consumed[a]);pending_folded+=nconsumed;
sx_natt=0;for(unsigned i=0;i<n;i++){VTexture *at=NULL;for(int k=0;k<rt->n+(rt->depth?1:0) && !at;k++){const tex_t *src=k==rt->n?rt->depth:rt->color[k];
if(src){VTexture *c=texture_get(src,0);if(c->image==images[i])at=c;}}
sx_att[sx_natt++]=(SxAtt){at,ranges[i]};}
G.current_fb=fb;G.in_pass=1;G.pass_count++;pp_draws0=G.draws;pp_ps=NULL;return pass->pass;
}
@@ -1942,6 +2032,10 @@ static void draw(const p_draw *a,const p_draw_idx *idx) {
blend_st b=G.state.blend[0];fprintf(stderr,"[nvn-vulkan] UI_BLEND draw=%llu enable=%u src=%u,%u dst=%u,%u equation=%u,%u channels=%#x\n",(unsigned long long)G.draws,G.state.color.blend_en,b.src_rgb,b.src_a,b.dst_rgb,b.dst_a,b.eq_rgb,b.eq_a,G.state.mask.mask);
}
if(G.state.rt.n&&!ps)die("color draw program fragment stage missing",1);
if(G.trace_frame&&ps){static const char *k;static int init;if(!init){init=1;k=getenv("DM_VK_NANSCAN_PS");}
if(k&&strstr(k,ps->key)){char tg[24];snprintf(tg,24,"draw%llu",(unsigned long long)G.draws);nan_snap(tg);}
static unsigned box[4];static int bset=-1;if(bset<0){const char *e=getenv("DM_VK_NANSCAN_BOX");bset=e&&sscanf(e,"%u,%u,%u,%u",&box[0],&box[1],&box[2],&box[3])==4;}
if(bset&&G.state.rt.n&&G.state.rt.color[0]){char tg[40];snprintf(tg,40,"draw%llu-%s",(unsigned long long)G.draws,ps->key);nan_snap_box(texture_get(G.state.rt.color[0],0),box,tg);}}
if(G.draws<9 || G.trace_frame)fprintf(stderr,"[nvn-vulkan] DRAW_TRACE draw=%llu vs=%s ps=%s count=%d instances=%d rt=%llu viewport=%g,%g,%g,%g scissor=%d,%d,%u,%u cull=%u front=%u depth=%u,%u,%u blend=%u mask=%#x\n",
(unsigned long long)G.draws,vs->key,ps?ps->key:"none",a?a->count:idx->count,a?1:idx->instances,
(unsigned long long)(G.state.rt.n&&G.state.rt.color[0]?G.state.rt.color[0]->serial:0),G.state.viewport.x,G.state.viewport.y,G.state.viewport.width,G.state.viewport.height,
@@ -1952,6 +2046,7 @@ static void draw(const p_draw *a,const p_draw_idx *idx) {
G.state.stencil_compare[0],G.state.stencil_compare[1],G.state.stencil_write[0],G.state.stencil_write[1],G.state.stencil_ref[0],G.state.stencil_ref[1],
G.state.ds.fail_f,G.state.ds.zfail_f,G.state.ds.zpass_f,G.state.ds.fail_b,G.state.ds.zfail_b,G.state.ds.zpass_b);
G.feedback_flags=0;G.general_feedback=0;G.depth_sampled=0;G.nimage_uses=0;collect_image_uses(vs);collect_image_uses(ps);
pending_resolve();
uint64_t bind_started=prof_ns();
prepare_comparison_images(vs);prepare_comparison_images(ps);
bind_shader(vs);if(ps)bind_shader(ps);
@@ -2144,6 +2239,8 @@ static void clear_color(const p_clear_color *p) {
VTexture *t=texture_get(G.state.rt.color[p->index],0);VkRect2D s=G.state.scissor;
VkImageSubresourceRange range=attachment_range(&t->source,G.state.rt.has_cview[p->index]?&G.state.rt.cview[p->index]:NULL);
unsigned w=t->width>>range.baseMipLevel,h=t->height>>range.baseMipLevel;if(!w)w=1;if(!h)h=1;
if(G.trace_frame)fprintf(stderr,"[nvn-vulkan] CLEAR_COLOR index=%d serial=%llu extent=%u,%u scissor=%d,%d,%u,%u rgba=%g,%g,%g,%g\n",p->index,(unsigned long long)t->source.serial,w,h,
s.offset.x,s.offset.y,s.extent.width,s.extent.height,p->rgba[0],p->rgba[1],p->rgba[2],p->rgba[3]);
if(s.offset.x || s.offset.y || (s.extent.width && s.extent.width!=w) || (s.extent.height && s.extent.height!=h)) {
if(s.offset.x<0 || s.offset.y<0)die("clear scissor negative",p->index);
if((unsigned)s.offset.x>=w || (unsigned)s.offset.y>=h)return;
@@ -2151,8 +2248,7 @@ static void clear_color(const p_clear_color *p) {
render_begin();VkClearAttachment a={.aspectMask=VK_IMAGE_ASPECT_COLOR_BIT,.colorAttachment=p->index};memcpy(a.clearValue.color.float32,p->rgba,16);
VkClearRect r={s,0,1};vkCmdClearAttachments(G.batch->command,1,&a,1,&r);t->cpu_owned=0;t->version++;return;
}
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);VkClearColorValue color;memcpy(color.float32,p->rgba,sizeof(p->rgba));
vkCmdClearColorImage(G.batch->command,t->image,t->layout,&color,1,&range);t->cpu_owned=0;t->version++;
VkClearValue value;memcpy(value.color.float32,p->rgba,sizeof(p->rgba));pending_add(t,range,&value);
}
static void clear_ds(const p_clear_ds *p) {
if(G.trace_frame)fprintf(stderr,"[nvn-vulkan] CLEAR_DS depth=%g depth_mask=%#x stencil=%#x stencil_mask=%#x serial=%llu\n",p->depth,p->depth_mask,p->stencil,p->stencil_mask,
@@ -2171,8 +2267,7 @@ static void clear_ds(const p_clear_ds *p) {
render_begin();VkClearAttachment a={.aspectMask=flags,.clearValue.depthStencil={p->depth,(uint32_t)p->stencil}};
VkClearRect r={s,0,1};vkCmdClearAttachments(G.batch->command,1,&a,1,&r);t->cpu_owned=0;t->version++;return;
}
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);VkClearDepthStencilValue value={p->depth,(uint32_t)p->stencil};
vkCmdClearDepthStencilImage(G.batch->command,t->image,t->layout,&value,1,&range);t->cpu_owned=0;t->version++;
VkClearValue value={.depthStencil={p->depth,(uint32_t)p->stencil}};pending_add(t,range,&value);
}
static void clear_tex(const p_clear_tex *p) {
const view_t *v=p->has_view?&p->view:NULL;
@@ -2259,6 +2354,123 @@ static void copy_t2t(const p_copy_t2t *p) {
}
d->cpu_owned=0;d->version++;all_barrier();
}
/* ---------- 写回前瞻索引 | store lookahead index ----------
* 提交开始时按回放顺序走一遍全部命令(跟随 JUMP / CALL),给每条记录编号,并为每张贴图记下事件:作附件(ATT)、被采样 / 存储访问(READ)、
* 被拷贝 / 贴图清除(NEED)、整块清除(CLEAR,带清掉的面)。通道结束时,附件某个面之后的第一件事若是整块清除,这次写回就是多余的。
* 回放时逐条核对记录地址,对不上就作废索引,一律写回。移植自 Metal 后端的 mtl_sub_index / sdx_decide。
* At submission start walk every command in replay order (following JUMP / CALL), number each record, and log events per texture:
* attachment (ATT), sampled / storage access (READ), copy / texture clear (NEED), full clear (CLEAR, with the aspects cleared). At pass
* end, if the first later event on an attachment aspect is a full clear, its store is redundant. Replay checks each record address;
* any mismatch invalidates the index and everything is stored. Ported from the Metal backend's mtl_sub_index / sdx_decide. */
enum { SX_ATT=1,SX_READ,SX_NEED,SX_CLEAR };
typedef struct { uint64_t serial; uint32_t seq; uint16_t lv,sl; uint8_t kind,aspects; } SxEvent; /* lv = 0xffff:所有子资源 | all subresources */
#define SX_HB 2048
static const uint8_t **sx_op;static uint32_t sx_nop,sx_opcap,sx_seq;static int sx_valid;static uint64_t sx_mismatch;
static SxEvent *sx_ev,*sx_sorted;static uint32_t sx_nev,sx_evcap,sx_bucket[SX_HB+1];
typedef struct { p_set_rt rt; VkRect2D scissor; const prog_t *program; uint64_t tex[6][128],img[6][32]; } SxState;
static SxState sx_st;
static int sx_on(void){static int on=-1;if(on<0){const char *e=getenv("DM_VK_SX");on=!(e&&*e=='0');}return on;}
static unsigned sx_hash(uint64_t serial){return (unsigned)((serial*0x9e3779b97f4a7c15ULL)>>53);}
static void sx_event(uint64_t serial,unsigned kind,unsigned lv,unsigned sl,unsigned aspects) {
if(!serial)return;
if(sx_nev==sx_evcap){sx_evcap=sx_evcap?2*sx_evcap:8192;sx_ev=realloc(sx_ev,sx_evcap*sizeof(*sx_ev));sx_sorted=realloc(sx_sorted,sx_evcap*sizeof(*sx_sorted));
if(!sx_ev||!sx_sorted)die("store index allocation",sx_evcap);}
sx_ev[sx_nev++]=(SxEvent){serial,sx_nop-1,(uint16_t)lv,(uint16_t)sl,(uint8_t)kind,(uint8_t)aspects};
}
static void sx_reads(int stage) {
const prog_t *save=G.state.program;G.state.program=sx_st.program;VShader *sh=program_stage_optional(stage);G.state.program=save;
if(!sh)return;
for(unsigned i=0;i<sh->h.nb;i++){const RBinding *b=&sh->b[i];if(b->kind!=4&&b->kind!=6)continue;if(b->slot<0||b->slot>=(b->kind==6?32:128))continue;
unsigned tid=(b->kind==6?sx_st.img[stage][b->slot]:sx_st.tex[stage][b->slot])&0xfffff;
if(tid<(unsigned)G.texture_pool_n && tid<G.texture_slots && G.tslot[tid].live)sx_event(G.tslot[tid].texture.serial,SX_READ,0xffff,0xffff,7);}
}
/* 程序缺省时,所有已绑贴图都算被读 | with no program, every bound texture counts as read */
static void sx_reads_all(void) {
for(int st=0;st<6;st++){for(int i=0;i<128;i++){unsigned tid=sx_st.tex[st][i]&0xfffff;if(sx_st.tex[st][i] && tid<(unsigned)G.texture_pool_n && tid<G.texture_slots && G.tslot[tid].live)sx_event(G.tslot[tid].texture.serial,SX_READ,0xffff,0xffff,7);}
for(int i=0;i<32;i++){unsigned tid=sx_st.img[st][i]&0xfffff;if(sx_st.img[st][i] && tid<(unsigned)G.texture_pool_n && tid<G.texture_slots && G.tslot[tid].live)sx_event(G.tslot[tid].texture.serial,SX_READ,0xffff,0xffff,7);}}
}
static void sx_sub(const view_t *v,unsigned *lv,unsigned *sl){*lv=v&&v->set_levels?v->base_level:0;*sl=v&&v->set_layers?v->min_layer:0;}
static int sx_full(const tex_t *t,unsigned lv) {
unsigned w=t->d.width>>lv,h=t->d.height>>lv;if(!w)w=1;if(!h)h=1;VkRect2D c=sx_st.scissor;
return !(c.offset.x || c.offset.y || (c.extent.width && c.extent.width!=w) || (c.extent.height && c.extent.height!=h));
}
static void sx_walk(const uint8_t *p,unsigned depth) {
if(depth>32){sx_valid=0;return;}
for(unsigned guard=0;guard<1000000 && sx_valid;guard++) {
if(!pool_find((uint64_t)(uintptr_t)p,8,NULL)){sx_valid=0;return;}
op_hdr h;memcpy(&h,p,sizeof(h));if(h.size<8 || h.size%8 || !pool_find((uint64_t)(uintptr_t)p,h.size,NULL)){sx_valid=0;return;}
if(sx_nop==sx_opcap){sx_opcap=sx_opcap?2*sx_opcap:16384;sx_op=realloc(sx_op,sx_opcap*sizeof(*sx_op));if(!sx_op)die("store index allocation",sx_opcap);}
sx_op[sx_nop++]=p;const uint8_t *a=p+8;p_set_rt *rt=&sx_st.rt;
switch(h.op) {
case OP_END:return;
case OP_JUMP:if(h.size<16){sx_valid=0;return;}memcpy(&p,a,8);continue;
case OP_CALL:{const uint8_t *next;if(h.size<16){sx_valid=0;return;}memcpy(&next,a,8);sx_walk(next,depth+1);break;}
case OP_SET_RT:if(h.size<8+sizeof(p_set_rt)){sx_valid=0;return;}memcpy(rt,a,sizeof(p_set_rt));break;
case OP_SCISSOR:{const p_scissor *c=(const void *)a;sx_st.scissor=(VkRect2D){{c->x,c->y},{c->w,c->h}};break;}
case OP_BIND_PROGRAM:sx_st.program=((const p_bind_program *)a)->prog;break;
case OP_BIND_TEX:case OP_BIND_IMG:{const p_bind_handles *b=(const void *)a;int limit=h.op==OP_BIND_IMG?32:128;
if(b->stage<0||b->stage>=6||b->first<0||b->n<0||b->n>32||b->first>limit||b->n>limit-b->first){sx_valid=0;return;}
memcpy((h.op==OP_BIND_TEX?sx_st.tex[b->stage]:sx_st.img[b->stage])+b->first,b->h,b->n*8);break;}
case OP_CLEAR_COLOR:{const p_clear_color *c=(const void *)a;if(c->index<0||c->index>=rt->n||c->index>=8||!rt->color[c->index])break;
const tex_t *t=rt->color[c->index];unsigned lv,sl;sx_sub(rt->has_cview[c->index]?&rt->cview[c->index]:NULL,&lv,&sl);
if(c->mask==15 && sx_full(t,lv))sx_event(t->serial,SX_CLEAR,lv,sl,VK_IMAGE_ASPECT_COLOR_BIT);else sx_event(t->serial,SX_ATT,lv,sl,7);break;}
case OP_CLEAR_DS:{const p_clear_ds *c=(const void *)a;if(!rt->depth)break;const tex_t *t=rt->depth;unsigned lv,sl;sx_sub(rt->has_dview?&rt->dview:NULL,&lv,&sl);
unsigned m=0;if(c->depth_mask)m|=VK_IMAGE_ASPECT_DEPTH_BIT;if(c->stencil_mask)m|=VK_IMAGE_ASPECT_STENCIL_BIT;
if(!m)break;
if(sx_full(t,lv) && (!c->stencil_mask || c->stencil_mask==255 || c->stencil_mask==-1))sx_event(t->serial,SX_CLEAR,lv,sl,m);else sx_event(t->serial,SX_ATT,lv,sl,7);break;}
case OP_DRAW:case OP_DRAW_IDX:
if(sx_st.program){sx_reads(0);sx_reads(1);}else sx_reads_all();
for(int i=0;i<rt->n+1 && i<9;i++){const tex_t *t=i==rt->n?rt->depth:rt->color[i];if(!t)continue;unsigned lv,sl;
const view_t *v=i==rt->n?(rt->has_dview?&rt->dview:NULL):(rt->has_cview[i]?&rt->cview[i]:NULL);sx_sub(v,&lv,&sl);sx_event(t->serial,SX_ATT,lv,sl,7);}
break;
case OP_DISPATCH:if(sx_st.program)sx_reads(5);else sx_reads_all();break;
case OP_COPY_T2T:{const p_copy_t2t *c=(const void *)a;if(c->src)sx_event(c->src->serial,SX_READ,0xffff,0xffff,7);if(c->dst)sx_event(c->dst->serial,SX_NEED,0xffff,0xffff,7);break;}
case OP_COPY_B2T:{const p_copy_b2t *c=(const void *)a;if(c->tex)sx_event(c->tex->serial,SX_NEED,0xffff,0xffff,7);break;}
case OP_CLEAR_TEX:{const p_clear_tex *c=(const void *)a;if(c->tex)sx_event(c->tex->serial,SX_NEED,0xffff,0xffff,7);break;}
default:break;
}
p+=h.size;
}
}
void mtl_sub_index(const uint64_t *handles,int n) {
sx_nop=sx_nev=sx_seq=0;sx_valid=0;if(!sx_on() || n<=0)return;
sx_valid=1;sx_st.rt=G.state.rt;sx_st.scissor=G.state.scissor;sx_st.program=G.state.program;
memcpy(sx_st.tex,G.state.tex,sizeof(sx_st.tex));memcpy(sx_st.img,G.state.img,sizeof(sx_st.img));
for(int i=0;i<n && sx_valid;i++)sx_walk((const uint8_t *)(uintptr_t)handles[i],0);
if(!sx_valid){sx_nop=sx_nev=0;return;}
/* 按贴图分桶的稳定计数排序:桶内保持记录序 | stable counting sort into texture buckets; each bucket stays in record order */
memset(sx_bucket,0,sizeof(sx_bucket));
for(uint32_t i=0;i<sx_nev;i++)sx_bucket[sx_hash(sx_ev[i].serial)+1]++;
for(unsigned b=0;b<SX_HB;b++)sx_bucket[b+1]+=sx_bucket[b];
uint32_t fill[SX_HB];memcpy(fill,sx_bucket,sizeof(fill));
for(uint32_t i=0;i<sx_nev;i++)sx_sorted[fill[sx_hash(sx_ev[i].serial)]++]=sx_ev[i];
}
/* 从当前记录起(含)看这个附件面:返回 0 = 之后先被整块清除(写回多余),否则 1 + 原因(1 读 2 拷贝 3 作附件 4 到提交末尾 / 无索引)|
* from the current record on (inclusive), for this attachment aspect: 0 = next fully cleared (store redundant), otherwise 1 + reason
* (1 read, 2 copy, 3 attachment, 4 end of submission / no index) */
static int sx_need(uint64_t serial,unsigned lv,unsigned sl,unsigned aspect) {
if(!sx_valid)return 4;
uint32_t cur=sx_seq?sx_seq-1:0;unsigned b=sx_hash(serial);uint32_t lo=sx_bucket[b],hi=sx_bucket[b+1];
while(lo<hi){uint32_t mid=(lo+hi)/2;if(sx_sorted[mid].seq<cur)lo=mid+1;else hi=mid;}
for(uint32_t i=lo;i<sx_bucket[b+1];i++){const SxEvent *e=&sx_sorted[i];if(e->serial!=serial)continue;
int same=e->lv==0xffff || (e->lv==lv && e->sl==sl);
if(e->kind==SX_READ)return 1;
if(e->kind==SX_NEED)return 2;
if(!same)continue;
if(e->kind==SX_ATT)return 3;
if(e->kind==SX_CLEAR && (e->aspects&aspect))return 0;
}
return 4;
}
static uint64_t sx_bytes[2][5],sx_count[2][5]; /* [颜色/深度模板][原因] | [color/depth-stencil][reason] */
static void sx_pass_end(void) {
for(unsigned i=0;i<sx_natt;i++){VTexture *t=sx_att[i].t;if(!t)continue;VkImageSubresourceRange r=sx_att[i].range;
unsigned w=t->width>>r.baseMipLevel,h=t->height>>r.baseMipLevel;if(!w)w=1;if(!h)h=1;
int ds=!(r.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT);int why=0;
for(unsigned bit=1;bit<=4;bit<<=1)if(r.aspectMask&bit){int k=sx_need(t->serial,r.baseMipLevel,r.baseArrayLayer,bit);if(k>why)why=k;}
sx_bytes[ds][why]+=(uint64_t)w*h*t->bpp;sx_count[ds][why]++;}
sx_natt=0;
}
static void payload_check(const op_hdr *h,size_t bytes) { if(h->size<8+bytes)die("command payload truncated",h->op); }
static void execute(const uint8_t *p,unsigned depth) {
if(depth>32)die("nested command recursion",depth);
@@ -2266,6 +2478,16 @@ static void execute(const uint8_t *p,unsigned depth) {
if(!pool_find((uint64_t)(uintptr_t)p,8,NULL))die("command memory outside pools",(long long)(uintptr_t)p);
op_hdr h;memcpy(&h,p,sizeof(h));if(h.size<8 || h.size%8 || !pool_find((uint64_t)(uintptr_t)p,h.size,NULL))die("command record size",h.size);
const uint8_t *a=p+8;
if(sx_valid && (sx_seq>=sx_nop || sx_op[sx_seq]!=p)){sx_valid=0;sx_mismatch++;}
sx_seq++;
if(npending)switch(h.op){
case OP_END:case OP_BEGIN:case OP_JUMP:case OP_CALL:case OP_SET_RT:case OP_CLEAR_COLOR:case OP_CLEAR_DS:case OP_VIEWPORTS:
case OP_SCISSOR:case OP_DEPTH_RANGE:case OP_BIND_PROGRAM:case OP_BIND_STATE:case OP_BIND_VATTR:case OP_BIND_VSTREAM:
case OP_BIND_VBUF:case OP_BIND_UBO:case OP_BIND_SSBO:case OP_STENCIL:case OP_BIND_TEX:case OP_BIND_SAMP:case OP_BIND_IMG:
case OP_DRAW:case OP_DRAW_IDX:case OP_POLY_OFFSET:case OP_COPY_STRIDE:case OP_BLEND_COLOR:case OP_SHADER_SCRATCH:
case OP_SET_TEX_POOL:case OP_SET_SAMP_POOL:break;
default:pending_flush();
}
switch(h.op) {
case OP_END:return;
case OP_BEGIN:break; /* Structural record; GPU binding state persists across command handles. */
@@ -2382,7 +2604,6 @@ static void execute(const uint8_t *p,unsigned depth) {
}
void mtl_exec(const uint8_t *handle) { if(!G.active)die("execute without submission",0);execute(handle,0); }
void mtl_exec_rest(const uint64_t *handles,int n) { (void)handles;(void)n; } /* Optimization-only lookahead; replay order is unchanged. */
void mtl_sub_index(const uint64_t *handles,int n) { (void)handles;(void)n; } /* No attachment store-elision optimizer in this backend. */
/* 拆交换链(持 G.lock):先等队列空,出图信号量才能销毁 | Tear down the swapchain (G.lock held): wait for the queue first so its semaphores can be destroyed */
static void swapchain_drop(void) {
@@ -2519,6 +2740,53 @@ static void adpf_frame(double period) {
uint64_t gap=now-last;last=now;
if(gap>slept && gap<1000000000ull)report(session,(int64_t)(gap-slept)); /* 超过 1 s 的间隔是后台 / 读取,不报 | gaps over 1 s are background / loading, not reported */
}
/* 追踪帧:把各浮点目标(B10G11R11 / RGBA16F / R16F,前 4 级)读回,数 NaN / Inf(查黑块:浮点目标里一团 NaN 会被 bloom 降采样链扩成方块)。
* nan_snap 只录拷贝,可在帧中任意绘制前调用(DM_VK_NANSCAN_PS=<像素着色器键>:该着色器每次绘制前各拍一次);nan_report 在等完 GPU 后统一扫描
* Trace frames: read back every float target (B10G11R11 / RGBA16F / R16F, first 4 levels) and count NaN / Inf (black-block hunt: a NaN blob in a float target is spread into a square by the bloom downsample chain).
* nan_snap only records copies and may run before any draw mid-frame (DM_VK_NANSCAN_PS=<pixel shader key,...>: one snapshot before each draw with those shaders); nan_report scans them all after the GPU has drained */
enum{NAN_SNAPS=1024};
/* 可扫的浮点格式:每像素字节数,0 = 不扫 | scannable float formats: bytes per pixel, 0 = not scanned */
static unsigned nan_bpp(VkFormat f) { return f==VK_FORMAT_B10G11R11_UFLOAT_PACK32?4:f==VK_FORMAT_R16G16B16A16_SFLOAT?8:f==VK_FORMAT_R16_SFLOAT?2:0; }
static struct { VBuffer buf; VTexture *t; uint64_t serial; unsigned lv,x,y,w,h; char tag[40]; } g_nan[NAN_SNAPS];
static int g_nnan;
static void nan_snap(const char *tag) {
pass_end();
for(int i=0;i<G.ntexture && g_nnan<NAN_SNAPS;i++){VTexture *u=&G.textures[i];
if(!nan_bpp(u->format) || !u->image || u->depth!=1)continue;
texture_transition(u,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
for(unsigned lv=0;lv<u->source.d.levels && lv<4 && g_nnan<NAN_SNAPS;lv++){unsigned w=u->width>>lv?u->width>>lv:1,h=u->height>>lv?u->height>>lv:1;
g_nan[g_nnan].buf=buffer_make((uint64_t)w*h*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,lv,0,1},.imageExtent={w,h,1}};
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c);
g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=lv;g_nan[g_nnan].x=g_nan[g_nnan].y=0;g_nan[g_nnan].w=w;g_nan[g_nnan].h=h;snprintf(g_nan[g_nnan++].tag,40,"%s",tag);}}
}
/* 只拷一张目标 0 级里的一个小框(DM_VK_NANSCAN_BOX=x,y,w,h:追踪帧里每次绘制前拍当前 0 号颜色目标,用来二分出第一次写出 NaN 的绘制)
* Copy just a small box of one target's level 0 (DM_VK_NANSCAN_BOX=x,y,w,h: on trace frames snapshot colour target 0 before every draw, to bisect the first draw that writes NaN) */
static void nan_snap_box(VTexture *u,const unsigned box[4],const char *tag) {
if(g_nnan>=NAN_SNAPS || !u || !u->image || !nan_bpp(u->format))return;
if(box[0]+box[2]>u->width || box[1]+box[3]>u->height || u->width<1000)return; /* 只看全尺寸 3D 目标 | full-size 3D targets only */
pass_end();texture_transition(u,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
g_nan[g_nnan].buf=buffer_make((uint64_t)box[2]*box[3]*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageOffset={(int)box[0],(int)box[1],0},.imageExtent={box[2],box[3],1}};
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c);
g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=0;g_nan[g_nnan].x=box[0];g_nan[g_nnan].y=box[1];g_nan[g_nnan].w=box[2];g_nan[g_nnan].h=box[3];snprintf(g_nan[g_nnan++].tag,40,"%s",tag);
}
static void nan_report(void) {
for(int k=0;k<g_nnan;k++){const uint32_t *px=(const uint32_t *)g_nan[k].buf.map;unsigned w=g_nan[k].w,h=g_nan[k].h;uint64_t nan=0,inf=0;unsigned x0=w,y0=h,x1=0,y1=0;
unsigned bpp=nan_bpp(g_nan[k].t->format);
for(unsigned y=0;y<h;y++)for(unsigned x=0;x<w;x++){int n=0,f=0;
if(bpp!=4){unsigned nc=bpp/2;const uint16_t *q=(const uint16_t *)px+((size_t)y*w+x)*nc; /* 半浮点:指数 10-14 全 1 | half: exponent bits 10-14 all ones */
for(unsigned c=0;c<nc;c++)if((q[c]&0x7c00)==0x7c00){if(q[c]&0x3ff)n=1;else f=1;}}
else{uint32_t v=px[(size_t)y*w+x]; /* R:0-10 G:11-21 B:22-31,各段高 5 位是指数 | R:0-10 G:11-21 B:22-31, top 5 bits of each field are the exponent */
unsigned er=(v>>6)&31,mr=v&63,eg=(v>>17)&31,mg=(v>>11)&63,eb=(v>>27)&31,mb=(v>>22)&31;
n=(er==31&&mr)||(eg==31&&mg)||(eb==31&&mb);f=(er==31&&!mr)||(eg==31&&!mg)||(eb==31&&!mb);}
if(n)nan++;if(f)inf++;if(n||f){if(x<x0)x0=x;if(y<y0)y0=y;if(x>x1)x1=x;if(y>y1)y1=y;}}
if(nan||inf||!strcmp(g_nan[k].tag,"present")||g_nan[k].x||g_nan[k].y)fprintf(stderr,"[nvn-vulkan] NAN_SCAN frame=%llu at=%s serial=%llu level=%u extent=%u,%u nan=%llu inf=%llu box=%u,%u-%u,%u\n",(unsigned long long)G.present_count+1,g_nan[k].tag,
(unsigned long long)g_nan[k].serial,g_nan[k].lv,w,h,(unsigned long long)nan,(unsigned long long)inf,x0+g_nan[k].x,y0+g_nan[k].y,x1+g_nan[k].x,y1+g_nan[k].y);
buffer_free(&g_nan[k].buf);}
g_nnan=0;
}
uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) {
uint64_t present_started=dm_android_nvn_clock_ns();
/* 没有 Surface(adb 无头):照常回放到出图贴图,只是不上屏;读回由 DM_FRAME_DIR / dm_gfx_shot_at 触发
@@ -2528,11 +2796,18 @@ uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) {
if(G.present_count<2 || G.trace_frame)fprintf(stderr,"[nvn-vulkan] PRESENT_FORMAT frame=%llu source_format=%u swap_format=%u source_extent=%u,%u swap_extent=%u,%u windowed=%d\n",(unsigned long long)G.present_count+1,t->format,G.swap_format,t->width,t->height,G.swap_extent.width,G.swap_extent.height,windowed);
const char *capture_root=getenv("DM_FRAME_DIR");VBuffer capture={0};char shot_path[1024];
int shot=shot_take(G.present_count+1,shot_path,sizeof shot_path);
int capture_frame=shot || (capture_root && (G.trace_frame || G.present_count<4 || (G.present_count%120==0 && G.present_count<1000)));
/* DM_VK_BURST=起-止 帧、DM_VK_BURST_FILE=路径:这段每帧出图贴图顶部 DM_VK_BURST_ROWS 行(缺省 200)原样 RGBA 追加进文件(查闪块用,读回会拖慢这几帧)
* DM_VK_BURST=first-last frames, DM_VK_BURST_FILE=path: the top DM_VK_BURST_ROWS rows (default 200) of the present texture of each of those frames are appended raw RGBA to the file (for flicker hunting; the readback slows those frames) */
static long burst_a=-1,burst_b=-1,burst_rows=200;static const char *burst_file;
if(burst_a==-1){const char *e=getenv("DM_VK_BURST"),*r=getenv("DM_VK_BURST_ROWS");burst_file=getenv("DM_VK_BURST_FILE");burst_a=-2;
if(e && burst_file && sscanf(e,"%ld-%ld",&burst_a,&burst_b)!=2)burst_a=-2;if(r)burst_rows=atol(r);}
int burst=burst_a>=0 && (long)G.present_count+1>=burst_a && (long)G.present_count+1<=burst_b;
int capture_frame=shot || burst || (capture_root && (G.trace_frame || G.present_count<4 || (G.present_count%120==0 && G.present_count<1000)));
if(capture_frame && t->bpp==4){capture=buffer_make((uint64_t)t->width*t->height*4,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageExtent={t->width,t->height,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture.b,1,&c);}
else if(capture_frame)fprintf(stderr,"[nvn-vulkan] readback skipped: present texture bpp=%u format=%u\n",t->bpp,t->format);
if(G.trace_frame && capture.b)nan_snap("present");
G.batch->ticket=++G.fence;VkFence fence=G.batch->fence;
if(windowed){
/* 取图信号量归批次槽、出图信号量按交换链图像各一个:都可复用,出图不再等 GPU 跑完(旧做法每帧建 / 等队列空 / 销毁)
@@ -2578,7 +2853,11 @@ uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) {
}else{flush_locked();}
if(capture.b || G.synchronous){G.wait_site=WAIT_CAPTURE;drain_locked();G.wait_site=WAIT_SYNC;}
if(capture.b){
if(capture_root && !shot){char file[1200];snprintf(file,sizeof file,"%s/frame-%04llu.ppm",capture_root,(unsigned long long)G.present_count+1);
nan_report();
if(burst){FILE *o=fopen(burst_file,"ab");long rows=burst_rows<(long)t->height?burst_rows:(long)t->height;
if(o){fwrite(capture.map,(size_t)t->width*4,(size_t)rows,o);fclose(o);}
fprintf(stderr,"[nvn-vulkan] BURST frame=%llu extent=%u,%u rows=%ld\n",(unsigned long long)G.present_count+1,t->width,t->height,rows);}
else if(capture_root && !shot){char file[1200];snprintf(file,sizeof file,"%s/frame-%04llu.ppm",capture_root,(unsigned long long)G.present_count+1);
unsigned nonblack=write_ppm(file,t,capture.map);
fprintf(stderr,"[nvn-vulkan] PRESENT_READBACK frame=%llu extent=%u,%u nonblack=%u draws=%llu passes=%llu\n",(unsigned long long)G.present_count+1,t->width,t->height,nonblack,(unsigned long long)G.draws,(unsigned long long)G.pass_count);}
if(shot){unsigned nonblack=write_ppm(shot_path,t,capture.map);
@@ -2596,6 +2875,13 @@ uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) {
(unsigned long long)G.present_count+1,(unsigned long long)(G.pso_hits-G.profile_pso_hits),(unsigned long long)(G.pso_misses-G.profile_pso_misses),
(unsigned long long)(G.pass_hits-G.profile_pass_hits),(unsigned long long)(G.fb_hits-G.profile_fb_hits),(unsigned long long)(G.pass_count-G.profile_passes),(unsigned long long)G.batch_count,
(unsigned long long)G.profile_barriers,(unsigned long long)G.profile_pass_breaks,(unsigned long long)G.profile_pipeline_binds,(unsigned long long)G.profile_set_binds,(unsigned long long)G.profile_set_writes,(unsigned long long)G.profile_temp_new,G.profile_temp_new_bytes/1048576.,(unsigned long long)G.profile_temp_max,(unsigned long long)G.profile_temp_drop,temporary_free_bytes/1048576.,G.profile_gpu_ns/1e6);
fprintf(stderr,"[nvn-vulkan] TBDR_PROFILE frame=%llu clears_folded=%llu clears_replayed=%llu\n",(unsigned long long)G.present_count+1,(unsigned long long)pending_folded,(unsigned long long)pending_flushed);
{double fr=G.profile_frames?G.profile_frames:1;fprintf(stderr,"[nvn-vulkan] STORE_PROFILE frame=%llu per_frame color_MiB dc=%.2f read=%.2f copy=%.2f att=%.2f end=%.2f ds_MiB dc=%.2f read=%.2f copy=%.2f att=%.2f end=%.2f n_dc=%llu,%llu mismatch=%llu ops=%u events=%u\n",(unsigned long long)G.present_count+1,
sx_bytes[0][0]/1048576./fr,sx_bytes[0][1]/1048576./fr,sx_bytes[0][2]/1048576./fr,sx_bytes[0][3]/1048576./fr,sx_bytes[0][4]/1048576./fr,
sx_bytes[1][0]/1048576./fr,sx_bytes[1][1]/1048576./fr,sx_bytes[1][2]/1048576./fr,sx_bytes[1][3]/1048576./fr,sx_bytes[1][4]/1048576./fr,
(unsigned long long)sx_count[0][0],(unsigned long long)sx_count[1][0],(unsigned long long)sx_mismatch,sx_nop,sx_nev);}
memset(sx_bytes,0,sizeof(sx_bytes));memset(sx_count,0,sizeof(sx_count));
pending_folded=pending_flushed=0;
G.profile_barriers=G.profile_pass_breaks=G.profile_pipeline_binds=G.profile_set_binds=G.profile_set_writes=G.profile_temp_new=G.profile_gpu_ns=G.profile_temp_new_bytes=G.profile_temp_drop=G.profile_temp_max=0;
if(cpu_profile())fprintf(stderr,"[nvn-vulkan] RENDER_INPUT_PROFILE frame=%llu input_ms=%.3f calls=%llu cpu_MiB=%.3f gpu_MiB=%.3f max_bytes=%llu shared_reads=%llu\n",(unsigned long long)G.present_count+1,G.profile_input_ns/1e6,(unsigned long long)G.input_calls,G.input_bytes/1048576.,G.input_gpu_bytes/1048576.,(unsigned long long)G.input_max,(unsigned long long)G.input_shared);
{char line[512];size_t o=0;for(int i=0;i<WAIT_SITES;i++)o+=(size_t)snprintf(line+o,sizeof line-o," %s=%.1f/%llu",wait_names[i],G.wait_ns[i]/1e6,(unsigned long long)G.wait_n[i]);
@@ -2748,4 +3034,4 @@ int mtl_link_wait_tick(uint64_t timeout) {
}
void mtl_xv_window_tex(uint64_t serial) { (void)serial; } /* No cross-frame store-elision ledger exists. */
void mtl_ub_present(double ms) { (void)ms; } /* Disabled diagnostic experiment. */
uint64_t mtl_upload_bytes(void) { uint64_t n=0;for(int i=0;i<G.ntexture;i++)if(G.textures[i].cpu_owned)n+=(uint64_t)G.textures[i].width*G.textures[i].height*G.textures[i].bpp;return n; }
uint64_t mtl_upload_bytes(void) { return atomic_load(&g_upload_total); }
+3
View File
@@ -6,6 +6,8 @@ static PFN_vkResetFences dm_vkResetFences;
#define vkResetFences dm_vkResetFences
static PFN_vkResetCommandBuffer dm_vkResetCommandBuffer;
#define vkResetCommandBuffer dm_vkResetCommandBuffer
static PFN_vkResetCommandPool dm_vkResetCommandPool;
#define vkResetCommandPool dm_vkResetCommandPool
static PFN_vkResetDescriptorPool dm_vkResetDescriptorPool;
#define vkResetDescriptorPool dm_vkResetDescriptorPool
/* Vulkan dispatch belongs to the explicitly selected loader instance. */
@@ -302,5 +304,6 @@ static void dm_vk_resolve(VkInstance instance) {
dm_vkGetFenceStatus=(PFN_vkGetFenceStatus)dm_vk_get(instance,"vkGetFenceStatus");if(!dm_vkGetFenceStatus)die("Vulkan dispatch vkGetFenceStatus",0);
dm_vkResetFences=(PFN_vkResetFences)dm_vk_get(instance,"vkResetFences");if(!dm_vkResetFences)die("Vulkan dispatch vkResetFences",0);
dm_vkResetCommandBuffer=(PFN_vkResetCommandBuffer)dm_vk_get(instance,"vkResetCommandBuffer");if(!dm_vkResetCommandBuffer)die("Vulkan dispatch vkResetCommandBuffer",0);
dm_vkResetCommandPool=(PFN_vkResetCommandPool)dm_vk_get(instance,"vkResetCommandPool");if(!dm_vkResetCommandPool)die("Vulkan dispatch vkResetCommandPool",0);
dm_vkResetDescriptorPool=(PFN_vkResetDescriptorPool)dm_vk_get(instance,"vkResetDescriptorPool");if(!dm_vkResetDescriptorPool)die("Vulkan dispatch vkResetDescriptorPool",0);
}
@@ -333,6 +333,13 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
private static OperationResult GenerateClamp(CodeGenContext context, AstOperation operation)
{
// NaN 安全:Maxwell 的 .SAT / FMNMX 遇 NaN 取另一操作数(饱和得 0),GLSL FClamp/FMax/FMin 遇 NaN 未定义(Adreno 原样传出 NaN)
// NaN-safe: Maxwell .SAT / FMNMX take the other operand on NaN (saturate gives 0); GLSL FClamp/FMax/FMin are undefined on NaN (Adreno passes the NaN through)
if (context.HostCapabilities.NanSafeMinMax)
{
return GenerateTernary(context, operation, context.GlslNClamp, context.Delegates.GlslSClamp);
}
return GenerateTernary(context, operation, context.Delegates.GlslFClamp, context.Delegates.GlslSClamp);
}
@@ -953,6 +960,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
private static OperationResult GenerateMaximum(CodeGenContext context, AstOperation operation)
{
if (context.HostCapabilities.NanSafeMinMax)
{
return GenerateBinary(context, operation, context.GlslNMax, context.Delegates.GlslSMax);
}
return GenerateBinary(context, operation, context.Delegates.GlslFMax, context.Delegates.GlslSMax);
}
@@ -969,6 +981,11 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
private static OperationResult GenerateMinimum(CodeGenContext context, AstOperation operation)
{
if (context.HostCapabilities.NanSafeMinMax)
{
return GenerateBinary(context, operation, context.GlslNMin, context.Delegates.GlslSMin);
}
return GenerateBinary(context, operation, context.Delegates.GlslFMin, context.Delegates.GlslSMin);
}
@@ -1678,7 +1695,21 @@ namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
if (isStore)
{
context.Store(pointer, context.Get(varType, operation.GetSource(operation.SourcesCount - 1)));
SpvInstruction value = context.Get(varType, operation.GetSource(operation.SourcesCount - 1));
// 浮点颜色输出里的 NaN 换成 0(主机要求时):浮点目标里一个 NaN 像素会被降采样 / bloom 链扩成一整块
// NaN in float color outputs becomes 0 (when the host asks): one NaN pixel in a float target is spread into a whole block by downsample / bloom chains
if (context.HostCapabilities.NanFreeColorOutput &&
varType == AggregateType.FP32 &&
operation.StorageKind == StorageKind.Output &&
operation.GetSource(0) is AstOperand { Type: OperandType.Constant } ioId &&
(IoVariable)ioId.Value == IoVariable.FragmentOutputColor)
{
SpvInstruction isNan = context.IsNan(context.TypeBool(), value);
value = context.Select(context.TypeFP32(), isNan, context.Constant(context.TypeFP32(), 0f), value);
}
context.Store(pointer, value);
return OperationResult.Invalid;
}
else
@@ -184,6 +184,24 @@ namespace Ryujinx.Graphics.Shader
return false;
}
/// <summary>
/// Queries host about whether float min/max/clamp must use NaN-aware semantics (Maxwell FMNMX and .SAT never return NaN when the other operand is a number).
/// </summary>
/// <returns>True to emit NMin/NMax/NClamp instead of FMin/FMax/FClamp, false otherwise</returns>
bool QueryHostNanSafeMinMax()
{
return false;
}
/// <summary>
/// Queries host about whether NaN written to a float fragment color output must be replaced by zero (a NaN pixel in a float target is spread into a block by downsample / bloom chains).
/// </summary>
/// <returns>True to store zero instead of NaN in float fragment color outputs, false otherwise</returns>
bool QueryHostNanFreeColorOutput()
{
return false;
}
/// <summary>
/// Queries host about the presence of the FrontFacing built-in variable bug.
/// </summary>
@@ -3,6 +3,8 @@ namespace Ryujinx.Graphics.Shader.Translation
class HostCapabilities
{
public readonly bool ReducedPrecision;
public bool NanSafeMinMax;
public bool NanFreeColorOutput;
public readonly bool SupportsFragmentShaderInterlock;
public readonly bool SupportsFragmentShaderOrderingIntel;
public readonly bool SupportsGeometryShaderPassthrough;
@@ -368,6 +368,9 @@ namespace Ryujinx.Graphics.Shader.Translation
GpuAccessor.QueryHostSupportsTextureShadowLod(),
GpuAccessor.QueryHostSupportsViewportMask());
hostCapabilities.NanSafeMinMax = GpuAccessor.QueryHostNanSafeMinMax();
hostCapabilities.NanFreeColorOutput = GpuAccessor.QueryHostNanFreeColorOutput();
CodeGenParameters parameters = new CodeGenParameters(attributeUsage, definitions, resourceManager.Properties, hostCapabilities, GpuAccessor, Options.TargetApi);
return Options.TargetLanguage switch