载入中...
搜索中...
未找到
Graphics3D.cpp
浏览该文件的文档.
1// Vulkan backend implementation — 3D frame, shadow and G-buffer passes.
2//
3// Re-split from the merged dev single-TU Graphics.cpp (pure move;
4// dev changes preserved). Shared helpers live in GraphicsInternal.h.
5
9#include "graphics/Light.h"
10#include "graphics/Outline.h"
17
18#include <SDL2/SDL.h>
19#include <SDL2/SDL_vulkan.h>
20
21#include <algorithm>
22#include <array>
23#include <bit>
24#include <cmath>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <functional>
29#include <stdexcept>
30#include <string>
31#include <vector>
32#if !defined(_WIN32)
33#include <unistd.h>
34#endif
35
36#include "common/Exception.h"
38#include "common/config.h"
40#include "image/Image.h"
41#include "image/ImageData.h"
42#include "zeroerr/assert.h"
43
44#include <memory>
45
46
47#include <assimp/mesh.h>
48#include <assimp/matrix3x3.h>
49#include <assimp/matrix4x4.h>
50#include <assimp/vector3.h>
51#include <glm/gtc/matrix_transform.hpp>
52
53#include "graphics/shaders/mesh3d_vert_spv.inc"
54#include "graphics/shaders/mesh3d_frag_spv.inc"
55#include "graphics/shaders/voxel_rect_vert_spv.inc"
56#include "graphics/shaders/voxel_rect_frag_spv.inc"
59#include "thread/Thread.h"
60
61namespace eve::graphics::vulkan {
62
65 applyPendingResourceChanges();
66 ASSERT(initialized);
67 if (!initialized) throw Exception("begin3DFrame: graphics not initialized");
68 if (isCanvasActive()) throw Exception("begin3DFrame: cannot start 3D while a Canvas is active");
69 createMesh3DPipeline();
70 if (swapchainPassOpen) {
71 // Previous eve_render opened 3D then threw before present().
72 try {
73 flushToSwapchain();
74 } catch (...) {
75 abortOpen3DFrame();
76 }
77 }
78 // Soft-fail like flushToSwapchain: on Android/iOS the surface may still be
79 // settling after orientation change; throwing would abort the whole script.
80 if (!beginPresentCommandBuffer())
81 return;
82 currentFrame2DBuffers().primitive3DDrawIndex = 0;
83 decalLayerFresh = false;
84 recordDeferredFrameGraph();
85 recordDecalPass();
86 vgAnyThisFrame_ = false;
87 currentFrameArena().reset();
88 ensureGpuDrivenCullResources(gbufferWidth > 0 ? gbufferWidth : int(swapchain.extent.width),
89 gbufferHeight > 0 ? gbufferHeight : int(swapchain.extent.height));
90
91 // 3D pass clears with backgroundColor (setBackgroundColor), not a stale 2D clear.
92 clearColor = backgroundColor;
93 createSceneColorResources(int(swapchain.extent.width), int(swapchain.extent.height));
94 // GPU-driven cull defers the scene color pass so the compute section
95 // (HZB build + cull + emit + VG cull) can run before the opaque draws;
96 // gpuDrivenOpenScenePass() opens it when the renderer reaches the forward
97 // section.
98 gpuDrivenScenePassPending_ = gpuDrivenEnabled_ && gpuDrivenCullReady_;
99 if (!gpuDrivenScenePassPending_) {
100 if (beginSceneColorRenderPass()) {
101 // Rebuild scene-pass pipelines to match the active scene pass (MSAA).
102 // Must happen AFTER the pass opens: if the MSAA scene pass is unavailable
103 // we fall back to the swapchain (e1) render pass below, and rasterizing
104 // with an Nx pipeline into an e1 pass is UB that can hang the GPU (TDR).
105 ensureScenePassPipelines(activeScenePass(), activeSceneSamples());
106 } else {
107 // Scene pass unavailable — draw 3D straight into the swapchain.
108 ensureScenePassPipelines(renderpass, vk::SampleCountFlagBits::e1);
109 beginSwapchainColorPass();
110 }
111 }
112
113 auto &cb = currentPresentCb();
114 setViewportAndScissor(cb, swapchain.extent.width, swapchain.extent.height);
115
116 {
117 auto &fslots = currentMesh3dFrameSlots();
118 fslots.lastDrawCount = fslots.drawIndex;
119 fslots.drawIndex = 0;
120 fslots.activePalette = 0;
121 ensureMesh3dRing(fslots);
122 auto &cslots = currentMesh3dClusteredFrameSlots();
123 cslots.lastDrawCount = cslots.drawIndex;
124 cslots.drawIndex = 0;
125 ensureMesh3dClusteredRing(cslots);
126 }
127 lastMesh3dPipeline = nullptr;
128 lastMesh3dClusteredPipeline = nullptr;
129 currentVoxelInstanceFrame().drawIndex = 0;
130 swapchainPassOpen = !gpuDrivenScenePassPending_;
131 frameHad3D = true;
132 hasPendingClear = false;
133}
134
135
136void Graphics::ensureOffscreen3DResources() {
137 auto &dev = getDevice();
138 auto createResources = [&](vk::Format colorFormat, vkb::BuiltRenderPass &renderPass, vk::Pipeline &meshPipeline,
139 std::array<vk::Pipeline, kMesh3DPipelineVariants> &surfacePipelines,
140 std::array<vk::Pipeline, kPrimitive3DPipelineVariants> &primitivePipelines) {
141 if (renderPass) return;
142 renderPass =
143 dev.createRenderPass()
144 .addSampledColorAttachment(colorFormat)
145 .addDepthAttachment(depthFormat, vk::AttachmentLoadOp::eClear,
146 vk::AttachmentStoreOp::eDontCare)
147 .addSubpass(vkb::SubpassBuilder()
148 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
149 .setDepthStencilAttachment(
150 1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
151 .addExternalShaderReadDependencies()
152 .build();
153 meshPipeline = createMesh3DStylePipeline(embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv),
154 mesh3dPipelineLayout, renderPass, vk::SampleCountFlagBits::e1,
156 for (int blendValue = 0; blendValue < 5; ++blendValue) {
157 const auto blend = BlendMode(blendValue);
158 for (int depthValue = 0; depthValue < 2; ++depthValue) {
159 for (int doubleValue = 0; doubleValue < 2; ++doubleValue) {
160 const size_t index =
161 mesh3dPipelineIndex(blend, depthValue != 0, doubleValue != 0);
162 surfacePipelines[index] = createMesh3DStylePipeline(
163 embeddedSpirv(mesh3d_vert_spv), embeddedSpirv(mesh3d_frag_spv), mesh3dPipelineLayout,
164 renderPass, vk::SampleCountFlagBits::e1, blend, depthValue != 0, doubleValue != 0,
167 }
168 }
169 }
170 buildPrimitive3DPipelines(renderPass, vk::SampleCountFlagBits::e1, primitivePipelines);
171 };
172 createResources(vk::Format::eR8G8B8A8Unorm, offscreen3DRenderPass, offscreen3DMeshPipeline,
173 offscreen3DSurfacePipelines, offscreenPrimitive3DPipelines);
174 createResources(vk::Format::eR16G16B16A16Sfloat, hdrOffscreen3DRenderPass, hdrOffscreen3DMeshPipeline,
175 hdrOffscreen3DSurfacePipelines, hdrOffscreenPrimitive3DPipelines);
176 if (!offscreen3DPool) {
177 vk::CommandPoolCreateInfo poolInfo{};
178 poolInfo.flags = vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer;
179 offscreen3DPool = dev->createCommandPool(poolInfo);
180 vk::CommandBufferAllocateInfo allocInfo{};
181 allocInfo.commandPool = offscreen3DPool;
182 allocInfo.level = vk::CommandBufferLevel::ePrimary;
183 allocInfo.commandBufferCount = 1;
184 auto bufs = dev->allocateCommandBuffers(allocInfo);
185 offscreen3DCB = bufs[0];
186 vk::FenceCreateInfo fenceInfo{};
187 fenceInfo.flags = vk::FenceCreateFlagBits::eSignaled; // first wait passes immediately
188 offscreen3DFence = dev->createFence(fenceInfo);
189 const auto &limits = dev.physical_device.properties.limits;
190 if (limits.timestampComputeAndGraphics && limits.timestampPeriod > 0.f) {
191 vk::QueryPoolCreateInfo queryInfo{};
192 queryInfo.queryType = vk::QueryType::eTimestamp;
193 queryInfo.queryCount = 2;
194 offscreen3DTimestampQueryPool = dev->createQueryPool(queryInfo);
195 offscreen3DTimestampPeriodNs = limits.timestampPeriod;
196 }
197 }
198}
199
200void Graphics::destroyOffscreen3DResources() {
201 auto &dev = getDevice();
202 if (offscreen3DFence) {
203 dev->destroyFence(offscreen3DFence);
204 offscreen3DFence = nullptr;
205 }
206 if (offscreen3DTimestampQueryPool) {
207 dev->destroyQueryPool(offscreen3DTimestampQueryPool);
208 offscreen3DTimestampQueryPool = nullptr;
209 }
210 offscreen3DTimestampPeriodNs = 0.f;
211 lastOffscreen3DGpuDurationMs = 0.f;
212 if (offscreen3DPool) {
213 dev->destroyCommandPool(offscreen3DPool);
214 offscreen3DPool = nullptr;
215 }
216 offscreen3DCB = nullptr;
217 if (offscreen3DMeshPipeline) {
218 device->destroyPipeline(offscreen3DMeshPipeline);
219 offscreen3DMeshPipeline = nullptr;
220 }
221 if (hdrOffscreen3DMeshPipeline) {
222 device->destroyPipeline(hdrOffscreen3DMeshPipeline);
223 hdrOffscreen3DMeshPipeline = nullptr;
224 }
225 for (auto &pipeline : offscreen3DSurfacePipelines) {
226 if (pipeline) device->destroyPipeline(pipeline);
227 pipeline = nullptr;
228 }
229 for (auto &pipeline : hdrOffscreen3DSurfacePipelines) {
230 if (pipeline) device->destroyPipeline(pipeline);
231 pipeline = nullptr;
232 }
233 for (auto &pipeline : offscreenPrimitive3DPipelines) {
234 if (pipeline) device->destroyPipeline(pipeline);
235 pipeline = nullptr;
236 }
237 for (auto &pipeline : hdrOffscreenPrimitive3DPipelines) {
238 if (pipeline) device->destroyPipeline(pipeline);
239 pipeline = nullptr;
240 }
241 offscreenPrimitive3DBufs.clear();
242 if (offscreen3DRenderPass) {
243 device->destroyRenderPass(offscreen3DRenderPass);
244 offscreen3DRenderPass = {};
245 }
246 if (hdrOffscreen3DRenderPass) {
247 device->destroyRenderPass(hdrOffscreen3DRenderPass);
248 hdrOffscreen3DRenderPass = {};
249 }
250}
251
254 applyPendingResourceChanges();
255 ASSERT(initialized);
256 if (!initialized) throw Exception("begin3DFrameToCanvas: graphics not initialized");
257 if (!canvas) throw Exception("begin3DFrameToCanvas: null canvas");
258 createMesh3DPipeline();
259 auto *oc = dynamic_cast<OffscreenCanvas *>(canvas);
260 if (!oc) throw Exception("begin3DFrameToCanvas: not an offscreen canvas");
261 if (offscreen3DPassOpen) throw Exception("begin3DFrameToCanvas: already open");
262 if (swapchainPassOpen) {
263 try {
264 flushToSwapchain();
265 } catch (...) {
266 abortOpen3DFrame();
267 }
268 }
269 clearColor = backgroundColor;
270 ensureOffscreen3DResources();
271 oc->ensure3D();
272 offscreen3DCanvas = oc;
273 offscreen3DHDRActive = oc->isHDR();
274
275 if (offscreen3DFence) (void)device->waitForFences(1, &offscreen3DFence, VK_TRUE, UINT64_MAX);
276 offscreenPrimitive3DDrawIndex = 0;
277 vk::CommandBufferBeginInfo beginInfo{};
278 offscreen3DCB.begin(beginInfo);
279 if (mesh3dShadows.active && shadowPendingMask != 0) {
280 // Offscreen previews submit synchronously, before any swapchain pass.
281 // Replay pending shadows on this same command buffer so color samples
282 // this camera's maps, including headless and repeated previews per frame.
284 auto &slot = currentShadowMap();
285 slot.image.beginDepthAttachment();
286 vk::ClearValue clear{};
287 clear.depthStencil = vk::ClearDepthStencilValue{1.f, 0};
288 for (int cascade = 0; cascade < ShadowConfig::kTotalLayers; ++cascade) {
289 if ((shadowPendingMask & (1u << cascade)) == 0) continue;
290 vk::RenderPassBeginInfo shadowBegin{};
291 shadowBegin.renderPass = shadowRenderPass;
292 shadowBegin.framebuffer = slot.framebuffers[cascade];
293 const uint32_t atlasSize =
294 uint32_t(allocatedShadowMapSize > 0 ? allocatedShadowMapSize : ShadowConfig::kMapSize);
295 uint32_t viewportSize = atlasSize;
296 if (cascade >= 0 && cascade < ShadowConfig::kCascades && mesh3dShadows.active) {
297 viewportSize = uint32_t(std::max(1, mesh3dShadows.cascadeMapSizes[cascade]));
298 }
299 shadowBegin.renderArea = vk::Rect2D{{0, 0}, {atlasSize, atlasSize}};
300 shadowBegin.clearValueCount = 1;
301 shadowBegin.pClearValues = &clear;
302 offscreen3DCB.beginRenderPass(shadowBegin, vk::SubpassContents::eInline);
303 recordShadowCascadeDraws(offscreen3DCB, cascade, viewportSize);
304 offscreen3DCB.endRenderPass();
305 shadowCascadeDraws[cascade].clear();
306 }
307 slot.image.endSampledLayout();
308 shadowPendingMask = 0;
309 }
310
311 lastOffscreen3DGpuDurationMs = 0.f;
312 if (offscreen3DTimestampQueryPool) {
313 offscreen3DCB.resetQueryPool(offscreen3DTimestampQueryPool, 0, 2);
314 offscreen3DCB.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe,
315 offscreen3DTimestampQueryPool, 0);
316 }
317 std::array<vk::ClearValue, 2> clears{};
318 clears[0].color =
319 vk::ClearColorValue(std::array<float, 4>{clearColor.r, clearColor.g, clearColor.b, 1.f});
320 clears[1].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
321 vk::RenderPassBeginInfo rpBegin{};
322 rpBegin.renderPass = getOffscreen3DRenderPass(offscreen3DHDRActive);
323 rpBegin.framebuffer = oc->framebuffer3D();
324 rpBegin.renderArea =
325 vk::Rect2D{{0, 0}, {uint32_t(oc->getWidth()), uint32_t(oc->getHeight())}};
326 rpBegin.clearValueCount = uint32_t(clears.size());
327 rpBegin.pClearValues = clears.data();
328 oc->colorImage().beginColorAttachment();
329 oc->depthImage().beginDepthAttachment();
330 offscreen3DCB.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
331 setViewportAndScissor(offscreen3DCB, oc->getWidth(), oc->getHeight());
332
333 {
334 auto &fslots = currentMesh3dFrameSlots();
335 fslots.lastDrawCount = fslots.drawIndex;
336 fslots.drawIndex = 0;
337 fslots.activePalette = 0;
338 ensureMesh3dRing(fslots);
339 auto &cslots = currentMesh3dClusteredFrameSlots();
340 cslots.lastDrawCount = cslots.drawIndex;
341 cslots.drawIndex = 0;
342 ensureMesh3dClusteredRing(cslots);
343 }
344 lastMesh3dPipeline = nullptr;
345 lastMesh3dClusteredPipeline = nullptr;
346 offscreen3DPassOpen = true;
347 frameHad3D = true;
348 hasPendingClear = false;
349}
350
352 if (!offscreen3DPassOpen || !offscreen3DCB) return;
353 offscreen3DCB.endRenderPass();
354 if (offscreen3DCanvas) {
355 // The sampled render pass already performed its final-layout transition.
356 offscreen3DCanvas->colorImage().endSampledLayout();
357 }
358 if (offscreen3DTimestampQueryPool) {
359 offscreen3DCB.writeTimestamp(vk::PipelineStageFlagBits::eBottomOfPipe,
360 offscreen3DTimestampQueryPool, 1);
361 }
362 offscreen3DCB.end();
363
364 // Submit the offscreen render directly to the graphics queue (no present),
365 // then wait for it so it is fully drained before any subsequent render or
366 // teardown.
367 vk::SubmitInfo submitInfo{};
368 submitInfo.commandBufferCount = 1;
369 submitInfo.pCommandBuffers = &offscreen3DCB;
370 if (offscreen3DFence) (void)device->resetFences(1, &offscreen3DFence);
371 (void)device.getQueue(vkb::QueueType::graphics).submit(1, &submitInfo, offscreen3DFence);
372 if (offscreen3DFence)
373 (void)device->waitForFences(1, &offscreen3DFence, VK_TRUE, UINT64_MAX);
374 if (offscreen3DTimestampQueryPool && offscreen3DTimestampPeriodNs > 0.f) {
375 std::array<uint64_t, 2> ticks{};
376 const vk::Result queryResult = device->getQueryPoolResults(
377 offscreen3DTimestampQueryPool, 0, uint32_t(ticks.size()), sizeof(ticks), ticks.data(),
378 sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
379 if (queryResult == vk::Result::eSuccess && ticks[1] >= ticks[0]) {
380 const double nanoseconds =
381 double(ticks[1] - ticks[0]) * double(offscreen3DTimestampPeriodNs);
382 lastOffscreen3DGpuDurationMs = float(nanoseconds * 1.0e-6);
383 }
384 }
385
386 offscreen3DPassOpen = false;
387 offscreen3DHDRActive = false;
388 offscreen3DCanvas = nullptr;
389}
390
391void Graphics::setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) {
392 glm::vec3 d = glm::normalize(dir);
393 if (glm::length(d) < 1e-6f) d = glm::vec3(0.f, 1.f, 0.f);
394 mesh3dFrameUbo.lightDir = glm::vec4(d, mesh3dFrameUbo.lightDir.w);
395 // Preserve .w (envIntensity) — filled per-draw in drawMeshShader.
396 mesh3dFrameUbo.lightColor = glm::vec4(color, mesh3dFrameUbo.lightColor.w);
397}
398
399void Graphics::setMesh3DCameraPos(const glm::vec3 &eye) {
400 mesh3dFrameUbo.cameraPos = glm::vec4(eye, mesh3dFrameUbo.cameraPos.w);
401}
402
403void Graphics::destroyVoxelRectResources() {
404 for (auto &frame : voxelInstanceFrames) {
405 for (auto &slot : frame.slots) {
406 slot.buffer.release();
407 slot.capacityBytes = 0;
408 }
409 frame.slots.clear();
410 frame.drawIndex = 0;
411 }
412 voxelInstanceFrames.clear();
413 voxelRectSets.clear();
414 auto destroyBuf = [&](vkb::GenericBuffer &b) { b.release(); };
415 if (voxelUnitQuadReady) {
416 destroyBuf(voxelUnitQuadVerts);
417 destroyBuf(voxelUnitQuadIndices);
418 voxelUnitQuadReady = false;
419 }
420 if (voxelRectPipeline) {
421 device->destroyPipeline(voxelRectPipeline);
422 voxelRectPipeline = vk::Pipeline{};
423 }
424 if (voxelRectPipelineLayout) {
425 device->destroyPipelineLayout(voxelRectPipelineLayout);
426 voxelRectPipelineLayout = vk::PipelineLayout{};
427 }
428 voxelRectSetLayoutUnique.reset();
429 voxelRectSetLayout = vk::DescriptorSetLayout{};
430}
431
432void Graphics::createVoxelRectPipeline() {
433 if (voxelRectPipeline) return;
434
435 if (!voxelRectPipelineLayout) {
436 vkb::DescriptorSetLayoutBuilder layoutBuilder;
437 voxelRectSetLayoutUnique =
438 layoutBuilder
439 .image(0, vk::DescriptorType::eCombinedImageSampler,
440 vk::ShaderStageFlagBits::eFragment, 1)
441 .createUnique(device.instance);
442 voxelRectSetLayout = *voxelRectSetLayoutUnique;
443
444 const auto pcr = pushConstantRange(vk::ShaderStageFlagBits::eVertex, sizeof(VoxelRectPC));
445 voxelRectPipelineLayout = createPipelineLayout(device, voxelRectSetLayout, &pcr);
446 }
447
448 voxelRectPipeline = buildVoxelRectPipeline(renderpass, vk::SampleCountFlagBits::e1);
449 ensureVoxelUnitQuad();
450}
451
452vk::Pipeline Graphics::buildVoxelRectPipeline(const vkb::BuiltRenderPass &rp,
453 vk::SampleCountFlagBits samples) {
454 auto vert = embeddedSpirv(voxel_rect_vert_spv);
455 auto frag = embeddedSpirv(voxel_rect_frag_spv);
456 ShaderModulePair modules(device, vert, frag);
457
458 vk::VertexInputBindingDescription bindings[3]{};
459 bindings[0].binding = 0;
460 bindings[0].stride = sizeof(glm::vec2);
461 bindings[0].inputRate = vk::VertexInputRate::eVertex;
462 bindings[1].binding = 1;
463 bindings[1].stride = sizeof(uint32_t);
464 bindings[1].inputRate = vk::VertexInputRate::eInstance;
465 bindings[2].binding = 2;
466 bindings[2].stride = sizeof(uint32_t);
467 bindings[2].inputRate = vk::VertexInputRate::eInstance;
468
469 vk::VertexInputAttributeDescription attrs[3]{};
470 attrs[0].location = 0;
471 attrs[0].binding = 0;
472 attrs[0].format = vk::Format::eR32G32Sfloat;
473 attrs[0].offset = 0;
474 attrs[1].location = 1;
475 attrs[1].binding = 1;
476 attrs[1].format = vk::Format::eR32Uint;
477 attrs[1].offset = 0;
478 attrs[2].location = 2;
479 attrs[2].binding = 2;
480 attrs[2].format = vk::Format::eR32Uint;
481 attrs[2].offset = 0;
482
483 vk::PipelineVertexInputStateCreateInfo vi{};
484 vi.vertexBindingDescriptionCount = 3;
485 vi.pVertexBindingDescriptions = bindings;
486 vi.vertexAttributeDescriptionCount = 3;
487 vi.pVertexAttributeDescriptions = attrs;
488
489 // Unit-quad indices 0-2-1 / 0-3-2 are object-space CCW for outward faces.
490 // perspectiveVulkanRH_ZO flips clip Y, so those faces are CCW in the
491 // framebuffer — CounterClockwise frontFace keeps them. Clockwise + Back
492 // (the mesh-pipeline convention) culls every submitted face after the Y
493 // flip; CPU 6-dir cull already dropped the true back faces, so the frame
494 // collapses to a 1px silhouette.
495 return device.createPipeline()
496 .useClassicPipeline(modules.vert, modules.frag)
497 .setPipelineLayout(voxelRectPipelineLayout)
498 .setVertexInputState(vi)
499 .setDynamicStatesViewportScissor()
500 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.0f, vk::CullModeFlagBits::eBack,
501 vk::FrontFace::eCounterClockwise)
502 .setMultisampler(false, samples)
503 .setDepthStencil(true, true, vk::CompareOp::eLess)
504 .setColorAttachmentCount(1)
505 .build(rp);
506}
507
508void Graphics::ensureVoxelUnitQuad() {
509 if (voxelUnitQuadReady) return;
510 const float corners[8] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
511 voxelUnitQuadVerts.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer, sizeof(corners),
512 vk::MemoryPropertyFlagBits::eHostVisible |
513 vk::MemoryPropertyFlagBits::eHostCoherent);
514 voxelUnitQuadVerts.updateLocal(frameToken(), corners, sizeof(corners));
515 const uint32_t indices[6] = {0, 2, 1, 0, 3, 2};
516 voxelUnitQuadIndices.allocate(frameToken(), device, vk::BufferUsageFlagBits::eIndexBuffer, sizeof(indices),
517 vk::MemoryPropertyFlagBits::eHostVisible |
518 vk::MemoryPropertyFlagBits::eHostCoherent);
519 voxelUnitQuadIndices.updateLocal(frameToken(), indices, sizeof(indices));
520 voxelUnitQuadReady = true;
521}
522
523vkb::BoundSet Graphics::voxelRectSetFor(GpuTexture *gpuTex) {
524 ASSERT(gpuTex != nullptr);
525 auto it = voxelRectSets.find(gpuTex);
526 if (it != voxelRectSets.end()) return it->second;
527
528 vk::DescriptorSetAllocateInfo alloc{};
529 alloc.descriptorPool = descriptorPool;
530 alloc.descriptorSetCount = 1;
531 alloc.pSetLayouts = &voxelRectSetLayout;
532 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
533
534 vkb::DescriptorSetUpdater updater(4, 4, 0);
535 updater.beginDescriptorSet(unbound)
536 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
537 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
538 .update(device.instance);
539
540 vkb::BoundSet bound = std::move(unbound).publish();
541 voxelRectSets.emplace(gpuTex, bound);
542 return bound;
543}
544
545void Graphics::drawVoxelFaceInstances(const uint32_t *packed, int count, float originX,
546 float originY, float originZ, const std::string &faceDir,
547 Texture *atlas, int tilesPerRow, const uint32_t *ao) {
548 ASSERT(initialized);
549 if (!initialized) throw Exception("drawVoxelFaceInstances: graphics not initialized");
550 if (!swapchainPassOpen) throw Exception("drawVoxelFaceInstances: call begin3DFrame first");
551 if (!voxelRectPipeline) createVoxelRectPipeline();
552 if (!packed || count <= 0) return;
553
554 int face = -1;
555 if (faceDir == "posX" || faceDir == "+x")
556 face = 0;
557 else if (faceDir == "negX" || faceDir == "-x")
558 face = 1;
559 else if (faceDir == "posY" || faceDir == "+y")
560 face = 2;
561 else if (faceDir == "negY" || faceDir == "-y")
562 face = 3;
563 else if (faceDir == "posZ" || faceDir == "+z")
564 face = 4;
565 else if (faceDir == "negZ" || faceDir == "-z")
566 face = 5;
567 else
568 throw Exception("drawVoxelFaceInstances: unknown faceDir '%s'", faceDir.c_str());
569
570 Texture *tex = atlas ? atlas : whiteTexture;
571 if (!tex || !tex->gpuHandle) throw Exception("drawVoxelFaceInstances: missing texture");
572 auto *gpuTex = static_cast<GpuTexture *>(tex->gpuHandle);
573
574 ensureVoxelUnitQuad();
575
576 const vk::DeviceSize bytes = vk::DeviceSize(count) * sizeof(uint32_t);
577 auto &vframe = currentVoxelInstanceFrame();
578 const size_t slotIndex = vframe.drawIndex++;
579 while (vframe.slots.size() <= slotIndex) vframe.slots.emplace_back();
580 auto &slot = vframe.slots[slotIndex];
581 if (slot.capacityBytes < size_t(bytes) || !slot.buffer.buffer) {
582 const size_t alloc = std::max(size_t(bytes), slot.capacityBytes ? slot.capacityBytes * 2 : size_t(bytes));
583 slot.buffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer, vk::DeviceSize(alloc),
584 vk::MemoryPropertyFlagBits::eHostVisible |
585 vk::MemoryPropertyFlagBits::eHostCoherent);
586 slot.capacityBytes = alloc;
587 }
588 slot.buffer.updateLocal(frameToken(), packed, size_t(bytes));
589
590 // Ambient-occlusion words (null → full bright). Kept parallel to packed.
591 const uint32_t defaultAO = 0xFFu; // all four corners AO=3
592 std::vector<uint32_t> aoDefaults;
593 if (!ao) {
594 aoDefaults.assign(size_t(count), defaultAO);
595 ao = aoDefaults.data();
596 }
597 const vk::DeviceSize aoBytes = vk::DeviceSize(count) * sizeof(uint32_t);
598 if (slot.aoCapacityBytes < size_t(aoBytes) || !slot.aoBuffer.buffer) {
599 const size_t alloc = std::max(size_t(aoBytes),
600 slot.aoCapacityBytes ? slot.aoCapacityBytes * 2
601 : size_t(aoBytes));
602 slot.aoBuffer.allocate(frameToken(), device, vk::BufferUsageFlagBits::eVertexBuffer,
603 vk::DeviceSize(alloc),
604 vk::MemoryPropertyFlagBits::eHostVisible |
605 vk::MemoryPropertyFlagBits::eHostCoherent);
606 slot.aoCapacityBytes = alloc;
607 }
608 slot.aoBuffer.updateLocal(frameToken(), ao, size_t(aoBytes));
609
610 VoxelRectPC pc{};
611 pc.viewProj = mesh3dFrameUbo.mvp;
612 pc.chunkOrigin = glm::vec4(originX, originY, originZ, float(face));
613 pc.atlasInfo = glm::vec4(float(std::max(1, tilesPerRow)), 0.f, 0.f, 0.f);
614 pc.tint = mesh3dFrameUbo.tint;
615
616 auto &cb = currentPresentCb();
617 vk::DescriptorSet set = voxelRectSetFor(gpuTex);
618 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, voxelRectPipeline);
619 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, voxelRectPipelineLayout, 0, 1, &set, 0,
620 nullptr);
621 cb.pushConstants(voxelRectPipelineLayout, vk::ShaderStageFlagBits::eVertex, 0, sizeof(VoxelRectPC),
622 &pc);
623
624 vk::Buffer vbufs[3] = {voxelUnitQuadVerts.buffer, slot.buffer.buffer, slot.aoBuffer.buffer};
625 vk::DeviceSize offsets[3] = {0, 0, 0};
626 cb.bindVertexBuffers(0, 3, vbufs, offsets);
627 cb.bindIndexBuffer(voxelUnitQuadIndices.buffer, 0, vk::IndexType::eUint32);
628 cb.drawIndexed(6, uint32_t(count), 0, 0, 0);
629}
630
631void Graphics::setMesh3DNormalTexture(Texture *normal) { mesh3dNormalTexture = normal; }
632
634 mesh3dVirtualAtlas.z = enabled ? 1.f : 0.f;
635 mesh3dFrameUbo.virtualAtlas = mesh3dVirtualAtlas;
636}
637
638void Graphics::setMesh3DHeightTexture(Texture *heightTex) { mesh3dHeightTexture = heightTex; }
639
640void Graphics::setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY,
641 int atlasSlotsX, int atlasSlotsY,
642 float borderFraction) {
643 mesh3dVirtualTexture =
644 enabled ? glm::vec4(1.f, float(pageCountX), float(pageCountY), borderFraction)
645 : glm::vec4(0.f);
646 const float packedNormalMask = mesh3dVirtualAtlas.z;
647 mesh3dVirtualAtlas = enabled ? glm::vec4(float(atlasSlotsX), float(atlasSlotsY), packedNormalMask, 0.f)
648 : glm::vec4(0.f, 0.f, packedNormalMask, 0.f);
649 mesh3dFrameUbo.virtualTexture = mesh3dVirtualTexture;
650 mesh3dFrameUbo.virtualAtlas = mesh3dVirtualAtlas;
651}
652
653void Graphics::setMesh3DSceneDepth(Texture *depth) { mesh3dSceneDepthTexture = depth; }
654
655void Graphics::setMesh3DSceneColor(Texture *color) { mesh3dSceneColorTexture = color; }
656
658 if (mesh3dSceneColorTexture) return Mesh3DSceneColorCaptureStatus::ExplicitOverride;
659 if (!sceneColorPassOpen || sceneColorSlots.size() < 2 || !sceneColorResumeRenderPass ||
660 sceneColorSamples != vk::SampleCountFlagBits::e1)
661 return sceneColorHistoryValid ? Mesh3DSceneColorCaptureStatus::HistoryReuse
663
664 const size_t sourceIndex = currentFrameSlot() % sceneColorSlots.size();
665 const size_t snapshotIndex = (sourceIndex + 1u) % sceneColorSlots.size();
666 SceneColorSlot &source = sceneColorSlots[sourceIndex];
667 SceneColorSlot &snapshot = sceneColorSlots[snapshotIndex];
668 auto &cb = currentPresentCb();
669
670 cb.endRenderPass();
671 sceneColorPassOpen = false;
672 source.color.endSampledLayout();
673 const vk::ImageSubresourceRange range{vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
674 std::array<vk::ImageMemoryBarrier, 2> before{};
675 before[0] = vk::ImageMemoryBarrier(vk::AccessFlagBits::eColorAttachmentWrite, vk::AccessFlagBits::eTransferRead,
676 vk::ImageLayout::eShaderReadOnlyOptimal, vk::ImageLayout::eTransferSrcOptimal,
677 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, source.color.image(), range);
678 before[1] = vk::ImageMemoryBarrier(
679 snapshot.color.currentLayout() == vk::ImageLayout::eUndefined ? vk::AccessFlags{}
680 : vk::AccessFlagBits::eShaderRead,
681 vk::AccessFlagBits::eTransferWrite, snapshot.color.currentLayout(), vk::ImageLayout::eTransferDstOptimal,
682 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, snapshot.color.image(), range);
683 cb.pipelineBarrier(vk::PipelineStageFlagBits::eColorAttachmentOutput | vk::PipelineStageFlagBits::eFragmentShader,
684 vk::PipelineStageFlagBits::eTransfer, {}, {}, {}, before);
685 vk::ImageCopy copy{};
686 copy.srcSubresource =
687 vk::ImageSubresourceLayers{vk::ImageAspectFlagBits::eColor, 0, 0, 1};
688 copy.dstSubresource =
689 vk::ImageSubresourceLayers{vk::ImageAspectFlagBits::eColor, 0, 0, 1};
690 copy.extent = vk::Extent3D{static_cast<uint32_t>(sceneColorWidth),
691 static_cast<uint32_t>(sceneColorHeight), 1};
692 cb.copyImage(source.color.image(), vk::ImageLayout::eTransferSrcOptimal,
693 snapshot.color.image(), vk::ImageLayout::eTransferDstOptimal, 1, &copy);
694 std::array<vk::ImageMemoryBarrier, 2> after{};
695 after[0] =
696 vk::ImageMemoryBarrier(vk::AccessFlagBits::eTransferRead,
697 vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite,
698 vk::ImageLayout::eTransferSrcOptimal, vk::ImageLayout::eColorAttachmentOptimal,
699 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, source.color.image(), range);
700 after[1] = vk::ImageMemoryBarrier(vk::AccessFlagBits::eTransferWrite, vk::AccessFlagBits::eShaderRead,
701 vk::ImageLayout::eTransferDstOptimal, vk::ImageLayout::eShaderReadOnlyOptimal,
702 VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, snapshot.color.image(), range);
703 cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
704 vk::PipelineStageFlagBits::eFragmentShader | vk::PipelineStageFlagBits::eColorAttachmentOutput,
705 {}, {}, {}, after);
706 source.color.setCurrentLayout(vk::ImageLayout::eColorAttachmentOptimal);
707 snapshot.color.setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
708 source.depth.setLayout(cb, vk::ImageLayout::eDepthStencilAttachmentOptimal,
709 vk::ImageAspectFlagBits::eDepth);
710 vk::RenderPassBeginInfo resume{};
711 resume.renderPass = sceneColorResumeRenderPass;
712 resume.framebuffer = source.framebuffer;
713 resume.renderArea =
714 vk::Rect2D{{0, 0}, {static_cast<uint32_t>(sceneColorWidth),
715 static_cast<uint32_t>(sceneColorHeight)}};
716 cb.beginRenderPass(resume, vk::SubpassContents::eInline);
717 source.color.beginColorAttachment();
718 source.depth.beginDepthAttachment();
719 sceneColorPassOpen = true;
720 completedSceneColorSlot = snapshotIndex;
721 sceneColorHistoryValid = true;
723}
724
725void Graphics::setMesh3DEnv(Texture *cube, float intensity) {
726 mesh3dEnvTexture = cube;
727 mesh3dEnvIntensity = intensity < 0.f ? 0.f : intensity;
728 if (!cube) mesh3dEnvIntensity = 0.f;
729}
730
731void Graphics::setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent) {
732 mesh3dEnvProbeCenter = center;
733 mesh3dEnvProbeExtent = glm::max(extent, glm::vec3(0.f));
734 mesh3dFrameUbo.envProbeCenter = glm::vec4(mesh3dEnvProbeCenter, 1.f);
735 mesh3dFrameUbo.envProbeExtent = glm::vec4(mesh3dEnvProbeExtent, 0.f);
736}
737
739 mesh3dReflectionProbes = upload;
740}
741
742void Graphics::setMesh3DShadows(const ShadowUpload &upload) { mesh3dShadows = upload; }
743
744void Graphics::setMesh3DShadowReceive(bool receive) { mesh3dShadowReceive = receive; }
745
747 mesh3dSkinInfluenceLimit = static_cast<int>(count);
748}
749
750void Graphics::beginShadowPass(int cascadeIndex) {
751 ASSERT(initialized);
752 // Recreate when scheme map size changes (dynamic shadow resolution).
753 createShadowResources();
754 if (cascadeIndex < 0 || cascadeIndex >= ShadowConfig::kTotalLayers) {
755 throw Exception("beginShadowPass: cascadeIndex out of range");
756 }
757 shadowPassCascade = cascadeIndex;
758 shadowPassDraws.clear();
759}
760
761void Graphics::drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided) {
762 if (shadowPassCascade < 0) throw Exception("drawMeshShadow: call beginShadowPass first");
763 if (!mesh || !mesh->gpuHandle) throw Exception("drawMeshShadow: null mesh");
764 ShadowDraw d;
765 d.mesh = mesh;
766 d.mvp = lightMVP;
767 d.doubleSided = doubleSided;
768 prepareSkinPass(mesh, nullptr, lightMVP, glm::mat4(1.f), glm::vec4(0.f), d.skinSet,
769 d.skinUboOffset);
770 shadowPassDraws.push_back(d);
771}
772
773void Graphics::drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo,
774 bool doubleSided, float lodWeight, bool lodFadeReverse,
775 bool lodDither) {
776 if (shadowPassCascade < 0) throw Exception("drawMeshShadowAlpha: call beginShadowPass first");
777 if (!mesh || !mesh->gpuHandle) throw Exception("drawMeshShadowAlpha: null mesh");
778 ShadowDraw d;
779 d.mesh = mesh;
780 d.mvp = lightMVP;
781 d.albedo = albedo;
782 d.alphaTest = true;
783 d.doubleSided = doubleSided;
784 d.lodFade = glm::vec4(std::clamp(lodWeight, 0.f, 1.f), lodFadeReverse ? 1.f : 0.f,
785 lodDither ? 1.f : 0.f, 0.f);
786 prepareSkinPass(mesh, albedo, lightMVP, glm::mat4(1.f), d.lodFade, d.skinSet,
787 d.skinUboOffset);
788 shadowPassDraws.push_back(d);
789}
790
792 if (shadowPassCascade < 0) throw Exception("endShadowPass: no active shadow pass");
793 if (!shadowPipeline || !shadowRenderPass) {
794 shadowPassCascade = -1;
795 shadowPassDraws.clear();
796 return;
797 }
798 const int cascade = shadowPassCascade;
799 shadowCascadeDraws[cascade] = std::move(shadowPassDraws);
800 shadowPassDraws.clear();
801 shadowPassCascade = -1;
802 shadowPendingMask |= (1u << cascade);
803 // GPU work is recorded into the swapchain command buffer in
804 // beginSwapchainRenderPass() so it shares the frame's submit and uses the
805 // ping-pong copy for this frame slot.
806}
807
809 ASSERT(initialized);
810 if (!initialized) throw Exception("beginGBufferPass: graphics not initialized");
811 if (w <= 0 || h <= 0) throw Exception("beginGBufferPass: invalid size");
812 if (!texSetLayout || !descriptorPool)
813 throw Exception("beginGBufferPass: textured descriptor layout not ready");
814 createGBufferResources(w, h);
815 gbufferPassActive = true;
816 gbufferPassDraws.clear();
817}
818
819void Graphics::drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
820 Texture *albedo, float tintR, float tintG, float tintB, float motionX, float motionY,
821 float roughness, float metallic, float tintA) {
822 if (!gbufferPassActive) throw Exception("drawMeshGBuffer: call beginGBufferPass first");
823 if (!mesh || !mesh->gpuHandle) throw Exception("drawMeshGBuffer: null mesh");
824 GBufferDraw d{};
825 d.mesh = mesh;
826 d.albedo = albedo;
827 d.push.mvp = mvp;
828 const glm::mat3 normal = glm::transpose(glm::inverse(glm::mat3(model)));
829 d.push.modelR0 = glm::vec4(normal[0][0], normal[1][0], normal[2][0], 0.f);
830 d.push.modelR1 = glm::vec4(normal[0][1], normal[1][1], normal[2][1], 0.f);
831 d.push.modelR2 = glm::vec4(normal[0][2], normal[1][2], normal[2][2], 0.f);
832 auto u6 = [](float x) -> uint32_t {
833 return uint32_t(std::lround(std::clamp(x, 0.f, 1.f) * 63.f));
834 };
835 // Phase B: tint RGB6 | rough7 | metal7. Payload exceeds the 24-bit exact
836 // integer range of float, so bit-cast through the push constant (shader
837 // reads floatBitsToUint). Motion stays numeric (≤24 bits).
838 const uint32_t rough7 = uint32_t(std::lround(std::clamp(roughness, 0.f, 1.f) * 127.f));
839 const uint32_t metal7 = uint32_t(std::lround(std::clamp(metallic, 0.f, 1.f) * 127.f));
840 const uint32_t packedTint = u6(tintR) | (u6(tintG) << 6) | (u6(tintB) << 12) | (rough7 << 18) | (metal7 << 25);
841 auto motion12 = [](float value) {
842 return uint32_t(std::lround(std::clamp(value, -1.f, 1.f) * 2047.f)) + 2047u;
843 };
844 const uint32_t packedMotion = motion12(motionX) | (motion12(motionY) << 12);
845 d.push.clip = glm::vec4(nearZ, farZ, std::bit_cast<float>(packedTint), float(packedMotion));
846 if (pbrSurface_) {
847 d.pbrClip = {nearZ, farZ, motionX, motionY};
848 d.pbrFactors = {metallic, roughness};
849 drawPbrMesh(mesh, model, Color(tintR, tintG, tintB, tintA), &d);
850 } else {
851 prepareSkinPass(mesh, albedo, mvp, model, d.push.clip, d.skinSet, d.skinUboOffset);
852 }
853 gbufferPassDraws.push_back(d);
854}
855
856void Graphics::drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ,
857 Texture *albedo, float tintR, float tintG, float tintB, float motionX,
858 float motionY, float roughness, float metallic, float tintA) {
859 if (!gbufferPassActive) throw Exception("drawMeshGBufferAlpha: call beginGBufferPass first");
860 if (!mesh || !mesh->gpuHandle) throw Exception("drawMeshGBufferAlpha: null mesh");
861 GBufferDraw d{};
862 d.mesh = mesh;
863 d.albedo = albedo;
864 d.alphaTest = true;
865 d.push.mvp = mvp;
866 const glm::mat3 normal = glm::transpose(glm::inverse(glm::mat3(model)));
867 d.push.modelR0 = glm::vec4(normal[0][0], normal[1][0], normal[2][0], 0.f);
868 d.push.modelR1 = glm::vec4(normal[0][1], normal[1][1], normal[2][1], 0.f);
869 d.push.modelR2 = glm::vec4(normal[0][2], normal[1][2], normal[2][2], 0.f);
870 auto u6 = [](float x) -> uint32_t {
871 return uint32_t(std::lround(std::clamp(x, 0.f, 1.f) * 63.f));
872 };
873 const uint32_t rough7 = uint32_t(std::lround(std::clamp(roughness, 0.f, 1.f) * 127.f));
874 const uint32_t metal7 = uint32_t(std::lround(std::clamp(metallic, 0.f, 1.f) * 127.f));
875 const uint32_t packedTint = u6(tintR) | (u6(tintG) << 6) | (u6(tintB) << 12) | (rough7 << 18) | (metal7 << 25);
876 auto motion12 = [](float value) {
877 return uint32_t(std::lround(std::clamp(value, -1.f, 1.f) * 2047.f)) + 2047u;
878 };
879 const uint32_t packedMotion = motion12(motionX) | (motion12(motionY) << 12);
880 d.push.clip = glm::vec4(nearZ, farZ, std::bit_cast<float>(packedTint), float(packedMotion));
881 if (pbrSurface_) {
882 d.pbrClip = {nearZ, farZ, motionX, motionY};
883 d.pbrFactors = {metallic, roughness};
884 drawPbrMesh(mesh, model, Color(tintR, tintG, tintB, tintA), &d);
885 } else {
886 prepareSkinPass(mesh, albedo, mvp, model, d.push.clip, d.skinSet, d.skinUboOffset);
887 }
888 gbufferPassDraws.push_back(d);
889}
890
892 if (!gbufferPassActive) throw Exception("endGBufferPass: no active gbuffer pass");
893 gbufferPassActive = false;
894
895 auto *slot = currentGBufferSlot();
896 if (!gbufferPipeline || !gbufferRenderPass || !slot || !slot->framebuffer) {
897 gbufferPassDraws.clear();
898 gbufferPending = false;
899 if (RenderControl* rc = getRenderControl()) rc->getGBuffer()->clear();
900 return;
901 }
902
903 gbufferPending = true;
904 if (RenderControl* rc = getRenderControl()) {
905 rc->getGBuffer()->setTargets(gbufferWidth, gbufferHeight, &slot->depthColorTex, &slot->normalTex,
906 &slot->albedoTex, &slot->depthTex, &slot->pbrParamsTex, &slot->emissiveTex);
907 }
908}
909
910void Graphics::ensureDecalPlaceholders() {
911 if (decalFlatAlbedo) return;
912 const uint8_t transparent[4] = {0, 0, 0, 0};
913 const uint8_t flatNormal[4] = {128, 128, 255, 255};
914 const uint8_t neutralParams[4] = {128, 128, 0, 255};
915 decalFlatAlbedo = newTexture(1, 1, transparent);
916 decalFlatNormal = newTexture(1, 1, flatNormal);
917 decalFlatParams = newTexture(1, 1, neutralParams);
918}
919
921 ASSERT(initialized);
922 if (!initialized) throw Exception("beginDecalPass: graphics not initialized");
923 if (w <= 0 || h <= 0) throw Exception("beginDecalPass: invalid size");
924 if (!texSetLayout || !descriptorPool)
925 throw Exception("beginDecalPass: textured descriptor layout not ready");
926 createDecalResources(w, h);
927 ensureDecalPlaceholders();
928 decalPassActive = true;
929 decalPassDraws.clear();
930}
931
932void Graphics::setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) {
933 decalViewProj = viewProj;
934 decalNear = nearZ > 1e-4f ? nearZ : 0.1f;
935 decalFar = farZ > decalNear ? farZ : decalNear + 1.f;
936}
937
939 Texture *params, const float uvRect[4], float fade,
940 float normalStrength, float roughnessStrength, float metalStrength,
941 float emissiveStrength, int blendMode, int projectionMode,
942 float blendSharpness, float parallaxScale, float parallaxMinLayers,
943 float parallaxMaxLayers, float edgeFadeWidth) {
944 if (!decalPassActive) throw Exception("drawDecal: call beginDecalPass first");
945 DecalDraw d{};
946 d.model = model;
947 d.albedo = albedo;
948 d.normal = normal;
949 d.params = params;
950 if (uvRect) {
951 for (int i = 0; i < 4; ++i) d.uvRect[i] = uvRect[i];
952 }
953 d.fade = fade;
954 d.normalStrength = normalStrength;
955 d.roughnessStrength = roughnessStrength;
956 d.metalStrength = metalStrength;
957 d.emissiveStrength = emissiveStrength;
958 d.blendMode = blendMode == 1 ? 1 : 0;
959 d.projectionMode = std::clamp(projectionMode, 0, 3);
960 d.blendSharpness = blendSharpness > 0.f ? blendSharpness : 4.f;
961 d.parallaxScale = std::clamp(parallaxScale, 0.f, 1.f);
962 d.parallaxMinLayers = std::clamp(parallaxMinLayers, 1.f, 64.f);
963 d.parallaxMaxLayers = std::clamp(parallaxMaxLayers, d.parallaxMinLayers, 64.f);
964 d.edgeFadeWidth = std::clamp(edgeFadeWidth, 0.f, 0.49f);
965 if (decalPassDraws.size() >= kMaxDecalInstances) return; // SSBO capacity guard
966 decalPassDraws.push_back(d);
967}
968
970 if (!decalPassActive) throw Exception("endDecalPass: no active decal pass");
971 decalPassActive = false;
972 auto *slot = currentDecalSlot();
973 if (!decalPipeline || !decalRenderPass || !slot || !slot->framebuffer) {
974 decalPassDraws.clear();
975 decalPending = false;
976 return;
977 }
978 decalPending = true;
979}
980
981void Graphics::recordDecalPass() {
982 if (!decalPending) return;
983 decalPending = false;
984 auto *slot = currentDecalSlot();
985 if (!slot || !decalPipeline || !decalRenderPass || !slot->framebuffer) {
986 decalPassDraws.clear();
987 return;
988 }
989 auto *gslot = currentGBufferSlot();
990 if (!gslot) {
991 decalPassDraws.clear();
992 return;
993 }
994
995 auto &cb = currentPresentCb();
996 recordDecalPassInto(cb, *slot, *gslot);
997}
998
999void Graphics::recordDecalPassInto(vk::CommandBuffer cb, DecalSlot &slot, GBufferSlot &gslot) {
1000 const uint32_t w = uint32_t(decalWidth);
1001 const uint32_t h = uint32_t(decalHeight);
1002 if (w == 0 || h == 0) {
1003 decalPassDraws.clear();
1004 return;
1005 }
1006
1007 DecalCameraUBO cam{};
1008 cam.viewProj = decalViewProj;
1009 cam.invViewProj = glm::inverse(decalViewProj);
1010 cam.nearFarTexel =
1011 glm::vec4(decalNear, decalFar, 1.f / float(w), 1.f / float(h));
1012 updateRingLocal(slot.cameraUbo, 0, &cam, sizeof(cam));
1013
1014 slot.albedo.beginColorAttachment();
1015 slot.normal.beginColorAttachment();
1016 slot.params.beginColorAttachment();
1017 std::array<vk::ClearValue, 3> clears{};
1018 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1019 clears[1].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1020 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
1021 vk::RenderPassBeginInfo rpBegin{};
1022 rpBegin.renderPass = decalRenderPass;
1023 rpBegin.framebuffer = slot.framebuffer;
1024 rpBegin.renderArea = vk::Rect2D{{0, 0}, {w, h}};
1025 rpBegin.clearValueCount = uint32_t(clears.size());
1026 rpBegin.pClearValues = clears.data();
1027 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
1028 setViewportAndScissor(cb, w, h);
1029 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, decalPipeline);
1030 decalLayerFresh = true;
1031
1032 for (const auto &d : decalPassDraws) {
1033 GpuTexture *gpuAlb = d.albedo && d.albedo->gpuHandle
1034 ? static_cast<GpuTexture *>(d.albedo->gpuHandle)
1035 : static_cast<GpuTexture *>(decalFlatAlbedo->gpuHandle);
1036 GpuTexture *gpuNrm = d.normal && d.normal->gpuHandle
1037 ? static_cast<GpuTexture *>(d.normal->gpuHandle)
1038 : static_cast<GpuTexture *>(decalFlatNormal->gpuHandle);
1039 GpuTexture *gpuPrm = d.params && d.params->gpuHandle
1040 ? static_cast<GpuTexture *>(d.params->gpuHandle)
1041 : static_cast<GpuTexture *>(decalFlatParams->gpuHandle);
1042 DecalInstanceData inst{};
1043 inst.model = d.model;
1044 inst.uvRect = glm::vec4(d.uvRect[0], d.uvRect[1], d.uvRect[2], d.uvRect[3]);
1045 inst.fadeParams =
1046 glm::vec4(d.fade, d.normalStrength, d.roughnessStrength, d.metalStrength);
1047 inst.extraParams = glm::vec4(d.emissiveStrength, float(d.blendMode),
1048 float(d.projectionMode), d.blendSharpness);
1049 inst.surfaceParams =
1050 glm::vec4(d.parallaxScale, d.parallaxMinLayers, d.parallaxMaxLayers, d.edgeFadeWidth);
1051 const vkb::BoundSet set = decalSetFor(slot, gpuAlb, gpuNrm, gpuPrm, &gslot.depthGpu,
1052 &gslot.normalGpu);
1053 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, decalPipelineLayout, 0, 1,
1054 set.ptr(), 0, nullptr);
1055 cb.pushConstants(decalPipelineLayout,
1056 vk::ShaderStageFlagBits::eVertex |
1057 vk::ShaderStageFlagBits::eFragment,
1058 0, sizeof(inst), &inst);
1059 cb.draw(3, 1, 0, 0);
1060 }
1061 decalPassDraws.clear();
1062 cb.endRenderPass();
1063 slot.albedo.endSampledLayout();
1064 slot.normal.endSampledLayout();
1065 slot.params.endSampledLayout();
1066}
1067
1068void Graphics::ensureDefaultEnvCubemap() {
1069 if (defaultEnvCubemap) return;
1070 const uint8_t black[4] = {0, 0, 0, 255};
1071 std::vector<uint8_t> faces(6u * 4u);
1072 for (int i = 0; i < 6; ++i) {
1073 faces[size_t(i) * 4u + 0] = black[0];
1074 faces[size_t(i) * 4u + 1] = black[1];
1075 faces[size_t(i) * 4u + 2] = black[2];
1076 faces[size_t(i) * 4u + 3] = black[3];
1077 }
1078 defaultEnvCubemap = newCubemap(1, faces.data());
1079}
1080
1082 mesh3dMetallic = metallic;
1083 mesh3dRoughness = roughness;
1084 mesh3dFrameUbo.ambient.w = metallic;
1085 mesh3dFrameUbo.cameraPos.w = roughness;
1086}
1087
1089 bool doubleSided, float alphaCutoff,
1090 const std::string &alphaTechnique) {
1091 mesh3dSurfaceMode = mode;
1092 mesh3dSurfaceBlend = blend;
1093 mesh3dSurfaceDepthWrite = depthWrite;
1094 mesh3dSurfaceDoubleSided = doubleSided;
1095 mesh3dAlphaCutoff = std::clamp(alphaCutoff, 0.f, 1.f);
1096 mesh3dAlphaTechnique = alphaTechnique;
1097}
1098
1099void Graphics::setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount) {
1100 mesh3dTexBombScale = cellScale > 1e-3f ? cellScale : 1e-3f;
1101 mesh3dTexBombStrength = strength < 0.f ? 0.f : (strength > 1.f ? 1.f : strength);
1102 mesh3dTexBombRot = rotAmount < 0.f ? 0.f : (rotAmount > 1.f ? 1.f : rotAmount);
1103 mesh3dFrameUbo.texBomb =
1104 glm::vec4(mesh3dTexBombScale, mesh3dTexBombStrength, mesh3dTexBombRot, 0.f);
1105}
1106
1107void Graphics::setMesh3DParallax(float scale, float minLayers, float maxLayers) {
1108 mesh3dParallaxScale = scale < 0.f ? 0.f : (scale > 0.25f ? 0.25f : scale);
1109 float minL = minLayers < 1.f ? 1.f : minLayers;
1110 float maxL = maxLayers < minL ? minL : maxLayers;
1111 if (maxL > 64.f) maxL = 64.f;
1112 mesh3dParallaxMinLayers = minL;
1113 mesh3dParallaxMaxLayers = maxL;
1114 mesh3dFrameUbo.parallax =
1115 glm::vec4(mesh3dParallaxScale, mesh3dParallaxMinLayers, mesh3dParallaxMaxLayers, 0.f);
1116}
1117
1118void Graphics::setMesh3DLodDither(float weight, bool reverse, bool enabled) {
1119 mesh3dLodFade = glm::vec4(std::clamp(weight, 0.f, 1.f), reverse ? 1.f : 0.f,
1120 enabled ? 1.f : 0.f, 0.f);
1121 mesh3dFrameUbo.lodFade = mesh3dLodFade;
1122}
1123
1125 mesh3dLighting = pack;
1126 mesh3dFrameUbo.ambient = glm::vec4(glm::vec3(pack.ambient), mesh3dMetallic); const int n = std::max(0, std::min(pack.count, Lighting3DPack::kMaxLights));
1127 for (size_t i = 0; i < pack.diffuseProbeSh.size(); ++i)
1128 mesh3dFrameUbo.diffuseProbeSh[i] = pack.diffuseProbeSh[i];
1129 mesh3dFrameUbo.diffuseProbeInfo.x = pack.diffuseProbeShEnabled ? 1.f : 0.f;
1130 for (size_t i = 0; i < pack.diffuseVolumePosition.size(); ++i) {
1131 mesh3dFrameUbo.diffuseVolumePosition[i] = pack.diffuseVolumePosition[i];
1132 mesh3dFrameUbo.diffuseVolumeExtent[i] = pack.diffuseVolumeExtent[i];
1133 }
1134 for (size_t i = 0; i < pack.diffuseVolumeSh.size(); ++i)
1135 mesh3dFrameUbo.diffuseVolumeSh[i] = pack.diffuseVolumeSh[i];
1136 mesh3dFrameUbo.diffuseVolumeInfo.x = static_cast<float>(pack.diffuseVolumeProbeCount);
1137 mesh3dFrameUbo.diffuseVolumeInfo.y = pack.diffuseVolumeTrilinearCell ? 1.f : 0.f;
1138 mesh3dFrameUbo.lightDir.w = float(n);
1139 int dirI = -1;
1140 for (int i = 0; i < n; ++i) {
1141 if (pack.lights[i].posRadius.w <= 0.f) {
1142 dirI = i;
1143 break;
1144 }
1145 }
1146 if (dirI >= 0) {
1147 glm::vec3 d(pack.lights[dirI].posRadius);
1148 if (glm::length(d) < 1e-6f) d = glm::vec3(0.f, 1.f, 0.f);
1149 else d = glm::normalize(d);
1150 mesh3dFrameUbo.lightDir = glm::vec4(d, float(n));
1151 mesh3dFrameUbo.lightColor =
1152 glm::vec4(glm::vec3(pack.lights[dirI].color), mesh3dFrameUbo.lightColor.w);
1153 } else {
1154 // No directional: zero the legacy primary slot. mesh3d.frag always shades it.
1155 mesh3dFrameUbo.lightDir = glm::vec4(0.f, 1.f, 0.f, float(n));
1156 mesh3dFrameUbo.lightColor =
1157 glm::vec4(0.f, 0.f, 0.f, mesh3dFrameUbo.lightColor.w);
1158 }
1159}
1160
1161void Graphics::setCloudShadows(float strength, float worldCell, float time, float windSpeed,
1162 float windAngle, float coverage, float detail) {
1163 mesh3dFrameUbo.cloud = glm::vec4(std::clamp(strength, 0.f, 1.f), std::max(worldCell, 1e-4f),
1164 time, 0.f);
1165 mesh3dFrameUbo.cloudWind = glm::vec4(std::cos(windAngle) * windSpeed,
1166 std::sin(windAngle) * windSpeed,
1167 std::clamp(coverage, 0.f, 1.f), std::clamp(detail, 0.f, 1.f));
1168}
1169
1170void Graphics::ensureFlatNormalTexture3D() {
1171 if (flatNormalTexture3D) return;
1172 const uint8_t px[4] = {128, 128, 255, 255};
1173 flatNormalTexture3D = newTexture(1, 1, px);
1174}
1175
1176void Graphics::ensureFlatHeightTexture3D() {
1177 if (flatHeightTexture3D) return;
1178 // Mid-gray height: no relief when scale>0 without a real height map.
1179 const uint8_t px[4] = {128, 128, 128, 255};
1180 flatHeightTexture3D = newTexture(1, 1, px);
1181}
1182
1183vkb::BoundSet Graphics::mesh3dSetFor(GpuTexture *gpuTex, GpuTexture *normalTex, GpuTexture *envTex,
1184 GpuTexture *heightTex, GpuTexture *depthTex, GpuTexture *sceneColorTex,
1185 GpuTexture *decalAlbedo, GpuTexture *decalNormal, GpuTexture *decalParams,
1186 Mesh3dFrameSlots &fslots, vk::DescriptorSetLayout resourceLayout) {
1187 ASSERT(gpuTex != nullptr);
1188 ASSERT(normalTex != nullptr);
1189 ASSERT(envTex != nullptr);
1190 ASSERT(heightTex != nullptr);
1191 ASSERT(sceneColorTex != nullptr);
1192 ASSERT(decalAlbedo != nullptr);
1193 ASSERT(decalNormal != nullptr);
1194 ASSERT(decalParams != nullptr);
1195 ASSERT(currentShadowArrayView());
1196 ASSERT(fslots.uboRing.buffer);
1197 ASSERT(fslots.shadowRing.buffer);
1198
1199 auto probeTexture = [&](int index) -> GpuTexture * {
1200 if (index < mesh3dReflectionProbes.count) {
1201 Texture *texture = mesh3dReflectionProbes.probes[index].cubemap;
1202 if (texture && texture->gpuHandle) {
1203 auto *gpu = static_cast<GpuTexture *>(texture->gpuHandle);
1204 if (gpu->isCube) return gpu;
1205 }
1206 }
1207 return static_cast<GpuTexture *>(defaultEnvCubemap->gpuHandle);
1208 };
1209 GpuTexture *probe0 = probeTexture(0);
1210 GpuTexture *probe1 = probeTexture(1);
1211 Mesh3dSetKey key{gpuTex, normalTex, envTex, probe0, probe1, heightTex, depthTex, sceneColorTex,
1212 decalAlbedo, decalNormal, decalParams};
1213 key.paletteSlot = fslots.activePalette;
1214 key.resourceProgram = bool(resourceLayout);
1215 if (fslots.palettes.empty()) uploadSkinPalette(nullptr, fslots);
1216 auto it = fslots.sets.find(key);
1217 if (it != fslots.sets.end()) return it->second;
1218
1219 vk::DescriptorSetAllocateInfo alloc{};
1220 alloc.descriptorPool = descriptorPool;
1221 alloc.descriptorSetCount = 1;
1222 alloc.pSetLayouts = resourceLayout ? &resourceLayout : &mesh3dSetLayout;
1223 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
1224
1225 if (resourceLayout) {
1226 vkb::DescriptorSetUpdater updater(3, 2, 0);
1227 updater.beginDescriptorSet(unbound)
1228 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
1229 .buffer(fslots.uboRing.buffer, 0, sizeof(Mesh3DUBO))
1230 .beginBuffers(4, 0, vk::DescriptorType::eUniformBufferDynamic)
1231 .buffer(fslots.shadowRing.buffer, 0, sizeof(ShadowUBO))
1232 .beginBuffers(21, 0, vk::DescriptorType::eStorageBuffer)
1233 .buffer(fslots.palettes[fslots.activePalette].buffer, 0, fslots.palettes[fslots.activePalette].capacity)
1234 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1235 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
1236 .beginImages(18, 0, vk::DescriptorType::eCombinedImageSampler)
1237 .image(vkb::SampledImage::forLaterSample(sceneColorTex->sampler, sceneColorTex->imageView()))
1238 .update(device.instance);
1239 auto bound = std::move(unbound).publish();
1240 fslots.sets.emplace(key, bound);
1241 return bound;
1242 }
1243 vkb::DescriptorSetUpdater updater(16, 16, 0);
1244 updater.beginDescriptorSet(unbound)
1245 .beginBuffers(0, 0, vk::DescriptorType::eUniformBufferDynamic)
1246 .buffer(fslots.uboRing.buffer, 0, sizeof(Mesh3DUBO))
1247 .beginBuffers(21, 0, vk::DescriptorType::eStorageBuffer)
1248 .buffer(fslots.palettes[fslots.activePalette].buffer, 0, fslots.palettes[fslots.activePalette].capacity)
1249 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1250 .image(vkb::SampledImage::forLaterSample(gpuTex->sampler, gpuTex->imageView()))
1251 .beginImages(2, 0, vk::DescriptorType::eCombinedImageSampler)
1252 .image(vkb::SampledImage::forLaterSample(normalTex->sampler, normalTex->imageView()))
1253 .beginImages(3, 0, vk::DescriptorType::eCombinedImageSampler)
1254 .image(vkb::SampledImage::forLaterSample(envTex->sampler, envTex->imageView()))
1255 .beginBuffers(4, 0, vk::DescriptorType::eUniformBufferDynamic)
1256 .buffer(fslots.shadowRing.buffer, 0, sizeof(ShadowUBO))
1257 .beginImages(5, 0, vk::DescriptorType::eCombinedImageSampler)
1258 .image(vkb::SampledImage::forLaterSample(shadowSampler, currentShadowArrayView()))
1259 .beginImages(6, 0, vk::DescriptorType::eCombinedImageSampler)
1260 .image(vkb::SampledImage::forLaterSample(heightTex->sampler, heightTex->imageView()))
1261 .beginImages(7, 0, vk::DescriptorType::eCombinedImageSampler)
1262 .image(vkb::SampledImage::forLaterSample(depthTex->sampler, depthTex->imageView()))
1263 .beginImages(8, 0, vk::DescriptorType::eCombinedImageSampler)
1264 .image(vkb::SampledImage::forLaterSample(decalAlbedo->sampler, decalAlbedo->imageView()))
1265 .beginImages(9, 0, vk::DescriptorType::eCombinedImageSampler)
1266 .image(vkb::SampledImage::forLaterSample(decalNormal->sampler, decalNormal->imageView()))
1267 .beginImages(10, 0, vk::DescriptorType::eCombinedImageSampler)
1268 .image(vkb::SampledImage::forLaterSample(decalParams->sampler, decalParams->imageView()))
1269 .beginImages(16, 0, vk::DescriptorType::eCombinedImageSampler)
1270 .image(vkb::SampledImage::forLaterSample(probe0->sampler, probe0->imageView()))
1271 .beginImages(17, 0, vk::DescriptorType::eCombinedImageSampler)
1272 .image(vkb::SampledImage::forLaterSample(probe1->sampler, probe1->imageView()))
1273 .beginImages(18, 0, vk::DescriptorType::eCombinedImageSampler)
1274 .image(vkb::SampledImage::forLaterSample(sceneColorTex->sampler, sceneColorTex->imageView()))
1275 .beginImages(20, 0, vk::DescriptorType::eCombinedImageSampler)
1276 .image(vkb::SampledImage::forLaterSample(shadowRawSampler, currentShadowArrayView()))
1277 .update(device.instance);
1278
1279 vkb::BoundSet bound = std::move(unbound).publish();
1280 fslots.sets.emplace(key, bound);
1281 return bound;
1282}
1283
1285 mesh3dFrameUbo.mvp = viewProj;
1286}
1287
1288void Graphics::setMesh3DView(const glm::mat4 &view) {
1289 mesh3dFrameUbo.view = view;
1290}
1291
1292void Graphics::setMesh3DClip(float nearZ, float farZ) {
1293 const float n = nearZ > 1e-4f ? nearZ : 0.1f;
1294 const float f = farZ > n ? farZ : n + 1.f;
1295 mesh3dFrameUbo.clipInfo = glm::vec4(n, f, mesh3dFrameUbo.clipInfo.z, mesh3dFrameUbo.clipInfo.w);
1296 mesh3dClustered.clipInfo.x = n;
1297 mesh3dClustered.clipInfo.y = f;
1298}
1299
1300} // namespace eve::graphics::vulkan
double x
float w
Definition AnimClip.cpp:738
float ao
float normalStrength
graphics::Texture * albedo
SQObjectPtr key
Definition ECS.cpp:155
float strength
vk::ShaderModule vert
vk::ShaderModule frag
glm::mat4 mvp
glm::vec3 n
Definition Grass.cpp:63
std::vector< std::uint32_t > indices
float blend
int h
std::vector< Colorf > px
Range range
std::array< float, 3 > scale
ActionGuidePack pack
std::string coverage
Snapshot snapshot
std::vector< RecipeParam > params
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
float roughness
bool doubleSided
Texture * normal
float alphaCutoff
float metallic
OceanMeshSettings mesh
std::shared_ptr< OceanGpuSpectrum > gpu
ssq::Object frame
glm::dvec2 center
OceanSprayView view
Texture * texture
float f
std::vector< ParticleBakeMaterial > bindings
Object::Ptr value
float d
int detail
std::string slot
Local-probe upload record kept off the high-fanout IGraphics3D header.
bool lodFadeReverse
glm::vec3 eye
float lodWeight
glm::mat4 viewProj
glm::mat4 model
Value::Array corners
std::string_view source
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
int count
V3 dir
Definition TreeMesh.cpp:151
std::uint32_t depth
const AssetImportLimits & limits
double weight
uint32_t index
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Canvas public API.
Definition Canvas.h:17
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
Mesh3DSceneColorCaptureStatus
Observable result of requesting a same-frame mesh SceneColor snapshot.
Definition Graphics.h:1227
RenderControl * getRenderControl()
Shared compilable 3D render control (features → pass list + GBuffer). Owned by Graphics; valid for th...
Definition Graphics.cpp:279
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
Declarative, compilable 3D render control.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
void setMesh3DReflectionProbes(const ReflectionProbeUpload &upload) override
Sets the mesh 3 d reflection probes.
void beginShadowPass(int cascadeIndex) override
Begins shadow pass.
void begin3DFrame() override
Begins 3 d frame.
void setMesh3DParallax(float scale, float minLayers=8.f, float maxLayers=32.f) override
Sets the mesh 3 d parallax.
void setCloudShadows(float strength, float worldCell, float time, float windSpeed, float windAngle, float coverage, float detail) override
Sets the cloud shadows.
void drawMeshShadowAlpha(Mesh *mesh, const glm::mat4 &lightMVP, Texture *albedo=nullptr, bool doubleSided=true, float lodWeight=1.f, bool lodFadeReverse=false, bool lodDither=false) override
Draws mesh shadow alpha.
void drawVoxelFaceInstances(const uint32_t *packed, int count, float originX, float originY, float originZ, const std::string &faceDir, Texture *atlas, int tilesPerRow=16, const uint32_t *ao=nullptr) override
Draws voxel face instances.
void end3DFrameToCanvas() override
Ends 3 d frame to canvas.
void endDecalPass() override
Ends decal pass.
void setMesh3DShadowReceive(bool receive) override
Sets the mesh 3 d shadow receive.
void setMesh3DLighting(const Lighting3DPack &pack) override
Sets the mesh 3 d lighting.
void drawMeshGBufferAlpha(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer alpha.
void setMesh3DEnv(Texture *cube, float intensity) override
Sets the mesh 3 d env.
Mesh3DSceneColorCaptureStatus captureMesh3DSceneColor() override
Capture mesh 3 d scene color.
void setDecalCamera(const glm::mat4 &viewProj, float nearZ, float farZ) override
Sets the decal camera.
void setMesh3DLodDither(float weight, bool reverse, bool enabled) override
Sets the mesh 3 d lod dither.
void waitForSharedGpuResources()
Block until all in-flight GPU work (all frames) has completed.
Definition Graphics.cpp:943
bool isCanvasActive() const override
True when canvas active.
void endGBufferPass() override
Ends g buffer pass.
void endShadowPass() override
Ends shadow pass.
void setMesh3DTexCellBomb(float cellScale, float strength, float rotAmount=1.f) override
Sets the mesh 3 d tex cell bomb.
void drawDecal(const glm::mat4 &model, Texture *albedo, Texture *normal, Texture *params, const float uvRect[4], float fade, float normalStrength, float roughnessStrength, float metalStrength, float emissiveStrength, int blendMode=0, int projectionMode=0, float blendSharpness=4.f, float parallaxScale=0.f, float parallaxMinLayers=8.f, float parallaxMaxLayers=24.f, float edgeFadeWidth=0.06f) override
Draws decal.
void setMesh3DSurface(SurfaceMode mode, BlendMode blend, bool depthWrite, bool doubleSided, float alphaCutoff, const std::string &alphaTechnique="cutoff") override
Sets the mesh 3 d surface.
void setMesh3DCameraPos(const glm::vec3 &eye) override
Sets the mesh 3 d camera pos.
void begin3DFrameToCanvas(Canvas *canvas) override
Begins 3 d frame to canvas.
void setMesh3DSceneColor(Texture *color) override
Sets the mesh 3 d scene color.
void setMesh3DViewProj(const glm::mat4 &viewProj) override
Sets the mesh 3 d view proj.
void drawMeshShadow(Mesh *mesh, const glm::mat4 &lightMVP, bool doubleSided=true) override
Draws mesh shadow.
void setMesh3DShadows(const ShadowUpload &upload) override
Sets the mesh 3 d shadows.
const vkb::BuiltRenderPass & getOffscreen3DRenderPass(bool hdr=false)
Returns the offscreen 3 d render pass.
Definition Graphics.h:1100
void beginGBufferPass(int width, int height) override
Begins g buffer pass.
void setMesh3DLight(const glm::vec3 &dir, const glm::vec3 &color) override
Sets the mesh 3 d light.
void drawMeshGBuffer(Mesh *mesh, const glm::mat4 &mvp, const glm::mat4 &model, float nearZ, float farZ, Texture *albedo=nullptr, float tintR=1.f, float tintG=1.f, float tintB=1.f, float motionX=0.f, float motionY=0.f, float roughness=0.45f, float metallic=0.f, float tintA=1.f) override
Draws mesh g buffer.
void setMesh3DHeightTexture(Texture *height) override
Sets the mesh 3 d height texture.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
void setMesh3DView(const glm::mat4 &view) override
Sets the mesh 3 d view.
void setMesh3DVirtualTexture(bool enabled, int pageCountX, int pageCountY, int atlasSlotsX, int atlasSlotsY, float borderFraction) override
Sets the mesh 3 d virtual texture.
vkb::Device & getDevice()
Returns the device.
Definition Graphics.h:1057
void setMesh3DNormalTexture(Texture *normal) override
Sets the mesh 3 d normal texture.
void setMesh3DClip(float nearZ, float farZ) override
Sets the mesh 3 d clip.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
void setMesh3DSceneDepth(Texture *depth) override
Sets the mesh 3 d scene depth.
void setMesh3DEnvProbe(const glm::vec3 &center, const glm::vec3 &extent) override
Sets the mesh 3 d env probe.
void setMesh3DPackedNormalMask(bool enabled) override
Sets the mesh 3 d packed normal mask.
void setMesh3DMaterial(float metallic, float roughness) override
Sets the mesh 3 d material.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
void setMesh3DSkinInfluenceLimit(SkinInfluenceLimit count) override
Sets the mesh 3 d skin influence limit.
FrameArena & currentFrameArena()
Per-frame arena for the current swapchain frame slot.
void beginDecalPass(int width, int height) override
Begins decal pass.
OffscreenCanvas public API.
Definition Canvas.h:15
vkb::ColorAttachmentImage & colorImage()
Color image.
Definition Canvas.h:50
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
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
SkinInfluenceLimit
Number of strongest vertex influences retained by GPU skinning.
Definition IGraphics3D.h:20
std::vector< int64_t > attrs(const Node &n, const char *key, std::vector< int64_t > fallback)
Attrs.
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
bool enabled
Lighting3DPack public API.
Definition Light.h:171
static constexpr int kMaxLights
Definition Light.h:172
ReflectionProbeUpload public API.
static constexpr int kMapSize
Definition Shadow.h:28
static constexpr int kCascades
Definition Shadow.h:24
static constexpr int kTotalLayers
Definition Shadow.h:27
ShadowUpload public API.
Definition Shadow.h:62
int cascadeMapSizes[ShadowConfig::kCascades]
Per-cascade render viewport edge length (texels); drives shadow pass viewport.
Definition Shadow.h:66
GpuTexture public API.
Definition Graphics.h:264
glm::vec4 diffuseVolumePosition[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:212
glm::vec4 diffuseVolumeExtent[Lighting3DPack::kMaxDiffuseVolumeProbes]
Definition Graphics.h:213
glm::vec4 diffuseVolumeSh[Lighting3DPack::kMaxDiffuseVolumeProbes *9]
Definition Graphics.h:214
glm::vec4 color