载入中...
搜索中...
未找到
GraphicsVisibility.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <cmath>
4#include <cstring>
5#include "graphics/Mesh.h"
8
9namespace eve::graphics::vulkan {
11 const std::vector<eve::graphics::EntityIdDraw>& draws, const glm::mat4& viewProj, int maskW, int maskH) try {
12 const auto reject = [](DiagnosticCode code, const char *message) {
14 };
15 if (!initialized || maskW <= 0 || maskH <= 0 || maskW > 2048 || maskH > 2048)
16 return reject(DiagnosticCode::InvalidArgument, "Visibility viewport must be 1..2048");
17 // Initialize shared immutable pipelines at the live viewport, never resize live targets for a query.
18 if (!gbufferPipeline) createGBufferResources(getPixelWidth(), getPixelHeight());
19 if (!gbufferPipeline || !gbufferRenderPass || !whiteTexture)
20 return reject(DiagnosticCode::Unsupported, "Visibility pipeline unavailable");
21 struct Scratch {
22 vkb::ColorTarget normal, depthColor, albedo, pbrParams, emissive;
23 vkb::GenericImage depth;
24 vk::Framebuffer framebuffer{};
25 } scratch;
26 struct Cleanup {
28 Scratch &slot;
29 ~Cleanup() {
30 if (slot.framebuffer) graphics.device.instance.destroyFramebuffer(slot.framebuffer);
31 }
32 } cleanup{*this, scratch};
33 const auto format = pickGBufferColorFormat(device);
34 scratch.normal = device.createColorTarget(maskW, maskH, format);
35 scratch.depthColor = device.createColorTarget(maskW, maskH, format);
36 scratch.albedo = device.createColorTarget(maskW, maskH, format);
37 scratch.pbrParams = device.createColorTarget(maskW, maskH, format);
38 scratch.emissive = device.createColorTarget(maskW, maskH, vk::Format::eR16G16B16A16Sfloat);
39 vk::ImageCreateInfo depthInfo{};
40 depthInfo.imageType = vk::ImageType::e2D;
41 depthInfo.format = vk::Format::eD32Sfloat;
42 depthInfo.extent = vk::Extent3D{uint32_t(maskW), uint32_t(maskH), 1};
43 depthInfo.mipLevels = 1;
44 depthInfo.arrayLayers = 1;
45 depthInfo.samples = vk::SampleCountFlagBits::e1;
46 depthInfo.tiling = vk::ImageTiling::eOptimal;
47 depthInfo.usage = vk::ImageUsageFlagBits::eDepthStencilAttachment | vk::ImageUsageFlagBits::eSampled |
48 vk::ImageUsageFlagBits::eTransferSrc;
49 scratch.depth =
50 vkb::GenericImage(device, depthInfo, vk::ImageViewType::e2D, vk::ImageAspectFlagBits::eDepth, false);
51 scratch.framebuffer = gbufferRenderPass.createFramebuffer(
52 device, maskW, maskH,
53 {scratch.normal.asAttachment(), scratch.depthColor.asAttachment(), scratch.albedo.asAttachment(),
54 scratch.pbrParams.asAttachment(), scratch.emissive.asAttachment(), scratch.depth.asAttachment()});
55 auto *slot = &scratch;
56
57 // Render each mesh with a flat idColor into the G-buffer albedo attachment
58 // (location 2) by reusing the G-buffer pipeline (its fragment shader writes
59 // outAlbedo = albedo * tint, so passing a white texture + idColor tint gives
60 // a per-pixel flat entity-ID color).
61 std::vector<GBufferDraw> idDraws;
62 idDraws.reserve(draws.size());
63 auto u8 = [](float x) -> uint32_t { return uint32_t(std::lround(std::clamp(x, 0.f, 1.f) * 255.f)); };
64 for (const auto &d : draws) {
65 if (!d.mesh || !describeMesh(d.mesh).ok())
66 return reject(DiagnosticCode::StaleHandle, "Visibility mesh does not belong to this backend");
67 GBufferDraw gd{};
68 gd.mesh = d.mesh;
69 gd.albedo = whiteTexture;
70 gd.push.mvp = viewProj * d.model;
71 gd.push.modelR0 = glm::vec4(d.model[0][0], d.model[1][0], d.model[2][0], d.model[3][0]);
72 gd.push.modelR1 = glm::vec4(d.model[0][1], d.model[1][1], d.model[2][1], d.model[3][1]);
73 gd.push.modelR2 = glm::vec4(d.model[0][2], d.model[1][2], d.model[2][2], d.model[3][2]);
74 const uint32_t packed = u8(d.idColor.r) | (u8(d.idColor.g) << 8) | (u8(d.idColor.b) << 16);
75 gd.push.clip = glm::vec4(0.1f, 100.f, glm::uintBitsToFloat(packed), 0.f);
76 idDraws.push_back(gd);
77 }
78
79
80 const uint32_t w = uint32_t(maskW);
81 const uint32_t h = uint32_t(maskH);
82 const vk::DeviceSize planeSize = vk::DeviceSize(w) * vk::DeviceSize(h) * 4;
83 const vk::DeviceSize byteSize = planeSize * 2;
84 vkb::GenericBuffer staging(device, vk::BufferUsageFlagBits::eTransferDst, byteSize,
85 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
86
87 vkb::executeImmediately(
88 device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics), [&](vk::CommandBuffer cb) {
89 std::array<vk::ClearValue, 6> clears{};
90 clears[0].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
91 clears[1].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
92 clears[2].color = vk::ClearColorValue(std::array<float, 4>{0, 0, 0, 0});
93 clears[5].depthStencil = vk::ClearDepthStencilValue{1.0f, 0};
94 vk::RenderPassBeginInfo rpBegin{};
95 rpBegin.renderPass = gbufferRenderPass;
96 rpBegin.framebuffer = slot->framebuffer;
97 rpBegin.renderArea = vk::Rect2D{{0, 0}, {w, h}};
98 rpBegin.clearValueCount = uint32_t(clears.size());
99 rpBegin.pClearValues = clears.data();
100 slot->normal.beginColorAttachment();
101 slot->depthColor.beginColorAttachment();
102 slot->albedo.beginColorAttachment();
103 slot->pbrParams.beginColorAttachment();
104 slot->emissive.beginColorAttachment();
105 slot->depth.beginDepthAttachment();
106 cb.beginRenderPass(rpBegin, vk::SubpassContents::eInline);
107 setViewportAndScissor(cb, w, h);
108 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, gbufferPipeline);
109 for (const auto &d : idDraws) {
110 auto *gpuMesh = static_cast<GpuMesh *>(d.mesh->gpuHandle);
111 if (!gpuMesh) continue;
112 if (whiteTexture && whiteTexture->gpuHandle && texSetLayout) {
113 auto *gpuTex = static_cast<GpuTexture *>(whiteTexture->gpuHandle);
114 cb.bindDescriptorSets(vk::PipelineBindPoint::eGraphics, gbufferPipelineLayout, 0, 1,
115 gpuTex->descriptorSet.ptr(), 0, nullptr);
116 }
117 cb.pushConstants(gbufferPipelineLayout,
118 vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment, 0,
119 sizeof(GBufferPush), &d.push);
120 drawIndexedMesh(cb, *gpuMesh);
121 }
122 cb.endRenderPass();
123 slot->normal.endSampledLayout();
124 slot->depthColor.endSampledLayout();
125 slot->albedo.endSampledLayout();
126 slot->pbrParams.endSampledLayout();
127 slot->emissive.endSampledLayout();
128 slot->depth.endSampledLayout();
129
130 // Copy the albedo attachment (location 2 = ID colors) to CPU.
131 slot->albedo.setLayout(cb, vk::ImageLayout::eTransferSrcOptimal);
132 vk::BufferImageCopy region{};
133 region.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
134 region.imageExtent = vk::Extent3D{w, h, 1};
135 cb.copyImageToBuffer(slot->albedo.image(), vk::ImageLayout::eTransferSrcOptimal, staging.buffer, region);
136 slot->albedo.setLayout(cb, vk::ImageLayout::eShaderReadOnlyOptimal);
137 slot->depth.setLayout(cb, vk::ImageLayout::eTransferSrcOptimal, vk::ImageAspectFlagBits::eDepth);
138 region.bufferOffset = planeSize;
139 region.imageSubresource.aspectMask = vk::ImageAspectFlagBits::eDepth;
140 cb.copyImageToBuffer(slot->depth.image(), vk::ImageLayout::eTransferSrcOptimal, staging.buffer, region);
141 slot->depth.setLayout(cb, vk::ImageLayout::eDepthStencilReadOnlyOptimal, vk::ImageAspectFlagBits::eDepth);
142 });
143
145 output.width = maskW;
146 output.height = maskH;
147 output.ids.resize(size_t(w) * h);
148 output.depth.resize(output.ids.size());
149 const auto *mapped = static_cast<const std::uint8_t *>(staging.map());
150 // G-buffer RGB6 tint packing is lossless for the bounded 18-bit ID space.
151 auto channel = [](std::uint8_t value) { return std::uint32_t(std::lround(value * (63.f / 255.f))); };
152 for (size_t i = 0; i < output.ids.size(); ++i)
153 output.ids[i] = channel(mapped[i * 4]) | (channel(mapped[i * 4 + 1]) << 6) | (channel(mapped[i * 4 + 2]) << 12);
154 std::memcpy(output.depth.data(), mapped + planeSize, size_t(planeSize));
155 staging.unmap();
156 staging.release();
157 return Result<VisibilityPixels>::success(std::move(output));
158} catch (const std::exception& error) {
160 Diagnostic::error(DiagnosticCode::Failed, std::string("Visibility GPU capture failed: ") + error.what()));
161}
162
163} // namespace eve::graphics::vulkan
double x
float w
Definition AnimClip.cpp:738
std::string output
graphics::Texture * albedo
ScriptFieldRegion region
std::string message
DiagnosticCode code
Entity-ID / isolated visibility capture kept off Graphics.h.
int h
Texture * normal
std::string error
Definition Package.cpp:174
Object::Ptr value
float d
std::string slot
glm::mat4 viewProj
Graphics * graphics
std::uint32_t depth
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
int getPixelHeight() const
Returns the pixel height.
Definition Graphics.h:495
int getPixelWidth() const
Returns the pixel width.
Definition Graphics.h:493
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:360
Result< VisibilityPixels > captureVisibilityPixels(const std::vector< EntityIdDraw > &draws, const glm::mat4 &viewProj, int width, int height) override
Private-target synchronous opaque ID and float depth readback.
eve::Result< eve::graphics::MeshBackendDescriptor > describeMesh(Mesh *mesh) const override
Return layout facts from the owned Vulkan mesh upload.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Owning isolated raster evidence; depth is Vulkan NDC in [0,1].
GpuMesh public API.
Definition Graphics.h:298
GpuTexture public API.
Definition Graphics.h:264