-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1378 lines (1144 loc) · 60.9 KB
/
Copy pathmain.cpp
File metadata and controls
1378 lines (1144 loc) · 60.9 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include "VulkanSwapchain.h"
#include "VulkanRayTracing.h"
#include "VulkanAcceleration.h"
#include "VulkanRTPipeline.h"
#include "Camera.h"
#include "EntityManager.h"
#include "Transform.h"
#include "NvidiaDenoiser.h"
#include "AsyncLogger.h"
#include <iostream>
#include <stdexcept>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <optional>
#include <set>
#include <chrono>
#include <filesystem>
#include <fstream>
#ifdef _WIN32
#include <windows.h>
#endif
// Set to 1 to enable verbose logging in the main render loop (performance impact)
#define ENABLE_RENDER_LOOP_LOGGING 0
// Vulkan Debug Callback
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* pUserData) {
const char* severity = "UNKNOWN";
if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) severity = "ERROR";
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) severity = "WARNING";
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT) severity = "INFO";
else if (messageSeverity & VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT) severity = "VERBOSE";
// Only print errors and warnings
if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT) {
std::cerr << "\n[VULKAN " << severity << "] " << pCallbackData->pMessage << "\n" << std::endl;
}
return VK_FALSE;
}
const uint32_t WIDTH = 1920;
const uint32_t HEIGHT = 1080;
const std::vector<const char*> validationLayers = {
"VK_LAYER_KHRONOS_validation"
};
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME,
VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME,
VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME,
VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME,
VK_KHR_RAY_QUERY_EXTENSION_NAME, // Inline RT in compute shaders
VK_KHR_PIPELINE_LIBRARY_EXTENSION_NAME, // RT pipeline compilation caching
VK_KHR_RAY_TRACING_MAINTENANCE_1_EXTENSION_NAME, // TraceRayIndirect, pipeline flags
VK_KHR_SPIRV_1_4_EXTENSION_NAME, // Required for ray query
VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME, // Required for SPIRV 1.4
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME, // Interop for denoiser
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME, // Sync for denoiser
#ifdef _WIN32
"VK_KHR_external_memory_win32",
"VK_KHR_external_semaphore_win32",
#endif
};
#ifdef NDEBUG
const bool enableValidationLayers = false;
#else
const bool enableValidationLayers = true;
#endif
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() {
return graphicsFamily.has_value() && presentFamily.has_value();
}
};
// Get project root directory (where shaders folder is located)
std::string getProjectRoot() {
#ifdef _WIN32
char buffer[MAX_PATH] = {0};
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::filesystem::path exePath(buffer);
// Navigate up from exe location to find shaders folder
std::filesystem::path searchPath = exePath.parent_path();
for (int i = 0; i < 5; i++) { // Search up to 5 levels
if (std::filesystem::exists(searchPath / "shaders" / "compiled")) {
return searchPath.string();
}
searchPath = searchPath.parent_path();
}
#endif
// Fallback to current directory
return std::filesystem::current_path().string();
}
class RacingEngine {
public:
void run() {
initWindow();
initVulkan();
mainLoop();
cleanup();
}
private:
GLFWwindow* window;
VkInstance instance;
VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VkDevice device;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkSurfaceKHR surface;
VulkanSwapchain swapchain;
VulkanRayTracing rayTracing;
VulkanAcceleration acceleration;
VulkanRTPipeline rtPipeline;
// OptiX AI Denoiser (Tensor Cores)
NvidiaDenoiserImpl denoiser;
QueueFamilyIndices queueIndices;
// Entity system
EntityManager entityManager;
// Camera
Camera camera;
float lastX = WIDTH / 2.0f;
float lastY = HEIGHT / 2.0f;
bool firstMouse = true;
// Timing
std::chrono::time_point<std::chrono::high_resolution_clock> lastFrameTime;
float deltaTime = 0.0f;
float currentFPS = 0.0f;
float frameTimeMs = 0.0f;
// Sync objects - one set per swapchain image for proper synchronization
std::vector<VkSemaphore> imageAvailableSemaphores;
std::vector<VkSemaphore> renderFinishedSemaphores;
std::vector<VkFence> inFlightFences;
std::vector<VkFence> imagesInFlight; // Track which fence is using which swapchain image
size_t currentFrame = 0;
const int MAX_FRAMES_IN_FLIGHT = 2;
// Temporal accumulation & reprojection
uint32_t accumulationFrames = 0;
uint32_t totalFrameCount = 0;
glm::vec3 lastCameraPos = glm::vec3(0.0f);
glm::vec3 lastCameraFront = glm::vec3(0.0f);
// Previous frame matrices for temporal reprojection
glm::mat4 prevViewProj = glm::mat4(1.0f);
glm::vec3 prevCameraPosition = glm::vec3(0.0f);
bool hasPreviousFrame = false; // First frame has no history
// Track first use of storage image (initialized once, then always TRANSFER_SRC after use)
bool storageImageInitialized = false;
// Denoiser toggle (D key)
bool denoiserEnabled = true;
bool denoiserKeyPressed = false;
// Cursor toggle (TAB key)
bool cursorLocked = true;
bool tabKeyPressed = false;
// Async Logger
AsyncLogger logger;
// UX State Tracking
void updateWindowTitle() {
glm::vec3 pos = camera.getPosition();
char title[512];
uint32_t totalSamples = accumulationFrames * 8; // 8 SPP per frame
const char* denoiserStatus = denoiserEnabled ? "ON" : "OFF";
const char* cursorStatus = cursorLocked ? "LOCKED" : "FREE";
snprintf(title, sizeof(title),
"IZTAPALAPA PATH TRACER | FPS: %.0f | %.2fms | %u samples | Pos: (%.1f, %.1f, %.1f) | AI: %s | Cursor: %s",
currentFPS, frameTimeMs, totalSamples, pos.x, pos.y, pos.z, denoiserStatus, cursorStatus);
glfwSetWindowTitle(window, title);
}
void initWindow() {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, "Racing Engine - Vulkan RT", nullptr, nullptr);
// Setup mouse input
glfwSetWindowUserPointer(window, this);
glfwSetCursorPosCallback(window, mouseCallback);
glfwSetKeyCallback(window, keyCallback);
glfwSetScrollCallback(window, scrollCallback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// Initialize camera with correct aspect ratio
camera = Camera(45.0f, (float)WIDTH / (float)HEIGHT, 0.1f, 1000.0f);
std::cout << "GLFW window created successfully!\n";
std::cout << "Camera controls: WASD - move, QE - up/down, Mouse - look, Shift - faster\n";
std::cout << " TAB - toggle cursor lock, Scroll - zoom (FOV)\n";
std::cout << " R - Reset Camera\n";
std::cout << "Press D to toggle AI Denoiser (Tensor Cores)\n";
}
static void scrollCallback(GLFWwindow* window, double xoffset, double yoffset) {
auto engine = reinterpret_cast<RacingEngine*>(glfwGetWindowUserPointer(window));
if (engine->cursorLocked) {
engine->camera.processMouseScroll(static_cast<float>(yoffset));
engine->updateWindowTitle();
}
}
static void mouseCallback(GLFWwindow* window, double xposIn, double yposIn) {
auto engine = reinterpret_cast<RacingEngine*>(glfwGetWindowUserPointer(window));
float xpos = static_cast<float>(xposIn);
float ypos = static_cast<float>(yposIn);
if (engine->firstMouse) {
engine->lastX = xpos;
engine->lastY = ypos;
engine->firstMouse = false;
}
float xoffset = xpos - engine->lastX;
float yoffset = engine->lastY - ypos; // Reversed since y-coordinates go from bottom to top
engine->lastX = xpos;
engine->lastY = ypos;
if (engine->cursorLocked) {
engine->camera.processMouseMovement(xoffset, yoffset);
}
}
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) {
auto engine = reinterpret_cast<RacingEngine*>(glfwGetWindowUserPointer(window));
// ESC to close window
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, true);
}
// TAB key to toggle cursor lock
if (key == GLFW_KEY_TAB && action == GLFW_PRESS && !engine->tabKeyPressed) {
engine->tabKeyPressed = true;
engine->cursorLocked = !engine->cursorLocked;
if (engine->cursorLocked) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
engine->firstMouse = true; // Reset mouse to prevent jump
} else {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
std::string status = engine->cursorLocked ? "LOCKED (Camera Active)" : "UNLOCKED (Camera Paused)";
engine->logger.log("\n[CURSOR] " + status + "\n");
engine->updateWindowTitle();
}
if (key == GLFW_KEY_TAB && action == GLFW_RELEASE) {
engine->tabKeyPressed = false;
}
// D key to toggle denoiser
if (key == GLFW_KEY_D && action == GLFW_PRESS && !engine->denoiserKeyPressed) {
engine->denoiserKeyPressed = true;
engine->denoiserEnabled = !engine->denoiserEnabled;
std::string status = engine->denoiserEnabled ? "ENABLED" : "DISABLED";
engine->logger.log("\n[DENOISER] " + status + "\n");
engine->updateWindowTitle();
}
if (key == GLFW_KEY_D && action == GLFW_RELEASE) {
engine->denoiserKeyPressed = false;
}
// R key to reset camera
if (key == GLFW_KEY_R && action == GLFW_PRESS) {
engine->camera.reset();
engine->accumulationFrames = 0; // Reset accumulation immediately
engine->logger.log("\n[CAMERA] Reset to default view\n");
engine->updateWindowTitle();
}
}
void initVulkan() {
createInstance();
setupDebugMessenger();
createSurface();
pickPhysicalDevice();
createLogicalDevice();
// Create swapchain
swapchain.create(physicalDevice, device, surface, WIDTH, HEIGHT,
queueIndices.graphicsFamily.value(),
queueIndices.presentFamily.value());
// Create ray tracing resources
rayTracing.createCommandPool(device, queueIndices.graphicsFamily.value());
rayTracing.createStorageImage(physicalDevice, device, WIDTH, HEIGHT,
VK_FORMAT_B8G8R8A8_UNORM); // Display output (matches swapchain)
rayTracing.createAccumulationImage(physicalDevice, device, WIDTH, HEIGHT); // HDR accumulation (R32G32B32A32_SFLOAT)
rayTracing.createDepthBuffer(physicalDevice, device, WIDTH, HEIGHT); // Depth for temporal rejection
rayTracing.createVelocityBuffer(physicalDevice, device, WIDTH, HEIGHT); // Motion vectors
rayTracing.createCommandBuffers(device, swapchain.images.size());
rayTracing.initializeImageLayouts(device, graphicsQueue); // Initialize to GENERAL layout
// Create acceleration structures
acceleration.loadRayTracingFunctions(device);
acceleration.createScene(physicalDevice, device, graphicsQueue, rayTracing.commandPool);
acceleration.createTopLevelAS(physicalDevice, device, graphicsQueue, rayTracing.commandPool);
// Allocate scratch buffer for dynamic TLAS updates
acceleration.allocateTLASScratchBuffer(physicalDevice, device);
// Create entities matching the geometry objects
// Ground plane should be at Y=0
auto groundEntity = entityManager.createEntity("Ground", 0, EntityType::STATIC);
groundEntity->transform.position = glm::vec3(0.0f, 0.0f, 0.0f);
// Cubes on ground (Y axis now fixed)
auto cube1 = entityManager.createEntity("Cube1", 1, EntityType::DYNAMIC);
cube1->transform.position = glm::vec3(0.0f, 0.5f, 0.0f); // On ground
cube1->transform.scale = glm::vec3(1.0f);
cube1->angularVelocity = glm::vec3(0.0f, 1.0f, 0.0f); // Spin
auto cube2 = entityManager.createEntity("Cube2", 2, EntityType::DYNAMIC);
cube2->transform.position = glm::vec3(4.0f, 0.4f, 0.0f); // On ground
cube2->transform.scale = glm::vec3(0.8f);
cube2->velocity = glm::vec3(1.0f, 0.0f, 0.0f); // Move along X
auto cube3 = entityManager.createEntity("Cube3", 3, EntityType::STATIC);
cube3->transform.position = glm::vec3(-4.0f, 0.6f, 0.0f); // On ground
cube3->transform.scale = glm::vec3(1.2f);
auto cube4 = entityManager.createEntity("Cube4", 4, EntityType::DYNAMIC);
cube4->transform.position = glm::vec3(0.0f, 0.75f, -5.0f); // On ground
cube4->transform.scale = glm::vec3(1.5f);
cube4->angularVelocity = glm::vec3(0.5f, 0.5f, 0.0f); // Tumble
std::cout << "Created " << entityManager.size() << " entities ("
<< entityManager.countDynamic() << " dynamic, "
<< entityManager.countStatic() << " static)\n";
// DEBUG: Print entity positions
std::cout << "\n=== ENTITY POSITIONS (for debugging) ===\n";
for (const auto& entity : entityManager.getEntities()) {
std::cout << entity->name << ": pos("
<< entity->transform.position.x << ", "
<< entity->transform.position.y << ", "
<< entity->transform.position.z << ") scale("
<< entity->transform.scale.x << ")\n";
}
std::cout << "Ground plane geometry has Y=0.0 in vertices\n";
std::cout << "Camera starts at: (0, 3, 8) - Y AXIS FIXED!\n";
std::cout << "=======================================\n\n";
// Create RT pipeline
rtPipeline.loadRTPipelineFunctions(device);
rtPipeline.createCameraBuffer(physicalDevice, device);
rtPipeline.createDescriptorSetLayout(device);
rtPipeline.createDescriptorPool(device);
rtPipeline.createDescriptorSet(device, acceleration.tlas.handle,
rayTracing.storageImageView, rayTracing.accumulationImageView,
rayTracing.depthImageView, rayTracing.prevDepthImageView,
rayTracing.velocityImageView);
// Get shader path relative to project root
std::string projectRoot = getProjectRoot();
std::string shaderPath = projectRoot + "/shaders/compiled";
std::cout << "Loading shaders from: " << shaderPath << "\n";
rtPipeline.createPipeline(device, shaderPath);
rtPipeline.createShaderBindingTable(physicalDevice, device);
rtPipeline.createTonemapPipeline(device, shaderPath);
rtPipeline.createTonemapDescriptorSet(device, rayTracing.accumulationImageView, rayTracing.storageImageView);
// Create sync objects
createSyncObjects();
std::cout << "\n========================================\n";
std::cout << " Vulkan Ray Tracing Initialized!\n";
std::cout << " [SYSTEM CHECK] EXCLUSIVE PROCESSING ACTIVE\n";
std::cout << " > Rasterization Pipeline: DISABLED\n";
std::cout << " > Optimization: EXCLUSIVE RT CORE EXECUTION\n";
std::cout << " > Tensor Cores: DEDICATED PIPELINE (Denoiser)\n";
std::cout << " Ready to render!\n";
std::cout << "========================================\n";
}
void createInstance() {
if (enableValidationLayers && !checkValidationLayerSupport()) {
throw std::runtime_error("Validation layers requested, but not available!");
}
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Racing Engine";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Custom Racing Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_3;
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
auto extensions = getRequiredExtensions();
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("Failed to create Vulkan instance!");
}
std::cout << "Vulkan instance created successfully!\n";
}
void createSurface() {
if (glfwCreateWindowSurface(instance, window, nullptr, &surface) != VK_SUCCESS) {
throw std::runtime_error("Failed to create window surface!");
}
std::cout << "Window surface created!\n";
}
void pickPhysicalDevice() {
uint32_t deviceCount = 0;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("Failed to find GPUs with Vulkan support!");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const auto& dev : devices) {
if (isDeviceSuitable(dev)) {
physicalDevice = dev;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("Failed to find a suitable NVIDIA GPU! This engine is for NVIDIA elites only. No AMD allowed.");
}
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
std::cout << "\n==================================================\n";
std::cout << " [ELITIST MODE] HARDWARE VERIFIED\n";
std::cout << " GPU: " << deviceProperties.deviceName << "\n";
std::cout << " ARCH: NVIDIA RTX (Ampere/Ada Lovelace/Blackwell)\n";
std::cout << " RT CORES: EXCLUSIVE ACCESS ENABLED\n";
std::cout << " TENSOR CORES: PIPELINE READY\n";
std::cout << "==================================================\n\n";
}
void createLogicalDevice() {
queueIndices = findQueueFamilies(physicalDevice);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = {
queueIndices.graphicsFamily.value(),
queueIndices.presentFamily.value()
};
float queuePriority = 1.0f;
for (uint32_t queueFamily : uniqueQueueFamilies) {
VkDeviceQueueCreateInfo queueCreateInfo{};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures{};
// Ray tracing features
// === NVIDIA RTX FULL HARDWARE ACCELERATION ===
// Buffer device address (required for RT)
VkPhysicalDeviceBufferDeviceAddressFeatures bufferDeviceAddressFeatures{};
bufferDeviceAddressFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES;
bufferDeviceAddressFeatures.bufferDeviceAddress = VK_TRUE;
// Vulkan 1.2 features for SPIRV 1.4
VkPhysicalDeviceVulkan12Features vulkan12Features{};
vulkan12Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
vulkan12Features.bufferDeviceAddress = VK_TRUE;
vulkan12Features.shaderFloat16 = VK_TRUE; // FP16 for Tensor Core efficiency
vulkan12Features.shaderInt8 = VK_TRUE; // INT8 for Tensor Cores
vulkan12Features.storageBuffer8BitAccess = VK_TRUE;
vulkan12Features.pNext = &bufferDeviceAddressFeatures;
// Ray Query - inline ray tracing in any shader stage (uses RT Cores)
VkPhysicalDeviceRayQueryFeaturesKHR rayQueryFeatures{};
rayQueryFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_QUERY_FEATURES_KHR;
rayQueryFeatures.rayQuery = VK_TRUE;
rayQueryFeatures.pNext = &vulkan12Features;
// RT Pipeline features - full RT Core utilization
VkPhysicalDeviceRayTracingPipelineFeaturesKHR rtPipelineFeatures{};
rtPipelineFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_PIPELINE_FEATURES_KHR;
rtPipelineFeatures.rayTracingPipeline = VK_TRUE;
rtPipelineFeatures.rayTracingPipelineTraceRaysIndirect = VK_TRUE; // GPU-driven RT
rtPipelineFeatures.rayTraversalPrimitiveCulling = VK_TRUE; // HW culling
rtPipelineFeatures.pNext = &rayQueryFeatures;
// RT Maintenance 1 - additional RT Core features
VkPhysicalDeviceRayTracingMaintenance1FeaturesKHR rtMaintenance1{};
rtMaintenance1.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_RAY_TRACING_MAINTENANCE_1_FEATURES_KHR;
rtMaintenance1.rayTracingMaintenance1 = VK_TRUE;
rtMaintenance1.rayTracingPipelineTraceRaysIndirect2 = VK_TRUE;
rtMaintenance1.pNext = &rtPipelineFeatures;
// Acceleration Structure features
VkPhysicalDeviceAccelerationStructureFeaturesKHR accelFeatures{};
accelFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ACCELERATION_STRUCTURE_FEATURES_KHR;
accelFeatures.accelerationStructure = VK_TRUE;
accelFeatures.accelerationStructureCaptureReplay = VK_TRUE;
accelFeatures.descriptorBindingAccelerationStructureUpdateAfterBind = VK_TRUE;
accelFeatures.pNext = &rtMaintenance1;
VkDeviceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
createInfo.pNext = &accelFeatures;
if (enableValidationLayers) {
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
} else {
createInfo.enabledLayerCount = 0;
}
if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
throw std::runtime_error("Failed to create logical device!");
}
vkGetDeviceQueue(device, queueIndices.graphicsFamily.value(), 0, &graphicsQueue);
vkGetDeviceQueue(device, queueIndices.presentFamily.value(), 0, &presentQueue);
std::cout << "Logical device created with ray tracing extensions!\n";
}
bool isDeviceSuitable(VkPhysicalDevice dev) {
QueueFamilyIndices indices = findQueueFamilies(dev);
bool extensionsSupported = checkDeviceExtensionSupport(dev);
VkPhysicalDeviceProperties deviceProperties;
vkGetPhysicalDeviceProperties(dev, &deviceProperties);
// --- ELITIST CHECK: ENFORCE NVIDIA HARDWARE ---
if (deviceProperties.vendorID != 0x10DE) {
std::cout << "[REJECTED] Non-NVIDIA GPU detected: " << deviceProperties.deviceName
<< " (VendorID: " << std::hex << deviceProperties.vendorID << std::dec << ")\n";
std::cout << " This engine is configured for FULL NVIDIA ELITIST MODE.\n";
std::cout << " AMD/Intel compatibility is explicitly disabled.\n";
return false;
}
return indices.isComplete() && extensionsSupported;
}
bool checkDeviceExtensionSupport(VkPhysicalDevice dev) {
uint32_t extensionCount;
vkEnumerateDeviceExtensionProperties(dev, nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> availableExtensions(extensionCount);
vkEnumerateDeviceExtensionProperties(dev, nullptr, &extensionCount, availableExtensions.data());
std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
for (const auto& extension : availableExtensions) {
requiredExtensions.erase(extension.extensionName);
}
return requiredExtensions.empty();
}
QueueFamilyIndices findQueueFamilies(VkPhysicalDevice dev) {
QueueFamilyIndices indices;
uint32_t queueFamilyCount = 0;
vkGetPhysicalDeviceQueueFamilyProperties(dev, &queueFamilyCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
vkGetPhysicalDeviceQueueFamilyProperties(dev, &queueFamilyCount, queueFamilies.data());
int i = 0;
for (const auto& queueFamily : queueFamilies) {
if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
indices.graphicsFamily = i;
}
VkBool32 presentSupport = false;
vkGetPhysicalDeviceSurfaceSupportKHR(dev, i, surface, &presentSupport);
if (presentSupport) {
indices.presentFamily = i;
}
if (indices.isComplete()) {
break;
}
i++;
}
return indices;
}
std::vector<const char*> getRequiredExtensions() {
uint32_t glfwExtensionCount = 0;
const char** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount);
if (enableValidationLayers) {
extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
}
return extensions;
}
void setupDebugMessenger() {
if (!enableValidationLayers) return;
VkDebugUtilsMessengerCreateInfoEXT createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT |
VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.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;
createInfo.pfnUserCallback = debugCallback;
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, &createInfo, nullptr, &debugMessenger);
std::cout << "Debug messenger created\n";
}
}
void destroyDebugMessenger() {
if (!enableValidationLayers || debugMessenger == VK_NULL_HANDLE) return;
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func != nullptr) {
func(instance, debugMessenger, nullptr);
}
}
bool checkValidationLayerSupport() {
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const char* layerName : validationLayers) {
bool layerFound = false;
for (const auto& layerProperties : availableLayers) {
if (strcmp(layerName, layerProperties.layerName) == 0) {
layerFound = true;
break;
}
}
if (!layerFound) {
return false;
}
}
return true;
}
void createSyncObjects() {
imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
imagesInFlight.resize(swapchain.images.size(), VK_NULL_HANDLE); // One per swapchain image
VkSemaphoreCreateInfo semaphoreInfo{};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
VkFenceCreateInfo fenceInfo{};
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences[i]) != VK_SUCCESS) {
throw std::runtime_error("Failed to create sync objects!");
}
}
std::cout << "Sync objects created (" << MAX_FRAMES_IN_FLIGHT << " frames in flight, "
<< swapchain.images.size() << " swapchain images)\n";
// Initialize OptiX AI Denoiser (Tensor Cores)
#ifdef CUDA_AVAILABLE
if (NvidiaDenoiserImpl::checkSupport(physicalDevice)) {
if (denoiser.initialize(physicalDevice, device, instance, WIDTH, HEIGHT)) {
denoiser.createSharedBuffers(physicalDevice, device);
std::cout << "\n========================================\n";
std::cout << " NVIDIA Tensor Cores: ACTIVE\n";
std::cout << " OptiX AI Denoiser: READY\n";
std::cout << "========================================\n";
}
}
#endif
}
void mainLoop() {
std::cout << "\n===========================================\n";
std::cout << " Racing Engine Ready!\n";
std::cout << " Rendering with Ray Tracing!\n";
std::cout << " Press ESC or close window to exit\n";
std::cout << "===========================================\n\n";
// Print initial debug info
std::cout << "\n=== DEBUG: Initial Scene State ===\n";
glm::vec3 camPos = camera.getPosition();
glm::vec3 camFront = camera.getFront();
std::cout << "Camera Position: ("
<< camPos.x << ", "
<< camPos.y << ", "
<< camPos.z << ")\n";
std::cout << "Camera Front: ("
<< camFront.x << ", "
<< camFront.y << ", "
<< camFront.z << ")\n";
std::cout << "Camera Pitch: " << camera.getPitch() << " degrees\n";
std::cout << "Camera Yaw: " << camera.getYaw() << " degrees\n\n";
for (const auto& entity : entityManager.getEntities()) {
std::cout << entity->name << ": pos("
<< entity->transform.position.x << ", "
<< entity->transform.position.y << ", "
<< entity->transform.position.z << ") scale("
<< entity->transform.scale.x << ", "
<< entity->transform.scale.y << ", "
<< entity->transform.scale.z << ")\n";
// Print 3x4 transform matrix
float mat[12];
entity->transform.getTransform3x4(mat);
std::cout << " Transform3x4:\n";
std::cout << " [" << mat[0] << ", " << mat[1] << ", " << mat[2] << ", " << mat[3] << "]\n";
std::cout << " [" << mat[4] << ", " << mat[5] << ", " << mat[6] << ", " << mat[7] << "]\n";
std::cout << " [" << mat[8] << ", " << mat[9] << ", " << mat[10] << ", " << mat[11] << "]\n";
}
std::cout << "==================================\n\n";
lastFrameTime = std::chrono::high_resolution_clock::now();
int frameCount = 0;
// FPS tracking
auto fpsStartTime = std::chrono::high_resolution_clock::now();
int fpsFrameCount = 0;
// Members currentFPS and frameTimeMs are used
float titleUpdateTimer = 0.0f;
// Initialize temporal accumulation tracking
lastCameraPos = camera.getPosition();
lastCameraFront = camera.getFront();
std::cout << "\n==========================================\n";
std::cout << " IZTAPALAPA EDITION v2.0 - NVIDIA ELITIST\n";
std::cout << "==========================================\n";
std::cout << "GPU Vendor: NVIDIA ONLY (0x10DE)\n";
std::cout << "RT Cores: FULLY UTILIZED (VK_KHR_ray_tracing)\n";
std::cout << "Tensor Cores: ENABLED (FP16/INT8 + AI Denoiser)\n";
std::cout << "AMD Compatibility: DISABLED (Hardcoded rejection)\n";
std::cout << "------------------------------------------\n";
std::cout << "Resolution: " << WIDTH << "x" << HEIGHT << "\n";
std::cout << "Samples: 8 SPP + R2 quasi-random\n";
std::cout << "Bounces: 8 max depth\n";
std::cout << "RNG: PCG (high quality)\n";
std::cout << "BRDF: GGX + Fresnel + Smith G\n";
std::cout << "Materials: Metallic + Roughness PBR\n";
std::cout << "Lighting: Physical sky + Sun + NEE\n";
std::cout << "Post-FX: Bloom + Vignette + Grain\n";
std::cout << "Tonemapping: ACES Filmic + sRGB\n";
std::cout << "==========================================\n";
std::cout << " DEJANDO EN RIDICULO A LOS AAA\n";
std::cout << "==========================================\n\n";
while (!glfwWindowShouldClose(window)) {
// Calculate delta time and frame time
auto currentTime = std::chrono::high_resolution_clock::now();
deltaTime = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - lastFrameTime).count();
frameTimeMs = deltaTime * 1000.0f;
lastFrameTime = currentTime;
// Calculate FPS
fpsFrameCount++;
auto fpsDuration = std::chrono::duration<float>(currentTime - fpsStartTime).count();
if (fpsDuration >= 1.0f) {
currentFPS = fpsFrameCount / fpsDuration;
fpsFrameCount = 0;
fpsStartTime = currentTime;
}
// Process input
glfwPollEvents();
camera.processKeyboard(window, deltaTime);
camera.update(deltaTime);
// Check if camera moved - reset accumulation if so
glm::vec3 currentCameraPos = camera.getPosition();
glm::vec3 currentCameraFront = camera.getFront();
bool cameraMoved = glm::length(currentCameraPos - lastCameraPos) > 0.001f ||
glm::length(currentCameraFront - lastCameraFront) > 0.001f;
if (cameraMoved) {
accumulationFrames = 0;
lastCameraPos = currentCameraPos;
lastCameraFront = currentCameraFront;
}
accumulationFrames++;
// Update entities
entityManager.update(deltaTime);
// Prepare TLAS instance data (CPU-side, before command buffer recording)
if (entityManager.countDynamic() > 0) {
const auto& transforms = entityManager.getTransforms();
acceleration.prepareInstanceData(device, transforms);
}
// Update window title with stats every 0.25s
titleUpdateTimer += deltaTime;
if (titleUpdateTimer >= 0.25f) {
updateWindowTitle();
titleUpdateTimer = 0.0f;
}
#if ENABLE_RENDER_LOOP_LOGGING
// Print detailed status to console periodically
if (frameCount % 120 == 0) {
std::stringstream ss;
ss << "\r[Frame " << frameCount << "] "
<< "FPS: " << (int)currentFPS << " | "
<< "Frame Time: " << frameTimeMs << "ms | "
<< "AccumFrames: " << accumulationFrames << " | "
<< "Samples: " << (accumulationFrames * 8);
logger.log(ss.str());
}
// Extra verbose debug every 500 frames
if (frameCount % 500 == 0 && frameCount > 0) {
std::stringstream ss;
ss << "\n[DEBUG Frame " << frameCount << "] "
<< "GPU Memory OK | "
<< "Sync objects valid | "
<< "currentFrame=" << currentFrame
<< "\n";
logger.log(ss.str());
}
#endif
frameCount++;
drawFrame();
// Run denoiser periodically when camera is still (during accumulation)
// Only denoise when we have accumulated enough samples and camera isn't moving
#ifdef CUDA_AVAILABLE
if (denoiserEnabled && denoiser.initialized && !cameraMoved &&
accumulationFrames > 1 && accumulationFrames % 32 == 0) {
runDenoiser();
}
#endif
}
vkDeviceWaitIdle(device);
}
// Debug tracking
inline static uint32_t debugFrameNumber = 0;
inline static uint32_t lastDebugPrintFrame = 0;
static constexpr bool VERBOSE_DEBUG = false; // Only print periodically
static constexpr int DEBUG_PRINT_INTERVAL = 500; // Print every N frames
#ifdef CUDA_AVAILABLE
void runDenoiser() {
// Run OptiX AI denoiser (Tensor Cores!)
// Async execution - no CPU blocking!
denoiser.denoiseImage(rayTracing.accumulationImage, rayTracing.accumulationImage,
device, graphicsQueue, rayTracing.commandPool);
#if ENABLE_RENDER_LOOP_LOGGING
logger.log("\n[DENOISER] Frame denoised with Tensor Cores!\n");
#endif
}
#endif
void printDebugStep(const char* step, uint32_t frame, int stepNum) {
#if ENABLE_RENDER_LOOP_LOGGING
if (VERBOSE_DEBUG || (frame - lastDebugPrintFrame >= DEBUG_PRINT_INTERVAL && stepNum == 0)) {
std::stringstream ss;
ss << "[F" << frame << "] " << step << "\n";
logger.log(ss.str());
if (stepNum == 0) lastDebugPrintFrame = frame;
}
#endif
}
void drawFrame() {
debugFrameNumber++;
printDebugStep("=== FRAME START ===", debugFrameNumber, 0);
// STEP 1: Wait for fence
printDebugStep("Step 1: Waiting for inFlightFence", debugFrameNumber, 1);
VkResult fenceResult = vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
if (fenceResult != VK_SUCCESS) {
std::cerr << "[F" << debugFrameNumber << "] FENCE WAIT FAILED: " << fenceResult << std::endl;
}
// STEP 2: Acquire image
printDebugStep("Step 2: Acquiring swapchain image", debugFrameNumber, 2);
uint32_t imageIndex;
VkResult result = vkAcquireNextImageKHR(device, swapchain.swapchain, UINT64_MAX,
imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
std::cerr << "[F" << debugFrameNumber << "] ACQUIRE FAILED: " << result << std::endl;
throw std::runtime_error("Failed to acquire swap chain image!");
}
// STEP 3: Wait for image-in-flight
printDebugStep("Step 3: Checking imagesInFlight", debugFrameNumber, 3);
if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
VkResult imgFenceResult = vkWaitForFences(device, 1, &imagesInFlight[imageIndex], VK_TRUE, UINT64_MAX);
if (imgFenceResult != VK_SUCCESS) {
std::cerr << "[F" << debugFrameNumber << "] IMAGE FENCE WAIT FAILED: " << imgFenceResult << std::endl;
}
}
imagesInFlight[imageIndex] = inFlightFences[currentFrame];
// STEP 4: Reset fence
printDebugStep("Step 4: Resetting fence", debugFrameNumber, 4);
vkResetFences(device, 1, &inFlightFences[currentFrame]);
// STEP 5: Update camera UBO with temporal reprojection data
printDebugStep("Step 5: Updating camera buffer", debugFrameNumber, 5);
// Calculate current view-projection matrix
glm::mat4 currentView = camera.getViewMatrix();
glm::mat4 currentProj = camera.getProjectionMatrix();
glm::mat4 currentViewProj = currentProj * currentView;
glm::vec3 currentCamPos = camera.getPosition();
CameraUBO cameraUBO{};
cameraUBO.viewInverse = camera.getViewInverse();
cameraUBO.projInverse = camera.getProjInverse();
cameraUBO.viewProj = currentViewProj;