-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryAllocator.cs
73 lines (59 loc) · 2.13 KB
/
MemoryAllocator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using Silk.NET.Vulkan;
namespace AvaVulkan
{
static class MemoryAllocator
{
private static Vk _vk;
public unsafe static DeviceMemory AllocateDeviceMemory(
Vk vk,
Device device,
PhysicalDevice physicalDevice,
MemoryRequirements requirements,
out long size,
MemoryPropertyFlags flags = 0,
bool isExternal = false)
{
_vk = vk;
size = 0;
int memoryTypeIndex = FindSuitableMemoryTypeIndex(physicalDevice, requirements.MemoryTypeBits, flags);
if (memoryTypeIndex < 0)
{
return default;
}
MemoryAllocateInfo info = new MemoryAllocateInfo()
{
SType = StructureType.MemoryAllocateInfo,
AllocationSize = requirements.Size,
MemoryTypeIndex = (uint) memoryTypeIndex
};
if (isExternal)
{
ExportMemoryAllocateInfo exInfo = new ExportMemoryAllocateInfo()
{
HandleTypes = ExternalMemoryHandleTypeFlags.ExternalMemoryHandleTypeOpaqueWin32Bit | ExternalMemoryHandleTypeFlags.ExternalMemoryHandleTypeOpaqueFDBit
};
info.PNext = &exInfo;
}
size = (long) requirements.Size;
var result = vk.AllocateMemory(device, &info, null, out var memory);
if (result != Result.Success)
{
return default;
}
return memory;
}
private static int FindSuitableMemoryTypeIndex(PhysicalDevice physicalDevice, uint memoryTypeBits, MemoryPropertyFlags flags)
{
_vk.GetPhysicalDeviceMemoryProperties(physicalDevice, out var props);
for (int i = 0; i < props.MemoryTypeCount; i++)
{
var type = props.MemoryTypes[i];
if ((memoryTypeBits & (1 << i)) != 0 && type.PropertyFlags.HasFlag(flags))
{
return i;
}
}
return -1;
}
}
}