using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics.Buffers.Abstract;
using ComputeSharp.Graphics.Helpers;
using SharpDX.Direct3D12;
using CommandList = ComputeSharp.Graphics.Commands.CommandList;
namespace ComputeSharp.Graphics.Buffers
{
///
/// A representing a typed read write buffer stored on GPU memory
///
/// The type of items stored on the buffer
public sealed class ReadWriteBuffer : HlslBuffer where T : unmanaged
{
///
/// Creates a new instance with the specified parameters
///
/// The associated with the current instance
/// The number of items to store in the current buffer
internal ReadWriteBuffer(GraphicsDevice device, int size) : base(device, size, size * Unsafe.SizeOf(), HeapType.Default) { }
///
/// Gets or sets a single value from the current read write buffer
///
/// The index of the value to get or set
/// This API can only be used from a compute shader, and will always throw if used anywhere else
public T this[uint i]
{
get => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
set => throw new InvalidOperationException("The indexer APIs can only be used from a compute shader");
}
///
public override void GetData(Span span)
{
using Buffer readbackBaffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Readback);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(this, 0, readbackBaffer, 0, SizeInBytes);
copyCommandList.Flush(true);
readbackBaffer.Map(0);
MemoryHelper.Copy(readbackBaffer.MappedResource, span);
readbackBaffer.Unmap(0);
}
///
public override void SetData(Span span)
{
using Buffer uploadBuffer = new Buffer(GraphicsDevice, Size, SizeInBytes, HeapType.Upload);
uploadBuffer.Map(0);
MemoryHelper.Copy(span, uploadBuffer.MappedResource);
uploadBuffer.Unmap(0);
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(uploadBuffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush(true);
}
///
public override void SetData(HlslBuffer buffer)
{
if (buffer is ReadOnlyBuffer readOnlyBuffer && !readOnlyBuffer.IsPaddingPresent)
{
// Directly copy the input buffer
using CommandList copyCommandList = new CommandList(GraphicsDevice, CommandListType.Copy);
copyCommandList.CopyBufferRegion(buffer, 0, this, 0, SizeInBytes);
copyCommandList.Flush(true);
}
else SetDataWithCpuBuffer(buffer);
}
}
}