using System.Numerics;
namespace Brutal.VulkanApi;
///
/// Class that wraps a Vulkan PhysicalDevice handle.
///
public class PhysicalDevice : VulkanHandleWrapper
{
///
/// The Instance that this physical device was created from.
///
public Instance Instance { get; }
///
/// Cached PhysicalDevice ExtensionNames.
///
///
/// Prefer for lookups: this property
/// materializes a managed string per supported extension (200+ on modern drivers), whereas
/// the byte-span lookup avoids all string allocation.
///
public HashSet ExtensionNames
{
get
{
if (_extensionNames == null)
{
var utf8 = ExtensionNamesUtf8;
_extensionNames = new HashSet(utf8.Length);
foreach (var name in utf8)
_extensionNames.Add(Utf8.GetString(name));
}
return _extensionNames;
}
}
private HashSet? _extensionNames;
///
/// Supported extension names as raw UTF-8 bytes (trimmed to the null terminator), enumerated
/// once on first access. Backs the allocation-free extension lookups.
///
private byte[][] ExtensionNamesUtf8
{
get
{
if (_extensionNamesUtf8 == null)
{
ReadOnlySpan extensionProperties =
stackalloc VkExtensionProperties[this.EnumerateDeviceExtensionProperties_Count([])];
var result = this.EnumerateDeviceExtensionProperties_Write([], extensionProperties);
if (result != VkResult.Success)
throw new InvalidOperationException("Failed to enumerate device extension properties: " + result);
var names = new byte[extensionProperties.Length][];
for (var i = 0; i < extensionProperties.Length; i++)
{
unsafe
{
fixed (byte* name = extensionProperties[i].ExtensionName)
names[i] = Utf8.GetNullTerminatedSpan(name).ToArray();
}
}
_extensionNamesUtf8 = names;
}
return _extensionNamesUtf8;
}
}
private byte[][]? _extensionNamesUtf8;
internal PhysicalDevice(Instance inInstance, VkPhysicalDevice inHandle)
{
Handle = inHandle;
Instance = inInstance;
}
///
/// Naively returns the index of the first queue family which has the given VkQueueFlag, or -1 if no family is found
///
public int GetFirstQueueFamilyWithFlag(VkQueueFlags flag)
{
using var properties = SpanOwner.Allocate(this.GetQueueFamilyProperties_Count());
this.GetQueueFamilyProperties_Write(properties.Span);
for (var i = 0; i < properties.Length; ++i)
if (properties.Span[i].QueueFlags.HasFlag(flag))
return i;
return -1;
}
///
/// Searches for the first memory type index that satisfies both the specified memory type filter and required property flags.
///
/// A bitmask representing the candidate memory types.
/// The memory property flags that must be present.
/// The index of the first suitable memory type.
/// Thrown if no memory type meets the required criteria.
public int FindMemoryType(int memoryTypeFilter, VkMemoryPropertyFlags requiredProperties)
{
var memoryProperties = this.GetMemoryProperties();
var memoryTypeCount = memoryProperties.MemoryTypeCount;
for (var i = 0; i < memoryTypeCount; i++)
{
var memoryTypeBits = 1 << i;
var isRequiredMemoryType = (memoryTypeFilter & memoryTypeBits) != 0;
if (!isRequiredMemoryType)
continue;
var properties = memoryProperties.MemoryTypes[i].PropertyFlags;
var hasRequiredProperties = (properties & requiredProperties) == requiredProperties;
if (hasRequiredProperties)
return i;
}
throw new Exception("failed to find suitable memory type!");
}
///
/// Searches for the first memory type index that satisfies both the specified memory type filter and required property flags.
///
/// A bitmask representing the candidate memory types.
/// The memory property flags that must be present.
/// Memory property flags that are preferred, and will be prioritized
/// The index of the first suitable memory type.
/// Thrown if no memory type meets the required criteria.
public int FindMemoryType(
int memoryTypeFilter,
VkMemoryPropertyFlags requiredProperties,
VkMemoryPropertyFlags preferredProperties
)
{
var memoryProperties = this.GetMemoryProperties();
var memoryTypeCount = memoryProperties.MemoryTypeCount;
int bestHits = 0;
int bestCandidate = -1;
for (var i = 0; i < memoryTypeCount; i++)
{
var memoryTypeBits = 1 << i;
var isRequiredMemoryType = (memoryTypeFilter & memoryTypeBits) != 0;
if (!isRequiredMemoryType)
continue;
var properties = memoryProperties.MemoryTypes[i].PropertyFlags;
var hasRequiredProperties = (properties & requiredProperties) == requiredProperties;
if (!hasRequiredProperties)
continue;
var prefMatch = (properties & preferredProperties);
// perfect candidate
if (prefMatch == preferredProperties)
return i;
// sort imperfect candidate by most preferredProperties flag hits
int hits = BitOperations.PopCount((ulong)prefMatch);
if (hits > bestHits)
{
bestCandidate = i;
bestHits = hits;
}
}
if (bestCandidate == -1)
throw new Exception("failed to find suitable memory type!");
return bestCandidate;
}
///
/// Determines if the physical device supports a given extension, without allocating a string.
///
/// The extension name as UTF-8 bytes, e.g. a "VK_KHR_swapchain"u8 literal.
public bool SupportsExtension(ReadOnlySpan utf8Name)
{
foreach (var name in ExtensionNamesUtf8)
if (utf8Name.SequenceEqual(name))
return true;
return false;
}
///
/// Determines if the physical device supports a given extension.
///
///
/// Answers from so it stays consistent with that mutable set and
/// with the pre-existing behaviour. This materializes the managed string set on first use;
/// prefer on hot paths to avoid the allocation.
///
public bool SupportsExtension(string extension)
{
return ExtensionNames.Contains(extension);
}
///
/// vkCreateDevice - Create a new device instance
///
/// Device object wrapping a DeviceHandle
public Device CreateDevice(Device.CreateInfo createInfo)
{
return new Device(this, createInfo);
}
public VkPhysicalDevice Handle { get; init; }
public ref VkInstance.FunctionTable PInvoke => ref Instance.PInvoke;
public bool IsNull() => Handle.IsNull();
public VkObjectType VkObjectType => Handle.VkObjectType;
public IntPtr VkHandle => Handle.VkHandle;
public static implicit operator VkPhysicalDevice(PhysicalDevice physicalDevice) => physicalDevice.Handle;
}