Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(native): a native frame can now prove it drew something

esenginec885fa6a2f9c
diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt
index c4d07aa67..a76adeda9 100644
--- a/native/CMakeLists.txt
+++ b/native/CMakeLists.txt
@@ -231,6 +231,7 @@ if(ESTELLA_QUICKJS_DIR)
host/Host.cpp
host/Runtime.cpp
host/BootLog.cpp
+ host/Shot.cpp
host/EsnShim.cpp
host/bindings/HeapBindings.cpp
host/bindings/EcsBindings.cpp
diff --git a/native/host/Host.cpp b/native/host/Host.cpp
index 4f240fe74..2fa8c4c4c 100644
--- a/native/host/Host.cpp
+++ b/native/host/Host.cpp
@@ -21,6 +21,7 @@
#include "BootLog.hpp"
#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on
+#include "Shot.hpp"
#include "esengine/core/Log.hpp"
#include "esengine/core/World.hpp"
#include "esengine/ecs/TransformSystem.hpp"
@@ -174,6 +175,9 @@ bool bindSurface() {
h.platform->surfaceSize(w, hh);
h.w = (f32)w;
h.h = (f32)hh;
+ // Before configureSurface, always: the copy usage is part of the swapchain's
+ // configuration, so asking afterwards would silently do nothing.
+ h.gfx->setSurfaceReadback(shotWanted());
if (!h.gfx->configureSurface(h.platform->surface(), w, hh)) {
ESHOST_LOGE("configureSurface failed");
return false;
@@ -303,6 +307,10 @@ void frame() {
h.lastFrameAt = nowAt;
h.haveLastFrame = true;
+ // Booked before the game renders, because the copy is served from inside the
+ // renderer's own endFrame (see Shot.hpp).
+ shotBeforeFrame(*h.gfx, h.frame, (u32)h.w, (u32)h.h);
+
JSValue dt = JS_NewFloat64(h.js, deltaSeconds);
callJs(h, "update", 1, &dt);
JS_FreeValue(h.js, dt);
@@ -328,9 +336,12 @@ void frame() {
// left here is what only a host can do: flip the swapchain.
if (!jsOwnsFrame(h)) fallbackFrame(h);
h.gfx->present();
+ if (shotAfterPresent(*h.gfx)) h.quitRequested = true;
if (++h.frame % 120 == 0) ESHOST_LOGI("real-SDK frame %llu", (unsigned long long)h.frame);
}
+bool quitRequested() { return hostAlive() && host().quitRequested; }
+
// Push one host touch to the game's es_onNativeTouch(type,id,x,y), which fans it
// out to the NativeBridge's registered listener.
void touch(int type, int id, float x, float y) {
diff --git a/native/host/Host.hpp b/native/host/Host.hpp
index 86e8f0a4d..891b87a94 100644
--- a/native/host/Host.hpp
+++ b/native/host/Host.hpp
@@ -234,6 +234,11 @@ void memoryWarning();
bool booted();
+/** @brief Whether the host has asked its event loop to stop. Set by a capture run
+ * (`ESTELLA_SHOT_QUIT`, see Shot.hpp) and by nothing else; a platform
+ * whose OS owns the app's lifetime may ignore it. */
+bool quitRequested();
+
/** Whether a surface is currently bound — false while the window is gone, which is
* when an event loop should block for events instead of spinning on frames. */
bool surfaceBound();
diff --git a/native/host/Runtime.hpp b/native/host/Runtime.hpp
index 2edae7e72..888873516 100644
--- a/native/host/Runtime.hpp
+++ b/native/host/Runtime.hpp
@@ -76,6 +76,9 @@ struct HostState {
esengine::f32 w = 0, h = 0;
bool ready = false; ///< engine + JS booted once
bool surfaceReady = false; ///< a live window surface is bound (false while screen off)
+ /// The host asked its event loop to stop. Only a capture run sets it (Shot.hpp);
+ /// a platform whose OS owns the app's lifetime is free to ignore it.
+ bool quitRequested = false;
uint64_t frame = 0;
/// When the last frame was stepped, for the delta the next one reports. Unset
/// until the first frame and cleared whenever the surface goes away, so a
diff --git a/native/host/Shot.cpp b/native/host/Shot.cpp
new file mode 100644
index 000000000..129f48dcb
--- /dev/null
+++ b/native/host/Shot.cpp
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Shot.cpp
+ * @brief The frame capture and its verdict. See Shot.hpp for what and why.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#include "Shot.hpp"
+
+#include <cstdio>
+#include <cstdlib>
+#include <string>
+#include <vector>
+
+#include "Runtime.hpp" // ESHOST_LOGI / ESHOST_LOGE
+#include "esengine/renderer/webgpu/WebGPUDevice.hpp"
+
+namespace eshost {
+
+using esengine::u32;
+using esengine::u64;
+using esengine::u8;
+
+namespace {
+
+/** The capture in flight, and what it is for. */
+struct ShotState {
+ bool asked = false;
+ bool started = false;
+ bool done = false;
+ u64 atFrame = 60;
+ bool quitAfter = false;
+ std::string outPath;
+ esengine::ReadbackHandle handle = esengine::ReadbackHandle::Invalid;
+ u32 width = 0;
+ u32 height = 0;
+};
+
+ShotState& state() {
+ static ShotState s = [] {
+ ShotState init;
+ const char* out = std::getenv("ESTELLA_SHOT");
+ const char* at = std::getenv("ESTELLA_SHOT_FRAME");
+ const char* quit = std::getenv("ESTELLA_SHOT_QUIT");
+ // The frame number alone is enough to ask for a capture: the verdict is the
+ // point, and the file is only there for a human to look at afterwards.
+ init.asked = (out && out[0]) || (at && at[0]);
+ if (out) init.outPath = out;
+ if (at && at[0]) {
+ const long n = std::strtol(at, nullptr, 10);
+ if (n > 0) init.atFrame = static_cast<u64>(n);
+ }
+ init.quitAfter = quit && quit[0] == '1';
+ return init;
+ }();
+ return s;
+}
+
+/**
+ * The verdict, computed exactly as the web render checks compute it.
+ *
+ * `spread` is the sum of each channel's max-minus-min over the frame; above 16
+ * counts as drawn. A frame cleared to one colour spreads zero however bright it
+ * is, which is the case that matters: rendering nothing still presents a clear.
+ */
+void logVerdict(const std::vector<u8>& rgba, u32 w, u32 h, bool bgra) {
+ int lo[3] = {255, 255, 255};
+ int hi[3] = {0, 0, 0};
+ u64 nonZero = 0;
+ for (size_t i = 0; i + 3 < rgba.size(); i += 4) {
+ for (int k = 0; k < 3; ++k) {
+ const int v = rgba[i + k];
+ if (v < lo[k]) lo[k] = v;
+ if (v > hi[k]) hi[k] = v;
+ }
+ if (rgba[i] | rgba[i + 1] | rgba[i + 2]) ++nonZero;
+ }
+ // Report in RGB order whatever the surface's byte order is, so the numbers mean
+ // the same thing on Metal (BGRA) and Vulkan (RGBA).
+ const int r = bgra ? 2 : 0, b = bgra ? 0 : 2;
+ const int spread = (hi[r] - lo[r]) + (hi[1] - lo[1]) + (hi[b] - lo[b]);
+ const u64 total = static_cast<u64>(w) * h;
+ ESHOST_LOGI("shot verdict: {\"w\":%u,\"h\":%u,\"totalPixels\":%llu,\"nonZeroPixels\":%llu,"
+ "\"min\":[%d,%d,%d],\"max\":[%d,%d,%d],\"spread\":%d,\"rendered\":%s}",
+ w, h, (unsigned long long)total, (unsigned long long)nonZero,
+ lo[r], lo[1], lo[b], hi[r], hi[1], hi[b], spread, spread > 16 ? "true" : "false");
+}
+
+} // namespace
+
+bool shotWanted() { return state().asked; }
+
+void shotBeforeFrame(esengine::WebGPUDevice& gfx, u64 frame, u32 w, u32 h) {
+ ShotState& s = state();
+ if (!s.asked || s.started || s.done || frame < s.atFrame || w == 0 || h == 0) return;
+ s.started = true;
+ s.width = w;
+ s.height = h;
+ // Booked, not taken: the copy happens inside the renderer's endFrame, which is
+ // the only point at which this frame is both finished and still ours.
+ s.handle = gfx.captureNextFrame(w, h);
+ if (s.handle == esengine::ReadbackHandle::Invalid) {
+ ESHOST_LOGE("shot: the swapchain cannot be captured — see the WebGPU error above");
+ s.done = true;
+ }
+}
+
+bool shotAfterPresent(esengine::WebGPUDevice& gfx) {
+ ShotState& s = state();
+ if (!s.started || s.done) return false;
+
+ const esengine::GfxReadbackStatus status = gfx.pollReadback(s.handle);
+ if (status == esengine::GfxReadbackStatus::Pending) return false;
+ s.done = true;
+ if (status != esengine::GfxReadbackStatus::Ready) {
+ ESHOST_LOGE("shot: readback failed");
+ return s.quitAfter;
+ }
+
+ std::vector<u8> rgba(static_cast<size_t>(s.width) * s.height * 4);
+ if (!gfx.takeReadback(s.handle, rgba.data(), rgba.size())) {
+ ESHOST_LOGE("shot: takeReadback refused the destination");
+ return s.quitAfter;
+ }
+
+ logVerdict(rgba, s.width, s.height, gfx.surfaceBytesAreBGRA());
+
+ // Raw bytes, not an image format: the verdict above is what decides anything,
+ // and an encoder compiled into every shipped binary to serve a debugging aid
+ // is weight for nothing. `tools/shot-to-png.mjs` turns this into a PNG.
+ if (!s.outPath.empty()) {
+ if (std::FILE* f = std::fopen(s.outPath.c_str(), "wb")) {
+ std::fwrite(rgba.data(), 1, rgba.size(), f);
+ std::fclose(f);
+ ESHOST_LOGI("shot: %ux%u %s bottom-up RGBA -> %s",
+ s.width, s.height, gfx.surfaceBytesAreBGRA() ? "BGRA" : "RGBA",
+ s.outPath.c_str());
+ } else {
+ ESHOST_LOGE("shot: cannot write %s", s.outPath.c_str());
+ }
+ }
+ return s.quitAfter;
+}
+
+} // namespace eshost
diff --git a/native/host/Shot.hpp b/native/host/Shot.hpp
new file mode 100644
index 000000000..047ef76e2
--- /dev/null
+++ b/native/host/Shot.hpp
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Shot.hpp
+ * @brief Read one presented frame back out of the GPU and judge it — the native
+ * host's answer to "did it actually draw anything?".
+ * @details Counting frames answers nothing: a host that renders nothing at all
+ * still reaches `real-SDK frame 360`. Until now the only evidence a
+ * native frame had pixels in it was a screenshot of a simulator, which
+ * an OS dialog sitting on top of the app quietly turns into a lie.
+ *
+ * So the host reads its own swapchain and reports the SAME verdict the
+ * web render checks compute (desktop/scripts/headless-verify.mjs):
+ * min/max per channel, their spread, and `rendered = spread > 16`. One
+ * rule, one threshold — a second one calibrated separately is two
+ * answers to one question.
+ *
+ * Driven by the environment, so nothing about a shipped game changes:
+ * - `ESTELLA_SHOT` raw RGBA output path (optional; the verdict is
+ * logged either way). Bottom-up rows, matching
+ * GfxDevice::takeReadback.
+ * - `ESTELLA_SHOT_FRAME` which frame to capture (default 60 — enough
+ * for a first scene to have loaded its assets).
+ * - `ESTELLA_SHOT_QUIT` `1` to exit once the verdict is out, which is
+ * what a CI run wants.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the Apache License, Version 2.0.
+ */
+#pragma once
+
+#include "esengine/core/Types.hpp"
+
+namespace esengine { class WebGPUDevice; }
+
+namespace eshost {
+
+/** Whether a capture was asked for. Read at device creation, because the
+ * swapchain has to be configured for copying BEFORE it exists. */
+bool shotWanted();
+
+/** Book the capture if @p frame is the one asked for. Call BEFORE the frame is
+ * rendered: the copy itself is performed inside the renderer's endFrame, since
+ * that is the last instant the swapchain image belongs to us. */
+void shotBeforeFrame(esengine::WebGPUDevice& gfx, esengine::u64 frame, esengine::u32 w, esengine::u32 h);
+
+/** Resolve an in-flight capture: write it, log the verdict.
+ * @return true when the host was asked to quit and the verdict is out. */
+bool shotAfterPresent(esengine::WebGPUDevice& gfx);
+
+} // namespace eshost
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
index e07f276ae..4930e694d 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp
@@ -293,6 +293,11 @@ bool WebGPUDevice::configureSurface(const NativeSurface& window, u32 width, u32
return configureSwapchain(width, height);
}
+bool WebGPUDevice::surfaceBytesAreBGRA() const {
+ return surface_format_ == WGPUTextureFormat_BGRA8Unorm
+ || surface_format_ == WGPUTextureFormat_BGRA8UnormSrgb;
+}
+
void WebGPUDevice::present() {
if (!surface_) return;
wgpuSurfacePresent(surface_);
@@ -324,6 +329,10 @@ bool WebGPUDevice::configureSwapchain(u32 width, u32 height) {
cfg.device = device_;
cfg.format = surface_format_;
cfg.usage = WGPUTextureUsage_RenderAttachment;
+#if !defined(__EMSCRIPTEN__)
+ // Opt-in (setSurfaceReadback): lets requestReadback copy the presented frame.
+ if (surface_readback_) cfg.usage |= WGPUTextureUsage_CopySrc;
+#endif
cfg.width = width;
cfg.height = height;
// Auto, not Opaque: let the backend pick a mode the surface advertises. A
@@ -1639,10 +1648,41 @@ void WebGPUDevice::endRenderPass() {
/** Give the swapchain texture back: the frame is over (see GfxDevice::endFrame).
* A frame may have opened several passes on it, so no single pass may do this. */
void WebGPUDevice::endFrame() {
+#if !defined(__EMSCRIPTEN__)
+ // A capture is served HERE and nowhere else: this is the last instant at which
+ // the frame is both finished and still ours. Asking from outside cannot work —
+ // whoever could ask runs after the renderer has already given the image back.
+ if (capture_id_) {
+ const u32 id = capture_id_;
+ capture_id_ = 0;
+ if (frame_texture_) {
+ submitReadbackCopy(id, frame_texture_);
+ } else {
+ // Nothing drew, so there is no image to copy. Leaving the record
+ // Pending would hang whoever is polling it.
+ auto it = readbacks_.find(id);
+ if (it != readbacks_.end()) it->second.status = GfxReadbackStatus::Failed;
+ }
+ }
+#endif
if (frame_view_) { wgpuTextureViewRelease(frame_view_); frame_view_ = nullptr; }
if (frame_texture_) { wgpuTextureRelease(frame_texture_); frame_texture_ = nullptr; }
}
+#if !defined(__EMSCRIPTEN__)
+ReadbackHandle WebGPUDevice::captureNextFrame(u32 w, u32 h) {
+ if (!isDeviceUsable() || !device_ || w == 0 || h == 0) return ReadbackHandle::Invalid;
+ if (!surface_readback_) {
+ ES_LOG_ERROR("WebGPUDevice::captureNextFrame: the surface was configured without CopySrc "
+ "(setSurfaceReadback must be on before configureSurface)");
+ return ReadbackHandle::Invalid;
+ }
+ if (capture_id_) return ReadbackHandle::Invalid; // one in flight is enough
+ capture_id_ = allocReadback(w, h);
+ return static_cast<ReadbackHandle>(capture_id_);
+}
+#endif
+
// =============================================================================
// Readback (async seam: texture → staging copy, resolved when the map lands)
// =============================================================================
@@ -1675,9 +1715,10 @@ ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u3
return ReadbackHandle::Invalid;
}
if (target == FramebufferHandle::Default) {
- // The surface texture is released at endRenderPass and carries no CopySrc;
- // page-level capture covers the presented frame instead.
- stubOnce("requestReadback(default framebuffer)");
+ // Not addressable from out here: the renderer gives the swapchain image
+ // back at the end of its own frame, so any caller is already too late.
+ // captureNextFrame reads the presented frame instead.
+ stubOnce("requestReadback(default framebuffer) — use captureNextFrame");
return ReadbackHandle::Invalid;
}
auto fit = framebuffers_.find(static_cast<u32>(target));
@@ -1685,6 +1726,16 @@ ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u3
auto tit = textures_.find(fit->second.color0);
if (tit == textures_.end() || !tit->second.texture) return ReadbackHandle::Invalid;
+ const u32 id = allocReadback(w, h);
+ if (!id) return ReadbackHandle::Invalid;
+ submitReadbackCopy(id, tit->second.texture);
+ return static_cast<ReadbackHandle>(id);
+}
+
+/** The staging buffer and its record, with no copy yet. Split from the copy so a
+ * capture can be handed a handle to poll NOW and filled in later, at the only
+ * moment the swapchain image exists (see captureNextFrame). */
+u32 WebGPUDevice::allocReadback(u32 w, u32 h) {
// copyTextureToBuffer requires a 256-byte row alignment; rows are compacted
// (and flipped to the bottom-up contract) in takeReadback.
const u32 padded = (w * 4u + 255u) & ~255u;
@@ -1692,33 +1743,39 @@ ReadbackHandle WebGPUDevice::requestReadback(FramebufferHandle target, u32 w, u3
bd.usage = WGPUBufferUsage_CopyDst | WGPUBufferUsage_MapRead;
bd.size = static_cast<u64>(padded) * h;
WGPUBuffer buffer = wgpuDeviceCreateBuffer(device_, &bd);
- if (!buffer) return ReadbackHandle::Invalid;
+ if (!buffer) return 0;
+ const u32 id = next_readback_id_++;
+ readbacks_[id] = ReadbackRec{buffer, w, h, padded, GfxReadbackStatus::Pending};
+ return id;
+}
+
+void WebGPUDevice::submitReadbackCopy(u32 id, WGPUTexture source) {
+ auto it = readbacks_.find(id);
+ if (it == readbacks_.end() || !source) return;
+ ReadbackRec& rec = it->second;
WGPUCommandEncoder encoder = wgpuDeviceCreateCommandEncoder(device_, nullptr);
WGPUTexelCopyTextureInfo src = WGPU_TEXEL_COPY_TEXTURE_INFO_INIT;
- src.texture = tit->second.texture;
+ src.texture = source;
WGPUTexelCopyBufferInfo dst = WGPU_TEXEL_COPY_BUFFER_INFO_INIT;
- dst.buffer = buffer;
+ dst.buffer = rec.buffer;
dst.layout.offset = 0;
- dst.layout.bytesPerRow = padded;
- dst.layout.rowsPerImage = h;
- WGPUExtent3D size{w, h, 1};
+ dst.layout.bytesPerRow = rec.paddedBytesPerRow;
+ dst.layout.rowsPerImage = rec.height;
+ WGPUExtent3D size{rec.width, rec.height, 1};
wgpuCommandEncoderCopyTextureToBuffer(encoder, &src, &dst, &size);
WGPUCommandBuffer commands = wgpuCommandEncoderFinish(encoder, nullptr);
wgpuCommandEncoderRelease(encoder);
wgpuQueueSubmit(queue_, 1, &commands);
wgpuCommandBufferRelease(commands);
- const u32 id = next_readback_id_++;
- readbacks_[id] = ReadbackRec{buffer, w, h, padded, GfxReadbackStatus::Pending};
-
WGPUBufferMapCallbackInfo cb = WGPU_BUFFER_MAP_CALLBACK_INFO_INIT;
cb.mode = WGPUCallbackMode_AllowSpontaneous;
cb.callback = &WebGPUDevice::onReadbackMapped;
cb.userdata1 = this;
cb.userdata2 = reinterpret_cast<void*>(static_cast<uintptr_t>(id));
- wgpuBufferMapAsync(buffer, WGPUMapMode_Read, 0, bd.size, cb);
- return static_cast<ReadbackHandle>(id);
+ wgpuBufferMapAsync(rec.buffer, WGPUMapMode_Read, 0,
+ static_cast<u64>(rec.paddedBytesPerRow) * rec.height, cb);
}
GfxReadbackStatus WebGPUDevice::pollReadback(ReadbackHandle handle) {
diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.hpp b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
index 21797a248..f184eed0d 100644
--- a/src/esengine/renderer/webgpu/WebGPUDevice.hpp
+++ b/src/esengine/renderer/webgpu/WebGPUDevice.hpp
@@ -210,6 +210,35 @@ public:
* host must present the surface explicitly, once per frame after
* endRenderPass. No-op until a surface is configured. */
void present();
+
+ /**
+ * @brief Configure the swapchain with CopySrc, so {@link captureNextFrame}
+ * can read it. Must be set BEFORE the surface is configured.
+ *
+ * Off by default: a surface is entitled not to support the usage, and every
+ * shipped frame would pay for a check nobody asked for.
+ */
+ void setSurfaceReadback(bool enabled) { surface_readback_ = enabled; }
+
+ /**
+ * @brief Copy the next completed frame's swapchain image into a readback,
+ * resolved through the usual pollReadback / takeReadback pair.
+ *
+ * Books the copy; endFrame performs it, because the renderer gives the
+ * swapchain image back there and every caller outside runs too late.
+ *
+ * Invalid without {@link setSurfaceReadback}, or with a capture in flight.
+ */
+ ReadbackHandle captureNextFrame(u32 w, u32 h);
+
+ /**
+ * @brief Whether bytes read back from the DEFAULT framebuffer are BGRA rather
+ * than RGBA.
+ *
+ * The format is the surface's choice (BGRA8 on Metal, RGBA8 on Vulkan), so
+ * anyone writing an image has to ask rather than assume.
+ */
+ bool surfaceBytesAreBGRA() const;
#endif
void endFrame() override;
@@ -346,6 +375,10 @@ private:
// masks and depth-tested draws target the backbuffer and expect them.
WGPUSurface surface_ = nullptr;
WGPUTextureFormat surface_format_ = WGPUTextureFormat_RGBA8Unorm;
+ /** Whether the surface was configured with CopySrc — see setSurfaceReadback. */
+ bool surface_readback_ = false;
+ /** A capture booked by captureNextFrame, served by endFrame. 0 = none. */
+ u32 capture_id_ = 0;
u32 surface_width_ = 0;
u32 surface_height_ = 0;
WGPUTexture surface_depth_texture_ = nullptr;
@@ -365,6 +398,9 @@ private:
void* userdata1, void* userdata2);
/** @brief Erases + releases a readback record (aborts a still-pending map). */
void releaseReadback(u32 id);
+ /** A staging buffer + record with no copy submitted yet; 0 on failure. */
+ u32 allocReadback(u32 w, u32 h);
+ void submitReadbackCopy(u32 id, WGPUTexture source);
// Internal clear family (region-scoped clears + mid-pass clearStencil).
// Explicit layout so ONE bind group serves every write-mask variant.
diff --git a/tools/shot-to-png.mjs b/tools/shot-to-png.mjs
new file mode 100644
index 000000000..d620b139b
--- /dev/null
+++ b/tools/shot-to-png.mjs
@@ -0,0 +1,90 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+//
+/**
+ * @file shot-to-png.mjs — a native host capture (ESTELLA_SHOT, see
+ * native/host/Shot.hpp), as a PNG.
+ *
+ * node tools/shot-to-png.mjs <shot.rgba> <width> <height> [--rgba] [-o out.png]
+ *
+ * Input is bottom-up (GfxDevice::takeReadback) and BGRA unless --rgba says so;
+ * the host logs which it wrote. The encoder is here rather than in the host
+ * because the verdict the host logs is what decides anything — a shipped binary
+ * should not carry an image format for a human's occasional look.
+ */
+
+import { readFileSync, writeFileSync } from 'node:fs';
+import { deflateSync } from 'node:zlib';
+
+const args = process.argv.slice(2);
+const positional = args.filter((a) => !a.startsWith('-'));
+const [input, widthArg, heightArg] = positional;
+if (!input || !widthArg || !heightArg) {
+ console.error('usage: shot-to-png.mjs <shot.rgba> <width> <height> [--rgba] [-o out.png]');
+ process.exit(2);
+}
+const width = Number(widthArg);
+const height = Number(heightArg);
+const isRgba = args.includes('--rgba');
+const outIndex = args.indexOf('-o');
+const output = outIndex >= 0 ? args[outIndex + 1] : input.replace(/\.[^.]*$/, '') + '.png';
+
+const raw = readFileSync(input);
+const expected = width * height * 4;
+if (raw.length !== expected) {
+ console.error(`${input} is ${raw.length} bytes; ${width}x${height} RGBA is ${expected}.`);
+ process.exit(1);
+}
+
+// PNG wants top-down rows, each prefixed with a filter byte (0 = None).
+const stride = width * 4;
+const scanlines = Buffer.alloc((stride + 1) * height);
+for (let y = 0; y < height; y++) {
+ const src = (height - 1 - y) * stride;
+ const dst = y * (stride + 1);
+ scanlines[dst] = 0;
+ raw.copy(scanlines, dst + 1, src, src + stride);
+ if (!isRgba) {
+ for (let x = dst + 1; x < dst + 1 + stride; x += 4) {
+ const b = scanlines[x];
+ scanlines[x] = scanlines[x + 2];
+ scanlines[x + 2] = b;
+ }
+ }
+}
+
+const CRC_TABLE = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+const crc32 = (buf) => {
+ let c = 0xffffffff;
+ for (const byte of buf) c = CRC_TABLE[(c ^ byte) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+
+const chunk = (type, data) => {
+ const head = Buffer.alloc(8);
+ head.writeUInt32BE(data.length, 0);
+ head.write(type, 4, 'ascii');
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])), 0);
+ return Buffer.concat([head, data, crc]);
+};
+
+const ihdr = Buffer.alloc(13);
+ihdr.writeUInt32BE(width, 0);
+ihdr.writeUInt32BE(height, 4);
+ihdr[8] = 8; // bit depth
+ihdr[9] = 6; // colour type: RGBA
+// 10/11/12 stay 0: deflate, adaptive filtering, no interlace.
+
+writeFileSync(output, Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(scanlines, { level: 9 })),
+ chunk('IEND', Buffer.alloc(0)),
+]));
+console.log(`${output} (${width}x${height}, from ${isRgba ? 'RGBA' : 'BGRA'} bottom-up)`);