diff --git a/src/ComputeSharp.Graphics/Buffers/Buffer2.cs b/src/ComputeSharp.Graphics/Buffers/Buffer2.cs index df75a923..740de6b8 100644 --- a/src/ComputeSharp.Graphics/Buffers/Buffer2.cs +++ b/src/ComputeSharp.Graphics/Buffers/Buffer2.cs @@ -1,6 +1,8 @@ -using System.Diagnostics.Contracts; +using System; +using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using ComputeSharp.Graphics.Buffers.Abstract; +using ComputeSharp.Graphics.Helpers; using SharpDX.Direct3D12; namespace ComputeSharp.Graphics.Buffers @@ -105,5 +107,55 @@ namespace ComputeSharp.Graphics.Buffers /// Gets the heap type being targeted by the current buffer /// public HeapType HeapType { get; } + + /// + /// Reads the contents of the current instance and writes them into a target + /// + /// The input to write data to + public void GetData(Span span) + { + // Create a temporary readback buffer if the current buffer type is read write (can't be read from directly) + if (HeapType == HeapType.Default) + { + using Buffer2 readbackBaffer = new Buffer2(GraphicsDevice, Size, HeapType.Readback); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes); + copyCommandList.Flush(true); + + readbackBaffer.GetData(span); + } + else + { + // Map and read the memory back directly + Map(0); + MemoryHelper.Copy(MappedResource, span); + Unmap(0); + } + } + + /// + /// Writes the contents of a given to the current instance + /// + /// The input to read data from + public void SetData(Span span) + { + // Create a temporary upload buffer if the current buffer type is read write (can't be written to directly) + if (HeapType == HeapType.Default) + { + using Buffer2 uploadBuffer = new Buffer2(GraphicsDevice, Size, HeapType.Upload); + using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy); + + copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes); + copyCommandList.Flush(true); + } + else + { + // Map and copy the memory directly + Map(0); + MemoryHelper.Copy(span, MappedResource); + Unmap(0); + } + } } }