Files
d2r-mobile/dm/gfx/vulkan/nvn_vk.c
T
shenleiandClaude Opus 5.5 3c25cd89fc Android: move the shell to dm/android and the Vulkan backend to dm/gfx/vulkan
Mirror the iOS layout instead of nesting Android inside dm/host:
- dm/android/app       GameActivity app (manifest, java, res, build_apk.sh)
- dm/android/Sources   front_app.c, touch_app.c, front_headless.c
- dm/android/Makefile  entry point (apk / lib / install / headless / tests);
                       rules in build.mk (was dm/host/Makefile.android),
                       run with dm/host as cwd; outputs in dm/android/build/
- dm/android/tests     t_vk_perf
- dm/gfx/vulkan        nvn_vk.c and friends, next to the Metal backend

Only include paths, build paths and docs change; no code changes.
The Mac / iOS source lists do not pick up gfx/vulkan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 16:59:36 +09:00

2752 lines
250 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* First Android Vulkan replay implementation for the original NVN recorder.
* This file preserves the recorder's mtl_* C interface to avoid guest changes.
* Unsupported semantics abort with a named boundary; no draw/dispatch is dropped.
* Logical NVN submissions are batched until present, wait or a CPU-visible write.
* Three fence slots own immutable uploads and transient resources until completion.
*/
#define VK_USE_PLATFORM_ANDROID_KHR
#include <vulkan/vulkan.h>
#include <android/hardware_buffer.h>
#include <vulkan/vulkan_android.h>
#include <android/native_window.h>
#include "nvn_obj.h"
#include "vk_platform.h"
#include "nvn_mtl.h"
#include "nvn_dirty.h"
#include "../tex/nvn_deswizzle.h"
#include "../tex/nvn_bcdec.h"
#include <stdatomic.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <zlib.h>
#include <math.h>
#include <dlfcn.h>
#include <unistd.h>
#include <sys/mman.h>
#include <errno.h>
#define LIMIT_POOLS 512
#define LIMIT_OBJECTS 4096
#define LIMIT_BINDINGS 64
#define SET_CACHE 4
#define LIMIT_WRITES 4096
/* 每帧约 4 次提交;3 槽会让 CPU 在同一帧内等待 GPU。| ~4 submits per frame; 3 slots made the CPU wait on its own frame. */
#define BATCH_SLOTS 8
/* 每批两个私有时间戳槽(开始/结束),位于游戏计数器之后。| Two private timestamp slots per batch (begin/end), after the guest counters. */
#define BATCH_STAMP LIMIT_WRITES
/* Driver constant table (c0): highest byte read is the sampler table end 0x968. */
#define TABLE_BYTES 0x980
#define TABLE_STRIDE 0xA00
#define TABLE_CHUNK (4u<<20)
#define CHECK(x) do { VkResult r_=(x); if(r_!=VK_SUCCESS) die(#x,(long long)r_); } while(0)
static _Noreturn void die(const char *where,long long value) {
fprintf(stderr,"[nvn-vulkan] STOP %s (%lld)\n",where,value); fflush(stderr); abort();
}
#include "nvn_vk_dispatch.h"
typedef struct { VkBuffer b; VkDeviceMemory m; uint8_t *map; uint64_t size; } VBuffer;
/* direct: the Vulkan buffer is the guest pages themselves, like newBufferWithBytesNoCopy on iOS;
* reads/writes need no staging or writeback. 1 = imported (VK_EXT_external_memory_host),
* 2 = AHardwareBuffer / exported Vulkan memory mmap'ed onto the guest address (mapped_len restores it on delete). */
typedef struct { const uint8_t *guest; uint64_t size; VBuffer v; int direct; uint64_t mapped_len; AHardwareBuffer *ahb; } VPool;
typedef struct { uint32_t set,binding,type,kind; int32_t slot,sampler; uint32_t count,flags; } RBinding;
typedef struct { uint32_t magic,version,stage,nb,na,c1n,ncap,local[3],fout,reserved; } RHeader;
typedef struct {
char key[17]; RHeader h; RBinding b[LIMIT_BINDINGS]; uint32_t attr[32][2],caps[32];
VBuffer c1; VkShaderModule module; VkDescriptorSetLayout layout; uint64_t fetch_bindings,dref_bindings;
/* 本批次最近写过的几个集,cache_words 按需分配,每项 3*nb 个字 |
* sets written recently in this batch; cache_words is allocated on first use, 3*nb words per entry */
uint64_t cache_epoch[SET_CACHE]; VkDescriptorSet cache_set[SET_CACHE]; uint64_t *cache_words; unsigned cache_last,cache_next; VkExtent2D vrs;
/* 动态偏移的缓冲单独放在 set+2:dyn_index 按 binding 号排序,dyn_off 是本次绘制的偏移;
* set / dyn_set 是本次绘制要绑定的两个集(没有对应绑定时为空)。
* Dynamic-offset buffers live in their own set (set+2): dyn_index is in binding order, dyn_off
* holds this draw's offsets; set / dyn_set are the two sets to bind (null when empty). */
uint32_t ndyn; uint8_t dyn_index[LIMIT_BINDINGS]; uint32_t dyn_off[LIMIT_BINDINGS]; uint64_t dyn_mask;
VkDescriptorSetLayout dyn_layout; VkDescriptorSet set,dyn_set; uint64_t dyn_epoch,dyn_words[2*LIMIT_BINDINGS];
} VShader;
typedef struct { uint64_t serial; tex_t source; VkImage image; VkDeviceMemory memory;
VkImageView view; VkFormat format; VkImageLayout layout; uint32_t width,height,depth,bpp; int cpu_owned; uint64_t upload_stamp,version,clean_now,clean_pools;
uint8_t *cpu_snapshot;
VkImage shadow;VkDeviceMemory shadow_memory;VkImageView shadow_view;VkFormat shadow_format;VkImageLayout shadow_layout;uint64_t shadow_version; } VTexture;
typedef struct { int live; tex_t texture; view_t view; uint8_t has_view; } TSlot;
typedef struct { int live; samp_par source; VkSampler sampler; } SSlot;
typedef struct { uint64_t addr,size; } Range;
typedef struct { volatile uint32_t *addr; uint32_t mode,value; } Event;
typedef struct { uint32_t kind,query; uint64_t address; } CounterOp;
typedef struct { Range range; VBuffer *buffer; int written; } AlignedBinding;
typedef struct { uint64_t serial; unsigned roles; } ImageUse;
typedef struct { const uint8_t *entry;uint64_t hash;int shader; } ShaderEntry; /* shader:G.shaders 下标 + 1,0 = 未加载 | index into G.shaders + 1, 0 = not loaded */
typedef struct { VBuffer *buffer;uint64_t bytes,offset;char path[1400]; } TraceCapture;
/* Keys contain effective Vulkan state only; addresses and dynamic state are excluded.
* Hash matches always require full key equality. Entries live with the device. */
typedef struct { uint32_t words[256],count; } PipelineKey;
typedef struct Pso { PipelineKey key; uint64_t hash; VkPipeline pipeline; VkPipelineLayout layout; struct Pso *next; } Pso;
typedef struct {
VkAttachmentDescription attachments[9]; VkAttachmentReference color[8],depth;
uint32_t n,ncolor,has_depth,feedback;
} PassKey;
typedef struct PassEntry { PassKey key; VkRenderPass pass; struct PassEntry *next; } PassEntry;
typedef struct FramebufferEntry {
PassEntry *pass; VkImage images[9]; VkImageSubresourceRange ranges[9];
VkImageView views[9]; VkFramebuffer framebuffer; uint32_t width,height;
struct FramebufferEntry *next;
} FramebufferEntry;
typedef struct {
const prog_t *program; p_set_rt rt; va_st attributes[16]; vs_st streams[16]; NVNbufferRange vbuf[16];
Range uniform[6][16],storage[6][16]; uint64_t tex[6][128],samp[6][128],img[6][32];
color_st color; chmask_st mask; blend_st blend[8]; poly_st polygon; ds_st ds; ms_st ms;
VkViewport viewport; VkRect2D scissor; float blend_color[4]; uint64_t copy_stride;
const dpool_t *texture_pool,*sampler_pool; Range scratch; uint32_t stencil_compare[2],stencil_write[2],stencil_ref[2];
} 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;
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;
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;
VBuffer tables[64]; unsigned ntables; uint64_t table_offset; uint64_t epoch;
struct { VkBuffer buffer; VkFormat format; uint64_t offset,range; VkBufferView view; } texel_views[512];
uint8_t table_last[6][3][TABLE_BYTES]; uint64_t table_last_offset[6][3],table_last_gen[6][3]; uint8_t table_last_valid[6][3];
/* Graphics bindings already recorded in this command buffer (DXVK-style
* redundant-bind elimination); cleared when recording begins. */
struct { VkPipeline pipeline; VkPipelineLayout layout; VkDescriptorSet sets[4]; uint32_t nsets;
VkBuffer vb[16]; uint64_t vb_offset[16]; VkBuffer ib; uint64_t ib_offset; VkIndexType ib_type;
VkViewport viewport; VkRect2D scissor; float blend[4]; int dynamic_valid; uint32_t offs[2][LIMIT_BINDINGS]; } bound;
} Batch;
static struct {
VkInstance instance; VkPhysicalDevice physical; VkDevice device; VkQueue queue; uint32_t family; VkSampler fetch_sampler;
VkPhysicalDeviceMemoryProperties memory; VkPhysicalDeviceProperties properties;
VkCommandPool command_pool; VkPipelineCache pipeline_cache;
VBuffer support,zero; VPool pools[LIMIT_POOLS]; int npool;
VShader shaders[LIMIT_OBJECTS]; int nshader; VkDescriptorSetLayout empty_layout; VTexture textures[LIMIT_OBJECTS]; int ntexture;
TSlot *tslot; size_t texture_slots; SSlot sslot[LIMIT_OBJECTS]; int texture_pool_n;
AlignedBinding aligned[2*LIMIT_BINDINGS]; int naligned;
ImageUse image_uses[2*LIMIT_BINDINGS]; unsigned nimage_uses;
uint32_t timestamp_bits; int precise_occlusion; uint64_t samples_passed;
Pso *pso[4096]; PassEntry *passes; FramebufferEntry *framebuffers,*current_fb;
char cache_path[1200]; uint64_t pso_hits,pso_misses,pass_hits,fb_hits,pso_made,pso_made_ns; _Atomic int cache_dirty;
int in_pass,active,feedback_layout,null_descriptor,depth_sampled,general_feedback; VkPipelineCreateFlags feedback_flags; ReplayState state; VkPhysicalDeviceSubgroupProperties subgroup;
uint8_t *shader_index; size_t index_bytes; char shader_root[1024]; ANativeWindow *window; int gather_extended,draw_parameters,vrs;
int wait_site;uint64_t wait_ns[10],wait_n[10],sync_lag_max,sync_cur_frame,event_queued,event_blocked;
ShaderEntry *shader_entries;size_t shader_entry_capacity;
VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkImage swap_images[8]; VkImageLayout swap_layouts[8]; VkSemaphore swap_done[8]; int swap_stale;
uint32_t nswap; VkFormat swap_format; VkExtent2D swap_extent; int display_hz;
_Atomic uint64_t fence,completed,present_count; uint64_t draws,pass_count,uploads,pool_adds,pool_epoch,frame;
int trace_frame,trace_ui;_Atomic int window_origin;
uint64_t profile_pipeline_ns,profile_wait_ns,profile_decode_ns,profile_submits,profile_start_ns,profile_draws,profile_frames;
uint64_t profile_passes,profile_pso_hits,profile_pso_misses,profile_pass_hits,profile_fb_hits;
uint64_t profile_input_ns,input_calls,input_bytes,input_max,input_gpu_bytes,input_shared;
uint64_t profile_lookup_ns,profile_pool_ns,profile_bind_ns,profile_render_ns,profile_present_ns;unsigned trace_meshes;
unsigned ntrace_textures;uint64_t trace_texture_serials[24];
Batch batches[BATCH_SLOTS],*batch; unsigned next_batch; int synchronous; int display_timing; uint64_t bind_gen[6]; uint64_t present_called[64];
uint64_t frame_fences[3],frame_tickets[3],batch_count;
pthread_cond_t completion;
pthread_mutex_t lock;
void *transfer_memory; size_t transfer_size; int graphics_live;
int host_import; uint64_t import_align; PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties; uint64_t direct_bytes; PFN_vkGetMemoryFdKHR get_memory_fd; PFN_vkGetAndroidHardwareBufferPropertiesANDROID get_ahb_properties;
int counting; int32_t query_active;
uint64_t profile_barriers,profile_pass_breaks,profile_pipeline_binds,profile_set_binds,profile_set_writes,profile_temp_new,profile_gpu_ns,gpu_last_end,profile_temp_new_bytes,profile_temp_drop,profile_temp_max;
} G={.lock=PTHREAD_MUTEX_INITIALIZER,.completion=PTHREAD_COND_INITIALIZER};
/* 阻塞等待按来源记账(WAIT_PROFILE 行):查 CPU 为何停下来等 GPU。| Blocking waits accounted by origin (WAIT_PROFILE line): why the CPU stops for the GPU. */
enum { WAIT_SYNC,WAIT_EVENT,WAIT_PRESENT,WAIT_SLOT,WAIT_READTEX,WAIT_TEXREL,WAIT_SAMPLER,WAIT_POOLDEL,WAIT_FINISH,WAIT_CAPTURE,WAIT_SITES };
static const char *const wait_names[WAIT_SITES]={"sync","event","present","slot","readtex","texrel","sampler","pooldel","finish","capture"};
static void *completion_worker(void *unused);
static void flush_locked(void);
static void drain_locked(void);
static int retire_locked(Batch *batch,uint64_t timeout);
static pthread_once_t init_once=PTHREAD_ONCE_INIT;
static VkDebugUtilsMessengerEXT validation_messenger;
static VKAPI_ATTR VkBool32 VKAPI_CALL validation_message(VkDebugUtilsMessageSeverityFlagBitsEXT severity,VkDebugUtilsMessageTypeFlagsEXT type,const VkDebugUtilsMessengerCallbackDataEXT *data,void *user) {
(void)type;(void)user;
static struct {int32_t id;unsigned count;} seen[128];static unsigned count;
unsigned i=0;while(i<count && seen[i].id!=data->messageIdNumber)i++;
if(i==count){if(count==128)return VK_FALSE;seen[count++].id=data->messageIdNumber;}
if(seen[i].count++<10)fprintf(stderr,"[nvn-vulkan] VALIDATION severity=%#x draw=%llu id=%s message=%s\n",severity,(unsigned long long)G.draws,data->pMessageIdName?data->pMessageIdName:"unknown",data->pMessage);
return VK_FALSE;
}
static uint32_t memory_type(uint32_t mask,VkMemoryPropertyFlags properties) {
for(uint32_t i=0;i<G.memory.memoryTypeCount;i++) if((mask&(1u<<i)) &&
(G.memory.memoryTypes[i].propertyFlags&properties)==properties) return i;
die("memory type",properties);
}
static VBuffer buffer_create(uint64_t size,VkBufferUsageFlags usage,int zero) {
VBuffer b={.size=size}; if(!size || size>SIZE_MAX) die("buffer size",size);
VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.size=size,.usage=usage,
.sharingMode=VK_SHARING_MODE_EXCLUSIVE}; CHECK(vkCreateBuffer(G.device,&info,NULL,&b.b));
VkMemoryRequirements r; vkGetBufferMemoryRequirements(G.device,b.b,&r);
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=r.size,
.memoryTypeIndex=memory_type(r.memoryTypeBits,VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)};
CHECK(vkAllocateMemory(G.device,&a,NULL,&b.m)); CHECK(vkBindBufferMemory(G.device,b.b,b.m,0));
void *mapped=NULL; CHECK(vkMapMemory(G.device,b.m,0,size,0,&mapped)); b.map=mapped;if(zero)memset(b.map,0,size);return b;
}
static VBuffer buffer_make(uint64_t size,VkBufferUsageFlags usage) { return buffer_create(size,usage,1); }
static void buffer_free(VBuffer *b) {
if(b->map) vkUnmapMemory(G.device,b->m); if(b->b) vkDestroyBuffer(G.device,b->b,NULL);
if(b->m) vkFreeMemory(G.device,b->m,NULL); memset(b,0,sizeof(*b));
}
/* Transient buffers recycle through power-of-two classes: allocating, mapping
* and zeroing fresh device memory cost ~6x the copy itself on Adreno. Every
* caller fully writes the bytes it reads, so recycled contents are not cleared. */
#define TEMPORARY_USAGE (VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT|VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT| \
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_VERTEX_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT|VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)
#define TEMPORARY_MIN_CLASS 12
#define TEMPORARY_CLASSES 20
static struct { VBuffer **free; size_t n,capacity; } temporary_free[TEMPORARY_CLASSES];
static uint64_t temporary_free_bytes,temporary_keep_bytes=128ull<<20;
static unsigned temporary_class(uint64_t size) {
unsigned c=TEMPORARY_MIN_CLASS;while(c<TEMPORARY_MIN_CLASS+TEMPORARY_CLASSES && (1ull<<c)<size)c++;return c;
}
static void temporary_release(VBuffer *b) {
unsigned c=temporary_class(b->size);
if((1ull<<c)!=b->size || c>=TEMPORARY_MIN_CLASS+TEMPORARY_CLASSES || temporary_free_bytes+b->size>temporary_keep_bytes){G.profile_temp_drop++;buffer_free(b);free(b);return;}
c-=TEMPORARY_MIN_CLASS;if(temporary_free[c].n==temporary_free[c].capacity){size_t count=temporary_free[c].capacity?temporary_free[c].capacity*2:16;
VBuffer **entries=realloc(temporary_free[c].free,count*sizeof(*entries));if(!entries)die("temporary free list allocation",count);temporary_free[c].free=entries;temporary_free[c].capacity=count;}
temporary_free[c].free[temporary_free[c].n++]=b;temporary_free_bytes+=b->size;
}
static VBuffer *temporary(uint64_t size,VkBufferUsageFlags usage) {
if(usage&~(VkBufferUsageFlags)TEMPORARY_USAGE)die("temporary buffer usage",usage);
if((size_t)G.batch->ntemporary==G.batch->temporary_capacity){size_t count=G.batch->temporary_capacity?G.batch->temporary_capacity*2:256;
VBuffer **entries=realloc(G.batch->temporaries,count*sizeof(*entries));if(!entries)die("temporary buffer registry allocation",count);G.batch->temporaries=entries;G.batch->temporary_capacity=count;}
unsigned c=temporary_class(size);VBuffer *b=NULL;
if(c<TEMPORARY_MIN_CLASS+TEMPORARY_CLASSES){size=1ull<<c;c-=TEMPORARY_MIN_CLASS;
if(temporary_free[c].n){b=temporary_free[c].free[--temporary_free[c].n];temporary_free_bytes-=b->size;}}
if(!b){G.profile_temp_new++;G.profile_temp_new_bytes+=size;if(size>G.profile_temp_max)G.profile_temp_max=size;b=malloc(sizeof(*b));if(!b)die("temporary buffer allocation",size);*b=buffer_create(size,TEMPORARY_USAGE,0);}
G.batch->temporaries[G.batch->ntemporary++]=b;return b;
}
static void trace_capture_queue(VBuffer *buffer,uint64_t bytes,const char *name) {
const char *root=getenv("DM_FRAME_DIR");if(!root)return;
if(G.batch->ntrace_captures==512)die("GPU trace capture capacity",512);
TraceCapture *c=&G.batch->trace_captures[G.batch->ntrace_captures++];c->buffer=buffer;c->bytes=bytes;c->offset=0;
snprintf(c->path,sizeof(c->path),"%s/%s.bin",root,name);
}
static void trace_capture_complete(void) {
for(unsigned i=0;i<G.batch->ntrace_captures;i++){TraceCapture *c=&G.batch->trace_captures[i];FILE *out=fopen(c->path,"wb");if(!out)die("GPU trace output",0);
if(fwrite(c->buffer->map+c->offset,1,c->bytes,out)!=c->bytes)die("GPU trace write",c->bytes);fclose(out);
fprintf(stderr,"[nvn-vulkan] GPU_TRACE_CAPTURE bytes=%llu path=%s\n",(unsigned long long)c->bytes,c->path);
}
G.batch->ntrace_captures=0;
}
void dm_vk_set_shader_root(const char *path) {
if(!path || strlen(path)>=sizeof(G.shader_root) || G.nshader) die("shader root change",0);
strcpy(G.shader_root,path);
}
void mtl_set_window_origin_mode(int mode) {
if(mode!=NVN_WINDOW_ORIGIN_MODE_LOWER_LEFT&&mode!=NVN_WINDOW_ORIGIN_MODE_UPPER_LEFT)die("NVN window origin mode",mode);
atomic_store(&G.window_origin,mode);
fprintf(stderr,"[nvn-vulkan] WINDOW_ORIGIN mode=%d negative_viewport=%d\n",mode,mode==NVN_WINDOW_ORIGIN_MODE_UPPER_LEFT);
}
/* 每次 draw 都要对管线键求哈希:按 8 字节一块混合,逐字节 FNV 曾是热点 | hashed per draw over the pipeline key: mix 8-byte blocks, byte-wise FNV was a hot spot */
static uint64_t state_hash(const void *data,size_t size) {
const uint8_t *p=data;uint64_t h=14695981039346656037ULL^size,w;
for(;size>=8;size-=8,p+=8){memcpy(&w,p,8);h=(h^w)*0x9e3779b97f4a7c15ULL;h^=h>>29;}
if(size){w=0;memcpy(&w,p,size);h=(h^w)*0x9e3779b97f4a7c15ULL;h^=h>>29;}
return h;
}
/* DM_VK_CPU_PROFILE=1:每 60 帧打印 RENDER_CPU_PROFILE / RENDER_INPUT_PROFILE;关闭时热路径不读时钟(每帧上万次)
* DM_VK_CPU_PROFILE=1: print RENDER_CPU_PROFILE / RENDER_INPUT_PROFILE every 60 frames; off, the hot paths skip the clock (tens of thousands of reads per frame) */
static int cpu_profile(void){static int t=-1;if(t<0){const char *e=getenv("DM_VK_CPU_PROFILE");t=e&&*e=='1';}return t;}
static uint64_t prof_ns(void){return cpu_profile()?dm_android_nvn_clock_ns():0;}
static void key_word(PipelineKey *key,uint32_t word) {
if(key->count==256)die("pipeline key capacity",key->count);key->words[key->count++]=word;
}
static Pso *pso_find(const PipelineKey *key,uint64_t hash) {
for(Pso *p=G.pso[hash%4096];p;p=p->next)
if(p->hash==hash && p->key.count==key->count && !memcmp(p->key.words,key->words,key->count*4)){G.pso_hits++;return p;}
G.pso_misses++;return NULL;
}
static Pso *pso_insert(const PipelineKey *key,uint64_t hash) {
Pso *p=calloc(1,sizeof(*p));if(!p)die("pipeline cache allocation",0);
p->key=*key;p->hash=hash;p->next=G.pso[hash%4096];G.pso[hash%4096]=p;G.cache_dirty=1;return p;
}
/* 管线缓存落盘:OnePlus 上缓存 5 MB+,取数据 + 写文件在出图线程上会卡一帧(野外新怪 / 新特效时每 60 帧一次)。
* 平时交给后台线程写(VkPipelineCache 自带内部同步),且至少隔 30 s;收尾(finish_at / 退出)仍同步写。
* Pipeline cache save: the cache is 5 MB+ on OnePlus; fetching it and writing the file on the present thread stalls a frame (every 60 frames
* while new monsters / effects appear in the field). Normally a background thread writes it (VkPipelineCache is internally synchronized), at most
* once per 30 s; shutdown paths (finish_at / exit) still write synchronously. */
/* 长帧日志的「新建管线」:提交线程上同步新建的渲染 + 计算管线(Vulkan 没有着色器库这一级,lib 记 0)
* "New pipelines" in the long-frame log: render + compute pipelines created synchronously on the submit thread (Vulkan has no shader-library level, lib is 0) */
void mtl_create_stats(uint64_t *lib, uint64_t *pso) { *lib = 0; *pso = G.pso_made; }
void mtl_create_ns(uint64_t *lib_ns, uint64_t *pso_ns) { *lib_ns = 0; *pso_ns = G.pso_made_ns; }
static _Atomic int cache_saving;
static void pipeline_cache_write(void) {
uint64_t t0=dm_android_nvn_clock_ns();
G.cache_dirty=0; /* 先清:写的过程中新建的管线留到下一次 | clear first: pipelines created during the write go to the next save */
size_t size=0;VkResult r=vkGetPipelineCacheData(G.device,G.pipeline_cache,&size,NULL);
if(r!=VK_SUCCESS || !size || size>64*1024*1024){G.cache_dirty=1;return;}
void *data=malloc(size);if(!data){G.cache_dirty=1;return;}
r=vkGetPipelineCacheData(G.device,G.pipeline_cache,&size,data);
char path[1280];snprintf(path,sizeof(path),"%s.tmp.%ld",G.cache_path,(long)getpid());
FILE *f=r==VK_SUCCESS?fopen(path,"wb"):NULL;int ok=0;
if(f){ok=fwrite(data,1,size,f)==size;if(fclose(f))ok=0;
if(!ok || rename(path,G.cache_path)){ok=0;unlink(path);}}
if(!ok)G.cache_dirty=1;
free(data);
fprintf(stderr,"[nvn-vulkan] pipeline_cache_save bytes=%zu ms=%.1f ok=%d\n",size,(dm_android_nvn_clock_ns()-t0)/1e6,ok);
}
static void *pipeline_cache_thread(void *arg) { (void)arg;pipeline_cache_write();atomic_store(&cache_saving,0);return NULL; }
static void pipeline_cache_save(void) { /* 同步 | synchronous */
if(!G.pipeline_cache || !G.cache_path[0] || !G.cache_dirty)return;
while(atomic_load(&cache_saving))usleep(1000);
pipeline_cache_write();
}
static void pipeline_cache_save_async(void) {
static uint64_t last;uint64_t now=dm_android_nvn_clock_ns();
if(!G.pipeline_cache || !G.cache_path[0] || !G.cache_dirty || now-last<30000000000ull)return;
int expect=0;if(!atomic_compare_exchange_strong(&cache_saving,&expect,1))return;
last=now;pthread_t th;pthread_attr_t a;pthread_attr_init(&a);pthread_attr_setdetachstate(&a,PTHREAD_CREATE_DETACHED);
if(pthread_create(&th,&a,pipeline_cache_thread,NULL))atomic_store(&cache_saving,0);
pthread_attr_destroy(&a);
}
static void pipeline_cache_init(void) {
const char *path=getenv("DM_VK_PIPELINE_CACHE");
if(path && strlen(path)<sizeof(G.cache_path))strcpy(G.cache_path,path);
else if(G.shader_root[0])snprintf(G.cache_path,sizeof(G.cache_path),"%s/pipeline-%08x-%08x-%08x.bin",G.shader_root,G.properties.vendorID,G.properties.deviceID,G.properties.driverVersion);
void *data=NULL;size_t size=0;FILE *f=G.cache_path[0]?fopen(G.cache_path,"rb"):NULL;
if(f){if(!fseek(f,0,SEEK_END)){long bytes=ftell(f);if(bytes>=32 && bytes<=64*1024*1024){
rewind(f);data=malloc(bytes);if(data && fread(data,1,bytes,f)==(size_t)bytes)size=bytes;}}
fclose(f);}
/* Android is little endian, as is the Vulkan cache header. Reject stale or
* foreign blobs before passing driver-owned bytes to the implementation. */
if(size){uint32_t header[4];memcpy(header,data,16);
if(header[0]<32 || header[0]>size || header[1]!=VK_PIPELINE_CACHE_HEADER_VERSION_ONE ||
header[2]!=G.properties.vendorID || header[3]!=G.properties.deviceID ||
memcmp((uint8_t *)data+16,G.properties.pipelineCacheUUID,VK_UUID_SIZE))size=0;}
VkPipelineCacheCreateInfo ci={.sType=VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO,.initialDataSize=size,.pInitialData=size?data:NULL};
VkResult r=vkCreatePipelineCache(G.device,&ci,NULL,&G.pipeline_cache);
if(r!=VK_SUCCESS){ci.initialDataSize=0;ci.pInitialData=NULL;CHECK(vkCreatePipelineCache(G.device,&ci,NULL,&G.pipeline_cache));}
fprintf(stderr,"[nvn-vulkan] pipeline_cache_load bytes=%zu path=%s\n",size,G.cache_path);free(data);
}
static void framebuffer_cache_clear(void) {
while(G.framebuffers){FramebufferEntry *f=G.framebuffers;G.framebuffers=f->next;
vkDestroyFramebuffer(G.device,f->framebuffer,NULL);
for(unsigned i=0;i<f->pass->key.n;i++)vkDestroyImageView(G.device,f->views[i],NULL);free(f);}
G.current_fb=NULL;
}
static void backend_init(void) {
void *loader=NULL;
/* 无头 / 命令行:着色器运行包目录取 DM_VK_SHADERS | headless / command line: shader runtime pack directory from DM_VK_SHADERS */
const char *shader_root=getenv("DM_VK_SHADERS");if(!G.shader_root[0] && shader_root)dm_vk_set_shader_root(shader_root);
const char *private_driver=getenv("DM_PRIVATE_VULKAN");
if(private_driver && !strcmp(private_driver,"turnip")) {
Dl_info info;char directory[1024];
if(!dladdr((void *)backend_init,&info) || !info.dli_fname || strlen(info.dli_fname)>=sizeof(directory))die("private Vulkan native library directory",0);
strcpy(directory,info.dli_fname);char *slash=strrchr(directory,'/');if(!slash)die("private Vulkan native path",0);slash[1]=0;
char tool_path[1100];snprintf(tool_path,sizeof tool_path,"%slibadrenotools.so",directory);
void *tool=dlopen(tool_path,RTLD_NOW|RTLD_LOCAL);if(!tool)die("private Vulkan adrenotools load",0);
void *(*open_driver)(int,int,const char *,const char *,const char *,const char *,const char *,void **)=dlsym(tool,"adrenotools_open_libvulkan");
if(!open_driver)die("private Vulkan driver entry",0);
loader=open_driver(RTLD_NOW|RTLD_LOCAL,1,NULL,directory,directory,"libd2r_turnip.so",NULL,NULL);
if(!loader)die("private Vulkan loader failed",0);
}else loader=dlopen("libvulkan.so",RTLD_NOW|RTLD_LOCAL);
if(!loader)die("Vulkan loader unavailable",0);
dm_vk_get=(PFN_vkGetInstanceProcAddr)dlsym(loader,"vkGetInstanceProcAddr");if(!dm_vk_get)die("Vulkan proc address unavailable",0);
dm_vkCreateInstance=(PFN_vkCreateInstance)dm_vk_get(NULL,"vkCreateInstance");if(!dm_vkCreateInstance)die("Vulkan create instance unavailable",0);
VkApplicationInfo app={.sType=VK_STRUCTURE_TYPE_APPLICATION_INFO,.pApplicationName="D2R Android",.apiVersion=VK_API_VERSION_1_1};
int validation=getenv("DM_VULKAN_VALIDATION")!=NULL;
const char *ie[]={VK_KHR_SURFACE_EXTENSION_NAME,VK_KHR_ANDROID_SURFACE_EXTENSION_NAME,VK_EXT_DEBUG_UTILS_EXTENSION_NAME};
const char *layers[]={"VK_LAYER_KHRONOS_validation"};
VkDebugUtilsMessengerCreateInfoEXT debug={.sType=VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT,
.messageSeverity=VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT|VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT,
.messageType=VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT|VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT|VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT,.pfnUserCallback=validation_message};
VkInstanceCreateInfo ii={.sType=VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,.pApplicationInfo=&app,
.enabledExtensionCount=validation?3u:2u,.ppEnabledExtensionNames=ie,.enabledLayerCount=validation?1u:0u,.ppEnabledLayerNames=validation?layers:NULL,.pNext=validation?&debug:NULL}; CHECK(vkCreateInstance(&ii,NULL,&G.instance));
if(validation){PFN_vkCreateDebugUtilsMessengerEXT create=(PFN_vkCreateDebugUtilsMessengerEXT)dm_vk_get(G.instance,"vkCreateDebugUtilsMessengerEXT");if(!create)die("validation debug messenger unavailable",0);CHECK(create(G.instance,&debug,NULL,&validation_messenger));fprintf(stderr,"[nvn-vulkan] VALIDATION_ENABLED\n");}
dm_vk_resolve(G.instance);
uint32_t n=0; CHECK(vkEnumeratePhysicalDevices(G.instance,&n,NULL)); if(!n) die("Vulkan physical device",0);
VkPhysicalDevice *physical=calloc(n,sizeof(*physical)); if(!physical) die("allocate physical list",n);
CHECK(vkEnumeratePhysicalDevices(G.instance,&n,physical)); G.physical=physical[0]; free(physical);
vkGetPhysicalDeviceProperties(G.physical,&G.properties); vkGetPhysicalDeviceMemoryProperties(G.physical,&G.memory);
G.subgroup=(VkPhysicalDeviceSubgroupProperties){.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_PROPERTIES};
VkPhysicalDeviceDriverProperties driver_properties={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES,.pNext=&G.subgroup};
VkPhysicalDeviceProperties2 properties2={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,.pNext=&driver_properties};
vkGetPhysicalDeviceProperties2(G.physical,&properties2);
if(private_driver && !strcmp(private_driver,"turnip") && driver_properties.driverID!=VK_DRIVER_ID_MESA_TURNIP)die("requested private driver was not loaded",driver_properties.driverID);
fprintf(stderr,"[nvn-vulkan] driver id=%u name=%s info=%s\n",driver_properties.driverID,driver_properties.driverName,driver_properties.driverInfo);
fprintf(stderr,"[nvn-vulkan] subgroup size=%u stages=%#x operations=%#x\n",G.subgroup.subgroupSize,G.subgroup.supportedStages,G.subgroup.supportedOperations);
vkGetPhysicalDeviceQueueFamilyProperties(G.physical,&n,NULL);
VkQueueFamilyProperties *families=calloc(n,sizeof(*families)); if(!families) die("queue list",n);
vkGetPhysicalDeviceQueueFamilyProperties(G.physical,&n,families); G.family=UINT32_MAX;
for(uint32_t i=0;i<n;i++) {
if((families[i].queueFlags&(VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT))==
(VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT)) { G.family=i; break; }
}
free(families);
if(G.family==UINT32_MAX) die("graphics/compute queue",0);
float priority=1; VkDeviceQueueCreateInfo qi={.sType=VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.queueFamilyIndex=G.family,.queueCount=1,.pQueuePriorities=&priority};
const char *de[]={VK_KHR_SWAPCHAIN_EXTENSION_NAME,VK_EXT_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_EXTENSION_NAME};
PFN_vkEnumerateDeviceExtensionProperties enumerate_extensions=(PFN_vkEnumerateDeviceExtensionProperties)dm_vk_get(G.instance,"vkEnumerateDeviceExtensionProperties");
uint32_t extension_count=0;CHECK(enumerate_extensions(G.physical,NULL,&extension_count,NULL));
VkExtensionProperties *extension_properties=calloc(extension_count,sizeof(*extension_properties));if(!extension_properties)die("device extension allocation",extension_count);
CHECK(enumerate_extensions(G.physical,NULL,&extension_count,extension_properties));int has_feedback=0,has_host=0,has_fd=0,has_ahb=0,has_foreign=0,has_shading_rate=0,has_renderpass2=0,has_timing=0,has_robust2=0;
if(getenv("DM_VK_LIST_EXTENSIONS")){for(uint32_t i=0;i<extension_count;i++)fprintf(stderr,"[nvn-vulkan] EXT %s\n",extension_properties[i].extensionName);
PFN_vkGetPhysicalDeviceExternalBufferProperties ebp=(PFN_vkGetPhysicalDeviceExternalBufferProperties)dm_vk_get(G.instance,"vkGetPhysicalDeviceExternalBufferProperties");
for(unsigned bit=0;ebp && bit<12;bit++){VkPhysicalDeviceExternalBufferInfo bi={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO,.usage=VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT,.handleType=1u<<bit};
VkExternalBufferProperties ep={.sType=VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES};ebp(G.physical,&bi,&ep);
fprintf(stderr,"[nvn-vulkan] EXTBUF handle=%#x features=%#x export_from=%#x compatible=%#x\n",1u<<bit,ep.externalMemoryProperties.externalMemoryFeatures,ep.externalMemoryProperties.exportFromImportedHandleTypes,ep.externalMemoryProperties.compatibleHandleTypes);}
for(uint32_t i=0;i<G.memory.memoryTypeCount;i++)fprintf(stderr,"[nvn-vulkan] MEMTYPE %u flags=%#x heap=%u\n",i,G.memory.memoryTypes[i].propertyFlags,G.memory.memoryTypes[i].heapIndex);}
for(uint32_t i=0;i<extension_count;i++){has_feedback|=!strcmp(extension_properties[i].extensionName,de[1]);
has_host|=!strcmp(extension_properties[i].extensionName,VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME);
has_fd|=!strcmp(extension_properties[i].extensionName,VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME);
has_ahb|=!strcmp(extension_properties[i].extensionName,VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME);
has_foreign|=!strcmp(extension_properties[i].extensionName,VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
has_shading_rate|=!strcmp(extension_properties[i].extensionName,VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME);
has_renderpass2|=!strcmp(extension_properties[i].extensionName,VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME);
has_timing|=!strcmp(extension_properties[i].extensionName,VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME);
has_robust2|=!strcmp(extension_properties[i].extensionName,VK_EXT_ROBUSTNESS_2_EXTENSION_NAME);}free(extension_properties);
if(getenv("DM_VK_POOL_COPY"))has_host=has_fd=has_ahb=0;
if(getenv("DM_VK_POOL_OPAQUE_FD"))has_ahb=0;
has_ahb&=has_foreign;
if(has_host){VkPhysicalDeviceExternalMemoryHostPropertiesEXT host={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
VkPhysicalDeviceProperties2 p2={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2,.pNext=&host};vkGetPhysicalDeviceProperties2(G.physical,&p2);
G.import_align=host.minImportedHostPointerAlignment;}
int has_vrs=has_shading_rate && has_renderpass2 && getenv("DM_VK_VRS");
VkPhysicalDeviceFragmentShadingRateFeaturesKHR shading_rate={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR};
VkPhysicalDeviceAttachmentFeedbackLoopLayoutFeaturesEXT feedback={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ATTACHMENT_FEEDBACK_LOOP_LAYOUT_FEATURES_EXT,.pNext=has_vrs?&shading_rate:NULL};
VkPhysicalDeviceShaderDrawParametersFeatures draw_parameters={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES,.pNext=has_feedback?(void *)&feedback:has_vrs?(void *)&shading_rate:NULL};
/* 空描述符(VK_EXT_robustness2 nullDescriptor):着色器声明了、游戏却没绑的贴图槽写空视图——读出 0、写入丢弃,同 iOS 的哑贴图(nvn_mtl.m dummy_tex)。
* 只开 nullDescriptor,不开 robustBufferAccess2 / robustImageAccess2(那两个有越界检查开销)。
* Null descriptors (VK_EXT_robustness2 nullDescriptor): texture slots a shader declares but the game left unbound get a null view -- reads return 0, writes are
* discarded, like the iOS dummy textures (nvn_mtl.m dummy_tex). Only nullDescriptor is enabled, not robustBufferAccess2 / robustImageAccess2 (those add bounds checks). */
VkPhysicalDeviceRobustness2FeaturesEXT robust2={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT,.pNext=&draw_parameters};
{VkPhysicalDeviceFeatures2 features={.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2,.pNext=has_robust2?(void *)&robust2:(void *)&draw_parameters};
PFN_vkGetPhysicalDeviceFeatures2 get_features=(PFN_vkGetPhysicalDeviceFeatures2)dm_vk_get(G.instance,"vkGetPhysicalDeviceFeatures2");get_features(G.physical,&features);}
G.feedback_layout=has_feedback && feedback.attachmentFeedbackLoopLayout;
G.null_descriptor=has_robust2 && robust2.nullDescriptor;
robust2=(VkPhysicalDeviceRobustness2FeaturesEXT){.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT,.pNext=&draw_parameters,.nullDescriptor=VK_TRUE};
/* 1839 个着色器声明 DrawParameters(gl_BaseInstance 等)| 1839 shaders declare DrawParameters (gl_BaseInstance etc.) */
G.draw_parameters=draw_parameters.shaderDrawParameters;
G.vrs=has_vrs && shading_rate.pipelineFragmentShadingRate;
shading_rate=(VkPhysicalDeviceFragmentShadingRateFeaturesKHR){.sType=VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADING_RATE_FEATURES_KHR,.pipelineFragmentShadingRate=VK_TRUE};
feedback.pNext=G.vrs?&shading_rate:NULL;
draw_parameters.pNext=G.feedback_layout?(void *)&feedback:G.vrs?(void *)&shading_rate:NULL;
VkPhysicalDeviceFeatures available,enabled={0}; vkGetPhysicalDeviceFeatures(G.physical,&available);
enabled.shaderStorageImageReadWithoutFormat=available.shaderStorageImageReadWithoutFormat;
enabled.shaderStorageImageWriteWithoutFormat=available.shaderStorageImageWriteWithoutFormat;
enabled.shaderImageGatherExtended=available.shaderImageGatherExtended;G.gather_extended=available.shaderImageGatherExtended;
enabled.samplerAnisotropy=available.samplerAnisotropy;
enabled.imageCubeArray=available.imageCubeArray;
enabled.occlusionQueryPrecise=available.occlusionQueryPrecise;
if(!available.independentBlend)die("NVN independent attachment blending unavailable",0);
enabled.independentBlend=VK_TRUE;
enabled.fragmentStoresAndAtomics=available.fragmentStoresAndAtomics;
enabled.vertexPipelineStoresAndAtomics=available.vertexPipelineStoresAndAtomics;
G.precise_occlusion=enabled.occlusionQueryPrecise;
vkGetPhysicalDeviceQueueFamilyProperties(G.physical,&n,NULL);
families=calloc(n,sizeof(*families));if(!families)die("timestamp queue properties",n);
vkGetPhysicalDeviceQueueFamilyProperties(G.physical,&n,families);G.timestamp_bits=families[G.family].timestampValidBits;free(families);
const char *enabled_extensions[10]={de[0]};uint32_t nenabled=1;
if(G.feedback_layout)enabled_extensions[nenabled++]=de[1];
if(has_host)enabled_extensions[nenabled++]=VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME;
if(has_fd)enabled_extensions[nenabled++]=VK_KHR_EXTERNAL_MEMORY_FD_EXTENSION_NAME;
if(has_ahb){enabled_extensions[nenabled++]=VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;enabled_extensions[nenabled++]=VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;}
if(G.vrs){enabled_extensions[nenabled++]=VK_KHR_CREATE_RENDERPASS_2_EXTENSION_NAME;enabled_extensions[nenabled++]=VK_KHR_FRAGMENT_SHADING_RATE_EXTENSION_NAME;}
/* DM_VK_DISPLAY_TIMING=1:读每帧真实上屏时刻(VK_GOOGLE_display_timing),每 300 帧一行「上屏间隔」——CPU 端的帧间隔看不出画面停了几拍
* DM_VK_DISPLAY_TIMING=1: read each frame's real on-screen time (VK_GOOGLE_display_timing) and log a "display interval" line every 300 frames -- CPU-side frame intervals cannot show how many vsyncs a picture stayed up */
G.display_timing=has_timing && getenv("DM_VK_DISPLAY_TIMING") && atoi(getenv("DM_VK_DISPLAY_TIMING"));
if(G.display_timing)enabled_extensions[nenabled++]=VK_GOOGLE_DISPLAY_TIMING_EXTENSION_NAME;
if(G.null_descriptor)enabled_extensions[nenabled++]=VK_EXT_ROBUSTNESS_2_EXTENSION_NAME;
VkDeviceCreateInfo di={.sType=VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,.queueCreateInfoCount=1,.pQueueCreateInfos=&qi,
.enabledExtensionCount=nenabled,.ppEnabledExtensionNames=enabled_extensions,.pEnabledFeatures=&enabled,.pNext=G.null_descriptor?(void *)&robust2:(void *)&draw_parameters}; CHECK(vkCreateDevice(G.physical,&di,NULL,&G.device));
if(has_host){PFN_vkGetDeviceProcAddr device_proc=(PFN_vkGetDeviceProcAddr)dm_vk_get(G.instance,"vkGetDeviceProcAddr");
G.get_host_pointer_properties=device_proc?(PFN_vkGetMemoryHostPointerPropertiesEXT)device_proc(G.device,"vkGetMemoryHostPointerPropertiesEXT"):NULL;
G.host_import=G.get_host_pointer_properties!=NULL && G.import_align && !(G.import_align&(G.import_align-1));}
if(has_fd && !G.host_import){PFN_vkGetDeviceProcAddr device_proc=(PFN_vkGetDeviceProcAddr)dm_vk_get(G.instance,"vkGetDeviceProcAddr");
G.get_memory_fd=device_proc?(PFN_vkGetMemoryFdKHR)device_proc(G.device,"vkGetMemoryFdKHR"):NULL;}
if(has_ahb && !G.host_import){PFN_vkGetDeviceProcAddr device_proc=(PFN_vkGetDeviceProcAddr)dm_vk_get(G.instance,"vkGetDeviceProcAddr");
G.get_ahb_properties=device_proc?(PFN_vkGetAndroidHardwareBufferPropertiesANDROID)device_proc(G.device,"vkGetAndroidHardwareBufferPropertiesANDROID"):NULL;}
if(TABLE_STRIDE%G.properties.limits.minUniformBufferOffsetAlignment || G.properties.limits.maxUniformBufferRange<65536)die("driver table alignment/range",G.properties.limits.minUniformBufferOffsetAlignment);
fprintf(stderr,"[nvn-vulkan] host_import=%d align=%llu fd_remap=%d ahb_remap=%d\n",G.host_import,(unsigned long long)G.import_align,G.get_memory_fd!=NULL,G.get_ahb_properties!=NULL);G.query_active=-1;
fprintf(stderr,"[nvn-vulkan] attachment_feedback_layout=%d independent_blend=%u fragment_stores=%u draw_parameters=%d gather_extended=%d vrs=%d null_descriptor=%d\n",G.feedback_layout,enabled.independentBlend,enabled.fragmentStoresAndAtomics,G.draw_parameters,G.gather_extended,G.vrs,G.null_descriptor);
vkGetDeviceQueue(G.device,G.family,0,&G.queue);
if(!getenv("DM_DISABLE_PIPELINE_CACHE"))pipeline_cache_init();
fprintf(stderr,"[nvn-vulkan] driver_pipeline_cache=%d\n",G.pipeline_cache!=VK_NULL_HANDLE);
VkCommandPoolCreateInfo ci={.sType=VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,.queueFamilyIndex=G.family,
.flags=VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT}; CHECK(vkCreateCommandPool(G.device,&ci,NULL,&G.command_pool));
G.support=buffer_make(1392,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); G.zero=buffer_make(65536,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
for(int i=0;i<73;i++) { float one=1; memcpy(G.support.map+192+16*i,&one,4); }
G.state.mask.mask=UINT32_MAX; G.state.polygon.mode=NVN_POLYGON_MODE_FILL;
G.state.color.logic_op=NVN_LOGIC_OP_COPY;G.state.color.alpha_func=NVN_ALPHA_FUNC_ALWAYS;
G.state.ds.df=NVN_DEPTH_FUNC_LESS; G.state.viewport=(VkViewport){0,0,1,1,0,1};
G.state.ds.sf_f=G.state.ds.sf_b=NVN_STENCIL_FUNC_ALWAYS;
G.state.ds.fail_f=G.state.ds.fail_b=G.state.ds.zfail_f=G.state.ds.zfail_b=G.state.ds.zpass_f=G.state.ds.zpass_b=NVN_STENCIL_OP_KEEP;
G.state.stencil_compare[0]=G.state.stencil_compare[1]=G.state.stencil_write[0]=G.state.stencil_write[1]=UINT32_MAX;
fprintf(stderr,"[nvn-vulkan] initialized %s\n",G.properties.deviceName);
G.synchronous=getenv("DM_VK_SYNC")!=NULL;
pthread_t worker;if(pthread_create(&worker,NULL,completion_worker,NULL))die("GPU completion worker",0);pthread_detach(worker);
G.profile_start_ns=dm_android_nvn_clock_ns();
}
void mtl_init(void) { if(pthread_once(&init_once,backend_init))die("Vulkan initialize once",0); }
void *dm_vk_native_window(void) {pthread_mutex_lock(&G.lock);void *w=G.window;pthread_mutex_unlock(&G.lock);return w;}
int dm_vk_graphics_live(void) {pthread_mutex_lock(&G.lock);int live=G.graphics_live;pthread_mutex_unlock(&G.lock);return live;}
void dm_vk_graphics_begin(void *memory,size_t size) {
if(!memory || !size || size>UINTPTR_MAX-(uintptr_t)memory)die("nv::InitializeGraphics transfer-memory bounds",size);
mtl_init();pthread_mutex_lock(&G.lock);
if(G.graphics_live)die("nv::InitializeGraphics duplicate session",size);
G.transfer_memory=memory;G.transfer_size=size;G.graphics_live=1;
fprintf(stderr,"[nvn-vulkan] graphics session registered transfer-memory=%p bytes=%zu; Vulkan device initialized\n",memory,size);
pthread_mutex_unlock(&G.lock);
}
void dm_vk_graphics_end(void) {
mtl_init();pthread_mutex_lock(&G.lock);
if(!G.graphics_live || G.active || G.npool)die("nv::FinalizeGraphics live session/pools/submission",G.npool);
drain_locked();pipeline_cache_save();CHECK(vkDeviceWaitIdle(G.device));G.graphics_live=0;G.transfer_memory=NULL;G.transfer_size=0;
fprintf(stderr,"[nvn-vulkan] graphics session ended after Vulkan device idle; host device retained\n");pthread_mutex_unlock(&G.lock);
}
#define POOL_USAGE (VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_VERTEX_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT| \
VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT)
/* Import the guest pages as coherent device memory: same zero-copy model as
* the Metal backend. Any refusal leaves the pool on the staged copy path. */
static int pool_import(VPool *pool) {
if(!G.host_import)return 0;
uintptr_t lo=(uintptr_t)pool->guest,base=lo&~(uintptr_t)(G.import_align-1);
uintptr_t hi=(lo+pool->size+G.import_align-1)&~(uintptr_t)(G.import_align-1);
VkMemoryHostPointerPropertiesEXT hp={.sType=VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
VkResult r=G.get_host_pointer_properties(G.device,VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,(void *)base,&hp);
if(r!=VK_SUCCESS){fprintf(stderr,"[nvn-vulkan] POOL_IMPORT host pointer properties failed %d guest=%p\n",r,pool->guest);return 0;}
VkExternalMemoryBufferCreateInfo external={.sType=VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,.handleTypes=VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT};
VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.pNext=&external,.size=pool->size,.usage=POOL_USAGE,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
VBuffer v={.size=pool->size};CHECK(vkCreateBuffer(G.device,&info,NULL,&v.b));
VkMemoryRequirements req;vkGetBufferMemoryRequirements(G.device,v.b,&req);
uint64_t delta=lo-base;uint32_t type=UINT32_MAX,mask=req.memoryTypeBits&hp.memoryTypeBits;
for(uint32_t i=0;i<G.memory.memoryTypeCount;i++)if((mask&(1u<<i)) &&
(G.memory.memoryTypes[i].propertyFlags&(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))==(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)){type=i;break;}
if(type==UINT32_MAX || delta%req.alignment || delta+req.size>hi-base){
fprintf(stderr,"[nvn-vulkan] POOL_IMPORT unsuitable guest=%p types=%#x/%#x delta=%llu alignment=%llu\n",pool->guest,req.memoryTypeBits,hp.memoryTypeBits,(unsigned long long)delta,(unsigned long long)req.alignment);
vkDestroyBuffer(G.device,v.b,NULL);return 0;}
VkImportMemoryHostPointerInfoEXT import={.sType=VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT,
.handleType=VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT,.pHostPointer=(void *)base};
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.pNext=&import,.allocationSize=hi-base,.memoryTypeIndex=type};
r=vkAllocateMemory(G.device,&a,NULL,&v.m);
if(r!=VK_SUCCESS){fprintf(stderr,"[nvn-vulkan] POOL_IMPORT allocate failed %d guest=%p bytes=%llu\n",r,pool->guest,(unsigned long long)(hi-base));vkDestroyBuffer(G.device,v.b,NULL);return 0;}
CHECK(vkBindBufferMemory(G.device,v.b,v.m,delta));
v.map=(uint8_t *)pool->guest;pool->v=v;pool->direct=1;G.direct_bytes+=pool->size;
fprintf(stderr,"[nvn-vulkan] POOL_IMPORT guest=%p bytes=%llu type=%u direct_total=%llu\n",pool->guest,(unsigned long long)pool->size,type,(unsigned long long)G.direct_bytes);
return 1;
}
/* 无 VK_EXT_external_memory_host(Adreno 官方驱动):分配可导出的 Vulkan 内存(VK_KHR_external_memory_fd),
* 复制游戏当前内容,再把导出的 fd 用 mmap(MAP_FIXED) 映射到游戏地址——游戏页与 GPU 页成为同一物理内存,
* 与 Switch/Metal 相同。KGSL 的 vkMapMemory 映射不能 mremap(EINVAL),所以走 fd。
* Without VK_EXT_external_memory_host (Adreno proprietary driver): allocate exportable Vulkan memory
* (VK_KHR_external_memory_fd), copy the guest's current bytes, then mmap(MAP_FIXED) the exported fd onto
* the guest address so guest pages and GPU pages are the same physical memory, as on Switch/Metal.
* KGSL's vkMapMemory mapping cannot be mremap'ed (EINVAL), hence the fd. */
static void (*pool_release_ahb)(AHardwareBuffer *);
static uintptr_t untag(const void *p) { return (uintptr_t)p&(((uintptr_t)1<<56)-1); } /* Android TBI heap tag */
/* 首选 AHardwareBuffer(BLOB,CPU_*_OFTEN):gralloc 给出可缓存的 dmabuf,Snapdragon GPU 对其 IO 一致;
* OPAQUE_FD 导出只允许未缓存内存类型,CPU 读(游戏自身、纹理脏检查)会慢数倍。
* Prefer an AHardwareBuffer (BLOB, CPU_*_OFTEN): gralloc gives a cacheable dmabuf that the Snapdragon GPU
* accesses IO-coherently. OPAQUE_FD export only allows an uncached memory type, making CPU reads (the game
* itself, texture dirty checks) several times slower. */
typedef struct { int version,numFds,numInts,data[]; } NativeHandle;
static int pool_remap_ahb(VPool *pool,uintptr_t lo,uint64_t len) {
static int (*allocate)(const AHardwareBuffer_Desc *,AHardwareBuffer **);static void (*release)(AHardwareBuffer *);
static const NativeHandle *(*native_handle)(const AHardwareBuffer *);static int resolved;
if(!resolved){resolved=1;void *lib=dlopen("libnativewindow.so",RTLD_NOW);
if(lib){allocate=(int (*)(const AHardwareBuffer_Desc *,AHardwareBuffer **))dlsym(lib,"AHardwareBuffer_allocate");
release=(void (*)(AHardwareBuffer *))dlsym(lib,"AHardwareBuffer_release");
native_handle=(const NativeHandle *(*)(const AHardwareBuffer *))dlsym(lib,"AHardwareBuffer_getNativeHandle");}
if(!allocate||!release||!native_handle)fprintf(stderr,"[nvn-vulkan] POOL_REMAP AHardwareBuffer entry points unavailable\n");}
/* 默认关闭:OnePlus 13(snapalloc)上大 BLOB 让 vendor allocator-service 溢出崩溃并连带重启显示栈;
* 已测设备上也从未分配成功。DM_VK_AHB_POOL=1 才尝试。
* Off by default: on OnePlus 13 (snapalloc) a large BLOB crashes the vendor allocator service with a
* multiply overflow and takes the display stack down with it; it never succeeded on tested devices either. */
static int enabled=-1;if(enabled<0){const char *e=getenv("DM_VK_AHB_POOL");enabled=e&&*e=='1';}
if(!enabled||!G.get_ahb_properties||!allocate||!release||!native_handle||len>UINT32_MAX)return 0;
AHardwareBuffer_Desc desc={.width=(uint32_t)len,.height=1,.layers=1,.format=AHARDWAREBUFFER_FORMAT_BLOB,
.usage=AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN|AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN|AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER};
AHardwareBuffer *ahb=NULL;if(allocate(&desc,&ahb)||!ahb){fprintf(stderr,"[nvn-vulkan] POOL_REMAP AHardwareBuffer allocate failed bytes=%llu\n",(unsigned long long)len);return 0;}
const NativeHandle *h=native_handle(ahb);int fd=h&&h->numFds>0?h->data[0]:-1;
void *staging=fd>=0?mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0):MAP_FAILED;
if(staging==MAP_FAILED){fprintf(stderr,"[nvn-vulkan] POOL_REMAP AHardwareBuffer mmap failed fd=%d errno=%d\n",fd,errno);release(ahb);return 0;}
VkAndroidHardwareBufferPropertiesANDROID props={.sType=VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID};
VkResult r=G.get_ahb_properties(G.device,ahb,&props);
VkExternalMemoryBufferCreateInfo external={.sType=VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,.handleTypes=VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.pNext=&external,.size=len,.usage=POOL_USAGE,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
VBuffer v={.size=pool->size};uint32_t type=UINT32_MAX;
if(r==VK_SUCCESS)CHECK(vkCreateBuffer(G.device,&info,NULL,&v.b));
if(r==VK_SUCCESS)for(int pass=0;pass<2 && type==UINT32_MAX;pass++)for(uint32_t i=0;i<G.memory.memoryTypeCount;i++){
VkMemoryPropertyFlags want=pass?0:VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
if((props.memoryTypeBits&(1u<<i)) && (G.memory.memoryTypes[i].propertyFlags&want)==want){type=i;break;}}
VkMemoryDedicatedAllocateInfo dedicated={.sType=VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,.buffer=v.b};
VkImportAndroidHardwareBufferInfoANDROID import={.sType=VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID,.pNext=&dedicated,.buffer=ahb};
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.pNext=&import,.allocationSize=props.allocationSize,.memoryTypeIndex=type};
if(type==UINT32_MAX || props.allocationSize<len || vkAllocateMemory(G.device,&a,NULL,&v.m)!=VK_SUCCESS){
fprintf(stderr,"[nvn-vulkan] POOL_REMAP AHardwareBuffer import failed result=%d types=%#x size=%llu\n",r,props.memoryTypeBits,(unsigned long long)props.allocationSize);
if(v.b)vkDestroyBuffer(G.device,v.b,NULL);munmap(staging,len);release(ahb);G.get_ahb_properties=NULL;return 0;}
CHECK(vkBindBufferMemory(G.device,v.b,v.m,0));
memcpy(staging,pool->guest,len);
void *placed=mmap((void *)lo,len,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_FIXED,fd,0);munmap(staging,len);
if(placed!=(void *)lo)die("pool AHardwareBuffer mmap onto guest",errno);
v.map=(uint8_t *)pool->guest;pool->v=v;pool->direct=2;pool->mapped_len=len;pool->ahb=ahb;G.direct_bytes+=pool->size;
pool_release_ahb=release;
fprintf(stderr,"[nvn-vulkan] POOL_REMAP ahb guest=%p bytes=%llu type=%u flags=%#x types=%#x direct_total=%llu\n",pool->guest,(unsigned long long)pool->size,type,G.memory.memoryTypes[type].propertyFlags,props.memoryTypeBits,(unsigned long long)G.direct_bytes);
return 1;
}
static int pool_remap(VPool *pool) {
if(G.host_import || (!G.get_memory_fd && !G.get_ahb_properties))return 0;
uintptr_t page=(uintptr_t)sysconf(_SC_PAGESIZE),lo=untag(pool->guest);uint64_t len=(pool->size+page-1)&~(uint64_t)(page-1);
if(lo%page){fprintf(stderr,"[nvn-vulkan] POOL_REMAP unaligned guest=%p\n",pool->guest);return 0;}
if(pool_remap_ahb(pool,lo,len))return 1;
if(!G.get_memory_fd)return 0;
VkExternalMemoryBufferCreateInfo external={.sType=VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,.handleTypes=VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT};
VkBufferCreateInfo info={.sType=VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,.pNext=&external,.size=len,.usage=POOL_USAGE,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
VBuffer v={.size=pool->size};CHECK(vkCreateBuffer(G.device,&info,NULL,&v.b));
VkMemoryRequirements req;vkGetBufferMemoryRequirements(G.device,v.b,&req);
const VkMemoryPropertyFlags coherent=VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT|VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
uint32_t type=UINT32_MAX;
for(int pass=0;pass<2 && type==UINT32_MAX;pass++)for(uint32_t i=0;i<G.memory.memoryTypeCount;i++){
VkMemoryPropertyFlags want=coherent|(pass?0:VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if((req.memoryTypeBits&(1u<<i)) && (G.memory.memoryTypes[i].propertyFlags&want)==want){type=i;break;}}
if(type==UINT32_MAX){vkDestroyBuffer(G.device,v.b,NULL);fprintf(stderr,"[nvn-vulkan] POOL_REMAP no memory type guest=%p\n",pool->guest);return 0;}
/* Adreno: OPAQUE_FD 仅支持专用分配 | OPAQUE_FD is dedicated-only on Adreno */
VkMemoryDedicatedAllocateInfo dedicated={.sType=VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,.buffer=v.b};
VkExportMemoryAllocateInfo export={.sType=VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO,.pNext=&dedicated,.handleTypes=VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT};
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.pNext=&export,.allocationSize=req.size,.memoryTypeIndex=type};
if(vkAllocateMemory(G.device,&a,NULL,&v.m)!=VK_SUCCESS){vkDestroyBuffer(G.device,v.b,NULL);fprintf(stderr,"[nvn-vulkan] POOL_REMAP allocate failed guest=%p\n",pool->guest);return 0;}
CHECK(vkBindBufferMemory(G.device,v.b,v.m,0));
VkMemoryGetFdInfoKHR fi={.sType=VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR,.memory=v.m,.handleType=VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT};
int fd=-1;VkResult r=G.get_memory_fd(G.device,&fi,&fd);
void *staging=r==VK_SUCCESS?mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0):MAP_FAILED;
if(staging==MAP_FAILED){fprintf(stderr,"[nvn-vulkan] POOL_REMAP export/mmap failed guest=%p result=%d errno=%d\n",pool->guest,r,errno);
if(fd>=0)close(fd);buffer_free(&v);G.get_memory_fd=NULL;return 0;}
memcpy(staging,pool->guest,len);
void *placed=mmap((void *)lo,len,PROT_READ|PROT_WRITE,MAP_SHARED|MAP_FIXED,fd,0);munmap(staging,len);close(fd);
if(placed!=(void *)lo)die("pool fd mmap onto guest",errno); /* the guest range is already gone */
v.map=(uint8_t *)pool->guest;pool->v=v;pool->direct=2;pool->mapped_len=len;G.direct_bytes+=pool->size;
fprintf(stderr,"[nvn-vulkan] POOL_REMAP guest=%p bytes=%llu type=%u flags=%#x direct_total=%llu\n",pool->guest,(unsigned long long)pool->size,type,G.memory.memoryTypes[type].propertyFlags,(unsigned long long)G.direct_bytes);
return 1;
}
/* 池销毁:把内容复制到匿名页并搬回游戏地址,之后才释放 Vulkan 内存。
* Pool teardown: copy the bytes to anonymous pages, move them over the guest address, then free. */
static void pool_unremap(VPool *pool) {
uint64_t len=pool->mapped_len;
void *anon=mmap(NULL,len,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANONYMOUS,-1,0);if(anon==MAP_FAILED)die("pool unremap anonymous pages",len);
memcpy(anon,pool->guest,len);void *untagged=(void *)untag(pool->guest);
if(mremap(anon,len,len,MREMAP_MAYMOVE|MREMAP_FIXED,untagged)!=untagged)die("pool unremap mremap",errno);
}
void mtl_pool_add(const void *mem,uint64_t size) {
mtl_init(); pthread_mutex_lock(&G.lock);
if(!mem || G.npool==LIMIT_POOLS || size>UINTPTR_MAX-(uintptr_t)mem) die("memory pool bounds",size);
for(int i=0;i<G.npool;i++) if(G.pools[i].guest==mem) die("duplicate memory pool",(long long)(uintptr_t)mem);
VPool *pool=&G.pools[G.npool++]; pool->guest=mem;
*pool=(VPool){.guest=mem,.size=size};G.pool_adds++;G.pool_epoch++;if(!pool_import(pool))pool_remap(pool); pthread_mutex_unlock(&G.lock);
}
static void pool_materialize(VPool *pool) {
if(pool->v.b)return;
/* pool_read supplies every CPU-owned range before a GPU read, and queued
* writes supply their own bytes. Touching the entire backing with memset
* would commit hundreds of MiB that the game has not used. */
pool->v=buffer_create(pool->size,POOL_USAGE,0);
uint64_t logical=0,resident=0;for(int i=0;i<G.npool;i++){logical+=G.pools[i].size;resident+=G.pools[i].v.size;}
fprintf(stderr,"[nvn-vulkan] POOL_MATERIALIZE bytes=%llu resident=%llu logical=%llu pools=%d\n",(unsigned long long)pool->size,(unsigned long long)resident,(unsigned long long)logical,G.npool);
}
static VPool *pool_find(uint64_t addr,uint64_t size,uint64_t *offset) {
if(size>UINT64_MAX-addr) return NULL;
/* 先试上一次命中的池:同一命令流的查询几乎都落在同一个池 | try the last hit first: lookups from one command stream nearly all land in one pool */
static int last;int n=G.npool;
for(int k=-1;k<n;k++) { int i=k<0?last:k;if(i>=n)continue;uint64_t base=(uint64_t)(uintptr_t)G.pools[i].guest;
if(addr>=base && addr-base<=G.pools[i].size && size<=G.pools[i].size-(addr-base)) {
last=i;if(offset) *offset=addr-base; return &G.pools[i]; } }
return NULL;
}
int mtl_addr(uint64_t addr,uint64_t len,void **buf,uint64_t *off) {
VPool *p=pool_find(addr,len,off); if(!p) return 0; *buf=p; return 1;
}
int mtl_gpu_addr(uint64_t addr,uint64_t len,void **buf,uint64_t *off,uint64_t *gpu) {
if(!mtl_addr(addr,len,buf,off)) return 0; *gpu=addr; return 1; /* NVN virtual address, resolved through descriptors. */
}
void mtl_pool_del(const void *mem) {
if(G.active) die("pool deleted during submission",(long long)(uintptr_t)mem);
pthread_mutex_lock(&G.lock);G.wait_site=WAIT_POOLDEL;drain_locked();G.wait_site=WAIT_SYNC; for(int i=0;i<G.npool;i++) if(G.pools[i].guest==mem) {
G.pool_epoch++;
if(G.pools[i].direct==2)pool_unremap(&G.pools[i]);
if(G.pools[i].direct){G.pools[i].v.map=NULL;G.direct_bytes-=G.pools[i].size;}
buffer_free(&G.pools[i].v); if(G.pools[i].ahb)pool_release_ahb(G.pools[i].ahb); G.pools[i]=G.pools[--G.npool]; pthread_mutex_unlock(&G.lock); return; }
pthread_mutex_unlock(&G.lock); die("unknown memory pool delete",(long long)(uintptr_t)mem);
}
static int overlap(uint64_t a,uint64_t an,uint64_t b,uint64_t bn) { return a<b+bn && b<a+an; }
static void all_barrier(void);
static VPool *pool_read(uint64_t addr,uint64_t len,uint64_t *off) {
uint64_t started=prof_ns();
VPool *p=pool_find(addr,len,off); if(!p) die("unmapped NVN buffer range",addr);
if(p->direct){G.profile_pool_ns+=prof_ns()-started;return p;}
pool_materialize(p);
/* A GPU-written range in this command stream must retain its queued value. */
uint64_t cursor=addr,end=addr+len;
while(cursor<end) {
uint64_t first=end,skip=cursor;
for(unsigned slot=0;slot<BATCH_SLOTS;slot++){Batch *batch=&G.batches[slot];if(!batch->pending && batch!=G.batch)continue;
for(int i=0;i<batch->nwrites;i++) { Range r=batch->writes[i];
if(cursor>=r.addr && cursor<r.addr+r.size && r.addr+r.size>skip)skip=r.addr+r.size;
else if(r.addr>cursor && r.addr<first)first=r.addr;
}
}
if(skip>cursor){cursor=skip<end?skip:end;continue;}
uint64_t bytes=first-cursor;
if(cursor%4 || bytes%4)die("shared buffer upload word alignment",cursor);
VBuffer *upload=temporary(bytes,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);memcpy(upload->map,(const void *)(uintptr_t)cursor,bytes);
all_barrier();VkBufferCopy copy={0,*off+(cursor-addr),bytes};vkCmdCopyBuffer(G.batch->command,upload->b,p->v.b,1,&copy);all_barrier();cursor=first;
}
G.profile_pool_ns+=prof_ns()-started;return p;
}
static void mark_write(uint64_t addr,uint64_t len) {
VPool *pool=pool_find(addr,len,NULL);if(!pool) die("unmapped write range",addr);
if(pool->direct)return; /* GPU writes land in guest memory directly. */
for(int i=0;i<G.batch->nwrites;i++){Range *r=&G.batch->writes[i];if(addr>=r->addr && addr+len<=r->addr+r->size)return;
if(overlap(addr,len,r->addr,r->size)){uint64_t begin=addr<r->addr?addr:r->addr,end=addr+len>r->addr+r->size?addr+len:r->addr+r->size;
if(pool_find(begin,end-begin,NULL)){*r=(Range){begin,end-begin};return;}}}
if(G.batch->nwrites==LIMIT_WRITES)die("write range limit",G.batch->nwrites);G.batch->writes[G.batch->nwrites++]=(Range){addr,len};
}
/* CPU inputs are immutable snapshots. A frame may contain many logical NVN
* submits, and the guest may reuse the same address before the GPU runs. */
static VPool *input_read(uint64_t addr,uint64_t len,uint64_t *offset) {
uint64_t started=prof_ns();G.input_calls++;
if(len>G.input_max)G.input_max=len;
VPool *direct=pool_find(addr,len,offset);if(!direct)die("input snapshot range",addr);
if(direct->direct){G.profile_input_ns+=prof_ns()-started;return direct;}
/* GPU-authored inputs stay in their shared GPU buffer. Ordered staging
* uploads supply uncovered CPU bytes; later GPU writes are ordered after
* this draw, so copying a whole skinned mesh per draw is unnecessary. */
for(unsigned slot=0;slot<BATCH_SLOTS;slot++){Batch *batch=&G.batches[slot];if(!batch->pending && batch!=G.batch)continue;
for(int i=0;i<batch->nwrites;i++)if(overlap(addr,len,batch->writes[i].addr,batch->writes[i].size)){
VPool *pool=pool_read(addr,len,offset);G.input_shared++;G.profile_input_ns+=prof_ns()-started;return pool;}}
uint64_t metadata[2]={addr,len};uint64_t hash=state_hash(metadata,sizeof(metadata));
for(Snapshot *s=G.batch->snapshots[hash%1024];s;s=s->next)
if(s->hash==hash && s->pool.guest==(const uint8_t *)(uintptr_t)addr && s->pool.size==len &&
!memcmp(s->pool.v.map+s->offset,(const void *)(uintptr_t)addr,len)){
*offset=s->offset;G.profile_input_ns+=prof_ns()-started;return &s->pool;}
uint64_t alignment=G.properties.limits.minStorageBufferOffsetAlignment;
if(alignment<G.properties.limits.minUniformBufferOffsetAlignment)alignment=G.properties.limits.minUniformBufferOffsetAlignment;
if(alignment<G.properties.limits.minTexelBufferOffsetAlignment)alignment=G.properties.limits.minTexelBufferOffsetAlignment;
if(alignment<4)alignment=4;
uint64_t off=(G.batch->upload_offset+alignment-1)&~(alignment-1);
uint64_t span=(len+3)&~3ULL;
if(!G.batch->upload_arena || off+span>G.batch->upload_arena->size){uint64_t size=4*1024*1024;if(size<span)size=span;
G.batch->upload_arena=temporary(size,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT|VK_BUFFER_USAGE_INDEX_BUFFER_BIT|VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT);
G.batch->upload_bytes+=size;off=0;}
/* Snapshot records live in blocks kept by the batch across reuse. */
unsigned block=G.batch->nsnapshot/4096;if(block==1024)die("input snapshot count",G.batch->nsnapshot);
if(!G.batch->snapshot_blocks[block] && !(G.batch->snapshot_blocks[block]=malloc(4096*sizeof(Snapshot))))die("input snapshot allocation",len);
Snapshot *snapshot=&G.batch->snapshot_blocks[block][G.batch->nsnapshot++%4096];memset(snapshot,0,sizeof(*snapshot));
snapshot->pool=(VPool){.guest=(const uint8_t *)(uintptr_t)addr,.size=len,.v=*G.batch->upload_arena};
G.input_bytes+=len;
snapshot->offset=off;snapshot->hash=hash;memcpy(snapshot->pool.v.map+off,(const void *)(uintptr_t)addr,len);memset(snapshot->pool.v.map+off+len,0,span-len);
snapshot->next=G.batch->snapshots[hash%1024];G.batch->snapshots[hash%1024]=snapshot;
G.batch->upload_offset=off+span;*offset=off;G.profile_input_ns+=prof_ns()-started;return &snapshot->pool;
}
/* SAMPLES_PASSED: one query spans the draws of a render pass since the last
* 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 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;
}
static void query_begin(void) {
if(!G.counting || G.query_active>=0)return;
if(!G.precise_occlusion || G.batch->nocc==LIMIT_WRITES)die("precise occlusion query support/count",G.batch->nocc);
G.query_active=(int32_t)G.batch->nocc++;vkCmdBeginQuery(G.batch->command,G.batch->occlusion,(uint32_t)G.query_active,VK_QUERY_CONTROL_PRECISE_BIT);
}
/* DM_VK_PASSPROF=N:第 N 帧每个 render pass / dispatch 结束打一个 GPU 时间戳,第 N+3 帧读回逐条打印(PASSPROF 行)。
* 两戳间的差值含其间非 pass 工作(拷贝、清除)。不设则零开销。
* DM_VK_PASSPROF=N: stamp the GPU at the end of every render pass / dispatch of frame N and print them (PASSPROF lines) at frame N+3.
* Each delta includes non-pass work (copies, clears) recorded before it. Unset costs nothing. */
#define PP_MAX 4096
static VkQueryPool pp_pool;static unsigned pp_n;static uint64_t pp_draws0;static const char *pp_ps;
static struct {char kind;unsigned w,h,draws;const char *ps;char att[96];} pp_info[PP_MAX];
/* 逐操作日志(COPY_T2T / BC_STREAM_REFRESH)每秒上千行,默认关;DM_VK_TRACE=1 打开
* Per-op log lines (COPY_T2T / BC_STREAM_REFRESH) run to thousands per second, so they are off unless DM_VK_TRACE=1 */
static int vk_trace(void){static int t=-1;if(t<0){const char *e=getenv("DM_VK_TRACE");t=e&&*e=='1';}return t;}
static long pp_target(void){static long t=-2;if(t==-2){const char *e=getenv("DM_VK_PASSPROF");t=e?atol(e):-1;}return t;}
static void pp_stamp(char kind,unsigned w,unsigned h){
if(pp_target()<0 || (long)G.present_count+1!=pp_target() || pp_n>=PP_MAX)return;
if(!pp_pool){VkQueryPoolCreateInfo qi={.sType=VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,.queryType=VK_QUERY_TYPE_TIMESTAMP,.queryCount=PP_MAX};CHECK(vkCreateQueryPool(G.device,&qi,NULL,&pp_pool));
vkCmdResetQueryPool(G.batch->command,pp_pool,0,PP_MAX);vkCmdWriteTimestamp(G.batch->command,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,pp_pool,pp_n);pp_info[pp_n++].kind='S';}
vkCmdWriteTimestamp(G.batch->command,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,pp_pool,pp_n);
pp_info[pp_n].kind=kind;pp_info[pp_n].w=w;pp_info[pp_n].h=h;pp_info[pp_n].draws=(unsigned)(G.draws-pp_draws0);pp_info[pp_n].ps=pp_ps;pp_info[pp_n].att[0]=0;
if(kind=='P' && G.current_fb){const PassKey *k=&G.current_fb->pass->key;size_t o=0; /* 附件:格式:load/store | attachments: format:load/store */
for(uint32_t a=0;a<k->n && o<sizeof pp_info[pp_n].att-16;a++)o+=(size_t)snprintf(pp_info[pp_n].att+o,sizeof pp_info[pp_n].att-o,"%s%u:%u/%u",a?",":"",k->attachments[a].format,k->attachments[a].loadOp,k->attachments[a].storeOp);}
pp_n++;
}
static void pp_report(void){
if(!pp_pool || pp_target()<0 || (long)G.present_count+1!=pp_target()+4)return;
static uint64_t ts[PP_MAX];CHECK(vkGetQueryPoolResults(G.device,pp_pool,0,pp_n,sizeof(ts),ts,8,VK_QUERY_RESULT_64_BIT|VK_QUERY_RESULT_WAIT_BIT));
double period=G.properties.limits.timestampPeriod,total=0;
for(unsigned i=1;i<pp_n;i++){double us=ts[i]>=ts[i-1]?(ts[i]-ts[i-1])*period/1e3:0;total+=us;
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 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};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&b,0,NULL,0,NULL);
}
#define DESCRIPTOR_TYPES 9
static const VkDescriptorType descriptor_types[DESCRIPTOR_TYPES]={VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER,
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE,
VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER,VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER,
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC,VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC};
static const unsigned descriptor_limits[DESCRIPTOR_TYPES]={16384,8192,16384,4096,16384,4096,4096,16384,8192};
static VkDescriptorPool descriptor_pool_create(void) {
VkDescriptorPoolSize sizes[DESCRIPTOR_TYPES];for(unsigned i=0;i<DESCRIPTOR_TYPES;i++)sizes[i]=(VkDescriptorPoolSize){descriptor_types[i],descriptor_limits[i]};
VkDescriptorPoolCreateInfo ci={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,.maxSets=8192,.poolSizeCount=DESCRIPTOR_TYPES,.pPoolSizes=sizes};
VkDescriptorPool pool;CHECK(vkCreateDescriptorPool(G.device,&ci,NULL,&pool));return pool;
}
static void recording_begin_locked(void) {
if(G.batch && G.batch->recording)return;
Batch *batch=&G.batches[G.next_batch++%BATCH_SLOTS];
if(batch->pending){/* Retire in queue order so counters/events retain NVN order. */
for(unsigned i=0;i<BATCH_SLOTS;i++){Batch *old=NULL;for(unsigned j=0;j<BATCH_SLOTS;j++)if(G.batches[j].pending && (!old || G.batches[j].submit_order<old->submit_order))old=&G.batches[j];
if(!old)break;int target=old==batch;int site=G.wait_site;G.wait_site=WAIT_SLOT;retire_locked(old,UINT64_MAX);G.wait_site=site;if(target)break;}}
G.batch=batch;batch->ticket=0;batch->awaiting_publish=0;batch->descriptor_sets=0;memset(batch->descriptor_used,0,sizeof(batch->descriptor_used));batch->draws=batch->sets=0;batch->upload_bytes=0;batch->upload_arena=NULL;batch->upload_offset=0;
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->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));
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);
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));
if(!batch->fence){VkFenceCreateInfo fi={.sType=VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};CHECK(vkCreateFence(G.device,&fi,NULL,&batch->fence));}
all_barrier();
}
void mtl_sub_begin(void) {
mtl_init();pthread_mutex_lock(&G.lock);if(G.active)die("nested submission",0);G.active=1;recording_begin_locked();
}
static void batch_checkpoint(void) {
if(G.batch->nocc<3000 && G.batch->ntime<3000 && G.batch->ncounter<3000 && G.batch->nview<3000 &&
G.batch->nbuffer_view<3000 && G.batch->ntemporary<3000 && G.batch->upload_bytes<=128*1024*1024 && G.batch->nextra_descriptors<48)return;
/* Split before resource limits, without publishing the in-progress logical
* submission's fence. All pieces use one ordered Vulkan queue. */
if(!G.batch->ticket)G.batch->ticket=G.fence;flush_locked();recording_begin_locked();
}
void mtl_sub_copy(uint64_t src,uint64_t dst,uint64_t len) {
all_barrier(); uint64_t so=0,doff=0; VPool *s=pool_read(src,len,&so),*d=pool_find(dst,len,&doff);
if(!d || overlap(src,len,dst,len)) die("buffer copy bounds/overlap",dst);pool_materialize(d);
VkBufferCopy copy={so,doff,len}; vkCmdCopyBuffer(G.batch->command,s->v.b,d->v.b,1,&copy); mark_write(dst,len);
}
void mtl_sub_event(volatile uint32_t *addr,uint32_t mode,uint32_t value) {
if(mode>1 || G.batch->nevents==LIMIT_WRITES) die("event mode/count",mode);
G.batch->events[G.batch->nevents++]=(Event){addr,mode,value};
}
static void counter_op(uint32_t kind,uint32_t query,uint64_t address) {
if(G.batch->ncounter==LIMIT_WRITES)die("counter operation limit",G.batch->ncounter);
G.batch->counter_ops[G.batch->ncounter++]=(CounterOp){kind,query,address};
}
void mtl_sub_counter(uint64_t addr,uint32_t type) {
if(type!=NVN_COUNTER_TYPE_SAMPLES_PASSED && type!=NVN_COUNTER_TYPE_TIMESTAMP && type!=NVN_COUNTER_TYPE_TIMESTAMP_TOP)
die("GPU counter type implementation pending",type);
if(!pool_find(addr,16,NULL) || addr%8)die("GPU counter report range/alignment",addr);
if(!G.timestamp_bits || G.batch->ntime==LIMIT_WRITES)die("GPU timestamp support/count",G.batch->ntime);
pass_end();uint32_t q=G.batch->ntime++;
vkCmdWriteTimestamp(G.batch->command,type==NVN_COUNTER_TYPE_TIMESTAMP_TOP?VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT:VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,G.batch->timestamps,q);
counter_op(type==NVN_COUNTER_TYPE_SAMPLES_PASSED?2:3,q,addr);
}
static void writeback_encode(void) {
if(G.batch->nwrites)all_barrier();
for(int i=0;i<G.batch->nwrites;i++){Range r=G.batch->writes[i];uint64_t offset=0;VPool *pool=pool_find(r.addr,r.size,&offset);
G.batch->writebacks[i]=temporary(r.size,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
if(offset%4 || r.size%4)die("writeback snapshot word alignment",offset);
VkBufferCopy copy={offset,0,r.size};vkCmdCopyBuffer(G.batch->command,pool->v.b,G.batch->writebacks[i]->b,1,&copy);}
}
static void batch_stamp_end(void) {
if(G.timestamp_bits){vkCmdWriteTimestamp(G.batch->command,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,G.batch->timestamps,BATCH_STAMP+1);G.batch->stamped=1;}
}
/* 当前事件值 + 未发布信号(已提交批次按提交序,再加正在录制的批次)| current event value + unpublished signals (submitted batches in submit order, then the recording batch) */
static int event_satisfied_queued(uint64_t address,uint32_t mode,uint32_t value) {
if(getenv("DM_VK_EVENT_SYNC"))return 0; /* 对照:恢复旧的 CPU 等待 | comparison: restore the old CPU wait */
uint32_t v=atomic_load((_Atomic uint32_t *)(uintptr_t)address);uint64_t after=0;
for(;;){Batch *next=NULL;for(unsigned i=0;i<BATCH_SLOTS;i++){Batch *b=&G.batches[i];
if(b->pending && b->submit_order>after && (!next || b->submit_order<next->submit_order))next=b;}
if(!next)break;after=next->submit_order;
for(int i=0;i<next->nevents;i++)if((uint64_t)(uintptr_t)next->events[i].addr==address)v=next->events[i].mode?v+next->events[i].value:next->events[i].value;}
if(G.batch && G.batch->recording)for(int i=0;i<G.batch->nevents;i++)if((uint64_t)(uintptr_t)G.batch->events[i].addr==address)v=G.batch->events[i].mode?v+G.batch->events[i].value:G.batch->events[i].value;
return mode==0?v==value:(int32_t)(v-value)>=0;
}
static void flush_locked(void) {
if(!G.batch || !G.batch->recording)return;pass_end();
writeback_encode();
VkMemoryBarrier barrier={.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT,.dstAccessMask=VK_ACCESS_HOST_READ_BIT};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&barrier,0,NULL,0,NULL);
batch_stamp_end();CHECK(vkEndCommandBuffer(G.batch->command));CHECK(vkResetFences(G.device,1,&G.batch->fence));
VkSubmitInfo si={.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO,.commandBufferCount=1,.pCommandBuffers=&G.batch->command};
CHECK(vkQueueSubmit(G.queue,1,&si,G.batch->fence));G.profile_submits++;G.batch->submit_order=++G.batch_count;
G.batch->recording=0;G.batch->pending=1;pthread_cond_signal(&G.completion);
}
static int retire_locked(Batch *batch,uint64_t timeout) {
if(!batch->pending)return 1;
uint64_t started=dm_android_nvn_clock_ns();
VkResult result=timeout?vkWaitForFences(G.device,1,&batch->fence,VK_TRUE,timeout):vkGetFenceStatus(G.device,batch->fence);
G.profile_wait_ns+=dm_android_nvn_clock_ns()-started;
if(timeout){G.wait_ns[G.wait_site]+=dm_android_nvn_clock_ns()-started;G.wait_n[G.wait_site]++;}
if(result==VK_TIMEOUT || result==VK_NOT_READY)return 0;if(result!=VK_SUCCESS)die("batch fence",result);
Batch *saved=G.batch;G.batch=batch;
trace_capture_complete();
for(int i=0;i<G.batch->nwrites;i++)memcpy((void *)(uintptr_t)G.batch->writes[i].addr,G.batch->writebacks[i]->map,G.batch->writes[i].size);
uint64_t occ[LIMIT_WRITES],times[LIMIT_WRITES];
if(G.batch->nocc)CHECK(vkGetQueryPoolResults(G.device,G.batch->occlusion,0,G.batch->nocc,G.batch->nocc*8,occ,8,VK_QUERY_RESULT_64_BIT|VK_QUERY_RESULT_WAIT_BIT));
if(G.present_count<2 || G.trace_frame)for(uint32_t i=0;i<G.batch->nocc;++i)fprintf(stderr,"[nvn-vulkan] DRAW_SAMPLES query=%u samples=%llu\n",i,(unsigned long long)occ[i]);
if(G.batch->ntime)CHECK(vkGetQueryPoolResults(G.device,G.batch->timestamps,0,G.batch->ntime,G.batch->ntime*8,times,8,VK_QUERY_RESULT_64_BIT|VK_QUERY_RESULT_WAIT_BIT));
if(batch->stamped){uint64_t span[2];CHECK(vkGetQueryPoolResults(G.device,batch->timestamps,BATCH_STAMP,2,sizeof span,span,8,VK_QUERY_RESULT_64_BIT|VK_QUERY_RESULT_WAIT_BIT));
uint64_t mask=G.timestamp_bits<64?(1ULL<<G.timestamp_bits)-1:UINT64_MAX;double period=G.properties.limits.timestampPeriod;
uint64_t begin=(uint64_t)((span[0]&mask)*period),end=(uint64_t)((span[1]&mask)*period);
/* 同一队列上批次的开始戳可能早于上一批结束;只计未重叠的部分。| A batch's begin stamp can precede the previous batch's end on the one queue; count only the non-overlapping part. */
if(begin<G.gpu_last_end && end>G.gpu_last_end)begin=G.gpu_last_end;if(end>begin)G.profile_gpu_ns+=end-begin;G.gpu_last_end=end;}
for(int i=0;i<G.batch->ncounter;++i) {CounterOp *op=&G.batch->counter_ops[i];
if(op->kind==0)G.samples_passed=0;
else if(op->kind==1)G.samples_passed+=occ[op->query];
else {uint64_t ticks=times[op->query];if(G.timestamp_bits<64)ticks&=(1ULL<<G.timestamp_bits)-1;
uint64_t stamp=(uint64_t)((long double)ticks*G.properties.limits.timestampPeriod*12/625);
uint64_t result[2]={op->kind==2?G.samples_passed:stamp,stamp},off=0;
VPool *p=pool_find(op->address,16,&off);if(!p)die("counter report pool lifetime",op->address);
memcpy((void *)(uintptr_t)op->address,result,16);}
}
for(int i=0;i<G.batch->nevents;i++) { Event *e=&G.batch->events[i]; if(e->mode) atomic_fetch_add((_Atomic uint32_t *)e->addr,e->value);
else atomic_store((_Atomic uint32_t *)e->addr,e->value); }
if(batch->ticket>G.completed)G.completed=batch->ticket;
for(int i=0;i<G.batch->ntemporary;i++)temporary_release(G.batch->temporaries[i]);
for(int i=0;i<G.batch->nview;++i)vkDestroyImageView(G.device,G.batch->temporary_views[i],NULL);
for(int i=0;i<G.batch->nbuffer_view;++i)vkDestroyBufferView(G.device,G.batch->buffer_views[i],NULL);
memset(batch->snapshots,0,sizeof(batch->snapshots));batch->nsnapshot=0;
for(unsigned i=0;i<batch->nextra_descriptors;i++)vkDestroyDescriptorPool(G.device,batch->extra_descriptors[i],NULL);
batch->nextra_descriptors=0;batch->pending=0;batch->ntemporary=0;G.batch=saved;return 1;
}
/* Publish CPU-visible reports/events even if the guest only polls memory and
* makes no subsequent renderer call. Vulkan queue and resource access share G.lock. */
static void *completion_worker(void *unused) {
(void)unused;pthread_mutex_lock(&G.lock);
for(;;){Batch *old=NULL;for(unsigned i=0;i<BATCH_SLOTS;i++)if(G.batches[i].pending && (!old || G.batches[i].submit_order<old->submit_order))old=&G.batches[i];
if(G.batch && G.batch->recording && G.batch->awaiting_publish &&
dm_android_nvn_clock_ns()-G.batch->last_commit_ns>=2000000){flush_locked();continue;}
if(!old && !(G.batch && G.batch->recording && G.batch->awaiting_publish)){pthread_cond_wait(&G.completion,&G.lock);continue;}
if(old && retire_locked(old,0))continue;
struct timespec deadline;clock_gettime(CLOCK_REALTIME,&deadline);deadline.tv_nsec+=1000000;
if(deadline.tv_nsec>=1000000000){deadline.tv_sec++;deadline.tv_nsec-=1000000000;}
pthread_cond_timedwait(&G.completion,&G.lock,&deadline);
}
return NULL;
}
static void drain_locked(void) {
flush_locked();
for(unsigned i=0;i<BATCH_SLOTS;i++){Batch *old=NULL;for(unsigned j=0;j<BATCH_SLOTS;j++)if(G.batches[j].pending && (!old || G.batches[j].submit_order<old->submit_order))old=&G.batches[j];
if(old)retire_locked(old,UINT64_MAX);}
}
uint64_t mtl_sub_commit(void) {
if(!G.active)die("commit without begin",0);
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;
if(G.synchronous)drain_locked();
else if(G.batch->nocc>3000 || G.batch->sets>7000 || G.batch->nview>3000 || G.batch->nbuffer_view>3000 ||
G.batch->ntemporary>3000 || G.batch->upload_bytes>128*1024*1024)flush_locked();
G.batch->last_commit_ns=dm_android_nvn_clock_ns();G.batch->awaiting_publish|=publish;
if(publish)pthread_cond_signal(&G.completion);
G.active=0;pthread_mutex_unlock(&G.lock);return ticket;
}
uint64_t mtl_last_fence(void) { return G.fence; }
int mtl_last_commit_error(void) { return 0; }
static int wait_at(uint64_t fence,uint64_t timeout,int site) {
mtl_init();pthread_mutex_lock(&G.lock);
if(fence>G.fence){pthread_mutex_unlock(&G.lock);return 0;}
G.wait_site=site;
if(site==WAIT_SYNC && timeout && fence>G.completed){uint64_t lag=G.fence-fence;if(lag>G.sync_lag_max)G.sync_lag_max=lag;
if(fence>G.frame_fences[G.present_count%3])G.sync_cur_frame++;} /* 等的是本帧(上次出图之后)的工作 | waiting on work after the last present */
if(fence>G.completed)flush_locked();
uint64_t started=dm_android_nvn_clock_ns();
while(fence>G.completed){Batch *old=NULL;for(unsigned i=0;i<BATCH_SLOTS;i++)if(G.batches[i].pending && (!old || G.batches[i].submit_order<old->submit_order))old=&G.batches[i];
if(!old)break;uint64_t elapsed=dm_android_nvn_clock_ns()-started;
uint64_t remaining=timeout==UINT64_MAX?UINT64_MAX:timeout>elapsed?timeout-elapsed:0;
if(!retire_locked(old,remaining))break;}
int complete=fence<=G.completed;G.wait_site=WAIT_SYNC;pthread_mutex_unlock(&G.lock);return complete;
}
int mtl_wait(uint64_t fence,uint64_t timeout) { return wait_at(fence,timeout,WAIT_SYNC); }
void mtl_queue_flush(void) { mtl_init();pthread_mutex_lock(&G.lock);flush_locked();pthread_mutex_unlock(&G.lock); }
static void finish_at(int site) { mtl_init();pthread_mutex_lock(&G.lock);G.wait_site=site;drain_locked();G.wait_site=WAIT_SYNC;pipeline_cache_save();pthread_mutex_unlock(&G.lock); }
void mtl_finish(void) { finish_at(WAIT_FINISH); }
void mtl_drain(void) { mtl_finish(); }
static VkFormat format(int nvn) {
switch(nvn) {
case NVN_FORMAT_R8:return VK_FORMAT_R8_UNORM; case NVN_FORMAT_RG8:return VK_FORMAT_R8G8_UNORM;
case NVN_FORMAT_R16:return VK_FORMAT_R16_UNORM;case NVN_FORMAT_RG16:return VK_FORMAT_R16G16_UNORM;case NVN_FORMAT_RGBA16:return VK_FORMAT_R16G16B16A16_UNORM;
case NVN_FORMAT_R8SN:return VK_FORMAT_R8_SNORM;case NVN_FORMAT_RG8SN:return VK_FORMAT_R8G8_SNORM;case NVN_FORMAT_RGBA8SN:return VK_FORMAT_R8G8B8A8_SNORM;
case NVN_FORMAT_R16SN:return VK_FORMAT_R16_SNORM;case NVN_FORMAT_RG16SN:return VK_FORMAT_R16G16_SNORM;case NVN_FORMAT_RGBA16SN:return VK_FORMAT_R16G16B16A16_SNORM;
case NVN_FORMAT_R8UI:return VK_FORMAT_R8_UINT;case NVN_FORMAT_RG8UI:return VK_FORMAT_R8G8_UINT;case NVN_FORMAT_RGBA8UI:return VK_FORMAT_R8G8B8A8_UINT;
case NVN_FORMAT_R32UI:return VK_FORMAT_R32_UINT;case NVN_FORMAT_RG32UI:return VK_FORMAT_R32G32_UINT;case NVN_FORMAT_RGBA32UI:return VK_FORMAT_R32G32B32A32_UINT;
case NVN_FORMAT_R16F:return VK_FORMAT_R16_SFLOAT; case NVN_FORMAT_RG16F:return VK_FORMAT_R16G16_SFLOAT;
case NVN_FORMAT_RGBA16F:return VK_FORMAT_R16G16B16A16_SFLOAT;
case NVN_FORMAT_R11G11B10F:return VK_FORMAT_B10G11R11_UFLOAT_PACK32;
case NVN_FORMAT_R32F:return VK_FORMAT_R32_SFLOAT; case NVN_FORMAT_RG32F:return VK_FORMAT_R32G32_SFLOAT;
case NVN_FORMAT_RGB32F:return VK_FORMAT_R32G32B32_SFLOAT; case NVN_FORMAT_RGBA32F:return VK_FORMAT_R32G32B32A32_SFLOAT;
case NVN_FORMAT_RGBA8:return VK_FORMAT_R8G8B8A8_UNORM; case NVN_FORMAT_RGBA8_SRGB:return VK_FORMAT_R8G8B8A8_SRGB;
case NVN_FORMAT_RGBA8_UI2F:return VK_FORMAT_R8G8B8A8_USCALED;case NVN_FORMAT_RGBA8_I2F:return VK_FORMAT_R8G8B8A8_SSCALED;
case NVN_FORMAT_DEPTH16:return VK_FORMAT_D16_UNORM; case NVN_FORMAT_DEPTH32F:return VK_FORMAT_D32_SFLOAT;
case NVN_FORMAT_DEPTH24_STENCIL8:return VK_FORMAT_D24_UNORM_S8_UINT;
case NVN_FORMAT_DEPTH32F_STENCIL8:return VK_FORMAT_D32_SFLOAT_S8_UINT;
default:die("NVN pixel/vertex format",nvn);
}
}
static VkImageAspectFlags aspect(VkFormat f) {
if(f==VK_FORMAT_D16_UNORM || f==VK_FORMAT_D32_SFLOAT) return VK_IMAGE_ASPECT_DEPTH_BIT;
if(f==VK_FORMAT_D24_UNORM_S8_UINT || f==VK_FORMAT_D32_SFLOAT_S8_UINT) return VK_IMAGE_ASPECT_DEPTH_BIT|VK_IMAGE_ASPECT_STENCIL_BIT;
return VK_IMAGE_ASPECT_COLOR_BIT;
}
static void texture_transition(VTexture *t,VkImageLayout layout) {
if(t->layout==layout) return; pass_end();
VkImageMemoryBarrier b={.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask=t->layout==VK_IMAGE_LAYOUT_UNDEFINED?0:VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT,
.dstAccessMask=VK_ACCESS_MEMORY_WRITE_BIT|VK_ACCESS_MEMORY_READ_BIT,.oldLayout=t->layout,.newLayout=layout,
.srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.image=t->image,
.subresourceRange={aspect(t->format),0,t->source.d.levels,0,t->source.L.layers}};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,0,NULL,0,NULL,1,&b);
t->layout=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. */
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);
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;
for(unsigned layer=0;layer<source->L.layers;layer++)for(unsigned level=0;level<source->d.levels;level++){
unsigned width=t->width>>level,height=t->height>>level,depth=t->depth>>level;if(!width)width=1;if(!height)height=1;if(!depth)depth=1;
int bw,bh;int block=nvn_fmt_bpb(source->d.format,&bw,&bh);unsigned columns=(width+bw-1)/bw,rows=(height+bh-1)/bh;
uint64_t row=(uint64_t)columns*block,linear_bytes=row*rows*depth;
uint8_t *old=malloc(linear_bytes),*next=malloc(linear_bytes);if(!old||!next)die("streamed BC block comparison allocation",linear_bytes);
if(nvn_deswizzle(&source->d,level,layer,t->cpu_snapshot,old,row)||nvn_deswizzle(&source->d,level,layer,snapshot,next,row))die("streamed BC block layout",source->serial);
if(!memcmp(old,next,linear_bytes)){free(old);free(next);continue;}
uint64_t plane=((uint64_t)width*height*t->bpp+3)&~3ULL;
VBuffer *staging=temporary(plane*depth,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
for(unsigned z=0;z<depth;z++)if(nvn_bc_decode(source->d.format,next+z*row*rows,row,width,height,staging->map+z*plane,(size_t)width*t->bpp))die("streamed BC block decode",source->d.format);
VkBufferImageCopy *regions=NULL;unsigned count=0,capacity=0;
for(unsigned z=0;z<depth;z++)for(unsigned y=0;y<rows;y++){
unsigned x=0;while(x<columns){uint64_t offset=((uint64_t)z*rows+y)*row+(uint64_t)x*block;
if(!memcmp(old+offset,next+offset,block)){x++;continue;}
unsigned first=x++;while(x<columns&&memcmp(old+((uint64_t)z*rows+y)*row+(uint64_t)x*block,next+((uint64_t)z*rows+y)*row+(uint64_t)x*block,block))x++;
if(count==capacity){capacity=capacity?capacity*2:64;VkBufferImageCopy *larger=realloc(regions,(size_t)capacity*sizeof(*regions));if(!larger)die("streamed BC copy regions",capacity);regions=larger;}
unsigned px=first*bw,py=y*bh,w=(x-first)*bw,h=bh;if(w>width-px)w=width-px;if(h>height-py)h=height-py;
regions[count++]=(VkBufferImageCopy){.bufferOffset=z*plane+((uint64_t)py*width+px)*t->bpp,.bufferRowLength=width,.bufferImageHeight=height,
.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,level,layer,1},.imageOffset={px,py,z},.imageExtent={w,h,1}};
}
}
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,count,regions);changed_regions+=count;
free(regions);free(old);free(next);
}
free(t->cpu_snapshot);t->cpu_snapshot=snapshot;t->upload_stamp=stamp;t->clean_now=0;
if(changed_regions){t->version++;G.uploads++;if(vk_trace())fprintf(stderr,"[nvn-vulkan] BC_STREAM_REFRESH serial=%llu changed_regions=%u gpu_blocks_preserved=1\n",(unsigned long long)t->serial,changed_regions);}
G.profile_decode_ns+=dm_android_nvn_clock_ns()-started;
}
/* Every guest write fault advances the global dirty generation, so a texture
* found clean stays clean until it moves or a pool is added/removed; this skips
* the per-page generation scan on each draw. */
static int texture_dirty(VTexture *t,const tex_t *source) {
uint64_t now=nvn_dirty_now();
if(t->clean_now==now && t->clean_pools==G.pool_epoch)return 0;
if(nvn_dirty_since(source->mem,source->L.size,t->upload_stamp))return 1;
t->clean_now=now;t->clean_pools=G.pool_epoch;return 0;
}
static VTexture *texture_get(const tex_t *source,int upload) {
if(!source || !source->serial) die("texture serial",0);
/* Direct-mapped serial hint; release swaps entries, so a hit is verified. */
static uint16_t hint[8192];unsigned h=(unsigned)((source->serial*0x9e3779b97f4a7c15ULL)>>51);
VTexture *t=NULL;
if(hint[h]<G.ntexture && G.textures[hint[h]].serial==source->serial)t=&G.textures[hint[h]];
else for(int i=0;i<G.ntexture;i++) if(G.textures[i].serial==source->serial) {t=&G.textures[i];hint[h]=(uint16_t)i;break;}
if(t) {
uint32_t decoded_format;int decoded_bpp;
if(upload&&!t->cpu_owned&&t->cpu_snapshot&&nvn_bc_unpacked(source->d.format,&decoded_format,&decoded_bpp)&&texture_dirty(t,source)){
refresh_compressed_cpu(t,source);return t;
}
// GPU render targets remain resident. Only CPU-backed sampled images
// use dirty generations to refresh streamed contents at the same serial.
if(!upload || !t->cpu_owned || !texture_dirty(t,source))return t;
goto upload_existing;
}
int one=source->d.target==NVN_TEXTURE_TARGET_1D || source->d.target==NVN_TEXTURE_TARGET_1D_ARRAY;
int layered=source->d.target==NVN_TEXTURE_TARGET_2D_ARRAY || source->d.target==NVN_TEXTURE_TARGET_1D_ARRAY;
int volume=source->d.target==NVN_TEXTURE_TARGET_3D;
int cube=source->d.target==NVN_TEXTURE_TARGET_CUBEMAP || source->d.target==NVN_TEXTURE_TARGET_CUBEMAP_ARRAY;
if(G.ntexture==LIMIT_OBJECTS || (source->d.target!=NVN_TEXTURE_TARGET_2D && !one && !layered && !cube && !volume) || source->d.samples>1)
die("texture target/layers/MSAA",source->d.target);
hint[h]=(uint16_t)G.ntexture;
t=&G.textures[G.ntexture++];memset(t,0,sizeof(*t));t->serial=source->serial; t->source=*source;t->version=1;
t->width=source->d.width; t->height=one?1:source->d.height;t->depth=volume?source->d.depth:1;t->layout=VK_IMAGE_LAYOUT_UNDEFINED;
uint32_t metal_format=0; int decompressed_bpp=0;
int bc=nvn_bc_unpacked(source->d.format,&metal_format,&decompressed_bpp);
if(bc) {
switch(metal_format) { case 10:t->format=VK_FORMAT_R8_UNORM;break;case 12:t->format=VK_FORMAT_R8_SNORM;break;
case 30:t->format=VK_FORMAT_R8G8_UNORM;break;case 32:t->format=VK_FORMAT_R8G8_SNORM;break;
case 70:t->format=VK_FORMAT_R8G8B8A8_UNORM;break;case 71:t->format=VK_FORMAT_R8G8B8A8_SRGB;break;
case 115:t->format=VK_FORMAT_R16G16B16A16_SFLOAT;break;default:die("BC decoded format",metal_format); }
t->bpp=decompressed_bpp;
} else { t->format=format(source->d.format); t->bpp=source->L.bpb; }
VkFormatProperties fp; vkGetPhysicalDeviceFormatProperties(G.physical,t->format,&fp);
VkImageUsageFlags usage=VK_IMAGE_USAGE_TRANSFER_SRC_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT|VK_IMAGE_USAGE_SAMPLED_BIT;
if(aspect(t->format)&VK_IMAGE_ASPECT_DEPTH_BIT) usage|=VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
else if(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) usage|=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
if(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) usage|=VK_IMAGE_USAGE_STORAGE_BIT;
if(G.feedback_layout && (usage&(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT|VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)))usage|=VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT;
VkImageCreateInfo ii={.sType=VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,.imageType=volume?VK_IMAGE_TYPE_3D:one?VK_IMAGE_TYPE_1D:VK_IMAGE_TYPE_2D,.format=t->format,
.flags=cube?VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT:0,
.extent={t->width,t->height,t->depth},.mipLevels=source->d.levels,.arrayLayers=source->L.layers,.samples=VK_SAMPLE_COUNT_1_BIT,
.tiling=VK_IMAGE_TILING_OPTIMAL,.usage=usage,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
CHECK(vkCreateImage(G.device,&ii,NULL,&t->image)); VkMemoryRequirements r; vkGetImageMemoryRequirements(G.device,t->image,&r);
VkMemoryAllocateInfo a={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=r.size,
.memoryTypeIndex=memory_type(r.memoryTypeBits,VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
CHECK(vkAllocateMemory(G.device,&a,NULL,&t->memory)); CHECK(vkBindImageMemory(G.device,t->image,t->memory,0));
VkImageViewType view_type=volume?VK_IMAGE_VIEW_TYPE_3D:one?(layered?VK_IMAGE_VIEW_TYPE_1D_ARRAY:VK_IMAGE_VIEW_TYPE_1D):cube?(source->L.layers==6?VK_IMAGE_VIEW_TYPE_CUBE:VK_IMAGE_VIEW_TYPE_CUBE_ARRAY):layered?VK_IMAGE_VIEW_TYPE_2D_ARRAY:VK_IMAGE_VIEW_TYPE_2D;
VkImageViewCreateInfo vi={.sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,.image=t->image,.viewType=view_type,
.format=t->format,.subresourceRange={aspect(t->format)&VK_IMAGE_ASPECT_DEPTH_BIT?VK_IMAGE_ASPECT_DEPTH_BIT:VK_IMAGE_ASPECT_COLOR_BIT,0,source->d.levels,0,source->L.layers}}; CHECK(vkCreateImageView(G.device,&vi,NULL,&t->view));
upload_existing:
if(upload) {
uint32_t decoded_format=0;int decoded_bpp=0;
int upload_bc=nvn_bc_unpacked(source->d.format,&decoded_format,&decoded_bpp);
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);
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;}
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
uint64_t decode_start=dm_android_nvn_clock_ns();
for(unsigned layer=0;layer<source->L.layers;layer++)for(unsigned level=0;level<source->d.levels;level++) {
uint32_t w=t->width>>level,h=t->height>>level,z=t->depth>>level;if(!w)w=1;if(!h)h=1;if(!z)z=1;
int bw=1,bh=1; int bb=nvn_fmt_bpb(source->d.format,&bw,&bh); if(!bb)die("texture block size",source->d.format);
uint64_t row=(uint64_t)((w+bw-1)/bw)*bb,rows=(h+bh-1)/bh;
uint8_t *linear=malloc(row*rows*z); if(!linear)die("texture decode allocation",row*rows*z);
if(source->d.flags&NVN_TEXTURE_FLAGS_LINEAR) { free(linear); die("linear texture upload layout",source->d.flags); }
if(nvn_deswizzle(&source->d,level,layer,upload_memory,linear,row))die("Tegra texture deswizzle",level);
VBuffer *staging=temporary((uint64_t)w*h*z*t->bpp,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
if(upload_bc) {for(unsigned slice=0;slice<z;++slice)if(nvn_bc_decode(source->d.format,linear+slice*row*rows,row,w,h,staging->map+(size_t)slice*w*h*t->bpp,(size_t)w*t->bpp))die("BC decode",source->d.format); }
else memcpy(staging->map,linear,(size_t)w*h*z*t->bpp); free(linear);
VkImageAspectFlags upload_aspect=aspect(t->format);
if(upload_aspect&VK_IMAGE_ASPECT_STENCIL_BIT)die("packaged depth/stencil upload requires separate aspect conversion",source->d.format);
VkBufferImageCopy copy={.imageSubresource={upload_aspect,level,layer,1},.imageExtent={w,h,z}};
vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,1,&copy);
}
G.profile_decode_ns+=dm_android_nvn_clock_ns()-decode_start;
t->cpu_owned=1;t->upload_stamp=stamp;t->clean_now=0;t->version++; G.uploads++;
}
return t;
}
void mtl_tex_release(tex_t *source) {
if(G.active) die("texture release during submission",source->serial);
finish_at(WAIT_TEXREL);pthread_mutex_lock(&G.lock);framebuffer_cache_clear();
for(int i=0;i<G.ntexture;i++)if(G.textures[i].serial==source->serial){ VTexture *t=&G.textures[i];
free(t->cpu_snapshot);
if(t->shadow){vkDestroyImageView(G.device,t->shadow_view,NULL);vkDestroyImage(G.device,t->shadow,NULL);vkFreeMemory(G.device,t->shadow_memory,NULL);}
vkDestroyImageView(G.device,t->view,NULL); vkDestroyImage(G.device,t->image,NULL); vkFreeMemory(G.device,t->memory,NULL);
G.textures[i]=G.textures[--G.ntexture]; pthread_mutex_unlock(&G.lock);return; }
pthread_mutex_unlock(&G.lock);
}
void mtl_reg_tex(int id,const tex_t *t,const view_t *v) {
if(id<0 || id>=G.texture_pool_n || (size_t)id>=G.texture_slots)die("texture descriptor id",id); G.tslot[id].live=t!=NULL;
if(t) G.tslot[id].texture=*t; G.tslot[id].has_view=v!=NULL; if(v)G.tslot[id].view=*v;
}
static VkSamplerAddressMode wrap(unsigned w) { switch(w) {
case NVN_WRAP_MODE_REPEAT:return VK_SAMPLER_ADDRESS_MODE_REPEAT;
case NVN_WRAP_MODE_MIRRORED_REPEAT:return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
case NVN_WRAP_MODE_CLAMP_TO_EDGE:return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
case NVN_WRAP_MODE_CLAMP_TO_BORDER:return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;default:die("sampler wrap mode",w); } }
void mtl_reg_samp(int id,const samp_par *p) {
mtl_init(); if(id<0 || id>=LIMIT_OBJECTS || !p)die("sampler descriptor id",id); SSlot *s=&G.sslot[id];
if(s->live) { if(G.active)die("sampler re-register in flight",id); finish_at(WAIT_SAMPLER);vkDestroySampler(G.device,s->sampler,NULL); }
s->source=*p;
VkSamplerCreateInfo i={.sType=VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,
.magFilter=p->magf==NVN_MAG_FILTER_NEAREST?VK_FILTER_NEAREST:VK_FILTER_LINEAR,
.minFilter=(p->minf==NVN_MIN_FILTER_NEAREST || p->minf==NVN_MIN_FILTER_NEAREST_MIPMAP_NEAREST || p->minf==NVN_MIN_FILTER_NEAREST_MIPMAP_LINEAR)?VK_FILTER_NEAREST:VK_FILTER_LINEAR,
.mipmapMode=(p->minf==NVN_MIN_FILTER_NEAREST_MIPMAP_LINEAR || p->minf==NVN_MIN_FILTER_LINEAR_MIPMAP_LINEAR)?VK_SAMPLER_MIPMAP_MODE_LINEAR:VK_SAMPLER_MIPMAP_MODE_NEAREST,
.addressModeU=wrap(p->ws),.addressModeV=wrap(p->wt),.addressModeW=wrap(p->wr),.minLod=p->lod_min,.maxLod=p->lod_max,
.mipLodBias=p->lod_bias,.anisotropyEnable=p->aniso>1,.maxAnisotropy=p->aniso>1?p->aniso:1,
.compareEnable=p->cmp_mode==NVN_COMPARE_MODE_COMPARE_R_TO_TEXTURE,.compareOp=(VkCompareOp)(p->cmp_func-1),
.borderColor=VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK};
if(p->border[0]==0 && p->border[1]==0 && p->border[2]==0 && p->border[3]==1)
i.borderColor=VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK;
else if(p->border[0]==1 && p->border[1]==1 && p->border[2]==1 && p->border[3]==1)
i.borderColor=VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
else if(p->border[0] || p->border[1] || p->border[2] || p->border[3]) {
fprintf(stderr,"[nvn-vulkan] unsupported sampler border rgba=%g,%g,%g,%g wrap=%u,%u,%u\n",
p->border[0],p->border[1],p->border[2],p->border[3],p->ws,p->wt,p->wr);
die("custom sampler border color",id);
}
CHECK(vkCreateSampler(G.device,&i,NULL,&s->sampler)); s->live=1;
}
void mtl_set_tex_pool_n(int n) {
/* NVN handles encode a 20-bit texture descriptor ID. Descriptor slots are
* CPU metadata, independent of the number of resident Vulkan images. */
if(n<0 || n>(1<<20))die("texture pool capacity",n);
if((size_t)n>G.texture_slots) {
TSlot *slots=realloc(G.tslot,(size_t)n*sizeof(*slots));
if(!slots)die("texture descriptor allocation",n);
memset(slots+G.texture_slots,0,((size_t)n-G.texture_slots)*sizeof(*slots));
G.tslot=slots;G.texture_slots=(size_t)n;
}
G.texture_pool_n=n;
fprintf(stderr,"[nvn-vulkan] texture descriptor slots=%d resident image limit=%d\n",n,LIMIT_OBJECTS);
}
static uint8_t *read_file(const char *name,size_t *size) {
char path[1200]; if(!G.shader_root[0] || snprintf(path,sizeof(path),"%s/%s",G.shader_root,name)>=(int)sizeof(path))die("shader cache path",0);
FILE *f=fopen(path,"rb"); if(!f)die(path,0); if(fseek(f,0,SEEK_END))die("shader cache seek",0);
long n=ftell(f); if(n<0 || n>64*1024*1024 || fseek(f,0,SEEK_SET))die("shader cache file size",n);
uint8_t *bytes=malloc(n?n:1); if(!bytes || fread(bytes,1,n,f)!=(size_t)n)die("shader cache read",n);
fclose(f);*size=n;return bytes;
}
static uint8_t *buffer_image_module(uint8_t *bytes,size_t *size,VShader *shader) {
uint32_t *w=(uint32_t *)bytes;unsigned bound=w[3];if(bound>1000000)die("buffer image id bound",bound);
uint32_t *definition=calloc(bound,4),*variable=calloc(bound,4),*loaded=calloc(bound,4),*pointers=calloc(bound,4);
if(!definition||!variable||!loaded||!pointers)die("buffer image audit allocation",bound);
for(size_t o=5;o<*size/4;) {unsigned n=w[o]>>16,op=w[o]&65535;if(!n||n>*size/4-o)die("buffer image instruction",o);
if((op==25||op==27||op==32)&&w[o+1]<bound)definition[w[o+1]]=o;o+=n;}
unsigned next=bound,count=0;
for(size_t o=5;o<*size/4;o+=w[o]>>16)if((w[o]&65535)==59&&w[o+1]<bound) {
uint32_t p=definition[w[o+1]];
if(!p||(w[p]&65535)!=32||w[p+2]!=0)continue;
uint32_t s=w[p+3]<bound?definition[w[p+3]]:0;
if(!s||(w[s]&65535)!=27)continue;
uint32_t im=w[s+2]<bound?definition[w[s+2]]:0;
if(!im||(w[im]&65535)!=25||w[im+3]!=5)continue;
unsigned id=w[o+2],image=w[im+1];if(id>=bound)die("buffer image variable id",id);
variable[id]=image;if(!pointers[image])pointers[image]=next++;
int binding=-1;
for(size_t d=5;d<*size/4;d+=w[d]>>16)if((w[d]&65535)==71&&w[d]>>16==4&&w[d+1]==id&&w[d+2]==33)binding=w[d+3];
int found=0;for(unsigned i=0;i<shader->h.nb;i++)if((int)shader->b[i].binding==binding){if(!(shader->b[i].kind==4&&shader->b[i].type==1)&&!(shader->b[i].kind==10&&shader->b[i].type==4))die("buffer image metadata",binding); /* dmsh_vk.py 已标成 texel buffer | already marked texel buffer by dmsh_vk.py */shader->b[i].kind=10;shader->b[i].type=4;found=1;}
if(!found)die("buffer image descriptor binding",binding);count++;
}
if(!count){free(definition);free(variable);free(loaded);free(pointers);return bytes;}
uint32_t *out=malloc(*size+4*(next-bound)*4);if(!out)die("buffer image module allocation",*size);memcpy(out,w,20);out[3]=next;size_t at=5;unsigned extracts=0;
for(size_t o=5;o<*size/4;o+=w[o]>>16) {
unsigned n=w[o]>>16,op=w[o]&65535;memcpy(out+at,w+o,n*4);
if(op==25&&w[o+1]<bound&&pointers[w[o+1]]){at+=n;uint32_t ptr[]={4u<<16|32,pointers[w[o+1]],0,w[o+1]};memcpy(out+at,ptr,16);at+=4;continue;}
if(op==59&&w[o+2]<bound&&variable[w[o+2]])out[at+1]=pointers[variable[w[o+2]]];
if(op==61&&w[o+3]<bound&&variable[w[o+3]]){out[at+1]=variable[w[o+3]];if(w[o+2]>=bound)die("buffer image load id",w[o+2]);loaded[w[o+2]]=out[at+1];}
if(op==100&&w[o+3]<bound&&loaded[w[o+3]]){if(n!=4||w[o+1]!=loaded[w[o+3]])die("buffer image extraction",w[o+2]);out[at]=4u<<16|83;extracts++;}
if(((op>=87&&op<=94)||op==96||op==97||op==105)&&n>3&&w[o+3]<bound&&loaded[w[o+3]])die("buffer image cannot use sampler",op);
at+=n;
}
if(!extracts)die("buffer image had no image extraction",count);
fprintf(stderr,"[nvn-vulkan] samplerless buffer adaptation shader=%s descriptors=%u extractions=%u\n",shader->key,count,extracts);
free(definition);free(variable);free(loaded);free(pointers);free(bytes);*size=at*4;return (uint8_t *)out;
}
static uint64_t control_hash(const void *control,uint32_t stage) {
const uint8_t *bytes=control;uint64_t hash=14695981039346656037ULL^stage;
for(unsigned i=0;i<0x880;i++){hash^=bytes[i];hash*=1099511628211ULL;}return hash;
}
static ShaderEntry *shader_entry(const void *control,uint32_t stage) {
if(!control)die("null shader control",stage);
if(!G.shader_index) { G.shader_index=read_file("shader_index.bin",&G.index_bytes);
if(G.index_bytes<12)die("shader index header",G.index_bytes); uint32_t *h=(uint32_t *)G.shader_index;
if(h[0]!=0x494b5644 || h[1]!=1 || G.index_bytes!=12+(size_t)h[2]*(20+0x880))die("shader index schema",h[0]); }
if(!G.shader_entries){
uint32_t count=((uint32_t *)G.shader_index)[2];if(count>1000000)die("shader control index count",count);
size_t capacity=16;while(capacity<(size_t)count*2)capacity*=2;
G.shader_entries=calloc(capacity,sizeof(*G.shader_entries));if(!G.shader_entries)die("shader control index allocation",capacity);
G.shader_entry_capacity=capacity;const uint8_t *entry=G.shader_index+12;
for(uint32_t i=0;i<count;i++,entry+=20+0x880){uint32_t st;memcpy(&st,entry+16,4);uint64_t hash=control_hash(entry+20,st);size_t slot=hash&(capacity-1);
while(G.shader_entries[slot].entry){const uint8_t *old=G.shader_entries[slot].entry;
if(G.shader_entries[slot].hash==hash&&!memcmp(old+16,entry+16,4+0x880))break;
slot=(slot+1)&(capacity-1);}
/* Preserve the first matching verified entry, including duplicates. */
if(!G.shader_entries[slot].entry)G.shader_entries[slot]=(ShaderEntry){entry,hash,0};
}
fprintf(stderr,"[nvn-vulkan] SHADER_CONTROL_INDEX entries=%u slots=%zu bytes=%zu full_control_verified=1\n",count,capacity,capacity*sizeof(*G.shader_entries));
}
uint64_t hash=control_hash(control,stage);size_t slot=hash&(G.shader_entry_capacity-1);
while(G.shader_entries[slot].entry){ShaderEntry *candidate=&G.shader_entries[slot];uint32_t st;memcpy(&st,candidate->entry+16,4);
if(candidate->hash==hash&&st==stage&&!memcmp(candidate->entry+20,control,0x880))return candidate;
slot=(slot+1)&(G.shader_entry_capacity-1);}
return NULL;
}
/* DM_VK_VRS=WxH[:hash,...]:对列出的像素着色器用管线级可变着色率(VK_KHR_fragment_shading_rate),每 W×H 像素块只着色一次;
* 深度、覆盖、几何边缘仍按全分辨率。不写哈希时只作用于角色选择 / 场景的前向+光照着色器 5c1ca4e7c3e4657c。驱动不支持时忽略。
* DM_VK_VRS=WxH[:hash,...]: pipeline fragment shading rate (VK_KHR_fragment_shading_rate) for the listed pixel shaders, shading once per W×H block;
* depth, coverage and geometry edges stay at full resolution. Without hashes it applies only to the forward+ lighting shader 5c1ca4e7c3e4657c. Ignored when the driver lacks support. */
static VkExtent2D vrs_rate(const char *key) {
const char *e=getenv("DM_VK_VRS");unsigned w,h;if(!G.vrs || !e || sscanf(e,"%ux%u",&w,&h)!=2 || !w || !h || w>4 || h>4)return (VkExtent2D){0,0};
const char *list=strchr(e,':');list=list?list+1:"5c1ca4e7c3e4657c";
for(const char *q=list;*q;){size_t n=strcspn(q,",");if(n==16 && !memcmp(q,key,16))return (VkExtent2D){w,h};q+=n;if(*q)q++;}
return (VkExtent2D){0,0};
}
static VShader *shader_get(ShaderEntry *slot,uint32_t stage) {
if(slot->shader)return &G.shaders[slot->shader-1];
const uint8_t *entry=slot->entry;char key[17]={0};memcpy(key,entry,16);
for(int i=0;i<G.nshader;i++)if(!strcmp(G.shaders[i].key,key)){slot->shader=i+1;return &G.shaders[i];}
slot->shader=G.nshader+1;
if(G.nshader==LIMIT_OBJECTS)die("shader object limit",G.nshader); VShader *s=&G.shaders[G.nshader++]; strcpy(s->key,key);s->vrs=vrs_rate(key);
char name[40];snprintf(name,sizeof(name),"%s.vkmeta",key);size_t size=0;uint8_t *bytes=read_file(name,&size);
if(size<sizeof(RHeader))die("shader metadata header",size);memcpy(&s->h,bytes,sizeof(RHeader));
if(s->h.magic!=0x4d4b5644 || s->h.version!=1 || s->h.stage!=stage || s->h.nb>LIMIT_BINDINGS || s->h.na>32 || s->h.ncap>32 || s->h.c1n>4096)
die("shader metadata bounds",stage);
size_t expected=sizeof(RHeader)+s->h.nb*sizeof(RBinding)+s->h.na*8+s->h.ncap*4+s->h.c1n;
if(size!=expected)die("shader metadata size",size);uint8_t *p=bytes+sizeof(RHeader);
memcpy(s->b,p,s->h.nb*sizeof(RBinding));p+=s->h.nb*sizeof(RBinding);memcpy(s->attr,p,s->h.na*8);p+=s->h.na*8;
memcpy(s->caps,p,s->h.ncap*4);p+=s->h.ncap*4;
for(uint32_t i=0;i<s->h.ncap;i++) {
unsigned cap=s->caps[i];VkSubgroupFeatureFlags feature=0;
if(cap>=61&&cap<=68){const VkSubgroupFeatureFlags features[]={VK_SUBGROUP_FEATURE_BASIC_BIT,VK_SUBGROUP_FEATURE_VOTE_BIT,VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,VK_SUBGROUP_FEATURE_BALLOT_BIT,VK_SUBGROUP_FEATURE_SHUFFLE_BIT,VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,VK_SUBGROUP_FEATURE_CLUSTERED_BIT,VK_SUBGROUP_FEATURE_QUAD_BIT};feature=features[cap-61];}
if(feature && (G.subgroup.supportedStages&(stage==5?VK_SHADER_STAGE_COMPUTE_BIT:stage==1?VK_SHADER_STAGE_FRAGMENT_BIT:VK_SHADER_STAGE_VERTEX_BIT)) && (G.subgroup.supportedOperations&feature))continue;
if(cap==51 && stage==1)continue; /* DerivativeControl is core fragment functionality. */
if(cap==25 && G.gather_extended)continue; /* ImageGatherExtended: textureGatherOffset 非常量偏移 | non-constant offsets */
if(cap==4427 && G.draw_parameters)continue; /* DrawParameters: gl_BaseVertex / gl_BaseInstance */
if(cap!=1 && cap!=46 && cap!=47 && cap!=50 && cap!=55 && cap!=56){fprintf(stderr,"[nvn-vulkan] shader feature key=%s stage=%u cap=%u\n",key,stage,cap);die("shader feature needs device/semantic adaptation",cap);}
}
if(s->h.c1n){s->c1=buffer_make(65536,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);memcpy(s->c1.map,p,s->h.c1n);}free(bytes);
if(s->h.reserved) {
/* Metadata records the exact uncompressed size. zlib validates gzip
* CRC32 and ISIZE; reject trailing/concatenated streams and short data.
* The IR is exactly the offline-validated original SPIR-V, unchanged.
*/
uint32_t expected_size=s->h.reserved;
if(expected_size<20 || expected_size%4 || expected_size>16*1024*1024)die("compressed SPIR-V declared length",expected_size);
snprintf(name,sizeof(name),"%s.spv.gz",key);uint8_t *compressed=read_file(name,&size);
if(size<18 || size>UINT32_MAX || compressed[0]!=0x1f || compressed[1]!=0x8b || compressed[2]!=8)die("shader gzip header",size);
bytes=malloc(expected_size);if(!bytes)die("SPIR-V inflate allocation",expected_size);
z_stream stream={.next_in=compressed,.avail_in=(uInt)size,.next_out=bytes,.avail_out=expected_size};
int initialized=inflateInit2(&stream,15+16);if(initialized!=Z_OK)die("shader gzip initialize",initialized);
int result=inflate(&stream,Z_FINISH);int complete=result==Z_STREAM_END && stream.total_out==expected_size && stream.avail_in==0;
int ended=inflateEnd(&stream);free(compressed);
if(!complete || ended!=Z_OK)die("shader gzip CRC/length/trailing-data validation",result);
size=expected_size;
} else {snprintf(name,sizeof(name),"%s.spv",key);bytes=read_file(name,&size);}
if(size%4 || size<20 || ((uint32_t *)bytes)[0]!=0x07230203)die("SPIR-V module",size);
bytes=buffer_image_module(bytes,&size,s);
uint32_t *words=(uint32_t *)bytes;int fetch=0,sampling=0;
for(size_t offset=5;offset<size/4;) {
unsigned length=words[offset]>>16,op=words[offset]&0xffff;
if(!length || length>size/4-offset)die("SPIR-V instruction bounds",offset);
if(op==95 || op==313)fetch=1; /* OpImageFetch / OpImageSparseFetch */
if((op>=87&&op<=94) || op==96 || op==97 || op==105 || (op>=305&&op<=312) || op==314 || op==315)sampling=1;
offset+=length;
}
(void)fetch;(void)sampling;
unsigned resource_bound=words[3];if(resource_bound>1000000)die("SPIR-V resource id bound",resource_bound);
uint64_t *resource=calloc(resource_bound,sizeof(*resource));if(!resource)die("SPIR-V resource audit allocation",resource_bound);
for(size_t o=5;o<size/4;o+=words[o]>>16)if((words[o]&65535)==71&&words[o]>>16==4&&words[o+2]==33&&words[o+1]<resource_bound)
for(unsigned b=0;b<s->h.nb;b++)if(s->b[b].binding==words[o+3])resource[words[o+1]]=1ull<<b;
uint64_t extracted=0,used_sampler=0;
for(size_t o=5;o<size/4;o+=words[o]>>16){unsigned op=words[o]&65535,n=words[o]>>16;
if((op==61||op==83||op==100)&&n>=4&&words[o+2]<resource_bound&&words[o+3]<resource_bound){resource[words[o+2]]=resource[words[o+3]];if(op==100)extracted|=resource[words[o+3]];}
if(op==86&&n>=5&&words[o+2]<resource_bound&&words[o+3]<resource_bound)resource[words[o+2]]=resource[words[o+3]];
if((op==89||op==90||op==93||op==94||op==97||op==307||op==308||op==311||op==312||op==315)&&n>=4&&words[o+3]<resource_bound)s->dref_bindings|=resource[words[o+3]];
if(((op>=87&&op<=94)||op==96||op==97||op==105||(op>=305&&op<=312)||op==314||op==315)&&n>=4&&words[o+3]<resource_bound)used_sampler|=resource[words[o+3]];
}
s->fetch_bindings=extracted&~used_sampler;free(resource);
/* DRIVER resources are the original binding tables, not zero constants.
* Verify every direct access is a statically known table field before
* constructing them from live NVN bindings. Reject unknown/dynamic reads.
*/
unsigned bound=words[3];if(bound>1000000)die("SPIR-V id bound",bound);
uint32_t *constants=calloc(bound,sizeof(*constants));uint8_t *known=calloc(bound,1);
if(!constants || !known)die("SPIR-V driver audit allocation",bound);
for(size_t o=5;o<size/4;o+=words[o]>>16)if((words[o]&0xffff)==43 && words[o]>>16==4 && words[o+2]<bound){constants[words[o+2]]=words[o+3];known[words[o+2]]=1;}
for(unsigned i=0;i<s->h.nb;i++)if(s->b[i].kind==8) {
RBinding *b=&s->b[i];uint32_t variable=0;
if(b->slot!=0 && b->slot!=2)die("driver constant bank",b->slot);
for(size_t o=5;o<size/4;o+=words[o]>>16)if((words[o]&0xffff)==71 && words[o]>>16==4 && words[o+2]==33 && words[o+3]==b->binding)variable=words[o+1];
if(!variable)die("driver constant variable",b->binding);
for(size_t o=5;o<size/4;o+=words[o]>>16)if(((words[o]&0xffff)==65 || (words[o]&0xffff)==66) && words[o+3]==variable) {
if(words[o]>>16!=7)die("driver access shape",b->binding);
uint32_t a=words[o+4],v=words[o+5],c=words[o+6];
if(a>=bound||v>=bound||c>=bound||!known[a]||!known[v]||!known[c]||constants[a]||constants[c]>3)die("dynamic driver constant access",b->binding);
uint64_t offset=(uint64_t)constants[v]*16+constants[c]*4;int valid=0;
if(b->slot==0){unsigned base=stage==5?0x310:stage==1?0x510:0x110;
valid=offset>=base && offset<base+256 && (offset-base)%16<12;
if(stage==5 && offset>=0x210 && offset<0x310 && (offset-0x210)%16<12)valid=1;
}else valid=(offset>=0x120&&offset<0x168&&(offset-0x120)%8==0)||(offset>=0x168&&offset<0x568&&(offset-0x168)%8==0)||(offset>=0x568&&offset<0x968&&(offset-0x568)%8==0);
if(!valid)die("driver constant access outside verified binding tables",offset);
}
}
free(constants);free(known);
/* 偏移随绘制变化的缓冲改用动态描述符,偏移在绑定时传入,换偏移不必重写描述符集。
* Adreno 绑定带动态偏移的集时会把整个集拷进命令缓冲,所以这些缓冲改写到单独的
* set+2(改 SPIR-V 的 DescriptorSet 装饰),贴图所在的集只在贴图变化时重绑。
* 每个着色器最多用设备上限的一半(VS/PS 共用一个管线布局)。DM_VK_DYNAMIC=0 关闭。
* Buffers whose offset changes per draw use dynamic descriptors: the offset is passed at bind
* time, so an offset change needs no new descriptor set. Adreno copies the whole set into the
* command buffer when binding one with dynamic offsets, so these buffers move to their own
* set+2 (by rewriting the SPIR-V DescriptorSet decoration) and the texture set is rebound only
* when textures change. Each shader takes at most half the device limit (VS and PS share one
* pipeline layout). DM_VK_DYNAMIC=0 disables. */
static int dynamic=-1;if(dynamic<0){const char *e=getenv("DM_VK_DYNAMIC");dynamic=(!e||strcmp(e,"0"))&&G.properties.limits.maxBoundDescriptorSets>=4;}
if(dynamic){unsigned ub=G.properties.limits.maxDescriptorSetUniformBuffersDynamic/2,sb=G.properties.limits.maxDescriptorSetStorageBuffersDynamic/2;
for(uint32_t i=0;i<s->h.nb;i++){RBinding *b=&s->b[i];if(b->kind!=2&&b->kind!=3&&b->kind!=8&&b->kind!=9)continue;
if(b->type==VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER&&ub){b->type=VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;ub--;s->dyn_mask|=1ull<<i;}
else if(b->type==VK_DESCRIPTOR_TYPE_STORAGE_BUFFER&&sb){b->type=VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC;sb--;s->dyn_mask|=1ull<<i;}}
for(uint32_t i=0;i<s->h.nb;i++)if(s->dyn_mask>>i&1){
unsigned rank=0;for(uint32_t j=0;j<s->h.nb;j++)if((s->dyn_mask>>j&1)&&s->b[j].binding<s->b[i].binding)rank++;
s->dyn_index[rank]=(uint8_t)i;s->ndyn++;}
if(s->ndyn){uint32_t *binding_of=calloc(bound,sizeof(*binding_of));if(!binding_of)die("SPIR-V set rewrite allocation",bound);unsigned moved=0;
for(size_t o=5;o<size/4;o+=words[o]>>16)if((words[o]&0xffff)==71&&words[o]>>16==4&&words[o+2]==33&&words[o+1]<bound)binding_of[words[o+1]]=words[o+3]+1;
for(size_t o=5;o<size/4;o+=words[o]>>16)if((words[o]&0xffff)==71&&words[o]>>16==4&&words[o+2]==34&&words[o+1]<bound&&binding_of[words[o+1]])
for(uint32_t i=0;i<s->h.nb;i++)if((s->dyn_mask>>i&1)&&s->b[i].binding==binding_of[words[o+1]]-1){
if(words[o+3]!=s->b[i].set)die("SPIR-V descriptor set mismatch",words[o+3]);words[o+3]+=2;moved++;}
free(binding_of);if(moved!=s->ndyn)die("SPIR-V dynamic binding rewrite",moved);}}
VkShaderModuleCreateInfo mi={.sType=VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,.codeSize=size,.pCode=(uint32_t *)bytes};
CHECK(vkCreateShaderModule(G.device,&mi,NULL,&s->module));free(bytes);
fprintf(stderr,"[nvn-vulkan] original shader key=%s stage=%u loaded\n",s->key,stage);
VkDescriptorSetLayoutBinding bindings[2][LIMIT_BINDINGS];uint32_t count[2]={0};for(uint32_t i=0;i<s->h.nb;i++){
if(s->b[i].count!=1 || s->b[i].set!=(stage==1?1u:0u))die("shader descriptor set/count",s->b[i].set);
unsigned d=s->dyn_mask>>i&1;
bindings[d][count[d]++]=(VkDescriptorSetLayoutBinding){s->b[i].binding,(VkDescriptorType)s->b[i].type,1,stage==0?VK_SHADER_STAGE_VERTEX_BIT:stage==1?VK_SHADER_STAGE_FRAGMENT_BIT:VK_SHADER_STAGE_COMPUTE_BIT,NULL}; }
for(unsigned d=0;d<2;d++){if(d&&!count[d])break;
VkDescriptorSetLayoutCreateInfo li={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,.bindingCount=count[d],.pBindings=bindings[d]};
CHECK(vkCreateDescriptorSetLayout(G.device,&li,NULL,d?&s->dyn_layout:&s->layout));}
return s;
}
/* 管线布局里没有对应着色器的集位用空布局占位 | empty layout for set numbers no shader uses */
static VkDescriptorSetLayout empty_set_layout(void) {
if(!G.empty_layout){VkDescriptorSetLayoutCreateInfo li={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO};CHECK(vkCreateDescriptorSetLayout(G.device,&li,NULL,&G.empty_layout));}
return G.empty_layout;
}
void mtl_prog_release(prog_t *p) { (void)p; /* Programs own only immutable shared shader-cache entries; no per-program GPU allocation. */ }
static void aligned_writeback(void) {
for(int i=0;i<G.naligned;i++)if(G.aligned[i].written){AlignedBinding *b=&G.aligned[i];uint64_t offset=0;
VPool *p=pool_find(b->range.addr,b->range.size,&offset);if(!p)die("aligned binding pool lifetime",b->range.addr);
all_barrier();VkBufferCopy copy={0,offset,b->range.size};vkCmdCopyBuffer(G.batch->command,b->buffer->b,p->v.b,1,&copy);
}
G.naligned=0;
}
static int depth_read_only(void) {
const ds_st *d=&G.state.ds;if(d->dw)return 0;
if(!d->st || (!G.state.stencil_write[0]&&!G.state.stencil_write[1]))return 1;
return d->fail_f==NVN_STENCIL_OP_KEEP&&d->zfail_f==NVN_STENCIL_OP_KEEP&&d->zpass_f==NVN_STENCIL_OP_KEEP&&d->fail_b==NVN_STENCIL_OP_KEEP&&d->zfail_b==NVN_STENCIL_OP_KEEP&&d->zpass_b==NVN_STENCIL_OP_KEEP;
}
/* 着色器声明、游戏没绑的贴图槽(贴图号无效或槽位空):有空描述符就写空视图,记一次日志;没有就照旧停 |
* a texture slot the shader declares but the game left unbound (invalid id or empty slot): with null descriptors write a null view and log once; otherwise stop as before */
static VkSampler fetch_sampler(void) {
if(!G.fetch_sampler){VkSamplerCreateInfo ci={.sType=VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO,.magFilter=VK_FILTER_NEAREST,.minFilter=VK_FILTER_NEAREST,.mipmapMode=VK_SAMPLER_MIPMAP_MODE_NEAREST,.addressModeU=VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,.addressModeV=VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,.addressModeW=VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,.maxLod=VK_LOD_CLAMP_NONE};CHECK(vkCreateSampler(G.device,&ci,NULL,&G.fetch_sampler));}
return G.fetch_sampler;
}
static int texture_unbound(unsigned tid,const VShader *s,const RBinding *b,const char *what) {
if(tid<(unsigned)G.texture_pool_n && tid<G.texture_slots && G.tslot[tid].live)return 0;
if(!G.null_descriptor)die(what,tid);
static int logged;if(logged<16){logged++;fprintf(stderr,"[nvn-vulkan] unbound texture -> null descriptor shader=%s stage=%u slot=%d kind=%u id=%u\n",s->key,s->h.stage,b->slot,b->kind,tid);}
return 1;
}
static void collect_image_uses(VShader *s) {
if(!s)return;
for(unsigned i=0;i<s->h.nb;i++) {RBinding *b=&s->b[i];if(b->kind!=4&&b->kind!=6)continue;
if(b->slot<0 || b->slot>=(b->kind==6?32:128))die("image-use shader slot",b->slot);
uint64_t handle=b->kind==6?G.state.img[s->h.stage][b->slot]:G.state.tex[s->h.stage][b->slot];unsigned tid=handle&0xfffff;
if(texture_unbound(tid,s,b,"image-use texture descriptor"))continue;
uint64_t serial=G.tslot[tid].texture.serial;unsigned j=0;while(j<G.nimage_uses&&G.image_uses[j].serial!=serial)j++;
if(j==G.nimage_uses){if(j==2*LIMIT_BINDINGS)die("image-use capacity",j);G.image_uses[G.nimage_uses++]=(ImageUse){serial,0};}
G.image_uses[j].roles|=b->kind==6?2u:1u;
}
}
static int storage_image_use(uint64_t serial) {
for(unsigned i=0;i<G.nimage_uses;i++)if(G.image_uses[i].serial==serial)return (G.image_uses[i].roles&2)!=0;
return 0;
}
static int image_sampled(uint64_t serial) {
for(unsigned i=0;i<G.nimage_uses;i++)if(G.image_uses[i].serial==serial)return (G.image_uses[i].roles&1)!=0;
return 0;
}
static VkImageLayout sampled_layout(VTexture *t,unsigned stage) {
if(storage_image_use(t->serial))return VK_IMAGE_LAYOUT_GENERAL;
if(stage!=5){
if(G.state.rt.depth && G.state.rt.depth->serial==t->serial){G.depth_sampled=1;
if(depth_read_only())return VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
/* 没有 VK_EXT_attachment_feedback_loop_layout(Adreno 官方驱动):附件与采样都用 GENERAL + 自依赖
* Without VK_EXT_attachment_feedback_loop_layout (Adreno proprietary driver): GENERAL for both attachment and sampling + self-dependency */
if(!G.feedback_layout){G.general_feedback=1;return VK_IMAGE_LAYOUT_GENERAL;}
G.feedback_flags|=VK_PIPELINE_CREATE_DEPTH_STENCIL_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT;
return VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT;
}
for(int i=0;i<G.state.rt.n;i++)if(G.state.rt.color[i]&&G.state.rt.color[i]->serial==t->serial){
if(!G.feedback_layout){G.general_feedback=1;return VK_IMAGE_LAYOUT_GENERAL;}
G.feedback_flags|=VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT;
return VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT;
}
}
return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
}
/* NVN permits comparison sampling of normalized color. Vulkan requires a
* depth image: transfer the identical R16/D16 or R32F/D32F element bits through
* a GPU buffer, retaining the original color attachment/storage image. */
static void comparison_image(VTexture *t) {
if(t->depth!=1 || t->source.d.target==NVN_TEXTURE_TARGET_1D || t->source.d.target==NVN_TEXTURE_TARGET_1D_ARRAY)
die("color comparison image dimensionality",t->source.d.target);
VkFormat f=t->format==VK_FORMAT_R16_UNORM?VK_FORMAT_D16_UNORM:t->format==VK_FORMAT_R32_SFLOAT?VK_FORMAT_D32_SFLOAT:VK_FORMAT_UNDEFINED;
if(f==VK_FORMAT_UNDEFINED)die("color comparison image format",t->format);
if(!t->shadow){
int cube=t->source.d.target==NVN_TEXTURE_TARGET_CUBEMAP||t->source.d.target==NVN_TEXTURE_TARGET_CUBEMAP_ARRAY;
VkImageCreateInfo ci={.sType=VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,.flags=cube?VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT:0,
.imageType=VK_IMAGE_TYPE_2D,.format=f,.extent={t->width,t->height,1},.mipLevels=t->source.d.levels,
.arrayLayers=t->source.L.layers,.samples=VK_SAMPLE_COUNT_1_BIT,.tiling=VK_IMAGE_TILING_OPTIMAL,
.usage=VK_IMAGE_USAGE_SAMPLED_BIT|VK_IMAGE_USAGE_TRANSFER_DST_BIT,.sharingMode=VK_SHARING_MODE_EXCLUSIVE};
CHECK(vkCreateImage(G.device,&ci,NULL,&t->shadow));VkMemoryRequirements r;vkGetImageMemoryRequirements(G.device,t->shadow,&r);
VkMemoryAllocateInfo ai={.sType=VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,.allocationSize=r.size,.memoryTypeIndex=memory_type(r.memoryTypeBits,VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)};
CHECK(vkAllocateMemory(G.device,&ai,NULL,&t->shadow_memory));CHECK(vkBindImageMemory(G.device,t->shadow,t->shadow_memory,0));
VkImageViewType type=cube?(t->source.L.layers==6?VK_IMAGE_VIEW_TYPE_CUBE:VK_IMAGE_VIEW_TYPE_CUBE_ARRAY):t->source.d.target==NVN_TEXTURE_TARGET_2D_ARRAY?VK_IMAGE_VIEW_TYPE_2D_ARRAY:VK_IMAGE_VIEW_TYPE_2D;
VkImageViewCreateInfo vi={.sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,.image=t->shadow,.viewType=type,.format=f,
.subresourceRange={VK_IMAGE_ASPECT_DEPTH_BIT,0,t->source.d.levels,0,t->source.L.layers}};
CHECK(vkCreateImageView(G.device,&vi,NULL,&t->shadow_view));t->shadow_format=f;t->shadow_layout=VK_IMAGE_LAYOUT_UNDEFINED;
fprintf(stderr,"[nvn-vulkan] COLOR_COMPARISON_ALIAS serial=%llu color=%u depth=%u size=%ux%u levels=%u layers=%u\n",(unsigned long long)t->serial,t->format,f,t->width,t->height,t->source.d.levels,t->source.L.layers);
}
if(t->shadow_version==t->version)return;
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
VkImageMemoryBarrier barrier={.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.srcAccessMask=t->shadow_layout==VK_IMAGE_LAYOUT_UNDEFINED?0:VK_ACCESS_SHADER_READ_BIT,.dstAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT,
.oldLayout=t->shadow_layout,.newLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,.srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.image=t->shadow,.subresourceRange={VK_IMAGE_ASPECT_DEPTH_BIT,0,t->source.d.levels,0,t->source.L.layers}};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,NULL,0,NULL,1,&barrier);
for(unsigned level=0;level<t->source.d.levels;level++){
unsigned width=t->width>>level,height=t->height>>level;if(!width)width=1;if(!height)height=1;
uint64_t bytes=(uint64_t)width*height*t->source.L.layers*(f==VK_FORMAT_D16_UNORM?2:4);
VBuffer *bridge=temporary((bytes+3)&~3ULL,VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy region={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,level,0,t->source.L.layers},.imageExtent={width,height,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,bridge->b,1,&region);
VkBufferMemoryBarrier bb={.sType=VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT,.dstAccessMask=VK_ACCESS_TRANSFER_READ_BIT,
.srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.buffer=bridge->b,.offset=0,.size=VK_WHOLE_SIZE};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,NULL,1,&bb,0,NULL);
region.imageSubresource.aspectMask=VK_IMAGE_ASPECT_DEPTH_BIT;
vkCmdCopyBufferToImage(G.batch->command,bridge->b,t->shadow,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,1,&region);
}
barrier.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;barrier.dstAccessMask=VK_ACCESS_SHADER_READ_BIT;
barrier.oldLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;barrier.newLayout=VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,0,NULL,0,NULL,1,&barrier);
t->shadow_layout=barrier.newLayout;t->shadow_version=t->version;
}
static void prepare_comparison_images(VShader *s) {
if(!s)return;
for(unsigned i=0;i<s->h.nb;i++)if(s->b[i].kind==4&&(s->dref_bindings&(1ull<<i))){
unsigned tid=G.state.tex[s->h.stage][s->b[i].slot]&0xfffff;
if(texture_unbound(tid,s,&s->b[i],"comparison texture descriptor"))continue;
VTexture *t=texture_get(&G.tslot[tid].texture,1);
if(aspect(t->format)==VK_IMAGE_ASPECT_COLOR_BIT)comparison_image(t);
}
}
static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding) {
if(!G.trace_frame||s->h.stage!=1||strcmp(s->key,G.trace_ui?"9a650561e5c40791":"5c1ca4e7c3e4657c")||G.ntrace_textures==24||t->depth!=1)return;
for(unsigned i=0;i<G.ntrace_textures;i++)if(G.trace_texture_serials[i]==t->serial)return;
uint64_t bytes=(uint64_t)t->width*t->height*t->source.L.layers*t->bpp;
if(bytes>32*1024*1024)return;
G.trace_texture_serials[G.ntrace_textures++]=t->serial;
all_barrier();VkImageLayout layout=t->layout;texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
VkImageAspectFlags flags=aspect(t->format)&VK_IMAGE_ASPECT_DEPTH_BIT?VK_IMAGE_ASPECT_DEPTH_BIT:VK_IMAGE_ASPECT_COLOR_BIT;
unsigned bpp=flags==VK_IMAGE_ASPECT_DEPTH_BIT?(t->format==VK_FORMAT_D16_UNORM?2:4):t->bpp;
for(unsigned level=0;level<t->source.d.levels;level++){
unsigned width=t->width>>level,height=t->height>>level;if(!width)width=1;if(!height)height=1;
bytes=(uint64_t)width*height*t->source.L.layers*bpp;
VBuffer *capture=temporary((bytes+3)&~3ULL,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy region={.imageSubresource={flags,level,0,t->source.L.layers},.imageExtent={width,height,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture->b,1,&region);
char name[160];snprintf(name,sizeof(name),"texture-%04llu-%llu-mip%u",(unsigned long long)G.present_count+1,(unsigned long long)t->serial,level);
trace_capture_queue(capture,bytes,name);
fprintf(stderr,"[nvn-vulkan] GPU_TEXTURE_CAPTURE name=%s draw=%llu serial=%llu slot=%d binding=%u format=%u nvn_format=%u extent=%u,%u layers=%u levels=%u mip=%u bpp=%u cpu_owned=%d\n",name,(unsigned long long)G.draws,(unsigned long long)t->serial,binding->slot,binding->binding,t->format,t->source.d.format,width,height,t->source.L.layers,t->source.d.levels,level,bpp,t->cpu_owned);
/* Compare streamed CPU backing with the actual GPU image. This is
* diagnostic data only; never substitute it for GPU-owned pixels. */
uint32_t decoded_format;int decoded_bpp;
if(t->source.L.layers==1&&nvn_bc_unpacked(t->source.d.format,&decoded_format,&decoded_bpp)&&t->source.mem){
int bw,bh;unsigned block=nvn_fmt_bpb(t->source.d.format,&bw,&bh);uint64_t row=(uint64_t)((width+bw-1)/bw)*block,rows=(height+bh-1)/bh;
uint8_t *linear=malloc(row*rows),*decoded=malloc((size_t)width*height*decoded_bpp);if(!linear||!decoded)die("CPU texture diagnostic allocation",bytes);
if(nvn_deswizzle(&t->source.d,level,0,t->source.mem,linear,row)||nvn_bc_decode(t->source.d.format,linear,row,width,height,decoded,(size_t)width*decoded_bpp))die("CPU texture diagnostic decode",t->serial);
char path[1400];snprintf(path,sizeof(path),"%s/%s-cpu.bin",getenv("DM_FRAME_DIR"),name);FILE *out=fopen(path,"wb");if(!out)die("CPU texture diagnostic output",0);
uint64_t cpu_bytes=(uint64_t)width*height*decoded_bpp;if(fwrite(decoded,1,cpu_bytes,out)!=cpu_bytes)die("CPU texture diagnostic write",cpu_bytes);fclose(out);free(linear);free(decoded);
fprintf(stderr,"[nvn-vulkan] CPU_TEXTURE_CAPTURE bytes=%llu path=%s\n",(unsigned long long)cpu_bytes,path);
}
}
texture_transition(t,layout);
}
static VkDescriptorSet shader_set_allocate(VShader *shader,unsigned dyn) {
unsigned need[DESCRIPTOR_TYPES]={0};for(unsigned binding=0;binding<shader->h.nb;binding++)if((shader->dyn_mask>>binding&1)==dyn)
for(unsigned type=0;type<DESCRIPTOR_TYPES;type++)if(shader->b[binding].type==descriptor_types[type])need[type]++;
int full=G.batch->descriptor_sets==8192;
for(unsigned i=0;i<DESCRIPTOR_TYPES;i++)if(G.batch->descriptor_used[i]+need[i]>descriptor_limits[i])full=1;
if(full){if(G.batch->nextra_descriptors==64)die("descriptor pool chunk limit",64);
G.batch->extra_descriptors[G.batch->nextra_descriptors++]=descriptor_pool_create();
G.batch->descriptor_sets=0;memset(G.batch->descriptor_used,0,sizeof(G.batch->descriptor_used));}
VkDescriptorPool pool=G.batch->nextra_descriptors?G.batch->extra_descriptors[G.batch->nextra_descriptors-1]:G.batch->descriptors;
VkDescriptorSetAllocateInfo ci={.sType=VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,.descriptorPool=pool,.descriptorSetCount=1,.pSetLayouts=dyn?&shader->dyn_layout:&shader->layout};
VkDescriptorSet set;CHECK(vkAllocateDescriptorSets(G.device,&ci,&set));G.batch->descriptor_sets++;
for(unsigned i=0;i<DESCRIPTOR_TYPES;i++)G.batch->descriptor_used[i]+=need[i];return set;
}
/* Driver tables live in persistent per-batch chunks. Each descriptor still
* spans 64 KiB as the shader declares it; only the first TABLE_BYTES are read,
* and every chunk keeps 64 KiB of zeroed tail so the span stays in bounds. */
static VkDescriptorBufferInfo table_bind(unsigned stage,int slot,const uint8_t *bytes) {
Batch *batch=G.batch;unsigned bank=slot==0?0:slot==2?1:2;
if(stage<6 && batch->table_last_valid[stage][bank] && !memcmp(batch->table_last[stage][bank],bytes,TABLE_BYTES)){
uint64_t o=batch->table_last_offset[stage][bank];return (VkDescriptorBufferInfo){batch->tables[o>>32].b,o&0xffffffffu,65536};}
unsigned chunk=batch->table_offset>>32;uint64_t off=batch->table_offset&0xffffffffu;
if(!batch->ntables || off+TABLE_STRIDE>TABLE_CHUNK){
if(batch->ntables && off)chunk++;
if(chunk==64)die("driver table chunk limit",chunk);
if(chunk==batch->ntables){batch->tables[batch->ntables++]=buffer_make(TABLE_CHUNK+65536,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);}
off=0;}
memcpy(batch->tables[chunk].map+off,bytes,TABLE_BYTES);
uint64_t packed=((uint64_t)chunk<<32)|off;batch->table_offset=packed+TABLE_STRIDE;
if(stage<6){memcpy(batch->table_last[stage][bank],bytes,TABLE_BYTES);batch->table_last_offset[stage][bank]=packed;batch->table_last_valid[stage][bank]=1;}
return (VkDescriptorBufferInfo){batch->tables[chunk].b,off,65536};
}
static VkDescriptorSet bind_shader(VShader *s) {
VkDescriptorSet set=VK_NULL_HANDLE;VkBufferView texel[LIMIT_BINDINGS];
VkWriteDescriptorSet w[LIMIT_BINDINGS];VkDescriptorBufferInfo bi[LIMIT_BINDINGS];VkDescriptorImageInfo ii[LIMIT_BINDINGS];
memset(bi,0,s->h.nb*sizeof(*bi));memset(ii,0,s->h.nb*sizeof(*ii));
for(uint32_t i=0;i<s->h.nb;i++) { RBinding *b=&s->b[i]; w[i]=(VkWriteDescriptorSet){.sType=VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET,
.dstSet=set,.dstBinding=b->binding,.descriptorCount=1,.descriptorType=(VkDescriptorType)b->type};
if(b->kind==1)bi[i]=(VkDescriptorBufferInfo){G.support.b,0,1392};
else if(b->kind==7) { if(!s->c1.b)die("missing shader c1",i);bi[i]=(VkDescriptorBufferInfo){s->c1.b,0,65536}; }
else if(b->kind==10) {
if(b->slot<0 || b->slot>=128)die("texel buffer slot",b->slot);
uint32_t tid=(b->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER?G.state.img[s->h.stage][b->slot]:G.state.tex[s->h.stage][b->slot])&0xfffff;
if(texture_unbound(tid,s,b,"unbound texel buffer")){texel[i]=VK_NULL_HANDLE;w[i].pTexelBufferView=&texel[i];continue;}
TSlot *slot=&G.tslot[tid];tex_t *t=&slot->texture;
if(t->d.target!=NVN_TEXTURE_TARGET_BUFFER||t->d.levels!=1||(slot->has_view&&(slot->view.set_layers||slot->view.set_levels)))die("texel buffer target/view",tid);
int nvn=slot->has_view&&slot->view.set_format?slot->view.format:t->d.format;
VkFormat f=format(nvn);static VkFormatProperties format_cache[256];static uint8_t format_known[256];VkFormatProperties properties;
if((unsigned)f<256 && format_known[f])properties=format_cache[f];
else{vkGetPhysicalDeviceFormatProperties(G.physical,f,&properties);if((unsigned)f<256){format_cache[f]=properties;format_known[f]=1;}}
VkFormatFeatureFlags required=b->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER?VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_BIT:VK_FORMAT_FEATURE_UNIFORM_TEXEL_BUFFER_BIT;
if(!(properties.bufferFeatures&required))die("texel buffer format feature",nvn);
uint64_t offset=0;VPool *p=b->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER?pool_read((uint64_t)(uintptr_t)t->mem,t->L.size,&offset):input_read((uint64_t)(uintptr_t)t->mem,t->L.size,&offset);VkBuffer buffer=p->v.b;
if(offset%G.properties.limits.minTexelBufferOffsetAlignment){VBuffer *aligned=temporary((t->L.size+3)&~3ULL,VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT);
if(b->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER||offset%4||t->L.size%4)die("writable/word-unaligned texel buffer",offset);
all_barrier();VkBufferCopy copy={offset,0,t->L.size};vkCmdCopyBuffer(G.batch->command,p->v.b,aligned->b,1,&copy);all_barrier();buffer=aligned->b;offset=0;}
unsigned vslot=(unsigned)((((uint64_t)(uintptr_t)buffer>>4)^offset*0x9e3779b1u^(uint64_t)f*131u^t->L.size)%512u);
if(G.batch->texel_views[vslot].view && G.batch->texel_views[vslot].buffer==buffer && G.batch->texel_views[vslot].format==f &&
G.batch->texel_views[vslot].offset==offset && G.batch->texel_views[vslot].range==t->L.size)
texel[i]=G.batch->texel_views[vslot].view;
else{
if(G.batch->nbuffer_view==LIMIT_WRITES)die("texel buffer view count",G.batch->nbuffer_view);
VkBufferViewCreateInfo vi={.sType=VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO,.buffer=buffer,.format=f,.offset=offset,.range=t->L.size};
CHECK(vkCreateBufferView(G.device,&vi,NULL,&G.batch->buffer_views[G.batch->nbuffer_view]));
G.batch->texel_views[vslot].buffer=buffer;G.batch->texel_views[vslot].format=f;G.batch->texel_views[vslot].offset=offset;
G.batch->texel_views[vslot].range=t->L.size;G.batch->texel_views[vslot].view=G.batch->buffer_views[G.batch->nbuffer_view];
texel[i]=G.batch->texel_views[vslot].view;G.batch->nbuffer_view++;}
w[i].pTexelBufferView=&texel[i];
if(b->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)mark_write((uint64_t)(uintptr_t)t->mem,t->L.size);
continue;
}
else if(b->kind==8) {
/* 驱动表只取决于本阶段的缓冲 / 纹理 / 采样器绑定:自上次建表后没有绑定操作就直接复用,不再每次 draw 重建并比较 2.4 KB
* The driver table depends only on this stage's buffer / texture / sampler bindings: with no bind op since it was last built, reuse it
* instead of rebuilding and comparing 2.4 KB per draw */
unsigned stage=s->h.stage,bank=b->slot==0?0:b->slot==2?1:2;
if(stage<6 && G.batch->table_last_valid[stage][bank] && G.batch->table_last_gen[stage][bank]==G.bind_gen[stage]){
uint64_t o=G.batch->table_last_offset[stage][bank];bi[i]=(VkDescriptorBufferInfo){G.batch->tables[o>>32].b,o&0xffffffffu,65536};w[i].pBufferInfo=&bi[i];continue;}
uint8_t table_bytes[TABLE_BYTES];memset(table_bytes,0,sizeof(table_bytes));struct {uint8_t *map;} table_view={table_bytes},*table=&table_view;
if(b->slot==0) {
unsigned base=s->h.stage==5?0x310:s->h.stage==1?0x510:0x110;
for(unsigned j=0;j<16;j++) {Range r=G.state.storage[s->h.stage][j];if(r.size>UINT32_MAX)die("driver buffer size",r.size);uint32_t n=r.size;memcpy(table->map+base+j*16,&r.addr,8);memcpy(table->map+base+j*16+8,&n,4);
if(s->h.stage==5){r=G.state.uniform[5][j];if(r.size>UINT32_MAX)die("driver uniform size",r.size);n=r.size;memcpy(table->map+0x210+j*16,&r.addr,8);memcpy(table->map+0x218+j*16,&n,4);}}
}else if(b->slot==2) {
for(unsigned j=0;j<128;j++){uint32_t t=G.state.tex[s->h.stage][j],sp=G.state.samp[s->h.stage][j];memcpy(table->map+0x168+j*8,&t,4);memcpy(table->map+0x568+j*8,&sp,4);}
for(unsigned j=0;j<9;j++){uint32_t image=G.state.img[s->h.stage][j];memcpy(table->map+0x120+j*8,&image,4);}
}else die("driver table bank",b->slot);
bi[i]=table_bind(s->h.stage,b->slot,table_bytes);if(stage<6)G.batch->table_last_gen[stage][bank]=G.bind_gen[stage];
}
else if(b->kind==2 || b->kind==3 || b->kind==9) {
if(b->slot<0 || b->slot>=16)die("shader buffer slot",b->slot);
Range r=(b->kind==2||b->kind==9)?G.state.uniform[s->h.stage][b->slot]:G.state.storage[s->h.stage][b->slot];
if(!r.addr || !r.size)die("unbound original shader buffer",b->slot);
// 位 1:着色器按 base & -64 求偏移,绑定从该地址起,零拷贝 | bit 1: shader offsets are relative to base & -64, so the binding starts there and needs no copy
if(b->kind==3 && (b->flags&2)){uint64_t rem=r.addr&63;r.addr-=rem;r.size+=rem;}
uint64_t offset=0;VPool *p=(b->kind==3&&(b->flags&1))?pool_read(r.addr,r.size,&offset):input_read(r.addr,r.size,&offset);
uint64_t alignment=b->kind==2?G.properties.limits.minUniformBufferOffsetAlignment:G.properties.limits.minStorageBufferOffsetAlignment;
if(offset%alignment){
AlignedBinding *aligned=NULL;
for(int j=0;j<G.naligned;j++)if(overlap(r.addr,r.size,G.aligned[j].range.addr,G.aligned[j].range.size)){
if(r.addr!=G.aligned[j].range.addr || r.size!=G.aligned[j].range.size)die("overlapping unaligned shader ranges",r.addr);
aligned=&G.aligned[j];break;
}
if(!aligned){if(G.naligned==2*LIMIT_BINDINGS)die("aligned binding count",G.naligned);
VBuffer *temp=temporary((r.size+3)&~3ULL,VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_TRANSFER_DST_BIT);
if(offset%4 || r.size%4)die("unaligned copy requires word granularity",offset);
all_barrier();VkBufferCopy copy={offset,0,r.size};vkCmdCopyBuffer(G.batch->command,p->v.b,temp->b,1,&copy);all_barrier();
aligned=&G.aligned[G.naligned++];*aligned=(AlignedBinding){r,temp,0};
}
if(b->kind==3&&(b->flags&1))aligned->written=1;
bi[i]=(VkDescriptorBufferInfo){aligned->buffer->b,0,r.size};
}else bi[i]=(VkDescriptorBufferInfo){p->v.b,offset,r.size};
if(b->kind==3 && (b->flags&1))mark_write(r.addr,r.size);
} else if(b->kind==4 || b->kind==6) {
if(b->slot<0 || b->slot>=(b->kind==6?32:128))die("texture shader slot",b->slot);
uint64_t handle=b->kind==6?G.state.img[s->h.stage][b->slot]:G.state.tex[s->h.stage][b->slot];
unsigned tid=(unsigned)handle&0xfffff;
if(texture_unbound(tid,s,b,"unbound texture descriptor")){
if(b->type==VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)ii[i].sampler=fetch_sampler();
ii[i].imageView=VK_NULL_HANDLE;ii[i].imageLayout=VK_IMAGE_LAYOUT_UNDEFINED;w[i].pImageInfo=&ii[i];continue;}
TSlot *slot=&G.tslot[tid];
VTexture *t=texture_get(&slot->texture,1);
trace_texture(t,s,b);
int alias=b->kind==4&&(s->dref_bindings&(1ull<<i))&&aspect(t->format)==VK_IMAGE_ASPECT_COLOR_BIT;
if(!alias)texture_transition(t,storage_image_use(t->serial)?VK_IMAGE_LAYOUT_GENERAL:sampled_layout(t,s->h.stage));
if(alias&&!t->shadow_view){fprintf(stderr,"[nvn-vulkan] missing comparison view shader=%s binding=%u slot=%d serial=%llu stage=%u\n",s->key,b->binding,b->slot,(unsigned long long)t->serial,s->h.stage);die("comparison image preparation",t->serial);}
VkImage selected_image=alias?t->shadow:t->image;VkFormat selected_format=alias?t->shadow_format:t->format;
ii[i].imageView=alias?t->shadow_view:t->view;ii[i].imageLayout=alias?t->shadow_layout:t->layout;
if(slot->has_view) {
view_t *v=&slot->view;
uint32_t level=v->set_levels?v->base_level:0,levels=v->set_levels?v->nlevels:t->source.d.levels;
uint32_t layer=v->set_layers?v->min_layer:0,layers=v->set_layers?v->nlayers:t->source.L.layers;
int target=v->set_target?v->target:t->source.d.target;
if(level>=t->source.d.levels || !levels || levels>t->source.d.levels-level ||
layer>=t->source.L.layers || !layers || layers>t->source.L.layers-layer ||
(v->set_format && v->format!=t->source.d.format) ||
(target!=NVN_TEXTURE_TARGET_2D && target!=NVN_TEXTURE_TARGET_3D && target!=NVN_TEXTURE_TARGET_2D_ARRAY && target!=NVN_TEXTURE_TARGET_CUBEMAP && target!=NVN_TEXTURE_TARGET_CUBEMAP_ARRAY) ||
(target==NVN_TEXTURE_TARGET_2D && layers!=1)) {
fprintf(stderr,"[nvn-vulkan] texture view id=%u flags=%u,%u,%u,%u levels=%d,%d layers=%d,%d format=%d/%d target=%d/%d\n",
tid,v->set_levels,v->set_layers,v->set_format,v->set_target,v->base_level,v->nlevels,v->min_layer,v->nlayers,
v->format,t->source.d.format,v->target,t->source.d.target);
die("texture view format/target/layer/range adaptation",tid);
}
if(level || levels!=t->source.d.levels || layer || layers!=t->source.L.layers || target!=t->source.d.target) {
if(G.batch->nview==LIMIT_WRITES)die("texture view count",G.batch->nview);
VkImageViewType view_type=target==NVN_TEXTURE_TARGET_3D?VK_IMAGE_VIEW_TYPE_3D:target==NVN_TEXTURE_TARGET_2D?VK_IMAGE_VIEW_TYPE_2D:target==NVN_TEXTURE_TARGET_2D_ARRAY?VK_IMAGE_VIEW_TYPE_2D_ARRAY:
target==NVN_TEXTURE_TARGET_CUBEMAP?VK_IMAGE_VIEW_TYPE_CUBE:VK_IMAGE_VIEW_TYPE_CUBE_ARRAY;
VkImageViewCreateInfo vi={.sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,.image=selected_image,.viewType=view_type,
.format=selected_format,.subresourceRange={aspect(selected_format)&VK_IMAGE_ASPECT_DEPTH_BIT?VK_IMAGE_ASPECT_DEPTH_BIT:VK_IMAGE_ASPECT_COLOR_BIT,level,levels,layer,layers}};
CHECK(vkCreateImageView(G.device,&vi,NULL,&G.batch->temporary_views[G.batch->nview]));ii[i].imageView=G.batch->temporary_views[G.batch->nview++];
}
}
if(b->kind==4 && b->type==VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) { unsigned sid=(unsigned)((b->sampler>=0?G.state.samp[s->h.stage][b->sampler]:handle)>>20)&0xfff;
if(sid>=LIMIT_OBJECTS || !G.sslot[sid].live){
/* Maxwell texel fetch requires no sampler. The translator
* still declares a combined descriptor; Vulkan requires a
* valid sampler there even though OpImage discards it. */
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")){
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);
}
} }
if(b->kind==6){t->cpu_owned=0;t->version++;}
w[i].pImageInfo=&ii[i];continue;
} else die("Vulkan shader resource kind",b->kind);
w[i].pBufferInfo=&bi[i];
}
for(uint32_t k=0;k<s->ndyn;k++){unsigned i=s->dyn_index[k];if(bi[i].offset>UINT32_MAX)die("dynamic buffer offset",bi[i].offset);
s->dyn_off[k]=(uint32_t)bi[i].offset;bi[i].offset=0;}
/* 动态缓冲集:缓冲和范围不变就沿用(偏移在绑定时传入)| dynamic-buffer set: reused while buffers and ranges are unchanged (offsets go in at bind time) */
if(s->ndyn){uint64_t dw[2*LIMIT_BINDINGS];VkWriteDescriptorSet wd[LIMIT_BINDINGS];
for(uint32_t k=0;k<s->ndyn;k++){unsigned i=s->dyn_index[k];dw[2*k]=(uint64_t)(uintptr_t)bi[i].buffer;dw[2*k+1]=bi[i].range;wd[k]=w[i];}
if(s->dyn_epoch!=G.batch->epoch || memcmp(s->dyn_words,dw,16*s->ndyn) || G.trace_frame){
s->dyn_set=shader_set_allocate(s,1);G.batch->sets++;G.profile_set_writes++;
for(uint32_t k=0;k<s->ndyn;k++)wd[k].dstSet=s->dyn_set;
vkUpdateDescriptorSets(G.device,s->ndyn,wd,0,NULL);s->dyn_epoch=G.batch->epoch;memcpy(s->dyn_words,dw,16*s->ndyn);}}
else s->dyn_set=VK_NULL_HANDLE;
if(s->ndyn==s->h.nb){s->set=VK_NULL_HANDLE;for(uint32_t k=0;k<s->ndyn;k++)bi[s->dyn_index[k]].offset=s->dyn_off[k];return VK_NULL_HANDLE;}
/* Consecutive draws usually bind identical resources: reuse the set
* written earlier in this batch instead of allocating and writing again.
* 相邻绘制常在几组贴图间交替:先查上次命中的项,再查其余项 |
* neighbouring draws often alternate between a few texture sets: try the last hit first, then the rest */
uint64_t words[3*LIMIT_BINDINGS];VkWriteDescriptorSet ws[LIMIT_BINDINGS];uint32_t nws=0;
for(uint32_t i=0;i<s->h.nb;i++){
if(s->dyn_mask>>i&1){words[3*i]=words[3*i+1]=words[3*i+2]=0;continue;}
ws[nws++]=w[i];
if(w[i].pTexelBufferView){words[3*i]=(uint64_t)(uintptr_t)*w[i].pTexelBufferView;words[3*i+1]=words[3*i+2]=0;}
else if(w[i].pImageInfo){words[3*i]=(uint64_t)(uintptr_t)ii[i].imageView;words[3*i+1]=(uint64_t)(uintptr_t)ii[i].sampler;words[3*i+2]=ii[i].imageLayout;}
else{words[3*i]=(uint64_t)(uintptr_t)bi[i].buffer;words[3*i+1]=bi[i].offset;words[3*i+2]=bi[i].range;}}
size_t nw=3*s->h.nb;
if(!s->cache_words && !(s->cache_words=calloc(SET_CACHE,8*nw+8)))die("descriptor set cache",nw);
if(!G.trace_frame)for(unsigned n=0;n<SET_CACHE;n++){unsigned k=(s->cache_last+n)%SET_CACHE;
if(s->cache_epoch[k]==G.batch->epoch && !memcmp(s->cache_words+k*nw,words,8*nw)){s->cache_last=k;return s->set=s->cache_set[k];}}
set=shader_set_allocate(s,0);G.batch->sets++;G.profile_set_writes++;
for(uint32_t i=0;i<nws;i++)ws[i].dstSet=set;
vkUpdateDescriptorSets(G.device,nws,ws,0,NULL);s->set=set;
{unsigned k=s->cache_next++%SET_CACHE;s->cache_epoch[k]=G.batch->epoch;s->cache_set[k]=set;memcpy(s->cache_words+k*nw,words,8*nw);s->cache_last=k;}
for(uint32_t k=0;k<s->ndyn;k++)bi[s->dyn_index[k]].offset=s->dyn_off[k];
if(G.trace_frame&&G.trace_ui&&s->h.stage==1&&!strcmp(s->key,"62ddcb3faa41a92a")){
for(unsigned i=0;i<s->h.nb;i++)if(s->b[i].kind==2||s->b[i].kind==9){uint64_t bytes=bi[i].range;
if(bytes%4)die("UI effective uniform capture alignment",bytes);
VBuffer *capture=temporary(bytes,VK_BUFFER_USAGE_TRANSFER_DST_BIT);all_barrier();VkBufferCopy copy={bi[i].offset,0,bytes};
vkCmdCopyBuffer(G.batch->command,bi[i].buffer,capture->b,1,&copy);char name[160];snprintf(name,sizeof(name),"ui-effective-%04llu-%llu-ps-ubo%d",(unsigned long long)G.present_count+1,(unsigned long long)G.draws,s->b[i].slot);trace_capture_queue(capture,bytes,name);
}
}
return set;
}
static VShader *program_stage_optional_impl(int stage) {
const prog_t *p=G.state.program;if(!p)die("draw/dispatch without program",stage);
for(uint32_t i=0;i<p->nstage;i++) { const void *control=p->sd[i].control;if(!control)die("shader data control",i);
ShaderEntry *slot=shader_entry(control,stage);if(slot)return shader_get(slot,stage); }
return NULL;
}
/* prog_t.serial changes on every SetShaders, so the resolved stage can be
* memoized per program instead of hashing 0x880 control bytes per draw. */
typedef struct { uint64_t serial; uint8_t known; VShader *stage[6]; } ProgramStages;
static ProgramStages program_stages[4096];
static VShader *program_stage_optional(int stage) {
uint64_t started=prof_ns();const prog_t *p=G.state.program;
if(!p)die("draw/dispatch without program",stage);
ProgramStages *m=&program_stages[(p->serial*0x9e3779b97f4a7c15ULL)>>52];
if(m->serial!=p->serial){memset(m,0,sizeof(*m));m->serial=p->serial;}
VShader *s;
if(m->known&(1u<<stage))s=m->stage[stage];
else{s=program_stage_optional_impl(stage);m->stage[stage]=s;m->known|=1u<<stage;}
G.profile_lookup_ns+=prof_ns()-started;return s;
}
static VShader *program_stage(int stage) {
VShader *s=program_stage_optional(stage);if(!s)die("requested program stage missing",stage);return s;
}
static VkBlendFactor blend_factor(unsigned f) {
switch(f) {
case NVN_BLEND_FUNC_ZERO:return VK_BLEND_FACTOR_ZERO;case NVN_BLEND_FUNC_ONE:return VK_BLEND_FACTOR_ONE;
case NVN_BLEND_FUNC_SRC_COLOR:return VK_BLEND_FACTOR_SRC_COLOR;case NVN_BLEND_FUNC_ONE_MINUS_SRC_COLOR:return VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
case NVN_BLEND_FUNC_SRC_ALPHA:return VK_BLEND_FACTOR_SRC_ALPHA;case NVN_BLEND_FUNC_ONE_MINUS_SRC_ALPHA:return VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
case NVN_BLEND_FUNC_DST_ALPHA:return VK_BLEND_FACTOR_DST_ALPHA;case NVN_BLEND_FUNC_ONE_MINUS_DST_ALPHA:return VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA;
case NVN_BLEND_FUNC_DST_COLOR:return VK_BLEND_FACTOR_DST_COLOR;case NVN_BLEND_FUNC_ONE_MINUS_DST_COLOR:return VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR;
case NVN_BLEND_FUNC_CONSTANT_COLOR:return VK_BLEND_FACTOR_CONSTANT_COLOR;case NVN_BLEND_FUNC_ONE_MINUS_CONSTANT_COLOR:return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR;
case NVN_BLEND_FUNC_CONSTANT_ALPHA:return VK_BLEND_FACTOR_CONSTANT_ALPHA;case NVN_BLEND_FUNC_ONE_MINUS_CONSTANT_ALPHA:return VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA;
case NVN_BLEND_FUNC_SRC_ALPHA_SATURATE:return VK_BLEND_FACTOR_SRC_ALPHA_SATURATE;
default:die("blend factor",f); }
}
static VkBlendOp blend_op(unsigned op) {
switch(op) {case NVN_BLEND_EQUATION_ADD:return VK_BLEND_OP_ADD;case NVN_BLEND_EQUATION_SUB:return VK_BLEND_OP_SUBTRACT;
case NVN_BLEND_EQUATION_REVERSE_SUB:return VK_BLEND_OP_REVERSE_SUBTRACT;case NVN_BLEND_EQUATION_MIN:return VK_BLEND_OP_MIN;
case NVN_BLEND_EQUATION_MAX:return VK_BLEND_OP_MAX;default:die("blend equation",op); }
}
static VkPrimitiveTopology topology(int p) {
switch(p) {case NVN_DRAW_PRIMITIVE_POINTS:return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
case NVN_DRAW_PRIMITIVE_LINES:return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;case NVN_DRAW_PRIMITIVE_LINE_STRIP:return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
case NVN_DRAW_PRIMITIVE_TRIANGLES:return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;case NVN_DRAW_PRIMITIVE_TRIANGLE_STRIP:return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
case NVN_DRAW_PRIMITIVE_TRIANGLE_FAN:return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;default:die("draw primitive",p); }
}
static VkImageSubresourceRange attachment_range(const tex_t *source,const view_t *v) {
unsigned level=v&&v->set_levels?v->base_level:0,layer=v&&v->set_layers?v->min_layer:0;
if(level>=source->d.levels || layer>=source->L.layers || (v&&v->set_levels&&v->nlevels<1) ||
(v&&v->set_layers&&v->nlayers!=1) || (v&&v->set_format&&v->format!=source->d.format) || source->d.target==NVN_TEXTURE_TARGET_3D)
die("attachment view format/layer/mip",level);
return (VkImageSubresourceRange){aspect(format(source->d.format)),level,1,layer,1};
}
static VkRenderPass render_begin(void) {
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));
memset(attachments,0,sizeof(attachments));
for(int i=0;i<rt->n;i++)color[i]=(VkAttachmentReference){VK_ATTACHMENT_UNUSED,VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
for(int i=0;i<rt->n+(rt->depth?1:0);i++) {
int is_depth=i==rt->n;const tex_t *source=is_depth?rt->depth:rt->color[i];
/* NVN color slots may be unbound. Pack only real image attachments,
* while keeping subpass references at their original output locations. */
if(!source)continue;
const view_t *v=is_depth?(rt->has_dview?&rt->dview:NULL):(rt->has_cview[i]?&rt->cview[i]:NULL);
VkImageSubresourceRange range=attachment_range(source,v);
VTexture *t=texture_get(source,0);uint32_t tw=t->width>>range.baseMipLevel,th=t->height>>range.baseMipLevel;if(!tw)tw=1;if(!th)th=1;
if(G.present_count<1 || G.trace_frame)fprintf(stderr,"[nvn-vulkan] RT_ATTACHMENT index=%d depth=%d serial=%llu extent=%u,%u base_extent=%u,%u level=%u layer=%u count=%d nvn_format=%u gpu_format=%u\n",i,is_depth,(unsigned long long)source->serial,tw,th,source->d.width,source->d.height,range.baseMipLevel,range.baseArrayLayer,rt->n,source->d.format,t->format);
/* NVN permits differently sized attachments. Vulkan framebuffer extent
* must fit every attachment; its render area is their intersection. */
if(!width){width=tw;height=th;}else {if(tw<width)width=tw;if(th<height)height=th;}
t->cpu_owned=0;t->version++;
VkImageLayout attachment_layout=is_depth?VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
if(is_depth&&G.depth_sampled&&depth_read_only())attachment_layout=VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
else if(G.general_feedback&&image_sampled(source->serial))attachment_layout=VK_IMAGE_LAYOUT_GENERAL;
else if(G.feedback_flags&(is_depth?VK_PIPELINE_CREATE_DEPTH_STENCIL_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT:VK_PIPELINE_CREATE_COLOR_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT))attachment_layout=VK_IMAGE_LAYOUT_ATTACHMENT_FEEDBACK_LOOP_OPTIMAL_EXT;
texture_transition(t,attachment_layout);
VkImageLayout layout=t->layout;
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};
images[n]=t->image;ranges[n]=range;
if(is_depth)depth=(VkAttachmentReference){n,layout};else color[i]=(VkAttachmentReference){n,layout};n++;
}
if(!n)die("render targets have no bound attachment",rt->n);
VkSubpassDescription sub={.pipelineBindPoint=VK_PIPELINE_BIND_POINT_GRAPHICS,.colorAttachmentCount=rt->n,.pColorAttachments=color,
.pDepthStencilAttachment=rt->depth?&depth:NULL};
VkSubpassDependency deps[3]={
{.srcSubpass=VK_SUBPASS_EXTERNAL,.dstSubpass=0,.srcStageMask=VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
.dstStageMask=VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT,.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT},
{.srcSubpass=0,.dstSubpass=VK_SUBPASS_EXTERNAL,.srcStageMask=VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,.dstStageMask=VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT,.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT},
{.srcSubpass=0,.dstSubpass=0,.srcStageMask=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT|VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT|VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT,
.dstStageMask=VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,.srcAccessMask=VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT|VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT,
.dstAccessMask=VK_ACCESS_SHADER_READ_BIT,.dependencyFlags=VK_DEPENDENCY_BY_REGION_BIT|VK_DEPENDENCY_FEEDBACK_LOOP_BIT_EXT}};
VkRenderPassCreateInfo ri={.sType=VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,.attachmentCount=n,.pAttachments=attachments,
.subpassCount=1,.pSubpasses=&sub,.dependencyCount=G.feedback_flags||G.general_feedback?3u:2u,.pDependencies=deps};
if(G.general_feedback)deps[2].dependencyFlags=VK_DEPENDENCY_BY_REGION_BIT;
PassKey key={0};memcpy(key.attachments,attachments,n*sizeof(*attachments));memcpy(key.color,color,rt->n*sizeof(*color));
key.depth=depth;key.n=n;key.ncolor=rt->n;key.has_depth=rt->depth!=NULL;key.feedback=ri.dependencyCount==3;
PassEntry *pass=G.passes;
while(pass && memcmp(&pass->key,&key,sizeof(key)))pass=pass->next;
if(!pass){pass=calloc(1,sizeof(*pass));if(!pass)die("render pass cache allocation",0);pass->key=key;
CHECK(vkCreateRenderPass(G.device,&ri,NULL,&pass->pass));pass->next=G.passes;G.passes=pass;}else G.pass_hits++;
FramebufferEntry *fb=G.framebuffers,**link=&G.framebuffers;
while(fb && !(fb->pass==pass && fb->width==width && fb->height==height &&
!memcmp(fb->images,images,sizeof(images)) && !memcmp(fb->ranges,ranges,sizeof(ranges)))){link=&fb->next;fb=fb->next;}
/* 命中的移到表头:一帧里反复用的那几个总在前面 | move a hit to the front so the few reused each frame are found first */
if(fb && fb!=G.framebuffers){*link=fb->next;fb->next=G.framebuffers;G.framebuffers=fb;}
if(!fb){fb=calloc(1,sizeof(*fb));if(!fb)die("framebuffer cache allocation",0);
fb->pass=pass;fb->width=width;fb->height=height;memcpy(fb->images,images,sizeof(images));memcpy(fb->ranges,ranges,sizeof(ranges));
for(unsigned i=0;i<n;i++){VkImageViewCreateInfo view={.sType=VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO,.image=images[i],
.viewType=VK_IMAGE_VIEW_TYPE_2D,.format=attachments[i].format,.subresourceRange=ranges[i]};
CHECK(vkCreateImageView(G.device,&view,NULL,&fb->views[i]));}
VkFramebufferCreateInfo fi={.sType=VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,.renderPass=pass->pass,.attachmentCount=n,
.pAttachments=fb->views,.width=width,.height=height,.layers=1};CHECK(vkCreateFramebuffer(G.device,&fi,NULL,&fb->framebuffer));
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;
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);
G.current_fb=fb;G.in_pass=1;G.pass_count++;pp_draws0=G.draws;pp_ps=NULL;return pass->pass;
}
static void trace_mesh_range(const char *name,uint64_t address,uint64_t bytes) {
const char *root=getenv("DM_FRAME_DIR");if(!root||!bytes)return;
if(bytes>16*1024*1024||!pool_find(address,bytes,NULL))die("mesh diagnostic range",bytes);
char path[1400];snprintf(path,sizeof(path),"%s/mesh-%04llu-%llu-%s.bin",root,(unsigned long long)G.present_count+1,(unsigned long long)G.draws,name);
FILE *out=fopen(path,"wb");if(!out)die("mesh diagnostic output",0);
if(fwrite((const void *)(uintptr_t)address,1,bytes,out)!=bytes)die("mesh diagnostic write",bytes);fclose(out);
fprintf(stderr,"[nvn-vulkan] MESH_GUEST_RANGE draw=%llu name=%s bytes=%llu path=%s\n",(unsigned long long)G.draws,name,(unsigned long long)bytes,path);
uint64_t prefix=address&3ULL,span=(prefix+bytes+3)&~3ULL;
uint64_t offset=0;VPool *pool=pool_read(address-prefix,span,&offset);VBuffer *capture=temporary(span,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
all_barrier();VkBufferCopy copy={offset,0,span};vkCmdCopyBuffer(G.batch->command,pool->v.b,capture->b,1,&copy);
char gpu_name[160];snprintf(gpu_name,sizeof(gpu_name),"mesh-%04llu-%llu-%s-gpu",(unsigned long long)G.present_count+1,(unsigned long long)G.draws,name);trace_capture_queue(capture,bytes,gpu_name);
G.batch->trace_captures[G.batch->ntrace_captures-1].offset=prefix;
}
static void draw(const p_draw *a,const p_draw_idx *idx) {
batch_checkpoint();if(!a&&!idx)die("draw parameters",0);
int upper_left=atomic_load(&G.window_origin)==NVN_WINDOW_ORIGIN_MODE_UPPER_LEFT;
if(G.state.ms.samples>1 || G.state.ms.a2c || G.state.ms.cov_mod || G.state.ms.sl_en)die("multisample semantics",G.state.ms.samples);
if(G.state.color.logic_op!=NVN_LOGIC_OP_COPY || G.state.color.alpha_func!=NVN_ALPHA_FUNC_ALWAYS)die("logic/alpha test adaptation",G.state.color.logic_op);
if(G.state.polygon.mode!=NVN_POLYGON_MODE_FILL || G.state.polygon.offset_en)die("polygon mode/offset",G.state.polygon.mode);
/* A zero-color pass may still run fragment discard, depth export or
* storage side effects. Only a program with no fragment stage omits it. */
VShader *vs=program_stage(0),*ps=program_stage_optional(1);
if(G.trace_frame&&!G.trace_ui&&idx&&idx->count>=100&&G.trace_meshes<4&&!strcmp(vs->key,"54f730a6c0efc118")){
G.trace_meshes++;for(unsigned i=0;i<16;i++)if(G.state.vbuf[i].size){char name[32];snprintf(name,sizeof(name),"vbuf%u",i);trace_mesh_range(name,G.state.vbuf[i].address,G.state.vbuf[i].size);}
for(unsigned i=0;i<vs->h.nb;i++)if(vs->b[i].kind==2||vs->b[i].kind==9){int slot=vs->b[i].slot;char name[32];snprintf(name,sizeof(name),"ubo%d",slot);trace_mesh_range(name,G.state.uniform[0][slot].addr,G.state.uniform[0][slot].size);}
trace_mesh_range("indices",idx->ibuf,(uint64_t)idx->count*(idx->itype==NVN_INDEX_TYPE_UNSIGNED_SHORT?2:4));
fprintf(stderr,"[nvn-vulkan] MESH_INDEX draw=%llu type=%u base_vertex=%d base_instance=%u count=%d\n",(unsigned long long)G.draws,idx->itype,idx->base_vertex,idx->base_instance,idx->count);
}
if(G.trace_frame&&G.trace_ui&&ps&&!strcmp(ps->key,"62ddcb3faa41a92a")){
for(unsigned stage=0;stage<2;stage++){VShader *s=stage?ps:vs;
for(unsigned i=0;i<s->h.nb;i++)if(s->b[i].kind==2||s->b[i].kind==9){unsigned slot=s->b[i].slot;char name[48];snprintf(name,sizeof(name),"ui-%s-ubo%u",stage?"ps":"vs",slot);Range r=G.state.uniform[stage][slot];trace_mesh_range(name,r.addr,r.size);}}
NVNbufferRange v=G.state.vbuf[0];trace_mesh_range("ui-vbuf0",v.address,v.size);
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.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,
G.state.scissor.offset.x,G.state.scissor.offset.y,G.state.scissor.extent.width,G.state.scissor.extent.height,
G.state.polygon.cull,G.state.polygon.front,G.state.ds.dt,G.state.ds.dw,G.state.ds.df,G.state.color.blend_en,G.state.mask.mask);
if(G.trace_frame)fprintf(stderr,"[nvn-vulkan] DRAW_DEPTH_STATE draw=%llu range=%g,%g stencil=%u func=%u,%u masks=%#x,%#x write=%#x,%#x ref=%#x,%#x ops=%u,%u,%u/%u,%u,%u\n",
(unsigned long long)G.draws,G.state.viewport.minDepth,G.state.viewport.maxDepth,G.state.ds.st,G.state.ds.sf_f,G.state.ds.sf_b,
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);
uint64_t bind_started=prof_ns();
prepare_comparison_images(vs);prepare_comparison_images(ps);
bind_shader(vs);if(ps)bind_shader(ps);
G.profile_bind_ns+=prof_ns()-bind_started;
VkDescriptorSetLayout set_layouts[4]={vs->layout,ps?ps->layout:empty_set_layout(),vs->ndyn?vs->dyn_layout:empty_set_layout(),ps&&ps->ndyn?ps->dyn_layout:empty_set_layout()};
uint32_t nsets=ps&&ps->ndyn?4:vs->ndyn?3:ps?2:1;
VkPipelineLayoutCreateInfo li={.sType=VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,.setLayoutCount=nsets,.pSetLayouts=set_layouts};
VkVertexInputAttributeDescription attributes[32];VkVertexInputBindingDescription bindings[16];uint32_t nbindings=0;uint8_t used[16]={0};
for(uint32_t i=0;i<vs->h.na;i++) { unsigned location=vs->attr[i][0];if(location>=16)die("vertex attribute count",location);
va_st v=G.state.attributes[location];if(v.stream>=16)die("vertex stream",v.stream);
if(G.trace_frame)fprintf(stderr,"[nvn-vulkan] VERTEX_INPUT draw=%llu location=%u shader_type=%u stream=%u format=%u offset=%u stride=%u divisor=%u address=%#llx size=%llu\n",(unsigned long long)G.draws,location,vs->attr[i][1],v.stream,v.fmt,v.offset,G.state.streams[v.stream].stride,G.state.streams[v.stream].divisor,(unsigned long long)G.state.vbuf[v.stream].address,(unsigned long long)G.state.vbuf[v.stream].size);
attributes[i]=(VkVertexInputAttributeDescription){location,v.stream,format(v.fmt),v.offset};used[v.stream]=1; }
for(unsigned i=0;i<16;i++)if(used[i]) { vs_st v=G.state.streams[i];if(v.divisor>1)die("vertex divisor",v.divisor);
bindings[nbindings++]=(VkVertexInputBindingDescription){i,v.stride,v.divisor?VK_VERTEX_INPUT_RATE_INSTANCE:VK_VERTEX_INPUT_RATE_VERTEX};
NVNbufferRange r=G.state.vbuf[i];if(!r.address || !r.size)die("unbound vertex stream",i);uint64_t offset=0;VPool *p=input_read(r.address,r.size,&offset);
if(G.batch->bound.vb[i]!=p->v.b || G.batch->bound.vb_offset[i]!=offset){vkCmdBindVertexBuffers(G.batch->command,i,1,&p->v.b,&offset);G.batch->bound.vb[i]=p->v.b;G.batch->bound.vb_offset[i]=offset;} }
VkPipelineVertexInputStateCreateInfo vi={.sType=VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,.vertexBindingDescriptionCount=nbindings,
.pVertexBindingDescriptions=bindings,.vertexAttributeDescriptionCount=vs->h.na,.pVertexAttributeDescriptions=attributes};
VkPipelineInputAssemblyStateCreateInfo ai={.sType=VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
.topology=topology(a?a->prim:idx->prim)};
VkPipelineViewportStateCreateInfo vp={.sType=VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,.viewportCount=1,.scissorCount=1};
VkPipelineRasterizationStateCreateInfo raster={.sType=VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,.polygonMode=VK_POLYGON_MODE_FILL,
.cullMode=G.state.polygon.cull==NVN_FACE_FRONT?VK_CULL_MODE_FRONT_BIT:G.state.polygon.cull==NVN_FACE_BACK?VK_CULL_MODE_BACK_BIT:
G.state.polygon.cull==NVN_FACE_FRONT_AND_BACK?VK_CULL_MODE_FRONT_AND_BACK:VK_CULL_MODE_NONE,
// An upper-left NVN window retains NDC y upwards; a negative Vulkan
// viewport restores that mapping. Facing follows the same inversion.
.frontFace=(G.state.polygon.front==NVN_FRONT_FACE_CCW)==upper_left?VK_FRONT_FACE_COUNTER_CLOCKWISE:VK_FRONT_FACE_CLOCKWISE,.lineWidth=1};
VkPipelineMultisampleStateCreateInfo ms={.sType=VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,.rasterizationSamples=VK_SAMPLE_COUNT_1_BIT};
VkPipelineDepthStencilStateCreateInfo ds={.sType=VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,.depthTestEnable=G.state.ds.dt,
.depthWriteEnable=G.state.ds.dw,.depthCompareOp=(VkCompareOp)(G.state.ds.df-1),.stencilTestEnable=G.state.ds.st};
ds.front=(VkStencilOpState){.failOp=(VkStencilOp)(G.state.ds.fail_f-1),.passOp=(VkStencilOp)(G.state.ds.zpass_f-1),
.depthFailOp=(VkStencilOp)(G.state.ds.zfail_f-1),.compareOp=(VkCompareOp)(G.state.ds.sf_f-1),
.compareMask=G.state.stencil_compare[0],.writeMask=G.state.stencil_write[0],.reference=G.state.stencil_ref[0]};
ds.back=(VkStencilOpState){.failOp=(VkStencilOp)(G.state.ds.fail_b-1),.passOp=(VkStencilOp)(G.state.ds.zpass_b-1),
.depthFailOp=(VkStencilOp)(G.state.ds.zfail_b-1),.compareOp=(VkCompareOp)(G.state.ds.sf_b-1),
.compareMask=G.state.stencil_compare[1],.writeMask=G.state.stencil_write[1],.reference=G.state.stencil_ref[1]};
VkPipelineColorBlendAttachmentState blends[8];memset(blends,0,sizeof(blends));
for(int i=0;i<G.state.rt.n;i++) {blend_st b=G.state.blend[i];
if(!G.state.rt.color[i])continue;
blends[i].colorWriteMask=(G.state.mask.mask>>(4*i))&15;
if(G.state.color.blend_en&(1u<<i)) {blends[i].blendEnable=1;blends[i].srcColorBlendFactor=blend_factor(b.src_rgb);
blends[i].dstColorBlendFactor=blend_factor(b.dst_rgb);blends[i].srcAlphaBlendFactor=blend_factor(b.src_a);
blends[i].dstAlphaBlendFactor=blend_factor(b.dst_a);blends[i].colorBlendOp=blend_op(b.eq_rgb);blends[i].alphaBlendOp=blend_op(b.eq_a);} }
VkPipelineColorBlendStateCreateInfo cb={.sType=VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,.attachmentCount=G.state.rt.n,.pAttachments=blends};
VkDynamicState dynamic[]={VK_DYNAMIC_STATE_VIEWPORT,VK_DYNAMIC_STATE_SCISSOR,VK_DYNAMIC_STATE_BLEND_CONSTANTS};
VkPipelineDynamicStateCreateInfo dy={.sType=VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,.dynamicStateCount=3,.pDynamicStates=dynamic};
VkBuffer index_buffer=VK_NULL_HANDLE;uint64_t index_offset=0;
if(idx){if(idx->count<0 || idx->instances<0 || (idx->itype!=NVN_INDEX_TYPE_UNSIGNED_SHORT && idx->itype!=NVN_INDEX_TYPE_UNSIGNED_INT))die("index type/bounds",idx->itype);
uint64_t size=(uint64_t)idx->count*(idx->itype==NVN_INDEX_TYPE_UNSIGNED_SHORT?2:4);
if(size){VPool *pool=input_read(idx->ibuf,size,&index_offset);index_buffer=pool->v.b;}}
uint64_t render_started=prof_ns();VkRenderPass renderpass=render_begin();G.profile_render_ns+=prof_ns()-render_started;
VkPipelineShaderStageCreateInfo stages[2]={
{.sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,.stage=VK_SHADER_STAGE_VERTEX_BIT,.module=vs->module,.pName="main"},
{.sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,.stage=VK_SHADER_STAGE_FRAGMENT_BIT,.module=ps?ps->module:VK_NULL_HANDLE,.pName="main"}};
VkGraphicsPipelineCreateInfo gp={.sType=VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,.flags=G.feedback_flags,.stageCount=ps?2u:1u,.pStages=stages,
.pVertexInputState=&vi,.pInputAssemblyState=&ai,.pViewportState=&vp,.pRasterizationState=&raster,.pMultisampleState=&ms,
.pDepthStencilState=&ds,.pColorBlendState=&cb,.pDynamicState=&dy,.renderPass=renderpass};
VkPipelineFragmentShadingRateStateCreateInfoKHR shading_rate={.sType=VK_STRUCTURE_TYPE_PIPELINE_FRAGMENT_SHADING_RATE_STATE_CREATE_INFO_KHR,
.combinerOps={VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR,VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR}};
if(ps && ps->vrs.width){shading_rate.fragmentSize=ps->vrs;gp.pNext=&shading_rate;} /* 着色率随像素着色器固定,已由 key 中的着色器序号区分 | rate is fixed per pixel shader, already keyed by its index */
PipelineKey key={0};
#define K(x) key_word(&key,(uint32_t)(x))
K(0);K(vs-G.shaders);K(ps?ps-G.shaders+1:0);K(G.feedback_flags);K(ai.topology);
K(nbindings);K(vs->h.na);
for(unsigned i=0;i<nbindings;i++){K(bindings[i].binding);K(bindings[i].stride);K(bindings[i].inputRate);}
for(unsigned i=0;i<vs->h.na;i++){K(attributes[i].location);K(attributes[i].binding);K(attributes[i].format);K(attributes[i].offset);}
K(raster.cullMode);K(raster.frontFace);K(ds.depthTestEnable);K(ds.depthWriteEnable);K(ds.depthCompareOp);K(ds.stencilTestEnable);
VkStencilOpState stencil[2]={ds.front,ds.back};
for(unsigned i=0;i<2;i++){K(stencil[i].failOp);K(stencil[i].passOp);K(stencil[i].depthFailOp);K(stencil[i].compareOp);K(stencil[i].compareMask);K(stencil[i].writeMask);K(stencil[i].reference);}
const PassKey *rk=&G.current_fb->pass->key;K(rk->ncolor);K(rk->has_depth);K(rk->feedback);
for(unsigned i=0;i<rk->ncolor;i++){unsigned ref=rk->color[i].attachment;K(ref);K(ref==VK_ATTACHMENT_UNUSED?0:rk->attachments[ref].format);
K(blends[i].blendEnable);K(blends[i].srcColorBlendFactor);K(blends[i].dstColorBlendFactor);K(blends[i].colorBlendOp);
K(blends[i].srcAlphaBlendFactor);K(blends[i].dstAlphaBlendFactor);K(blends[i].alphaBlendOp);K(blends[i].colorWriteMask);}
if(rk->has_depth){K(rk->depth.attachment);K(rk->attachments[rk->depth.attachment].format);}
#undef K
uint64_t hash=state_hash(key.words,key.count*4);Pso *pso=pso_find(&key,hash);
if(!pso){pso=pso_insert(&key,hash);CHECK(vkCreatePipelineLayout(G.device,&li,NULL,&pso->layout));gp.layout=pso->layout;
uint64_t started=dm_android_nvn_clock_ns();CHECK(vkCreateGraphicsPipelines(G.device,G.pipeline_cache,1,&gp,NULL,&pso->pipeline));started=dm_android_nvn_clock_ns()-started;G.profile_pipeline_ns+=started;G.pso_made++;G.pso_made_ns+=started;}
__typeof__(G.batch->bound) *bound=&G.batch->bound;
if(bound->pipeline!=pso->pipeline){vkCmdBindPipeline(G.batch->command,VK_PIPELINE_BIND_POINT_GRAPHICS,pso->pipeline);bound->pipeline=pso->pipeline;G.profile_pipeline_binds++;}
/* 布局不变时只重绑变了的集:set 0/1 是 VS/PS 的贴图等,set 2/3 是它们的动态缓冲 |
* with an unchanged layout, rebind only the sets that changed: sets 0/1 hold VS/PS textures etc., sets 2/3 their dynamic buffers */
VShader *set_shaders[2]={vs,ps};int all=bound->layout!=pso->layout || bound->nsets!=nsets;
for(uint32_t k=0;k<nsets;k++){VShader *st=set_shaders[k&1];if(!st)continue;unsigned d=k>=2;
VkDescriptorSet set=d?st->dyn_set:st->set;if(!set)continue;uint32_t n=d?st->ndyn:0;
if(all || bound->sets[k]!=set || (d && memcmp(bound->offs[k&1],st->dyn_off,4*n))){
vkCmdBindDescriptorSets(G.batch->command,VK_PIPELINE_BIND_POINT_GRAPHICS,pso->layout,k,1,&set,n,st->dyn_off);
bound->sets[k]=set;if(d)memcpy(bound->offs[k&1],st->dyn_off,4*n);G.profile_set_binds++;}}
bound->layout=pso->layout;bound->nsets=nsets;
if(G.state.viewport.width<=0 || G.state.viewport.height<=0)die("viewport bounds",0);
VkViewport viewport=G.state.viewport;if(upper_left){viewport.y+=viewport.height;viewport.height=-viewport.height;}
if(!bound->dynamic_valid || memcmp(&bound->viewport,&viewport,sizeof(viewport))){vkCmdSetViewport(G.batch->command,0,1,&viewport);bound->viewport=viewport;}
if(!bound->dynamic_valid || memcmp(&bound->scissor,&G.state.scissor,sizeof(G.state.scissor))){vkCmdSetScissor(G.batch->command,0,1,&G.state.scissor);bound->scissor=G.state.scissor;}
if(!bound->dynamic_valid || memcmp(bound->blend,G.state.blend_color,sizeof(bound->blend))){vkCmdSetBlendConstants(G.batch->command,G.state.blend_color);memcpy(bound->blend,G.state.blend_color,sizeof(bound->blend));}
bound->dynamic_valid=1;
query_begin();
if(a) {if(a->count<0 || a->first<0)die("draw arrays bounds",a->count);vkCmdDraw(G.batch->command,a->count,1,a->first,0);}
else {
VkIndexType index_type=idx->itype==NVN_INDEX_TYPE_UNSIGNED_SHORT?VK_INDEX_TYPE_UINT16:VK_INDEX_TYPE_UINT32;
if(index_buffer && (bound->ib!=index_buffer || bound->ib_offset!=index_offset || bound->ib_type!=index_type)){
vkCmdBindIndexBuffer(G.batch->command,index_buffer,index_offset,index_type);bound->ib=index_buffer;bound->ib_offset=index_offset;bound->ib_type=index_type;}
if(idx->count)vkCmdDrawIndexed(G.batch->command,idx->count,idx->instances,0,idx->base_vertex,idx->base_instance); }
if(G.trace_frame&&G.trace_ui&&ps&&!strcmp(ps->key,"62ddcb3faa41a92a")&&G.state.rt.n==1){
VTexture *t=texture_get(G.state.rt.color[0],0);if(t->bpp!=4||aspect(t->format)!=VK_IMAGE_ASPECT_COLOR_BIT)die("UI result capture format",t->format);
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);uint64_t bytes=(uint64_t)t->width*t->height*4;
VBuffer *capture=temporary(bytes,VK_BUFFER_USAGE_TRANSFER_DST_BIT);VkBufferImageCopy copy={.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,&copy);char name[160];snprintf(name,sizeof(name),"ui-result-%04llu-%llu-%ux%u",(unsigned long long)G.present_count+1,(unsigned long long)G.draws,t->width,t->height);trace_capture_queue(capture,bytes,name);
}
if(!pp_ps)pp_ps=ps?ps->key:"-";
G.draws++;G.batch->draws++;aligned_writeback();
int storage_write=0;
VShader *shaders[2]={vs,ps};for(unsigned stage=0;stage<2;stage++)if(shaders[stage])
for(unsigned i=0;i<shaders[stage]->h.nb;i++){RBinding *binding=&shaders[stage]->b[i];
if((binding->kind==3&&(binding->flags&1)) || binding->kind==6 || binding->type==VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER)storage_write=1;}
if(storage_write)all_barrier();
}
static void dispatch(const p_dispatch *p) {
batch_checkpoint();pass_end();if(p->x<0 || p->y<0 || p->z<0)die("dispatch dimensions",p->x);VShader *s=program_stage(5);
G.nimage_uses=0;collect_image_uses(s);prepare_comparison_images(s);
bind_shader(s);VkDescriptorSetLayout set_layouts[3]={s->layout,empty_set_layout(),s->dyn_layout};
VkPipelineLayoutCreateInfo li={.sType=VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,.setLayoutCount=s->ndyn?3u:1u,.pSetLayouts=set_layouts};
PipelineKey key={0};key_word(&key,1);key_word(&key,s-G.shaders);
uint64_t hash=state_hash(key.words,key.count*4);Pso *pso=pso_find(&key,hash);
if(!pso){pso=pso_insert(&key,hash);CHECK(vkCreatePipelineLayout(G.device,&li,NULL,&pso->layout));
VkComputePipelineCreateInfo ci={.sType=VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO,
.stage={.sType=VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,.stage=VK_SHADER_STAGE_COMPUTE_BIT,.module=s->module,.pName="main"},.layout=pso->layout};
uint64_t started=dm_android_nvn_clock_ns();CHECK(vkCreateComputePipelines(G.device,G.pipeline_cache,1,&ci,NULL,&pso->pipeline));started=dm_android_nvn_clock_ns()-started;G.profile_pipeline_ns+=started;G.pso_made++;G.pso_made_ns+=started;}
vkCmdBindPipeline(G.batch->command,VK_PIPELINE_BIND_POINT_COMPUTE,pso->pipeline);
if(s->set)vkCmdBindDescriptorSets(G.batch->command,VK_PIPELINE_BIND_POINT_COMPUTE,pso->layout,0,1,&s->set,0,NULL);
if(s->dyn_set)vkCmdBindDescriptorSets(G.batch->command,VK_PIPELINE_BIND_POINT_COMPUTE,pso->layout,2,1,&s->dyn_set,s->ndyn,s->dyn_off);
vkCmdDispatch(G.batch->command,p->x,p->y,p->z);
pp_draws0=G.draws;pp_ps=s->key;pp_stamp('D',p->x,p->y);
aligned_writeback();all_barrier();
}
static void copy_b2t(const p_copy_b2t *p) {
if(p->flags || p->r.zoffset<0 || p->r.depth<1 || p->r.xoffset<0 || p->r.yoffset<0 || p->r.width<0 || p->r.height<0)
die("buffer-to-texture flags/view/region",p->flags);
unsigned level=p->has_view&&p->view.set_levels?(unsigned)p->view.base_level:0;
int volume=p->tex->d.target==NVN_TEXTURE_TARGET_3D;
unsigned layer=(p->has_view&&p->view.set_layers?(unsigned)p->view.min_layer:0)+(unsigned)p->r.zoffset;
unsigned available=volume?(p->tex->d.depth>>level):p->tex->L.layers;if(!available)available=1;
if(layer>=available || (unsigned)p->r.depth>available-layer) {
fprintf(stderr,"[nvn-vulkan] b2t target=%d extent=%u,%u,%u layers=%u region=%d,%d,%d,%d,%d,%d view_flags=%u,%u levels=%d,%d layers=%d,%d\n",
p->tex->d.target,p->tex->d.width,p->tex->d.height,p->tex->d.depth,p->tex->L.layers,
p->r.xoffset,p->r.yoffset,p->r.zoffset,p->r.width,p->r.height,p->r.depth,p->view.set_levels,p->view.set_layers,
p->view.base_level,p->view.nlevels,p->view.min_layer,p->view.nlayers);
die("buffer-to-texture layer range",layer);
}
if(level>=p->tex->d.levels || (p->has_view &&
((p->view.set_format&&p->view.format!=p->tex->d.format) ||
(p->view.set_target&&p->view.target!=p->tex->d.target))))die("buffer-to-texture view range/format/target",level);
uint32_t pf;int bb;int bc=nvn_bc_unpacked(p->tex->d.format,&pf,&bb);
/* A compressed texture can already contain streamed CPU mip data when a
* transfer updates only its tail. Preserve the other levels from its NVN
* backing on first materialization, just as copy_t2t does. */
VTexture *t=texture_get(p->tex,bc);uint64_t row=G.state.copy_stride?G.state.copy_stride:(uint64_t)p->r.width*t->bpp;
unsigned width=t->width>>level,height=t->height>>level;if(!width)width=1;if(!height)height=1;
if(bc) {
int bw,bh;int block=nvn_fmt_bpb(p->tex->d.format,&bw,&bh);
row=G.state.copy_stride?G.state.copy_stride:(uint64_t)((p->r.width+bw-1)/bw)*block;
uint64_t rows=(p->r.height+bh-1)/bh,size=row*rows*p->r.depth;
if(!block || row<(uint64_t)((p->r.width+bw-1)/bw)*block ||
(uint64_t)p->r.xoffset+p->r.width>width || (uint64_t)p->r.yoffset+p->r.height>height)
die("compressed buffer-to-texture range/stride",row);
for(int i=0;i<G.batch->nwrites;++i)if(overlap(p->src,size,G.batch->writes[i].addr,G.batch->writes[i].size))
die("compressed decode requires completed GPU source write",p->src);
if(!pool_find(p->src,size,NULL))die("compressed decode source range",p->src);
/* No queued GPU write overlaps this range (checked above), so the
* compressed source bytes are authoritative in guest CPU memory. */
const uint8_t *compressed=(const void *)(uintptr_t)p->src;
uint64_t image_bytes=(uint64_t)p->r.width*p->r.height*t->bpp;
VBuffer *staging=temporary(image_bytes*p->r.depth,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
for(int z=0;z<p->r.depth;++z)if(nvn_bc_decode(p->tex->d.format,compressed+z*row*rows,row,p->r.width,p->r.height,staging->map+z*image_bytes,(size_t)p->r.width*t->bpp))
die("buffer-to-texture BC decode",p->tex->d.format);
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,volume?0:layer,volume?1:p->r.depth},
.imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}};
vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,1,&c);t->cpu_owned=0;t->version++;return;
}
if(row%t->bpp || row<(uint64_t)p->r.width*t->bpp || (uint64_t)p->r.xoffset+p->r.width>width || (uint64_t)p->r.yoffset+p->r.height>height)
die("buffer-to-texture extent/stride",row);
uint64_t offset=0;VPool *src=pool_read(p->src,row*p->r.height*p->r.depth,&offset);all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkBufferImageCopy c={.bufferOffset=offset,.bufferRowLength=(uint32_t)(row/t->bpp),.imageSubresource={aspect(t->format),level,volume?0:layer,volume?1:p->r.depth},
.imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}};
vkCmdCopyBufferToImage(G.batch->command,src->v.b,t->image,t->layout,1,&c);t->cpu_owned=0;t->version++;
}
static void clear_color(const p_clear_color *p) {
if(p->mask!=15 || p->index<0 || p->index>=G.state.rt.n)die("clear-color target/mask/view",p->mask);
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(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;
if(s.extent.width>w-s.offset.x)s.extent.width=w-s.offset.x;if(s.extent.height>h-s.offset.y)s.extent.height=h-s.offset.y;
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++;
}
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,
(unsigned long long)(G.state.rt.depth?G.state.rt.depth->serial:0));
if(!G.state.rt.depth || (p->stencil_mask && p->stencil_mask!=255 && p->stencil_mask!=-1))die("depth/stencil clear target/mask",p->stencil_mask);
VTexture *t=texture_get(G.state.rt.depth,0);VkImageAspectFlags flags=0;
if(p->depth_mask)flags|=VK_IMAGE_ASPECT_DEPTH_BIT;if(p->stencil_mask)flags|=VK_IMAGE_ASPECT_STENCIL_BIT;
flags&=aspect(t->format);if(!flags)return;
VkImageSubresourceRange range=attachment_range(&t->source,G.state.rt.has_dview?&G.state.rt.dview:NULL);range.aspectMask=flags;
unsigned w=t->width>>range.baseMipLevel,h=t->height>>range.baseMipLevel;if(!w)w=1;if(!h)h=1;
VkRect2D s=G.state.scissor;
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("depth clear negative scissor",0);
if((unsigned)s.offset.x>=w || (unsigned)s.offset.y>=h)return;
if(s.extent.width>w-s.offset.x)s.extent.width=w-s.offset.x;if(s.extent.height>h-s.offset.y)s.extent.height=h-s.offset.y;
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++;
}
static void clear_tex(const p_clear_tex *p) {
const view_t *v=p->has_view?&p->view:NULL;
unsigned level=v&&v->set_levels?v->base_level:0,layer=v&&v->set_layers?v->min_layer:0;
int nvn=v&&v->set_format?v->format:p->tex->d.format;
VTexture *t=texture_get(p->tex,0);
fprintf(stderr,"[nvn-vulkan] CLEAR_TEX serial=%llu basefmt=%d viewfmt=%d region=%d,%d,%d,%d,%d,%d uint=%u\n",(unsigned long long)p->tex->serial,p->tex->d.format,nvn,p->r.xoffset,p->r.yoffset,p->r.zoffset,p->r.width,p->r.height,p->r.depth,p->is_uint);
unsigned w=t->width>>level,h=t->height>>level;if(!w)w=1;if(!h)h=1;
int volume=p->tex->d.target==NVN_TEXTURE_TARGET_3D;
unsigned z=volume?(t->depth>>level):p->tex->L.layers;if(!z)z=1;
int bw,bh,bpp=nvn_fmt_bpb(nvn,&bw,&bh);
if(p->mask!=15 || level>=p->tex->d.levels || p->r.xoffset<0 || p->r.yoffset<0 || p->r.zoffset<0 ||
p->r.width<0 || p->r.height<0 || p->r.depth<1 || bw!=1 || bh!=1 || bpp>16 || bpp!=(int)t->bpp ||
(v&&v->set_target&&v->target!=p->tex->d.target) || (uint64_t)p->r.xoffset+p->r.width>w ||
(uint64_t)p->r.yoffset+p->r.height>h || (uint64_t)(volume?0:layer)+p->r.zoffset+p->r.depth>z)
die("texture clear view/region/mask",nvn);
if(!p->r.width || !p->r.height)return;
uint8_t pixel[16]={0};int channels=0,unorm=0,integer=0,floating=0;
switch(nvn) {
case NVN_FORMAT_R8:channels=1;unorm=1;break;case NVN_FORMAT_RG8:channels=2;unorm=1;break;case NVN_FORMAT_RGBA8:case NVN_FORMAT_RGBA8_SRGB:channels=4;unorm=1;break;
case NVN_FORMAT_R8UI:channels=1;integer=1;break;case NVN_FORMAT_RG8UI:channels=2;integer=1;break;case NVN_FORMAT_RGBA8UI:channels=4;integer=1;break;
case NVN_FORMAT_R32UI:channels=1;integer=4;break;case NVN_FORMAT_RG32UI:channels=2;integer=4;break;case NVN_FORMAT_RGBA32UI:channels=4;integer=4;break;
case NVN_FORMAT_R32F:channels=1;floating=1;break;case NVN_FORMAT_RG32F:channels=2;floating=1;break;case NVN_FORMAT_RGBA32F:channels=4;floating=1;break;
default:die("texture clear value format",nvn);
}
for(int i=0;i<channels;i++) {
double value=p->is_uint?(double)p->c.u[i]:(double)p->c.f[i];
if(unorm) {
value=fmax(0,fmin(1,value));
if(nvn==NVN_FORMAT_RGBA8_SRGB && i<3)value=value<=0.0031308?12.92*value:1.055*pow(value,1.0/2.4)-0.055;
pixel[i]=(uint8_t)floor(value*255+0.5);
}else if(integer==1)pixel[i]=(uint8_t)fmax(0,fmin(255,value));
else if(integer==4) {uint32_t u=p->is_uint?p->c.u[i]:(uint32_t)fmax(0,fmin(4294967295.0,value));memcpy(pixel+i*4,&u,4);}
else if(floating) {float f=(float)value;memcpy(pixel+i*4,&f,4);}
}
uint64_t bytes=(uint64_t)p->r.width*p->r.height*p->r.depth*bpp;
VBuffer *staging=temporary(bytes,VK_BUFFER_USAGE_TRANSFER_SRC_BIT);
for(uint64_t i=0;i<bytes;i+=bpp)memcpy(staging->map+i,pixel,bpp);
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,volume?0:layer+p->r.zoffset,volume?1:p->r.depth},
.imageOffset={p->r.xoffset,p->r.yoffset,volume?p->r.zoffset:0},.imageExtent={p->r.width,p->r.height,volume?p->r.depth:1}};
vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layout,1,&c);
t->cpu_owned=0;t->version++; /* GPU now owns the image; sampled access must preserve it. */
}
static VkImageSubresourceLayers copy_layers(const tex_t *t,VkFormat gpu_format,const view_t *v,const NVNcopyRegion *r) {
unsigned level=v&&v->set_levels?v->base_level:0,base=v&&v->set_layers?v->min_layer:0;
int volume=t->d.target==NVN_TEXTURE_TARGET_3D;
if(level>=t->d.levels || (v&&v->set_levels&&v->nlevels<1) || (v&&v->set_format&&v->format!=t->d.format) ||
(v&&v->set_target&&v->target!=t->d.target) || r->xoffset<0 || r->yoffset<0 || r->zoffset<0 || r->width<1 || r->height<1 || r->depth<1)
die("texture copy view/region",t->serial);
unsigned w=t->d.width>>level,h=(t->d.target==NVN_TEXTURE_TARGET_1D || t->d.target==NVN_TEXTURE_TARGET_1D_ARRAY)?1:t->d.height>>level;
unsigned z=volume?t->d.depth>>level:t->L.layers;if(!w)w=1;if(!h)h=1;if(!z)z=1;
if((uint64_t)r->xoffset+r->width>w || (uint64_t)r->yoffset+r->height>h || (uint64_t)(volume?0:base)+r->zoffset+r->depth>z)
die("texture copy extent",t->serial);
/* BC images have already been expanded into the resident GPU format.
* Their guest format is not a Vulkan image format in this backend. */
return (VkImageSubresourceLayers){aspect(gpu_format),level,volume?0:base+r->zoffset,volume?1:r->depth};
}
static void copy_t2t(const p_copy_t2t *p) {
if(p->flags&~(NVN_COPY_FLAGS_ENGINE_2D_BIT|NVN_COPY_FLAGS_LINEAR_FILTER_BIT))die("texture copy flags",p->flags);
uint32_t decoded_format;int decoded_bpp;
int bc_destination=nvn_bc_unpacked(p->dst->d.format,&decoded_format,&decoded_bpp);
/* A partial BC update must retain the other compressed blocks already
* present in guest storage, even when the destination is first used here. */
VTexture *s=texture_get(p->src,1),*d=texture_get(p->dst,bc_destination);
int sv=p->src->d.target==NVN_TEXTURE_TARGET_3D,dv=p->dst->d.target==NVN_TEXTURE_TARGET_3D;
if(s==d || sv!=dv || s->format!=d->format || p->src->d.format!=p->dst->d.format)die("texture copy alias/dimension/format",p->dst->serial);
VkImageSubresourceLayers sl=copy_layers(p->src,s->format,p->has_sv?&p->sv:NULL,&p->sr),dl=copy_layers(p->dst,d->format,p->has_dv?&p->dv:NULL,&p->dr);
if(vk_trace())fprintf(stderr,"[nvn-vulkan] COPY_T2T src=%llu dst=%llu region=%d,%d,%d -> %d,%d,%d flags=%#x src_level=%u dst_level=%u src_layer=%u dst_layer=%u\n",(unsigned long long)p->src->serial,(unsigned long long)p->dst->serial,p->sr.width,p->sr.height,p->sr.depth,p->dr.width,p->dr.height,p->dr.depth,p->flags,sl.mipLevel,dl.mipLevel,sl.baseArrayLayer,dl.baseArrayLayer);
texture_transition(s,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);texture_transition(d,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);all_barrier();
VkOffset3D so={p->sr.xoffset,p->sr.yoffset,sv?p->sr.zoffset:0},doff={p->dr.xoffset,p->dr.yoffset,dv?p->dr.zoffset:0};
if(p->sr.width==p->dr.width&&p->sr.height==p->dr.height&&p->sr.depth==p->dr.depth) {
VkImageCopy c={.srcSubresource=sl,.srcOffset=so,.dstSubresource=dl,.dstOffset=doff,.extent={p->sr.width,p->sr.height,sv?p->sr.depth:1}};
vkCmdCopyImage(G.batch->command,s->image,s->layout,d->image,d->layout,1,&c);
}else {
VkFormatProperties fp;vkGetPhysicalDeviceFormatProperties(G.physical,s->format,&fp);
if(aspect(s->format)!=VK_IMAGE_ASPECT_COLOR_BIT || !(p->flags&NVN_COPY_FLAGS_ENGINE_2D_BIT) || (!sv&&p->sr.depth!=p->dr.depth) ||
!(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_SRC_BIT)||!(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_DST_BIT))die("texture scaled copy feature/flags",p->flags);
VkFilter filter=p->flags&NVN_COPY_FLAGS_LINEAR_FILTER_BIT?VK_FILTER_LINEAR:VK_FILTER_NEAREST;
if(filter==VK_FILTER_LINEAR&&!(fp.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))die("texture blit linear feature",s->format);
VkImageBlit c={.srcSubresource=sl,.srcOffsets={so,{so.x+p->sr.width,so.y+p->sr.height,so.z+(sv?p->sr.depth:1)}},
.dstSubresource=dl,.dstOffsets={doff,{doff.x+p->dr.width,doff.y+p->dr.height,doff.z+(dv?p->dr.depth:1)}}};
vkCmdBlitImage(G.batch->command,s->image,s->layout,d->image,d->layout,1,&c,filter);
}
d->cpu_owned=0;d->version++;all_barrier();
}
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);
for(unsigned guard=0;guard<1000000;guard++) {
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;
switch(h.op) {
case OP_END:return;
case OP_BEGIN:break; /* Structural record; GPU binding state persists across command handles. */
case OP_JUMP:payload_check(&h,8);memcpy(&p,a,8);continue;
case OP_CALL:{const uint8_t *next;payload_check(&h,8);memcpy(&next,a,8);execute(next,depth+1);break;}
case OP_SIGNAL_EVENT:{Event e;payload_check(&h,16);memcpy(&e.addr,a,8);memcpy(&e.mode,a+8,4);memcpy(&e.value,a+12,4);mtl_sub_event(e.addr,e.mode,e.value);break;}
case OP_REPORT_COUNTER:{uint64_t type,address;payload_check(&h,16);memcpy(&type,a,8);memcpy(&address,a+8,8);mtl_sub_counter(address,type);break;}
case OP_RESET_COUNTER:{uint64_t type;payload_check(&h,8);memcpy(&type,a,8);
if(type!=NVN_COUNTER_TYPE_SAMPLES_PASSED)die("GPU counter reset type implementation pending",type);
query_end();counter_op(0,0,0);G.counting=1;break;}
case OP_COPY_B2B:{uint64_t src,dst,len;payload_check(&h,24);memcpy(&src,a,8);memcpy(&dst,a+8,8);memcpy(&len,a+16,8);mtl_sub_copy(src,dst,len);break;}
case OP_UPDATE_UB:{uint64_t dst,len;payload_check(&h,16);memcpy(&dst,a,8);memcpy(&len,a+8,8);if(len>h.size-24)die("uniform update payload",len);
all_barrier();uint64_t off=0;VPool *pool=pool_find(dst,len,&off);if(!pool || off%4 || len%4 || len>65536)die("uniform update bounds/alignment",len);
pool_materialize(pool);vkCmdUpdateBuffer(G.batch->command,pool->v.b,off,len,a+16);mark_write(dst,len);break;}
case OP_SET_RT:payload_check(&h,sizeof(p_set_rt));memcpy(&G.state.rt,a,sizeof(p_set_rt));break;
case OP_CLEAR_COLOR:payload_check(&h,sizeof(p_clear_color));clear_color((const p_clear_color *)a);break;
case OP_CLEAR_DS:payload_check(&h,sizeof(p_clear_ds));clear_ds((const p_clear_ds *)a);break;
case OP_VIEWPORTS:{payload_check(&h,sizeof(p_viewports));const p_viewports *v=(const void *)a;if(v->first || v->n!=1)die("multiple viewports",v->n);
/* NVN SetViewports records only x/y/w/h; depth range has its own
* command and survives viewport changes. */
G.state.viewport.x=v->v[0][0];G.state.viewport.y=v->v[0][1];
G.state.viewport.width=v->v[0][2];G.state.viewport.height=v->v[0][3];break;}
case OP_SCISSOR:{payload_check(&h,sizeof(p_scissor));const p_scissor *s=(const void *)a;if(s->x<0||s->y<0||s->w<0||s->h<0)die("scissor bounds",s->x);
G.state.scissor=(VkRect2D){{s->x,s->y},{s->w,s->h}};break;}
case OP_DEPTH_RANGE:{payload_check(&h,sizeof(p_depth_range));const p_depth_range *d=(const void *)a;G.state.viewport.minDepth=d->n;G.state.viewport.maxDepth=d->f;break;}
case OP_BIND_PROGRAM:payload_check(&h,sizeof(p_bind_program));G.state.program=((const p_bind_program *)a)->prog;break;
case OP_BIND_STATE:{payload_check(&h,sizeof(p_bind_state));const p_bind_state *b=(const void *)a;switch(b->kind){
case 0:{blend_st s;memcpy(&s,b->bytes,sizeof(s));if(s.target>=8)die("blend target",s.target);G.state.blend[s.target]=s;break;}
case 1:memcpy(&G.state.color,b->bytes,sizeof(color_st));break;case 2:memcpy(&G.state.mask,b->bytes,sizeof(chmask_st));break;
case 3:memcpy(&G.state.ms,b->bytes,sizeof(ms_st));break;case 4:memcpy(&G.state.polygon,b->bytes,sizeof(poly_st));break;
case 5:memcpy(&G.state.ds,b->bytes,sizeof(ds_st));break;default:die("state kind",b->kind);}break;}
case OP_BIND_VATTR:{payload_check(&h,offsetof(p_bind_vattr,st));const p_bind_vattr *b=(const void *)a;if(b->first<0||b->n<0||b->first>16||b->n>16-b->first)die("vertex attribute range",b->n);
payload_check(&h,offsetof(p_bind_vattr,st)+(size_t)b->n*sizeof(va_st));
memcpy(G.state.attributes+b->first,b->st,b->n*sizeof(va_st));break;}
case OP_BIND_VSTREAM:{payload_check(&h,offsetof(p_bind_vstream,st));const p_bind_vstream *b=(const void *)a;if(b->first<0||b->n<0||b->first>16||b->n>16-b->first)die("vertex stream range",b->n);
payload_check(&h,offsetof(p_bind_vstream,st)+(size_t)b->n*sizeof(vs_st));
memcpy(G.state.streams+b->first,b->st,b->n*sizeof(vs_st));break;}
case OP_BIND_VBUF:{payload_check(&h,offsetof(p_bind_vbuf,r));const p_bind_vbuf *b=(const void *)a;if(b->first<0||b->n<0||b->first>16||b->n>16-b->first)die("vertex buffer range",b->n);
payload_check(&h,offsetof(p_bind_vbuf,r)+(size_t)b->n*sizeof(NVNbufferRange));
memcpy(G.state.vbuf+b->first,b->r,b->n*sizeof(NVNbufferRange));break;}
case OP_BIND_UBO:case OP_BIND_SSBO:{payload_check(&h,sizeof(p_bind_buf));const p_bind_buf *b=(const void *)a;if(b->stage<0||b->stage>=6||b->index<0||b->index>=16)die("buffer stage/index",b->index);
Range *dest=h.op==OP_BIND_UBO?G.state.uniform[b->stage]:G.state.storage[b->stage];dest[b->index]=(Range){b->addr,b->size};G.bind_gen[b->stage]++;break;}
case OP_STENCIL:{payload_check(&h,sizeof(p_stencil));const p_stencil *s=(const void *)a;if(s->face<0||s->face>3||s->which<0||s->which>2)die("stencil dynamic parameters",s->face);
for(int i=0;i<2;i++) {
if(s->face&(1<<i)){if(s->which==0)G.state.stencil_compare[i]=s->value_mask;
else if(s->which==1)G.state.stencil_write[i]=s->mask;else G.state.stencil_ref[i]=s->ref;}
}
break;}
case OP_BIND_TEX:case OP_BIND_SAMP:case OP_BIND_IMG:{payload_check(&h,offsetof(p_bind_handles,h));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)die("texture/sampler binding range",b->n);
payload_check(&h,offsetof(p_bind_handles,h)+(size_t)b->n*sizeof(uint64_t));
uint64_t *dest=h.op==OP_BIND_TEX?G.state.tex[b->stage]:h.op==OP_BIND_SAMP?G.state.samp[b->stage]:G.state.img[b->stage];
memcpy(dest+b->first,b->h,b->n*8);G.bind_gen[b->stage]++;break;}
case OP_DRAW:payload_check(&h,sizeof(p_draw));draw((const p_draw *)a,NULL);break;
case OP_DRAW_IDX:payload_check(&h,sizeof(p_draw_idx));draw(NULL,(const p_draw_idx *)a);break;
case OP_DISPATCH:payload_check(&h,sizeof(p_dispatch));dispatch((const p_dispatch *)a);break;
case OP_BARRIER:all_barrier();break; /* Full barrier is stronger than every supported NVN barrier bit. */
case OP_POLY_OFFSET:{payload_check(&h,sizeof(p_poly_offset));const p_poly_offset *v=(const void *)a;
if(v->factor || v->units || v->clamp)die("nonzero polygon offset requires Vulkan pipeline bias",0);
break;}
case OP_WAIT_EVENT:{uint64_t address;uint32_t mode,value;payload_check(&h,16);
memcpy(&address,a,8);memcpy(&mode,a+8,4);memcpy(&value,a+12,4);
if(!pool_find(address,4,NULL) || address%4 || mode>1)die("event wait storage/mode",address);
/* NVN 的 WaitEvent 是 GPU 端等待。单队列按序执行:若此前排队(未发布)的 GPU 信号按序作用后条件已满足,
* GPU 走到这里时必然满足,只需全屏障,CPU 不必等。否则条件要靠之后的 CPU 信号满足,走下面的提交 + 等待 + 轮询。
* NVN WaitEvent is a GPU-side wait. One queue executes in order: if the condition holds once the queued (unpublished)
* GPU signals are applied in order, the GPU must find it satisfied here, so a full barrier suffices and the CPU need not wait.
* Otherwise only a later CPU signal can satisfy it: submit, wait and poll below. */
if(event_satisfied_queued(address,mode,value)){all_barrier();G.event_queued++;break;}
G.event_blocked++;
/* Submit preceding work and publish only its actual GPU results.
* This also handles a signal earlier in the same command handle. */
uint64_t committed=mtl_sub_commit();wait_at(committed,UINT64_MAX,WAIT_EVENT);
uint64_t start=dm_android_nvn_clock_ns();
for(;;){uint32_t observed=atomic_load((_Atomic uint32_t *)(uintptr_t)address);
if(mode==0 ? observed==value : (int32_t)(observed-value)>=0)break;
if(dm_android_nvn_clock_ns()-start>30000000000ULL)die("event wait exceeded diagnostic deadline",address);
struct timespec pause={0,100000};nanosleep(&pause,NULL);
}
mtl_sub_begin();break;}
case OP_WAIT_SYNC:case OP_FENCE_SYNC:{payload_check(&h,sizeof(p_sync));const p_sync *v=(const void *)a;
if(!v->sync || v->sync->magic!=MAGIC('S','Y','N','C'))die("sync lifetime",0);
if(h.op==OP_WAIT_SYNC){
if(!v->sync->fenced || v->sync->fence>G.fence+1)die("wait on unsubmitted sync",v->sync->fence);
/* One queue orders earlier submits; a full barrier orders GPU accesses. */
all_barrier();
}else{
if(v->condition<0 || v->condition>1 || v->flags&~1)die("fence condition/flags",v->flags);
all_barrier();v->sync->fence=G.fence+1;v->sync->fenced=1;
/* CPU completion remains false until vkWaitForFences finishes. */
}break;}
case OP_COPY_B2T:payload_check(&h,sizeof(p_copy_b2t));copy_b2t((const p_copy_b2t *)a);break;
case OP_CLEAR_TEX:payload_check(&h,sizeof(p_clear_tex));clear_tex((const p_clear_tex *)a);break;
case OP_COPY_T2T:payload_check(&h,sizeof(p_copy_t2t));copy_t2t((const p_copy_t2t *)a);break;
case OP_COPY_STRIDE:payload_check(&h,sizeof(p_copy_stride));G.state.copy_stride=((const p_copy_stride *)a)->stride;break;
case OP_BLEND_COLOR:payload_check(&h,sizeof(p_blend_color));memcpy(G.state.blend_color,((const p_blend_color *)a)->rgba,16);break;
case OP_SHADER_SCRATCH:payload_check(&h,sizeof(p_bind_buf));
{const p_bind_buf *r=(const p_bind_buf *)a;
if(!pool_find(r->addr,r->size,NULL))die("shader scratch pool lifetime/range",r->addr);
/* Maxwell LDL/STL are translated to SPIR-V Private variables.
* Vulkan's compiler owns the physical per-invocation allocation;
* the NVN scratch range has no application-visible payload. */
G.state.scratch=(Range){r->addr,r->size};}break;
case OP_SET_TEX_POOL:case OP_SET_SAMP_POOL:payload_check(&h,sizeof(p_set_pool));
if(!((const p_set_pool *)a)->pool)die("null descriptor pool",h.op);
{const dpool_t **current=h.op==OP_SET_TEX_POOL?&G.state.texture_pool:&G.state.sampler_pool;
if(*current && *current!=((const p_set_pool *)a)->pool)die("multiple descriptor pools need qualified registration",h.op);
*current=((const p_set_pool *)a)->pool;}break;
default:die("unimplemented NVN command opcode",h.op);
}
p+=h.size;
}
die("command iteration limit",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) {
if(!G.swapchain)return;CHECK(vkQueueWaitIdle(G.queue));
for(uint32_t i=0;i<8;i++)if(G.swap_done[i]){vkDestroySemaphore(G.device,G.swap_done[i],NULL);G.swap_done[i]=VK_NULL_HANDLE;}
vkDestroySwapchainKHR(G.device,G.swapchain,NULL);G.swapchain=VK_NULL_HANDLE;G.nswap=0;G.swap_stale=0;
}
/* App 前端:没有 Surface(切后台)时出图阻塞到窗口回来,不在后台空跑 GPU | App front end: with no Surface (backgrounded) present blocks until a window returns instead of rendering in the background */
static pthread_mutex_t window_mu=PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t window_cv=PTHREAD_COND_INITIALIZER;
static int window_hold,window_live;
void dm_vk_hold_without_window(int on) { pthread_mutex_lock(&window_mu);window_hold=on;pthread_cond_broadcast(&window_cv);pthread_mutex_unlock(&window_mu); }
static void window_wait(void) {
pthread_mutex_lock(&window_mu);
if(window_hold && !window_live){fprintf(stderr,"[nvn-vulkan] WINDOW_HOLD frame=%llu\n",(unsigned long long)G.present_count);
while(window_hold && !window_live)pthread_cond_wait(&window_cv,&window_mu);
fprintf(stderr,"[nvn-vulkan] WINDOW_RESUME frame=%llu\n",(unsigned long long)G.present_count);}
pthread_mutex_unlock(&window_mu);
}
void dm_vk_set_window(void *native) {
mtl_init();pthread_mutex_lock(&G.lock);drain_locked();CHECK(vkQueueWaitIdle(G.queue));
/* Focus/resume notifications may publish the same BufferQueue again.
* Retain its Vulkan surface instead of disconnecting and reconnecting the
* producer. Invalidate only the swapchain if this window changed size. */
if(native && G.window==native){
if(G.swapchain && ((uint32_t)ANativeWindow_getWidth(G.window)!=G.swap_extent.width ||
(uint32_t)ANativeWindow_getHeight(G.window)!=G.swap_extent.height))swapchain_drop();
pthread_mutex_unlock(&G.lock);return;
}
swapchain_drop();if(G.surface)vkDestroySurfaceKHR(G.instance,G.surface,NULL);
if(G.window)ANativeWindow_release(G.window);G.window=native;G.surface=VK_NULL_HANDLE;
if(G.window){ANativeWindow_acquire(G.window);VkAndroidSurfaceCreateInfoKHR i={.sType=VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR,.window=G.window};
PFN_vkCreateAndroidSurfaceKHR create=(PFN_vkCreateAndroidSurfaceKHR)dm_vk_get(G.instance,"vkCreateAndroidSurfaceKHR");
if(!create)die("Android Vulkan surface entry",0);CHECK(create(G.instance,&i,NULL,&G.surface)); }
pthread_mutex_unlock(&G.lock);
pthread_mutex_lock(&window_mu);window_live=native!=NULL;pthread_cond_broadcast(&window_cv);pthread_mutex_unlock(&window_mu);
}
static void swapchain_make(void) {
if(G.swapchain)return;if(!G.surface)die("present without Android Surface",0);
VkBool32 supported=0;CHECK(vkGetPhysicalDeviceSurfaceSupportKHR(G.physical,G.family,G.surface,&supported));if(!supported)die("queue surface support",0);
VkSurfaceCapabilitiesKHR caps;CHECK(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(G.physical,G.surface,&caps));
if(!(caps.supportedUsageFlags&VK_IMAGE_USAGE_TRANSFER_DST_BIT))die("swapchain transfer usage",caps.supportedUsageFlags);
uint32_t n=0;CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(G.physical,G.surface,&n,NULL));if(!n)die("surface formats",0);
VkSurfaceFormatKHR *formats=calloc(n,sizeof(*formats));if(!formats)die("surface format allocation",n);
CHECK(vkGetPhysicalDeviceSurfaceFormatsKHR(G.physical,G.surface,&n,formats));VkSurfaceFormatKHR chosen=formats[0];
for(uint32_t i=0;i<n;i++)if(formats[i].format==VK_FORMAT_R8G8B8A8_UNORM || formats[i].format==VK_FORMAT_B8G8R8A8_UNORM){chosen=formats[i];break;}free(formats);
G.swap_format=chosen.format;G.swap_extent=caps.currentExtent;
if(G.swap_extent.width==UINT32_MAX)G.swap_extent=(VkExtent2D){(uint32_t)ANativeWindow_getWidth(G.window),(uint32_t)ANativeWindow_getHeight(G.window)};
uint32_t count=caps.minImageCount+1;{const char *e=getenv("DM_VK_SWAP_IMAGES");if(e && atoi(e)>0)count=(uint32_t)atoi(e);}
if(count<caps.minImageCount)count=caps.minImageCount;if(caps.maxImageCount && count>caps.maxImageCount)count=caps.maxImageCount;
VkCompositeAlphaFlagBitsKHR alpha=VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;if(!(caps.supportedCompositeAlpha&alpha))alpha=VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
if(!(caps.supportedCompositeAlpha&alpha))die("surface composite alpha",caps.supportedCompositeAlpha);
VkSwapchainCreateInfoKHR i={.sType=VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR,.surface=G.surface,.minImageCount=count,
.imageFormat=chosen.format,.imageColorSpace=chosen.colorSpace,.imageExtent=G.swap_extent,.imageArrayLayers=1,
.imageUsage=VK_IMAGE_USAGE_TRANSFER_DST_BIT,.imageSharingMode=VK_SHARING_MODE_EXCLUSIVE,.preTransform=caps.supportedTransforms&VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR?VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR:caps.currentTransform,
.compositeAlpha=alpha,.presentMode=VK_PRESENT_MODE_FIFO_KHR,.clipped=VK_TRUE};CHECK(vkCreateSwapchainKHR(G.device,&i,NULL,&G.swapchain));
CHECK(vkGetSwapchainImagesKHR(G.device,G.swapchain,&G.nswap,NULL));if(G.nswap>8)die("swapchain image limit",G.nswap);
CHECK(vkGetSwapchainImagesKHR(G.device,G.swapchain,&G.nswap,G.swap_images));memset(G.swap_layouts,0,sizeof(G.swap_layouts));
VkSemaphoreCreateInfo sem_info={.sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
for(uint32_t k=0;k<G.nswap;k++)CHECK(vkCreateSemaphore(G.device,&sem_info,NULL,&G.swap_done[k]));
fprintf(stderr,"[nvn-vulkan] SWAPCHAIN extent=%u,%u images=%u (min %u) format=%u transform=0x%x\n",G.swap_extent.width,G.swap_extent.height,G.nswap,caps.minImageCount,G.swap_format,(unsigned)caps.currentTransform);
}
/* 按请求截图(dm_gfx_shot_at,DM_NVN_SHOT_UI 等用):第 k 帧出图时读回,写 PPM(路径的 .png 换成 .ppm)
* Screenshot on request (dm_gfx_shot_at, used by DM_NVN_SHOT_UI etc.): read back at the k-th present, written as PPM (a .png path becomes .ppm) */
#define SHOTQ_MAX 8
static struct { uint64_t frame; char path[1024]; } shotq[SHOTQ_MAX]; static int nshotq;
static pthread_mutex_t shotq_mu=PTHREAD_MUTEX_INITIALIZER;
void dm_gfx_shot_at(long k,const char *path) {
pthread_mutex_lock(&shotq_mu);
if(nshotq<SHOTQ_MAX){shotq[nshotq].frame=G.present_count+(uint64_t)(k>0?k:1);snprintf(shotq[nshotq].path,sizeof shotq[0].path,"%s",path);
char *dot=strrchr(shotq[nshotq].path,'.');if(dot && !strcmp(dot,".png"))strcpy(dot,".ppm");nshotq++;}
else fprintf(stderr,"[nvn-vulkan] screenshot queue full, drop %s\n",path);
pthread_mutex_unlock(&shotq_mu);
}
/* 取走第 frame 帧到期的截图请求(一次最多一条,其余下帧再取)| take one screenshot request due at frame (others are taken on later frames) */
static int shot_take(uint64_t frame,char *path,size_t n) {
int hit=0;pthread_mutex_lock(&shotq_mu);
for(int i=0;i<nshotq;i++)if(shotq[i].frame<=frame){snprintf(path,n,"%s",shotq[i].path);shotq[i]=shotq[--nshotq];hit=1;break;}
pthread_mutex_unlock(&shotq_mu);return hit;
}
static unsigned write_ppm(const char *file,const VTexture *t,const uint8_t *map) {
FILE *out=fopen(file,"wb");if(!out){fprintf(stderr,"[nvn-vulkan] cannot write %s\n",file);return 0;}
fprintf(out,"P6\n%u %u\n255\n",t->width,t->height);
size_t row_bytes=(size_t)t->width*3;uint8_t *rgb_row=malloc(row_bytes);if(!rgb_row)die("frame readback row allocation",row_bytes);
unsigned nonblack=0;unsigned red=t->format==VK_FORMAT_B8G8R8A8_UNORM||t->format==VK_FORMAT_B8G8R8A8_SRGB?2:0,blue=2-red;
for(unsigned y=0;y<t->height;y++){
const uint8_t *pixels=map+(uint64_t)y*t->width*4;
for(unsigned x=0;x<t->width;x++){const uint8_t *pixel=pixels+(size_t)x*4;uint8_t *rgb=rgb_row+(size_t)x*3;
rgb[0]=pixel[red];rgb[1]=pixel[1];rgb[2]=pixel[blue];if(rgb[0]||rgb[1]||rgb[2])nonblack++;}
if(fwrite(rgb_row,1,row_bytes,out)!=row_bytes)die("frame readback write",row_bytes);
}
free(rgb_row);fclose(out);return nonblack;
}
/* ADPF(APerformanceHint,API 33+):出图线程单核占用九成以上,一帧的余量只有一两毫秒;不告诉调度器帧预算,它会把线程放到中小核 / 降频,
* 走动时每秒好几帧拖到 25–30 ms。这里给出图线程建会话、目标 = 出图周期,每帧报真实工作时长 = 两次出图的间隔 − 取图里的节拍等待(hle_nvn 经 mtl_pace_slept 报来)。DM_ADPF=0 关
* ADPF (APerformanceHint, API 33+): the present thread runs above 90% of a core, leaving a frame only a millisecond or two of slack; without a frame budget the scheduler
* moves it to mid/little cores or lowers the clock, and while walking several frames a second stretch to 25-30 ms. Open a session for the present thread with target = present period,
* and report each frame's real work time = interval between presents - pacing wait inside acquire (reported by hle_nvn via mtl_pace_slept). DM_ADPF=0 turns it off */
#include <sys/syscall.h>
static _Atomic uint64_t adpf_slept;
void mtl_pace_slept(uint64_t ns) { atomic_fetch_add(&adpf_slept,ns); }
static double v_ms(uint64_t ns){return ns/1e6;}
static void display_timing_poll(void) {
static PFN_vkGetPastPresentationTimingGOOGLE past;static PFN_vkGetRefreshCycleDurationGOOGLE cycle;static uint64_t last,refresh,n,repeat,max_ns,hist[5],lat_sum,lat_n,lat_max;
if(!past){PFN_vkGetDeviceProcAddr dp=(PFN_vkGetDeviceProcAddr)dm_vk_get(G.instance,"vkGetDeviceProcAddr");past=(PFN_vkGetPastPresentationTimingGOOGLE)dp(G.device,"vkGetPastPresentationTimingGOOGLE");cycle=(PFN_vkGetRefreshCycleDurationGOOGLE)dp(G.device,"vkGetRefreshCycleDurationGOOGLE");if(!past){G.display_timing=0;return;}}
if(cycle){VkRefreshCycleDurationGOOGLE r;if(cycle(G.device,G.swapchain,&r)==VK_SUCCESS)refresh=r.refreshDuration;}
VkPastPresentationTimingGOOGLE t[16];uint32_t c=16;if(past(G.device,G.swapchain,&c,t)<0)return;
for(uint32_t i=0;i<c;i++){uint64_t a=t[i].actualPresentTime;if(!a)continue;
{ uint64_t q=G.present_called[t[i].presentID%64];if(q && a>q && a-q<1000000000ull){lat_sum+=a-q;lat_n++;if(a-q>lat_max)lat_max=a-q;} } /* 调出图 → 上屏 | present call -> on screen */
if(last && a>last && a-last<1000000000ull){uint64_t d=a-last,v=refresh?refresh:16666667;n++;if(d>v*3/2)repeat++;if(d>max_ns)max_ns=d;uint64_t k=(d+v/2)/v;hist[k>4?4:k]++;}
last=a;
if(n>=300){fprintf(stderr,"[nvn-vulkan] DISPLAY_TIMING frames=%llu refresh_ms=%.2f repeat=%llu (1拍 %llu / 2拍 %llu / 3拍 %llu / 4+拍 %llu) max_ms=%.1f 出图→上屏 平均 %.1f ms 最大 %.1f ms\n",(unsigned long long)n,v_ms(refresh),(unsigned long long)repeat,
(unsigned long long)hist[1],(unsigned long long)hist[2],(unsigned long long)hist[3],(unsigned long long)hist[4],max_ns/1e6,lat_n?lat_sum/1e6/lat_n:-1.0,lat_max/1e6);n=repeat=max_ns=lat_sum=lat_n=lat_max=0;memset(hist,0,sizeof hist);}}
}
static void adpf_frame(double period) {
static int state;static void *session;static pid_t tid;static int64_t target;static uint64_t last;
static void *(*get_mgr)(void);static void *(*create)(void *,const int32_t *,size_t,int64_t);
static int (*update_target)(void *,int64_t);static int (*report)(void *,int64_t);
if(state<0)return;
if(!state){const char *e=getenv("DM_ADPF");state=-1;if(e && *e=='0')return;
void *lib=dlopen("libandroid.so",RTLD_NOW);if(!lib)return;
get_mgr=(void *(*)(void))dlsym(lib,"APerformanceHint_getManager");
create=(void *(*)(void *,const int32_t *,size_t,int64_t))dlsym(lib,"APerformanceHint_createSession");
update_target=(int (*)(void *,int64_t))dlsym(lib,"APerformanceHint_updateTargetWorkDuration");
report=(int (*)(void *,int64_t))dlsym(lib,"APerformanceHint_reportActualWorkDuration");
if(!get_mgr || !create || !update_target || !report)return;
state=1;}
uint64_t now=dm_android_nvn_clock_ns(),slept=atomic_exchange(&adpf_slept,0);
pid_t self=(pid_t)syscall(SYS_gettid);int64_t want=period>0?(int64_t)(period*1e9):16666667;
if(!session || tid!=self){
void *mgr=get_mgr();int32_t t=self;session=mgr?create(mgr,&t,1,want):NULL;tid=self;target=want;last=now;
fprintf(stderr,"[nvn-vulkan] ADPF session=%p tid=%d target_ms=%.2f\n",session,(int)self,want/1e6);
if(!session)state=-1;return;}
if(want!=target){update_target(session,want);target=want;}
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 */
}
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 触发
* No Surface (adb headless): replay into the present texture as usual but skip the swapchain; readback is triggered by DM_FRAME_DIR / dm_gfx_shot_at */
adpf_frame(period);window_wait();mtl_sub_begin();all_barrier();int windowed=G.window!=NULL;if(windowed){if(G.swap_stale)swapchain_drop();swapchain_make();}
VTexture *t=texture_get(source,0);if(aspect(t->format)!=VK_IMAGE_ASPECT_COLOR_BIT)die("present depth texture",t->format);
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)));
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);
G.batch->ticket=++G.fence;VkFence fence=G.batch->fence;
if(windowed){
/* 取图信号量归批次槽、出图信号量按交换链图像各一个:都可复用,出图不再等 GPU 跑完(旧做法每帧建 / 等队列空 / 销毁)
* The acquire semaphore belongs to the batch slot and there is one present semaphore per swapchain image: both are reused, so present no longer waits for the GPU (the old path created, waited for queue idle and destroyed them every frame) */
if(!G.batch->acquire){VkSemaphoreCreateInfo sem_info={.sType=VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};CHECK(vkCreateSemaphore(G.device,&sem_info,NULL,&G.batch->acquire));}
VkSemaphore available=G.batch->acquire;
uint32_t index=0;VkResult acquired=vkAcquireNextImageKHR(G.device,G.swapchain,UINT64_MAX,available,VK_NULL_HANDLE,&index);
if(acquired==VK_ERROR_OUT_OF_DATE_KHR){swapchain_drop();swapchain_make();acquired=vkAcquireNextImageKHR(G.device,G.swapchain,UINT64_MAX,available,VK_NULL_HANDLE,&index);}
if(acquired!=VK_SUCCESS && acquired!=VK_SUBOPTIMAL_KHR)die("swapchain acquisition",acquired);
VkSemaphore finished=G.swap_done[index];
texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
VkImageMemoryBarrier barrier={.sType=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,.oldLayout=G.swap_layouts[index],
.newLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,.srcQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED,
.dstAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT,.image=G.swap_images[index],.subresourceRange={VK_IMAGE_ASPECT_COLOR_BIT,0,1,0,1}};
/* 源阶段须与取图信号量的等待阶段(TRANSFER)相同,布局转换才排在信号量之后;用 TOP_OF_PIPE 时转换可能抢在合成器读完上一帧前执行,Adreno 上 UBWC 元数据被改,上屏出现台阶状黑块
* The source stage must match the acquire semaphore's wait stage (TRANSFER) so the layout transition is ordered after it; with TOP_OF_PIPE the transition could run while the compositor still reads the previous frame, and on Adreno the rewritten UBWC metadata showed as stepped black blocks on screen */
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,NULL,0,NULL,1,&barrier);
int x=0,y=0,w=t->width,h=t->height;if(crop && crop[2]>0 && crop[3]>0){x=crop[0];y=crop[1];w=crop[2];h=crop[3];}
if(x<0||y<0||w<=0||h<=0||(uint64_t)x+w>t->width||(uint64_t)y+h>t->height)die("present crop bounds",w);
VkImageBlit blit={.srcSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.srcOffsets={{x,y,0},{x+w,y+h,1}},
.dstSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.dstOffsets={{0,0,0},{(int)G.swap_extent.width,(int)G.swap_extent.height,1}}};
VkFormatProperties src_format,dst_format;vkGetPhysicalDeviceFormatProperties(G.physical,t->format,&src_format);
vkGetPhysicalDeviceFormatProperties(G.physical,G.swap_format,&dst_format);
if(!(src_format.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_SRC_BIT)||!(dst_format.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_DST_BIT))die("present blit formats",t->format);
vkCmdBlitImage(G.batch->command,t->image,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,G.swap_images[index],VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,1,&blit,
src_format.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT?VK_FILTER_LINEAR:VK_FILTER_NEAREST);
barrier.oldLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;barrier.newLayout=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;barrier.dstAccessMask=0;
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,0,0,NULL,0,NULL,1,&barrier);
G.swap_layouts[index]=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;writeback_encode();
VkMemoryBarrier host={.sType=VK_STRUCTURE_TYPE_MEMORY_BARRIER,.srcAccessMask=VK_ACCESS_MEMORY_WRITE_BIT,.dstAccessMask=VK_ACCESS_HOST_READ_BIT};
vkCmdPipelineBarrier(G.batch->command,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&host,0,NULL,0,NULL);batch_stamp_end();CHECK(vkEndCommandBuffer(G.batch->command));
VkPipelineStageFlags wait_stage=VK_PIPELINE_STAGE_TRANSFER_BIT;VkSubmitInfo si={.sType=VK_STRUCTURE_TYPE_SUBMIT_INFO,.waitSemaphoreCount=1,
.pWaitSemaphores=&available,.pWaitDstStageMask=&wait_stage,.commandBufferCount=1,.pCommandBuffers=&G.batch->command,
.signalSemaphoreCount=1,.pSignalSemaphores=&finished};
CHECK(vkResetFences(G.device,1,&fence));CHECK(vkQueueSubmit(G.queue,1,&si,fence));G.batch->recording=0;G.batch->pending=1;G.profile_submits++;G.batch->submit_order=++G.batch_count;pthread_cond_signal(&G.completion);VkPresentInfoKHR pi={.sType=VK_STRUCTURE_TYPE_PRESENT_INFO_KHR,.waitSemaphoreCount=1,
.pWaitSemaphores=&finished,.swapchainCount=1,.pSwapchains=&G.swapchain,.pImageIndices=&index};
VkPresentTimeGOOGLE pt={.presentID=(uint32_t)G.present_count+1};VkPresentTimesInfoGOOGLE ptinfo={.sType=VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE,.swapchainCount=1,.pTimes=&pt};
if(G.display_timing){pi.pNext=&ptinfo;struct timespec now;clock_gettime(CLOCK_MONOTONIC,&now);G.present_called[pt.presentID%64]=(uint64_t)now.tv_sec*1000000000ull+now.tv_nsec;}
VkResult presented=vkQueuePresentKHR(G.queue,&pi);if(presented==VK_ERROR_OUT_OF_DATE_KHR)G.swap_stale=1;
else if(presented!=VK_SUCCESS && presented!=VK_SUBOPTIMAL_KHR)die("queue present",presented);
if(G.display_timing)display_timing_poll();
}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);
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);
fprintf(stderr,"[nvn-vulkan] SHOT frame=%llu extent=%u,%u nonblack=%u path=%s\n",(unsigned long long)G.present_count+1,t->width,t->height,nonblack,shot_path);}
buffer_free(&capture);
}
G.active=0;
G.profile_frames++;
if(G.present_count%60==0)pipeline_cache_save_async();
G.profile_present_ns+=dm_android_nvn_clock_ns()-present_started;
if(G.trace_frame || G.profile_frames>=60 || G.present_count<2){uint64_t now=dm_android_nvn_clock_ns();
fprintf(stderr,"[nvn-vulkan] RENDER_PROFILE frame=%llu frames=%llu elapsed_ms=%.3f pipeline_ms=%.3f gpu_wait_ms=%.3f upload_decode_ms=%.3f submits=%llu draws=%llu\n",(unsigned long long)G.present_count+1,(unsigned long long)G.profile_frames,(now-G.profile_start_ns)/1e6,G.profile_pipeline_ns/1e6,G.profile_wait_ns/1e6,G.profile_decode_ns/1e6,(unsigned long long)G.profile_submits,(unsigned long long)(G.draws-G.profile_draws));
if(cpu_profile())fprintf(stderr,"[nvn-vulkan] RENDER_CPU_PROFILE frame=%llu lookup_ms=%.3f pool_ms=%.3f bind_ms=%.3f renderpass_ms=%.3f present_ms=%.3f\n",(unsigned long long)G.present_count+1,G.profile_lookup_ns/1e6,G.profile_pool_ns/1e6,G.profile_bind_ns/1e6,G.profile_render_ns/1e6,G.profile_present_ns/1e6);
fprintf(stderr,"[nvn-vulkan] RENDER_CACHE_PROFILE frame=%llu pso_hits=%llu pso_misses=%llu pass_hits=%llu framebuffer_hits=%llu passes=%llu batches=%llu barriers=%llu pass_breaks=%llu pipeline_binds=%llu set_binds=%llu set_writes=%llu temp_new=%llu temp_new_MiB=%.1f temp_max=%llu temp_drop=%llu temp_free_MiB=%.1f gpu_ms=%.3f\n",
(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);
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]);
fprintf(stderr,"[nvn-vulkan] WAIT_PROFILE frame=%llu%s sync_lag_max=%llu sync_cur_frame=%llu event_queued=%llu event_blocked=%llu\n",(unsigned long long)G.present_count+1,line,(unsigned long long)G.sync_lag_max,(unsigned long long)G.sync_cur_frame,(unsigned long long)G.event_queued,(unsigned long long)G.event_blocked);
memset(G.wait_ns,0,sizeof G.wait_ns);memset(G.wait_n,0,sizeof G.wait_n);G.sync_lag_max=G.sync_cur_frame=G.event_queued=G.event_blocked=0;}
G.profile_input_ns=G.input_calls=G.input_bytes=G.input_max=G.input_gpu_bytes=G.input_shared=0;
G.profile_pso_hits=G.pso_hits;G.profile_pso_misses=G.pso_misses;G.profile_pass_hits=G.pass_hits;G.profile_fb_hits=G.fb_hits;G.profile_passes=G.pass_count;
G.profile_lookup_ns=G.profile_pool_ns=G.profile_bind_ns=G.profile_render_ns=G.profile_present_ns=0;
G.profile_start_ns=now;G.profile_pipeline_ns=G.profile_wait_ns=G.profile_decode_ns=G.profile_submits=G.profile_frames=0;G.profile_draws=G.draws;}
G.trace_frame=G.trace_ui=0;
if(capture_root){char request[1200];snprintf(request,sizeof request,"%s/trace-ui-request",capture_root);
if(!access(request,F_OK)){if(unlink(request))die("UI trace request consume",0);G.trace_frame=G.trace_ui=1;G.trace_meshes=G.ntrace_textures=0;
fprintf(stderr,"[nvn-vulkan] TRACE_NEXT_FRAME frame=%llu ui=1\n",(unsigned long long)G.present_count+2);}
snprintf(request,sizeof request,"%s/trace-request",capture_root);
if(!access(request,F_OK)){if(unlink(request))die("trace request consume",0);G.trace_frame=1;G.trace_meshes=G.ntrace_textures=0;
fprintf(stderr,"[nvn-vulkan] TRACE_NEXT_FRAME frame=%llu\n",(unsigned long long)G.present_count+2);}}
pp_report();
uint64_t ticket=++G.present_count;unsigned slot=ticket%3;
G.frame_tickets[slot]=ticket;G.frame_fences[slot]=G.fence;
pthread_mutex_unlock(&G.lock);return ticket;
}
void mtl_present_wait(uint64_t ticket) {
pthread_mutex_lock(&G.lock);if(ticket>G.present_count)die("unknown present ticket",ticket);
uint64_t fence=G.frame_tickets[ticket%3]==ticket?G.frame_fences[ticket%3]:0;pthread_mutex_unlock(&G.lock);
if(fence)wait_at(fence,UINT64_MAX,WAIT_PRESENT);
}
void mtl_present_flush(void) { mtl_finish(); }
int mtl_has_window(void) { return G.window!=NULL; }
void dm_vk_set_display_hz(int hz) { if(hz<0 || hz>1000)die("Android display refresh rate",hz);G.display_hz=hz; }
int mtl_display_hz(void) { return G.window?G.display_hz:0; } /* 0 means the front end has not supplied a measured display mode. */
double mtl_presented_time(uint64_t ticket) { (void)ticket;return 0; } /* Actual scanout timing is not available yet. */
uint64_t mtl_present_count(void) { return G.present_count; }
void mtl_read_texels(const tex_t *source,unsigned level,unsigned layer,const NVNcopyRegion *region,uint8_t *dst,size_t row,size_t img) {
int volume=source->d.target==NVN_TEXTURE_TARGET_3D;
unsigned depth=volume?source->d.depth>>level:1;if(!depth)depth=1;
if(G.active || !region || region->zoffset<0 || (unsigned)region->zoffset>=depth || region->depth!=1 || level>=source->d.levels || layer>=source->L.layers)die("CPU texture read mip/layer/inflight",level);
uint32_t decoded_format;int decoded_bpp;if(nvn_bc_unpacked(source->d.format,&decoded_format,&decoded_bpp))die("BC readback needs original-format encoding",source->d.format);
mtl_sub_begin();VTexture *t=texture_get(source,1);unsigned width=t->width>>level,height=t->height>>level;if(!width)width=1;if(!height)height=1;
if(region->xoffset<0||region->yoffset<0||region->width<0||region->height<0||
(uint64_t)region->xoffset+region->width>width||(uint64_t)region->yoffset+region->height>height)die("CPU texture read bounds",region->width);
size_t pitch=(size_t)region->width*t->bpp;if(row<pitch || (img && img<row*(size_t)region->height))die("CPU texture read stride",row);
VBuffer readback=buffer_make(pitch*region->height,VK_BUFFER_USAGE_TRANSFER_DST_BIT);texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
VkBufferImageCopy copy={.imageSubresource={aspect(t->format),level,layer,1},.imageOffset={region->xoffset,region->yoffset,region->zoffset},.imageExtent={region->width,region->height,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,readback.b,1,&copy);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX);
for(int y=0;y<region->height;y++)memcpy(dst+y*row,readback.map+y*pitch,pitch);buffer_free(&readback);
}
#ifdef DM_VK_COPY_TEST
void dm_vk_copy_test_pool_bytes(uint64_t *logical,uint64_t *resident) {
*logical=*resident=0;for(int i=0;i<G.npool;i++){*logical+=G.pools[i].size;*resident+=G.pools[i].v.size;}
}
/* Independent device probe only: inspect expanded BC pixels without promising
* compressed guest-format CPU readback or introducing a lossy BC encoder. */
void dm_vk_copy_test_read(const tex_t *source,unsigned level,unsigned layer,uint8_t *dst) {
if(G.active || level>=source->d.levels || layer>=source->L.layers)die("copy probe subresource",level);
mtl_sub_begin();VTexture *t=texture_get(source,1);
unsigned w=t->width>>level,h=t->height>>level;if(!w)w=1;if(!h)h=1;
VBuffer readback=buffer_make((uint64_t)w*h*t->bpp,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
VkBufferImageCopy c={.imageSubresource={aspect(t->format),level,layer,1},.imageExtent={w,h,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,readback.b,1,&c);uint64_t ticket=mtl_sub_commit();wait_at(ticket,UINT64_MAX,WAIT_READTEX);
memcpy(dst,readback.map,(size_t)w*h*t->bpp);buffer_free(&readback);
}
#endif
void mtl_stats(uint64_t *passes,uint64_t *draws) { *passes=G.pass_count;*draws=G.draws; }
void mtl_pkg_stats(uint64_t *uploads,uint64_t *reuploads) { *uploads=G.uploads;*reuploads=0; }
void mtl_set_frame(uint64_t frame) { G.frame=frame; }
double mtl_gpu_ms(uint64_t frame) { (void)frame;return -1; }
int mtl_gpu_span(uint64_t frame,uint64_t *a,uint64_t *b) { (void)frame;(void)a;(void)b;return 0; }
int mtl_warm_wait(int timeout) { (void)timeout;return 0; } /* No asynchronous pipeline warm-up job exists. */
/* 出图节拍(同 iOS 的 DM_PRESENT_LINK,缺省开):AChoreographer 的显示节拍定游戏开帧时刻——跑得快就等下一拍,落后(上一帧开工后已过了一拍)立刻开工;
* 一帧占几拍 = 目标帧周期 / 实测节拍周期(60 帧在 60 Hz 屏 1 拍、在 120 Hz 屏 2 拍;省电 30 帧 2 / 4 拍)。hle_nvn 自己的 60 Hz 软件时钟只在节拍等不到(后台 / 无窗口)时兜底。
* iOS 真机同进程交替:负载超一拍时长帧 15% → 0、帧间隔变匀。省电模式另提示合成器降刷新率。DM_PRESENT_LINK=0 回到软件时钟(30 帧时为软件 30 Hz 节拍)
* Present pacing (same as iOS DM_PRESENT_LINK, on by default): AChoreographer's display ticks decide when the game starts a frame -- when running fast wait for the next tick, when behind (a tick already passed since the previous frame started) start at once;
* ticks per frame = target frame period / measured tick period (60 fps: 1 tick on a 60 Hz panel, 2 on 120 Hz; eco 30 fps: 2 / 4). hle_nvn's own 60 Hz software clock is only the fallback when no tick arrives (background / no window).
* iOS same-process A/B: with load above one tick, long frames 15% -> 0 and frame intervals even out. Eco mode also hints the compositor to lower the refresh rate. DM_PRESENT_LINK=0 returns to the software clock (a software 30 Hz tick at 30 fps) */
#include <android/choreographer.h>
#include <android/looper.h>
int mtl_fps_target(void); /* nvn_vk_stats.c */
static void frame_rate_hint(int fps) {
static ANativeWindow *hinted;static int hinted_fps;static int (*set_rate)(ANativeWindow *,float,int8_t);static int looked;
if(!G.window || (G.window==hinted && fps==hinted_fps))return;
if(!looked){looked=1;void *lib=dlopen("libnativewindow.so",RTLD_NOW);if(lib)set_rate=(int (*)(ANativeWindow *,float,int8_t))dlsym(lib,"ANativeWindow_setFrameRate");}
hinted=G.window;hinted_fps=fps;
int rc=set_rate?set_rate(G.window,(float)fps,0):-1;fprintf(stderr,"[nvn-vulkan] FRAME_RATE_HINT fps=%d rc=%d\n",fps,rc);
}
static pthread_mutex_t link_mu=PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t link_cv;
static uint64_t link_tick_n,link_last_ns,link_vsync_ns; /* 节拍号 / 上一拍时刻 / 实测节拍周期 | tick number / last tick time / measured tick period */
static int link_state; /* 0 未起,1 节拍线程在跑,-1 关 / 起不来 | 0 not started, 1 tick thread running, -1 off / failed */
static void link_frame(int64_t frame_ns,void *arg) {
static uint64_t win_min,win_n; /* 近 60 拍间隔的最小值 | minimum interval over the last 60 ticks */
pthread_mutex_lock(&link_mu);
uint64_t t=(uint64_t)frame_ns,d=link_last_ns && t>link_last_ns?t-link_last_ns:0;
/* 周期取近况的下沿:漏回调的两拍间隔、回调扎堆的 5 ms 以下间隔(200 Hz 以上)都不算,变短立刻跟;变长(120→60,如切后台时桌面临时拉到 120 Hz、回来降回 60)按 60 拍窗口的最小间隔整段换,
* 旧做法只跟 1.5 倍以内的变长,120→60 永远停在 8.3 ms,60 帧被当成每帧 2 拍、实际掉到 20 多帧。系统的刷新率回调(link_rate)另清零重测
* The period tracks the lower edge: a gap from a missed callback and an interval under 5 ms from bunched callbacks (above 200 Hz) do not count, and a shorter one is taken at once; a longer one (120->60, e.g. the launcher boosting to 120 Hz while the app is in the background, then back to 60)
* is replaced wholesale by the minimum interval of a 60-tick window. The old code only followed growth within 1.5x, so 120->60 stayed at 8.3 ms, 60 fps counted as 2 ticks a frame and dropped to the low 20s. The system refresh-rate callback (link_rate) also clears it for a re-measure */
if(d>5000000 && d<100000000){if(!link_vsync_ns || d<link_vsync_ns)link_vsync_ns=d;
if(!win_min || d<win_min)win_min=d;
if(++win_n>=60){if(win_min>link_vsync_ns*5/4){fprintf(stderr,"[nvn-vulkan] PRESENT_LINK 节拍周期 %.2f → %.2f ms\n",link_vsync_ns/1e6,win_min/1e6);link_vsync_ns=win_min;}win_min=win_n=0;}}
link_last_ns=t;link_tick_n++;pthread_cond_broadcast(&link_cv);pthread_mutex_unlock(&link_mu);
AChoreographer_postFrameCallback64(AChoreographer_getInstance(),link_frame,arg);
}
/* 显示换刷新率(Choreographer 线程上回调):只清掉估计、从下一拍起重测——屏幕周期不一定是本应用收到的节拍(系统可按应用帧率限流成 60 Hz 回调)
* Display refresh rate changed (called on the Choreographer thread): only clear the estimate and re-measure from the next tick -- the panel period is not necessarily the tick this app receives (the system may throttle callbacks to the app's frame rate) */
static void link_rate(int64_t period_ns,void *arg) {
(void)arg;pthread_mutex_lock(&link_mu);
fprintf(stderr,"[nvn-vulkan] PRESENT_LINK 刷新率 %.1f Hz,节拍周期重测(原 %.2f ms)\n",period_ns>0?1e9/period_ns:0.0,link_vsync_ns/1e6);
link_vsync_ns=0;pthread_mutex_unlock(&link_mu);
}
static void *link_main(void *arg) {
(void)arg;pthread_setname_np("nvn-present-link");
ALooper_prepare(0);AChoreographer *c=AChoreographer_getInstance();
if(!c){pthread_mutex_lock(&link_mu);link_state=-1;pthread_mutex_unlock(&link_mu);fprintf(stderr,"[nvn-vulkan] PRESENT_LINK no choreographer\n");return NULL;}
AChoreographer_postFrameCallback64(c,link_frame,NULL);
{ void (*reg)(AChoreographer *,void (*)(int64_t,void *),void *)=(void (*)(AChoreographer *,void (*)(int64_t,void *),void *))dlsym(RTLD_DEFAULT,"AChoreographer_registerRefreshRateCallback"); /* API 30+ */
if(reg)reg(c,link_rate,NULL); }
for(;;)ALooper_pollOnce(-1,NULL,NULL,NULL);
}
static int link_on(void) {
if(link_state)return link_state>0;
const char *e=getenv("DM_PRESENT_LINK");if(e && *e=='0'){link_state=-1;return 0;}
pthread_condattr_t ca;pthread_condattr_init(&ca);pthread_condattr_setclock(&ca,CLOCK_MONOTONIC);pthread_cond_init(&link_cv,&ca);
pthread_t th;link_state=pthread_create(&th,NULL,link_main,NULL)?-1:1;if(link_state>0)pthread_detach(th);
fprintf(stderr,"[nvn-vulkan] PRESENT_LINK %s\n",link_state>0?"on (AChoreographer)":"off");
return link_state>0;
}
int mtl_link_active(void) {
int fps=mtl_fps_target()==30?30:60;frame_rate_hint(fps);
if(!G.window)return 0;
return link_on() || fps==30; /* 节拍不可用时 30 帧仍走下面的软件 30 Hz 节拍 | without ticks, 30 fps still uses the software 30 Hz tick below */
}
static int soft_tick_30(void) {
static uint64_t next;const uint64_t period=1000000000ull/30;uint64_t now=dm_android_nvn_clock_ns();
if(next>now+period)next=now; /* 时钟跳变 / 停过(后台) | clock jumped / was paused (background) */
if(now<next){uint64_t d=next-now;struct timespec ts={(time_t)(d/1000000000ull),(long)(d%1000000000ull)};while(nanosleep(&ts,&ts) && errno==EINTR){}}
next=(now>next+period?now:next)+period; /* 落后超过一拍就从现在重新起拍,不连追 | more than one tick behind: restart from now instead of catching up */
return 1;
}
int mtl_link_wait_tick(uint64_t timeout) {
if(!link_on())return soft_tick_30();
static uint64_t started_tick; /* 上一帧开工时的节拍号(只有游戏出图线程调) | tick number when the previous frame started (called only by the game's present thread) */
uint64_t frame=1000000000ull/(uint64_t)(mtl_fps_target()==30?30:60);
pthread_mutex_lock(&link_mu);
uint64_t step=link_vsync_ns?(frame+link_vsync_ns/2)/link_vsync_ns:1;if(!step)step=1;
if(link_tick_n>=started_tick+step){started_tick=link_tick_n;pthread_mutex_unlock(&link_mu);return 1;}
struct timespec ts;clock_gettime(CLOCK_MONOTONIC,&ts);
ts.tv_sec+=timeout/1000000000ull;ts.tv_nsec+=timeout%1000000000ull;if(ts.tv_nsec>=1000000000L){ts.tv_sec++;ts.tv_nsec-=1000000000L;}
while(link_tick_n<started_tick+step)if(pthread_cond_timedwait(&link_cv,&link_mu,&ts)==ETIMEDOUT){pthread_mutex_unlock(&link_mu);return 0;}
started_tick=link_tick_n;pthread_mutex_unlock(&link_mu);return 1;
}
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; }