Android: track disjoint mip layouts and add Vulkan validation tools

This commit is contained in:
shen
2026-10-15 18:53:45 -07:00
parent 8eb294e7e0
commit a6c3655e21
12 changed files with 546 additions and 47 deletions
+87 -37
View File
@@ -2,7 +2,7 @@
* 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.
* Eight fence slots own immutable uploads and transient resources until completion.
*/
#define VK_USE_PLATFORM_ANDROID_KHR
#include <vulkan/vulkan.h>
@@ -11,6 +11,7 @@
#include <android/native_window.h>
#include "nvn_obj.h"
#include "vk_platform.h"
#include "nvn_vk_mip_layout.h"
#include "nvn_mtl.h"
#include "nvn_dirty.h"
#include "../tex/nvn_deswizzle.h"
@@ -67,7 +68,7 @@ typedef struct {
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;
VkImageView view; VkFormat format; NvnVkMipLayouts layouts; 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;
@@ -76,7 +77,7 @@ 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 { uint64_t serial; unsigned roles,sampled_mips; } 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.
@@ -134,7 +135,7 @@ static struct {
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;
int in_pass,active,feedback_layout,null_descriptor,depth_sampled,general_feedback,subresources; 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;
@@ -155,7 +156,7 @@ static struct {
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};
} G={.lock=PTHREAD_MUTEX_INITIALIZER,.completion=PTHREAD_COND_INITIALIZER,.subresources=1};
/* 阻塞等待按来源记账(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"};
@@ -483,6 +484,8 @@ static void backend_init(void) {
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;
const char *subres=getenv("DM_VK_SUBRES");G.subresources=!(subres&&*subres=='0');
fprintf(stderr,"[nvn-vulkan] disjoint_mip_layouts=%d\n",G.subresources);
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();
}
@@ -1028,15 +1031,28 @@ static VkImageAspectFlags aspect(VkFormat f) {
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();
static void texture_mip_barrier(void *ctx,VkImageLayout old,VkImageLayout layout,unsigned base,unsigned count) {
VTexture *t=ctx;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,
.srcAccessMask=old==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=old,.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}};
.subresourceRange={aspect(t->format),base,count,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;
}
static void texture_transition_levels(VTexture *t,unsigned base,unsigned count,VkImageLayout layout) {
if(!nvn_vk_mip_transition(&t->layouts,t->source.d.levels,base,count,layout,texture_mip_barrier,t))
die("texture mip transition bounds",t->serial);
}
static void texture_transition(VTexture *t,VkImageLayout layout) {
texture_transition_levels(t,0,t->source.d.levels,layout);
}
/* Start with the bounded, color-only 2D path used by dodola. Depth/stencil,
* arrays, volume textures and devices with feedback layouts keep the old path. */
static int texture_range_ok(const VTexture *t) {
return G.subresources && !G.feedback_layout && t->source.d.levels>1 &&
t->source.d.levels<=NVN_VK_TRACKED_MIPS && t->source.L.layers==1 &&
t->source.d.target==NVN_TEXTURE_TARGET_2D && aspect(t->format)==VK_IMAGE_ASPECT_COLOR_BIT;
}
/* GPU transfers and CPU streaming can update different compression blocks of
* one NVN allocation. Compare actual block bytes to the last CPU snapshot so
@@ -1070,7 +1086,7 @@ static void refresh_compressed_cpu(VTexture *t,const tex_t *source) {
.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;
all_barrier();texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,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;
@@ -1111,7 +1127,7 @@ static VTexture *texture_get(const tex_t *source,int upload) {
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;
t->width=source->d.width; t->height=one?1:source->d.height;t->depth=volume?source->d.depth:1;t->layouts.uniform=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) {
@@ -1471,9 +1487,16 @@ static void collect_image_uses(VShader *s) {
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};}
TSlot *slot=&G.tslot[tid];uint64_t serial=slot->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=serial};}
G.image_uses[j].roles|=b->kind==6?2u:1u;
if(b->kind==4) {
unsigned mask=0,base=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.base_level:0;
unsigned count=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.nlevels:slot->texture.d.levels;
if(!nvn_vk_mip_mask(slot->texture.d.levels,base,count,&mask))mask=~0u;
G.image_uses[j].sampled_mips|=mask;
if(s->dref_bindings&(1ull<<i))G.image_uses[j].roles|=4u;
}
}
}
static int storage_image_use(uint64_t serial) {
@@ -1484,6 +1507,24 @@ 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;
}
/* Every sampled view in both graphics stages must be disjoint from every
* attachment of this image. Checking only the descriptor currently being bound
* could invalidate another descriptor when the attachment is transitioned. */
static int disjoint_mip_sampling(const VTexture *t) {
if(!texture_range_ok(t))return 0;
const ImageUse *use=NULL;
for(unsigned i=0;i<G.nimage_uses;i++)if(G.image_uses[i].serial==t->serial){use=&G.image_uses[i];break;}
if(!use || use->roles!=1u)return 0; /* storage/comparison views retain whole-image layouts */
unsigned attachments=0;
for(int i=0;i<G.state.rt.n;i++)if(G.state.rt.color[i] && G.state.rt.color[i]->serial==t->serial) {
const view_t *v=G.state.rt.has_cview[i]?&G.state.rt.cview[i]:NULL;
unsigned mask=0,level=v&&v->set_levels?(unsigned)v->base_level:0;
if((v&&v->set_levels&&v->nlevels!=1) || (v&&v->set_layers&&(v->min_layer!=0||v->nlayers!=1)) ||
!nvn_vk_mip_mask(t->source.d.levels,level,1,&mask))return 0;
attachments|=mask;
}
return attachments && !(attachments&use->sampled_mips);
}
static VkImageLayout sampled_layout(VTexture *t,unsigned stage) {
if(storage_image_use(t->serial))return VK_IMAGE_LAYOUT_GENERAL;
if(stage!=5){
@@ -1538,7 +1579,7 @@ static void comparison_image(VTexture *t) {
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);
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,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);
@@ -1565,7 +1606,7 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding)
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);
all_barrier();NvnVkMipLayouts saved=t->layouts;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++){
@@ -1573,7 +1614,7 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding)
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);
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,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);
@@ -1589,7 +1630,10 @@ static void trace_texture(VTexture *t,const VShader *s,const RBinding *binding)
fprintf(stderr,"[nvn-vulkan] CPU_TEXTURE_CAPTURE bytes=%llu path=%s\n",(unsigned long long)cpu_bytes,path);
}
}
texture_transition(t,layout);
if(saved.mixed) {
for(unsigned level=0;level<t->source.d.levels;level++)
if(saved.levels[level]!=VK_IMAGE_LAYOUT_UNDEFINED)texture_transition_levels(t,level,1,saved.levels[level]);
} else if(saved.uniform!=VK_IMAGE_LAYOUT_UNDEFINED)texture_transition(t,saved.uniform);
}
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)
@@ -1714,10 +1758,15 @@ static VkDescriptorSet bind_shader(VShader *s) {
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));
int ranged=b->kind==4 && !alias && s->h.stage!=5 && disjoint_mip_sampling(t);
if(ranged) {
unsigned base=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.base_level:0;
unsigned count=slot->has_view&&slot->view.set_levels?(unsigned)slot->view.nlevels:t->source.d.levels;
texture_transition_levels(t,base,count,VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
} else 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;
ii[i].imageView=alias?t->shadow_view:t->view;ii[i].imageLayout=alias?t->shadow_layout:ranged?VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL:t->layouts.uniform;
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;
@@ -1874,8 +1923,8 @@ static void pending_drop(int i){pending[i]=pending[--npending];}
static void pending_flush_one(int i) {
PendingClear c=pending[i];pending_drop(i);pending_flushed++;
all_barrier();texture_transition(c.t,VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
if(c.range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)vkCmdClearColorImage(G.batch->command,c.t->image,c.t->layout,&c.value.color,1,&c.range);
else vkCmdClearDepthStencilImage(G.batch->command,c.t->image,c.t->layout,&c.value.depthStencil,1,&c.range);
if(c.range.aspectMask&VK_IMAGE_ASPECT_COLOR_BIT)vkCmdClearColorImage(G.batch->command,c.t->image,c.t->layouts.uniform,&c.value.color,1,&c.range);
else vkCmdClearDepthStencilImage(G.batch->command,c.t->image,c.t->layouts.uniform,&c.value.depthStencil,1,&c.range);
}
static void pending_flush(void){while(npending)pending_flush_one(npending-1);}
static void pending_add(VTexture *t,VkImageSubresourceRange range,const VkClearValue *value) {
@@ -1936,10 +1985,11 @@ static VkRenderPass render_begin(void) {
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.general_feedback&&image_sampled(source->serial)&&!disjoint_mip_sampling(t))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;
if(disjoint_mip_sampling(t))texture_transition_levels(t,range.baseMipLevel,range.levelCount,attachment_layout);
else texture_transition(t,attachment_layout);
VkImageLayout layout=attachment_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};
@@ -2153,7 +2203,7 @@ static void draw(const p_draw *a,const p_draw_idx *idx) {
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);
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,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();
@@ -2225,14 +2275,14 @@ static void copy_b2t(const p_copy_b2t *p) {
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;
vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,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++;
vkCmdCopyBufferToImage(G.batch->command,src->v.b,t->image,t->layouts.uniform,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);
@@ -2309,7 +2359,7 @@ static void clear_tex(const p_clear_tex *p) {
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);
vkCmdCopyBufferToImage(G.batch->command,staging->b,t->image,t->layouts.uniform,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) {
@@ -2341,7 +2391,7 @@ static void copy_t2t(const p_copy_t2t *p) {
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);
vkCmdCopyImage(G.batch->command,s->image,s->layouts.uniform,d->image,d->layouts.uniform,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) ||
@@ -2350,7 +2400,7 @@ static void copy_t2t(const p_copy_t2t *p) {
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);
vkCmdBlitImage(G.batch->command,s->image,s->layouts.uniform,d->image,d->layouts.uniform,1,&c,filter);
}
d->cpu_owned=0;d->version++;all_barrier();
}
@@ -2757,7 +2807,7 @@ static void nan_snap(const char *tag) {
for(unsigned lv=0;lv<u->source.d.levels && lv<4 && g_nnan<NAN_SNAPS;lv++){unsigned w=u->width>>lv?u->width>>lv:1,h=u->height>>lv?u->height>>lv:1;
g_nan[g_nnan].buf=buffer_make((uint64_t)w*h*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,lv,0,1},.imageExtent={w,h,1}};
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c);
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layouts.uniform,g_nan[g_nnan].buf.b,1,&c);
g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=lv;g_nan[g_nnan].x=g_nan[g_nnan].y=0;g_nan[g_nnan].w=w;g_nan[g_nnan].h=h;snprintf(g_nan[g_nnan++].tag,40,"%s",tag);}}
}
/* 只拷一张目标 0 级里的一个小框(DM_VK_NANSCAN_BOX=x,y,w,h:追踪帧里每次绘制前拍当前 0 号颜色目标,用来二分出第一次写出 NaN 的绘制)
@@ -2768,7 +2818,7 @@ static void nan_snap_box(VTexture *u,const unsigned box[4],const char *tag) {
pass_end();texture_transition(u,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
g_nan[g_nnan].buf=buffer_make((uint64_t)box[2]*box[3]*nan_bpp(u->format),VK_BUFFER_USAGE_TRANSFER_DST_BIT);
VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageOffset={(int)box[0],(int)box[1],0},.imageExtent={box[2],box[3],1}};
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layout,g_nan[g_nnan].buf.b,1,&c);
vkCmdCopyImageToBuffer(G.batch->command,u->image,u->layouts.uniform,g_nan[g_nnan].buf.b,1,&c);
g_nan[g_nnan].t=u;g_nan[g_nnan].serial=u->serial;g_nan[g_nnan].lv=0;g_nan[g_nnan].x=box[0];g_nan[g_nnan].y=box[1];g_nan[g_nnan].w=box[2];g_nan[g_nnan].h=box[3];snprintf(g_nan[g_nnan++].tag,40,"%s",tag);
}
static void nan_report(void) {
@@ -2805,7 +2855,7 @@ uint64_t mtl_present(const tex_t *source,double period,const int crop[4]) {
int capture_frame=shot || burst || (capture_root && (G.trace_frame || G.present_count<4 || (G.present_count%120==0 && G.present_count<1000)));
if(capture_frame && t->bpp==4){capture=buffer_make((uint64_t)t->width*t->height*4,VK_BUFFER_USAGE_TRANSFER_DST_BIT);
texture_transition(t,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);VkBufferImageCopy c={.imageSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1},.imageExtent={t->width,t->height,1}};
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layout,capture.b,1,&c);}
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,capture.b,1,&c);}
else if(capture_frame)fprintf(stderr,"[nvn-vulkan] readback skipped: present texture bpp=%u format=%u\n",t->bpp,t->format);
if(G.trace_frame && capture.b)nan_snap("present");
G.batch->ticket=++G.fence;VkFence fence=G.batch->fence;
@@ -2925,7 +2975,7 @@ void mtl_read_texels(const tex_t *source,unsigned level,unsigned layer,const NVN
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);
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,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
@@ -2941,7 +2991,7 @@ void dm_vk_copy_test_read(const tex_t *source,unsigned level,unsigned layer,uint
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);
vkCmdCopyImageToBuffer(G.batch->command,t->image,t->layouts.uniform,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
+50
View File
@@ -0,0 +1,50 @@
/* Per-mip layout tracking, inspired by dodola/d2r-mobile's Vulkan backend
* (642480b). Keep the current backend's conservative synchronization masks.
* No game addresses, platform services or shader metadata are shared. */
#ifndef NVN_VK_MIP_LAYOUT_H
#define NVN_VK_MIP_LAYOUT_H
#include <vulkan/vulkan_core.h>
#define NVN_VK_TRACKED_MIPS 16
typedef struct {
/* uniform is only usable as an image-wide layout when mixed == 0. */
VkImageLayout uniform, levels[NVN_VK_TRACKED_MIPS];
unsigned mixed;
} NvnVkMipLayouts;
typedef void (*NvnVkMipBarrier)(void *, VkImageLayout, VkImageLayout, unsigned, unsigned);
static inline int nvn_vk_mip_mask(unsigned total, unsigned base, unsigned count, unsigned *mask) {
if (!total || total > NVN_VK_TRACKED_MIPS || base >= total || !count || count > total - base) return 0;
*mask = ((1u << count) - 1u) << base;
return 1;
}
/* Validate before changing state or emitting barriers. Whole-image transitions
* remain supported for images outside the bounded per-mip tracking path. */
static inline int nvn_vk_mip_transition(NvnVkMipLayouts *s, unsigned total,
unsigned base, unsigned count, VkImageLayout next, NvnVkMipBarrier emit, void *ctx) {
if (!total || base >= total || !count || count > total - base ||
(total > NVN_VK_TRACKED_MIPS && (base || count != total || s->mixed))) return 0;
if (!s->mixed) {
if (s->uniform == next) return 1;
if (!base && count == total) {
emit(ctx, s->uniform, next, 0, total); s->uniform = next; return 1;
}
for (unsigned i = 0; i < total; i++) s->levels[i] = s->uniform;
s->mixed = 1;
}
for (unsigned i = base; i < base + count;) {
VkImageLayout old = s->levels[i];
if (old == next) { i++; continue; }
unsigned end = i + 1;
while (end < base + count && s->levels[end] == old) end++;
emit(ctx, old, next, i, end - i);
for (unsigned k = i; k < end; k++) s->levels[k] = next;
i = end;
}
unsigned i = 1;
while (i < total && s->levels[i] == s->levels[0]) i++;
if (i == total) { s->uniform = s->levels[0]; s->mixed = 0; }
return 1;
}
#endif