载入中...
搜索中...
未找到
Graphics.h
浏览该文件的文档.
1#pragma once
2#include <array>
3#include <atomic>
4#include <cstdint>
5#include <glm/ext/vector_uint4_sized.hpp>
6#include <glm/mat4x4.hpp>
7#include <glm/vec2.hpp>
8#include <glm/vec3.hpp>
9#include <glm/vec4.hpp>
10#include <map>
11#include <memory>
12#include <optional>
13#include <unordered_map>
14#include <vector>
15#include "common/Capability.h"
16#include "common/Export.h"
17#include "common/FrameCapture.h"
18#include "common/GpuTimer.h"
19#include "graphics/Batcher.h"
22#include "graphics/Graphics.h"
25#include "graphics/Light.h"
26#include "graphics/Mesh.h"
27#include "graphics/PbrSurface.h"
31#include "graphics/Shader.h"
32#include "graphics/Shadow.h"
34#include "graphics/Texture.h"
39#include "vkbuilder.hpp"
40#include "vkbuilder/framegraph.hpp"
41
42namespace eve::graphics::vulkan {
43
44class OffscreenCanvas;
45
46#if defined(VKB_ENABLE_VMA)
48class VmaAllocatorOwner {
49public:
51 VmaAllocatorOwner() = default;
53 ~VmaAllocatorOwner();
54 VmaAllocatorOwner(const VmaAllocatorOwner &) = delete;
55 VmaAllocatorOwner &operator=(const VmaAllocatorOwner &) = delete;
56
58 void create(const vkb::Instance &instance, const vkb::PhysicalDevice &physicalDevice,
59 vkb::Device &device);
60
61private:
62 VmaAllocator allocator_ = VK_NULL_HANDLE;
63};
64#endif
65
68 glm::vec2 pos;
69 glm::vec4 color;
70
72 static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding) {
73 vk::VertexInputBindingDescription b{};
74 b.binding = binding;
75 b.stride = sizeof(ColorVertex);
76 b.inputRate = vk::VertexInputRate::eVertex;
77 return b;
78 }
80 static std::vector<vk::VertexInputAttributeDescription> getAttributeDescription(uint32_t binding) {
81 return {
82 {0, binding, vk::Format::eR32G32Sfloat, offsetof(ColorVertex, pos)},
83 {1, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(ColorVertex, color)},
84 };
85 }
86};
87
90 glm::vec4 clipPosition;
91 glm::vec4 color;
92
94 static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding) {
95 return {binding, sizeof(Primitive3DVertex), vk::VertexInputRate::eVertex};
96 }
98 static std::vector<vk::VertexInputAttributeDescription> getAttributeDescription(uint32_t binding) {
99 return {{0, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(Primitive3DVertex, clipPosition)},
100 {1, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(Primitive3DVertex, color)}};
101 }
102};
103
106 glm::vec2 pos;
107 glm::vec4 color;
108 glm::vec2 uv;
109
111 static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding) {
112 vk::VertexInputBindingDescription b{};
113 b.binding = binding;
114 b.stride = sizeof(TexturedVertex);
115 b.inputRate = vk::VertexInputRate::eVertex;
116 return b;
117 }
119 static std::vector<vk::VertexInputAttributeDescription> getAttributeDescription(uint32_t binding) {
120 return {
121 {0, binding, vk::Format::eR32G32Sfloat, offsetof(TexturedVertex, pos)},
122 {1, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(TexturedVertex, color)},
123 {2, binding, vk::Format::eR32G32Sfloat, offsetof(TexturedVertex, uv)},
124 };
125 }
126};
127
130 Texture *texture = nullptr;
131 float x = 0.f;
132 float y = 0.f;
133 float w = 0.f;
134 float h = 0.f;
135 float u0 = 0.f;
136 float v0 = 0.f;
137 float u1 = 1.f;
138 float v1 = 1.f;
139 Color tint{1.f, 1.f, 1.f, 1.f};
140 float clipX = 0.f;
141 float clipY = 0.f;
142 float clipW = 0.f;
143 float clipH = 0.f;
144 bool opaque = false;
145};
146
149 glm::vec3 pos;
150 glm::vec3 normal;
151 glm::vec2 uv;
152 glm::u16vec4 joints{0};
153 glm::vec4 weights{0.f};
154 glm::vec4 color{1.f};
155 // Optional imported tangent basis; w=0 explicitly denotes an absent stream.
156 glm::vec4 tangent{0.f};
157
159 static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding) {
160 vk::VertexInputBindingDescription b{};
161 b.binding = binding;
162 b.stride = sizeof(MeshVertex);
163 b.inputRate = vk::VertexInputRate::eVertex;
164 return b;
165 }
167 static std::vector<vk::VertexInputAttributeDescription> getAttributeDescription(uint32_t binding) {
168 return {
169 {0, binding, vk::Format::eR32G32B32Sfloat, offsetof(MeshVertex, pos)},
170 {1, binding, vk::Format::eR32G32B32Sfloat, offsetof(MeshVertex, normal)},
171 {2, binding, vk::Format::eR32G32Sfloat, offsetof(MeshVertex, uv)},
172 {3, binding, vk::Format::eR16G16B16A16Uint, offsetof(MeshVertex, joints)},
173 {4, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(MeshVertex, weights)},
174 {5, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(MeshVertex, color)},
175 {6, binding, vk::Format::eR32G32B32A32Sfloat, offsetof(MeshVertex, tangent)},
176 };
177 }
178};
179
181struct Mesh3DUBO {
182 // Layout prefix matches legacy custom Mesh3D shaders (toon etc.).
183 glm::mat4 mvp{1.f};
184 glm::mat4 model{1.f};
185 glm::vec4 lightDir{0.4f, 1.f, 0.3f, 0.f}; // xyz = primary dir; w = lightCount
186 glm::vec4 lightColor{1.f, 1.f, 1.f, 0.f}; // rgb = primary color; w = envIntensity (IBL)
187 glm::vec4 tint{1.f, 1.f, 1.f, 1.f};
188 glm::vec4 cameraPos{0.f, 0.f, 3.f, 0.45f}; // xyz = eye; w = roughness
189 glm::vec4 ambient{0.12f, 0.12f, 0.14f, 0.f}; // rgb = ambient; w = metallic
191 // Appended: custom shaders that only read the prefix stay valid (buffer may be larger).
192 glm::vec4 texBomb{4.f, 0.f, 1.f, 0.f}; // x=cellScale, y=strength (0=off), z=rotAmount
193 glm::vec4 parallax{0.f, 8.f, 32.f, 0.f}; // x=scale (0=off), y=minLayers, z=maxLayers
194 glm::mat4 view{1.f}; // camera view (CSM / view-space depth)
195 glm::vec4 clipInfo{0.1f, 100.f, 0.f, 0.f}; // x=near, y=far (linear depth in scene color A)
196 // Dynamic cloud shadows on ground. cloud.x=strength (0=off), y=world cell size,
197 // z=time, w=unused; cloudWind.xy=wind velocity (world/s), z=coverage, w=detail.
198 glm::vec4 cloud{0.f, 1.5f, 0.f, 0.f};
199 glm::vec4 cloudWind{4.f, 0.f, 0.55f, 0.5f};
200 glm::vec4 virtualTexture{0.f}; // enabled, pageCountX, pageCountY, border/extent
201 glm::vec4 virtualAtlas{0.f}; // slotsX, slotsY
202 // GPU-driven only: x = bindless env cubemap slot, y = envIntensity.
203 // Appended after the legacy prefix so legacy shaders are unaffected.
204 glm::vec4 bindlessEnv{0.f, 0.f, 0.f, 0.f};
205 glm::vec4 envProbeCenter{0.f};
206 glm::vec4 envProbeExtent{0.f};
207 glm::vec4 skinInfo{0.f};
210 glm::vec4 diffuseProbeSh[9]{};
211 glm::vec4 diffuseProbeInfo{0.f}; // x = enabled
215 glm::vec4 diffuseVolumeInfo{0.f}; // x = probe count
216 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f}; // coverage, complementary pattern, enabled
217};
218
221 glm::mat4 mvp{1.f};
222 glm::mat4 model{1.f};
223 glm::vec4 clip{0.f};
224 glm::vec4 skinInfo{0.f};
225};
226static_assert(sizeof(SkinPassUBO) == 160, "SkinPassUBO must match std140 shaders");
227
230 glm::mat4 invViewProj{1.f};
231 glm::mat4 view{1.f};
232 glm::vec4 lightDir{0.4f, 1.f, 0.3f, 0.f};
233 glm::vec4 lightColor{1.f, 1.f, 1.f, 0.f};
234 glm::vec4 cameraPos{0.f, 0.f, 3.f, 0.f};
235 glm::vec4 ambient{0.12f, 0.12f, 0.14f, 0.f};
236 glm::vec4 gridInfo{16.f, 9.f, 24.f, 0.f};
237 glm::vec4 clipInfo{0.1f, 100.f, 1.f, 1.f};
238};
239static_assert(sizeof(DeferredLightingUBO) == 224, "DeferredLightingUBO must match std140 shader");
240
243 glm::mat4 mvp{1.f};
244 glm::mat4 model{1.f};
245 glm::mat4 view{1.f};
246 glm::vec4 lightDir{0.4f, 1.f, 0.3f, 0.f};
247 glm::vec4 lightColor{1.f, 1.f, 1.f, 0.f}; // rgb = primary; w = envIntensity
248 glm::vec4 tint{1.f, 1.f, 1.f, 1.f};
249 glm::vec4 cameraPos{0.f, 0.f, 3.f, 0.45f};
250 glm::vec4 ambient{0.12f, 0.12f, 0.14f, 0.f};
251 glm::vec4 gridInfo{16.f, 9.f, 24.f, 0.f};
252 glm::vec4 clipInfo{0.1f, 100.f, 1.f, 1.f};
253 glm::vec4 texBomb{4.f, 0.f, 1.f, 0.f}; // x=cellScale, y=strength (0=off), z=rotAmount
254 glm::vec4 parallax{0.f, 8.f, 32.f, 0.f}; // x=scale (0=off), y=minLayers, z=maxLayers
255 glm::vec4 virtualTexture{0.f};
256 glm::vec4 virtualAtlas{0.f};
257 glm::vec4 envProbeCenter{0.f};
258 glm::vec4 envProbeExtent{0.f};
261};
262
265 vkb::TextureImage2D image;
266 vkb::GenericImage arrayImage;
267 vkb::GenericImage cubeImage;
269 vkb::CubemapRenderTarget hdrCube;
270 bool isCube = false;
271 bool isArray = false;
272 bool isVolume = false;
273 bool isHDR = false;
274 vk::Sampler sampler;
275 bool sharedSampler = false;
276 vkb::BoundSet descriptorSet;
277 vk::ImageView viewOverride{};
278 int width = 0;
279 int height = 0;
280 uint32_t mipLevels = 1;
283 uint64_t contentIdentity = 0;
287
289 vk::ImageView imageView() const {
290 if (viewOverride) return viewOverride;
291 if (isHDR && hdrCube.valid()) return hdrCube.cubeView();
292 if (isArray || isVolume) return arrayImage.imageView();
293 return isCube ? cubeImage.imageView() : image.imageView();
294 }
295};
296
298struct GpuMesh {
303 static constexpr size_t kDynamicVertexCopies = 3;
304 vkb::HostVertexBuffer vertices;
305 vkb::GenericBuffer indices;
306 std::array<vkb::HostVertexBuffer, kDynamicVertexCopies> dynVertices;
307 std::array<vkb::GenericBuffer, kDynamicVertexCopies> dynIndices;
310 std::vector<uint32_t> cpuIndices;
311 std::vector<MeshVertex> updateVertices;
313 uint64_t dynamicWriteCount = 0;
314 bool dynamic = false;
315 // Borrowed only while drawMeshResidentVertices records one draw.
317 vk::DeviceSize residentVertexOffset = 0;
318 uint32_t vertexCount = 0;
319 uint32_t indexCount = 0;
320 vk::IndexType indexType = vk::IndexType::eUint32;
325};
326
331 void operator()(MeshShaderResources *resources) const noexcept;
332};
333
335struct GpuShader {
336 vk::Pipeline swapchainPipeline;
337 vk::Pipeline offscreenPipeline;
342 vk::Pipeline mesh3dPipeline;
343 vk::Pipeline mesh3dXrayPipeline;
346 vk::PipelineLayout pipelineLayout;
347 vk::DescriptorSet resourceSet;
348 // Borrowed from resources; identical compact frame ABI for all resource programs.
349 vk::DescriptorSetLayout resourceFrameLayout;
350 std::unique_ptr<MeshShaderResources, MeshShaderResourcesDeleter> resources;
351 bool isMesh3D = false;
352 bool isHair3D = false;
353 Shader *owner = nullptr;
354};
355
361public:
362 // Keep the base draw(Drawable*, mat4) overload visible alongside the
363 // canvas composite overloads below.
365
367 Graphics();
369 ~Graphics() override;
370
371 // ---- GPU frame timing (eve::service::IGpuTimer) ----------------------
373 void initGpuTiming();
375 void writeGpuTimestampBegin();
377 void writeGpuTimestampEnd();
379 void readGpuFrameTiming();
380
382 bool gpuTimingAvailable() const override;
384 float gpuFrameMs() const override;
385
387 std::string getBackendName() const override;
389 bool supportsRuntimeGlslCompilation() const override;
390
392 void initWithWindow(void *nativeWindow) override;
394 void initHeadless(int width, int height) override;
396 bool isHeadless() const override { return headless_; }
398 void present() override;
400 void requestSurfaceRecreate() override { surfaceNeedsRecreate = true; }
402 void onNativeWindowDestroyed() override;
404 void setScreenReadbackEnabled(bool enabled) override {
408 ensurePresentCaptureHook();
409 }
411 void setVSync(bool enabled) override {
412 if (vsyncEnabled == enabled) return;
416 markSwapchainDirty();
417 }
419 void setMsaaSamples(int samples) override {
420 const int raw = samples > 1 ? samples : 0;
421 if (raw == msaaSamples) return;
424 }
426 int getMsaaSamples() const override { return msaaSamples; }
428 void setViewportSize(int width, int height, int pixelwidth, int pixelheight) override;
429
430 // ---- GPU-driven rendering (stage 0: bindless + resource tables) ----
431
433 const GpuDrivenCaps &gpuDrivenCaps() const { return gpuDrivenCaps_; }
434
436 const RayTracingCaps& rayTracingCapsRef() const { return rayTracingCaps_; }
438 RayTracingCaps rayTracingCaps() const override { return rayTracingCaps_; }
440 bool supportsRayTracing() const override { return rayTracingCaps_.rayTracingAvailable(); }
441
443 FrameArena &currentFrameArena();
444
446 uint32_t materialTableGetOrCreate(eve::graphics::Material *material);
447
449 void syncMaterialTable();
450
452 uint32_t bindlessSlot2D(const GpuTexture *tex) const {
453 return tex ? tex->bindlessIndex2D : kInvalidBindlessSlot;
454 }
456 uint32_t bindlessSlotCube(const GpuTexture *tex) const {
457 return tex ? tex->bindlessIndexCube : kInvalidBindlessSlot;
458 }
460 bool supportsGpuDriven3D() const override {
461 return gpuDrivenCaps_.gpuDrivenAvailable();
462 }
464 bool supportsDeferredLighting() const override { return true; }
466 void drawDeferredLighting() override;
468 bool gpuDrivenEnabled() const override {
469 return gpuDrivenEnabled_ && gpuDrivenCaps_.gpuDrivenAvailable();
470 }
472 void gpuDrivenSetEnabled(bool enabled) override { gpuDrivenEnabled_ = enabled; }
474 uint32_t gpuDrivenMeshRecord(Mesh *mesh) override;
478 return materialTableGetOrCreate(material);
479 }
481 bool gpuDrivenMaterialUsable(Material *material) override;
483 [[nodiscard]] Result<void> gpuDrivenReleaseMaterialRecord(Material *material) override;
485 uint32_t gpuDrivenReflectionProbeSlot(Texture *cubemap) override;
488 bool gpuDrivenSubmitOpaque(const GpuInstance *instances, uint32_t instanceCount) override;
490 GpuResidentSubmitStatus gpuDrivenSubmitResident(const GpuResidentInstanceBatch &batch) override;
493 Texture *getSceneLinearDepthTexture() override;
494
496 [[nodiscard]] IGpuParticles* gpuParticles() noexcept override { return this; }
497 [[nodiscard]] IVisibilityCapture* visibilityCapture() noexcept override { return this; }
499 bool supportsGpuParticles() const override { return initialized && !headless_; }
501 bool canSubmitGpuParticles() const override;
503 GpuParticleHandle createGpuParticleEmitter(std::uint32_t capacity) override;
505 void releaseGpuParticleEmitter(GpuParticleHandle handle) override;
507 void resetGpuParticleEmitter(GpuParticleHandle handle) override;
510 bool updateGpuParticleEmitter(GpuParticleHandle handle, const GpuParticleUpdate &update,
511 const GpuParticleSpawn *spawns,
512 std::uint32_t spawnCount) override;
515 bool drawGpuParticleEmitter(GpuParticleHandle handle,
516 const GpuParticleDraw &draw) override;
518 GpuParticleStats getGpuParticleStats(GpuParticleHandle handle) const override;
520 uint32_t debugBindlessIndex(Texture *tex) const;
522 uint32_t debugMeshRecordIndex(Mesh *mesh) const;
524 uint32_t debugLastGpuDrivenDrawCount() const { return lastGpuDrivenDrawCount_; }
526 void waitForSharedGpuResources();
528 bool gpuDrivenCullEnabled() const {
529 return gpuDrivenEnabled_ && gpuDrivenCaps_.gpuDrivenCullAvailable();
530 }
532 bool gpuDrivenScenePassPending() const { return gpuDrivenScenePassPending_; }
534 bool gpuDrivenCullBegin(const GpuInstance *instances, uint32_t instanceCount);
536 void gpuDrivenCullEmit(const glm::mat4 &viewProj, const glm::vec3 &eye, float fovYDeg,
537 float nearZ, float farZ);
539 void gpuDrivenOpenScenePass();
541 void gpuDrivenDrawOpaque();
543 bool gpuDrivenResolveWanted() const override;
545 void gpuDrivenRecordVisPass() override;
547 void gpuDrivenResolve() override;
549 uint32_t gpuDrivenVgUpload(const GpuVgAssetUpload &asset) override;
551 uint32_t gpuDrivenVgAssetId(Mesh *mesh) const override;
553 bool gpuDrivenVgAttachToMesh(Mesh *mesh, uint32_t vgAssetId) override;
555 bool gpuDrivenVgSetInstance(uint32_t vgAssetId, const glm::mat4 &model,
556 uint32_t materialId) override;
558 void gpuDrivenVgComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye,
559 float fovYDeg, float nearZ, float farZ) override;
561 uint32_t debugGpuDrivenVgVisibleCount() const;
563 uint32_t debugGpuDrivenVisibleCount() const;
565 uint32_t debugGpuDrivenCulledDrawCount() const;
566
568 void drawSolidRect(float x, float y, float w, float h, const Color &color,
569 BlendMode blend = BlendMode::Alpha) override;
571 void drawPrimitiveCanvas(const PrimitiveCanvas2D &canvas) override;
573 void drawSolidRectRotated(float cx, float cy, float w, float h, float degrees,
574 const Color &color,
575 BlendMode blend = BlendMode::Alpha) override;
577 void pushValidationScope() override {}
579 void popValidationScope() override {}
581 Texture *newTexture(int width, int height, const uint8_t *rgba, bool repeatU = false,
582 bool repeatV = false) override;
584 Texture *newTexture(int width, int height, const uint8_t *rgba,
585 const TextureCreateInfo &info) override;
587 [[nodiscard]] Result<Texture *> newTextureMipChain(uint32_t width, uint32_t height, uint32_t levels,
588 std::span<const uint8_t> rgba) override;
590 [[nodiscard]] Result<Texture *> newTextureArrayRgba16f(uint32_t width, uint32_t height, uint32_t layers,
591 std::span<const uint16_t> rgbaHalf) override;
593 [[nodiscard]] Result<Texture *> newTexture3DRgba8(uint32_t width, uint32_t height, uint32_t depth,
594 std::span<const uint8_t> rgba) override;
596 Texture *newCubemap(int faceSize, const uint8_t *rgbaFaces) override;
598 Texture *newCubemap(int faceSize, const uint8_t *rgbaFaces,
599 const TextureCreateInfo &info) override;
602 Texture *newHDRCubemap(int faceSize) override;
605 bool copyHDRCanvasToCubemapFace(Canvas *source, Texture *cubemap, int face) override;
607 bool copyHDRCanvasesToCubemap(Canvas *const *sources, int faceCount,
608 Texture *cubemap) override;
611 bool filterHDRReflectionCubemap(Texture *cubemap, int sampleCount = 64) override;
613 Texture *newTexture(image::ImageData *data) override;
615 Texture *newTexture(image::ImageData *data, const TextureCreateInfo &info) override;
617 [[nodiscard]] ResultRef<Texture> newSharedTexture(image::ImageData *data, const std::string &contentKey) override;
619 void setTextureSampler(Texture *texture, const TextureSampler &sampler) override;
621 float getMaxAnisotropy() const override;
624 bool reloadTextureFromFile(const std::string &filename) override;
626 bool uploadDeferredFileTexture(Texture *texture, image::ImageData *data) override;
628 bool releaseTexture(Texture *texture) override;
630 bool updateTexture(Texture *texture, int width, int height,
631 const uint8_t *rgba) override;
633 eve::Result<void> updateTextureFromResidentRgba8(Texture* texture, const GpuResidentBufferView& source, int width,
634 int height) override;
636 eve::Result<void> updateTextureRegion(Texture *texture, int x, int y, int width,
637 int height, std::span<const std::uint8_t> rgba,
638 std::size_t bytesPerRow = 0) override;
640 eve::Result<void> updateTextureRegions(
641 Texture *texture, std::span<const TextureRegionUpload> regions) override;
643 bool replaceTexturePixels(Texture *tex, image::ImageData *data);
645 bool replaceTexturePixelsRGBA(Texture *tex, int w, int h, const uint8_t *rgba);
647 void drawTexturedRect(Texture *texture, float x, float y, float w, float h, const Color &color) override;
649 void drawTexturedRectShader(Texture *texture, Shader *shader, float x, float y, float w, float h,
650 const Color &color) override;
652 void drawTexturedRectUV(Texture *texture, float x, float y, float w, float h, float u0, float v0,
653 float u1, float v1, const Color &color) override;
655 void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w,
656 float h, float u0, float v0, float u1, float v1,
657 const Color &color, bool rotatedUV = false,
658 BlendMode blend = BlendMode::Alpha) override;
660 void drawTexturedRectShaderUVRotated(Texture *texture, Shader *shader, float cx, float cy,
661 float w, float h, float degrees, float u0, float v0,
662 float u1, float v1, const Color &color,
663 bool rotatedUV = false,
664 BlendMode blend = BlendMode::Alpha) override;
666 void drawTexturedRectShaderDepth(Texture *color, Texture *depth, Shader *shader, float x, float y,
667 float w, float h, const Color &tint) override;
669 void drawTexturedRectShaderDepthMotion(Texture *color, Texture *depth, Texture *motion,
670 Shader *shader, float x, float y, float w, float h,
671 const Color &tint) override;
673 void drawTexturedRectShader4(Texture *color, Texture *depth, Texture *motion, Texture *extra,
674 Shader *shader, float x, float y, float w, float h,
675 const Color &tint) override;
677 void drawTexturedRectShader5(Texture *color, Texture *depth, Texture *motion, Texture *extra,
678 Texture *specular, Shader *shader, float x, float y, float w,
679 float h, const Color &tint) override;
681 SceneColorDistortionStatus drawSceneColorDistortionUVRotated(
682 Texture *displacement, float cx, float cy, float w, float h, float degrees, float u0,
683 float v0, float u1, float v1, float strengthPixels, float opacity,
684 bool rotatedUV = false) override;
686 void drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0, float v0,
687 float u1, float v1, const Color &color, BlendMode blend = BlendMode::Alpha) override;
689 void drawTexturedRectLitUVRotated(Texture *albedo, Texture *normal, float cx, float cy, float w, float h,
690 float degrees, float u0, float v0, float u1, float v1, const Color &color,
691 BlendMode blend = BlendMode::Alpha) override;
693 void setLighting2D(const Lighting2DUBO &ubo) override;
695 Shader *newShaderFromSpv(const std::vector<uint32_t> &vertSpv,
696 const std::vector<uint32_t> &fragSpv) override;
698 Shader *newShaderFromSpvFile(const std::string &vertPath, const std::string &fragPath) override;
700 Shader *newShader(const std::string &vertGlsl, const std::string &fragGlsl) override;
702 Shader *newMeshShaderFromSpv(const std::vector<uint32_t> &vertSpv,
703 const std::vector<uint32_t> &fragSpv) override;
705 Shader *newMeshShaderFromWgsl(const std::string &vertWgsl,
706 const std::string &fragWgsl) override;
708 Shader *newShaderFromWgsl(const std::string &vertWgsl,
709 const std::string &fragWgsl) override;
711 [[nodiscard]] Result<void> replaceShaderFromSpv(
712 Shader &shader, const std::vector<uint32_t> &vertSpv,
713 const std::vector<uint32_t> &fragSpv) override;
715 [[nodiscard]] Result<void> replaceMeshShaderResources(Shader &shader, const std::vector<uint32_t> &vertSpv,
716 const std::vector<uint32_t> &fragSpv,
717 const ShaderResourceInputs &resources) override;
719 [[nodiscard]] Result<void> replaceShaderFromWgsl(
720 Shader &shader, const std::string &vertWgsl,
721 const std::string &fragWgsl) override;
723 [[nodiscard]] Result<void> replaceShaderFromGlsl(
724 Shader &shader, const std::string &vertGlsl,
725 const std::string &fragGlsl) override;
727 Shader *newMeshShader(const std::string &vertGlsl, const std::string &fragGlsl) override;
729 Shader *newHairShaderFromSpv(const std::vector<uint32_t> &vertSpv,
730 const std::vector<uint32_t> &fragSpv) override;
732 Shader *newHairShaderFromWgsl(const std::string &vertWgsl,
733 const std::string &fragWgsl) override;
735 bool releaseShader(Shader *shader) override;
737 eve::Result<void> configureMeshShaderSurface(Shader &shader, BlendMode blend, bool depthWrite,
738 bool doubleSided) override;
740 eve::Result<void> configureMeshShaderRaster(Shader &shader, const MeshShaderRasterState &state) override;
742 Mesh *newMeshFromAssimp(const ::aiMesh &mesh) override;
744 Mesh* newMeshFromAssimp(const ::aiMesh& mesh, const glm::mat4& worldTransform) override;
746 Mesh *newMeshFromArrays(const float *posXYZ, const float *nrmXYZ, const float *uvST,
747 int vertexCount, const uint32_t *indices, int indexCount) override;
755 Mesh *newMeshFromArraysColored(const float *posXYZ, const float *nrmXYZ, const float *uvST,
756 const float *colorRGBA, int vertexCount,
757 const uint32_t *indices, int indexCount) override;
759 [[nodiscard]] eve::Result<eve::graphics::MeshBackendDescriptor> describeMesh(Mesh* mesh) const override;
767 [[nodiscard]] eve::Result<uint64_t> textureContentIdentity(const Texture *texture) const;
768 bool bakeMeshMorph(Mesh *mesh) override;
770 bool updateMeshVertices(Mesh *mesh, const float *posXYZ, const float *nrmXYZ, const float *uvST,
771 int vertexCount, const uint32_t *indices, int indexCount) override;
773 bool setMeshSkinningData(Mesh *mesh, const uint16_t *joints4, const float *weights4,
774 int vertexCount) override;
776 Mesh *newMeshSphere(int slices = 32, int stacks = 16) override;
778 Mesh *newMeshCylinder(int slices = 32, int stacks = 1, bool caps = true) override;
780 bool releaseMesh(Mesh *mesh) override;
782 [[nodiscard]] Result<void> drawMeshResidentVertices(Mesh &mesh, const GpuResidentBufferView &source) override;
784 void begin3DFrame() override;
786 void begin3DFrameToCanvas(Canvas *canvas) override;
788 void end3DFrameToCanvas() override;
790 void drawPrimitiveScene(const PrimitiveSceneCanvas3D &canvas) override;
792 float getLastOffscreen3DGpuDurationMs() const override {
793 return lastOffscreen3DGpuDurationMs;
794 }
796 void setMesh3DViewProj(const glm::mat4 &viewProj) override;
798 void setMesh3DView(const glm::mat4 &view) override;
800 void setMesh3DClip(float nearZ, float farZ) override;
802 Texture *getSceneColorTexture() override;
808 image::ImageData* renderEntityIdMask(const std::vector<EntityIdDraw>& draws, const glm::mat4& viewProj, int width,
809 int height) override;
811 [[nodiscard]] Result<VisibilityPixels> captureVisibilityPixels(const std::vector<EntityIdDraw> &draws,
812 const glm::mat4 &viewProj, int width,
813 int height) override;
815 image::ImageData *readGBufferToImageData(const std::string &name) override;
817 image::ImageData *readDecalLayerToImageData(const std::string &attachment) override;
819 void drawMesh(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint) override;
821 void drawMeshShader(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint,
822 Shader *shader) override;
824 [[nodiscard]] bool supportsMeshInstancing() const override { return initialized; }
826 [[nodiscard]] Result<void> drawMeshInstances(Mesh &mesh, std::span<const glm::mat4> models,
827 OptionalRef<Texture> texture, const Color &tint) override;
828
830 [[nodiscard]] Result<void> drawMeshShaderInstances(Mesh &mesh, Shader &shader, const glm::mat4 &model,
831 const Color &tint, std::uint32_t first,
832 std::uint32_t count) override;
834 void drawVoxelFaceInstances(const uint32_t *packed, int count, float originX, float originY, float originZ,
835 const std::string &faceDir, Texture *atlas, int tilesPerRow = 16,
836 const uint32_t *ao = nullptr) override;
838 void setMesh3DNormalTexture(Texture *normal) override;
840 void setMesh3DPackedNormalMask(bool enabled) override;
842 void setMesh3DHeightTexture(Texture *height) override;
844 void setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY,
845 int atlasSlotsX, int atlasSlotsY,
846 float borderFraction) override;
848 void setMesh3DSceneDepth(Texture *depth) override;
850 void setMesh3DSceneColor(Texture *color) override;
852 [[nodiscard]] Mesh3DSceneColorCaptureStatus captureMesh3DSceneColor() override;
854 void setMesh3DMaterial(float metallic, float roughness) override;
856 [[nodiscard]] Result<void> setMesh3DPbrSurface(const PbrSurface* surface) override;
858 void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite,
859 bool doubleSided, float alphaCutoff,
860 const std::string &alphaTechnique = "cutoff") override;
862 void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount = 1.f) override;
864 void setMesh3DParallax(float scale, float minLayers = 8.f, float maxLayers = 32.f) override;
866 void setMesh3DLodDither(float weight, bool reverse, bool enabled) override;
868 void setMesh3DLighting(const Lighting3DPack &pack) override;
870 void setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle, float coverage,
871 float detail) override;
873 void setMesh3DClusteredLighting(const ClusteredLightingUpload &upload) override;
875 void setMesh3DClusteredActive(bool active) override;
877 void setMesh3DSSAO(float intensity) override { (void)intensity; }
879 void setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) override;
881 void setMesh3DCameraPos(const glm::vec3 &eye) override;
883 void setMesh3DEnv(Texture *cube, float intensity) override;
885 void setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent) override;
887 void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload) override;
889 [[nodiscard]] Result<void> setSceneToneMapping(SceneToneMapping mode) override;
891 SceneToneMapping getSceneToneMapping() const override { return sceneToneMapping_; }
893 [[nodiscard]] Result<void> setDisplayOutputMode(DisplayOutputMode mode) override;
895 [[nodiscard]] Result<void> setDisplayHdrCalibration(float paperWhiteNits, float peakNits) override;
897 [[nodiscard]] Result<DisplayOutputSupport> queryDisplayOutputSupport() const override;
899 [[nodiscard]] Result<void> setScenePhotographicVignette(float intensity) override;
901 float getScenePhotographicVignette() const override { return scenePhotographicVignette_; }
903 void setSceneExposure(float exposure) override { sceneExposure = std::max(exposure, 0.f); }
905 float getSceneExposure() const override { return sceneExposure; }
907 void setSceneColorFilter(const RgbF& color) override {
908 sceneColorFilter = glm::max(glm::vec3(color.r, color.g, color.b), glm::vec3(0.f));
909 }
911 RgbF getSceneColorFilter() const override { return {sceneColorFilter.r, sceneColorFilter.g, sceneColorFilter.b}; }
913 void setSceneLiftGammaGain(const RgbF& lift, const RgbF& inverseGamma, const RgbF& gain) override {
914 sceneLift = glm::vec3(lift.r, lift.g, lift.b);
915 sceneInverseGamma = glm::max(glm::vec3(inverseGamma.r, inverseGamma.g, inverseGamma.b), glm::vec3(0.001F));
916 sceneGain = glm::vec3(gain.r, gain.g, gain.b);
917 }
919 RgbF getSceneLift() const override { return {sceneLift.r, sceneLift.g, sceneLift.b}; }
921 RgbF getSceneInverseGamma() const override {
922 return {sceneInverseGamma.r, sceneInverseGamma.g, sceneInverseGamma.b};
923 }
925 RgbF getSceneGain() const override { return {sceneGain.r, sceneGain.g, sceneGain.b}; }
927 void setSceneTransitionFx(float vignette, float vignetteSmoothness,
928 float lensDistortion, float lensScale) override {
929 sceneTransitionVignette = std::clamp(vignette, 0.0F, 1.0F);
930 sceneTransitionVignetteSmoothness = std::clamp(vignetteSmoothness, 0.01F, 1.0F);
931 sceneTransitionLensDistortion = std::clamp(lensDistortion, 0.0F, 1.0F);
932 sceneTransitionLensScale = std::clamp(lensScale, 0.01F, 5.0F);
933 }
935 float getSceneTransitionVignette() const override { return sceneTransitionVignette; }
937 float getSceneTransitionVignetteSmoothness() const override { return sceneTransitionVignetteSmoothness; }
939 float getSceneTransitionLensDistortion() const override { return sceneTransitionLensDistortion; }
941 float getSceneTransitionLensScale() const override { return sceneTransitionLensScale; }
943 void setSceneAutoExposure(bool enabled, float minEV, float maxEV) override {
944 sceneAutoExposure = enabled;
945 sceneAutoExposureMinEV = minEV;
946 sceneAutoExposureMaxEV = maxEV;
947 }
949 bool getSceneAutoExposure() const override { return sceneAutoExposure; }
951 float getSceneAutoExposureMinEV() const override { return sceneAutoExposureMinEV; }
953 float getSceneAutoExposureMaxEV() const override { return sceneAutoExposureMaxEV; }
955 void setSceneBloom(float intensity, float threshold) override {
956 sceneBloomIntensity = intensity;
957 sceneBloomThreshold = threshold;
958 }
960 float getSceneBloomIntensity() const override { return sceneBloomIntensity; }
962 float getSceneBloomThreshold() const override { return sceneBloomThreshold; }
964 void setSceneDepthOfField(float focusDistance, float maxBlurPx, float focusRange, float nearZ,
965 float farZ) override {
966 sceneDofFocusDistance = focusDistance;
967 sceneDofMaxBlurPx = maxBlurPx;
968 sceneDofFocusRange = focusRange;
969 sceneDofNearZ = nearZ;
970 sceneDofFarZ = farZ;
971 }
973 float getSceneDofFocusDistance() const override { return sceneDofFocusDistance; }
975 float getSceneDofMaxBlur() const override { return sceneDofMaxBlurPx; }
977 float getSceneDofFocusRange() const override { return sceneDofFocusRange; }
979 float getSceneDofNearZ() const override { return sceneDofNearZ; }
981 float getSceneDofFarZ() const override { return sceneDofFarZ; }
983 void setMesh3DShadows(const ShadowUpload &upload) override;
985 void setMesh3DShadowReceive(bool receive) override;
987 void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count) override;
989 void beginShadowPass(int cascadeIndex) override;
991 void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided = true) override;
993 void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo = nullptr,
994 bool doubleSided = true, float lodWeight = 1.f,
995 bool lodFadeReverse = false, bool lodDither = false) override;
997 void endShadowPass() override;
998
1000 void beginGBufferPass(int width, int height) override;
1002 void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
1003 Texture *albedo = nullptr, float tintR = 1.f, float tintG = 1.f, float tintB = 1.f,
1004 float motionX = 0.f, float motionY = 0.f, float roughness = 0.45f, float metallic = 0.f,
1005 float tintA = 1.f) override;
1007 void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
1008 Texture *albedo = nullptr, float tintR = 1.f, float tintG = 1.f, float tintB = 1.f,
1009 float motionX = 0.f, float motionY = 0.f, float roughness = 0.45f, float metallic = 0.f,
1010 float tintA = 1.f) override;
1012 void endGBufferPass() override;
1013
1015 bool supportsDecal() const override { return true; }
1017 void beginDecalPass(int width, int height) override;
1019 void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) override;
1021 void drawDecal(const glm::mat4 &model, Texture *albedo, Texture *normal, Texture *params,
1022 const float uvRect[4], float fade, float normalStrength, float roughnessStrength,
1023 float metalStrength, float emissiveStrength, int blendMode = 0,
1024 int projectionMode = 0, float blendSharpness = 4.f,
1025 float parallaxScale = 0.f, float parallaxMinLayers = 8.f,
1026 float parallaxMaxLayers = 24.f, float edgeFadeWidth = 0.06f) override;
1028 void endDecalPass() override;
1029
1031 Canvas *newCanvas(int width, int height) override;
1034 Canvas *newHDRCanvas(int width, int height) override;
1036 void setCanvas(Canvas *canvas) override;
1038 bool isCanvasActive() const override;
1040 Canvas *getCanvas() const override;
1041
1043 Texture *getTexture() override;
1045 image::ImageData *newImageData() override;
1046
1048 void draw(eve::graphics::Graphics* gfx, const glm::mat4& matrix) const override;
1050 void draw(Canvas* C, const glm::mat4& matrix) const override;
1052 void clear(std::optional<Color> color, std::optional<int> stencil, std::optional<double> depth) override;
1054 Color getPixel(int x, int y) override;
1055
1057 vkb::Device &getDevice() { return device; }
1059 vk::CommandPool getUploadPool() const { return uploadPool; }
1065 bool canRecordPostSceneGpuWork() const { return bool(presentRecording) && !sceneColorPassOpen; }
1067 bool hasOpenPresentFrame() const { return bool(presentRecording); }
1069 vk::PresentModeKHR currentPresentMode() const { return swapchain.present_mode; }
1071 void beginPathSceneOutput();
1073 void resolvePathSceneOutput(Texture *texture);
1075 void retirePathSceneOutput();
1080 uint64_t recordingPresentSequence() const { return presentRecording ? presentSequence_ : 0; }
1085 uint64_t submittedPresentSequence() const { return submittedPresentSequence_; }
1090 vk::CommandBuffer& postSceneCommandBuffer() { return currentPresentCb(); }
1092 vk::DescriptorSetLayout getTexSetLayout() const { return texSetLayout; }
1094 vk::DescriptorPool getDescriptorPool() const { return descriptorPool; }
1096 const vkb::BuiltRenderPass &getOffscreenRenderPass(bool hdr = false) const {
1097 return hdr ? hdrOffscreenRenderPass : offscreenRenderPass;
1098 }
1100 const vkb::BuiltRenderPass &getOffscreen3DRenderPass(bool hdr = false) {
1101 return hdr ? hdrOffscreen3DRenderPass : offscreen3DRenderPass;
1102 }
1104 vk::Format getDepthFormat() const { return depthFormat; }
1106 vk::RenderPass getSwapchainRenderPass() const { return renderpass; }
1108 vk::RenderPass getUiMsaaRenderPass() const { return uiRenderPass; }
1110 vk::SampleCountFlagBits getUiMsaaSamples() const { return uiColorSamples; }
1114 createUiColorResources(int(swapchain.extent.width), int(swapchain.extent.height));
1115 }
1128 void drawUiTextureRects(void* commandBuffer, const std::vector<UiTextureDraw>& draws, std::size_t bufferOffset = 0);
1130 vkb::Instance &getInstance() { return inst; }
1132 vkb::Swapchain &getSwapchain() { return swapchain; }
1134 void *getSdlWindow() const { return sdlWindow; }
1136 uint32_t getSwapchainImageCount() const { return swapchain.image_count; }
1137
1138 friend class OffscreenCanvas;
1139
1141 struct LitBatch {
1142 Texture *albedo = nullptr;
1143 Texture *normal = nullptr;
1144 BlendMode blend = BlendMode::Alpha;
1146 };
1147
1148private:
1149 void drawMeshShaderRange(Mesh *mesh, const glm::mat4 &model, Texture *texture, const Color &tint, Shader *shader,
1150 std::uint32_t first, std::uint32_t count, std::span<const glm::mat4> models);
1151 struct GpuParticleDrawRequest;
1152 struct GpuParticleResource;
1153
1154 struct Mesh3dFrameSlots;
1155 struct Mesh3dClusteredFrameSlots;
1156 struct DecalSlot;
1157 struct DecalSetKey;
1158 struct DecalSetKeyHash;
1159 struct GBufferSlot;
1160 void createSwapchainAndPipeline();
1161 void applyPreferredSwapchainFormats(vkb::SwapchainBuilder &builder);
1162 void applyPendingResourceChanges() override;
1163 [[nodiscard]] ResultRef<Texture> requestFileTexture(const std::string &filename) override;
1164 bool samplerChangesPending_ = false;
1165 struct CachedSampler {
1167 uint32_t mipLevels;
1168 vk::UniqueSampler sampler;
1169 };
1170 std::vector<CachedSampler> cachedSamplers_;
1171 void createTexturedPipeline();
1172 void createLit2DPipeline();
1173 void createGpuParticlePipelines();
1174 void destroyGpuParticleResources();
1175 void recordGpuParticleCompute(vk::CommandBuffer cb);
1176 void drawGpuParticleRequest(vk::CommandBuffer cb, const GpuParticleDrawRequest& request);
1177 struct PbrResources;
1178 static void deletePbrResources(PbrResources* resources);
1179 std::unique_ptr<PbrResources, void (*)(PbrResources*)> pbrResources_{nullptr, &deletePbrResources};
1180 std::optional<PbrSurface> pbrSurface_;
1181 void destroyPbrResources();
1182 void destroyPbrGBufferResources();
1183 struct GBufferDraw;
1184 void drawPbrMesh(Mesh *mesh, const glm::mat4 &model, const Color &tint, GBufferDraw *gbuffer = nullptr);
1185 void createMesh3DPipeline();
1186 void createMesh3DClusteredPipeline();
1187 void createDeferredLightingPipeline();
1188 void destroyDeferredLightingResources();
1189 void createVoxelRectPipeline();
1190 vk::Pipeline buildVoxelRectPipeline(const vkb::BuiltRenderPass &rp,
1191 vk::SampleCountFlagBits samples);
1192 void destroyVoxelRectResources();
1193 void ensureVoxelUnitQuad();
1194 vkb::BoundSet voxelRectSetFor(GpuTexture *gpuTex);
1195 void createShadowResources();
1196 void destroyShadowResources();
1197 void createGBufferResources(int width, int height);
1198 void destroyGBufferResources();
1199 void createDecalResources(int width, int height);
1200 void destroyDecalResources();
1201 void recordDecalPass();
1202 void recordDecalPassInto(vk::CommandBuffer cb, DecalSlot &slot, GBufferSlot &gslot);
1203 void ensureDecalUnitBox();
1204 void ensureDecalPlaceholders();
1205 vkb::BoundSet decalSetFor(DecalSlot &slot, GpuTexture *albedo, GpuTexture *normal,
1206 GpuTexture *params, GpuTexture *depth, GpuTexture *gbNormal);
1207 DecalSlot *currentDecalSlot();
1208 void createSceneColorResources(int width, int height);
1209 void destroySceneColorResources();
1210 void createUiColorResources(int width, int height);
1211 void destroyUiColorTargets();
1212 void destroyUiColorResources();
1213 void queueUiResolve();
1215 bool renderUiOverlayPass();
1217 void recordDeferredFrameGraph();
1218 void dropPendingOffscreenPasses();
1220 bool beginSwapchainRenderPass();
1222 void beginSwapchainColorPass();
1223 bool beginSceneColorRenderPass();
1224 void endSceneColorRenderPass();
1225 void ensureOffscreen3DResources();
1226 void destroyOffscreen3DResources();
1227 void queueSceneColorResolve();
1228 void materializeSceneColorResolve();
1229 void ensureClusteredBuffers(size_t lightsBytes, size_t tableBytes, size_t indicesBytes);
1230 void uploadClusteredLighting(const ClusteredLightingUpload &upload);
1231 void ensureMesh3dStrides();
1232 void ensureMesh3dRing(Mesh3dFrameSlots &fslots);
1233 size_t uploadSkinPalette(Mesh* mesh, Mesh3dFrameSlots& fslots);
1234 vk::DescriptorSet skinPassSetFor(GpuTexture *albedo, Mesh3dFrameSlots &fslots);
1235 bool prepareSkinPass(Mesh *mesh, Texture *albedo, const glm::mat4 &mvp,
1236 const glm::mat4 &model, const glm::vec4 &clip,
1237 vk::DescriptorSet &set, uint32_t &uboOffset);
1238 void ensureMesh3dClusteredRing(Mesh3dClusteredFrameSlots &fslots);
1239 vkb::BoundSet mesh3dClusteredSetFor(GpuTexture *gpuTex, GpuTexture *normalTex,
1240 GpuTexture *envTex, GpuTexture *heightTex,
1241 GpuTexture *decalAlbedo, GpuTexture *decalNormal,
1242 GpuTexture *decalParams,
1243 Mesh3dClusteredFrameSlots &fslots);
1244 void ensureOffscreenPipelines();
1245 void ensureHdrOffscreenPipelines();
1246 void ensureShaderOffscreenPipeline(Shader *shader);
1247 void ensureShaderHdrOffscreenPipeline(Shader *shader);
1249 void destroyPresentGraphicsPipelines();
1251 void rebuildGpuParticleDrawPipelines(const vkb::BuiltRenderPass &target);
1253 void ensureHdrGpuParticleDrawPipelines();
1255 void ensurePresentComposeResources(int width, int height);
1256 void destroyPresentComposeResources();
1257 struct PresentComposeSlot;
1265 PresentComposeSlot *currentPresentComposeSlot();
1267 bool beginPresentComposePass();
1268 void endPresentComposePass();
1270 void encodePresentComposeToSwapchain(vk::CommandBuffer cb);
1271 vk::Pipeline createTexturedStylePipeline(const std::vector<uint32_t> &vert, const std::vector<uint32_t> &frag,
1272 const vkb::BuiltRenderPass &rp, vk::PipelineLayout layout,
1273 BlendMode mode = BlendMode::Alpha,
1274 vk::SampleCountFlagBits samples = vk::SampleCountFlagBits::e1);
1275 vk::Pipeline createMesh3DStylePipeline(const std::vector<uint32_t> &vert, const std::vector<uint32_t> &frag,
1276 vk::PipelineLayout layout, const vkb::BuiltRenderPass &rp,
1277 vk::SampleCountFlagBits samples, BlendMode blend = BlendMode::Opaque,
1278 bool depthWrite = true, bool doubleSided = true,
1279 const MeshShaderRasterState &raster = {});
1280 eve::Result<void> rebuildMeshShaderSurface(Shader &shader, BlendMode blend, bool depthWrite, bool doubleSided,
1281 const MeshShaderRasterState &raster);
1282 static constexpr size_t kMesh3DPipelineVariants = 20;
1283 static size_t mesh3dPipelineIndex(BlendMode blend, bool depthWrite, bool doubleSided);
1284 static constexpr size_t kPrimitive3DPipelineVariants = 45;
1285 static size_t primitive3DPipelineIndex(PrimitiveDepthMode depth, BlendMode blend, PrimitiveCullMode cull);
1287 vk::Pipeline createMesh3DXrayPipeline(const std::vector<uint32_t> &vert,
1288 const std::vector<uint32_t> &frag,
1289 vk::PipelineLayout layout,
1290 const vkb::BuiltRenderPass &rp,
1291 vk::SampleCountFlagBits samples);
1292 vk::Pipeline createMesh3DHairPipeline(const std::vector<uint32_t> &vert,
1293 const std::vector<uint32_t> &frag,
1294 vk::PipelineLayout layout,
1295 const vkb::BuiltRenderPass &rp,
1296 vk::SampleCountFlagBits samples);
1298 void ensureScenePassPipelines(const vkb::BuiltRenderPass &target,
1299 vk::SampleCountFlagBits samples);
1300 void rebuildPrimitive3DPipelines(const vkb::BuiltRenderPass &target, vk::SampleCountFlagBits samples);
1301 void buildPrimitive3DPipelines(const vkb::BuiltRenderPass &target, vk::SampleCountFlagBits samples,
1302 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> &pipelines);
1304 int clampMsaaSamples(int requested) const;
1306 const vkb::BuiltRenderPass &activeScenePass() const {
1307 return sceneColorRenderPass ? sceneColorRenderPass : renderpass;
1308 }
1310 vk::SampleCountFlagBits activeSceneSamples() const {
1311 return sceneColorRenderPass ? sceneColorSamples : vk::SampleCountFlagBits::e1;
1312 }
1313 void destroySwapchainResources();
1314 void flushBatch();
1315 void flushToSwapchain();
1316 void flushToOffscreen(OffscreenCanvas *canvas);
1317 void abortOpen3DFrame();
1318 void noteSolidOverlay(uint32_t batchIndex);
1319 void noteTexturedOverlay(Texture *tex, uint32_t batchIndex);
1320 void noteLitOverlay(uint32_t batchIndex);
1321 void clear2DBatches();
1322 void drawLitBatches(vk::CommandBuffer cb, int viewW, int viewH, std::vector<LitBatch> &batches,
1323 std::vector<vkb::HostVertexBuffer> &texBufs, size_t &texBufIndex, bool offscreen,
1324 bool hdr = false);
1325 vkb::BoundSet lit2dSetFor(GpuTexture *albedo, GpuTexture *normal, bool offscreen);
1326 vkb::BoundSet post2SetFor(GpuTexture *color, GpuTexture *depth,
1327 GpuTexture *motion = nullptr, GpuTexture *extra = nullptr,
1328 GpuTexture *specular = nullptr);
1329 void ensureFlatNormalTexture();
1331 void ensureReadbackSlots();
1333 bool recordSwapchainReadback(vk::CommandBuffer cb);
1335 void syncReadbackCpu();
1337 void destroyReadbackResources();
1338 void ensurePresentCaptureHook();
1339 vkb::BoundSet mesh3dSetFor(GpuTexture *gpuTex, GpuTexture *normalTex, GpuTexture *envTex, GpuTexture *heightTex,
1340 GpuTexture *depthTex, GpuTexture *sceneColorTex, GpuTexture *decalAlbedo,
1341 GpuTexture *decalNormal, GpuTexture *decalParams, Mesh3dFrameSlots &fslots,
1342 vk::DescriptorSetLayout resourceLayout);
1343 void ensureDefaultEnvCubemap();
1344 void ensureFlatNormalTexture3D();
1345 void ensureFlatHeightTexture3D();
1346 vk::Sampler createVkSampler(const TextureSampler &sampler, uint32_t mipLevels) const;
1347 void writeCombinedImageDescriptor(GpuTexture *gpu);
1354 void createInstanceAndDevice(const std::vector<const char *> &instanceExtensions,
1355 void *nativeWindow, vk::SurfaceKHR *surfaceOut);
1357 bool rebuildSwapchainIfNeeded();
1359 bool beginPresentCommandBuffer();
1360
1361 bool initialized = false;
1362 bool headless_ = false;
1363 bool hasPresentedFrame = false;
1364 float maxSamplerAnisotropy = 1.f;
1365 std::vector<uint8_t> lastFrameRgba;
1366 struct CaptureCopy {
1367 eve::FrameCaptureBuffer metadata;
1368 vkb::GenericBuffer staging;
1369 vk::Image source;
1370 vk::ImageLayout layout{};
1371 vk::ImageAspectFlags aspect{};
1372 uint32_t layer = 0;
1373 size_t storageIndex = 0;
1374 };
1375 std::vector<CaptureCopy> captureCopies_;
1376 eve::FrameCaptureSnapshot captureSnapshot_;
1377 std::string captureToken_;
1378 vk::Fence captureFence_;
1379 uint64_t captureFrameId_ = 0;
1380 uint64_t captureTargetGeneration_ = 1;
1381 bool captureSubmitted_ = false;
1382 void recordFrameCapture(vk::CommandBuffer cb);
1383 void markFrameCaptureSubmitted();
1384 void pollFrameCapture();
1385 void destroyFrameCapture();
1386 // Persistent host-visible staging buffers for swapchain readback. The copy
1387 // is recorded into the present command buffer (no extra submit / no
1388 // per-frame GPU wait), and each present frame slot owns one slot so a
1389 // staging buffer is only reused after that slot's fence has signaled.
1390 struct ScreenReadbackSlot {
1391 vkb::GenericBuffer staging;
1392 void *mapped = nullptr;
1393 };
1394 std::vector<ScreenReadbackSlot> screenReadbackSlots;
1395 size_t screenReadbackBytes = 0;
1396 size_t readbackWriteSlot = 0;
1397 bool readbackReady = false; // at least one copy submitted
1398 bool readbackCpuSynced = false; // newest copy already converted to lastFrameRgba
1399 bool readbackBgra = false; // swapchain format of the newest captured frame
1400 Canvas *activeCanvas = nullptr;
1401 bool swapchainDirty = false;
1402 void markSwapchainDirty() override { swapchainDirty = true; }
1403 // Set from the SDL event-watch thread on Android foreground; consumed on
1404 // the render thread inside flushToSwapchain().
1405 std::atomic<bool> surfaceNeedsRecreate{false};
1406 void recreateSurfaceForResume();
1407 // False while the native window is mid-(re)creation / rotation (Android),
1408 // when touching the swapchain or presenting would crash the GPU driver.
1409 bool isRenderSurfaceReady() const;
1410 // Returns true only once the drawable size has been non-zero and identical
1411 // across consecutive frames, i.e. the surface has settled after a
1412 // rotation/resume and is safe to (re)build a swapchain against.
1413 bool isRenderSurfaceStable();
1414 int pendingSurfaceW = 0;
1415 int pendingSurfaceH = 0;
1416 int surfaceStableFrames = 0;
1417 void *sdlWindow = nullptr;
1418 vk::SurfaceKHR surface;
1419
1420 vkb::Instance inst;
1421#if defined(VKB_ENABLE_VMA)
1422 // Declared before Device and all GPU resources so reverse member
1423 // destruction keeps the allocator alive until every buffer is gone.
1424 VmaAllocatorOwner vmaAllocatorOwner_;
1425#endif
1426 vkb::Device device;
1427 vkb::Swapchain swapchain;
1428 vkb::BuiltRenderPass renderpass;
1429
1430 vk::Pipeline pipeline;
1431 vk::PipelineLayout pipelineLayout;
1432 vk::Pipeline solidAlphaPipeline; // alpha-blended solid (BlendMode::Alpha)
1433 vk::Pipeline additiveSolidPipeline; // additive solid (BlendMode::Additive)
1434 vk::Pipeline premultipliedSolidPipeline;
1435 vk::Pipeline multiplySolidPipeline;
1436
1437 vk::DescriptorSetLayout texSetLayout;
1438 vk::UniqueDescriptorSetLayout texSetLayoutUnique;
1439 vk::DescriptorPool descriptorPool;
1440 vk::Pipeline texPipeline;
1441 vk::Pipeline additiveTexPipeline;
1442 vk::Pipeline premultipliedTexPipeline;
1443 vk::Pipeline multiplyTexPipeline;
1444 vk::Pipeline opaqueTexPipeline;
1445 vk::Pipeline particleDistortionPipeline;
1446 vk::Pipeline sceneTonemapPipeline;
1448 vk::Format presentAttachmentFormat_ = vk::Format::eUndefined;
1449 SceneToneMapping sceneToneMapping_ = SceneToneMapping::Aces;
1450 vk::SurfaceFormatKHR selectedSurfaceFormat_{vk::Format::eB8G8R8A8Unorm,
1451 vk::ColorSpaceKHR::eSrgbNonlinear};
1452 float sceneExposure = 1.f;
1453 glm::vec3 sceneColorFilter{1.f};
1454 glm::vec3 sceneLift{0.f};
1455 glm::vec3 sceneInverseGamma{1.f};
1456 glm::vec3 sceneGain{1.f};
1457 float scenePhotographicVignette_ = 0.0F;
1458 float sceneTransitionVignette = 0.0F;
1459 float sceneTransitionVignetteSmoothness = 0.2F;
1460 float sceneTransitionLensDistortion = 0.0F;
1461 float sceneTransitionLensScale = 1.0F;
1462 bool sceneAutoExposure = false;
1463 float sceneAutoExposureMinEV = -8.f;
1464 float sceneAutoExposureMaxEV = 8.f;
1465 float sceneBloomIntensity = 0.f;
1466 float sceneBloomThreshold = 1.f;
1467 float sceneDofFocusDistance = 0.f;
1468 float sceneDofMaxBlurPx = 0.f;
1469 float sceneDofFocusRange = 8.f;
1470 float sceneDofNearZ = 0.1f;
1471 float sceneDofFarZ = 100.f;
1472 vk::PipelineLayout texPipelineLayout;
1473 vk::PipelineLayout shaderPipelineLayout; // tex set + push constants
1474 vk::CommandPool uploadPool;
1475
1476 vkb::BuiltRenderPass offscreenRenderPass;
1477 vkb::BuiltRenderPass hdrOffscreenRenderPass;
1478 vk::Pipeline offscreenSolidPipeline;
1479 vk::Pipeline offscreenSolidAlphaPipeline;
1480 vk::Pipeline offscreenAdditiveSolidPipeline;
1481 vk::Pipeline offscreenPremultipliedSolidPipeline;
1482 vk::Pipeline offscreenMultiplySolidPipeline;
1483 vk::Pipeline offscreenTexPipeline;
1484 vk::Pipeline offscreenAdditiveTexPipeline;
1485 vk::Pipeline offscreenPremultipliedTexPipeline;
1486 vk::Pipeline offscreenMultiplyTexPipeline;
1487 vk::Pipeline offscreenOpaqueTexPipeline;
1488 vk::Pipeline hdrOffscreenTexPipeline;
1489 vk::Pipeline hdrOffscreenOpaqueTexPipeline;
1490 vk::Pipeline hdrOffscreenAdditiveTexPipeline;
1491 vk::Pipeline hdrOffscreenPremultipliedTexPipeline;
1492 vk::Pipeline hdrOffscreenMultiplyTexPipeline;
1493 vk::Pipeline hdrOffscreenSolidPipeline;
1494 vk::Pipeline hdrOffscreenSolidAlphaPipeline;
1495 vk::Pipeline hdrOffscreenAdditiveSolidPipeline;
1496 vk::Pipeline hdrOffscreenPremultipliedSolidPipeline;
1497 vk::Pipeline hdrOffscreenMultiplySolidPipeline;
1498 vk::Pipeline hdrOffscreenLitPipeline;
1499 vk::Pipeline hdrOffscreenLitAdditivePipeline;
1500 vk::Pipeline hdrOffscreenLitPremultipliedPipeline;
1501 vk::Pipeline hdrOffscreenLitMultiplyPipeline;
1502 vk::Pipeline hdrOffscreenLitOpaquePipeline;
1503 vk::Pipeline hdrOffscreenTonemapPipeline;
1504 vk::Pipeline hdrOffscreenParticleDistortionPipeline;
1505 vk::Pipeline hdrGpuParticleAlphaPipeline_{};
1506 vk::Pipeline hdrGpuParticleAdditivePipeline_{};
1507 vk::Pipeline hdrGpuParticlePremultipliedPipeline_{};
1508 vk::Pipeline hdrGpuParticleMultiplyPipeline_{};
1509 vk::Pipeline hdrGpuParticleOpaquePipeline_{};
1510 bool presentComposeActive_ = false;
1511
1512 vk::DescriptorSetLayout mesh3dSetLayout;
1513 vk::UniqueDescriptorSetLayout mesh3dSetLayoutUnique;
1514 vk::PipelineLayout mesh3dPipelineLayout;
1515 vk::PipelineLayout mesh3dShaderPipelineLayout; // + push constants for custom mesh shaders
1516 vk::Pipeline mesh3dPipeline;
1517 vk::Pipeline mesh3dTransparentPipeline;
1518 std::array<vk::Pipeline, kMesh3DPipelineVariants> mesh3dSurfacePipelines{};
1519 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> primitive3DPipelines{};
1520 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> offscreenPrimitive3DPipelines{};
1521 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> hdrOffscreenPrimitive3DPipelines{};
1522 std::vector<vkb::HostVertexBuffer> offscreenPrimitive3DBufs;
1523 std::size_t offscreenPrimitive3DDrawIndex = 0;
1524 // One UBO (+ per-texture descriptor sets) per draw in the current 3D frame.
1525 // Avoids vkUpdateDescriptorSets on a set already bound in a recording /
1526 // executable command buffer (which invalidates the CB).
1527 struct Mesh3dSetKey {
1528 GpuTexture *albedo = nullptr;
1529 GpuTexture *normal = nullptr;
1530 GpuTexture *env = nullptr;
1531 GpuTexture *reflectionProbe0 = nullptr;
1532 GpuTexture *reflectionProbe1 = nullptr;
1533 GpuTexture *height = nullptr;
1534 GpuTexture *depth = nullptr;
1535 GpuTexture *sceneColor = nullptr;
1536 GpuTexture *decalAlbedo = nullptr;
1537 GpuTexture *decalNormal = nullptr;
1538 GpuTexture *decalParams = nullptr;
1539 size_t paletteSlot = 0;
1540 bool resourceProgram = false;
1542 bool operator==(const Mesh3dSetKey &o) const {
1543 return albedo == o.albedo && normal == o.normal && env == o.env && reflectionProbe0 == o.reflectionProbe0 &&
1544 reflectionProbe1 == o.reflectionProbe1 && height == o.height && depth == o.depth &&
1545 sceneColor == o.sceneColor && decalAlbedo == o.decalAlbedo && decalNormal == o.decalNormal &&
1546 decalParams == o.decalParams && paletteSlot == o.paletteSlot && resourceProgram == o.resourceProgram;
1547 }
1548 };
1549 struct Mesh3dSetKeyHash {
1551 size_t operator()(const Mesh3dSetKey &k) const {
1552 return std::hash<GpuTexture *>()(k.albedo) ^ (std::hash<GpuTexture *>()(k.normal) << 1) ^
1553 (std::hash<GpuTexture *>()(k.env) << 2) ^ (std::hash<GpuTexture *>()(k.height) << 3) ^
1554 (std::hash<GpuTexture *>()(k.reflectionProbe0) << 8) ^
1555 (std::hash<GpuTexture *>()(k.reflectionProbe1) << 9) ^ (std::hash<GpuTexture *>()(k.depth) << 4) ^
1556 (std::hash<GpuTexture *>()(k.sceneColor) << 10) ^ (std::hash<GpuTexture *>()(k.decalAlbedo) << 5) ^
1557 (std::hash<GpuTexture *>()(k.decalNormal) << 6) ^ (std::hash<GpuTexture *>()(k.decalParams) << 7) ^
1558 k.paletteSlot ^ (size_t(k.resourceProgram) << 11);
1559 }
1560 };
1561 // Per-frame-slot UBO rings, keyed by Present::frames_in_flight so a frame
1562 // never overwrites a UBO that an in-flight frame is still reading.
1563 // Per-draw data is written at dynamic offsets into the ring and the same
1564 // descriptor set (cached per texture combination) is re-bound with a new
1565 // offset, so descriptor-pool usage is bounded by texture count instead of
1566 // growing with draw count.
1567 struct Mesh3dFrameSlots {
1568 vkb::GenericBuffer uboRing; // capacity * mesh3dUboStride bytes
1569 vkb::GenericBuffer shadowRing; // capacity * shadowUboStride bytes
1570 size_t capacity = 0; // per-draw slot count the rings hold
1571 size_t drawIndex = 0;
1572 size_t lastDrawCount = 0;
1573 std::unordered_map<Mesh3dSetKey, vkb::BoundSet, Mesh3dSetKeyHash> sets;
1574 std::map<std::pair<size_t, GpuTexture*>, vkb::BoundSet> skinSets;
1575 std::vector<vkb::GenericBuffer> palettes;
1576 size_t activePalette = 0;
1577 };
1578 std::vector<Mesh3dFrameSlots> mesh3dFrameSlots;
1579 Texture *whiteTexture = nullptr;
1580 Texture *defaultExtrasArray = nullptr;
1581 Texture *defaultColorsArray = nullptr;
1582 Texture *defaultVertexArray = nullptr;
1583 Texture *defaultMotionArray = nullptr;
1584 Texture *defaultVegetationFadeNoise = nullptr;
1586 Texture *defaultBindlessCube = nullptr;
1587 Texture *flatNormalTexture3D = nullptr;
1588 Texture *flatHeightTexture3D = nullptr;
1589 Texture *defaultEnvCubemap = nullptr;
1590 Texture *mesh3dNormalTexture = nullptr;
1591 Texture *mesh3dHeightTexture = nullptr;
1592 Texture *mesh3dEnvTexture = nullptr;
1593 Texture *mesh3dSceneDepthTexture = nullptr;
1594 Texture *mesh3dSceneColorTexture = nullptr;
1595 float mesh3dEnvIntensity = 0.f;
1596 glm::vec3 mesh3dEnvProbeCenter{0.f};
1597 glm::vec3 mesh3dEnvProbeExtent{0.f};
1598 ReflectionProbeUpload mesh3dReflectionProbes{};
1599 float mesh3dMetallic = 0.f;
1600 float mesh3dRoughness = 0.45f;
1601 SurfaceMode mesh3dSurfaceMode = SurfaceMode::Opaque;
1602 BlendMode mesh3dSurfaceBlend = BlendMode::Alpha;
1603 bool mesh3dSurfaceDepthWrite = false;
1604 bool mesh3dSurfaceDoubleSided = false;
1605 float mesh3dAlphaCutoff = 0.5f;
1606 std::string mesh3dAlphaTechnique = "cutoff";
1607 glm::vec4 mesh3dLodFade{1.f, 0.f, 0.f, 0.f};
1608 float mesh3dTexBombScale = 4.f;
1609 float mesh3dTexBombStrength = 0.f;
1610 float mesh3dTexBombRot = 1.f;
1611 float mesh3dParallaxScale = 0.f;
1612 float mesh3dParallaxMinLayers = 8.f;
1613 float mesh3dParallaxMaxLayers = 32.f;
1614 glm::vec4 mesh3dVirtualTexture{0.f};
1615 glm::vec4 mesh3dVirtualAtlas{0.f};
1616 Lighting3DPack mesh3dLighting{};
1617 ShadowUpload mesh3dShadows{};
1618 bool mesh3dShadowReceive = true;
1619 int mesh3dSkinInfluenceLimit = 4;
1620
1621 // Clustered forward (separate set layout / pipeline; default PBR only).
1622 bool mesh3dClusteredActive = false;
1623 ClusteredLightingUpload mesh3dClustered{};
1624 vk::DescriptorSetLayout mesh3dClusteredSetLayout;
1625 vk::UniqueDescriptorSetLayout mesh3dClusteredSetLayoutUnique;
1626 vk::PipelineLayout mesh3dClusteredPipelineLayout;
1627 vk::Pipeline mesh3dClusteredPipeline;
1628 // Per-frame clustered storage (lights / cluster table / light indices),
1629 // multi-buffered so an in-flight frame's forward pass never reads storage
1630 // that the next frame is overwriting.
1631 struct ClusteredStorage {
1632 vkb::GenericBuffer lightsBuf;
1633 vkb::GenericBuffer tableBuf;
1634 vkb::GenericBuffer indicesBuf;
1635 size_t lightsCap = 0;
1636 size_t tableCap = 0;
1637 size_t indicesCap = 0;
1638 };
1639 std::vector<ClusteredStorage> clusteredStorages; // per swapchain frame slot
1640 struct Mesh3dClusteredFrameSlots {
1641 vkb::GenericBuffer uboRing; // capacity * mesh3dClusteredUboStride bytes
1642 vkb::GenericBuffer shadowRing; // capacity * shadowUboStride bytes
1643 size_t capacity = 0;
1644 size_t drawIndex = 0;
1645 size_t lastDrawCount = 0;
1646 std::unordered_map<Mesh3dSetKey, vkb::BoundSet, Mesh3dSetKeyHash> sets;
1647 };
1648 std::vector<Mesh3dClusteredFrameSlots> mesh3dClusteredFrameSlots;
1649
1651 uint32_t mesh3dUboStride = 0;
1652 uint32_t shadowUboStride = 0;
1653 uint32_t mesh3dClusteredUboStride = 0;
1655 vk::Pipeline lastMesh3dPipeline = nullptr;
1656 vk::Pipeline lastMesh3dClusteredPipeline = nullptr;
1657
1658 // Ping-pong copies so frame N+1 can write while frame N still samples.
1659 static constexpr uint32_t kAsyncResourceCopies = 2;
1660
1661 // ---- GPU-driven (stage 0): bindless set + per-frame arena + tables ----
1662 GpuDrivenCaps gpuDrivenCaps_{};
1663 RayTracingCaps rayTracingCaps_{};
1664 std::vector<FrameArena> frameArenas_;
1665
1666 vk::UniqueDescriptorSetLayout bindlessSetLayoutUnique_{};
1667 vk::DescriptorSetLayout bindlessSetLayout_ = nullptr;
1668 vk::DescriptorPool bindlessPool_ = nullptr;
1669 // One bindless set per frame-in-flight slot. A frame rewrites only the set
1670 // belonging to its own slot, and only AFTER acquireForFrame() has waited
1671 // that slot's fence; pending command buffers therefore never observe a
1672 // descriptor set being rewritten (VUID-vkUpdateDescriptorSets-None-03047).
1673 // The texture arrays (bindings 0/1) are mirrored into every set at
1674 // registration time so any slot can sample any registered texture.
1675 std::vector<vk::DescriptorSet> bindlessSets_;
1676 std::vector<GpuTexture *> bindlessTextures2D_;
1677 std::vector<uint32_t> bindlessFree2D_;
1678 std::vector<GpuTexture *> bindlessCubemaps_;
1679 std::vector<uint32_t> bindlessFreeCube_;
1680
1681 vkb::GenericBuffer meshTableBuffer_;
1682 std::vector<GpuMeshRecord> meshTableRecords_;
1684 std::vector<GpuMesh *> meshRecordOwners_;
1685 uint32_t meshTableCapacity_ = 0;
1686
1687 vkb::GenericBuffer materialTableBuffer_;
1688 std::vector<GpuMaterialRecord> materialTableRecords_;
1689 std::vector<uint32_t> materialTableFree_;
1690 std::unordered_map<const Material *, uint32_t> materialTableIndex_;
1691 uint32_t materialTableCapacity_ = 0;
1692
1693 uint32_t registerBindlessTexture2D(GpuTexture *tex);
1694 uint32_t registerBindlessTextureCube(GpuTexture *tex);
1695 void unregisterBindlessTexture(GpuTexture *tex);
1696 uint32_t registerMeshRecord(GpuMesh *gpu, const std::vector<MeshVertex> *vertices = nullptr,
1697 const std::vector<uint32_t> *indices = nullptr);
1698 void syncMeshTable();
1699 GpuMaterialRecord buildMaterialRecord(Material *material);
1700 void createBindlessSet();
1702 vk::DescriptorSet bindlessSetForFrame() const;
1703
1704 // ---- GPU-driven (stage 3): pooled vertices + visibility buffer ----
1706 struct GpuVertexPool {
1707 vkb::GenericBuffer positions; // vec4 per vertex (16B; w unused)
1708 vkb::GenericBuffer normals; // vec4 per vertex
1709 vkb::GenericBuffer uvs; // vec2 per vertex (8B)
1710 vkb::GenericBuffer indices; // uint32 (u16 meshes converted)
1711 uint32_t vertexCount = 0;
1712 uint32_t indexCount = 0;
1713 };
1714 GpuVertexPool gpuVertexPool_;
1715 void ensureGpuVertexPool();
1716 void growGpuVertexPool(uint32_t needVertices, uint32_t needIndices);
1718 void bindGpuVertexPoolBindless();
1719 void appendGpuMeshToPool(GpuMesh &gpu, const std::vector<MeshVertex> *vertices = nullptr,
1720 const std::vector<uint32_t> *indices = nullptr);
1721
1722 // ---- GPU-driven (stage 3): virtual geometry ----
1723 static constexpr uint32_t kMaxVgAssets = 64;
1724 static constexpr uint32_t kMaxVgClusters = 65536;
1725 struct VgGpuBuffers {
1726 vkb::GenericBuffer positions; // float xyz stream (growable)
1727 vkb::GenericBuffer triangles; // u32 global triangle stream
1728 vkb::GenericBuffer clusters; // GpuVgCluster (4 x uvec4)
1729 vkb::GenericBuffer clusterAssets; // u32 per cluster -> asset id
1730 vkb::GenericBuffer visible; // kAsyncResourceCopies x (counter + ids)
1731 vkb::GenericBuffer indirect; // kAsyncResourceCopies x VkDrawIndirectCommand
1732 vkb::GenericBuffer assetMaterials; // kAsyncResourceCopies x u32 per asset
1733 vkb::GenericBuffer assetModels; // kAsyncResourceCopies x mat4 per asset
1734 };
1735 VgGpuBuffers vgGpu_;
1736 uint32_t vgClusterCount_ = 0; // total clusters across uploaded assets
1737 uint32_t vgAssetCount_ = 0;
1738 uint32_t vgVertexCount_ = 0; // global position-stream vertices
1739 uint32_t vgTriangleCount_ = 0; // global triangle-stream indices
1740 uint32_t vgLastVisible_ = 0;
1741 bool vgAnyThisFrame_ = false;
1742 ComputePass vgCullPass_;
1743 vk::Pipeline gbufferVgVisPipeline = nullptr;
1744 void ensureVgBuffers();
1745 void growVgBuffers(uint32_t needClusters, uint32_t needVertices, uint32_t needTriangles);
1747 void bindVgPoolBindless();
1749 void bindVgFrameBindless(vk::DescriptorSet bindless, size_t slot);
1751 void recordVgCull();
1753 void drawVgClusters(vk::CommandBuffer cb);
1754
1755 // ---- GPU-driven (stage 1): opaque forward path ----
1756 bool gpuDrivenEnabled_ = false;
1757 uint32_t lastGpuDrivenDrawCount_ = 0;
1758 vk::PipelineLayout mesh3dGpuDrivenPipelineLayout = nullptr;
1759 vk::Pipeline mesh3dGpuDrivenPipeline = nullptr;
1760 vk::Pipeline resolveVisPipeline = nullptr;
1761 // Phase C: Hybrid clustered deferred lighting (fullscreen into scene color).
1762 vk::DescriptorSetLayout deferredLightingSetLayout{};
1763 vk::UniqueDescriptorSetLayout deferredLightingSetLayoutUnique;
1764 vk::PipelineLayout deferredLightingPipelineLayout{};
1765 vk::Pipeline deferredLightingPipeline{};
1766 // Reused only after the present model has waited for this frame slot.
1767 // Graphics owns buffers; descriptor sets belong to descriptorPool.
1768 struct DeferredLightingFrame {
1769 vkb::GenericBuffer ubo;
1770 vk::DescriptorSet set{};
1771 };
1772 std::vector<DeferredLightingFrame> deferredLightingFrames;
1773 vk::Sampler deferredLightingSampler{};
1774 void createMesh3DGpuDrivenPipeline();
1776 struct GpuDrivenFrameSet0 {
1777 vk::DescriptorSet set;
1778 uint32_t uboOffset = 0;
1779 uint32_t shadowOffset = 0;
1780 };
1781 GpuDrivenFrameSet0 gpuDrivenFrameSet0();
1782 void createResolveVisPipeline(const vkb::BuiltRenderPass &rp,
1783 vk::SampleCountFlagBits samples);
1785 void initGpuDrivenResources();
1787 void createGpuDrivenVisResources(int width, int height);
1788
1789 // ---- GPU-driven (stage 2): HZB + GPU cull ----
1790 struct GpuDrivenCullSlot {
1791 vkb::GenericBuffer visibleFlags; // uint32 per instance (GPU-written)
1792 vkb::GenericBuffer compacted; // GpuInstance per instance (GPU-written)
1793 vkb::GenericBuffer indirect; // GpuIndirectCommand per bucket (GPU-written)
1794 vkb::GenericBuffer indirectNI; // VkDrawIndirectCommand per bucket (non-indexed)
1795 vkb::GenericBuffer bucketCounters; // uint32 per bucket (GPU atomic, CPU-reset)
1796 vkb::GenericBuffer hzb; // header + R32F mip chain (GPU-written)
1797 vkb::GenericBuffer cullParams; // GpuCullParams UBO (CPU-written)
1798 };
1799 std::vector<GpuDrivenCullSlot> gpuDrivenCullSlots_;
1800 vkb::GenericBuffer gpuDrivenCullParamsPlaceholder_; // valid UBO target at set creation
1801 int gpuDrivenCullWidth = 0;
1802 int gpuDrivenCullHeight = 0;
1803 uint32_t gpuDrivenCullMaxMip = 0;
1804 vk::PipelineLayout gpuDrivenComputeLayout = nullptr;
1805 vk::DescriptorSetLayout gpuDrivenComputeEmptyLayout_ = nullptr;
1806 ComputePass hzbBuildPass_;
1807 ComputePass cullPass_;
1808 ComputePass emitPass_;
1809 bool gpuDrivenCullReady_ = false;
1810 bool gpuDrivenScenePassPending_ = false;
1811 // Per-frame CPU metadata for the cull chain (uploaded to the frame arena).
1812 std::vector<uint32_t> gpuDrivenBucketIds_;
1813 std::vector<uint32_t> gpuDrivenBucketOffsets_;
1814 std::vector<uint32_t> gpuDrivenBucketMeshIds_;
1815 uint32_t gpuDrivenBucketCount_ = 0;
1816 uint32_t gpuDrivenCullInstanceCount_ = 0;
1817 uint32_t gpuDrivenLastCullSlot_ = 0;
1818 FrameArena::Alloc gpuDrivenInstAlloc_{};
1819 FrameArena::Alloc gpuDrivenBucketIdAlloc_{};
1820 FrameArena::Alloc gpuDrivenBucketOffAlloc_{};
1821 void ensureGpuDrivenCullResources(int width, int height);
1822 void recordGpuDrivenHzbBuild();
1823 void gpuDrivenRecordComputeSection(const glm::mat4 &viewProj, const glm::vec3 &eye,
1824 float fovYDeg, float nearZ, float farZ);
1825 void destroyGpuDrivenCullResources();
1826 GpuDrivenCullSlot &currentGpuDrivenCullSlot();
1827 GpuDrivenCullSlot &gpuDrivenCullSlot(uint32_t frameSlot);
1828
1829 // CSM shadow map (3 cascade layers), one array per in-flight slot.
1830 struct ShadowMapSlot {
1831 vkb::DepthArrayImage image;
1832 vk::Framebuffer framebuffers[ShadowConfig::kTotalLayers]{};
1833 };
1834 std::vector<ShadowMapSlot> shadowMaps;
1836 int allocatedShadowMapSize = 0;
1837 vkb::DepthSampler shadowSampler{};
1838 vk::Sampler shadowRawSampler{};
1839 vkb::BuiltRenderPass shadowRenderPass{};
1840 vk::PipelineLayout shadowPipelineLayout{};
1841 vk::Pipeline shadowPipeline{};
1842 vk::Pipeline shadowSingleSidedPipeline{};
1843 vk::PipelineLayout shadowAlphaPipelineLayout{};
1844 vk::Pipeline shadowAlphaPipeline{};
1845 vk::Pipeline shadowAlphaSingleSidedPipeline{};
1846 vk::PipelineLayout skinPassPipelineLayout{};
1847 vk::DescriptorSetLayout skinPassSetLayout{};
1848 vk::UniqueDescriptorSetLayout skinPassSetLayoutUnique;
1849 vk::Pipeline shadowSkinPipeline{};
1850 vk::Pipeline shadowSkinSingleSidedPipeline{};
1851 vk::Pipeline shadowSkinAlphaPipeline{};
1852 vk::Pipeline shadowSkinAlphaSingleSidedPipeline{};
1853 int shadowPassCascade = -1;
1854 struct ShadowDraw {
1855 Mesh *mesh = nullptr;
1856 glm::mat4 mvp{1.f};
1857 Texture *albedo = nullptr;
1858 bool alphaTest = false; // use the alpha-cutout shadow pipeline
1859 bool doubleSided = true;
1860 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f};
1861 vk::DescriptorSet skinSet{};
1862 uint32_t skinUboOffset = 0;
1863 };
1864 struct ShadowAlphaPush {
1865 glm::mat4 mvp{1.f};
1866 glm::vec4 lodFade{1.f, 0.f, 0.f, 0.f};
1867 };
1868 std::vector<ShadowDraw> shadowPassDraws;
1869 std::vector<ShadowDraw> shadowCascadeDraws[ShadowConfig::kTotalLayers];
1870 uint32_t shadowPendingMask = 0;
1871 ShadowMapSlot &currentShadowMap();
1872 vk::ImageView currentShadowArrayView();
1873
1874 // Screen-space G-buffer (normal / linear-depth / albedo + HW depth).
1875 struct GBufferPush {
1876 glm::mat4 mvp{1.f};
1877 // The three rows hold the precomputed inverse-transpose normal matrix.
1878 glm::vec4 modelR0{1.f, 0.f, 0.f, 0.f};
1879 glm::vec4 modelR1{0.f, 1.f, 0.f, 0.f};
1880 glm::vec4 modelR2{0.f, 0.f, 1.f, 0.f};
1881 glm::vec4 clip{0.1f, 100.f, 0.f, 0.f};
1884 static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding) {
1885 return {binding, sizeof(GBufferPush), vk::VertexInputRate::eInstance};
1886 }
1890 static std::vector<vk::VertexInputAttributeDescription> getAttributeDescription(uint32_t binding) {
1891 std::vector<vk::VertexInputAttributeDescription> attributes;
1892 attributes.reserve(8);
1893 for (uint32_t i = 0; i < 8; ++i)
1894 attributes.push_back({7u + i, binding, vk::Format::eR32G32B32A32Sfloat, i * 16u});
1895 return attributes;
1896 }
1897 };
1898 static_assert(sizeof(GBufferPush) == 128, "GBuffer push constants must be 128 bytes");
1899 struct GBufferDraw {
1900 Mesh *mesh = nullptr;
1901 Texture *albedo = nullptr;
1902 GBufferPush push{};
1903 // Immutable frame-slot resources prepared on the render thread; workers only bind them.
1904 vk::Pipeline pbrPipeline{};
1905 vk::PipelineLayout pbrLayout{};
1906 vk::DescriptorSet pbrSet{};
1907 vk::Buffer pbrUv{};
1908 std::array<vk::DeviceSize, 11> pbrUvOffsets{};
1909 glm::vec4 pbrClip{};
1910 glm::vec2 pbrFactors{};
1911 bool alphaTest = false; // use the alpha-cutout gbuffer pipeline
1912 vk::DescriptorSet skinSet{};
1913 uint32_t skinUboOffset = 0;
1914 };
1915 struct GBufferSlot {
1916 vkb::GenericBuffer instanceBuffer;
1917 size_t instanceCapacity = 0;
1918 vkb::ColorTarget normal;
1919 vkb::ColorTarget depthColor;
1920 vkb::ColorTarget albedo;
1921 vkb::ColorTarget pbrParams; // RGBA8: metallic, roughness, occlusion, specularFactor
1922 vkb::ColorTarget emissive; // RGB emissive (A unused)
1923 vkb::ColorTarget visID; // R32G32UI: x = instance, y = pooled index offset
1924 vkb::ColorTarget visBary; // R16G16F: barycentric (u, v)
1925 vkb::DepthTarget depth;
1926 vk::Framebuffer framebuffer{};
1927 vk::Framebuffer visFramebuffer{};
1928 GpuTexture normalGpu{};
1929 GpuTexture depthColorGpu{};
1930 GpuTexture albedoGpu{};
1931 GpuTexture pbrParamsGpu{};
1932 GpuTexture emissiveGpu{};
1933 GpuTexture visIDGpu{};
1934 GpuTexture visBaryGpu{};
1935 GpuTexture depthGpu{};
1936 Texture normalTex{};
1937 Texture depthColorTex{};
1938 Texture albedoTex{};
1939 Texture pbrParamsTex{};
1940 Texture emissiveTex{};
1941 Texture visIDTex{};
1942 Texture visBaryTex{};
1943 Texture depthTex{};
1944 };
1945 int gbufferWidth = 0;
1946 int gbufferHeight = 0;
1947 std::vector<GBufferSlot> gbufferSlots;
1948 vkb::BuiltRenderPass gbufferRenderPass{};
1949 vkb::BuiltRenderPass gbufferVisRenderPass{};
1950 vk::PipelineLayout gbufferPipelineLayout{};
1951 vk::Pipeline gbufferPipeline{};
1952 vk::Pipeline gbufferInstancedPipeline{};
1953 vk::Pipeline gbufferAlphaPipeline{};
1954 vk::Pipeline gbufferSkinPipeline{};
1955 vk::Pipeline gbufferSkinAlphaPipeline{};
1956 vk::Pipeline gbufferVisPipeline = nullptr;
1957 bool gbufferPassActive = false;
1958 bool gbufferPending = false;
1959 std::vector<GBufferDraw> gbufferPassDraws;
1960 struct GBufferInstancedBatch {
1961 size_t first = 0;
1962 uint32_t count = 0;
1963 vk::Buffer buffer{};
1964 vk::DeviceSize offset = 0;
1965 };
1966 std::vector<GBufferInstancedBatch> gbufferInstancedBatches;
1967 void prepareGBufferInstanceBatches();
1968 GBufferSlot *currentGBufferSlot();
1969
1970 // Screen-space decal layer: box-projected decals write albedo/normal/params
1971 // targets after the G-buffer; mesh3d.frag samples them before lighting.
1973 struct DecalInstanceData {
1974 glm::mat4 model{1.f};
1975 glm::vec4 uvRect{0.f, 0.f, 1.f, 1.f};
1976 glm::vec4 fadeParams{1.f, 0.f, 0.f, 0.f}; // fade, normalStrength, roughStrength, metalStrength
1977 glm::vec4 extraParams{0.f, 0.f, 0.f, 0.f}; // emissive, blendMode, projectionMode, sharpness
1978 glm::vec4 surfaceParams{0.f, 8.f, 24.f, 0.06f}; // POM scale/min/max, edge fade width
1979 };
1980 static_assert(sizeof(DecalInstanceData) == 128, "DecalInstanceData must be 128 bytes");
1981 struct DecalCameraUBO {
1982 glm::mat4 viewProj{1.f};
1983 glm::mat4 invViewProj{1.f};
1984 glm::vec4 nearFarTexel{0.1f, 100.f, 0.f, 0.f}; // x=near, y=far, z=1/w, w=1/h
1985 };
1987 static constexpr size_t kMaxDecalInstances = 512;
1988 struct DecalDraw {
1989 glm::mat4 model{1.f};
1990 Texture *albedo = nullptr;
1991 Texture *normal = nullptr;
1992 Texture *params = nullptr;
1993 float uvRect[4] = {0.f, 0.f, 1.f, 1.f};
1994 float fade = 1.f;
1995 float normalStrength = 0.f;
1996 float roughnessStrength = 0.f;
1997 float metalStrength = 0.f;
1998 float emissiveStrength = 0.f;
1999 int blendMode = 0; // 0 = premultiplied over, 1 = additive (emissive)
2000 int projectionMode = 0; // 0 = planar, 1 = local triplanar, 2 = spherical, 3 = world-aligned
2001 float blendSharpness = 4.f;
2002 float parallaxScale = 0.f;
2003 float parallaxMinLayers = 8.f;
2004 float parallaxMaxLayers = 24.f;
2005 float edgeFadeWidth = 0.06f;
2006 };
2007 struct DecalSetKey {
2008 GpuTexture *albedo = nullptr;
2009 GpuTexture *normal = nullptr;
2010 GpuTexture *params = nullptr;
2011 GpuTexture *depth = nullptr;
2012 GpuTexture *gbNormal = nullptr;
2014 bool operator==(const DecalSetKey &o) const {
2015 return albedo == o.albedo && normal == o.normal && params == o.params &&
2016 depth == o.depth && gbNormal == o.gbNormal;
2017 }
2018 };
2019 struct DecalSetKeyHash {
2021 size_t operator()(const DecalSetKey &k) const {
2022 return std::hash<GpuTexture *>()(k.albedo) ^
2023 (std::hash<GpuTexture *>()(k.normal) << 1) ^
2024 (std::hash<GpuTexture *>()(k.params) << 2) ^
2025 (std::hash<GpuTexture *>()(k.depth) << 3) ^
2026 (std::hash<GpuTexture *>()(k.gbNormal) << 4);
2027 }
2028 };
2029 struct DecalSlot {
2030 vkb::ColorTarget albedo;
2031 vkb::ColorTarget normal;
2032 vkb::ColorTarget params;
2033 vk::Framebuffer framebuffer{};
2034 GpuTexture albedoGpu{};
2035 GpuTexture normalGpu{};
2036 GpuTexture paramsGpu{};
2037 Texture albedoTex{};
2038 Texture normalTex{};
2039 Texture paramsTex{};
2040 vkb::GenericBuffer cameraUbo; // capacity 1 per frame slot
2041 std::unordered_map<DecalSetKey, vkb::BoundSet, DecalSetKeyHash> sets;
2042 };
2043 int decalWidth = 0;
2044 int decalHeight = 0;
2045 std::vector<DecalSlot> decalSlots;
2046 vkb::BuiltRenderPass decalRenderPass{};
2047 vk::DescriptorSetLayout decalSetLayout;
2048 vk::UniqueDescriptorSetLayout decalSetLayoutUnique;
2049 vk::PipelineLayout decalPipelineLayout{};
2050 vk::Pipeline decalPipeline{};
2051 bool decalPassActive = false;
2052 bool decalPending = false;
2055 bool decalLayerFresh = false;
2056 std::vector<DecalDraw> decalPassDraws;
2057 vk::Pipeline lastDecalPipeline = nullptr;
2058 Mesh *decalUnitBox = nullptr;
2060 Texture *decalFlatAlbedo = nullptr;
2061 Texture *decalFlatNormal = nullptr;
2062 Texture *decalFlatParams = nullptr;
2063 glm::mat4 decalViewProj{1.f};
2064 float decalNear = 0.1f;
2065 float decalFar = 100.f;
2066 // Two lazily-created FrameGraphs per in-flight slot: G-buffer-only (0),
2067 // or all shadow layers plus G-buffer (1), with passes in one layer,
2068 // recorded concurrently on JobSystem workers. Each graph's command buffer
2069 // is only reused two frames later — by then the present slot fence (waited
2070 // in Present::begin) guarantees the previous graph submit has completed
2071 // (same queue, submitted before the present command buffer). The graphs
2072 // import the engine-owned shadow array + ColorTarget images; the engine
2073 // keeps ownership so readback / entity-ID rendering / postFX wrappers keep
2074 // working unchanged.
2075 std::array<std::array<std::unique_ptr<vkb::FrameGraph>, 2>, kAsyncResourceCopies> deferredFrameGraphs_;
2076 FrameGraphRecordingState deferredRecordingState_;
2077 // Only fully overwritten pipeline intermediates are frame-local. User canvases
2078 // and temporal histories retain their persistent-image semantics.
2079 std::array<std::vector<Canvas *>, 2> framePostTargets_;
2080 Canvas &prepareFramePostTarget(FramePostTarget target, int width, int height) override;
2081 void releaseFramePostTargets();
2082 vkb::FrameGraph *currentDeferredFrameGraph();
2084 bool deferredGraphRecorded_ = false;
2085 size_t deferredGraphRecordedSlot_ = 0;
2087 void buildDeferredFrameGraphs();
2092 void resetDeferredFrameGraphs();
2094 void recordShadowCascadePass(vkb::FrameGraphPassContext &ctx, int cascade);
2095 void recordShadowCascadeDraws(vk::CommandBuffer cb, int cascade, uint32_t size);
2097 void recordGBufferPassDraws(vkb::FrameGraphPassContext &ctx);
2098
2099 struct SceneColorSlot {
2100 vkb::ColorTarget msaaColor;
2101 vkb::ColorTarget color;
2102 vkb::DepthTarget depth;
2103 vk::Framebuffer framebuffer{};
2104 GpuTexture colorGpu{};
2105 Texture colorTex{};
2106 };
2107 int sceneColorWidth = 0;
2108 int sceneColorHeight = 0;
2109 vk::Format sceneColorFormat = vk::Format::eUndefined;
2110 vk::SampleCountFlagBits sceneColorSamples = vk::SampleCountFlagBits::e1;
2111 std::vector<SceneColorSlot> sceneColorSlots;
2112 size_t completedSceneColorSlot = 0;
2113 bool sceneColorHistoryValid = false;
2114 vkb::BuiltRenderPass sceneColorRenderPass{};
2115 vk::RenderPass sceneColorResumeRenderPass{};
2116 bool sceneColorPassOpen = false;
2117 vk::RenderPass scenePassPipelineTarget = vk::RenderPass{};
2118 vk::SampleCountFlagBits scenePassPipelineSamples = vk::SampleCountFlagBits::e1;
2119 int appliedMsaa = -1;
2120 SceneColorSlot *currentSceneColorSlot();
2121
2122 // Offscreen 3D render-to-canvas (color + D32 depth) used for planar
2123 // reflection / render targets. Rendered on a dedicated command buffer and
2124 // submitted directly to the graphics queue (no swapchain / present).
2125 vkb::BuiltRenderPass offscreen3DRenderPass{};
2126 vkb::BuiltRenderPass hdrOffscreen3DRenderPass{};
2127 vk::Pipeline offscreen3DMeshPipeline = nullptr;
2128 vk::Pipeline hdrOffscreen3DMeshPipeline = nullptr;
2129 std::array<vk::Pipeline, kMesh3DPipelineVariants> offscreen3DSurfacePipelines{};
2130 std::array<vk::Pipeline, kMesh3DPipelineVariants> hdrOffscreen3DSurfacePipelines{};
2131 vk::UniqueDescriptorSetLayout reflectionProbeFilterSetLayout;
2132 vk::UniquePipelineLayout reflectionProbeFilterPipelineLayout;
2133 ComputePass reflectionProbeFilterPass;
2134 vk::CommandPool offscreen3DPool = nullptr;
2135 vk::CommandBuffer offscreen3DCB = nullptr;
2136 vk::Fence offscreen3DFence = nullptr;
2137 vk::QueryPool offscreen3DTimestampQueryPool = nullptr;
2138 float offscreen3DTimestampPeriodNs = 0.f;
2139 float lastOffscreen3DGpuDurationMs = 0.f;
2140 bool offscreen3DPassOpen = false;
2141 bool offscreen3DHDRActive = false;
2142 OffscreenCanvas *offscreen3DCanvas = nullptr;
2143
2144 // Dedicated 4x-MSAA color target for the UI overlay (ImGui), resolved to a
2145 // single-sample texture that is composited as the top-most fullscreen quad.
2146 struct UiColorSlot {
2147 vkb::ColorTarget msaaColor;
2148 vkb::ColorTarget color;
2149 vk::Framebuffer framebuffer{};
2150 GpuTexture colorGpu{};
2151 Texture colorTex{};
2152 };
2153 int uiColorWidth = 0;
2154 int uiColorHeight = 0;
2155 vk::Format uiColorFormat = vk::Format::eUndefined;
2156 vk::SampleCountFlagBits uiColorSamples = vk::SampleCountFlagBits::e1;
2157 std::vector<UiColorSlot> uiColorSlots;
2158 vkb::BuiltRenderPass uiRenderPass{};
2159 vk::Pipeline uiTexturePipeline{};
2160 vk::Pipeline uiTextureOpaquePipeline{};
2161 UiColorSlot *currentUiColorSlot();
2162
2163 // Linear HDR compose target: scene + overlays blend in paper-white-relative
2164 // display-linear space, then a single fullscreen tonemap encodes to the
2165 // HDR10/scRGB swapchain.
2166 struct PresentComposeSlot {
2167 vkb::ColorTarget color;
2168 vk::Framebuffer framebuffer{};
2169 GpuTexture colorGpu{};
2170 Texture colorTex{};
2171 };
2172 int presentComposeWidth = 0;
2173 int presentComposeHeight = 0;
2174 std::vector<PresentComposeSlot> presentComposeSlots;
2175
2176 vkb::Present presentModel;
2177 vkb::RecordingCmd presentRecording;
2178 uint64_t presentSequence_ = 0;
2179 uint64_t submittedPresentSequence_ = 0;
2180 vkb::InRenderPass swapchainPass;
2181 vkb::DepthStencilImage depthImage;
2182 vk::Format depthFormat = vk::Format::eD32Sfloat;
2183
2184 // One timestamp pair and prefix command buffer per reusable frame slot.
2185 void submitGpuTimingPrefix();
2186 std::array<vk::CommandBuffer, kAsyncResourceCopies> gpuTimingPrefix_{};
2187 std::array<bool, kAsyncResourceCopies> gpuTimingPrefixSubmitted_{};
2188 vk::QueryPool gpuQueryPool_{};
2189 float timestampPeriod_ = 1.f;
2190 bool gpuTimingReady_ = false;
2191 float gpuFrameMs_ = 0.f;
2192
2193 struct SolidBatch {
2194 BlendMode blend = BlendMode::Alpha;
2195 Batcher batch;
2196 };
2197 std::vector<SolidBatch> solidBatches;
2198 struct TexturedBatch {
2200 enum class Effect { Default, SceneColorDistortion, DisplayEncode };
2201 Texture *texture = nullptr;
2202 Texture *depth = nullptr;
2203 Shader *shader = nullptr;
2204 BlendMode blend = BlendMode::Alpha;
2205 Batcher batch;
2206 Effect effect = Effect::Default;
2207 Texture *motion = nullptr;
2208 Texture *extra = nullptr;
2209 Texture *specular = nullptr;
2210 };
2211 std::vector<TexturedBatch> texturedBatches;
2212
2213 std::vector<LitBatch> litBatches;
2214
2215 enum class OverlayKind : uint8_t { Solid, Textured, Lit, GpuParticles };
2216 struct OverlaySpan {
2217 OverlayKind kind = OverlayKind::Solid;
2218 uint32_t index = 0;
2219 uint32_t vertBegin = 0;
2220 uint32_t vertCount = 0;
2221 };
2222 std::vector<OverlaySpan> overlaySpans;
2223 std::vector<OverlaySpan> engine3DSpans;
2224 std::optional<TexturedBatch> pendingSceneResolve;
2225 Texture *pendingSceneResolveSource = nullptr;
2226 std::optional<TexturedBatch> pendingUiResolve;
2227 bool sceneColorComposited = false;
2228
2229 struct GpuParticleDrawRequest {
2231 GpuParticleDraw draw;
2232 };
2233 std::unordered_map<GpuParticleHandle, GpuParticleResource*> gpuParticles_;
2234 std::vector<GpuParticleDrawRequest> gpuParticleDraws_;
2235 GpuParticleHandle nextGpuParticleHandle_ = 1;
2236 vk::DescriptorSetLayout gpuParticleComputeSetLayout_{};
2237 vk::DescriptorSetLayout gpuParticleDrawSetLayout_{};
2238 vk::DescriptorSetLayout gpuParticleSortSetLayout_{};
2239 vk::PipelineLayout gpuParticleComputeLayout_{};
2240 vk::PipelineLayout gpuParticleDrawLayout_{};
2241 vk::PipelineLayout gpuParticleSortLayout_{};
2242 vk::Pipeline gpuParticleComputePipeline_{};
2243 vk::Pipeline gpuParticleSortPipeline_{};
2244 vk::Pipeline gpuParticleAlphaPipeline_{};
2245 vk::Pipeline gpuParticleAdditivePipeline_{};
2246 vk::Pipeline gpuParticlePremultipliedPipeline_{};
2247 vk::Pipeline gpuParticleMultiplyPipeline_{};
2248 vk::Pipeline gpuParticleOpaquePipeline_{};
2249
2250 // Persistent host-visible vertex buffers for 2D batching, reused across
2251 // frames. GenericBuffer now owns the Vulkan handles.
2252 struct Frame2DBuffers {
2253 std::vector<vkb::HostVertexBuffer> solidBufs;
2254 std::vector<vkb::HostVertexBuffer> texBufs;
2255 std::vector<vkb::HostVertexBuffer> uiTexBufs;
2256 std::vector<vkb::HostVertexBuffer> primitive3DBufs;
2257 std::size_t primitive3DDrawIndex = 0;
2258 };
2259 std::vector<Frame2DBuffers> frame2dBuffers; // per swapchain frame slot
2260 Frame2DBuffers offscreenBuffers; // synchronous offscreen path
2261
2262 vk::DescriptorSetLayout lit2dSetLayout;
2263 vk::UniqueDescriptorSetLayout lit2dSetLayoutUnique;
2264 vk::PipelineLayout lit2dPipelineLayout;
2265 vk::Pipeline lit2dPipeline;
2266 vk::Pipeline lit2dAdditivePipeline;
2267 vk::Pipeline lit2dPremultipliedPipeline;
2268 vk::Pipeline lit2dMultiplyPipeline;
2269 vk::Pipeline lit2dOpaquePipeline;
2270 vk::Pipeline offscreenLitPipeline;
2271 vk::Pipeline offscreenLitAdditivePipeline;
2272 vk::Pipeline offscreenLitPremultipliedPipeline;
2273 vk::Pipeline offscreenLitMultiplyPipeline;
2274 vk::Pipeline offscreenLitOpaquePipeline;
2276 vk::Pipeline selectLit2DPipeline(BlendMode blend, bool offscreen, bool hdr = false) const;
2277 std::vector<vkb::GenericBuffer> lighting2dUboSlots; // per swapchain frame slot
2278 vkb::GenericBuffer offscreenLighting2dUbo; // synchronous offscreen path
2279 Lighting2DUBO lighting2dFrame{};
2280 struct LitSetKey {
2281 GpuTexture *albedo = nullptr;
2282 GpuTexture *normal = nullptr;
2284 bool operator==(const LitSetKey &o) const {
2285 return albedo == o.albedo && normal == o.normal;
2286 }
2287 };
2288 struct LitSetKeyHash {
2290 size_t operator()(const LitSetKey &k) const {
2291 return std::hash<void *>()(k.albedo) ^ (std::hash<void *>()(k.normal) << 1);
2292 }
2293 };
2294 struct PostSetKey {
2295 GpuTexture *color = nullptr;
2296 GpuTexture *depth = nullptr;
2297 GpuTexture *motion = nullptr;
2298 GpuTexture *extra = nullptr;
2299 GpuTexture *specular = nullptr;
2301 bool operator==(const PostSetKey &o) const {
2302 return color == o.color && depth == o.depth && motion == o.motion && extra == o.extra &&
2303 specular == o.specular;
2304 }
2305 };
2306 struct PostSetKeyHash {
2308 size_t operator()(const PostSetKey &k) const {
2309 return std::hash<void *>()(k.color) ^ (std::hash<void *>()(k.depth) << 1) ^
2310 (std::hash<void *>()(k.motion) << 2) ^
2311 (std::hash<void *>()(k.extra) << 3) ^
2312 (std::hash<void *>()(k.specular) << 4);
2313 }
2314 };
2315 std::vector<std::unordered_map<LitSetKey, vkb::BoundSet, LitSetKeyHash>> lit2dSets;
2316 std::unordered_map<LitSetKey, vkb::BoundSet, LitSetKeyHash> offscreenLit2dSets;
2317 std::unordered_map<PostSetKey, vkb::BoundSet, PostSetKeyHash> post2Sets;
2318 Texture *flatNormalTexture = nullptr;
2319
2320 Color clearColor{0.1f, 0.1f, 0.12f, 1.0f};
2321 bool hasPendingClear = true;
2322
2323 std::vector<std::unique_ptr<Texture>> ownedTextures;
2324 std::vector<std::unique_ptr<GpuTexture>> ownedGpuTextures;
2326 std::unordered_map<std::string, Texture *> texturesByPath;
2327 std::unordered_map<std::string, Texture *> sharedTexturesByContent;
2328 std::vector<std::unique_ptr<Mesh>> ownedMeshes;
2329 std::vector<std::unique_ptr<GpuMesh>> ownedGpuMeshes;
2330 std::vector<std::unique_ptr<Shader>> ownedShaders;
2331 std::vector<std::unique_ptr<GpuShader>> ownedGpuShaders;
2332 std::vector<std::unique_ptr<eve::graphics::Canvas>> ownedCanvases;
2333
2334 bool swapchainPassOpen = false;
2335 bool flushingSwapchain_ = false;
2336 Mesh3DUBO mesh3dFrameUbo{};
2337
2338 // Instanced voxel face rectangles (packed uint32 instances).
2339 struct VoxelRectPC {
2340 glm::mat4 viewProj{1.f};
2341 glm::vec4 chunkOrigin{0.f}; // xyz = origin, w = faceDir
2342 glm::vec4 atlasInfo{16.f, 0.f, 0.f, 0.f};
2343 glm::vec4 tint{1.f};
2344 };
2345 vk::DescriptorSetLayout voxelRectSetLayout{};
2346 vk::UniqueDescriptorSetLayout voxelRectSetLayoutUnique;
2347 vk::PipelineLayout voxelRectPipelineLayout{};
2348 vk::Pipeline voxelRectPipeline{};
2349 vkb::GenericBuffer voxelUnitQuadVerts;
2350 vkb::GenericBuffer voxelUnitQuadIndices;
2351 bool voxelUnitQuadReady = false;
2352 std::unordered_map<GpuTexture *, vkb::BoundSet> voxelRectSets;
2353 // Grow-only instance buffer pool (reset index each begin3DFrame), per
2354 // swapchain frame slot for async safety.
2355 struct VoxelInstanceSlot {
2356 vkb::GenericBuffer buffer;
2357 size_t capacityBytes = 0;
2358 vkb::GenericBuffer aoBuffer;
2359 size_t aoCapacityBytes = 0;
2360 };
2361 struct VoxelInstanceFrame {
2362 std::vector<VoxelInstanceSlot> slots;
2363 size_t drawIndex = 0;
2364 };
2365 std::vector<VoxelInstanceFrame> voxelInstanceFrames; // per swapchain frame slot
2366
2367 Frame2DBuffers &currentFrame2DBuffers();
2368 Mesh3dFrameSlots &currentMesh3dFrameSlots();
2369 Mesh3dClusteredFrameSlots &currentMesh3dClusteredFrameSlots();
2370 vkb::GenericBuffer &currentLighting2dUbo();
2371 std::unordered_map<LitSetKey, vkb::BoundSet, LitSetKeyHash> &currentLit2dSets();
2372 ClusteredStorage &currentClusteredStorage();
2373 VoxelInstanceFrame &currentVoxelInstanceFrame();
2374 uint32_t frameSlotCount() const;
2375 size_t currentFrameSlot() const;
2376 vk::CommandBuffer &currentPresentCb();
2377 vkb::FrameSlot frameToken() const;
2378 void invalidateTextureBindings();
2379 // Inspection service owns private GPU resources; destroyed only after device retirement.
2380 struct InspectionService;
2381 std::shared_ptr<InspectionService> inspectionService_;
2382 void pollEntityInspection();
2383 void destroyEntityInspection();
2384 // Guide-capture service: offscreen silhouette/depth(/bone) AOVs from GuidePack cameras.
2385 struct GuideCaptureService;
2386 std::shared_ptr<GuideCaptureService> guideCaptureService_;
2387 void pollGuideCapture();
2388 void destroyGuideCapture();
2389};
2390
2391} // namespace eve::graphics::vulkan
double y
double x
LogicalId target
bool & active
float w
Definition AnimClip.cpp:738
float ao
float normalStrength
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
graphics::Texture * albedo
std::string name
Definition ECS.cpp:154
double raw
#define EVENGINE_API_BACKENDS
Definition Export.h:108
std::string layout
float strength
std::uint32_t vertexCount
std::uint32_t indexCount
const GltfImportRequest & request
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
std::uint32_t spawnCount
std::uint32_t instanceCount
std::uint32_t capacity
POD RGB triple for Graphics tone-map controls without glm headers.
vk::UniqueSampler sampler
vk::UniqueImage image
glm::vec4 clip
glm::vec4 tint
glm::mat4 mvp
Entity-ID / isolated visibility capture kept off Graphics.h.
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
std::int32_t first
float blend
int h
std::uint32_t height
std::uint32_t width
size_t offset
std::array< float, 3 > scale
ActionGuidePack pack
bool present
std::string coverage
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
std::vector< TriangleRef > triangles
MeshVfxBatchedDraw draw
float roughness
bool doubleSided
Texture * normal
float alphaCutoff
float metallic
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec2 center
glm::dvec3 displacement
OceanSprayView view
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::vector< std::weak_ptr< DeviceBytes > > resources
Definition OnnxGpgpu.cpp:55
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::unique_ptr< ParticleEffect > effect
eve::action::ActionVfxBinding binding
std::array< uint32_t, 16 > material
Texture * texture
TileLayer * layer
PrimitiveHandle handle
int detail
std::map< std::string, double > attributes
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
bool lodFadeReverse
glm::vec3 eye
float lodWeight
glm::mat4 viewProj
Shader * shader
glm::mat4 model
Color clearColor
glm::dmat4 matrix
bool repeatV
bool repeatU
std::string_view source
std::string kind
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
std::array< double, 2 > vertices[3]
float opacity
bool visible
float size
Definition TreeMesh.cpp:158
int caps
Definition TreeMesh.cpp:164
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
double weight
uint32_t index
double gain
Move-only operation result carrying either a value or Status.
Definition Result.h:176
Accumulates solid / textured quads in logical (Y-down) coordinates. Used by RenderSystem; not a publi...
Definition Batcher.h:23
Canvas public API.
Definition Canvas.h:17
virtual void draw(Drawable *drawable, const glm::mat4 &m)
Draws .
virtual void setVSync(bool enabled)
Prefer uncapped present (IMMEDIATE/MAILBOX) when false, vsync (MAILBOX/FIFO) when true....
Definition Graphics.h:1589
virtual void setMsaaSamples(int samples)
Hardware MSAA sample count for the 3D scene color pass (0 disables, then 2/4/8 are used when the devi...
Definition Graphics.h:1602
SceneToneMapping
Final display mapping; None preserves linear color, Aces uses the fitted curve, and Filmic uses Rec....
Definition Graphics.h:1386
Mesh3DSceneColorCaptureStatus
Observable result of requesting a same-frame mesh SceneColor snapshot.
Definition Graphics.h:1227
virtual void setScreenReadbackEnabled(bool enabled)
When true, each present copies the swapchain to a CPU buffer for getPixel/newImageData....
Definition Graphics.h:1563
Resident GPU particle surface kept off the high-fanout Graphics facade.
Offscreen entity-ID and isolated visibility capture surface.
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Frame-local Skia-style recorder for 2D line primitives.
Frame-local scene recorder for 3D line primitives.
Custom GPU program.
Definition Shader.h:41
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:360
float getSceneAutoExposureMinEV() const override
Returns the scene auto exposure min ev.
Definition Graphics.h:951
float getSceneDofFocusRange() const override
Returns the scene dof focus range.
Definition Graphics.h:977
bool supportsGpuParticles() const override
Supports gpu particles.
Definition Graphics.h:499
vkb::Instance & getInstance()
Returns the instance.
Definition Graphics.h:1130
vk::PresentModeKHR currentPresentMode() const
Actual swapchain present mode; render-thread query, valid after window initialization.
Definition Graphics.h:1069
bool hasOpenPresentFrame() const
True while the present frame command buffer is being recorded, including its render passes.
Definition Graphics.h:1067
IGpuParticles * gpuParticles() noexcept override
Supports gpu particles.
Definition Graphics.h:496
float getSceneBloomThreshold() const override
Returns the scene bloom threshold.
Definition Graphics.h:962
uint32_t bindlessSlot2D(const GpuTexture *tex) const
Bindless slot 2 d.
Definition Graphics.h:452
bool gpuDrivenCullEnabled() const
Stage 2 cull is live for this frame (GPU-written commands).
Definition Graphics.h:528
bool supportsRayTracing() const override
Supports ray tracing.
Definition Graphics.h:440
float getSceneTransitionVignette() const override
Returns the scene transition vignette.
Definition Graphics.h:935
float getSceneBloomIntensity() const override
Returns the scene bloom intensity.
Definition Graphics.h:960
float getSceneTransitionLensScale() const override
Returns the scene transition lens scale.
Definition Graphics.h:941
float getSceneDofFarZ() const override
Returns the scene dof far z.
Definition Graphics.h:981
Result< void > drawMeshShaderInstances(Mesh &mesh, Shader &shader, const glm::mat4 &model, const Color &tint, std::uint32_t first, std::uint32_t count) override
Draws mesh shader instances.
int getMsaaSamples() const override
Returns the msaa samples.
Definition Graphics.h:426
bool supportsGpuDriven3D() const override
Supports gpu driven 3 d.
Definition Graphics.h:460
void pushValidationScope() override
Pushes validation scope.
Definition Graphics.h:577
const RayTracingCaps & rayTracingCapsRef() const
Hardware ray-tracing capabilities probed at device creation.
Definition Graphics.h:436
float getSceneAutoExposureMaxEV() const override
Returns the scene auto exposure max ev.
Definition Graphics.h:953
float getScenePhotographicVignette() const override
Read the current render-thread photographic vignette.
Definition Graphics.h:901
float getSceneExposure() const override
Returns the scene exposure.
Definition Graphics.h:905
uint32_t gpuDrivenMaterialRecord(Material *material) override
Gpu driven material record.
Definition Graphics.h:476
uint32_t debugLastGpuDrivenDrawCount() const
Indirect draws emitted by the last successful GPU-driven submit.
Definition Graphics.h:524
uint32_t getSwapchainImageCount() const
Returns the swapchain image count.
Definition Graphics.h:1136
float getSceneDofNearZ() const override
Returns the scene dof near z.
Definition Graphics.h:979
RayTracingCaps rayTracingCaps() const override
Ray tracing caps.
Definition Graphics.h:438
bool supportsDeferredLighting() const override
Supports deferred lighting.
Definition Graphics.h:464
bool supportsMeshInstancing() const override
Native ordinary-material batching; see Graphics ownership and frame-fence contract.
Definition Graphics.h:824
void setSceneLiftGammaGain(const RgbF &lift, const RgbF &inverseGamma, const RgbF &gain) override
Sets the scene lift gamma gain.
Definition Graphics.h:913
void setMsaaSamples(int samples) override
Sets the msaa samples.
Definition Graphics.h:419
bool supportsDecal() const override
Supports decal.
Definition Graphics.h:1015
float getSceneDofFocusDistance() const override
Returns the scene dof focus distance.
Definition Graphics.h:973
vk::CommandPool getUploadPool() const
Returns the upload pool.
Definition Graphics.h:1059
void setMesh3DSSAO(float intensity) override
Sets the mesh 3 dssao.
Definition Graphics.h:877
vk::RenderPass getUiMsaaRenderPass() const
Returns the ui msaa render pass.
Definition Graphics.h:1108
float getSceneTransitionVignetteSmoothness() const override
Returns the scene transition vignette smoothness.
Definition Graphics.h:937
void setScreenReadbackEnabled(bool enabled) override
Sets the screen readback enabled.
Definition Graphics.h:404
const vkb::BuiltRenderPass & getOffscreenRenderPass(bool hdr=false) const
Returns the offscreen render pass.
Definition Graphics.h:1096
const GpuDrivenCaps & gpuDrivenCaps() const
Capabilities probed at device creation; empty when unavailable.
Definition Graphics.h:433
uint64_t submittedPresentSequence() const
Most recent successfully submitted present identity; zero before the first submission.
Definition Graphics.h:1085
void setSceneDepthOfField(float focusDistance, float maxBlurPx, float focusRange, float nearZ, float farZ) override
Sets the scene depth of field.
Definition Graphics.h:964
float getSceneDofMaxBlur() const override
Returns the scene dof max blur.
Definition Graphics.h:975
bool canRecordPostSceneGpuWork() const
True when the present command buffer is open and the scene-color pass has ended, so post-scene GPU wo...
Definition Graphics.h:1065
void setSceneExposure(float exposure) override
Sets the scene exposure.
Definition Graphics.h:903
uint64_t recordingPresentSequence() const
Current recording identity, or zero outside a present recording. @lifetime Identities are monotonic f...
Definition Graphics.h:1080
float getSceneTransitionLensDistortion() const override
Returns the scene transition lens distortion.
Definition Graphics.h:939
vk::DescriptorSetLayout getTexSetLayout() const
Returns the tex set layout.
Definition Graphics.h:1092
const vkb::BuiltRenderPass & getOffscreen3DRenderPass(bool hdr=false)
Returns the offscreen 3 d render pass.
Definition Graphics.h:1100
RgbF getSceneColorFilter() const override
Returns the scene color filter.
Definition Graphics.h:911
vk::RenderPass getSwapchainRenderPass() const
Returns the swapchain render pass.
Definition Graphics.h:1106
void popValidationScope() override
Pops validation scope.
Definition Graphics.h:579
RgbF getSceneGain() const override
Returns the scene gain.
Definition Graphics.h:925
vkb::Swapchain & getSwapchain()
Returns the swapchain.
Definition Graphics.h:1132
void ensureUiColorResources()
Create the UI MSAA render pass (once) and its color targets for ImGui init.
Definition Graphics.h:1112
float getLastOffscreen3DGpuDurationMs() const override
Returns the last offscreen 3 d gpu duration ms.
Definition Graphics.h:792
SceneToneMapping getSceneToneMapping() const override
Returns the scene tone mapping.
Definition Graphics.h:891
bool gpuDrivenEnabled() const override
Gpu driven enabled.
Definition Graphics.h:468
bool getSceneAutoExposure() const override
Returns the scene auto exposure.
Definition Graphics.h:949
void setSceneBloom(float intensity, float threshold) override
Sets the scene bloom.
Definition Graphics.h:955
vk::CommandBuffer & postSceneCommandBuffer()
Borrow the open present command buffer for post-scene recording.
Definition Graphics.h:1090
void setVSync(bool enabled) override
Sets the v sync.
Definition Graphics.h:411
RgbF getSceneLift() const override
Returns the scene lift.
Definition Graphics.h:919
bool gpuDrivenScenePassPending() const
Scene color pass is deferred until after the compute cull section.
Definition Graphics.h:532
uint32_t bindlessSlotCube(const GpuTexture *tex) const
Bindless slot cube.
Definition Graphics.h:456
void gpuDrivenSetEnabled(bool enabled) override
Gpu driven set enabled.
Definition Graphics.h:472
void setSceneColorFilter(const RgbF &color) override
Sets the scene color filter.
Definition Graphics.h:907
IVisibilityCapture * visibilityCapture() noexcept override
Borrow the entity-ID / isolated visibility capture surface when present.
Definition Graphics.h:497
RgbF getSceneInverseGamma() const override
Returns the scene inverse gamma.
Definition Graphics.h:921
vkb::Device & getDevice()
Returns the device.
Definition Graphics.h:1057
vk::Format getDepthFormat() const
Returns the depth format.
Definition Graphics.h:1104
void requestSurfaceRecreate() override
Request surface recreate.
Definition Graphics.h:400
void * getSdlWindow() const
Returns the sdl window.
Definition Graphics.h:1134
void setSceneTransitionFx(float vignette, float vignetteSmoothness, float lensDistortion, float lensScale) override
Sets the scene transition fx.
Definition Graphics.h:927
vk::DescriptorPool getDescriptorPool() const
Returns the descriptor pool.
Definition Graphics.h:1094
bool isHeadless() const override
True when headless.
Definition Graphics.h:396
vk::SampleCountFlagBits getUiMsaaSamples() const
Sample count the UI MSAA pass runs with (matches getUiMsaaRenderPass).
Definition Graphics.h:1110
void setSceneAutoExposure(bool enabled, float minEV, float maxEV) override
Sets the scene auto exposure.
Definition Graphics.h:943
OffscreenCanvas public API.
Definition Canvas.h:15
Represents raw pixel data.
Definition ImageData.h:38
Reads the GPU frame timing captured by the renderer via Vulkan timestamp queries. Providers: eve::gra...
Definition GpuTimer.h:17
EffectInstance Effect
Backward-compatible name for the runtime instance type.
vkb::FrameArena FrameArena
Engine alias for the VKBuilder per-frame bump allocator.
Definition FrameArena.h:8
constexpr uint32_t kInvalidBindlessSlot
Definition GpuDriven.h:22
eve::graphics::GpuMaterialRecord GpuMaterialRecord
Definition GpuDriven.h:16
std::uint64_t GpuParticleHandle
Opaque backend-owned GPU particle emitter handle.
SurfaceMode
How a 3D surface contributes to depth and color passes.
Definition SurfaceMode.h:6
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
constexpr GpuParticleHandle kInvalidGpuParticleHandle
Invalid GPU particle handle returned when the backend cannot allocate the resource.
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
Definition IGraphics3D.h:20
GpuResidentSubmitStatus
Structured result for direct resident-instance submission.
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
bool enabled
Immutable CPU attachment with producer-provided decoding metadata.
Owning snapshot metadata; byte storage is immutable and lease-owned.
Transient backend buffer slice shared between sibling GPU modules. @ownership Non-owning; nativeHandl...
CPU-built clustered lighting upload for one frame/camera. Point lights are clustered; directional lig...
Per-instance GPU record (std430). Mirrors GLSL GpuInstance.
GPU-driven rendering std430 GPU layouts.
Parameters for rendering a resident GPU particle emitter.
GPU particle state uploaded only for newly spawned particles.
Delayed non-blocking counters from a resident GPU emitter.
Parameters for one resident GPU simulation step.
Direct-render description for a GPU-authored array of GpuInstance records. @ownership buckets and buf...
Neutral GPU upload for one virtual-geometry asset. Raw arrays so the graphics module does not depend ...
GPU light packing for mesh3d / PBR (std140-friendly).
Definition Light.h:160
Lighting2DUBO public API.
Definition Light.h:52
Lighting3DPack public API.
Definition Light.h:171
static constexpr int kMaxLights
Definition Light.h:172
static constexpr int kMaxDiffuseVolumeProbes
Definition Light.h:178
Value snapshot of custom mesh rasterization state, independent of blending/culling.
Owning material parameter snapshot; texture pointers remain borrowed. Base color/metallic/roughness c...
Definition PbrSurface.h:240
Hardware ray-tracing capabilities probed once at Vulkan device creation.
ReflectionProbeUpload public API.
Linear RGB triple used by scene color-grade getters/setters.
Definition GraphicsRgb.h:11
Inputs for descriptor set 1 of a resource mesh program.
ShadowUpload public API.
Definition Shadow.h:62
Options for Graphics::newTexture / newCubemap. When generateMipmaps is true and sampler....
Sampler state for a Texture (filter, wrap, mip LOD, anisotropy). Defaults match historical engine beh...
ColorVertex public API.
Definition Graphics.h:67
static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding)
Returns the binding description.
Definition Graphics.h:72
static std::vector< vk::VertexInputAttributeDescription > getAttributeDescription(uint32_t binding)
Returns the attribute description.
Definition Graphics.h:80
DeferredLightingUBO public API.
Definition Graphics.h:229
Capabilities required for the GPU-driven path. All must be true for gpuDrivenAvailable()....
Definition GpuDriven.h:31
GpuMesh public API.
Definition Graphics.h:298
vkb::HostVertexBuffer vertices
Definition Graphics.h:304
static constexpr size_t kDynamicVertexCopies
Ring copies for per-frame updated meshes (skin/morph/sprite stack). Writing the next copy never races...
Definition Graphics.h:303
uint32_t gpuRecordIndex
Index into the GPU mesh table (GpuMeshRecord).
Definition Graphics.h:322
uint64_t dynamicWriteCount
Number of dynamic updates; ring slot = count % kDynamicVertexCopies.
Definition Graphics.h:313
std::array< vkb::GenericBuffer, kDynamicVertexCopies > dynIndices
Definition Graphics.h:307
GpuMeshRecord record
CPU-side record for this mesh (bounds/ranges); uploaded by registerMeshRecord.
Definition Graphics.h:324
std::vector< MeshVertex > updateVertices
Definition Graphics.h:311
vk::DeviceSize residentVertexOffset
Definition Graphics.h:317
vkb::GenericBuffer indices
Definition Graphics.h:305
std::array< vkb::HostVertexBuffer, kDynamicVertexCopies > dynVertices
Definition Graphics.h:306
std::vector< uint32_t > cpuIndices
CPU index copy for dynamic meshes (also normalizes 16-bit static indices to 32-bit ring buffers).
Definition Graphics.h:310
GpuShader public API.
Definition Graphics.h:335
vk::Pipeline hdrOffscreenOpaquePipeline
Definition Graphics.h:341
vk::Pipeline mesh3dHdrOffscreenPipeline
Definition Graphics.h:345
vk::PipelineLayout pipelineLayout
Definition Graphics.h:346
std::unique_ptr< MeshShaderResources, MeshShaderResourcesDeleter > resources
Definition Graphics.h:350
vk::DescriptorSetLayout resourceFrameLayout
Definition Graphics.h:349
vk::DescriptorSet resourceSet
Definition Graphics.h:347
GpuTexture public API.
Definition Graphics.h:264
vkb::TextureImage2D image
Definition Graphics.h:265
uint32_t bindlessIndex2D
Bindless texture-array slot (stage 0 GPU-driven path).
Definition Graphics.h:285
vk::ImageView imageView() const
Image view.
Definition Graphics.h:289
uint64_t contentIdentity
Globally unique identity of the last completed owned RGBA8 upload; zero is unavailable.
Definition Graphics.h:283
vkb::CubemapRenderTarget hdrCube
HDR probe cube (attachment + storage + transfer); empty when unused.
Definition Graphics.h:269
Mesh3DClusteredUBO public API.
Definition Graphics.h:242
glm::vec4 reflectionProbeExtent[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:260
glm::vec4 reflectionProbeCenter[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:259
Mesh3DUBO public API.
Definition Graphics.h:181
glm::vec4 reflectionProbeExtent[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:209
glm::vec4 diffuseVolumePosition[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:212
Light3DGpu lights[Lighting3DPack::kMaxLights]
Definition Graphics.h:190
glm::vec4 reflectionProbeCenter[ReflectionProbeUpload::kMaxProbes]
Definition Graphics.h:208
glm::vec4 diffuseVolumeExtent[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:213
glm::vec4 diffuseVolumeSh[Lighting3DPack::kMaxDiffuseVolumeProbes *9]
Definition Graphics.h:214
MeshShaderResourcesDeleter public API.
Definition Graphics.h:329
void operator()(MeshShaderResources *resources) const noexcept
Operator .
MeshVertex public API.
Definition Graphics.h:148
static std::vector< vk::VertexInputAttributeDescription > getAttributeDescription(uint32_t binding)
Returns the attribute description.
Definition Graphics.h:167
static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding)
Returns the binding description.
Definition Graphics.h:159
Clip-space vertex emitted by the backend-neutral primitive tessellator.
Definition Graphics.h:89
static std::vector< vk::VertexInputAttributeDescription > getAttributeDescription(uint32_t binding)
Returns the attribute description.
Definition Graphics.h:98
static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding)
Returns the binding description.
Definition Graphics.h:94
SkinPassUBO public API.
Definition Graphics.h:220
TexturedVertex public API.
Definition Graphics.h:105
static std::vector< vk::VertexInputAttributeDescription > getAttributeDescription(uint32_t binding)
Returns the attribute description.
Definition Graphics.h:119
static vk::VertexInputBindingDescription getBindingDescription(uint32_t binding)
Returns the binding description.
Definition Graphics.h:111
Backend-internal textured rectangle queued by a UI presenter.
Definition Graphics.h:129
glm::mat4 invViewProj
glm::uvec4 info
glm::vec4 color