This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
11 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,29 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Alignment helpers for <see cref="ByteSize"/>.
/// </summary>
public static class ByteSizeExtensions
{
/// <summary>
/// Round the value up to the next multiple of <paramref name="alignment"/>.
/// The alignment must be a power of two; an alignment of zero returns the value unchanged.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ByteSize AlignUp(this ByteSize value, ByteSize alignment)
{
if (alignment == 0)
return value;
return ByteSize.Of((value + alignment - 1) & ~(alignment - 1));
}
/// <summary>
/// True when the value is a multiple of <paramref name="alignment"/> (an alignment of zero always matches).
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsAlignedTo(this ByteSize value, ByteSize alignment)
{
return value.AlignUp(alignment) == value;
}
}

View file

@ -0,0 +1,273 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Scope handle returned by <see cref="CommandBufferExtensions.DebugScope"/>; ends the
/// debug label region on dispose.
/// </summary>
public readonly struct DebugLabelScope(CommandBuffer inCommandBuffer) : IDisposable
{
/// <inheritdoc />
public void Dispose()
{
inCommandBuffer.EndDebugLabel();
}
}
/// <summary>
/// Provides extension methods for recording Vulkan command buffer commands.
/// </summary>
public static class CommandBufferExtensions
{
/// <summary>
/// Resets the command buffer to its initial state using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkResetCommandBuffer.html">vkResetCommandBuffer</see>.
/// The command buffer must not be in a pending state and will be reset to the initial state.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to reset.</param>
public static void Reset(this CommandBuffer inCommandBuffer)
{
inCommandBuffer.Reset(VkCommandBufferResetFlags.None);
}
/// <summary>
/// Begins recording commands on the command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
public static void Begin(this CommandBuffer inCommandBuffer)
{
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = VkCommandBufferUsageFlags.None });
}
/// <summary>
/// Begins a Vulkan debug label region on the command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBeginDebugUtilsLabelEXT.html">vkCmdBeginDebugUtilsLabelEXT</see>.
/// This allows grouping commands within a labeled region for better debugging and profiling.
/// </summary>
/// <param name="inCommandBuffer">The Vulkan command buffer on which to begin the debug label.</param>
/// <param name="label">A read-only span of bytes representing the label name. The label should be null-terminated.</param>
/// <param name="color">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
public static unsafe void BeginDebugLabel(
this CommandBuffer inCommandBuffer,
in ReadOnlySpan<byte> label,
in float4 color
)
{
var vkLabel = new VkDebugUtilsLabelEXT { LabelName = label.AsPointer() };
vkLabel.Color[0] = color.R;
vkLabel.Color[1] = color.G;
vkLabel.Color[2] = color.B;
vkLabel.Color[3] = color.A;
inCommandBuffer.BeginDebugUtilsLabelEXT(vkLabel);
}
/// <summary>
/// Begins a Vulkan debug label region on the command buffer, encoding the label from a managed string.
/// Labels longer than 255 UTF-8 bytes are truncated at a character boundary. See
/// <see cref="BeginDebugLabel(CommandBuffer, in ReadOnlySpan{byte}, in float4)"/>.
/// </summary>
/// <param name="inCommandBuffer">The Vulkan command buffer on which to begin the debug label.</param>
/// <param name="inLabel">The label text.</param>
/// <param name="inColor">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
public static void BeginDebugLabel(this CommandBuffer inCommandBuffer, string inLabel, in float4 inColor = default)
{
Span<byte> bytes = stackalloc byte[MAX_DEBUG_LABEL_LENGTH];
// Encode as much as fits in the 255-byte budget (one byte reserved for the terminator).
// FromUtf16 stops at a character boundary when the destination runs out, so a truncated
// label is still valid UTF-8 rather than ending mid-character.
System.Text.Unicode.Utf8.FromUtf16(
inLabel,
bytes[..(MAX_DEBUG_LABEL_LENGTH - 1)],
out _,
out var written,
replaceInvalidSequences: true,
isFinalBlock: true
);
bytes[written] = 0;
BeginDebugLabel(inCommandBuffer, bytes[..(written + 1)], inColor);
}
private const int MAX_DEBUG_LABEL_LENGTH = 256;
/// <summary>
/// Begins a debug label region and returns a scope that ends it when disposed:
/// <c>using var _ = cmd.DebugScope("Shadow pass");</c>
/// </summary>
/// <param name="inCommandBuffer">The Vulkan command buffer to label.</param>
/// <param name="inLabel">The label text.</param>
/// <param name="inColor">A <see cref="float4"/> structure representing the RGBA color of the label.</param>
public static DebugLabelScope DebugScope(
this CommandBuffer inCommandBuffer,
string inLabel,
in float4 inColor = default
)
{
BeginDebugLabel(inCommandBuffer, inLabel, inColor);
return new DebugLabelScope(inCommandBuffer);
}
/// <summary>
/// Ends the current Vulkan debug label region on the command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdEndDebugUtilsLabelEXT.html">vkCmdEndDebugUtilsLabelEXT</see>.
/// This marks the end of a previously started debug label region, allowing Vulkan debugging tools to identify command groups.
/// </summary>
/// <param name="inCommandBuffer">The Vulkan command buffer on which to end the debug label.</param>
public static void EndDebugLabel(this CommandBuffer inCommandBuffer)
{
inCommandBuffer.EndDebugUtilsLabelEXT();
}
/// <summary>
/// Begins recording commands on the command buffer with specified usage flags using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
/// <param name="usage">The usage flags determining how the command buffer will be used.</param>
public static void Begin(this CommandBuffer inCommandBuffer, VkCommandBufferUsageFlags usage)
{
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = usage });
}
/// <summary>
/// Begins recording commands on the command buffer with specified usage flags and inheritance information
/// for secondary command buffers, using <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkBeginCommandBuffer.html">vkBeginCommandBuffer</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to begin recording.</param>
/// <param name="usage">The usage flags for the command buffer.</param>
/// <param name="inheritanceInfo">
/// For secondary command buffers, a pointer to a <c>VkCommandBufferInheritanceInfo</c> structure providing additional state;
/// ignored for primary command buffers.
/// </param>
public static void Begin(
this CommandBuffer inCommandBuffer,
VkCommandBufferUsageFlags usage,
VkCommandBufferInheritanceInfo inheritanceInfo
)
{
unsafe
{
inCommandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = usage, InheritanceInfo = &inheritanceInfo });
}
}
/// <summary>
/// Records a command to copy data between buffers using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdCopyBuffer.html">vkCmdCopyBuffer</see>.
/// Copies the specified region from the source buffer to the destination buffer.
/// </summary>
/// <param name="inCommandBuffer">The command buffer that will record the copy command.</param>
/// <param name="inSrcBuffer">The source buffer.</param>
/// <param name="inDstBuffer">The destination buffer.</param>
/// <param name="inRegion">A <c>VkBufferCopy</c> structure defining the region to copy.</param>
public static void CopyBuffer(
this CommandBuffer inCommandBuffer,
VkBuffer inSrcBuffer,
VkBuffer inDstBuffer,
VkBufferCopy inRegion
)
{
inCommandBuffer.CopyBuffer(inSrcBuffer, inDstBuffer, [inRegion]);
}
/// <summary>
/// Records a command to copy a specified number of bytes from the source buffer to the destination buffer.
/// This is a convenience overload that assumes zero offsets.
/// </summary>
/// <param name="inCommandBuffer">The command buffer that will record the copy command.</param>
/// <param name="inSrcBuffer">The source buffer.</param>
/// <param name="inDstBuffer">The destination buffer.</param>
/// <param name="inSize">The number of bytes to copy from the start of the buffers.</param>
public static void CopyBuffer(
this CommandBuffer inCommandBuffer,
VkBuffer inSrcBuffer,
VkBuffer inDstBuffer,
ByteSize inSize
)
{
CopyBuffer(
inCommandBuffer,
inSrcBuffer,
inDstBuffer,
new VkBufferCopy
{
Size = inSize,
DstOffset = ByteSize.Zero,
SrcOffset = ByteSize.Zero,
}
);
}
/// <summary>
/// Binds a vertex buffer to the command buffer at the specified binding index using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindVertexBuffers.html">vkCmdBindVertexBuffers</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to record the binding command.</param>
/// <param name="inBinding">The vertex input binding index to update.</param>
/// <param name="inBuffer">The vertex buffer to bind.</param>
/// <param name="inOffset">The offset (in bytes) within the buffer to start binding from. Defaults to 0.</param>
public static void BindVertexBuffer(
this CommandBuffer inCommandBuffer,
int inBinding,
VkBuffer inBuffer,
ByteSize inOffset = default
)
{
inCommandBuffer.BindVertexBuffers(inBinding, [inBuffer], [inOffset]);
}
/// <summary>
/// Records a command to update a push constant value of type <typeparamref name="T"/> in the command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdPushConstants.html">vkCmdPushConstants</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to record the push constant update.</param>
/// <param name="inLayout">The pipeline layout that defines the push constant ranges.</param>
/// <param name="inStageFlags">A bitmask of <c>VkShaderStageFlags</c> indicating which shader stages will access the push constant.</param>
/// <param name="inOffset">The byte offset within the push constant range at which to start updating.</param>
/// <param name="inData">The push constant value to update.</param>
public static void PushConstants<T>(
this CommandBuffer inCommandBuffer,
VkPipelineLayout inLayout,
VkShaderStageFlags inStageFlags,
ByteSize inOffset,
T inData
)
where T : unmanaged
{
inCommandBuffer.PushConstants(inLayout, inStageFlags, inOffset, [inData]);
}
/// <summary>
/// Records a command to update a sequence of push constants of type <typeparamref name="T"/> in the command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdPushConstants.html">vkCmdPushConstants</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to record the push constant update.</param>
/// <param name="inLayout">The pipeline layout that defines the push constant ranges.</param>
/// <param name="inStageFlags">A bitmask of <c>VkShaderStageFlags</c> indicating which shader stages will access the push constants.</param>
/// <param name="inOffset">The byte offset within the push constant range at which to start updating.</param>
/// <param name="inData">A span containing the push constant values to update.</param>
public static void PushConstants<T>(
this CommandBuffer inCommandBuffer,
VkPipelineLayout inLayout,
VkShaderStageFlags inStageFlags,
ByteSize inOffset,
ReadOnlySpan<T> inData
)
where T : unmanaged
{
unsafe
{
fixed (T* ptr = inData)
{
inCommandBuffer.PInvoke.vkCmdPushConstants.Invoke(
inCommandBuffer.Handle,
inLayout,
inStageFlags,
(int)inOffset,
(int)ByteSize.Of<T>(inData.Length),
ptr
);
}
}
}
}

View file

@ -0,0 +1,694 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Functions to extend the Device class
/// </summary>
public static class DeviceExtensions
{
/// <summary>
/// Creates a default render pass configured for common rendering scenarios. This method sets up attachments for color,
/// depth, and, if multisampling is enabled, resolve operations, and configures the corresponding subpass dependencies.
/// </summary>
/// <param name="inDevice">The logical device used for creating the render pass.</param>
/// <param name="sampleColor">If true, a color attachment is created and sampled; otherwise, no color attachment is configured.</param>
/// <param name="sampleDepth">If true, a depth attachment is created and sampled; otherwise, no depth attachment is configured.</param>
/// <param name="sampleCount">Specifies the number of samples per pixel. A value other than <c>VkSampleCountFlags._1</c> indicates that multisampling is enabled.</param>
/// <param name="colorFormat">The format to be used for the color attachment image.</param>
/// <param name="depthFormat">The format to be used for the depth attachment image.</param>
/// <param name="resolvedFormat">The format to be used for the resolve attachment image when multisampling is enabled.</param>
/// <returns>A <c>VkRenderPass</c> object representing the configured render pass.</returns>
public static unsafe VkRenderPass CreateDefaultRenderPass(
this Device inDevice,
bool sampleColor,
bool sampleDepth,
VkSampleCountFlags sampleCount,
VkFormat colorFormat,
VkFormat depthFormat,
VkFormat resolvedFormat,
VkAllocator? allocator
)
{
var multisamplingEnabled = sampleCount != VkSampleCountFlags._1Bit;
VkAttachmentDescription? colorAttachment = null;
VkAttachmentDescription? depthAttachment = null;
VkAttachmentDescription? resolveAttachment = null;
// Describe the color attachment
if (sampleColor)
{
var storeOp = VkAttachmentStoreOp.DontCare;
var finalLayout = VkImageLayout.ShaderReadOnlyOptimal;
if (multisamplingEnabled)
{
storeOp = VkAttachmentStoreOp.DontCare;
finalLayout = VkImageLayout.ColorAttachmentOptimal;
}
colorAttachment = new VkAttachmentDescription
{
Format = colorFormat,
Samples = sampleCount,
LoadOp = VkAttachmentLoadOp.Clear,
StoreOp = storeOp,
StencilLoadOp = VkAttachmentLoadOp.DontCare,
StencilStoreOp = VkAttachmentStoreOp.DontCare,
InitialLayout = VkImageLayout.Undefined,
FinalLayout = finalLayout,
};
}
// Describe the depth attachment
if (sampleDepth)
{
depthAttachment = new VkAttachmentDescription
{
Format = depthFormat,
Samples = sampleCount,
LoadOp = VkAttachmentLoadOp.Clear,
StoreOp = VkAttachmentStoreOp.Store,
StencilLoadOp = VkAttachmentLoadOp.DontCare,
StencilStoreOp = VkAttachmentStoreOp.DontCare,
InitialLayout = VkImageLayout.Undefined,
FinalLayout = VkImageLayout.DepthStencilReadOnlyOptimal,
};
}
// Describe the Multisample-to-singlesample color resolve attachments
if (multisamplingEnabled)
{
// Resolve color attachment
if (sampleColor)
{
resolveAttachment = new VkAttachmentDescription
{
Format = resolvedFormat,
Samples = VkSampleCountFlags._1Bit,
LoadOp = VkAttachmentLoadOp.DontCare,
StoreOp = VkAttachmentStoreOp.Store,
StencilLoadOp = VkAttachmentLoadOp.DontCare,
StencilStoreOp = VkAttachmentStoreOp.DontCare,
InitialLayout = VkImageLayout.Undefined,
FinalLayout = VkImageLayout.ShaderReadOnlyOptimal,
};
}
// Resolve depth attachment
if (sampleDepth)
{
// (Not yet implemented)
}
}
// Pack the enabled attachments and record the index each one lands at
var attachments = stackalloc VkAttachmentDescription[3];
var attachmentCount = 0;
var colorIndex = -1;
var depthIndex = -1;
var resolveIndex = -1;
if (colorAttachment.HasValue)
{
colorIndex = attachmentCount;
attachments[attachmentCount++] = colorAttachment.Value;
}
if (depthAttachment.HasValue)
{
depthIndex = attachmentCount;
attachments[attachmentCount++] = depthAttachment.Value;
}
if (resolveAttachment.HasValue)
{
resolveIndex = attachmentCount;
attachments[attachmentCount++] = resolveAttachment.Value;
}
// Describe the attachment references
var references =
stackalloc VkAttachmentReference[3] {
new VkAttachmentReference { Attachment = colorIndex, Layout = VkImageLayout.ColorAttachmentOptimal },
new VkAttachmentReference
{
Attachment = depthIndex,
Layout = VkImageLayout.DepthStencilAttachmentOptimal,
},
new VkAttachmentReference { Attachment = resolveIndex, Layout = VkImageLayout.ColorAttachmentOptimal },
};
// Create a subpass
var subpass = new VkSubpassDescription { PipelineBindPoint = VkPipelineBindPoint.Graphics };
if (colorIndex >= 0)
{
subpass.ColorAttachmentCount = 1;
subpass.ColorAttachments = &references[0];
}
if (depthIndex >= 0)
{
subpass.DepthStencilAttachment = &references[1];
}
if (resolveIndex >= 0)
{
subpass.ResolveAttachments = &references[2];
}
// Create subpass dependencies determined by whether multisampling is enabled or not
VkSubpassDependency renderSubpass;
VkSubpassDependency? resolveSubpass = null;
if (multisamplingEnabled)
{
renderSubpass = new VkSubpassDependency
{
SrcSubpass = VK.SUBPASS_EXTERNAL,
DstSubpass = 0,
SrcStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
DstStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
SrcAccessMask = VkAccessFlags.None,
DstAccessMask = VkAccessFlags.ColorAttachmentWriteBit | VkAccessFlags.ColorAttachmentReadBit,
DependencyFlags = VkDependencyFlags.None,
};
resolveSubpass = new VkSubpassDependency
{
SrcSubpass = VK.SUBPASS_EXTERNAL,
DstSubpass = 0,
SrcStageMask = VkPipelineStageFlags.EarlyFragmentTestsBit | VkPipelineStageFlags.LateFragmentTestsBit,
DstStageMask = VkPipelineStageFlags.EarlyFragmentTestsBit | VkPipelineStageFlags.LateFragmentTestsBit,
SrcAccessMask = VkAccessFlags.DepthStencilAttachmentWriteBit,
DstAccessMask =
VkAccessFlags.DepthStencilAttachmentWriteBit | VkAccessFlags.DepthStencilAttachmentReadBit,
DependencyFlags = VkDependencyFlags.None,
};
}
else
{
renderSubpass = new VkSubpassDependency
{
SrcSubpass = VK.SUBPASS_EXTERNAL,
DstSubpass = 0,
SrcStageMask =
VkPipelineStageFlags.ColorAttachmentOutputBit | VkPipelineStageFlags.LateFragmentTestsBit,
DstStageMask =
VkPipelineStageFlags.ColorAttachmentOutputBit | VkPipelineStageFlags.EarlyFragmentTestsBit,
SrcAccessMask = VkAccessFlags.DepthStencilAttachmentWriteBit,
DstAccessMask = VkAccessFlags.ColorAttachmentWriteBit | VkAccessFlags.DepthStencilAttachmentWriteBit,
DependencyFlags = VkDependencyFlags.None,
};
}
// Build the dependency array we'll be passing to the render pass creation
var dependencies = stackalloc VkSubpassDependency[2];
Span<VkSubpassDescription> subpasses = [subpass];
var dependencyCount = 0;
dependencies[dependencyCount++] = renderSubpass;
if (resolveSubpass.HasValue)
dependencies[dependencyCount++] = resolveSubpass.Value;
return inDevice.CreateRenderPass(
new VkRenderPassCreateInfo
{
Flags = 0,
AttachmentCount = attachmentCount,
Attachments = attachments,
SubpassCount = subpasses.Length,
Subpasses = subpasses.AsPointer(),
DependencyCount = dependencyCount,
Dependencies = dependencies,
},
allocator
);
}
/// <summary>
/// Creates a new pipeline layout object using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreatePipelineLayout.html">vkCreatePipelineLayout</see>.
/// </summary>
/// <param name="inDevice">The logical device used to create the pipeline layout.</param>
/// <param name="setLayouts">
/// A span of <see cref="VkDescriptorSetLayout"/> handles that define the descriptor set layouts to be used in the pipeline layout.
/// </param>
/// <param name="pushConstantRanges">
/// A span of <see cref="VkPushConstantRange"/> structures specifying the push constant ranges for the pipeline layout.
/// </param>
/// <returns>A <c>VkPipelineLayout</c> object representing the created pipeline layout.</returns>
public static VkPipelineLayout CreatePipelineLayout(
this Device inDevice,
ReadOnlySpan<VkDescriptorSetLayout> setLayouts,
ReadOnlySpan<VkPushConstantRange> pushConstantRanges,
VkAllocator? allocator
)
{
unsafe
{
fixed (VkDescriptorSetLayout* p1 = setLayouts)
fixed (VkPushConstantRange* p2 = pushConstantRanges)
return inDevice.CreatePipelineLayout(
new VkPipelineLayoutCreateInfo
{
SetLayouts = p1,
PushConstantRanges = p2,
SetLayoutCount = setLayouts.Length,
PushConstantRangeCount = pushConstantRanges.Length,
},
allocator
);
}
}
/// <summary>
/// Creates a graphics pipeline using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateGraphicsPipelines.html">vkCreateGraphicsPipelines</see>.
/// </summary>
/// <param name="inDevice">The logical device used for creating the graphics pipeline.</param>
/// <param name="inPipelineCache">
/// A pipeline cache handle. Use <c>VK_NULL_HANDLE</c> if pipeline caching is disabled; otherwise, provide the handle of a valid
/// pipeline cache object to enable caching during pipeline creation.
/// </param>
/// <param name="inCreateInfo">
/// A <see cref="VkGraphicsPipelineCreateInfo"/> structure containing the parameters required to create the graphics pipeline.
/// </param>
/// <returns>A <c>VkPipeline</c> object representing the created graphics pipeline.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe VkPipeline CreateGraphicsPipeline(
this Device inDevice,
VkPipelineCache inPipelineCache,
VkGraphicsPipelineCreateInfo inCreateInfo,
VkAllocator? allocator
)
{
VkPipeline pipeline = new();
inDevice.CreateGraphicsPipelines(
inPipelineCache,
[inCreateInfo],
allocator,
new ReadOnlySpan<VkPipeline>(&pipeline, 1)
);
return pipeline;
}
/// <summary>
/// Creates a compute pipeline using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateComputePipelines.html">vkCreateComputePipelines</see>.
/// </summary>
/// <param name="inDevice">The logical device used for creating the compute pipeline.</param>
/// <param name="inPipelineCache">
/// A pipeline cache handle. Use <c>VK_NULL_HANDLE</c> if pipeline caching is disabled; otherwise, provide the handle of a valid
/// pipeline cache object to enable caching during pipeline creation.
/// </param>
/// <param name="inCreateInfo">
/// A <see cref="VkComputePipelineCreateInfo"/> structure containing the parameters required to create the compute pipeline.
/// </param>
/// <returns>A <c>VkPipeline</c> object representing the created compute pipeline.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe VkPipeline CreateComputePipeline(
this Device inDevice,
VkPipelineCache inPipelineCache,
VkComputePipelineCreateInfo inCreateInfo,
VkAllocator? allocator
)
{
VkPipeline pipeline = new();
inDevice.CreateComputePipelines(
inPipelineCache,
[inCreateInfo],
allocator,
new ReadOnlySpan<VkPipeline>(&pipeline, 1)
);
return pipeline;
}
/// <summary>
/// Query a buffer's GPU virtual address using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkGetBufferDeviceAddress.html">vkGetBufferDeviceAddress</see>.
/// The buffer must have been created with <see cref="VkBufferUsageFlags.ShaderDeviceAddressBit"/> and its memory
/// allocated with <see cref="VkMemoryAllocateFlags.DeviceAddressBit"/>.
/// </summary>
/// <param name="inDevice">The logical device that owns the buffer.</param>
/// <param name="inBuffer">The buffer to query.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VkDeviceAddress GetBufferDeviceAddress(this Device inDevice, VkBuffer inBuffer)
{
return inDevice.GetBufferDeviceAddress(new VkBufferDeviceAddressInfo { Buffer = inBuffer });
}
/// <summary>
/// Allocates a single command buffer from the specified command pool using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateCommandBuffers.html">vkAllocateCommandBuffers</see>.
/// </summary>
/// <param name="device">The logical device that owns the command pool.</param>
/// <param name="createInfo">A <see cref="VkCommandBufferAllocateInfo"/> structure specifying the command pool and allocation parameters.</param>
/// <returns>A <c>CommandBuffer</c> object representing the allocated command buffer.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe CommandBuffer AllocateCommandBuffer(this Device device, VkCommandBufferAllocateInfo createInfo)
{
Span<VkCommandBuffer> commandBufferHandles = stackalloc VkCommandBuffer[1];
createInfo.CommandBufferCount = 1;
device.AllocateCommandBuffersInternal(createInfo, commandBufferHandles);
return new CommandBuffer(device, commandBufferHandles[0]);
}
/// <summary>
/// Allocates multiple command buffers from the specified command pool using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateCommandBuffers.html">vkAllocateCommandBuffers</see>.
/// </summary>
/// <param name="device">The logical device that owns the command pool.</param>
/// <param name="createInfo">A <see cref="VkCommandBufferAllocateInfo"/> structure specifying the command pool and allocation parameters.</param>
/// <param name="commandBuffers">A span of <see cref="CommandBuffer"/> to store the allocated command buffers.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void AllocateCommandBuffers(
this Device device,
VkCommandBufferAllocateInfo createInfo,
Span<CommandBuffer> commandBuffers
)
{
if (commandBuffers.Length == 0)
throw new ArgumentException("The command buffer span must not be empty.", nameof(commandBuffers));
Span<VkCommandBuffer> commandBufferHandles = stackalloc VkCommandBuffer[commandBuffers.Length];
createInfo.CommandBufferCount = commandBuffers.Length;
device.AllocateCommandBuffersInternal(createInfo, commandBufferHandles);
for (var i = 0; i < commandBuffers.Length; i++)
commandBuffers[i] = new CommandBuffer(device, commandBufferHandles[i]);
}
/// <summary>
/// Allocates device memory for a buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateMemory.html">vkAllocateMemory</see>.
/// It queries the memory requirements of the specified buffer and selects an appropriate memory type that matches the required properties.
/// </summary>
/// <param name="inDevice">The logical device that owns the memory.</param>
/// <param name="inPhysicalDevice">The physical device used to determine a compatible memory type.</param>
/// <param name="inBuffer">The buffer for which memory is to be allocated.</param>
/// <param name="inRequiredProperties">The required memory property flags that the allocated memory must satisfy.</param>
/// <returns>A <c>VkDeviceMemory</c> object representing the allocated memory for the buffer.</returns>
public static VkDeviceMemory AllocateMemory(
this Device inDevice,
PhysicalDevice inPhysicalDevice,
VkBuffer inBuffer,
VkMemoryPropertyFlags inRequiredProperties,
VkAllocator? allocator
)
{
// Check the memory requirements for the vertex buffer
var bufferMemoryRequirements = inDevice.GetBufferMemoryRequirements(inBuffer);
var bufferMemoryTypeIndex = inPhysicalDevice.FindMemoryType(
bufferMemoryRequirements.MemoryTypeBits,
inRequiredProperties
);
// Allocate memory for the vertex buffer
var memory = inDevice.AllocateMemory(
new VkMemoryAllocateInfo
{
AllocationSize = bufferMemoryRequirements.Size,
MemoryTypeIndex = bufferMemoryTypeIndex,
},
allocator
);
return memory;
}
/// <summary>
/// Allocates device memory for an image using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkAllocateMemory.html">vkAllocateMemory</see>.
/// It queries the memory requirements of the specified image and selects an appropriate memory type that meets the required properties.
/// </summary>
/// <param name="inDevice">The logical device that owns the memory.</param>
/// <param name="inPhysicalDevice">The physical device used to determine a compatible memory type.</param>
/// <param name="inImage">The image for which memory is to be allocated.</param>
/// <param name="inRequiredProperties">The required memory property flags that the allocated memory must satisfy.</param>
/// <returns>A <c>VkDeviceMemory</c> object representing the allocated memory for the image.</returns>
public static VkDeviceMemory AllocateMemory(
this Device inDevice,
PhysicalDevice inPhysicalDevice,
VkImage inImage,
VkMemoryPropertyFlags inRequiredProperties,
VkAllocator? allocator
)
{
// Check the memory requirements for the vertex buffer
var bufferMemoryRequirements = inDevice.GetImageMemoryRequirements(inImage);
var bufferMemoryTypeIndex = inPhysicalDevice.FindMemoryType(
bufferMemoryRequirements.MemoryTypeBits,
inRequiredProperties
);
// Allocate memory for the vertex buffer
var memory = inDevice.AllocateMemory(
new VkMemoryAllocateInfo
{
AllocationSize = bufferMemoryRequirements.Size,
MemoryTypeIndex = bufferMemoryTypeIndex,
},
allocator
);
return memory;
}
/// <summary>
/// Maps device memory to a pointer of type T using vkMapMemory.
/// </summary>
/// <param name="inDevice">The logical device that owns the memory.</param>
/// <param name="mapInfo">A <see cref="MapInfo"/> structure specifying the memory range to map.</param>
/// <returns>A pointer to the mapped memory cast to type T.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Ptr<T> MapMemory<T>(this Device inDevice, in MapInfo mapInfo)
where T : unmanaged
{
return inDevice.MapMemory(mapInfo).Cast<T>();
}
/// <summary>
/// Maps device memory to a pointer of type T using vkMapMemory.
/// </summary>
/// <param name="inDevice">The logical device that owns the memory.</param>
/// <param name="mapInfo">A <see cref="MapInfo"/> structure specifying the memory range to map.</param>
/// <returns>A pointer to the mapped memory cast to type T.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe Ptr MapMemory(this Device inDevice, in MapInfo mapInfo)
{
if (mapInfo.Region.Size < 1 && mapInfo.Region.Size != VK.WHOLE_SIZE)
throw new ArgumentOutOfRangeException(
nameof(mapInfo.Region.Size),
"The size of the memory region must be greater than zero, or VK.WHOLE_SIZE."
);
var ptr = inDevice.MapMemory(mapInfo.Memory, mapInfo.Region.Offset, mapInfo.Region.Size, mapInfo.Flags);
return ptr;
}
/// <summary>
/// Writes data from a span to device memory. This method maps the specified memory, copies the data from the source span,
/// and then unmaps the memory.
/// </summary>
/// <typeparam name="T">The type of elements in the source span.</typeparam>
/// <param name="inDevice">The logical device that owns the destination memory.</param>
/// <param name="inSrc">The source span containing the data to write.</param>
/// <param name="inDstMemory">The <c>VkDeviceMemory</c> object that will receive the data.</param>
/// <param name="inOffset">The zero-based byte offset from the beginning of the memory object at which to start writing.</param>
/// <param name="inFlags">Reserved for future use; typically set to <c>VkMemoryMapFlags.None</c>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void WriteMemory<T>(
this Device inDevice,
Span<T> inSrc,
VkDeviceMemory inDstMemory,
ByteSize inOffset = default,
VkMemoryMapFlags inFlags = VkMemoryMapFlags.None
)
where T : unmanaged
{
Ptr ptr = inDevice.MapMemory(inDstMemory, inOffset, ByteSize.Of(inSrc), inFlags);
Mem.Copy(inSrc, ptr.AsSpan<T>(inSrc.Length));
inDevice.UnmapMemory(inDstMemory);
}
/// <summary>
/// Writes data from an array to device memory. This method maps the specified memory, copies the data from the source array,
/// and then unmaps the memory.
/// </summary>
/// <typeparam name="T">The type of elements in the source array.</typeparam>
/// <param name="inDevice">The logical device that owns the destination memory.</param>
/// <param name="inSrc">The source array containing the data to write.</param>
/// <param name="inDstMemory">The <c>VkDeviceMemory</c> object that will receive the data.</param>
/// <param name="inOffset">The zero-based byte offset from the beginning of the memory object at which to start writing.</param>
/// <param name="inFlags">Reserved for future use; typically set to <c>VkMemoryMapFlags.None</c>.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void WriteMemory<T>(
this Device inDevice,
ReadOnlySpan<T> inSrc,
VkDeviceMemory inDstMemory,
ByteSize inOffset = default,
VkMemoryMapFlags inFlags = VkMemoryMapFlags.None
)
where T : unmanaged
{
Ptr ptr = inDevice.MapMemory(inDstMemory, inOffset, ByteSize.Of(inSrc), inFlags);
Mem.Copy(inSrc, ptr.AsSpan<T>(inSrc.Length));
inDevice.UnmapMemory(inDstMemory);
}
/// <summary>
/// Binds a descriptor set to a command buffer using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindDescriptorSets.html">vkCmdBindDescriptorSets</see>.
/// An optional dynamic offset can be provided.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to which the descriptor set will be bound.</param>
/// <param name="inPipelineBindPoint">
/// The pipeline bind point indicating the type of pipeline that will use the descriptor set. Binding at a specific bind point
/// does not disturb descriptor sets bound at other bind points.
/// </param>
/// <param name="inLayout">The pipeline layout that defines the descriptor set bindings.</param>
/// <param name="inSet">The index of the descriptor set to bind.</param>
/// <param name="inDescriptorSet">The descriptor set to be bound to the command buffer.</param>
/// <param name="inDynamicOffsets">
/// Span of dynamic offsets to be used with the descriptor set. If no dynamic offsets are needed, pass an empty span.
/// </param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void BindDescriptorSet(
this CommandBuffer inCommandBuffer,
VkPipelineBindPoint inPipelineBindPoint,
VkPipelineLayout inLayout,
int inSet,
VkDescriptorSet inDescriptorSet,
Span<ByteSize32> inDynamicOffsets
)
{
inCommandBuffer.BindDescriptorSets(inPipelineBindPoint, inLayout, inSet, [inDescriptorSet], inDynamicOffsets);
}
/// <summary>
/// Binds any <see cref="IDescriptorSetWrapper"/>'s set (and its dynamic offsets, if it declares any)
/// to a command buffer. See
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdBindDescriptorSets.html">vkCmdBindDescriptorSets</see>.
/// </summary>
/// <param name="inCommandBuffer">The command buffer to which the descriptor set will be bound.</param>
/// <param name="inPipelineBindPoint">The pipeline bind point the set is consumed at.</param>
/// <param name="inLayout">The pipeline layout that defines the descriptor set bindings.</param>
/// <param name="inSet">The index of the descriptor set to bind.</param>
/// <param name="inDescriptorSetWrapper">The wrapper whose set and dynamic offsets are bound.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void BindDescriptorSet(
this CommandBuffer inCommandBuffer,
VkPipelineBindPoint inPipelineBindPoint,
VkPipelineLayout inLayout,
int inSet,
IDescriptorSetWrapper inDescriptorSetWrapper
)
{
var descriptorSet = inDescriptorSetWrapper.DescriptorSet;
var dynamicOffsets = inDescriptorSetWrapper.DynamicOffsets;
// Pinned raw call: the offsets are read-only, but the generated BindDescriptorSets wrapper
// currently demands a mutable span even though vkCmdBindDescriptorSets takes a const pointer
fixed (ByteSize32* dynamicOffsetsPtr = dynamicOffsets)
{
inCommandBuffer.PInvoke.vkCmdBindDescriptorSets.Invoke(
inCommandBuffer.Handle,
inPipelineBindPoint,
inLayout,
inSet,
1,
&descriptorSet,
dynamicOffsets.Length,
(int*)dynamicOffsetsPtr
);
}
}
/// <summary>
/// Creates a new fence object using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCreateFence.html">vkCreateFence</see>.
/// </summary>
/// <param name="inDevice">The logical device that creates the fence.</param>
/// <param name="inCreateFlags">
/// Flags that control the creation and initial state of the fence. See <see cref="VkFenceCreateFlags"/> for details.
/// </param>
/// <returns>A <c>VkFence</c> object representing the created fence.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VkFence CreateFence(this Device inDevice, VkFenceCreateFlags inCreateFlags, VkAllocator? allocator)
{
return inDevice.CreateFence(new VkFenceCreateInfo { Flags = inCreateFlags }, allocator);
}
/// <summary>
/// Waits for a fence to become signaled using
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkWaitForFences.html">vkWaitForFences</see>.
/// The timeout value is adjusted to the closest allowed value by the implementation.
/// </summary>
/// <param name="inDevice">The logical device that owns the fence.</param>
/// <param name="inFence">The fence to wait on.</param>
/// <param name="inTimeout">
/// The timeout period in nanoseconds. The actual timeout may be longer than requested due to implementation-dependent timeout accuracy.
/// </param>
/// <returns>A <c>VkResult</c> indicating the outcome of the wait operation.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VkResult WaitForFence(this Device inDevice, VkFence inFence, nint inTimeout)
{
return inDevice.WaitForFences([inFence], true, inTimeout);
}
/// <summary>
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkFreeCommandBuffers.html">vkFreeCommandBuffers</see> - Free command buffers
/// </summary>
/// <remarks>
/// <para>
/// To free command buffers, call:
/// </para>
/// <code>
/// // Provided by VK_VERSION_1_0
/// void vkFreeCommandBuffers(
/// VkDevice device,
/// VkCommandPool commandPool,
/// uint32_t commandBufferCount,
/// const VkCommandBuffer* pCommandBuffers);
/// </code>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void FreeCommandBuffers(
this VulkanHandleWrapper<VkDevice, VkDevice.FunctionTable> handle,
VkCommandPool commandPool,
ReadOnlySpan<CommandBuffer> pCommandBuffers
)
{
Span<VkCommandBuffer> vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length];
for (var index = 0; index < pCommandBuffers.Length; index++)
vkCommandBuffers[index] = pCommandBuffers[index].Handle;
handle.FreeCommandBuffersInternal(commandPool, vkCommandBuffers);
}
/// <summary>
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/vkCmdExecuteCommands.html">vkCmdExecuteCommands</see> - Execute a secondary command buffer from a primary command buffer
/// </summary>
/// <remarks>
/// <para>
/// Secondary command buffers <i>must</i> not be directly submitted to a queue.
/// To record a secondary command buffer to execute as part of a primary command
/// buffer, call:
/// </para>
/// <code>
/// // Provided by VK_VERSION_1_0
/// void vkCmdExecuteCommands(
/// VkCommandBuffer commandBuffer,
/// uint32_t commandBufferCount,
/// const VkCommandBuffer* pCommandBuffers);
/// </code>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ExecuteCommands(
this VulkanHandleWrapper<VkCommandBuffer, VkDevice.FunctionTable> handle,
ReadOnlySpan<CommandBuffer> pCommandBuffers
)
{
Span<VkCommandBuffer> vkCommandBuffers = stackalloc VkCommandBuffer[pCommandBuffers.Length];
for (var index = 0; index < pCommandBuffers.Length; index++)
vkCommandBuffers[index] = pCommandBuffers[index].Handle;
handle.CmdExecuteCommandsInternal(vkCommandBuffers);
}
}

View file

@ -0,0 +1,45 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Provides extension methods for IDisposable objects.
/// </summary>
public static class DisposableExtensions
{
/// <summary>
/// Disposes each element in the provided span.
/// </summary>
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
/// <param name="inObjects">The span of IDisposable objects to dispose.</param>
public static void Dispose<T>(this Span<T> inObjects)
where T : IDisposable
{
foreach (var obj in inObjects)
obj.Dispose();
}
/// <summary>
/// Disposes each element in the provided array.
/// </summary>
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
/// <param name="inObjects">The array of IDisposable objects to dispose.</param>
public static void Dispose<T>(this T[] inObjects)
where T : IDisposable
{
foreach (var obj in inObjects)
obj.Dispose();
}
/// <summary>
/// Disposes each element in the provided enumerable collection.
/// </summary>
/// <typeparam name="T">The type of IDisposable objects.</typeparam>
/// <param name="inObjects">The enumerable collection of IDisposable objects to dispose.</param>
public static void Destroy<T>(this IEnumerable<T> inObjects)
where T : IDisposable
{
using var enumerator = inObjects.GetEnumerator();
while (enumerator.MoveNext())
enumerator.Current.Dispose();
}
}

View file

@ -0,0 +1,56 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Classification helpers for <see cref="VkFormat"/>.
/// </summary>
public static class FormatExtensions
{
/// <summary>
/// True when the format has a depth component (including packed depth-stencil formats).
/// </summary>
public static bool IsDepthFormat(this VkFormat format) =>
format switch
{
VkFormat.D16UNorm
or VkFormat.X8D24UNormPack32
or VkFormat.D32SFloat
or VkFormat.D16UNormS8UInt
or VkFormat.D24UNormS8UInt
or VkFormat.D32SFloatS8UInt => true,
_ => false,
};
/// <summary>
/// True when the format has a stencil component (including packed depth-stencil formats).
/// </summary>
public static bool IsStencilFormat(this VkFormat format) =>
format switch
{
VkFormat.S8UInt or VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt => true,
_ => false,
};
/// <summary>
/// True when the format has both a depth and a stencil component.
/// </summary>
public static bool IsDepthStencilFormat(this VkFormat format) =>
format switch
{
VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt => true,
_ => false,
};
/// <summary>
/// The full aspect mask implied by the format: depth and/or stencil bits for depth-stencil
/// formats, otherwise <see cref="VkImageAspectFlags.ColorBit"/>.
/// </summary>
public static VkImageAspectFlags GetAspectMask(this VkFormat format) =>
format switch
{
VkFormat.D16UNormS8UInt or VkFormat.D24UNormS8UInt or VkFormat.D32SFloatS8UInt =>
VkImageAspectFlags.DepthBit | VkImageAspectFlags.StencilBit,
VkFormat.S8UInt => VkImageAspectFlags.StencilBit,
VkFormat.D16UNorm or VkFormat.X8D24UNormPack32 or VkFormat.D32SFloat => VkImageAspectFlags.DepthBit,
_ => VkImageAspectFlags.ColorBit,
};
}

View file

@ -0,0 +1,6 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Provides extension methods for managing a Vulkan instance
/// </summary>
public static class InstanceExtensions { }

View file

@ -0,0 +1,22 @@
using System.Diagnostics;
namespace Brutal.VulkanApi.Abstractions;
[DebuggerDisplay("Offset: {Offset}, Size: {Size}")]
public struct MapRegion()
{
public ByteSize Offset { get; init; } = ByteSize.Zero;
public ByteSize Size { get; init; } = VK.WHOLE_SIZE;
}
/// <summary>
/// Information required to map a memory region.
/// </summary>
public readonly struct MapInfo(VkDeviceMemory memory)
{
public readonly VkDeviceMemory Memory = memory;
public MapRegion Region { get; init; } = new();
public VkMemoryMapFlags Flags { get; init; } = VkMemoryMapFlags.None;
public static implicit operator MapInfo(VkDeviceMemory memory) => new(memory);
}

View file

@ -0,0 +1,81 @@
using System.Numerics;
namespace Brutal.VulkanApi.Abstractions;
public static class PhysicalDeviceExtensions
{
public static DeviceEx CreateDevice(this PhysicalDevice physicalDevice, DeviceEx.CreateInfo createInfo)
{
return new DeviceEx(physicalDevice, createInfo);
}
/// <summary>
/// Return the first format from <paramref name="candidates"/> that supports all of
/// <paramref name="features"/> under the given tiling, or <see cref="VkFormat.Undefined"/>
/// when none qualifies. Typical use: picking a supported depth(-stencil) format.
/// </summary>
public static VkFormat FindSupportedFormat(
this PhysicalDevice physicalDevice,
ReadOnlySpan<VkFormat> candidates,
VkImageTiling tiling,
VkFormatFeatureFlags features
)
{
foreach (var format in candidates)
{
var properties = physicalDevice.GetFormatProperties(format);
var supported = tiling switch
{
VkImageTiling.Optimal => properties.OptimalTilingFeatures,
VkImageTiling.Linear => properties.LinearTilingFeatures,
_ => VkFormatFeatureFlags.None,
};
if ((supported & features) == features)
return format;
}
return VkFormat.Undefined;
}
/// <summary>
/// Find the queue family that has all of <paramref name="requiredFlags"/>, none of
/// <paramref name="excludedFlags"/>, and the fewest extra capabilities - so a dedicated
/// family (e.g. transfer-only, or compute without graphics) wins over the do-everything
/// family when one exists. Returns -1 when no family qualifies.
/// </summary>
public static int FindQueueFamily(
this PhysicalDevice physicalDevice,
VkQueueFlags requiredFlags,
VkQueueFlags excludedFlags = VkQueueFlags.None
)
{
using var properties = SpanOwner<VkQueueFamilyProperties>.Allocate(
physicalDevice.GetQueueFamilyProperties_Count()
);
physicalDevice.GetQueueFamilyProperties_Write(properties.Span);
var bestFamily = -1;
var bestExtraFlags = int.MaxValue;
for (var i = 0; i < properties.Length; ++i)
{
var flags = properties.Span[i].QueueFlags;
if ((flags & requiredFlags) != requiredFlags)
continue;
if ((flags & excludedFlags) != 0)
continue;
var extraFlags = BitOperations.PopCount(unchecked((uint)(int)(flags & ~requiredFlags)));
if (extraFlags >= bestExtraFlags)
continue;
bestFamily = i;
bestExtraFlags = extraFlags;
}
return bestFamily;
}
}

View file

@ -0,0 +1,137 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Provides extension methods for submitting command buffers and handling synchronization for Vulkan queues.
/// </summary>
public static class QueueExtensions
{
/// <summary>
/// Submits command buffers to a Vulkan queue with specified wait and signal semaphores, and a fence for synchronization.
/// </summary>
/// <param name="queue">The Vulkan queue to submit command buffers to.</param>
/// <param name="waitSemaphores">A span of semaphores to wait on before executing the command buffers.</param>
/// <param name="waitDstStageMask">A span of pipeline stage flags indicating the stages to wait for.</param>
/// <param name="commandBuffers">A span of command buffers to execute.</param>
/// <param name="signalSemaphores">A span of semaphores to signal after executing the command buffers.</param>
/// <param name="fence">A fence that is signaled when the queue finishes executing the submitted command buffers.</param>
public static void Submit(
this Queue queue,
Span<VkSemaphore> waitSemaphores,
Span<VkPipelineStageFlags> waitDstStageMask,
Span<CommandBuffer> commandBuffers,
Span<VkSemaphore> signalSemaphores,
VkFence fence
)
{
// The implementation reads WaitSemaphoreCount stage masks, so a shorter span is an out-of-bounds read
if (waitDstStageMask.Length != waitSemaphores.Length)
throw new ArgumentException(
"waitDstStageMask must be the same length as waitSemaphores",
nameof(waitDstStageMask)
);
unsafe
{
var commandBuffersPtr = stackalloc VkCommandBuffer[commandBuffers.Length];
for (var i = 0; i < commandBuffers.Length; i++)
commandBuffersPtr[i] = commandBuffers[i].Handle;
fixed (VkSemaphore* waitSemaphoresPtr = waitSemaphores)
fixed (VkPipelineStageFlags* waitDstStageMaskPtr = waitDstStageMask)
fixed (VkSemaphore* signalSemaphoresPtr = signalSemaphores)
{
var submitInfo = new VkSubmitInfo
{
WaitSemaphoreCount = waitSemaphores.Length,
WaitSemaphores = waitSemaphoresPtr,
WaitDstStageMask = waitDstStageMaskPtr,
CommandBufferCount = commandBuffers.Length,
CommandBuffers = commandBuffersPtr,
SignalSemaphoreCount = signalSemaphores.Length,
SignalSemaphores = signalSemaphoresPtr,
};
queue.Submit([submitInfo], fence);
}
}
}
/// <summary>
/// Submits command buffers with timeline-semaphore wait/signal values, chaining a
/// <see href="https://registry.khronos.org/vulkan/specs/1.3-extensions/man/html/VkTimelineSemaphoreSubmitInfo.html">VkTimelineSemaphoreSubmitInfo</see>
/// onto the submit. The value spans must be the same length as their semaphore spans;
/// entries for binary semaphores are ignored by the implementation, so leave them zero.
/// </summary>
/// <param name="queue">The Vulkan queue to submit command buffers to.</param>
/// <param name="waitSemaphores">A span of semaphores to wait on before executing the command buffers.</param>
/// <param name="waitDstStageMask">A span of pipeline stage flags indicating the stages to wait for.</param>
/// <param name="waitSemaphoreValues">Timeline values to wait for, one per wait semaphore.</param>
/// <param name="commandBuffers">A span of command buffers to execute.</param>
/// <param name="signalSemaphores">A span of semaphores to signal after executing the command buffers.</param>
/// <param name="signalSemaphoreValues">Timeline values to signal, one per signal semaphore.</param>
/// <param name="fence">A fence that is signaled when the queue finishes executing the submitted command buffers.</param>
public static void Submit(
this Queue queue,
Span<VkSemaphore> waitSemaphores,
Span<VkPipelineStageFlags> waitDstStageMask,
ReadOnlySpan<ulong> waitSemaphoreValues,
Span<CommandBuffer> commandBuffers,
Span<VkSemaphore> signalSemaphores,
ReadOnlySpan<ulong> signalSemaphoreValues,
VkFence fence
)
{
// The implementation reads WaitSemaphoreCount stage masks, so a shorter span is an out-of-bounds read
if (waitDstStageMask.Length != waitSemaphores.Length)
throw new ArgumentException(
"waitDstStageMask must be the same length as waitSemaphores",
nameof(waitDstStageMask)
);
if (waitSemaphoreValues.Length != waitSemaphores.Length)
throw new ArgumentException(
"waitSemaphoreValues must be the same length as waitSemaphores",
nameof(waitSemaphoreValues)
);
if (signalSemaphoreValues.Length != signalSemaphores.Length)
throw new ArgumentException(
"signalSemaphoreValues must be the same length as signalSemaphores",
nameof(signalSemaphoreValues)
);
unsafe
{
var commandBuffersPtr = stackalloc VkCommandBuffer[commandBuffers.Length];
for (var i = 0; i < commandBuffers.Length; i++)
commandBuffersPtr[i] = commandBuffers[i].Handle;
fixed (VkSemaphore* waitSemaphoresPtr = waitSemaphores)
fixed (VkPipelineStageFlags* waitDstStageMaskPtr = waitDstStageMask)
fixed (VkSemaphore* signalSemaphoresPtr = signalSemaphores)
fixed (ulong* waitValuesPtr = waitSemaphoreValues)
fixed (ulong* signalValuesPtr = signalSemaphoreValues)
{
var timelineInfo = new VkTimelineSemaphoreSubmitInfo
{
WaitSemaphoreValueCount = waitSemaphoreValues.Length,
WaitSemaphoreValues = (nint*)waitValuesPtr,
SignalSemaphoreValueCount = signalSemaphoreValues.Length,
SignalSemaphoreValues = (nint*)signalValuesPtr,
};
var submitInfo = new VkSubmitInfo
{
Next = &timelineInfo,
WaitSemaphoreCount = waitSemaphores.Length,
WaitSemaphores = waitSemaphoresPtr,
WaitDstStageMask = waitDstStageMaskPtr,
CommandBufferCount = commandBuffers.Length,
CommandBuffers = commandBuffersPtr,
SignalSemaphoreCount = signalSemaphores.Length,
SignalSemaphores = signalSemaphoresPtr,
};
queue.Submit([submitInfo], fence);
}
}
}
}

View file

@ -0,0 +1,12 @@
namespace Brutal.VulkanApi.Abstractions;
public static class ShaderModuleExtensions
{
public static unsafe VkShaderModule FromSpirv(Device device, ReadOnlySpan<byte> bytes, VkAllocator? allocator)
{
return device.CreateShaderModule(
new VkShaderModuleCreateInfo { Code = bytes.Cast<byte, int>().AsPointer(), CodeSize = ByteSize.Of(bytes) },
allocator
);
}
}

View file

@ -0,0 +1,93 @@
namespace Brutal.VulkanApi.Abstractions;
/// <summary>
/// Factories for the common <see cref="VkImageSubresourceRange"/> shapes.
/// </summary>
public static class Subresources
{
/// <summary>
/// All mip levels and array layers of an image, using <see cref="VK.REMAINING_MIP_LEVELS"/> /
/// <see cref="VK.REMAINING_ARRAY_LAYERS"/>. Valid for barriers and image views; copy commands
/// need explicit counts.
/// </summary>
public static VkImageSubresourceRange Full(VkImageAspectFlags aspectMask) =>
new()
{
AspectMask = aspectMask,
BaseMipLevel = 0,
LevelCount = VK.REMAINING_MIP_LEVELS,
BaseArrayLayer = 0,
LayerCount = VK.REMAINING_ARRAY_LAYERS,
};
/// <summary>
/// A single mip level of a single array layer - the shape of most render targets.
/// </summary>
public static VkImageSubresourceRange Single(VkImageAspectFlags aspectMask, int mipLevel = 0, int arrayLayer = 0) =>
new()
{
AspectMask = aspectMask,
BaseMipLevel = mipLevel,
LevelCount = 1,
BaseArrayLayer = arrayLayer,
LayerCount = 1,
};
/// <summary>
/// A contiguous run of mip levels across a single array layer.
/// </summary>
public static VkImageSubresourceRange Mips(
VkImageAspectFlags aspectMask,
int baseMipLevel,
int levelCount,
int arrayLayer = 0
) =>
new()
{
AspectMask = aspectMask,
BaseMipLevel = baseMipLevel,
LevelCount = levelCount,
BaseArrayLayer = arrayLayer,
LayerCount = 1,
};
/// <summary>
/// A contiguous run of array layers at a single mip level.
/// </summary>
public static VkImageSubresourceRange Layers(
VkImageAspectFlags aspectMask,
int baseArrayLayer,
int layerCount,
int mipLevel = 0
) =>
new()
{
AspectMask = aspectMask,
BaseMipLevel = mipLevel,
LevelCount = 1,
BaseArrayLayer = baseArrayLayer,
LayerCount = layerCount,
};
}
/// <summary>
/// Conversions between <see cref="VkImageSubresourceRange"/> and <see cref="VkImageSubresourceLayers"/>.
/// </summary>
public static class SubresourceExtensions
{
/// <summary>
/// Convert a subresource range to the <see cref="VkImageSubresourceLayers"/> for one of its mip levels,
/// as consumed by copy and blit commands. The range's <c>LayerCount</c> must be explicit
/// (not <see cref="VK.REMAINING_ARRAY_LAYERS"/>).
/// </summary>
/// <param name="range">The source range.</param>
/// <param name="mipLevel">Mip level relative to the range's <c>BaseMipLevel</c>.</param>
public static VkImageSubresourceLayers ToLayers(this VkImageSubresourceRange range, int mipLevel = 0) =>
new()
{
AspectMask = range.AspectMask,
MipLevel = range.BaseMipLevel + mipLevel,
BaseArrayLayer = range.BaseArrayLayer,
LayerCount = range.LayerCount,
};
}