5#include <glm/gtc/packing.hpp>
14#if defined(__EMSCRIPTEN__)
15#include <emscripten/emscripten.h>
18void Graphics::recordPresentedReadback(wgpu::CommandEncoder &encoder,
const wgpu::Texture &surfaceTexture) {
19 if (!surfaceCanCopySrc)
throw Exception(
"WebGPU: surface does not support screen readback");
20 const int w =
static_cast<int>(surfaceTexture.GetWidth());
21 const int h =
static_cast<int>(surfaceTexture.GetHeight());
22 if (!presentedReadback || presentedReadbackW !=
w || presentedReadbackH !=
h ||
23 presentedReadbackFormat != surfaceFormat) {
24 WGPUTextureDescriptor
desc{};
25 desc.label =
sv(
"eve_presented_readback");
26 desc.dimension = WGPUTextureDimension_2D;
27 desc.size = {
static_cast<uint32_t
>(
w),
static_cast<uint32_t
>(
h), 1};
28 desc.format = surfaceFormat;
29 desc.mipLevelCount = 1;
31 desc.usage = WGPUTextureUsage_CopyDst | WGPUTextureUsage_CopySrc;
32 presentedReadback = device.CreateTexture(
reinterpret_cast<const wgpu::TextureDescriptor *
>(&
desc));
33 presentedReadbackW =
w;
34 presentedReadbackH =
h;
35 presentedReadbackFormat = surfaceFormat;
37 WGPUTexelCopyTextureInfo
from{},
to{};
38 from.texture = surfaceTexture.Get();
39 from.aspect = WGPUTextureAspect_All;
40 to.texture = presentedReadback.Get();
41 to.aspect = WGPUTextureAspect_All;
42 WGPUExtent3D extent{
static_cast<uint32_t
>(
w),
static_cast<uint32_t
>(
h), 1};
43 encoder.CopyTextureToTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo *
>(&
from),
44 reinterpret_cast<const wgpu::TexelCopyTextureInfo *
>(&
to),
45 reinterpret_cast<const wgpu::Extent3D *
>(&extent));
59 throw Exception(
"WebGPU: no presented frame is available for screen readback");
70bool copyTextureToCpu(wgpu::Instance &instance, wgpu::Device &
device, wgpu::Queue &queue, wgpu::Texture src,
int width,
71 int height, std::vector<uint8_t> &outRgba,
int bytesPerPixel = 4) {
72 if (!src)
return false;
73 uint64_t bytesPerRow =
static_cast<uint64_t
>(
width) * bytesPerPixel;
74 bytesPerRow = (bytesPerRow + 255) / 256 * 256;
77 WGPUBufferDescriptor bd{};
78 bd.label =
sv(
"eve_readback");
80 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
81 bd.mappedAtCreation =
false;
82 wgpu::Buffer dst =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor *
>(&bd));
84 wgpu::CommandEncoder enc =
device.CreateCommandEncoder();
85 WGPUTexelCopyTextureInfo
from{};
86 from.texture = src.Get();
88 from.aspect = WGPUTextureAspect_All;
89 from.origin = {0, 0, 0};
90 WGPUTexelCopyBufferInfo
to{};
91 to.buffer = dst.Get();
93 to.layout.bytesPerRow =
static_cast<uint32_t
>(bytesPerRow);
94 to.layout.rowsPerImage =
static_cast<uint32_t
>(
height);
95 WGPUExtent3D extent{
static_cast<uint32_t
>(
width),
static_cast<uint32_t
>(
height), 1};
96 enc.CopyTextureToBuffer(
reinterpret_cast<const wgpu::TexelCopyTextureInfo *
>(&
from),
97 reinterpret_cast<const wgpu::TexelCopyBufferInfo *
>(&
to),
98 reinterpret_cast<const wgpu::Extent3D *
>(&extent));
99 wgpu::CommandBuffer cmd = enc.Finish();
100 queue.Submit(1, &cmd);
105 WGPUMapAsyncStatus
status = WGPUMapAsyncStatus_Force32;
107 WGPUBufferMapCallbackInfo cbInfo{};
108#if defined(__EMSCRIPTEN__)
109 cbInfo.mode = WGPUCallbackMode_AllowProcessEvents;
111 cbInfo.mode = WGPUCallbackMode_WaitAnyOnly;
113 cbInfo.callback = [](WGPUMapAsyncStatus
status, WGPUStringView ,
void *userdata1,
void * ) {
114 auto *
state =
static_cast<MapState *
>(userdata1);
116 state->success =
status == WGPUMapAsyncStatus_Success;
119 cbInfo.userdata1 = ↦
120 WGPUFuture
future = wgpuBufferMapAsync(dst.Get(), WGPUMapMode_Read, 0,
size, cbInfo);
122#if defined(__EMSCRIPTEN__)
124 while (!map.done && guard < 2000) {
126 wgpuInstanceProcessEvents(instance.Get());
130 WGPUFutureWaitInfo waitInfo{};
132 (void)wgpuInstanceWaitAny(instance.Get(), 1, &waitInfo, UINT64_MAX);
135 std::fprintf(stderr,
"[webgpu] texture readback map failed: status=%d done=%d\n",
int(map.status),
140 const uint8_t *data =
static_cast<const uint8_t *
>(dst.GetConstMappedRange(0,
size));
141 if (!data)
return false;
142 const size_t tightRowBytes =
static_cast<size_t>(
width) * bytesPerPixel;
143 outRgba.resize(tightRowBytes *
height);
145 std::memcpy(outRgba.data() + size_t(
y) * tightRowBytes, data + size_t(
y) * bytesPerRow, tightRowBytes);
150float decodeHalf(uint16_t
value) {
151 const uint32_t sign = uint32_t(
value & 0x8000u) << 16u;
152 uint32_t exponent = (
value >> 10u) & 0x1fu;
153 uint32_t mantissa =
value & 0x03ffu;
160 while ((mantissa & 0x0400u) == 0) {
165 bits = sign | ((exponent + 112u) << 23u) | (mantissa << 13u);
167 }
else if (exponent == 31u) {
168 bits = sign | 0x7f800000u | (mantissa << 13u);
170 bits = sign | ((exponent + 112u) << 23u) | (mantissa << 13u);
177float hdrToDisplay(
float value) {
181 return mapped <= 0.0031308f ? mapped * 12.92f : 1.055f * std::pow(mapped, 1.f / 2.4f) - 0.055f;
184Color hdrPixelToColor(
const uint8_t *pixel) {
188 hdrToDisplay(decodeHalf(
channels[2])), std::clamp(decodeHalf(
channels[3]), 0.f, 1.f));
195 const bool bgra = presented && (presentedReadbackFormat == WGPUTextureFormat_BGRA8Unorm ||
196 presentedReadbackFormat == WGPUTextureFormat_BGRA8UnormSrgb);
197 int w = presented ? presentedReadbackW : canvas ? canvas->
getWidth() : (sceneColorWidth > 0 ? sceneColorWidth : 1);
198 int h = presented ? presentedReadbackH
200 : (sceneColorHeight > 0 ? sceneColorHeight : 1);
201 if (
x < 0 || y < 0 || x >=
w ||
y >=
h)
return Color(0.f, 0.f, 0.f, 0.f);
202 std::vector<uint8_t> rgba;
203 wgpu::Texture src = presented ? presentedReadback
204 : canvas ? canvas->color
205 : (sceneColorSlots.empty() ? nullptr : sceneColorSlots[lastPresentSlot].color);
206 const bool hdrScene = !presented && canvas ==
nullptr && sceneColorFormat == WGPUTextureFormat_RGBA16Float;
207 if (!src || !copyTextureToCpu(instance,
device, queue, src,
w,
h, rgba, hdrScene ? 8 : 4))
return clearColor;
208 if (hdrScene)
return hdrPixelToColor(rgba.data() + (
size_t(
y) *
w +
x) * 8);
209 const uint8_t *
p = rgba.data() + (size_t(
y) *
w +
x) * 4;
210 return Color(
p[bgra ? 2 : 0] / 255.f,
p[1] / 255.f,
p[bgra ? 0 : 2] / 255.f,
p[3] / 255.f);
215 const bool bgra = presented && (presentedReadbackFormat == WGPUTextureFormat_BGRA8Unorm ||
216 presentedReadbackFormat == WGPUTextureFormat_BGRA8UnormSrgb);
217 int w = presented ? presentedReadbackW : canvas ? canvas->
getWidth() : (sceneColorWidth > 0 ? sceneColorWidth : 1);
218 int h = presented ? presentedReadbackH
220 : (sceneColorHeight > 0 ? sceneColorHeight : 1);
221 auto img = std::make_unique<image::ImageData>(
w,
h,
"RGBA8");
222 std::vector<uint8_t> rgba;
223 wgpu::Texture src = presented ? presentedReadback
224 : canvas ? canvas->color
225 : (sceneColorSlots.empty() ? nullptr : sceneColorSlots[lastPresentSlot].color);
226 const bool hdrScene = !presented && canvas ==
nullptr && sceneColorFormat == WGPUTextureFormat_RGBA16Float;
227 if (src && copyTextureToCpu(instance,
device, queue, src,
w,
h, rgba, hdrScene ? 8 : 4)) {
230 for (
size_t pixel = 0; pixel < size_t(
w) *
h; ++pixel) std::swap(rgba[pixel * 4], rgba[pixel * 4 + 2]);
231 std::memcpy(img->getData(), rgba.data(), rgba.size());
233 auto *dst =
static_cast<uint8_t *
>(img->getData());
234 for (
size_t pixel = 0; pixel < size_t(
w) *
h; ++pixel) {
235 const Color color = hdrPixelToColor(rgba.data() + pixel * 8);
236 dst[pixel * 4 + 0] = uint8_t(std::clamp(
color.r * 255.f, 0.f, 255.f));
237 dst[pixel * 4 + 1] = uint8_t(std::clamp(
color.g * 255.f, 0.f, 255.f));
238 dst[pixel * 4 + 2] = uint8_t(std::clamp(
color.b * 255.f, 0.f, 255.f));
239 dst[pixel * 4 + 3] = uint8_t(std::clamp(
color.a * 255.f, 0.f, 255.f));
243 throw Exception(
"WebGPU: texture readback failed");
245 return img.release();
249 if (!canvas || !canvas->hdr)
return nullptr;
252 std::vector<uint8_t> rgba16f;
253 if (!copyTextureToCpu(instance,
device, queue, canvas->color,
w,
h, rgba16f, 8))
return nullptr;
255 std::memcpy(img->getData(), rgba16f.data(), rgba16f.size());
260 submitPendingDeferredPasses();
261 if (!
device || gbufferSlots.empty() || gbufferWidth <= 0 || gbufferHeight <= 0)
return nullptr;
262 GbufferSlot &
slot = gbufferSlots[std::min<size_t>(lastGbufferSlot, gbufferSlots.size() - 1)];
264 if (attachment ==
"depth")
265 src =
slot.depthColor;
266 else if (attachment ==
"normal")
268 else if (attachment ==
"albedo")
270 else if (attachment ==
"pbrParams")
271 src =
slot.pbrParams;
272 else if (attachment ==
"emissive")
277 std::vector<uint8_t> rgba;
278 const bool hdr = attachment ==
"emissive";
279 if (!copyTextureToCpu(instance,
device, queue, src, gbufferWidth, gbufferHeight, rgba, hdr ? 8 : 4))
return nullptr;
281 const size_t channels = size_t(gbufferWidth) * size_t(gbufferHeight) * 4;
282 for (
size_t i = 0; i <
channels; ++i) {
284 std::memcpy(&half, rgba.data() + i * 2,
sizeof(half));
285 rgba[i] = uint8_t(std::lround(std::clamp(glm::unpackHalf1x16(half), 0.f, 1.f) * 255.f));
290 std::memcpy(
image->getData(), rgba.data(), rgba.size());
291 if (attachment ==
"depth") {
293 auto*
pixels =
static_cast<uint8_t*
>(
image->getData());
294 const size_t pixelCount = size_t(gbufferWidth) * size_t(gbufferHeight);
295 for (
size_t i = 0; i < pixelCount; ++i) {
304 submitPendingDeferredPasses();
305 if (!
device || decalSlots.empty() || decalWidth <= 0 || decalHeight <= 0)
return nullptr;
306 DecalSlot &
slot = decalSlots[std::min<size_t>(lastDecalSlot, decalSlots.size() - 1)];
308 if (attachment ==
"albedo")
310 else if (attachment ==
"normal")
312 else if (attachment ==
"params")
316 std::vector<uint8_t> rgba;
317 if (!copyTextureToCpu(instance,
device, queue, src, decalWidth, decalHeight, rgba))
return nullptr;
319 std::memcpy(
image->getData(), rgba.data(), rgba.size());
329bool encodeRgbaToPng(
const std::string &
path,
int width,
int height,
const std::vector<uint8_t> &rgba) {
332 std::memcpy(img.getData(), rgba.data(), rgba.size());
333 std::unique_ptr<eve::filesystem::FileData> png(
334 img.encode(medialoader::FormatHandler::ENCODED_PNG,
path.c_str(),
false));
335 if (!png)
return false;
336 std::ofstream
out(
path, std::ios::binary);
337 if (!
out)
return false;
338 out.write(
static_cast<const char *
>(png->getData()),
static_cast<std::streamsize
>(png->getSize()));
349 if ((pendingReadback_ && !pendingReadback_->done) || !
device)
return false;
351 wgpu::Texture src = presented ? presentedReadback : lastReadbackTex;
352 int w = presented ? presentedReadbackW : lastReadbackW;
353 int h = presented ? presentedReadbackH : lastReadbackH;
354 if (!src ||
w <= 0 ||
h <= 0) {
356 if (sceneColorSlots.empty())
return false;
357 const uint32_t
slot = lastPresentSlot;
358 if (
slot >= sceneColorSlots.size())
return false;
359 src = sceneColorSlots[
slot].color;
361 h = sceneColorHeight;
362 if (!src ||
w <= 0 ||
h <= 0)
return false;
365 const bool hdr = src.GetFormat() == wgpu::TextureFormat::RGBA16Float;
367 src.GetFormat() == wgpu::TextureFormat::BGRA8Unorm || src.GetFormat() == wgpu::TextureFormat::BGRA8UnormSrgb;
368 uint64_t bytesPerRow =
static_cast<uint64_t
>(
w * (hdr ? 8 : 4));
369 bytesPerRow = (bytesPerRow + 255) / 256 * 256;
370 const uint64_t
size = bytesPerRow *
static_cast<uint64_t
>(
h);
372 WGPUBufferDescriptor bd{};
373 bd.label =
sv(
"eve_readback");
375 bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
376 bd.mappedAtCreation =
false;
377 wgpu::Buffer dst =
device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor *
>(&bd));
378 if (!dst)
return false;
383 wgpu::CommandEncoder enc =
device.CreateCommandEncoder();
384 WGPUTexelCopyTextureInfo
from{};
385 from.texture = src.Get();
387 from.aspect = WGPUTextureAspect_All;
388 from.origin = {0, 0, 0};
389 WGPUTexelCopyBufferInfo
to{};
390 to.buffer = dst.Get();
391 to.layout.offset = 0;
392 to.layout.bytesPerRow =
static_cast<uint32_t
>(bytesPerRow);
393 to.layout.rowsPerImage =
static_cast<uint32_t
>(
h);
394 WGPUExtent3D extent{
static_cast<uint32_t
>(
w),
static_cast<uint32_t
>(
h), 1};
395 enc.CopyTextureToBuffer(
reinterpret_cast<const wgpu::TexelCopyTextureInfo *
>(&
from),
396 reinterpret_cast<const wgpu::TexelCopyBufferInfo *
>(&
to),
397 reinterpret_cast<const wgpu::Extent3D *
>(&extent));
398 wgpu::CommandBuffer cmd = enc.Finish();
399 queue.Submit(1, &cmd);
401 auto pr = std::make_unique<PendingReadback>();
405 pr->bytesPerRow = bytesPerRow;
410 WGPUBufferMapCallbackInfo cbInfo{};
411 cbInfo.mode = WGPUCallbackMode_AllowSpontaneous;
412 cbInfo.callback = [](WGPUMapAsyncStatus
status, WGPUStringView ,
void *userdata1,
void * ) {
413 auto *
p =
static_cast<PendingReadback *
>(userdata1);
414 p->mapped = (
status == WGPUMapAsyncStatus_Success);
416 cbInfo.userdata1 = pr.get();
417 wgpuBufferMapAsync(dst.Get(), WGPUMapMode_Read, 0,
size, cbInfo);
419 pendingReadback_ = std::move(pr);
424 if (!pendingReadback_)
return 0;
425 if (!pendingReadback_->done)
return 1;
426 return pendingReadback_->ok ? 2 : 3;
430 if (!pendingReadback_ || pendingReadback_->done)
return;
431 auto &pr = *pendingReadback_;
436#if defined(__EMSCRIPTEN__)
437 wgpuInstanceProcessEvents(instance.Get());
441 const uint8_t *data =
442 static_cast<const uint8_t *
>(pr.dst.GetConstMappedRange(0, pr.bytesPerRow *
static_cast<uint64_t
>(pr.height)));
443 std::vector<uint8_t> rgba(
static_cast<size_t>(pr.width) * pr.height * 4);
445 for (
int y = 0;
y < pr.height; ++
y) {
446 auto *dst = rgba.data() + size_t(
y) * pr.width * 4;
447 const auto *row = data + size_t(
y) * pr.bytesPerRow;
448 for (
int x = 0;
x < pr.width; ++
x) {
450 const auto color = hdrPixelToColor(row +
size_t(
x) * 8);
451 dst[
x * 4] = uint8_t(std::clamp(
color.r * 255.f, 0.f, 255.f));
452 dst[
x * 4 + 1] = uint8_t(std::clamp(
color.g * 255.f, 0.f, 255.f));
453 dst[
x * 4 + 2] = uint8_t(std::clamp(
color.b * 255.f, 0.f, 255.f));
454 dst[
x * 4 + 3] = uint8_t(std::clamp(
color.a * 255.f, 0.f, 255.f));
456 dst[
x * 4] = row[
x * 4 + (pr.bgra ? 2 : 0)];
457 dst[
x * 4 + 1] = row[
x * 4 + 1];
458 dst[
x * 4 + 2] = row[
x * 4 + (pr.bgra ? 0 : 2)];
459 dst[
x * 4 + 3] = row[
x * 4 + 3];
465 pr.ok = data && encodeRgbaToPng(pr.path, pr.width, pr.height, rgba);
std::map< std::string, std::vector< Key >, std::less<> > channels
wgpu::PopErrorScopeStatus status
std::future< JobOutput > future
EVENGINE_API_FOUNDATION public API.
bool screenReadbackEnabled
image::ImageData * readGBufferToImageData(const std::string &attachment) override
Reads g buffer to image data.
void pumpReadback()
Advances a pending frame readback; called every present().
Color getPixelImpl(OffscreenCanvas *canvas, int x, int y)
Blocking CPU readback of an offscreen canvas or scene color target.
image::ImageData * newImageData() override
Creates a image data. @ownership Caller deletes unless documented otherwise.
image::ImageData * newHDRImageDataImpl(OffscreenCanvas *canvas)
Blocking linear RGBA16F readback of an HDR offscreen canvas. @ownership The caller owns the returned ...
bool beginFrameReadback(const std::string &path) override
Begins frame readback.
image::ImageData * newImageDataImpl(OffscreenCanvas *canvas)
Creates a image data impl. @ownership Caller deletes unless documented otherwise.
int frameReadbackStatus() const override
Frame readback status.
Color getPixel(int x, int y) override
Returns the pixel.
image::ImageData * readDecalLayerToImageData(const std::string &attachment) override
Reads decal layer to image data.
Offscreen render target (RGBA8Unorm color, optional Depth32Float). 2D batches are flushed into the ca...
int getWidth() const override
Returns the width.
int getHeight() const override
Returns the height.
Represents raw pixel data.
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
eve::Result< void > success()