-
Notifications
You must be signed in to change notification settings - Fork 294
Expand file tree
/
Copy pathVulkan.java
More file actions
432 lines (325 loc) · 16.1 KB
/
Vulkan.java
File metadata and controls
432 lines (325 loc) · 16.1 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package net.vulkanmod.vulkan;
import net.vulkanmod.vulkan.device.Device;
import net.vulkanmod.vulkan.device.DeviceManager;
import net.vulkanmod.vulkan.framebuffer.SwapChain;
import net.vulkanmod.vulkan.memory.buffer.Buffer;
import net.vulkanmod.vulkan.memory.MemoryManager;
import net.vulkanmod.vulkan.memory.MemoryTypes;
import net.vulkanmod.vulkan.memory.buffer.StagingBuffer;
import net.vulkanmod.vulkan.queue.Queue;
import net.vulkanmod.vulkan.shader.Pipeline;
import net.vulkanmod.vulkan.texture.SamplerManager;
import net.vulkanmod.vulkan.util.VkResult;
import org.lwjgl.PointerBuffer;
import org.lwjgl.system.MemoryStack;
import static org.lwjgl.vulkan.EXTSwapchainColorspace.VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME;
import org.lwjgl.util.vma.VmaAllocatorCreateInfo;
import org.lwjgl.util.vma.VmaVulkanFunctions;
import org.lwjgl.vulkan.*;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.util.*;
import static java.util.stream.Collectors.toSet;
import static net.vulkanmod.vulkan.queue.Queue.getQueueFamilies;
import static net.vulkanmod.vulkan.util.VUtil.asPointerBuffer;
import static org.lwjgl.glfw.GLFWVulkan.glfwCreateWindowSurface;
import static org.lwjgl.glfw.GLFWVulkan.glfwGetRequiredInstanceExtensions;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.NULL;
import static org.lwjgl.util.vma.Vma.vmaCreateAllocator;
import static org.lwjgl.util.vma.Vma.vmaDestroyAllocator;
import static org.lwjgl.vulkan.EXTDebugUtils.*;
import static org.lwjgl.vulkan.KHRDynamicRendering.VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME;
import static org.lwjgl.vulkan.KHRSwapchain.VK_KHR_SWAPCHAIN_EXTENSION_NAME;
import static org.lwjgl.vulkan.VK10.*;
import static org.lwjgl.vulkan.VK12.VK_API_VERSION_1_2;
public class Vulkan {
public static final boolean ENABLE_VALIDATION_LAYERS = false;
// public static final boolean ENABLE_VALIDATION_LAYERS = true;
public static final boolean DYNAMIC_RENDERING = false;
public static final Set<String> VALIDATION_LAYERS;
static {
if (ENABLE_VALIDATION_LAYERS) {
VALIDATION_LAYERS = new HashSet<>();
VALIDATION_LAYERS.add("VK_LAYER_KHRONOS_validation");
// VALIDATION_LAYERS.add("VK_LAYER_KHRONOS_synchronization2");
} else {
// We are not going to use it, so we don't create it
VALIDATION_LAYERS = null;
}
}
public static final Set<String> REQUIRED_EXTENSION = getRequiredExtensionSet();
private static Set<String> getRequiredExtensionSet() {
ArrayList<String> extensions = new ArrayList<>(List.of(VK_KHR_SWAPCHAIN_EXTENSION_NAME));
if (DYNAMIC_RENDERING) {
extensions.add(VK_KHR_DYNAMIC_RENDERING_EXTENSION_NAME);
}
return new HashSet<>(extensions);
}
private static int debugCallback(int messageSeverity, int messageType, long pCallbackData, long pUserData) {
VkDebugUtilsMessengerCallbackDataEXT callbackData = VkDebugUtilsMessengerCallbackDataEXT.create(pCallbackData);
String s;
if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0) {
s = "\u001B[31m" + callbackData.pMessageString();
// System.err.println("Stack dump:");
// Thread.dumpStack();
} else {
s = callbackData.pMessageString();
}
System.err.println(s);
if ((messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) != 0)
System.nanoTime();
return VK_FALSE;
}
private static int createDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerCreateInfoEXT createInfo,
VkAllocationCallbacks allocationCallbacks, LongBuffer pDebugMessenger) {
if (vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT") != NULL) {
return vkCreateDebugUtilsMessengerEXT(instance, createInfo, allocationCallbacks, pDebugMessenger);
}
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
private static void destroyDebugUtilsMessengerEXT(VkInstance instance, long debugMessenger, VkAllocationCallbacks allocationCallbacks) {
if (vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT") != NULL) {
vkDestroyDebugUtilsMessengerEXT(instance, debugMessenger, allocationCallbacks);
}
}
public static long window;
private static VkInstance instance;
private static long debugMessenger;
private static long surface;
private static List<String> supportedInstanceExtensions;
private static long commandPool;
private static VkCommandBuffer immediateCmdBuffer;
private static long immediateFence;
private static long allocator;
private static StagingBuffer[] stagingBuffers;
private static boolean colorSpaceExtSupport;
public static boolean use24BitsDepthFormat = true;
private static int DEFAULT_DEPTH_FORMAT = 0;
public static void initVulkan(long window) {
createInstance();
setupDebugMessenger();
createSurface(window);
DeviceManager.init(instance);
createVma();
MemoryTypes.createMemoryTypes();
createCommandPool();
setupDepthFormat();
}
static void createStagingBuffers() {
if (stagingBuffers != null) {
freeStagingBuffers();
}
stagingBuffers = new StagingBuffer[Renderer.getFramesNum()];
for (int i = 0; i < stagingBuffers.length; ++i) {
stagingBuffers[i] = new StagingBuffer();
}
}
static void setupDepthFormat() {
DEFAULT_DEPTH_FORMAT = DeviceManager.findDepthFormat(use24BitsDepthFormat);
}
public static void waitIdle() {
vkDeviceWaitIdle(DeviceManager.vkDevice);
}
public static void cleanUp() {
vkDeviceWaitIdle(DeviceManager.vkDevice);
vkDestroyCommandPool(DeviceManager.vkDevice, commandPool, null);
vkDestroyFence(DeviceManager.vkDevice, immediateFence, null);
Pipeline.destroyPipelineCache();
Renderer.getInstance().cleanUpResources();
freeStagingBuffers();
try {
MemoryManager.getInstance().freeAllBuffers();
} catch (Exception e) {
e.printStackTrace();
}
vmaDestroyAllocator(allocator);
SamplerManager.cleanUp();
DeviceManager.destroy();
destroyDebugUtilsMessengerEXT(instance, debugMessenger, null);
KHRSurface.vkDestroySurfaceKHR(instance, surface, null);
vkDestroyInstance(instance, null);
}
private static void freeStagingBuffers() {
Arrays.stream(stagingBuffers).forEach(Buffer::scheduleFree);
}
private static void createInstance() {
if (ENABLE_VALIDATION_LAYERS && !checkValidationLayerSupport()) {
throw new RuntimeException("Validation requested but not supported");
}
supportedInstanceExtensions = getAvailableInstanceExtension();
colorSpaceExtSupport = supportedInstanceExtensions.contains(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME);
try (MemoryStack stack = stackPush()) {
// Use calloc to initialize the structs with 0s. Otherwise, the program can crash due to random values
VkApplicationInfo appInfo = VkApplicationInfo.calloc(stack);
appInfo.sType(VK_STRUCTURE_TYPE_APPLICATION_INFO);
appInfo.pApplicationName(stack.UTF8Safe("VulkanMod"));
appInfo.applicationVersion(VK_MAKE_VERSION(1, 0, 0));
appInfo.pEngineName(stack.UTF8Safe("VulkanMod Engine"));
appInfo.engineVersion(VK_MAKE_VERSION(1, 0, 0));
appInfo.apiVersion(VK_API_VERSION_1_2);
VkInstanceCreateInfo createInfo = VkInstanceCreateInfo.calloc(stack);
createInfo.sType(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
createInfo.pApplicationInfo(appInfo);
createInfo.ppEnabledExtensionNames(getRequiredInstanceExtensions());
if (ENABLE_VALIDATION_LAYERS) {
createInfo.ppEnabledLayerNames(asPointerBuffer(VALIDATION_LAYERS));
VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo = VkDebugUtilsMessengerCreateInfoEXT.calloc(stack);
populateDebugMessengerCreateInfo(debugCreateInfo);
createInfo.pNext(debugCreateInfo.address());
}
// We need to retrieve the pointer of the created instance
PointerBuffer instancePtr = stack.mallocPointer(1);
int result = vkCreateInstance(createInfo, null, instancePtr);
checkResult(result, "Failed to create instance");
instance = new VkInstance(instancePtr.get(0), createInfo);
}
}
static boolean checkValidationLayerSupport() {
try (MemoryStack stack = stackPush()) {
IntBuffer layerCount = stack.ints(0);
vkEnumerateInstanceLayerProperties(layerCount, null);
VkLayerProperties.Buffer availableLayers = VkLayerProperties.malloc(layerCount.get(0), stack);
vkEnumerateInstanceLayerProperties(layerCount, availableLayers);
Set<String> availableLayerNames = availableLayers.stream()
.map(VkLayerProperties::layerNameString)
.collect(toSet());
return availableLayerNames.containsAll(Vulkan.VALIDATION_LAYERS);
}
}
private static void populateDebugMessengerCreateInfo(VkDebugUtilsMessengerCreateInfoEXT debugCreateInfo) {
debugCreateInfo.sType(VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT);
// debugCreateInfo.messageSeverity(VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT);
debugCreateInfo.messageSeverity(VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT);
debugCreateInfo.messageType(VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT);
// debugCreateInfo.messageType(VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT);
debugCreateInfo.pfnUserCallback(Vulkan::debugCallback);
}
private static void setupDebugMessenger() {
if (!ENABLE_VALIDATION_LAYERS) {
return;
}
try (MemoryStack stack = stackPush()) {
VkDebugUtilsMessengerCreateInfoEXT createInfo = VkDebugUtilsMessengerCreateInfoEXT.calloc(stack);
populateDebugMessengerCreateInfo(createInfo);
LongBuffer pDebugMessenger = stack.longs(VK_NULL_HANDLE);
checkResult(createDebugUtilsMessengerEXT(instance, createInfo, null, pDebugMessenger),
"Failed to set up debug messenger");
debugMessenger = pDebugMessenger.get(0);
}
}
public static void setDebugLabel(MemoryStack stack, int objectType, long handle, String label) {
if (ENABLE_VALIDATION_LAYERS) {
VkDebugUtilsObjectNameInfoEXT nameInfo = VkDebugUtilsObjectNameInfoEXT.calloc(stack);
nameInfo.sType$Default();
nameInfo.objectType(objectType);
nameInfo.objectHandle(handle);
nameInfo.pObjectName(stackUTF8(label));
EXTDebugUtils.vkSetDebugUtilsObjectNameEXT(Vulkan.getVkDevice(), nameInfo);
}
}
private static void createSurface(long handle) {
window = handle;
try (MemoryStack stack = stackPush()) {
LongBuffer pSurface = stack.longs(VK_NULL_HANDLE);
checkResult(glfwCreateWindowSurface(instance, window, null, pSurface),
"Failed to create window surface");
surface = pSurface.get(0);
}
}
private static void createVma() {
try (MemoryStack stack = stackPush()) {
VmaVulkanFunctions vulkanFunctions = VmaVulkanFunctions.calloc(stack);
vulkanFunctions.set(instance, DeviceManager.vkDevice);
VmaAllocatorCreateInfo allocatorCreateInfo = VmaAllocatorCreateInfo.calloc(stack);
allocatorCreateInfo.physicalDevice(DeviceManager.physicalDevice);
allocatorCreateInfo.device(DeviceManager.vkDevice);
allocatorCreateInfo.pVulkanFunctions(vulkanFunctions);
allocatorCreateInfo.instance(instance);
allocatorCreateInfo.vulkanApiVersion(VK_API_VERSION_1_2);
PointerBuffer pAllocator = stack.pointers(VK_NULL_HANDLE);
checkResult(vmaCreateAllocator(allocatorCreateInfo, pAllocator),
"Failed to create Allocator");
allocator = pAllocator.get(0);
}
}
private static void createCommandPool() {
try (MemoryStack stack = stackPush()) {
Queue.QueueFamilyIndices queueFamilyIndices = getQueueFamilies();
VkCommandPoolCreateInfo poolInfo = VkCommandPoolCreateInfo.calloc(stack);
poolInfo.sType(VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO);
poolInfo.queueFamilyIndex(queueFamilyIndices.graphicsFamily);
poolInfo.flags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT);
LongBuffer pCommandPool = stack.mallocLong(1);
checkResult(vkCreateCommandPool(DeviceManager.vkDevice, poolInfo, null, pCommandPool),
"Failed to create command pool");
commandPool = pCommandPool.get(0);
}
}
private static List<String> getAvailableInstanceExtension() {
try (MemoryStack stack = MemoryStack.stackPush()) {
// Query first for extension count
IntBuffer extensionCount = stack.ints(0);
vkEnumerateInstanceExtensionProperties((String) null, extensionCount, null);
VkExtensionProperties.Buffer availableExtensions = VkExtensionProperties.malloc(extensionCount.get(0), stack);
vkEnumerateInstanceExtensionProperties((String) null, extensionCount, availableExtensions);
return availableExtensions.stream()
.map(VkExtensionProperties::extensionNameString)
.toList();
}
}
private static PointerBuffer getRequiredInstanceExtensions() {
PointerBuffer glfwExtensions = glfwGetRequiredInstanceExtensions();
MemoryStack stack = stackGet();
List<String> requestedExtensions = new ArrayList<>();
// Check for VK_EXT_SWAPCHAIN_COLOR_SPACE support
if (supportedInstanceExtensions.contains(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME)) {
requestedExtensions.add(VK_EXT_SWAPCHAIN_COLOR_SPACE_EXTENSION_NAME);
}
if (ENABLE_VALIDATION_LAYERS) {
requestedExtensions.add(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
PointerBuffer extensions = stack.mallocPointer(glfwExtensions.capacity() + requestedExtensions.size());
extensions.put(glfwExtensions);
for (String extName : requestedExtensions) {
extensions.put(stack.UTF8(extName));
}
return extensions.rewind();
}
public static void checkResult(int result, String errorMessage) {
if (result != VK_SUCCESS) {
throw new RuntimeException(String.format("%s: %s", errorMessage, VkResult.decode(result)));
}
}
public static void setVsync(boolean b) {
SwapChain swapChain = Renderer.getInstance().getSwapChain();
if (swapChain.isVsync() != b) {
Renderer.scheduleSwapChainUpdate();
swapChain.setVsync(b);
}
}
public static VkDevice getVkDevice() {
return DeviceManager.vkDevice;
}
public static long getAllocator() {
return allocator;
}
public static long getSurface() {
return surface;
}
public static long getCommandPool() {
return commandPool;
}
public static StagingBuffer getStagingBuffer() {
return stagingBuffers[Renderer.getCurrentFrame()];
}
public static Device getDevice() {
return DeviceManager.device;
}
public static boolean colorSpaceExtSupport() {
return colorSpaceExtSupport;
}
public static int getDefaultDepthFormat() {
return DEFAULT_DEPTH_FORMAT;
}
}