forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer_rendering.cpp
More file actions
2753 lines (2477 loc) · 127 KB
/
renderer_rendering.cpp
File metadata and controls
2753 lines (2477 loc) · 127 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
/* Copyright (c) 2025 Holochip Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "imgui/imgui.h"
#include "imgui_system.h"
#include "mesh_component.h"
#include "model_loader.h"
#include "renderer.h"
#include "transform_component.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <glm/gtx/norm.hpp>
#include <iomanip>
#include <iostream>
#include <map>
#include <ranges>
#include <sstream>
#include <stdexcept>
// ===================== Culling helpers implementation =====================
Renderer::FrustumPlanes Renderer::extractFrustumPlanes(const glm::mat4& vp) {
// Work in row-major form for standard plane extraction by transposing GLM's column-major matrix
glm::mat4 m = glm::transpose(vp);
FrustumPlanes fp{};
// Left : m[3] + m[0]
fp.planes[0] = m[3] + m[0];
// Right : m[3] - m[0]
fp.planes[1] = m[3] - m[0];
// Bottom : m[3] + m[1]
fp.planes[2] = m[3] + m[1];
// Top : m[3] - m[1]
fp.planes[3] = m[3] - m[1];
// Near : m[2] (matches Vulkan [0, 1] clip range)
fp.planes[4] = m[2];
// Far : m[3] - m[2]
fp.planes[5] = m[3] - m[2];
// Normalize planes
for (auto& p : fp.planes) {
glm::vec3 n(p.x, p.y, p.z);
float len = glm::length(n);
if (len > 0.0f) {
p /= len;
}
}
return fp;
}
void Renderer::transformAABB(const glm::mat4& M,
const glm::vec3& localMin,
const glm::vec3& localMax,
glm::vec3& outMin,
glm::vec3& outMax) {
// OBB (from model) to world AABB using center/extents and absolute 3x3
const glm::vec3 c = 0.5f * (localMin + localMax);
const glm::vec3 e = 0.5f * (localMax - localMin);
const glm::vec3 worldCenter = glm::vec3(M * glm::vec4(c, 1.0f));
// Upper-left 3x3
const glm::mat3 A = glm::mat3(M);
const glm::mat3 AbsA = glm::mat3(glm::abs(A[0]), glm::abs(A[1]), glm::abs(A[2]));
const glm::vec3 worldExtents = AbsA * e; // component-wise combination
outMin = worldCenter - worldExtents;
outMax = worldCenter + worldExtents;
}
bool Renderer::aabbIntersectsFrustum(const glm::vec3& worldMin,
const glm::vec3& worldMax,
const FrustumPlanes& frustum) {
// Use the p-vertex test against each plane; if outside any plane → culled
for (const auto& p : frustum.planes) {
const glm::vec3 n(p.x, p.y, p.z);
// Choose positive vertex (furthest in direction of normal)
glm::vec3 v{
n.x >= 0.0f ? worldMax.x : worldMin.x,
n.y >= 0.0f ? worldMax.y : worldMin.y,
n.z >= 0.0f ? worldMax.z : worldMin.z
};
// If the most positive vertex is still on the negative side of the plane,
// then the entire box is on the negative side.
// Use a small epsilon to avoid numerical issues.
if (glm::dot(n, v) + p.w < -0.01f) {
return false; // completely outside
}
}
return true;
}
// This file contains rendering-related methods from the Renderer class
// Create swap chain
bool Renderer::createSwapChain() {
try {
// Query swap chain support
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
// Choose swap surface format, present mode, and extent
vk::SurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
vk::PresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
vk::Extent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
// Choose image count
uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
imageCount = swapChainSupport.capabilities.maxImageCount;
}
// Create swap chain info
vk::SwapchainCreateInfoKHR createInfo{
.surface = *surface,
.minImageCount = imageCount,
.imageFormat = surfaceFormat.format,
.imageColorSpace = surfaceFormat.colorSpace,
.imageExtent = extent,
.imageArrayLayers = 1,
.imageUsage = vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eTransferDst,
.preTransform = swapChainSupport.capabilities.currentTransform,
.compositeAlpha = vk::CompositeAlphaFlagBitsKHR::eOpaque,
.presentMode = presentMode,
.clipped = VK_TRUE,
.oldSwapchain = nullptr
};
// Find queue families
QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
std::array<uint32_t, 2> queueFamilyIndicesLoc = {indices.graphicsFamily.value(), indices.presentFamily.value()};
// Set sharing mode
if (indices.graphicsFamily != indices.presentFamily) {
createInfo.imageSharingMode = vk::SharingMode::eConcurrent;
createInfo.queueFamilyIndexCount = static_cast<uint32_t>(queueFamilyIndicesLoc.size());
createInfo.pQueueFamilyIndices = queueFamilyIndicesLoc.data();
} else {
createInfo.imageSharingMode = vk::SharingMode::eExclusive;
createInfo.queueFamilyIndexCount = 0;
createInfo.pQueueFamilyIndices = nullptr;
}
// Create swap chain
swapChain = vk::raii::SwapchainKHR(device, createInfo);
// Get swap chain images
swapChainImages = swapChain.getImages();
// Swapchain images start in UNDEFINED layout; track per-image layout for correct barriers.
swapChainImageLayouts.assign(swapChainImages.size(), vk::ImageLayout::eUndefined);
// Store swap chain format and extent
swapChainImageFormat = surfaceFormat.format;
swapChainExtent = extent;
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create swap chain: " << e.what() << std::endl;
return false;
}
}
// ===================== Planar reflections resources =====================
bool Renderer::createReflectionResources(uint32_t width, uint32_t height) {
try {
destroyReflectionResources();
reflections.clear();
reflections.resize(MAX_FRAMES_IN_FLIGHT);
reflectionVPs.clear();
reflectionVPs.resize(MAX_FRAMES_IN_FLIGHT, glm::mat4(1.0f));
sampleReflectionVP = glm::mat4(1.0f);
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
auto& rt = reflections[i];
rt.width = width;
rt.height = height;
// Color RT: use swapchain format to match existing PBR pipeline rendering formats
vk::Format colorFmt = swapChainImageFormat;
auto [colorImg, colorAlloc] = createImagePooled(
width,
height,
colorFmt,
vk::ImageTiling::eOptimal,
// Allow sampling in glass and blitting to swapchain for diagnostics
vk::ImageUsageFlagBits::eColorAttachment | vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eDeviceLocal,
/*mipLevels*/
1,
vk::SharingMode::eExclusive,
{});
rt.color = std::move(colorImg);
rt.colorAlloc = std::move(colorAlloc);
rt.colorView = createImageView(rt.color, colorFmt, vk::ImageAspectFlagBits::eColor, 1);
// Simple sampler for sampling reflection texture (no mips)
vk::SamplerCreateInfo sampInfo{.magFilter = vk::Filter::eLinear, .minFilter = vk::Filter::eLinear, .mipmapMode = vk::SamplerMipmapMode::eNearest, .addressModeU = vk::SamplerAddressMode::eClampToEdge, .addressModeV = vk::SamplerAddressMode::eClampToEdge, .addressModeW = vk::SamplerAddressMode::eClampToEdge, .minLod = 0.0f, .maxLod = 0.0f};
rt.colorSampler = vk::raii::Sampler(device, sampInfo);
// Depth RT
vk::Format depthFmt = findDepthFormat();
auto [depthImg, depthAlloc] = createImagePooled(
width,
height,
depthFmt,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eDepthStencilAttachment,
vk::MemoryPropertyFlagBits::eDeviceLocal,
/*mipLevels*/
1,
vk::SharingMode::eExclusive,
{});
rt.depth = std::move(depthImg);
rt.depthAlloc = std::move(depthAlloc);
rt.depthView = createImageView(rt.depth, depthFmt, vk::ImageAspectFlagBits::eDepth, 1);
}
// One-time initialization: transition all per-frame reflection color images
// from UNDEFINED to SHADER_READ_ONLY_OPTIMAL so that the first frame can
// legally sample the "previous" frame's image.
if (!reflections.empty()) {
vk::CommandPoolCreateInfo poolInfo{
.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value()
};
vk::raii::CommandPool tempPool(device, poolInfo);
vk::CommandBufferAllocateInfo allocInfo{.commandPool = *tempPool, .level = vk::CommandBufferLevel::ePrimary, .commandBufferCount = 1};
vk::raii::CommandBuffers cbs(device, allocInfo);
vk::raii::CommandBuffer& cb = cbs[0];
cb.begin({.flags = vk::CommandBufferUsageFlagBits::eOneTimeSubmit});
std::vector<vk::ImageMemoryBarrier2> barriers;
barriers.reserve(reflections.size());
for (auto& rt : reflections) {
if (!!*rt.color) {
barriers.push_back(vk::ImageMemoryBarrier2{
.srcStageMask = vk::PipelineStageFlagBits2::eTopOfPipe,
.srcAccessMask = vk::AccessFlagBits2::eNone,
.dstStageMask = vk::PipelineStageFlagBits2::eFragmentShader,
.dstAccessMask = vk::AccessFlagBits2::eShaderRead,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *rt.color,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}
});
}
}
if (!barriers.empty()) {
vk::DependencyInfo depInfo{.imageMemoryBarrierCount = static_cast<uint32_t>(barriers.size()), .pImageMemoryBarriers = barriers.data()};
cb.pipelineBarrier2(depInfo);
}
cb.end();
vk::SubmitInfo submit{.commandBufferCount = 1, .pCommandBuffers = &*cb};
vk::raii::Fence fence(device, vk::FenceCreateInfo{}); {
std::lock_guard<std::mutex> lock(queueMutex);
graphicsQueue.submit(submit, *fence);
}
vk::Result result = waitForFencesSafe(*fence, VK_TRUE);
if (result != vk::Result::eSuccess) {
std::cerr << "Error: Failed to wait for reflection resource fence: " << vk::to_string(result) << std::endl;
}
}
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create reflection resources: " << e.what() << std::endl;
destroyReflectionResources();
return false;
}
}
void Renderer::destroyReflectionResources() {
for (auto& rt : reflections) {
rt.colorSampler = vk::raii::Sampler(nullptr);
rt.colorView = vk::raii::ImageView(nullptr);
rt.colorAlloc = nullptr;
rt.color = vk::raii::Image(nullptr);
rt.depthView = vk::raii::ImageView(nullptr);
rt.depthAlloc = nullptr;
rt.depth = vk::raii::Image(nullptr);
rt.width = rt.height = 0;
}
}
void Renderer::renderReflectionPass(vk::raii::CommandBuffer& cmd,
const glm::vec4& planeWS,
CameraComponent* camera,
const std::vector<RenderJob>& jobs) {
if (reflections.empty())
return;
auto& rt = reflections[currentFrame];
if (rt.width == 0 || rt.height == 0 || !*rt.colorView || !*rt.depthView)
return;
// Transition reflection color to COLOR_ATTACHMENT_OPTIMAL (Sync2)
vk::ImageMemoryBarrier2 toColor2{
.srcStageMask = vk::PipelineStageFlagBits2::eTopOfPipe,
.srcAccessMask = {},
.dstStageMask = vk::PipelineStageFlagBits2::eColorAttachmentOutput,
.dstAccessMask = vk::AccessFlagBits2::eColorAttachmentWrite | vk::AccessFlagBits2::eColorAttachmentRead,
.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.newLayout = vk::ImageLayout::eColorAttachmentOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *rt.color,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}
};
// Transition reflection depth to DEPTH_STENCIL_ATTACHMENT_OPTIMAL (Sync2)
vk::ImageMemoryBarrier2 toDepth2{
.srcStageMask = vk::PipelineStageFlagBits2::eTopOfPipe,
.srcAccessMask = {},
.dstStageMask = vk::PipelineStageFlagBits2::eEarlyFragmentTests,
.dstAccessMask = vk::AccessFlagBits2::eDepthStencilAttachmentWrite | vk::AccessFlagBits2::eDepthStencilAttachmentRead,
.oldLayout = vk::ImageLayout::eUndefined,
.newLayout = vk::ImageLayout::eDepthAttachmentOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *rt.depth,
.subresourceRange = {vk::ImageAspectFlagBits::eDepth, 0, 1, 0, 1}
};
std::array<vk::ImageMemoryBarrier2, 2> preBarriers{toColor2, toDepth2};
vk::DependencyInfo depInfoToColor{.imageMemoryBarrierCount = static_cast<uint32_t>(preBarriers.size()), .pImageMemoryBarriers = preBarriers.data()};
cmd.pipelineBarrier2(depInfoToColor);
vk::RenderingAttachmentInfo colorAtt{
.imageView = *rt.colorView,
.imageLayout = vk::ImageLayout::eColorAttachmentOptimal,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
// Clear to black so scene content dominates reflections
.clearValue = vk::ClearValue{vk::ClearColorValue{std::array < float, 4 >{0.0f, 0.0f, 0.0f, 1.0f}}}
};
vk::RenderingAttachmentInfo depthAtt{
.imageView = *rt.depthView,
.imageLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eDontCare,
.clearValue = vk::ClearValue{vk::ClearDepthStencilValue{1.0f, 0}}
};
vk::RenderingInfo rinfo{
.renderArea = vk::Rect2D({0, 0}, {rt.width, rt.height}),
.layerCount = 1,
.colorAttachmentCount = 1,
.pColorAttachments = &colorAtt,
.pDepthAttachment = &depthAtt
};
cmd.beginRendering(rinfo);
// Compute mirrored view matrix about planeWS (default Y=0 plane)
glm::mat4 reflectM(1.0f);
// For Y=0 plane, reflection is simply flip Y
if (glm::length(glm::vec3(planeWS.x, planeWS.y, planeWS.z)) > 0.5f && fabsf(planeWS.y - 1.0f) < 1e-3f && fabsf(planeWS.x) < 1e-3f && fabsf(planeWS.z) < 1e-3f) {
reflectM[1][1] = -1.0f;
} else {
// General plane reflection matrix R = I - 2*n*n^T for normalized plane; ignore translation for now
glm::vec3 n = glm::normalize(glm::vec3(planeWS));
glm::mat3 R = glm::mat3(1.0f) - 2.0f * glm::outerProduct(n, n);
reflectM = glm::mat4(R);
}
glm::mat4 viewReflected = camera ? (camera->GetViewMatrix() * reflectM) : reflectM;
glm::mat4 projReflected = camera ? camera->GetProjectionMatrix() : glm::mat4(1.0f);
currentReflectionVP = projReflected * viewReflected;
currentReflectionPlane = planeWS;
if (currentFrame < reflectionVPs.size()) {
reflectionVPs[currentFrame] = currentReflectionVP;
}
// Set viewport/scissor to reflection RT size
vk::Viewport rv(0.0f, 0.0f, static_cast<float>(rt.width), static_cast<float>(rt.height), 0.0f, 1.0f);
cmd.setViewport(0, rv);
vk::Rect2D rs({0, 0}, {rt.width, rt.height});
cmd.setScissor(0, rs);
// Draw opaque entities with mirrored view
// Use reflection-specific pipeline (cull none) to avoid mirrored winding issues.
if (!!*pbrReflectionGraphicsPipeline) {
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, *pbrReflectionGraphicsPipeline);
} else if (!!*pbrGraphicsPipeline) {
cmd.bindPipeline(vk::PipelineBindPoint::eGraphics, *pbrGraphicsPipeline);
}
// Prepare frustum for mirrored view to allow culling
FrustumPlanes reflectFrustum = extractFrustumPlanes(currentReflectionVP);
// Render all jobs (skip transparency)
for (const auto& job : jobs) {
Entity* entity = job.entity;
MeshComponent* meshComponent = job.meshComp;
EntityResources* entityRes = job.entityRes;
MeshResources* meshRes = job.meshRes;
if (entityRes->cachedIsBlended)
continue;
// Frustum culling for mirrored view
if (meshComponent->HasLocalAABB()) {
const glm::mat4 model = job.transformComp ? job.transformComp->GetModelMatrix() : glm::mat4(1.0f);
glm::vec3 wmin, wmax;
transformAABB(model, meshComponent->GetLocalAABBMin(), meshComponent->GetLocalAABBMax(), wmin, wmax);
if (!aabbIntersectsFrustum(wmin, wmax, reflectFrustum)) {
continue; // culled from reflection
}
}
// Bind geometry
std::array<vk::Buffer, 2> buffers = {*meshRes->vertexBuffer, *entityRes->instanceBuffer};
std::array<vk::DeviceSize, 2> offsets = {0, 0};
cmd.bindVertexBuffers(0, buffers, offsets);
cmd.bindIndexBuffer(*meshRes->indexBuffer, 0, vk::IndexType::eUint32);
// Populate UBO with mirrored view + clip plane and reflection flags
UniformBufferObject ubo{};
if (job.transformComp)
ubo.model = job.transformComp->GetModelMatrix();
else
ubo.model = glm::mat4(1.0f);
ubo.view = viewReflected;
ubo.proj = projReflected;
ubo.camPos = glm::vec4(camera ? camera->GetPosition() : glm::vec3(0), 1.0f);
ubo.reflectionPass = 1;
ubo.reflectionEnabled = 0;
ubo.reflectionVP = currentReflectionVP;
ubo.clipPlaneWS = planeWS;
// Ray query shadows in reflection pass
ubo.padding2 = enableRasterRayQueryShadows ? 1.0f : 0.0f;
updateUniformBufferInternal(currentFrame, entity, entityRes, camera, ubo);
// Bind descriptor set (PBR set 0)
cmd.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
*pbrPipelineLayout,
0,
*entityRes->pbrDescriptorSets[currentFrame],
nullptr);
// Push material properties
MaterialProperties mp = entityRes->cachedMaterialProps;
// Transmission suppressed during reflection pass via UBO (reflectionPass=1)
mp.transmissionFactor = 0.0f;
pushMaterialProperties(*cmd, mp);
// Issue draw
uint32_t instanceCount = std::max(1u, static_cast<uint32_t>(meshComponent->GetInstanceCount()));
cmd.drawIndexed(meshRes->indexCount, instanceCount, 0, 0, 0);
}
cmd.endRendering();
// Transition reflection color to SHADER_READ_ONLY for sampling in main pass (Sync2)
vk::ImageMemoryBarrier2 toSample2{
.srcStageMask = vk::PipelineStageFlagBits2::eColorAttachmentOutput,
.srcAccessMask = vk::AccessFlagBits2::eColorAttachmentWrite,
.dstStageMask = vk::PipelineStageFlagBits2::eFragmentShader,
.dstAccessMask = vk::AccessFlagBits2::eShaderRead,
.oldLayout = vk::ImageLayout::eColorAttachmentOptimal,
.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = *rt.color,
.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1}
};
vk::DependencyInfo depInfoToSample{.imageMemoryBarrierCount = 1, .pImageMemoryBarriers = &toSample2};
cmd.pipelineBarrier2(depInfoToSample);
}
// Create image views
bool Renderer::createImageViews() {
try {
opaqueSceneColorImages.clear();
opaqueSceneColorImageAllocations.clear();
opaqueSceneColorImageViews.clear();
opaqueSceneColorImageLayouts.clear();
opaqueSceneColorSampler.clear();
// Resize image views vector
swapChainImageViews.clear();
swapChainImageViews.reserve(swapChainImages.size());
// Create image view info template (image will be set per iteration)
vk::ImageViewCreateInfo createInfo{
.viewType = vk::ImageViewType::e2D,
.format = swapChainImageFormat,
.components = {
.r = vk::ComponentSwizzle::eIdentity,
.g = vk::ComponentSwizzle::eIdentity,
.b = vk::ComponentSwizzle::eIdentity,
.a = vk::ComponentSwizzle::eIdentity
},
.subresourceRange = {.aspectMask = vk::ImageAspectFlagBits::eColor, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1}
};
// Create image view for each swap chain image
for (const auto& image : swapChainImages) {
createInfo.image = image;
swapChainImageViews.emplace_back(device, createInfo);
}
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create image views: " << e.what() << std::endl;
return false;
}
}
// Setup dynamic rendering
bool Renderer::setupDynamicRendering() {
try {
// Create color attachment
colorAttachments = {
vk::RenderingAttachmentInfo{
.imageLayout = vk::ImageLayout::eColorAttachmentOptimal,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.clearValue = vk::ClearColorValue(std::array < float, 4 >{0.0f, 0.0f, 0.0f, 1.0f})
}
};
// Create depth attachment
depthAttachment = vk::RenderingAttachmentInfo{
.imageLayout = vk::ImageLayout::eDepthStencilAttachmentOptimal,
.loadOp = vk::AttachmentLoadOp::eClear,
.storeOp = vk::AttachmentStoreOp::eStore,
.clearValue = vk::ClearDepthStencilValue(1.0f, 0)
};
// Create rendering info
renderingInfo = vk::RenderingInfo{
.renderArea = vk::Rect2D(vk::Offset2D(0, 0), swapChainExtent),
.layerCount = 1,
.colorAttachmentCount = static_cast<uint32_t>(colorAttachments.size()),
.pColorAttachments = colorAttachments.data(),
.pDepthAttachment = &depthAttachment
};
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to setup dynamic rendering: " << e.what() << std::endl;
return false;
}
}
// Create command pool
bool Renderer::createCommandPool() {
try {
// Find queue families
QueueFamilyIndices queueFamilyIndicesLoc = findQueueFamilies(physicalDevice);
// Create command pool info
vk::CommandPoolCreateInfo poolInfo{
.flags = vk::CommandPoolCreateFlagBits::eResetCommandBuffer,
.queueFamilyIndex = queueFamilyIndicesLoc.graphicsFamily.value()
};
// Create command pool
commandPool = vk::raii::CommandPool(device, poolInfo);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create command pool: " << e.what() << std::endl;
return false;
}
}
// Create command buffers
bool Renderer::createCommandBuffers() {
try {
// Resize command buffers vector
commandBuffers.clear();
commandBuffers.reserve(MAX_FRAMES_IN_FLIGHT);
// Create command buffer allocation info
vk::CommandBufferAllocateInfo allocInfo{
.commandPool = *commandPool,
.level = vk::CommandBufferLevel::ePrimary,
.commandBufferCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT)
};
// Allocate command buffers
commandBuffers = vk::raii::CommandBuffers(device, allocInfo);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create command buffers: " << e.what() << std::endl;
return false;
}
}
// Create sync objects
bool Renderer::createSyncObjects() {
try {
// Resize semaphores and fences vectors
imageAvailableSemaphores.clear();
renderFinishedSemaphores.clear();
inFlightFences.clear();
// Semaphores per swapchain image (indexed by imageIndex from acquireNextImage)
// The presentation engine holds semaphores until the image is re-acquired, so we need
// one semaphore per swapchain image to avoid reuse conflicts. See Vulkan spec:
// https://docs.vulkan.org/guide/latest/swapchain_semaphore_reuse.html
const auto semaphoreCount = static_cast<uint32_t>(swapChainImages.size());
imageAvailableSemaphores.reserve(semaphoreCount);
renderFinishedSemaphores.reserve(semaphoreCount);
// Fences per frame-in-flight for CPU-GPU synchronization (indexed by currentFrame)
inFlightFences.reserve(MAX_FRAMES_IN_FLIGHT);
// Create semaphore info
vk::SemaphoreCreateInfo semaphoreInfo{};
// Create semaphores per swapchain image (indexed by imageIndex for presentation sync)
for (uint32_t i = 0; i < semaphoreCount; i++) {
imageAvailableSemaphores.emplace_back(device, semaphoreInfo);
renderFinishedSemaphores.emplace_back(device, semaphoreInfo);
}
// Create fences per frame-in-flight (indexed by currentFrame for CPU-GPU pacing)
vk::FenceCreateInfo fenceInfo{
.flags = vk::FenceCreateFlagBits::eSignaled
};
for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
inFlightFences.emplace_back(device, fenceInfo);
}
// Ensure uploads timeline semaphore exists (created early in createLogicalDevice)
// No action needed here unless reinitializing after swapchain recreation.
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create sync objects: " << e.what() << std::endl;
return false;
}
}
// Clean up swap chain
void Renderer::cleanupSwapChain() {
// Clean up depth resources
depthImageView = vk::raii::ImageView(nullptr);
depthImage = vk::raii::Image(nullptr);
depthImageAllocation = nullptr;
// Clean up swap chain image views
swapChainImageViews.clear();
// Note: Keep descriptor pool alive here to ensure descriptor sets remain valid during swapchain recreation.
// descriptorPool is preserved; it will be managed during full renderer teardown.
// Destroy reflection render targets if present
destroyReflectionResources();
// Clean up pipelines
graphicsPipeline = vk::raii::Pipeline(nullptr);
pbrGraphicsPipeline = vk::raii::Pipeline(nullptr);
lightingPipeline = vk::raii::Pipeline(nullptr);
// Clean up pipeline layouts
pipelineLayout = vk::raii::PipelineLayout(nullptr);
pbrPipelineLayout = vk::raii::PipelineLayout(nullptr);
lightingPipelineLayout = vk::raii::PipelineLayout(nullptr);
// Clean up sync objects (they need to be recreated with new swap chain image count)
imageAvailableSemaphores.clear();
renderFinishedSemaphores.clear();
inFlightFences.clear();
// Clean up swap chain
swapChain = vk::raii::SwapchainKHR(nullptr);
}
// Recreate swap chain
void Renderer::recreateSwapChain() {
// Prevent background uploads worker from mutating descriptors while we rebuild
StopUploadsWorker();
// Block descriptor writes while we rebuild swapchain and descriptor pools
descriptorSetsValid.store(false, std::memory_order_relaxed); {
// Drop any deferred descriptor updates that target old descriptor sets
std::lock_guard<std::mutex> lk(pendingDescMutex);
pendingDescOps.clear();
descriptorRefreshPending.store(false, std::memory_order_relaxed);
}
// Wait for all frames in flight to complete before recreating the swap chain
std::vector<vk::Fence> allFences;
allFences.reserve(inFlightFences.size());
for (const auto& fence : inFlightFences) {
allFences.push_back(*fence);
}
if (!allFences.empty()) {
vk::Result result = waitForFencesSafe(allFences, VK_TRUE);
if (result != vk::Result::eSuccess) {
std::cerr << "Error: Failed to wait for in-flight fences during swap chain recreation: " << vk::to_string(result) << std::endl;
}
}
// Wait for the device to be idle before recreating the swap chain
// External synchronization required (VVL): serialize against queue submits/present.
WaitIdle();
// Clean up old swap chain resources
cleanupSwapChain();
// Recreate swap chain and related resources
createSwapChain();
createImageViews();
setupDynamicRendering();
createDepthResources();
// (Re)create reflection resources if enabled
if (enablePlanarReflections) {
uint32_t rw = std::max(1u, static_cast<uint32_t>(static_cast<float>(swapChainExtent.width) * reflectionResolutionScale));
uint32_t rh = std::max(1u, static_cast<uint32_t>(static_cast<float>(swapChainExtent.height) * reflectionResolutionScale));
createReflectionResources(rw, rh);
}
// Recreate sync objects with correct sizing for new swap chain
createSyncObjects();
// Recreate off-screen opaque scene color and descriptor sets needed by transparent pass
createOpaqueSceneColorResources();
createTransparentDescriptorSets();
createTransparentFallbackDescriptorSets();
// Wait for all command buffers to complete before clearing resources
for (const auto& fence : inFlightFences) {
vk::Result result = waitForFencesSafe(*fence, VK_TRUE);
if (result != vk::Result::eSuccess) {
std::cerr << "Error: Failed to wait for fence before clearing resources: " << vk::to_string(result) << std::endl;
}
}
// Clear all entity descriptor sets since they're now invalid (allocated from the old pool)
{
// Serialize descriptor frees against any other descriptor operations
std::lock_guard<std::mutex> lk(descriptorMutex);
for (auto& kv : entityResources) {
auto& resources = kv.second;
resources.basicDescriptorSets.clear();
resources.pbrDescriptorSets.clear();
// Descriptor initialization flags must be reset because new descriptor sets
// will be allocated and only the current frame will be initialized at runtime.
resources.pbrUboBindingWritten.assign(MAX_FRAMES_IN_FLIGHT, false);
resources.basicUboBindingWritten.assign(MAX_FRAMES_IN_FLIGHT, false);
resources.pbrImagesWritten.assign(MAX_FRAMES_IN_FLIGHT, false);
resources.basicImagesWritten.assign(MAX_FRAMES_IN_FLIGHT, false);
resources.pbrFixedBindingsWritten.assign(MAX_FRAMES_IN_FLIGHT, false);
}
}
// Clear ray query descriptor sets - they reference the old output image which will be destroyed
// Must clear before recreating to avoid descriptor set corruption
rayQueryDescriptorSets.clear();
rayQueryDescriptorsWritten.clear();
rayQueryDescriptorsDirtyMask.store(0u, std::memory_order_relaxed);
// Destroy ray query output image resources - they're sized to old swapchain dimensions
rayQueryOutputImageView = vk::raii::ImageView(nullptr);
rayQueryOutputImage = vk::raii::Image(nullptr);
rayQueryOutputImageAllocation = nullptr;
createGraphicsPipeline();
createPBRPipeline();
createLightingPipeline();
createCompositePipeline();
// Recreate Forward+ specific pipelines/resources and resize tile buffers for new extent
if (useForwardPlus) {
createDepthPrepassPipeline();
uint32_t tilesX = (swapChainExtent.width + forwardPlusTileSizeX - 1) / forwardPlusTileSizeX;
uint32_t tilesY = (swapChainExtent.height + forwardPlusTileSizeY - 1) / forwardPlusTileSizeY;
createOrResizeForwardPlusBuffers(tilesX, tilesY, forwardPlusSlicesZ);
}
// Re-create command buffers to ensure fresh recording against new swapchain state
commandBuffers.clear();
createCommandBuffers();
currentFrame = 0;
// Recreate ray query resources with new swapchain dimensions
// This must happen after descriptor pool is valid but before marking descriptor sets valid
if (rayQueryEnabled && accelerationStructureEnabled) {
if (!createRayQueryResources()) {
std::cerr << "Warning: Failed to recreate ray query resources after swapchain recreation\n";
}
}
// Recreate descriptor sets for all entities after swapchain/pipeline rebuild
for (const auto& kv : entityResources) {
const auto& entity = kv.first;
if (!entity)
continue;
auto meshComponent = entity->GetComponent<MeshComponent>();
if (!meshComponent)
continue;
std::string texturePath = meshComponent->GetTexturePath();
// Fallback for basic pipeline: use baseColor when legacy path is empty
if (texturePath.empty()) {
const std::string& baseColor = meshComponent->GetBaseColorTexturePath();
if (!baseColor.empty()) {
texturePath = baseColor;
}
}
// Recreate basic descriptor sets (ignore failures here to avoid breaking resize)
createDescriptorSets(entity, texturePath, false);
// Recreate PBR descriptor sets
createDescriptorSets(entity, texturePath, true);
}
// Descriptor sets are now valid again
descriptorSetsValid.store(true, std::memory_order_relaxed);
// Resume background uploads worker now that swapchain and descriptors are recreated
StartUploadsWorker();
}
void Renderer::prepareFrameUboTemplate(CameraComponent* camera) {
frameUboTemplate = UniformBufferObject{};
if (!camera) return;
frameUboTemplate.view = camera->GetViewMatrix();
frameUboTemplate.proj = camera->GetProjectionMatrix();
frameUboTemplate.proj[1][1] *= -1; // Flip Y for Vulkan
frameUboTemplate.camPos = glm::vec4(camera->GetPosition(), 1.0f);
frameUboTemplate.lightCount = static_cast<int>(lastFrameLightCount);
frameUboTemplate.exposure = std::clamp(this->exposure, 0.2f, 4.0f);
frameUboTemplate.gamma = this->gamma;
frameUboTemplate.screenDimensions = glm::vec2(swapChainExtent.width, swapChainExtent.height);
frameUboTemplate.nearZ = camera->GetNearPlane();
frameUboTemplate.farZ = camera->GetFarPlane();
frameUboTemplate.slicesZ = static_cast<float>(forwardPlusSlicesZ);
int outputIsSRGB = (swapChainImageFormat == vk::Format::eR8G8B8A8Srgb ||
swapChainImageFormat == vk::Format::eB8G8R8A8Srgb) ? 1 : 0;
frameUboTemplate.padding0 = outputIsSRGB;
// Raster PBR shader uses padding1 as the Forward+ enable flag.
// 0 = disabled (always use global light loop), non-zero = enabled (use culled tile lists).
frameUboTemplate.padding1 = useForwardPlus ? 1.0f : 0.0f;
frameUboTemplate.padding2 = enableRasterRayQueryShadows ? 1.0f : 0.0f;
bool reflReady = false;
if (enablePlanarReflections && !reflections.empty()) {
const uint32_t count = static_cast<uint32_t>(reflections.size());
const uint32_t prev = (currentFrame + count - 1u) % count;
auto& rtPrev = reflections[prev];
reflReady = (!!*rtPrev.colorView) && (!!*rtPrev.colorSampler);
}
frameUboTemplate.reflectionEnabled = reflReady ? 1 : 0;
frameUboTemplate.reflectionVP = sampleReflectionVP;
frameUboTemplate.clipPlaneWS = currentReflectionPlane;
frameUboTemplate.reflectionIntensity = std::clamp(reflectionIntensity, 0.0f, 2.0f);
frameUboTemplate.enableRayQueryReflections = enableRayQueryReflections ? 1 : 0;
frameUboTemplate.enableRayQueryTransparency = enableRayQueryTransparency ? 1 : 0;
// Ray-query shared buffers are also used by raster PBR when doing ray-query shadows.
// Populate counts so shaders can bounds-check even when running in raster mode.
frameUboTemplate.geometryInfoCount = static_cast<int>(geometryInfoCountCPU);
frameUboTemplate.materialCount = static_cast<int>(materialCountCPU);
}
// Update uniform buffer
void Renderer::updateUniformBuffer(uint32_t currentImage, Entity* entity, EntityResources* entityRes, CameraComponent* camera, TransformComponent* tc) {
if (!entityRes) {
return;
}
// Get transform component
auto transformComponent = tc ? tc : (entity ? entity->GetComponent<TransformComponent>() : nullptr);
if (!transformComponent) {
return;
}
// Create uniform buffer object
UniformBufferObject ubo{};
ubo.model = transformComponent->GetModelMatrix();
ubo.view = camera->GetViewMatrix();
ubo.proj = camera->GetProjectionMatrix();
ubo.proj[1][1] *= -1; // Flip Y for Vulkan
// Continue with the rest of the uniform buffer setup
updateUniformBufferInternal(currentImage, entity, entityRes, camera, ubo);
}
// Overloaded version that accepts a custom transform matrix
void Renderer::updateUniformBuffer(uint32_t currentImage, Entity* entity, EntityResources* entityRes, CameraComponent* camera, const glm::mat4& customTransform) {
if (!entityRes) return;
// Create the uniform buffer object with custom transform
UniformBufferObject ubo{};
ubo.model = customTransform;
ubo.view = camera->GetViewMatrix();
ubo.proj = camera->GetProjectionMatrix();
ubo.proj[1][1] *= -1; // Flip Y for Vulkan
// Continue with the rest of the uniform buffer setup
updateUniformBufferInternal(currentImage, entity, entityRes, camera, ubo);
}
// Internal helper function to complete uniform buffer setup
void Renderer::updateUniformBufferInternal(uint32_t currentImage, Entity* entity, EntityResources* entityRes, CameraComponent* camera, UniformBufferObject& ubo) {
if (!entityRes) {
return;
}
// Use frame template for most fields
UniformBufferObject finalUbo = frameUboTemplate;
finalUbo.model = ubo.model;
// For reflection pass, we must override view/proj/reflection flags
if (ubo.reflectionPass == 1) {
finalUbo.view = ubo.view;
finalUbo.proj = ubo.proj;
finalUbo.reflectionPass = 1;
finalUbo.reflectionEnabled = 0;
finalUbo.reflectionVP = ubo.reflectionVP;
finalUbo.clipPlaneWS = ubo.clipPlaneWS;
finalUbo.padding2 = ubo.padding2;
}
// Copy to uniform buffer (guard against null mapped pointer)
void* dst = entityRes->uniformBuffersMapped[currentImage];
if (!dst) {
std::cerr << "Warning: UBO mapped ptr null for entity '" << (entity ? entity->GetName() : "unknown") << "' frame " << currentImage << std::endl;
return;
}
std::memcpy(dst, &finalUbo, sizeof(UniformBufferObject));
}
void Renderer::ensureEntityMaterialCache(Entity* entity, EntityResources& res) {
if (!entity)
return;
if (res.materialCacheValid)
return;
res.materialCacheValid = true;
res.cachedMaterial = nullptr;
res.cachedIsBlended = false;
res.cachedIsGlass = false;
res.cachedIsLiquid = false;
// Defaults represent the common case (no explicit material); textures come from descriptor bindings.
MaterialProperties mp{};
// Sensible defaults for entities without explicit material
mp.baseColorFactor = glm::vec4(1.0f);
mp.metallicFactor = 0.0f;
mp.roughnessFactor = 1.0f;
mp.baseColorTextureSet = 0;
mp.physicalDescriptorTextureSet = 0;
mp.normalTextureSet = -1;
mp.occlusionTextureSet = -1;
mp.emissiveTextureSet = -1;
mp.alphaMask = 0.0f;
mp.alphaMaskCutoff = 0.5f;
mp.emissiveFactor = glm::vec3(0.0f);
mp.emissiveStrength = 1.0f;
mp.transmissionFactor = 0.0f;
mp.useSpecGlossWorkflow = 0;
mp.glossinessFactor = 0.0f;
mp.specularFactor = glm::vec3(1.0f);
mp.ior = 1.5f;
mp.hasEmissiveStrengthExtension = 0;
if (modelLoader) {
const std::string& entityName = entity->GetName();
const size_t tagPos = entityName.find("_Material_");
if (tagPos != std::string::npos) {
const size_t afterTag = tagPos + std::string("_Material_").size();
if (afterTag < entityName.length()) {
// Entity name format: "modelName_Material_<index>_<materialName>"
const std::string remainder = entityName.substr(afterTag);
const size_t nextUnderscore = remainder.find('_');
if (nextUnderscore != std::string::npos && nextUnderscore + 1 < remainder.length()) {
const std::string materialName = remainder.substr(nextUnderscore + 1);
if (const Material* material = modelLoader->GetMaterial(materialName)) {
res.cachedMaterial = material;
res.cachedIsGlass = material->isGlass;
res.cachedIsLiquid = material->isLiquid;
// Base factors
mp.baseColorFactor = glm::vec4(material->albedo, material->alpha);
mp.metallicFactor = material->metallic;
mp.roughnessFactor = material->roughness;
// Texture set flags (-1 = no texture)