From 50b8cb11c91564e87781f9686f255391d8ce37d4 Mon Sep 17 00:00:00 2001 From: cosmonaut Date: Fri, 23 Feb 2024 16:00:29 -0800 Subject: [PATCH] add SetBufferData to ResourceUploader --- src/Graphics/ResourceUploader.cs | 40 ++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/src/Graphics/ResourceUploader.cs b/src/Graphics/ResourceUploader.cs index ac1dc40..c4f426c 100644 --- a/src/Graphics/ResourceUploader.cs +++ b/src/Graphics/ResourceUploader.cs @@ -21,7 +21,7 @@ namespace MoonWorks.Graphics uint dataOffset = 0; uint dataSize = 1024; - List<(GpuBuffer, uint, uint)> BufferUploads = new List<(GpuBuffer, uint, uint)>(); + List<(GpuBuffer, BufferCopy)> BufferUploads = new List<(GpuBuffer, BufferCopy)>(); List<(TextureSlice, uint)> TextureUploads = new List<(TextureSlice, uint)>(); public ResourceUploader(GraphicsDevice device) : base(device) @@ -29,6 +29,8 @@ namespace MoonWorks.Graphics data = (byte*) NativeMemory.Alloc(dataSize); } + // Buffers + /// /// Creates a GpuBuffer with data to be uploaded. /// @@ -37,17 +39,30 @@ namespace MoonWorks.Graphics var lengthInBytes = (uint) (Marshal.SizeOf() * data.Length); var gpuBuffer = new GpuBuffer(Device, usageFlags, lengthInBytes); + SetBufferData(gpuBuffer, 0, data); + + return gpuBuffer; + } + + /// + /// Prepares upload of data into a GpuBuffer. + /// + public void SetBufferData(GpuBuffer buffer, uint bufferOffset, Span data) where T : unmanaged + { + var lengthInBytes = (uint) (Marshal.SizeOf() * data.Length); + uint resourceOffset; fixed (void* spanPtr = data) { resourceOffset = CopyData(spanPtr, lengthInBytes); } - BufferUploads.Add((gpuBuffer, resourceOffset, lengthInBytes)); - - return gpuBuffer; + var bufferCopyParams = new BufferCopy(resourceOffset, bufferOffset, lengthInBytes); + BufferUploads.Add((buffer, bufferCopyParams)); } + // Textures + /// /// Creates a 2D Texture from compressed image data to be uploaded. /// @@ -193,6 +208,8 @@ namespace MoonWorks.Graphics TextureUploads.Add((textureSlice, resourceOffset)); } + // Upload + /// /// Uploads all the data corresponding to the created resources. /// @@ -220,6 +237,8 @@ namespace MoonWorks.Graphics Device.ReleaseFence(fence); } + // Helper methods + private void CopyToTransferBuffer() { if (TransferBuffer == null || TransferBuffer.Size < dataSize) @@ -236,16 +255,12 @@ namespace MoonWorks.Graphics { commandBuffer.BeginCopyPass(); - foreach (var (gpuBuffer, offset, size) in BufferUploads) + foreach (var (gpuBuffer, bufferCopyParams) in BufferUploads) { commandBuffer.UploadToBuffer( TransferBuffer, gpuBuffer, - new BufferCopy( - offset, - 0, - size - ) + bufferCopyParams ); } @@ -296,6 +311,11 @@ namespace MoonWorks.Graphics return alignment * ((value + alignment - 1) / alignment); } + // Dispose + + /// + /// It is valid to immediately call Dispose after calling Upload. + /// protected override void Dispose(bool disposing) { if (!IsDisposed)