Render original lab and Jimmy with native Vulkan and SDL3 on .NET 10
This commit is contained in:
1 parent
3df20ac19a
commit
008c0e16da
41 files changed
+2125
-68
No files matched your search
@@ -0,0 +1,431 @@
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using GamePort.Assets;
|
||||
using GamePort.Platform;
|
||||
using Silk.NET.Vulkan;
|
||||
using Silk.NET.Vulkan.Extensions.KHR;
|
||||
using Silk.NET.Vulkan.Extensions.EXT;
|
||||
using Buffer = Silk.NET.Vulkan.Buffer;
|
||||
using Image = Silk.NET.Vulkan.Image;
|
||||
using Semaphore = Silk.NET.Vulkan.Semaphore;
|
||||
|
||||
namespace GamePort.Rendering.Vulkan;
|
||||
|
||||
/// <summary>A deliberately small, synchronous renderer for recovering the original scenes.</summary>
|
||||
public sealed unsafe class VulkanRenderer : IDisposable
|
||||
{
|
||||
private readonly Vk vk=Vk.GetApi();
|
||||
private Instance instance;
|
||||
private PhysicalDevice physical;
|
||||
private Device device;
|
||||
private Queue queue;
|
||||
private uint queueFamily;
|
||||
private CommandPool pool;
|
||||
private CommandBuffer command;
|
||||
private Buffer vertexBuffer,indexBuffer,readback;
|
||||
private DeviceMemory vertexMemory,indexMemory,readbackMemory;
|
||||
private Image color,depth;
|
||||
private DeviceMemory colorMemory,depthMemory;
|
||||
private ImageView colorView,depthView;
|
||||
private RenderPass renderPass;
|
||||
private Framebuffer framebuffer;
|
||||
private Pipeline pipeline;
|
||||
private PipelineLayout pipelineLayout;
|
||||
private DescriptorSetLayout descriptorLayout;
|
||||
private DescriptorPool descriptorPool;
|
||||
private Sampler sampler;
|
||||
private readonly List<Texture> textures=[];
|
||||
private readonly Dictionary<int,DescriptorSet> descriptors=[];
|
||||
private readonly Mesh mesh;
|
||||
private readonly nint window;
|
||||
private SurfaceKHR surface;
|
||||
private KhrSurface? surfaceApi;
|
||||
private KhrSwapchain? swapApi;
|
||||
private SwapchainKHR swapchain;
|
||||
private Image[] swapImages=[];
|
||||
private ExtDebugUtils? debugApi;
|
||||
private DebugUtilsMessengerEXT messenger;
|
||||
private readonly DebugUtilsMessengerCallbackFunctionEXT debugCallback;
|
||||
private Semaphore acquired,finished;
|
||||
private uint width,height;
|
||||
public string DeviceName { get; private set; }="";
|
||||
public int ValidationErrors { get; private set; }
|
||||
public uint Width=>width;
|
||||
public uint Height=>height;
|
||||
|
||||
private sealed record Texture(Image Image,DeviceMemory Memory,ImageView View);
|
||||
private static void Check(Result result,string operation)
|
||||
{if(result!=Result.Success)throw new InvalidOperationException($"{operation}: {result}");}
|
||||
|
||||
public VulkanRenderer(Mesh mesh,PngImage texture,uint width=960,uint height=720,nint window=0,bool validation=true)
|
||||
{
|
||||
this.mesh=mesh;this.width=width;this.height=height;this.window=window;
|
||||
debugCallback=OnValidation;
|
||||
try
|
||||
{
|
||||
CreateInstance(validation);
|
||||
if(window!=0)
|
||||
{
|
||||
if(!Sdl.SDL_Vulkan_CreateSurface(window,instance.Handle,null,out var handle))throw new InvalidOperationException(Sdl.Error);
|
||||
surface=new SurfaceKHR(handle);
|
||||
if(!vk.TryGetInstanceExtension(instance,out surfaceApi))throw new NotSupportedException("VK_KHR_surface unavailable.");
|
||||
}
|
||||
CreateDevice();
|
||||
var poolInfo=new CommandPoolCreateInfo{SType=StructureType.CommandPoolCreateInfo,QueueFamilyIndex=queueFamily,Flags=CommandPoolCreateFlags.ResetCommandBufferBit};
|
||||
Check(vk.CreateCommandPool(device,&poolInfo,null,out pool),"CreateCommandPool");
|
||||
var allocation=new CommandBufferAllocateInfo{SType=StructureType.CommandBufferAllocateInfo,CommandPool=pool,Level=CommandBufferLevel.Primary,CommandBufferCount=1};
|
||||
Check(vk.AllocateCommandBuffers(device,&allocation,out command),"AllocateCommandBuffers");
|
||||
UploadBuffers();
|
||||
CreateDescriptors(texture);
|
||||
CreateRenderPass();
|
||||
CreatePipeline();
|
||||
if(window!=0)CreateSwapchain();
|
||||
CreateTarget();
|
||||
}
|
||||
catch{Dispose();throw;}
|
||||
}
|
||||
|
||||
private uint OnValidation(DebugUtilsMessageSeverityFlagsEXT severity,DebugUtilsMessageTypeFlagsEXT type,DebugUtilsMessengerCallbackDataEXT* data,void* user)
|
||||
{
|
||||
if((severity&DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt)!=0)ValidationErrors++;
|
||||
Console.Error.WriteLine($"Vulkan {severity}: {Marshal.PtrToStringUTF8((nint)data->PMessage)}");
|
||||
return Vk.False;
|
||||
}
|
||||
|
||||
private void CreateInstance(bool validation)
|
||||
{
|
||||
uint n=0;Check(vk.EnumerateInstanceLayerProperties(&n,null),"EnumerateInstanceLayers");
|
||||
var layers=new LayerProperties[n];
|
||||
fixed(LayerProperties* p=layers)Check(vk.EnumerateInstanceLayerProperties(&n,p),"EnumerateInstanceLayers");
|
||||
bool hasLayer=false;
|
||||
foreach(var layer in layers){var l=layer;if(Marshal.PtrToStringUTF8((nint)l.LayerName)=="VK_LAYER_KHRONOS_validation")hasLayer=true;}
|
||||
var names=new List<string>();
|
||||
if(window!=0)
|
||||
{
|
||||
var extensions=Sdl.SDL_Vulkan_GetInstanceExtensions(out var count);
|
||||
if(extensions==null)throw new InvalidOperationException(Sdl.Error);
|
||||
for(var i=0;i<count;i++)names.Add(Marshal.PtrToStringUTF8((nint)extensions[i])!);
|
||||
}
|
||||
validation &= hasLayer;
|
||||
if(validation)names.Add(ExtDebugUtils.ExtensionName);
|
||||
Console.WriteLine($"Vulkan validation: {(validation?"enabled":"unavailable or disabled")}");
|
||||
var native=names.Select(s=>Marshal.StringToCoTaskMemUTF8(s)).ToArray();
|
||||
var layerName=Marshal.StringToCoTaskMemUTF8("VK_LAYER_KHRONOS_validation");
|
||||
try
|
||||
{
|
||||
var app=new ApplicationInfo{SType=StructureType.ApplicationInfo,ApiVersion=Vk.Version13};
|
||||
fixed(nint* p=native)
|
||||
{
|
||||
var info=new InstanceCreateInfo{SType=StructureType.InstanceCreateInfo,PApplicationInfo=&app,EnabledExtensionCount=(uint)native.Length,PpEnabledExtensionNames=(byte**)p,
|
||||
EnabledLayerCount=validation?1u:0u,PpEnabledLayerNames=(byte**)&layerName};
|
||||
Check(vk.CreateInstance(&info,null,out instance),"CreateInstance");
|
||||
}
|
||||
if(validation && vk.TryGetInstanceExtension(instance,out debugApi))
|
||||
{
|
||||
var debugInfo=new DebugUtilsMessengerCreateInfoEXT{SType=StructureType.DebugUtilsMessengerCreateInfoExt,
|
||||
MessageSeverity=DebugUtilsMessageSeverityFlagsEXT.WarningBitExt|DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
|
||||
MessageType=DebugUtilsMessageTypeFlagsEXT.GeneralBitExt|DebugUtilsMessageTypeFlagsEXT.ValidationBitExt|DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
|
||||
PfnUserCallback=debugCallback};
|
||||
Check(debugApi!.CreateDebugUtilsMessenger(instance,&debugInfo,null,out messenger),"CreateDebugMessenger");
|
||||
}
|
||||
}
|
||||
finally{foreach(var p in native)Marshal.FreeCoTaskMem(p);Marshal.FreeCoTaskMem(layerName);}
|
||||
}
|
||||
|
||||
private void CreateDevice()
|
||||
{
|
||||
foreach(var gpu in vk.GetPhysicalDevices(instance))
|
||||
{
|
||||
vk.GetPhysicalDeviceProperties(gpu,out var properties);
|
||||
if(properties.ApiVersion<Vk.Version13)continue;
|
||||
uint count=0;vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,null);
|
||||
var families=new QueueFamilyProperties[count];
|
||||
fixed(QueueFamilyProperties* p=families)vk.GetPhysicalDeviceQueueFamilyProperties(gpu,&count,p);
|
||||
for(uint f=0;f<count;f++)
|
||||
{
|
||||
if((families[f].QueueFlags&QueueFlags.GraphicsBit)==0)continue;
|
||||
if(window!=0){Check(surfaceApi!.GetPhysicalDeviceSurfaceSupport(gpu,f,surface,out var supported),"SurfaceSupport");if(!supported)continue;}
|
||||
physical=gpu;queueFamily=f;DeviceName=Marshal.PtrToStringUTF8((nint)properties.DeviceName)!;break;
|
||||
}
|
||||
if(physical.Handle!=0)break;
|
||||
}
|
||||
if(physical.Handle==0)throw new NotSupportedException("A Vulkan 1.3 graphics/presentation device is required.");
|
||||
float priority=1;
|
||||
var queueInfo=new DeviceQueueCreateInfo{SType=StructureType.DeviceQueueCreateInfo,QueueFamilyIndex=queueFamily,QueueCount=1,PQueuePriorities=&priority};
|
||||
var name=Marshal.StringToCoTaskMemUTF8(KhrSwapchain.ExtensionName);
|
||||
try
|
||||
{
|
||||
var info=new DeviceCreateInfo{SType=StructureType.DeviceCreateInfo,QueueCreateInfoCount=1,PQueueCreateInfos=&queueInfo,EnabledExtensionCount=window!=0?1u:0u,PpEnabledExtensionNames=(byte**)&name};
|
||||
Check(vk.CreateDevice(physical,&info,null,out device),"CreateDevice");
|
||||
}
|
||||
finally{Marshal.FreeCoTaskMem(name);}
|
||||
vk.GetDeviceQueue(device,queueFamily,0,out queue);
|
||||
if(window!=0)
|
||||
{
|
||||
if(!vk.TryGetDeviceExtension(instance,device,out swapApi))throw new NotSupportedException("VK_KHR_swapchain unavailable.");
|
||||
var si=new SemaphoreCreateInfo{SType=StructureType.SemaphoreCreateInfo};
|
||||
Check(vk.CreateSemaphore(device,&si,null,out acquired),"CreateSemaphore");
|
||||
Check(vk.CreateSemaphore(device,&si,null,out finished),"CreateSemaphore");
|
||||
}
|
||||
Console.WriteLine($"Vulkan device: {DeviceName}");
|
||||
}
|
||||
|
||||
private uint MemoryType(uint allowed,MemoryPropertyFlags flags)
|
||||
{
|
||||
vk.GetPhysicalDeviceMemoryProperties(physical,out var memory);
|
||||
for(uint i=0;i<memory.MemoryTypeCount;i++)if((allowed&(1u<<(int)i))!=0 && (memory.MemoryTypes[(int)i].PropertyFlags&flags)==flags)return i;
|
||||
throw new NotSupportedException($"No memory type for {flags}.");
|
||||
}
|
||||
private void MakeBuffer(ulong size,BufferUsageFlags usage,MemoryPropertyFlags flags,out Buffer buffer,out DeviceMemory memory)
|
||||
{
|
||||
var info=new BufferCreateInfo{SType=StructureType.BufferCreateInfo,Size=size,Usage=usage,SharingMode=SharingMode.Exclusive};
|
||||
Check(vk.CreateBuffer(device,&info,null,out buffer),"CreateBuffer");
|
||||
vk.GetBufferMemoryRequirements(device,buffer,out var requirements);
|
||||
var allocation=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=requirements.Size,MemoryTypeIndex=MemoryType(requirements.MemoryTypeBits,flags)};
|
||||
Check(vk.AllocateMemory(device,&allocation,null,out memory),"AllocateBufferMemory");
|
||||
Check(vk.BindBufferMemory(device,buffer,memory,0),"BindBufferMemory");
|
||||
}
|
||||
private void UploadBuffers()
|
||||
{
|
||||
var vertexBytes=MemoryMarshal.AsBytes(mesh.Vertices.AsSpan());
|
||||
MakeBuffer((ulong)vertexBytes.Length,BufferUsageFlags.VertexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out vertexBuffer,out vertexMemory);
|
||||
CopyToMemory(vertexMemory,vertexBytes);
|
||||
var indexBytes=MemoryMarshal.AsBytes(mesh.Indices.AsSpan());
|
||||
MakeBuffer((ulong)indexBytes.Length,BufferUsageFlags.IndexBufferBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out indexBuffer,out indexMemory);
|
||||
CopyToMemory(indexMemory,indexBytes);
|
||||
}
|
||||
public void UpdateVertices(ReadOnlySpan<MeshVertex> vertices)
|
||||
{
|
||||
if(vertices.Length!=mesh.Vertices.Length)throw new ArgumentException("Vertex count must match the uploaded mesh.");
|
||||
// Frames are completed synchronously; host coherent memory is safe to update here.
|
||||
CopyToMemory(vertexMemory,MemoryMarshal.AsBytes(vertices));
|
||||
}
|
||||
private void CopyToMemory(DeviceMemory memory,ReadOnlySpan<byte> bytes)
|
||||
{
|
||||
void* data;Check(vk.MapMemory(device,memory,0,(ulong)bytes.Length,0,&data),"MapMemory");
|
||||
bytes.CopyTo(new Span<byte>(data,bytes.Length));vk.UnmapMemory(device,memory);
|
||||
}
|
||||
private void MakeImage(uint w,uint h,Format format,ImageUsageFlags usage,ImageAspectFlags aspect,out Image image,out DeviceMemory memory,out ImageView view)
|
||||
{
|
||||
var info=new ImageCreateInfo{SType=StructureType.ImageCreateInfo,ImageType=ImageType.Type2D,Format=format,Extent=new Extent3D(w,h,1),MipLevels=1,ArrayLayers=1,Samples=SampleCountFlags.Count1Bit,Tiling=ImageTiling.Optimal,Usage=usage,SharingMode=SharingMode.Exclusive,InitialLayout=ImageLayout.Undefined};
|
||||
Check(vk.CreateImage(device,&info,null,out image),"CreateImage");
|
||||
vk.GetImageMemoryRequirements(device,image,out var req);
|
||||
var alloc=new MemoryAllocateInfo{SType=StructureType.MemoryAllocateInfo,AllocationSize=req.Size,MemoryTypeIndex=MemoryType(req.MemoryTypeBits,MemoryPropertyFlags.DeviceLocalBit)};
|
||||
Check(vk.AllocateMemory(device,&alloc,null,out memory),"AllocateImageMemory");Check(vk.BindImageMemory(device,image,memory,0),"BindImageMemory");
|
||||
var vi=new ImageViewCreateInfo{SType=StructureType.ImageViewCreateInfo,Image=image,ViewType=ImageViewType.Type2D,Format=format,SubresourceRange=new ImageSubresourceRange(aspect,0,1,0,1)};
|
||||
Check(vk.CreateImageView(device,&vi,null,out view),"CreateImageView");
|
||||
}
|
||||
private void Begin()
|
||||
{
|
||||
Check(vk.ResetCommandBuffer(command,0),"ResetCommandBuffer");
|
||||
var info=new CommandBufferBeginInfo{SType=StructureType.CommandBufferBeginInfo,Flags=CommandBufferUsageFlags.OneTimeSubmitBit};
|
||||
Check(vk.BeginCommandBuffer(command,&info),"BeginCommandBuffer");
|
||||
}
|
||||
private void Submit()
|
||||
{
|
||||
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;
|
||||
var info=new SubmitInfo{SType=StructureType.SubmitInfo,CommandBufferCount=1,PCommandBuffers=&cmd};
|
||||
Check(vk.QueueSubmit(queue,1,&info,default),"QueueSubmit");Check(vk.QueueWaitIdle(queue),"QueueWaitIdle");
|
||||
}
|
||||
private void Barrier(Image image,ImageLayout oldLayout,ImageLayout newLayout,AccessFlags source,AccessFlags destination,PipelineStageFlags srcStage,PipelineStageFlags dstStage)
|
||||
{
|
||||
var barrier=new ImageMemoryBarrier{SType=StructureType.ImageMemoryBarrier,OldLayout=oldLayout,NewLayout=newLayout,SrcAccessMask=source,DstAccessMask=destination,SrcQueueFamilyIndex=Vk.QueueFamilyIgnored,DstQueueFamilyIndex=Vk.QueueFamilyIgnored,Image=image,SubresourceRange=new ImageSubresourceRange(ImageAspectFlags.ColorBit,0,1,0,1)};
|
||||
vk.CmdPipelineBarrier(command,srcStage,dstStage,0,0,null,0,null,1,&barrier);
|
||||
}
|
||||
private Texture UploadTexture(PngImage image)
|
||||
{
|
||||
MakeBuffer((ulong)image.Rgba.Length,BufferUsageFlags.TransferSrcBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out var staging,out var memory);
|
||||
CopyToMemory(memory,image.Rgba);
|
||||
MakeImage(image.Width,image.Height,Format.R8G8B8A8Unorm,ImageUsageFlags.TransferDstBit|ImageUsageFlags.SampledBit,ImageAspectFlags.ColorBit,out var texture,out var textureMemory,out var view);
|
||||
Begin();Barrier(texture,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
|
||||
var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(image.Width,image.Height,1)};
|
||||
vk.CmdCopyBufferToImage(command,staging,texture,ImageLayout.TransferDstOptimal,1,©);
|
||||
Barrier(texture,ImageLayout.TransferDstOptimal,ImageLayout.ShaderReadOnlyOptimal,AccessFlags.TransferWriteBit,AccessFlags.ShaderReadBit,PipelineStageFlags.TransferBit,PipelineStageFlags.FragmentShaderBit);Submit();
|
||||
vk.DestroyBuffer(device,staging,null);vk.FreeMemory(device,memory,null);
|
||||
var result=new Texture(texture,textureMemory,view);textures.Add(result);return result;
|
||||
}
|
||||
private void CreateDescriptors(PngImage fallback)
|
||||
{
|
||||
var binding=new DescriptorSetLayoutBinding{Binding=0,DescriptorType=DescriptorType.CombinedImageSampler,DescriptorCount=1,StageFlags=ShaderStageFlags.FragmentBit};
|
||||
var layout=new DescriptorSetLayoutCreateInfo{SType=StructureType.DescriptorSetLayoutCreateInfo,BindingCount=1,PBindings=&binding};
|
||||
Check(vk.CreateDescriptorSetLayout(device,&layout,null,out descriptorLayout),"CreateDescriptorSetLayout");
|
||||
var count=(uint)mesh.Textures.Count+1;
|
||||
var size=new DescriptorPoolSize(DescriptorType.CombinedImageSampler,count);
|
||||
var poolInfo=new DescriptorPoolCreateInfo{SType=StructureType.DescriptorPoolCreateInfo,MaxSets=count,PoolSizeCount=1,PPoolSizes=&size};
|
||||
Check(vk.CreateDescriptorPool(device,&poolInfo,null,out descriptorPool),"CreateDescriptorPool");
|
||||
var samplerInfo=new SamplerCreateInfo{SType=StructureType.SamplerCreateInfo,MagFilter=Filter.Linear,MinFilter=Filter.Linear,MipmapMode=SamplerMipmapMode.Nearest,AddressModeU=SamplerAddressMode.Repeat,AddressModeV=SamplerAddressMode.Repeat,AddressModeW=SamplerAddressMode.Repeat,MaxLod=0};
|
||||
Check(vk.CreateSampler(device,&samplerInfo,null,out sampler),"CreateSampler");
|
||||
var images=new Dictionary<int,PngImage>(mesh.Textures){[-1]=fallback};
|
||||
foreach(var (id,image) in images)
|
||||
{
|
||||
var texture=UploadTexture(image);var descriptor=descriptorLayout;
|
||||
var alloc=new DescriptorSetAllocateInfo{SType=StructureType.DescriptorSetAllocateInfo,DescriptorPool=descriptorPool,DescriptorSetCount=1,PSetLayouts=&descriptor};
|
||||
Check(vk.AllocateDescriptorSets(device,&alloc,out var set),"AllocateDescriptorSets");
|
||||
var imageInfo=new DescriptorImageInfo{Sampler=sampler,ImageView=texture.View,ImageLayout=ImageLayout.ShaderReadOnlyOptimal};
|
||||
var write=new WriteDescriptorSet{SType=StructureType.WriteDescriptorSet,DstSet=set,DstBinding=0,DescriptorCount=1,DescriptorType=DescriptorType.CombinedImageSampler,PImageInfo=&imageInfo};
|
||||
vk.UpdateDescriptorSets(device,1,&write,0,null);descriptors[id]=set;
|
||||
}
|
||||
}
|
||||
private void CreateRenderPass()
|
||||
{
|
||||
var attachments=stackalloc AttachmentDescription[2];
|
||||
attachments[0]=new AttachmentDescription{Format=Format.R8G8B8A8Unorm,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.Store,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.TransferSrcOptimal};
|
||||
attachments[1]=new AttachmentDescription{Format=Format.D32Sfloat,Samples=SampleCountFlags.Count1Bit,LoadOp=AttachmentLoadOp.Clear,StoreOp=AttachmentStoreOp.DontCare,StencilLoadOp=AttachmentLoadOp.DontCare,StencilStoreOp=AttachmentStoreOp.DontCare,InitialLayout=ImageLayout.Undefined,FinalLayout=ImageLayout.DepthStencilAttachmentOptimal};
|
||||
var cr=new AttachmentReference(0,ImageLayout.ColorAttachmentOptimal);var dr=new AttachmentReference(1,ImageLayout.DepthStencilAttachmentOptimal);
|
||||
var subpass=new SubpassDescription{PipelineBindPoint=PipelineBindPoint.Graphics,ColorAttachmentCount=1,PColorAttachments=&cr,PDepthStencilAttachment=&dr};
|
||||
var dependencies=stackalloc SubpassDependency[2];
|
||||
dependencies[0]=new SubpassDependency{SrcSubpass=Vk.SubpassExternal,DstSubpass=0,SrcStageMask=PipelineStageFlags.TopOfPipeBit,DstStageMask=PipelineStageFlags.ColorAttachmentOutputBit|PipelineStageFlags.EarlyFragmentTestsBit,DstAccessMask=AccessFlags.ColorAttachmentWriteBit|AccessFlags.DepthStencilAttachmentWriteBit};
|
||||
dependencies[1]=new SubpassDependency{SrcSubpass=0,DstSubpass=Vk.SubpassExternal,SrcStageMask=PipelineStageFlags.ColorAttachmentOutputBit,DstStageMask=PipelineStageFlags.TransferBit,SrcAccessMask=AccessFlags.ColorAttachmentWriteBit,DstAccessMask=AccessFlags.TransferReadBit};
|
||||
var info=new RenderPassCreateInfo{SType=StructureType.RenderPassCreateInfo,AttachmentCount=2,PAttachments=attachments,SubpassCount=1,PSubpasses=&subpass,DependencyCount=2,PDependencies=dependencies};
|
||||
Check(vk.CreateRenderPass(device,&info,null,out renderPass),"CreateRenderPass");
|
||||
}
|
||||
private ShaderModule Shader(string name)
|
||||
{
|
||||
var bytes=File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory,"Shaders",name));
|
||||
fixed(byte* p=bytes){var info=new ShaderModuleCreateInfo{SType=StructureType.ShaderModuleCreateInfo,CodeSize=(nuint)bytes.Length,PCode=(uint*)p};Check(vk.CreateShaderModule(device,&info,null,out var shader),"CreateShaderModule");return shader;}
|
||||
}
|
||||
private void CreatePipeline()
|
||||
{
|
||||
var vertex=Shader("mesh.vert.spv");var fragment=Shader("mesh.frag.spv");var main=Marshal.StringToCoTaskMemUTF8("main");
|
||||
try
|
||||
{
|
||||
var push=new PushConstantRange(ShaderStageFlags.VertexBit,0,64);var dl=descriptorLayout;
|
||||
var layout=new PipelineLayoutCreateInfo{SType=StructureType.PipelineLayoutCreateInfo,SetLayoutCount=1,PSetLayouts=&dl,PushConstantRangeCount=1,PPushConstantRanges=&push};
|
||||
Check(vk.CreatePipelineLayout(device,&layout,null,out pipelineLayout),"CreatePipelineLayout");
|
||||
var stages=stackalloc PipelineShaderStageCreateInfo[2];
|
||||
stages[0]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.VertexBit,Module=vertex,PName=(byte*)main};
|
||||
stages[1]=new PipelineShaderStageCreateInfo{SType=StructureType.PipelineShaderStageCreateInfo,Stage=ShaderStageFlags.FragmentBit,Module=fragment,PName=(byte*)main};
|
||||
var binding=new VertexInputBindingDescription(0,(uint)sizeof(MeshVertex),VertexInputRate.Vertex);
|
||||
var attributes=stackalloc VertexInputAttributeDescription[3];
|
||||
attributes[0]=new VertexInputAttributeDescription(0,0,Format.R32G32B32Sfloat,0);
|
||||
attributes[1]=new VertexInputAttributeDescription(1,0,Format.R32G32Sfloat,12);
|
||||
attributes[2]=new VertexInputAttributeDescription(2,0,Format.R32G32B32Sfloat,20);
|
||||
var input=new PipelineVertexInputStateCreateInfo{SType=StructureType.PipelineVertexInputStateCreateInfo,VertexBindingDescriptionCount=1,PVertexBindingDescriptions=&binding,VertexAttributeDescriptionCount=3,PVertexAttributeDescriptions=attributes};
|
||||
var assembly=new PipelineInputAssemblyStateCreateInfo{SType=StructureType.PipelineInputAssemblyStateCreateInfo,Topology=PrimitiveTopology.TriangleList};
|
||||
var viewport=new PipelineViewportStateCreateInfo{SType=StructureType.PipelineViewportStateCreateInfo,ViewportCount=1,ScissorCount=1};
|
||||
var raster=new PipelineRasterizationStateCreateInfo{SType=StructureType.PipelineRasterizationStateCreateInfo,PolygonMode=PolygonMode.Fill,CullMode=CullModeFlags.None,FrontFace=FrontFace.CounterClockwise,LineWidth=1};
|
||||
var ms=new PipelineMultisampleStateCreateInfo{SType=StructureType.PipelineMultisampleStateCreateInfo,RasterizationSamples=SampleCountFlags.Count1Bit};
|
||||
var ds=new PipelineDepthStencilStateCreateInfo{SType=StructureType.PipelineDepthStencilStateCreateInfo,DepthTestEnable=true,DepthWriteEnable=true,DepthCompareOp=CompareOp.LessOrEqual};
|
||||
var blendAttachment=new PipelineColorBlendAttachmentState{ColorWriteMask=ColorComponentFlags.RBit|ColorComponentFlags.GBit|ColorComponentFlags.BBit|ColorComponentFlags.ABit};
|
||||
var blend=new PipelineColorBlendStateCreateInfo{SType=StructureType.PipelineColorBlendStateCreateInfo,AttachmentCount=1,PAttachments=&blendAttachment};
|
||||
var dynamicStates=stackalloc DynamicState[2]{DynamicState.Viewport,DynamicState.Scissor};
|
||||
var dynamic=new PipelineDynamicStateCreateInfo{SType=StructureType.PipelineDynamicStateCreateInfo,DynamicStateCount=2,PDynamicStates=dynamicStates};
|
||||
var info=new GraphicsPipelineCreateInfo{SType=StructureType.GraphicsPipelineCreateInfo,StageCount=2,PStages=stages,PVertexInputState=&input,PInputAssemblyState=&assembly,PViewportState=&viewport,PRasterizationState=&raster,PMultisampleState=&ms,PDepthStencilState=&ds,PColorBlendState=&blend,PDynamicState=&dynamic,Layout=pipelineLayout,RenderPass=renderPass,Subpass=0};
|
||||
Check(vk.CreateGraphicsPipelines(device,default,1,&info,null,out pipeline),"CreateGraphicsPipeline");
|
||||
}
|
||||
finally{Marshal.FreeCoTaskMem(main);vk.DestroyShaderModule(device,vertex,null);vk.DestroyShaderModule(device,fragment,null);}
|
||||
}
|
||||
private void CreateTarget()
|
||||
{
|
||||
MakeImage(width,height,Format.R8G8B8A8Unorm,ImageUsageFlags.ColorAttachmentBit|ImageUsageFlags.TransferSrcBit,ImageAspectFlags.ColorBit,out color,out colorMemory,out colorView);
|
||||
MakeImage(width,height,Format.D32Sfloat,ImageUsageFlags.DepthStencilAttachmentBit,ImageAspectFlags.DepthBit,out depth,out depthMemory,out depthView);
|
||||
var views=stackalloc ImageView[2]{colorView,depthView};
|
||||
var info=new FramebufferCreateInfo{SType=StructureType.FramebufferCreateInfo,RenderPass=renderPass,AttachmentCount=2,PAttachments=views,Width=width,Height=height,Layers=1};
|
||||
Check(vk.CreateFramebuffer(device,&info,null,out framebuffer),"CreateFramebuffer");
|
||||
MakeBuffer((ulong)width*height*4,BufferUsageFlags.TransferDstBit,MemoryPropertyFlags.HostVisibleBit|MemoryPropertyFlags.HostCoherentBit,out readback,out readbackMemory);
|
||||
}
|
||||
private void DestroyTarget()
|
||||
{
|
||||
vk.DestroyFramebuffer(device,framebuffer,null);vk.DestroyImageView(device,colorView,null);vk.DestroyImageView(device,depthView,null);
|
||||
vk.DestroyImage(device,color,null);vk.DestroyImage(device,depth,null);vk.FreeMemory(device,colorMemory,null);vk.FreeMemory(device,depthMemory,null);
|
||||
vk.DestroyBuffer(device,readback,null);vk.FreeMemory(device,readbackMemory,null);
|
||||
}
|
||||
private void CreateSwapchain()
|
||||
{
|
||||
Check(surfaceApi!.GetPhysicalDeviceSurfaceCapabilities(physical,surface,out var caps),"SurfaceCapabilities");
|
||||
uint count=0;Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,null),"SurfaceFormats");
|
||||
var formats=new SurfaceFormatKHR[count];fixed(SurfaceFormatKHR* p=formats)Check(surfaceApi.GetPhysicalDeviceSurfaceFormats(physical,surface,&count,p),"SurfaceFormats");
|
||||
var format=formats.FirstOrDefault(f=>f.Format==Format.B8G8R8A8Unorm);if(format.Format==0)format=formats[0];
|
||||
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);
|
||||
width=caps.CurrentExtent.Width==uint.MaxValue?Math.Clamp((uint)Math.Max(1,w),caps.MinImageExtent.Width,caps.MaxImageExtent.Width):caps.CurrentExtent.Width;
|
||||
height=caps.CurrentExtent.Height==uint.MaxValue?Math.Clamp((uint)Math.Max(1,h),caps.MinImageExtent.Height,caps.MaxImageExtent.Height):caps.CurrentExtent.Height;
|
||||
if((caps.SupportedUsageFlags&ImageUsageFlags.TransferDstBit)==0)throw new NotSupportedException("Swapchain does not support transfer destinations.");
|
||||
var imageCount=caps.MinImageCount+1;if(caps.MaxImageCount>0)imageCount=Math.Min(imageCount,caps.MaxImageCount);
|
||||
var info=new SwapchainCreateInfoKHR{SType=StructureType.SwapchainCreateInfoKhr,Surface=surface,MinImageCount=imageCount,ImageFormat=format.Format,ImageColorSpace=format.ColorSpace,ImageExtent=new Extent2D(width,height),ImageArrayLayers=1,ImageUsage=ImageUsageFlags.TransferDstBit,ImageSharingMode=SharingMode.Exclusive,PreTransform=caps.CurrentTransform,CompositeAlpha=CompositeAlphaFlagsKHR.OpaqueBitKhr,PresentMode=PresentModeKHR.FifoKhr,Clipped=true};
|
||||
Check(swapApi!.CreateSwapchain(device,&info,null,out swapchain),"CreateSwapchain");
|
||||
count=0;Check(swapApi.GetSwapchainImages(device,swapchain,&count,null),"GetSwapchainImages");swapImages=new Image[count];
|
||||
fixed(Image* p=swapImages)Check(swapApi.GetSwapchainImages(device,swapchain,&count,p),"GetSwapchainImages");
|
||||
}
|
||||
public void Resize()
|
||||
{
|
||||
if(window==0)return;
|
||||
Sdl.SDL_GetWindowSizeInPixels(window,out var w,out var h);if(w<1||h<1)return;
|
||||
Check(vk.DeviceWaitIdle(device),"ResizeWaitIdle");DestroyTarget();swapApi!.DestroySwapchain(device,swapchain,null);CreateSwapchain();CreateTarget();
|
||||
}
|
||||
public void Render(Matrix4x4 mvp)
|
||||
{
|
||||
uint imageIndex=0;
|
||||
if(window!=0)
|
||||
{
|
||||
var result=swapApi!.AcquireNextImage(device,swapchain,ulong.MaxValue,acquired,default,&imageIndex);
|
||||
if(result==Result.ErrorOutOfDateKhr){Resize();return;}
|
||||
if(result!=Result.SuboptimalKhr)Check(result,"AcquireNextImage");
|
||||
}
|
||||
Begin();
|
||||
var clear=stackalloc ClearValue[2];clear[0].Color=new ClearColorValue(0.12f,0.20f,0.30f,1);clear[1].DepthStencil=new ClearDepthStencilValue(1,0);
|
||||
var begin=new RenderPassBeginInfo{SType=StructureType.RenderPassBeginInfo,RenderPass=renderPass,Framebuffer=framebuffer,RenderArea=new Rect2D(new Offset2D(0,0),new Extent2D(width,height)),ClearValueCount=2,PClearValues=clear};
|
||||
vk.CmdBeginRenderPass(command,&begin,SubpassContents.Inline);vk.CmdBindPipeline(command,PipelineBindPoint.Graphics,pipeline);
|
||||
var viewport=new Viewport(0,0,width,height,0,1);var scissor=new Rect2D(new Offset2D(0,0),new Extent2D(width,height));
|
||||
vk.CmdSetViewport(command,0,1,&viewport);vk.CmdSetScissor(command,0,1,&scissor);
|
||||
var vb=vertexBuffer;ulong offset=0;vk.CmdBindVertexBuffers(command,0,1,&vb,&offset);vk.CmdBindIndexBuffer(command,indexBuffer,0,IndexType.Uint32);
|
||||
vk.CmdPushConstants(command,pipelineLayout,ShaderStageFlags.VertexBit,0,64,&mvp);
|
||||
var draws=mesh.HasExplicitDraws?mesh.Draws:[new MeshDraw(0,(uint)mesh.Indices.Length,-1)];
|
||||
foreach(var draw in draws)
|
||||
{
|
||||
var descriptor=descriptors.GetValueOrDefault(draw.TextureId,descriptors[-1]);
|
||||
vk.CmdBindDescriptorSets(command,PipelineBindPoint.Graphics,pipelineLayout,0,1,&descriptor,0,null);
|
||||
vk.CmdDrawIndexed(command,draw.IndexCount,1,draw.FirstIndex,0,0);
|
||||
}
|
||||
vk.CmdEndRenderPass(command);
|
||||
if(window==0){Submit();return;}
|
||||
var target=swapImages[imageIndex];Barrier(target,ImageLayout.Undefined,ImageLayout.TransferDstOptimal,0,AccessFlags.TransferWriteBit,PipelineStageFlags.TopOfPipeBit,PipelineStageFlags.TransferBit);
|
||||
var blit=new ImageBlit{SrcSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),DstSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1)};
|
||||
blit.SrcOffsets[0]=new Offset3D(0,0,0);blit.SrcOffsets[1]=new Offset3D((int)width,(int)height,1);blit.DstOffsets[0]=new Offset3D(0,0,0);blit.DstOffsets[1]=new Offset3D((int)width,(int)height,1);
|
||||
vk.CmdBlitImage(command,color,ImageLayout.TransferSrcOptimal,target,ImageLayout.TransferDstOptimal,1,&blit,Filter.Nearest);
|
||||
Barrier(target,ImageLayout.TransferDstOptimal,ImageLayout.PresentSrcKhr,AccessFlags.TransferWriteBit,0,PipelineStageFlags.TransferBit,PipelineStageFlags.BottomOfPipeBit);
|
||||
Check(vk.EndCommandBuffer(command),"EndCommandBuffer");var cmd=command;var wait=acquired;var signal=finished;var stage=PipelineStageFlags.TransferBit;
|
||||
var submit=new SubmitInfo{SType=StructureType.SubmitInfo,WaitSemaphoreCount=1,PWaitSemaphores=&wait,PWaitDstStageMask=&stage,CommandBufferCount=1,PCommandBuffers=&cmd,SignalSemaphoreCount=1,PSignalSemaphores=&signal};
|
||||
Check(vk.QueueSubmit(queue,1,&submit,default),"QueueSubmit");var swap=swapchain;
|
||||
var present=new PresentInfoKHR{SType=StructureType.PresentInfoKhr,WaitSemaphoreCount=1,PWaitSemaphores=&signal,SwapchainCount=1,PSwapchains=&swap,PImageIndices=&imageIndex};
|
||||
var presentation=swapApi!.QueuePresent(queue,&present);Check(vk.QueueWaitIdle(queue),"PresentWaitIdle");
|
||||
if(presentation is Result.ErrorOutOfDateKhr or Result.SuboptimalKhr)Resize();else Check(presentation,"QueuePresent");
|
||||
}
|
||||
public byte[] ReadPixels()
|
||||
{
|
||||
Begin();var copy=new BufferImageCopy{ImageSubresource=new ImageSubresourceLayers(ImageAspectFlags.ColorBit,0,0,1),ImageExtent=new Extent3D(width,height,1)};
|
||||
vk.CmdCopyImageToBuffer(command,color,ImageLayout.TransferSrcOptimal,readback,1,©);Submit();
|
||||
var pixels=new byte[checked((int)(width*height*4))];void* data;
|
||||
Check(vk.MapMemory(device,readbackMemory,0,(ulong)pixels.Length,0,&data),"ReadbackMap");new ReadOnlySpan<byte>(data,pixels.Length).CopyTo(pixels);vk.UnmapMemory(device,readbackMemory);return pixels;
|
||||
}
|
||||
public void SavePpm(string path)
|
||||
{
|
||||
var rgba=ReadPixels();Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||
using var file=File.Create(path);file.Write(System.Text.Encoding.ASCII.GetBytes($"P6\n{width} {height}\n255\n"));
|
||||
for(var i=0;i<rgba.Length;i+=4)file.Write(rgba,i,3);
|
||||
}
|
||||
public void Dispose()
|
||||
{
|
||||
if(device.Handle!=0)
|
||||
{
|
||||
vk.DeviceWaitIdle(device);
|
||||
if(framebuffer.Handle!=0)DestroyTarget();
|
||||
if(pipeline.Handle!=0)vk.DestroyPipeline(device,pipeline,null);
|
||||
if(pipelineLayout.Handle!=0)vk.DestroyPipelineLayout(device,pipelineLayout,null);
|
||||
if(renderPass.Handle!=0)vk.DestroyRenderPass(device,renderPass,null);
|
||||
if(descriptorPool.Handle!=0)vk.DestroyDescriptorPool(device,descriptorPool,null);
|
||||
if(descriptorLayout.Handle!=0)vk.DestroyDescriptorSetLayout(device,descriptorLayout,null);
|
||||
if(sampler.Handle!=0)vk.DestroySampler(device,sampler,null);
|
||||
foreach(var t in textures){vk.DestroyImageView(device,t.View,null);vk.DestroyImage(device,t.Image,null);vk.FreeMemory(device,t.Memory,null);}
|
||||
if(vertexBuffer.Handle!=0)vk.DestroyBuffer(device,vertexBuffer,null);if(vertexMemory.Handle!=0)vk.FreeMemory(device,vertexMemory,null);
|
||||
if(indexBuffer.Handle!=0)vk.DestroyBuffer(device,indexBuffer,null);if(indexMemory.Handle!=0)vk.FreeMemory(device,indexMemory,null);
|
||||
if(acquired.Handle!=0)vk.DestroySemaphore(device,acquired,null);if(finished.Handle!=0)vk.DestroySemaphore(device,finished,null);
|
||||
if(swapchain.Handle!=0)swapApi!.DestroySwapchain(device,swapchain,null);
|
||||
if(pool.Handle!=0)vk.DestroyCommandPool(device,pool,null);
|
||||
vk.DestroyDevice(device,null);device=default;
|
||||
}
|
||||
if(surface.Handle!=0){surfaceApi!.DestroySurface(instance,surface,null);surface=default;}
|
||||
if(messenger.Handle!=0){debugApi!.DestroyDebugUtilsMessenger(instance,messenger,null);messenger=default;}
|
||||
if(instance.Handle!=0){vk.DestroyInstance(instance,null);instance=default;}
|
||||
vk.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user