The SDL_GPU pipeline renders into its own view-sized colour target and already composites it over the whole render target, so routing it through gpu_scene_texture cost one extra same-size copy per frame. The scaled intermediate is now used only by the SDL geometry fallback; the hardware composite upscales with linear filtering. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
331 lines
25 KiB
C++
331 lines
25 KiB
C++
#include "HardwareScene.h"
|
|
#include "shaders/SceneSpirv.h"
|
|
#include <cmath>
|
|
#include <cstddef>
|
|
#include <cstring>
|
|
#include <algorithm>
|
|
#include <unordered_set>
|
|
namespace ava2 {
|
|
namespace {
|
|
constexpr const char* metal = R"(
|
|
#include <metal_stdlib>
|
|
using namespace metal;
|
|
struct Input { float4 position [[attribute(0)]]; float4 color [[attribute(1)]]; float2 uv [[attribute(2)]]; float4 normal [[attribute(3)]]; uint4 bones [[attribute(4)]]; float4 weights [[attribute(5)]]; };
|
|
struct Transform { float4 world[4]; float4 mvp[4]; float4 diffuse,ambient,emissive,lightDirection,lightAmbient,lightDiffuse,fogColor,fogParams,modes,skin; };
|
|
struct Output { float4 position [[position]]; float4 color; float2 uv; };
|
|
float4 rows(float4 p,float4 a,float4 b,float4 c,float4 d){return p.x*a+p.y*b+p.z*c+p.w*d;}
|
|
vertex Output scene_vertex(Input in [[stage_in]], uint instance [[instance_id]], constant Transform& header [[buffer(0)]], constant float4* palette [[buffer(1)]], device const Transform* instances [[buffer(2)]]) {
|
|
Transform t=header;if(header.modes.x>1.5)t=instances[instance]; // ?: across address spaces is ambiguous in MSL
|
|
float4 p=in.position; float3 n=in.normal.xyz;
|
|
if(t.skin.x>0.5){float4 sp=0;float3 sn=0;float total=0;
|
|
for(uint i=0;i<4;++i)if(in.weights[i]>0 && in.bones[i]<uint(t.skin.x)){
|
|
uint b=in.bones[i]*4;float w=in.weights[i];
|
|
sp+=rows(p,palette[b],palette[b+1],palette[b+2],palette[b+3])*w;
|
|
sn+=rows(float4(n,0),palette[b],palette[b+1],palette[b+2],palette[b+3]).xyz*w;total+=w;
|
|
}if(total>0.0001){p=float4(sp.xyz,1);n=sn;}
|
|
}
|
|
float4 clip=p,c=in.color;
|
|
if(t.modes.x>0.5){
|
|
clip=rows(p,t.mvp[0],t.mvp[1],t.mvp[2],t.mvp[3]);c*=t.diffuse;
|
|
if(t.modes.y>0.5 && in.normal.w>0.5){float3 wn=rows(float4(n,0),t.world[0],t.world[1],t.world[2],t.world[3]).xyz;
|
|
float len=length(wn);if(len>0.00001)wn/=len;
|
|
float ndotl=max(0.f,dot(wn,t.lightDirection.xyz));c.rgb=clamp(t.emissive.rgb+t.ambient.rgb*t.lightAmbient.rgb+c.rgb*t.lightDiffuse.rgb*ndotl,0.f,1.f);
|
|
}
|
|
if(t.modes.z>0.5 && clip.w>0){float f=t.modes.z>1.5 ? exp(-clamp(clip.w*t.fogParams.x,0.f,10.f)) : clamp((t.fogParams.z-clip.w)/(t.fogParams.z-t.fogParams.y),0.f,1.f);c.rgb=mix(t.fogColor.rgb,c.rgb,f);}
|
|
if(t.modes.w>0.5)clip.z=0;
|
|
}
|
|
Output out;out.position=clip;out.color=c;out.uv=in.uv;return out;
|
|
}
|
|
fragment float4 scene_fragment(Output in [[stage_in]], texture2d<float> image [[texture(0)]], sampler sampling [[sampler(0)]], constant float4& params [[buffer(0)]]) {
|
|
float4 c=image.sample(sampling,in.uv)*in.color;
|
|
if(params.x>=0.0 && c.a<=params.x) discard_fragment();
|
|
if(params.y>0.5) c.a=1.0;
|
|
return c;
|
|
}
|
|
)";
|
|
|
|
}
|
|
HardwareScene::~HardwareScene() {
|
|
for (auto& [key,mesh]:resident_) {SDL_ReleaseGPUBuffer(device_,mesh.vertices);SDL_ReleaseGPUBuffer(device_,mesh.indices);}
|
|
if(instances_)SDL_ReleaseGPUBuffer(device_,instances_);
|
|
if(instanceTransfer_)SDL_ReleaseGPUTransferBuffer(device_,instanceTransfer_);
|
|
if(output_) SDL_DestroyTexture(output_);
|
|
for(auto& [key,t]:textures_) SDL_ReleaseGPUTexture(device_,t.texture);
|
|
for(auto& [key,p]:pipelines_) SDL_ReleaseGPUGraphicsPipeline(device_,p);
|
|
if(color_) SDL_ReleaseGPUTexture(device_,color_);
|
|
if(depth_) SDL_ReleaseGPUTexture(device_,depth_);
|
|
if(vertex_) SDL_ReleaseGPUShader(device_,vertex_);
|
|
if(fragment_) SDL_ReleaseGPUShader(device_,fragment_);
|
|
if(sampler_) SDL_ReleaseGPUSampler(device_,sampler_);
|
|
if(vertices_) SDL_ReleaseGPUBuffer(device_,vertices_);
|
|
if(indices_) SDL_ReleaseGPUBuffer(device_,indices_);
|
|
if(transfer_) SDL_ReleaseGPUTransferBuffer(device_,transfer_);
|
|
}
|
|
SDL_GPUTexture* HardwareScene::FindTexture(const std::string& key) {
|
|
auto it=textures_.find(key);if(it==textures_.end())return nullptr;
|
|
it->second.lastUsed=frame_+1;return it->second.texture;
|
|
}
|
|
SDL_GPUTexture* HardwareScene::Texture(const std::string& key,int width,int height,const void* rgba) {
|
|
if(auto* found=FindTexture(key))return found;
|
|
// Own uploads on the same queue as the 3D pass (SDL_Renderer's pending texture uploads are
|
|
// submitted at Present, after our custom command buffer); copied at the start of Render.
|
|
SDL_GPUTextureCreateInfo ti{};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
|
|
// Full mip chain: minified terrain/props otherwise shimmer and read the whole level-0 texel footprint.
|
|
// SDL_GenerateMipmapsForGPUTexture needs COLOR_TARGET usage.
|
|
Uint32 levels=1;for(int extent=std::max(width,height);extent>1;extent>>=1)++levels;
|
|
ti.usage=SDL_GPU_TEXTUREUSAGE_SAMPLER|(levels>1 ? SDL_GPU_TEXTUREUSAGE_COLOR_TARGET : 0);ti.width=width;ti.height=height;ti.layer_count_or_depth=1;ti.num_levels=levels;
|
|
auto* texture=SDL_CreateGPUTexture(device_,&ti);if(!texture)return nullptr;
|
|
const uint32_t size=uint32_t(width)*height*4;uint32_t offset=0;
|
|
std::memcpy(Stage(size,offset),rgba,size);
|
|
pending_.push_back({texture,nullptr,offset,size,uint32_t(width),uint32_t(height),levels>1});
|
|
const size_t imageBytes=size_t(width)*height*4*(levels>1 ? 4 : 3)/3; // mip chain adds ~1/3
|
|
textures_.emplace(key,TextureEntry{texture,imageBytes,frame_+1});textureBytes_+=imageBytes;++textureUploads_;return texture;
|
|
}
|
|
bool HardwareScene::Initialize(SDL_Renderer* renderer,int width,int height) {
|
|
if(!vertex_) {
|
|
bool msl=(SDL_GetGPUShaderFormats(device_) & SDL_GPU_SHADERFORMAT_MSL)!=0;
|
|
SDL_GPUShaderCreateInfo info{};
|
|
info.format=msl ? SDL_GPU_SHADERFORMAT_MSL : SDL_GPU_SHADERFORMAT_SPIRV;
|
|
info.stage=SDL_GPU_SHADERSTAGE_VERTEX; info.num_uniform_buffers=2;info.num_storage_buffers=1;
|
|
info.code=msl ? reinterpret_cast<const Uint8*>(metal) : scene_vert_spv;
|
|
info.code_size=msl ? std::strlen(metal) : sizeof(scene_vert_spv);
|
|
info.entrypoint=msl ? "scene_vertex" : "main";
|
|
vertex_=SDL_CreateGPUShader(device_,&info);
|
|
info.stage=SDL_GPU_SHADERSTAGE_FRAGMENT; info.num_samplers=1;info.num_uniform_buffers=1;info.num_storage_buffers=0;
|
|
info.code=msl ? reinterpret_cast<const Uint8*>(metal) : scene_frag_spv;
|
|
info.code_size=msl ? std::strlen(metal) : sizeof(scene_frag_spv);
|
|
info.entrypoint=msl ? "scene_fragment" : "main";
|
|
fragment_=SDL_CreateGPUShader(device_,&info);
|
|
SDL_GPUSamplerCreateInfo si{};
|
|
si.min_filter=si.mag_filter=SDL_GPU_FILTER_LINEAR;
|
|
si.mipmap_mode=SDL_GPU_SAMPLERMIPMAPMODE_LINEAR;
|
|
si.max_lod=1000.f; // zero-initialized max_lod would clamp sampling to level 0
|
|
si.address_mode_u=si.address_mode_v=si.address_mode_w=SDL_GPU_SAMPLERADDRESSMODE_REPEAT;
|
|
sampler_=SDL_CreateGPUSampler(device_,&si);
|
|
const Uint32 white=0xffffffff;
|
|
white_=Texture("__ava2_white",1,1,&white);
|
|
}
|
|
if(!vertex_ || !fragment_ || !sampler_ || !white_) return false;
|
|
if(width_!=width || height_!=height) {
|
|
if(output_) SDL_DestroyTexture(output_);
|
|
if(color_) SDL_ReleaseGPUTexture(device_,color_);
|
|
if(depth_) SDL_ReleaseGPUTexture(device_,depth_);
|
|
output_=nullptr;color_=depth_=nullptr;
|
|
SDL_GPUTextureCreateInfo ti{};ti.type=SDL_GPU_TEXTURETYPE_2D;ti.width=width;ti.height=height;ti.layer_count_or_depth=1;ti.num_levels=1;
|
|
ti.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;ti.usage=SDL_GPU_TEXTUREUSAGE_COLOR_TARGET|SDL_GPU_TEXTUREUSAGE_SAMPLER;
|
|
color_=SDL_CreateGPUTexture(device_,&ti);
|
|
ti.format=SDL_GPU_TEXTUREFORMAT_D32_FLOAT;ti.usage=SDL_GPU_TEXTUREUSAGE_DEPTH_STENCIL_TARGET;
|
|
depth_=SDL_CreateGPUTexture(device_,&ti);
|
|
if(!color_ || !depth_) return false;
|
|
auto props=SDL_CreateProperties();
|
|
SDL_SetPointerProperty(props,SDL_PROP_TEXTURE_CREATE_GPU_TEXTURE_POINTER,color_);
|
|
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_FORMAT_NUMBER,SDL_PIXELFORMAT_ABGR8888);
|
|
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_WIDTH_NUMBER,width);
|
|
SDL_SetNumberProperty(props,SDL_PROP_TEXTURE_CREATE_HEIGHT_NUMBER,height);
|
|
output_=SDL_CreateTextureWithProperties(renderer,props);SDL_DestroyProperties(props);
|
|
if(!output_)return false;
|
|
// The target accumulates premultiplied colors. Transparent pixels keep
|
|
// the Python selection background and other existing 2D layers intact.
|
|
SDL_SetTextureBlendMode(output_,SDL_BLENDMODE_BLEND_PREMULTIPLIED);
|
|
SDL_SetTextureScaleMode(output_,SDL_SCALEMODE_LINEAR); // render-scale < 1 upscales in the composite
|
|
width_=width;height_=height;
|
|
}
|
|
return true;
|
|
}
|
|
SDL_GPUGraphicsPipeline* HardwareScene::Pipeline(const HardwareBatch& b) {
|
|
unsigned key=b.cull|(b.depth<<3)|(b.depthWrite<<4)|(b.blend<<5)|(b.additive<<6);
|
|
auto it=pipelines_.find(key);if(it!=pipelines_.end())return it->second;
|
|
SDL_GPUGraphicsPipelineCreateInfo info{};
|
|
info.vertex_shader=vertex_;info.fragment_shader=fragment_;info.primitive_type=SDL_GPU_PRIMITIVETYPE_TRIANGLELIST;
|
|
SDL_GPUVertexBufferDescription buffer{};buffer.slot=0;buffer.pitch=sizeof(HardwareVertex);buffer.input_rate=SDL_GPU_VERTEXINPUTRATE_VERTEX;
|
|
SDL_GPUVertexAttribute attributes[6]{};
|
|
attributes[0]={0,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT4,0};
|
|
attributes[1]={1,0,SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4_NORM,offsetof(HardwareVertex,color)};
|
|
attributes[2]={2,0,SDL_GPU_VERTEXELEMENTFORMAT_FLOAT2,offsetof(HardwareVertex,uv)};
|
|
attributes[3]={3,0,SDL_GPU_VERTEXELEMENTFORMAT_SHORT4_NORM,offsetof(HardwareVertex,normal)};
|
|
attributes[4]={4,0,SDL_GPU_VERTEXELEMENTFORMAT_UBYTE4,offsetof(HardwareVertex,bones)};
|
|
attributes[5]={5,0,SDL_GPU_VERTEXELEMENTFORMAT_USHORT4_NORM,offsetof(HardwareVertex,weights)};
|
|
info.vertex_input_state={&buffer,1,attributes,6};
|
|
info.rasterizer_state.fill_mode=SDL_GPU_FILLMODE_FILL;
|
|
info.rasterizer_state.front_face=SDL_GPU_FRONTFACE_COUNTER_CLOCKWISE;
|
|
info.rasterizer_state.cull_mode=b.cull==1 ? SDL_GPU_CULLMODE_NONE : b.cull==2 ? SDL_GPU_CULLMODE_BACK : SDL_GPU_CULLMODE_FRONT;
|
|
info.depth_stencil_state.compare_op=SDL_GPU_COMPAREOP_LESS_OR_EQUAL;
|
|
info.depth_stencil_state.enable_depth_test=b.depth;
|
|
info.depth_stencil_state.enable_depth_write=b.depthWrite;
|
|
SDL_GPUColorTargetDescription target{};target.format=SDL_GPU_TEXTUREFORMAT_R8G8B8A8_UNORM;
|
|
auto& blend=target.blend_state;blend.enable_blend=b.blend||b.additive;
|
|
blend.src_color_blendfactor=SDL_GPU_BLENDFACTOR_SRC_ALPHA;
|
|
blend.dst_color_blendfactor=b.additive ? SDL_GPU_BLENDFACTOR_ONE : SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
|
blend.color_blend_op=blend.alpha_blend_op=SDL_GPU_BLENDOP_ADD;
|
|
blend.src_alpha_blendfactor=SDL_GPU_BLENDFACTOR_ONE;blend.dst_alpha_blendfactor=SDL_GPU_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
|
|
info.target_info.color_target_descriptions=⌖info.target_info.num_color_targets=1;
|
|
info.target_info.has_depth_stencil_target=true;info.target_info.depth_stencil_format=SDL_GPU_TEXTUREFORMAT_D32_FLOAT;
|
|
auto* p=SDL_CreateGPUGraphicsPipeline(device_,&info);if(p)pipelines_.emplace(key,p);return p;
|
|
}
|
|
HardwareVertex MakeHardwareVertex(const Render3DDraw& mesh,size_t i) {
|
|
HardwareVertex v{};
|
|
v.position[0]=mesh.positions[i*3];v.position[1]=mesh.positions[i*3+1];v.position[2]=mesh.positions[i*3+2];v.position[3]=1;
|
|
uint32_t color=i<mesh.diffuse.size() ? mesh.diffuse[i] : 0xffffffff;
|
|
v.color[0]=uint8_t(color>>16);v.color[1]=uint8_t(color>>8);v.color[2]=uint8_t(color);v.color[3]=uint8_t(color>>24);
|
|
if(i*2+1<mesh.uv0.size()){v.uv[0]=mesh.uv0[i*2];v.uv[1]=mesh.uv0[i*2+1];}
|
|
if(i*3+2<mesh.normals.size()){
|
|
// The shader renormalises after the (linear) skin/world transform, so storing the unit
|
|
// direction keeps lighting identical while fitting SNORM.
|
|
const float* n=&mesh.normals[i*3];const float len=std::sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]);
|
|
if(len>1e-12f)for(int k=0;k<3;++k)v.normal[k]=int16_t(std::lround(std::clamp(n[k]/len,-1.f,1.f)*32767.f));
|
|
v.normal[3]=32767;
|
|
}
|
|
if(i*4+3<mesh.bone_indices.size() && i*4+3<mesh.bone_weights.size())for(int k=0;k<4;++k){
|
|
v.bones[k]=mesh.bone_indices[i*4+k];v.weights[k]=uint16_t(std::lround(std::clamp(mesh.bone_weights[i*4+k],0.f,1.f)*65535.f));}
|
|
return v;
|
|
}
|
|
uint8_t* HardwareScene::Stage(uint32_t size,uint32_t& offset) {
|
|
offset=uint32_t((pendingBytes_.size()+15)&~size_t(15)); // texel/placement-friendly offsets
|
|
pendingBytes_.resize(offset+size);return pendingBytes_.data()+offset;
|
|
}
|
|
void HardwareScene::DropPending(const void* resource) {
|
|
pending_.erase(std::remove_if(pending_.begin(),pending_.end(),[&](const PendingUpload& upload){
|
|
return upload.texture==resource || upload.buffer==resource;}),pending_.end());
|
|
}
|
|
bool HardwareScene::FlushUploads(SDL_GPUCommandBuffer* command) {
|
|
if(pending_.empty())return true;
|
|
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=uint32_t(pendingBytes_.size());
|
|
auto* transfer=SDL_CreateGPUTransferBuffer(device_,&ti);
|
|
auto* bytes=transfer ? SDL_MapGPUTransferBuffer(device_,transfer,false) : nullptr;
|
|
if(!bytes){if(transfer)SDL_ReleaseGPUTransferBuffer(device_,transfer);return false;}
|
|
std::memcpy(bytes,pendingBytes_.data(),pendingBytes_.size());SDL_UnmapGPUTransferBuffer(device_,transfer);
|
|
auto* copy=SDL_BeginGPUCopyPass(command);if(!copy){SDL_ReleaseGPUTransferBuffer(device_,transfer);return false;}
|
|
for(const auto& upload:pending_) {
|
|
if(upload.texture) {
|
|
SDL_GPUTextureTransferInfo source{};source.transfer_buffer=transfer;source.offset=upload.offset;source.pixels_per_row=upload.width;source.rows_per_layer=upload.height;
|
|
SDL_GPUTextureRegion dest{};dest.texture=upload.texture;dest.w=upload.width;dest.h=upload.height;dest.d=1;
|
|
SDL_UploadToGPUTexture(copy,&source,&dest,false);
|
|
} else {
|
|
SDL_GPUTransferBufferLocation from{transfer,upload.offset};SDL_GPUBufferRegion to{upload.buffer,0,upload.size};
|
|
SDL_UploadToGPUBuffer(copy,&from,&to,false);
|
|
}
|
|
}
|
|
SDL_EndGPUCopyPass(copy);
|
|
for(const auto& upload:pending_)if(upload.texture && upload.mipmaps)SDL_GenerateMipmapsForGPUTexture(command,upload.texture);
|
|
SDL_ReleaseGPUTransferBuffer(device_,transfer); // released once the command buffer completes
|
|
pending_.clear();pendingBytes_.clear();
|
|
if(pendingBytes_.capacity()>64u*1024u*1024u)pendingBytes_.shrink_to_fit(); // drop a map-load burst
|
|
return true;
|
|
}
|
|
HardwareScene::ResidentMesh* HardwareScene::Resident(const std::shared_ptr<const Render3DDraw>& geometry) {
|
|
auto it=resident_.find(geometry.get());
|
|
if(it!=resident_.end()){it->second.lastUsed=frame_;return &it->second;}
|
|
const auto& mesh=*geometry;
|
|
const size_t count=mesh.positions.size()/3;
|
|
if(!count || mesh.indices.empty())return nullptr;
|
|
for(auto index:mesh.indices)if(index>=count)return nullptr;
|
|
const uint32_t vb=count*sizeof(HardwareVertex),ib=mesh.indices.size()*sizeof(uint32_t);
|
|
SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_VERTEX;bi.size=vb;
|
|
ResidentMesh r;r.source=geometry;r.vertices=SDL_CreateGPUBuffer(device_,&bi);
|
|
bi.usage=SDL_GPU_BUFFERUSAGE_INDEX;bi.size=ib;r.indices=SDL_CreateGPUBuffer(device_,&bi);
|
|
if(!r.vertices || !r.indices){if(r.vertices)SDL_ReleaseGPUBuffer(device_,r.vertices);if(r.indices)SDL_ReleaseGPUBuffer(device_,r.indices);return nullptr;}
|
|
uint32_t offset=0;auto* packed=Stage(vb,offset);
|
|
for(size_t i=0;i<count;++i){const auto vertex=MakeHardwareVertex(mesh,i);std::memcpy(packed+i*sizeof(vertex),&vertex,sizeof(vertex));}
|
|
pending_.push_back({nullptr,r.vertices,offset,vb});
|
|
std::memcpy(Stage(ib,offset),mesh.indices.data(),ib);
|
|
pending_.push_back({nullptr,r.indices,offset,ib});
|
|
r.count=mesh.indices.size();r.bytes=vb+ib;r.lastUsed=frame_;residentBytes_+=r.bytes;++residentUploads_;
|
|
return &resident_.emplace(geometry.get(),std::move(r)).first->second;
|
|
}
|
|
bool HardwareScene::Render(SDL_Renderer* renderer,int width,int height,const std::vector<HardwareVertex>& vertices,const std::vector<uint32_t>& indices,const std::vector<HardwareBatch>& batches) {
|
|
if(batches.empty())return true;
|
|
const auto tick=SDL_GetPerformanceCounter();++frame_;lastDrawCalls_=0;
|
|
if(!Initialize(renderer,width,height))return false;
|
|
if(textureBytes_>textureBudget_) {
|
|
std::unordered_set<SDL_GPUTexture*> activeTextures{white_};
|
|
for(const auto& b:batches)if(b.texture)activeTextures.insert(b.texture);
|
|
for(auto& [key,entry]:textures_)if(activeTextures.count(entry.texture))entry.lastUsed=frame_;
|
|
// Oldest inactive images first; the active working set is protected, even above the soft budget.
|
|
std::vector<decltype(textures_)::iterator> candidates;
|
|
for(auto it=textures_.begin();it!=textures_.end();++it)
|
|
if(it->second.lastUsed<frame_ && it->second.texture!=white_)candidates.push_back(it);
|
|
std::sort(candidates.begin(),candidates.end(),[](const auto& a,const auto& b){return a->second.lastUsed<b->second.lastUsed;});
|
|
for(auto oldest:candidates) {
|
|
if(textureBytes_<=textureBudget_)break;
|
|
textureBytes_-=oldest->second.bytes;DropPending(oldest->second.texture);SDL_ReleaseGPUTexture(device_,oldest->second.texture);textures_.erase(oldest);
|
|
}
|
|
}
|
|
// Cached buffers can be released without waiting; SDL defers GPU destruction.
|
|
for(auto it=resident_.begin();it!=resident_.end();) {
|
|
if(residentBytes_>256u*1024u*1024u && it->second.lastUsed+2<frame_){
|
|
residentBytes_-=it->second.bytes;DropPending(it->second.vertices);DropPending(it->second.indices);SDL_ReleaseGPUBuffer(device_,it->second.vertices);SDL_ReleaseGPUBuffer(device_,it->second.indices);it=resident_.erase(it);
|
|
}else ++it;
|
|
}
|
|
std::vector<ResidentMesh*> meshes;meshes.reserve(batches.size());
|
|
for(const auto& b:batches){if(!Pipeline(b))return false;auto* mesh=b.geometry ? Resident(b.geometry) : nullptr;if(b.geometry&&!mesh)return false;meshes.push_back(mesh);}
|
|
uint32_t vb=vertices.size()*sizeof(HardwareVertex),ib=indices.size()*sizeof(uint32_t);
|
|
lastDynamicBytes_=vb+ib;
|
|
if(vb>vertexBytes_||ib>indexBytes_) {
|
|
if(vertices_)SDL_ReleaseGPUBuffer(device_,vertices_);if(indices_)SDL_ReleaseGPUBuffer(device_,indices_);if(transfer_)SDL_ReleaseGPUTransferBuffer(device_,transfer_);
|
|
vertexBytes_=std::max(vb,vertexBytes_)*2;indexBytes_=std::max(ib,indexBytes_)*2;
|
|
SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_VERTEX;bi.size=vertexBytes_;vertices_=SDL_CreateGPUBuffer(device_,&bi);
|
|
bi.usage=SDL_GPU_BUFFERUSAGE_INDEX;bi.size=indexBytes_;indices_=SDL_CreateGPUBuffer(device_,&bi);
|
|
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=vertexBytes_+indexBytes_;transfer_=SDL_CreateGPUTransferBuffer(device_,&ti);
|
|
}
|
|
if(vb || ib){
|
|
if(!vertices_||!indices_||!transfer_)return false;
|
|
auto* data=static_cast<Uint8*>(SDL_MapGPUTransferBuffer(device_,transfer_,true));if(!data)return false;
|
|
std::memcpy(data,vertices.data(),vb);std::memcpy(data+vb,indices.data(),ib);SDL_UnmapGPUTransferBuffer(device_,transfer_);
|
|
}
|
|
const uint32_t instanceSize=std::max<size_t>(1,batches.size())*sizeof(HardwareTransform);
|
|
if(instanceSize>instanceBytes_){
|
|
if(instances_)SDL_ReleaseGPUBuffer(device_,instances_);if(instanceTransfer_)SDL_ReleaseGPUTransferBuffer(device_,instanceTransfer_);
|
|
instanceBytes_=instanceSize*2;SDL_GPUBufferCreateInfo bi{};bi.usage=SDL_GPU_BUFFERUSAGE_GRAPHICS_STORAGE_READ;bi.size=instanceBytes_;instances_=SDL_CreateGPUBuffer(device_,&bi);
|
|
SDL_GPUTransferBufferCreateInfo ti{};ti.usage=SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD;ti.size=instanceBytes_;instanceTransfer_=SDL_CreateGPUTransferBuffer(device_,&ti);
|
|
}
|
|
if(!instances_||!instanceTransfer_)return false;
|
|
auto* instData=static_cast<HardwareTransform*>(SDL_MapGPUTransferBuffer(device_,instanceTransfer_,true));if(!instData)return false;
|
|
for(size_t i=0;i<batches.size();++i)instData[i]=batches[i].transform;
|
|
SDL_UnmapGPUTransferBuffer(device_,instanceTransfer_);
|
|
if(!SDL_FlushRenderer(renderer))return false;
|
|
auto* cmd=SDL_AcquireGPUCommandBuffer(device_);if(!cmd)return false;
|
|
if(!FlushUploads(cmd)){SDL_CancelGPUCommandBuffer(cmd);return false;}
|
|
// Resource uploads are recorded now; on failure submit rather than cancel so they still land.
|
|
auto* copy=SDL_BeginGPUCopyPass(cmd);if(!copy){SDL_SubmitGPUCommandBuffer(cmd);return false;}
|
|
SDL_GPUTransferBufferLocation source{};SDL_GPUBufferRegion dest{};
|
|
if(vb||ib){source={transfer_,0};dest={vertices_,0,vb};SDL_UploadToGPUBuffer(copy,&source,&dest,true);source.offset=vb;dest={indices_,0,ib};SDL_UploadToGPUBuffer(copy,&source,&dest,true);}
|
|
source={instanceTransfer_,0};dest={instances_,0,instanceSize};SDL_UploadToGPUBuffer(copy,&source,&dest,true);SDL_EndGPUCopyPass(copy);
|
|
SDL_GPUColorTargetInfo color{};color.texture=color_;color.clear_color={0,0,0,0};color.load_op=SDL_GPU_LOADOP_CLEAR;color.store_op=SDL_GPU_STOREOP_STORE;
|
|
SDL_GPUDepthStencilTargetInfo depth{};depth.texture=depth_;depth.clear_depth=1;depth.load_op=SDL_GPU_LOADOP_CLEAR;depth.store_op=SDL_GPU_STOREOP_DONT_CARE;depth.stencil_load_op=SDL_GPU_LOADOP_DONT_CARE;depth.stencil_store_op=SDL_GPU_STOREOP_DONT_CARE;
|
|
auto* pass=SDL_BeginGPURenderPass(cmd,&color,1,&depth);if(!pass){SDL_SubmitGPUCommandBuffer(cmd);return false;}
|
|
SDL_BindGPUVertexStorageBuffers(pass,0,&instances_,1);
|
|
float palette[128*16]{};SDL_PushGPUVertexUniformData(cmd,1,palette,sizeof(palette));
|
|
// Every draw reads its transform from the instance storage buffer (firstInstance = batch index),
|
|
// so the uniform header is pushed once per frame instead of 288 bytes per draw.
|
|
HardwareTransform header{};header.modes[0]=2;SDL_PushGPUVertexUniformData(cmd,0,&header,sizeof(header));
|
|
float pushedParams[4]={-2,-1,0,0}; // never a real alphaRef/opaque pair
|
|
const std::vector<float>* pushedPalette=nullptr; // draws of one instance share a palette; push once
|
|
for(size_t i=0;i<batches.size();) {
|
|
const auto& batch=batches[i];auto* mesh=meshes[i];
|
|
size_t count=1;
|
|
// Instance only compatible opaque resident meshes; preserve all translucent ordering.
|
|
if(mesh && !batch.blend && !batch.additive && batch.depthWrite && batch.transform.skin[0]==0 && batch.transform.modes[0]>0.5f)
|
|
while(i+count<batches.size()) {
|
|
const auto& next=batches[i+count];
|
|
if(meshes[i+count]!=mesh || next.firstIndex!=batch.firstIndex || next.indexCount!=batch.indexCount || next.texture!=batch.texture || next.cull!=batch.cull || next.depth!=batch.depth || next.depthWrite!=batch.depthWrite || next.blend || next.additive || next.alphaRef!=batch.alphaRef || next.transform.skin[0]!=0 || next.transform.modes[0]<.5f)break;
|
|
++count;
|
|
}
|
|
SDL_GPUBufferBinding binding{mesh ? mesh->vertices : vertices_,0};SDL_BindGPUVertexBuffers(pass,0,&binding,1);
|
|
binding.buffer=mesh ? mesh->indices : indices_;SDL_BindGPUIndexBuffer(pass,&binding,SDL_GPU_INDEXELEMENTSIZE_32BIT);
|
|
SDL_BindGPUGraphicsPipeline(pass,Pipeline(batch));
|
|
SDL_GPUTextureSamplerBinding texture{batch.texture ? batch.texture : white_,sampler_};SDL_BindGPUFragmentSamplers(pass,0,&texture,1);
|
|
float params[4]={batch.alphaRef,(!batch.blend&&!batch.additive)?1.f:0.f,0,0};
|
|
if(std::memcmp(params,pushedParams,sizeof(params))!=0){std::memcpy(pushedParams,params,sizeof(params));SDL_PushGPUFragmentUniformData(cmd,0,params,sizeof(params));}
|
|
const auto& transform=batch.transform;
|
|
if(transform.skin[0]>0 && batch.palette && batch.palette.get()!=pushedPalette){pushedPalette=batch.palette.get();std::fill(std::begin(palette),std::end(palette),0);std::copy_n(batch.palette->data(),std::min(batch.palette->size(),size_t(128*16)),palette);SDL_PushGPUVertexUniformData(cmd,1,palette,sizeof(palette));}
|
|
SDL_DrawGPUIndexedPrimitives(pass,batch.indexCount,count,batch.firstIndex,0,i);++lastDrawCalls_;i+=count;
|
|
}
|
|
SDL_EndGPURenderPass(pass);const auto beforeSubmit=SDL_GetPerformanceCounter();
|
|
if(!SDL_SubmitGPUCommandBuffer(cmd))return false;
|
|
static unsigned count=0;if(++count%120==0)SDL_Log("Resident GPU batches=%zu calls=%zu dynamic=%zu resident=%zu uploads=%zu encode=%.2f submit=%.2f ms",batches.size(),lastDrawCalls_,lastDynamicBytes_,residentBytes_,residentUploads_,1000.0*(beforeSubmit-tick)/SDL_GetPerformanceFrequency(),1000.0*(SDL_GetPerformanceCounter()-beforeSubmit)/SDL_GetPerformanceFrequency());
|
|
float w,h;SDL_Texture* target=SDL_GetRenderTarget(renderer);
|
|
if(target)SDL_GetTextureSize(target,&w,&h);else {int lw,lh;SDL_RendererLogicalPresentation lp;SDL_GetRenderLogicalPresentation(renderer,&lw,&lh,&lp);w=lw;h=lh;if(w<=0||h<=0){int pw,ph;SDL_GetRenderOutputSize(renderer,&pw,&ph);w=pw;h=ph;}}
|
|
SDL_FRect rect{0,0,w,h};return SDL_RenderTexture(renderer,output_,nullptr,&rect);
|
|
}
|
|
}
|