diff --git a/AGENTS.md b/AGENTS.md index 46dc62ff..88c10f0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,6 +53,14 @@ platform setup (Vulkan SDK, GLFW, etc.). The editor's GPU Options window (menu Windows; drawn in `--play` too) changes the rate, the cap, VSync and interpolation at run time. Detail: [`Docs/time-and-ticks.md`](Docs/time-and-ticks.md) section 2. +- See a run without a window: `--dump-state ` writes the simulation + state as JSON at chosen ticks (works with `--null-render`), and `--offscreen + --screenshot ` renders with Vulkan into offscreen images and saves PNG + files (no window, no display; a software driver such as llvmpipe is enough). + Prefer the state dump; use screenshots for rendering work. From C++ (any + module, any thread): `Fling::Screenshot::Request(path, callback)` in + `Screenshot.h`; the editor's GPU Options window has a Take screenshot button. Detail: + [`Skills/testing.md`](Skills/testing.md#seeing-the-game-without-a-window). - Drive a headless run with `--replay-input `. Agents can write their own `.input.jsonl` files. Format and flags: [`Skills/input-playback.md`](Skills/input-playback.md). - Load a level other than `[Game] StartLevel` with `--level ` (relative diff --git a/Assets/Shaders/Deferred/deferred.frag b/Assets/Shaders/Deferred/deferred.frag index 8501131f..415d033d 100644 --- a/Assets/Shaders/Deferred/deferred.frag +++ b/Assets/Shaders/Deferred/deferred.frag @@ -12,6 +12,9 @@ layout (binding = 4) uniform sampler2D samplerMetal; layout (binding = 5) uniform sampler2D samplerRoughness; // In UV from the vertex shader +// True on a CPU driver such as llvmpipe (VK_PHYSICAL_DEVICE_TYPE_CPU): see the loop counts in main +layout (constant_id = 0) const bool CPU_DRIVER = false; + layout (location = 0) in vec2 inUV; // Final screen color @@ -60,10 +63,25 @@ void main() // so that calculations only have to be done for visible fragments // independent of no. of lights. + // The loop counts. On a CPU driver only (CPU_DRIVER, set by GeometrySubpass), the min with + // a value only the GPU knows (the G-buffer size, never 0) changes nothing, but keeps the + // driver from compiling the shader again for each count: llvmpipe's uniform inlining does + // that for loop bounds read from a uniform buffer, and its code for these two loops reads + // a null pointer (a crash on CPU rendering). A GPU driver removes the branch when it + // specializes the shader, so it pays nothing + uint DirLightCount = lights.DirLightCount; + uint PointLightCount = lights.PointLightCount; + if (CPU_DRIVER) + { + const uint NotInlined = uint(textureSize(samplerposition, 0).x) + 128u; + DirLightCount = min(DirLightCount, NotInlined); + PointLightCount = min(PointLightCount, NotInlined); + } + // Ambient part vec3 LightColor = vec3(0.0, 0.0, 0.0); // Directional lights ------------------------- - for(uint i = 0; i < lights.DirLightCount; i++) + for(uint i = 0; i < DirLightCount; i++) { LightColor += DirLightPBR( lights.DirLights[i], @@ -78,7 +96,7 @@ void main() } // Point lights ------------------------- - for(uint i = 0; i < lights.PointLightCount; i++) + for(uint i = 0; i < PointLightCount; i++) { // Vector to light vec3 L = lights.PointLights[i].Pos.xyz - fragPos; diff --git a/Docs/agent-guide.md b/Docs/agent-guide.md index c6e94523..beec0e06 100644 --- a/Docs/agent-guide.md +++ b/Docs/agent-guide.md @@ -770,7 +770,11 @@ flag or key. The startup line `Run settings: ...` names each value and its sourc | Interpolation | `--interpolation on\|off` | `Interpolation` | on | GPU Options | | Thread jitter (tests) | `--thread-jitter S:U` (threaded only; an error otherwise) | none | off | no | -Other flags: `--null-render` (no window or GPU, virtual clock), `--unattended` (no +Other flags: `--null-render` (no window or GPU, virtual clock), `--offscreen` (render +with the GPU into images, no window, with the timing of `--null-render`), +`--resolution WxH`, `--screenshot ` and `--screenshot-ticks L` (PNG of the +frame that shows each tick), `--dump-state ` and `--dump-state-ticks L` (the +simulation state as JSON after each tick), `--unattended` (no dialogs; a crash exits 2 with a stack trace), `--frames N` (see below), `--frames-per-tick N` (headless frames between ticks), `--seed S`, `--level ` (relative to `Assets/`), `--play`, `--dump-schedule`, `--validate-schedule`, `--dump-ticks `, @@ -829,6 +833,9 @@ the tests from the repository root. clang-cl configure flags are in Headless run: `Sandbox --null-render --unattended --frames 120 --seed 1` (the last log lines print `Sandbox: 754 transforms, checksum ...` and `Fling exit: code=0 ticks=120 ...`). +To see what a run did without a window, read the state (`--dump-state`), or render +offscreen and look at a PNG (`--offscreen --screenshot`; a software Vulkan driver such +as llvmpipe is enough): `Skills/testing.md`, "Seeing the game without a window". Test layout (Catch2 3; each executable links only its module): diff --git a/FlingEngine/Application/inc/Engine.h b/FlingEngine/Application/inc/Engine.h index 5318a889..d3e5f7d3 100644 --- a/FlingEngine/Application/inc/Engine.h +++ b/FlingEngine/Application/inc/Engine.h @@ -25,6 +25,8 @@ #include #include #include +#include +#include /** * Triggers a breakpoint at the call site, halting execution if a debugger is attached. @@ -50,8 +52,9 @@ namespace Fling * along with all startup/shutdown ordering. * * The loop does not need a window: with --null-render the engine makes no - * window and no GPU device, and ticks with a fixed delta. See LaunchOptions - * for the launch flags. + * window and no GPU device, and ticks with a fixed delta. With --offscreen it + * renders with the GPU into images it owns, still with no window, on the same + * fixed delta. See LaunchOptions for the launch flags. */ class Engine { @@ -238,6 +241,24 @@ namespace Fling /** Writes the ledger rows of the ticks since the last call to the --dump-ticks file (main thread). */ void DumpNewTicks(); + /** Writes the state dumps that the ticks made since the last call to their --dump-state files (main thread). */ + void WriteStateDumps(); + + /** Before the frame is drawn: a Screenshot::Request for each --screenshot tick that it shows. */ + void RequestScreenshots(); + + /** --dump-state: the ticks whose state has not been written yet. Sorted. */ + std::vector m_PendingStateDumps; + + /** --dump-state: files that could not be written. */ + uint32 m_StateDumpsFailed = 0; + + /** --screenshot: the ticks whose frame has not been saved yet. Sorted. */ + std::vector m_PendingScreenshots; + + /** --screenshot: captures that failed. */ + uint32 m_ScreenshotsFailed = 0; + /** The exec mode's policies: the world's mode and last tick, and for threaded play the game thread and input. */ void SetUpExecMode(); diff --git a/FlingEngine/Application/src/Engine.cpp b/FlingEngine/Application/src/Engine.cpp index be314e83..eaf7d4e9 100644 --- a/FlingEngine/Application/src/Engine.cpp +++ b/FlingEngine/Application/src/Engine.cpp @@ -17,12 +17,14 @@ #include "PresentMode.h" #include "Random.h" #include "RegisterGraphics.h" +#include "Screenshot.h" #include "Strings/String.h" #include "Threading/Lane.h" #include "Threading/Thread.h" #include "VulkanApp.h" #include +#include #include #include #include @@ -286,10 +288,10 @@ namespace Fling ResourceManager::Get().Init(); Timing::Get().Init(); - // A headless run has no real time: the platform clock is virtual, and the loop - // moves it by a fixed step per frame. Install it before input, so every input - // message time comes from it. - if (m_Options.NullRender) + // A headless run (--null-render or --offscreen) has no real time: the platform clock + // is virtual, and the loop moves it by a fixed step per frame. Install it before + // input, so every input message time comes from it. + if (m_Options.IsHeadless()) { m_HeadlessClock = std::make_unique(HeadlessFrameNs(0)); PlatformTime::UseVirtualClock(m_HeadlessClock.get()); @@ -361,11 +363,27 @@ namespace Fling } else { + RenderSurfaceDesc Surface; + Surface.Offscreen = m_Options.Offscreen; + Surface.Width = m_Options.ResolutionWidth; + Surface.Height = m_Options.ResolutionHeight; + VulkanApp::Get().SetRenderSurface(Surface); + + uint32 Pipelines = PipelineFlags::DEFERRED | PipelineFlags::CUBEMAP; + if (m_Options.Offscreen) + { + // The developer UI is ImGui, which reads its input from a window: offscreen there + // is none, so the frames show the game only + F_LOG_TRACE("Fling render: offscreen (--offscreen), no window"); + m_DebugUI.reset(); + } + else + { + Pipelines |= PipelineFlags::IMGUI; + } VulkanApp::Get().SetVSync(m_Settings.VSync); - VulkanApp::Get().Init( - static_cast(PipelineFlags::DEFERRED | PipelineFlags::CUBEMAP | PipelineFlags::IMGUI), - Storage, - m_DebugUI); + VulkanApp::Get().Init(static_cast(Pipelines), Storage, m_DebugUI); + F_LOG_TRACE("Render size: {}x{}", VulkanApp::Get().GetFrameWidth(), VulkanApp::Get().GetFrameHeight()); } // The frame cap's default is the refresh rate of the window's monitor @@ -410,11 +428,12 @@ namespace Fling m_World->SetTickClock([]() { return PlatformTime::NowNanoseconds(); }); // The per-tick state hash costs about 0.7 ms a tick in a Debug Sandbox (754 // transforms): on for headless runs and --dump-ticks, off for a windowed game. - m_World->SetStateHashEnabled(m_Options.NullRender || !m_Options.DumpTicks.empty()); + m_World->SetStateHashEnabled(m_Options.IsHeadless() || !m_Options.DumpTicks.empty() || + !m_Options.DumpState.empty()); m_World->SetInterpolation(m_Settings.Interpolation); m_Controls = std::make_unique(m_Settings, *m_World); UpdateFrameLimiter(); - if (m_Options.NullRender) + if (m_Options.IsHeadless()) { m_World->SetTickTimelineStart(HeadlessFrameNs(1) - TickNs()); m_World->SetTickClockOnlyMovesWithFrames(true); @@ -430,7 +449,7 @@ namespace Fling // every exec mode; World::MakeTickInputConfig says how a game thread waits for it: a // headless run or a replay waits for every message of the window (the cuts are the // same as in Direct), live windowed play does not wait. - const int64 WatermarkWaitNs = (m_Options.NullRender || !m_Options.ReplayInput.empty()) ? -1 : 0; + const int64 WatermarkWaitNs = (m_Options.IsHeadless() || !m_Options.ReplayInput.empty()) ? -1 : 0; auto TickInputs = std::make_shared(Input::Get(), m_World->MakeTickInputConfig(WatermarkWaitNs)); m_World->SetTickInputSource([TickInputs](TickInput& t_Out, const TickWindow& t_Window) @@ -450,6 +469,25 @@ namespace Fling m_World->KeepTickRecords(); } + // --dump-state and --screenshot: at the listed ticks, or the last tick of the run + if (!m_Options.DumpState.empty()) + { + m_PendingStateDumps = + m_Options.DumpStateTicks.empty() ? std::vector{LastTickOfRun()} : m_Options.DumpStateTicks; + m_World->SetStateDumpTicks(m_PendingStateDumps); + F_LOG_TRACE("Writing the state at {} tick(s) to {} (--dump-state)", + m_PendingStateDumps.size(), + FlingPaths::ResolveProjectPath(m_Options.DumpState)); + } + if (!m_Options.Screenshot.empty()) + { + m_PendingScreenshots = + m_Options.ScreenshotTicks.empty() ? std::vector{LastTickOfRun()} : m_Options.ScreenshotTicks; + F_LOG_TRACE("Saving the frames of {} tick(s) to {} (--screenshot)", + m_PendingScreenshots.size(), + FlingPaths::ResolveProjectPath(m_Options.Screenshot)); + } + // The runner fills PendingInput for the frame side with the messages after the cut of the tick // it shows (RealFrameTime::Latest: the packet in the mirror in Inline and Threaded // play), without consuming them. UI capture comes from the stream, so it drops the @@ -478,7 +516,7 @@ namespace Fling F_LOG_TRACE("Fling debug UI: Disabled"); } - if (!m_Options.NullRender) + if (!m_Options.IsHeadless()) { // The window exists now. Its events are pumped by the GLFW input interface m_InputWindow = GetInputWindowHandle(VulkanApp::Get().GetCurrentWindow()); @@ -551,7 +589,7 @@ namespace Fling // Under --null-render each frame has the same delta and never waits on real time // for its ticks, so a run is as fast as the CPU allows - const float DeltaTime = m_Options.NullRender ? NullRenderDeltaTime : Timing.GetDeltaTime(); + const float DeltaTime = m_Options.IsHeadless() ? NullRenderDeltaTime : Timing.GetDeltaTime(); Stats::Frames::FrameStats(DeltaTime); PumpInput(DeltaTime); @@ -561,6 +599,7 @@ namespace Fling // threaded play), the ticks' outbox, then the frame systems on what the world shows m_World->Update(DeltaTime); DumpNewTicks(); + WriteStateDumps(); HandleAppRequests(); if (m_World->ShouldQuit()) @@ -571,11 +610,16 @@ namespace Fling if (m_Options.NullRender) { + // No renderer to serve a Screenshot::Request: it fails now, so its caller hears back + Screenshot::FailPending("there is no renderer (--null-render); use --offscreen"); // No cap unless a setting asks for one (RunSettings::ResolveFrameCap), so tests stay fast m_FrameLimiter.WaitForNextFrame(); } else { + // A window, or offscreen images (--offscreen). The present saves the screenshots + // that are waiting (Screenshot::Request), from --screenshot or anywhere else + RequestScreenshots(); Present(DeltaTime); } Timing.UpdateFps(); @@ -590,6 +634,27 @@ namespace Fling m_World->GetTickCount(), AverageFrameMs, AverageFrameMs > 0.0 ? 1000.0 / AverageFrameMs : 0.0); + // The screenshots that frames copied are written on a thread: wait for them, so the checks + // below see every result + if (!m_Options.NullRender) + { + VulkanApp::Get().FinishScreenshots(); + } + // A request that no frame served (the loop ended first) fails, so its caller hears back + Screenshot::FailPending("the run ended before the next frame was drawn"); + + // A screenshot that was asked for and not made fails the run, so a script does not read an old file + bool bCapturesOk = m_ScreenshotsFailed == 0; + for (const uint64 Tick : m_PendingScreenshots) + { + F_LOG_ERROR( + "--screenshot: no frame showed tick {} (the run showed up to tick {})", Tick, m_World->GetShownTick()); + bCapturesOk = false; + } + if (!bCapturesOk) + { + return ExitCode::Failure; + } #if WITH_INPUT_RECORDING if (Input::Get().GetPlayback().HasOverrun()) { @@ -623,7 +688,7 @@ namespace Fling { for (const AppRequest Request : m_World->TakeAppRequests()) { - if (Request == AppRequest::ToggleCursor && !m_Options.NullRender) + if (Request == AppRequest::ToggleCursor && !m_Options.IsHeadless()) { FlingWindow* Window = VulkanApp::Get().GetCurrentWindow(); if (Window) @@ -641,20 +706,24 @@ namespace Fling VulkanApp::Get().SetVSync(m_Controls->VSync()); VulkanApp::Get().Update(t_DeltaTime, m_World->GetPresentedStorage()); - const bool bInBackground = !VulkanApp::Get().GetCurrentWindow()->IsFocused(); - if (bInBackground != m_Controls->InBackground()) - { - m_Controls->SetInBackground(bInBackground); - F_LOG_TRACE("Window in the {}", bInBackground ? "background" : "front"); - } - // The window can move to another monitor; a frame cap that came from the monitor follows - const int64 NowNs = PlatformTime::NowNanoseconds(); - if (NowNs >= m_NextMonitorCheckNs) + // Offscreen there is no window: no focus, no monitor, and no frame cap (headless) + if (const FlingWindow* Window = VulkanApp::Get().GetCurrentWindow()) { - m_NextMonitorCheckNs = NowNs + MonitorCheckIntervalNs; - m_Controls->SetMonitorHz(WindowMonitorHz()); + const bool bInBackground = !Window->IsFocused(); + if (bInBackground != m_Controls->InBackground()) + { + m_Controls->SetInBackground(bInBackground); + F_LOG_TRACE("Window in the {}", bInBackground ? "background" : "front"); + } + // The window can move to another monitor; a frame cap that came from the monitor follows + const int64 NowNs = PlatformTime::NowNanoseconds(); + if (NowNs >= m_NextMonitorCheckNs) + { + m_NextMonitorCheckNs = NowNs + MonitorCheckIntervalNs; + m_Controls->SetMonitorHz(WindowMonitorHz()); + } + UpdateFrameLimiter(); } - UpdateFrameLimiter(); // The game ticks on its own clock, so it runs at the same speed, only shown less often m_FrameLimiter.WaitForNextFrame(); @@ -662,14 +731,15 @@ namespace Fling std::optional Engine::WindowMonitorHz() const { - const FlingWindow* Window = m_Options.NullRender ? nullptr : VulkanApp::Get().GetCurrentWindow(); + const FlingWindow* Window = m_Options.IsHeadless() ? nullptr : VulkanApp::Get().GetCurrentWindow(); return Window != nullptr ? std::optional(Window->GetRefreshRate()) : std::nullopt; } void Engine::UpdateFrameLimiter() { // Headless there is no swap chain and no refresh rate, so the cap applies as it is - const bool bDisplayPacesFrames = !m_Options.NullRender && DisplayPacesFrames(VulkanApp::Get().GetPresentMode()); + const bool bDisplayPacesFrames = + !m_Options.IsHeadless() && DisplayPacesFrames(VulkanApp::Get().GetPresentMode()); const uint32 LimiterFps = m_Controls->LimiterFps(bDisplayPacesFrames); if (LimiterFps != m_FrameLimiter.GetMaxFps()) { @@ -677,7 +747,7 @@ namespace Fling F_LOG_TRACE("Frame limiter: {} (cap {} fps, present mode {})", m_Controls->DescribeLimiter(bDisplayPacesFrames), m_Controls->MaxFps(), - m_Options.NullRender ? "none" : PresentModeName(VulkanApp::Get().GetPresentMode())); + m_Options.IsHeadless() ? "none" : PresentModeName(VulkanApp::Get().GetPresentMode())); } } @@ -701,7 +771,7 @@ namespace Fling // as soon as it is due. Input::Get().SetWriterLane(Lane::Frame); GameLaneDesc Desc; - Desc.Pacing = m_Options.NullRender ? GameLanePacing::AsFastAsPossible : GameLanePacing::RealTime; + Desc.Pacing = m_Options.IsHeadless() ? GameLanePacing::AsFastAsPossible : GameLanePacing::RealTime; Desc.JitterSeed = m_Options.JitterSeed; Desc.JitterMaxMicroseconds = m_Options.JitterMaxMicroseconds; m_World->SetGameLaneDesc(Desc); @@ -748,6 +818,66 @@ namespace Fling m_DumpTicksFile->flush(); } + void Engine::WriteStateDumps() + { + if (!m_World || m_Options.DumpState.empty()) + { + return; + } + const bool bManyTicks = m_Options.DumpStateTicks.size() > 1; + for (const World::StateDump& Dump : m_World->TakeStateDumps()) + { + std::erase(m_PendingStateDumps, Dump.Tick); + const String Path = + FlingPaths::ResolveProjectPath(CaptureFilePath(m_Options.DumpState, Dump.Tick, bManyTicks)); + String WriteError; + if (!FlingPaths::SaveFile(Path, Dump.Doc.Dump(2) + '\n', WriteError)) + { + F_LOG_ERROR("--dump-state: {}", WriteError); + ++m_StateDumpsFailed; + continue; + } + F_LOG_TRACE("Wrote the state of tick {} ({} entities, state hash {}) to {}", + Dump.Tick, + Dump.Doc.GetUInt64("entityCount"), + Dump.Doc.GetString("stateHash"), + Path); + } + } + + void Engine::RequestScreenshots() + { + if (m_PendingScreenshots.empty()) + { + return; + } + // The frame that first shows each tick. With threaded play the frame side can show a + // later tick than the one asked for; the log line says which tick the file shows. + const uint64 Shown = m_World->GetShownTick(); + const bool bManyTicks = m_Options.ScreenshotTicks.size() > 1; + while (!m_PendingScreenshots.empty() && m_PendingScreenshots.front() <= Shown) + { + const uint64 Tick = m_PendingScreenshots.front(); + m_PendingScreenshots.erase(m_PendingScreenshots.begin()); + // The renderer serves it at this frame's present; the callback runs on this thread + Screenshot::Request(CaptureFilePath(m_Options.Screenshot, Tick, bManyTicks), + [this, Tick, Shown](const ScreenshotResult& t_Result) + { + if (!t_Result.Ok) + { + ++m_ScreenshotsFailed; + return; + } + F_LOG_TRACE("Saved the frame of tick {} (it shows tick {}, {}x{}) to {}", + Tick, + Shown, + t_Result.Width, + t_Result.Height, + t_Result.Path); + }); + } + } + bool Engine::ShouldTick() const { // --frames: the run ends after N frames, once the frame side shows the last tick (the @@ -760,7 +890,7 @@ namespace Fling return false; } - if (!m_Options.NullRender && VulkanApp::Get().GetCurrentWindow()->ShouldClose()) + if (!m_Options.IsHeadless() && VulkanApp::Get().GetCurrentWindow()->ShouldClose()) { return false; } @@ -775,6 +905,25 @@ namespace Fling { m_World->Shutdown(); m_TicksAtExit = m_World->GetTickCount(); + + // No frame is drawn from here on: a screenshot request still waiting fails, so its caller hears back + Screenshot::FailPending("the engine shut down before the next frame was drawn"); + + // The game thread has joined: a dump that it made after the last frame is here now + WriteStateDumps(); + if (!m_Options.DumpState.empty() && t_Code == ExitCode::Success) + { + bool bDumpsOk = m_StateDumpsFailed == 0; + for (const uint64 Tick : m_PendingStateDumps) + { + F_LOG_ERROR("--dump-state: tick {} did not run (the run ran {} ticks)", Tick, m_TicksAtExit); + bDumpsOk = false; + } + if (!bDumpsOk) + { + t_Code = ExitCode::Failure; + } + } } // The world still holds the game until the world is destroyed below @@ -841,7 +990,7 @@ namespace Fling { const double WallSeconds = std::chrono::duration(std::chrono::steady_clock::now() - m_StartTime).count(); - const char* Render = m_Options.NullRender ? "null" : "vulkan"; + const char* Render = m_Options.NullRender ? "null" : (m_Options.Offscreen ? "offscreen" : "vulkan"); if (m_Options.Format == LogFormat::Json) { diff --git a/FlingEngine/Core/inc/FlingPaths.h b/FlingEngine/Core/inc/FlingPaths.h index 6e8d63bd..ad275d6e 100644 --- a/FlingEngine/Core/inc/FlingPaths.h +++ b/FlingEngine/Core/inc/FlingPaths.h @@ -76,6 +76,16 @@ namespace Fling */ static void GetCurrentWorkingDir(char* t_OutBuf, size_t t_BufSize); + /** + * Write t_Bytes to a file, replacing it. Missing folders are made. Any thread. + * + * @param t_Path The file (UTF-8) + * @param t_Bytes What to write, as is (binary) + * @param t_OutError Receives why it failed + * @return True when every byte was written + */ + static bool SaveFile(StringView t_Path, StringView t_Bytes, String& t_OutError); + // TODO: Add options to get the current user's home path }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Core/inc/LaunchOptions.h b/FlingEngine/Core/inc/LaunchOptions.h index eaa4236b..b285c7f2 100644 --- a/FlingEngine/Core/inc/LaunchOptions.h +++ b/FlingEngine/Core/inc/LaunchOptions.h @@ -6,6 +6,7 @@ #include "Strings/String.h" #include +#include namespace Fling { @@ -27,6 +28,22 @@ namespace Fling * LaunchOptions::Parse. * * --null-render No window, no swapchain, no GPU work + * --offscreen Render with the GPU into images the engine owns: no window and no + * surface. Timing is the same as --null-render (a virtual clock, no + * frame cap), so a run gives the same ticks. For --screenshot + * --resolution WxH The size of the frames (--offscreen) or of the window, for example 1280x720. + * Overrides [Engine] WindowWidth and WindowHeight. A window is still + * made smaller to fit the screen + * --screenshot F Save the rendered frame as a PNG file F (relative to the project). + * Needs a renderer (--offscreen or a window), not --null-render + * --screenshot-ticks L The ticks to save a frame at, a comma list such as 30,60,120: the + * first frame that shows each tick. With more than one tick, or with + * {tick} in F, each file name gets the tick. Without it: the last tick + * of the run (needs --frames) + * --dump-state F Write the simulation state (every saved component and singleton) as + * JSON to file F, on the game thread right after a tick. Works with + * --null-render + * --dump-state-ticks L The ticks to write the state at (the same rules as --screenshot-ticks) * --unattended No modal dialogs. A crash prints a stack trace and exits with code 2 * --frames N Run N frames, then exit, in every exec mode. No tick runs after * tick N / frames-per-tick (rounded up), and the run ends once that @@ -65,6 +82,28 @@ namespace Fling { bool NullRender = false; + /** Render into offscreen images: no window, no surface (--offscreen). */ + bool Offscreen = false; + + /** --resolution: the frame or window size. 0 means use the config. */ + uint32 ResolutionWidth = 0; + uint32 ResolutionHeight = 0; + + /** The PNG file to save rendered frames to (--screenshot). Empty means none. */ + String Screenshot; + + /** The ticks to save a frame at (--screenshot-ticks). Empty: the last tick of the run. Sorted. */ + std::vector ScreenshotTicks; + + /** The JSON file to write the simulation state to (--dump-state). Empty means none. */ + String DumpState; + + /** The ticks to write the state at (--dump-state-ticks). Empty: the last tick of the run. Sorted. */ + std::vector DumpStateTicks; + + /** True with no window (--null-render, --offscreen): a virtual clock and no frame cap. */ + bool IsHeadless() const { return NullRender || Offscreen; } + bool Unattended = false; /** Number of frames to run before the engine exits (--frames). 0 means no limit. */ @@ -157,6 +196,13 @@ namespace Fling static bool Parse(const CommandLine& t_CmdLine, LaunchOptions& t_Out, String& t_OutError); }; + /** + * The file name of one capture (--screenshot, --dump-state) at a tick. "{tick}" in the path + * is replaced with the tick. Without it, when there is more than one tick, "_tick" goes + * before the extension (shot.png: shot_tick30.png). Otherwise the path is used as it is. + */ + String CaptureFilePath(StringView t_Path, uint64 t_Tick, bool t_ManyTicks); + /** Read "on" or "off" (a switch setting such as --vsync or [Engine] VSync). False for any other text. */ inline bool ParseOnOff(const StringView t_Text, bool& t_Out) { diff --git a/FlingEngine/Core/inc/RunSettings.h b/FlingEngine/Core/inc/RunSettings.h index e857bf4d..dc4a1ccb 100644 --- a/FlingEngine/Core/inc/RunSettings.h +++ b/FlingEngine/Core/inc/RunSettings.h @@ -124,6 +124,9 @@ namespace Fling /** True for a --null-render run: no monitor, and no frame cap unless a setting asks for one. */ bool Headless = false; + /** The flag that made the run headless, for messages: "--null-render" or "--offscreen". */ + const char* HeadlessFlag = "--null-render"; + /** Settings that were given but do nothing in this run, one line each, for the startup log. */ std::vector Ignored; diff --git a/FlingEngine/Core/inc/Screenshot.h b/FlingEngine/Core/inc/Screenshot.h new file mode 100644 index 00000000..a7d8350b --- /dev/null +++ b/FlingEngine/Core/inc/Screenshot.h @@ -0,0 +1,97 @@ +#pragma once + +#include "CoreAPI.h" +#include "FlingTypes.h" +#include "Strings/String.h" + +#include +#include + +namespace Fling +{ + /** How one screenshot went (Screenshot::Request). */ + struct ScreenshotResult + { + /** The file that was asked for, resolved to an absolute path. */ + String Path; + + /** True when the PNG file was written. */ + bool Ok = false; + + /** Why it failed, when Ok is false. */ + String Error; + + /** The size of the frame in pixels. 0 when it failed. */ + uint32 Width = 0; + uint32 Height = 0; + }; + + /** Called once for each request, on the main thread, after the file is written or the request fails. */ + using ScreenshotCallback = std::function; + + /** + * Save the next frame that the renderer draws as a PNG file, from anywhere in the engine: + * the editor, a frame system, a tool, a test. Request is safe on any thread, and needs no + * Graphics header: the renderer (VulkanApp) takes the requests at its next frame. It + * works with a window (the image then has the editor UI in it) and with --offscreen. + * Under --null-render there is no renderer, so each request fails at the next frame. + * + * It costs nothing when nobody asks: a frame with no request does one atomic load. A + * request does not stall the frame either: the GPU copies the frame in its own command + * buffer, and a writer thread encodes and writes the PNG. The callback arrives a few + * frames later. + * + * A frame shows the simulation state that the frame side has, not a tick on the game + * thread. To save the frame of a given tick, use --screenshot-ticks, which calls this + * when the frame side first shows that tick. + * + * Fling::Screenshot::Request("Saved/door_open.png", + * [](const Fling::ScreenshotResult& t_Result) { F_LOG_TRACE("Saved: {}", t_Result.Ok); }); + * + * Do not call it from simulation code to change the simulation: the result arrives on + * the main thread, out of step with the ticks. + */ + class CORE_API Screenshot + { + public: + /** One request waiting for a frame. The renderer side reads it. */ + struct Pending + { + String Path; + ScreenshotCallback OnDone; + }; + + /** + * Ask for the next frame to be saved. Safe on any thread. + * + * @param t_Path The PNG file. Relative paths are relative to the project folder. + * Missing folders are made. Empty: DefaultPath() + * @param t_OnDone Optional. Called on the main thread when the file is written or the + * request fails. A result is also logged either way + * @return The resolved path the file will be written to + */ + static String Request(StringView t_Path = {}, ScreenshotCallback t_OnDone = {}); + + /** A new file name under Saved/Screenshots, named with the local time, for example + * Screenshot_2026-11-16_14-03-22_1.png. */ + static String DefaultPath(); + + /** + * True when a request is waiting. One atomic load and no lock, so the renderer can ask + * every frame for free. Any thread. + */ + static bool HasPending(); + + /** + * Renderer side (main thread): the requests since the last call, in request order. + * With none waiting it takes no lock and allocates nothing. + */ + static std::vector TakePending(); + + /** Renderer side (main thread): log the result and call the request's callback. */ + static void Finish(Pending& t_Request, const ScreenshotResult& t_Result); + + /** Fail every waiting request with t_Reason (--null-render, or shutdown). Main thread. */ + static void FailPending(StringView t_Reason); + }; +} // namespace Fling diff --git a/FlingEngine/Core/src/FlingPaths.cpp b/FlingEngine/Core/src/FlingPaths.cpp index c92711d5..bf04be08 100644 --- a/FlingEngine/Core/src/FlingPaths.cpp +++ b/FlingEngine/Core/src/FlingPaths.cpp @@ -4,6 +4,8 @@ #include #include +#include +#include namespace Fling { @@ -101,4 +103,33 @@ namespace Fling } return PathToUtf8(PathFromUtf8(Root) / Path); } -} // namespace Fling \ No newline at end of file + + bool FlingPaths::SaveFile(const StringView t_Path, const StringView t_Bytes, String& t_OutError) + { + const std::filesystem::path Path = PathFromUtf8(t_Path); + if (Path.has_parent_path()) + { + std::error_code Error; + std::filesystem::create_directories(Path.parent_path(), Error); + if (Error) + { + t_OutError = "cannot make the folder " + PathToUtf8(Path.parent_path()) + ": " + Error.message(); + return false; + } + } + std::ofstream File(Path, std::ios::binary | std::ios::trunc); + if (!File) + { + t_OutError = "cannot open " + String(t_Path) + " to write"; + return false; + } + File.write(t_Bytes.data(), static_cast(t_Bytes.size())); + File.flush(); + if (!File) + { + t_OutError = "cannot write " + String(t_Path); + return false; + } + return true; + } +} // namespace Fling diff --git a/FlingEngine/Core/src/Input/InputRecording.cpp b/FlingEngine/Core/src/Input/InputRecording.cpp index c3da0d8b..db80a462 100644 --- a/FlingEngine/Core/src/Input/InputRecording.cpp +++ b/FlingEngine/Core/src/Input/InputRecording.cpp @@ -1,3 +1,4 @@ +#include "FlingPaths.h" #include "Input/InputRecording.h" #include "Strings/String.h" @@ -1098,32 +1099,7 @@ namespace Fling bool SaveInputRecording(const StringView t_Path, const InputRecording& t_Recording, String& t_OutError) { - namespace fs = std::filesystem; - std::error_code Code; - const fs::path Path = PathFromUtf8(t_Path); - if (Path.has_parent_path()) - { - fs::create_directories(Path.parent_path(), Code); - if (Code) - { - t_OutError = "cannot make folder '" + Path.parent_path().string() + "': " + Code.message(); - return false; - } - } - std::ofstream File(Path, std::ios::binary | std::ios::trunc); - if (!File) - { - t_OutError = "cannot write '" + String(t_Path) + "'"; - return false; - } - File << WriteInputRecording(t_Recording); - File.flush(); - if (!File) - { - t_OutError = "error while writing '" + String(t_Path) + "'"; - return false; - } - return true; + return FlingPaths::SaveFile(t_Path, WriteInputRecording(t_Recording), t_OutError); } String DescribeRecordedMessage(double t_TimeSeconds, StringView t_DeviceName, const InputMessage& t_Message) diff --git a/FlingEngine/Core/src/LaunchOptions.cpp b/FlingEngine/Core/src/LaunchOptions.cpp index 36d91bcc..f4dd412f 100644 --- a/FlingEngine/Core/src/LaunchOptions.cpp +++ b/FlingEngine/Core/src/LaunchOptions.cpp @@ -3,11 +3,19 @@ #include "Strings/String.h" #include "Strings/StringUtils.h" +#include + namespace Fling { namespace { constexpr StringView NullRenderFlag = "null-render"; + constexpr StringView OffscreenFlag = "offscreen"; + constexpr StringView ResolutionFlag = "resolution"; + constexpr StringView ScreenshotFlag = "screenshot"; + constexpr StringView ScreenshotTicksFlag = "screenshot-ticks"; + constexpr StringView DumpStateFlag = "dump-state"; + constexpr StringView DumpStateTicksFlag = "dump-state-ticks"; constexpr StringView UnattendedFlag = "unattended"; constexpr StringView FramesFlag = "frames"; constexpr StringView FramesPerTickFlag = "frames-per-tick"; @@ -137,6 +145,48 @@ namespace Fling return true; } + /** Read a list of tick numbers, such as 30,60,120 (each 1 or more). The result is sorted, with no repeats. */ + bool + ReadTickList(const CommandLine& t_CmdLine, StringView t_Flag, std::vector& t_Out, String& t_OutError) + { + const std::optional Value = t_CmdLine.GetValueAsString(t_Flag); + if (!Value) + { + return true; + } + StringView Rest = *Value; + const auto Fail = [&]() + { + t_OutError = "--" + String(t_Flag) + + " needs a comma list of ticks (1 or more), for example 30,60,120, not '" + String(*Value) + + "'"; + return false; + }; + if (Rest.empty() || Rest == "true") + { + return Fail(); + } + while (true) + { + const size_t Comma = Rest.find(','); + const StringView Item = Rest.substr(0, Comma); + uint32 Tick = 0; + if (!TryParseUint32(Item, Tick) || Tick == 0) + { + return Fail(); + } + t_Out.push_back(Tick); + if (Comma == StringView::npos) + { + break; + } + Rest = Rest.substr(Comma + 1); + } + std::sort(t_Out.begin(), t_Out.end()); + t_Out.erase(std::unique(t_Out.begin(), t_Out.end()), t_Out.end()); + return true; + } + /** Read a uint32 flag into an optional: empty when the flag is not given. */ bool ReadOptionalUint32(const CommandLine& t_CmdLine, StringView t_Flag, @@ -172,6 +222,59 @@ namespace Fling return false; } + if (!ReadBool(t_CmdLine, OffscreenFlag, t_Out.Offscreen, t_OutError)) + { + return false; + } + if (t_Out.Offscreen && t_Out.NullRender) + { + t_OutError = "--offscreen and --null-render cannot be used together: --offscreen renders, --null-render " + "does not"; + return false; + } + + if (const std::optional Resolution = t_CmdLine.GetValueAsString(ResolutionFlag)) + { + const StringView Str = *Resolution; + const size_t X = Str.find('x'); + uint32 Width = 0; + uint32 Height = 0; + if (X == StringView::npos || !TryParseUint32(Str.substr(0, X), Width) || + !TryParseUint32(Str.substr(X + 1), Height) || Width == 0 || Height == 0 || Width > 8192 || + Height > 8192) + { + t_OutError = "--resolution needs x from 1 to 8192, for example 1280x720, not '" + + String(Str) + "'"; + return false; + } + t_Out.ResolutionWidth = Width; + t_Out.ResolutionHeight = Height; + } + + if (!ReadPath(t_CmdLine, ScreenshotFlag, t_Out.Screenshot, t_OutError) || + !ReadTickList(t_CmdLine, ScreenshotTicksFlag, t_Out.ScreenshotTicks, t_OutError) || + !ReadPath(t_CmdLine, DumpStateFlag, t_Out.DumpState, t_OutError) || + !ReadTickList(t_CmdLine, DumpStateTicksFlag, t_Out.DumpStateTicks, t_OutError)) + { + return false; + } + if (!t_Out.ScreenshotTicks.empty() && t_Out.Screenshot.empty()) + { + t_OutError = "--screenshot-ticks needs --screenshot "; + return false; + } + if (!t_Out.DumpStateTicks.empty() && t_Out.DumpState.empty()) + { + t_OutError = "--dump-state-ticks needs --dump-state "; + return false; + } + if (!t_Out.Screenshot.empty() && t_Out.NullRender) + { + t_OutError = "--screenshot needs a renderer: use --offscreen instead of --null-render (or --dump-state " + "for the state as text)"; + return false; + } + if (!ReadBool(t_CmdLine, DumpScheduleFlag, t_Out.DumpSchedule, t_OutError) || !ReadBool(t_CmdLine, ValidateScheduleFlag, t_Out.ValidateSchedule, t_OutError)) { @@ -337,6 +440,44 @@ namespace Fling } #endif + // A capture with no tick list is at the last tick of the run, so the run must have one + if (t_Out.Frames == 0) + { + if (!t_Out.Screenshot.empty() && t_Out.ScreenshotTicks.empty()) + { + t_OutError = "--screenshot needs --frames N (a frame at the last tick) or --screenshot-ticks"; + return false; + } + if (!t_Out.DumpState.empty() && t_Out.DumpStateTicks.empty()) + { + t_OutError = "--dump-state needs --frames N (the state at the last tick) or --dump-state-ticks"; + return false; + } + } + return true; } + + String CaptureFilePath(const StringView t_Path, const uint64 t_Tick, const bool t_ManyTicks) + { + String Path(t_Path); + const String TickText = std::to_string(t_Tick); + constexpr StringView Placeholder = "{tick}"; + if (const size_t At = Path.find(Placeholder); At != String::npos) + { + Path.replace(At, Placeholder.size(), TickText); + return Path; + } + if (!t_ManyTicks) + { + return Path; + } + // Before the extension, if the file name has one + const size_t Slash = Path.find_last_of("/\\"); + const size_t Dot = Path.find_last_of('.'); + const bool bHasExtension = Dot != String::npos && (Slash == String::npos || Dot > Slash); + const size_t InsertAt = bHasExtension ? Dot : Path.size(); + Path.insert(InsertAt, "_tick" + TickText); + return Path; + } } // namespace Fling diff --git a/FlingEngine/Core/src/RunSettings.cpp b/FlingEngine/Core/src/RunSettings.cpp index 2411bfd7..d20f11a2 100644 --- a/FlingEngine/Core/src/RunSettings.cpp +++ b/FlingEngine/Core/src/RunSettings.cpp @@ -162,7 +162,8 @@ namespace Fling using Keys = RunSettingsConfig; t_Out = RunSettings{}; t_OutError.clear(); - t_Out.Headless = t_Options.NullRender; + t_Out.Headless = t_Options.IsHeadless(); + t_Out.HeadlessFlag = t_Options.Offscreen ? "--offscreen" : "--null-render"; const NumberRange SimHzRange{.Min = SimRate::MinHz, .Max = SimRate::MaxHz, .Unit = "ticks a second"}; const NumberRange MaxFpsRange{.Min = 1, .Max = MaxMaxFps, .AllowZero = true, .Unit = "frames a second"}; @@ -202,7 +203,8 @@ namespace Fling } if (t_Out.Headless && t_Options.VSync) { - t_Out.Ignored.push_back("--vsync does nothing with --null-render: there is no swap chain"); + t_Out.Ignored.push_back(String("--vsync does nothing with ") + t_Out.HeadlessFlag + + ": there is no swap chain"); } return true; } @@ -241,7 +243,8 @@ namespace Fling String CapSource = SettingSourceName(MaxFpsSource); if (MaxFpsSource == SettingSource::Default) { - CapSource = Headless ? "default for --null-render" : "default: the monitor refresh rate is not known"; + CapSource = + Headless ? String("default for ") + HeadlessFlag : "default: the monitor refresh rate is not known"; } else if (MaxFpsSource == SettingSource::Monitor) { diff --git a/FlingEngine/Core/src/Screenshot.cpp b/FlingEngine/Core/src/Screenshot.cpp new file mode 100644 index 00000000..f4c0246d --- /dev/null +++ b/FlingEngine/Core/src/Screenshot.cpp @@ -0,0 +1,101 @@ +#include "FlingPaths.h" +#include "Logger.h" +#include "Screenshot.h" +#include "Threading/ThreadQueue.h" + +#include +#include +#include +#include +#include + +namespace Fling +{ + namespace + { + /** Any thread to the main thread: the requests waiting for a frame. */ + ThreadQueue& PendingQueue() + { + static ThreadQueue s_Queue; + return s_Queue; + } + + /** + * The requests in the queue: one atomic load answers HasPending, so a frame with no + * request takes no lock. Signed: a drain can take an item before its push adds 1. + */ + std::atomic s_PendingCount{0}; + + /** Makes DefaultPath names unique within one second. */ + std::atomic s_DefaultPathCount{0}; + } // namespace + + String Screenshot::DefaultPath() + { + const std::time_t Now = std::time(nullptr); + std::tm LocalTime = {}; +#if defined(_WIN32) + localtime_s(&LocalTime, &Now); +#else + localtime_r(&Now, &LocalTime); +#endif + std::ostringstream Name; + Name << FlingPaths::ProjectSavedDir() << "/Screenshots/Screenshot_" + << std::put_time(&LocalTime, "%Y-%m-%d_%H-%M-%S") << "_" + << s_DefaultPathCount.fetch_add(1, std::memory_order_relaxed) + 1 << ".png"; + return Name.str(); + } + + String Screenshot::Request(const StringView t_Path, ScreenshotCallback t_OnDone) + { + const String Path = t_Path.empty() ? DefaultPath() : FlingPaths::ResolveProjectPath(t_Path); + PendingQueue().Push(Pending{Path, std::move(t_OnDone)}); + s_PendingCount.fetch_add(1, std::memory_order_release); + return Path; + } + + bool Screenshot::HasPending() + { + return s_PendingCount.load(std::memory_order_acquire) > 0; + } + + std::vector Screenshot::TakePending() + { + std::vector Requests; + // The common case, every frame: nothing asked for, so no lock and no allocation + if (!HasPending()) + { + return Requests; + } + PendingQueue().Drain([&Requests](Pending& t_Request) { Requests.push_back(std::move(t_Request)); }); + s_PendingCount.fetch_sub(static_cast(Requests.size()), std::memory_order_acq_rel); + return Requests; + } + + void Screenshot::Finish(Pending& t_Request, const ScreenshotResult& t_Result) + { + if (t_Result.Ok) + { + F_LOG_TRACE("Screenshot saved ({}x{}) to {}", t_Result.Width, t_Result.Height, t_Result.Path); + } + else + { + F_LOG_ERROR("Screenshot not saved to {}: {}", t_Result.Path, t_Result.Error); + } + if (t_Request.OnDone) + { + t_Request.OnDone(t_Result); + } + } + + void Screenshot::FailPending(const StringView t_Reason) + { + for (Pending& Request : TakePending()) + { + ScreenshotResult Result; + Result.Path = Request.Path; + Result.Error = String(t_Reason); + Finish(Request, Result); + } + } +} // namespace Fling diff --git a/FlingEngine/Editor/inc/BaseEditor.h b/FlingEngine/Editor/inc/BaseEditor.h index c5c30022..510dac2e 100644 --- a/FlingEngine/Editor/inc/BaseEditor.h +++ b/FlingEngine/Editor/inc/BaseEditor.h @@ -53,6 +53,12 @@ namespace Fling float m_FrameTimeMax = 0.0f; bool m_DisplayGpuOptions = false; + + /** + * The last screenshot taken with the GPU Options button: what the window shows under it. + * Shared, so a result that arrives after the editor is gone writes nowhere. + */ + std::shared_ptr m_ScreenshotStatus = std::make_shared(); bool m_DisplayComponentEditor = true; bool m_DisplayWorldOutline = true; bool m_DisplayWindowOptions = false; @@ -81,7 +87,8 @@ namespace Fling /** * The GPU Options window: the device, VSync (with the present mode in use), the frame * cap, the simulation rate and render interpolation, with what the frame limiter does - * and the measured rates. Each control + * and the measured rates, and a button that saves the next frame as a PNG + * (Screenshot::Request). Each control * calls RunControls, which checks the request; a number box applies when its edit is * committed (Enter or focus loss). */ diff --git a/FlingEngine/Editor/src/BaseEditor.cpp b/FlingEngine/Editor/src/BaseEditor.cpp index 1b5c62bd..83f92cc8 100644 --- a/FlingEngine/Editor/src/BaseEditor.cpp +++ b/FlingEngine/Editor/src/BaseEditor.cpp @@ -16,6 +16,7 @@ #include "MeshRenderer.h" #include "PresentMode.h" #include "RunControls.h" +#include "Screenshot.h" #include "SimRate.h" #include "Timing.h" #include "TransformUtil.h" @@ -410,7 +411,7 @@ namespace Fling // Right of the World Outline and Entity Editor windows, so none covers another on // first use, and wide enough for the limiter and measured lines ImGui::SetNextWindowPos(ImVec2(520, 30), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowSize(ImVec2(600, 340), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(ImVec2(600, 400), ImGuiCond_FirstUseEver); ImGui::Begin("GPU Options"); const String DeviceName = VulkanApp::Get().GetPhysicalDeviceName(); @@ -453,6 +454,29 @@ namespace Fling ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", m_ControlsError.c_str()); } + ImGui::Separator(); + // The next frame as it is shown, this window included, to Saved/Screenshots + if (ImGui::Button("Take screenshot")) + { + const std::weak_ptr Status = m_ScreenshotStatus; + const String Path = Screenshot::Request({}, + [Status](const ScreenshotResult& t_Result) + { + if (const std::shared_ptr Text = Status.lock()) + { + *Text = t_Result.Ok ? "Saved " + t_Result.Path + : "Not saved: " + t_Result.Error; + } + }); + *m_ScreenshotStatus = "Saving " + Path; + } + ImGui::SameLine(); + ImGui::TextDisabled("The next frame, with the editor UI, as a PNG"); + if (!m_ScreenshotStatus->empty()) + { + ImGui::TextWrapped("%s", m_ScreenshotStatus->c_str()); + } + ImGui::Separator(); const float Fps = static_cast(Timing::Get().GetFrameCount()); ImGui::TextWrapped("%s", Controls.DescribeMeasured(Fps).c_str()); diff --git a/FlingEngine/Engine/inc/Ecs/TypeRegistry.h b/FlingEngine/Engine/inc/Ecs/TypeRegistry.h index 01ad4355..5cdd7a87 100644 --- a/FlingEngine/Engine/inc/Ecs/TypeRegistry.h +++ b/FlingEngine/Engine/inc/Ecs/TypeRegistry.h @@ -96,6 +96,9 @@ namespace Fling /** Ids that the save gives to entities with none (or a shared one): the document has them, the storage not. */ const std::unordered_map* NewGuids = nullptr; + + /** Write Transient fields too (World::SaveStateToJson): a state dump shows every field, a level does not. */ + bool IncludeTransientFields = false; }; /** What a load needs beyond the object: how to find an entity from a saved EntityGuid. */ diff --git a/FlingEngine/Engine/inc/World.h b/FlingEngine/Engine/inc/World.h index 9a6aae8f..af75f290 100644 --- a/FlingEngine/Engine/inc/World.h +++ b/FlingEngine/Engine/inc/World.h @@ -146,6 +146,24 @@ namespace Fling /** The ledger records of the ticks since the last call, in tick order (KeepTickRecords). */ std::vector TakeNewTickRecords(); + /** The simulation state after one tick (SetStateDumpTicks). */ + struct StateDump + { + uint64 Tick = 0; + + /** SaveStateToJson's document. */ + Json Doc; + }; + + /** + * Write the state (SaveStateToJson) right after each of these ticks, on the thread that + * runs the ticks, for TakeStateDumps (--dump-state). Sorted. Call it before play starts. + */ + void SetStateDumpTicks(std::vector t_Ticks) { m_StateDumpTicks = std::move(t_Ticks); } + + /** The state dumps of the ticks since the last call, in tick order (SetStateDumpTicks). */ + std::vector TakeStateDumps(); + /** * Set the function that reads the input after a sequence, for the frame side * (see SystemRunner::SetPendingInputSource). Set it before Init. @@ -344,6 +362,19 @@ namespace Fling */ bool SaveToJson(Json& t_OutDoc, StringView t_Title) const; + /** + * Write the simulation state to a document, for an agent or a test to read (--dump-state). + * The types are the ones the state hash covers (rollback state) and the ones a level + * saves, with every field (Transient fields too). Top level: "tick", "stateHash" + * (TickRecord::StateHash, 0 when off), "simHz", "entityCount", "entities" (in handle + * order: "entity" index:generation, "name" when it has one, "guid", then one object per + * component) and "singletons". An entity with no EntityGuid gets an id made from its + * handle, not a random one, so the same run writes the same document. It is not a level + * file: LoadFromJson does not read it. Call it on the thread that owns the simulation + * storage (OnTickDone does). + */ + bool SaveStateToJson(Json& t_OutDoc, uint64 t_Tick) const; + /** * Remove all entities, then make the entities in a level document. A component * loads after the components that it requires, and one that the document does not @@ -404,7 +435,7 @@ namespace Fling TickHost& AsTickHost() { return *this; } /** A new EntityGuid for each entity that has none, or the same one as an entity before it. */ - std::unordered_map MakeMissingEntityGuids() const; + std::unordered_map MakeMissingEntityGuids(bool t_FromHandles = false) const; /** Run the pending start or stop request, if there is one */ void ProcessPlayRequest(); @@ -595,6 +626,12 @@ namespace Fling /** Tick thread to main thread: @see KeepTickRecords */ ThreadQueue m_NewTickRecords; + /** @see SetStateDumpTicks. Set before play; the tick thread reads it. */ + std::vector m_StateDumpTicks; + + /** Tick thread to main thread: @see SetStateDumpTicks */ + ThreadQueue m_StateDumps; + // The main thread's state /** The newest tick whose outbox entry was applied. An entry that is not newer is a repeat. */ diff --git a/FlingEngine/Engine/src/Ecs/Reflection.cpp b/FlingEngine/Engine/src/Ecs/Reflection.cpp index 63cbd217..31501088 100644 --- a/FlingEngine/Engine/src/Ecs/Reflection.cpp +++ b/FlingEngine/Engine/src/Ecs/Reflection.cpp @@ -607,7 +607,7 @@ namespace Fling for (const FieldDesc& field : type.Fields) { - if (!field.Transient) + if (!field.Transient || context.IncludeTransientFields) { SaveField(field, object, out, context); } diff --git a/FlingEngine/Engine/src/World.cpp b/FlingEngine/Engine/src/World.cpp index b09d06f5..8831e718 100644 --- a/FlingEngine/Engine/src/World.cpp +++ b/FlingEngine/Engine/src/World.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -611,6 +612,15 @@ namespace Fling { m_NewTickRecords.Push(*m_Runner->GetLedger().Latest()); } + if (std::binary_search(m_StateDumpTicks.begin(), m_StateDumpTicks.end(), t_Tick)) + { + StateDump Dump; + Dump.Tick = t_Tick; + if (SaveStateToJson(Dump.Doc, t_Tick)) + { + m_StateDumps.Push(std::move(Dump)); + } + } AppRequests* Queue = m_Storage.TryGetSingleton(); if (!Queue || Queue->Requests.empty()) { @@ -737,6 +747,13 @@ namespace Fling return Records; } + std::vector World::TakeStateDumps() + { + std::vector Dumps; + m_StateDumps.Drain([&Dumps](StateDump& t_Dump) { Dumps.push_back(std::move(t_Dump)); }); + return Dumps; + } + bool World::RequestSimHz(const uint32 t_Hz, String& t_OutError, const uint64 t_BeforeTick) { t_OutError.clear(); @@ -819,7 +836,7 @@ namespace Fling return root.SaveToFile(FullPath); } - std::unordered_map World::MakeMissingEntityGuids() const + std::unordered_map World::MakeMissingEntityGuids(const bool t_FromHandles) const { std::unordered_set UsedGuids; std::vector NeedGuid; @@ -840,13 +857,15 @@ namespace Fling { return NewGuids; } - std::mt19937_64 Generator{std::random_device{}()}; + // A state dump makes the same ids in the same run: each one comes from the handle, + // with the top bit set so it is not 0, and the next free value if it is taken + std::mt19937_64 Generator{t_FromHandles ? 0u : std::random_device{}()}; for (const Fling::Entity Entity : NeedGuid) { - uint64 Value = 0; + uint64 Value = t_FromHandles ? (Entity.ToBits() | (uint64{1} << 63)) : 0; while (Value == 0 || !UsedGuids.insert(Value).second) { - Value = Generator(); + Value = t_FromHandles ? Value + 1 : Generator(); } NewGuids.emplace(Entity, Value); } @@ -956,6 +975,116 @@ namespace Fling return true; } + bool World::SaveStateToJson(Json& t_OutDoc, const uint64 t_Tick) const + { + if (!m_TypesBuilt) + { + F_LOG_ERROR("Cannot write the world state before World::Init"); + return false; + } + + // The types that the state hash covers (rollback state) and the ones a level saves, + // with every field, Transient ones too + std::vector ComponentTypes; + std::vector SingletonTypes; + for (const TypeDesc& Type : m_Types.All()) + { + if (!Type.IsSaved() && !Type.IsRollbackState()) + { + continue; + } + if (Type.IsSingleton()) + { + SingletonTypes.push_back(&Type); + } + else if (!IsReservedEntityKey(Type.Name)) + { + ComponentTypes.push_back(&Type); + } + } + const auto ByName = [](const TypeDesc* a, const TypeDesc* b) + { + return a->Name < b->Name; + }; + std::sort(ComponentTypes.begin(), ComponentTypes.end(), ByName); + std::sort(SingletonTypes.begin(), SingletonTypes.end(), ByName); + + // Entities in handle order, which is the same for the same run. Ids made from the handles, + // so Entity fields name their targets the same way in every run + const std::unordered_map NewGuids = MakeMissingEntityGuids(/* t_FromHandles */ true); + SaveContext Context{&m_Storage, &NewGuids}; + Context.IncludeTransientFields = true; + std::vector Entities; + m_Storage.EachEntity([&](const Fling::Entity t_Entity) { Entities.push_back(t_Entity); }); + std::sort(Entities.begin(), Entities.end()); + + Json EntitiesJson = Json::Array(); + for (const Fling::Entity Each : Entities) + { + Json EntityJson = Json::Object(); + char Handle[32]; + std::snprintf(Handle, sizeof(Handle), "%u:%u", Each.Index, Each.Generation); + EntityJson.Set("entity", StringView(Handle)); + if (const NameComponent* Named = m_Storage.TryGet(Each)) + { + EntityJson.Set("name", Named->Name.ToView()); + } + if (const auto Found = NewGuids.find(Each); Found != NewGuids.end()) + { + EntityJson.SetUInt64("guid", Found->second); + } + else if (const EntityGuid* Guid = m_Storage.TryGet(Each)) + { + EntityJson.SetUInt64("guid", Guid->Value); + } + for (const TypeDesc* Type : ComponentTypes) + { + if (Type->Has == nullptr || !Type->Has(m_Storage, Each) || Type->Name == EntityGuid::Component.Name) + { + continue; + } + Json ComponentJson = Json::Object(); + if (!Type->IsTag() && Type->GetConst) + { + SaveObject(*Type, Type->GetConst(m_Storage, Each), ComponentJson, Context); + } + EntityJson.Set(Type->Name, ComponentJson); + } + EntitiesJson.PushBack(EntityJson); + } + + Json Singletons = Json::Object(); + for (const TypeDesc* Type : SingletonTypes) + { + if (const void* Object = Type->GetSingletonConst ? Type->GetSingletonConst(m_Storage) : nullptr) + { + Json SingletonJson = Json::Object(); + SaveObject(*Type, Object, SingletonJson, Context); + Singletons.Set(Type->Name, SingletonJson); + } + } + + uint64 StateHash = 0; + if (m_Runner) + { + if (const TickRecord* Latest = m_Runner->GetLedger().Latest(); Latest && Latest->Stamp.Tick == t_Tick) + { + StateHash = Latest->Stamp.StateHash; + } + } + char HashText[17]; + std::snprintf(HashText, sizeof(HashText), "%016llx", static_cast(StateHash)); + + t_OutDoc = Json::Object(); + t_OutDoc.SetUInt64("tick", t_Tick); + t_OutDoc.Set("stateHash", StringView(HashText)); + t_OutDoc.SetUInt64("simHz", GetSimHz()); + t_OutDoc.SetUInt64("entityCount", Entities.size()); + t_OutDoc.Set("entities", EntitiesJson); + t_OutDoc.Set("singletons", Singletons); + return true; + } + bool World::LoadLevelFile(const StringView t_LevelToLoad) { if (!m_TypesBuilt) diff --git a/FlingEngine/Graphics/inc/VulkanApp.h b/FlingEngine/Graphics/inc/VulkanApp.h index 57e4b8e9..df6de8d1 100644 --- a/FlingEngine/Graphics/inc/VulkanApp.h +++ b/FlingEngine/Graphics/inc/VulkanApp.h @@ -7,6 +7,7 @@ #include "Strings/String.h" #include +#include #include namespace Fling @@ -23,6 +24,23 @@ namespace Fling ALL = 0xff }; + /** + * What the renderer draws to. Set it with VulkanApp::SetRenderSurface before Init. + */ + struct RenderSurfaceDesc + { + /** + * True: draw into images that the renderer owns (--offscreen). There is no window, no + * surface, and no window system: a run works on a machine with no display, and opens + * nothing on a machine that has one. Screenshots (Screenshot::Request) still work. + */ + bool Offscreen = false; + + /** The size of the frames (offscreen) or the window. 0: [Engine] WindowWidth and WindowHeight. */ + uint32 Width = 0; + uint32 Height = 0; + }; + class Instance; class LogicalDevice; class PhysicalDevice; @@ -33,6 +51,7 @@ namespace Fling class FirstPersonCamera; class DepthBuffer; class IDebugUI; + class FrameCapturer; /** * Core rendering functionality of the Fling Engine. Controls what Render pipelines @@ -56,6 +75,13 @@ namespace Fling /** Wait for the GPU, then free the render pipelines, the device, and the window. */ void ShutdownRenderer(); + /** + * Wait for the screenshots that are being written (Screenshot::Request) and call their + * callbacks. A frame copies a screenshot; a writer thread saves it later, so a run that + * counts its screenshots calls this before it ends. Main thread. + */ + void FinishScreenshots(); + /** * Specify default constructible so that we have more explicit * control with Init and Shutdown @@ -100,6 +126,16 @@ namespace Fling /** The present mode of the swap chain. */ PresentMode GetPresentMode() const; + /** What to draw to: a window or offscreen images, and the size. Call it before Init. */ + void SetRenderSurface(const RenderSurfaceDesc& t_Desc) { m_SurfaceDesc = t_Desc; } + + /** True when the renderer draws offscreen (RenderSurfaceDesc::Offscreen): there is no window. */ + bool IsOffscreen() const { return m_SurfaceDesc.Offscreen; } + + /** The size of the frames the renderer draws, in pixels. 0 x 0 before Init. */ + uint32 GetFrameWidth() const; + uint32 GetFrameHeight() const; + protected: void Init() override {} void Shutdown() override {} @@ -178,5 +214,11 @@ namespace Fling FirstPersonCamera* m_Camera = nullptr; std::unique_ptr m_State; + + /** @see SetRenderSurface */ + RenderSurfaceDesc m_SurfaceDesc; + + /** Serves Screenshot::Request: the copy in the frame, and the PNG on a writer thread. */ + std::unique_ptr m_Capturer; }; } // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.cpp b/FlingEngine/Graphics/src/FrameCapture.cpp new file mode 100644 index 00000000..bebe170b --- /dev/null +++ b/FlingEngine/Graphics/src/FrameCapture.cpp @@ -0,0 +1,369 @@ +#include "Buffer.h" +#include "FlingPaths.h" +#include "FrameCapture.h" +#include "Logger.h" +#include "SwapChain.h" +#include "Threading/CommandRunnable.h" +#include "Threading/Thread.h" + +#include +#include + +#define STB_IMAGE_WRITE_IMPLEMENTATION +#define STB_IMAGE_WRITE_STATIC +#include + +namespace Fling +{ + namespace + { + /** stbi_write_png_to_func's callback: append to a String. */ + void AppendToString(void* t_Context, void* t_Data, int t_Size) + { + static_cast(t_Context)->append(static_cast(t_Data), static_cast(t_Size)); + } + + bool IsBgra(const VkFormat t_Format) + { + return t_Format == VK_FORMAT_B8G8R8A8_UNORM || t_Format == VK_FORMAT_B8G8R8A8_SRGB; + } + + bool IsRgba(const VkFormat t_Format) + { + return t_Format == VK_FORMAT_R8G8B8A8_UNORM || t_Format == VK_FORMAT_R8G8B8A8_SRGB; + } + } // namespace + + namespace FrameCapture + { + bool ToRgba(const VkFormat t_Format, uint8* t_Pixels, const size_t t_Size) + { + if (!IsBgra(t_Format) && !IsRgba(t_Format)) + { + return false; + } + const bool bSwap = IsBgra(t_Format); + for (size_t i = 0; i + 3 < t_Size; i += 4) + { + if (bSwap) + { + std::swap(t_Pixels[i], t_Pixels[i + 2]); + } + t_Pixels[i + 3] = 255; + } + return true; + } + + bool EncodePng(const uint32 t_Width, const uint32 t_Height, const uint8* t_Rgba, String& t_OutPng) + { + t_OutPng.clear(); + const int Stride = static_cast(t_Width) * 4; + return stbi_write_png_to_func(&AppendToString, + &t_OutPng, + static_cast(t_Width), + static_cast(t_Height), + 4, + t_Rgba, + Stride) != 0; + } + + bool WritePng(const StringView t_Path, + const uint32 t_Width, + const uint32 t_Height, + const uint8* t_Rgba, + String& t_OutError) + { + String Png; + if (!EncodePng(t_Width, t_Height, t_Rgba, Png)) + { + t_OutError = "cannot encode the PNG file " + String(t_Path); + return false; + } + return FlingPaths::SaveFile(t_Path, Png, t_OutError); + } + } // namespace FrameCapture + + FrameCapturer::FrameCapturer() = default; + + FrameCapturer::~FrameCapturer() + { + // VulkanApp calls Release before the device goes; this only stops the thread + Flush(); + } + + FrameCapturer::Slot* FrameCapturer::AcquireSlot(const VkDeviceSize t_Size) + { + for (std::unique_ptr& Each : m_Slots) + { + if (Each->InUse.load(std::memory_order_acquire)) + { + continue; + } + // The frame size changed (a resize): a buffer of the new size + if (Each->Staging == nullptr || Each->Staging->GetSize() != t_Size) + { + Each->Staging.reset(); + Each->Mapped = nullptr; + } + return Each.get(); + } + if (m_Slots.size() >= MaxSlots) + { + return nullptr; + } + m_Slots.emplace_back(std::make_unique()); + return m_Slots.back().get(); + } + + void FrameCapturer::Fail(std::vector& t_Requests, const StringView t_Error) + { + for (Screenshot::Pending& Request : t_Requests) + { + ScreenshotResult Result; + Result.Path = Request.Path; + Result.Error = String(t_Error); + Screenshot::Finish(Request, Result); + } + t_Requests.clear(); + } + + void FrameCapturer::RecordCopy(const VkCommandBuffer t_Cmd, const Swapchain& t_SwapChain, const uint32 t_ImageIndex) + { + // The common case, every frame: nobody asked, so no lock + if (!Screenshot::HasPending() && m_Waiting.empty()) + { + return; + } + for (Screenshot::Pending& Request : Screenshot::TakePending()) + { + m_Waiting.push_back(std::move(Request)); + } + if (m_Waiting.empty()) + { + return; + } + + if (!t_SwapChain.CanCopyImages()) + { + Fail(m_Waiting, "the window's surface does not allow copying its images; use --offscreen"); + return; + } + const VkFormat Format = t_SwapChain.GetImageFormat(); + if (!IsBgra(Format) && !IsRgba(Format)) + { + Fail(m_Waiting, + "the frame's format (" + std::to_string(static_cast(Format)) + ") is not 8-bit RGBA or BGRA"); + return; + } + + const VkExtent2D Extent = t_SwapChain.GetExtents(); + const VkDeviceSize Size = static_cast(Extent.width) * Extent.height * 4; + Slot* Target = AcquireSlot(Size); + if (Target == nullptr) + { + // Every staging buffer is with the writer: a later frame serves these requests + return; + } + if (Target->Staging == nullptr) + { + // Host-visible memory that the writer thread reads, kept mapped. Made on the first + // capture of this size only + Target->Staging = + std::make_unique(Size, + VK_BUFFER_USAGE_TRANSFER_DST_BIT, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + const VkResult MapResult = Target->Staging->MapMemory(); + if (MapResult != VK_SUCCESS || Target->Staging->m_MappedMem == nullptr) + { + Target->Staging.reset(); + Fail(m_Waiting, + "cannot map the screenshot's staging memory (VkResult " + + std::to_string(static_cast(MapResult)) + ")"); + return; + } + Target->Mapped = Target->Staging->m_MappedMem; + } + + const VkImage Image = t_SwapChain.GetImages()[t_ImageIndex]; + const VkImageLayout Layout = t_SwapChain.GetFinalLayout(); + + VkImageSubresourceRange Range = {}; + Range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + Range.levelCount = 1; + Range.layerCount = 1; + + // After the render pass's writes (and its final layout change), the copy reads the image. + // All commands: only a capture frame pays for the wide wait + VkImageMemoryBarrier ToCopy = {}; + ToCopy.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + ToCopy.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT; + ToCopy.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + ToCopy.oldLayout = Layout; + ToCopy.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + ToCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToCopy.image = Image; + ToCopy.subresourceRange = Range; + vkCmdPipelineBarrier(t_Cmd, + VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, + VK_PIPELINE_STAGE_TRANSFER_BIT, + 0, + 0, + nullptr, + 0, + nullptr, + 1, + &ToCopy); + + VkBufferImageCopy Region = {}; + Region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; + Region.imageSubresource.layerCount = 1; + Region.imageExtent = {Extent.width, Extent.height, 1}; + vkCmdCopyImageToBuffer( + t_Cmd, Image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, Target->Staging->GetVkBuffer(), 1, &Region); + + // Back to the layout the present (or the next frame) expects, and the copy's writes to the host + VkImageMemoryBarrier Back = ToCopy; + Back.srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT; + Back.dstAccessMask = 0; + Back.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + Back.newLayout = Layout; + + VkBufferMemoryBarrier ToHost = {}; + ToHost.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; + ToHost.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + ToHost.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + ToHost.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToHost.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + ToHost.buffer = Target->Staging->GetVkBuffer(); + ToHost.size = VK_WHOLE_SIZE; + vkCmdPipelineBarrier(t_Cmd, + VK_PIPELINE_STAGE_TRANSFER_BIT, + VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, + 0, + 0, + nullptr, + 1, + &ToHost, + Layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ? 0u : 1u, + &Back); + + Target->InUse.store(true, std::memory_order_release); + m_Recorded = std::make_shared(); + m_Recorded->Target = Target; + m_Recorded->Extent = Extent; + m_Recorded->Format = Format; + m_Recorded->Requests = std::move(m_Waiting); + m_Waiting.clear(); + } + + void FrameCapturer::OnFrameDone() + { + if (m_Recorded == nullptr) + { + return; + } + if (m_WriterThread == nullptr) + { + // Made on the first capture: a run that takes none has no writer thread + m_Writer = std::make_shared(); + m_WriterThread = + Thread::Create(m_Writer, {.Name = "Screenshot Writer", .Priority = ThreadPriority::BelowNormal}); + if (m_WriterThread == nullptr) + { + // No thread: write here. Slow, but the request is not lost + F_LOG_WARN("Cannot start the screenshot writer thread; writing on the main thread"); + m_Writer.reset(); + } + } + std::shared_ptr Capture = std::move(m_Recorded); + m_Recorded.reset(); + if (m_Writer == nullptr) + { + Write(*Capture); + DeliverResults(); + return; + } + m_Writer->Enqueue([this, Capture]() { Write(*Capture); }); + } + + void FrameCapturer::Write(Recorded& t_Capture) + { + Slot& Target = *t_Capture.Target; + const size_t Size = static_cast(t_Capture.Extent.width) * t_Capture.Extent.height * 4; + + // One read of the staging memory (it can be slow to read: uncached), then the slot is + // free for the next capture while this one encodes + std::vector Pixels(Size); + std::memcpy(Pixels.data(), Target.Mapped, Size); + Target.InUse.store(false, std::memory_order_release); + + String Error; + String Png; + bool bEncoded = FrameCapture::ToRgba(t_Capture.Format, Pixels.data(), Pixels.size()); + if (!bEncoded) + { + Error = "the frame's format is not 8-bit RGBA or BGRA"; + } + else if (!FrameCapture::EncodePng(t_Capture.Extent.width, t_Capture.Extent.height, Pixels.data(), Png)) + { + bEncoded = false; + Error = "cannot encode the PNG file"; + } + + // Encoded once, written once for each request + for (Screenshot::Pending& Request : t_Capture.Requests) + { + Finished Done; + Done.Result.Path = Request.Path; + Done.Result.Error = Error; + Done.Result.Ok = bEncoded && FlingPaths::SaveFile(Request.Path, Png, Done.Result.Error); + if (Done.Result.Ok) + { + Done.Result.Width = t_Capture.Extent.width; + Done.Result.Height = t_Capture.Extent.height; + } + Done.Request = std::move(Request); + m_Finished.Push(std::move(Done)); + m_FinishedCount.fetch_add(1, std::memory_order_release); + } + } + + void FrameCapturer::DeliverResults() + { + // The common case, every frame: nothing finished, so no lock + if (m_FinishedCount.load(std::memory_order_acquire) <= 0) + { + return; + } + const uint32 Count = + m_Finished.Drain([](Finished& t_Done) { Screenshot::Finish(t_Done.Request, t_Done.Result); }); + m_FinishedCount.fetch_sub(static_cast(Count), std::memory_order_acq_rel); + } + + void FrameCapturer::Flush() + { + // A copy that was recorded but whose frame never finished: nothing to write + if (m_Recorded != nullptr) + { + m_Recorded->Target->InUse.store(false, std::memory_order_release); + Fail(m_Recorded->Requests, "the frame was not finished"); + m_Recorded.reset(); + } + if (m_WriterThread != nullptr) + { + // Kill runs the writes that are queued, then joins. A later capture starts it again + m_WriterThread->Kill(); + m_WriterThread.reset(); + m_Writer.reset(); + } + DeliverResults(); + } + + void FrameCapturer::Release() + { + Flush(); + Fail(m_Waiting, "the renderer shut down before the next frame was drawn"); + m_Slots.clear(); + } +} // namespace Fling diff --git a/FlingEngine/Graphics/src/FrameCapture.h b/FlingEngine/Graphics/src/FrameCapture.h new file mode 100644 index 00000000..01a08744 --- /dev/null +++ b/FlingEngine/Graphics/src/FrameCapture.h @@ -0,0 +1,138 @@ +#pragma once + +#include "FlingTypes.h" +#include "FlingVulkan.h" +#include "Screenshot.h" +#include "Strings/String.h" +#include "Threading/ThreadQueue.h" + +#include +#include +#include + +namespace Fling +{ + class Buffer; + class CommandRunnable; + class Swapchain; + class Thread; + + namespace FrameCapture + { + /** + * Turn the pixels of a copied frame into RGBA8 in place (4 bytes a pixel, rows top to + * bottom): BGRA formats are swizzled, and alpha is written as opaque (the frame's clear + * alpha is not meant to be seen). False if t_Format is not 8-bit RGBA or BGRA. + */ + bool ToRgba(VkFormat t_Format, uint8* t_Pixels, size_t t_Size); + + /** + * Encode RGBA8 pixels (4 bytes a pixel, rows top to bottom) as PNG bytes. Pure CPU + * work: the tests call it with no GPU. False if the encoder fails. + */ + bool EncodePng(uint32 t_Width, uint32 t_Height, const uint8* t_Rgba, String& t_OutPng); + + /** EncodePng, then FlingPaths::SaveFile. */ + bool WritePng(StringView t_Path, uint32 t_Width, uint32 t_Height, const uint8* t_Rgba, String& t_OutError); + } // namespace FrameCapture + + /** + * Serves Screenshot::Request for VulkanApp without stalling the frame: + * + * 1. RecordCopy (main thread, in the frame): when a request waits, the frame's own command + * buffer copies the finished image into a staging buffer, after the render pass. That + * is GPU work in the same submit; the CPU does not wait for it. + * 2. OnFrameDone (main thread, after the frame's fence): the copy is done, so the staging + * buffer goes to the writer thread. Nothing is copied on the main thread. + * 3. The writer thread converts the pixels, encodes the PNG once, writes each file, and + * frees the staging buffer for the next capture. + * 4. DeliverResults (main thread, next frames): the requests' callbacks. + * + * A frame with no request costs one atomic load in RecordCopy and one in DeliverResults. + * The writer thread and the staging buffers are made on the first capture only. + */ + class FrameCapturer + { + public: + FrameCapturer(); + ~FrameCapturer(); + + FrameCapturer(const FrameCapturer&) = delete; + FrameCapturer& operator=(const FrameCapturer&) = delete; + + /** + * Record the copy of t_SwapChain's image t_ImageIndex into t_Cmd, outside of a render + * pass, after everything that draws to it. Takes the waiting requests. Main thread. + */ + void RecordCopy(VkCommandBuffer t_Cmd, const Swapchain& t_SwapChain, uint32 t_ImageIndex); + + /** The fence of the frame that RecordCopy recorded into has signaled: start the writes. Main thread. */ + void OnFrameDone(); + + /** Call the callbacks of the captures that the writer finished. Main thread. */ + void DeliverResults(); + + /** + * Wait for the writer to finish every capture, then DeliverResults: the end of a run + * (its exit code counts the screenshots), and before the device is destroyed. Main thread. + */ + void Flush(); + + /** Flush, then free the staging buffers. Before the logical device is destroyed. */ + void Release(); + + private: + /** One staging buffer. The writer owns it while InUse. */ + struct Slot + { + std::unique_ptr Staging; + void* Mapped = nullptr; + std::atomic InUse{false}; + }; + + /** A copy that RecordCopy recorded, waiting for its frame's fence. */ + struct Recorded + { + Slot* Target = nullptr; + VkExtent2D Extent = {}; + VkFormat Format = VK_FORMAT_UNDEFINED; + std::vector Requests; + }; + + /** A finished request, for the main thread. */ + struct Finished + { + Screenshot::Pending Request; + ScreenshotResult Result; + }; + + /** A free slot that holds t_Size bytes, or null when all are with the writer and there are MaxSlots. */ + Slot* AcquireSlot(VkDeviceSize t_Size); + + /** The writer thread's work for one capture. */ + void Write(Recorded& t_Capture); + + /** Fail t_Requests with t_Error now (main thread). */ + void Fail(std::vector& t_Requests, StringView t_Error); + + /** At most this many captures in flight; more requests wait for a frame with a free slot. */ + static constexpr size_t MaxSlots = 3; + + std::vector> m_Slots; + + /** Requests taken from Screenshot that wait for a free slot. */ + std::vector m_Waiting; + + /** The copy recorded into this frame, if any. */ + std::shared_ptr m_Recorded; + + std::shared_ptr m_Writer; + std::shared_ptr m_WriterThread; + + /** Writer thread to main thread. */ + ThreadQueue m_Finished; + + /** Items in m_Finished: one atomic load answers "nothing to deliver". */ + std::atomic m_FinishedCount{0}; + }; +} // namespace Fling diff --git a/FlingEngine/Graphics/src/GeometrySubpass.cpp b/FlingEngine/Graphics/src/GeometrySubpass.cpp index 7c9e8a92..07864d57 100644 --- a/FlingEngine/Graphics/src/GeometrySubpass.cpp +++ b/FlingEngine/Graphics/src/GeometrySubpass.cpp @@ -237,6 +237,11 @@ namespace Fling m_GraphicsPipeline->m_RasterizationState = Initializers::PipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_FRONT_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE); + // deferred.frag's CPU_DRIVER: its llvmpipe workaround runs on a CPU driver only + const bool bCpuDriver = + VulkanApp::Get().GetPhysicalDevice()->GetDeviceProps().deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU; + m_GraphicsPipeline->SetFragmentConstant(0, bCpuDriver ? 1u : 0u); + // Create it otherwise with defaults m_GraphicsPipeline->CreateGraphicsPipeline(m_GlobalRenderPass, nullptr); } diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.cpp b/FlingEngine/Graphics/src/GraphicsPipeline.cpp index b3941ee8..e9100d93 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.cpp +++ b/FlingEngine/Graphics/src/GraphicsPipeline.cpp @@ -102,6 +102,27 @@ namespace Fling { // Shader stages std::vector shaderStages; + // The fragment shader's specialization constants (SetFragmentConstant), 4 bytes each + std::vector FragmentEntries; + for (size_t i = 0; i < m_FragmentConstants.size(); ++i) + { + VkSpecializationMapEntry Entry = {}; + Entry.constantID = m_FragmentConstants[i].first; + Entry.offset = static_cast(i * sizeof(uint32)); + Entry.size = sizeof(uint32); + FragmentEntries.push_back(Entry); + } + std::vector FragmentData; + for (const std::pair& Constant : m_FragmentConstants) + { + FragmentData.push_back(Constant.second); + } + VkSpecializationInfo FragmentSpecialization = {}; + FragmentSpecialization.mapEntryCount = static_cast(FragmentEntries.size()); + FragmentSpecialization.pMapEntries = FragmentEntries.data(); + FragmentSpecialization.dataSize = FragmentData.size() * sizeof(uint32); + FragmentSpecialization.pData = FragmentData.data(); + for (Shader* shader : m_Shaders) { VkPipelineShaderStageCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; @@ -110,7 +131,10 @@ namespace Fling { createInfo.pName = "main"; createInfo.flags = 0; createInfo.pNext = nullptr; - createInfo.pSpecializationInfo = nullptr; + createInfo.pSpecializationInfo = + (shader->GetStage() == VK_SHADER_STAGE_FRAGMENT_BIT && !FragmentEntries.empty()) + ? &FragmentSpecialization + : nullptr; shaderStages.push_back(createInfo); } @@ -118,12 +142,16 @@ namespace Fling { VkVertexInputBindingDescription BindingDescription = Vertex::GetBindingDescription(); std::array AttributeDescriptions = Vertex::GetAttributeDescriptions(); + m_VertexInputStateCreateInfo = {}; m_VertexInputStateCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; - m_VertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; - m_VertexInputStateCreateInfo.pVertexBindingDescriptions = &BindingDescription; - m_VertexInputStateCreateInfo.vertexAttributeDescriptionCount = - static_cast(AttributeDescriptions.size()); - m_VertexInputStateCreateInfo.pVertexAttributeDescriptions = AttributeDescriptions.data(); + if (m_HasVertexInput) + { + m_VertexInputStateCreateInfo.vertexBindingDescriptionCount = 1; + m_VertexInputStateCreateInfo.pVertexBindingDescriptions = &BindingDescription; + m_VertexInputStateCreateInfo.vertexAttributeDescriptionCount = + static_cast(AttributeDescriptions.size()); + m_VertexInputStateCreateInfo.pVertexAttributeDescriptions = AttributeDescriptions.data(); + } // Create graphics pipeline ------------------------ m_PipelineCreateInfo = {}; diff --git a/FlingEngine/Graphics/src/GraphicsPipeline.h b/FlingEngine/Graphics/src/GraphicsPipeline.h index 117139cd..a7ba0460 100644 --- a/FlingEngine/Graphics/src/GraphicsPipeline.h +++ b/FlingEngine/Graphics/src/GraphicsPipeline.h @@ -4,6 +4,7 @@ #include "Shader.h" #include "Vertex.h" +#include #include namespace Fling @@ -33,6 +34,23 @@ namespace Fling const std::vector GetShaders() const { return m_Shaders; } + /** + * Set a 32-bit specialization constant of the fragment shader (layout(constant_id = + * t_Id)), for example a bool as 0 or 1. Used by the next CreateGraphicsPipeline. + */ + void SetFragmentConstant(uint32 t_Id, uint32 t_Value) + { + for (std::pair& Constant : m_FragmentConstants) + { + if (Constant.first == t_Id) + { + Constant.second = t_Value; + return; + } + } + m_FragmentConstants.emplace_back(t_Id, t_Value); + } + Depth GetDepth() const { return m_Depth; } VkPrimitiveTopology GetTopology() const { return m_Topology; } VkPolygonMode GetPolygonMode() const { return m_PolygonMode; } @@ -66,6 +84,17 @@ namespace Fling VkDescriptorSetLayout m_DescriptorSetLayout; VkPipelineVertexInputStateCreateInfo m_VertexInputStateCreateInfo = {}; + + /** + * True (the default): the pipeline reads mesh vertices (Vertex) from binding 0. False: it + * has no vertex input, for a draw that makes its positions from gl_VertexIndex and binds + * no vertex buffer (a full screen triangle). A pipeline that declares input it is never + * given reads unbound memory: software drivers such as llvmpipe crash on it. + */ + bool m_HasVertexInput = true; + + /** @see SetFragmentConstant: (constant id, value). */ + std::vector> m_FragmentConstants; VkPipelineInputAssemblyStateCreateInfo m_InputAssemblyState = {}; VkPipelineRasterizationStateCreateInfo m_RasterizationState = {}; std::vector m_ColorBlendAttachmentStates; diff --git a/FlingEngine/Graphics/src/Instance.cpp b/FlingEngine/Graphics/src/Instance.cpp index 01c778d7..faf89b56 100644 --- a/FlingEngine/Graphics/src/Instance.cpp +++ b/FlingEngine/Graphics/src/Instance.cpp @@ -12,8 +12,12 @@ namespace Fling { - Instance::Instance() + Instance::Instance(const bool t_WithSurface) : m_WithSurface(t_WithSurface) { + if (m_WithSurface) + { + m_DeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); + } m_EnableValidationLayers = FlingConfig::GetBool("Vulkan", "EnableValidationLayers", false); F_LOG_TRACE("[Renderer] m_EnableValidationLayers is {}", (m_EnableValidationLayers ? "TRUE" : "FALSE")); @@ -121,11 +125,17 @@ namespace Fling std::vector Instance::GetRequiredExtensions() { - uint32 glfwExtensionCount = 0; - const char** glfwExtensions; - glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); - - std::vector extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); + std::vector extensions; + // An offscreen renderer has no window, so it needs no window system extension (and no glfwInit) + if (m_WithSurface) + { + uint32 glfwExtensionCount = 0; + const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); + if (glfwExtensions != nullptr) + { + extensions.assign(glfwExtensions, glfwExtensions + glfwExtensionCount); + } + } if (m_EnableValidationLayers) { diff --git a/FlingEngine/Graphics/src/Instance.h b/FlingEngine/Graphics/src/Instance.h index 84ed28ca..ae425d87 100644 --- a/FlingEngine/Graphics/src/Instance.h +++ b/FlingEngine/Graphics/src/Instance.h @@ -17,7 +17,12 @@ namespace Fling Instance(const Instance&) = delete; Instance& operator=(const Instance&) = delete; - explicit Instance(); + /** + * t_WithSurface: enable the extensions that a window needs (GLFW's instance extensions + * and VK_KHR_swapchain on the device). False for an offscreen renderer, which needs no + * window system at all. + */ + explicit Instance(bool t_WithSurface = true); ~Instance(); @@ -47,6 +52,9 @@ namespace Fling */ uint8 m_EnableValidationLayers : 1; + /** @see Instance() */ + bool m_WithSurface = true; + /** * Create the VkInstance of this object and application information */ @@ -99,7 +107,7 @@ namespace Fling /** The validation layers that we want to look for on this instance */ const std::vector m_ValidationLayers = {"VK_LAYER_LUNARG_standard_validation"}; - /** Device extension support for the swap chain */ - const std::vector m_DeviceExtensions = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; + /** The device extensions to enable: VK_KHR_swapchain with a surface, none offscreen */ + std::vector m_DeviceExtensions; }; } // namespace Fling \ No newline at end of file diff --git a/FlingEngine/Graphics/src/LogicalDevice.cpp b/FlingEngine/Graphics/src/LogicalDevice.cpp index f11d1d57..172cba99 100644 --- a/FlingEngine/Graphics/src/LogicalDevice.cpp +++ b/FlingEngine/Graphics/src/LogicalDevice.cpp @@ -41,10 +41,18 @@ namespace Fling m_SupportedQueues |= VK_QUEUE_GRAPHICS_BIT; } - // Check for presentation support. - VkBool32 presentSupport; - vkGetPhysicalDeviceSurfaceSupportKHR( - m_PhysicalDevice->GetVkPhysicalDevice(), i, m_Surface, &presentSupport); + // Check for presentation support. With no surface (offscreen) nothing is presented, + // and the "present" queue is the graphics queue + VkBool32 presentSupport = VK_FALSE; + if (m_Surface != VK_NULL_HANDLE) + { + vkGetPhysicalDeviceSurfaceSupportKHR( + m_PhysicalDevice->GetVkPhysicalDevice(), i, m_Surface, &presentSupport); + } + else + { + presentSupport = (QueueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) ? VK_TRUE : VK_FALSE; + } if (QueueFamilies[i].queueCount > 0 && presentSupport) { diff --git a/FlingEngine/Graphics/src/SkyboxSubpass.cpp b/FlingEngine/Graphics/src/SkyboxSubpass.cpp index 2fbc7023..6973aefa 100644 --- a/FlingEngine/Graphics/src/SkyboxSubpass.cpp +++ b/FlingEngine/Graphics/src/SkyboxSubpass.cpp @@ -118,6 +118,9 @@ namespace Fling m_GraphicsPipeline->m_RasterizationState = Initializers::PipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE); + // The vertex shader makes the triangle from gl_VertexIndex: no vertex buffer is bound + m_GraphicsPipeline->m_HasVertexInput = false; + m_GraphicsPipeline->m_DepthStencilState.depthTestEnable = VK_FALSE; m_GraphicsPipeline->m_DepthStencilState.depthWriteEnable = VK_FALSE; diff --git a/FlingEngine/Graphics/src/SwapChain.cpp b/FlingEngine/Graphics/src/SwapChain.cpp index afe4f671..3ba398ce 100644 --- a/FlingEngine/Graphics/src/SwapChain.cpp +++ b/FlingEngine/Graphics/src/SwapChain.cpp @@ -1,5 +1,6 @@ #include "FlingIntegers.h" #include "FlingWindow.h" +#include "GraphicsHelpers.h" #include "Logger.h" #include "LogicalDevice.h" #include "PhyscialDevice.h" @@ -40,6 +41,24 @@ namespace Fling Recreate(m_Extents); } + Swapchain::Swapchain(const VkExtent2D& t_Extent, + LogicalDevice* t_Dev, + PhysicalDevice* t_PhysDev, + const uint32 t_ImageCount) + : m_VSync(false), + m_Extents{t_Extent}, + m_Device(t_Dev), + m_PhysicalDevice(t_PhysDev), + m_Surface(VK_NULL_HANDLE), + m_Offscreen(true), + m_OffscreenImageCount(t_ImageCount) + { + assert(m_Device && m_PhysicalDevice && m_OffscreenImageCount > 0); + // Nothing is presented, so nothing waits for a display + m_PresentMode = PresentMode::Immediate; + Recreate(m_Extents); + } + Swapchain::~Swapchain() { Cleanup(); @@ -62,7 +81,7 @@ namespace Fling assert(m_Device); VkDevice Device = m_Device->GetVkDevice(); - // Image views + // Image views. Cleared, so a second Cleanup (the destructor after a resize) frees nothing twice for (size_t i = 0; i < m_ImageViews.size(); i++) { if (m_ImageViews[i] != VK_NULL_HANDLE) @@ -70,11 +89,25 @@ namespace Fling vkDestroyImageView(Device, m_ImageViews[i], nullptr); } } + m_ImageViews.clear(); if (m_SwapChain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(Device, m_SwapChain, nullptr); + m_SwapChain = VK_NULL_HANDLE; } + + // Offscreen: this swap chain made the images, so it frees them + if (m_Offscreen) + { + for (size_t i = 0; i < m_Images.size(); ++i) + { + vkDestroyImage(Device, m_Images[i], nullptr); + vkFreeMemory(Device, m_ImageMemory[i], nullptr); + } + m_ImageMemory.clear(); + } + m_Images.clear(); } SwapChainSupportDetails Swapchain::QuerySwapChainSupport() @@ -110,8 +143,52 @@ namespace Fling return Details; } + void Swapchain::CreateOffscreenImages() + { + // The format a surface would most likely give (ChooseSwapChainSurfaceFormat), so the + // pipelines are the same as with a window. RGBA if the device cannot draw to BGRA. + m_ImageFormat = VK_FORMAT_B8G8R8A8_UNORM; + VkFormatProperties Props = {}; + vkGetPhysicalDeviceFormatProperties(m_PhysicalDevice->GetVkPhysicalDevice(), m_ImageFormat, &Props); + if (!(Props.optimalTilingFeatures & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) + { + m_ImageFormat = VK_FORMAT_R8G8B8A8_UNORM; + } + F_LOG_TRACE("Offscreen swap chain: {} images of {}x{}, format {}", + m_OffscreenImageCount, + m_Extents.width, + m_Extents.height, + static_cast(m_ImageFormat)); + + // Always copyable: a capture (Screenshot::Request) copies from the image in the frame's + // own command buffer, and there is no display whose compression the usage could cost + m_CanCopyImages = true; + const VkImageUsageFlags Usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + m_Images.resize(m_OffscreenImageCount); + m_ImageMemory.resize(m_OffscreenImageCount); + for (uint32 i = 0; i < m_OffscreenImageCount; ++i) + { + GraphicsHelpers::CreateVkImage(m_Device->GetVkDevice(), + m_Extents.width, + m_Extents.height, + m_ImageFormat, + VK_IMAGE_TILING_OPTIMAL, + Usage, + VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, + m_Images[i], + m_ImageMemory[i]); + } + // AquireNextImage moves to the next image first, so the first frame draws to image 0 + m_ActiveImageIndex = m_OffscreenImageCount - 1; + } + void Swapchain::CreateResources() { + if (m_Offscreen) + { + CreateOffscreenImages(); + return; + } assert(m_Device && m_Surface); SwapChainSupportDetails SwapChainSupport = QuerySwapChainSupport(); @@ -139,6 +216,14 @@ namespace Fling CreateInfo.imageExtent = m_Extents; CreateInfo.imageArrayLayers = 1; CreateInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; + // A capture (Screenshot::Request) copies from the image in the frame's own command + // buffer. The usage is set once, when the surface allows it, so a capture never makes + // the swap chain again. It costs no CPU time; desktop drivers keep their compression + m_CanCopyImages = (SwapChainSupport.Capabilities.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) != 0; + if (m_CanCopyImages) + { + CreateInfo.imageUsage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + } // Specify the handling of multiple queue families uint32 GraphicsFam = m_Device->GetGraphicsFamily(); @@ -228,6 +313,14 @@ namespace Fling { assert(m_Device); + if (m_Offscreen) + { + // Each image in turn, with no GPU work: the image is free, because the last frame's + // fence was waited on, and VulkanApp::Update does not wait on t_CompletedSemaphore + m_ActiveImageIndex = (m_ActiveImageIndex + 1) % static_cast(m_Images.size()); + return VK_SUCCESS; + } + VkDevice Device = m_Device->GetVkDevice(); VkResult iRes = vkAcquireNextImageKHR(Device, m_SwapChain, @@ -240,6 +333,12 @@ namespace Fling VkResult Swapchain::QueuePresent(const VkQueue& t_PresentQueue, const VkSemaphore& t_WaitSemaphore) { + if (m_Offscreen) + { + // Nothing to show, and no GPU work: VulkanApp::Update does not signal t_WaitSemaphore + return VK_SUCCESS; + } + VkPresentInfoKHR presentInfo = {}; presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; diff --git a/FlingEngine/Graphics/src/SwapChain.h b/FlingEngine/Graphics/src/SwapChain.h index 09a877b5..f5d759b8 100644 --- a/FlingEngine/Graphics/src/SwapChain.h +++ b/FlingEngine/Graphics/src/SwapChain.h @@ -29,6 +29,14 @@ namespace Fling /** t_VSync: SetVSync. */ Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, VkSurfaceKHR t_Surface, bool t_VSync); + /** + * An offscreen swap chain (--offscreen): t_ImageCount images that it makes and owns, with + * no surface. AquireNextImage takes the next image in turn and QueuePresent shows + * nothing. Neither does GPU work or touches the semaphores: VulkanApp::Update skips + * the present semaphores offscreen. + */ + Swapchain(const VkExtent2D& t_Extent, LogicalDevice* t_Dev, PhysicalDevice* t_PhysDev, uint32 t_ImageCount); + ~Swapchain(); VkResult AquireNextImage(const VkSemaphore& t_CompletedSemaphore); @@ -51,6 +59,24 @@ namespace Fling const VkSwapchainKHR& GetVkSwapChain() const { return m_SwapChain; } + /** True for an offscreen swap chain: no surface, no present. */ + bool IsOffscreen() const { return m_Offscreen; } + + /** + * The layout of an image after the frame's render pass: PRESENT_SRC with a surface. + * Offscreen nothing presents it, and a capture copies from it: TRANSFER_SRC. + */ + VkImageLayout GetFinalLayout() const + { + return m_Offscreen ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + } + + /** + * True when the images can be copied from (VK_IMAGE_USAGE_TRANSFER_SRC_BIT), for a + * capture. Always offscreen; with a surface, when the surface allows the usage. + */ + bool CanCopyImages() const { return m_CanCopyImages; } + /** The present mode it was made with. */ PresentMode GetPresentMode() const { return m_PresentMode; } @@ -83,6 +109,21 @@ namespace Fling const PhysicalDevice* m_PhysicalDevice; const VkSurfaceKHR m_Surface; + /** @see IsOffscreen */ + const bool m_Offscreen = false; + + /** Offscreen: how many images to make. */ + uint32 m_OffscreenImageCount = 0; + + /** Offscreen: the memory of each image. */ + std::vector m_ImageMemory; + + /** @see CanCopyImages */ + bool m_CanCopyImages = false; + + /** Offscreen CreateResources: make the images and their memory. */ + void CreateOffscreenImages(); + /** The images inside of the swap chain */ std::vector m_Images; std::vector m_ImageViews; diff --git a/FlingEngine/Graphics/src/VulkanApp.cpp b/FlingEngine/Graphics/src/VulkanApp.cpp index 32db0422..7d6d68a0 100644 --- a/FlingEngine/Graphics/src/VulkanApp.cpp +++ b/FlingEngine/Graphics/src/VulkanApp.cpp @@ -8,6 +8,7 @@ #include "FlingConfig.h" #include "FlingIntegers.h" #include "FlingWindow.h" +#include "FrameCapture.h" #include "GeometrySubpass.h" #include "GitVersion.h" #include "GraphicsHelpers.h" @@ -140,26 +141,65 @@ namespace Fling void VulkanApp::Prepare() { - CreateGameWindow(FlingConfig::GetInt("Engine", "WindowWidth", FLING_DEFAULT_WINDOW_WIDTH), - FlingConfig::GetInt("Engine", "WindowHeight", FLING_DEFAULT_WINDOW_WIDTH)); + // --resolution, else the config + const uint32 Width = m_SurfaceDesc.Width > 0 + ? m_SurfaceDesc.Width + : FlingConfig::GetInt("Engine", "WindowWidth", FLING_DEFAULT_WINDOW_WIDTH); + const uint32 Height = m_SurfaceDesc.Height > 0 + ? m_SurfaceDesc.Height + : FlingConfig::GetInt("Engine", "WindowHeight", FLING_DEFAULT_WINDOW_HEIGHT); + const bool bOffscreen = m_SurfaceDesc.Offscreen; - m_Instance = new Instance(); + // Offscreen: no window, no glfwInit, and no window system extension + if (!bOffscreen) + { + CreateGameWindow(Width, Height); + } + + m_Instance = new Instance(/* t_WithSurface */ !bOffscreen); assert(m_Instance); - m_CurrentWindow->CreateSurface(m_Instance->GetRawVkInstance(), &m_State->m_Surface); + if (!bOffscreen) + { + if (const char* Missing = VulkanLoader::MissingSurfaceCommand()) + { + F_LOG_ERROR("The Vulkan driver has no {}: a window cannot be shown", Missing); + F_LOG_FATAL("The Vulkan driver cannot show a window (no VK_KHR_surface). Try --offscreen"); + } + m_CurrentWindow->CreateSurface(m_Instance->GetRawVkInstance(), &m_State->m_Surface); + } m_PhysicalDevice = new PhysicalDevice(m_Instance->GetBestPhysicalDevice()); assert(m_PhysicalDevice); + F_LOG_TRACE("Render device: {} ({})", GetPhysicalDeviceName(), bOffscreen ? "offscreen" : "window"); m_LogicalDevice = new LogicalDevice(m_Instance, m_PhysicalDevice, m_State->m_Surface); assert(m_LogicalDevice); + if (!bOffscreen) + { + if (const char* Missing = VulkanLoader::MissingSwapchainCommand()) + { + F_LOG_ERROR("The Vulkan driver has no {}: a window cannot be shown", Missing); + F_LOG_FATAL("The Vulkan driver cannot show a window (no VK_KHR_swapchain). Try --offscreen"); + } + } - m_SwapChain = new Swapchain(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface), - m_LogicalDevice, - m_PhysicalDevice, - m_State->m_Surface, - m_VSync); + if (bOffscreen) + { + const VkExtent2D Extent = {std::max(Width, 1), std::max(Height, 1)}; + m_SwapChain = new Swapchain(Extent, m_LogicalDevice, m_PhysicalDevice, VkConfig::MAX_FRAMES_IN_FLIGHT); + } + else + { + m_SwapChain = new Swapchain(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface), + m_LogicalDevice, + m_PhysicalDevice, + m_State->m_Surface, + m_VSync); + } assert(m_SwapChain); + // Holds nothing until the first Screenshot::Request: no thread and no buffer + m_Capturer = std::make_unique(); GraphicsHelpers::CreateCommandPool(&m_State->m_CommandPool, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT); @@ -168,7 +208,10 @@ namespace Fling // Create the camera float CamMoveSpeed = FlingConfig::GetFloat("Camera", "MoveSpeed", 10.0f); float CamRotSpeed = FlingConfig::GetFloat("Camera", "RotationSpeed", 40.0f); - m_Camera = new FirstPersonCamera(m_CurrentWindow->GetAspectRatio(), CamMoveSpeed, CamRotSpeed); + const float Aspect = m_CurrentWindow ? m_CurrentWindow->GetAspectRatio() + : static_cast(m_SwapChain->GetExtents().width) / + static_cast(m_SwapChain->GetExtents().height); + m_Camera = new FirstPersonCamera(Aspect, CamMoveSpeed, CamRotSpeed); BuildSwapChainResources(); } @@ -228,7 +271,8 @@ namespace Fling colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; - colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; + // PRESENT_SRC for a window; offscreen, TRANSFER_SRC (a capture copies from it) + colorAttachment.finalLayout = m_SwapChain->GetFinalLayout(); VkAttachmentDescription depthAttachment = {}; depthAttachment.format = DepthBuffer::GetDepthBufferFormat(); @@ -388,10 +432,29 @@ namespace Fling return m_SwapChain ? m_SwapChain->GetPresentMode() : PresentMode::Fifo; } + uint32 VulkanApp::GetFrameWidth() const + { + return m_SwapChain ? m_SwapChain->GetExtents().width : 0; + } + + uint32 VulkanApp::GetFrameHeight() const + { + return m_SwapChain ? m_SwapChain->GetExtents().height : 0; + } + + void VulkanApp::FinishScreenshots() + { + if (m_Capturer) + { + m_Capturer->Flush(); + } + } + void VulkanApp::RecreateSwapchain() { F_LOG_TRACE("Making the swap chain again"); - if (!m_CurrentWindow->WaitForNewWindowSize()) + // Offscreen images keep their size (there is no window) + if (m_CurrentWindow != nullptr && !m_CurrentWindow->WaitForNewWindowSize()) { // The window was closed while minimized. ShouldTick sees the close next. return; @@ -400,7 +463,9 @@ namespace Fling CleanupSwapChainResources(); - m_SwapChain->Recreate(ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface)); + m_SwapChain->Recreate(m_CurrentWindow != nullptr + ? ChooseSwapExtent(m_CurrentWindow, m_PhysicalDevice, m_State->m_Surface) + : m_SwapChain->GetExtents()); BuildSwapChainResources(); @@ -509,7 +574,12 @@ namespace Fling ); }*/ - if (t_Conf & PipelineFlags::IMGUI) + if ((t_Conf & PipelineFlags::IMGUI) && m_CurrentWindow == nullptr) + { + // ImGui reads its input from the window + F_LOG_WARN("IMGUI render pipeline needs a window: there is none offscreen, so it is left out"); + } + else if (t_Conf & PipelineFlags::IMGUI) { #if WITH_IMGUI F_LOG_TRACE("Bulid IMGUI render pipeline! "); @@ -540,9 +610,17 @@ namespace Fling const RenderSnapshot& Snapshot = SnapshotPtr ? *SnapshotPtr : s_EmptySnapshot; // Prepare the frame for submission by waiting for the swap chain - m_CurrentWindow->Update(); - m_Camera->SetViewportSize(static_cast(m_CurrentWindow->GetFramebufferWidth()), - static_cast(m_CurrentWindow->GetFramebufferHeight())); + if (m_CurrentWindow) + { + m_CurrentWindow->Update(); + m_Camera->SetViewportSize(static_cast(m_CurrentWindow->GetFramebufferWidth()), + static_cast(m_CurrentWindow->GetFramebufferHeight())); + } + else + { + m_Camera->SetViewportSize(static_cast(m_SwapChain->GetExtents().width), + static_cast(m_SwapChain->GetExtents().height)); + } m_Camera->Update(DeltaTime); // A game's view (CameraView, written by its frame system) turns the camera. The debug camera still moves it. const CameraView* View = t_Reg.TryGetSingleton(); @@ -551,6 +629,12 @@ namespace Fling m_Camera->SetLookRotation(View->Yaw, View->Pitch); } + // The screenshots that the writer thread finished: their callbacks (one atomic load when none) + m_Capturer->DeliverResults(); + + // Offscreen there is no present engine: no semaphores between the acquire, the frame and the present + const bool bPresentSync = !m_SwapChain->IsOffscreen(); + // Aquire the active image index VkResult iResult = m_SwapChain->AquireNextImage(m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]); uint32 ImageIndex = m_SwapChain->GetActiveImageIndex(); @@ -621,6 +705,10 @@ namespace Fling CmdBuf->EndRenderPass(); + // A screenshot waits: the GPU copies this frame out in the same command buffer + // (nothing is recorded when none waits) + m_Capturer->RecordCopy(CmdBuf->GetHandle(), *m_SwapChain, ImageIndex); + // End command buffer recording CmdBuf->End(); } @@ -651,7 +739,7 @@ namespace Fling OffscreenSubmission.pWaitDstStageMask = waitStages; // Wait on Present complete OffscreenSubmission.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; - OffscreenSubmission.waitSemaphoreCount = 1; + OffscreenSubmission.waitSemaphoreCount = bPresentSync ? 1 : 0; // Signal that the dependent semaphores are done when this is complete OffscreenSubmission.pSignalSemaphores = SemaphoresToWaitOn.data(); @@ -678,7 +766,7 @@ namespace Fling else { // Track any semaphores that we may need to wait on for the render pipeline - FinalScreenSubmitInfo.waitSemaphoreCount = 1; + FinalScreenSubmitInfo.waitSemaphoreCount = bPresentSync ? 1 : 0; FinalScreenSubmitInfo.pWaitSemaphores = &m_State->m_PresentCompleteSemaphores[CurrentFrameIndex]; } @@ -693,7 +781,7 @@ namespace Fling FinalScreenSubmitInfo.commandBufferCount = (uint32)submitCommandBuffers.size(); // Actually present the swap chain queue. This is always going to be the signal for the final semaphore - FinalScreenSubmitInfo.signalSemaphoreCount = 1; + FinalScreenSubmitInfo.signalSemaphoreCount = bPresentSync ? 1 : 0; FinalScreenSubmitInfo.pSignalSemaphores = &m_State->m_RenderFinishedSemaphores[ImageIndex]; VK_CHECK_RESULT(vkQueueSubmit(m_LogicalDevice->GetGraphicsQueue(), @@ -708,6 +796,9 @@ namespace Fling VK_TRUE, std::numeric_limits::max()); + // The frame is drawn, and so is a screenshot's copy: the writer thread takes it from here + m_Capturer->OnFrameDone(); + // Present the swap chain with the renderer finished semaphore iResult = m_SwapChain->QueuePresent(m_LogicalDevice->GetPresentQueue(), m_State->m_RenderFinishedSemaphores[ImageIndex]); @@ -758,6 +849,13 @@ namespace Fling delete m_Camera; m_Camera = nullptr; + // Screenshots: the writes that are queued finish, and the staging buffers go before the device + if (m_Capturer) + { + m_Capturer->Release(); + m_Capturer.reset(); + } + // Destroy swap chain (created in Prepare) ----------- delete m_SwapChain; m_SwapChain = nullptr; @@ -794,7 +892,12 @@ namespace Fling delete m_LogicalDevice; m_LogicalDevice = nullptr; - vkDestroySurfaceKHR(m_Instance->GetRawVkInstance(), m_State->m_Surface, nullptr); + // Offscreen there is no surface + if (m_State->m_Surface != VK_NULL_HANDLE) + { + vkDestroySurfaceKHR(m_Instance->GetRawVkInstance(), m_State->m_Surface, nullptr); + m_State->m_Surface = VK_NULL_HANDLE; + } delete m_PhysicalDevice; m_PhysicalDevice = nullptr; diff --git a/FlingEngine/Graphics/src/VulkanFunctions.inl b/FlingEngine/Graphics/src/VulkanFunctions.inl index 7c779c75..05818299 100644 --- a/FlingEngine/Graphics/src/VulkanFunctions.inl +++ b/FlingEngine/Graphics/src/VulkanFunctions.inl @@ -51,7 +51,6 @@ FLING_VK_GLOBAL_OPTIONAL(vkEnumerateInstanceVersion) FLING_VK_INSTANCE(vkCreateDevice) FLING_VK_INSTANCE(vkDestroyInstance) -FLING_VK_INSTANCE(vkDestroySurfaceKHR) FLING_VK_INSTANCE(vkEnumerateDeviceExtensionProperties) FLING_VK_INSTANCE(vkEnumeratePhysicalDevices) FLING_VK_INSTANCE(vkGetDeviceProcAddr) @@ -60,15 +59,18 @@ FLING_VK_INSTANCE(vkGetPhysicalDeviceFormatProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceMemoryProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceProperties) FLING_VK_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceFormatsKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfacePresentModesKHR) -FLING_VK_INSTANCE(vkGetPhysicalDeviceSurfaceSupportKHR) FLING_VK_INSTANCE_OPTIONAL(vkCreateDebugUtilsMessengerEXT) FLING_VK_INSTANCE_OPTIONAL(vkDestroyDebugUtilsMessengerEXT) -FLING_VK_DEVICE(vkAcquireNextImageKHR) +// VK_KHR_surface: an offscreen renderer (--offscreen) does not enable it. +// VulkanLoader::MissingPresentCommand checks them when there is a window. +FLING_VK_INSTANCE_OPTIONAL(vkDestroySurfaceKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceCapabilitiesKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceFormatsKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfacePresentModesKHR) +FLING_VK_INSTANCE_OPTIONAL(vkGetPhysicalDeviceSurfaceSupportKHR) + FLING_VK_DEVICE(vkAllocateCommandBuffers) FLING_VK_DEVICE(vkAllocateDescriptorSets) FLING_VK_DEVICE(vkAllocateMemory) @@ -83,6 +85,7 @@ FLING_VK_DEVICE(vkCmdBindVertexBuffers) FLING_VK_DEVICE(vkCmdBlitImage) FLING_VK_DEVICE(vkCmdCopyBuffer) FLING_VK_DEVICE(vkCmdCopyBufferToImage) +FLING_VK_DEVICE(vkCmdCopyImageToBuffer) FLING_VK_DEVICE(vkCmdDraw) FLING_VK_DEVICE(vkCmdDrawIndexed) FLING_VK_DEVICE(vkCmdEndRenderPass) @@ -106,7 +109,6 @@ FLING_VK_DEVICE(vkCreateRenderPass) FLING_VK_DEVICE(vkCreateSampler) FLING_VK_DEVICE(vkCreateSemaphore) FLING_VK_DEVICE(vkCreateShaderModule) -FLING_VK_DEVICE(vkCreateSwapchainKHR) FLING_VK_DEVICE(vkDestroyBuffer) FLING_VK_DEVICE(vkDestroyCommandPool) FLING_VK_DEVICE(vkDestroyDescriptorPool) @@ -123,7 +125,6 @@ FLING_VK_DEVICE(vkDestroyRenderPass) FLING_VK_DEVICE(vkDestroySampler) FLING_VK_DEVICE(vkDestroySemaphore) FLING_VK_DEVICE(vkDestroyShaderModule) -FLING_VK_DEVICE(vkDestroySwapchainKHR) FLING_VK_DEVICE(vkDeviceWaitIdle) FLING_VK_DEVICE(vkEndCommandBuffer) FLING_VK_DEVICE(vkFlushMappedMemoryRanges) @@ -133,9 +134,7 @@ FLING_VK_DEVICE(vkFreeMemory) FLING_VK_DEVICE(vkGetBufferMemoryRequirements) FLING_VK_DEVICE(vkGetDeviceQueue) FLING_VK_DEVICE(vkGetImageMemoryRequirements) -FLING_VK_DEVICE(vkGetSwapchainImagesKHR) FLING_VK_DEVICE(vkMapMemory) -FLING_VK_DEVICE(vkQueuePresentKHR) FLING_VK_DEVICE(vkQueueSubmit) FLING_VK_DEVICE(vkQueueWaitIdle) FLING_VK_DEVICE(vkResetFences) @@ -143,6 +142,14 @@ FLING_VK_DEVICE(vkUnmapMemory) FLING_VK_DEVICE(vkUpdateDescriptorSets) FLING_VK_DEVICE(vkWaitForFences) +// VK_KHR_swapchain: an offscreen renderer (--offscreen) does not enable it. +// VulkanLoader::MissingPresentCommand checks them when there is a window. +FLING_VK_DEVICE_OPTIONAL(vkAcquireNextImageKHR) +FLING_VK_DEVICE_OPTIONAL(vkCreateSwapchainKHR) +FLING_VK_DEVICE_OPTIONAL(vkDestroySwapchainKHR) +FLING_VK_DEVICE_OPTIONAL(vkGetSwapchainImagesKHR) +FLING_VK_DEVICE_OPTIONAL(vkQueuePresentKHR) + #ifdef FLING_VK_CLEAR_GLOBAL #undef FLING_VK_GLOBAL #undef FLING_VK_CLEAR_GLOBAL diff --git a/FlingEngine/Graphics/src/VulkanLoader.cpp b/FlingEngine/Graphics/src/VulkanLoader.cpp index 42a72007..37de93f4 100644 --- a/FlingEngine/Graphics/src/VulkanLoader.cpp +++ b/FlingEngine/Graphics/src/VulkanLoader.cpp @@ -4,7 +4,9 @@ #include "Strings/String.h" #include "VulkanLoader.h" +#include #include +#include extern "C" { @@ -169,6 +171,48 @@ namespace Fling #undef FLING_VK_DEVICE } + namespace + { + /** The name of the first null command, or null. */ + const char* FirstMissing(std::initializer_list> t_Commands) + { + for (const auto& [Name, Command] : t_Commands) + { + if (Command == nullptr) + { + return Name; + } + } + return nullptr; + } + } // namespace + + const char* VulkanLoader::MissingSurfaceCommand() + { + return FirstMissing({ + {"vkDestroySurfaceKHR", reinterpret_cast(vkDestroySurfaceKHR)}, + {"vkGetPhysicalDeviceSurfaceCapabilitiesKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceCapabilitiesKHR)}, + {"vkGetPhysicalDeviceSurfaceFormatsKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceFormatsKHR)}, + {"vkGetPhysicalDeviceSurfacePresentModesKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfacePresentModesKHR)}, + {"vkGetPhysicalDeviceSurfaceSupportKHR", + reinterpret_cast(vkGetPhysicalDeviceSurfaceSupportKHR)}, + }); + } + + const char* VulkanLoader::MissingSwapchainCommand() + { + return FirstMissing({ + {"vkAcquireNextImageKHR", reinterpret_cast(vkAcquireNextImageKHR)}, + {"vkCreateSwapchainKHR", reinterpret_cast(vkCreateSwapchainKHR)}, + {"vkDestroySwapchainKHR", reinterpret_cast(vkDestroySwapchainKHR)}, + {"vkGetSwapchainImagesKHR", reinterpret_cast(vkGetSwapchainImagesKHR)}, + {"vkQueuePresentKHR", reinterpret_cast(vkQueuePresentKHR)}, + }); + } + void VulkanLoader::UnloadLoader() { #define FLING_VK_GLOBAL(name) ClearProc(name); diff --git a/FlingEngine/Graphics/src/VulkanLoader.h b/FlingEngine/Graphics/src/VulkanLoader.h index 2f2ef2d7..b04e0a51 100644 --- a/FlingEngine/Graphics/src/VulkanLoader.h +++ b/FlingEngine/Graphics/src/VulkanLoader.h @@ -34,5 +34,15 @@ namespace Fling * Call this after vkDestroyInstance. */ static void UnloadLoader(); + + /** + * The name of the first surface command (VK_KHR_surface, loaded with the instance) that + * did not load, or null when all did. A renderer with a window needs them; an offscreen + * one does not. + */ + static const char* MissingSurfaceCommand(); + + /** The same for the swap chain commands (VK_KHR_swapchain, loaded with the device). */ + static const char* MissingSwapchainCommand(); }; } // namespace Fling diff --git a/FlingTests/Core/FlingPathsTests.cpp b/FlingTests/Core/FlingPathsTests.cpp new file mode 100644 index 00000000..f5716d2b --- /dev/null +++ b/FlingTests/Core/FlingPathsTests.cpp @@ -0,0 +1,56 @@ +#include "FlingPaths.h" +#include "Strings/String.h" + +#include +#include +#include +#include +#include + +using Fling::FlingPaths; +using Fling::String; + +namespace +{ + String ReadAll(const std::filesystem::path& t_Path) + { + std::ifstream File(t_Path, std::ios::binary); + return String(std::istreambuf_iterator(File), std::istreambuf_iterator()); + } +} // namespace + +TEST_CASE("FlingPaths::SaveFile makes the folders and replaces the file", "[FlingPaths]") +{ + const std::filesystem::path Root = std::filesystem::temp_directory_path() / "FlingPathsSaveFileTest"; + std::error_code Ignored; + std::filesystem::remove_all(Root, Ignored); + const std::filesystem::path File = Root / "a" / "b" / "out.bin"; + + String Error; + // Binary: a zero byte and a newline are written as is + const String Bytes("one\0two\n", 8); + REQUIRE(FlingPaths::SaveFile(Fling::PathToUtf8(File), Bytes, Error)); + REQUIRE(Error.empty()); + REQUIRE(ReadAll(File) == Bytes); + + // Replaced, not appended to + REQUIRE(FlingPaths::SaveFile(Fling::PathToUtf8(File), "short", Error)); + REQUIRE(ReadAll(File) == "short"); + + std::filesystem::remove_all(Root, Ignored); +} + +TEST_CASE("FlingPaths::SaveFile says why it failed", "[FlingPaths]") +{ + const std::filesystem::path Root = std::filesystem::temp_directory_path() / "FlingPathsSaveFileFail"; + std::error_code Ignored; + std::filesystem::remove_all(Root, Ignored); + std::filesystem::create_directories(Root / "folder", Ignored); + + // The path is a folder, so it cannot be opened as a file + String Error; + REQUIRE_FALSE(FlingPaths::SaveFile(Fling::PathToUtf8(Root / "folder"), "x", Error)); + REQUIRE_FALSE(Error.empty()); + + std::filesystem::remove_all(Root, Ignored); +} diff --git a/FlingTests/Core/LaunchOptionsTests.cpp b/FlingTests/Core/LaunchOptionsTests.cpp index 26a935fe..534f769b 100644 --- a/FlingTests/Core/LaunchOptionsTests.cpp +++ b/FlingTests/Core/LaunchOptionsTests.cpp @@ -263,3 +263,113 @@ TEST_CASE("Launch Options", "[Launch Options]") REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--present-mode is not a flag: --vsync on|off")); } } + +TEST_CASE("Launch Options: offscreen rendering and captures", "[Launch Options]") +{ + using namespace Fling; + + LaunchOptions Options; + String Error; + + SECTION("Defaults: a window, no captures") + { + REQUIRE(ParseLaunchArgs({}, Options, Error)); + REQUIRE_FALSE(Options.Offscreen); + REQUIRE_FALSE(Options.IsHeadless()); + REQUIRE(Options.ResolutionWidth == 0); + REQUIRE(Options.Screenshot.empty()); + REQUIRE(Options.DumpState.empty()); + } + + SECTION("--offscreen is headless, and renders") + { + REQUIRE(ParseLaunchArgs({"--offscreen", "--resolution", "1280x720"}, Options, Error)); + REQUIRE(Options.Offscreen); + REQUIRE_FALSE(Options.NullRender); + REQUIRE(Options.IsHeadless()); + REQUIRE(Options.ResolutionWidth == 1280); + REQUIRE(Options.ResolutionHeight == 720); + + REQUIRE(ParseLaunchArgs({"--null-render"}, Options, Error)); + REQUIRE(Options.IsHeadless()); + + REQUIRE_FALSE(ParseLaunchArgs({"--offscreen", "--null-render"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("cannot be used together")); + } + + SECTION("--resolution must be x") + { + for (const char* Bad : {"1280", "1280x", "x720", "0x720", "1280x0", "99999x10", "wide"}) + { + REQUIRE_FALSE(ParseLaunchArgs({"--resolution", Bad}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--resolution")); + } + } + + SECTION("Captures at a tick list, sorted, with no repeats") + { + REQUIRE(ParseLaunchArgs({"--offscreen", + "--screenshot", + "shot.png", + "--screenshot-ticks", + "60,30,60", + "--dump-state", + "state.json", + "--dump-state-ticks", + "5"}, + Options, + Error)); + REQUIRE(Options.Screenshot == "shot.png"); + REQUIRE(Options.ScreenshotTicks == std::vector{30, 60}); + REQUIRE(Options.DumpState == "state.json"); + REQUIRE(Options.DumpStateTicks == std::vector{5}); + + for (const char* Bad : {"0", "1,,2", "a", "3,"}) + { + REQUIRE_FALSE(ParseLaunchArgs({"--dump-state", "s.json", "--dump-state-ticks", Bad}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--dump-state-ticks")); + } + } + + SECTION("A capture with no tick list is at the last tick, so it needs --frames") + { + REQUIRE(ParseLaunchArgs({"--null-render", "--frames", "30", "--dump-state", "s.json"}, Options, Error)); + REQUIRE(Options.DumpStateTicks.empty()); + + REQUIRE_FALSE(ParseLaunchArgs({"--null-render", "--dump-state", "s.json"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--dump-state needs --frames")); + REQUIRE_FALSE(ParseLaunchArgs({"--offscreen", "--screenshot", "s.png"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--screenshot needs --frames")); + } + + SECTION("Misused capture flags are errors") + { + REQUIRE_FALSE(ParseLaunchArgs({"--screenshot-ticks", "3"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs --screenshot")); + REQUIRE_FALSE(ParseLaunchArgs({"--dump-state-ticks", "3"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs --dump-state")); + + // There is no frame to save without a renderer; the state dump is the text view + REQUIRE_FALSE(ParseLaunchArgs({"--null-render", "--frames", "5", "--screenshot", "s.png"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("--offscreen")); + REQUIRE_FALSE(ParseLaunchArgs({"--screenshot"}, Options, Error)); + REQUIRE_THAT(Error, Catch::Matchers::ContainsSubstring("needs a file path")); + } +} + +TEST_CASE("Capture file names", "[Launch Options]") +{ + using Fling::CaptureFilePath; + + // One tick: the path as it is + REQUIRE(CaptureFilePath("Saved/shot.png", 30, false) == "Saved/shot.png"); + // More than one: the tick before the extension + REQUIRE(CaptureFilePath("Saved/shot.png", 30, true) == "Saved/shot_tick30.png"); + REQUIRE(CaptureFilePath("state", 7, true) == "state_tick7"); + // A dot in a folder name is not an extension + REQUIRE(CaptureFilePath("out.d/state", 7, true) == "out.d/state_tick7"); + REQUIRE(CaptureFilePath("out.d\\state", 7, true) == "out.d\\state_tick7"); + // {tick} puts the tick where the caller wants it, with one tick or many + REQUIRE(CaptureFilePath("frames/{tick}.png", 120, false) == "frames/120.png"); + REQUIRE(CaptureFilePath("frames/f{tick}.png", 5, true) == "frames/f5.png"); +} diff --git a/FlingTests/Core/RunSettingsTests.cpp b/FlingTests/Core/RunSettingsTests.cpp index 9f98cdf6..ee2f5faa 100644 --- a/FlingTests/Core/RunSettingsTests.cpp +++ b/FlingTests/Core/RunSettingsTests.cpp @@ -83,6 +83,14 @@ TEST_CASE("Run settings: the frame cap is the monitor's refresh rate, else 60", Settings.ResolveFrameCap(std::nullopt); REQUIRE(Settings.MaxFps == 30); REQUIRE(Settings.MaxFpsSource == SettingSource::CommandLine); + + // --offscreen renders, but it is headless too: no monitor, no cap + REQUIRE(Resolve({"--offscreen"}, {}, Settings, Error)); + REQUIRE(Settings.Headless); + Settings.ResolveFrameCap(144u); + REQUIRE(Settings.MaxFps == 0); + REQUIRE_THAT(Settings.Describe(), + Catch::Matchers::ContainsSubstring("frame cap none (default for --offscreen)")); } SECTION("A set cap wins over the monitor; 0 is no cap") { diff --git a/FlingTests/Core/ScreenshotTests.cpp b/FlingTests/Core/ScreenshotTests.cpp new file mode 100644 index 00000000..e4aa32c1 --- /dev/null +++ b/FlingTests/Core/ScreenshotTests.cpp @@ -0,0 +1,127 @@ +#include "FlingPaths.h" +#include "Screenshot.h" +#include "Strings/String.h" + +#include +#include +#include + +using Fling::Screenshot; +using Fling::ScreenshotResult; +using Fling::String; + +TEST_CASE("Screenshot requests wait for the renderer, in order", "[Screenshot]") +{ + // Nothing left from another test + Screenshot::FailPending("test start"); + + const String First = Screenshot::Request("Saved/a.png"); + const String Second = Screenshot::Request("Saved/b.png"); + REQUIRE(First == Fling::FlingPaths::ResolveProjectPath("Saved/a.png")); + + std::vector Pending = Screenshot::TakePending(); + REQUIRE(Pending.size() == 2); + REQUIRE(Pending[0].Path == First); + REQUIRE(Pending[1].Path == Second); + // Taken once + REQUIRE(Screenshot::TakePending().empty()); +} + +TEST_CASE("Screenshot::HasPending is the free check the renderer makes every frame", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + REQUIRE_FALSE(Screenshot::HasPending()); + // With nothing waiting, TakePending returns at once (no lock, nothing allocated) + REQUIRE(Screenshot::TakePending().empty()); + + Screenshot::Request("Saved/pending.png"); + REQUIRE(Screenshot::HasPending()); + REQUIRE(Screenshot::TakePending().size() == 1); + REQUIRE_FALSE(Screenshot::HasPending()); + + Screenshot::Request("Saved/failed.png"); + Screenshot::FailPending("no renderer"); + REQUIRE_FALSE(Screenshot::HasPending()); +} + +TEST_CASE("Screenshot with no path gets a new file under Saved/Screenshots", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + const String A = Screenshot::Request(); + const String B = Screenshot::Request(); + REQUIRE(A != B); + REQUIRE_THAT(A, Catch::Matchers::StartsWith(Fling::FlingPaths::ProjectSavedDir() + "/Screenshots/Screenshot_")); + REQUIRE_THAT(A, Catch::Matchers::EndsWith(".png")); + Screenshot::FailPending("test end"); +} + +TEST_CASE("Screenshot callbacks hear the result", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + std::vector Results; + const auto Keep = [&Results](const ScreenshotResult& t_Result) + { + Results.push_back(t_Result); + }; + + SECTION("Finish passes the renderer's result on") + { + Screenshot::Request("Saved/ok.png", Keep); + std::vector Pending = Screenshot::TakePending(); + REQUIRE(Pending.size() == 1); + ScreenshotResult Done; + Done.Path = Pending[0].Path; + Done.Ok = true; + Done.Width = 320; + Done.Height = 180; + Screenshot::Finish(Pending[0], Done); + + REQUIRE(Results.size() == 1); + REQUIRE(Results[0].Ok); + REQUIRE(Results[0].Width == 320); + } + + SECTION("FailPending fails each waiting request with the reason (no renderer)") + { + Screenshot::Request("Saved/one.png", Keep); + Screenshot::Request("Saved/two.png", Keep); + Screenshot::FailPending("there is no renderer"); + + REQUIRE(Results.size() == 2); + for (const ScreenshotResult& Result : Results) + { + REQUIRE_FALSE(Result.Ok); + REQUIRE(Result.Error == "there is no renderer"); + } + REQUIRE_THAT(Results[1].Path, Catch::Matchers::EndsWith("two.png")); + REQUIRE(Screenshot::TakePending().empty()); + } +} + +TEST_CASE("Screenshot requests from many threads all arrive", "[Screenshot]") +{ + Screenshot::FailPending("test start"); + + constexpr int ThreadCount = 4; + constexpr int PerThread = 50; + std::vector Threads; + for (int t = 0; t < ThreadCount; ++t) + { + Threads.emplace_back( + [t]() + { + for (int i = 0; i < PerThread; ++i) + { + Screenshot::Request("Saved/t" + std::to_string(t) + "_" + std::to_string(i) + ".png"); + } + }); + } + for (std::thread& Each : Threads) + { + Each.join(); + } + REQUIRE(Screenshot::TakePending().size() == ThreadCount * PerThread); + REQUIRE_FALSE(Screenshot::HasPending()); +} diff --git a/FlingTests/Engine/WorldStateDumpTests.cpp b/FlingTests/Engine/WorldStateDumpTests.cpp new file mode 100644 index 00000000..3d302dfd --- /dev/null +++ b/FlingTests/Engine/WorldStateDumpTests.cpp @@ -0,0 +1,190 @@ +#include "Components/Name.hpp" +#include "Components/Transform.h" +#include "Ecs/ModuleRegistration.h" +#include "Ecs/RegisterEngine.h" +#include "Ecs/SystemBase.h" +#include "Game.h" +#include "Json.h" +#include "Logger.h" +#include "Strings/String.h" +#include "World.h" + +#include +#include +#include + +using Fling::String; + +namespace +{ + constexpr uint32 TestSimHz = 60; + + /** A frame a little longer than one fixed step (1/60 s): each Update runs one tick */ + constexpr float OneTickFrame = 0.017f; + + /** + * Simulation state that a level does not save (Transient) but a rollback restores: the + * state dump must show it, as the state hash covers it. + */ + struct DumpCounter + { + static constexpr Fling::ComponentInfo Component{.Name = "Test.DumpCounter", + .Kind = Fling::ComponentKind::Singleton, + .Transient = true, + .Rollback = Fling::RollbackClass::Restore}; + int Ticks = 0; + }; + + /** A setting that is neither saved nor rolled back: the state dump leaves it out. */ + struct DumpScratch + { + static constexpr Fling::ComponentInfo Component{.Name = "Test.DumpScratch", + .Kind = Fling::ComponentKind::Singleton, + .Transient = true, + .Rollback = Fling::RollbackClass::Keep}; + int Value = 7; + }; + + /** Counts the ticks and moves every transform one unit along x each tick. */ + class DumpTickSystem final + : public Fling::System, Fling::Write>> + { + public: + static constexpr Fling::SystemInfo Info{.Name = "Test.DumpTicks", .In = Fling::Order::Input}; + + void OnCreate(Setup& setup) const { setup.AddSingleton(); } + + void OnDestroy(Setup& setup) const { setup.RemoveSingleton(); } + + void FixedUpdate(Context& ctx) const + { + ++ctx.Singleton().Ticks; + for (auto [Entity, Trans] : ctx.Query()) + { + Trans.Position.x += 1.0f; + } + } + }; + + class DumpTestGame : public Fling::Game + { + public: + void Init(Fling::EntityStorage&) override {} + void OnStartGame(Fling::EntityStorage&) override {} + void OnStopGame(Fling::EntityStorage&) override {} + void Shutdown(Fling::EntityStorage&) override {} + + void Register(Fling::ModuleRegistration& t_Modules) override + { + Fling::RegisterEngine(t_Modules); + t_Modules.Component([](Fling::TypeBuilder& t_Type) + { t_Type.Field("ticks", &DumpCounter::Ticks); }); + t_Modules.Component([](Fling::TypeBuilder& t_Type) + { t_Type.Field("value", &DumpScratch::Value); }); + t_Modules.System(); + } + }; + + void InitTestLogger() + { + Fling::Logger::Get().Init(); + Fling::Logger::GetCurrentConsole()->set_level(spdlog::level::off); + Fling::Logger::GetCurrentLogFile()->set_level(spdlog::level::off); + } + + /** Make a world with two named entities, start play, and run t_Ticks ticks. */ + std::vector RunAndDump(const std::vector& t_DumpTicks, const int t_Ticks) + { + using namespace Fling; + World TestWorld(std::make_shared()); + TestWorld.SetExecMode(ExecMode::Direct); + TestWorld.SetSystemRunnerConfig(SystemRunnerConfig{.SimHz = TestSimHz}); + TestWorld.SetStateHashEnabled(true); + TestWorld.SetStateDumpTicks(t_DumpTicks); + TestWorld.Init(); + + EntityStorage& Reg = TestWorld.GetStorage(); + for (const char* EntityName : {"Ball", "Wall"}) + { + const Entity Each = Reg.Create(); + Reg.Add(Each).Name = Name(EntityName); + Reg.Add(Each); + } + Reg.SetSingleton(); + + TestWorld.RequestGameStart(); + std::vector Dumps; + for (int i = 0; i < t_Ticks; ++i) + { + TestWorld.Update(OneTickFrame); + for (World::StateDump& Dump : TestWorld.TakeStateDumps()) + { + Dumps.push_back(std::move(Dump)); + } + } + TestWorld.Shutdown(); + return Dumps; + } +} // namespace + +TEST_CASE("World state dump at chosen ticks", "[world][state-dump]") +{ + using namespace Fling; + InitTestLogger(); + + const std::vector Dumps = RunAndDump({2, 4}, 5); + REQUIRE(Dumps.size() == 2); + REQUIRE(Dumps[0].Tick == 2); + REQUIRE(Dumps[1].Tick == 4); + + const Json& Doc = Dumps[1].Doc; + REQUIRE(Doc.GetUInt64("tick") == 4); + REQUIRE(Doc.GetUInt64("simHz") == TestSimHz); + REQUIRE(Doc.GetUInt64("entityCount") == 2); + // On: the hash of the tick, as 16 hex digits + REQUIRE(Doc.GetString("stateHash").size() == 16); + REQUIRE(Doc.GetString("stateHash") != "0000000000000000"); + + SECTION("Entities have their name, handle, id and components with every field") + { + const Json Entities = Doc.Get("entities"); + REQUIRE(Entities.IsArray()); + REQUIRE(Entities.Size() == 2); + std::vector Names; + for (std::size_t i = 0; i < Entities.Size(); ++i) + { + const Json Entity = Entities.At(i); + Names.push_back(Entity.GetString("name")); + REQUIRE_FALSE(Entity.GetString("entity").empty()); + REQUIRE(Entity.GetUInt64("guid") != 0); + // Four ticks moved it four units along x + REQUIRE(Entity.Get("Transform").GetVec3("position").x == Catch::Approx(4.0f)); + } + // In handle order, which is the order they were made in + REQUIRE(Names == std::vector{"Ball", "Wall"}); + } + + SECTION("Singletons: rollback state is in (even Transient), Keep state is out") + { + const Json Singletons = Doc.Get("singletons"); + REQUIRE(Singletons.Contains("Test.DumpCounter")); + REQUIRE(Singletons.Get("Test.DumpCounter").GetInt("ticks") == 4); + REQUIRE_FALSE(Singletons.Contains("Test.DumpScratch")); + } + + SECTION("The same run writes the same document") + { + const std::vector Again = RunAndDump({2, 4}, 5); + REQUIRE(Again.size() == 2); + REQUIRE(Again[1].Doc.Dump(2) == Doc.Dump(2)); + // A different tick has a different state, so a different document + REQUIRE(Dumps[0].Doc.Dump(2) != Doc.Dump(2)); + } +} + +TEST_CASE("World state dump: a tick that does not run makes no dump", "[world][state-dump]") +{ + InitTestLogger(); + REQUIRE(RunAndDump({50}, 3).empty()); + REQUIRE(RunAndDump({}, 3).empty()); +} diff --git a/Plans/improve-ai-iteration.md b/Plans/improve-ai-iteration.md index 831eae92..61154156 100644 --- a/Plans/improve-ai-iteration.md +++ b/Plans/improve-ai-iteration.md @@ -268,10 +268,21 @@ Done. The rules that it establishes are in `improve-time.md`. The tick clocks (`FixedTickClock`) come with T1 and T2. - JSON logs go to the existing `Logs/` folder (`fling_log.jsonl`), not to `Saved/Logs/`. Move them when `project-model.md` adds `Saved/`. -- `--dump-state` is not done. It needs the state hash from phase C. +- `--dump-state ` (with `--dump-state-ticks`) is done: the state at chosen + ticks as JSON, written on the game thread after the tick, with the tick's state + hash. See [`Skills/testing.md`](../Skills/testing.md#seeing-the-game-without-a-window). - CTest runs the Sandbox headless and runs `CrashProbe` to check that each kind of crash exits with code 2, with a stack trace and no dialog. +### Phase F status + +Offscreen capture is done, before phases C to E: `--offscreen` renders into images +that the renderer owns (no window, no surface, no GLFW), with the headless timing of +`--null-render`, and `--screenshot` saves PNG files at chosen ticks, offscreen or +windowed. See [`Skills/testing.md`](../Skills/testing.md#seeing-the-game-without-a-window). +The `screenshot` command of the command layer (section 5) can call the same +`VulkanApp::RequestCapture`. The MCP wrapper and hot reload are not done. + ## Open questions - Where does `TickInput` live: Core (with `Input`) or Engine (with diff --git a/Sandbox/CMakeLists.txt b/Sandbox/CMakeLists.txt index 3cfbe9cc..a6450d1c 100644 --- a/Sandbox/CMakeLists.txt +++ b/Sandbox/CMakeLists.txt @@ -333,6 +333,50 @@ if( FLING_BUILD_TESTS ) PASS_REGULAR_EXPRESSION "Run settings: tick rate 30 Hz \\(default\\), exec threaded \\(default\\), frame cap none \\(default for --null-render\\), vsync on \\(default\\), interpolation on \\(default\\).*Fling exit: code=0 ticks=10" ) + # --dump-state: the simulation state as JSON at chosen ticks, with no window and no GPU. + # The same bytes in --exec direct and threaded (Sandbox/Tests/CheckCaptures.cmake). + add_test( NAME "Sandbox: headless state dump" + COMMAND ${CMAKE_COMMAND} + -DSANDBOX=$ + -DROOT=${FLING_ROOT_DIR} + -DOUT=${CMAKE_BINARY_DIR}/TestOutput/StateDump + -DKIND=state + -P "${FLING_ROOT_DIR}/Sandbox/Tests/CheckCaptures.cmake" + ) + set_tests_properties( "Sandbox: headless state dump" PROPERTIES + PASS_REGULAR_EXPRESSION "Captures are the same in --exec direct and threaded" + TIMEOUT 120 + ) + + # A capture that was asked for and not made fails the run, so a script never reads an old file + add_test( NAME "Sandbox: state dump of a tick that does not run" + COMMAND ${PROJECT_NAME} --null-render --unattended --frames 10 --seed 1 + --dump-state ${CMAKE_BINARY_DIR}/TestOutput/NoState.json --dump-state-ticks 99 + WORKING_DIRECTORY "${FLING_ROOT_DIR}" + ) + set_tests_properties( "Sandbox: state dump of a tick that does not run" PROPERTIES + PASS_REGULAR_EXPRESSION "--dump-state: tick 99 did not run.*Fling exit: code=1" + ) + + # --offscreen --screenshot renders with the GPU into images and saves PNG files, with no + # window. It needs a Vulkan driver (llvmpipe is enough, no display), which CI machines may + # not have, so it is off unless FLING_TEST_OFFSCREEN is on. + option( FLING_TEST_OFFSCREEN "Add the CTest that renders offscreen (needs a Vulkan driver, no display)" OFF ) + if( FLING_TEST_OFFSCREEN ) + add_test( NAME "Sandbox: offscreen screenshots" + COMMAND ${CMAKE_COMMAND} + -DSANDBOX=$ + -DROOT=${FLING_ROOT_DIR} + -DOUT=${CMAKE_BINARY_DIR}/TestOutput/Screenshots + -DKIND=screenshot + -P "${FLING_ROOT_DIR}/Sandbox/Tests/CheckCaptures.cmake" + ) + set_tests_properties( "Sandbox: offscreen screenshots" PROPERTIES + PASS_REGULAR_EXPRESSION "Captures are the same in --exec direct and threaded" + TIMEOUT 300 + ) + endif() + # The linked binary must not import libvulkan / vulkan-1.dll. The loader is # opened at runtime by Fling::DynamicLibrary. add_test(NAME "Sandbox: no Vulkan import" diff --git a/Sandbox/Tests/CheckCaptures.cmake b/Sandbox/Tests/CheckCaptures.cmake new file mode 100644 index 00000000..33c13c10 --- /dev/null +++ b/Sandbox/Tests/CheckCaptures.cmake @@ -0,0 +1,75 @@ +# Runs the Sandbox headless twice, in --exec direct and --exec threaded, each writing captures +# at two ticks, then fails unless every file is there and the two runs wrote the same bytes: +# a capture shows the simulation, which does not depend on threads (Docs/threading-model.md +# section 9). +# +# KIND=state --null-render with --dump-state (JSON). Needs no GPU. +# KIND=screenshot --offscreen with --screenshot (PNG). Needs a Vulkan driver (a software one, +# such as llvmpipe, is enough) but no display. +# +# -DSANDBOX= -DROOT= -DOUT= -DKIND=state|screenshot + +foreach( _var SANDBOX ROOT OUT KIND ) + if( NOT DEFINED ${_var} ) + message( FATAL_ERROR "CheckCaptures.cmake needs -D${_var}=..." ) + endif() +endforeach() + +set( _ticks 10 30 ) +if( KIND STREQUAL "state" ) + set( _render --null-render ) + set( _flags --dump-state "{tick}.json" --dump-state-ticks 10,30 ) + set( _ext json ) +elseif( KIND STREQUAL "screenshot" ) + set( _render --offscreen --resolution 320x180 ) + set( _flags --screenshot "{tick}.png" --screenshot-ticks 10,30 ) + set( _ext png ) +else() + message( FATAL_ERROR "KIND must be state or screenshot, not ${KIND}" ) +endif() + +file( REMOVE_RECURSE "${OUT}" ) +foreach( _exec direct threaded ) + set( _dir "${OUT}/${_exec}" ) + file( MAKE_DIRECTORY "${_dir}" ) + # The file names are relative to the project, so give the folder as an absolute path + string( REPLACE "{tick}" "${_dir}/{tick}" _run_flags "${_flags}" ) + execute_process( + COMMAND "${SANDBOX}" ${_render} --unattended --frames 30 --seed 1 --exec ${_exec} ${_run_flags} + WORKING_DIRECTORY "${ROOT}" + RESULT_VARIABLE _code + OUTPUT_VARIABLE _out + ERROR_VARIABLE _out + ) + if( NOT _code EQUAL 0 ) + message( FATAL_ERROR "--exec ${_exec} exited with ${_code}:\n${_out}" ) + endif() + foreach( _tick IN LISTS _ticks ) + if( NOT EXISTS "${_dir}/${_tick}.${_ext}" ) + message( FATAL_ERROR "--exec ${_exec} wrote no ${_dir}/${_tick}.${_ext}:\n${_out}" ) + endif() + endforeach() +endforeach() + +foreach( _tick IN LISTS _ticks ) + file( SHA256 "${OUT}/direct/${_tick}.${_ext}" _direct ) + file( SHA256 "${OUT}/threaded/${_tick}.${_ext}" _threaded ) + if( NOT _direct STREQUAL _threaded ) + message( FATAL_ERROR "The ${KIND} of tick ${_tick} differs between --exec direct and threaded" ) + endif() +endforeach() + +if( KIND STREQUAL "state" ) + file( READ "${OUT}/direct/30.json" _doc ) + if( NOT _doc MATCHES "\"tick\": 30" OR NOT _doc MATCHES "\"Transform\"" ) + message( FATAL_ERROR "The state of tick 30 has no tick or no Transform:\n${_doc}" ) + endif() +else() + # A PNG file starts with these 8 bytes + file( READ "${OUT}/direct/30.png" _sig LIMIT 8 HEX ) + if( NOT _sig STREQUAL "89504e470d0a1a0a" ) + message( FATAL_ERROR "30.png is not a PNG file (it starts with ${_sig})" ) + endif() +endif() + +message( STATUS "Captures are the same in --exec direct and threaded" ) diff --git a/Skills/testing.md b/Skills/testing.md index 7a8b8887..8fba171c 100644 --- a/Skills/testing.md +++ b/Skills/testing.md @@ -159,6 +159,119 @@ Rules for code that can run under `--null-render`: headless, check the JSON exit summary, and check that a bad argument exits with code 3. +## Seeing the game without a window + +An agent (or a script) can look at a run in two ways, and neither opens a window. +Read the state first: it is cheaper than an image and you can check it exactly. Use a +screenshot only when the question is about what the frame looks like. + +### The state as text: `--dump-state` + +```bash +./build/Sandbox/bin/Sandbox --null-render --unattended --frames 60 --seed 1 \ + --dump-state Saved/state.json --dump-state-ticks 10,60 +# writes Saved/state_tick10.json and Saved/state_tick60.json +``` + +| Flag | What it does | +| --- | --- | +| `--dump-state F` | Write the simulation state as JSON to `F` (relative to the project folder, or absolute; missing folders are made). Works with `--null-render`: no GPU | +| `--dump-state-ticks L` | The ticks to write, a comma list such as `10,60`. Without it: the last tick of the run (`--frames` is then required) | + +Each file is written on the game thread right after its tick, so it is the state the +tick left (`World::SaveStateToJson`). It holds: + +- `tick`, `simHz`, `entityCount` and `stateHash` (the same hash as `--dump-ticks`). +- `entities`, in handle order: `entity` (`index:generation`), `name` when it has a + `NameComponent`, `guid`, then one object for each component, with every reflected field. +- `singletons`: one object for each singleton. + +The types are the ones the state hash covers (rollback state, Transient ones too) and +the ones a level saves. A type that is neither (a `RollbackClass::Keep` setting, a +render cache) is left out. The same seed, input and flags write the same bytes in +every exec mode, so two dumps can be diffed. It is not a level file: `--level` cannot +load it. + +### The rendered frame: `--offscreen` and `--screenshot` + +```bash +./build/Sandbox/bin/Sandbox --offscreen --unattended --frames 30 --seed 1 \ + --resolution 640x360 --screenshot Saved/shot.png --screenshot-ticks 1,30 +# writes Saved/shot_tick1.png and Saved/shot_tick30.png +``` + +| Flag | What it does | +| --- | --- | +| `--offscreen` | Render with Vulkan into images that the renderer owns. No window, no surface, no window system extension, and no GLFW: it runs on a machine with no display, and opens nothing on a machine that has one. The timing is the same as `--null-render` (a virtual clock, no frame cap), so the ticks are the same as a `--null-render` run. There is no developer UI (ImGui needs a window). Cannot be used with `--null-render` | +| `--resolution WxH` | The size of the frames (`--offscreen`) or of the window. Overrides `[Engine] WindowWidth` and `WindowHeight`. A window is still made smaller to fit the screen's work area; offscreen frames are always this size | +| `--screenshot F` | Save the frame as a PNG file `F`. Works with `--offscreen` and with a window (then the editor UI is in the image too). Not with `--null-render` | +| `--screenshot-ticks L` | Save the first frame that shows each of these ticks. Without it: the last tick of the run (`--frames` is then required). The log line `Saved the frame of tick N (it shows tick M, WxH) to F` says which tick the frame shows | + +File names: with one tick the path is used as it is. With more than one, `_tick` goes +before the extension. `{tick}` in the path puts the tick where you want it +(`--screenshot frames/{tick}.png`). `CaptureFilePath` in `LaunchOptions.h` has the rule. + +A capture that was asked for and not made (the tick never ran, the file cannot be +written) logs an error and the run exits with code 1, so a script never reads an +old file. + +`--offscreen` needs a Vulkan driver, but a software one is enough: Mesa's lavapipe +(`llvmpipe`, package `mesa-vulkan-drivers` on Ubuntu) renders the Sandbox at 640x360 +in about 5 s for 30 ticks. The same flags give the same image in every exec mode. +`FLING_TEST_OFFSCREEN=ON` adds the CTest `Sandbox: offscreen screenshots`; it is off by +default because CI machines may have no Vulkan driver. `Sandbox: headless state dump` +always runs. + +To view a PNG, an agent reads the file (most agent tools show images). Choose a small +`--resolution` to keep the image cheap. + +### Screenshots from the editor or from C++ + +The editor's GPU Options window (menu Windows; open in `--play` too) has a **Take +screenshot** button. It saves the next frame as it is shown, editor UI included, to +`Saved/Screenshots/Screenshot__.png`, and shows the path under the button. + +Code anywhere in the engine can do the same with `Fling::Screenshot` (`Screenshot.h`, in +Core, so a module needs no Graphics header): + +```cpp +#include "Screenshot.h" + +// Any thread. Empty path: a new file under Saved/Screenshots +Fling::Screenshot::Request("Saved/door_open.png", + [](const Fling::ScreenshotResult& t_Result) + { + // On the main thread, after the file is written (or not) + F_LOG_TRACE("{}: {}", t_Result.Path, t_Result.Ok ? "saved" : t_Result.Error); + }); +``` + +The renderer copies its next frame for every waiting request, and a writer thread saves +the PNG files, then logs `Screenshot saved (WxH) to ` or the error. The callback is optional. Under +`--null-render` there is no renderer, so a request fails at the next frame with that +reason; a request still waiting when the run ends fails too. `--screenshot` uses this API. +Use it for tools, tests and debugging, not to feed results back into the simulation: the +callback arrives on the main thread, out of step with the ticks. + +Cost: nothing when nobody asks, and no stall when somebody does (`FrameCapturer` in +`Graphics/src/FrameCapture.h`): + +- A frame with no request does two atomic loads (`Screenshot::HasPending()`, and "any + results to deliver"). No lock, no allocation. The writer thread and the staging buffers + are made on the first capture only. +- The frame of a capture records one more barrier and a `vkCmdCopyImageToBuffer` into its + own command buffer, after the render pass. That is GPU work in the frame's submit; the + CPU does not wait for it, and the swap chain is never made again. +- After the frame's fence, the staging buffer goes to the `Screenshot Writer` thread, + which converts the pixels, encodes the PNG once and writes it to each requested path. + The main thread copies nothing. At 1920x1080 on llvmpipe the encode takes about a second + on the writer while the frames keep their normal time. +- The callbacks run on the main thread at a later frame. A run's end waits for the writes + (`VulkanApp::FinishScreenshots`), so `--screenshot` checks every file before it exits. +- The swap chain images are made with `VK_IMAGE_USAGE_TRANSFER_SRC_BIT` once, when the + surface allows it (always offscreen). It costs no CPU time, and desktop drivers keep + their framebuffer compression with it. + ## Unattended crash tests `FlingTests/CMakeLists.txt` adds `Unattended crash: ` tests. Each runs