载入中...
搜索中...
未找到
Graphics2D.cpp
浏览该文件的文档.
1// Vulkan backend implementation — 2D drawing, textures and batching.
2//
3// Re-split from the merged dev single-TU Graphics.cpp (pure move;
4// dev changes preserved). Shared helpers live in GraphicsInternal.h.
5
6#include "common/Profile.h"
9#include "graphics/Light.h"
17
18#include <SDL2/SDL.h>
19#include <SDL2/SDL_vulkan.h>
20
21#include <algorithm>
22#include <array>
23#include <cmath>
24#include <cstdint>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <functional>
29#include <glm/gtc/packing.hpp>
30#include <stdexcept>
31#include <string>
32#include <vector>
33
34#include "common/Exception.h"
36#include "common/config.h"
38#include "image/Image.h"
39#include "image/ImageData.h"
40#include "zeroerr/assert.h"
41
42#include <memory>
43
44
45#include <assimp/mesh.h>
46#include <assimp/matrix3x3.h>
47#include <assimp/matrix4x4.h>
48#include <assimp/vector3.h>
49#include <glm/gtc/matrix_transform.hpp>
50
51#include "graphics/shaders/textured_vert_spv.inc"
52#include "graphics/shaders/textured_frag_spv.inc"
53#include "graphics/shaders/mesh3d_vert_spv.inc"
54#include "graphics/shaders/mesh3d_frag_spv.inc"
55#include "graphics/shaders/mesh3d_hair_vert_spv.inc"
56#include "graphics/shaders/mesh3d_hair_frag_spv.inc"
58
59namespace eve::graphics::vulkan {
60
61namespace {
62
63void transitionSampledColorForTransfer(vk::CommandBuffer cb, vkb::ColorTarget &image,
64 vk::ImageLayout newLayout) {
65 vk::ImageMemoryBarrier barrier{};
66 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
67 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
68 barrier.oldLayout = image.currentLayout();
69 barrier.newLayout = newLayout;
70 barrier.image = image.image();
71 barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
72 vk::PipelineStageFlags srcStages;
73 vk::PipelineStageFlags dstStages;
74 if (newLayout == vk::ImageLayout::eTransferSrcOptimal) {
75 barrier.srcAccessMask = vk::AccessFlagBits::eShaderRead;
76 barrier.dstAccessMask = vk::AccessFlagBits::eTransferRead;
77 srcStages = vk::PipelineStageFlagBits::eVertexShader |
78 vk::PipelineStageFlagBits::eFragmentShader |
79 vk::PipelineStageFlagBits::eComputeShader;
80 dstStages = vk::PipelineStageFlagBits::eTransfer;
81 } else {
82 barrier.srcAccessMask = vk::AccessFlagBits::eTransferRead;
83 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
84 srcStages = vk::PipelineStageFlagBits::eTransfer;
85 dstStages = vk::PipelineStageFlagBits::eVertexShader |
86 vk::PipelineStageFlagBits::eFragmentShader |
87 vk::PipelineStageFlagBits::eComputeShader;
88 }
89 cb.pipelineBarrier(srcStages, dstStages, {}, 0, nullptr, 0, nullptr, 1, &barrier);
90 image.setCurrentLayout(newLayout);
91}
92
93} // namespace
94
95// Shader helper functions. They used to live in GraphicsInternal.h (which is
96// an anonymous-namespace header copied into every backend TU); only this file
97// uses them, so they are defined here to avoid the per-TU duplication and the
98// header's dependency on the filesystem module.
99namespace {
100
101std::vector<uint32_t> loadSpirvBytes(const void *data, size_t size) {
102 if (!data || size < 4 || (size % 4) != 0)
103 throw Exception("SPIR-V: invalid size %zu", size);
104 const auto *words = static_cast<const uint32_t *>(data);
105 if (words[0] != 0x07230203)
106 throw Exception("SPIR-V: bad magic (expected 0x07230203)");
107 return std::vector<uint32_t>(words, words + size / 4);
108}
109
110std::vector<uint32_t> readSpirvFile(const std::string &path) {
111 auto *fs = filesystem::Filesystem::create();
112 std::unique_ptr<filesystem::FileData> fd(fs->read(path));
113 if (!fd) throw Exception("newShaderFromSpvFile: failed to read '%s'", path.c_str());
114 return loadSpirvBytes(fd->getData(), fd->getSize());
115}
116
121std::vector<uint32_t> compileShaderStage(const std::string &source, const char *stage, GlslStage glslStage) {
122 if (source.empty()) throw Exception("newShader: empty %s GLSL", stage);
123 try {
124 return compileGlslToSpirv(source, glslStage, std::string("eve_shader.") + stage);
125 } catch (const std::exception &error) {
126 // The shared helper throws plain runtime errors (it also runs on CPU
127 // worker threads); wrap them into the engine exception callers expect.
128 throw Exception("newShader: GLSL compile failed for %s:\n%s", stage, error.what());
129 }
130}
131
132} // namespace
133
134void Graphics::ensurePresentCaptureHook() {
135 // Screen readback is recorded inline into the present command buffer (see
136 // flushToSwapchain / abortOpen3DFrame), so the present model must never
137 // get a post-submit hook: drawFrame() waits for this frame's fence
138 // whenever the hook is set, which serializes every frame and erases the
139 // multi-frame overlap we rely on for async rendering.
140 presentModel.after_render_before_present = nullptr;
141}
142
143void Graphics::ensureReadbackSlots() {
144 if (pixelWidth <= 0 || pixelHeight <= 0) return;
145 const size_t bytes = size_t(pixelWidth) * size_t(pixelHeight) * 4;
146 const size_t want = std::max<size_t>(2, frameSlotCount());
147 if (!screenReadbackSlots.empty() && screenReadbackSlots.size() >= want &&
148 screenReadbackBytes == bytes)
149 return;
150 // Recreating the staging ring must never race in-flight copies. Callers
151 // run on the render thread, and a size change implies the swapchain was
152 // rebuilt under waitIdle (rebuildSwapchainIfNeeded / recreate path).
153 for (auto &slot : screenReadbackSlots) {
154 if (slot.mapped) {
155 slot.staging.unmap();
156 slot.mapped = nullptr;
157 }
158 slot.staging.release();
159 }
160 screenReadbackSlots.clear();
161 screenReadbackSlots.resize(want);
162 for (auto &slot : screenReadbackSlots) {
163 slot.staging = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eTransferDst,
164 vk::DeviceSize(bytes),
165 vk::MemoryPropertyFlagBits::eHostVisible |
166 vk::MemoryPropertyFlagBits::eHostCoherent);
167 }
168 screenReadbackBytes = bytes;
169 readbackReady = false;
170 readbackCpuSynced = false;
171 readbackWriteSlot = 0;
172}
173
174bool Graphics::recordSwapchainReadback(vk::CommandBuffer cb) {
175 if (!screenReadbackEnabled || pixelWidth <= 0 || pixelHeight <= 0) return false;
176 if (!presentModel.has_acquired_image) return false;
177 const vk::Format fmt = swapchain.image_format;
178 const bool bgra = (fmt == vk::Format::eB8G8R8A8Unorm || fmt == vk::Format::eB8G8R8A8Srgb);
179 const bool rgba = (fmt == vk::Format::eR8G8B8A8Unorm || fmt == vk::Format::eR8G8B8A8Srgb);
180 if (!bgra && !rgba) return false;
181 readbackBgra = bgra;
182
183 const uint32_t imageIndex = presentModel.acquired_image_index;
184 auto &images = swapchain.get_images();
185 if (imageIndex >= images.size()) return false;
186
187 ensureReadbackSlots();
188 if (screenReadbackSlots.empty()) return false;
189
190 const size_t slot = size_t(presentRecording.slot().index) % screenReadbackSlots.size();
191 readbackWriteSlot = slot;
192 const vk::Image image = images[imageIndex];
193 // Recorded at the end of the present command buffer: the swapchain render
194 // pass has already transitioned the image back to PresentSrcKHR, and the
195 // copy runs in the same submit+present — no extra queue submit, no
196 // waitIdle, no per-frame buffer allocation.
197 detail::recordFrameReadback(cb, image, screenReadbackSlots[slot].staging.buffer,
198 vk::Extent2D{uint32_t(pixelWidth), uint32_t(pixelHeight)},
199 vk::ImageAspectFlagBits::eColor, 0, vk::ImageLayout::ePresentSrcKHR);
200 return true;
201}
202
203void Graphics::syncReadbackCpu() {
204 if (!readbackReady || screenReadbackSlots.empty()) return;
205 if (readbackCpuSynced && !lastFrameRgba.empty()) return;
206 if (readbackWriteSlot >= screenReadbackSlots.size()) return;
207
208 const size_t bytes = screenReadbackBytes;
209 if (bytes == 0) return;
210
211 // The newest copy lives in the present submission of this frame slot; wait
212 // only that slot's fence instead of a device-wide waitIdle.
213 presentModel.waitForFrameSlot(readbackWriteSlot);
214
215 auto &slot = screenReadbackSlots[readbackWriteSlot];
216 if (!slot.mapped)
217 slot.mapped = slot.staging.map();
218
219 lastFrameRgba.resize(bytes);
220 if (readbackBgra) {
221 // BGRA -> RGBA byte swap, two pixels per 64-bit word (masked swap).
222 const size_t words = bytes / 8;
223 const uint64_t *src64 = static_cast<const uint64_t *>(slot.mapped);
224 uint64_t *dst64 = reinterpret_cast<uint64_t *>(lastFrameRgba.data());
225 for (size_t i = 0; i < words; ++i) {
226 const uint64_t v = src64[i];
227 dst64[i] = (v & 0xFF00FF00FF00FF00ull) |
228 ((v & 0x000000FF000000FFull) << 16) |
229 ((v >> 16) & 0x000000FF000000FFull);
230 }
231 for (size_t i = words * 8; i < bytes; i += 4) {
232 const uint32_t v = *reinterpret_cast<const uint32_t *>(
233 static_cast<const uint8_t *>(slot.mapped) + i);
234 const uint32_t out = (v & 0xFF00FF00u) | ((v & 0xFFu) << 16) | ((v >> 16) & 0xFFu);
235 std::memcpy(lastFrameRgba.data() + i, &out, 4);
236 }
237 } else {
238 std::memcpy(lastFrameRgba.data(), slot.mapped, bytes);
239 }
240 readbackCpuSynced = true;
241}
242
243void Graphics::destroyReadbackResources() {
244 destroyFrameCapture();
245 for (auto &slot : screenReadbackSlots) {
246 if (slot.mapped) {
247 slot.staging.unmap();
248 slot.mapped = nullptr;
249 }
250 slot.staging.release();
251 }
252 screenReadbackSlots.clear();
253 screenReadbackBytes = 0;
254 readbackReady = false;
255 readbackCpuSynced = false;
256 hasPresentedFrame = false;
257}
258
260 syncReadbackCpu();
261 if (!hasPresentedFrame || lastFrameRgba.empty())
262 throw Exception("Graphics::newImageData: no presented frame");
263 auto *img = new image::ImageData(pixelWidth, pixelHeight, "RGBA8");
264 std::memcpy(img->getData(), lastFrameRgba.data(), lastFrameRgba.size());
265 return img;
266}
267
269 syncReadbackCpu();
270 if (!hasPresentedFrame || lastFrameRgba.empty())
271 throw Exception("Graphics::getPixel: no presented frame");
272 if (x < 0 || y < 0 || x >= width || y >= height)
273 throw Exception("Graphics::getPixel: out of bounds (%d,%d)", x, y);
274
275 const int pxX = (width > 0) ? int((int64_t(x) * pixelWidth) / width) : x;
276 const int pxY = (height > 0) ? int((int64_t(y) * pixelHeight) / height) : y;
277 const int cx = std::min(std::max(pxX, 0), pixelWidth - 1);
278 const int cy = std::min(std::max(pxY, 0), pixelHeight - 1);
279 const size_t i = (size_t(cy) * size_t(pixelWidth) + size_t(cx)) * 4;
280 float r = lastFrameRgba[i + 0] / 255.f;
281 float g = lastFrameRgba[i + 1] / 255.f;
282 float b = lastFrameRgba[i + 2] / 255.f;
283 float a = lastFrameRgba[i + 3] / 255.f;
284 // If surface ended up sRGB, convert encoded bytes back to linear Color space.
285 const vk::Format fmt = swapchain.image_format;
286 if (fmt == vk::Format::eB8G8R8A8Srgb || fmt == vk::Format::eR8G8B8A8Srgb) {
287 auto toLinear = [](float u) {
288 return (u <= 0.04045f) ? (u / 12.92f) : std::pow((u + 0.055f) / 1.055f, 2.4f);
289 };
290 r = toLinear(r);
291 g = toLinear(g);
292 b = toLinear(b);
293 }
294 return Color(r, g, b, a);
295}
296
297image::ImageData* Graphics::renderEntityIdMask(const std::vector<eve::graphics::EntityIdDraw>& draws,
298 const glm::mat4& viewProj, int maskW, int maskH) {
299 if (!initialized || maskW <= 0 || maskH <= 0) return nullptr;
300 // G-buffer pipeline / render pass are created lazily by createGBufferResources,
301 // so that must run before the availability check.
302 createGBufferResources(maskW, maskH);
303 if (!gbufferPipeline || !gbufferRenderPass) return nullptr;
304 auto *slot = currentGBufferSlot();
305 if (!slot || !slot->framebuffer || !whiteTexture) return nullptr;
306
307 // Render each mesh with a flat idColor into the G-buffer albedo attachment
308 // (location 2) by reusing the G-buffer pipeline (its fragment shader writes
309 // outAlbedo = albedo * tint, so passing a white texture + idColor tint gives
310 // a per-pixel flat entity-ID color).
311 std::vector<GBufferDraw> idDraws;
312 idDraws.reserve(draws.size());
313 auto u8 = [](float x) -> uint32_t { return uint32_t(std::lround(std::clamp(x, 0.f, 1.f) * 255.f)); };
314 for (const auto &d : draws) {
315 if (!d.mesh || !d.mesh->gpuHandle) continue;
316 GBufferDraw gd{};
317 gd.mesh = d.mesh;
318 gd.albedo = whiteTexture;
319 gd.push.mvp = viewProj * d.model;
320 gd.push.modelR0 = glm::vec4(d.model[0][0], d.model[1][0], d.model[2][0], d.model[3][0]);
321 gd.push.modelR1 = glm::vec4(d.model[0][1], d.model[1][1], d.model[2][1], d.model[3][1]);
322 gd.push.modelR2 = glm::vec4(d.model[0][2], d.model[1][2], d.model[2][2], d.model[3][2]);
323 const uint32_t packed =
324 u8(d.idColor.r) | (u8(d.idColor.g) << 8) | (u8(d.idColor.b) << 16) | (u8(d.idColor.a) << 24);
325 // Negative motion selects exact RGBA8 IDs instead of RGB6 material tint packing.
326 gd.push.clip = glm::vec4(0.1f, 100.f, glm::uintBitsToFloat(packed), -1.f);
327 idDraws.push_back(gd);
328 }
329 if (idDraws.empty()) return nullptr;
330
331 const uint32_t w = uint32_t(maskW);
332 const uint32_t h = uint32_t(maskH);
333 const vk::DeviceSize byteSize = vk::DeviceSize(w) * vk::DeviceSize(h) * 4;
334 vkb::GenericBuffer staging(device, vk::BufferUsageFlagBits::eTransferDst, byteSize,
335 vk::MemoryPropertyFlagBits::eHostVisible |
336 vk::MemoryPropertyFlagBits::eHostCoherent);
337
338 vkb::executeImmediately(device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics),
339 [&](vk::CommandBuffer cb) {
340 std::array<vk::ClearValue, 6> clears{};
341 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
342 clears[1].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
343 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
344 clears[3].color = vk::ClearColorValue(std::array<float, 4>{0, 1, 1, 1});
345 clears[4].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
346 clears[5].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
347 vk::RenderPassBeginInfo rpBegin{};
348 rpBegin.renderPass = gbufferRenderPass;
349 rpBegin.framebuffer = slot->framebuffer;
350 rpBegin.renderArea = vk::Rect2D{{0, 0}, {w, h}};
351 rpBegin.clearValueCount = uint32_t(clears.size());
352 rpBegin.pClearValues = clears.data();
353 slot->normal.beginColorAttachment();
354 slot->depthColor.beginColorAttachment();
355 slot->albedo.beginColorAttachment();
356 slot->pbrParams.beginColorAttachment();
357 slot->emissive.beginColorAttachment();
358 slot->depth.beginDepthAttachment();
359 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
360 setViewportAndScissor(cb, w, h);
361 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, gbufferPipeline);
362 for (const auto &d : idDraws) {
363 auto *gpuMesh = static_cast<GpuMesh *>(d.mesh->gpuHandle);
364 if (!gpuMesh) continue;
365 if (whiteTexture && whiteTexture->gpuHandle && texSetLayout) {
366 auto *gpuTex = static_cast<GpuTexture *>(whiteTexture->gpuHandle);
367 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics,
368 gbufferPipelineLayout, 0, 1,
369 gpuTex->descriptorSet.ptr(), 0, nullptr);
370 }
371 cb.pushConstants(gbufferPipelineLayout,
372 vk::ShaderStageFlagBits::eVertex |
373 vk::ShaderStageFlagBits::eFragment,
374 0, sizeof(GBufferPush), &d.push);
375 drawIndexedMesh(cb, *gpuMesh);
376 }
377 cb.endRenderPass();
378 slot->normal.endSampledLayout();
379 slot->depthColor.endSampledLayout();
380 slot->albedo.endSampledLayout();
381 slot->pbrParams.endSampledLayout();
382 slot->emissive.endSampledLayout();
383 slot->depth.endSampledLayout();
384
385 // Copy the albedo attachment (location 2 = ID colors) to CPU.
386 slot->albedo.setLayout(cb, vk::ImageLayout::eTransferSrcOptimal);
387 vk::BufferImageCopy region{};
388 region.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
389 region.imageExtent = vk::Extent3D{w, h, 1};
390 cb.copyImageToBuffer(slot->albedo.image(),
391 vk::ImageLayout::eTransferSrcOptimal, staging.buffer,
392 region);
393 slot->albedo.setLayout(cb, vk::ImageLayout::eShaderReadOnlyOptimal);
394 });
395
396 auto *img = new image::ImageData(int(w), int(h), "RGBA8");
397 void *mapped = staging.map();
398 std::memcpy(img->getData(), mapped, size_t(byteSize));
399 staging.unmap();
400 staging.release();
401
402 // 让 RenderControl 的 GBuffer 也指向该槽位(镜像 endGBufferPass),这样
403 // 上层可通过 getDepthTexture()/getNormalTexture() 读取本次离屏 ID 渲染
404 // 生成的深度/法线(供 capture_render_frame 的 depth/normal 复用)。
405 if (RenderControl *rc = getRenderControl()) {
406 rc->getGBuffer()->setTargets(int(w), int(h), &slot->depthColorTex, &slot->normalTex, &slot->albedoTex,
407 &slot->depthTex, &slot->pbrParamsTex, &slot->emissiveTex);
408 }
409 return img;
410}
411
412image::ImageData *Graphics::readGBufferToImageData(const std::string &attachment) {
413 if (!initialized) return nullptr;
414 auto *slot = currentGBufferSlot();
415 if (!slot) return nullptr;
416 vkb::ColorTarget *src = nullptr;
417 if (attachment == "depth")
418 src = &slot->depthColor; // RGBA8 linear depth
419 else if (attachment == "normal")
420 src = &slot->normal;
421 else if (attachment == "albedo")
422 src = &slot->albedo;
423 else if (attachment == "pbrParams")
424 src = &slot->pbrParams;
425 else if (attachment == "emissive")
426 src = &slot->emissive;
427 else
428 return nullptr;
429
430 const uint32_t w = uint32_t(gbufferWidth);
431 const uint32_t h = uint32_t(gbufferHeight);
432 if (w == 0 || h == 0) return nullptr;
433
434 const bool hdr = attachment == "emissive";
435 const vk::DeviceSize byteSize = vk::DeviceSize(w) * vk::DeviceSize(h) * (hdr ? 8 : 4);
436 if (gbufferPending) recordDeferredFrameGraph();
437 vkb::GenericBuffer staging(device, vk::BufferUsageFlagBits::eTransferDst, byteSize,
438 vk::MemoryPropertyFlagBits::eHostVisible |
439 vk::MemoryPropertyFlagBits::eHostCoherent);
440 vkb::executeImmediately(
441 device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics), [&](vk::CommandBuffer cb) {
442 detail::recordFrameReadback(cb, src->image(), staging.buffer, vk::Extent2D{w, h},
443 vk::ImageAspectFlagBits::eColor, 0, vk::ImageLayout::eShaderReadOnlyOptimal);
444 src->setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
445 });
446
447 auto *img = new image::ImageData(int(w), int(h), "RGBA8");
448 void *mapped = staging.map();
449 if (hdr) {
450 auto *pixels = static_cast<uint8_t *>(img->getData());
451 const auto *halves = static_cast<const uint16_t *>(mapped);
452 for (size_t i = 0; i < size_t(w) * size_t(h) * 4; ++i)
453 pixels[i] = uint8_t(std::lround(std::clamp(glm::unpackHalf1x16(halves[i]), 0.f, 1.f) * 255.f));
454 } else {
455 std::memcpy(img->getData(), mapped, size_t(byteSize));
456 }
457 staging.unmap();
458 staging.release();
459 if (attachment == "depth") {
460 auto *pixels = static_cast<uint8_t *>(img->getData());
461 const size_t pixelCount = size_t(w) * size_t(h);
462 for (size_t i = 0; i < pixelCount; ++i) {
463 pixels[i * 4u + 1u] = pixels[i * 4u];
464 pixels[i * 4u + 2u] = pixels[i * 4u];
465 }
466 }
467 return img;
468}
469
471 if (!initialized) return nullptr;
472 auto *slot = currentDecalSlot();
473 auto *gslot = currentGBufferSlot();
474 if (!slot || !gslot || !slot->framebuffer || !decalPipeline || !decalRenderPass || !gbufferPipeline ||
475 !gbufferRenderPass || !gslot->framebuffer)
476 return nullptr;
477 vkb::ColorTarget *src = nullptr;
478 if (attachment == "normal")
479 src = &slot->normal;
480 else if (attachment == "params")
481 src = &slot->params;
482 else if (attachment == "albedo")
483 src = &slot->albedo;
484 else
485 return nullptr;
486
487 const uint32_t w = uint32_t(decalWidth);
488 const uint32_t h = uint32_t(decalHeight);
489 if (w == 0 || h == 0) return nullptr;
490 if (gbufferPending) recordDeferredFrameGraph();
491
492 const vk::DeviceSize byteSize = vk::DeviceSize(w) * vk::DeviceSize(h) * 4;
493 vkb::GenericBuffer staging(device, vk::BufferUsageFlagBits::eTransferDst, byteSize,
494 vk::MemoryPropertyFlagBits::eHostVisible |
495 vk::MemoryPropertyFlagBits::eHostCoherent);
496 vkb::executeImmediately(device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics),
497 [&](vk::CommandBuffer cb) {
498 // The G-buffer was submitted through the production FrameGraph
499 // above. Queue order makes it visible to this immediate pass.
500 recordDecalPassInto(cb, *slot, *gslot);
501 transitionSampledColorForTransfer(
502 cb, *src, vk::ImageLayout::eTransferSrcOptimal);
503 vk::BufferImageCopy region{};
504 region.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0,
505 1};
506 region.imageExtent = vk::Extent3D{w, h, 1};
507 cb.copyImageToBuffer(src->image(),
508 vk::ImageLayout::eTransferSrcOptimal,
509 staging.buffer, region);
510 transitionSampledColorForTransfer(
511 cb, *src, vk::ImageLayout::eShaderReadOnlyOptimal);
512 });
513
514 auto *img = new image::ImageData(int(w), int(h), "RGBA8");
515 void *mapped = staging.map();
516 std::memcpy(img->getData(), mapped, size_t(byteSize));
517 staging.unmap();
518 staging.release();
519 return img;
520}
521
523 ASSERT(initialized);
524 ASSERT_GT(w, 0);
525 ASSERT_GT(h, 0);
526 if (!initialized) throw Exception("newCanvas: graphics not initialized");
527 if (w <= 0 || h <= 0) throw Exception("newCanvas: invalid size");
528 ensureOffscreenPipelines();
529 auto c = std::make_unique<OffscreenCanvas>(this, w, h);
530 Canvas *raw = c.get();
531 ownedCanvases.push_back(std::move(c));
532 return raw;
533}
534
536 ASSERT(initialized);
537 ASSERT_GT(w, 0);
538 ASSERT_GT(h, 0);
539 if (!initialized) throw Exception("newHDRCanvas: graphics not initialized");
540 if (w <= 0 || h <= 0) throw Exception("newHDRCanvas: invalid size");
541 ensureHdrOffscreenPipelines();
542 auto c = std::make_unique<OffscreenCanvas>(this, w, h, true);
543 Canvas *raw = c.get();
544 ownedCanvases.push_back(std::move(c));
545 return raw;
546}
547
548void Graphics::beginPathSceneOutput() {
549 if (sceneColorPassOpen) endSceneColorRenderPass();
550}
551
552void Graphics::resolvePathSceneOutput(Texture *texture) { pendingSceneResolveSource = texture; }
553
554void Graphics::retirePathSceneOutput() { invalidateTextureBindings(); }
555
557 Canvas *next = canvas;
558 if (next == static_cast<Canvas *>(this)) next = nullptr;
559 if (next == activeCanvas) return;
560 bool hasSolid = false;
561 for (const auto &sb : solidBatches)
562 if (!sb.batch.empty()) hasSolid = true;
563 if (hasSolid || !texturedBatches.empty() || !litBatches.empty()) flushBatch();
564 if (next && sceneColorPassOpen) {
565 endSceneColorRenderPass();
566 queueSceneColorResolve();
567 }
568 activeCanvas = next;
569}
570
572 return activeCanvas != nullptr;
573}
574
576 return activeCanvas ? activeCanvas : const_cast<Graphics *>(this);
577}
578
579void Graphics::setViewportSize(int newW, int newH, int newPw, int newPh) {
580 bool changed = (newW != width) || (newH != height) || (newPw != pixelWidth) || (newPh != pixelHeight);
581 width = newW;
582 height = newH;
583 pixelWidth = newPw;
584 pixelHeight = newPh;
585 if (initialized && changed) swapchainDirty = true;
586}
587
588void Graphics::clear2DBatches() {
589 solidBatches.clear();
590 texturedBatches.clear();
591 litBatches.clear();
592 overlaySpans.clear();
593 engine3DSpans.clear();
594 gpuParticleDraws_.clear();
595 pendingSceneResolve.reset();
596 pendingUiResolve.reset();
597 sceneColorComposited = false;
598}
599
600void Graphics::noteSolidOverlay(uint32_t idx) {
601 if (idx >= solidBatches.size()) return;
602 const uint32_t n = uint32_t(solidBatches[idx].batch.vertices().size());
603 auto &spans = recordingEngine3D_ ? engine3DSpans : overlaySpans;
604 if (!spans.empty() && spans.back().kind == OverlayKind::Solid &&
605 spans.back().index == idx) {
606 spans.back().vertCount = n - spans.back().vertBegin;
607 return;
608 }
609 const uint32_t begin = n >= 6u ? n - 6u : 0u;
610 spans.push_back({OverlayKind::Solid, idx, begin, n - begin});
611}
612
613void Graphics::noteTexturedOverlay(Texture *tex, uint32_t idx) {
614 // Sampling scene color into an offscreen post-process target is not a
615 // swapchain composite. Marking it as one suppresses the real final
616 // resolve and leaves the presented frame at its clear color.
617 if (!recordingEngine3D_ && !activeCanvas && tex && tex == getSceneColorTexture())
618 sceneColorComposited = true;
619 auto &spans = recordingEngine3D_ ? engine3DSpans : overlaySpans;
620 if (!spans.empty() && spans.back().kind == OverlayKind::Textured && spans.back().index == idx)
621 return;
622 spans.push_back({OverlayKind::Textured, idx, 0, 0});
623}
624
625void Graphics::noteLitOverlay(uint32_t idx) {
626 auto &spans = recordingEngine3D_ ? engine3DSpans : overlaySpans;
627 if (!spans.empty() && spans.back().kind == OverlayKind::Lit && spans.back().index == idx)
628 return;
629 spans.push_back({OverlayKind::Lit, idx, 0, 0});
630}
631
632void Graphics::clear(std::optional<Color> color, std::optional<int>, std::optional<double>) {
633 // Keep 3D framebuffer contents when composing 2D on top of an open 3D pass.
634 if (frameHad3D && activeCanvas == nullptr) return;
635 clearColor = color.value_or(backgroundColor);
636 hasPendingClear = true;
637 clear2DBatches();
638 if (auto *oc = dynamic_cast<OffscreenCanvas *>(activeCanvas)) {
639 oc->clear(clearColor, std::nullopt, std::nullopt);
640 }
641}
642
643void Graphics::drawSolidRect(float x, float y, float w, float h, const Color &color,
645 auto it = std::find_if(solidBatches.begin(), solidBatches.end(),
646 [&](const SolidBatch &sb) { return sb.blend == blend; });
647 if (it == solidBatches.end()) {
648 solidBatches.push_back(SolidBatch{blend, Batcher{}});
649 it = solidBatches.end() - 1;
650 }
651 it->batch.addRect(x, y, w, h, color);
652 noteSolidOverlay(uint32_t(it - solidBatches.begin()));
653}
654
656 const int targetWidth = activeCanvas ? activeCanvas->getWidth() : getWidth();
657 const int targetHeight = activeCanvas ? activeCanvas->getHeight() : getHeight();
658 const auto triangles = resolvePrimitiveStrokes2D(canvas, {targetWidth, targetHeight});
659 if (triangles.vertices.empty()) return;
660 auto logicalPoint = [targetWidth, targetHeight](const PrimitiveTriangleVertex &vertex) {
661 const glm::vec2 ndc = glm::vec2(vertex.clipPosition) / vertex.clipPosition.w;
662 return glm::vec2((ndc.x + 1.f) * 0.5f * static_cast<float>(targetWidth),
663 (ndc.y + 1.f) * 0.5f * static_cast<float>(targetHeight));
664 };
665 auto &spans = recordingEngine3D_ ? engine3DSpans : overlaySpans;
666 for (const ResolvedPrimitiveBatch2D &resolvedBatch : triangles.batches2D) {
667 auto it = std::find_if(solidBatches.begin(), solidBatches.end(),
668 [&](const SolidBatch &batch) { return batch.blend == resolvedBatch.blend; });
669 if (it == solidBatches.end()) {
670 solidBatches.push_back(SolidBatch{resolvedBatch.blend, Batcher{}});
671 it = solidBatches.end() - 1;
672 }
673 for (std::size_t i = resolvedBatch.firstVertex; i < resolvedBatch.firstVertex + resolvedBatch.vertexCount;
674 i += 3) {
675 it->batch.addTriangle(logicalPoint(triangles.vertices[i]), logicalPoint(triangles.vertices[i + 1]),
676 logicalPoint(triangles.vertices[i + 2]), triangles.vertices[i].color,
677 triangles.vertices[i + 1].color, triangles.vertices[i + 2].color);
678 }
679 const auto batchIndex = static_cast<std::uint32_t>(it - solidBatches.begin());
680 const std::uint32_t count = static_cast<std::uint32_t>(resolvedBatch.vertexCount);
681 const std::uint32_t end = static_cast<std::uint32_t>(it->batch.vertices().size());
682 spans.push_back({OverlayKind::Solid, batchIndex, end - count, count});
683 }
684}
685
686void Graphics::drawSolidRectRotated(float cx, float cy, float w, float h, float degrees,
687 const Color &color, BlendMode blend) {
688 auto it = std::find_if(solidBatches.begin(), solidBatches.end(),
689 [&](const SolidBatch &sb) { return sb.blend == blend; });
690 if (it == solidBatches.end()) {
691 solidBatches.push_back(SolidBatch{blend, Batcher{}});
692 it = solidBatches.end() - 1;
693 }
694 it->batch.addRectRotated(cx, cy, w, h, degrees, color);
695 noteSolidOverlay(uint32_t(it - solidBatches.begin()));
696}
697
698
699float Graphics::getMaxAnisotropy() const { return maxSamplerAnisotropy; }
700
701vk::Sampler Graphics::createVkSampler(const TextureSampler &sampler, uint32_t mipLevels) const {
702 auto wrapMode = [](bool repeat) {
703 return repeat ? vk::SamplerAddressMode::eRepeat : vk::SamplerAddressMode::eClampToEdge;
704 };
705 auto toFilter = [](FilterMode m) {
706 return m == FilterMode::Nearest ? vk::Filter::eNearest : vk::Filter::eLinear;
707 };
708 auto toMip = [](MipmapMode m) {
709 return m == MipmapMode::Nearest ? vk::SamplerMipmapMode::eNearest
710 : vk::SamplerMipmapMode::eLinear;
711 };
712
713 const bool useMips = sampler.mipmap != MipmapMode::Disabled && mipLevels > 1;
714 float maxLod = useMips ? std::min(sampler.maxLod, float(mipLevels - 1)) : 0.f;
715 if (maxLod < sampler.minLod) maxLod = sampler.minLod;
716
717 float aniso = 1.f;
718 bool enableAniso = false;
719 if (sampler.maxAnisotropy > 1.f && maxSamplerAnisotropy > 1.f) {
720 enableAniso = true;
721 aniso = std::min(sampler.maxAnisotropy, maxSamplerAnisotropy);
722 }
723
724 vkb::SamplerBuilder sb;
725 return sb.magFilter(toFilter(sampler.mag))
726 .minFilter(toFilter(sampler.min))
727 .mipmapMode(useMips ? toMip(sampler.mipmap) : vk::SamplerMipmapMode::eNearest)
728 .addressModeU(wrapMode(sampler.repeatU))
729 .addressModeV(wrapMode(sampler.repeatV))
730 .addressModeW(wrapMode(sampler.repeatW))
731 .mipLodBias(sampler.lodBias)
732 .anisotropyEnable(enableAniso ? VK_TRUE : VK_FALSE)
733 .maxAnisotropy(aniso)
734 .minLod(useMips ? sampler.minLod : 0.f)
735 .maxLod(maxLod)
736 .build(device);
737}
738
739
740void Graphics::drawTexturedRect(Texture *texture, float x, float y, float w, float h, const Color &color) {
741 drawTexturedRectUV(texture, x, y, w, h, 0.f, 0.f, 1.f, 1.f, color);
742}
743
745 float h, const Color &color) {
746 drawTexturedRectShaderUV(texture, shader, x, y, w, h, 0.f, 0.f, 1.f, 1.f, color);
747}
748
749void Graphics::drawTexturedRectUV(Texture *texture, float x, float y, float w, float h, float u0,
750 float v0, float u1, float v1, const Color &color) {
751 drawTexturedRectShaderUV(texture, currentShader, x, y, w, h, u0, v0, u1, v1, color);
752}
753
755 float h, float u0, float v0, float u1, float v1,
756 const Color &color, bool rotatedUV, BlendMode blend) {
757 if (!texture) {
758 drawSolidRect(x, y, w, h, color, blend);
759 return;
760 }
761 if (texturedBatches.empty() || texturedBatches.back().texture != texture ||
762 texturedBatches.back().depth != nullptr ||
763 texturedBatches.back().shader != shader ||
764 texturedBatches.back().blend != blend) {
765 texturedBatches.push_back(TexturedBatch{texture, nullptr, shader, blend, Batcher{}});
766 }
767 texturedBatches.back().batch.addTexturedRect(x, y, w, h, color, u0, v0, u1, v1, rotatedUV);
768 noteTexturedOverlay(texture, uint32_t(texturedBatches.size() - 1));
769}
770
772 float w, float h, float degrees, float u0, float v0,
773 float u1, float v1, const Color &color,
774 bool rotatedUV, BlendMode blend) {
775 if (!texture) {
776 drawSolidRect(cx - w * 0.5f, cy - h * 0.5f, w, h, color, blend);
777 return;
778 }
779 if (texturedBatches.empty() || texturedBatches.back().texture != texture ||
780 texturedBatches.back().depth != nullptr ||
781 texturedBatches.back().shader != shader ||
782 texturedBatches.back().blend != blend) {
783 texturedBatches.push_back(TexturedBatch{texture, nullptr, shader, blend, Batcher{}});
784 }
785 texturedBatches.back().batch.addTexturedRectRotated(cx, cy, w, h, degrees, color, u0, v0, u1, v1,
786 rotatedUV);
787 noteTexturedOverlay(texture, uint32_t(texturedBatches.size() - 1));
788}
789
791 float y, float w, float h, const Color &tint) {
792 if (!color) {
793 drawSolidRect(x, y, w, h, tint);
794 return;
795 }
796 if (!depth) {
798 return;
799 }
800 if (texturedBatches.empty() || texturedBatches.back().texture != color ||
801 texturedBatches.back().depth != depth || texturedBatches.back().shader != shader) {
802 texturedBatches.push_back(
803 TexturedBatch{color, depth, shader, BlendMode::Alpha, Batcher{}});
804 }
805 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f);
806 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
807}
808
810 Shader *shader, float x, float y, float w,
811 float h, const Color &tint) {
812 if (!color) {
813 drawSolidRect(x, y, w, h, tint);
814 return;
815 }
816 if (texturedBatches.empty() || texturedBatches.back().texture != color ||
817 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
818 texturedBatches.back().shader != shader) {
819 TexturedBatch batch{color, depth, shader, BlendMode::Opaque, Batcher{}};
820 batch.motion = motion;
821 texturedBatches.push_back(std::move(batch));
822 }
823 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f);
824 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
825}
826
828 Texture *extra, Shader *shader, float x, float y, float w,
829 float h, const Color &tint) {
830 if (!color) {
831 drawSolidRect(x, y, w, h, tint);
832 return;
833 }
834 if (texturedBatches.empty() || texturedBatches.back().texture != color ||
835 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
836 texturedBatches.back().extra != extra || texturedBatches.back().shader != shader) {
837 TexturedBatch batch{color, depth, shader, BlendMode::Opaque, Batcher{}};
838 batch.motion = motion;
839 batch.extra = extra;
840 texturedBatches.push_back(std::move(batch));
841 }
842 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f);
843 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
844}
845
847 Texture *extra, Texture *specular, Shader *shader, float x,
848 float y, float w, float h, const Color &tint) {
849 if (!color) {
850 drawSolidRect(x, y, w, h, tint);
851 return;
852 }
853 if (texturedBatches.empty() || texturedBatches.back().texture != color ||
854 texturedBatches.back().depth != depth || texturedBatches.back().motion != motion ||
855 texturedBatches.back().extra != extra || texturedBatches.back().specular != specular ||
856 texturedBatches.back().shader != shader) {
857 TexturedBatch batch{color, depth, shader, BlendMode::Opaque, Batcher{}};
858 batch.motion = motion;
859 batch.extra = extra;
860 batch.specular = specular;
861 texturedBatches.push_back(std::move(batch));
862 }
863 texturedBatches.back().batch.addTexturedRect(x, y, w, h, tint, 0.f, 0.f, 1.f, 1.f);
864 noteTexturedOverlay(color, uint32_t(texturedBatches.size() - 1));
865}
866
868 Texture *displacement, float cx, float cy, float w, float h, float degrees, float u0, float v0,
869 float u1, float v1, float strengthPixels, float opacity, bool rotatedUV) {
871 if (!displacement || !scene || !scene->gpuHandle || !particleDistortionPipeline)
873
874 TexturedBatch batch{scene, displacement, nullptr, BlendMode::Alpha, Batcher{}};
875 batch.effect = TexturedBatch::Effect::SceneColorDistortion;
876 batch.batch.addTexturedRectRotated(cx, cy, w, h, degrees,
877 Color(strengthPixels, 0.f, 0.f, opacity), u0, v0, u1, v1,
878 rotatedUV);
879 texturedBatches.push_back(std::move(batch));
880 // Distortion samples scene color but does not replace the base scene
881 // composite; keep the automatic scene resolve underneath this overlay.
882 noteTexturedOverlay(nullptr, uint32_t(texturedBatches.size() - 1));
884}
885
886void Graphics::drawUiTextureRects(void* commandBuffer, const std::vector<UiTextureDraw>& draws,
887 std::size_t bufferOffset) {
888 if (!commandBuffer || draws.empty() || !uiTexturePipeline || uiColorWidth <= 0 ||
889 uiColorHeight <= 0)
890 return;
891
892 vk::CommandBuffer cb(static_cast<VkCommandBuffer>(commandBuffer));
893 auto &buffers = currentFrame2DBuffers().uiTexBufs;
894 std::size_t bufferIndex = bufferOffset;
895 setViewportAndScissor(cb, uint32_t(uiColorWidth), uint32_t(uiColorHeight));
896
897 for (const UiTextureDraw &draw : draws) {
898 if (!draw.texture || !draw.texture->gpuHandle || draw.w <= 0.f || draw.h <= 0.f)
899 continue;
900 auto *gpu = static_cast<GpuTexture *>(draw.texture->gpuHandle);
901 const vk::DescriptorSet set = gpu->descriptorSet;
902 if (!set) continue;
903
904 Batcher batch;
905 batch.addTexturedRect(draw.x, draw.y, draw.w, draw.h, draw.tint, draw.u0, draw.v0,
906 draw.u1, draw.v1);
907 batch.toNDC(uiColorWidth, uiColorHeight);
908 std::vector<TexturedVertex> vertices;
909 vertices.reserve(batch.vertices().size());
910 for (const auto &vertex : batch.vertices())
911 vertices.push_back(TexturedVertex{vertex.pos, vertex.color, vertex.uv});
912
913 while (bufferIndex >= buffers.size()) buffers.emplace_back();
914 vkb::HostVertexBuffer &vertexBuffer = buffers[bufferIndex++];
915 vertexBuffer.allocate<TexturedVertex>(frameToken(), device, vertices);
916
917 const int clipX = std::clamp(int(std::floor(draw.clipX)), 0, uiColorWidth);
918 const int clipY = std::clamp(int(std::floor(draw.clipY)), 0, uiColorHeight);
919 const int clipRight = std::clamp(int(std::ceil(draw.clipX + draw.clipW)), 0, uiColorWidth);
920 const int clipBottom = std::clamp(int(std::ceil(draw.clipY + draw.clipH)), 0, uiColorHeight);
921 if (clipRight <= clipX || clipBottom <= clipY) continue;
922 const vk::Rect2D scissor{{clipX, clipY},
923 {uint32_t(clipRight - clipX), uint32_t(clipBottom - clipY)}};
924 cb.setScissor(0, 1, &scissor);
925 cb.bindPipeline(vk::PipelineBindPoint::eGraphics,
926 draw.opaque ? uiTextureOpaquePipeline : uiTexturePipeline);
927 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &set, 0,
928 nullptr);
929 const vk::DeviceSize offset = 0;
930 cb.bindVertexBuffers(0, 1, vertexBuffer, &offset);
931 cb.draw(uint32_t(vertices.size()), 1, 0, 0);
932 }
933}
934
935void Graphics::setLighting2D(const Lighting2DUBO &ubo) { lighting2dFrame = ubo; }
936
937void Graphics::ensureFlatNormalTexture() {
938 if (flatNormalTexture) return;
939 const uint8_t px[4] = {128, 128, 255, 255}; // flat normal pointing +Z
940 flatNormalTexture = newTexture(1, 1, px);
941}
942
943void Graphics::drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0,
944 float v0, float u1, float v1, const Color &color, BlendMode blend) {
945 if (!albedo) {
946 drawSolidRect(x, y, w, h, color, blend);
947 return;
948 }
949 ensureFlatNormalTexture();
950 if (!normal) normal = flatNormalTexture;
951 if (litBatches.empty() || litBatches.back().albedo != albedo || litBatches.back().normal != normal ||
952 litBatches.back().blend != blend) {
953 litBatches.push_back(LitBatch{albedo, normal, blend, Batcher{}});
954 }
955 litBatches.back().batch.addTexturedRect(x, y, w, h, color, u0, v0, u1, v1);
956 noteLitOverlay(uint32_t(litBatches.size() - 1));
957}
958
960 float degrees, float u0, float v0, float u1, float v1, const Color &color,
962 if (!albedo) {
964 return;
965 }
966 ensureFlatNormalTexture();
967 if (!normal) normal = flatNormalTexture;
968 if (litBatches.empty() || litBatches.back().albedo != albedo || litBatches.back().normal != normal ||
969 litBatches.back().blend != blend) {
970 litBatches.push_back(LitBatch{albedo, normal, blend, Batcher{}});
971 }
972 litBatches.back().batch.addTexturedRectRotated(cx, cy, w, h, degrees, color, u0, v0, u1, v1);
973 noteLitOverlay(uint32_t(litBatches.size() - 1));
974}
975
976vkb::BoundSet Graphics::lit2dSetFor(GpuTexture *albedo, GpuTexture *normal, bool offscreen) {
977 ASSERT(albedo != nullptr);
978 ASSERT(normal != nullptr);
979 auto &sets = offscreen ? offscreenLit2dSets : currentLit2dSets();
980 vkb::GenericBuffer &ubo = offscreen ? offscreenLighting2dUbo : currentLighting2dUbo();
981 LitSetKey key{albedo, normal};
982 auto it = sets.find(key);
983 if (it != sets.end()) return it->second;
984
985 vk::DescriptorSetAllocateInfo alloc{};
986 alloc.descriptorPool = descriptorPool;
987 alloc.descriptorSetCount = 1;
988 alloc.pSetLayouts = &lit2dSetLayout;
989 vkb::UnboundSet unbound{device->allocateDescriptorSets(alloc).front()};
990
991 vkb::DescriptorSetUpdater updater;
992 updater.beginDescriptorSet(unbound)
993 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
994 .image(vkb::SampledImage::forLaterSample(albedo->sampler, albedo->image.imageView()))
995 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
996 .image(vkb::SampledImage::forLaterSample(normal->sampler, normal->image.imageView()))
997 .beginBuffers(2, 0, vk::DescriptorType::eUniformBuffer)
998 .buffer(ubo.buffer, 0, sizeof(Lighting2DUBO))
999 .update(device.instance);
1000
1001 vkb::BoundSet bound = std::move(unbound).publish();
1002 sets.emplace(key, bound);
1003 return bound;
1004}
1005
1006vkb::BoundSet Graphics::post2SetFor(GpuTexture *color, GpuTexture *depth, GpuTexture *motion,
1007 GpuTexture *extra, GpuTexture *specular) {
1008 if (!color || !color->sampler) return {};
1009 vk::ImageView colorView = color->imageView();
1010 if (!colorView) return {};
1011 if (!depth || !depth->sampler || !depth->imageView()) depth = color;
1012 if (!motion || !motion->sampler || !motion->imageView()) motion = color;
1013 if (!extra || !extra->sampler || !extra->imageView()) extra = color;
1014 if (!specular || !specular->sampler || !specular->imageView()) specular = color;
1015 PostSetKey key{color, depth, motion, extra, specular};
1016 auto it = post2Sets.find(key);
1017 if (it != post2Sets.end()) return it->second;
1018
1019 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
1020
1021 vkb::UnboundSet unbound{sets[0]};
1022 vkb::DescriptorSetUpdater updater;
1023 updater.beginDescriptorSet(unbound)
1024 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
1025 .image(vkb::SampledImage::forLaterSample(color->sampler, colorView))
1026 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
1027 .image(vkb::SampledImage::forLaterSample(depth->sampler, depth->imageView()))
1028 .beginImages(2, 0, vk::DescriptorType::eCombinedImageSampler)
1029 .image(vkb::SampledImage::forLaterSample(motion->sampler, motion->imageView()))
1030 .beginImages(3, 0, vk::DescriptorType::eCombinedImageSampler)
1031 .image(vkb::SampledImage::forLaterSample(extra->sampler, extra->imageView()))
1032 .beginImages(4, 0, vk::DescriptorType::eCombinedImageSampler)
1033 .image(vkb::SampledImage::forLaterSample(specular->sampler, specular->imageView()))
1034 .update(device.instance);
1035 vkb::BoundSet bound = std::move(unbound).publish();
1036 post2Sets.emplace(key, bound);
1037 return bound;
1038}
1039
1040void Graphics::drawLitBatches(vk::CommandBuffer cb, int viewW, int viewH, std::vector<LitBatch> &batches,
1041 std::vector<vkb::HostVertexBuffer> &texBufs, size_t &texBufIndex, bool offscreen,
1042 bool hdr) {
1043 if (batches.empty() || !lit2dPipelineLayout) return;
1044 lighting2dFrame.meta.y = float(viewW);
1045 lighting2dFrame.meta.z = float(viewH);
1046 vkb::GenericBuffer &ubo = offscreen ? offscreenLighting2dUbo : currentLighting2dUbo();
1047 ubo.updateLocal(frameToken(), &lighting2dFrame, sizeof(Lighting2DUBO));
1048
1049 for (auto &lb : batches) {
1050 if (lb.batch.empty() || !lb.albedo || !lb.albedo->gpuHandle) continue;
1051 vk::Pipeline litPipeline = selectLit2DPipeline(lb.blend, offscreen, hdr);
1052 if (!litPipeline) continue;
1053 ensureFlatNormalTexture();
1054 Texture *ntex = lb.normal ? lb.normal : flatNormalTexture;
1055 if (!ntex || !ntex->gpuHandle) continue;
1056 auto *albedoGpu = static_cast<GpuTexture *>(lb.albedo->gpuHandle);
1057 auto *normalGpu = static_cast<GpuTexture *>(ntex->gpuHandle);
1058
1059 Batcher ndc = lb.batch;
1060 ndc.toNDC(viewW, viewH);
1061 std::vector<TexturedVertex> gpuVerts;
1062 gpuVerts.reserve(ndc.vertices().size());
1063 for (const auto &v : ndc.vertices()) {
1064 gpuVerts.push_back(TexturedVertex{v.pos, v.color, v.uv});
1065 }
1066
1067 if (texBufIndex >= texBufs.size()) texBufs.emplace_back();
1068 vkb::HostVertexBuffer &vb = texBufs[texBufIndex++];
1069 vb.allocate<TexturedVertex>(frameToken(), device, gpuVerts);
1070
1071 vk::DescriptorSet set = lit2dSetFor(albedoGpu, normalGpu, offscreen);
1072 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, litPipeline);
1073 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, lit2dPipelineLayout, 0, 1, &set, 0,
1074 nullptr);
1075 vk::DeviceSize offset = 0;
1076 cb.bindVertexBuffers(0, 1, vb, &offset);
1077 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
1078 }
1079}
1080
1081
1082Shader *Graphics::newShaderFromSpv(const std::vector<uint32_t> &vertSpv,
1083 const std::vector<uint32_t> &fragSpv) {
1084 ASSERT(initialized);
1085 if (!initialized) throw Exception("newShaderFromSpv: graphics not initialized");
1086 if (fragSpv.empty()) throw Exception("newShaderFromSpv: empty fragment SPIR-V");
1087
1088 std::vector<uint32_t> vert = vertSpv;
1089 if (vert.empty())
1090 vert.assign(textured_vert_spv, textured_vert_spv + textured_vert_spv_count);
1091 if (vert[0] != 0x07230203 || fragSpv[0] != 0x07230203)
1092 throw Exception("newShaderFromSpv: SPIR-V magic mismatch");
1093
1094 auto gpu = std::make_unique<GpuShader>();
1095 gpu->pipelineLayout = shaderPipelineLayout;
1096 gpu->swapchainPipeline =
1097 createTexturedStylePipeline(vert, fragSpv, renderpass, shaderPipelineLayout);
1098 gpu->swapchainOpaquePipeline = createTexturedStylePipeline(
1099 vert, fragSpv, renderpass, shaderPipelineLayout, BlendMode::Opaque);
1100 if (offscreenRenderPass) {
1101 gpu->offscreenPipeline =
1102 createTexturedStylePipeline(vert, fragSpv, offscreenRenderPass, shaderPipelineLayout);
1103 gpu->offscreenOpaquePipeline = createTexturedStylePipeline(
1104 vert, fragSpv, offscreenRenderPass, shaderPipelineLayout, BlendMode::Opaque);
1105 }
1106
1107 auto sh = std::make_unique<Shader>();
1108 sh->setSpirv(std::move(vert), fragSpv);
1109 sh->gpuHandle = gpu.get();
1110
1111 Shader *raw = sh.get();
1112 ownedShaders.push_back(std::move(sh));
1113 ownedGpuShaders.push_back(std::move(gpu));
1114 return raw;
1115}
1116
1117Shader *Graphics::newShaderFromSpvFile(const std::string &vertPath, const std::string &fragPath) {
1118 if (fragPath.empty()) throw Exception("newShaderFromSpvFile: empty fragPath");
1119 std::vector<uint32_t> vert;
1120 if (!vertPath.empty()) vert = readSpirvFile(vertPath);
1121 auto frag = readSpirvFile(fragPath);
1122 return newShaderFromSpv(vert, frag);
1123}
1124
1125Shader *Graphics::newShader(const std::string &vertGlsl, const std::string &fragGlsl) {
1126 if (fragGlsl.empty()) throw Exception("newShader: empty fragment GLSL");
1127 std::vector<uint32_t> vert;
1128 if (!vertGlsl.empty()) vert = compileShaderStage(vertGlsl, "vert", GlslStage::eVertex);
1129 auto frag = compileShaderStage(fragGlsl, "frag", GlslStage::eFragment);
1130 return newShaderFromSpv(vert, frag);
1131}
1132
1133Shader *Graphics::newMeshShaderFromSpv(const std::vector<uint32_t> &vertSpv,
1134 const std::vector<uint32_t> &fragSpv) {
1135 ASSERT(initialized);
1136 if (!initialized) throw Exception("newMeshShaderFromSpv: graphics not initialized");
1137 createMesh3DPipeline();
1138 if (!mesh3dShaderPipelineLayout)
1139 throw Exception("newMeshShaderFromSpv: mesh3d pipeline layout missing");
1140
1141 std::vector<uint32_t> vert = vertSpv;
1142 std::vector<uint32_t> frag = fragSpv;
1143 if (vert.empty())
1144 vert.assign(mesh3d_vert_spv, mesh3d_vert_spv + mesh3d_vert_spv_count);
1145 if (frag.empty())
1146 frag.assign(mesh3d_frag_spv, mesh3d_frag_spv + mesh3d_frag_spv_count);
1147 if (vert[0] != 0x07230203 || frag[0] != 0x07230203)
1148 throw Exception("newMeshShaderFromSpv: SPIR-V magic mismatch");
1149
1150 auto gpu = std::make_unique<GpuShader>();
1151 gpu->isMesh3D = true;
1152 gpu->pipelineLayout = mesh3dShaderPipelineLayout;
1153 ensureOffscreen3DResources();
1154 gpu->mesh3dPipeline = createMesh3DStylePipeline(vert, frag, mesh3dShaderPipelineLayout,
1155 activeScenePass(), activeSceneSamples());
1156 // Built here, not lazily in drawMeshShader: vkCreateGraphicsPipelines
1157 // during an open render pass crashes software ICDs (Lavapipe).
1158 gpu->mesh3dXrayPipeline = createMesh3DXrayPipeline(vert, frag, mesh3dShaderPipelineLayout,
1159 activeScenePass(), activeSceneSamples());
1160 gpu->mesh3dOffscreenPipeline = createMesh3DStylePipeline(
1161 vert, frag, mesh3dShaderPipelineLayout, offscreen3DRenderPass,
1162 vk::SampleCountFlagBits::e1);
1163 gpu->mesh3dHdrOffscreenPipeline = createMesh3DStylePipeline(
1164 vert, frag, mesh3dShaderPipelineLayout, hdrOffscreen3DRenderPass,
1165 vk::SampleCountFlagBits::e1);
1166
1167 auto sh = std::make_unique<Shader>();
1168 sh->setKind(Shader::Kind::eMesh3D);
1169 sh->setSpirv(std::move(vert), std::move(frag));
1170 sh->gpuHandle = gpu.get();
1171 gpu->owner = sh.get();
1172
1173 Shader *raw = sh.get();
1174 ownedShaders.push_back(std::move(sh));
1175 ownedGpuShaders.push_back(std::move(gpu));
1176 return raw;
1177}
1178
1179Shader *Graphics::newHairShaderFromSpv(const std::vector<uint32_t> &vertSpv,
1180 const std::vector<uint32_t> &fragSpv) {
1181 ASSERT(initialized);
1182 if (!initialized) throw Exception("newHairShaderFromSpv: graphics not initialized");
1183 createMesh3DPipeline();
1184 if (fragSpv.empty()) throw Exception("newHairShaderFromSpv: empty fragment SPIR-V");
1185 if (!mesh3dShaderPipelineLayout)
1186 throw Exception("newHairShaderFromSpv: mesh3d pipeline layout missing");
1187
1188 std::vector<uint32_t> vert = vertSpv;
1189 if (vert.empty())
1190 vert.assign(mesh3d_hair_vert_spv, mesh3d_hair_vert_spv + mesh3d_hair_vert_spv_count);
1191 if (vert[0] != 0x07230203 || fragSpv[0] != 0x07230203)
1192 throw Exception("newHairShaderFromSpv: SPIR-V magic mismatch");
1193
1194 auto gpu = std::make_unique<GpuShader>();
1195 gpu->isMesh3D = true;
1196 gpu->isHair3D = true;
1197 gpu->pipelineLayout = mesh3dShaderPipelineLayout;
1198 ensureOffscreen3DResources();
1199 gpu->mesh3dPipeline = createMesh3DHairPipeline(vert, fragSpv, mesh3dShaderPipelineLayout,
1200 activeScenePass(), activeSceneSamples());
1201 gpu->mesh3dOffscreenPipeline = createMesh3DHairPipeline(
1202 vert, fragSpv, mesh3dShaderPipelineLayout, offscreen3DRenderPass,
1203 vk::SampleCountFlagBits::e1);
1204 gpu->mesh3dHdrOffscreenPipeline = createMesh3DHairPipeline(
1205 vert, fragSpv, mesh3dShaderPipelineLayout, hdrOffscreen3DRenderPass,
1206 vk::SampleCountFlagBits::e1);
1207
1208 auto sh = std::make_unique<Shader>();
1209 sh->setKind(Shader::Kind::eMesh3D);
1210 sh->setSpirv(std::move(vert), fragSpv);
1211 sh->gpuHandle = gpu.get();
1212 gpu->owner = sh.get();
1213
1214 Shader *raw = sh.get();
1215 ownedShaders.push_back(std::move(sh));
1216 ownedGpuShaders.push_back(std::move(gpu));
1217 return raw;
1218}
1219
1220Shader *Graphics::newHairShaderFromWgsl(const std::string &, const std::string &) {
1221 throw Exception("newHairShaderFromWgsl: WGSL is only supported on the WebGPU backend");
1222}
1223
1225 if (!shader || !shader->gpuHandle) return false;
1226
1227 auto *gpu = static_cast<GpuShader *>(shader->gpuHandle);
1228 auto gpuIt = std::find_if(ownedGpuShaders.begin(), ownedGpuShaders.end(),
1229 [&](const std::unique_ptr<GpuShader> &g) {
1230 return g.get() == gpu;
1231 });
1232 if (gpuIt == ownedGpuShaders.end()) return false;
1233
1234 auto shIt = std::find_if(ownedShaders.begin(), ownedShaders.end(),
1235 [&](const std::unique_ptr<Shader> &s) {
1236 return s.get() == shader;
1237 });
1238 if (shIt == ownedShaders.end()) return false;
1239
1240 // Mirror ~Graphics: pipelines are raw handles that must be destroyed here;
1241 // pipelineLayout is shared and must not be destroyed per-shader.
1242 waitForSharedGpuResources();
1243 if (gpu->swapchainPipeline) device->destroyPipeline(gpu->swapchainPipeline);
1244 if (gpu->offscreenPipeline) device->destroyPipeline(gpu->offscreenPipeline);
1245 if (gpu->swapchainOpaquePipeline) device->destroyPipeline(gpu->swapchainOpaquePipeline);
1246 if (gpu->offscreenOpaquePipeline) device->destroyPipeline(gpu->offscreenOpaquePipeline);
1247 if (gpu->hdrOffscreenPipeline) device->destroyPipeline(gpu->hdrOffscreenPipeline);
1248 if (gpu->hdrOffscreenOpaquePipeline)
1249 device->destroyPipeline(gpu->hdrOffscreenOpaquePipeline);
1250 if (gpu->mesh3dPipeline) device->destroyPipeline(gpu->mesh3dPipeline);
1251 if (gpu->mesh3dXrayPipeline) device->destroyPipeline(gpu->mesh3dXrayPipeline);
1252 if (gpu->mesh3dOffscreenPipeline)
1253 device->destroyPipeline(gpu->mesh3dOffscreenPipeline);
1254 if (gpu->mesh3dHdrOffscreenPipeline)
1255 device->destroyPipeline(gpu->mesh3dHdrOffscreenPipeline);
1256 shader->gpuHandle = nullptr;
1257 ownedGpuShaders.erase(gpuIt);
1258 // Transfer the CPU facade to the caller instead of destroying it.
1259 (void)shIt->release();
1260 ownedShaders.erase(shIt);
1261 return true;
1262}
1263
1264Shader *Graphics::newMeshShader(const std::string &vertGlsl, const std::string &fragGlsl) {
1265 if (fragGlsl.empty()) throw Exception("newMeshShader: empty fragment GLSL");
1266 std::vector<uint32_t> vert;
1267 if (!vertGlsl.empty()) vert = compileShaderStage(vertGlsl, "vert", GlslStage::eVertex);
1268 auto frag = compileShaderStage(fragGlsl, "frag", GlslStage::eFragment);
1270}
1271
1272Shader *Graphics::newMeshShaderFromWgsl(const std::string &, const std::string &) {
1273 throw Exception("newMeshShaderFromWgsl: WGSL mesh shaders are only supported on the "
1274 "WebGPU backend; use newMeshShaderFromSpv on Vulkan.");
1275}
1276
1277Shader *Graphics::newShaderFromWgsl(const std::string &, const std::string &) {
1278 throw Exception("newShaderFromWgsl: WGSL shaders are only supported on the WebGPU "
1279 "backend; use newShaderFromSpv on Vulkan.");
1280}
1281
1282void Graphics::flushBatch() {
1285 if (!initialized) return;
1286 if (isCanvasActive()) {
1287 auto *oc = dynamic_cast<OffscreenCanvas *>(activeCanvas);
1288 if (!oc) throw Exception("flushBatch: active canvas is not an OffscreenCanvas");
1289 flushToOffscreen(oc);
1290 } else {
1291 flushToSwapchain();
1292 }
1293}
1294
1295void Graphics::abortOpen3DFrame() {
1296 const bool hadScene = sceneColorPassOpen;
1297 const bool had3D = swapchainPassOpen;
1298 try {
1299 if (hadScene) endSceneColorRenderPass();
1300 } catch (...) {
1301 sceneColorPassOpen = false;
1302 }
1303 try {
1304 if (had3D) {
1305 // Scene-pass path never opened the swapchain pass; open a dummy
1306 // one so the acquired command buffer can be submitted.
1307 if (hadScene) beginSwapchainColorPass();
1308 presentRecording = swapchainPass.endRenderPass();
1309 swapchainPass = {};
1310 const bool captured = screenReadbackEnabled
1311 ? recordSwapchainReadback(presentRecording.commandBuffer())
1312 : false;
1313 submitGpuTimingPrefix();
1314 presentRecording.end().submitAndPresent();
1315 submittedPresentSequence_ = presentSequence_;
1316 presentRecording = {};
1317 if (captured) {
1318 hasPresentedFrame = true;
1319 readbackReady = true;
1320 readbackCpuSynced = false;
1321 }
1322 }
1323 } catch (...) {
1324 swapchainPass = {};
1325 presentRecording = {};
1326 }
1327 swapchainPassOpen = false;
1328 sceneColorPassOpen = false;
1329 frameHad3D = false;
1330 hasPendingClear = false;
1331 flushingSwapchain_ = false;
1332 clear2DBatches();
1333}
1334
1335void Graphics::flushToSwapchain() {
1336 EV_PROFILE_MODULE("graphics", "Present.Flush");
1337 if (flushingSwapchain_) return;
1338 flushingSwapchain_ = true;
1339 bool completed = false;
1340 struct FlushGuard {
1341 Graphics *g;
1342 bool *completed;
1343 ~FlushGuard() {
1344 g->flushingSwapchain_ = false;
1345 if (!*completed) g->abortOpen3DFrame();
1346 }
1347 } guard{this, &completed};
1348
1349 const bool continue3D = swapchainPassOpen;
1350 const bool hadScenePass = sceneColorPassOpen;
1351 const bool hasScenePath = hadScenePass || pendingSceneResolveSource != nullptr;
1352
1353 if (hadScenePass) {
1354 endSceneColorRenderPass();
1355 queueSceneColorResolve();
1356 }
1357
1358 if (!continue3D) {
1359 // 2D-only path: acquire the present CB and record deferred passes now,
1360 // so the UI overlay's dedicated MSAA pass can be recorded before the
1361 // swapchain pass begins.
1362 if (!beginPresentCommandBuffer()) {
1363 dropPendingOffscreenPasses();
1364 hasPendingClear = false;
1365 completed = true;
1366 return;
1367 }
1368 recordDeferredFrameGraph();
1369 }
1370
1371 if (!(continue3D && !hasScenePath))
1372 recordGpuParticleCompute(presentRecording.commandBuffer());
1373
1374 materializeSceneColorResolve();
1375
1376 // Render the UI overlay (ImGui) into its own MSAA pass, resolved and
1377 // composited as the top-most fullscreen quad. Skipped only on the rare 3D
1378 // fallback path where the swapchain pass is already open from begin3DFrame.
1379 if (presentOverlayFn_ && !(continue3D && !hasScenePath)) {
1380 renderUiOverlayPass();
1381 }
1382
1383 // HDR present: compose scene + overlays in paper-white-relative linear space,
1384 // then encode once into the swapchain. SDR (and the rare already-open 3D
1385 // path) keep drawing directly into the present pass.
1386 const bool useHdrCompose =
1387 isDisplayHdrActive() && (hasScenePath || !continue3D) && !swapchainPassOpen;
1388 if (useHdrCompose) {
1389 if (!beginPresentComposePass()) {
1390 // Compose target unavailable — fall back to direct swapchain draws.
1391 beginSwapchainColorPass();
1392 swapchainPassOpen = true;
1393 }
1394 } else if (hasScenePath || !continue3D) {
1395 beginSwapchainColorPass();
1396 swapchainPassOpen = true;
1397 }
1398
1399 auto solid = std::move(solidBatches);
1400 auto textured = std::move(texturedBatches);
1401 auto lit = std::move(litBatches);
1402 auto spans = std::move(overlaySpans);
1403 auto engineSpans = std::move(engine3DSpans);
1404 auto gpuParticleDraws = std::move(gpuParticleDraws_);
1405 auto sceneResolve = std::move(pendingSceneResolve);
1406 auto uiResolve = std::move(pendingUiResolve);
1407 const bool autoScene = sceneResolve.has_value() && !sceneColorComposited;
1408 Texture *sceneTex = getSceneColorTexture();
1409 clear2DBatches();
1410
1411 auto &cb = currentPresentCb();
1412 setViewportAndScissor(cb, swapchain.extent.width, swapchain.extent.height);
1413
1414 // Persistent per-frame-slot buffers (see currentFrame2DBuffers). Safe to
1415 // overwrite: acquireForFrame() already waited this slot's fence.
1416 auto &frameBufs = currentFrame2DBuffers();
1417 std::vector<vkb::HostVertexBuffer> &solidBufs = frameBufs.solidBufs;
1418 std::vector<vkb::HostVertexBuffer> &texBufs = frameBufs.texBufs;
1419 size_t texBufIndex = 0;
1420
1421 auto swapchainTexPipe = [&](BlendMode mode) -> vk::Pipeline {
1422 if (presentComposeActive_) {
1423 switch (mode) {
1425 return hdrOffscreenAdditiveTexPipeline;
1427 return hdrOffscreenPremultipliedTexPipeline;
1429 return hdrOffscreenMultiplyTexPipeline;
1430 case BlendMode::Opaque:
1431 return hdrOffscreenOpaqueTexPipeline;
1432 case BlendMode::Alpha:
1433 default:
1434 return hdrOffscreenTexPipeline;
1435 }
1436 }
1437 switch (mode) {
1439 return additiveTexPipeline;
1441 return premultipliedTexPipeline;
1443 return multiplyTexPipeline;
1444 case BlendMode::Opaque:
1445 return opaqueTexPipeline;
1446 case BlendMode::Alpha:
1447 default:
1448 return texPipeline;
1449 }
1450 };
1451 auto swapchainSolidPipe = [&](BlendMode mode) -> vk::Pipeline {
1452 if (presentComposeActive_) {
1453 switch (mode) {
1455 return hdrOffscreenAdditiveSolidPipeline;
1457 return hdrOffscreenPremultipliedSolidPipeline;
1459 return hdrOffscreenMultiplySolidPipeline;
1460 case BlendMode::Alpha:
1461 return hdrOffscreenSolidAlphaPipeline;
1462 case BlendMode::Opaque:
1463 default:
1464 return hdrOffscreenSolidPipeline;
1465 }
1466 }
1467 switch (mode) {
1469 return additiveSolidPipeline;
1471 return premultipliedSolidPipeline;
1473 return multiplySolidPipeline;
1474 case BlendMode::Alpha:
1475 return solidAlphaPipeline;
1476 case BlendMode::Opaque:
1477 default:
1478 return pipeline;
1479 }
1480 };
1481 const vk::Pipeline tonemapPipe =
1482 presentComposeActive_ && hdrOffscreenTonemapPipeline ? hdrOffscreenTonemapPipeline
1483 : sceneTonemapPipeline;
1484 const vk::Pipeline distortionPipe =
1485 presentComposeActive_ && hdrOffscreenParticleDistortionPipeline
1486 ? hdrOffscreenParticleDistortionPipeline
1487 : particleDistortionPipeline;
1488 const bool litAvailable = lit2dPipeline || (presentComposeActive_ && hdrOffscreenLitPipeline);
1489
1490 auto drawTextured = [&](TexturedBatch &tb, bool toneMapScene = false) {
1491 EV_PROFILE_MODULE("graphics", "Present.DrawTextured");
1492 if (tb.batch.empty() || !tb.texture || !tb.texture->gpuHandle) return;
1493 auto *gpu = static_cast<GpuTexture *>(tb.texture->gpuHandle);
1494 vk::DescriptorSet texSet = gpu->descriptorSet;
1495 Texture *depthTexture = toneMapScene ? sceneTex : tb.depth;
1496 if ((depthTexture && depthTexture->gpuHandle) || (tb.motion && tb.motion->gpuHandle) ||
1497 (tb.extra && tb.extra->gpuHandle)) {
1498 auto *depthGpu =
1499 depthTexture ? static_cast<GpuTexture *>(depthTexture->gpuHandle) : nullptr;
1500 auto *motionGpu =
1501 tb.motion ? static_cast<GpuTexture *>(tb.motion->gpuHandle) : nullptr;
1502 auto *extraGpu = tb.extra ? static_cast<GpuTexture *>(tb.extra->gpuHandle) : nullptr;
1503 auto *specularGpu =
1504 tb.specular ? static_cast<GpuTexture *>(tb.specular->gpuHandle) : nullptr;
1505 if (vk::DescriptorSet combo =
1506 post2SetFor(gpu, depthGpu, motionGpu, extraGpu, specularGpu))
1507 texSet = combo;
1508 }
1509 Batcher ndc = tb.batch;
1510 ndc.toNDC(width, height);
1511 std::vector<TexturedVertex> gpuVerts;
1512 gpuVerts.reserve(ndc.vertices().size());
1513 for (const auto &v : ndc.vertices())
1514 gpuVerts.push_back(TexturedVertex{v.pos, v.color, v.uv});
1515
1516 if (texBufIndex >= texBufs.size()) texBufs.emplace_back();
1517 vkb::HostVertexBuffer &vb = texBufs[texBufIndex++];
1518 vb.allocate<TexturedVertex>(frameToken(), device, gpuVerts);
1519
1520 if (tb.effect == TexturedBatch::Effect::SceneColorDistortion) {
1521 if (!distortionPipe) return;
1522 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, distortionPipe);
1523 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0, nullptr);
1524 } else if (tb.effect == TexturedBatch::Effect::DisplayEncode) {
1525 if (!tonemapPipe) return;
1526 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, tonemapPipe);
1527 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1, &texSet, 0,
1528 nullptr);
1529 } else if (tb.shader && tb.shader->gpuHandle) {
1530 auto *gs = static_cast<GpuShader *>(tb.shader->gpuHandle);
1531 vk::Pipeline customPipeline = nullptr;
1532 if (presentComposeActive_) {
1533 ensureShaderHdrOffscreenPipeline(tb.shader);
1534 customPipeline = tb.blend == BlendMode::Opaque && gs->hdrOffscreenOpaquePipeline
1535 ? gs->hdrOffscreenOpaquePipeline
1536 : gs->hdrOffscreenPipeline;
1537 } else {
1538 customPipeline = tb.blend == BlendMode::Opaque && gs->swapchainOpaquePipeline
1539 ? gs->swapchainOpaquePipeline
1540 : gs->swapchainPipeline;
1541 }
1542 if (!customPipeline) return;
1543 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, customPipeline);
1544 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, shaderPipelineLayout, 0, 1,
1545 &texSet, 0, nullptr);
1546 cb.pushConstants(shaderPipelineLayout,
1547 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
1548 Shader::kPushConstantBytes, tb.shader->pushConstantData());
1549 } else {
1550 vk::Pipeline pipe = toneMapScene ? tonemapPipe : swapchainTexPipe(tb.blend);
1551 if (!pipe) return;
1552 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
1553 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, texPipelineLayout, 0, 1,
1554 &texSet, 0, nullptr);
1555 }
1556 vk::DeviceSize offset = 0;
1557 cb.bindVertexBuffers(0, 1, vb, &offset);
1558 cb.draw(uint32_t(gpuVerts.size()), 1, 0, 0);
1559 };
1560
1561 std::vector<bool> solidUploaded(solid.size(), false);
1562 auto uploadSolid = [&](size_t idx) {
1563 if (idx >= solid.size() || solidUploaded[idx] || solid[idx].batch.empty()) return;
1564 vk::Pipeline pipe = swapchainSolidPipe(solid[idx].blend);
1565 if (!pipe) return;
1566 Batcher ndc = solid[idx].batch;
1567 ndc.toNDC(width, height);
1568 std::vector<ColorVertex> gpuVerts;
1569 gpuVerts.reserve(ndc.vertices().size());
1570 for (const auto &v : ndc.vertices())
1571 gpuVerts.push_back(ColorVertex{v.pos, v.color});
1572 if (solidBufs.size() <= idx) solidBufs.resize(idx + 1);
1573 solidBufs[idx].allocate<ColorVertex>(frameToken(), device, gpuVerts);
1574 solidUploaded[idx] = true;
1575 };
1576
1577 auto drawSolidSpan = [&](uint32_t batchIndex, uint32_t begin, uint32_t count) {
1578 if (batchIndex >= solid.size() || count == 0 || solid[batchIndex].batch.empty()) return;
1579 vk::Pipeline pipe = swapchainSolidPipe(solid[batchIndex].blend);
1580 if (!pipe) return;
1581 uploadSolid(batchIndex);
1582 vk::DeviceSize offset = 0;
1583 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipe);
1584 cb.bindVertexBuffers(0, 1, solidBufs[batchIndex], &offset);
1585 cb.draw(count, 1, begin, 0);
1586 };
1587
1588 auto replaySpans = [&](const std::vector<OverlaySpan> &list) {
1589 for (const auto &sp : list) {
1590 if (sp.kind == OverlayKind::Solid && sp.index < solid.size() && sp.vertCount > 0) {
1591 drawSolidSpan(sp.index, sp.vertBegin, sp.vertCount);
1592 } else if (sp.kind == OverlayKind::Textured && (texPipeline || hdrOffscreenTexPipeline) &&
1593 sp.index < textured.size()) {
1594 drawTextured(textured[sp.index]);
1595 } else if (sp.kind == OverlayKind::Lit && litAvailable && sp.index < lit.size()) {
1596 std::vector<LitBatch> one;
1597 one.push_back(std::move(lit[sp.index]));
1598 drawLitBatches(cb, width, height, one, texBufs, texBufIndex, false);
1599 } else if (sp.kind == OverlayKind::GpuParticles && sp.index < gpuParticleDraws.size()) {
1600 drawGpuParticleRequest(cb, gpuParticleDraws[sp.index]);
1601 }
1602 }
1603 };
1604
1605 bool engineDrawn = false;
1606 auto drawEngine3D = [&]() {
1607 if (engineDrawn) return;
1608 engineDrawn = true;
1609 replaySpans(engineSpans);
1610 };
1611
1612 auto drawPlacedSceneResolve = [&](TexturedBatch &placed) {
1613 if (!sceneResolve) {
1614 drawTextured(placed);
1615 return;
1616 }
1617 TexturedBatch blit = *sceneResolve;
1618 const glm::vec4 acesColor = sceneResolve->batch.vertices().empty()
1619 ? glm::vec4(1.f, 1.f, 1.f, 65536.f)
1620 : sceneResolve->batch.vertices().front().color;
1621 const auto &src = placed.batch.vertices();
1622 if (src.size() >= 6) {
1623 const float x = src[0].pos.x;
1624 const float y = src[0].pos.y;
1625 const float w = src[1].pos.x - x;
1626 const float h = src[2].pos.y - y;
1627 const glm::vec4 tint = src[0].color;
1628 blit.batch.clear();
1629 blit.batch.addTexturedRect(x, y, w, h,
1630 Color(tint.r * acesColor.r, tint.g * acesColor.g,
1631 tint.b * acesColor.b, acesColor.a),
1632 src[0].uv.x, src[0].uv.y, src[1].uv.x, src[2].uv.y);
1633 }
1634 drawTextured(blit, true);
1635 };
1636
1637 // Default: blit 3D fullscreen under script 2D. Scripts that call
1638 // drawScene3D / drawTexturedRect(getSceneColorTexture()) own the order.
1639 if (autoScene && sceneResolve) {
1640 drawTextured(*sceneResolve, true);
1641 drawEngine3D();
1642 }
1643
1644 if (spans.empty() && engineSpans.empty()) {
1645 for (size_t i = 0; i < solid.size(); ++i) {
1646 if (!solid[i].batch.empty())
1647 drawSolidSpan(uint32_t(i), 0, uint32_t(solid[i].batch.vertices().size()));
1648 }
1649 if (texPipeline || hdrOffscreenTexPipeline) {
1650 for (auto &tb : textured) drawTextured(tb);
1651 }
1652 if (litAvailable) drawLitBatches(cb, width, height, lit, texBufs, texBufIndex, false);
1653 } else {
1654 for (const auto &sp : spans) {
1655 if (sp.kind == OverlayKind::Solid && sp.index < solid.size() && sp.vertCount > 0) {
1656 drawSolidSpan(sp.index, sp.vertBegin, sp.vertCount);
1657 } else if (sp.kind == OverlayKind::Textured &&
1658 (texPipeline || hdrOffscreenTexPipeline) && sp.index < textured.size()) {
1659 // Distortion overlays sample scene color; they are not
1660 // drawScene3D placements. Replacing them with the ACES
1661 // resolve skips particleDistortionPipeline and can cover
1662 // the autoScene blit with a near-empty frame.
1663 const bool placedScene =
1664 sceneResolve && textured[sp.index].texture == sceneTex &&
1665 textured[sp.index].effect != TexturedBatch::Effect::SceneColorDistortion;
1666 if (placedScene) {
1667 drawPlacedSceneResolve(textured[sp.index]);
1668 } else {
1669 drawTextured(textured[sp.index]);
1670 }
1671 if (placedScene) {
1672 drawEngine3D();
1673 }
1674 } else if (sp.kind == OverlayKind::Lit && litAvailable && sp.index < lit.size()) {
1675 std::vector<LitBatch> one;
1676 one.push_back(std::move(lit[sp.index]));
1677 drawLitBatches(cb, width, height, one, texBufs, texBufIndex, false);
1678 } else if (sp.kind == OverlayKind::GpuParticles && sp.index < gpuParticleDraws.size()) {
1679 drawGpuParticleRequest(cb, gpuParticleDraws[sp.index]);
1680 }
1681 }
1682 }
1683
1684 if (uiResolve) drawTextured(*uiResolve);
1685
1686 // Invalidate prior readback so a failed present cannot reuse a stale frame.
1687 if (screenReadbackEnabled) hasPresentedFrame = false;
1688
1689 // Fallback path only: the swapchain pass was already open when this frame
1690 // began (3D MSAA scene pass unavailable), so draw the overlay directly.
1691 if (presentOverlayFn_ && continue3D && !hadScenePass) {
1692 VkCommandBuffer raw = static_cast<VkCommandBuffer>(cb);
1694 }
1695
1696 if (presentComposeActive_) {
1697 endPresentComposePass();
1698 beginSwapchainColorPass();
1699 swapchainPassOpen = true;
1700 auto &presentCb = currentPresentCb();
1701 setViewportAndScissor(presentCb, swapchain.extent.width, swapchain.extent.height);
1702 encodePresentComposeToSwapchain(presentCb);
1703 }
1704
1705 presentRecording = swapchainPass.endRenderPass();
1706 swapchainPass = {};
1707 const bool captured =
1708 screenReadbackEnabled ? recordSwapchainReadback(presentRecording.commandBuffer()) : false;
1709 writeGpuTimestampEnd();
1710 recordFrameCapture(presentRecording.commandBuffer());
1711 {
1712 EV_PROFILE_MODULE("graphics", "Frame.SubmitPresent");
1713 submitGpuTimingPrefix();
1714 presentRecording.end().submitAndPresent();
1715 submittedPresentSequence_ = presentSequence_;
1716 }
1717 markFrameCaptureSubmitted();
1718 presentRecording = {};
1719 if (captured) {
1720 hasPresentedFrame = true;
1721 readbackReady = true;
1722 readbackCpuSynced = false;
1723 }
1724 hasPendingClear = false;
1725 swapchainPassOpen = false;
1726 frameHad3D = false;
1727 completed = true;
1728}
1729
1730
1731} // namespace eve::graphics::vulkan
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
float degrees
Definition CardTypes.cpp:38
float uv
bool changed
graphics::Texture * albedo
SQObjectPtr key
Definition ECS.cpp:155
double raw
ScriptFieldRegion region
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::ShaderModule vert
vk::ShaderModule frag
vk::UniqueSampler sampler
vk::UniqueImage image
glm::vec4 tint
Entity-ID / isolated visibility capture kept off Graphics.h.
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
float blend
int h
std::vector< Colorf > px
size_t offset
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
MeshVfxBatchedDraw draw
float tb
Texture * normal
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec3 displacement
std::string error
Definition Package.cpp:174
Texture * texture
int idx
std::string path
Definition PlayHost.cpp:111
std::weak_ptr< PrimitiveScene > scene
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
float d
uint8_t * pixels
std::string build
std::string slot
glm::mat4 viewProj
Shader * shader
Color clearColor
bool repeatV
bool repeatU
ScriptStructure out
std::string_view source
size_t begin
size_t end
int count
bool placed
std::array< double, 2 > vertices[3]
float opacity
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Accumulates solid / textured quads in logical (Y-down) coordinates. Used by RenderSystem; not a publi...
Definition Batcher.h:23
void addTexturedRect(float x, float y, float w, float h, const Color &color, float u0, float v0, float u1, float v1, bool rotatedUV=false)
Adds textured rect.
Definition Batcher.cpp:25
void addTexturedRectRotated(float cx, float cy, float w, float h, float degrees, const Color &color, float u0, float v0, float u1, float v1, bool rotatedUV=false)
Textured quad rotated degrees (clockwise, screen Y-down) around (cx, cy).
Definition Batcher.cpp:52
void toNDC(int logicalW, int logicalH)
To ndc.
Definition Batcher.cpp:119
const std::vector< BatchVertex > & vertices() const
Vertices.
Definition Batcher.h:45
Canvas public API.
Definition Canvas.h:17
virtual void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth)=0
Clears .
virtual image::ImageData * readGBufferToImageData(const std::string &attachment)
Read a G-buffer attachment back to CPU as RGBA8. name is one of "depth" (RGBA8 linear depth),...
Definition Graphics.h:1094
virtual void drawTexturedRectShader4(Texture *color, Texture *depth, Texture *motion, Texture *extra, Shader *shader, float x, float y, float w, float h, const Color &tint)=0
Post draw with four sampled textures at bindings 0, 1, 2 and 3.
virtual Shader * newMeshShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Create a Mesh3D custom shader (MeshVertex + Frame UBO + albedo). Empty vert → default mesh3d....
int getWidth() const
Returns the width.
Definition Graphics.h:489
virtual Shader * newHairShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl)=0
Create an alpha-blended hair/card shader from WGSL on WebGPU.
virtual Shader * newShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl)=0
Create a 2D custom shader from WGSL source (WebGPU backend). Empty vert → default textured vertex sha...
virtual void drawTexturedRectShaderUV(Texture *texture, Shader *shader, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha)=0
UV draw with an explicit Shader (nullptr = default textured pipeline).
virtual Shader * newMeshShader(const std::string &vertGlsl, const std::string &fragGlsl)=0
Creates a mesh shader. @ownership Caller deletes unless documented otherwise.
virtual void drawTexturedRectLitUVRotated(Texture *albedo, Texture *normal, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Lit 2D draw rotated degrees clockwise (screen Y-down) around (cx, cy). Fragment tangent frame is rebu...
bool recordingEngine3D_
True while RenderSystem3D is submitting (AO / engine overlays).
Definition Graphics.h:2325
virtual void setLighting2D(const Lighting2DUBO &ubo)=0
Upload per-frame / per-canvas 2D lighting constants for subsequent lit draws.
virtual image::ImageData * readDecalLayerToImageData(const std::string &attachment)
Read back a DecalLayer attachment ("albedo" | "normal" | "params") to CPU. Renders the pending G-buff...
Definition Graphics.h:1104
virtual SceneColorDistortionStatus drawSceneColorDistortionUVRotated(Texture *displacement, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, float strengthPixels, float opacity, bool rotatedUV=false)
Draws scene color distortion uv rotated.
Definition Graphics.h:795
SceneColorDistortionStatus
Refract the resolved 3D scene color through a displacement texture.
Definition Graphics.h:792
virtual Canvas * getCanvas() const =0
Returns the canvas.
virtual bool isDisplayHdrActive() const
True when the live swapchain is scRGB or HDR10.
virtual void drawSolidRect(float x, float y, float w, float h, float r, float g, float b, float a=1.f)
RGBA-float overload matching the script-facing drawSolidRect name.
void ensureFileTexturesReady()
Finish CPU decode and GPU upload for outstanding newTextureFromFile results. @thread Game/render thre...
virtual Shader * newShader(const std::string &vertGlsl, const std::string &fragGlsl)=0
Compile GLSL source with the engine's build-time GLSL compiler. Empty vertGlsl → default textured ver...
virtual void drawTexturedRectShaderUVRotated(Texture *texture, Shader *shader, float cx, float cy, float w, float h, float degrees, float u0, float v0, float u1, float v1, const Color &color, bool rotatedUV=false, BlendMode blend=BlendMode::Alpha)=0
UV draw rotated degrees clockwise (screen Y-down) around the rect center. texture may be null → solid...
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
void setCanvas()
Sets the canvas.
Definition Graphics.h:2060
virtual Shader * newHairShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Hair/fur card shader (alpha blend + Kajiya-Kay). Empty vert → mesh3d_hair.vert. Owned by Graphics.
virtual void drawSolidRectRotated(float cx, float cy, float w, float h, float degrees, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Rotated solid quad degrees clockwise (screen Y-down) around (cx, cy).
virtual bool releaseShader(Shader *shader)
Eagerly releases a shader created by this Graphics.
Definition Graphics.h:1976
virtual bool isCanvasActive() const =0
True when canvas active.
virtual void drawTexturedRectShaderDepthMotion(Texture *color, Texture *depth, Texture *motion, Shader *shader, float x, float y, float w, float h, const Color &tint)=0
Post draw with color, depth/history and motion/reactive textures.
virtual float getMaxAnisotropy() const =0
Device max supported anisotropy (1 if unsupported). Valid after initWithWindow.
virtual void drawTexturedRectUV(Texture *texture, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color)=0
Draw a textured sub-rect (atlas / tile UVs). texture may be null → solid.
virtual void drawTexturedRect(Texture *texture, float x, float y, float w, float h, float r, float g, float b, float a=1.f)
RGBA-float overload matching the script-facing drawTexturedRect name.
virtual Shader * newShaderFromSpv(const std::vector< uint32_t > &vertSpv, const std::vector< uint32_t > &fragSpv)=0
Create a custom 2D shader from SPIR-V words (vert + frag). Owned by Graphics. Vertex stage may be emp...
virtual Canvas * newHDRCanvas(int width, int height)=0
Create an engine-internal linear RGBA16F post-process target.
virtual Texture * getSceneColorTexture()
Sampleable 3D color target for the current frame (RGB = lit, A = linear depth). Valid after begin3DFr...
Definition Graphics.h:1075
PresentOverlayFn presentOverlayFn_
Definition Graphics.h:2335
virtual void drawTexturedRectShader5(Texture *color, Texture *depth, Texture *motion, Texture *extra, Texture *specular, Shader *shader, float x, float y, float w, float h, const Color &tint)=0
Post draw with five sampled textures at bindings 0 through 4.
virtual Canvas * newCanvas(int width, int height)=0
Create an offscreen render target (sampleable). Owned by Graphics.
virtual Shader * newMeshShaderFromWgsl(const std::string &vertWgsl, const std::string &fragWgsl)=0
Create a Mesh3D custom shader from WGSL source (WebGPU backend). The WGSL must declare the engine's F...
virtual void setViewportSize(int width, int height, int pixelwidth, int pixelheight)=0
Sets the current graphics display viewport dimensions.
virtual void drawTexturedRectLitUV(Texture *albedo, Texture *normal, float x, float y, float w, float h, float u0, float v0, float u1, float v1, const Color &color, BlendMode blend=BlendMode::Alpha)=0
Lit 2D draw (albedo + normal map). Uses Lighting2DUBO from setLighting2D. normal may be null → treate...
int getHeight() const
Returns the height.
Definition Graphics.h:491
virtual Shader * newShaderFromSpvFile(const std::string &vertPath, const std::string &fragPath)=0
Load SPIR-V from files via Filesystem (empty vertPath → default textured vert).
virtual void drawTexturedRectShader(Texture *texture, Shader *shader, float x, float y, float w, float h, const Color &color)=0
Draw with an explicit Shader (nullptr = default textured pipeline).
virtual void applyPendingResourceChanges()
Publish queued resource state before its next consuming draw. @thread Graphics thread; no callbacks....
Definition Graphics.h:2308
virtual void drawTexturedRectShaderDepth(Texture *color, Texture *depth, Shader *shader, float x, float y, float w, float h, const Color &tint)=0
Fullscreen/post draw sampling color at binding 0 and depth at binding 1 (hardware D32,...
virtual void drawPrimitiveCanvas(const PrimitiveCanvas2D &canvas)=0
Resolves and queues one frame-local primitive Canvas.
Frame-local Skia-style recorder for 2D line primitives.
Declarative, compilable 3D render control.
Custom GPU program.
Definition Shader.h:41
static constexpr uint32_t kPushConstantBytes
Definition Shader.h:45
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:360
Color getPixel(int x, int y) override
Returns the pixel.
image::ImageData * renderEntityIdMask(const std::vector< EntityIdDraw > &draws, const glm::mat4 &viewProj, int width, int height) override
Renders entity id mask. @ownership Result transfers to caller. Draw inputs are borrowed only for this...
image::ImageData * newImageData() override
Creates a image data. @ownership Caller deletes unless documented otherwise.
void clear(std::optional< Color > color, std::optional< int > stencil, std::optional< double > depth) override
Clears .
OffscreenCanvas public API.
Definition Canvas.h:15
Represents raw pixel data.
Definition ImageData.h:38
void recordFrameReadback(vk::CommandBuffer cb, vk::Image source, vk::Buffer destination, vk::Extent2D extent, vk::ImageAspectFlags aspect, uint32_t layer, vk::ImageLayout originalLayout)
FilterMode
Mag/min filter for texture sampling.
std::vector< std::uint32_t > compileGlslToSpirv(const std::string &source, GlslStage stage, const std::string &debugName)
Compile GLSL text to SPIR-V words.
ResolvedPrimitiveTriangles resolvePrimitiveStrokes2D(const PrimitiveCanvas2D &canvas, glm::ivec2 viewport)
Resolves 2D stroke segment bodies into clip-space triangles.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
MipmapMode
Mipmap filter; Disabled turns off mip sampling (maxLod clamped to 0).
eve::BlendMode BlendMode
Compatibility alias for the shared 2D blend mode.
Definition BlendMode.h:8
GlslStage
GLSL stage accepted by compileGlslToSpirv.
ControlEdit combo(const char *label, int &selected, const std::vector< const char * > &items)
Shared immediate renderer for indexed combo boxes.
WidgetDesc list(std::string listId, const std::vector< std::string > &items, const std::function< WidgetDesc(const std::string &, int)> &itemFn)
Expand a string list into a Group of item widgets. itemFn(label, index) builds each row; keys default...
Definition Widget.cpp:906
BlendMode
Render-neutral 2D blend mode shared by graphics-facing modules.
Definition RenderTypes.h:11
Lighting2DUBO public API.
Definition Light.h:52
Resolved triangle vertex consumed by primitive GPU backends.
One contiguous 2D blend/order batch in the resolved vertex stream.
Sampler state for a Texture (filter, wrap, mip LOD, anisotropy). Defaults match historical engine beh...
GpuMesh public API.
Definition Graphics.h:298
GpuShader public API.
Definition Graphics.h:335
GpuTexture public API.
Definition Graphics.h:264
TexturedVertex public API.
Definition Graphics.h:105
Backend-internal textured rectangle queued by a UI presenter.
Definition Graphics.h:129
glm::vec4 color