载入中...
搜索中...
未找到
Graphics.cpp
浏览该文件的文档.
1// Vulkan backend implementation — backend lifecycle and frame orchestration.
2//
3// Re-split from the merged dev single-TU Graphics.cpp (pure move;
4// dev changes preserved). Shared helpers live in GraphicsInternal.h.
5
6#define VKB_IMPL
8#include "common/Profile.h"
12#include "graphics/Light.h"
13#include "graphics/Outline.h"
17
18#include <SDL2/SDL.h>
19#include <SDL2/SDL_vulkan.h>
20
21#include <algorithm>
22#include <array>
23#include <cmath>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <functional>
28#include <future>
29#include <mutex>
30#include <stdexcept>
31#include <string>
32#include <vector>
33#if !defined(_WIN32)
34#include <unistd.h>
35#endif
36
37#include "common/BootWarmup.h"
38#include "common/Capability.h"
39#include "common/CrashLog.h"
40#include "common/Exception.h"
42#include "common/config.h"
43#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
44#include <vulkan/vulkan_beta.h>
45#endif
49#include "image/Image.h"
50#include "image/ImageData.h"
51#include "zeroerr/assert.h"
52
53#include <memory>
54
55
56#include <assimp/matrix3x3.h>
57#include <assimp/matrix4x4.h>
58#include <assimp/mesh.h>
59#include <assimp/vector3.h>
60#include <glm/gtc/matrix_transform.hpp>
61
63
64namespace eve::graphics::vulkan {
65
66namespace {
67
68bool wantVulkanValidation() {
69#if defined(EVENGINE_IOS)
70 return false;
71#else
72 const char* vkVal = std::getenv("EVENGINE_VULKAN_VALIDATION");
73 return vkVal && vkVal[0] != '\0' && vkVal[0] != '0';
74#endif
75}
76
77void disableImplicitLayersIfSafe() {
78 if (wantVulkanValidation()) return;
79 if (const char* existing = std::getenv("VK_LOADER_LAYERS_DISABLE")) {
80 if (existing[0] != '\0') return;
81 }
82 if (const char* layers = std::getenv("VK_INSTANCE_LAYERS")) {
83 if (layers[0] != '\0') return;
84 }
85#if defined(_WIN32)
86 _putenv_s("VK_LOADER_LAYERS_DISABLE", "~implicit~");
87#else
88 setenv("VK_LOADER_LAYERS_DISABLE", "~implicit~", 0);
89#endif
90}
91
92bool extensionAvailable(const std::vector<vk::ExtensionProperties>& props, const char* name) {
93 for (const auto& p : props) {
94 if (std::strcmp(p.extensionName, name) == 0) return true;
95 }
96 return false;
97}
98
99void addIfAvailable(std::vector<const char*>& exts, const std::vector<vk::ExtensionProperties>& props,
100 const char* name) {
101 if (extensionAvailable(props, name)) exts.push_back(name);
102}
103
104std::vector<const char*> collectFastInstanceExtensions(const std::vector<vk::ExtensionProperties>& props,
105 vk::InstanceCreateFlags* flagsOut) {
106 std::vector<const char*> exts;
107 addIfAvailable(exts, props, "VK_KHR_surface");
108 // Required before surface formats report HDR10 / extended-sRGB color spaces.
109 addIfAvailable(exts, props, "VK_EXT_swapchain_colorspace");
110#if defined(_WIN32)
111 addIfAvailable(exts, props, "VK_KHR_win32_surface");
112#elif defined(__ANDROID__)
113 addIfAvailable(exts, props, "VK_KHR_android_surface");
114#elif defined(__APPLE__)
115 addIfAvailable(exts, props, "VK_EXT_metal_surface");
116 if (extensionAvailable(props, "VK_KHR_portability_enumeration")) {
117 exts.push_back("VK_KHR_portability_enumeration");
118 if (flagsOut) *flagsOut |= vk::InstanceCreateFlagBits::eEnumeratePortabilityKHR;
119 }
120#else
121 addIfAvailable(exts, props, "VK_KHR_xcb_surface");
122 addIfAvailable(exts, props, "VK_KHR_xlib_surface");
123 addIfAvailable(exts, props, "VK_KHR_wayland_surface");
124#endif
125 return exts;
126}
127
128void initVulkanDispatcher() {
129#if defined(EVENGINE_MACOSX)
130 if (PFN_vkGetInstanceProcAddr sdlGpa =
131 reinterpret_cast<PFN_vkGetInstanceProcAddr>(SDL_Vulkan_GetVkGetInstanceProcAddr())) {
132 VULKAN_HPP_DEFAULT_DISPATCHER.init(sdlGpa);
133 vkb::InstanceBuilder::loaded = true;
134 return;
135 }
136#endif
137 if (!vkb::InstanceBuilder::loaded) {
138 vkb::InstanceBuilder::loadDefault();
139 vkb::InstanceBuilder::loaded = true;
140 }
141}
142
143uint32_t negotiatedInstanceApiVersion() {
144 // Vulkan 1.0 loaders do not expose vkEnumerateInstanceVersion. Newer
145 // loaders let us advertise the highest core version used by this backend,
146 // capped at 1.2 because that is the newest feature struct queried below.
147 uint32_t loaderVersion = VK_API_VERSION_1_0;
148 if (VULKAN_HPP_DEFAULT_DISPATCHER.vkEnumerateInstanceVersion) {
149 if (VULKAN_HPP_DEFAULT_DISPATCHER.vkEnumerateInstanceVersion(&loaderVersion) != VK_SUCCESS)
150 loaderVersion = VK_API_VERSION_1_0;
151 }
152 return std::min(loaderVersion, static_cast<uint32_t>(VK_API_VERSION_1_2));
153}
154
155vkb::Instance createInstanceFast() {
156 initVulkanDispatcher();
157 disableImplicitLayersIfSafe();
158 const uint32_t apiVersion = negotiatedInstanceApiVersion();
159 // Enumerate instance extensions only. vk-bootstrap's SystemInfo::query() also
160 // walks every implicit layer (and each layer's extensions), which is the
161 // bulk of "instance + surface" on a Windows SDK install.
162 const auto props = vk::enumerateInstanceExtensionProperties();
163 vk::InstanceCreateFlags flags{};
164 const auto exts = collectFastInstanceExtensions(props, &flags);
165
166 if (wantVulkanValidation()) {
167 vkb::InstanceBuilder builder;
168 builder.require_api_version(VK_API_VERSION_MAJOR(apiVersion), VK_API_VERSION_MINOR(apiVersion));
169 builder.request_validation_layers();
170 builder.use_default_debug_messenger();
171 for (auto* e : exts) builder.enable_extension(e);
172#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
173 builder.set_headless(true);
174 builder.add_flags(flags);
175#endif
176 std::printf("EVEngine: Vulkan validation layers enabled (EVENGINE_VULKAN_VALIDATION)\n");
177 return builder.build();
178 }
179
180 vk::ApplicationInfo app{};
181 app.pApplicationName = "EVEngine";
182 app.pEngineName = "EVEngine";
183 app.apiVersion = apiVersion;
184
185 vk::InstanceCreateInfo ci{};
186 ci.flags = flags;
187 ci.pApplicationInfo = &app;
188 ci.enabledExtensionCount = static_cast<uint32_t>(exts.size());
189 ci.ppEnabledExtensionNames = exts.data();
190
191 vkb::Instance inst;
192 inst.instance = vk::createInstance(ci);
193 VULKAN_HPP_DEFAULT_DISPATCHER.init(inst.instance);
194 return inst;
195}
196
197struct InstanceWarmup {
198 std::mutex mu;
199 std::future<vkb::Instance> future;
200 bool started = false;
201 bool consumed = false;
202};
203
204InstanceWarmup& instanceWarmup() {
205 static InstanceWarmup state;
206 return state;
207}
208
209void startVulkanInstanceWarmupImpl() {
210#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
211 // MoltenVK / SDL loader affinity is main-thread on Apple.
212 return;
213#else
214 auto& w = instanceWarmup();
215 std::lock_guard<std::mutex> lock(w.mu);
216 if (w.started) return;
217 w.started = true;
218 w.future = std::async(std::launch::async, [] {
219 StartupStage stage(" vulkan: instance (warmup thread)");
220 return createInstanceFast();
221 });
222#endif
223}
224
225vkb::Instance consumeWarmedInstance() {
226#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
227 StartupStage stage(" vulkan: instance");
228 return createInstanceFast();
229#else
230 startVulkanInstanceWarmupImpl();
231 std::future<vkb::Instance> fut;
232 {
233 auto& w = instanceWarmup();
234 std::lock_guard<std::mutex> lock(w.mu);
235 if (!w.consumed) {
236 w.consumed = true;
237 fut = std::move(w.future);
238 }
239 }
240 // Boot warmup transfers one instance only. A later Graphics owner creates
241 // its own instance after the previous owner has retired; never reuse its handle.
242 if (!fut.valid()) {
243 StartupStage stage(" vulkan: instance (new owner)");
244 return createInstanceFast();
245 }
246 StartupStage waitStage(" vulkan: wait instance warmup");
247 return fut.get();
248#endif
249}
250
251void discardWarmedInstance() noexcept {
252#if !defined(EVENGINE_MACOSX) && !defined(EVENGINE_IOS)
253 std::future<vkb::Instance> fut;
254 {
255 auto& w = instanceWarmup();
256 std::lock_guard<std::mutex> lock(w.mu);
257 if (!w.started || w.consumed) return;
258 w.consumed = true;
259 fut = std::move(w.future);
260 }
261 try {
262 vkb::Instance warmed = fut.get();
263 if (static_cast<VkInstance>(warmed.instance) != VK_NULL_HANDLE) warmed.destroy();
264 } catch (const std::exception& e) {
265 std::fprintf(stderr, "[vulkan] instance warmup cleanup failed: %s\n", e.what());
266 } catch (...) {
267 std::fprintf(stderr, "[vulkan] instance warmup cleanup failed with an unknown error\n");
268 }
269#endif
270}
271
272struct RegisterVulkanWarmup {
273 RegisterVulkanWarmup() { eve::boot::registerVulkanInstanceWarmup(&startVulkanInstanceWarmupImpl); }
274} gRegisterVulkanWarmup;
275
276} // namespace
277
278// --- Backend lifecycle and frame orchestration --------------------------------
279
280#if defined(VKB_ENABLE_VMA)
281VmaAllocatorOwner::~VmaAllocatorOwner() {
282 if (allocator_) vmaDestroyAllocator(allocator_);
283}
284
285void VmaAllocatorOwner::create(const vkb::Instance& instance, const vkb::PhysicalDevice& physicalDevice,
286 vkb::Device& device) {
287 VmaAllocatorCreateInfo createInfo{};
288 createInfo.instance = static_cast<VkInstance>(instance.instance);
289 createInfo.physicalDevice = static_cast<VkPhysicalDevice>(physicalDevice.instance);
290 createInfo.device = static_cast<VkDevice>(device.instance);
291 VmaVulkanFunctions vulkanFunctions{};
292 // The headless backend does not ask SDL to load Vulkan, so its loader
293 // accessor may legitimately be null. Reuse the dispatcher that created
294 // this instance; it is also the portable path on Android.
295 vulkanFunctions.vkGetInstanceProcAddr = VULKAN_HPP_DEFAULT_DISPATCHER.vkGetInstanceProcAddr;
296 if (!vulkanFunctions.vkGetInstanceProcAddr) {
297 throw Exception("VMA could not resolve vkGetInstanceProcAddr from the Vulkan dispatcher");
298 }
299 vulkanFunctions.vkGetDeviceProcAddr = reinterpret_cast<PFN_vkGetDeviceProcAddr>(
300 vulkanFunctions.vkGetInstanceProcAddr(createInfo.instance, "vkGetDeviceProcAddr"));
301 if (!vulkanFunctions.vkGetDeviceProcAddr) {
302 throw Exception("VMA could not resolve vkGetDeviceProcAddr");
303 }
304 createInfo.pVulkanFunctions = &vulkanFunctions;
305 // VMA is compiled with VMA_VULKAN_VERSION=1.0 so Android never statically
306 // imports newer core entry points. Keep the allocator on that contract even
307 // when the application instance negotiates a newer API version.
308 createInfo.vulkanApiVersion = VK_API_VERSION_1_0;
309 const VkResult result = vmaCreateAllocator(&createInfo, &allocator_);
310 if (result != VK_SUCCESS) throw Exception("vmaCreateAllocator failed: %d", int(result));
311 device.attachVmaAllocator(allocator_);
312}
313#endif
314
315std::string Graphics::getBackendName() const { return "vulkan"; }
316
318
321 caps.backend = "vulkan";
322 for (int i = 0; i < 11; ++i) caps.attachments.push_back(static_cast<FrameAttachment>(i));
323 frameCaptures().configure(std::move(caps));
324}
325
329 if (!initialized) {
330 // A process-level boot warmup may exist even when callers decide not
331 // to initialize graphics. Join it before the Vulkan loader unloads.
332 discardWarmedInstance();
333 if (static_cast<VkInstance>(inst.instance) != VK_NULL_HANDLE) inst.destroy();
334 return;
335 }
336 device->waitIdle();
337 // Drop optional RT resources while the logical device is still valid.
338 if (auto* rt = eve::cap::query<eve::graphics::IRayTracing>()) rt->detachFromGraphics();
339 destroyPbrResources();
340 deferredFileTextures_.clear();
341 if (gpuQueryPool_) device->destroyQueryPool(gpuQueryPool_);
342 gpuQueryPool_ = nullptr;
343 gpuTimingReady_ = false;
344 gpuFrameMs_ = 0.f;
345 gpuTimingPrefix_.fill(vk::CommandBuffer{});
346 gpuTimingPrefixSubmitted_.fill(false);
347 // Pipeline objects hold raw Shader* owned by ownedShaders. Drop them
348 // first so their destructors do not see freed shader pointers.
349 pipelineAA_.reset();
350 pipelineAO_.reset();
351 pipelineGI_.reset();
352 renderControl_.reset();
353 destroyGpuParticleResources();
354 for (auto& slots : framePostTargets_) slots.clear();
355 for (auto& target : sharedFramePostTargets_) target = nullptr;
356 spatialAAResolve_ = nullptr;
357 ownedCanvases.clear();
358 ownedMeshes.clear();
359 ownedGpuMeshes.clear();
360 ownedTextures.clear();
361 for (auto& g : ownedGpuTextures) {
362 if (g->sampler && !g->sharedSampler) device->destroySampler(g->sampler);
363 }
364 ownedGpuTextures.clear();
365 cachedSamplers_.clear();
366 samplerChangesPending_ = false;
367 texturesByPath.clear();
368 for (auto& g : ownedGpuShaders) {
369 if (g->swapchainPipeline) device->destroyPipeline(g->swapchainPipeline);
370 if (g->offscreenPipeline) device->destroyPipeline(g->offscreenPipeline);
371 if (g->swapchainOpaquePipeline) device->destroyPipeline(g->swapchainOpaquePipeline);
372 if (g->offscreenOpaquePipeline) device->destroyPipeline(g->offscreenOpaquePipeline);
373 if (g->hdrOffscreenPipeline) device->destroyPipeline(g->hdrOffscreenPipeline);
374 if (g->hdrOffscreenOpaquePipeline) device->destroyPipeline(g->hdrOffscreenOpaquePipeline);
375 if (g->mesh3dPipeline) device->destroyPipeline(g->mesh3dPipeline);
376 if (g->mesh3dXrayPipeline) device->destroyPipeline(g->mesh3dXrayPipeline);
377 if (g->mesh3dOffscreenPipeline) device->destroyPipeline(g->mesh3dOffscreenPipeline);
378 if (g->mesh3dHdrOffscreenPipeline) device->destroyPipeline(g->mesh3dHdrOffscreenPipeline);
379 // pipelineLayout is shared; do not destroy per-shader
380 }
381 ownedGpuShaders.clear();
382 ownedShaders.clear();
383 destroySwapchainResources();
384 if (pipeline) device->destroyPipeline(pipeline);
385 if (solidAlphaPipeline) device->destroyPipeline(solidAlphaPipeline);
386 if (additiveSolidPipeline) device->destroyPipeline(additiveSolidPipeline);
387 if (premultipliedSolidPipeline) device->destroyPipeline(premultipliedSolidPipeline);
388 if (multiplySolidPipeline) device->destroyPipeline(multiplySolidPipeline);
389 if (pipelineLayout) device->destroyPipelineLayout(pipelineLayout);
390 if (texPipeline) device->destroyPipeline(texPipeline);
391 if (additiveTexPipeline) device->destroyPipeline(additiveTexPipeline);
392 if (premultipliedTexPipeline) device->destroyPipeline(premultipliedTexPipeline);
393 if (multiplyTexPipeline) device->destroyPipeline(multiplyTexPipeline);
394 if (opaqueTexPipeline) device->destroyPipeline(opaqueTexPipeline);
395 if (particleDistortionPipeline) device->destroyPipeline(particleDistortionPipeline);
396 if (sceneTonemapPipeline) device->destroyPipeline(sceneTonemapPipeline);
397 if (texPipelineLayout) device->destroyPipelineLayout(texPipelineLayout);
398 if (shaderPipelineLayout) device->destroyPipelineLayout(shaderPipelineLayout);
399 if (mesh3dPipeline) device->destroyPipeline(mesh3dPipeline);
400 if (mesh3dTransparentPipeline) device->destroyPipeline(mesh3dTransparentPipeline);
401 for (auto pipeline : mesh3dSurfacePipelines)
402 if (pipeline) device->destroyPipeline(pipeline);
403 for (auto pipeline : primitive3DPipelines)
404 if (pipeline) device->destroyPipeline(pipeline);
405 destroyOffscreen3DResources();
406 if (mesh3dPipelineLayout) device->destroyPipelineLayout(mesh3dPipelineLayout);
407 if (mesh3dShaderPipelineLayout) device->destroyPipelineLayout(mesh3dShaderPipelineLayout);
408 mesh3dSetLayoutUnique.reset();
409 mesh3dFrameSlots.clear();
410 destroyVoxelRectResources();
411 if (mesh3dClusteredPipeline) device->destroyPipeline(mesh3dClusteredPipeline);
412 if (mesh3dClusteredPipelineLayout) device->destroyPipelineLayout(mesh3dClusteredPipelineLayout);
413 mesh3dClusteredSetLayoutUnique.reset();
414 mesh3dClusteredFrameSlots.clear();
415 destroyShadowResources();
416 destroyGBufferResources();
417 if (skinPassPipelineLayout) device->destroyPipelineLayout(skinPassPipelineLayout);
418 skinPassPipelineLayout = nullptr;
419 skinPassSetLayoutUnique.reset();
420 skinPassSetLayout = nullptr;
421 destroyDecalResources();
422 destroySceneColorResources();
423 destroyUiColorResources();
424 auto destroyBuf = [&](vkb::GenericBuffer& b) { b.release(); };
425 for (auto& st : clusteredStorages) {
426 destroyBuf(st.lightsBuf);
427 destroyBuf(st.tableBuf);
428 destroyBuf(st.indicesBuf);
429 }
430 clusteredStorages.clear();
431 if (lit2dPipeline) device->destroyPipeline(lit2dPipeline);
432 if (lit2dAdditivePipeline) device->destroyPipeline(lit2dAdditivePipeline);
433 if (lit2dPremultipliedPipeline) device->destroyPipeline(lit2dPremultipliedPipeline);
434 if (lit2dMultiplyPipeline) device->destroyPipeline(lit2dMultiplyPipeline);
435 if (lit2dOpaquePipeline) device->destroyPipeline(lit2dOpaquePipeline);
436 if (offscreenLitPipeline) device->destroyPipeline(offscreenLitPipeline);
437 if (offscreenLitAdditivePipeline) device->destroyPipeline(offscreenLitAdditivePipeline);
438 if (offscreenLitPremultipliedPipeline) device->destroyPipeline(offscreenLitPremultipliedPipeline);
439 if (offscreenLitMultiplyPipeline) device->destroyPipeline(offscreenLitMultiplyPipeline);
440 if (offscreenLitOpaquePipeline) device->destroyPipeline(offscreenLitOpaquePipeline);
441 if (lit2dPipelineLayout) device->destroyPipelineLayout(lit2dPipelineLayout);
442 lit2dSetLayoutUnique.reset();
443 for (auto& m : lit2dSets) m.clear();
444 lit2dSets.clear();
445 offscreenLit2dSets.clear();
446 destroyBuf(offscreenLighting2dUbo);
447 if (offscreenSolidPipeline) device->destroyPipeline(offscreenSolidPipeline);
448 if (offscreenSolidAlphaPipeline) device->destroyPipeline(offscreenSolidAlphaPipeline);
449 if (offscreenAdditiveSolidPipeline) device->destroyPipeline(offscreenAdditiveSolidPipeline);
450 if (offscreenPremultipliedSolidPipeline) device->destroyPipeline(offscreenPremultipliedSolidPipeline);
451 if (offscreenMultiplySolidPipeline) device->destroyPipeline(offscreenMultiplySolidPipeline);
452 if (offscreenTexPipeline) device->destroyPipeline(offscreenTexPipeline);
453 if (offscreenAdditiveTexPipeline) device->destroyPipeline(offscreenAdditiveTexPipeline);
454 if (offscreenPremultipliedTexPipeline) device->destroyPipeline(offscreenPremultipliedTexPipeline);
455 if (offscreenMultiplyTexPipeline) device->destroyPipeline(offscreenMultiplyTexPipeline);
456 if (offscreenOpaqueTexPipeline) device->destroyPipeline(offscreenOpaqueTexPipeline);
457 if (offscreenRenderPass) device->destroyRenderPass(offscreenRenderPass);
458 if (hdrOffscreenTexPipeline) device->destroyPipeline(hdrOffscreenTexPipeline);
459 if (hdrOffscreenOpaqueTexPipeline) device->destroyPipeline(hdrOffscreenOpaqueTexPipeline);
460 if (hdrOffscreenAdditiveTexPipeline) device->destroyPipeline(hdrOffscreenAdditiveTexPipeline);
461 if (hdrOffscreenPremultipliedTexPipeline) device->destroyPipeline(hdrOffscreenPremultipliedTexPipeline);
462 if (hdrOffscreenMultiplyTexPipeline) device->destroyPipeline(hdrOffscreenMultiplyTexPipeline);
463 if (hdrOffscreenSolidPipeline) device->destroyPipeline(hdrOffscreenSolidPipeline);
464 if (hdrOffscreenSolidAlphaPipeline) device->destroyPipeline(hdrOffscreenSolidAlphaPipeline);
465 if (hdrOffscreenAdditiveSolidPipeline) device->destroyPipeline(hdrOffscreenAdditiveSolidPipeline);
466 if (hdrOffscreenPremultipliedSolidPipeline) device->destroyPipeline(hdrOffscreenPremultipliedSolidPipeline);
467 if (hdrOffscreenMultiplySolidPipeline) device->destroyPipeline(hdrOffscreenMultiplySolidPipeline);
468 if (hdrOffscreenLitPipeline) device->destroyPipeline(hdrOffscreenLitPipeline);
469 if (hdrOffscreenLitAdditivePipeline) device->destroyPipeline(hdrOffscreenLitAdditivePipeline);
470 if (hdrOffscreenLitPremultipliedPipeline) device->destroyPipeline(hdrOffscreenLitPremultipliedPipeline);
471 if (hdrOffscreenLitMultiplyPipeline) device->destroyPipeline(hdrOffscreenLitMultiplyPipeline);
472 if (hdrOffscreenLitOpaquePipeline) device->destroyPipeline(hdrOffscreenLitOpaquePipeline);
473 if (hdrOffscreenTonemapPipeline) device->destroyPipeline(hdrOffscreenTonemapPipeline);
474 if (hdrOffscreenParticleDistortionPipeline) device->destroyPipeline(hdrOffscreenParticleDistortionPipeline);
475 destroyPresentComposeResources();
476 if (hdrOffscreenRenderPass) device->destroyRenderPass(hdrOffscreenRenderPass);
477 texSetLayoutUnique.reset();
478 if (descriptorPool) device->destroyDescriptorPool(descriptorPool);
479 if (uploadPool) device->destroyCommandPool(uploadPool);
480 if (renderpass) device->destroyRenderPass(renderpass);
481 if (surface) inst.instance.destroySurfaceKHR(surface);
482}
483
484void Graphics::createInstanceAndDevice(const std::vector<const char*>& extNames, void* nativeWindow,
485 vk::SurfaceKHR* surfaceOut) {
486 (void)extNames;
487 if (static_cast<VkInstance>(inst.instance) == VK_NULL_HANDLE) inst = consumeWarmedInstance();
488
489 if (nativeWindow != nullptr && surfaceOut != nullptr) {
490 StartupStage stage(" vulkan: surface");
491 auto* window = static_cast<SDL_Window*>(nativeWindow);
492 VkSurfaceKHR rawSurface = VK_NULL_HANDLE;
493 if (!SDL_Vulkan_CreateSurface(window, static_cast<VkInstance>(inst.instance), &rawSurface))
494 throw Exception("SDL_Vulkan_CreateSurface failed: %s", SDL_GetError());
495 surface = rawSurface;
496 *surfaceOut = rawSurface;
497 }
498
499 {
500 StartupStage stage(" vulkan: physical device + device");
501 auto selector = inst.selectPhysicalDevice();
502 selector.set_minimum_version(1, 0);
503 if (surface) {
504 selector.set_surface(surface);
505 } else {
506 // Headless: pick a device without requiring a presentable surface.
507 // VKBuilder's instance.headless flag is not propagated from
508 // InstanceBuilder, so defer_surface_initialization() is the
509 // supported way to select a device with no VkSurfaceKHR.
510 selector.defer_surface_initialization();
511 }
512#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
513 selector.add_required_extension("VK_KHR_portability_subset");
514#endif
515 // Soft-request KHR ray tracing. Devices without these extensions remain
516 // selectable; supported ones get the extensions into extensions_to_enable.
517 selector.add_desired_extension(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME);
518 selector.add_desired_extension(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME);
519 selector.add_desired_extension(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
520 selector.add_desired_extension(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME);
521 selector.add_desired_extension(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
522 selector.add_desired_extension(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
523 selector.add_desired_extension(VK_KHR_RAY_QUERY_EXTENSION_NAME);
524 auto phys = selector.select();
525 {
526 // Record the GPU identity into the crash/error log before any Vulkan
527 // work, so a device/driver crash can be tied to the exact GPU+driver.
528 const auto& pp = phys.properties;
529 const char* vendor = "unknown";
530 switch (pp.vendorID) {
531 case 0x10DE: vendor = "NVIDIA"; break;
532 case 0x1002: vendor = "AMD"; break;
533 case 0x8086: vendor = "Intel"; break;
534 case 0x13B5: vendor = "ARM"; break;
535 case 0x5143: vendor = "Qualcomm"; break;
536 default: break;
537 }
538 char vendorHex[16], deviceHex[16], driverHex[16];
539 std::snprintf(vendorHex, sizeof(vendorHex), "%04X", pp.vendorID);
540 std::snprintf(deviceHex, sizeof(deviceHex), "%04X", pp.deviceID);
541 std::snprintf(driverHex, sizeof(driverHex), "%08X", pp.driverVersion);
542 const uint32_t maj = VK_API_VERSION_MAJOR(pp.apiVersion);
543 const uint32_t min = VK_API_VERSION_MINOR(pp.apiVersion);
544 const uint32_t pat = VK_API_VERSION_PATCH(pp.apiVersion);
545 eve::recordLogEvent("info", std::string("gpu: ") + vendor + " '" + std::string(pp.deviceName.data()) +
546 "' vendorId=0x" + vendorHex + " deviceId=0x" + deviceHex +
547 " api=" + std::to_string(maj) + "." + std::to_string(min) + "." +
548 std::to_string(pat) + " driver=0x" + driverHex +
549 (nativeWindow ? "" : " [headless]"));
550 }
551 {
552 const vk::PhysicalDeviceFeatures supported = phys->getFeatures();
553 if (supported.samplerAnisotropy) {
554 phys.features.samplerAnisotropy = VK_TRUE;
555 maxSamplerAnisotropy = phys.properties.limits.maxSamplerAnisotropy;
556 if (maxSamplerAnisotropy < 1.f) maxSamplerAnisotropy = 1.f;
557 } else {
558 maxSamplerAnisotropy = 1.f;
559 }
560 if (supported.independentBlend) phys.features.independentBlend = VK_TRUE;
561 // Probe Vulkan 1.2 GPU-driven capabilities (bindless tables + GPU
562 // cull chain). The vendored headers omit `computeShader` / draw
563 // features from VkPhysicalDeviceFeatures; compute is core and
564 // universal, so treat it as present.
565 gpuDrivenCaps_ = GpuDrivenCaps{};
566 vk::PhysicalDeviceVulkan12Features vk12{};
567 gpuDrivenCaps_.api12 = negotiatedInstanceApiVersion() >= VK_API_VERSION_1_2 &&
568 phys.properties.apiVersion >= VK_API_VERSION_1_2;
569 if (gpuDrivenCaps_.api12) {
570 vk::PhysicalDeviceFeatures2 features2{};
571 vk12.sType = vk::StructureType::ePhysicalDeviceVulkan12Features;
572 features2.sType = vk::StructureType::ePhysicalDeviceFeatures2;
573 features2.pNext = &vk12;
574 phys->getFeatures2(&features2);
575 }
576 gpuDrivenCaps_.computeShader = true;
577 gpuDrivenCaps_.multiDrawIndirect = supported.multiDrawIndirect == VK_TRUE;
579 supported.shaderSampledImageArrayDynamicIndexing == VK_TRUE;
580 gpuDrivenCaps_.drawIndirectCount = vk12.drawIndirectCount == VK_TRUE;
581 gpuDrivenCaps_.descriptorIndexing = vk12.descriptorIndexing == VK_TRUE;
582 gpuDrivenCaps_.samplerArrayCapacity =
583 phys.properties.limits.maxPerStageDescriptorSamplers >= kMaxBindlessTextures;
584 if (gpuDrivenCaps_.gpuDrivenAvailable()) {
585 phys.features.shaderSampledImageArrayDynamicIndexing = VK_TRUE;
586 phys.features.shaderStorageBufferArrayDynamicIndexing = VK_TRUE;
587 phys.features.multiDrawIndirect = VK_TRUE;
588 }
589 }
590 // Optional KHR ray tracing: soft-request extensions via desired list
591 // (already added before select). Probe features here; enable them only
592 // when every required extension is present on the physical device.
593 // extensions_to_enable is private to vk-bootstrap — re-enumerate instead.
594 rayTracingCaps_ = RayTracingCaps{};
595 vk::PhysicalDeviceAccelerationStructureFeaturesKHR rtAsEnable{};
596 vk::PhysicalDeviceRayTracingPipelineFeaturesKHR rtPipeEnable{};
597 vk::PhysicalDeviceRayQueryFeaturesKHR rtQueryEnable{};
598 bool enableRtFeatures = false;
599 {
600 const auto extProps = phys->enumerateDeviceExtensionProperties();
601 auto hasExt = [&](const char* name) {
602 for (const auto& p : extProps) {
603 if (std::strcmp(p.extensionName, name) == 0) return true;
604 }
605 return false;
606 };
607 const bool extsOk = hasExt(VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME) &&
608 hasExt(VK_KHR_RAY_TRACING_PIPELINE_EXTENSION_NAME) &&
609 hasExt(VK_KHR_DEFERRED_HOST_OPERATIONS_EXTENSION_NAME);
610 const bool api12 = phys.properties.apiVersion >= VK_API_VERSION_1_2;
611 const bool bdaExt = hasExt(VK_KHR_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME) || api12;
612 const bool spirv14 = hasExt(VK_KHR_SPIRV_1_4_EXTENSION_NAME) || api12;
613
614 vk::PhysicalDeviceBufferDeviceAddressFeatures bdaFeat{};
615 bdaFeat.sType = vk::StructureType::ePhysicalDeviceBufferDeviceAddressFeatures;
616 vk::PhysicalDeviceAccelerationStructureFeaturesKHR asFeat{};
617 asFeat.sType = vk::StructureType::ePhysicalDeviceAccelerationStructureFeaturesKHR;
618 asFeat.pNext = &bdaFeat;
619 vk::PhysicalDeviceRayTracingPipelineFeaturesKHR rtFeat{};
620 rtFeat.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelineFeaturesKHR;
621 rtFeat.pNext = &asFeat;
622 vk::PhysicalDeviceFeatures2 features2Rt{};
623 features2Rt.sType = vk::StructureType::ePhysicalDeviceFeatures2;
624 features2Rt.pNext = &rtFeat;
625 phys->getFeatures2(&features2Rt);
626
627 vk::PhysicalDeviceRayQueryFeaturesKHR rqFeat{};
628 rqFeat.sType = vk::StructureType::ePhysicalDeviceRayQueryFeaturesKHR;
629 if (hasExt(VK_KHR_RAY_QUERY_EXTENSION_NAME)) {
630 // Probe rayQuery separately so its feature struct is not required
631 // on devices that only expose the acceleration-structure path.
632 vk::PhysicalDeviceFeatures2 features2Rq{};
633 features2Rq.sType = vk::StructureType::ePhysicalDeviceFeatures2;
634 features2Rq.pNext = &rqFeat;
635 phys->getFeatures2(&features2Rq);
636 }
637
638 const bool featuresOk = rtFeat.rayTracingPipeline == VK_TRUE && asFeat.accelerationStructure == VK_TRUE &&
639 bdaFeat.bufferDeviceAddress == VK_TRUE;
640
641 if (extsOk && bdaExt && spirv14 && featuresOk) {
642 rayTracingCaps_.accelerationStructure = true;
643 rayTracingCaps_.rayTracingPipeline = true;
644 rayTracingCaps_.bufferDeviceAddress = true;
645 rayTracingCaps_.available = true;
646 if (hasExt(VK_KHR_RAY_QUERY_EXTENSION_NAME) && rqFeat.rayQuery == VK_TRUE)
647 rayTracingCaps_.rayQuery = true;
648
649 vk::PhysicalDeviceRayTracingPipelinePropertiesKHR rtProps{};
650 rtProps.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelinePropertiesKHR;
651 vk::PhysicalDeviceProperties2 props2{};
652 props2.sType = vk::StructureType::ePhysicalDeviceProperties2;
653 props2.pNext = &rtProps;
654 phys->getProperties2(&props2);
655 rayTracingCaps_.shaderGroupHandleSize = rtProps.shaderGroupHandleSize;
656 rayTracingCaps_.shaderGroupBaseAlignment = rtProps.shaderGroupBaseAlignment;
657 rayTracingCaps_.shaderGroupHandleAlignment = rtProps.shaderGroupHandleAlignment;
658 rayTracingCaps_.maxRecursionDepth = rtProps.maxRayRecursionDepth;
659
660 // VUID-02830: do not chain VkPhysicalDeviceBufferDeviceAddressFeatures
661 // alongside VkPhysicalDeviceVulkan12Features. Enable BDA via the 1.2
662 // feature struct below; only AS / RT pipeline / optional rayQuery here.
663 rtAsEnable.sType = vk::StructureType::ePhysicalDeviceAccelerationStructureFeaturesKHR;
664 rtAsEnable.accelerationStructure = VK_TRUE;
665 rtPipeEnable.sType = vk::StructureType::ePhysicalDeviceRayTracingPipelineFeaturesKHR;
666 rtPipeEnable.rayTracingPipeline = VK_TRUE;
667 if (rayTracingCaps_.rayQuery) {
668 rtQueryEnable.sType = vk::StructureType::ePhysicalDeviceRayQueryFeaturesKHR;
669 rtQueryEnable.rayQuery = VK_TRUE;
670 }
671 enableRtFeatures = true;
672 }
673 // When features are missing, desired RT extensions may still be
674 // listed on the device; they stay inert without the feature bits.
675 }
676
677 vkb::DeviceBuilder deviceBuilder = phys.createDevice();
678#if defined(EVENGINE_MACOSX) || defined(EVENGINE_IOS)
679 // Portability features are disabled unless explicitly enabled, even
680 // when the physical device supports updating comparison descriptors.
681 VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilitySupported{};
682 // The pinned core headers hide this beta extension's enum token.
683 constexpr auto portabilityFeatureType = static_cast<VkStructureType>(1000163000);
684 portabilitySupported.sType = portabilityFeatureType;
685 vk::PhysicalDeviceFeatures2 portabilityQuery{};
686 portabilityQuery.pNext = &portabilitySupported;
687 phys->getFeatures2(&portabilityQuery);
688 VkPhysicalDevicePortabilitySubsetFeaturesKHR portabilityEnable{};
689 portabilityEnable.sType = portabilityFeatureType;
690 portabilityEnable.mutableComparisonSamplers = portabilitySupported.mutableComparisonSamplers;
691 deviceBuilder.add_pNext(&portabilityEnable);
692#endif
693 // Vulkan 1.2 feature: vkCmdDrawIndirectCount (VG cluster draws) and BDA for RT.
694 vk::PhysicalDeviceVulkan12Features vk12Enable{};
695 vk12Enable.sType = vk::StructureType::ePhysicalDeviceVulkan12Features;
696 if (gpuDrivenCaps_.drawIndirectCount) vk12Enable.drawIndirectCount = VK_TRUE;
697 if (enableRtFeatures) {
698 vk12Enable.bufferDeviceAddress = VK_TRUE;
699 // DeviceBuilder reconstructs the chain from individually registered
700 // structures, overwriting any prelinked pNext pointers.
701 deviceBuilder.add_pNext(&rtPipeEnable);
702 deviceBuilder.add_pNext(&rtAsEnable);
703 if (rayTracingCaps_.rayQuery) deviceBuilder.add_pNext(&rtQueryEnable);
704 }
705 if (gpuDrivenCaps_.api12) deviceBuilder.add_pNext(&vk12Enable);
706 device = deviceBuilder.build();
707 // Load device-level extension entry points (needed for KHR RT).
708 VULKAN_HPP_DEFAULT_DISPATCHER.init(device.instance);
709#if defined(VKB_ENABLE_VMA)
710 vmaAllocatorOwner_.create(inst, phys, device);
711#endif
712 maxSamplerAnisotropy = device.caps.maxSamplerAnisotropy;
713 eve::recordLogEvent("info",
714 "gpu: logical device created (gpuDriven=" +
715 std::string(gpuDrivenCaps_.gpuDrivenAvailable() ? "on" : "off") +
716 ", rayTracing=" + std::string(rayTracingCaps_.rayTracingAvailable() ? "on" : "off") +
717#if defined(VKB_ENABLE_VMA)
718 ", allocator=VMA" +
719#else
720 ", allocator=native" +
721#endif
722 ", maxAniso=" + std::to_string(maxSamplerAnisotropy) + ")");
723 }
724}
725
727 StartupStage initStage("graphics: initHeadless (total)");
728 if (initialized) {
729 if (headless_) {
730 // Re-entrant: test cases share the process-wide Graphics singleton.
731 // Update the logical viewport and keep the existing device.
733 return;
734 }
735 throw Exception("Graphics::initHeadless: already initialized with a window");
736 }
737 if (width <= 0 || height <= 0) throw Exception("Graphics::initHeadless: invalid size");
738
739 // No window, no surface extensions, no swapchain: a bare Vulkan device that
740 // renders into offscreen canvases and reads pixels back on the CPU.
741 createInstanceAndDevice({}, nullptr, nullptr);
742
743 uploadPool = device.createCommandPool();
745 headless_ = true;
746
747 {
748 StartupStage stage(" vulkan: headless renderpass + pipelines");
749 // Plain color+depth render pass mirroring the swapchain pass format so
750 // the shared pipeline builders can reuse it; nothing is ever presented.
751 vkb::RenderPassBuilder rpBuilder{device};
752 renderpass =
753 rpBuilder.addPresentAttachment(vk::Format::eB8G8R8A8Unorm, vk::AttachmentLoadOp::eClear)
754 .addDepthAttachment(depthFormat, vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eDontCare)
755 .addSubpass(vkb::SubpassBuilder()
756 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
757 .setDepthStencilAttachment(1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
758 .addDependency(
759 VK_SUBPASS_EXTERNAL, 0,
760 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
761 vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eEarlyFragmentTests,
762 {},
763 vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite |
764 vk::AccessFlagBits::eDepthStencilAttachmentWrite)
765 .build();
766 depthImage = vkb::DepthStencilImage{device, uint32_t(width), uint32_t(height), depthFormat};
767 pipelineLayout = createPipelineLayout(device);
768 createTexturedPipeline();
769 createMesh3DPipeline();
770 createMesh3DClusteredPipeline();
771 createVoxelRectPipeline();
772 }
773
774 initialized = true;
775 {
776 StartupStage stage(" vulkan: shadow resources (CSM atlas + pipelines)");
777 createShadowResources();
778 }
779 {
780 StartupStage stage(" vulkan: white texture");
781 const uint8_t whitePixel[4] = {255, 255, 255, 255};
782 whiteTexture = newTexture(1, 1, whitePixel);
783 const std::vector<uint8_t> cubePx(6 * 4, 255);
784 defaultBindlessCube = newCubemap(1, cubePx.data());
785 }
786 {
787 StartupStage stage(" vulkan: gpu-driven bindless set + pipeline");
788 initGpuDrivenResources();
789 }
790 eve::recordLogEvent("info", "gfx: graphics initialized (headless)");
791}
792
793void Graphics::initWithWindow(void* nativeWindow) {
794 eve::cap::provide<eve::service::IGpuTimer>(this);
795 StartupStage initStage("graphics: initWithWindow (total)");
796 if (initialized) {
797 // Window module may destroy/recreate the SDL window (tests, setWindowSettings).
798 // The Vulkan surface is tied to the native window. SDL can hand back the
799 // same pointer for a freshly recreated window, so pointer identity alone
800 // can't tell whether the surface is still valid: Window::close() drops it
801 // via onNativeWindowDestroyed(), and a missing surface must be rebuilt too.
802 if (sdlWindow == nativeWindow && surface) return;
803 sdlWindow = nativeWindow;
804 recreateSurfaceForResume();
805 // Restore the initWithWindow contract (device + swapchain valid on
806 // return): rebuild the swapchain synchronously. On desktop this runs
807 // immediately; on Android/iOS isRenderSurfaceStable() defers it until
808 // the native surface settles, leaving swapchainDirty set (same as before).
809 rebuildSwapchainIfNeeded();
810 return;
811 }
812 sdlWindow = nativeWindow;
813 auto* window = static_cast<SDL_Window*>(nativeWindow);
814 ASSERT(window != nullptr);
815 if (!window) throw Exception("Graphics::initWithWindow: null SDL_Window");
816
817 unsigned int count = 0;
818 if (!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr))
819 throw Exception("SDL_Vulkan_GetInstanceExtensions failed: %s", SDL_GetError());
820
821 std::vector<const char*> extNames(count);
822 if (!SDL_Vulkan_GetInstanceExtensions(window, &count, extNames.data()))
823 throw Exception("SDL_Vulkan_GetInstanceExtensions failed: %s", SDL_GetError());
824
825 createInstanceAndDevice(extNames, nativeWindow, &surface);
826
827 uploadPool = device.createCommandPool();
828
829 int pw = 0, ph = 0;
830 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
831 int lw = 0, lh = 0;
832 SDL_GetWindowSize(window, &lw, &lh);
833 setViewportSize(lw, lh, pw, ph);
834
835 {
836 StartupStage stage(" vulkan: swapchain + solid pipelines");
837 createSwapchainAndPipeline();
838 eve::recordLogEvent("info", "gfx: swapchain + solid pipelines created");
839 }
840 {
841 StartupStage stage(" vulkan: textured/lit2d pipelines");
842 createTexturedPipeline();
843 }
844 {
845 StartupStage stage(" vulkan: mesh3d pipeline");
846 createMesh3DPipeline();
847 }
848 {
849 StartupStage stage(" vulkan: clustered pipeline");
850 createMesh3DClusteredPipeline();
851 }
852 {
853 StartupStage stage(" vulkan: voxel pipeline");
854 createVoxelRectPipeline();
855 }
856 initialized = true;
857 {
858 StartupStage stage(" vulkan: shadow resources (CSM atlas + pipelines)");
859 createShadowResources();
860 }
861 {
862 StartupStage stage(" vulkan: white texture");
863 const uint8_t whitePixel[4] = {255, 255, 255, 255};
864 whiteTexture = newTexture(1, 1, whitePixel);
865 const std::vector<uint8_t> cubePx(6 * 4, 255);
866 defaultBindlessCube = newCubemap(1, cubePx.data());
867 }
868 {
869 StartupStage stage(" vulkan: gpu-driven bindless set + pipeline");
870 initGpuDrivenResources();
871 }
872 eve::recordLogEvent("info", "gfx: graphics initialized (window)");
873}
874
876 if (!initialized) return;
877 if (swapchainPassOpen || sceneColorPassOpen) abortOpen3DFrame();
878 // Fire registered window-destroyed callbacks (UI backend tears down its
879 // ImGui context here) before the device/surface resources are released.
880 for (auto& cb : windowDestroyedCallbacks_) cb.first(cb.second);
883
884 device->waitIdle();
885 destroySwapchainResources();
886 swapchain.destroy();
887 swapchain = vkb::Swapchain{};
888 if (surface) {
889 inst.instance.destroySurfaceKHR(surface);
890 surface = VK_NULL_HANDLE;
891 }
892 sdlWindow = nullptr;
893 swapchainDirty = true;
894}
895
896void Graphics::destroySwapchainResources() {
897 destroyPbrResources();
898 presentRecording = {};
899 swapchainPass = {};
900 presentModel.destroy();
901 presentModel = vkb::Present{};
902 destroyGpuDrivenCullResources();
903 depthImage = vkb::DepthStencilImage{};
904 destroyReadbackResources();
905 // Release reused per-frame vertex buffers. Callers hold a device-wide
906 // waitIdle before this runs.
907 for (auto& fb : frame2dBuffers) releaseFrame2dBuffers(fb);
908 frame2dBuffers.clear();
909 releaseFrame2dBuffers(offscreenBuffers);
910 // Per-frame lit-2D UBOs are keyed to the in-flight slot count; release them
911 // here (slot count may change across recreation).
912 for (auto& ubo : lighting2dUboSlots) ubo.release();
913 lighting2dUboSlots.clear();
914 // Descriptor sets cached against the released UBO handles must be dropped;
915 // they live in the shared descriptor pool, so only the cache is cleared.
916 lit2dSets.clear();
917}
918
919uint32_t Graphics::frameSlotCount() const {
920 uint32_t n = presentModel.frames_in_flight;
921 if (n == 0) n = swapchain.image_count;
922 return n ? n : 1u;
923}
924
925size_t Graphics::currentFrameSlot() const {
926 const uint32_t n = frameSlotCount();
927 size_t slot = presentRecording ? presentRecording.slot().index : swapchain.current_frame;
928 return (n > 0 && slot >= n) ? 0 : slot;
929}
930
931vk::CommandBuffer& Graphics::currentPresentCb() {
932 if (offscreen3DPassOpen && offscreen3DCB) return offscreen3DCB;
933 if (swapchainPass) return swapchainPass.commandBuffer();
934 return presentRecording.commandBuffer();
935}
936
937vkb::FrameSlot Graphics::frameToken() const {
938 if (offscreen3DPassOpen) return vkb::FrameSlot{0};
939 if (presentRecording) return presentRecording.slot();
940 return vkb::FrameSlot::gpuIdle();
941}
942
944 EV_PROFILE_MODULE("graphics", "GpuResources.WaitAllFrames");
945 presentModel.waitForAllFrames();
946}
947
948void Graphics::invalidateTextureBindings() {
949 for (auto& frame : mesh3dFrameSlots) frame.sets.clear();
950 for (auto& frame : mesh3dClusteredFrameSlots) frame.sets.clear();
951 for (auto& m : lit2dSets) m.clear();
952 offscreenLit2dSets.clear();
953 post2Sets.clear();
954 voxelRectSets.clear();
955}
956
957Graphics::Frame2DBuffers& Graphics::currentFrame2DBuffers() {
958 return currentSlot(frame2dBuffers, frameSlotCount(), currentFrameSlot());
959}
960
961Graphics::Mesh3dFrameSlots& Graphics::currentMesh3dFrameSlots() {
962 return currentSlot(mesh3dFrameSlots, frameSlotCount(), currentFrameSlot());
963}
964
965Graphics::Mesh3dClusteredFrameSlots& Graphics::currentMesh3dClusteredFrameSlots() {
966 return currentSlot(mesh3dClusteredFrameSlots, frameSlotCount(), currentFrameSlot());
967}
968
969vkb::GenericBuffer& Graphics::currentLighting2dUbo() {
970 auto& ubo = currentSlot(lighting2dUboSlots, frameSlotCount(), currentFrameSlot());
971 // allocate() reuses the slot's buffer when it already fits (same usage/
972 // memflags, fixed sizeof(Lighting2DUBO)), so this is a no-op after first use.
973 ubo.allocate(frameToken(), device, vk::BufferUsageFlagBits::eUniformBuffer, sizeof(Lighting2DUBO),
974 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
975 return ubo;
976}
977
978std::unordered_map<Graphics::LitSetKey, vkb::BoundSet, Graphics::LitSetKeyHash>& Graphics::currentLit2dSets() {
979 return currentSlot(lit2dSets, frameSlotCount(), currentFrameSlot());
980}
981
982Graphics::ClusteredStorage& Graphics::currentClusteredStorage() {
983 return currentSlot(clusteredStorages, frameSlotCount(), currentFrameSlot());
984}
985
986Graphics::VoxelInstanceFrame& Graphics::currentVoxelInstanceFrame() {
987 return currentSlot(voxelInstanceFrames, frameSlotCount(), currentFrameSlot());
988}
989
990Graphics::ShadowMapSlot& Graphics::currentShadowMap() {
991 ASSERT(!shadowMaps.empty());
992 return shadowMaps[currentFrameSlot() % shadowMaps.size()];
993}
994
995vk::ImageView Graphics::currentShadowArrayView() {
996 if (shadowMaps.empty()) return vk::ImageView{};
997 return currentShadowMap().image.arrayView();
998}
999
1000Graphics::GBufferSlot* Graphics::currentGBufferSlot() {
1001 if (gbufferSlots.empty()) return nullptr;
1002 return &gbufferSlots[currentFrameSlot() % gbufferSlots.size()];
1003}
1004
1006 if (auto* slot = currentGBufferSlot(); slot && gbufferPending && slot->depthColorTex.gpuHandle)
1007 return &slot->depthColorTex;
1008 GBuffer* gbuffer = renderControl_ ? renderControl_->getGBuffer() : nullptr;
1009 return gbuffer && gbuffer->isValid() ? gbuffer->getDepthTexture() : nullptr;
1010}
1011
1012Graphics::DecalSlot* Graphics::currentDecalSlot() {
1013 if (decalSlots.empty()) return nullptr;
1014 return &decalSlots[currentFrameSlot() % decalSlots.size()];
1015}
1016
1017Graphics::SceneColorSlot* Graphics::currentSceneColorSlot() {
1018 if (sceneColorSlots.empty()) return nullptr;
1019 return &sceneColorSlots[currentFrameSlot() % sceneColorSlots.size()];
1020}
1021
1023 auto* slot = currentSceneColorSlot();
1024 if (!slot || !slot->colorTex.gpuHandle) return nullptr;
1025 return &slot->colorTex;
1026}
1027
1028Graphics::UiColorSlot* Graphics::currentUiColorSlot() {
1029 if (uiColorSlots.empty()) return nullptr;
1030 return &uiColorSlots[currentFrameSlot() % uiColorSlots.size()];
1031}
1032
1033void Graphics::dropPendingOffscreenPasses() {
1034 shadowPendingMask = 0;
1035 for (auto& d : shadowCascadeDraws) d.clear();
1036 gbufferPending = false;
1037 gbufferPassDraws.clear();
1038 gbufferInstancedBatches.clear();
1039 decalPending = false;
1040 decalPassDraws.clear();
1041}
1042
1043bool Graphics::beginSwapchainRenderPass() {
1044 if (!beginPresentCommandBuffer()) {
1045 dropPendingOffscreenPasses();
1046 return false;
1047 }
1048 recordDeferredFrameGraph();
1049 beginSwapchainColorPass();
1050 return true;
1051}
1052
1053void Graphics::beginSwapchainColorPass() {
1054 std::array<vk::ClearValue, 2> clears{};
1055 clears[0].color = vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, clearColor.a});
1056 clears[1].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
1057 swapchainPass = presentRecording.beginRenderPass(renderpass, clears.data(), uint32_t(clears.size()));
1058}
1059
1060bool Graphics::rebuildSwapchainIfNeeded() {
1061 const bool wantRecreate = surfaceNeedsRecreate.load() || swapchainDirty || presentModel.needs_recreate;
1062 if (!wantRecreate) return true;
1063 if (!isRenderSurfaceStable()) return false;
1064
1065 if (surfaceNeedsRecreate.exchange(false)) recreateSurfaceForResume();
1066 if (presentModel.needs_recreate) {
1067 presentModel.needs_recreate = false;
1068 // presentKHR sets needs_recreate on both OUT_OF_DATE and SUBOPTIMAL.
1069 // After a Cocoa resize MoltenVK often stays SUBOPTIMAL for many presents
1070 // even when the drawable size already matches the live swapchain; forcing
1071 // a rebuild every frame then never leaves the first-frame clear path
1072 // (SpatialAA/offscreen recreate). Rebuild only when the drawable size
1073 // actually disagrees — true OUT_OF_DATE with a matching size still trips
1074 // the acquire-failure path in beginPresentCommandBuffer, which forces a
1075 // recreate.
1076 auto* window = static_cast<SDL_Window*>(sdlWindow);
1077 int pw = 0, ph = 0;
1078 if (window) SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1079 // vkb::Swapchain's bool conversion is explicit; use extent as the live-
1080 // chain probe (empty/destroyed swapchains keep extent at 0x0).
1081 const bool sizeMismatch = swapchain.extent.width == 0 || swapchain.extent.height == 0 || pw <= 0 || ph <= 0 ||
1082 uint32_t(pw) != swapchain.extent.width || uint32_t(ph) != swapchain.extent.height;
1083 if (sizeMismatch) swapchainDirty = true;
1084 }
1085 if (swapchainDirty) {
1086 device->waitIdle();
1087 createSwapchainAndPipeline();
1088 }
1089 return true;
1090}
1091
1092bool Graphics::beginPresentCommandBuffer() {
1093 pollFrameCapture();
1094 for (int attempt = 0; attempt < 3; ++attempt) {
1095 if (!rebuildSwapchainIfNeeded()) return false;
1096 {
1097 EV_PROFILE_MODULE("graphics", "Frame.Acquire");
1098 const bool newFrame = !presentRecording;
1099 presentRecording = presentModel.begin();
1100 // A slot can recur after empty frames. Its number is not a frame identity.
1101 if (presentRecording && newFrame) {
1102 ++presentSequence_;
1103 deferredGraphRecorded_ = false;
1104 }
1105 }
1106 if (presentRecording) {
1107 pollFrameCapture();
1110 return true;
1111 }
1112 // Acquire failed without beginning the CB (see Present::begin). Rebuild once.
1113 if (presentModel.needs_recreate) {
1114 presentModel.needs_recreate = false;
1115 swapchainDirty = true;
1116 continue;
1117 }
1118 return false;
1119 }
1120 return false;
1121}
1122
1123bool Graphics::isRenderSurfaceReady() const {
1124 auto* window = static_cast<SDL_Window*>(sdlWindow);
1125 if (!window) return false;
1126 // Mobile background/resume and desktop minimize can report a zero drawable
1127 // size until the native window settles — skip present rather than touching
1128 // an invalid swapchain.
1129 int pw = 0, ph = 0;
1130 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1131 return pw > 0 && ph > 0;
1132}
1133
1134bool Graphics::isRenderSurfaceStable() {
1135#if defined(EVENGINE_ANDROID) || defined(EVENGINE_IOS)
1136 auto* window = static_cast<SDL_Window*>(sdlWindow);
1137 if (!window) return false;
1138 int pw = 0, ph = 0;
1139 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1140 if (pw <= 0 || ph <= 0) {
1141 surfaceStableFrames = 0;
1142 return false;
1143 }
1144 if (pw != pendingSurfaceW || ph != pendingSurfaceH) {
1145 // Size still changing (mid-rotation / Split View); wait for it to settle.
1146 pendingSurfaceW = pw;
1147 pendingSurfaceH = ph;
1148 surfaceStableFrames = 1;
1149 return false;
1150 }
1151 // Require a couple of consecutive identical polls before rebuilding.
1152 if (surfaceStableFrames < 3) {
1153 ++surfaceStableFrames;
1154 return false;
1155 }
1156 return true;
1157#else
1158 return true;
1159#endif
1160}
1161
1162void Graphics::recreateSurfaceForResume() {
1163 // Mobile platforms destroy the native window when backgrounded, which
1164 // invalidates the VkSurfaceKHR. On resume SDL creates a fresh native
1165 // window, so we must rebuild the surface (and the swapchain that depends on
1166 // it) before presenting again. Runs on the render thread.
1167 if (!initialized) return;
1168 auto* window = static_cast<SDL_Window*>(sdlWindow);
1169 if (!window) return;
1170
1171 device->waitIdle();
1172
1173 // Tear down surface-dependent resources first.
1174 destroySwapchainResources();
1175 swapchain.destroy();
1176 swapchain = vkb::Swapchain{};
1177 if (surface) {
1178 inst.instance.destroySurfaceKHR(surface);
1179 surface = VK_NULL_HANDLE;
1180 }
1181
1182 // Create a new surface from the freshly created native window.
1183 VkSurfaceKHR rawSurface = VK_NULL_HANDLE;
1184 if (!SDL_Vulkan_CreateSurface(window, static_cast<VkInstance>(inst.instance), &rawSurface))
1185 throw Exception("resume: SDL_Vulkan_CreateSurface failed: %s", SDL_GetError());
1186 surface = rawSurface;
1187 device.surface = surface;
1188
1189 // Refresh drawable size (orientation / Split View may have changed).
1190 int pw = 0, ph = 0, lw = 0, lh = 0;
1191 SDL_Vulkan_GetDrawableSize(window, &pw, &ph);
1192 SDL_GetWindowSize(window, &lw, &lh);
1193 if (pw > 0 && ph > 0) setViewportSize(lw, lh, pw, ph);
1194
1195 swapchainDirty = true;
1196}
1197
1199 pollFrameCapture();
1200 if (!initialized) return;
1201 if (headless_) return;
1202 if (!isActive()) return;
1203 if (isCanvasActive()) throw Exception("present: cannot present while a Canvas is active");
1204 if (!isRenderSurfaceReady()) {
1205 // Native window is mid-(re)creation / rotation; drop this frame's work
1206 // instead of touching an invalid swapchain (which crashes the driver).
1207 if (swapchainPassOpen)
1208 abortOpen3DFrame();
1209 else
1210 clear2DBatches();
1211 hasPendingClear = false;
1212 return;
1213 }
1214 flushBatch();
1215}
1216
1217void Graphics::draw(eve::graphics::Graphics*, const glm::mat4&) const {}
1218void Graphics::draw(Canvas*, const glm::mat4&) const {}
1219
1220// ---- GPU frame timing ------------------------------------------------------
1221
1223 if (const char* setting = std::getenv("EVENGINE_GPU_TIMING"); setting && std::strcmp(setting, "0") == 0) return;
1224 if (gpuQueryPool_) return;
1225 try {
1226 timestampPeriod_ = device.physical_device.properties.limits.timestampPeriod;
1227 vk::QueryPoolCreateInfo ci;
1228 ci.queryType = vk::QueryType::eTimestamp;
1229 ci.queryCount = 2 * kAsyncResourceCopies;
1230 gpuQueryPool_ = device->createQueryPool(ci);
1231 const auto buffers = device->allocateCommandBuffers(
1232 vk::CommandBufferAllocateInfo{uploadPool, vk::CommandBufferLevel::ePrimary, kAsyncResourceCopies});
1233 std::copy(buffers.begin(), buffers.end(), gpuTimingPrefix_.begin());
1234 gpuTimingPrefixSubmitted_.fill(false);
1235 gpuTimingReady_ = true;
1236 } catch (...) {
1237 gpuTimingReady_ = false;
1238 if (gpuQueryPool_) device->destroyQueryPool(gpuQueryPool_);
1239 gpuQueryPool_ = nullptr;
1240 }
1241}
1242
1244 if (!gpuTimingReady_ || !presentRecording) return;
1245 const uint32_t slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1246 auto cb = gpuTimingPrefix_[slot];
1247 cb.reset();
1248 cb.begin(vk::CommandBufferBeginInfo{});
1249 cb.resetQueryPool(gpuQueryPool_, slot * 2, 2);
1250 cb.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe, gpuQueryPool_, slot * 2);
1251 cb.end();
1252 gpuTimingPrefixSubmitted_[slot] = false;
1253}
1254
1255void Graphics::submitGpuTimingPrefix() {
1256 if (!gpuTimingReady_ || !presentRecording) return;
1257 const uint32_t slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1258 if (gpuTimingPrefixSubmitted_[slot]) return;
1259 EV_PROFILE_MODULE("graphics", "GpuTiming.SubmitPrefix");
1260 vk::SubmitInfo info{};
1261 info.commandBufferCount = 1;
1262 info.pCommandBuffers = &gpuTimingPrefix_[slot];
1263 const auto result = device.getQueue(vkb::QueueType::graphics).submit(1, &info, vk::Fence{});
1264 if (result != vk::Result::eSuccess) throw Exception("GPU timing prefix submission failed");
1265 gpuTimingPrefixSubmitted_[slot] = true;
1266}
1267
1269 if (!gpuTimingReady_ || !presentRecording) return;
1270 vk::CommandBuffer cb = presentRecording.commandBuffer();
1271 const uint32_t first = uint32_t(currentFrameSlot() % kAsyncResourceCopies) * 2;
1272 cb.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe, gpuQueryPool_, first + 1);
1273}
1274
1276 EV_PROFILE_MODULE("graphics", "GpuTiming.Readback");
1277 if (!gpuTimingReady_ || !gpuQueryPool_) return;
1278 // Called after acquiring this frame slot (its prior fence has completed),
1279 // before resetting its query pair. Never wait for the just-submitted frame
1280 // or race a different in-flight slot's reset. GPU values are delayed.
1281 const uint32_t slot = uint32_t(currentFrameSlot() % kAsyncResourceCopies);
1282 if (!gpuTimingPrefixSubmitted_[slot]) {
1283 gpuFrameMs_ = 0.f;
1284 return;
1285 }
1286 const uint32_t first = slot * 2;
1287 std::array<uint64_t, 4> ts{};
1288 const auto result =
1289 device->getQueryPoolResults(gpuQueryPool_, first, 2, sizeof(ts), ts.data(), 2 * sizeof(uint64_t),
1290 vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWithAvailability);
1291 if (result == vk::Result::eSuccess && ts[1] && ts[3] && ts[2] > ts[0])
1292 gpuFrameMs_ = float(double(ts[2] - ts[0]) * double(timestampPeriod_) / 1'000'000.0);
1293 else
1294 gpuFrameMs_ = 0.f;
1295}
1296
1297bool Graphics::gpuTimingAvailable() const { return gpuTimingReady_ && gpuFrameMs_ > 0.f; }
1298
1299float Graphics::gpuFrameMs() const { return gpuFrameMs_; }
1300
1301} // namespace eve::graphics::vulkan
double m[16]
LogicalId target
float w
Definition AnimClip.cpp:738
Persistent, thread-safe record of engine crash and problem events.
glm::vec4 p[6]
std::string name
Definition ECS.cpp:154
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
glm::vec3 n
Definition Grass.cpp:63
std::int32_t first
std::uint32_t height
std::uint32_t width
std::future< JobOutput > future
Poco::JSON::Object::Ptr result
MeleePoint3 b
Definition MeleeHit.cpp:41
ssq::Object frame
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
std::string build
std::string slot
std::string string
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
int caps
Definition TreeMesh.cpp:164
uint32_t flags
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
void configure(FrameCaptureCapabilities capabilities)
Set backend support at provider initialization.
StartupStage public API.
Canvas public API.
Definition Canvas.h:17
Screen-space buffers for mid/post effects and Hybrid deferred lighting.
Definition GBuffer.h:28
Texture * getDepthTexture() const
Returns the depth texture.
Definition GBuffer.h:51
bool isValid() const
True when valid.
Definition GBuffer.cpp:5
std::vector< std::pair< WindowDestroyedCallback, void * > > windowDestroyedCallbacks_
Definition Graphics.h:2337
std::unique_ptr< AntiAliasing > pipelineAA_
Definition Graphics.h:2346
std::vector< DeferredFileTexture > deferredFileTextures_
Definition Graphics.h:2313
void retireResourceLifetime() const
Retire resource lifetime.
Canvas * sharedFramePostTargets_[2]
Definition Graphics.h:2288
void clearPresentOverlay()
Drop the present overlay callback (window gone; re-register on UI init).
Definition Graphics.h:1649
std::unique_ptr< RenderControl > renderControl_
Definition Graphics.h:2340
bool isActive() const
True when active.
Definition Graphics.h:1616
std::unique_ptr< GlobalIllumination > pipelineGI_
Definition Graphics.h:2344
std::unique_ptr< AmbientOcclusion > pipelineAO_
Definition Graphics.h:2342
FrameCaptureStore & frameCaptures()
Graphics-owned frame capture authority. @thread Engine main thread only. @lifetime Borrowed until Gra...
Definition Graphics.cpp:202
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
void onNativeWindowDestroyed() override
On native window destroyed.
Definition Graphics.cpp:875
void draw(eve::graphics::Graphics *gfx, const glm::mat4 &matrix) const override
Draws .
void present() override
Present.
Texture * getSceneColorTexture() override
Returns the scene color texture.
std::string getBackendName() const override
Returns the backend name.
Definition Graphics.cpp:315
void waitForSharedGpuResources()
Block until all in-flight GPU work (all frames) has completed.
Definition Graphics.cpp:943
bool isCanvasActive() const override
True when canvas active.
void initWithWindow(void *nativeWindow) override
Initializes with window.
Definition Graphics.cpp:793
void writeGpuTimestampEnd()
Writes an end timestamp into the current present command buffer.
void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override
Sets the viewport size.
float gpuFrameMs() const override
Gpu frame ms.
Graphics()
Starts asynchronous VkInstance creation (overlaps later window init).
Definition Graphics.cpp:319
bool gpuTimingAvailable() const override
Gpu timing available.
bool supportsRuntimeGlslCompilation() const override
Supports runtime glsl compilation.
Definition Graphics.cpp:317
Texture * getSceneLinearDepthTexture() override
Returns the scene linear depth texture.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
void readGpuFrameTiming()
Reads a completed reusable slot without blocking; call after acquire and before recording.
void initGpuTiming()
Creates the GPU timestamp query pool; call after device init.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void initHeadless(int width, int height) override
Initializes headless.
Definition Graphics.cpp:726
~Graphics() override
Graphics.
Definition Graphics.cpp:326
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void writeGpuTimestampBegin()
Records a slot-owned prefix timestamp; submitted before deferred or present GPU work.
EVENGINE_API_FOUNDATION void registerVulkanInstanceWarmup(void(*start)())
Register the graphics-backend function that starts VkInstance creation.
constexpr uint32_t kMaxBindlessTextures
Definition GpuDriven.h:19
bool glslRuntimeCompilationAvailable()
Whether this build can compile GLSL text to SPIR-V at runtime.
void detachGraphicsArtifactProvider(Graphics *graphics) noexcept
Detach a Graphics instance before its derived backend is destroyed.
WidgetDesc window(std::string title, std::vector< WidgetDesc > children, std::string id)
Top-level window widget with a title bar.
Definition Widget.cpp:326
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
Definition CrashLog.cpp:70
FrameAttachment
Stable logical render attachments; Depth and Velocity share storage.
Backend support is explicit; candidates need not be produced in every frame.
bool available
Full KHR RT pipeline path usable
bool rayQuery
Optional VK_KHR_ray_query
bool gpuDrivenAvailable() const
Gpu driven available.
Definition GpuDriven.h:41
bool started
Definition Graphics.cpp:200
bool consumed
Definition Graphics.cpp:201
std::mutex mu
Definition Graphics.cpp:198
glm::uvec4 info