11#include "graphics/shaders/deferred_lighting_frag_spv.inc"
12#include "graphics/shaders/deferred_lighting_vert_spv.inc"
24std::vector<uint32_t> embeddedSpirv(
const uint32_t* words,
size_t count) {
25 return std::vector<uint32_t>(words, words +
count);
30void Graphics::destroyDeferredLightingResources() {
31 destroyPipeline(device, deferredLightingPipeline);
32 destroyPipelineLayout(device, deferredLightingPipelineLayout);
33 deferredLightingSetLayout = vk::DescriptorSetLayout{};
34 deferredLightingSetLayoutUnique.reset();
35 deferredLightingFrames.clear();
36 if (deferredLightingSampler) {
37 device->destroySampler(deferredLightingSampler);
38 deferredLightingSampler =
nullptr;
42void Graphics::createDeferredLightingPipeline() {
43 if (deferredLightingPipeline || !sceneColorRenderPass)
return;
45 vkb::DescriptorSetLayoutBuilder layoutBuilder;
46 deferredLightingSetLayoutUnique =
47 layoutBuilder.buffer(0, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eFragment, 1)
48 .image(1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
49 .image(2, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
50 .image(3, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
51 .image(4, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
52 .image(5, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
53 .image(6, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
54 .buffer(7, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
55 .buffer(8, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
56 .buffer(9, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
57 .buffer(10, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eFragment, 1)
58 .image(11, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
59 .createUnique(device.instance);
60 deferredLightingSetLayout = *deferredLightingSetLayoutUnique;
61 deferredLightingPipelineLayout = createPipelineLayout(device, deferredLightingSetLayout);
63 auto vert = embeddedSpirv(deferred_lighting_vert_spv, deferred_lighting_vert_spv_count);
64 auto frag = embeddedSpirv(deferred_lighting_frag_spv, deferred_lighting_frag_spv_count);
65 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance,
vert);
66 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance,
frag);
67 deferredLightingPipeline = device.createPipeline()
68 .useClassicPipeline(vertModule, fragModule)
69 .setPipelineLayout(deferredLightingPipelineLayout)
70 .setDynamicStatesViewportScissor()
71 .setRasterizer(vk::PolygonMode::eFill,
false,
false, 1.0f,
72 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
73 .setMultisampler(
false, sceneColorSamples)
76 .setDepthStencil(
true,
true, vk::CompareOp::eAlways)
77 .setColorAttachmentCount(1)
78 .build(sceneColorRenderPass);
79 device->destroyShaderModule(vertModule);
80 device->destroyShaderModule(fragModule);
82 if (!deferredLightingSampler) {
83 vkb::SamplerBuilder sb;
84 deferredLightingSampler = sb.nearestClamp().build(device);
89 if (!sceneColorPassOpen || !sceneColorRenderPass)
return;
90 auto* gslot = currentGBufferSlot();
91 if (!gslot || !gslot->normalGpu.sampler)
return;
92 createDeferredLightingPipeline();
93 if (!deferredLightingPipeline || !descriptorPool)
return;
94 auto&
frame = currentSlot(deferredLightingFrames, frameSlotCount(), currentFrameSlot());
96 kHostVisibleCoherent);
98 vk::DescriptorSetAllocateInfo alloc{};
99 alloc.descriptorPool = descriptorPool;
100 alloc.descriptorSetCount = 1;
101 alloc.pSetLayouts = &deferredLightingSetLayout;
102 frame.set = device->allocateDescriptorSets(alloc).front();
104 const auto deferredLightingSet =
frame.set;
106 createShadowResources();
107 vk::ImageView shadowView = currentShadowArrayView();
108 if (!shadowView || !shadowSampler)
return;
112 if (!mesh3dClustered.
active) {
113 std::vector<ClusteredLightGpu> dirs;
114 if (glm::length(glm::vec3(mesh3dFrameUbo.
lightDir)) > 1e-4f) {
117 d.color = glm::vec4(glm::vec3(mesh3dFrameUbo.
lightColor), 1.f);
122 std::max(1, sceneColorWidth), std::max(1, sceneColorHeight), 1.f, mesh3dFrameUbo.
ambient);
126 uploadClusteredLighting(mesh3dClustered);
128 auto& storage = currentClusteredStorage();
129 if (!storage.lightsBuf.buffer || !storage.tableBuf.buffer || !storage.indicesBuf.buffer)
return;
133 ubo.view = mesh3dFrameUbo.
view;
134 ubo.lightDir = mesh3dFrameUbo.
lightDir;
137 ubo.lightDir.w = glm::length(glm::vec3(mesh3dFrameUbo.
lightDir)) > 1e-4f ? 1.f : 0.f;
139 ubo.cameraPos = glm::vec4(glm::vec3(mesh3dFrameUbo.
cameraPos), 0.f);
140 ubo.ambient = mesh3dFrameUbo.
ambient;
141 if (mesh3dClustered.
active) {
142 ubo.gridInfo = mesh3dClustered.
gridInfo;
143 ubo.clipInfo = mesh3dClustered.
clipInfo;
144 ubo.ambient = mesh3dClustered.
ambient;
146 ubo.lightColor = glm::vec4(glm::vec3(mesh3dClustered.
primaryColor), 0.f);
147 ubo.view = mesh3dClustered.
view;
149 ubo.clipInfo.z = float(std::max(1, sceneColorWidth));
150 ubo.clipInfo.w = float(std::max(1, sceneColorHeight));
151 frame.ubo.updateLocal(frameToken(), &ubo,
sizeof(ubo));
154 ensureMesh3dStrides();
155 auto& cfslots = currentMesh3dClusteredFrameSlots();
156 ensureMesh3dClusteredRing(cfslots);
157 if (cfslots.drawIndex >= cfslots.capacity)
158 throw Exception(
"drawDeferredLighting: clustered shadow UBO ring exhausted (%zu draws)", cfslots.capacity);
161 const size_t shadowSlot = cfslots.drawIndex++;
162 const uint32_t shadowOffset = uint32_t(shadowSlot) * shadowUboStride;
163 updateRingLocal(cfslots.shadowRing, shadowOffset, &mesh3dShadows.
ubo,
sizeof(
ShadowUBO));
166 vk::ImageLayout
layout = vk::ImageLayout::eShaderReadOnlyOptimal) {
167 vk::DescriptorImageInfo img{};
169 img.imageView =
view;
171 vk::WriteDescriptorSet
w{};
172 w.dstSet = deferredLightingSet;
174 w.descriptorCount = 1;
175 w.descriptorType = vk::DescriptorType::eCombinedImageSampler;
177 device->updateDescriptorSets(
w, {});
179 auto writeBuffer = [&](uint32_t
binding, vk::Buffer
buffer, vk::DeviceSize
size, vk::DescriptorType
type) {
180 vk::DescriptorBufferInfo buf{};
184 vk::WriteDescriptorSet
w{};
185 w.dstSet = deferredLightingSet;
187 w.descriptorCount = 1;
188 w.descriptorType =
type;
189 w.pBufferInfo = &buf;
190 device->updateDescriptorSets(
w, {});
194 writeImage(1, gslot->normal.imageView(), deferredLightingSampler);
195 writeImage(2, gslot->depthColor.imageView(), deferredLightingSampler);
196 writeImage(3, gslot->albedo.imageView(), deferredLightingSampler);
197 writeImage(4, gslot->pbrParams.imageView(), deferredLightingSampler);
198 writeImage(5, gslot->emissive.imageView(), deferredLightingSampler);
199 writeImage(6, gslot->depth.imageView(), deferredLightingSampler);
200 writeBuffer(7, storage.lightsBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
201 writeBuffer(8, storage.tableBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
202 writeBuffer(9, storage.indicesBuf.buffer, VK_WHOLE_SIZE, vk::DescriptorType::eStorageBuffer);
204 vk::DescriptorBufferInfo buf{};
205 buf.buffer = cfslots.shadowRing.buffer;
206 buf.offset = shadowOffset;
208 vk::WriteDescriptorSet
w{};
209 w.dstSet = deferredLightingSet;
211 w.descriptorCount = 1;
212 w.descriptorType = vk::DescriptorType::eUniformBuffer;
213 w.pBufferInfo = &buf;
214 device->updateDescriptorSets(
w, {});
216 writeImage(11, shadowView, vk::Sampler(shadowSampler), currentShadowMap().
image.currentLayout());
218 auto& cb = currentPresentCb();
219 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, deferredLightingPipeline);
220 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, deferredLightingPipelineLayout, 0, 1, &deferredLightingSet,
222 setViewportAndScissor(cb, uint32_t(sceneColorWidth), uint32_t(sceneColorHeight));
234 if (!phys || !surface)
return support;
235 const auto formats = phys.getSurfaceFormatsKHR(surface);
236 for (
const auto& fmt : formats) {
237 if (fmt.colorSpace == vk::ColorSpaceKHR::eHdr10St2084EXT &&
238 (fmt.format == vk::Format::eA2B10G10R10UnormPack32 || fmt.format == vk::Format::eA2R10G10B10UnormPack32))
239 support.
hdr10 =
true;
240 if (fmt.colorSpace == vk::ColorSpaceKHR::eExtendedSrgbLinearEXT &&
241 (fmt.format == vk::Format::eR16G16B16A16Sfloat || fmt.format == vk::Format::eB10G11R11UfloatPack32))
242 support.scRgb =
true;
247vk::SurfaceFormatKHR chooseSurfaceFormat(
const std::vector<vk::SurfaceFormatKHR>& available,
249 auto has = [&](vk::Format format, vk::ColorSpaceKHR space) {
250 for (
const auto& fmt : available)
251 if (fmt.format == format && fmt.
colorSpace == space) return true;
254 auto pickHdr10 = [&]() -> std::optional<vk::SurfaceFormatKHR> {
255 const vk::Format formats[] = {vk::Format::eA2B10G10R10UnormPack32, vk::Format::eA2R10G10B10UnormPack32};
256 for (vk::Format format : formats) {
257 if (
has(format, vk::ColorSpaceKHR::eHdr10St2084EXT))
258 return vk::SurfaceFormatKHR{format, vk::ColorSpaceKHR::eHdr10St2084EXT};
262 auto pickScRgb = [&]() -> std::optional<vk::SurfaceFormatKHR> {
263 const vk::Format formats[] = {vk::Format::eR16G16B16A16Sfloat, vk::Format::eB10G11R11UfloatPack32};
264 for (vk::Format format : formats) {
265 if (
has(format, vk::ColorSpaceKHR::eExtendedSrgbLinearEXT))
266 return vk::SurfaceFormatKHR{format, vk::ColorSpaceKHR::eExtendedSrgbLinearEXT};
271 std::optional<vk::SurfaceFormatKHR> chosen;
277 chosen = pickHdr10();
278 if (!chosen) chosen = pickScRgb();
289 const vk::SurfaceFormatKHR sdrPrefs[] = {
290 {vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear},
291 {vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear},
292 {vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear},
293 {vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear},
295 for (
const auto& pref : sdrPrefs) {
296 if (
has(pref.format, pref.colorSpace))
return pref;
298 if (!available.empty())
return available.front();
311 markSwapchainDirty();
316 if (!std::isfinite(paperWhiteNits) || !std::isfinite(peakNits))
326 if (!initialized || !surface)
329 "graphics.presentation"));
333void Graphics::applyPreferredSwapchainFormats(vkb::SwapchainBuilder& builder) {
335 std::vector<vk::SurfaceFormatKHR> available;
336 if (surface) available = device.physical_device->getSurfaceFormatsKHR(surface);
339 builder.set_desired_format(selectedSurfaceFormat_);
340 builder.add_fallback_format({vk::Format::eB8G8R8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear});
341 builder.add_fallback_format({vk::Format::eR8G8B8A8Unorm, vk::ColorSpaceKHR::eSrgbNonlinear});
342 builder.add_fallback_format({vk::Format::eB8G8R8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear});
343 builder.add_fallback_format({vk::Format::eR8G8B8A8Srgb, vk::ColorSpaceKHR::eSrgbNonlinear});
346void Graphics::destroyPresentComposeResources() {
347 if (device.instance) device->waitIdle();
348 for (
auto&
slot : presentComposeSlots) {
349 slot.colorTex.gpuHandle =
nullptr;
350 if (
slot.framebuffer) {
351 device->destroyFramebuffer(
slot.framebuffer);
352 slot.framebuffer = vk::Framebuffer{};
354 destroySampler(device,
slot.colorGpu.sampler);
356 presentComposeSlots.clear();
357 presentComposeWidth = 0;
358 presentComposeHeight = 0;
361void Graphics::ensurePresentComposeResources(
int composeW,
int composeH) {
362 if (composeW <= 0 || composeH <= 0)
return;
363 ensureHdrOffscreenPipelines();
364 if (!texSetLayout || !descriptorPool || !hdrOffscreenRenderPass)
return;
365 if (!presentComposeSlots.empty() && presentComposeWidth == composeW && presentComposeHeight == composeH)
return;
366 destroyPresentComposeResources();
367 presentComposeWidth = composeW;
368 presentComposeHeight = composeH;
369 const uint32_t
w = uint32_t(composeW);
370 const uint32_t
h = uint32_t(composeH);
371 const vk::Format colorFmt = vk::Format::eR16G16B16A16Sfloat;
372 presentComposeSlots.resize(kAsyncResourceCopies);
373 for (
auto&
slot : presentComposeSlots) {
374 slot.color = device.createColorTarget(
w,
h, colorFmt);
375 slot.framebuffer = hdrOffscreenRenderPass.createFramebuffer(device,
w,
h, {
slot.color.asAttachment()});
376 vkb::SamplerBuilder sb;
377 slot.colorGpu.sampler = sb.magFilter(vk::Filter::eLinear)
378 .minFilter(vk::Filter::eLinear)
379 .addressModeU(vk::SamplerAddressMode::eClampToEdge)
380 .addressModeV(vk::SamplerAddressMode::eClampToEdge)
382 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
383 slot.colorGpu.descriptorSet = vkb::BoundSet{sets[0]};
384 slot.colorGpu.width = composeW;
385 slot.colorGpu.height = composeH;
386 slot.colorGpu.viewOverride =
slot.color.imageView();
387 writeCombinedImageDescriptor(&
slot.colorGpu);
388 slot.colorTex.width = composeW;
389 slot.colorTex.height = composeH;
390 slot.colorTex.pixelWidth = composeW;
391 slot.colorTex.pixelHeight = composeH;
392 slot.colorTex.gpuHandle = &
slot.colorGpu;
396Graphics::PresentComposeSlot* Graphics::currentPresentComposeSlot() {
397 if (presentComposeSlots.empty())
return nullptr;
398 return &presentComposeSlots[currentFrameSlot() % presentComposeSlots.size()];
401bool Graphics::beginPresentComposePass() {
402 ensurePresentComposeResources(
int(swapchain.extent.width),
int(swapchain.extent.height));
403 auto*
slot = currentPresentComposeSlot();
404 if (!
slot || !hdrOffscreenRenderPass || !
slot->framebuffer)
return false;
405 auto& cb = currentPresentCb();
406 vk::ClearValue
clear{};
407 clear.color = vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, clearColor.a});
408 vk::RenderPassBeginInfo rpBegin{};
409 rpBegin.renderPass = hdrOffscreenRenderPass;
410 rpBegin.framebuffer =
slot->framebuffer;
411 rpBegin.renderArea = vk::Rect2D{{0, 0}, {uint32_t(presentComposeWidth), uint32_t(presentComposeHeight)}};
412 rpBegin.clearValueCount = 1;
413 rpBegin.pClearValues = &
clear;
414 slot->color.beginColorAttachment();
415 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
416 presentComposeActive_ =
true;
420void Graphics::endPresentComposePass() {
421 if (!presentComposeActive_)
return;
422 auto& cb = currentPresentCb();
424 if (
auto*
slot = currentPresentComposeSlot())
slot->color.endSampledLayout();
425 presentComposeActive_ =
false;
428void Graphics::encodePresentComposeToSwapchain(vk::CommandBuffer cb) {
429 auto*
slot = currentPresentComposeSlot();
430 if (!
slot || !
slot->colorTex.gpuHandle || !sceneTonemapPipeline)
return;
431 auto*
gpu =
static_cast<GpuTexture*
>(
slot->colorTex.gpuHandle);
437 batch.addTexturedRect(0.f, 0.f,
float(
width),
float(
height),
tint, 0.f, 0.f, 1.f, 1.f);
439 std::vector<TexturedVertex> gpuVerts;
440 gpuVerts.reserve(batch.vertices().size());
442 auto& frameBufs = currentFrame2DBuffers();
443 if (frameBufs.texBufs.empty()) frameBufs.texBufs.emplace_back();
446 frameBufs.texBufs.emplace_back();
447 vkb::HostVertexBuffer& vb = frameBufs.texBufs.back();
448 vb.allocate<TexturedVertex>(frameToken(), device, gpuVerts);
449 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, sceneTonemapPipeline);
450 vk::DescriptorSet texSet =
gpu->descriptorSet;
451 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0,
nullptr);
452 vk::DeviceSize
offset = 0;
453 cb.bindVertexBuffers(0, 1, vb, &
offset);
454 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
461void Graphics::ensureGpuVertexPool() {
462 if (gpuVertexPool_.positions.buffer)
return;
463 constexpr uint32_t kInitialVertices = 256u << 10;
464 constexpr uint32_t kInitialIndices = 768u << 10;
465 const auto hostMem = kHostVisibleCoherent;
466 gpuVertexPool_.positions = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
467 kInitialVertices *
sizeof(glm::vec4), hostMem);
468 gpuVertexPool_.normals = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
469 kInitialVertices *
sizeof(glm::vec4), hostMem);
470 gpuVertexPool_.uvs = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
471 kInitialVertices *
sizeof(glm::vec2), hostMem);
472 gpuVertexPool_.indices = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eStorageBuffer,
473 kInitialIndices *
sizeof(uint32_t), hostMem);
474 gpuVertexPool_.vertexCount = 0;
475 gpuVertexPool_.indexCount = 0;
478void Graphics::growGpuVertexPool(uint32_t needVertices, uint32_t needIndices) {
482 const uint32_t oldVerts = gpuVertexPool_.vertexCount;
483 const uint32_t oldInds = gpuVertexPool_.indexCount;
484 const auto hostMem = kHostVisibleCoherent;
485 auto copyInto = [&](vkb::GenericBuffer& dst, vkb::GenericBuffer& src, vk::DeviceSize oldBytes,
486 vk::DeviceSize newBytes) {
487 vkb::GenericBuffer grown(device, vk::BufferUsageFlagBits::eStorageBuffer, newBytes, hostMem);
489 void* srcMap = src.map();
490 void* dstMap = grown.map();
491 std::memcpy(dstMap, srcMap, oldBytes);
496 dst = std::move(grown);
500 const auto capacity = [](uint32_t needed) {
501 return uint32_t(std::min(uint64_t(needed) * 2u, uint64_t(UINT32_MAX)));
503 const uint32_t newVerts =
504 std::max(
capacity(needVertices), uint32_t(gpuVertexPool_.positions.size /
sizeof(glm::vec4)));
505 const uint32_t newInds = std::max(
capacity(needIndices), uint32_t(gpuVertexPool_.indices.size /
sizeof(uint32_t)));
506 copyInto(gpuVertexPool_.positions, gpuVertexPool_.positions, vk::DeviceSize(oldVerts) *
sizeof(glm::vec4),
507 vk::DeviceSize(newVerts) *
sizeof(glm::vec4));
508 copyInto(gpuVertexPool_.normals, gpuVertexPool_.normals, vk::DeviceSize(oldVerts) *
sizeof(glm::vec4),
509 vk::DeviceSize(newVerts) *
sizeof(glm::vec4));
510 copyInto(gpuVertexPool_.uvs, gpuVertexPool_.uvs, vk::DeviceSize(oldVerts) *
sizeof(glm::vec2),
511 vk::DeviceSize(newVerts) *
sizeof(glm::vec2));
512 copyInto(gpuVertexPool_.indices, gpuVertexPool_.indices, vk::DeviceSize(oldInds) *
sizeof(uint32_t),
513 vk::DeviceSize(newInds) *
sizeof(uint32_t));
514 bindGpuVertexPoolBindless();
517void Graphics::bindGpuVertexPoolBindless() {
518 if (bindlessSets_.empty() || !gpuVertexPool_.positions.buffer)
return;
519 auto bufWrite = [&](vk::DescriptorSet set, uint32_t
binding, vk::Buffer
buffer, vk::DeviceSize
size) {
521 vk::WriteDescriptorSet
w{};
524 w.descriptorCount = 1;
525 w.descriptorType = vk::DescriptorType::eStorageBuffer;
526 w.pBufferInfo = &
info;
527 device->updateDescriptorSets(1, &
w, 0,
nullptr);
529 const uint32_t cap = [&]() {
530 const vk::DeviceSize
bytes = gpuVertexPool_.positions.size;
531 return uint32_t(
bytes /
sizeof(glm::vec4));
533 const uint32_t indCap = uint32_t(gpuVertexPool_.indices.size /
sizeof(uint32_t));
534 for (vk::DescriptorSet set : bindlessSets_) {
535 bufWrite(set, 18, gpuVertexPool_.positions.buffer, vk::DeviceSize(cap) *
sizeof(glm::vec4));
536 bufWrite(set, 19, gpuVertexPool_.normals.buffer, vk::DeviceSize(cap) *
sizeof(glm::vec4));
537 bufWrite(set, 20, gpuVertexPool_.uvs.buffer, vk::DeviceSize(cap) *
sizeof(glm::vec2));
538 bufWrite(set, 21, gpuVertexPool_.indices.buffer, vk::DeviceSize(indCap) *
sizeof(uint32_t));
542void Graphics::appendGpuMeshToPool(GpuMesh&
gpu,
const std::vector<MeshVertex>*
vertices,
543 const std::vector<uint32_t>*
indices) {
544 if (!
gpu.vertices.buffer || !
gpu.indices.buffer)
return;
545 ensureGpuVertexPool();
546 const uint32_t nVerts =
gpu.record.vertexCount;
547 const uint32_t nInds =
gpu.record.indexCount;
548 if (nVerts == 0 || nInds == 0)
return;
549 const uint32_t newVerts = gpuVertexPool_.vertexCount + nVerts;
550 const uint32_t newInds = gpuVertexPool_.indexCount + nInds;
551 const uint32_t capVerts = uint32_t(gpuVertexPool_.positions.size /
sizeof(glm::vec4));
552 const uint32_t capInds = uint32_t(gpuVertexPool_.indices.size /
sizeof(uint32_t));
553 if (newVerts > capVerts || newInds > capInds) {
554 growGpuVertexPool(newVerts, newInds);
559 if (!vMap || !iMap)
return;
560 auto*
verts =
static_cast<const MeshVertex*
>(vMap);
561 auto* posDst =
static_cast<glm::vec4*
>(gpuVertexPool_.positions.map());
562 auto* nrmDst =
static_cast<glm::vec4*
>(gpuVertexPool_.normals.map());
563 auto* uvDst =
static_cast<glm::vec2*
>(gpuVertexPool_.uvs.map());
564 auto* idxDst =
static_cast<uint32_t*
>(gpuVertexPool_.indices.map());
565 if (!posDst || !nrmDst || !uvDst || !idxDst) {
570 posDst += gpuVertexPool_.vertexCount;
571 nrmDst += gpuVertexPool_.vertexCount;
572 uvDst += gpuVertexPool_.vertexCount;
573 idxDst += gpuVertexPool_.indexCount;
574 for (uint32_t i = 0; i < nVerts; ++i) {
575 posDst[i] = glm::vec4(
verts[i].
pos, 0.f);
577 uvDst[i] =
verts[i].uv;
579 if (!
indices &&
gpu.indexType == vk::IndexType::eUint16) {
580 const auto* src16 =
static_cast<const uint16_t*
>(iMap);
581 for (uint32_t i = 0; i < nInds; ++i) idxDst[i] = uint32_t(src16[i]);
583 const auto* src32 =
static_cast<const uint32_t*
>(iMap);
584 for (uint32_t i = 0; i < nInds; ++i) idxDst[i] = src32[i];
586 gpuVertexPool_.positions.unmap();
587 gpuVertexPool_.normals.unmap();
588 gpuVertexPool_.uvs.unmap();
589 gpuVertexPool_.indices.unmap();
594 gpu.record.vertexOffset = gpuVertexPool_.vertexCount;
595 gpu.record.indexOffset = gpuVertexPool_.indexCount;
596 gpu.record.firstIndex = 0;
597 gpu.record.vertexBase = 0;
598 gpuVertexPool_.vertexCount = newVerts;
599 gpuVertexPool_.indexCount = newInds;
602uint32_t Graphics::registerMeshRecord(GpuMesh*
gpu,
const std::vector<MeshVertex>*
vertices,
603 const std::vector<uint32_t>*
indices) {
609 if (
gpu->record.vertexCount == 0 &&
gpu->vertices.buffer) {
610 const uint32_t
vertexCount = uint32_t(
gpu->vertices.size /
sizeof(MeshVertex));
612 gpu->record.indexCount =
gpu->indexCount;
613 gpu->record.indexType =
gpu->indexType == vk::IndexType::eUint16 ? 0
u : 1u;
616 const auto*
verts =
static_cast<const MeshVertex*
>(map);
617 glm::vec3 minv(1e30f), maxv(-1e30f);
619 minv = glm::min(minv,
verts[i].
pos);
620 maxv = glm::max(maxv,
verts[i].
pos);
622 const glm::vec3
center = (minv + maxv) * 0.5f;
632 const uint32_t
idx = uint32_t(meshTableRecords_.size());
633 meshTableRecords_.push_back(
gpu->record);
634 meshRecordOwners_.push_back(
gpu);
635 gpu->gpuRecordIndex =
idx;
645vk::Pipeline Graphics::createMesh3DStylePipeline(
const std::vector<uint32_t>&
vert,
const std::vector<uint32_t>&
frag,
646 vk::PipelineLayout
layout,
const vkb::BuiltRenderPass& rp,
647 vk::SampleCountFlagBits samples,
BlendMode blend,
bool depthWrite,
648 bool doubleSided,
const MeshShaderRasterState& raster) {
649 vk::ShaderModuleCreateInfo vertexInfo{};
650 vertexInfo.codeSize =
vert.size() *
sizeof(uint32_t);
651 vertexInfo.pCode =
vert.data();
652 auto vertModule =
device->createShaderModuleUnique(vertexInfo);
653 vk::ShaderModuleCreateInfo fragmentInfo{};
654 fragmentInfo.codeSize =
frag.size() *
sizeof(uint32_t);
655 fragmentInfo.pCode =
frag.data();
656 auto fragModule =
device->createShaderModuleUnique(fragmentInfo);
657 const auto cull =
doubleSided ? vk::CullModeFlagBits::eNone : vk::CullModeFlagBits::eBack;
660 : vk::CompareOp::eLess;
663 std::vector<vk::PipelineColorBlendAttachmentState> attachments(1, makeBlendAttachment(
blend));
665 attachments[0].colorWriteMask = vk::ColorComponentFlags(raster.colorWriteMask);
666 vk::PipelineColorBlendStateCreateInfo cbs{};
667 cbs.attachmentCount = 1;
668 cbs.pAttachments = attachments.data();
671 .useClassicPipeline(vertModule.get(), fragModule.get())
672 .setPipelineLayout(
layout)
673 .setVertexInputState(
674 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
675 .setDynamicStatesViewportScissor()
676 .setRasterizer(vk::PolygonMode::eFill,
false,
false, 1.0f, cull, vk::FrontFace::eCounterClockwise)
677 .setMultisampler(
false, samples)
678 .setDepthBias(raster.depthBiasConstant, raster.depthBiasSlope)
679 .setDepthStencil(
true, depthWrite, compare)
680 .setColorBlending(cbs)
685 .useClassicPipeline(vertModule.get(), fragModule.get())
686 .setPipelineLayout(
layout)
687 .setVertexInputState(
688 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
689 .setDynamicStatesViewportScissor()
690 .setRasterizer(vk::PolygonMode::eFill,
false,
false, 1.0f, cull, vk::FrontFace::eCounterClockwise)
691 .setMultisampler(
false, samples)
692 .setDepthBias(raster.depthBiasConstant, raster.depthBiasSlope)
693 .setDepthStencil(
true, depthWrite, compare)
694 .setColorAttachmentCount(1)
std::vector< std::uint32_t > verts
std::uint32_t vertexCount
vk::UniqueSampler sampler
std::vector< std::uint32_t > indices
std::shared_ptr< OceanGpuSpectrum > gpu
std::unique_ptr< gpgpu::GpuBuffer > buffer
eve::action::ActionVfxBinding binding
std::array< double, 2 > vertices[3]
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
float displayPaperWhiteNits_
DisplayOutputMode
Requested swapchain present preference.
DisplayColorSpace activeDisplayColorSpace_
DisplayColorSpace
Color space actually selected for the live swapchain.
DisplayOutputMode displayOutputMode_
void drawDeferredLighting() override
Draws deferred lighting.
Result< void > setDisplayOutputMode(DisplayOutputMode mode) override
Sets the display output mode.
Result< DisplayOutputSupport > queryDisplayOutputSupport() const override
Queries display output support.
Result< void > setDisplayHdrCalibration(float paperWhiteNits, float peakNits) override
Sets the display hdr calibration.
void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload) override
Sets the mesh 3 d clustered lighting.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
Color sceneResolveTint(bool aces, ActiveColorSpace space, bool attachmentEncodesSrgb, float paperWhiteNits, float peakNits) noexcept
Build the Color tint used by the final scene present resolve.
void clampCalibration(float &paperWhiteNits, float &peakNits) noexcept
Clamp paper-white / peak luminance into the engine-supported range.
ActiveColorSpace
Active present color encoding after swapchain selection.
constexpr uint32_t kInvalidBindlessSlot
ClusteredLightingUpload buildClusteredLighting(const std::vector< ClusteredLightGpu > &points, const std::vector< ClusteredLightGpu > &dirs, const glm::mat4 &view, float nearZ, float farZ, int screenW, int screenH, float fovYRad, const glm::vec4 &ambient)
Build clustered tables for point lights in view space.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
bool has(const std::vector< std::reference_wrapper< const HouseComponent > > &values)
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
Surface present formats the current device/window can offer.
GPU light packing for mesh3d / PBR (std140-friendly).
Per-frame / per-draw CSM + local-spot constants (std140).
DeferredLightingUBO public API.