namespace Brutal.VulkanApi.Abstractions;
///
/// Basic linear allocator/partitioner, allocates memory/partitions in a linear fashion
/// Very simple design, doesn't support freeing any space except for a full clear
/// Provides optional alignment for buffers that require a minimum alignment offset
///
public class LinearBufferPartitioner : IBufferPartitioner, ISize
{
///
/// Basic linear allocator/partitioner, allocates memory/partitions in a linear fashion
/// Very simple design, doesn't support freeing any space except for a full clear
/// Provides optional alignment for buffers that require a minimum alignment offset
///
public LinearBufferPartitioner(BufferPartitionInfo backingPartition, ByteSize alignment = default)
{
Alignment = alignment;
BackingPartition = backingPartition;
// Alignment of zero means "no alignment"; only validate the backing offset when one is set
if (Alignment > 0 && GetAlignedOffset(Alignment, backingPartition.BindOffset) != backingPartition.BindOffset)
throw new Exception("Invalid alignment of backing buffer partition");
}
///
/// Backing partition this partitioner is slicing up buffer portions of
///
public BufferPartitionInfo BackingPartition { get; set; }
///
/// Capacity of this partitioner
///
public ByteSize Capacity => BackingPartition.PartitionSize;
///
/// Current offset from the start of the backing partition
///
public ByteSize CurrentOffset { get; private set; }
///
/// Alignment of allocations: if zero, no alignment applied
///
public readonly ByteSize Alignment;
///
int ISize.Size => (int)Capacity;
///
/// Number of bytes remaining in the partitioner
///
public ByteSize FreeSpace => Capacity - CurrentOffset;
///
public bool TryCreatePartition(BufferPartitionInfo.CreateInfo info, out BufferPartitionInfo partition)
{
var size = Alignment > 0 ? GetAlignedOffset(Alignment, info.Size) : info.Size;
// Check we haven't exceeded the capacity of the partitioner
if (CurrentOffset + size > Capacity)
{
partition = default;
return false;
}
// Claim the space
var offset = CurrentOffset;
CurrentOffset += size;
// Create the partition info object
partition = new BufferPartitionInfo(
Partitioner: this,
BufferInfo: BackingPartition.BufferInfo,
PartitionOffset: offset + BackingPartition.PartitionOffset,
PartitionSize: size
);
return true;
}
///
public void Reset(BufferPartitionInfo info)
{
BackingPartition = info;
CurrentOffset = ByteSize.Zero;
}
///
/// Get an offset (or size of an object) fitting correct minimum memory alignment
///
/// Min Alignment
/// Required offset
/// Aligned offset
public static ByteSize GetAlignedOffset(ByteSize alignment, ByteSize offset)
{
return ByteSize.Of((offset + alignment - 1) & ~(alignment - 1));
}
}