载入中...
搜索中...
未找到
GraphicsGuideCapture.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <cstring>
4#include <glm/gtc/type_ptr.hpp>
5#include <limits>
6#include <unordered_map>
7
9#include "common/Capability.h"
10#include "graphics/ClipSpace.h"
12#include "graphics/shaders/primitive3d_frag_spv.inc"
13#include "graphics/shaders/primitive3d_vert_spv.inc"
16
17namespace eve::graphics::vulkan {
18namespace {
19
20template <class T>
21Result<T> guideFail(DiagnosticCode code, std::string message) {
23}
24
25bool finitePosition(const glm::vec3& v) { return std::isfinite(v.x) && std::isfinite(v.y) && std::isfinite(v.z); }
26
27bool shotSelected(const std::vector<std::string>& selected, const std::string& shotId) {
28 return selected.empty() || std::find(selected.begin(), selected.end(), shotId) != selected.end();
29}
30
31bool wantsAov(const ActionGuideShot& shot, std::string_view name) {
32 return std::find(shot.aovs.begin(), shot.aovs.end(), name) != shot.aovs.end();
33}
34
35std::array<float, 3> boneHue(std::string_view boneId) {
36 uint32_t hash = 2166136261u;
37 for (unsigned char c : boneId) {
38 hash ^= c;
39 hash *= 16777619u;
40 }
41 const float h = float(hash % 360u);
42 const float s = 0.85f;
43 const float v = 1.f;
44 const float c = v * s;
45 const float x = c * (1.f - std::fabs(std::fmod(h / 60.f, 2.f) - 1.f));
46 const float m = v - c;
47 float r = 0, g = 0, b = 0;
48 if (h < 60) {
49 r = c;
50 g = x;
51 } else if (h < 120) {
52 r = x;
53 g = c;
54 } else if (h < 180) {
55 g = c;
56 b = x;
57 } else if (h < 240) {
58 g = x;
59 b = c;
60 } else if (h < 300) {
61 r = x;
62 b = c;
63 } else {
64 r = c;
65 b = x;
66 }
67 return {r + m, g + m, b + m};
68}
69
70void putPixel(std::vector<uint8_t>& rgba, uint32_t w, uint32_t h, int x, int y, const std::array<float, 3>& rgb) {
71 if (x < 0 || y < 0 || uint32_t(x) >= w || uint32_t(y) >= h) return;
72 const size_t i = (size_t(y) * w + size_t(x)) * 4;
73 rgba[i + 0] = static_cast<uint8_t>(std::lround(std::clamp(rgb[0], 0.f, 1.f) * 255.f));
74 rgba[i + 1] = static_cast<uint8_t>(std::lround(std::clamp(rgb[1], 0.f, 1.f) * 255.f));
75 rgba[i + 2] = static_cast<uint8_t>(std::lround(std::clamp(rgb[2], 0.f, 1.f) * 255.f));
76 rgba[i + 3] = 255;
77}
78
79void drawCircle(std::vector<uint8_t>& rgba, uint32_t w, uint32_t h, int cx, int cy, int radius,
80 const std::array<float, 3>& rgb) {
81 const int r2 = radius * radius;
82 for (int y = -radius; y <= radius; ++y)
83 for (int x = -radius; x <= radius; ++x)
84 if (x * x + y * y <= r2) putPixel(rgba, w, h, cx + x, cy + y, rgb);
85}
86
87void drawLine(std::vector<uint8_t>& rgba, uint32_t w, uint32_t h, int x0, int y0, int x1, int y1,
88 const std::array<float, 3>& rgb) {
89 const int dx = std::abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
90 const int dy = -std::abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
91 int err = dx + dy;
92 for (;;) {
93 putPixel(rgba, w, h, x0, y0, rgb);
94 putPixel(rgba, w, h, x0 + 1, y0, rgb);
95 putPixel(rgba, w, h, x0, y0 + 1, rgb);
96 if (x0 == x1 && y0 == y1) break;
97 const int e2 = 2 * err;
98 if (e2 >= dy) {
99 err += dy;
100 x0 += sx;
101 }
102 if (e2 <= dx) {
103 err += dx;
104 y0 += sy;
105 }
106 }
107}
108
109std::shared_ptr<const std::vector<uint8_t>> rasterizeBoneAov(uint32_t w, uint32_t h,
110 const std::vector<ActionGuideLandmark>& landmarks) {
111 auto bytes = std::make_shared<std::vector<uint8_t>>(size_t(w) * h * 4, uint8_t{0});
112 std::unordered_map<std::string, const ActionGuideLandmark*> byId;
113 byId.reserve(landmarks.size());
114 for (const auto& landmark : landmarks) byId.emplace(landmark.boneId, &landmark);
115 const int radius = std::max(2, int(std::lround(std::min(w, h) * 0.02)));
116 for (const auto& landmark : landmarks) {
117 const auto rgb = boneHue(landmark.boneId);
118 if (landmark.parentId) {
119 auto parent = byId.find(*landmark.parentId);
120 if (parent != byId.end())
121 drawLine(*bytes, w, h, int(std::lround(parent->second->x)), int(std::lround(parent->second->y)),
122 int(std::lround(landmark.x)), int(std::lround(landmark.y)), rgb);
123 }
124 drawCircle(*bytes, w, h, int(std::lround(landmark.x)), int(std::lround(landmark.y)), radius, rgb);
125 }
126 return bytes;
127}
128
129std::shared_ptr<const std::vector<uint8_t>> depthToGrayRgba(const float* depth, uint32_t w, uint32_t h) {
130 auto bytes = std::make_shared<std::vector<uint8_t>>(size_t(w) * h * 4);
131 for (uint32_t y = 0; y < h; ++y) {
132 for (uint32_t x = 0; x < w; ++x) {
133 const size_t i = size_t(y) * w + x;
134 const float z = depth[i];
135 const float nearW = (!std::isfinite(z) || z >= 1.f) ? 0.f : std::clamp(1.f - z, 0.f, 1.f);
136 const auto g = static_cast<uint8_t>(std::lround(nearW * 255.f));
137 (*bytes)[i * 4 + 0] = g;
138 (*bytes)[i * 4 + 1] = g;
139 (*bytes)[i * 4 + 2] = g;
140 (*bytes)[i * 4 + 3] = 255;
141 }
142 }
143 return bytes;
144}
145
146} // namespace
147
148// Owner-thread provider. Graphics owns this service and retires GPU work before destruction.
149// Frozen geometry + CPU AOV bytes are job leases; never mutate the live gameplay Camera3D.
153 std::vector<std::string> selectedShotIds;
154 std::vector<ActionGuideShot> pendingShots;
155 size_t shotIndex = 0;
156 std::vector<Primitive3DVertex> frozenGeometry;
157 std::vector<ActionGuideBoneWorld> frozenBones;
158 uint64_t frozenFrame = 0;
159 vkb::ColorTarget color;
160 vkb::DepthStencilImage depth;
161 vkb::HostVertexBuffer vertices;
162 vkb::GenericBuffer colorStaging;
163 vkb::GenericBuffer depthStaging;
164 vkb::BuiltRenderPass pass;
165 vk::Framebuffer framebuffer{};
166 vk::PipelineLayout layout{};
167 vk::Pipeline pipeline{};
168 vk::CommandPool pool{};
169 vk::Fence fence{};
170 bool submitted = false;
171 bool needSilhouette = false;
172 bool needDepth = false;
173 bool needBone = false;
174
177
178 void clearGpu() {
179 auto& device = graphics.device;
180 if (pool) device->destroyCommandPool(pool);
181 if (fence) device->destroyFence(fence);
182 if (pipeline) device->destroyPipeline(pipeline);
183 if (layout) device->destroyPipelineLayout(layout);
184 if (framebuffer) device->destroyFramebuffer(framebuffer);
185 if (pass) device->destroyRenderPass(pass.handle);
186 pool = nullptr;
187 fence = nullptr;
188 pipeline = nullptr;
189 layout = nullptr;
190 framebuffer = nullptr;
191 pass = {};
192 vertices.release();
193 colorStaging.release();
194 depthStaging.release();
195 color = {};
196 depth = {};
197 submitted = false;
198 }
199
200 bool busy() const {
201 if (evidence.token.empty()) return false;
204 }
205
206 Result<std::string> requestCapture(std::string_view packJson, std::span<const std::string> shotIds) override {
207 if (busy())
208 return guideFail<std::string>(DiagnosticCode::InvalidArgument,
209 "Guide capture busy; release the previous token");
210 auto parsed = Value::fromJson(std::string(packJson));
211 if (!parsed) return Result<std::string>::failure(parsed.status());
212 auto pack = decodeActionGuidePack(parsed.value());
213 if (!pack) return Result<std::string>::failure(pack.status());
214 if (pack.value().canvas.width < 8 || pack.value().canvas.height < 8 || pack.value().canvas.width > 2048 ||
215 pack.value().canvas.height > 2048)
216 return guideFail<std::string>(DiagnosticCode::InvalidArgument, "canvas must be 8..2048 on each side");
217
218 selectedShotIds.assign(shotIds.begin(), shotIds.end());
219 pendingShots.clear();
220 for (const auto& shot : pack.value().shots)
221 if (shotSelected(selectedShotIds, shot.shotId)) pendingShots.push_back(shot);
222 if (pendingShots.empty())
223 return guideFail<std::string>(DiagnosticCode::InvalidArgument, "no shots selected for capture");
224
225 evidence = {};
227 "guide:" + std::to_string(graphics.captureFrameId_) + ":" + std::to_string(pack.value().revision);
229 evidence.revision = pack.value().revision;
230 evidence.backend = "vulkan-action-guide";
231 evidence.pack = std::move(pack).takeValue();
232 evidence.shots.clear();
233 shotIndex = 0;
234 frozenBones.clear();
235
236 auto frozen = freeze();
237 if (!frozen) {
239 evidence.reason = frozen.status().describe();
240 return Result<std::string>::failure(frozen.status());
241 }
242 frozenGeometry = std::move(frozen.value());
243 frozenFrame = graphics.captureFrameId_;
245 }
246
248 if (token != evidence.token)
249 return guideFail<ActionGuideCaptureSnapshot>(DiagnosticCode::NotFound, "Unknown guide-capture token");
251 }
252
253 Result<void> releaseCapture(std::string_view token) override {
254 if (token != evidence.token) return guideFail<void>(DiagnosticCode::NotFound, "Unknown guide-capture token");
255 if (submitted) {
257 // GPU resources survive until fence completes in poll().
258 return Result<void>::success();
259 }
260 clearGpu();
261 frozenGeometry = {};
262 frozenBones = {};
263 pendingShots.clear();
265 evidence.shots.clear();
266 return Result<void>::success();
267 }
268
270 using Output = std::vector<Primitive3DVertex>;
271 if (evidence.pack.subject.id > std::numeric_limits<uint32_t>::max() ||
272 evidence.pack.subject.generation > std::numeric_limits<uint32_t>::max())
273 return guideFail<Output>(DiagnosticCode::InvalidArgument, "subject id/generation out of range");
274 ecs::EntityHandle handle{ecs::current(), std::type_index(typeid(Renderable3D)),
275 static_cast<uint32_t>(evidence.pack.subject.id),
276 static_cast<uint32_t>(evidence.pack.subject.generation)};
277 auto* entity = dynamic_cast<Renderable3D*>(ecs::try_get(handle));
278 if (!entity) return guideFail<Output>(DiagnosticCode::StaleHandle, "Renderable3D generation is stale");
279 const auto renderer = entity->meshRenderer();
280 if (renderer->instances || renderer->lodCount || renderer->shader || renderer->isHair ||
281 renderer->heightTexture)
282 return guideFail<Output>(
284 "Guide capture does not support instances, LOD, custom shaders, hair or displacement");
285
286 const auto& camera = evidence.pack.camera;
287 const auto& canvas = evidence.pack.canvas;
288 const float aspect = float(canvas.width) / float(canvas.height);
289 const auto view =
290 glm::lookAtRH(glm::vec3(float(camera.eye[0]), float(camera.eye[1]), float(camera.eye[2])),
291 glm::vec3(float(camera.target[0]), float(camera.target[1]), float(camera.target[2])),
292 glm::vec3(float(camera.up[0]), float(camera.up[1]), float(camera.up[2])));
293 // Pack orthoSize is half-height (landmark contract); Vulkan helper halves orthoHeight again.
294 const float orthoHeight =
295 camera.projection == ActionGuideProjection::Orthographic ? float(camera.orthoSize) * 2.f : 1.f;
296 const auto projection = cameraProjectionVulkanRH_ZO(camera.projection == ActionGuideProjection::Orthographic,
297 glm::radians(float(camera.fovYDegrees)), orthoHeight,
298 aspect, float(camera.nearPlane), float(camera.farPlane));
299 const auto viewProj = projection * view;
300
301 const auto model = eve::graphics::detail::modelFromTransform(*entity->transform());
302 if (!std::isfinite(glm::determinant(model)) || std::abs(glm::determinant(model)) < 1e-12f)
303 return guideFail<Output>(DiagnosticCode::InvalidArgument, "Entity transform is singular or non-finite");
304 const auto normalModel = glm::transpose(glm::inverse(glm::mat3(model)));
305
306 std::vector<glm::vec3> worldPositions;
307 auto append = [&](Mesh* mesh, Material* material, int /*part*/) -> Result<void> {
308 if (!mesh || !graphics.describeMesh(mesh))
309 return guideFail<void>(DiagnosticCode::StaleHandle, "Mesh is unavailable in this backend");
310 if ((material && (material->effectiveShader() || material->getShadingModel() == "hair")) ||
311 mesh->isMorphDirty())
312 return guideFail<void>(DiagnosticCode::Unsupported,
313 "Custom material or unapplied morph cannot be frozen faithfully");
314 auto* gpu = static_cast<GpuMesh*>(mesh->gpuHandle);
315 if (!gpu || gpu->residentVertexOverride || !gpu->vertexCount || !gpu->indexCount || gpu->indexCount % 3 ||
316 gpu->vertexCount > 250000 || gpu->indexCount > 450000 ||
317 worldPositions.size() + gpu->indexCount > 450000)
318 return guideFail<void>(DiagnosticCode::InvalidArgument,
319 "Unsupported geometry or guide geometry budget exceeded");
320 std::vector<MeshVertex> source(gpu->vertexCount);
321 auto& vb = meshDrawVertices(*gpu);
322 std::memcpy(source.data(), vb.map(), source.size() * sizeof(MeshVertex));
323 vb.unmap();
324 std::vector<uint32_t> indices(gpu->indexCount);
325 auto& ib = meshDrawIndices(*gpu);
326 const auto* bytes = static_cast<const uint8_t*>(ib.map());
327 for (size_t i = 0; i < indices.size(); ++i) {
328 if (gpu->indexType == vk::IndexType::eUint16)
329 indices[i] = reinterpret_cast<const uint16_t*>(bytes)[i];
330 else
331 indices[i] = reinterpret_cast<const uint32_t*>(bytes)[i];
332 }
333 ib.unmap();
334 if (mesh->hasGpuSkinning()) {
335 const auto& palette = mesh->skinPalette();
336 if (palette.empty() || palette.size() % 16)
337 return guideFail<void>(DiagnosticCode::InvalidArgument, "Skin palette is empty or malformed");
338 if (palette.size() > 65536u * 16u)
339 return guideFail<void>(DiagnosticCode::InvalidArgument, "Skin palette exceeds 65536 matrices");
340 for (size_t bone = 0; bone < palette.size(); bone += 16) {
341 for (size_t element = 0; element < 16; ++element)
342 if (!std::isfinite(palette[bone + element]))
343 return guideFail<void>(DiagnosticCode::InvalidArgument, "Skin palette is non-finite");
344 }
345 for (size_t bone = 0; bone < palette.size() / 16; ++bone) {
346 const glm::mat4 boneMat = glm::make_mat4(palette.data() + bone * 16);
347 const glm::vec3 joint = glm::vec3(model * boneMat * glm::vec4(0.f, 0.f, 0.f, 1.f));
348 if (!finitePosition(joint)) continue;
350 sample.boneId = "joint." + std::to_string(bone);
351 sample.name = sample.boneId;
352 sample.position = {joint.x, joint.y, joint.z};
353 if (bone > 0) sample.parentId = "joint." + std::to_string(bone - 1);
354 frozenBones.push_back(std::move(sample));
355 }
356 for (auto& vertex : source) {
357 auto weights = vertex.weights;
358 for (int influence = 0; influence < 4; ++influence) {
359 if (size_t(vertex.joints[influence]) >= palette.size() / 16 ||
360 !std::isfinite(weights[influence]) || weights[influence] < 0.f)
361 return guideFail<void>(DiagnosticCode::InvalidArgument, "Invalid skin joint or weight");
362 }
363 const float sum = glm::dot(weights, glm::vec4(1.f));
364 if (!std::isfinite(sum) || sum <= 1e-8f)
365 return guideFail<void>(DiagnosticCode::InvalidArgument,
366 "Skin weights have no finite positive sum");
367 weights /= sum;
368 glm::mat4 skin(0.f);
369 for (int influence = 0; influence < 4; ++influence)
370 skin +=
371 weights[influence] * glm::make_mat4(palette.data() + size_t(vertex.joints[influence]) * 16);
372 vertex.pos = glm::vec3(skin * glm::vec4(vertex.pos, 1.f));
373 vertex.normal = glm::mat3(skin) * vertex.normal;
374 }
375 }
376 for (auto index : indices) {
377 if (index >= source.size())
378 return guideFail<void>(DiagnosticCode::InvalidArgument, "Mesh index outside vertex stream");
379 const auto& vertex = source[index];
380 const auto position = glm::vec3(model * glm::vec4(vertex.pos, 1.f));
381 const auto normal = normalModel * vertex.normal;
382 if (!finitePosition(position) || !finitePosition(normal) || glm::length(normal) < 1e-8f)
383 return guideFail<void>(DiagnosticCode::InvalidArgument,
384 "Mesh has non-finite positions or invalid normals");
385 worldPositions.push_back(position);
386 }
387 return Result<void>::success();
388 };
389
390 if (renderer->partCount < 0 || renderer->partCount > Renderable3D::MeshRenderer::kMaxParts)
391 return guideFail<Output>(DiagnosticCode::InvalidArgument, "Invalid model part count");
392 const int count = std::max(1, renderer->partCount);
393 for (int part = 0; part < count; ++part) {
394 auto copied = renderer->partCount ? append(renderer->parts[part].mesh, renderer->parts[part].material, part)
395 : append(renderer->mesh, renderer->material, part);
396 if (!copied.ok()) return Result<Output>::failure(copied.status());
397 }
398 if (worldPositions.empty())
399 return guideFail<Output>(DiagnosticCode::InvalidArgument, "Guide subject has no triangles");
400
401 Output output;
402 output.reserve(worldPositions.size());
403 for (const auto& position : worldPositions)
404 output.push_back({viewProj * glm::vec4(position, 1.f), glm::vec4(1.f, 1.f, 1.f, 1.f)});
405 return Result<Output>::success(std::move(output));
406 }
407
409 auto& device = graphics.device;
410 const uint32_t width = static_cast<uint32_t>(evidence.pack.canvas.width);
411 const uint32_t height = static_cast<uint32_t>(evidence.pack.canvas.height);
412 const auto& shot = pendingShots[shotIndex];
413 needSilhouette = wantsAov(shot, "silhouette");
414 needDepth = wantsAov(shot, "depth");
415 needBone = wantsAov(shot, "bone");
416 if (!needSilhouette && !needDepth && !needBone) throw Exception("Guide shot requests no supported AOVs");
417
418 color = device.createColorTarget(width, height, vk::Format::eR8G8B8A8Unorm);
419 depth = vkb::DepthStencilImage{device, width, height, vk::Format::eD32Sfloat};
420 pass =
421 device.createRenderPass()
422 .addSampledColorAttachment(vk::Format::eR8G8B8A8Unorm)
423 .addDepthAttachment(vk::Format::eD32Sfloat, vk::AttachmentLoadOp::eClear, vk::AttachmentStoreOp::eStore)
424 .addSubpass(vkb::SubpassBuilder()
425 .addAttachmentRef(0, vk::ImageLayout::eColorAttachmentOptimal)
426 .setDepthStencilAttachment(1, vk::ImageLayout::eDepthStencilAttachmentOptimal))
427 .addExternalShaderReadDependencies()
428 .build();
429 framebuffer = pass.createFramebuffer(device, width, height, {color.asAttachment(), depth.asAttachment()});
430 layout = device.createPipelineLayout().build();
431 pipeline = device.createPipeline()
432 .useClassicPipeline(embeddedSpirv(primitive3d_vert_spv), embeddedSpirv(primitive3d_frag_spv))
433 .setPipelineLayout(layout)
434 .setVertexInputState(vkb::VertexInputStateBuilder()
435 .addInputBinding<Primitive3DVertex>()
436 .addAttributeDescription<Primitive3DVertex>())
437 .setDynamicStatesViewportScissor()
438 .setRasterizer(vk::PolygonMode::eFill, false, false, 1.f, vk::CullModeFlagBits::eNone,
439 vk::FrontFace::eCounterClockwise)
440 .setDepthStencil(true, true, vk::CompareOp::eLessOrEqual)
441 .build(pass);
442 vertices.allocate(vkb::FrameSlot::gpuIdle(), device, frozenGeometry);
443 colorStaging = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eTransferDst,
444 vk::DeviceSize(width) * height * 4, kHostVisibleCoherent);
445 depthStaging = vkb::GenericBuffer(device, vk::BufferUsageFlagBits::eTransferDst,
446 vk::DeviceSize(width) * height * 4, kHostVisibleCoherent);
447 pool = device.createCommandPool();
448 vk::CommandBufferAllocateInfo allocate(pool, vk::CommandBufferLevel::ePrimary, 1);
449 auto cb = device->allocateCommandBuffers(allocate).front();
450 fence = device->createFence({});
451 cb.begin(vk::CommandBufferBeginInfo(vk::CommandBufferUsageFlagBits::eOneTimeSubmit));
452
453 std::array<vk::ClearValue, 2> clears;
454 const auto& bg = evidence.pack.canvas.backgroundRgba;
455 clears[0].color =
456 vk::ClearColorValue(std::array<float, 4>{float(bg[0]), float(bg[1]), float(bg[2]), float(bg[3])});
457 clears[1].depthStencil = vk::ClearDepthStencilValue(1.f, 0);
458 vk::RenderPassBeginInfo begin(pass.handle, framebuffer, vk::Rect2D({0, 0}, {width, height}), 2, clears.data());
459 color.beginColorAttachment();
460 depth.beginDepthAttachment();
461 cb.beginRenderPass(begin, vk::SubpassContents::eInline);
462 cb.bindPipeline(vk::PipelineBindPoint::eGraphics, pipeline);
463 const vk::DeviceSize offset = 0;
464 cb.bindVertexBuffers(0, 1, vertices, &offset);
465 const vk::Viewport viewport(0.f, 0.f, float(width), float(height), 0.f, 1.f);
466 const vk::Rect2D scissor({0, 0}, {width, height});
467 cb.setViewport(0, 1, &viewport);
468 cb.setScissor(0, 1, &scissor);
469 cb.draw(uint32_t(frozenGeometry.size()), 1, 0, 0);
470 cb.endRenderPass();
471 color.endSampledLayout();
472 detail::recordFrameReadback(cb, color.image(), colorStaging.buffer, {width, height},
473 vk::ImageAspectFlagBits::eColor, 0, vk::ImageLayout::eShaderReadOnlyOptimal);
474 detail::recordFrameReadback(cb, depth.image(), depthStaging.buffer, {width, height},
475 vk::ImageAspectFlagBits::eDepth, 0,
476 vk::ImageLayout::eDepthStencilAttachmentOptimal);
477 cb.end();
478 vk::SubmitInfo submit;
479 submit.commandBufferCount = 1;
480 submit.pCommandBuffers = &cb;
481 const auto result = device.getQueue(vkb::QueueType::graphics).submit(1, &submit, fence);
482 if (result != vk::Result::eSuccess) throw Exception("Guide capture queue submission failed");
483 submitted = true;
484 }
485
487 const uint32_t width = static_cast<uint32_t>(evidence.pack.canvas.width);
488 const uint32_t height = static_cast<uint32_t>(evidence.pack.canvas.height);
489 const auto& shot = pendingShots[shotIndex];
490
492 artifact.shotId = shot.shotId;
493 artifact.timeSeconds = shot.timeSeconds;
494 artifact.sampleIndex = shot.sampleIndex;
495 artifact.view = shot.view;
496 artifact.tags = shot.tags;
497
498 auto colorBytes = std::make_shared<std::vector<uint8_t>>(size_t(width) * height * 4);
499 std::memcpy(colorBytes->data(), colorStaging.map(), colorBytes->size());
500 colorStaging.unmap();
501 auto depthFloat = std::make_shared<std::vector<float>>(size_t(width) * height);
502 std::memcpy(depthFloat->data(), depthStaging.map(), depthFloat->size() * sizeof(float));
503 depthStaging.unmap();
504
505 if (needSilhouette) {
507 buffer.aov = "silhouette";
508 buffer.width = width;
509 buffer.height = height;
510 buffer.rgba8 = std::move(colorBytes);
511 artifact.aovs.push_back(std::move(buffer));
512 }
513 if (needDepth) {
515 buffer.aov = "depth";
516 buffer.width = width;
517 buffer.height = height;
518 buffer.rgba8 = depthToGrayRgba(depthFloat->data(), width, height);
519 artifact.aovs.push_back(std::move(buffer));
520 }
521 if (needBone) {
523 buffer.aov = "bone";
524 buffer.width = width;
525 buffer.height = height;
526 if (frozenBones.empty()) {
527 buffer.rgba8 = std::make_shared<const std::vector<uint8_t>>(size_t(width) * height * 4, uint8_t{0});
528 } else {
529 auto landmarks = projectActionGuideLandmarks(evidence.pack, frozenBones);
530 if (!landmarks)
531 throw Exception(
532 "%s", (std::string("Guide bone projection failed: ") + landmarks.status().describe()).c_str());
533 buffer.rgba8 = rasterizeBoneAov(width, height, landmarks.value());
534 }
535 artifact.aovs.push_back(std::move(buffer));
536 }
537 evidence.shots.push_back(std::move(artifact));
538 }
539
540 void fail(std::string reason) {
542 evidence.reason = std::move(reason);
543 clearGpu();
544 frozenGeometry = {};
545 }
546
547 void poll() {
548 if (evidence.token.empty()) return;
551 return;
552
554 if (submitted) {
555 const auto status = graphics.device->getFenceStatus(fence);
556 if (status == vk::Result::eNotReady) return;
557 clearGpu();
558 }
559 frozenGeometry = {};
560 return;
561 }
562
563 if (submitted) {
564 const auto status = graphics.device->getFenceStatus(fence);
565 if (status == vk::Result::eNotReady) return;
566 if (status != vk::Result::eSuccess) {
567 fail("Guide capture fence failed");
568 return;
569 }
570 publishCurrentShot();
571 clearGpu();
572 ++shotIndex;
573 if (shotIndex >= pendingShots.size()) {
575 frozenGeometry = {};
576 return;
577 }
578 }
579
580 if (!submitted && (evidence.phase == ActionGuideCapturePhase::Queued ||
583 recordCurrentShot();
584 }
585 }
586};
587
588void Graphics::pollGuideCapture() {
589 if (!initialized || !device.instance) return;
590 if (!guideCaptureService_) {
591 guideCaptureService_ = std::make_shared<GuideCaptureService>(*this);
592 cap::provide<IActionGuideCapture>(guideCaptureService_.get());
593 }
594 try {
595 guideCaptureService_->poll();
596 } catch (const std::exception& exception) {
597 guideCaptureService_->fail(exception.what());
598 }
599}
600
601void Graphics::destroyGuideCapture() {
602 if (!guideCaptureService_) return;
603 cap::revoke<IActionGuideCapture>(guideCaptureService_.get());
604 guideCaptureService_.reset();
605}
606
607} // namespace eve::graphics::vulkan
double z
double y
double m[16]
double x
Versioned eve.action.guide-pack document codec and CPU landmark projection.
float w
Definition AnimClip.cpp:738
std::string selected
std::string output
const std::string & s
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
std::string name
Definition ECS.cpp:154
std::string palette
std::string layout
std::string message
DiagnosticCode code
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
float camera[2]
wgpu::PopErrorScopeStatus status
double r
std::vector< std::uint32_t > indices
float v
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
const ColourScope * parent
size_t offset
std::array< float, 3 > position
std::uint32_t bone
ActionGuidePack pack
std::string evidence
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
Texture * normal
OceanGpuFrameToken token
std::shared_ptr< OceanGpuSpectrum > owner
OceanMeshSettings mesh
std::shared_ptr< OceanRenderer > renderer
std::shared_ptr< OceanGpuSpectrum > gpu
glm::dvec3 dx
OceanSprayView view
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::array< uint32_t, 16 > material
PrimitiveHandle handle
std::string hash
const EntityFact * entity
glm::mat4 viewProj
glm::mat4 model
Graphics * graphics
std::string_view source
size_t begin
float dy
Definition Shadow.cpp:151
std::string element
int count
float weights[3]
std::array< double, 2 > vertices[3]
std::uint32_t depth
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Optional GPU guide-capture provider (silhouette/depth/bone AOV export). @thread Engine owner thread o...
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
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
Packages shading method + surface parameters into one attachable asset.
Definition Material.h:38
GPU mesh handle (+ optional CPU morph targets).
Definition Mesh.h:26
EVENGINE_API_BACKENDS public API.
EVENGINE_API_BACKENDS public API.
Definition Graphics.h:360
eve::Result< eve::graphics::MeshBackendDescriptor > describeMesh(Mesh *mesh) const override
Return layout facts from the owned Vulkan mesh upload.
glm::mat4 modelFromTransform(const Renderable3D::Transform3D &t)
Resolve the value-owned scene world matrix or the local TRS on the render thread.
void recordFrameReadback(vk::CommandBuffer cb, vk::Image source, vk::Buffer destination, vk::Extent2D extent, vk::ImageAspectFlags aspect, uint32_t layer, vk::ImageLayout originalLayout)
glm::mat4 cameraProjectionVulkanRH_ZO(bool orthographic, float fovyRad, float orthoHeight, float aspect, float zNear, float zFar)
Camera projection shared by rendering, picking, and diagnostic passes.
Definition ClipSpace.h:38
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< std::vector< ActionGuideLandmark > > projectActionGuideLandmarks(const ActionGuidePack &pack, std::span< const ActionGuideBoneWorld > bones)
Project world-space bones into guide-canvas landmarks using the pack camera/canvas.
Result< ActionGuidePack > decodeActionGuidePack(const Value &value)
Decode schema version 1; unknown fields/versions and incomplete shots are rejected.
One lease-owned CPU AOV buffer (always RGBA8 for PNG export). @ownership rgba8 is immutable shared st...
World-space bone sample supplied by an animation/pose owner.
Immutable CPU snapshot for one guide-capture job. @lifetime Bytes remain valid until releaseCapture; ...
ActionGuideCapturePhase phase
std::vector< ActionGuideShotArtifact > shots
ActionGuideCamera camera
ActionGuideSubject subject
ActionGuideCanvas canvas
Per-shot artifact set for a Ready capture.
std::vector< std::string > tags
std::optional< std::int64_t > sampleIndex
std::vector< ActionGuideAovBuffer > aovs
GpuMesh public API.
Definition Graphics.h:298
Result< void > releaseCapture(std::string_view token) override
Cancel/release; GPU resources survive until their fence completes.
Result< std::string > requestCapture(std::string_view packJson, std::span< const std::string > shotIds) override
Queue guide AOV capture for one pack revision / shot set; never block on GPU.
Result< ActionGuideCaptureSnapshot > captureSnapshot(std::string_view token) override
Poll without waiting; Ready includes lease-owned RGBA buffers for export. @cost O(1) metadata copy; b...
Result< std::vector< Primitive3DVertex > > freeze()
MeshVertex public API.
Definition Graphics.h:148
glm::vec4 color