载入中...
搜索中...
未找到
GraphicsPipeline.cpp
浏览该文件的文档.
1#include "common/Profile.h"
2// Vulkan backend implementation — swapchain and pipeline creation.
3//
4// Re-split from the merged dev single-TU Graphics.cpp (pure move;
5// dev changes preserved). Shared helpers live in GraphicsInternal.h.
6
11#include "graphics/Light.h"
15#include "graphics/GBuffer.h"
16#include "graphics/Outline.h"
18
19#include <SDL2/SDL.h>
20#include <SDL2/SDL_vulkan.h>
21
22#include <algorithm>
23#include <array>
24#include <cmath>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <functional>
29#include <stdexcept>
30#include <string>
31#include <vector>
32#if !defined(_WIN32)
33#include <unistd.h>
34#endif
35
36#include "common/Exception.h"
38#include "common/config.h"
40#include "image/Image.h"
41#include "image/ImageData.h"
42#include "zeroerr/assert.h"
43
44#include <memory>
45
46
47#include <assimp/mesh.h>
48#include <assimp/matrix3x3.h>
49#include <assimp/matrix4x4.h>
50#include <assimp/vector3.h>
51#include <glm/gtc/matrix_transform.hpp>
52
53#include "graphics/shaders/color_frag_spv.inc"
54#include "graphics/shaders/color_vert_spv.inc"
55#include "graphics/shaders/decal_box_frag_spv.inc"
56#include "graphics/shaders/decal_box_vert_spv.inc"
57#include "graphics/shaders/lit2d_frag_spv.inc"
58#include "graphics/shaders/lit2d_vert_spv.inc"
59#include "graphics/shaders/mesh3d_clustered_frag_spv.inc"
60#include "graphics/shaders/mesh3d_clustered_vert_spv.inc"
61#include "graphics/shaders/mesh3d_frag_spv.inc"
62#include "graphics/shaders/mesh3d_gbuffer_alpha_frag_spv.inc"
63#include "graphics/shaders/mesh3d_gbuffer_frag_spv.inc"
64#include "graphics/shaders/mesh3d_gbuffer_instanced_frag_spv.inc"
65#include "graphics/shaders/mesh3d_gbuffer_instanced_vert_spv.inc"
66#include "graphics/shaders/mesh3d_gbuffer_skin_alpha_frag_spv.inc"
67#include "graphics/shaders/mesh3d_gbuffer_skin_frag_spv.inc"
68#include "graphics/shaders/mesh3d_gbuffer_skin_vert_spv.inc"
69#include "graphics/shaders/mesh3d_gbuffer_vert_spv.inc"
70#include "graphics/shaders/mesh3d_gpudriven_frag_spv.inc"
71#include "graphics/shaders/mesh3d_gpudriven_vert_spv.inc"
72#include "graphics/shaders/mesh3d_hair_frag_spv.inc"
73#include "graphics/shaders/mesh3d_hair_vert_spv.inc"
74#include "graphics/shaders/mesh3d_shadow_alpha_frag_spv.inc"
75#include "graphics/shaders/mesh3d_shadow_alpha_vert_spv.inc"
76#include "graphics/shaders/mesh3d_shadow_frag_spv.inc"
77#include "graphics/shaders/mesh3d_shadow_skin_alpha_frag_spv.inc"
78#include "graphics/shaders/mesh3d_shadow_skin_vert_spv.inc"
79#include "graphics/shaders/mesh3d_shadow_vert_spv.inc"
80#include "graphics/shaders/mesh3d_vert_spv.inc"
81#include "graphics/shaders/particle_distortion_frag_spv.inc"
82#include "graphics/shaders/primitive3d_frag_spv.inc"
83#include "graphics/shaders/primitive3d_vert_spv.inc"
84#include "graphics/shaders/resolve_vis_frag_spv.inc"
85#include "graphics/shaders/resolve_vis_vert_spv.inc"
86#include "graphics/shaders/scene_tonemap_frag_spv.inc"
87#include "graphics/shaders/textured_frag_spv.inc"
88#include "graphics/shaders/textured_opaque_frag_spv.inc"
89#include "graphics/shaders/textured_vert_spv.inc"
91
92namespace eve::graphics::vulkan {
93
94namespace {
95
96vk::Pipeline createPrimitive3DPipeline(vkb::Device &device, const vkb::BuiltRenderPass &renderPass,
97 vk::PipelineLayout layout, PrimitiveDepthMode depth, BlendMode blend,
98 PrimitiveCullMode cull, vk::SampleCountFlagBits samples) {
99 const bool depthTest = depth != PrimitiveDepthMode::Ignore;
100 const bool depthWrite = depth == PrimitiveDepthMode::TestAndWrite;
101 const vk::CullModeFlags cullFlags =
103 ? vk::CullModeFlagBits::eBack
104 : (cull == PrimitiveCullMode::Front ? vk::CullModeFlagBits::eFront : vk::CullModeFlagBits::eNone);
105 std::vector<vk::PipelineColorBlendAttachmentState> attachments(1, makeBlendAttachment(blend));
106 vk::PipelineColorBlendStateCreateInfo blending{};
107 blending.attachmentCount = 1;
108 blending.pAttachments = attachments.data();
109 return device.createPipeline()
110 .useClassicPipeline(embeddedSpirv(primitive3d_vert_spv), embeddedSpirv(primitive3d_frag_spv))
111 .setPipelineLayout(layout)
112 .setVertexInputState(vkb::VertexInputStateBuilder()
113 .addInputBinding<Primitive3DVertex>()
114 .addAttributeDescription<Primitive3DVertex>())
115 .setDynamicStatesViewportScissor()
116 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.f, cullFlags, vk::FrontFace::eCounterClockwise)
117 .setDepthStencil(depthTest, depthWrite, depthTest ? vk::CompareOp::eLessOrEqual : vk::CompareOp::eAlways)
118 .setMultisampler(false, samples)
119 .setColorBlending(blending)
120 .build(renderPass);
121}
122} // namespace
123
124// --- Swapchain and graphics pipelines -----------------------------------------
125
126void Graphics::destroyPresentGraphicsPipelines() {
127 auto destroyPipe = [&](vk::Pipeline &p) {
128 if (p) {
129 device->destroyPipeline(p);
130 p = nullptr;
131 }
132 };
133 destroyPipe(pipeline);
134 destroyPipe(solidAlphaPipeline);
135 destroyPipe(additiveSolidPipeline);
136 destroyPipe(premultipliedSolidPipeline);
137 destroyPipe(multiplySolidPipeline);
138 destroyPipe(texPipeline);
139 destroyPipe(additiveTexPipeline);
140 destroyPipe(premultipliedTexPipeline);
141 destroyPipe(multiplyTexPipeline);
142 destroyPipe(opaqueTexPipeline);
143 destroyPipe(particleDistortionPipeline);
144 destroyPipe(sceneTonemapPipeline);
145 destroyPipe(lit2dPipeline);
146 destroyPipe(lit2dAdditivePipeline);
147 destroyPipe(lit2dPremultipliedPipeline);
148 destroyPipe(lit2dMultiplyPipeline);
149 destroyPipe(lit2dOpaquePipeline);
150 destroyPipe(gpuParticleAlphaPipeline_);
151 destroyPipe(gpuParticleAdditivePipeline_);
152 destroyPipe(gpuParticlePremultipliedPipeline_);
153 destroyPipe(gpuParticleMultiplyPipeline_);
154 destroyPipe(gpuParticleOpaquePipeline_);
155 for (auto &g : ownedGpuShaders) {
156 if (!g || g->isMesh3D) continue;
157 destroyPipe(g->swapchainPipeline);
158 destroyPipe(g->swapchainOpaquePipeline);
159 }
160 if (renderpass) {
161 device->destroyRenderPass(renderpass);
162 renderpass = {};
163 }
164 presentAttachmentFormat_ = vk::Format::eUndefined;
165 // Mesh/scene-pass pipelines may still target the destroyed present RP.
166 scenePassPipelineTarget = vk::RenderPass{};
167}
168
169void Graphics::createSwapchainAndPipeline() {
171 // Framebuffers / command buffers alias the current swapchain images; tear
172 // them down before replacing the swapchain (destroy() waitIdles first).
173 presentRecording = {};
174 swapchainPass = {};
175 presentModel.waitForAllFrames();
176 destroyFrameCapture();
177 presentModel.destroy();
178 presentModel = vkb::Present{};
179
180 vkb::SwapchainBuilder swapchainBuilder = device.createSwapchain();
181 if (pixelWidth > 0 && pixelHeight > 0)
182 swapchainBuilder.set_desired_extent(uint32_t(pixelWidth), uint32_t(pixelHeight));
183 // Prefer HDR present formats when requested; always keep SDR UNORM fallbacks.
184 applyPreferredSwapchainFormats(swapchainBuilder);
185 if (vsyncEnabled) {
186 swapchainBuilder.set_desired_present_mode(vk::PresentModeKHR::eMailbox);
187 swapchainBuilder.add_fallback_present_mode(vk::PresentModeKHR::eFifo);
188 } else {
189 swapchainBuilder.set_desired_present_mode(vk::PresentModeKHR::eImmediate);
190 swapchainBuilder.add_fallback_present_mode(vk::PresentModeKHR::eMailbox);
191 swapchainBuilder.add_fallback_present_mode(vk::PresentModeKHR::eFifo);
192 }
193 // Allow screen getPixel / newImageData readback after present.
194 swapchainBuilder.add_image_usage_flags(vk::ImageUsageFlagBits::eTransferSrc);
195 // Retire the old swapchain before installing its replacement. MoltenVK
196 // 1.2.11 can force oldSwapchain presentation completion after setting the
197 // new CAMetalLayer size, overwriting it with 1x1. Completing retirement
198 // first keeps that shared-surface mutation ahead of new drawable setup.
199 swapchain.destroy();
200 swapchain = vkb::Swapchain{};
201 swapchain = swapchainBuilder.build();
202 if (swapchain.image_format != selectedSurfaceFormat_.format) {
203 // Builder fell through to an unlisted surface format; treat as SDR.
205 selectedSurfaceFormat_ = {swapchain.image_format, vk::ColorSpaceKHR::eSrgbNonlinear};
206 }
207
208 {
209 StartupStage stage(" vulkan: depth image");
210 depthImage = vkb::DepthStencilImage{device, swapchain.extent.width, swapchain.extent.height, depthFormat};
211 }
212
213 // HDR/SDR mode switches change the swapchain image format; cached present
214 // render-pass + pipelines must be rebuilt for the new attachment format.
215 if (renderpass && presentAttachmentFormat_ == vk::Format::eUndefined)
216 presentAttachmentFormat_ = swapchain.image_format;
217 if (renderpass && presentAttachmentFormat_ != swapchain.image_format)
218 destroyPresentGraphicsPipelines();
219
220 if (!renderpass) {
221 vkb::RenderPassBuilder rpBuilder{device};
222 renderpass =
223 rpBuilder.addPresentAttachment(swapchain.image_format, vk::AttachmentLoadOp::eClear)
224 .addDepthAttachment(depthFormat, vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eDontCare)
225 .addSubpass(vkb::SubpassBuilder()
226 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
227 .setDepthStencilAttachment(1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
228 .addDependency(
229 VK_SUBPASS_EXTERNAL, 0,
230 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests |
231 vk::PipelineStageFlagBits::eLateFragmentTests,
232 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
233 vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite,
234 vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite |
235 vk::AccessFlagBits::eDepthStencilAttachmentRead |
236 vk::AccessFlagBits::eDepthStencilAttachmentWrite)
237 .build();
238 presentAttachmentFormat_ = swapchain.image_format;
239 }
240
241 if (!pipeline) {
242 if (!pipelineLayout) pipelineLayout = createPipelineLayout(device);
243 pipeline = createSolidColorPipeline(device, renderpass, pipelineLayout);
244 solidAlphaPipeline = createSolidColorPipeline(device, renderpass, pipelineLayout,
246 additiveSolidPipeline = createSolidColorPipeline(device, renderpass, pipelineLayout,
248 premultipliedSolidPipeline = createSolidColorPipeline(
249 device, renderpass, pipelineLayout, BlendMode::Premultiplied);
250 multiplySolidPipeline = createSolidColorPipeline(device, renderpass, pipelineLayout,
252 }
253
254 // Recreate textured / tonemap / lit / particle draw pipelines when they were
255 // torn down with the present render pass (format change).
256 if (!texPipeline && texSetLayout) {
257 auto vert = embeddedSpirv(textured_vert_spv);
258 auto frag = embeddedSpirv(textured_frag_spv);
259 texPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout);
260 additiveTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
262 premultipliedTexPipeline = createTexturedStylePipeline(
263 vert, frag, renderpass, texPipelineLayout, BlendMode::Premultiplied);
264 multiplyTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
266 opaqueTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
268 particleDistortionPipeline = createTexturedStylePipeline(
269 vert, embeddedSpirv(particle_distortion_frag_spv), renderpass, texPipelineLayout,
271 sceneTonemapPipeline = createTexturedStylePipeline(
272 vert, embeddedSpirv(scene_tonemap_frag_spv), renderpass, texPipelineLayout,
274 if (lit2dPipelineLayout) {
275 auto lvert = embeddedSpirv(lit2d_vert_spv);
276 auto lfrag = embeddedSpirv(lit2d_frag_spv);
277 lit2dPipeline = createTexturedStylePipeline(lvert, lfrag, renderpass, lit2dPipelineLayout);
278 lit2dAdditivePipeline =
279 createTexturedStylePipeline(lvert, lfrag, renderpass, lit2dPipelineLayout, BlendMode::Additive);
280 lit2dPremultipliedPipeline =
281 createTexturedStylePipeline(lvert, lfrag, renderpass, lit2dPipelineLayout, BlendMode::Premultiplied);
282 lit2dMultiplyPipeline =
283 createTexturedStylePipeline(lvert, lfrag, renderpass, lit2dPipelineLayout, BlendMode::Multiply);
284 lit2dOpaquePipeline =
285 createTexturedStylePipeline(lvert, lfrag, renderpass, lit2dPipelineLayout, BlendMode::Opaque);
286 }
287 rebuildGpuParticleDrawPipelines(renderpass);
288 for (auto &shader : ownedShaders) {
289 if (!shader || !shader->gpuHandle) continue;
290 auto *gpu = static_cast<GpuShader *>(shader->gpuHandle);
291 if (gpu->isMesh3D || gpu->swapchainPipeline) continue;
292 gpu->swapchainPipeline = createTexturedStylePipeline(
293 shader->vertexSpirv(), shader->fragmentSpirv(), renderpass, shaderPipelineLayout);
294 gpu->swapchainOpaquePipeline = createTexturedStylePipeline(
295 shader->vertexSpirv(), shader->fragmentSpirv(), renderpass, shaderPipelineLayout,
297 }
298 }
299
300 // After a present format change scenePassPipelineTarget was cleared so the
301 // next ensureScenePassPipelines rebuilds against the live scene/present pass.
302 // On first create (no prior mesh pipelines) seed the target so the initial
303 // createMesh3DPipeline build is treated as matching the present pass.
304 if (!scenePassPipelineTarget && !mesh3dPipeline) {
305 scenePassPipelineTarget = vk::RenderPass(renderpass);
306 scenePassPipelineSamples = vk::SampleCountFlagBits::e1;
307 }
308
309 presentModel = device.createPresent(swapchain).build(renderpass, depthImage.imageView());
310 // Multi-frame overlap: submit + present without waiting on this frame's
311 // fence, so the CPU can build frame N+1 while the GPU still renders frame N.
312 // Present caps frames_in_flight at 2 (independent of swapchain image count)
313 // so present-wait semaphores are not reused while WSI still holds them.
314 // Per-frame mutable GPU resources must be multi-buffered (see *FrameSlots).
315 presentModel.synchronous_frames = false;
316 ensurePresentCaptureHook();
317 swapchainDirty = false;
318}
319
320void Graphics::createTexturedPipeline() {
321 if (texPipeline) return;
322
323 if (!texSetLayout) {
324 vkb::DescriptorSetLayoutBuilder layoutBuilder;
325 texSetLayoutUnique = layoutBuilder
326 .image(0, vk::DescriptorType::eCombinedImageSampler,
327 vk::ShaderStageFlagBits::eFragment, 1)
328 .image(1, vk::DescriptorType::eCombinedImageSampler,
329 vk::ShaderStageFlagBits::eFragment, 1)
330 .image(2, vk::DescriptorType::eCombinedImageSampler,
331 vk::ShaderStageFlagBits::eFragment, 1)
332 .image(3, vk::DescriptorType::eCombinedImageSampler,
333 vk::ShaderStageFlagBits::eFragment, 1)
334 .image(4, vk::DescriptorType::eCombinedImageSampler,
335 vk::ShaderStageFlagBits::eFragment, 1)
336 .createUnique(device.instance);
337 texSetLayout = *texSetLayoutUnique;
338
339 vk::DescriptorPoolSize poolSizes[] = {
340 {vk::DescriptorType::eCombinedImageSampler, 8192},
341 {vk::DescriptorType::eUniformBuffer, 2048},
342 // Dynamic-offset UBOs (per-frame mesh3d ring) count against their own
343 // pool size type; without this entry the first dynamic set allocation
344 // fails with VK_ERROR_OUT_OF_POOL_MEMORY.
345 {vk::DescriptorType::eUniformBufferDynamic, 4096},
346 {vk::DescriptorType::eStorageBuffer, 16384},
347 };
348 vk::DescriptorPoolCreateInfo poolInfo{};
349 poolInfo.flags = vk::DescriptorPoolCreateFlagBits::eFreeDescriptorSet;
350 poolInfo.maxSets = 8192;
351 poolInfo.poolSizeCount = 4;
352 poolInfo.pPoolSizes = poolSizes;
353 descriptorPool = device->createDescriptorPool(poolInfo);
354
355 texPipelineLayout = createPipelineLayout(device, texSetLayout);
356 const auto pcr =
357 pushConstantRange(vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
359 shaderPipelineLayout = createPipelineLayout(device, texSetLayout, &pcr);
360 }
361
362 auto vert = embeddedSpirv(textured_vert_spv);
363 auto frag = embeddedSpirv(textured_frag_spv);
364 texPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout);
365 additiveTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
367 premultipliedTexPipeline = createTexturedStylePipeline(
368 vert, frag, renderpass, texPipelineLayout, BlendMode::Premultiplied);
369 multiplyTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
371 opaqueTexPipeline = createTexturedStylePipeline(vert, frag, renderpass, texPipelineLayout,
373 particleDistortionPipeline = createTexturedStylePipeline(
374 vert, embeddedSpirv(particle_distortion_frag_spv), renderpass, texPipelineLayout,
376 sceneTonemapPipeline = createTexturedStylePipeline(
377 vert, embeddedSpirv(scene_tonemap_frag_spv), renderpass, texPipelineLayout,
379
380 createLit2DPipeline();
381 createGpuParticlePipelines();
382}
383
384vk::Pipeline Graphics::createTexturedStylePipeline(const std::vector<uint32_t> &vert,
385 const std::vector<uint32_t> &frag,
386 const vkb::BuiltRenderPass &rp,
387 vk::PipelineLayout layout, BlendMode mode,
388 vk::SampleCountFlagBits samples) {
389 ShaderModulePair modules(device, vert, frag);
390 if (mode == BlendMode::Additive || mode == BlendMode::Premultiplied ||
391 mode == BlendMode::Multiply) {
392 // cbs/attachments must outlive build(); keep the builder as a single
393 // expression (see createSolidColorPipeline).
394 std::vector<vk::PipelineColorBlendAttachmentState> attachments(1,
395 makeBlendAttachment(mode));
396 vk::PipelineColorBlendStateCreateInfo cbs{};
397 cbs.logicOpEnable = false;
398 cbs.attachmentCount = 1;
399 cbs.pAttachments = attachments.data();
400 return device.createPipeline()
401 .useClassicPipeline(modules.vert, modules.frag)
402 .setPipelineLayout(layout)
403 .setVertexInputState(vkb::VertexInputStateBuilder()
404 .addInputBinding<TexturedVertex>()
405 .addAttributeDescription<TexturedVertex>())
406 .setDynamicStatesViewportScissor()
407 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
408 vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise)
409 .setDepthStencil(false, false)
410 .setMultisampler(false, samples)
411 .setColorBlending(cbs)
412 .build(rp);
413 }
414 if (mode == BlendMode::Opaque) {
415 return device.createPipeline()
416 .useClassicPipeline(modules.vert, modules.frag)
417 .setPipelineLayout(layout)
418 .setVertexInputState(vkb::VertexInputStateBuilder()
419 .addInputBinding<TexturedVertex>()
420 .addAttributeDescription<TexturedVertex>())
421 .setDynamicStatesViewportScissor()
422 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
423 vk::CullModeFlagBits::eNone, vk::FrontFace::eCounterClockwise)
424 .setDepthStencil(false, false)
425 .setMultisampler(false, samples)
426 .setColorBlending()
427 .build(rp);
428 }
429 // Alpha (original behavior).
430 return device.createPipeline()
431 .useClassicPipeline(modules.vert, modules.frag)
432 .setPipelineLayout(layout)
433 .setVertexInputState(vkb::VertexInputStateBuilder()
434 .addInputBinding<TexturedVertex>()
435 .addAttributeDescription<TexturedVertex>())
436 .setDynamicStatesViewportScissor()
437 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
438 vk::FrontFace::eCounterClockwise)
439 .setDepthStencil(false, false)
440 .setMultisampler(false, samples)
441 .setAlphaBlending(1)
442 .build(rp);
443}
444
445void Graphics::createLit2DPipeline() {
446 if (lit2dPipeline) return;
447
448 vkb::DescriptorSetLayoutBuilder layoutBuilder;
449 lit2dSetLayoutUnique =
450 layoutBuilder
451 .image(0, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
452 .image(1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
453 .buffer(2, vk::DescriptorType::eUniformBuffer, vk::ShaderStageFlagBits::eFragment, 1)
454 .createUnique(device.instance);
455 lit2dSetLayout = *lit2dSetLayoutUnique;
456
457 lit2dPipelineLayout = createPipelineLayout(device, lit2dSetLayout);
458
459 // Offscreen (synchronous) lit-2D path owns a dedicated UBO. The swapchain
460 // path's per-frame UBOs are allocated lazily in currentLighting2dUbo().
461 offscreenLighting2dUbo.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
462 sizeof(Lighting2DUBO),
463 vk::MemoryPropertyFlagBits::eHostVisible |
464 vk::MemoryPropertyFlagBits::eHostCoherent);
465
466 auto vert = embeddedSpirv(lit2d_vert_spv);
467 auto frag = embeddedSpirv(lit2d_frag_spv);
468 lit2dPipeline = createTexturedStylePipeline(vert, frag, renderpass, lit2dPipelineLayout);
469 lit2dAdditivePipeline =
470 createTexturedStylePipeline(vert, frag, renderpass, lit2dPipelineLayout, BlendMode::Additive);
471 lit2dPremultipliedPipeline =
472 createTexturedStylePipeline(vert, frag, renderpass, lit2dPipelineLayout, BlendMode::Premultiplied);
473 lit2dMultiplyPipeline =
474 createTexturedStylePipeline(vert, frag, renderpass, lit2dPipelineLayout, BlendMode::Multiply);
475 lit2dOpaquePipeline = createTexturedStylePipeline(vert, frag, renderpass, lit2dPipelineLayout, BlendMode::Opaque);
476}
477
478vk::Pipeline Graphics::selectLit2DPipeline(BlendMode blend, bool offscreen, bool hdr) const {
479 auto pick = [](BlendMode mode, vk::Pipeline alpha, vk::Pipeline additive, vk::Pipeline premultiplied,
480 vk::Pipeline multiply, vk::Pipeline opaque) -> vk::Pipeline {
481 switch (mode) {
482 case BlendMode::Additive: return additive ? additive : alpha;
483 case BlendMode::Premultiplied: return premultiplied ? premultiplied : alpha;
484 case BlendMode::Multiply: return multiply ? multiply : alpha;
485 case BlendMode::Opaque: return opaque ? opaque : alpha;
486 case BlendMode::Alpha:
487 default: return alpha;
488 }
489 };
490 // HDR canvas flush and HDR present-compose both target hdrOffscreenRenderPass.
491 if ((offscreen && hdr) || (!offscreen && presentComposeActive_)) {
492 vk::Pipeline pipe =
493 pick(blend, hdrOffscreenLitPipeline, hdrOffscreenLitAdditivePipeline, hdrOffscreenLitPremultipliedPipeline,
494 hdrOffscreenLitMultiplyPipeline, hdrOffscreenLitOpaquePipeline);
495 if (pipe) return pipe;
496 }
497 if (offscreen) {
498 return pick(blend, offscreenLitPipeline, offscreenLitAdditivePipeline, offscreenLitPremultipliedPipeline,
499 offscreenLitMultiplyPipeline, offscreenLitOpaquePipeline);
500 }
501 return pick(blend, lit2dPipeline, lit2dAdditivePipeline, lit2dPremultipliedPipeline, lit2dMultiplyPipeline,
502 lit2dOpaquePipeline);
503}
504
505void Graphics::createMesh3DPipeline() {
506 if (mesh3dPipeline) return;
507
508 // Right-handed view, Y-up world. Projection uses perspectiveVulkanRH_ZO (Y flip for
509 // Vulkan NDC), so frontFace is Clockwise while mesh winding stays CCW in object space.
510 vkb::DescriptorSetLayoutBuilder layoutBuilder;
511 mesh3dSetLayoutUnique =
512 layoutBuilder.buffer(21, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eVertex, 1)
513 .buffer(0, vk::DescriptorType::eUniformBufferDynamic,
514 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
515 .image(1, vk::DescriptorType::eCombinedImageSampler,
516 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
517 .image(2, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
518 .image(3, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
519 .buffer(4, vk::DescriptorType::eUniformBufferDynamic, vk::ShaderStageFlagBits::eFragment, 1)
520 .image(5, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
521 .image(6, vk::DescriptorType::eCombinedImageSampler,
522 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
523 .image(7, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
524 .image(8, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
525 .image(9, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
526 .image(10, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
527 .image(16, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
528 .image(17, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
529 .image(18, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
530 .image(20, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
531 .createUnique(device.instance);
532 mesh3dSetLayout = *mesh3dSetLayoutUnique;
533
534 vkb::DescriptorSetLayoutBuilder skinLayoutBuilder;
535 skinPassSetLayoutUnique =
536 skinLayoutBuilder.buffer(2, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eVertex, 1)
537 .buffer(0, vk::DescriptorType::eUniformBufferDynamic,
538 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
539 .image(1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
540 .createUnique(device.instance);
541 skinPassSetLayout = *skinPassSetLayoutUnique;
542 skinPassPipelineLayout = createPipelineLayout(device, skinPassSetLayout);
543
544 mesh3dPipelineLayout = createPipelineLayout(device, mesh3dSetLayout);
545 const auto pcr =
546 pushConstantRange(vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
548 mesh3dShaderPipelineLayout = createPipelineLayout(device, mesh3dSetLayout, &pcr);
549
550 // Per-draw UBOs live in a per-frame-slot ring; descriptor sets are cached
551 // per texture combination (see mesh3dSetFor / ensureMesh3dRing).
552 mesh3dFrameSlots.clear();
553
554 // Deferred lighting copies G-buffer depth into scene color. Built-in opaque
555 // ForwardPlus overlays must accept that same surface depth, without blending
556 // a second lighting contribution. Transparent/custom raster policies stay unchanged.
557 auto vert = embeddedSpirv(mesh3d_vert_spv);
558 auto frag = embeddedSpirv(mesh3d_frag_spv);
559 mesh3dPipeline =
560 createMesh3DStylePipeline(vert, frag, mesh3dPipelineLayout, renderpass, vk::SampleCountFlagBits::e1,
562 mesh3dTransparentPipeline =
563 createMesh3DHairPipeline(vert, frag, mesh3dPipelineLayout, renderpass,
564 vk::SampleCountFlagBits::e1);
565 for (int blendValue = 0; blendValue < 5; ++blendValue) {
566 const auto blend = BlendMode(blendValue);
567 for (int depthValue = 0; depthValue < 2; ++depthValue) {
568 for (int doubleValue = 0; doubleValue < 2; ++doubleValue) {
569 const size_t index = mesh3dPipelineIndex(blend, depthValue != 0, doubleValue != 0);
570 mesh3dSurfacePipelines[index] = createMesh3DStylePipeline(
571 vert, frag, mesh3dPipelineLayout, renderpass, vk::SampleCountFlagBits::e1, blend, depthValue != 0,
572 doubleValue != 0,
575 }
576 }
577 }
578}
579
580void Graphics::createMesh3DClusteredPipeline() {
581 if (mesh3dClusteredPipeline) return;
582
583 vkb::DescriptorSetLayoutBuilder layoutBuilder;
584 mesh3dClusteredSetLayoutUnique =
585 layoutBuilder
586 .buffer(0, vk::DescriptorType::eUniformBufferDynamic,
587 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
588 .image(1, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
589 .image(2, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
590 .image(3, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
591 .buffer(4, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
592 .buffer(5, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
593 .buffer(6, vk::DescriptorType::eStorageBuffer, vk::ShaderStageFlagBits::eFragment, 1)
594 .buffer(7, vk::DescriptorType::eUniformBufferDynamic, vk::ShaderStageFlagBits::eFragment, 1)
595 .image(8, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
596 .image(9, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
597 .image(10, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
598 .image(11, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
599 .image(12, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
600 .image(18, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
601 .image(19, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
602 .image(20, vk::DescriptorType::eCombinedImageSampler, vk::ShaderStageFlagBits::eFragment, 1)
603 .createUnique(device.instance);
604 mesh3dClusteredSetLayout = *mesh3dClusteredSetLayoutUnique;
605
606 mesh3dClusteredPipelineLayout = createPipelineLayout(device, mesh3dClusteredSetLayout);
607
608 mesh3dClusteredFrameSlots.clear();
609
610 auto vert = embeddedSpirv(mesh3d_clustered_vert_spv);
611 auto frag = embeddedSpirv(mesh3d_clustered_frag_spv);
612 mesh3dClusteredPipeline =
613 createMesh3DStylePipeline(vert, frag, mesh3dClusteredPipelineLayout, renderpass, vk::SampleCountFlagBits::e1,
615}
616
617void Graphics::destroyShadowResources() {
618 resetDeferredFrameGraphs();
619 destroyPipeline(device, shadowPipeline);
620 destroyPipeline(device, shadowSingleSidedPipeline);
621 destroyPipelineLayout(device, shadowPipelineLayout);
622 destroyPipeline(device, shadowAlphaPipeline);
623 destroyPipeline(device, shadowAlphaSingleSidedPipeline);
624 destroyPipeline(device, shadowSkinPipeline);
625 destroyPipeline(device, shadowSkinSingleSidedPipeline);
626 destroyPipeline(device, shadowSkinAlphaPipeline);
627 destroyPipeline(device, shadowSkinAlphaSingleSidedPipeline);
628 destroyPipelineLayout(device, shadowAlphaPipelineLayout);
629 for (auto &slot : shadowMaps) {
630 for (int i = 0; i < ShadowConfig::kTotalLayers; ++i) {
631 if (slot.framebuffers[i]) {
632 device->destroyFramebuffer(slot.framebuffers[i]);
633 slot.framebuffers[i] = vk::Framebuffer{};
634 }
635 }
636 }
637 shadowMaps.clear();
638 allocatedShadowMapSize = 0;
639 if (shadowSampler) {
640 device->destroySampler(shadowSampler);
641 shadowSampler = vkb::DepthSampler{};
642 }
643 if (shadowRawSampler) {
644 device->destroySampler(shadowRawSampler);
645 shadowRawSampler = nullptr;
646 }
647 if (shadowRenderPass) {
648 device->destroyRenderPass(shadowRenderPass);
649 shadowRenderPass = {};
650 }
651 shadowPassCascade = -1;
652 shadowPassDraws.clear();
653 shadowPendingMask = 0;
654 for (auto &d : shadowCascadeDraws) d.clear();
655}
656
657void Graphics::destroyGBufferResources() {
658 resetDeferredFrameGraphs();
659 destroyPbrGBufferResources();
660 gbufferPassActive = false;
661 gbufferPending = false;
662 gbufferPassDraws.clear();
663 for (auto &slot : gbufferSlots) {
664 slot.normalTex.gpuHandle = nullptr;
665 slot.depthColorTex.gpuHandle = nullptr;
666 slot.albedoTex.gpuHandle = nullptr;
667 slot.pbrParamsTex.gpuHandle = nullptr;
668 slot.emissiveTex.gpuHandle = nullptr;
669 slot.visIDTex.gpuHandle = nullptr;
670 slot.visBaryTex.gpuHandle = nullptr;
671 slot.depthTex.gpuHandle = nullptr;
672 if (slot.framebuffer) {
673 device->destroyFramebuffer(slot.framebuffer);
674 slot.framebuffer = vk::Framebuffer{};
675 }
676 if (slot.visFramebuffer) {
677 device->destroyFramebuffer(slot.visFramebuffer);
678 slot.visFramebuffer = vk::Framebuffer{};
679 }
680 destroySampler(device, slot.normalGpu.sampler);
681 destroySampler(device, slot.depthColorGpu.sampler);
682 destroySampler(device, slot.albedoGpu.sampler);
683 destroySampler(device, slot.pbrParamsGpu.sampler);
684 destroySampler(device, slot.emissiveGpu.sampler);
685 destroySampler(device, slot.visIDGpu.sampler);
686 destroySampler(device, slot.visBaryGpu.sampler);
687 destroySampler(device, slot.depthGpu.sampler);
688 }
689 gbufferSlots.clear();
690 post2Sets.clear();
691 destroyPipeline(device, gbufferPipeline);
692 destroyPipeline(device, gbufferInstancedPipeline);
693 destroyPipeline(device, gbufferAlphaPipeline);
694 destroyPipeline(device, gbufferSkinPipeline);
695 destroyPipeline(device, gbufferSkinAlphaPipeline);
696 destroyPipeline(device, gbufferVisPipeline);
697 destroyPipeline(device, gbufferVgVisPipeline);
698 destroyPipelineLayout(device, gbufferPipelineLayout);
699 if (gbufferRenderPass) {
700 device->destroyRenderPass(gbufferRenderPass);
701 gbufferRenderPass = {};
702 }
703 if (gbufferVisRenderPass) {
704 device->destroyRenderPass(gbufferVisRenderPass);
705 gbufferVisRenderPass = {};
706 }
707 gbufferWidth = 0;
708 gbufferHeight = 0;
709 if (renderControl_) renderControl_->getGBuffer()->clear();
710}
711
712void Graphics::destroySceneColorResources() {
713 releaseFramePostTargets();
714 sceneColorPassOpen = false;
715 sceneColorHistoryValid = false;
716 if (device.instance) device->waitIdle();
717 destroyDeferredLightingResources();
718 for (auto &slot : sceneColorSlots) {
719 slot.colorTex.gpuHandle = nullptr;
720 if (slot.framebuffer) {
721 device->destroyFramebuffer(slot.framebuffer);
722 slot.framebuffer = vk::Framebuffer{};
723 }
724 destroySampler(device, slot.colorGpu.sampler);
725 }
726 sceneColorSlots.clear();
727 post2Sets.clear();
728 if (sceneColorRenderPass) {
729 device->destroyRenderPass(sceneColorRenderPass);
730 sceneColorRenderPass = {};
731 }
732 if (sceneColorResumeRenderPass) {
733 device->destroyRenderPass(sceneColorResumeRenderPass);
734 sceneColorResumeRenderPass = vk::RenderPass{};
735 }
736 sceneColorWidth = 0;
737 sceneColorHeight = 0;
738 sceneColorFormat = vk::Format::eUndefined;
739 sceneColorSamples = vk::SampleCountFlagBits::e1;
740}
741
742void Graphics::createUiColorResources(int uiW, int uiH) {
743 if (uiW <= 0 || uiH <= 0) return;
744 // Keep scene lighting in linear HDR. The swapchain remains display
745 // encoded and receives a separate final composite; regular script Canvas
746 // targets intentionally stay RGBA8.
747 const vk::Format colorFmt = vk::Format::eR16G16B16A16Sfloat;
748
749 const vk::SampleCountFlags supported =
750 device.physical_device.properties.limits.framebufferColorSampleCounts;
751 const vk::SampleCountFlagBits samples =
752 (supported & vk::SampleCountFlagBits::e4) ? vk::SampleCountFlagBits::e4
753 : vk::SampleCountFlagBits::e1;
754
755 // The render pass is size-independent and must remain stable for ImGui's
756 // lifetime: ImGui_ImplVulkan_Init builds its pipeline against it. Create it
757 // once, before any early-returns below.
758 if (!uiRenderPass) {
759 if (samples != vk::SampleCountFlagBits::e1) {
760 uiRenderPass =
761 device.createRenderPass()
762 .addColorAttachment(colorFmt, vk::AttachmentLoadOp::eClear,
763 vk::AttachmentStoreOp::eDontCare, samples)
764 .addResolveColorAttachment(colorFmt, vk::AttachmentLoadOp::eDontCare)
765 .addSubpass(vkb::SubpassBuilder()
766 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
767 .addResolveAttachment(1, vk::ImageLayout::eColorAttachmentOptimal))
768 .addExternalShaderReadDependencies()
769 .build();
770 } else {
771 uiRenderPass =
772 device.createRenderPass()
773 .addSampledColorAttachment(colorFmt)
774 .addSubpass(vkb::SubpassBuilder()
775 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal))
776 .addExternalShaderReadDependencies()
777 .build();
778 }
779 }
780 // Keep sample count in sync with the render pass even if target creation
781 // returns early (ImGui builds its pipeline from getUiMsaaSamples()).
782 uiColorSamples = samples;
783
784 if (!texSetLayout || !descriptorPool) return;
785 if (!uiTexturePipeline) {
786 const auto vert = embeddedSpirv(textured_vert_spv);
787 const auto frag = embeddedSpirv(textured_frag_spv);
788 const auto opaqueFrag = embeddedSpirv(textured_opaque_frag_spv);
789 uiTexturePipeline = createTexturedStylePipeline(vert, frag, uiRenderPass,
790 texPipelineLayout, BlendMode::Alpha,
791 uiColorSamples);
792 uiTextureOpaquePipeline = createTexturedStylePipeline(
793 vert, opaqueFrag, uiRenderPass, texPipelineLayout, BlendMode::Opaque,
794 uiColorSamples);
795 }
796
797 if (!uiColorSlots.empty() && uiColorWidth == uiW && uiColorHeight == uiH &&
798 uiColorFormat == colorFmt && uiColorSamples == samples)
799 return;
800 destroyUiColorTargets();
801
802 uiColorWidth = uiW;
803 uiColorHeight = uiH;
804 uiColorFormat = colorFmt;
805 uiColorSamples = samples;
806 const uint32_t w = uint32_t(uiW);
807 const uint32_t h = uint32_t(uiH);
808 const bool msaa = samples != vk::SampleCountFlagBits::e1;
809
810 uiColorSlots.resize(kAsyncResourceCopies);
811 for (auto &slot : uiColorSlots) {
812 slot.color = device.createColorTarget(w, h, colorFmt);
813 if (msaa) slot.msaaColor = device.createColorTarget(w, h, colorFmt, samples);
814 }
815 auto uiPass = uiRenderPass;
816
817 for (auto &slot : uiColorSlots) {
818 if (msaa) {
819 slot.framebuffer = uiPass.createFramebuffer(
820 device, w, h, {slot.msaaColor.asAttachment(), slot.color.asAttachment()});
821 } else {
822 slot.framebuffer = uiPass.createFramebuffer(device, w, h, {slot.color.asAttachment()});
823 }
824 }
825
826 auto makeSampleTex = [&](GpuTexture &gpu, Texture &tex, vk::ImageView view) {
827 vkb::SamplerBuilder sb;
828 gpu.sampler = sb.magFilter(vk::Filter::eLinear)
829 .minFilter(vk::Filter::eLinear)
830 .addressModeU(vk::SamplerAddressMode::eClampToEdge)
831 .addressModeV(vk::SamplerAddressMode::eClampToEdge)
832 .build(device);
833 auto sets = vkb::DescriptorSetBuilder()
834 .layout(texSetLayout)
835 .build(device.instance, descriptorPool);
836 gpu.descriptorSet = vkb::BoundSet{sets[0]};
837 // Stamp the actual UI target extent, not Graphics::width/height — those
838 // can diverge from the offscreen size for one frame around resize.
839 gpu.width = uiW;
840 gpu.height = uiH;
841 gpu.viewOverride = view;
842 writeCombinedImageDescriptor(&gpu);
843 tex.width = uiW;
844 tex.height = uiH;
845 tex.pixelWidth = uiW;
846 tex.pixelHeight = uiH;
847 tex.gpuHandle = &gpu;
848 };
849 for (auto &slot : uiColorSlots)
850 makeSampleTex(slot.colorGpu, slot.colorTex, slot.color.imageView());
851}
852
853void Graphics::destroyUiColorTargets() {
854 if (device.instance) device->waitIdle();
855 for (auto &slot : uiColorSlots) {
856 slot.colorTex.gpuHandle = nullptr;
857 if (slot.framebuffer) {
858 device->destroyFramebuffer(slot.framebuffer);
859 slot.framebuffer = vk::Framebuffer{};
860 }
861 destroySampler(device, slot.colorGpu.sampler);
862 }
863 uiColorSlots.clear();
864 uiColorWidth = 0;
865 uiColorHeight = 0;
866 uiColorFormat = vk::Format::eUndefined;
867 // Keep uiColorSamples matching uiRenderPass; ImGui's pipeline is bound to it.
868}
869
870void Graphics::destroyUiColorResources() {
871 destroyUiColorTargets();
872 if (uiTexturePipeline) {
873 device->destroyPipeline(uiTexturePipeline);
874 uiTexturePipeline = nullptr;
875 }
876 if (uiTextureOpaquePipeline) {
877 device->destroyPipeline(uiTextureOpaquePipeline);
878 uiTextureOpaquePipeline = nullptr;
879 }
880 if (uiRenderPass) {
881 device->destroyRenderPass(uiRenderPass);
882 uiRenderPass = {};
883 }
884}
885
886void Graphics::queueUiResolve() {
887 auto *slot = currentUiColorSlot();
888 if (!slot || !slot->colorTex.gpuHandle) return;
889 // HDR present always composites UI in paper-white-relative linear space on
890 // the compose target (or, on the rare already-open swapchain path, draws
891 // ImGui directly). Never bind the opaque DisplayEncode path here — it would
892 // replace transparent texels with the UI clear color.
893 TexturedBatch resolve{&slot->colorTex, nullptr, nullptr, BlendMode::Alpha, Batcher{}};
894 // The overlay texture is physical pixels; the compositing batch uses logical coordinates.
895 resolve.batch.addTexturedRect(0.f, 0.f, float(width), float(height), Color(1.f, 1.f, 1.f, 1.f), 0.f, 0.f, 1.f, 1.f);
896 pendingUiResolve = std::move(resolve);
897}
898
899bool Graphics::renderUiOverlayPass() {
900 if (!presentOverlayFn_) return false;
901 if (!presentOverlayFn_(presentOverlayUser_, nullptr)) return false;
902 createUiColorResources(int(swapchain.extent.width), int(swapchain.extent.height));
903 auto *slot = currentUiColorSlot();
904 if (!slot || !uiRenderPass || !slot->framebuffer) return false;
905
906 auto &cb = currentPresentCb();
907 const bool msaa = uiColorSamples != vk::SampleCountFlagBits::e1;
908 std::array<vk::ClearValue, 2> clears{};
909 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0.f, 0.f, 0.f, 0.f});
910 clears[1].color = vk::ClearColorValue(std::array<float, 4>{0.f, 0.f, 0.f, 0.f});
911 vk::RenderPassBeginInfo rpBegin{};
912 rpBegin.renderPass = uiRenderPass;
913 rpBegin.framebuffer = slot->framebuffer;
914 rpBegin.renderArea = vk::Rect2D{{0, 0}, {uint32_t(uiColorWidth), uint32_t(uiColorHeight)}};
915 rpBegin.clearValueCount = msaa ? 2 : 1;
916 rpBegin.pClearValues = clears.data();
917
918 slot->color.beginColorAttachment();
919 if (msaa) slot->msaaColor.beginColorAttachment();
920 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
921
922 VkCommandBuffer raw = static_cast<VkCommandBuffer>(cb);
924
925 cb.endRenderPass();
926 slot->color.endSampledLayout();
927 queueUiResolve();
928 return true;
929}
930
931
932void Graphics::createGBufferResources(int gbufW, int gbufH) {
933 if (gbufW <= 0 || gbufH <= 0) return;
934 if (!gbufferSlots.empty() && gbufferWidth == gbufW && gbufferHeight == gbufH && gbufferPipeline)
935 return;
936 destroyGBufferResources();
937
938 gbufferWidth = gbufW;
939 gbufferHeight = gbufH;
940 const uint32_t w = uint32_t(gbufW);
941 const uint32_t h = uint32_t(gbufH);
942 const vk::Format colorFmt = pickGBufferColorFormat(device);
943 const vk::Format depthFmt = vk::Format::eD32Sfloat;
944 const vk::Format visIDFmt = vk::Format::eR32G32Uint;
945 const vk::Format visBaryFmt = vk::Format::eR16G16Sfloat;
946
947 gbufferSlots.resize(kAsyncResourceCopies);
948 for (auto &slot : gbufferSlots) {
949 slot.normal = device.createColorTarget(w, h, colorFmt);
950 slot.depthColor = device.createColorTarget(w, h, colorFmt);
951 slot.albedo = device.createColorTarget(w, h, colorFmt);
952 slot.pbrParams = device.createColorTarget(w, h, colorFmt);
953 slot.emissive = device.createColorTarget(w, h, vk::Format::eR16G16B16A16Sfloat);
954 slot.visID = device.createColorTarget(w, h, visIDFmt);
955 slot.visBary = device.createColorTarget(w, h, visBaryFmt);
956 slot.depth = device.createDepthTarget(w, h, depthFmt, true);
957 }
958
959 auto gbufferPass =
960 device.createRenderPass()
961 .addSampledColorAttachment(colorFmt)
962 .addSampledColorAttachment(colorFmt)
963 .addSampledColorAttachment(colorFmt)
964 .addSampledColorAttachment(colorFmt)
965 .addSampledColorAttachment(vk::Format::eR16G16B16A16Sfloat)
966 .addSampledDepthAttachment(depthFmt)
967 .addSubpass(vkb::SubpassBuilder()
968 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
969 .addAttachmentRef(1, vk::ImageLayout::eColorAttachmentOptimal)
970 .addAttachmentRef(2, vk::ImageLayout::eColorAttachmentOptimal)
971 .addAttachmentRef(3, vk::ImageLayout::eColorAttachmentOptimal)
972 .addAttachmentRef(4, vk::ImageLayout::eColorAttachmentOptimal)
973 .setDepthStencilAttachment(5, vk::ImageLayout::eDepthStencilAttachmentOptimal))
974 // Match the FrameGraph render pass used to record this pipeline:
975 // imported G-buffer targets begin undefined and leave sampled, so
976 // only the subpass-to-reader dependency is materialized.
977 .addDependency(0, VK_SUBPASS_EXTERNAL,
978 vk::PipelineStageFlagBits::eColorAttachmentOutput |
979 vk::PipelineStageFlagBits::eEarlyFragmentTests |
980 vk::PipelineStageFlagBits::eLateFragmentTests,
981 vk::PipelineStageFlagBits::eVertexShader | vk::PipelineStageFlagBits::eFragmentShader,
982 vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite,
983 vk::AccessFlagBits::eShaderRead)
984 .build();
985 gbufferRenderPass = gbufferPass;
986
987 for (auto &slot : gbufferSlots) {
988 slot.framebuffer = gbufferPass.createFramebuffer(
989 device, w, h,
990 {slot.normal.asAttachment(), slot.depthColor.asAttachment(), slot.albedo.asAttachment(),
991 slot.pbrParams.asAttachment(), slot.emissive.asAttachment(), slot.depth.asAttachment()});
992 }
993
994 auto layoutBuilder = device.createPipelineLayout();
995 if (texSetLayout) layoutBuilder.set(texSetLayout);
996 gbufferPipelineLayout =
997 layoutBuilder
998 .push<GBufferPush>(vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment)
999 .build();
1000
1001 // All mesh G-buffer shaders emit zero emissive. Preserve the attachment's
1002 // black clear without redundant per-fragment writes when the enabled
1003 // device feature permits different attachment masks.
1004 std::array<vk::PipelineColorBlendAttachmentState, 5> gbufferBlendAttachments{};
1005 const size_t writableTargets = device.physical_device.features.independentBlend ? 4u : 5u;
1006 for (size_t i = 0; i < writableTargets; ++i)
1007 gbufferBlendAttachments[i].colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG |
1008 vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA;
1009 vk::PipelineColorBlendStateCreateInfo gbufferBlend{};
1010 gbufferBlend.setAttachments(gbufferBlendAttachments);
1011
1012 std::vector<uint32_t> vert(mesh3d_gbuffer_vert_spv,
1013 mesh3d_gbuffer_vert_spv + mesh3d_gbuffer_vert_spv_count);
1014 std::vector<uint32_t> frag(mesh3d_gbuffer_frag_spv,
1015 mesh3d_gbuffer_frag_spv + mesh3d_gbuffer_frag_spv_count);
1016 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
1017 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
1018 gbufferPipeline =
1019 device.createPipeline()
1020 .useClassicPipeline(vertModule, fragModule)
1021 .setPipelineLayout(gbufferPipelineLayout)
1022 .setVertexInputState(
1023 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
1024 .setDynamicStatesViewportScissor()
1025 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1026 vk::FrontFace::eClockwise)
1027 .setColorBlending(gbufferBlend)
1028 .build(gbufferPass);
1029 device->destroyShaderModule(vertModule);
1030 device->destroyShaderModule(fragModule);
1031
1032 auto instancedVert =
1033 vkb::PipelineBuilder::createShaderModule(device.instance, embeddedSpirv(mesh3d_gbuffer_instanced_vert_spv));
1034 auto instancedFrag =
1035 vkb::PipelineBuilder::createShaderModule(device.instance, embeddedSpirv(mesh3d_gbuffer_instanced_frag_spv));
1036 gbufferInstancedPipeline = device.createPipeline()
1037 .useClassicPipeline(instancedVert, instancedFrag)
1038 .setPipelineLayout(gbufferPipelineLayout)
1039 .setVertexInputState(vkb::VertexInputStateBuilder()
1040 .addInputBinding<MeshVertex>()
1041 .addInputBinding<GBufferPush>()
1042 .addAttributeDescription<MeshVertex>(1)
1043 .addAttributeDescription<GBufferPush>(2))
1044 .setDynamicStatesViewportScissor()
1045 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1046 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
1047 .setColorBlending(gbufferBlend)
1048 .build(gbufferPass);
1049 device->destroyShaderModule(instancedVert);
1050 device->destroyShaderModule(instancedFrag);
1051
1052 // Alpha-cutout variant for billboard/card geometry (sprite-stack slices):
1053 // same layout/push constants, fragment discards transparent texels.
1054 vk::ShaderModule alphaVertModule =
1055 vkb::PipelineBuilder::createShaderModule(device.instance, vert);
1056 std::vector<uint32_t> alphaFrag(mesh3d_gbuffer_alpha_frag_spv,
1057 mesh3d_gbuffer_alpha_frag_spv +
1058 mesh3d_gbuffer_alpha_frag_spv_count);
1059 vk::ShaderModule alphaFragModule =
1060 vkb::PipelineBuilder::createShaderModule(device.instance, alphaFrag);
1061 gbufferAlphaPipeline =
1062 device.createPipeline()
1063 .useClassicPipeline(alphaVertModule, alphaFragModule)
1064 .setPipelineLayout(gbufferPipelineLayout)
1065 .setVertexInputState(
1066 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
1067 .setDynamicStatesViewportScissor()
1068 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1069 vk::FrontFace::eClockwise)
1070 .setColorBlending(gbufferBlend)
1071 .build(gbufferPass);
1072 device->destroyShaderModule(alphaVertModule);
1073 device->destroyShaderModule(alphaFragModule);
1074
1075 auto skinVert = embeddedSpirv(mesh3d_gbuffer_skin_vert_spv);
1076 auto skinFrag = embeddedSpirv(mesh3d_gbuffer_skin_frag_spv);
1077 gbufferSkinPipeline =
1078 device.createPipeline()
1079 .useClassicPipeline(skinVert, skinFrag)
1080 .setPipelineLayout(skinPassPipelineLayout)
1081 .setVertexInputState(
1082 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
1083 .setDynamicStatesViewportScissor()
1084 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1085 vk::FrontFace::eClockwise)
1086 .setColorBlending(gbufferBlend)
1087 .build(gbufferPass);
1088 auto skinAlphaFrag = embeddedSpirv(mesh3d_gbuffer_skin_alpha_frag_spv);
1089 gbufferSkinAlphaPipeline =
1090 device.createPipeline()
1091 .useClassicPipeline(skinVert, skinAlphaFrag)
1092 .setPipelineLayout(skinPassPipelineLayout)
1093 .setVertexInputState(
1094 vkb::VertexInputStateBuilder().addInputBinding<MeshVertex>().addAttributeDescription<MeshVertex>())
1095 .setDynamicStatesViewportScissor()
1096 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1097 vk::FrontFace::eClockwise)
1098 .setColorBlending(gbufferBlend)
1099 .build(gbufferPass);
1100
1101 auto makeSampleTex = [&](GpuTexture &gpu, Texture &tex, vk::ImageView view) {
1102 vkb::SamplerBuilder sb;
1103 gpu.sampler = sb.nearestClamp().build(device);
1104 auto sets = vkb::DescriptorSetBuilder()
1105 .layout(texSetLayout)
1106 .build(device.instance, descriptorPool);
1107 gpu.descriptorSet = vkb::BoundSet{sets[0]};
1108 gpu.width = gbufW;
1109 gpu.height = gbufH;
1110 gpu.viewOverride = view;
1111 writeCombinedImageDescriptor(&gpu);
1112 tex.width = gbufW;
1113 tex.height = gbufH;
1114 tex.pixelWidth = gbufW;
1115 tex.pixelHeight = gbufH;
1116 tex.gpuHandle = &gpu;
1117 };
1118 for (auto &slot : gbufferSlots) {
1119 makeSampleTex(slot.normalGpu, slot.normalTex, slot.normal.imageView());
1120 makeSampleTex(slot.depthColorGpu, slot.depthColorTex, slot.depthColor.imageView());
1121 makeSampleTex(slot.albedoGpu, slot.albedoTex, slot.albedo.imageView());
1122 makeSampleTex(slot.pbrParamsGpu, slot.pbrParamsTex, slot.pbrParams.imageView());
1123 makeSampleTex(slot.emissiveGpu, slot.emissiveTex, slot.emissive.imageView());
1124 makeSampleTex(slot.visIDGpu, slot.visIDTex, slot.visID.imageView());
1125 makeSampleTex(slot.visBaryGpu, slot.visBaryTex, slot.visBary.imageView());
1126 makeSampleTex(slot.depthGpu, slot.depthTex, slot.depth.imageView());
1127 }
1128 createGpuDrivenVisResources(gbufW, gbufH);
1129}
1130
1131void Graphics::ensureDecalUnitBox() {
1132 if (decalUnitBox) return;
1133 // Unit cube [-0.5, 0.5]^3, one 4-vertex face per side with its own
1134 // normal + UVs so the decal projection samples a clean square per face.
1135 const float h = 0.5f;
1136 const std::vector<glm::vec3> pos = {
1137 // +Z
1138 {-h, -h, h}, {h, -h, h}, {h, h, h}, {-h, h, h},
1139 // -Z
1140 {h, -h, -h}, {-h, -h, -h}, {-h, h, -h}, {h, h, -h},
1141 // +X
1142 {h, -h, h}, {h, -h, -h}, {h, h, -h}, {h, h, h},
1143 // -X
1144 {-h, -h, -h}, {-h, -h, h}, {-h, h, h}, {-h, h, -h},
1145 // +Y
1146 {-h, h, h}, {h, h, h}, {h, h, -h}, {-h, h, -h},
1147 // -Y
1148 {-h, -h, -h}, {h, -h, -h}, {h, -h, h}, {-h, -h, h},
1149 };
1150 const std::vector<glm::vec3> nrm = {
1151 {0, 0, 1}, {0, 0, 1}, {0, 0, 1}, {0, 0, 1},
1152 {0, 0, -1}, {0, 0, -1}, {0, 0, -1}, {0, 0, -1},
1153 {1, 0, 0}, {1, 0, 0}, {1, 0, 0}, {1, 0, 0},
1154 {-1, 0, 0}, {-1, 0, 0}, {-1, 0, 0}, {-1, 0, 0},
1155 {0, 1, 0}, {0, 1, 0}, {0, 1, 0}, {0, 1, 0},
1156 {0, -1, 0}, {0, -1, 0}, {0, -1, 0}, {0, -1, 0},
1157 };
1158 const std::vector<glm::vec2> uv = {
1159 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1160 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1161 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1162 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1163 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1164 {0, 0}, {1, 0}, {1, 1}, {0, 1},
1165 };
1166 const std::vector<uint32_t> idx = {
1167 0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7,
1168 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15,
1169 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23,
1170 };
1171 std::vector<float> posF, nrmF, uvF;
1172 posF.reserve(pos.size() * 3);
1173 nrmF.reserve(nrm.size() * 3);
1174 uvF.reserve(uv.size() * 2);
1175 for (const auto &p : pos) posF.insert(posF.end(), {p.x, p.y, p.z});
1176 for (const auto &n : nrm) nrmF.insert(nrmF.end(), {n.x, n.y, n.z});
1177 for (const auto &t : uv) uvF.insert(uvF.end(), {t.x, t.y});
1178 decalUnitBox =
1179 newMeshFromArrays(posF.data(), nrmF.data(), uvF.data(), int(pos.size()), idx.data(),
1180 int(idx.size()));
1181}
1182
1183void Graphics::createDecalResources(int decalW, int decalH) {
1184 if (decalW <= 0 || decalH <= 0) return;
1185 if (!decalSlots.empty() && decalWidth == decalW && decalHeight == decalH && decalPipeline)
1186 return;
1187 destroyDecalResources();
1188
1189 decalWidth = decalW;
1190 decalHeight = decalH;
1191 const uint32_t w = uint32_t(decalW);
1192 const uint32_t h = uint32_t(decalH);
1193 const vk::Format colorFmt = pickGBufferColorFormat(device); // RGBA8
1194
1195 decalSlots.resize(kAsyncResourceCopies);
1196 for (auto &slot : decalSlots) {
1197 slot.albedo = device.createColorTarget(w, h, colorFmt);
1198 slot.normal = device.createColorTarget(w, h, colorFmt);
1199 slot.params = device.createColorTarget(w, h, colorFmt);
1200 slot.cameraUbo.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
1201 sizeof(DecalCameraUBO), kHostVisibleCoherent);
1202 }
1203
1204 auto decalPass =
1205 device.createRenderPass()
1206 .addSampledColorAttachment(colorFmt)
1207 .addSampledColorAttachment(colorFmt)
1208 .addSampledColorAttachment(colorFmt)
1209 .addSubpass(vkb::SubpassBuilder()
1210 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
1211 .addAttachmentRef(1, vk::ImageLayout::eColorAttachmentOptimal)
1212 .addAttachmentRef(2, vk::ImageLayout::eColorAttachmentOptimal))
1213 .addExternalShaderReadDependencies()
1214 .build();
1215 decalRenderPass = decalPass;
1216
1217 for (auto &slot : decalSlots) {
1218 slot.framebuffer = decalPass.createFramebuffer(
1219 device, w, h,
1220 {slot.albedo.asAttachment(), slot.normal.asAttachment(), slot.params.asAttachment()});
1221 }
1222
1223 vkb::DescriptorSetLayoutBuilder layoutBuilder;
1224 decalSetLayoutUnique =
1225 layoutBuilder
1226 .image(0, vk::DescriptorType::eCombinedImageSampler,
1227 vk::ShaderStageFlagBits::eFragment, 1)
1228 .image(1, vk::DescriptorType::eCombinedImageSampler,
1229 vk::ShaderStageFlagBits::eFragment, 1)
1230 .image(2, vk::DescriptorType::eCombinedImageSampler,
1231 vk::ShaderStageFlagBits::eFragment, 1)
1232 .image(3, vk::DescriptorType::eCombinedImageSampler,
1233 vk::ShaderStageFlagBits::eFragment, 1)
1234 .image(4, vk::DescriptorType::eCombinedImageSampler,
1235 vk::ShaderStageFlagBits::eFragment, 1)
1236 .buffer(5, vk::DescriptorType::eUniformBuffer,
1237 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 1)
1238 .createUnique(device.instance);
1239 decalSetLayout = *decalSetLayoutUnique;
1240 const vk::PushConstantRange decalPushRange{
1241 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
1242 uint32_t(sizeof(DecalInstanceData))};
1243 decalPipelineLayout = device.createPipelineLayout()
1244 .set(decalSetLayout)
1245 .push(vk::ShaderStageFlagBits::eVertex |
1246 vk::ShaderStageFlagBits::eFragment,
1247 decalPushRange.size, decalPushRange.offset)
1248 .build();
1249
1250 std::vector<uint32_t> vert(decal_box_vert_spv, decal_box_vert_spv + decal_box_vert_spv_count);
1251 std::vector<uint32_t> frag(decal_box_frag_spv, decal_box_frag_spv + decal_box_frag_spv_count);
1252 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
1253 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
1254
1255 // Alpha-over compositing for the three layer targets (non-premultiplied
1256 // decal output; the shader writes rgb + coverage in alpha).
1257 decalPipeline = device.createPipeline()
1258 .useClassicPipeline(vertModule, fragModule)
1259 .setPipelineLayout(decalPipelineLayout)
1260 .setDynamicStatesViewportScissor()
1261 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1262 vk::CullModeFlagBits::eNone, vk::FrontFace::eClockwise)
1263 .setMultisampler(false, vk::SampleCountFlagBits::e1)
1264 .setDepthStencil(false, false, vk::CompareOp::eAlways)
1265 .setAlphaBlending(3)
1266 .build(decalPass);
1267 device->destroyShaderModule(vertModule);
1268 device->destroyShaderModule(fragModule);
1269
1270 auto makeSampleTex = [&](GpuTexture &gpu, Texture &tex, vk::ImageView view) {
1271 vkb::SamplerBuilder sb;
1272 gpu.sampler = sb.nearestClamp().build(device);
1273 auto sets = vkb::DescriptorSetBuilder()
1274 .layout(texSetLayout)
1275 .build(device.instance, descriptorPool);
1276 gpu.descriptorSet = vkb::BoundSet{sets[0]};
1277 gpu.width = decalW;
1278 gpu.height = decalH;
1279 gpu.viewOverride = view;
1280 writeCombinedImageDescriptor(&gpu);
1281 tex.width = decalW;
1282 tex.height = decalH;
1283 tex.pixelWidth = decalW;
1284 tex.pixelHeight = decalH;
1285 tex.gpuHandle = &gpu;
1286 };
1287 for (auto &slot : decalSlots) {
1288 makeSampleTex(slot.albedoGpu, slot.albedoTex, slot.albedo.imageView());
1289 makeSampleTex(slot.normalGpu, slot.normalTex, slot.normal.imageView());
1290 makeSampleTex(slot.paramsGpu, slot.paramsTex, slot.params.imageView());
1291 }
1292}
1293
1294void Graphics::destroyDecalResources() {
1295 decalPassActive = false;
1296 decalPending = false;
1297 decalPassDraws.clear();
1298 for (auto &slot : decalSlots) {
1299 slot.albedoTex.gpuHandle = nullptr;
1300 slot.normalTex.gpuHandle = nullptr;
1301 slot.paramsTex.gpuHandle = nullptr;
1302 if (slot.framebuffer) {
1303 device->destroyFramebuffer(slot.framebuffer);
1304 slot.framebuffer = vk::Framebuffer{};
1305 }
1306 destroySampler(device, slot.albedoGpu.sampler);
1307 destroySampler(device, slot.normalGpu.sampler);
1308 destroySampler(device, slot.paramsGpu.sampler);
1309 slot.cameraUbo.release();
1310 slot.sets.clear();
1311 }
1312 decalSlots.clear();
1313 destroyPipeline(device, decalPipeline);
1314 destroyPipelineLayout(device, decalPipelineLayout);
1315 if (decalSetLayoutUnique) decalSetLayoutUnique.reset();
1316 if (decalRenderPass) {
1317 device->destroyRenderPass(decalRenderPass);
1318 decalRenderPass = {};
1319 }
1320 decalWidth = 0;
1321 decalHeight = 0;
1322}
1323
1324vkb::BoundSet Graphics::decalSetFor(DecalSlot &slot, GpuTexture *albedo, GpuTexture *normal,
1325 GpuTexture *params, GpuTexture *depth,
1326 GpuTexture *gbNormal) {
1327 ASSERT(albedo != nullptr);
1328 ASSERT(normal != nullptr);
1329 ASSERT(params != nullptr);
1330 ASSERT(depth != nullptr);
1331 ASSERT(gbNormal != nullptr);
1332 DecalSetKey key{albedo, normal, params, depth, gbNormal};
1333 auto it = slot.sets.find(key);
1334 if (it != slot.sets.end()) return it->second;
1335
1336 auto sets = vkb::DescriptorSetBuilder()
1337 .layout(decalSetLayout)
1338 .build(device.instance, descriptorPool);
1339 vkb::UnboundSet unbound{sets.front()};
1340 vkb::DescriptorSetUpdater updater(1, 5, 0);
1341 updater.beginDescriptorSet(unbound)
1342 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
1343 .image(vkb::SampledImage::forLaterSample(albedo->sampler, albedo->imageView()))
1344 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1345 .image(vkb::SampledImage::forLaterSample(normal->sampler, normal->imageView()))
1346 .beginImages(2, 0, vk::DescriptorType::eCombinedImageSampler)
1347 .image(vkb::SampledImage::forLaterSample(params->sampler, params->imageView()))
1348 .beginImages(3, 0, vk::DescriptorType::eCombinedImageSampler)
1349 .image(vkb::SampledImage::forLaterSample(depth->sampler, depth->imageView()))
1350 .beginImages(4, 0, vk::DescriptorType::eCombinedImageSampler)
1351 .image(vkb::SampledImage::forLaterSample(gbNormal->sampler, gbNormal->imageView()))
1352 .beginBuffers(5, 0, vk::DescriptorType::eUniformBuffer)
1353 .buffer(slot.cameraUbo.buffer, 0, slot.cameraUbo.size)
1354 .update(device.instance);
1355
1356 vkb::BoundSet bound = std::move(unbound).publish();
1357 slot.sets.emplace(key, bound);
1358 return bound;
1359}
1360
1361void Graphics::createSceneColorResources(int sceneW, int sceneH) {
1362 if (sceneW <= 0 || sceneH <= 0) return;
1363 if (!texSetLayout || !descriptorPool) return;
1364 // Lighting and post effects stay linear HDR until the final swapchain resolve.
1365 const vk::Format colorFmt = vk::Format::eR16G16B16A16Sfloat;
1366
1367 const bool featureMsaa = !renderControl_ || renderControl_->isEnabled("msaa");
1368 const int desired = featureMsaa ? msaaSamples : 0;
1369 if (desired != appliedMsaa) appliedMsaa = desired;
1370 const vk::SampleCountFlagBits samples = sampleCountFlagFor(clampMsaaSamples(appliedMsaa));
1371
1372 if (!sceneColorSlots.empty() && sceneColorWidth == sceneW && sceneColorHeight == sceneH &&
1373 sceneColorFormat == colorFmt && sceneColorSamples == samples && sceneColorRenderPass)
1374 return;
1375 destroySceneColorResources();
1376
1377 sceneColorWidth = sceneW;
1378 sceneColorHeight = sceneH;
1379 sceneColorFormat = colorFmt;
1380 sceneColorSamples = samples;
1381 const uint32_t w = uint32_t(sceneW);
1382 const uint32_t h = uint32_t(sceneH);
1383 const vk::Format depthFmt = depthFormat;
1384 const bool msaa = samples != vk::SampleCountFlagBits::e1;
1385
1386 sceneColorSlots.resize(kAsyncResourceCopies);
1387 // Every scene slot can also be the destination of a same-frame snapshot.
1388 for (auto &slot : sceneColorSlots) {
1389 slot.color = device.createCopyableColorTarget(w, h, colorFmt);
1390 if (msaa) {
1391 slot.msaaColor = device.createColorTarget(w, h, colorFmt, samples);
1392 slot.depth = device.createDepthTarget(w, h, depthFmt, false, samples);
1393 } else {
1394 slot.depth = device.createDepthTarget(w, h, depthFmt, false);
1395 }
1396 }
1397
1398 if (msaa) {
1399 // MSAA color is transient (DONT_CARE store). Sampling the 1x resolve.
1400 // addSampledColorAttachment on the MSAA target makes MoltenVK treat it
1401 // as a shader-readable texture2d and segfaults on macOS.
1402 sceneColorRenderPass =
1403 device.createRenderPass()
1404 .addColorAttachment(colorFmt, vk::AttachmentLoadOp::eClear,
1405 vk::AttachmentStoreOp::eDontCare, samples)
1406 .addResolveColorAttachment(colorFmt, vk::AttachmentLoadOp::eDontCare)
1407 .addDepthAttachment(depthFmt, vk::AttachmentLoadOp::eClear,
1408 vk::AttachmentStoreOp::eDontCare, samples)
1409 .addSubpass(vkb::SubpassBuilder()
1410 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
1411 .addResolveAttachment(1, vk::ImageLayout::eColorAttachmentOptimal)
1412 .setDepthStencilAttachment(
1413 2, vk::ImageLayout::eDepthStencilAttachmentOptimal))
1414 .addExternalShaderReadDependencies()
1415 .build();
1416 } else {
1417 sceneColorRenderPass =
1418 device.createRenderPass()
1419 .addSampledColorAttachment(colorFmt)
1420 .addDepthAttachment(depthFmt, vk::AttachmentLoadOp::eClear,
1421 vk::AttachmentStoreOp::eStore)
1422 .addSubpass(vkb::SubpassBuilder()
1423 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
1424 .setDepthStencilAttachment(
1425 1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
1426 .addExternalShaderReadDependencies()
1427 .build();
1428
1429 std::array<vk::AttachmentDescription, 2> attachments{};
1430 attachments[0] = vk::AttachmentDescription()
1431 .setFormat(colorFmt)
1432 .setSamples(vk::SampleCountFlagBits::e1)
1433 .setLoadOp(vk::AttachmentLoadOp::eLoad)
1434 .setStoreOp(vk::AttachmentStoreOp::eStore)
1435 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1436 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1437 .setInitialLayout(vk::ImageLayout::eColorAttachmentOptimal)
1438 .setFinalLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1439 attachments[1] = vk::AttachmentDescription()
1440 .setFormat(depthFmt)
1441 .setSamples(vk::SampleCountFlagBits::e1)
1442 .setLoadOp(vk::AttachmentLoadOp::eLoad)
1443 .setStoreOp(vk::AttachmentStoreOp::eStore)
1444 .setStencilLoadOp(vk::AttachmentLoadOp::eDontCare)
1445 .setStencilStoreOp(vk::AttachmentStoreOp::eDontCare)
1446 .setInitialLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal)
1447 .setFinalLayout(vk::ImageLayout::eDepthStencilAttachmentOptimal);
1448 const vk::AttachmentReference colorRef{0, vk::ImageLayout::eColorAttachmentOptimal};
1449 const vk::AttachmentReference depthRef{1, vk::ImageLayout::eDepthStencilAttachmentOptimal};
1450 const vk::SubpassDescription subpass =
1451 vk::SubpassDescription()
1452 .setPipelineBindPoint(vk::PipelineBindPoint::eGraphics)
1453 .setColorAttachmentCount(1)
1454 .setPColorAttachments(&colorRef)
1455 .setPDepthStencilAttachment(&depthRef);
1456 std::array<vk::SubpassDependency, 2> dependencies{};
1457 // Match addExternalShaderReadDependencies() exactly: dependencies are
1458 // part of render-pass compatibility with existing pipelines/framebuffers.
1459 // The copy is synchronized explicitly outside these compatible passes.
1460 dependencies[0] = vk::SubpassDependency()
1461 .setSrcSubpass(VK_SUBPASS_EXTERNAL)
1462 .setDstSubpass(0)
1463 .setSrcStageMask(vk::PipelineStageFlagBits::eFragmentShader)
1464 .setDstStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput |
1465 vk::PipelineStageFlagBits::eEarlyFragmentTests)
1466 .setSrcAccessMask(vk::AccessFlagBits::eShaderRead)
1467 .setDstAccessMask(vk::AccessFlagBits::eColorAttachmentWrite |
1468 vk::AccessFlagBits::eDepthStencilAttachmentWrite);
1469 dependencies[1] = vk::SubpassDependency()
1470 .setSrcSubpass(0)
1471 .setDstSubpass(VK_SUBPASS_EXTERNAL)
1472 .setSrcStageMask(vk::PipelineStageFlagBits::eColorAttachmentOutput |
1473 vk::PipelineStageFlagBits::eLateFragmentTests)
1474 .setDstStageMask(vk::PipelineStageFlagBits::eFragmentShader)
1475 .setSrcAccessMask(vk::AccessFlagBits::eColorAttachmentWrite |
1476 vk::AccessFlagBits::eDepthStencilAttachmentWrite)
1477 .setDstAccessMask(vk::AccessFlagBits::eShaderRead);
1478 const vk::RenderPassCreateInfo resumeInfo =
1479 vk::RenderPassCreateInfo()
1480 .setAttachmentCount(static_cast<uint32_t>(attachments.size()))
1481 .setPAttachments(attachments.data())
1482 .setSubpassCount(1)
1483 .setPSubpasses(&subpass)
1484 .setDependencyCount(static_cast<uint32_t>(dependencies.size()))
1485 .setPDependencies(dependencies.data());
1486 sceneColorResumeRenderPass = device->createRenderPass(resumeInfo);
1487 }
1488 auto scenePass = sceneColorRenderPass;
1489
1490 for (auto &slot : sceneColorSlots) {
1491 if (msaa) {
1492 slot.framebuffer = scenePass.createFramebuffer(
1493 device, w, h,
1494 {slot.msaaColor.asAttachment(), slot.color.asAttachment(), slot.depth.asAttachment()});
1495 } else {
1496 slot.framebuffer = scenePass.createFramebuffer(
1497 device, w, h, {slot.color.asAttachment(), slot.depth.asAttachment()});
1498 }
1499 }
1500
1501 auto makeSampleTex = [&](GpuTexture &gpu, Texture &tex, vk::ImageView view) {
1502 vkb::SamplerBuilder sb;
1503 gpu.sampler = sb.magFilter(vk::Filter::eLinear)
1504 .minFilter(vk::Filter::eLinear)
1505 .addressModeU(vk::SamplerAddressMode::eClampToEdge)
1506 .addressModeV(vk::SamplerAddressMode::eClampToEdge)
1507 .build(device);
1508 auto sets = vkb::DescriptorSetBuilder()
1509 .layout(texSetLayout)
1510 .build(device.instance, descriptorPool);
1511 gpu.descriptorSet = vkb::BoundSet{sets[0]};
1512 // Stamp the actual scene-target extent, not Graphics::width/height —
1513 // those can briefly disagree with swapchain.extent around a resize, and
1514 // post (FXAA/bloom) sizes itself from Texture::getWidth/Height.
1515 gpu.width = sceneW;
1516 gpu.height = sceneH;
1517 gpu.viewOverride = view;
1518 writeCombinedImageDescriptor(&gpu);
1519 tex.width = sceneW;
1520 tex.height = sceneH;
1521 tex.pixelWidth = sceneW;
1522 tex.pixelHeight = sceneH;
1523 tex.gpuHandle = &gpu;
1524 };
1525 for (auto &slot : sceneColorSlots) makeSampleTex(slot.colorGpu, slot.colorTex, slot.color.imageView());
1526
1527 // Hybrid deferred lighting targets the scene-color render pass; rebuild when
1528 // the pass (format/samples/extent) changes.
1529 createDeferredLightingPipeline();
1530}
1531
1532bool Graphics::beginSceneColorRenderPass() {
1533 auto *slot = currentSceneColorSlot();
1534 if (!slot || !sceneColorRenderPass || !slot->framebuffer) return false;
1535 auto &cb = currentPresentCb();
1536 const bool msaa = sceneColorSamples != vk::SampleCountFlagBits::e1;
1537 // A=1 marks sky / far plane so SSGI skips uncleared pixels.
1538 if (msaa) {
1539 std::array<vk::ClearValue, 3> clears{};
1540 clears[0].color = vk::ClearColorValue(
1541 std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, 1.f});
1542 clears[1].color = vk::ClearColorValue(
1543 std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, 1.f});
1544 clears[2].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1545 vk::RenderPassBeginInfo rpBegin{};
1546 rpBegin.renderPass = sceneColorRenderPass;
1547 rpBegin.framebuffer = slot->framebuffer;
1548 rpBegin.renderArea =
1549 vk::Rect2D{{0, 0}, {uint32_t(sceneColorWidth), uint32_t(sceneColorHeight)}};
1550 rpBegin.clearValueCount = uint32_t(clears.size());
1551 rpBegin.pClearValues = clears.data();
1552 slot->msaaColor.beginColorAttachment();
1553 slot->color.beginColorAttachment();
1554 slot->depth.beginDepthAttachment();
1555 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1556 } else {
1557 std::array<vk::ClearValue, 2> clears{};
1558 clears[0].color = vk::ClearColorValue(
1559 std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, 1.f});
1560 clears[1].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1561 vk::RenderPassBeginInfo rpBegin{};
1562 rpBegin.renderPass = sceneColorRenderPass;
1563 rpBegin.framebuffer = slot->framebuffer;
1564 rpBegin.renderArea =
1565 vk::Rect2D{{0, 0}, {uint32_t(sceneColorWidth), uint32_t(sceneColorHeight)}};
1566 rpBegin.clearValueCount = uint32_t(clears.size());
1567 rpBegin.pClearValues = clears.data();
1568 slot->color.beginColorAttachment();
1569 slot->depth.beginDepthAttachment();
1570 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1571 }
1572 sceneColorPassOpen = true;
1573 return true;
1574}
1575
1576void Graphics::endSceneColorRenderPass() {
1577 if (!sceneColorPassOpen) return;
1578 auto &cb = currentPresentCb();
1579 cb.endRenderPass();
1580 sceneColorPassOpen = false;
1581 if (auto *slot = currentSceneColorSlot()) {
1582 slot->color.endSampledLayout();
1583 completedSceneColorSlot = currentFrameSlot() % sceneColorSlots.size();
1584 sceneColorHistoryValid = true;
1585 }
1586}
1587
1588int Graphics::clampMsaaSamples(int requested) const {
1589 if (requested <= 1) return 0;
1590 vk::SampleCountFlags supported =
1591 device.physical_device.properties.limits.framebufferColorSampleCounts &
1592 device.physical_device.properties.limits.framebufferDepthSampleCounts;
1593 const int candidates[3] = {8, 4, 2};
1594 for (int c : candidates) {
1595 if (requested >= c && (supported & sampleCountFlagFor(c))) return c;
1596 }
1597 for (int c : candidates) {
1598 if (supported & sampleCountFlagFor(c)) return c;
1599 }
1600 return 0;
1601}
1602
1603void Graphics::ensureScenePassPipelines(const vkb::BuiltRenderPass &target,
1604 vk::SampleCountFlagBits samples) {
1605 createMesh3DPipeline();
1606 const vk::RenderPass targetHandle = vk::RenderPass(target);
1607 if (targetHandle == scenePassPipelineTarget && samples == scenePassPipelineSamples) return;
1608 device->waitIdle();
1609 destroyPbrResources();
1610
1611 destroyPipeline(device, mesh3dPipeline);
1612 destroyPipeline(device, mesh3dTransparentPipeline);
1613 for (auto &pipeline : mesh3dSurfacePipelines) destroyPipeline(device, pipeline);
1614 destroyPipeline(device, mesh3dClusteredPipeline);
1615 destroyPipeline(device, mesh3dGpuDrivenPipeline);
1616 destroyPipeline(device, resolveVisPipeline);
1617 destroyPipeline(device, voxelRectPipeline);
1618 for (auto &pipeline : primitive3DPipelines) destroyPipeline(device, pipeline);
1619
1620 mesh3dPipeline =
1621 createMesh3DStylePipeline(embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv), mesh3dPipelineLayout,
1622 target, samples, BlendMode::Opaque, true, true, {MeshDepthCompare::LessEqual});
1623 mesh3dTransparentPipeline =
1624 createMesh3DHairPipeline(embeddedSpirv(mesh3d_vert_spv),
1625 embeddedSpirv(mesh3d_frag_spv), mesh3dPipelineLayout,
1626 target, samples);
1627 for (int blendValue = 0; blendValue < 5; ++blendValue) {
1628 const auto blend = BlendMode(blendValue);
1629 for (int depthValue = 0; depthValue < 2; ++depthValue) {
1630 for (int doubleValue = 0; doubleValue < 2; ++doubleValue) {
1631 const size_t index = mesh3dPipelineIndex(blend, depthValue != 0, doubleValue != 0);
1632 mesh3dSurfacePipelines[index] = createMesh3DStylePipeline(
1633 embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv), mesh3dPipelineLayout, target,
1634 samples, blend, depthValue != 0, doubleValue != 0,
1635 {blend == BlendMode::Opaque && depthValue != 0 ? MeshDepthCompare::LessEqual
1637 }
1638 }
1639 }
1640 if (mesh3dGpuDrivenPipelineLayout) {
1641 mesh3dGpuDrivenPipeline =
1642 createMesh3DStylePipeline(embeddedSpirv(mesh3d_gpudriven_vert_spv),
1643 embeddedSpirv(mesh3d_gpudriven_frag_spv),
1644 mesh3dGpuDrivenPipelineLayout, target, samples);
1645 createResolveVisPipeline(target, samples);
1646 }
1647 if (mesh3dClusteredPipelineLayout) {
1648 mesh3dClusteredPipeline =
1649 createMesh3DStylePipeline(embeddedSpirv(mesh3d_clustered_vert_spv),
1650 embeddedSpirv(mesh3d_clustered_frag_spv), mesh3dClusteredPipelineLayout, target,
1651 samples, BlendMode::Opaque, true, true, {MeshDepthCompare::LessEqual});
1652 }
1653 if (voxelRectPipelineLayout)
1654 voxelRectPipeline = buildVoxelRectPipeline(target, samples);
1655 rebuildPrimitive3DPipelines(target, samples);
1656
1657 for (auto &g : ownedGpuShaders) {
1658 if (!g->isMesh3D) continue;
1659 destroyPipeline(device, g->mesh3dPipeline);
1660 destroyPipeline(device, g->mesh3dXrayPipeline);
1661 g->mesh3dXrayPipeline = nullptr;
1662 if (!g->owner) continue;
1663 if (g->isHair3D) {
1664 g->mesh3dPipeline =
1665 createMesh3DHairPipeline(g->owner->vertexSpirv(), g->owner->fragmentSpirv(),
1666 g->pipelineLayout, target, samples);
1667 } else {
1668 g->mesh3dPipeline = createMesh3DStylePipeline(
1669 g->owner->vertexSpirv(), g->owner->fragmentSpirv(), g->pipelineLayout, target, samples,
1670 g->owner->meshBlend, g->owner->meshDepthWrite, g->owner->meshDoubleSided, g->owner->meshRasterState());
1671 g->mesh3dXrayPipeline =
1672 createMesh3DXrayPipeline(g->owner->vertexSpirv(), g->owner->fragmentSpirv(),
1673 g->pipelineLayout, target, samples);
1674 }
1675 }
1676
1677 scenePassPipelineTarget = targetHandle;
1678 scenePassPipelineSamples = samples;
1679}
1680
1681size_t Graphics::primitive3DPipelineIndex(PrimitiveDepthMode depth, BlendMode blend, PrimitiveCullMode cull) {
1682 return static_cast<size_t>(depth) * 15u + static_cast<size_t>(blend) * 3u + static_cast<size_t>(cull);
1683}
1684
1685void Graphics::rebuildPrimitive3DPipelines(const vkb::BuiltRenderPass &target, vk::SampleCountFlagBits samples) {
1686 buildPrimitive3DPipelines(target, samples, primitive3DPipelines);
1687}
1688
1689void Graphics::buildPrimitive3DPipelines(const vkb::BuiltRenderPass &target, vk::SampleCountFlagBits samples,
1690 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> &pipelines) {
1691 for (auto &pipeline : pipelines) destroyPipeline(device, pipeline);
1692 for (int depthValue = 0; depthValue < 3; ++depthValue) {
1693 for (int blendValue = 0; blendValue < 5; ++blendValue) {
1694 for (int cullValue = 0; cullValue < 3; ++cullValue) {
1695 const auto depth = static_cast<PrimitiveDepthMode>(depthValue);
1696 const auto blend = static_cast<BlendMode>(blendValue);
1697 const auto cull = static_cast<PrimitiveCullMode>(cullValue);
1698 pipelines[primitive3DPipelineIndex(depth, blend, cull)] =
1699 createPrimitive3DPipeline(device, target, pipelineLayout, depth, blend, cull, samples);
1700 }
1701 }
1702 }
1703}
1704
1705void Graphics::queueSceneColorResolve() {
1707 if (!src) src = getSceneColorTexture();
1708 if (!src || !src->gpuHandle) return;
1709 // Still build the AA/Bloom/Exposure resolve when a script called
1710 // drawScene3D (sceneColorComposited). autoScene skips the implicit
1711 // fullscreen blit; present replaces the script's scene-color span.
1712 const bool reflectionPasses =
1713 renderControl_ && (renderControl_->isEnabled("rtgi") || renderControl_->isEnabled("ssr") ||
1714 renderControl_->isEnabled("rtx") || renderControl_->isEnabled("reflectionChain"));
1715 if (reflectionPasses) {
1716 auto *slot = currentSceneColorSlot();
1717 auto *snapshot = dynamic_cast<OffscreenCanvas *>(
1718 pipelineReflectionComposite(src->getWidth(), src->getHeight()));
1719 if (slot && snapshot) {
1720 auto &cb = currentPresentCb();
1721 slot->color.setLayout(cb, vk::ImageLayout::eTransferSrcOptimal);
1722 snapshot->colorImage().setLayout(cb, vk::ImageLayout::eTransferDstOptimal);
1723 vk::ImageCopy region{};
1724 region.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
1725 region.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
1726 region.extent = vk::Extent3D{uint32_t(src->getWidth()),
1727 uint32_t(src->getHeight()), 1};
1728 cb.copyImage(slot->color.image(), vk::ImageLayout::eTransferSrcOptimal,
1729 snapshot->colorImage().image(), vk::ImageLayout::eTransferDstOptimal,
1730 region);
1731 slot->color.setLayout(cb, vk::ImageLayout::eShaderReadOnlyOptimal);
1732 snapshot->colorImage().setLayout(cb, vk::ImageLayout::eShaderReadOnlyOptimal);
1733 src = snapshot->getTexture();
1734 }
1735 }
1736 pendingSceneResolveSource = src;
1737}
1738
1739void Graphics::materializeSceneColorResolve() {
1740 EV_PROFILE_MODULE("graphics", "Present.SceneResolve");
1741 Texture *src = pendingSceneResolveSource;
1742 pendingSceneResolveSource = nullptr;
1743 if (!src || !src->gpuHandle) return;
1744 auto savedSolid = std::move(solidBatches);
1745 auto savedTextured = std::move(texturedBatches);
1746 auto savedLit = std::move(litBatches);
1747 auto savedSpans = std::move(overlaySpans);
1748 auto savedEngineSpans = std::move(engine3DSpans);
1749 auto savedUiResolve = std::move(pendingUiResolve);
1750 solidBatches.clear();
1751 texturedBatches.clear();
1752 litBatches.clear();
1753 overlaySpans.clear();
1754 engine3DSpans.clear();
1755 Texture *motion = nullptr;
1756 if (renderControl_ && renderControl_->getGBuffer()->isValid())
1757 motion = renderControl_->getGBuffer()->getVelocityTexture();
1758 Texture *postProcessed = prepareFinalSceneTexture(src, motion);
1759 if (postProcessed) {
1760 // AA and exposure are already applied. Use the final tone-map pipeline;
1761 // UNORM SDR swapchains also require explicit linear-to-sRGB encoding.
1762 // HDR compose keeps paper-white-relative linear; the final encode pass
1763 // applies PQ/scRGB. Direct HDR present (rare already-open swapchain path)
1764 // encodes here.
1765 const bool composeLinear = isDisplayHdrActive();
1766 const bool attachmentEncodesSrgb =
1767 !composeLinear && (swapchain.image_format == vk::Format::eB8G8R8A8Srgb ||
1768 swapchain.image_format == vk::Format::eR8G8B8A8Srgb);
1769 TexturedBatch resolve{postProcessed, nullptr, nullptr, BlendMode::Opaque, Batcher{}};
1770 Color tint = composeLinear
1775 ? display::ActiveColorSpace::Hdr10
1777 ? display::ActiveColorSpace::ScRgb
1778 : display::ActiveColorSpace::Sdr),
1779 attachmentEncodesSrgb, displayPaperWhiteNits_, displayPeakNits_);
1780 tint.r = static_cast<float>(getSceneToneMapping());
1781 tint.g += getScenePhotographicVignette() * .25f;
1782 resolve.batch.addTexturedRect(0.f, 0.f, float(width), float(height), tint, 0.f, 0.f, 1.f, 1.f);
1783 pendingSceneResolve = std::move(resolve);
1784 }
1785 solidBatches = std::move(savedSolid);
1786 texturedBatches = std::move(savedTextured);
1787 litBatches = std::move(savedLit);
1788 overlaySpans = std::move(savedSpans);
1789 engine3DSpans = std::move(savedEngineSpans);
1790 pendingUiResolve = std::move(savedUiResolve);
1791}
1792
1793void Graphics::createShadowResources() {
1794 const int wantSize = ShadowSchemeSettings::current().resolvedAtlasMapSize();
1795 if (!shadowMaps.empty()) {
1796 if (allocatedShadowMapSize == wantSize) return;
1797 // Resolution changed: drop the old atlas + deferred graphs that import it.
1798 destroyShadowResources();
1799 }
1800
1801 const uint32_t size = uint32_t(wantSize);
1802 const uint32_t layers = uint32_t(ShadowConfig::kTotalLayers);
1803 allocatedShadowMapSize = wantSize;
1804
1805 shadowMaps.resize(kAsyncResourceCopies);
1806 for (auto &slot : shadowMaps)
1807 slot.image = device.createDepthArray(size, size, layers, vk::Format::eD32Sfloat);
1808
1809 vkb::SamplerBuilder sb;
1810 // Hardware PCF: linear filtering + depth compare on the D32 shadow map.
1811 // The compare result of each filtered depth sample is blended by the driver,
1812 // giving a soft penumbra instead of the hard 1-texel boundary.
1813 shadowSampler = sb.linearClamp().compareEnable(VK_TRUE).compareOp(vk::CompareOp::eLess).buildDepthPcf(device);
1814 vkb::SamplerBuilder rawBuilder;
1815 shadowRawSampler = rawBuilder.magFilter(vk::Filter::eNearest)
1816 .minFilter(vk::Filter::eNearest)
1817 .addressModeU(vk::SamplerAddressMode::eClampToEdge)
1818 .addressModeV(vk::SamplerAddressMode::eClampToEdge)
1819 .build(device);
1820
1821 auto shadowPass =
1822 device.createRenderPass()
1823 .addSampledDepthAttachment(vk::Format::eD32Sfloat)
1824 .addSubpass(
1825 vkb::SubpassBuilder().setDepthStencilAttachment(0, vk::ImageLayout::eDepthStencilAttachmentOptimal))
1826 // Imported cascades start undefined and finish sampled. Match the
1827 // actual FrameGraph pass, including its single outgoing dependency.
1828 .addDependency(
1829 0, VK_SUBPASS_EXTERNAL,
1830 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests |
1831 vk::PipelineStageFlagBits::eLateFragmentTests,
1832 vk::PipelineStageFlagBits::eVertexShader | vk::PipelineStageFlagBits::eFragmentShader,
1833 vk::AccessFlagBits::eColorAttachmentWrite | vk::AccessFlagBits::eDepthStencilAttachmentWrite,
1834 vk::AccessFlagBits::eShaderRead)
1835 .build();
1836 shadowRenderPass = shadowPass;
1837
1838 for (auto& slot : shadowMaps) {
1839 for (uint32_t i = 0; i < layers; ++i) {
1840 slot.framebuffers[i] =
1841 shadowPass.createFramebuffer(device, size, size, {slot.image.layerAttachment(i)});
1842 }
1843 }
1844
1845 shadowPipelineLayout =
1846 device.createPipelineLayout()
1847 .push<glm::mat4>(vk::ShaderStageFlagBits::eVertex)
1848 .build();
1849
1850 std::vector<uint32_t> vert(mesh3d_shadow_vert_spv,
1851 mesh3d_shadow_vert_spv + mesh3d_shadow_vert_spv_count);
1852 std::vector<uint32_t> frag(mesh3d_shadow_frag_spv,
1853 mesh3d_shadow_frag_spv + mesh3d_shadow_frag_spv_count);
1854 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
1855 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
1856 shadowPipeline =
1857 device.createPipeline()
1858 .useClassicPipeline(vertModule, fragModule)
1859 .setPipelineLayout(shadowPipelineLayout)
1860 .setVertexInputState(vkb::VertexInputStateBuilder()
1861 .addInputBinding<MeshVertex>()
1862 .addAttributeDescription<MeshVertex>())
1863 .setDynamicStatesViewportScissor()
1864 // No cull: Cornell-style one-sided interiors keep writing when the
1865 // ceiling/walls are back-facing the sun. Closest depth still wins
1866 // on closed meshes, so floors are not punched through.
1867 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1868 vk::FrontFace::eClockwise)
1869 .setDepthBias(0.0f, 0.5f)
1870 .build(shadowPass);
1871 shadowSingleSidedPipeline =
1872 device.createPipeline()
1873 .useClassicPipeline(vertModule, fragModule)
1874 .setPipelineLayout(shadowPipelineLayout)
1875 .setVertexInputState(vkb::VertexInputStateBuilder()
1876 .addInputBinding<MeshVertex>()
1877 .addAttributeDescription<MeshVertex>())
1878 .setDynamicStatesViewportScissor()
1879 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eBack,
1880 vk::FrontFace::eClockwise)
1881 .setDepthBias(0.0f, 0.5f)
1882 .build(shadowPass);
1883 device->destroyShaderModule(vertModule);
1884 device->destroyShaderModule(fragModule);
1885
1886 // Alpha-cutout variant for billboard/card shadow casters (sprite-stack
1887 // slices): same transform push constant, fragment samples the albedo and
1888 // discards transparent texels so shadows follow the silhouette.
1889 shadowAlphaPipelineLayout = device.createPipelineLayout()
1890 .set(texSetLayout)
1891 .push<ShadowAlphaPush>(vk::ShaderStageFlagBits::eVertex |
1892 vk::ShaderStageFlagBits::eFragment)
1893 .build();
1894 std::vector<uint32_t> alphaVert(mesh3d_shadow_alpha_vert_spv,
1895 mesh3d_shadow_alpha_vert_spv +
1896 mesh3d_shadow_alpha_vert_spv_count);
1897 std::vector<uint32_t> alphaFrag(mesh3d_shadow_alpha_frag_spv,
1898 mesh3d_shadow_alpha_frag_spv +
1899 mesh3d_shadow_alpha_frag_spv_count);
1900 vk::ShaderModule alphaVertModule =
1901 vkb::PipelineBuilder::createShaderModule(device.instance, alphaVert);
1902 vk::ShaderModule alphaFragModule =
1903 vkb::PipelineBuilder::createShaderModule(device.instance, alphaFrag);
1904 shadowAlphaPipeline =
1905 device.createPipeline()
1906 .useClassicPipeline(alphaVertModule, alphaFragModule)
1907 .setPipelineLayout(shadowAlphaPipelineLayout)
1908 .setVertexInputState(vkb::VertexInputStateBuilder()
1909 .addInputBinding<MeshVertex>()
1910 .addAttributeDescription<MeshVertex>())
1911 .setDynamicStatesViewportScissor()
1912 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
1913 vk::FrontFace::eClockwise)
1914 .setDepthBias(0.0f, 0.5f)
1915 .build(shadowPass);
1916 shadowAlphaSingleSidedPipeline =
1917 device.createPipeline()
1918 .useClassicPipeline(alphaVertModule, alphaFragModule)
1919 .setPipelineLayout(shadowAlphaPipelineLayout)
1920 .setVertexInputState(vkb::VertexInputStateBuilder()
1921 .addInputBinding<MeshVertex>()
1922 .addAttributeDescription<MeshVertex>())
1923 .setDynamicStatesViewportScissor()
1924 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eBack,
1925 vk::FrontFace::eClockwise)
1926 .setDepthBias(0.0f, 0.5f)
1927 .build(shadowPass);
1928 device->destroyShaderModule(alphaVertModule);
1929 device->destroyShaderModule(alphaFragModule);
1930
1931 auto skinVert = embeddedSpirv(mesh3d_shadow_skin_vert_spv);
1932 shadowSkinPipeline = device.createPipeline()
1933 .useClassicPipeline(skinVert, frag)
1934 .setPipelineLayout(skinPassPipelineLayout)
1935 .setVertexInputState(vkb::VertexInputStateBuilder()
1936 .addInputBinding<MeshVertex>()
1937 .addAttributeDescription<MeshVertex>())
1938 .setDynamicStatesViewportScissor()
1939 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1940 vk::CullModeFlagBits::eNone,
1941 vk::FrontFace::eClockwise)
1942 .setDepthBias(0.0f, 0.5f)
1943 .build(shadowPass);
1944 shadowSkinSingleSidedPipeline = device.createPipeline()
1945 .useClassicPipeline(skinVert, frag)
1946 .setPipelineLayout(skinPassPipelineLayout)
1947 .setVertexInputState(vkb::VertexInputStateBuilder()
1948 .addInputBinding<MeshVertex>()
1949 .addAttributeDescription<MeshVertex>())
1950 .setDynamicStatesViewportScissor()
1951 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1952 vk::CullModeFlagBits::eBack,
1953 vk::FrontFace::eClockwise)
1954 .setDepthBias(0.0f, 0.5f)
1955 .build(shadowPass);
1956 auto skinAlphaFrag = embeddedSpirv(mesh3d_shadow_skin_alpha_frag_spv);
1957 shadowSkinAlphaPipeline = device.createPipeline()
1958 .useClassicPipeline(skinVert, skinAlphaFrag)
1959 .setPipelineLayout(skinPassPipelineLayout)
1960 .setVertexInputState(vkb::VertexInputStateBuilder()
1961 .addInputBinding<MeshVertex>()
1962 .addAttributeDescription<MeshVertex>())
1963 .setDynamicStatesViewportScissor()
1964 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1965 vk::CullModeFlagBits::eNone,
1966 vk::FrontFace::eClockwise)
1967 .setDepthBias(0.0f, 0.5f)
1968 .build(shadowPass);
1969 shadowSkinAlphaSingleSidedPipeline = device.createPipeline()
1970 .useClassicPipeline(skinVert, skinAlphaFrag)
1971 .setPipelineLayout(skinPassPipelineLayout)
1972 .setVertexInputState(vkb::VertexInputStateBuilder()
1973 .addInputBinding<MeshVertex>()
1974 .addAttributeDescription<MeshVertex>())
1975 .setDynamicStatesViewportScissor()
1976 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f,
1977 vk::CullModeFlagBits::eBack,
1978 vk::FrontFace::eClockwise)
1979 .setDepthBias(0.0f, 0.5f)
1980 .build(shadowPass);
1981
1982 // Clear every ping-pong copy so sampling before the first real shadow pass
1983 // sees SHADER_READ_ONLY rather than UNDEFINED.
1984 vkb::executeImmediately(device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics),
1985 [&](vk::CommandBuffer cb) {
1986 vk::ClearValue clear{};
1987 clear.depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1988 for (auto &slot : shadowMaps) {
1989 slot.image.beginDepthAttachment();
1990 for (int c = 0; c < ShadowConfig::kTotalLayers; ++c) {
1991 vk::RenderPassBeginInfo rpBegin{};
1992 rpBegin.renderPass = shadowRenderPass;
1993 rpBegin.framebuffer = slot.framebuffers[c];
1994 rpBegin.renderArea = vk::Rect2D{{0, 0}, {size, size}};
1995 rpBegin.clearValueCount = 1;
1996 rpBegin.pClearValues = &clear;
1997 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1998 cb.endRenderPass();
1999 }
2000 slot.image.endSampledLayout();
2001 }
2002 });
2003}
2004
2005void Graphics::ensureClusteredBuffers(size_t lightsBytes, size_t tableBytes, size_t indicesBytes) {
2006 auto &st = currentClusteredStorage();
2007 bool reallocated = false;
2008 auto ensure = [&](vkb::GenericBuffer &buf, size_t &cap, size_t need) {
2009 if (need == 0) need = 4;
2010 if (cap >= need && buf.buffer) return;
2011 buf.release();
2012 // Grow with some slack.
2013 size_t alloc = std::max(need, cap ? cap * 2 : need);
2014 buf.allocate(frameToken(), device, vk::BufferUsageFlagBits::eStorageBuffer, vk::DeviceSize(alloc),
2015 vk::MemoryPropertyFlagBits::eHostVisible |
2016 vk::MemoryPropertyFlagBits::eHostCoherent);
2017 cap = alloc;
2018 reallocated = true;
2019 };
2020 ensure(st.lightsBuf, st.lightsCap, lightsBytes);
2021 ensure(st.tableBuf, st.tableCap, tableBytes);
2022 ensure(st.indicesBuf, st.indicesCap, indicesBytes);
2023 // Reallocated handles invalidate this frame's cached descriptor sets; drop
2024 // them so mesh3dClusteredSetFor rebinds against the new buffers.
2025 if (reallocated) currentMesh3dClusteredFrameSlots().sets.clear();
2026}
2027
2028void Graphics::uploadClusteredLighting(const ClusteredLightingUpload &upload) {
2029 const size_t lightsBytes =
2030 std::max(size_t(1), upload.lights.size()) * sizeof(ClusteredLightGpu);
2031 const size_t tableBytes =
2032 std::max(size_t(1), upload.clusterTable.size()) * sizeof(ClusterTableEntry);
2033 const size_t indicesBytes =
2034 std::max(size_t(1), upload.lightIndices.size()) * sizeof(uint32_t);
2035 ensureClusteredBuffers(lightsBytes, tableBytes, indicesBytes);
2036
2037 auto &st = currentClusteredStorage();
2038 if (!upload.lights.empty())
2039 st.lightsBuf.updateLocal(frameToken(), upload.lights.data(),
2040 upload.lights.size() * sizeof(ClusteredLightGpu));
2041 else {
2042 ClusteredLightGpu zero{};
2043 st.lightsBuf.updateLocal(frameToken(), &zero, sizeof(zero));
2044 }
2045 st.tableBuf.updateLocal(frameToken(), upload.clusterTable.data(),
2046 upload.clusterTable.size() * sizeof(ClusterTableEntry));
2047 st.indicesBuf.updateLocal(frameToken(), upload.lightIndices.data(),
2048 upload.lightIndices.size() * sizeof(uint32_t));
2049}
2050
2052 mesh3dClusteredActive = upload.active;
2053 mesh3dClustered = upload;
2054 if (upload.active) {
2055 createMesh3DClusteredPipeline();
2056 uploadClusteredLighting(upload);
2057 }
2058}
2059
2061 mesh3dClusteredActive = active;
2062 if (active) createMesh3DClusteredPipeline();
2063}
2064
2065void Graphics::ensureMesh3dStrides() {
2066 if (mesh3dUboStride != 0) return;
2067 const uint32_t align = std::max(
2068 1u, uint32_t(device.physical_device.properties.limits.minUniformBufferOffsetAlignment));
2069 mesh3dUboStride = alignUpValue(uint32_t(sizeof(Mesh3DUBO)), align);
2070 shadowUboStride = alignUpValue(uint32_t(sizeof(ShadowUBO)), align);
2071 mesh3dClusteredUboStride = alignUpValue(uint32_t(sizeof(Mesh3DClusteredUBO)), align);
2072}
2073
2074void Graphics::ensureMesh3dRing(Mesh3dFrameSlots &fslots) {
2075 ensureMesh3dStrides();
2076 const size_t want = std::max<size_t>(2048, fslots.lastDrawCount + 512);
2077 if (fslots.uboRing.buffer && fslots.capacity >= want) return;
2078 const size_t cap = std::max(want, fslots.capacity * 2);
2079 // Only called at frame start (before any draw of this frame is recorded),
2080 // so releasing the old ring is safe: no in-flight reader of this slot.
2081 fslots.uboRing.release();
2082 fslots.uboRing.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
2083 vk::DeviceSize(cap) * mesh3dUboStride, kHostVisibleCoherent);
2084 fslots.shadowRing.release();
2085 fslots.shadowRing.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
2086 vk::DeviceSize(cap) * shadowUboStride, kHostVisibleCoherent);
2087 fslots.capacity = cap;
2088 fslots.sets.clear(); // cached sets reference the old rings
2089 fslots.skinSets.clear();
2090}
2091
2092void Graphics::ensureMesh3dClusteredRing(Mesh3dClusteredFrameSlots &fslots) {
2093 ensureMesh3dStrides();
2094 const size_t want = std::max<size_t>(2048, fslots.lastDrawCount + 512);
2095 if (fslots.uboRing.buffer && fslots.capacity >= want) return;
2096 const size_t cap = std::max(want, fslots.capacity * 2);
2097 fslots.uboRing.release();
2098 fslots.uboRing.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
2099 vk::DeviceSize(cap) * mesh3dClusteredUboStride, kHostVisibleCoherent);
2100 fslots.shadowRing.release();
2101 fslots.shadowRing.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer,
2102 vk::DeviceSize(cap) * shadowUboStride, kHostVisibleCoherent);
2103 fslots.capacity = cap;
2104 fslots.sets.clear();
2105}
2106
2107vkb::BoundSet Graphics::mesh3dClusteredSetFor(GpuTexture *gpuTex, GpuTexture *normalTex,
2108 GpuTexture *envTex, GpuTexture *heightTex,
2109 GpuTexture *decalAlbedo, GpuTexture *decalNormal,
2110 GpuTexture *decalParams,
2111 Mesh3dClusteredFrameSlots &fslots) {
2112 ASSERT(gpuTex != nullptr);
2113 ASSERT(normalTex != nullptr);
2114 ASSERT(envTex != nullptr);
2115 ASSERT(heightTex != nullptr);
2116 ASSERT(decalAlbedo != nullptr);
2117 ASSERT(decalNormal != nullptr);
2118 ASSERT(decalParams != nullptr);
2119 ASSERT(currentShadowArrayView());
2120 ASSERT(fslots.uboRing.buffer);
2121 ASSERT(fslots.shadowRing.buffer);
2122
2123 auto probeTexture = [&](int index) -> GpuTexture * {
2124 if (index < mesh3dReflectionProbes.count) {
2125 Texture *texture = mesh3dReflectionProbes.probes[index].cubemap;
2126 if (texture && texture->gpuHandle) {
2127 auto *gpu = static_cast<GpuTexture *>(texture->gpuHandle);
2128 if (gpu->isCube) return gpu;
2129 }
2130 }
2131 return static_cast<GpuTexture *>(defaultEnvCubemap->gpuHandle);
2132 };
2133 GpuTexture *probe0 = probeTexture(0);
2134 GpuTexture *probe1 = probeTexture(1);
2135 Mesh3dSetKey key{gpuTex, normalTex, envTex, probe0, probe1, heightTex, nullptr, nullptr,
2136 decalAlbedo, decalNormal, decalParams};
2137 auto it = fslots.sets.find(key);
2138 if (it != fslots.sets.end()) return it->second;
2139
2140 vk::DescriptorSetAllocateInfo alloc{};
2141 alloc.descriptorPool = descriptorPool;
2142 alloc.descriptorSetCount = 1;
2143 alloc.pSetLayouts = &mesh3dClusteredSetLayout;
2144 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
2145
2146 auto &st = currentClusteredStorage();
2147 vkb::DescriptorSetUpdater updater(17, 17, 0);
2148 updater.beginDescriptorSet(unbound)
2149 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
2150 .buffer(fslots.uboRing.buffer, 0, sizeof(Mesh3DClusteredUBO))
2151 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
2152 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
2153 .beginImages(2, 0, vk::DescriptorType::eCombinedImageSampler)
2154 .image(vkb::SampledImage::forLaterSample(normalTex->sampler, normalTex->imageView()))
2155 .beginImages(3, 0, vk::DescriptorType::eCombinedImageSampler)
2156 .image(vkb::SampledImage::forLaterSample(envTex->sampler, envTex->imageView()))
2157 .beginBuffers(4, 0, vk::DescriptorType::eStorageBuffer)
2158 .buffer(st.lightsBuf.buffer, 0, vk::DeviceSize(st.lightsCap))
2159 .beginBuffers(5, 0, vk::DescriptorType::eStorageBuffer)
2160 .buffer(st.tableBuf.buffer, 0, vk::DeviceSize(st.tableCap))
2161 .beginBuffers(6, 0, vk::DescriptorType::eStorageBuffer)
2162 .buffer(st.indicesBuf.buffer, 0, vk::DeviceSize(st.indicesCap))
2163 .beginBuffers(7, 0, vk::DescriptorType::eUniformBufferDynamic)
2164 .buffer(fslots.shadowRing.buffer, 0, sizeof(ShadowUBO))
2165 .beginImages(8, 0, vk::DescriptorType::eCombinedImageSampler)
2166 .image(vkb::SampledImage::forLaterSample(shadowSampler, currentShadowArrayView()))
2167 .beginImages(9, 0, vk::DescriptorType::eCombinedImageSampler)
2168 .image(vkb::SampledImage::forLaterSample(heightTex->sampler, heightTex->imageView()))
2169 .beginImages(10, 0, vk::DescriptorType::eCombinedImageSampler)
2170 .image(vkb::SampledImage::forLaterSample(decalAlbedo->sampler, decalAlbedo->imageView()))
2171 .beginImages(11, 0, vk::DescriptorType::eCombinedImageSampler)
2172 .image(vkb::SampledImage::forLaterSample(decalNormal->sampler, decalNormal->imageView()))
2173 .beginImages(12, 0, vk::DescriptorType::eCombinedImageSampler)
2174 .image(vkb::SampledImage::forLaterSample(decalParams->sampler, decalParams->imageView()))
2175 .beginImages(18, 0, vk::DescriptorType::eCombinedImageSampler)
2176 .image(vkb::SampledImage::forLaterSample(probe0->sampler, probe0->imageView()))
2177 .beginImages(19, 0, vk::DescriptorType::eCombinedImageSampler)
2178 .image(vkb::SampledImage::forLaterSample(probe1->sampler, probe1->imageView()))
2179 .beginImages(20, 0, vk::DescriptorType::eCombinedImageSampler)
2180 .image(vkb::SampledImage::forLaterSample(shadowRawSampler, currentShadowArrayView()))
2181 .update(device.instance);
2182
2183 vkb::BoundSet bound = std::move(unbound).publish();
2184 fslots.sets.emplace(key, bound);
2185 return bound;
2186}
2187
2188size_t Graphics::mesh3dPipelineIndex(BlendMode blend, bool depthWrite, bool doubleSided) {
2189 return size_t(blend) * 4u + (depthWrite ? 2u : 0u) + (doubleSided ? 1u : 0u);
2190}
2191
2192vk::Pipeline Graphics::createMesh3DHairPipeline(const std::vector<uint32_t> &vert,
2193 const std::vector<uint32_t> &frag,
2194 vk::PipelineLayout layout,
2195 const vkb::BuiltRenderPass &rp,
2196 vk::SampleCountFlagBits samples) {
2197 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
2198 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
2199 vk::Pipeline pipe =
2200 device.createPipeline()
2201 .useClassicPipeline(vertModule, fragModule)
2202 .setPipelineLayout(layout)
2203 .setVertexInputState(vkb::VertexInputStateBuilder()
2204 .addInputBinding<MeshVertex>()
2205 .addAttributeDescription<MeshVertex>())
2206 .setDynamicStatesViewportScissor()
2207 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
2208 vk::FrontFace::eClockwise)
2209 .setDepthBias(-1.5f, -1.0f)
2210 .setMultisampler(false, samples)
2211 .setDepthStencil(true, false, vk::CompareOp::eLess)
2212 .setAlphaBlending(1)
2213 .build(rp);
2214 device->destroyShaderModule(vertModule);
2215 device->destroyShaderModule(fragModule);
2216 return pipe;
2217}
2218
2219vk::Pipeline Graphics::createMesh3DXrayPipeline(const std::vector<uint32_t> &vert,
2220 const std::vector<uint32_t> &frag,
2221 vk::PipelineLayout layout,
2222 const vkb::BuiltRenderPass &rp,
2223 vk::SampleCountFlagBits samples) {
2224 vk::ShaderModule vertModule = vkb::PipelineBuilder::createShaderModule(device.instance, vert);
2225 vk::ShaderModule fragModule = vkb::PipelineBuilder::createShaderModule(device.instance, frag);
2226 vk::Pipeline pipe =
2227 device.createPipeline()
2228 .useClassicPipeline(vertModule, fragModule)
2229 .setPipelineLayout(layout)
2230 .setVertexInputState(vkb::VertexInputStateBuilder()
2231 .addInputBinding<MeshVertex>()
2232 .addAttributeDescription<MeshVertex>())
2233 .setDynamicStatesViewportScissor()
2234 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eNone,
2235 vk::FrontFace::eClockwise)
2236 .setMultisampler(false, samples)
2237 // Depth test/write off: the shader discards visible fragments itself
2238 // (sampling G-buffer scene depth), so occluded ones can paint over walls.
2239 .setDepthStencil(false, false, vk::CompareOp::eLess)
2240 .setAlphaBlending(1)
2241 .setColorAttachmentCount(1)
2242 .build(rp);
2243 device->destroyShaderModule(vertModule);
2244 device->destroyShaderModule(fragModule);
2245 return pipe;
2246}
2247
2248Texture *Graphics::getTexture() { return nullptr; }
2249
2250
2251} // namespace eve::graphics::vulkan
LogicalId target
bool & active
float w
Definition AnimClip.cpp:738
float uv
graphics::Texture * albedo
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
double raw
std::string layout
ScriptFieldRegion region
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
vk::UniqueImage image
glm::vec4 tint
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
float blend
int h
Snapshot snapshot
std::vector< RecipeParam > params
bool doubleSided
Texture * normal
std::shared_ptr< OceanGpuSpectrum > gpu
OceanSprayView view
Texture * texture
int idx
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
float t
std::string build
std::string slot
Shader * shader
size_t end
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
uint32_t index
virtual Texture * getTexture()=0
Sampleable color buffer; screen Canvas returns nullptr.
Texture * prepareFinalSceneTexture(Texture *scene, Texture *motion=nullptr)
Build the shared linear-HDR AA, DOF, bloom, and exposure result for final ACES. @lifetime Returned te...
virtual void setMesh3DClusteredActive(bool active)=0
Cheap per-draw toggle for the already-uploaded clustered light table. Unlike setMesh3DClusteredLighti...
virtual bool isDisplayHdrActive() const
True when the live swapchain is scRGB or HDR10.
virtual void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload)=0
Enable clustered forward path for subsequent default mesh draws (SSBO light lists)....
SceneToneMapping
Final display mapping; None preserves linear color, Aces uses the fitted curve, and Filmic uses Rec....
Definition Graphics.h:1386
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
DisplayColorSpace activeDisplayColorSpace_
Definition Graphics.h:2330
PresentOverlayFn presentOverlayFn_
Definition Graphics.h:2335
DisplayColorSpace
Color space actually selected for the live swapchain.
Definition Graphics.h:1390
Texture * takeFinalSceneTexture()
Consume and clear the per-frame HDR scene resolve override. @lifetime Returned texture is borrowed an...
Definition Graphics.h:2150
Canvas * pipelineReflectionComposite(int width, int height)
Return a reusable HDR target for composing screen-space lighting. @lifetime Returned canvas is Graphi...
static constexpr uint32_t kPushConstantBytes
Definition Shader.h:45
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
float getScenePhotographicVignette() const override
Read the current render-thread photographic vignette.
Definition Graphics.h:901
Texture * getSceneColorTexture() override
Returns the scene color texture.
Mesh * newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST, int vertexCount, const uint32_t *indices, int indexCount) override
Creates a mesh from arrays. @ownership Caller deletes unless documented otherwise.
SceneToneMapping getSceneToneMapping() const override
Returns the scene tone mapping.
Definition Graphics.h:891
void initGpuTiming()
Creates the GPU timestamp query pool; call after device init.
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.
ActiveColorSpace
Active present color encoding after swapchain selection.
Color sceneComposeTint(bool aces, float paperWhiteNits, float peakNits) noexcept
Build the Color tint for tonemapping into a linear HDR compose target.
vk::Pipeline createSolidColorPipeline(vkb::Device &device, const vkb::BuiltRenderPass &renderPass, vk::PipelineLayout layout, BlendMode mode)
Internal synchronous pipeline factory; caller destroys the returned Vulkan pipeline.
PrimitiveCullMode
Face culling used by filled 3D primitives.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
Light3DGpu ClusteredLightGpu
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
PrimitiveDepthMode
Depth behavior of one 3D primitive.
const HouseComponent * pick(const std::vector< std::reference_wrapper< const HouseComponent > > &choices, std::mt19937 &rng)
Borrow a weighted component from library-backed choices. @ownership Borrowed; the session's library o...
CompareOp
CompareOp public API.
Definition NpcAi.h:27
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
static constexpr int kTotalLayers
Definition Shadow.h:27
int resolvedAtlasMapSize() const
Atlas edge length actually allocated for GPU shadow maps.
Definition Shadow.cpp:242
static ShadowSchemeSettings & current()
Borrow the process-wide settings object.
Definition Shadow.cpp:216
Per-frame / per-draw CSM + local-spot constants (std140).
Definition Shadow.h:36
Mesh3DClusteredUBO public API.
Definition Graphics.h:242
Mesh3DUBO public API.
Definition Graphics.h:181
glm::vec4 color