From 5ae9fb16c7f02f2a695d69d2382c2081854d9264 Mon Sep 17 00:00:00 2001 From: Simon Tippe Date: Tue, 13 Oct 2026 21:50:06 +0200 Subject: [PATCH 001/174] New capture tool --- CMakeLists.txt | 9 + data/editor/icons/pause.png | Bin 0 -> 1238 bytes data/editor/icons/pause.svg | 1 + data/editor/icons/pause_light.png | Bin 0 -> 1022 bytes data/shader/atmosphere/common.hsh | 5 +- data/shader/atmosphere/multipleScattering.csh | 48 +- data/shader/clouds/clouds.hsh | 11 +- data/shader/clouds/integrate.hsh | 31 +- data/shader/volumetric/volumetric.csh | 14 +- src/capture/App.cpp | 1882 +++++++++++++++++ src/capture/App.h | 238 +++ src/capture/CMakeLists.txt | 44 + src/capture/CaptureRenderer.cpp | 245 +++ src/capture/CaptureRenderer.h | 82 + src/capture/Checks.cpp | 433 ++++ src/capture/Checks.h | 87 + src/capture/Common.cpp | 148 ++ src/capture/Common.h | 46 + src/capture/Image.cpp | 201 ++ src/capture/Image.h | 33 + src/capture/Job.cpp | 615 ++++++ src/capture/Job.h | 220 ++ src/capture/Overlay.cpp | 91 + src/capture/Overlay.h | 43 + src/capture/README.md | 425 ++++ src/capture/SceneEditor.cpp | 451 ++++ src/capture/SceneEditor.h | 19 + src/capture/SceneTools.cpp | 798 +++++++ src/capture/SceneTools.h | 87 + src/editor/App.cpp | 30 +- src/editor/App.h | 2 + src/editor/Icons.cpp | 2 + src/editor/Icons.h | 1 + src/editor/ui/panels/SceneHierarchyPanel.h | 3 + src/editor/ui/windows/SceneWindow.cpp | 24 +- src/editor/ui/windows/SceneWindow.h | 2 + src/engine/Engine.cpp | 15 +- src/engine/Engine.h | 4 +- src/engine/EngineInstance.cpp | 3 +- src/engine/EngineInstance.h | 11 +- src/engine/Font.cpp | 9 +- src/engine/Font.h | 5 +- src/engine/Main.cpp | 19 +- src/engine/common/Image.h | 26 +- src/engine/graphics/Common.h | 15 +- src/engine/graphics/DescriptorPool.cpp | 10 +- src/engine/graphics/DescriptorSetLayout.cpp | 2 + src/engine/graphics/DescriptorSetLayout.h | 3 +- src/engine/graphics/GraphicsDevice.cpp | 39 +- src/engine/graphics/GraphicsDevice.h | 22 +- src/engine/graphics/Instance.cpp | 44 +- src/engine/graphics/Instance.h | 4 +- src/engine/graphics/Pipeline.cpp | 9 +- src/engine/input/ControllerMap.cpp | 81 + src/engine/input/ControllerMap.h | 45 + src/engine/input/PlayerInput.cpp | 23 + src/engine/input/PlayerInput.h | 34 + src/engine/lighting/LightingSerializer.cpp | 7 + src/engine/lighting/VolumetricClouds.h | 3 +- src/engine/loader/ModelImporter.cpp | 2 - src/engine/physics/PhysicsWorld.cpp | 8 +- src/engine/physics/Player.cpp | 11 + src/engine/physics/Player.h | 3 + src/engine/renderer/AtmosphereRenderer.cpp | 53 +- src/engine/renderer/AtmosphereRenderer.h | 7 +- src/engine/renderer/FSR2Renderer.cpp | 3 +- src/engine/renderer/MainRenderer.cpp | 9 +- src/engine/renderer/PostProcessRenderer.cpp | 3 +- src/engine/renderer/TextRenderer.cpp | 14 +- .../renderer/VolumetricCloudRenderer.cpp | 3 +- src/engine/renderer/target/RenderTarget.cpp | 6 + src/engine/renderer/target/RenderTarget.h | 5 + src/engine/scene/Scene.cpp | 142 +- src/engine/scene/Scene.h | 31 +- .../scene/components/AudioComponent.cpp | 17 +- .../scene/components/AudioVolumeComponent.cpp | 2 +- .../scene/components/LuaScriptComponent.cpp | 4 + src/engine/scripting/LuaScriptBindings.cpp | 1 + .../scripting/bindings/InputBindings.cpp | 38 + src/engine/scripting/bindings/InputBindings.h | 2 + .../scripting/bindings/ResourceBindings.cpp | 21 + .../scripting/bindings/SceneBindings.cpp | 246 ++- .../scripting/bindings/UtilityBindings.cpp | 12 + src/engine/volume/Ray.cpp | 27 + src/engine/volume/Ray.h | 7 + src/tests/App.cpp | 2 +- 86 files changed, 7237 insertions(+), 246 deletions(-) create mode 100644 data/editor/icons/pause.png create mode 100644 data/editor/icons/pause.svg create mode 100644 data/editor/icons/pause_light.png create mode 100644 src/capture/App.cpp create mode 100644 src/capture/App.h create mode 100644 src/capture/CMakeLists.txt create mode 100644 src/capture/CaptureRenderer.cpp create mode 100644 src/capture/CaptureRenderer.h create mode 100644 src/capture/Checks.cpp create mode 100644 src/capture/Checks.h create mode 100644 src/capture/Common.cpp create mode 100644 src/capture/Common.h create mode 100644 src/capture/Image.cpp create mode 100644 src/capture/Image.h create mode 100644 src/capture/Job.cpp create mode 100644 src/capture/Job.h create mode 100644 src/capture/Overlay.cpp create mode 100644 src/capture/Overlay.h create mode 100644 src/capture/README.md create mode 100644 src/capture/SceneEditor.cpp create mode 100644 src/capture/SceneEditor.h create mode 100644 src/capture/SceneTools.cpp create mode 100644 src/capture/SceneTools.h create mode 100644 src/engine/input/ControllerMap.cpp create mode 100644 src/engine/input/ControllerMap.h create mode 100644 src/engine/input/PlayerInput.cpp create mode 100644 src/engine/input/PlayerInput.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a25207ea..3daa5abf3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,6 +27,7 @@ option(ATLAS_EXPORT_MAIN "Add main file in root of directory tree. Add ${ATLAS_E option(ATLAS_NO_APP "Disables the engines main function" OFF) option(ATLAS_DEMO "Build demo executable" OFF) option(ATLAS_EDITOR "Build editor executable" ON) +option(ATLAS_CAPTURE "Build the scene capture and inspection tool executable" OFF) option(ATLAS_IMGUI "Activate ImGui integration" OFF) option(ATLAS_ASSIMP "Activate Assimp integration" ON) option(ATLAS_HEADLESS "Activate support for running the engine in headless mode" OFF) @@ -72,12 +73,16 @@ endif() if (ATLAS_DEMO) set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE) endif() +if (ATLAS_CAPTURE) +set(ATLAS_EXPORT_MAIN ON CACHE BOOL "Override engine settings" FORCE) +endif() # Set dependencies location ####################################################################### set (ATLAS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/engine) set (DEMO_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/demo) set (TESTS_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/tests) set (EDITOR_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/editor) +set (CAPTURE_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/capture) set (IMGUI_EXTENSION_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/libs/ImguiExtension) # Add dependencies ################################################################################ @@ -121,6 +126,10 @@ if (ATLAS_EDITOR) add_subdirectory(${EDITOR_LOCATION}) endif() +if (ATLAS_CAPTURE) + add_subdirectory(${CAPTURE_LOCATION}) +endif() + if (ATLAS_TESTS) add_subdirectory(${TESTS_LOCATION}) endif() diff --git a/data/editor/icons/pause.png b/data/editor/icons/pause.png new file mode 100644 index 0000000000000000000000000000000000000000..01b8e529394db17f4c46861cbd51a5f77e7888d8 GIT binary patch literal 1238 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|GzJEixt=bLAr-gY-Z{v7$Uwm5 z;*=*smlk?^dFmZ(aAB0Wu^@Hc()zQBGJ6;I@BOZ*X{_wQFoA`^lNJOggWCiK1x|)Z z1c-wC&o@QyXxu1i$+u#>u>5+f>io?KmyK&Ka|3-vAMnAL;o7>&93$C=E?;p5h6_*G zJ=hig{sV>XC>RX^@(d5@-IrI~@K}(=_&j{Nw5B=d#Wzp$Py$z \ No newline at end of file diff --git a/data/editor/icons/pause_light.png b/data/editor/icons/pause_light.png new file mode 100644 index 0000000000000000000000000000000000000000..61fdadb4487f0ea82394d88a14749d275f93f94b GIT binary patch literal 1022 zcmeAS@N?(olHy`uVBq!ia0y~yU<5K5893O0R7}x|GzJFdqn<8~Ar-gY-r2}|*nr2? zv3H5!o`r6oJfseKHt;Eu!-nyv_91RQ#3``0jngc{L0colT*>fL|Gwt_X#=anFc{Bsdg46sH6M55iqxe%`^syG{J2wsb5;x%f7IXndLx$wb$ zrVaP+|NXWEnrt3$>b?VFXH;G)SW$V-KWXTTz*_>GYYVx#vF2)w>SLsw9KF4-7hU VZs#`TJdy$F^>p=fS?83{1OR&FcuxQT literal 0 HcmV?d00001 diff --git a/data/shader/atmosphere/common.hsh b/data/shader/atmosphere/common.hsh index 424bbcffa..6da4fafb4 100644 --- a/data/shader/atmosphere/common.hsh +++ b/data/shader/atmosphere/common.hsh @@ -222,6 +222,7 @@ void GetRadiusMuFromMultipleScatteringTextureUv(vec2 uv, AtmosphereParameters at } +// Multiple scattering for a unit sun radiance vec3 GetMultipleScattering(sampler2D multipleScatteringTexture, float radius, float muS, AtmosphereParameters atmosphere) { @@ -263,7 +264,7 @@ vec3 GetGroundRadiance(sampler2D transmittanceTexture, sampler2D multipleScatter vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, groundRadius, sunZenithCosAngle, atmosphere); vec3 directIrradiance = sunRadiance * transmittanceToSun * saturate(sunZenithCosAngle); - vec3 indirectIrradiance = GetMultipleScattering(multipleScatteringTexture, groundRadius, + vec3 indirectIrradiance = sunRadiance * GetMultipleScattering(multipleScatteringTexture, groundRadius, sunZenithCosAngle, atmosphere) * PI * atmosphereGroundIndirectFactor; return atmosphere.groundAlbedo * (directIrradiance + indirectIrradiance) / PI; @@ -365,7 +366,7 @@ vec3 IntegrateAtmosphereScattering(sampler2D transmittanceTexture, sampler2D mul vec3 transmittanceToSun = GetTransmittanceToSun(transmittanceTexture, sampleRadius, muS, atmosphere); vec3 phaseScattering = GetAtmospherePhaseScattering(densities, cosTheta, atmosphere); - vec3 multipleScattering = GetMultipleScattering(multipleScatteringTexture, sampleRadius, + vec3 multipleScattering = sunRadiance * GetMultipleScattering(multipleScatteringTexture, sampleRadius, muS, atmosphere); float shadowVisibility = max3(transmittanceToSun); float multipleScatteringVisibility = shadowVisibility * diff --git a/data/shader/atmosphere/multipleScattering.csh b/data/shader/atmosphere/multipleScattering.csh index 60430b156..e5d2c7e59 100644 --- a/data/shader/atmosphere/multipleScattering.csh +++ b/data/shader/atmosphere/multipleScattering.csh @@ -1,12 +1,12 @@ #include -layout (local_size_x = 8, local_size_y = 8) in; +// One work group per texel, each invocation integrates one direction +layout (local_size_x = 64) in; layout(set = 3, binding = 0, rgba16f) writeonly uniform image2D multipleScatteringImage; layout(set = 3, binding = 1) uniform sampler2D transmittanceTexture; layout(set = 3, binding = 2, std140) uniform UniformBuffer { - vec4 sunRadiance; vec4 rayleighScatteringCoeff; vec4 groundAlbedo; float mieScatteringCoeff; @@ -20,16 +20,17 @@ layout(set = 3, binding = 2, std140) uniform UniformBuffer { const int multipleScatteringDirectionSampleCount = 64; const int multipleScatteringRaySampleCount = 20; +shared vec3 sharedLuminance[multipleScatteringDirectionSampleCount]; +shared vec3 sharedMultiScatteringFactor[multipleScatteringDirectionSampleCount]; + AtmosphereParameters GetAtmosphereParameters(); vec3 GetSphericalFibonacciDirection(int index, int count); void main() { - ivec2 pixel = ivec2(gl_GlobalInvocationID.xy); + ivec2 pixel = ivec2(gl_WorkGroupID.xy); ivec2 resolution = imageSize(multipleScatteringImage); - - if (pixel.x >= resolution.x || pixel.y >= resolution.y) - return; + int index = int(gl_LocalInvocationIndex); vec2 uv = (vec2(pixel) + 0.5) / vec2(resolution); @@ -40,25 +41,36 @@ void main() { vec3 samplePosition = vec3(0.0, 0.0, radius); vec3 sunDirection = vec3(sqrt(max(1.0 - muS * muS, 0.0)), 0.0, muS); + vec3 rayDirection = GetSphericalFibonacciDirection(index, multipleScatteringDirectionSampleCount); - vec3 inScatteredLuminance = vec3(0.0); - vec3 multiScatteringFactor = vec3(0.0); + vec3 rayLuminance; + vec3 rayMultiScatteringFactor; + // Computed for a unit sun radiance, the sun is applied where the table is sampled + IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection, + vec3(0.0), atmosphere, vec3(1.0), multipleScatteringRaySampleCount, 1.4, + rayLuminance, rayMultiScatteringFactor); - float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount); + sharedLuminance[index] = rayLuminance; + sharedMultiScatteringFactor[index] = rayMultiScatteringFactor; - for (int i = 0; i < multipleScatteringDirectionSampleCount; i++) { - vec3 rayDirection = GetSphericalFibonacciDirection(i, multipleScatteringDirectionSampleCount); + barrier(); - vec3 rayLuminance; - vec3 rayMultiScatteringFactor; - IntegrateAtmosphereMultiScattering(transmittanceTexture, samplePosition, rayDirection, sunDirection, - vec3(0.0), atmosphere, uniforms.sunRadiance.rgb, multipleScatteringRaySampleCount, 1.4, - rayLuminance, rayMultiScatteringFactor); + for (int stride = multipleScatteringDirectionSampleCount / 2; stride > 0; stride /= 2) { + if (index < stride) { + sharedLuminance[index] += sharedLuminance[index + stride]; + sharedMultiScatteringFactor[index] += sharedMultiScatteringFactor[index + stride]; + } - inScatteredLuminance += rayLuminance * sampleWeight * atmosphereIsotropicPhase; - multiScatteringFactor += rayMultiScatteringFactor * sampleWeight; + barrier(); } + if (index > 0) + return; + + float sampleWeight = 4.0 * PI / float(multipleScatteringDirectionSampleCount); + vec3 inScatteredLuminance = sharedLuminance[0] * sampleWeight * atmosphereIsotropicPhase; + vec3 multiScatteringFactor = sharedMultiScatteringFactor[0] * sampleWeight; + vec3 clampedFactor = min(multiScatteringFactor, vec3(0.999)); vec3 multipleScattering = inScatteredLuminance / max(vec3(1.0) - clampedFactor, vec3(0.01)); diff --git a/data/shader/clouds/clouds.hsh b/data/shader/clouds/clouds.hsh index a9800249c..409c466bb 100644 --- a/data/shader/clouds/clouds.hsh +++ b/data/shader/clouds/clouds.hsh @@ -58,7 +58,7 @@ const float cloudTypeVariation = 0.55; const float bottomTypeVariation = 0.12; const float windSkew = 0.12; -const float multiScatteringIntensity = 0.28; +const float multiScatteringIntensity = 0.45; const float multiScatteringAttenuation = 0.65; const float multiScatteringContribution = 0.50; const float multiScatteringEccentricityAttenuation = 0.60; @@ -68,6 +68,15 @@ const float edgeAlbedo = 0.68; const float edgeAlbedoCurve = 2.0; const float ambientAlbedoMix = 0.35; +// Cloud tops see the bright sky, bottoms are occluded by the cloud above and mostly see the ground +const float ambientTopStrength = 0.6; +const float ambientBottomStrength = 0.18; +const float ambientGroundMix = 0.5; + +// Powder effect: surfaces which only received light close to the surface scatter less light back. +// It darkens the creases of billowing clouds when the sun is behind the viewer. +const float powderStrength = 0.65; + vec3 cloudPlanetCenter = cloudUniforms.planetCenter.xyz; #define MULTISCATTER_OCTAVES 4 diff --git a/data/shader/clouds/integrate.hsh b/data/shader/clouds/integrate.hsh index 12517fd0b..46a04adbe 100644 --- a/data/shader/clouds/integrate.hsh +++ b/data/shader/clouds/integrate.hsh @@ -136,11 +136,28 @@ vec3 ComputeAmbientColor(vec3 pos, float extinction) { float distFromCenter = distance(pos, cloudPlanetCenter); vec3 isotropicLightTop = textureLod(diffuseProbe, vec3(0.0, 1.0, 0.0), 0.0).rgb; + vec3 isotropicLightBottom = textureLod(diffuseProbe, vec3(0.0, -1.0, 0.0), 0.0).rgb; - float heightFraction = (distFromCenter - cloudUniforms.innerRadius) / - (cloudUniforms.outerRadius - cloudUniforms.innerRadius); - float ambientContribution = saturate(0.5); - return 0.5 * isotropicLightTop * ambientContribution; + float heightFraction = saturate((distFromCenter - cloudUniforms.innerRadius) / + (cloudUniforms.outerRadius - cloudUniforms.innerRadius)); + + // The sky lights the tops, the bases only get light reflected from the ground below + vec3 topAmbient = ambientTopStrength * isotropicLightTop; + vec3 bottomAmbient = ambientBottomStrength * mix(isotropicLightTop, isotropicLightBottom, ambientGroundMix); + return mix(bottomAmbient, topAmbient, sqrt(heightFraction)); + +} + +float ComputePowder(vec3 lightExtinction, float lightDotView) { + + // Optical depth towards the light is -log(lightExtinction). Following Schneider (2015) the powder + // term is 1 - exp(-2 * depth), which equals 1 - lightExtinction^2. + float extinctionToLight = dot(lightExtinction, vec3(0.3333)); + float powder = 1.0 - extinctionToLight * extinctionToLight; + + // Only applied when looking away from the sun, forward scattering is unaffected + float viewWeight = saturate(0.5 - lightDotView * 0.5); + return mix(1.0, mix(1.0 - powderStrength, 1.0, powder), viewWeight); } @@ -245,7 +262,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart vec4 clampedExtinction = max(extinctionCoefficient, 0.0000001); vec4 stepExtinction = exp(-extinctionCoefficient * smallStepLength); - float lightDotView = dot(cloudUniforms.light.direction.xyz, rayDirection); + // Cosine between the view ray and the direction to the sun, positive eccentricities scatter forward + float lightDotView = dot(-cloudUniforms.light.direction.xyz, rayDirection); vec3 lightColor = cloudUniforms.light.color.rgb * cloudUniforms.light.intensity; vec4 lightExtinction = GetExtinctionToLight(rayPos, i % 4, noiseVector); @@ -253,7 +271,8 @@ vec4 IntegrateVolumetricClouds(vec3 rayOrigin, vec3 rayDirection, float rayStart cloudUniforms.eccentricitySecondPhase, cloudUniforms.phaseAlpha, lightDotView); vec3 multipleScattering = ApproximateMultipleScattering(lightExtinction.rgb, lightDotView); - vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb; + vec3 directLighting = directAlbedo * phaseFunction * lightColor * lightExtinction.rgb * + ComputePowder(lightExtinction.rgb, lightDotView); vec3 multiScatterLighting = directAlbedo * multiScatteringIntensity * lightColor * multipleScattering; vec3 ambientLighting = ambientAlbedo * ComputeAmbientColor(rayPos, extinction.a); diff --git a/data/shader/volumetric/volumetric.csh b/data/shader/volumetric/volumetric.csh index dc39ed199..91c6c6610 100644 --- a/data/shader/volumetric/volumetric.csh +++ b/data/shader/volumetric/volumetric.csh @@ -108,10 +108,8 @@ void LoadLightTypeData(uint requestedLightType) { void main() { + // No early return, all invocations have to reach the barriers when loading the lights ivec2 pixel = ivec2(gl_GlobalInvocationID); - if (pixel.x > imageSize(volumetricImage).x || - pixel.y > imageSize(volumetricImage).y) - return; vec2 texCoord = (vec2(pixel) + 0.5) / vec2(imageSize(volumetricImage)); @@ -405,13 +403,16 @@ float GetShadowFactorDirectionalLight(int lightIdx, int shadowIdx, uint lightTyp float dist = -currentPosition.z; + if (shadowIdx < 0) + return 1.0; + #ifndef AE_BINDLESS int mapIdx = lightIdx; #else int mapIdx = volumetricShadows[shadowIdx].mapIdx; #endif - if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) + if (dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) return 1.0; float shadowValue = 1.0; @@ -470,13 +471,16 @@ float GetShadowFactorPunctualLight(int lightIdx, int shadowIdx, uint lightType, float dist = -currentPosition.z; + if (shadowIdx < 0) + return 1.0; + #ifndef AE_BINDLESS int mapIdx = lightIdx; #else int mapIdx = volumetricShadows[shadowIdx].mapIdx; #endif - if (shadowIdx < 0 || dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) + if (dist > volumetricShadows[shadowIdx].distance || mapIdx < 0) return 1.0; float shadowValue = 1.0; diff --git a/src/capture/App.cpp b/src/capture/App.cpp new file mode 100644 index 000000000..0c6b63f00 --- /dev/null +++ b/src/capture/App.cpp @@ -0,0 +1,1882 @@ +#include "App.h" +#include "SceneEditor.h" + +#include "Serializer.h" +#include "loader/ImageLoader.h" +#include "Log.h" +#include "resource/ResourceManager.h" +#include "scripting/Script.h" +#include "scene/components/LuaScriptComponent.h" +#include "events/EventManager.h" +#include "graphics/GraphicsDevice.h" +#include "graphics/Instance.h" +#include "graphics/Profiler.h" + +#include + +#include +#include +#include +#include +#include + +#ifdef AE_OS_WINDOWS +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +// Collides with Loader::ImageLoader::LoadImage +#undef LoadImage +#else +#include +#endif + +const Atlas::EngineConfig Atlas::EngineInstance::engineConfig = { + .assetDirectory = "../../data", + .shaderDirectory = "shader" +}; + +namespace Atlas::Capture { + + using namespace Scene::Components; + + static int32_t jobExitCode = 0; + // Preserve the job result if shutdown crashes after the report was written + static bool reportWritten = false; + + // Known to the crash handlers, which write the report of a crashed run + static std::string runId; + static std::string runJobName; + static fs::path reportPath; + static fs::path lockPath; + + static uint32_t CurrentProcessId() { + +#ifdef AE_OS_WINDOWS + return uint32_t(::GetCurrentProcessId()); +#else + return uint32_t(getpid()); +#endif + + } + + static bool IsProcessRunning(uint32_t processId) { + +#ifdef AE_OS_WINDOWS + auto process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId); + if (!process) + return false; + DWORD code = 0; + bool running = GetExitCodeProcess(process, &code) && code == STILL_ACTIVE; + CloseHandle(process); + return running; +#else + return kill(pid_t(processId), 0) == 0; +#endif + + } + + // Write next to the target, then rename; a failed rename leaves the target unchanged + static bool WriteFileAtomic(const fs::path& path, const std::string& content) { + + auto temporary = path; + temporary += ".tmp"; + { + std::ofstream stream(temporary, std::ios::binary); + if (!stream.is_open()) + return false; + stream << content; + } + + std::error_code error; + fs::rename(temporary, path, error); + return !error; + + } + + // Prevent concurrent runs from mixing outputs + static std::string AcquireLock(const fs::path& directory) { + + auto path = directory / "capture.lock"; + for (int32_t attempt = 0; attempt < 2; attempt++) { + // Exclusive creation, only one process can succeed + if (auto file = std::fopen(path.string().c_str(), "wx")) { + auto content = json{ { "pid", CurrentProcessId() }, { "job", runJobName }, { "runId", runId } }.dump(); + std::fputs(content.c_str(), file); + std::fclose(file); + lockPath = path; + return {}; + } + + std::ifstream stream(path); + auto lock = json::parse(stream, nullptr, false); + stream.close(); + auto processId = lock.is_object() ? lock.value("pid", uint32_t(0)) : uint32_t(0); + if (processId != 0 && IsProcessRunning(processId)) + return "The output directory " + directory.string() + " is used by capture process " + + std::to_string(processId) + " (job '" + lock.value("job", std::string()) + "', run " + + lock.value("runId", std::string()) + "). Wait for it or choose another directory with --out"; + + // Left behind by a process that crashed or was killed + std::error_code error; + fs::remove(path, error); + } + + return "Couldn't create the lock file " + path.string(); + + } + + static void ReleaseLock() { + + if (lockPath.empty()) + return; + std::error_code error; + fs::remove(lockPath, error); + lockPath.clear(); + + } + + static void WriteCrashReport(const std::string& reason) { + + if (reportWritten || reportPath.empty()) + return; + + json report = { { "job", runJobName }, { "runId", runId }, { "status", "crashed" }, { "exitCode", 3 }, + { "reason", reason } }; + WriteFileAtomic(reportPath, report.dump(2)); + + } + + struct ViewAngles { + + float azimuth; + float elevation; + + }; + + static ViewAngles GetViewAngles(const std::string& view) { + + // Azimuth 0 places the camera on the +Z side looking towards -Z + static const std::map views = { + { "front", { 0.0f, 15.0f } }, + { "right", { 90.0f, 15.0f } }, + { "back", { 180.0f, 15.0f } }, + { "left", { 270.0f, 15.0f } }, + { "top", { 0.0f, 89.0f } }, + { "iso", { 45.0f, 35.0f } }, + // Almost at ground level, best to see whether something floats + { "low", { 0.0f, 2.0f } }, + { "lowSide", { 90.0f, 2.0f } }, + }; + + auto it = views.find(view); + if (it == views.end()) + throw std::runtime_error("Unknown view '" + view + "' (front, right, back, left, top, iso, low, lowSide)"); + + return it->second; + + } + + // Record crashes in the job output + static void PrintCrash(const std::string& reason) { + + auto message = "[capture] CRASH: " + reason + "\nStack trace:\n" + std::to_string(std::stacktrace::current()); + std::fprintf(stderr, "%s\n", message.c_str()); + std::fprintf(stdout, "%s\n", message.c_str()); + std::fflush(stderr); + std::fflush(stdout); + + WriteCrashReport(reason); + ReleaseLock(); + + } + + static void InstallCrashHandlers() { + + std::set_terminate([]() { + + std::string reason = "std::terminate"; + if (auto exception = std::current_exception()) { + try { + std::rethrow_exception(exception); + } + catch (const std::exception& e) { + reason += " with uncaught exception: " + std::string(e.what()); + } + catch (...) { + reason += " with an unknown exception"; + } + } + PrintCrash(reason); + std::_Exit(reportWritten ? jobExitCode : 3); + + }); + + std::signal(SIGABRT, [](int32_t) { + + PrintCrash("abort"); + std::_Exit(reportWritten ? jobExitCode : 3); + + }); + +#ifdef AE_OS_WINDOWS + SetUnhandledExceptionFilter([](EXCEPTION_POINTERS* info) -> LONG { + + char code[32]; + std::snprintf(code, sizeof(code), "0x%08lX", info->ExceptionRecord->ExceptionCode); + PrintCrash(std::string("unhandled exception ") + code); + std::_Exit(reportWritten ? jobExitCode : 3); + + }); +#endif + + } + + // Keep scripts active with a minimal time step while waiting for real-time playback + static constexpr float freezeDeltaTime = 1e-5f; + + static bool RunCompose(const std::vector& args) { + + if (args.size() < 3 || args[1] != "--compose") + return false; + + auto output = ResolveUserPath(args[2]); + std::string title; + int32_t columns = 0; + std::vector> images; + std::vector labels; + + for (size_t i = 3; i < args.size(); i++) { + if (args[i] == "--title" && i + 1 < args.size()) { + title = args[++i]; + continue; + } + if (args[i] == "--columns" && i + 1 < args.size()) { + columns = std::stoi(args[++i]); + continue; + } + + auto separator = args[i].find('='); + auto label = + separator == std::string::npos ? fs::path(args[i]).stem().string() : args[i].substr(0, separator); + auto path = ResolveUserPath(separator == std::string::npos ? args[i] : args[i].substr(separator + 1)); + + auto image = Loader::ImageLoader::LoadImage(path.string(), false, 4); + if (!image || !image->HasData()) { + std::printf("Couldn't load %s\n", path.string().c_str()); + jobExitCode = 2; + return true; + } + images.push_back(image); + labels.push_back(label); + } + + auto sheet = ComposeSheet(images, labels, columns, title); + jobExitCode = WritePng(sheet, output) ? 0 : 2; + std::printf("[capture] Composed %zu images into %s\n", images.size(), output.string().c_str()); + return true; + + } + + // Remove only outputs listed in the previous report + static void RemovePreviousOutputs(const fs::path& directory) { + + std::ifstream stream(directory / "report.json"); + if (!stream.is_open()) + return; + + auto previousReport = json::parse(stream, nullptr, false); + stream.close(); + if (previousReport.is_discarded() || !previousReport.contains("outputs")) + return; + + std::error_code error; + for (const auto& output : previousReport["outputs"]) { + auto path = (directory / output.get()).lexically_normal(); + if (path.lexically_relative(directory).string().starts_with("..")) + continue; + + fs::remove(path, error); + // Directories of strips and variants + auto parent = path.parent_path(); + if (parent != directory && fs::is_empty(parent, error)) + fs::remove(parent, error); + } + + } + + static std::string FormatTime(float time) { + + return "t=" + FormatFloat(time, 2) + "s"; + + } + + void App::LoadContent() { + + startTime = std::chrono::steady_clock::now(); + InstallCrashHandlers(); + + if (RunCompose(args)) { + phase = Phase::Done; + Exit(jobExitCode); + return; + } + + try { + job = ParseCommandLine(args); + } + catch (const std::exception& e) { + std::string message = e.what(); + std::printf("%s\n", message.c_str()); + jobExitCode = message.starts_with("Usage:") ? 0 : 2; + phase = Phase::Done; + Exit(jobExitCode); + return; + } + + fs::create_directories(job.outputDirectory); + + runId = std::to_string(std::chrono::system_clock::now().time_since_epoch() / std::chrono::seconds(1)) + "-" + + std::to_string(CurrentProcessId()); + runJobName = job.name; + if (auto error = AcquireLock(job.outputDirectory); !error.empty()) { + std::printf("[capture] ERROR: %s\n", error.c_str()); + std::printf("[capture] Status: error (%s)\n", error.c_str()); + jobExitCode = 2; + phase = Phase::Done; + Exit(jobExitCode); + return; + } + + // Clear stale outputs before recording the running state + RemovePreviousOutputs(job.outputDirectory); + reportPath = job.outputDirectory / "report.json"; + WriteFileAtomic(reportPath, + json{ { "job", job.name }, { "runId", runId }, { "status", "running" }, { "pid", CurrentProcessId() } } + .dump(2)); + logFile.open(job.outputDirectory / "log.txt"); + + if (job.showWindow) { + font = CreateRef("font/roboto.ttf", 16.0f, 5); + + // The frame keeps its aspect ratio above the output panel, large captures are shown smaller + auto panelHeight = CaptureRenderer::GetPanelHeight(font, outputLineCount + 1); + auto scale = std::min({ 1.0f, 1600.0f / float(job.resolution.x), 900.0f / float(job.resolution.y) }); + window.SetSize( + int32_t(float(job.resolution.x) * scale), int32_t(float(job.resolution.y) * scale + panelHeight)); + window.Show(); + } + + // The profiler is disabled by default in release builds + if (job.profileFrames > 0) + Graphics::Profiler::enable = true; + + Print("Job '" + job.name + "' with scene " + job.scene + " (run " + runId + ")"); + + if (job.validation) { + auto instance = Graphics::Instance::DefaultInstance; + if (!instance->extendedValidationEnabled) { + Fail("Validation layers aren't available, they are part of the Vulkan SDK"); + return; + } + + VkDebugUtilsMessengerCreateInfoEXT createInfo = {}; + createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; + createInfo.messageSeverity = + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + createInfo.messageType = + VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; + createInfo.pfnUserCallback = ValidationCallback; + createInfo.pUserData = this; + VK_CHECK(vkCreateDebugUtilsMessengerEXT(instance->GetNativeInstance(), &createInfo, nullptr, &validationMessenger)) + + Print("Validation: GPU assisted, synchronization and best practices validation enabled"); + } + Print("Output directory: " + job.outputDirectory.string()); + + captureRenderer.Init(mainRenderer, job.resolution); + overlay = std::make_unique(); + + // Capture errors that happen while loading + logIndex = Log::GetEntryCount(); + + try { + auto binary = fs::path(job.scene).extension() != ".json"; + scene = Serializer::DeserializeScene(job.scene, binary); + } + catch (const std::exception& e) { + Fail("Couldn't load scene " + job.scene + ": " + e.what()); + return; + } + + if (!scene) { + Fail("Couldn't load scene " + job.scene); + return; + } + + captureCameraEntity = scene->CreateEntity(); + auto& camera = captureCameraEntity.AddComponent( + 60.0f, float(job.resolution.x) / float(job.resolution.y), 0.1f, 2000.0f); + camera.isMain = false; + + // The mouse over a shown window must not turn the players of a running job + playerInput.useMouse = false; + + checkRunner = std::make_unique(job.checks); + if (job.track) + tracker = std::make_unique(*job.track); + + // Load with the camera of the first shot such that streaming and probes start in the right area + if (!job.shots.empty()) + activeCamera = job.shots.front().camera; + else + activeCamera = job.observer.value_or(CameraSpec {}); + + } + + void App::UnloadContent() { + + if (phase != Phase::Done) { + Fail("The window was closed before the job finished"); + Finish(); + } + ReleaseLock(); + + graphicsDevice->WaitForIdle(); + + if (validationMessenger != VK_NULL_HANDLE) + vkDestroyDebugUtilsMessengerEXT( + Graphics::Instance::DefaultInstance->GetNativeInstance(), validationMessenger, nullptr); + + scene.reset(); + logFile.close(); + + } + + void App::Update(float deltaTime) { + + if (phase == Phase::Done) + return; + + graphicsDevice->WaitForPreviousFrameSubmission(); + + try { + ProcessReadback(); + CollectLog(); + + frameCount++; + + switch (phase) { + case Phase::Loading: { + UpdateSceneWithCaptureCamera(*activeCamera); + auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - startTime).count(); + if (IsSceneReady()) { + for (const auto& mesh : scene->GetMeshes()) + if (mesh.IsValid() && !mesh.IsLoaded()) + Warn("Mesh " + mesh.GetResource()->path + " failed to load"); + + loadSeconds = elapsed; + Print("Scene ready after " + FormatFloat(loadSeconds, 1) + "s (" + std::to_string(frameCount) + + " frames, " + std::to_string(scene->GetEntityCount() - 1) + " entities)"); + phase = Phase::Prepare; + } + else if (elapsed > job.loadTimeout) { + Fail("Scene didn't finish loading within " + FormatFloat(job.loadTimeout, 0) + "s"); + } + break; + } + case Phase::Prepare: + Prepare(); + break; + case Phase::EditSave: + FinishEdit(); + break; + case Phase::Shots: + UpdateShots(); + break; + case Phase::Play: + UpdatePlay(); + break; + case Phase::Finish: + if (!HasPendingCaptures()) + Finish(); + break; + default: + break; + } + } + catch (const std::exception& e) { + Fail(e.what()); + } + + } + + void App::Render(float deltaTime) { + + // While finishing the scene isn't updated anymore, rendering it without an update shows garbage + auto finished = phase == Phase::Done || (phase == Phase::Finish && captureRequests.empty()); + if (finished || !scene) { + // Scene updates can enqueue GPU work even when no scene frame is rendered + if (scene) + scene->WaitForAsyncWorkCompletion(); + PresentWindow(); + return; + } + + std::vector passes; + for (const auto& request : captureRequests) + for (const auto& pass : request.passes) + if (std::find(passes.begin(), passes.end(), pass) == passes.end()) + passes.push_back(pass); + + try { + BuildOverlay(); + captureRenderer.Render(scene, passes, overlay->GetBatches()); + } + catch (const std::exception& e) { + // E.g. validation errors, which the engine throws in non-release builds + Fail(std::string("Rendering failed: ") + e.what()); + captureRequests.clear(); + PresentWindow(); + return; + } + + pendingReadbacks = std::move(captureRequests); + captureRequests.clear(); + + PresentWindow(); + + } + + void App::PresentWindow() { + + if (!job.showWindow || !font) { + captureRenderer.Present(); + return; + } + + std::vector lines = { { GetStatusLine(), vec4(0.55f, 0.8f, 1.0f, 1.0f) } }; + auto first = outputLines.size() > outputLineCount ? outputLines.size() - outputLineCount : 0; + lines.insert(lines.end(), outputLines.begin() + first, outputLines.end()); + + captureRenderer.Present(font, lines); + + } + + std::string App::GetStatusLine() const { + + std::string line = job.name + " | "; + switch (phase) { + case Phase::Loading: + line += "loading " + job.scene; + break; + case Phase::Prepare: + case Phase::EditSave: + line += "preparing"; + break; + case Phase::Shots: + line += "shots"; + break; + case Phase::Play: + line += "playing " + FormatFloat(playTime, 2) + " / " + FormatFloat(job.duration, 2) + " s"; + if (scene && scene->paused) + line += " (paused)"; + break; + case Phase::Finish: + line += "writing outputs"; + break; + case Phase::Done: + line += jobExitCode == 0 ? "passed" : jobExitCode == 1 ? "failed" : "error"; + break; + } + return line + " | frame " + std::to_string(frameCount); + } + + void App::Fail(const std::string& message) { + + errors.push_back(message); + fatal = true; + Print("ERROR: " + message); + + if (phase != Phase::Done) + phase = Phase::Finish; + + } + + void App::Warn(const std::string& message) { + + warnings.push_back(message); + Print("WARNING: " + message); + + } + + void App::Print(const std::string& message) { + + std::printf("[capture] %s\n", message.c_str()); + std::fflush(stdout); + + if (job.showWindow) { + auto color = vec4(0.85f, 0.85f, 0.85f, 1.0f); + if (message.starts_with("ERROR") || message.starts_with("FAILED")) + color = vec4(1.0f, 0.4f, 0.35f, 1.0f); + else if (message.starts_with("WARNING")) + color = vec4(1.0f, 0.8f, 0.3f, 1.0f); + else if (message.starts_with("Status: passed")) + color = vec4(0.45f, 0.9f, 0.45f, 1.0f); + outputLines.push_back({ message, color }); + if (outputLines.size() > 200) + outputLines.pop_front(); + } + + if (logFile.is_open()) + logFile << "[capture] " << message << "\n"; + + } + + void App::CollectLog() { + + auto entries = Log::GetEntriesSince(logIndex); + logIndex += entries.size(); + + for (const auto& entry : entries) { + // Log conditions: a text without wildcards matches when the message contains it + for (auto& trigger : triggers) { + if (trigger.logMatched || playTime + 1e-4f < trigger.event.time || !trigger.event.when->contains("log")) + continue; + auto pattern = (*trigger.event.when)["log"].get(); + if (pattern.find_first_of("*?") == std::string::npos) + pattern = "*" + pattern + "*"; + trigger.logMatched = MatchPattern(pattern, entry.message); + } + + std::string type = + entry.type == Log::TYPE_ERROR ? "ERROR" : (entry.type == Log::TYPE_WARNING ? "WARNING" : "INFO"); + if (logFile.is_open()) + logFile << "[" << FormatFloat(entry.time, 2) << "] " << type << ": " << entry.message << "\n"; + + if (entry.type == Log::TYPE_ERROR) { + logErrorCount++; + std::printf("[engine] ERROR: %s\n", entry.message.c_str()); + if (checkRunner && job.checks.logErrors && !MatchAnyPattern(job.checks.logIgnore, entry.message)) + checkRunner->AddFailure({ "log", entry.message.substr(0, 160), playTime, entry.message }); + } + } + + if (logFile.is_open()) + logFile.flush(); + + } + + bool App::IsSceneReady() { + + // A few frames are needed to kick off the asynchronous work + if (frameCount < 3) + return false; + + // Meshes that failed to load count as done, they're reported once the scene is ready + for (const auto& mesh : scene->GetMeshes()) { + if (mesh.IsLoaded()) + continue; + if (!mesh.IsValid() || !mesh.GetResource()->errorOnLoad) + return false; + } + if (scene->terrain.IsValid() && !scene->terrain.IsLoaded()) + return false; + + // Ray tracing structures are built asynchronously, but not every device/scene builds them + if (scene->rayTracingWorld && !scene->IsRtDataValid() && rtWaitFrames++ < 300) + return false; + + return true; + + } + + void App::Prepare() { + + // The renderer expects a scene update in every frame + UpdateSceneWithCaptureCamera(*activeCamera); + + if (!job.settings.empty()) + ApplySettings(*scene, job.settings); + baseSettings = ExportSettings(*scene); + + EntitySet excluded = { captureCameraEntity }; + + if (job.inspect) { + auto inspection = InspectScene(*scene, job.inspect->filter, job.inspect->detail, excluded); + WriteJson(job.inspect->file, inspection); + Print("Inspection: " + std::to_string(inspection["entities"].size()) + " entities written to " + + job.inspect->file); + } + + if (!job.queries.empty()) { + // Pixel picking uses the same camera setup as shots + auto pickRay = [&](const json& cameraJson, vec2 pixel) { + + // The scene update computes the camera matrices, the simulation is paused at this point + UpdateSceneWithCaptureCamera(ParseCamera(cameraJson)); + const auto& camera = captureCameraEntity.GetComponent(); + + auto ray = Volume::Ray(captureRenderer.GetViewport(), camera, pixel + vec2(0.5f)); + return std::make_pair(ray.origin, ray.direction); + + }; + + auto results = RunQueries(*scene, job.queries, pickRay); + WriteJson("queries.json", results); + queryResults = results; + for (const auto& result : results) { + auto text = + result.contains("error") ? "error: " + result["error"].get() : result["result"].dump(); + if (text.size() > 400) + text = text.substr(0, 400) + "... (see queries.json)"; + Print("Query " + result["query"].dump() + " -> " + text); + } + } + + if (job.edit) { + report["edit"]["before"] = InspectScene(*scene, {}, {}, excluded); + report["edit"]["operations"] = ApplyEditOperations(*scene, job.edit->operations); + Print("Applied " + std::to_string(job.edit->operations.size()) + " edit operations"); + phase = Phase::EditSave; + return; + } + + // Checks of a static scene run once, while playing they run continuously + if (!job.play) + checkRunner->Run(*scene, 0.0f); + + if (!job.shots.empty()) + phase = Phase::Shots; + else if (job.play) + StartPlay(); + else + phase = Phase::Finish; + + } + + void App::FinishEdit() { + + // Propagate transforms and bounds before inspection + UpdateSceneWithCaptureCamera(*activeCamera); + if (++editFrames < 3) + return; + + EntitySet excluded = { captureCameraEntity }; + auto& edit = report["edit"]; + + auto after = InspectScene(*scene, {}, {}, excluded); + auto diff = DiffInspections(edit["before"], after); + edit.erase("before"); + WriteJson("edit_diff.json", diff); + edit["diff"] = diff["summary"]; + Print("Edit diff: " + diff["summary"].get() + " (see edit_diff.json)"); + + checkRunner->Run(*scene, 0.0f); + if (checkRunner->HasFailures()) { + edit["saved"] = false; + Fail("Checks failed after the edit, the scene was not saved"); + return; + } + + // Edits which only changed material files leave the scene untouched, no need to rewrite it + if (diff["changed"].empty() && diff["added"].empty() && diff["removed"].empty() && !job.edit->saveUnchanged) { + edit["saved"] = false; + Print("The scene itself didn't change, it is not saved"); + phase = job.shots.empty() ? Phase::Finish : Phase::Shots; + return; + } + + auto output = job.edit->output; + if (output.empty()) { + auto scenePath = fs::path(job.scene); + output = (scenePath.parent_path() / (scenePath.stem().string() + ".edit" + scenePath.extension().string())) + .generic_string(); + } + + auto absoluteOutput = GetAssetDirectory() / output; + if (output == job.scene && !job.edit->overwrite) { + Fail("Refusing to overwrite the input scene " + output + + ", set edit.overwrite = true or choose another output"); + return; + } + if (fs::exists(absoluteOutput) && output != job.scene && !job.edit->overwrite) { + Fail("Output scene " + output + " already exists, set edit.overwrite = true to replace it"); + return; + } + + if (fs::exists(absoluteOutput)) { + auto timestamp = std::chrono::system_clock::now().time_since_epoch() / std::chrono::seconds(1); + auto backup = absoluteOutput; + backup += ".backup-" + std::to_string(timestamp); + fs::copy_file(absoluteOutput, backup); + edit["backup"] = backup.string(); + Print("Backup of the previous scene: " + backup.string()); + } + + // The capture camera must not end up in the scene, the editor does the same with its camera + auto entityCount = scene->GetEntityCount() - 1; + scene->DestroyEntity(captureCameraEntity); + + auto binary = fs::path(output).extension() != ".json"; + Serializer::SerializeScene(scene, output, false, binary); + + captureCameraEntity = scene->CreateEntity(); + captureCameraEntity + .AddComponent(60.0f, float(job.resolution.x) / float(job.resolution.y), 0.1f, 2000.0f) + .isMain = false; + + try { + auto reloaded = Serializer::DeserializeScene(output, binary); + auto reloadedCount = reloaded->GetEntityCount(); + edit["verified"] = reloadedCount == entityCount; + if (reloadedCount != entityCount) + Fail("Saved scene has " + std::to_string(reloadedCount) + " entities, expected " + + std::to_string(entityCount)); + } + catch (const std::exception& e) { + Fail("Saved scene " + output + " couldn't be loaded again: " + e.what()); + return; + } + + edit["saved"] = true; + edit["output"] = output; + Print("Saved edited scene to data/" + output); + + if (phase == Phase::Finish) + return; + + phase = job.shots.empty() ? Phase::Finish : Phase::Shots; + + } + + void App::UpdateShots() { + + auto variantCount = std::max(job.variants.size(), size_t(1)); + const auto& shot = job.shots[shotState.shot]; + auto views = shot.views.empty() ? std::vector { "" } : shot.views; + const auto& view = views[shotState.view]; + + bool firstFrameOfShot = shotState.settledFrames == 0 && !shotState.requested; + if (firstFrameOfShot && !job.variants.empty() && shotState.shot == 0 && shotState.view == 0) { + const auto& variant = job.variants[shotState.variant]; + ApplySettings(*scene, baseSettings); + ApplySettings(*scene, variant.settings); + Print("Variant '" + variant.name + "'"); + } + + auto camera = shot.camera; + if (!view.empty()) { + camera.view = view; + camera.azimuth.reset(); + camera.elevation.reset(); + if (camera.mode == "scene" || camera.mode == "manual") + throw std::runtime_error( + "Shot '" + shot.name + "' has views, which require a focus or overview camera"); + } + activeCamera = camera; + + UpdateSceneWithCaptureCamera(camera); + + auto settleFrames = shot.settleFrames >= 0 ? shot.settleFrames : job.settleFrames; + if (!shotState.requested) { + if (shotState.settledFrames++ < settleFrames) + return; + + auto prefix = + job.variants.empty() ? std::string() : SanitizeFileName(job.variants[shotState.variant].name) + "/"; + auto baseName = SanitizeFileName(shot.name) + (view.empty() ? "" : "_" + view); + + CaptureRequest request; + request.path = job.outputDirectory / (prefix + baseName + ".png"); + request.passes = shot.passes; + request.label = view.empty() ? shot.name : view; + + if (views.size() > 1) { + request.group = prefix + SanitizeFileName(shot.name) + "_views"; + if (!sheets.contains(request.group)) { + sheets[request.group] = { .title = shot.name + + (prefix.empty() ? "" : " (" + job.variants[shotState.variant].name + ")"), + .path = job.outputDirectory / (request.group + ".png") }; + sheetOrder.push_back(request.group); + } + } + + RequestCapture(request); + + // Variants of the same shot/view are compared in an additional sheet + if (!job.variants.empty()) { + auto group = baseName + "_variants"; + if (!sheets.contains(group)) { + sheets[group] = { .title = baseName + " variants", .path = job.outputDirectory / (group + ".png") }; + sheetOrder.push_back(group); + } + variantCaptures[request.path.string()] = { group, job.variants[shotState.variant].name }; + } + + shotState.requested = true; + return; + } + + if (HasPendingCaptures()) + return; + + shotState.requested = false; + shotState.settledFrames = 0; + + if (++shotState.view < views.size()) + return; + shotState.view = 0; + + if (++shotState.shot < job.shots.size()) + return; + shotState.shot = 0; + + if (++shotState.variant < variantCount) + return; + + if (job.play) + StartPlay(); + else + phase = Phase::Finish; + + } + + void App::StartPlay() { + + playStartTime = std::chrono::steady_clock::now(); + events = job.timeline; + + for (auto it = events.begin(); it != events.end();) { + if (it->when) { + triggers.push_back({ .event = *it }); + it = events.erase(it); + } + else { + ++it; + } + } + + // Strips are expanded into capture events + for (const auto& strip : job.strips) { + auto group = SanitizeFileName(strip.name); + sheets[group] = { + .title = strip.name, .columns = strip.columns, .path = job.outputDirectory / (group + ".png") + }; + sheetOrder.push_back(group); + + if (strip.hasCamera) + stripCameras[group] = strip.camera; + + // Integer steps avoid accumulating floating point errors + auto count = int32_t(std::floor((strip.to - strip.from) / strip.every + 1e-3f)); + for (int32_t i = 0; i <= count; i++) { + auto time = strip.from + float(i) * strip.every; + + EventSpec event; + event.time = time; + event.type = "capture"; + event.data["capture"] = json::object(); + event.data["capture"]["file"] = group + "/" + FormatFloat(time, 2) + "s.png"; + event.data["capture"]["group"] = group; + event.data["capture"]["stripCamera"] = strip.hasCamera; + events.push_back(event); + } + } + + std::stable_sort(events.begin(), events.end(), [](const EventSpec& a, const EventSpec& b) { + + return a.time < b.time; + + }); + + auto beyond = std::remove_if(events.begin(), events.end(), [&](const EventSpec& event) { + + return event.time > job.duration + 1e-4f; + + }); + if (beyond != events.end()) { + Warn(std::to_string(std::distance(beyond, events.end())) + " timeline events after the duration of " + + FormatFloat(job.duration, 2) + "s are ignored"); + events.erase(beyond, events.end()); + } + + activeCamera = job.observer.value_or(CameraSpec {}); + + // Focus cameras are framed once, re-framing a moving object every frame makes the camera jump + if ((activeCamera->mode == "focus" || activeCamera->mode == "overview") && !activeCamera->dynamic) { + ApplyCameraSpec(*activeCamera); + const auto& camera = captureCameraEntity.GetComponent(); + + CameraSpec fixed = *activeCamera; + fixed.mode = "manual"; + fixed.position = camera.location; + fixed.lookAt.reset(); + fixed.yaw = glm::degrees(camera.rotation.x); + fixed.pitch = glm::degrees(camera.rotation.y); + fixed.farPlane = camera.farPlane; + activeCamera = fixed; + } + + for (const auto& spec : job.scripts) { + auto script = ResourceManager::GetOrLoadResource(spec.path); + if (!script.IsLoaded()) + throw std::runtime_error("Couldn't load script " + spec.path); + + std::vector entities; + if (spec.entity.empty()) { + auto entity = scene->CreateEntity(); + entity.AddComponent("Capture script " + fs::path(spec.path).stem().string()); + entity.AddComponent(mat4(1.0f), false); + entities.push_back(entity); + } + else { + entities = RemoveDescendants(*scene, FindEntities(*scene, spec.entity)); + if (entities.empty()) + throw std::runtime_error("Script " + spec.path + ": no entity matches '" + spec.entity + "'"); + } + + for (auto entity : entities) { + if (entity.HasComponent()) + throw std::runtime_error( + GetEntityLabel(entity) + " already has a script, attach to a new entity instead"); + entity.AddComponent(script); + Print("Attached script " + spec.path + " to " + GetEntityLabel(entity)); + } + } + + // Enable play mode; scene.paused controls pauses and resetScripts temporarily leaves play mode + scene->physicsWorld->pauseSimulation = false; + playTime = 0.0f; + nextEvent = 0; + phase = Phase::Play; + + Print("Playing for " + FormatFloat(job.duration, 2) + "s with " + std::to_string(events.size()) + + " timeline events and " + std::to_string(triggers.size()) + " conditional events"); + + } + + void App::UpdatePlay() { + + if (stillState.active) { + UpdateStill(); + return; + } + + // A shown window plays in real time, the simulation still advances in fixed steps + auto realPlayTime = std::chrono::duration(std::chrono::steady_clock::now() - playStartTime).count(); + if (job.showWindow && playTime > realPlayTime) { + UpdateSceneWithCaptureCamera(*activeCamera, freezeDeltaTime); + return; + } + + for (auto it = pendingKeyReleases.begin(); it != pendingKeyReleases.end();) { + if (it->first <= playTime + 1e-4f) { + FireKey(it->second, false); + it = pendingKeyReleases.erase(it); + } + else { + ++it; + } + } + + UpdateTriggers(); + + bool liveCapture = false; + while (nextEvent < events.size() && events[nextEvent].time <= playTime + 1e-4f) { + const auto& event = events[nextEvent]; + const auto& data = event.data; + + if (event.type == "capture") { + const auto& capture = data["capture"]; + auto group = capture.value("group", std::string()); + + CameraSpec camera = activeCamera.value_or(CameraSpec {}); + bool ownCamera = false; + if (capture.contains("camera")) { + camera = ParseCamera(capture["camera"]); + ownCamera = true; + } + else if (capture.value("stripCamera", false)) { + camera = stripCameras[group]; + ownCamera = true; + } + + CaptureRequest request; + auto file = capture.value("file", + SanitizeFileName(capture.value("name", "capture")) + "_" + FormatFloat(playTime, 2) + "s.png"); + request.path = job.outputDirectory / file; + request.group = group; + request.label = capture.value("label", FormatTime(event.time)); + request.time = event.time; + if (capture.contains("passes")) + request.passes = capture["passes"].get>(); + + // A different camera than the observer needs frozen frames to let temporal effects settle + if (ownCamera || capture.value("still", false)) { + // Pending live captures are taken first, the still starts in the next frame + if (liveCapture) + break; + + stillState = StillState { .active = true, + .camera = camera, + .request = request, + .settleFrames = capture.value("settleFrames", job.settleFrames) }; + // The paused scene doesn't advance the exposure adaptation, it starts over for the new view + captureRenderer.InvalidateHistory(); + nextEvent++; + UpdateStill(); + return; + } + + RequestCapture(request); + liveCapture = true; + } + else if (event.type == "key") { + const auto& key = data["key"]; + auto name = key.is_string() ? key.get() : key.at("key").get(); + auto action = key.is_object() ? key.value("action", std::string("press")) : std::string("press"); + if (action == "down" || action == "press") + FireKey(name, true); + if (action == "up") + FireKey(name, false); + if (action == "press") { + auto duration = + key.is_object() ? key.value("duration", job.fixedDeltaTime * 2.0f) : job.fixedDeltaTime * 2.0f; + pendingKeyReleases.emplace_back(playTime + duration, name); + } + Print(FormatTime(playTime) + " key " + name + " " + action); + } + else if (event.type == "teleport") { + const auto& teleport = data["teleport"]; + auto position = ToVec3(teleport.at("position")); + auto entities = + RemoveDescendants(*scene, FindEntities(*scene, teleport.at("entity").get())); + if (entities.empty()) + Warn(FormatTime(playTime) + " teleport: no entity matches " + teleport["entity"].dump()); + + for (auto entity : entities) { + if (auto player = entity.TryGetComponent(); player && player->IsValid()) + player->SetPosition(position); + SetWorldPosition(entity, position); + if (teleport.contains("yaw") || teleport.contains("pitch")) + SetLookDirection(entity, teleport); + Print( + FormatTime(playTime) + " teleported " + GetEntityLabel(entity) + " to " + FormatVec3(position)); + } + } + else if (event.type == "look") { + const auto& look = data["look"]; + auto entities = RemoveDescendants(*scene, FindEntities(*scene, look.at("entity").get())); + if (entities.empty()) + Warn(FormatTime(playTime) + " look: no entity matches " + look["entity"].dump()); + for (auto entity : entities) + SetLookDirection(entity, look); + } + else if (event.type == "resetScripts") { + // Leaving play mode discards non-permanent script environments; scene.paused keeps their state + scene->physicsWorld->pauseSimulation = true; + UpdateSceneWithCaptureCamera(*activeCamera, freezeDeltaTime); + scene->physicsWorld->pauseSimulation = false; + Print(FormatTime(playTime) + " reset the state of all scripts"); + } + else if (event.type == "pause") { + // The job time continues, e.g. to check that nothing moves and scripts keep their state + scene->paused = data["pause"].get(); + Print(FormatTime(playTime) + (scene->paused ? " paused the scene" : " resumed the scene")); + } + else if (event.type == "log") { + Print(FormatTime(playTime) + " " + data["log"].get()); + } + else if (event.type == "expect") { + RunExpectation(event); + } + + nextEvent++; + } + + // A live capture shows the regular step of this frame, which also gives correct motion vectors + // The job only finishes once it was rendered + if (!liveCapture && playTime >= job.duration - 1e-4f && nextEvent >= events.size()) { + for (const auto& trigger : triggers) { + if (trigger.fired) + continue; + auto message = "Conditional event never happened: " + trigger.event.data.dump(); + if (trigger.event.optional) + Warn(message); + else + checkRunner->AddFailure({ "timeline", trigger.event.type, playTime, message }); + } + checkRunner->Run(*scene, playTime); + if (tracker) + tracker->Record(*scene, playTime); + phase = Phase::Finish; + return; + } + + // The observer is the main camera during the update, culling, shadows and terrain LODs + // are computed for the main camera. Scripts access their camera through their entity + playerInput.Update(*scene, job.fixedDeltaTime); + UpdateSceneWithCaptureCamera(*activeCamera); + playTime += job.fixedDeltaTime; + + if (playTime + 1e-4f >= nextCheckTime) { + checkRunner->Run(*scene, playTime); + nextCheckTime += job.checks.interval; + } + if (tracker && playTime + 1e-4f >= nextTrackTime) { + tracker->Record(*scene, playTime); + nextTrackTime += tracker->spec.interval; + } + + } + + void App::UpdateTriggers() { + + std::vector due; + for (auto& trigger : triggers) { + const auto& when = *trigger.event.when; + if (!trigger.metTime && playTime + 1e-4f >= trigger.event.time) { + bool passed = trigger.logMatched; + if (!when.contains("log")) + EvaluateExpectation(*scene, when, passed); + if (passed) { + trigger.metTime = playTime; + Print(FormatTime(playTime) + " condition met: " + when.dump()); + } + } + + if (trigger.metTime && !trigger.fired && playTime + 1e-4f >= *trigger.metTime + trigger.event.delay) { + trigger.fired = true; + auto event = trigger.event; + event.time = playTime; + due.push_back(event); + } + } + + // Due events run in this frame before the timed events of the frame + events.insert(events.begin() + nextEvent, due.begin(), due.end()); + + } + + void App::UpdateStill() { + + auto wasPaused = scene->paused; + scene->paused = true; + UpdateSceneWithCaptureCamera(stillState.camera, freezeDeltaTime); + scene->paused = wasPaused; + + if (!stillState.requested) { + if (stillState.settledFrames++ < stillState.settleFrames) + return; + + RequestCapture(stillState.request); + stillState.requested = true; + return; + } + + if (HasPendingCaptures()) + return; + + captureRenderer.InvalidateHistory(); + stillState = StillState {}; + + } + + void App::WriteProfile() { + + auto threads = Graphics::Profiler::GetQueriesAverage(uint32_t(job.profileFrames)); + + json queries = json::array(); + std::function addQuery = + [&](const Graphics::Profiler::Query& query, const std::string& parent, int32_t depth) { + + auto path = parent.empty() ? query.name : parent + " / " + query.name; + auto milliseconds = double(query.timer.elapsedTime) / 1000000.0; + queries.push_back( + { { "query", path }, { "depth", depth }, { "ms", std::round(milliseconds * 10000.0) / 10000.0 } }); + for (const auto& child : query.children) + addQuery(child, path, depth + 1); + + }; + + json profile; + profile["frames"] = job.profileFrames; + for (const auto& thread : threads) { + queries = json::array(); + double total = 0.0; + for (const auto& query : thread.queries) { + total += double(query.timer.elapsedTime) / 1000000.0; + addQuery(query, "", 0); + } + profile["threads"].push_back( + { { "thread", thread.name }, { "ms", std::round(total * 10000.0) / 10000.0 }, { "queries", queries } }); + + Print("GPU " + thread.name + ": " + FormatFloat(float(total), 3) + " ms per frame"); + for (const auto& query : queries) + if (query["depth"].get() <= 1 && query["ms"].get() >= 0.05) + Print( + " " + FormatFloat(query["ms"].get(), 3) + " ms " + query["query"].get()); + } + + WriteJson("profile.json", profile); + + } + + void App::WriteValidationReport() { + + std::lock_guard lock(validationMutex); + + // Errors first, then the most frequent messages + std::vector> sorted(validationMessages.begin(), validationMessages.end()); + std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { + + bool aError = a.second.severity == "error", bError = b.second.severity == "error"; + if (aError != bError) + return aError; + return a.second.count > b.second.count; + + }); + + json messages = json::array(); + std::map counts = { { "error", 0 }, { "warning", 0 }, { "performance", 0 } }; + for (const auto& [id, message] : sorted) { + messages.push_back({ { "id", id }, { "severity", message.severity }, { "count", message.count }, + { "message", message.message } }); + counts[message.severity]++; + } + + json summary = { { "errors", counts["error"] }, { "warnings", counts["warning"] }, + { "performance", counts["performance"] } }; + WriteJson("validation.json", { { "summary", summary }, { "messages", messages } }); + report["validation"] = summary; + + Print("Validation: " + std::to_string(counts["error"]) + " errors, " + std::to_string(counts["warning"]) + + " warnings, " + std::to_string(counts["performance"]) + " performance warnings (distinct ids)"); + for (const auto& [id, message] : sorted) { + if (message.severity == "error") + Print("VALIDATION " + id + " (" + std::to_string(message.count) + "x)"); + } + + } + + VkBool32 App::ValidationCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* data, void* userData) { + + auto app = static_cast(userData); + auto id = data->pMessageIdName ? std::string(data->pMessageIdName) : std::to_string(data->messageIdNumber); + + std::lock_guard lock(app->validationMutex); + auto& message = app->validationMessages[id]; + if (message.count++ == 0) { + if (severity == VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT) + message.severity = "error"; + else + message.severity = type & VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT ? "performance" : "warning"; + // Contains the involved objects with their debug names + message.message = data->pMessage; + } + + return VK_FALSE; + + } + + void App::Finish() { + + for (const auto& group : sheetOrder) { + auto& sheet = sheets[group]; + if (sheet.images.empty()) + continue; + + auto image = ComposeSheet(sheet.images, sheet.labels, sheet.columns, sheet.title); + if (WritePng(image, sheet.path)) + outputs.push_back(fs::relative(sheet.path, job.outputDirectory).generic_string()); + } + + if (tracker) + WriteJson("trace.json", tracker->GetTrace()); + + if (job.profileFrames > 0) + WriteProfile(); + + if (validationMessenger != VK_NULL_HANDLE) + WriteValidationReport(); + + if (fatal) + jobExitCode = 2; + else if ((checkRunner && checkRunner->HasFailures()) || expectationFailed) + jobExitCode = 1; + else + jobExitCode = 0; + + std::string reason; + if (fatal) + reason = errors.empty() ? "unknown error" : errors.front(); + else if (jobExitCode == 1) { + size_t failedExpectations = + std::count_if(expectations.begin(), expectations.end(), [](const json& expectation) { + + return !expectation["passed"].get(); + + }); + auto failedChecks = checkRunner ? checkRunner->GetSummary().size() : size_t(0); + reason = std::to_string(failedChecks) + " failed checks, " + std::to_string(failedExpectations) + + " failed expectations"; + } + + report["job"] = job.name; + report["runId"] = runId; + report["scene"] = job.scene; + report["status"] = jobExitCode == 0 ? "passed" : (jobExitCode == 1 ? "failed" : "error"); + report["exitCode"] = jobExitCode; + if (!reason.empty()) + report["reason"] = reason; + report["loadSeconds"] = loadSeconds; + report["frames"] = frameCount; + report["totalSeconds"] = std::chrono::duration(std::chrono::steady_clock::now() - startTime).count(); + report["errors"] = errors; + report["warnings"] = warnings; + report["engineLogErrors"] = logErrorCount; + if (checkRunner) + report["checks"] = checkRunner->GetReport(); + if (!expectations.empty()) + report["expectations"] = expectations; + if (job.play) + report["playedSeconds"] = playTime; + if (!triggers.empty()) { + json triggerReport = json::array(); + for (const auto& trigger : triggers) + triggerReport.push_back({ { "event", trigger.event.data }, { "fired", trigger.fired }, + { "conditionMetAt", trigger.metTime ? json(*trigger.metTime) : json() } }); + report["conditionalEvents"] = triggerReport; + } + report["outputs"] = outputs; + + WriteJson("report.json", report); + reportWritten = true; + + Print("---------------------------------------------"); + Print("Status: " + report["status"].get() + (reason.empty() ? "" : " (" + reason + ")")); + if (checkRunner) { + for (const auto& line : checkRunner->GetSummary()) + Print("FAILED " + line); + } + for (const auto& expectation : expectations) + if (!expectation["passed"].get()) + Print("FAILED expectation " + expectation.dump()); + for (const auto& error : errors) + Print("ERROR " + error); + Print("Outputs in " + job.outputDirectory.string() + ":"); + for (const auto& output : outputs) + Print(" " + output.get()); + + phase = Phase::Done; + ReleaseLock(); + Exit(jobExitCode); + + } + + void App::UpdateSceneWithCaptureCamera(const CameraSpec& spec, float deltaTime) { + + bool useCaptureCamera = UsesCaptureCamera(spec); + if (useCaptureCamera) + ApplyCameraSpec(spec); + + // Override main-camera flags only during the scene update + std::vector> mainStates; + auto cameraSubset = scene->GetSubset(); + if (useCaptureCamera) { + for (auto entity : cameraSubset) { + auto& camera = cameraSubset.Get(entity); + mainStates.emplace_back(entity, camera.isMain); + camera.isMain = entity == ECS::Entity(captureCameraEntity); + } + } + + scene->Update(deltaTime < 0.0f ? job.fixedDeltaTime : deltaTime); + + for (auto [entity, isMain] : mainStates) + cameraSubset.Get(entity).isMain = isMain; + + } + + bool App::UsesCaptureCamera(const CameraSpec& spec) const { + + if (spec.mode != "scene") + return true; + + // Scenes without a main camera of their own are shown from an overview + auto cameraSubset = scene->GetSubset(); + for (auto entity : cameraSubset) { + if (entity != ECS::Entity(captureCameraEntity) && cameraSubset.Get(entity).isMain) + return false; + } + + return true; + } + + void App::ApplyCameraSpec(const CameraSpec& spec) { + + auto& camera = captureCameraEntity.GetComponent(); + camera.aspectRatio = float(job.resolution.x) / float(job.resolution.y); + camera.fieldOfView = spec.fieldOfView; + camera.nearPlane = spec.nearPlane; + camera.farPlane = spec.farPlane; + + vec3 position = camera.location; + std::optional target; + float yaw = glm::radians(spec.yaw), pitch = glm::radians(spec.pitch); + + auto mode = spec.mode == "scene" ? std::string("overview") : spec.mode; + + if (mode == "manual") { + position = spec.position; + target = spec.lookAt; + } + else if (mode == "focus" || mode == "overview") { + Volume::AABB bounds; + float entityYaw = 0.0f; + EntitySet focused; + if (mode == "focus") { + auto entities = RemoveDescendants(*scene, FindEntities(*scene, spec.entity)); + if (entities.empty()) { + // Entities created by scripts might not exist yet while loading or playing + if (phase == Phase::Play || phase == Phase::Loading) + return; + throw std::runtime_error("Camera focus: no entity matches '" + spec.entity + "'"); + } + bounds = GetBounds(entities); + entityYaw = glm::degrees(GetEntityYaw(entities.front())); + for (auto entity : entities) + CollectHierarchy(entity, focused); + } + else { + bounds = GetSceneBounds(*scene); + } + + auto angles = GetViewAngles(spec.view.empty() ? (mode == "overview" ? "iso" : "front") : spec.view); + auto azimuth = spec.azimuth.value_or(angles.azimuth) + (spec.local ? entityYaw : 0.0f); + auto elevation = spec.elevation.value_or(angles.elevation); + + auto az = glm::radians(azimuth), el = glm::radians(elevation); + auto direction = vec3(cos(el) * sin(az), sin(el), cos(el) * cos(az)); + + auto center = bounds.GetCenter(); + auto radius = std::max(glm::length(bounds.GetSize()) * 0.5f, 0.25f); + + // Fit the bounding sphere into the smaller of the two field of view angles + auto halfFov = glm::radians(spec.fieldOfView) * 0.5f; + auto halfFovHorizontal = std::atan(std::tan(halfFov) * camera.aspectRatio); + auto distance = spec.distance > 0.0f ? + spec.distance : + radius * spec.padding / std::sin(std::min(halfFov, halfFovHorizontal)); + + // Prefer nearby unobstructed angles before reducing the camera distance + if (mode == "focus" && spec.avoidOcclusion) { + static const vec2 angleOffsets[] = { { 0.0f, 0.0f }, { 0.0f, 15.0f }, { 20.0f, 10.0f }, + { -20.0f, 10.0f }, { 0.0f, 30.0f }, { 40.0f, 20.0f }, { -40.0f, 20.0f }, { 0.0f, 50.0f }, + { 0.0f, -10.0f } }; + + // Sample corners as well as the center to account for partial occlusion + std::vector samples = { center }; + for (auto corner : bounds.GetCorners()) { + samples.push_back(glm::mix(corner, center, 0.1f)); + } + + auto countVisible = [&](vec3 cameraPosition) { + + int32_t visible = 0; + for (auto sample : samples) { + auto toSample = sample - cameraPosition; + auto length = glm::length(toSample); + if (length < 1e-4f || + !Raycast(*scene, cameraPosition, toSample / length, length, focused).valid) + visible++; + } + return visible; + + }; + + auto bestDirection = direction; + auto bestVisible = 0; + for (auto offset : angleOffsets) { + auto a = glm::radians(azimuth + offset.x); + auto e = glm::radians(glm::clamp(elevation + offset.y, -80.0f, 89.0f)); + auto candidate = vec3(cos(e) * sin(a), sin(e), cos(e) * cos(a)); + + auto visible = countVisible(center + candidate * distance); + if (visible > bestVisible) { + bestVisible = visible; + bestDirection = candidate; + } + if (visible == int32_t(samples.size())) + break; + } + + if (bestVisible > 0) { + direction = bestDirection; + } + else { + // Moving closer only helps if the camera stays outside of the focused bounds, + // otherwise the requested view is kept even though it's occluded + auto hit = Raycast(*scene, center, direction, distance, focused); + if (hit.valid && hit.distance - 0.25f > radius) + distance = hit.distance - 0.25f; + } + } + + position = center + direction * distance; + target = center; + camera.farPlane = std::max(spec.farPlane, distance + radius * 4.0f); + } + else if (mode == "follow") { + auto entities = RemoveDescendants(*scene, FindEntities(*scene, spec.entity)); + if (entities.empty()) + return; + + auto bounds = GetEntityBounds(entities.front()); + auto center = bounds.GetCenter(); + auto offset = spec.offset; + if (spec.local) + offset = vec3(glm::rotate(GetEntityYaw(entities.front()), vec3(0.0f, 1.0f, 0.0f)) * vec4(offset, 0.0f)); + + position = center + offset; + target = center; + } + + if (target && glm::distance(*target, position) > 1e-4f) { + auto direction = glm::normalize(*target - position); + yaw = std::atan2(direction.x, direction.z); + pitch = std::asin(glm::clamp(direction.y, -1.0f, 1.0f)); + } + + camera.location = position; + camera.rotation = vec2(yaw, pitch); + + } + + void App::RequestCapture(const CaptureRequest& request) { + + captureRequests.push_back(request); + + } + + bool App::HasPendingCaptures() const { + + return !captureRequests.empty() || !pendingReadbacks.empty(); + } + + void App::ProcessReadback() { + + if (pendingReadbacks.empty()) + return; + + auto requests = std::move(pendingReadbacks); + pendingReadbacks.clear(); + + // All requests of a frame were rendered into the same image + auto image = captureRenderer.ReadOutput(); + std::map> passImages; + + for (const auto& request : requests) { + if (!WritePng(image, request.path)) { + Fail("Couldn't write " + request.path.string()); + continue; + } + + auto relative = fs::relative(request.path, job.outputDirectory).generic_string(); + outputs.push_back(relative); + Print("Captured " + relative + (phase == Phase::Play ? " at " + FormatTime(request.time) : "")); + + if (!request.group.empty()) + AddToSheet(request.group, image, request.label); + + if (auto it = variantCaptures.find(request.path.string()); it != variantCaptures.end()) + AddToSheet(it->second.first, image, it->second.second); + + if (request.passes.empty()) + continue; + + auto stem = request.path.parent_path() / request.path.stem(); + auto group = fs::relative(stem, job.outputDirectory).generic_string() + "_passes"; + sheets[group] = { .title = relative + " passes", .path = job.outputDirectory / (group + ".png") }; + sheetOrder.push_back(group); + AddToSheet(group, image, "lit"); + + for (const auto& pass : request.passes) { + if (!passImages.contains(pass)) + passImages[pass] = captureRenderer.ReadPass(pass); + + auto passPath = fs::path(stem.string() + "_" + pass + ".png"); + if (WritePng(passImages[pass], passPath)) + outputs.push_back(fs::relative(passPath, job.outputDirectory).generic_string()); + AddToSheet(group, passImages[pass], pass); + } + } + + } + + void App::AddToSheet(const std::string& group, const Ref& image, const std::string& label) { + + auto& sheet = sheets[group]; + // Only the downscaled version is needed for the sheet + sheet.images.push_back(Downscale(image, 640)); + sheet.labels.push_back(label); + + } + + void App::WriteJson(const std::string& fileName, const json& j) { + + auto path = job.outputDirectory / fileName; + fs::create_directories(path.parent_path()); + + if (!WriteFileAtomic(path, j.dump(2))) + Warn("Couldn't write " + path.string()); + + outputs.push_back(fileName); + + } + + void App::RunExpectation(const EventSpec& event) { + + bool passed = false; + auto result = EvaluateExpectation(*scene, event.data["expect"], passed); + result["t"] = playTime; + result["passed"] = passed; + expectations.push_back(result); + + if (!passed) + expectationFailed = true; + + Print(FormatTime(playTime) + " expectation " + (passed ? "passed: " : "FAILED: ") + result.dump()); + + } + + void App::SetLookDirection(Scene::Entity entity, const json& look) { + + auto camera = entity.TryGetComponent(); + if (!camera) { + // Entities without a camera (e.g. driven by a script) are turned around the world Y axis instead + auto transform = entity.TryGetComponent(); + if (!transform || !look.contains("yaw")) { + Warn(GetEntityLabel(entity) + " has no camera, only the yaw of its transform can be set"); + return; + } + + auto parentMatrix = transform->globalMatrix * glm::inverse(transform->matrix); + auto global = glm::translate(vec3(transform->globalMatrix[3])) * + glm::rotate(glm::radians(look["yaw"].get()), vec3(0.0f, 1.0f, 0.0f)); + transform->Set(glm::inverse(parentMatrix) * global); + transform->globalMatrix = global; + Print(FormatTime(playTime) + " " + GetEntityLabel(entity) + " turned to yaw " + + FormatFloat(look["yaw"].get(), 1)); + return; + } + + // Yaw 0 looks towards +Z, 90 towards +X + if (look.contains("yaw")) + camera->rotation.x = glm::radians(look["yaw"].get()); + if (look.contains("pitch")) + camera->rotation.y = glm::radians(look["pitch"].get()); + + Print(FormatTime(playTime) + " " + GetEntityLabel(entity) + " looks at yaw " + + FormatFloat(glm::degrees(camera->rotation.x), 1) + ", pitch " + + FormatFloat(glm::degrees(camera->rotation.y), 1)); + + } + + void App::BuildOverlay() { + + overlay->Clear(); + if (!job.overlay) + return; + + const auto& spec = *job.overlay; + overlay->depthTest = spec.depthTest; + + for (auto entity : RemoveDescendants(*scene, FindEntities(*scene, spec.bounds))) + overlay->Box(GetEntityBounds(entity), vec3(1.0f, 0.85f, 0.1f)); + + if (spec.players) { + auto playerSubset = scene->GetSubset(); + for (auto entity : playerSubset) + overlay->Figure(GetEntityPosition(entity), 1.8f, 0.35f, vec3(0.1f, 0.9f, 1.0f)); + } + + if (spec.trails && tracker) { + for (const auto& [label, samples] : tracker->GetSamples()) + for (size_t i = 1; i < samples.size(); i++) + overlay->Line(samples[i - 1].position, samples[i].position, vec3(1.0f, 0.2f, 0.9f)); + } + + if (spec.queries) { + for (const auto& result : queryResults) { + const auto& query = result["query"]; + if (!result.contains("result")) + continue; + const auto& hit = result["result"]; + auto type = query.value("type", std::string()); + + if (type == "pick") { + for (const auto& pick : hit) + if (pick.value("hit", false)) + overlay->Cross(ToVec3(pick["position"]), 0.3f, vec3(1.0f, 1.0f, 0.2f)); + continue; + } + if (!hit.is_object()) + continue; + + if (type == "raycast") { + auto origin = ToVec3(query["origin"]); + auto end = hit.value("hit", false) ? + ToVec3(hit["position"]) : + origin + glm::normalize(ToVec3(query["direction"])) * query.value("maxDistance", 4096.0f); + overlay->Line( + origin, end, hit.value("hit", false) ? vec3(0.2f, 1.0f, 0.2f) : vec3(1.0f, 0.2f, 0.2f)); + } + if ((type == "raycast" || type == "ground") && hit.value("hit", false)) + overlay->Cross(ToVec3(hit["position"]), 0.3f, vec3(0.2f, 1.0f, 0.2f)); + if (type == "path") { + const auto& samples = hit["samples"]; + for (size_t i = 1; i < samples.size(); i++) + overlay->Line(ToVec3(samples[i - 1]["position"]) + vec3(0.0f, 0.05f, 0.0f), + ToVec3(samples[i]["position"]) + vec3(0.0f, 0.05f, 0.0f), vec3(0.2f, 1.0f, 0.2f)); + for (const auto& issue : hit["issues"]) + overlay->Cross(ToVec3(issue["at"]), 0.4f, vec3(1.0f, 0.15f, 0.15f)); + } + } + } + + for (const auto& marker : spec.markers) + overlay->Cross(ToVec3(marker.at("position")), marker.value("size", 0.5f), + ToVec3(marker.value("color", json()), vec3(1.0f, 0.3f, 0.1f))); + + for (const auto& axes : spec.axes) + overlay->Axes(axes, 2.0f); + + } + + void App::FireKey(const std::string& key, bool down) { + + auto keyCode = SDL_GetKeyFromName(key.c_str()); + if (keyCode == SDLK_UNKNOWN) + throw std::runtime_error("Unknown key '" + key + "', use SDL key names like E, Space, Left Shift, Up"); + + SDL_KeyboardEvent event = {}; + event.type = down ? SDL_KEYDOWN : SDL_KEYUP; + event.state = down ? SDL_PRESSED : SDL_RELEASED; + event.repeat = 0; + event.keysym.sym = keyCode; + event.keysym.scancode = SDL_GetScancodeFromKey(keyCode); + + Events::EventManager::KeyboardEventDelegate.Fire(Events::KeyboardEvent(event)); + + } + +} + +Atlas::EngineInstance* GetEngineInstance() { + + return new Atlas::Capture::App(); + +} diff --git a/src/capture/App.h b/src/capture/App.h new file mode 100644 index 000000000..049cff4fd --- /dev/null +++ b/src/capture/App.h @@ -0,0 +1,238 @@ +#pragma once + +#include "Job.h" +#include "CaptureRenderer.h" +#include "Checks.h" +#include "SceneTools.h" +#include "Overlay.h" + +#include "EngineInstance.h" +#include "input/PlayerInput.h" + +#include +#include +#include +#include +#include + +namespace Atlas::Capture { + + class App : public EngineInstance { + + public: + App() : EngineInstance("Atlas Engine Capture", 1280, 720, AE_WINDOW_HIDDEN) {} + + void LoadContent() final; + + void UnloadContent() final; + + void Update(float deltaTime) final; + + void Render(float deltaTime) final; + + private: + enum class Phase { + Loading, + Prepare, + EditSave, + Shots, + Play, + Finish, + Done + }; + + struct CaptureRequest { + + std::string group; + std::string label; + fs::path path; + std::vector passes; + float time = 0.0f; + + }; + + struct SheetGroup { + + std::string title; + int32_t columns = 0; + fs::path path; + std::vector> images; + std::vector labels; + + }; + + struct ShotState { + + size_t variant = 0; + size_t shot = 0; + size_t view = 0; + int32_t settledFrames = 0; + bool requested = false; + + }; + + struct Trigger { + + EventSpec event; + bool logMatched = false; + std::optional metTime; + bool fired = false; + + }; + + struct StillState { + + bool active = false; + CameraSpec camera; + CaptureRequest request; + int32_t settleFrames = 0; + int32_t settledFrames = 0; + bool requested = false; + + }; + + struct ValidationMessage { + std::string severity; + std::string message; + int32_t count = 0; + }; + + void Fail(const std::string& message); + + void Warn(const std::string& message); + + void Print(const std::string& message); + + void CollectLog(); + + bool IsSceneReady(); + + void Prepare(); + + void FinishEdit(); + + void UpdateShots(); + + void StartPlay(); + + void UpdatePlay(); + + void UpdateStill(); + + // Checks the conditions of conditional events and queues the events that are due + void UpdateTriggers(); + + // Writes the GPU timings averaged over the last frames to profile.json and prints the most expensive ones + void WriteProfile(); + + // Writes the validation messages grouped by their id to validation.json + void WriteValidationReport(); + + void Finish(); + + // Updates the scene while the capture camera is the main camera. A negative delta + // time uses the fixed delta time of the job + void UpdateSceneWithCaptureCamera(const CameraSpec& spec, float deltaTime = -1.0f); + + void ApplyCameraSpec(const CameraSpec& spec); + + bool UsesCaptureCamera(const CameraSpec& spec) const; + + void RequestCapture(const CaptureRequest& request); + + bool HasPendingCaptures() const; + + void ProcessReadback(); + + void AddToSheet(const std::string& group, const Ref& image, const std::string& label); + + void WriteJson(const std::string& fileName, const json& j); + + void RunExpectation(const EventSpec& event); + + void FireKey(const std::string& key, bool down); + + void BuildOverlay(); + + void SetLookDirection(Scene::Entity entity, const json& look); + + // Presents the frame, in a shown window with a status line and the latest output below it + void PresentWindow(); + + std::string GetStatusLine() const; + + static VKAPI_ATTR VkBool32 VKAPI_CALL ValidationCallback(VkDebugUtilsMessageSeverityFlagBitsEXT severity, + VkDebugUtilsMessageTypeFlagsEXT type, const VkDebugUtilsMessengerCallbackDataEXT* data, void* userData); + + Job job; + Phase phase = Phase::Loading; + bool fatal = false; + + Ref scene; + Scene::Entity captureCameraEntity; + + CaptureRenderer captureRenderer; + + std::optional activeCamera; + + // All requests of a frame share the same rendered image + std::vector captureRequests; + std::vector pendingReadbacks; + std::map sheets; + std::vector sheetOrder; + + ShotState shotState; + StillState stillState; + json baseSettings; + int32_t editFrames = 0; + + // Capture path -> (sheet group, label) for the comparison of variants + std::map> variantCaptures; + std::map stripCameras; + + float playTime = 0.0f; + size_t nextEvent = 0; + std::vector events; + std::vector triggers; + std::vector> pendingKeyReleases; + float nextCheckTime = 0.0f; + float nextTrackTime = 0.0f; + + Input::PlayerInput playerInput; + std::unique_ptr overlay; + json queryResults = json::array(); + + std::unique_ptr checkRunner; + std::unique_ptr tracker; + + json report; + json outputs = json::array(); + json expectations = json::array(); + std::vector errors; + std::vector warnings; + bool expectationFailed = false; + + std::ofstream logFile; + size_t logIndex = 0; + int32_t logErrorCount = 0; + + // Message id -> message, the validation layers call back from any thread + VkDebugUtilsMessengerEXT validationMessenger = VK_NULL_HANDLE; + std::map validationMessages; + std::mutex validationMutex; + + int32_t frameCount = 0; + int32_t readyFrame = -1; + int32_t rtWaitFrames = 0; + std::chrono::steady_clock::time_point startTime; + float loadSeconds = 0.0f; + + // Shown window: output panel and playback in real time + static constexpr size_t outputLineCount = 12; + Ref font; + std::deque outputLines; + std::chrono::steady_clock::time_point playStartTime; + + }; + +} diff --git a/src/capture/CMakeLists.txt b/src/capture/CMakeLists.txt new file mode 100644 index 000000000..05e567b00 --- /dev/null +++ b/src/capture/CMakeLists.txt @@ -0,0 +1,44 @@ +cmake_minimum_required(VERSION 3.25) + +project(AtlasEngineCapture VERSION 0.2.1) + +# Note: For this project, the root CMakeLists.txt turns the ATLAS_EXPORT_MAIN option on. +# The capture tool only uses the public engine API, it doesn't need ImGui. + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/) + +file(GLOB_RECURSE CAPTURE_SOURCE_FILES + "*.cpp" + "*.c" + "*.h" + "*.hpp" + ) + +# Required: Set both the source and dependency directories +# as include directories +include_directories(../engine) +include_directories(../../libs) + +foreach(SOURCE_FILE IN ITEMS ${CAPTURE_SOURCE_FILES}) + if (IS_ABSOLUTE "${SOURCE_FILE}") + file(RELATIVE_PATH SOURCE_FILE_REL "${CMAKE_CURRENT_SOURCE_DIR}" "${SOURCE_FILE}") + else() + set(SOURCE_FILE_REL "${SOURCE_FILE}") + endif() + get_filename_component(SOURCE_PATH "${SOURCE_FILE_REL}" PATH) + string(REPLACE "/" "\\" SOURCE_PATH_CONVERTED "${SOURCE_PATH}") + source_group("${SOURCE_PATH_CONVERTED}" FILES "${SOURCE_FILE}") +endforeach() + +# We want to make sure that the linker searches for local libraries first +if (UNIX AND NOT APPLE AND NOT ANDROID) +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath='$ORIGIN'") +endif() +# Need to reference the vulkan SDK for MacOS to search at runtime +if (APPLE) +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,'/usr/local/lib'") +endif() + +add_executable(${PROJECT_NAME} ${CAPTURE_SOURCE_FILES} ${ATLAS_ENGINE_MAIN_FILE}) +target_compile_definitions(${PROJECT_NAME} PUBLIC ${ATLAS_ENGINE_COMPILE_DEFINITIONS}) +target_link_libraries(${PROJECT_NAME} AtlasEngine) diff --git a/src/capture/CaptureRenderer.cpp b/src/capture/CaptureRenderer.cpp new file mode 100644 index 000000000..297dea0a8 --- /dev/null +++ b/src/capture/CaptureRenderer.cpp @@ -0,0 +1,245 @@ +#include "CaptureRenderer.h" + +#include "graphics/GraphicsDevice.h" +#include + +#include + +namespace Atlas::Capture { + + void CaptureRenderer::Init(Ref mainRenderer, ivec2 resolution) { + + this->mainRenderer = mainRenderer; + this->resolution = resolution; + + renderTarget = CreateRef(resolution.x, resolution.y); + viewport = CreateRef(0, 0, resolution.x, resolution.y); + + // Post-processing output is already tone mapped and gamma corrected + outputTexture = CreateRef(resolution.x, resolution.y, VK_FORMAT_R16G16B16A16_SFLOAT); + + auto device = Graphics::GraphicsDevice::DefaultDevice; + // Passes keep negative values, e.g. of the velocity + auto colorAttachment = Graphics::RenderPassColorAttachment { + .imageFormat = VK_FORMAT_R16G16B16A16_SFLOAT, + .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR, + .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, + .outputLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, + }; + passRenderPass = device->CreateRenderPass(Graphics::RenderPassDesc { .colorAttachments = { colorAttachment } }); + + } + + void CaptureRenderer::Render(const Ref& scene, const std::vector& passes, + std::span> primitiveBatches) { + + mainRenderer->RenderScene(viewport, renderTarget, scene, primitiveBatches, outputTexture.get()); + hasFrame = true; + + float exposure = scene->HasMainCamera() ? scene->GetMainCamera().exposure : 1.0f; + for (const auto& pass : passes) + RenderPass(pass, exposure); + + } + + void CaptureRenderer::Present(const Ref& font, const std::vector& lines) { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto commandList = device->GetCommandList(); + + commandList->BeginCommands(); + device->swapChain->colorClearValue.color = { 0.0f, 0.0f, 0.0f, 1.0f }; + commandList->BeginRenderPass(device->swapChain, true); + + auto extent = device->swapChain->extent; + auto windowViewport = CreateRef(0, 0, int32_t(extent.width), int32_t(extent.height)); + auto panelHeight = font && !lines.empty() ? GetPanelHeight(font, lines.size()) : 0.0f; + + if (hasFrame && outputTexture->image->layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) { + // Keep the aspect ratio of the capture in the area above the panel + auto areaWidth = float(extent.width); + auto areaHeight = std::max(float(extent.height) - panelHeight, 1.0f); + auto scale = std::min(areaWidth / float(outputTexture->width), areaHeight / float(outputTexture->height)); + auto width = float(outputTexture->width) * scale; + auto height = float(outputTexture->height) * scale; + // The texture renderer places the image from the bottom and needs to flip it + mainRenderer->textureRenderer.RenderTexture2D(commandList, windowViewport, outputTexture.get(), + (areaWidth - width) * 0.5f, panelHeight + (areaHeight - height) * 0.5f, width, height, 0.0f, 1.0f, + false, true); + } + + if (panelHeight > 0.0f) { + auto y = float(extent.height) - panelHeight + panelPadding; + for (const auto& line : lines) { + mainRenderer->textRenderer.Render( + commandList, windowViewport, font, line.text, panelPadding, y, line.color); + y += font->lineHeight; + } + } + + commandList->EndRenderPass(); + commandList->EndCommands(); + + device->SubmitCommandList(commandList); + + } + + float CaptureRenderer::GetPanelHeight(const Ref& font, size_t lineCount) { + + return float(lineCount) * font->lineHeight + 2.0f * panelPadding; + + } + + Ref CaptureRenderer::ReadOutput() { + + auto data = outputTexture->GetData(); + + // Images don't support half floats, the output goes through a float image + Common::Image floatImage(outputTexture->width, outputTexture->height, 4); + auto& floatData = floatImage.GetData(); + std::transform(data.begin(), data.end(), floatData.begin(), [](float16 value) { + + return glm::detail::toFloat32(value); + + }); + // The alpha channel isn't meaningful, write opaque images + for (size_t i = 3; i < floatData.size(); i += 4) + floatData[i] = 1.0f; + + auto image = CreateImage(outputTexture->width, outputTexture->height); + image->SetData(floatImage.ConvertData()); + + return image; + + } + + Ref CaptureRenderer::ReadPass(const std::string& pass) { + + auto& target = GetPassTarget(pass); + auto data = target.texture->GetData(); + + Common::Image floatImage(target.texture->width, target.texture->height, 4); + auto& floatData = floatImage.GetData(); + std::transform(data.begin(), data.end(), floatData.begin(), [](float16 value) { + + return glm::detail::toFloat32(value); + + }); + + for (size_t i = 0; i < floatData.size(); i += 4) { + // Signed screen space motion, no motion is gray + if (pass == "velocity") { + floatData[i] = 0.5f + 0.5f * floatData[i]; + floatData[i + 1] = 0.5f + 0.5f * floatData[i + 1]; + floatData[i + 2] = 0.5f; + } + floatData[i + 3] = 1.0f; + } + + auto image = CreateImage(target.texture->width, target.texture->height); + image->SetData(floatImage.ConvertData()); + + return image; + + } + + const std::vector& CaptureRenderer::GetPassNames() { + + static const std::vector names = { "albedo", "normal", "geometryNormal", "roughness", "emissive", + "depth", "velocity", "stencil", "materialIdx", "reflection", "volumetric", "clouds", "sss", "gi" }; + return names; + + } + + void CaptureRenderer::RenderPass(const std::string& pass, float exposure) { + + auto device = Graphics::GraphicsDevice::DefaultDevice; + auto& target = GetPassTarget(pass); + auto rtData = renderTarget->GetData(Renderer::RenderResolution::FULL_RES); + + Texture::Texture2D* texture = nullptr; + float scale = 1.0f; + if (pass == "albedo") + texture = rtData->baseColorTexture.get(); + else if (pass == "normal") + texture = rtData->normalTexture.get(); + else if (pass == "geometryNormal") + texture = rtData->geometryNormalTexture.get(); + else if (pass == "roughness") + texture = rtData->roughnessMetallicAoTexture.get(); + else if (pass == "emissive") + texture = rtData->emissiveTexture.get(); + else if (pass == "depth") + texture = rtData->depthTexture.get(); + else if (pass == "velocity") { + texture = rtData->velocityTexture.get(); + scale = 100.0f; + } + else if (pass == "stencil") { + texture = rtData->stencilTexture.get(); + scale = 1.0f / 255.0f; + } + else if (pass == "materialIdx") { + texture = rtData->materialIdxTexture.get(); + scale = 1.0f / 10000.0f; + } + else if (pass == "reflection") { + texture = &renderTarget->reflectionTexture; + scale = exposure; + } + else if (pass == "volumetric") { + texture = &renderTarget->volumetricTexture; + scale = exposure; + } + else if (pass == "clouds") { + texture = &renderTarget->volumetricCloudsTexture; + scale = exposure; + } + else if (pass == "sss") + texture = &renderTarget->sssTexture; + else if (pass == "gi") { + texture = &renderTarget->giTexture; + scale = exposure; + } + + if (!texture) + return; + + auto commandList = device->GetCommandList(Graphics::GraphicsQueue); + commandList->BeginCommands(); + commandList->BeginRenderPass(passRenderPass, target.frameBuffer, true); + + mainRenderer->textureRenderer.RenderTexture2D(commandList, viewport, texture, 0.0f, 0.0f, + float(viewport->width), float(viewport->height), 0.0f, scale, false, true); + + commandList->EndRenderPass(); + commandList->ImageMemoryBarrier(target.texture->image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, + VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT); + commandList->EndCommands(); + + device->SubmitCommandList(commandList); + + } + + CaptureRenderer::PassTarget& CaptureRenderer::GetPassTarget(const std::string& pass) { + + if (std::find(GetPassNames().begin(), GetPassNames().end(), pass) == GetPassNames().end()) + throw std::runtime_error("Unknown pass '" + pass + "'"); + + auto it = passTargets.find(pass); + if (it != passTargets.end()) + return it->second; + + auto device = Graphics::GraphicsDevice::DefaultDevice; + + PassTarget target; + target.texture = CreateRef(resolution.x, resolution.y, VK_FORMAT_R16G16B16A16_SFLOAT); + target.frameBuffer = device->CreateFrameBuffer(Graphics::FrameBufferDesc { .renderPass = passRenderPass, + .colorAttachments = { { target.texture->image, 0, true } }, + .extent = { uint32_t(resolution.x), uint32_t(resolution.y) } }); + + return passTargets[pass] = target; + + } + +} diff --git a/src/capture/CaptureRenderer.h b/src/capture/CaptureRenderer.h new file mode 100644 index 000000000..016ee3966 --- /dev/null +++ b/src/capture/CaptureRenderer.h @@ -0,0 +1,82 @@ +#pragma once + +#include "Common.h" +#include "Image.h" + +#include "Viewport.h" +#include "Font.h" +#include "renderer/MainRenderer.h" +#include "texture/Texture2D.h" +#include "graphics/RenderPass.h" +#include "graphics/Framebuffer.h" + +#include + +namespace Atlas::Capture { + + // Renders a scene into an offscreen texture like the editor viewport does, + // optionally renders debug views of intermediate passes and reads everything back + class CaptureRenderer { + + public: + struct TextLine { + + std::string text; + vec4 color = vec4(1.0f); + + }; + + void Init(Ref mainRenderer, ivec2 resolution); + + void Render(const Ref& scene, const std::vector& passes, + std::span> primitiveBatches = {}); + + // Shows the last rendered frame in the (possibly hidden) window. This also keeps + // the swap chain acquire/present cycle going. Text lines are shown in a panel below the frame + void Present(const Ref& font = nullptr, const std::vector& lines = {}); + + // Height of the text panel for a number of lines + static float GetPanelHeight(const Ref& font, size_t lineCount); + + // Only valid after the frame that rendered the content has finished on the GPU + Ref ReadOutput(); + + Ref ReadPass(const std::string& pass); + + static const std::vector& GetPassNames(); + + const Ref& GetViewport() const { return viewport; } + + // Temporal effects start over, e.g. when switching to another camera while the scene is paused + void InvalidateHistory() { renderTarget->InvalidateHistory(); } + + ivec2 resolution = ivec2(0); + + private: + struct PassTarget { + + Ref texture; + Ref frameBuffer; + + }; + + void RenderPass(const std::string& pass, float exposure); + + PassTarget& GetPassTarget(const std::string& pass); + + Ref mainRenderer; + Ref renderTarget; + Ref viewport; + + Ref outputTexture; + + Ref passRenderPass; + std::map passTargets; + + bool hasFrame = false; + + static constexpr float panelPadding = 8.0f; + + }; + +} diff --git a/src/capture/Checks.cpp b/src/capture/Checks.cpp new file mode 100644 index 000000000..6dd2b634e --- /dev/null +++ b/src/capture/Checks.cpp @@ -0,0 +1,433 @@ +#include "Checks.h" + +#include + +namespace Atlas::Capture { + + using namespace Scene::Components; + + // Separating axis test against the box faces, triangle normal and edge cross products + static bool TriangleIntersectsBox(vec3 center, vec3 halfSize, vec3 a, vec3 b, vec3 c) { + + auto v0 = a - center, v1 = b - center, v2 = c - center; + vec3 edges[3] = { v1 - v0, v2 - v1, v0 - v2 }; + + auto separated = [&](vec3 axis) { + + if (glm::dot(axis, axis) < 1e-12f) + return false; + auto p0 = glm::dot(v0, axis), p1 = glm::dot(v1, axis), p2 = glm::dot(v2, axis); + auto radius = glm::dot(halfSize, glm::abs(axis)); + return std::min({ p0, p1, p2 }) > radius || std::max({ p0, p1, p2 }) < -radius; + + }; + + for (int32_t i = 0; i < 3; i++) { + vec3 boxAxis(0.0f); + boxAxis[i] = 1.0f; + if (separated(boxAxis)) + return false; + for (const auto& edge : edges) + if (separated(glm::cross(boxAxis, edge))) + return false; + } + + return !separated(glm::cross(edges[0], edges[1])); + + } + + // Counts the triangles of a mesh that intersect the given world space box + static int32_t CountIntrudingTriangles(const MeshComponent& meshComponent, const TransformComponent& transform, + const Volume::AABB& box) { + + if (!meshComponent.mesh.IsLoaded()) + return 0; + + auto& data = meshComponent.mesh->data; + auto& vertices = data.vertices.Get(); + auto& indices = data.indices.Get(); + + // Cheap rejection in local space with the conservatively transformed box + auto localBox = box.Transform(glm::inverse(transform.globalMatrix)); + auto center = box.GetCenter(), halfSize = box.GetSize() * 0.5f; + + int32_t count = 0; + for (size_t i = 0; i + 2 < indices.size(); i += 3) { + const auto& a = vertices[indices[i]]; + const auto& b = vertices[indices[i + 1]]; + const auto& c = vertices[indices[i + 2]]; + + auto min = glm::min(a, glm::min(b, c)), max = glm::max(a, glm::max(b, c)); + if (glm::any(glm::lessThan(max, localBox.min)) || glm::any(glm::greaterThan(min, localBox.max))) + continue; + + auto worldA = vec3(transform.globalMatrix * vec4(a, 1.0f)); + auto worldB = vec3(transform.globalMatrix * vec4(b, 1.0f)); + auto worldC = vec3(transform.globalMatrix * vec4(c, 1.0f)); + if (TriangleIntersectsBox(center, halfSize, worldA, worldB, worldC)) + count++; + } + + return count; + + } + + static bool MatchesSelfOrAncestor(Scene::Scene& scene, Scene::Entity entity, + const std::vector& patterns) { + + while (entity.IsValid()) { + if (MatchAnyPattern(patterns, GetEntityName(entity))) + return true; + entity = scene.GetParentEntity(entity); + } + + return false; + + } + + static bool Compare(float actual, const std::string& op, float expected, float tolerance) { + + if (op == ">") + return actual > expected; + if (op == ">=") + return actual >= expected; + if (op == "<") + return actual < expected; + if (op == "<=") + return actual <= expected; + if (op == "==") + return std::abs(actual - expected) <= tolerance; + if (op == "!=") + return std::abs(actual - expected) > tolerance; + throw std::runtime_error("Unknown comparison operator '" + op + "'"); + + } + + std::vector RemoveDescendants(Scene::Scene& scene, const std::vector& entities) { + + EntitySet contained; + for (auto entity : entities) + contained.insert(entity); + + std::vector result; + for (auto entity : entities) { + bool ancestorContained = false; + auto parent = scene.GetParentEntity(entity); + while (parent.IsValid() && !ancestorContained) { + ancestorContained = contained.contains(parent); + parent = scene.GetParentEntity(parent); + } + + if (!ancestorContained) + result.push_back(entity); + } + + return result; + + } + + void CheckRunner::Run(Scene::Scene& scene, float time) { + + if (spec.grounded) + CheckGrounded(scene, time); + if (spec.penetration) + CheckPenetration(scene, time); + if (spec.invalidTransforms) + CheckInvalidTransforms(scene, time); + + } + + void CheckRunner::AddFailure(const Failure& failure) { + + auto key = failure.check + "|" + failure.entity; + if (failureCounts[key]++ == 0) + failures.push_back(failure); + + } + + void CheckRunner::CheckGrounded(Scene::Scene& scene, float time) { + + auto entities = RemoveDescendants(scene, FindEntities(scene, spec.grounded->entities)); + runCounts["grounded"] += int32_t(entities.size()); + + for (auto entity : entities) { + EntitySet ignored; + CollectHierarchy(entity, ignored); + + // Skip entities whose hierarchy has no loaded mesh bounds + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + if (!hasMesh) + continue; + + auto center = bounds.GetCenter(); + // Start just above the entity so roofs or arches above it are not hit + auto ground = GroundBelow(scene, vec3(center.x, bounds.max.y + 0.5f, center.z), ignored); + + if (!ground.valid) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "no ground below the entity at " + FormatVec3(center) }); + continue; + } + + // Standing on a prop (e.g. walking over hay bales) counts as a failure if surfaces are given + const auto& surfaces = spec.grounded->surfaces; + if (!surfaces.empty() && ground.entity.IsValid() && + !MatchesSelfOrAncestor(scene, ground.entity, surfaces)) { + + AddFailure({ "grounded", GetEntityLabel(entity), time, + "stands on " + GetEntityLabel(ground.entity) + ", which doesn't match the allowed surfaces" }); + continue; + + } + + auto gap = bounds.min.y - ground.position.y; + if (gap > spec.grounded->maxGap) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "floats " + FormatFloat(gap) + " m above " + + (ground.entity.IsValid() ? GetEntityLabel(ground.entity) : ground.kind) + " (bottom y " + + FormatFloat(bounds.min.y) + ", ground y " + FormatFloat(ground.position.y) + ")" }); + } + else if (gap < -spec.grounded->maxSink) { + AddFailure({ "grounded", GetEntityLabel(entity), time, + "sinks " + FormatFloat(-gap) + " m into " + + (ground.entity.IsValid() ? GetEntityLabel(ground.entity) : ground.kind) + " (bottom y " + + FormatFloat(bounds.min.y) + ", ground y " + FormatFloat(ground.position.y) + ")" }); + } + } + + } + + void CheckRunner::CheckPenetration(Scene::Scene& scene, float time) { + + auto& penetration = *spec.penetration; + auto entities = RemoveDescendants(scene, FindEntities(scene, penetration.entities)); + runCounts["penetration"] += int32_t(entities.size()); + + for (auto entity : entities) { + EntitySet hierarchy; + CollectHierarchy(entity, hierarchy); + + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + if (!hasMesh) + continue; + + // Shrink the bounds such that touching neighbors (e.g. resting on the floor) don't count + auto margin = glm::min(vec3(penetration.margin), bounds.GetSize() * 0.45f); + auto box = Volume::AABB(bounds.min + margin, bounds.max - margin); + + for (auto other : scene.QueryAABB(box)) { + if (hierarchy.contains(other)) + continue; + if (!MatchesSelfOrAncestor(scene, other, penetration.against)) + continue; + + auto meshComponent = other.TryGetComponent(); + auto transform = other.TryGetComponent(); + if (!meshComponent || !transform || !meshComponent->visible) + continue; + + auto intruding = CountIntrudingTriangles(*meshComponent, *transform, box); + + // Count only additional intersections relative to the first observation + auto key = std::make_pair(ECS::Entity(entity), ECS::Entity(other)); + auto [it, inserted] = baselineIntrusions.try_emplace(key, intruding); + auto increase = intruding - it->second; + + if (increase >= penetration.minTriangles) { + AddFailure({ "penetration", GetEntityLabel(entity), time, + std::to_string(increase) + " more triangles of " + GetEntityLabel(other) + + " intrude into its bounds than at the start (" + std::to_string(intruding) + " vs " + + std::to_string(it->second) + ", bounds " + FormatVec3(bounds.min) + " - " + + FormatVec3(bounds.max) + ")" }); + } + } + } + + } + + void CheckRunner::CheckInvalidTransforms(Scene::Scene& scene, float time) { + + auto transformSubset = scene.GetSubset(); + for (auto entity : transformSubset) { + const auto& transform = transformSubset.Get(entity); + + bool valid = true; + for (int32_t column = 0; column < 4; column++) + for (int32_t row = 0; row < 4; row++) + valid &= std::isfinite(transform.globalMatrix[column][row]); + + if (!valid) + AddFailure({ "invalidTransforms", GetEntityLabel({ entity, &scene.entityManager }), time, + "transform contains NaN or infinite values" }); + } + + } + + json CheckRunner::GetReport() const { + + json j; + j["passed"] = failures.empty(); + + json checks = json::object(); + if (spec.grounded) + checks["grounded"] = { { "evaluations", runCounts.contains("grounded") ? runCounts.at("grounded") : 0 } }; + if (spec.penetration) + checks["penetration"] = { { "evaluations", + runCounts.contains("penetration") ? runCounts.at("penetration") : 0 } }; + j["checks"] = checks; + + json failureList = json::array(); + for (const auto& failure : failures) { + auto key = failure.check + "|" + failure.entity; + failureList.push_back( + { { "check", failure.check }, { "entity", failure.entity }, { "firstTime", failure.time }, + { "message", failure.message }, { "occurrences", failureCounts.at(key) } }); + } + j["failures"] = failureList; + + return j; + } + + std::vector CheckRunner::GetSummary() const { + + std::vector lines; + for (const auto& failure : failures) { + auto key = failure.check + "|" + failure.entity; + lines.push_back("[" + failure.check + "] t=" + FormatFloat(failure.time, 2) + "s " + failure.entity + ": " + + failure.message + " (" + std::to_string(failureCounts.at(key)) + "x)"); + } + + return lines; + } + + void Tracker::Record(Scene::Scene& scene, float time) { + + auto entities = RemoveDescendants(scene, FindEntities(scene, spec.entities)); + for (auto entity : entities) { + auto bounds = GetEntityBounds(entity); + samples[GetEntityLabel(entity)].push_back( + { time, GetEntityPosition(entity), glm::degrees(GetEntityYaw(entity)), bounds.min.y }); + } + + } + + json Tracker::GetTrace() const { + + json j; + j["interval"] = spec.interval; + + json summary = json::object(); + json entities = json::object(); + for (const auto& [label, list] : samples) { + json entitySamples = json::array(); + float travelled = 0.0f; + float minY = std::numeric_limits::max(), maxY = -std::numeric_limits::max(); + for (size_t i = 0; i < list.size(); i++) { + const auto& sample = list[i]; + entitySamples.push_back({ { "t", std::round(sample.time * 1000.0f) / 1000.0f }, + { "position", FromVec3(sample.position) }, { "yaw", std::round(sample.yaw * 10.0f) / 10.0f }, + { "bottomY", std::round(sample.minY * 1000.0f) / 1000.0f } }); + if (i > 0) + travelled += glm::distance(sample.position, list[i - 1].position); + minY = std::min(minY, sample.position.y); + maxY = std::max(maxY, sample.position.y); + } + entities[label] = entitySamples; + + if (!list.empty()) { + summary[label] = { { "start", FromVec3(list.front().position) }, + { "end", FromVec3(list.back().position) }, { "distanceTravelled", travelled }, { "minY", minY }, + { "maxY", maxY }, { "firstSeen", list.front().time }, { "lastSeen", list.back().time } }; + } + } + + j["summary"] = summary; + j["entities"] = entities; + return j; + } + + json EvaluateExpectation(Scene::Scene& scene, const json& expectation, bool& passed) { + + json result; + result["expect"] = expectation; + passed = false; + + auto entityPattern = expectation.at("entity").get(); + auto property = expectation.at("property").get(); + auto entities = RemoveDescendants(scene, FindEntities(scene, entityPattern)); + + if (property == "count") { + auto op = expectation.value("op", std::string("==")); + auto expected = expectation.at("value").get(); + passed = Compare(float(entities.size()), op, expected, 0.5f); + result["actual"] = entities.size(); + return result; + } + + if (property == "exists") { + auto expected = expectation.value("value", true); + passed = entities.empty() != expected; + result["actual"] = !entities.empty(); + return result; + } + + if (entities.empty()) { + result["error"] = "No entity matches '" + entityPattern + "'"; + return result; + } + + auto op = expectation.value("op", std::string(">")); + auto expected = expectation.at("value").get(); + auto tolerance = expectation.value("tolerance", 0.01f); + + // All matching entities have to fulfill the expectation + passed = true; + json actualValues = json::object(); + for (auto entity : entities) { + auto position = GetEntityPosition(entity); + bool hasMesh = false; + auto bounds = GetEntityBounds(entity, &hasMesh); + + // Like the grounded check, skip entities whose hierarchy has no loaded mesh bounds + if (property == "gapToGround" && !hasMesh) + continue; + + float actual = 0.0f; + if (property == "position.x") + actual = position.x; + else if (property == "position.y") + actual = position.y; + else if (property == "position.z") + actual = position.z; + else if (property == "bottom.y") + actual = bounds.min.y; + else if (property == "top.y") + actual = bounds.max.y; + else if (property == "yaw") + actual = glm::degrees(GetEntityYaw(entity)); + else if (property == "distanceTo") + actual = glm::distance(position, ToVec3(expectation.at("point"))); + else if (property == "gapToGround") { + EntitySet ignored; + CollectHierarchy(entity, ignored); + auto center = bounds.GetCenter(); + auto ground = GroundBelow(scene, vec3(center.x, bounds.max.y + 0.5f, center.z), ignored); + actual = ground.valid ? bounds.min.y - ground.position.y : std::numeric_limits::infinity(); + } + else { + throw std::runtime_error("Unknown expectation property '" + property + + "' (exists, position.x/y/z, " "bottom.y, top.y, yaw, distanceTo, gapToGround)"); + } + + actualValues[GetEntityLabel(entity)] = actual; + passed &= Compare(actual, op, expected, tolerance); + } + + result["actual"] = actualValues; + return result; + + } + +} diff --git a/src/capture/Checks.h b/src/capture/Checks.h new file mode 100644 index 000000000..dac73dcef --- /dev/null +++ b/src/capture/Checks.h @@ -0,0 +1,87 @@ +#pragma once + +#include "Job.h" +#include "SceneTools.h" + +#include + +namespace Atlas::Capture { + + struct Failure { + + std::string check; + std::string entity; + float time = 0.0f; + std::string message; + + }; + + // Runs the plausibility checks of a job, either once (static) or repeatedly while playing + class CheckRunner { + + public: + explicit CheckRunner(const ChecksSpec& spec) : spec(spec) {} + + void Run(Scene::Scene& scene, float time); + + void AddFailure(const Failure& failure); + + bool HasFailures() const { return !failures.empty(); } + + json GetReport() const; + + std::vector GetSummary() const; + + const ChecksSpec spec; + + private: + void CheckGrounded(Scene::Scene& scene, float time); + + void CheckPenetration(Scene::Scene& scene, float time); + + void CheckInvalidTransforms(Scene::Scene& scene, float time); + + std::vector failures; + // Only the first failure per check and entity is kept in detail, the rest is counted + std::map failureCounts; + std::map runCounts; + + std::map, int32_t> baselineIntrusions; + + }; + + // Records positions of entities over time + class Tracker { + + public: + explicit Tracker(const TrackSpec& spec) : spec(spec) {} + + void Record(Scene::Scene& scene, float time); + + json GetTrace() const; + + struct Sample { + + float time; + vec3 position; + float yaw; + float minY; + + }; + + const std::map>& GetSamples() const { return samples; } + + const TrackSpec spec; + + private: + std::map> samples; + + }; + + // Removes entities whose ancestor is also contained in the list + std::vector RemoveDescendants(Scene::Scene& scene, const std::vector& entities); + + // Evaluates a timeline expectation, e.g. { "entity": "Crate", "property": "position.y", "op": ">", "value": 0 } + json EvaluateExpectation(Scene::Scene& scene, const json& expectation, bool& passed); + +} diff --git a/src/capture/Common.cpp b/src/capture/Common.cpp new file mode 100644 index 000000000..8d425e39f --- /dev/null +++ b/src/capture/Common.cpp @@ -0,0 +1,148 @@ +#include "Common.h" + +#include "loader/AssetLoader.h" + +#include +#include + +namespace Atlas::Capture { + + // Runs before main(), which changes the working directory to the executable directory + static const fs::path launchDirectory = fs::current_path(); + + const fs::path& GetLaunchDirectory() { + + return launchDirectory; + + } + + fs::path GetAssetDirectory() { + + return fs::weakly_canonical(Loader::AssetLoader::GetDataDirectory()); + + } + + fs::path ResolveUserPath(const std::string& path) { + + fs::path userPath(path); + if (userPath.is_absolute()) + return userPath.lexically_normal(); + + return (launchDirectory / userPath).lexically_normal(); + + } + + std::string ToAssetPath(const std::string& path) { + + auto assetDirectory = GetAssetDirectory(); + + // Prefer paths that exist relative to the launch directory (e.g. data/scenes/x.aescene) + auto userPath = ResolveUserPath(path); + if (fs::exists(userPath)) { + auto relative = fs::weakly_canonical(userPath).lexically_relative(assetDirectory); + if (!relative.empty() && relative.native()[0] != '.') + return relative.generic_string(); + // Outside of the asset directory, the engine accepts absolute paths + return fs::weakly_canonical(userPath).generic_string(); + } + + auto generic = fs::path(path).generic_string(); + if (generic.starts_with("data/")) + generic = generic.substr(5); + + return generic; + + } + + bool MatchPattern(const std::string& pattern, const std::string& text) { + + // Iterative wildcard matching with backtracking to the last star + size_t p = 0, t = 0, starIdx = std::string::npos, matchIdx = 0; + while (t < text.size()) { + if (p < pattern.size() && (pattern[p] == '?' || pattern[p] == text[t])) { + p++; + t++; + } + else if (p < pattern.size() && pattern[p] == '*') { + starIdx = p++; + matchIdx = t; + } + else if (starIdx != std::string::npos) { + p = starIdx + 1; + t = ++matchIdx; + } + else { + return false; + } + } + + while (p < pattern.size() && pattern[p] == '*') + p++; + + return p == pattern.size(); + + } + + bool MatchAnyPattern(const std::vector& patterns, const std::string& text) { + + for (const auto& pattern : patterns) + if (MatchPattern(pattern, text)) + return true; + + return false; + + } + + vec3 ToVec3(const json& j, vec3 defaultValue) { + + if (j.is_array() && j.size() == 3) + return vec3(j[0].get(), j[1].get(), j[2].get()); + if (j.is_number()) + return vec3(j.get()); + + return defaultValue; + + } + + json FromVec3(vec3 v) { + + // Round a bit to keep the output readable + auto round = [](float x) { + + return std::round(x * 10000.0f) / 10000.0f; + + }; + return json::array({ round(v.x), round(v.y), round(v.z) }); + + } + + std::string FormatFloat(float value, int32_t precision) { + + std::ostringstream stream; + stream << std::fixed << std::setprecision(precision) << value; + return stream.str(); + + } + + std::string FormatVec3(vec3 v, int32_t precision) { + + return "(" + FormatFloat(v.x, precision) + ", " + FormatFloat(v.y, precision) + ", " + + FormatFloat(v.z, precision) + ")"; + + } + + std::string SanitizeFileName(const std::string& name) { + + std::string result; + for (auto c : name) { + if (std::isalnum(uint8_t(c)) || c == '-' || c == '_' || c == '.') + result.push_back(c); + else + result.push_back('_'); + } + + return result.empty() ? "unnamed" : result; + + } + +} diff --git a/src/capture/Common.h b/src/capture/Common.h new file mode 100644 index 000000000..7ce74c9a7 --- /dev/null +++ b/src/capture/Common.h @@ -0,0 +1,46 @@ +#pragma once + +#include "System.h" +#include "common/SerializationHelper.h" + +#include +#include +#include + +namespace Atlas::Capture { + + namespace fs = std::filesystem; + + using glm::u8vec4; + using glm::uvec4; + + // Directory the tool was launched from. The engine main changes the working directory + // to the executable directory, so this is captured during static initialization + const fs::path& GetLaunchDirectory(); + + // Absolute path of the engine's filesystem data directory + fs::path GetAssetDirectory(); + + // Resolves a user supplied path relative to the launch directory + fs::path ResolveUserPath(const std::string& path); + + // Converts a user supplied scene path into a path relative to the asset directory, + // e.g. "data/scenes/Kingdom.aescene" or "scenes/Kingdom.aescene" -> "scenes/Kingdom.aescene" + std::string ToAssetPath(const std::string& path); + + // Case sensitive glob match supporting '*' and '?' + bool MatchPattern(const std::string& pattern, const std::string& text); + + bool MatchAnyPattern(const std::vector& patterns, const std::string& text); + + vec3 ToVec3(const json& j, vec3 defaultValue = vec3(0.0f)); + + json FromVec3(vec3 v); + + std::string FormatFloat(float value, int32_t precision = 3); + + std::string FormatVec3(vec3 v, int32_t precision = 3); + + std::string SanitizeFileName(const std::string& name); + +} diff --git a/src/capture/Image.cpp b/src/capture/Image.cpp new file mode 100644 index 000000000..2c2f5ebc2 --- /dev/null +++ b/src/capture/Image.cpp @@ -0,0 +1,201 @@ +#include "Image.h" + +#include "loader/ImageLoader.h" + +#include + +#include +#include + +namespace Atlas::Capture { + + struct FontData { + + std::vector data; + stbtt_fontinfo info; + bool valid = false; + + }; + + static FontData& GetFont() { + + static FontData font; + static std::once_flag flag; + + std::call_once(flag, [&]() { + + std::ifstream stream(GetAssetDirectory() / "font" / "roboto.ttf", std::ios::binary); + if (!stream.is_open()) + return; + + font.data = std::vector(std::istreambuf_iterator(stream), {}); + font.valid = stbtt_InitFont(&font.info, font.data.data(), 0) != 0; + + }); + + return font; + + } + + static void SetPixel(Image& image, int32_t x, int32_t y, u8vec4 color) { + + if (x < 0 || y < 0 || x >= image.width || y >= image.height) + return; + + image.SetData(x, y, ivec4(color)); + + } + + Ref CreateImage(int32_t width, int32_t height, u8vec4 color) { + + auto image = CreateRef(width, height, 4); + auto& data = image->GetData(); + for (size_t i = 0; i < data.size(); i += 4) { + data[i] = color.r; + data[i + 1] = color.g; + data[i + 2] = color.b; + data[i + 3] = color.a; + } + + return image; + + } + + bool WritePng(const Ref& image, const fs::path& path) { + + image->fileFormat = Common::ImageFormat::PNG; + auto mutableImage = image; + Loader::ImageLoader::SaveImage(mutableImage, path.string()); + + return fs::exists(path); + + } + + Ref Downscale(const Ref& image, int32_t maxWidth) { + + if (image->width <= maxWidth) + return image; + + auto scale = float(maxWidth) / float(image->width); + auto copy = CreateRef(image->width, image->height, image->channels); + copy->SetData(image->GetData()); + copy->Resize(maxWidth, std::max(int32_t(float(image->height) * scale), 1)); + + return copy; + + } + + void Blit(Image& target, const Image& source, int32_t x, int32_t y) { + + for (int32_t sy = 0; sy < source.height; sy++) + for (int32_t sx = 0; sx < source.width; sx++) + SetPixel(target, x + sx, y + sy, u8vec4(source.Sample(sx, sy))); + + } + + void FillRect(Image& image, int32_t x, int32_t y, int32_t width, int32_t height, u8vec4 color) { + + for (int32_t py = y; py < y + height; py++) + for (int32_t px = x; px < x + width; px++) + SetPixel(image, px, py, color); + + } + + int32_t DrawText(Image& image, int32_t x, int32_t y, const std::string& text, float pixelHeight, u8vec4 color) { + + auto& font = GetFont(); + if (!font.valid) + return 0; + + auto scale = stbtt_ScaleForPixelHeight(&font.info, pixelHeight); + + int32_t ascent, descent, lineGap; + stbtt_GetFontVMetrics(&font.info, &ascent, &descent, &lineGap); + auto baseline = y + int32_t(float(ascent) * scale); + + float cursor = float(x); + for (size_t i = 0; i < text.size(); i++) { + auto codepoint = int32_t(uint8_t(text[i])); + + int32_t advance, leftBearing; + stbtt_GetCodepointHMetrics(&font.info, codepoint, &advance, &leftBearing); + + int32_t x0, y0, x1, y1; + stbtt_GetCodepointBitmapBox(&font.info, codepoint, scale, scale, &x0, &y0, &x1, &y1); + + auto glyphWidth = x1 - x0, glyphHeight = y1 - y0; + if (glyphWidth > 0 && glyphHeight > 0) { + std::vector bitmap(size_t(glyphWidth) * size_t(glyphHeight)); + stbtt_MakeCodepointBitmap( + &font.info, bitmap.data(), glyphWidth, glyphHeight, glyphWidth, scale, scale, codepoint); + + for (int32_t gy = 0; gy < glyphHeight; gy++) { + for (int32_t gx = 0; gx < glyphWidth; gx++) { + auto px = int32_t(cursor) + x0 + gx, py = baseline + y0 + gy; + if (px < 0 || py < 0 || px >= image.width || py >= image.height) + continue; + + auto alpha = float(bitmap[size_t(gy) * size_t(glyphWidth) + size_t(gx)]) / 255.0f; + auto background = vec4(image.Sample(px, py)); + SetPixel(image, px, py, u8vec4(glm::mix(background, vec4(color), alpha))); + } + } + } + + cursor += float(advance) * scale; + if (i + 1 < text.size()) + cursor += + scale * float(stbtt_GetCodepointKernAdvance(&font.info, codepoint, int32_t(uint8_t(text[i + 1])))); + } + + return int32_t(cursor) - x; + + } + + Ref ComposeSheet(const std::vector>& images, const std::vector& labels, + int32_t columns, const std::string& title, int32_t cellWidth) { + + if (images.empty()) + return CreateImage(1, 1); + + const int32_t labelHeight = 26; + const int32_t titleHeight = title.empty() ? 0 : 34; + const int32_t spacing = 4; + + if (columns <= 0) + columns = int32_t(std::ceil(std::sqrt(float(images.size())))); + columns = std::min(columns, int32_t(images.size())); + auto rows = (int32_t(images.size()) + columns - 1) / columns; + + std::vector> cells; + int32_t cellHeight = 0; + for (const auto& image : images) { + cells.push_back(Downscale(image, cellWidth)); + cellHeight = std::max(cellHeight, cells.back()->height); + } + cellWidth = std::min(cellWidth, cells.front()->width); + + auto width = columns * (cellWidth + spacing) + spacing; + auto height = titleHeight + rows * (cellHeight + labelHeight + spacing) + spacing; + auto sheet = CreateImage(width, height, u8vec4(24, 24, 24, 255)); + + if (!title.empty()) + DrawText(*sheet, spacing + 4, 6, title, 22.0f); + + for (size_t i = 0; i < cells.size(); i++) { + auto column = int32_t(i) % columns, row = int32_t(i) / columns; + auto x = spacing + column * (cellWidth + spacing); + auto y = titleHeight + spacing + row * (cellHeight + labelHeight + spacing); + + FillRect(*sheet, x, y, cellWidth, labelHeight, u8vec4(48, 48, 48, 255)); + if (i < labels.size()) + DrawText(*sheet, x + 6, y + 4, labels[i], 17.0f); + + Blit(*sheet, *cells[i], x, y + labelHeight); + } + + return sheet; + + } + +} diff --git a/src/capture/Image.h b/src/capture/Image.h new file mode 100644 index 000000000..59bec95ba --- /dev/null +++ b/src/capture/Image.h @@ -0,0 +1,33 @@ +#pragma once + +#include "Common.h" + +#include "common/Image.h" + +namespace Atlas::Capture { + + // Captures are stored in engine images with 4 channels (RGBA8) + using Image = Common::Image; + + Ref CreateImage(int32_t width, int32_t height, u8vec4 color = u8vec4(0, 0, 0, 255)); + + // Saved with the engine image loader + bool WritePng(const Ref& image, const fs::path& path); + + // Returns the input if it fits maxWidth, otherwise a copy resized with the engine image resampling + Ref Downscale(const Ref& image, int32_t maxWidth); + + void Blit(Image& target, const Image& source, int32_t x, int32_t y); + + void FillRect(Image& image, int32_t x, int32_t y, int32_t width, int32_t height, u8vec4 color); + + // Draws byte-wise text with font/roboto.ttf from the asset directory and returns its width + // The engine font stores glyph textures on the GPU; CPU bitmaps are rasterized here with stb_truetype + int32_t DrawText( + Image& image, int32_t x, int32_t y, const std::string& text, float pixelHeight, u8vec4 color = u8vec4(255)); + + // Grid of labeled images with an optional title + Ref ComposeSheet(const std::vector>& images, const std::vector& labels, + int32_t columns, const std::string& title, int32_t cellWidth = 640); + +} diff --git a/src/capture/Job.cpp b/src/capture/Job.cpp new file mode 100644 index 000000000..6a21d406b --- /dev/null +++ b/src/capture/Job.cpp @@ -0,0 +1,615 @@ +#include "Job.h" + +#include +#include +#include + +namespace Atlas::Capture { + + static void CheckKeys(const json& j, const std::set& allowed, const std::string& context) { + + if (!j.is_object()) + throw std::runtime_error(context + " must be a JSON object"); + + // Typos in job files would otherwise be silently ignored + for (auto& [key, value] : j.items()) { + if (!allowed.contains(key)) + throw std::runtime_error("Unknown key '" + key + "' in " + context); + } + + } + + static std::vector ToStringList(const json& j) { + + std::vector list; + if (j.is_string()) + list.push_back(j.get()); + else if (j.is_array()) + for (const auto& item : j) + list.push_back(item.get()); + + return list; + + } + + static std::vector SplitList(const std::string& text, char separator = ',') { + + std::vector list; + size_t start = 0; + while (start <= text.size()) { + auto end = text.find(separator, start); + if (end == std::string::npos) + end = text.size(); + auto item = text.substr(start, end - start); + if (!item.empty()) + list.push_back(item); + start = end + 1; + } + + return list; + + } + + static json ParseVec3Argument(const std::string& text, const std::string& option) { + + auto parts = SplitList(text); + if (parts.size() != 3) + throw std::runtime_error(option + " expects x,y,z but got '" + text + "'"); + + return json::array({ std::stof(parts[0]), std::stof(parts[1]), std::stof(parts[2]) }); + + } + + static ShotSpec ParseShot(const json& j, size_t index) { + + CheckKeys(j, { "name", "camera", "views", "passes", "settleFrames" }, "shot"); + + ShotSpec shot; + shot.name = j.value("name", "shot" + std::to_string(index)); + if (j.contains("camera")) + shot.camera = ParseCamera(j["camera"]); + if (j.contains("views")) + shot.views = ToStringList(j["views"]); + if (j.contains("passes")) + shot.passes = ToStringList(j["passes"]); + shot.settleFrames = j.value("settleFrames", -1); + + return shot; + + } + + static GroundedCheckSpec ParseGrounded(const json& j) { + + CheckKeys(j, { "entities", "maxGap", "maxSink", "surfaces" }, "checks.grounded"); + + GroundedCheckSpec spec; + spec.entities = ToStringList(j.at("entities")); + spec.maxGap = j.value("maxGap", spec.maxGap); + spec.maxSink = j.value("maxSink", spec.maxSink); + if (j.contains("surfaces")) + spec.surfaces = ToStringList(j["surfaces"]); + return spec; + + } + + static PenetrationCheckSpec ParsePenetration(const json& j) { + + CheckKeys(j, { "entities", "against", "margin", "minTriangles" }, "checks.penetration"); + + PenetrationCheckSpec spec; + spec.entities = ToStringList(j.at("entities")); + spec.against = j.contains("against") ? ToStringList(j["against"]) : std::vector { "*" }; + spec.margin = j.value("margin", spec.margin); + spec.minTriangles = j.value("minTriangles", spec.minTriangles); + return spec; + + } + + static const std::set eventTypes = { "capture", "key", "look", "teleport", "log", "expect", + "resetScripts", "pause" }; + + CameraSpec ParseCamera(const json& j) { + + CameraSpec camera; + + if (j.is_string()) { + camera.mode = j.get(); + return camera; + } + + CheckKeys(j, + { "mode", "position", "lookAt", "yaw", "pitch", "entity", "view", "azimuth", "elevation", "local", + "distance", "padding", "avoidOcclusion", "dynamic", "offset", "fov", "near", "far" }, + "camera"); + + // Infer the mode from the given keys if it isn't specified + if (j.contains("mode")) + camera.mode = j["mode"].get(); + else if (j.contains("entity") && j.contains("offset")) + camera.mode = "follow"; + else if (j.contains("entity")) + camera.mode = "focus"; + else if (j.contains("position")) + camera.mode = "manual"; + + static const std::set modes = { "scene", "manual", "focus", "follow", "overview" }; + if (!modes.contains(camera.mode)) + throw std::runtime_error("Unknown camera mode '" + camera.mode + "'"); + + camera.position = ToVec3(j.value("position", json()), camera.position); + if (j.contains("lookAt")) + camera.lookAt = ToVec3(j["lookAt"]); + camera.yaw = j.value("yaw", camera.yaw); + camera.pitch = j.value("pitch", camera.pitch); + camera.entity = j.value("entity", camera.entity); + camera.view = j.value("view", camera.view); + if (j.contains("azimuth")) + camera.azimuth = j["azimuth"].get(); + if (j.contains("elevation")) + camera.elevation = j["elevation"].get(); + camera.local = j.value("local", camera.local); + camera.distance = j.value("distance", camera.distance); + camera.padding = j.value("padding", camera.padding); + camera.avoidOcclusion = j.value("avoidOcclusion", camera.avoidOcclusion); + camera.dynamic = j.value("dynamic", camera.dynamic); + camera.offset = ToVec3(j.value("offset", json()), camera.offset); + camera.fieldOfView = j.value("fov", camera.fieldOfView); + camera.nearPlane = j.value("near", camera.nearPlane); + camera.farPlane = j.value("far", camera.farPlane); + + if ((camera.mode == "focus" || camera.mode == "follow") && camera.entity.empty()) + throw std::runtime_error("Camera mode '" + camera.mode + "' requires an entity pattern"); + + return camera; + + } + + Job ParseJob(const json& j, const fs::path& baseDirectory) { + + CheckKeys(j, + { "name", "scene", "out", "resolution", "settleFrames", "loadTimeout", "fixedDt", "showWindow", "settings", + "variants", "inspect", "queries", "edit", "shots", "play", "duration", "timeline", "strips", "observer", + "scripts", "track", "overlay", "checks", "profile", "$schema", "description" }, + "job"); + + Job job; + + if (!j.contains("scene")) + throw std::runtime_error("The job doesn't specify a scene"); + + job.scene = ToAssetPath(j["scene"].get()); + job.name = j.value("name", fs::path(job.scene).stem().string()); + + if (j.contains("out")) { + fs::path out(j["out"].get()); + job.outputDirectory = out.is_absolute() ? out : (baseDirectory / out).lexically_normal(); + } + else { + // bin//../capture/, the bin directory is ignored by git + job.outputDirectory = + (fs::current_path() / ".." / "capture" / SanitizeFileName(job.name)).lexically_normal(); + } + + if (j.contains("resolution")) { + auto& resolution = j["resolution"]; + job.resolution = ivec2(resolution.at(0).get(), resolution.at(1).get()); + if (job.resolution.x <= 0 || job.resolution.y <= 0) + throw std::runtime_error("Invalid resolution"); + } + + job.settleFrames = j.value("settleFrames", job.settleFrames); + job.loadTimeout = j.value("loadTimeout", job.loadTimeout); + job.fixedDeltaTime = j.value("fixedDt", job.fixedDeltaTime); + job.showWindow = j.value("showWindow", job.showWindow); + + if (job.fixedDeltaTime <= 0.0f) + throw std::runtime_error("fixedDt must be positive"); + + if (j.contains("settings")) + job.settings = j["settings"]; + + if (j.contains("variants")) { + for (const auto& variant : j["variants"]) { + CheckKeys(variant, { "name", "settings" }, "variant"); + job.variants.push_back( + { variant.at("name").get(), variant.value("settings", json::object()) }); + } + } + + if (j.contains("inspect")) { + auto& inspect = j["inspect"]; + InspectSpec spec; + if (inspect.is_string()) { + spec.file = inspect.get(); + } + else if (inspect.is_object()) { + CheckKeys(inspect, { "file", "filter", "detail" }, "inspect"); + spec.file = inspect.value("file", spec.file); + if (inspect.contains("filter")) + spec.filter = ToStringList(inspect["filter"]); + if (inspect.contains("detail")) + spec.detail = ToStringList(inspect["detail"]); + } + if (!inspect.is_boolean() || inspect.get()) + job.inspect = spec; + } + + if (j.contains("queries")) + job.queries = j["queries"]; + + if (j.contains("edit")) { + auto& edit = j["edit"]; + CheckKeys(edit, { "operations", "output", "overwrite", "saveUnchanged" }, "edit"); + EditSpec spec; + spec.operations = edit.value("operations", json::array()); + spec.output = edit.contains("output") ? ToAssetPath(edit["output"].get()) : ""; + spec.overwrite = edit.value("overwrite", false); + spec.saveUnchanged = edit.value("saveUnchanged", false); + job.edit = spec; + } + + if (j.contains("shots")) { + size_t index = 0; + for (const auto& shot : j["shots"]) + job.shots.push_back(ParseShot(shot, index++)); + } + + job.play = j.value("play", false); + job.duration = j.value("duration", 0.0f); + + if (j.contains("timeline")) { + for (const auto& event : j["timeline"]) { + EventSpec spec; + spec.time = event.value("t", 0.0f); + spec.data = event; + + for (const auto& type : eventTypes) { + if (event.contains(type)) { + if (!spec.type.empty()) + throw std::runtime_error("A timeline event can only have one type: " + event.dump()); + spec.type = type; + } + } + if (spec.type.empty()) + throw std::runtime_error( + "Timeline event without a known type (capture, key, look, teleport, log, expect, resetScripts, pause): " + + event.dump()); + if (spec.type == "pause" && !event["pause"].is_boolean()) + throw std::runtime_error("A pause event needs true or false: " + event.dump()); + + if (event.contains("when")) { + const auto& when = event["when"]; + bool isLog = when.is_object() && when.contains("log") && when["log"].is_string(); + bool isProperty = when.is_object() && when.contains("entity") && when.contains("property"); + if (!isLog && !isProperty) + throw std::runtime_error( + "A when condition needs a log text or entity, property, op and value " "like an expectation: " + + event.dump()); + spec.when = when; + spec.delay = event.value("delay", 0.0f); + spec.optional = event.value("optional", false); + } + + job.timeline.push_back(spec); + } + } + + if (j.contains("strips")) { + for (const auto& strip : j["strips"]) { + CheckKeys(strip, { "name", "from", "to", "every", "camera", "columns" }, "strip"); + StripSpec spec; + spec.name = strip.value("name", "strip" + std::to_string(job.strips.size())); + spec.from = strip.value("from", 0.0f); + spec.to = strip.value("to", job.duration); + spec.every = strip.value("every", spec.every); + spec.columns = strip.value("columns", 0); + if (strip.contains("camera")) { + spec.camera = ParseCamera(strip["camera"]); + spec.hasCamera = true; + } + if (spec.every <= 0.0f) + throw std::runtime_error("strip.every must be positive"); + job.strips.push_back(spec); + } + } + + if (j.contains("observer")) + job.observer = ParseCamera(j["observer"]); + + if (j.contains("scripts")) { + for (const auto& script : j["scripts"]) { + ScriptSpec spec; + if (script.is_string()) { + spec.path = script.get(); + } + else { + CheckKeys(script, { "script", "entity" }, "scripts"); + spec.path = script.at("script").get(); + spec.entity = script.value("entity", std::string()); + } + + // Scripts inside data/ are referenced like any other asset, others by their absolute path + fs::path path(spec.path); + auto resolved = path.is_absolute() ? path : (baseDirectory / path).lexically_normal(); + if (fs::exists(resolved)) { + auto assetPath = ToAssetPath(resolved.string()); + spec.path = fs::path(assetPath).is_absolute() ? resolved.generic_string() : assetPath; + } + else if (!fs::exists(GetAssetDirectory() / path)) { + throw std::runtime_error("Script " + spec.path + " doesn't exist"); + } + + job.scripts.push_back(spec); + } + } + + if (j.contains("track")) { + auto& track = j["track"]; + TrackSpec spec; + if (track.is_object()) { + CheckKeys(track, { "entities", "interval" }, "track"); + spec.entities = ToStringList(track.at("entities")); + spec.interval = track.value("interval", spec.interval); + } + else { + spec.entities = ToStringList(track); + } + job.track = spec; + } + + if (j.contains("profile")) { + auto& profile = j["profile"]; + if (profile.is_object()) { + CheckKeys(profile, { "frames" }, "profile"); + job.profileFrames = std::max(profile.value("frames", 32), 1); + } + else { + job.profileFrames = profile.get() ? 32 : 0; + } + } + + if (j.contains("overlay")) { + auto& overlay = j["overlay"]; + OverlaySpec spec; + if (overlay.is_object()) { + CheckKeys( + overlay, { "bounds", "markers", "axes", "players", "trails", "queries", "depthTest" }, "overlay"); + if (overlay.contains("bounds")) + spec.bounds = ToStringList(overlay["bounds"]); + spec.markers = overlay.value("markers", json::array()); + for (const auto& axes : overlay.value("axes", json::array())) + spec.axes.push_back(ToVec3(axes)); + spec.players = overlay.value("players", spec.players); + spec.trails = overlay.value("trails", spec.trails); + spec.queries = overlay.value("queries", spec.queries); + spec.depthTest = overlay.value("depthTest", spec.depthTest); + } + if (!overlay.is_boolean() || overlay.get()) + job.overlay = spec; + } + + if (j.contains("checks")) { + auto& checks = j["checks"]; + CheckKeys(checks, { "grounded", "penetration", "logErrors", "invalidTransforms", "interval" }, "checks"); + if (checks.contains("grounded")) + job.checks.grounded = ParseGrounded(checks["grounded"]); + if (checks.contains("penetration")) + job.checks.penetration = ParsePenetration(checks["penetration"]); + if (checks.contains("logErrors") && checks["logErrors"].is_object()) { + CheckKeys(checks["logErrors"], { "ignore" }, "checks.logErrors"); + job.checks.logIgnore = ToStringList(checks["logErrors"].value("ignore", json::array())); + } + else { + job.checks.logErrors = checks.value("logErrors", job.checks.logErrors); + } + job.checks.invalidTransforms = checks.value("invalidTransforms", job.checks.invalidTransforms); + job.checks.interval = checks.value("interval", job.checks.interval); + } + + if (job.play && job.duration <= 0.0f) + throw std::runtime_error("A job with play = true needs a positive duration"); + if (!job.play && (!job.timeline.empty() || !job.strips.empty() || !job.scripts.empty())) + throw std::runtime_error("timeline, strips and scripts require play = true"); + if (job.play && job.edit) + throw std::runtime_error( + "edit and play can't be combined, scripts would create runtime entities " "that end up in the saved scene. Run a second job on the edited scene instead"); + + // Without any explicit work, take a picture with the scene camera + if (job.shots.empty() && !job.play && !job.inspect && job.queries.empty() && !job.edit) { + job.shots.push_back(ShotSpec { .name = "frame" }); + } + + return job; + + } + + Job ParseCommandLine(const std::vector& args) { + + json j = json::object(); + fs::path baseDirectory = GetLaunchDirectory(); + + json cliShot = json::object(); + json cliCamera = json::object(); + bool validation = false; + + // Skip the executable path + for (size_t i = 1; i < args.size(); i++) { + const auto& arg = args[i]; + + auto next = [&]() -> std::string { + + if (i + 1 >= args.size()) + throw std::runtime_error(arg + " expects a value"); + return args[++i]; + + }; + auto hasValue = [&]() { + + return i + 1 < args.size() && !args[i + 1].starts_with("--"); + + }; + + if (arg == "--help" || arg == "-h") { + throw std::runtime_error(GetUsage()); + } + else if (arg == "--job" || (!arg.starts_with("--") && arg.ends_with(".json"))) { + auto path = ResolveUserPath(arg == "--job" ? next() : arg); + std::ifstream stream(path); + if (!stream.is_open()) + throw std::runtime_error("Couldn't open job file " + path.string()); + + json fileJob; + try { + fileJob = json::parse(stream, nullptr, true, true); + } + catch (const json::exception& e) { + throw std::runtime_error("Couldn't parse job file " + path.string() + ": " + e.what()); + } + + // Values given on the command line before the job file are kept + fileJob.merge_patch(j); + j = fileJob; + if (!j.contains("name")) + j["name"] = path.stem().string(); + baseDirectory = path.parent_path(); + } + else if (arg == "--scene") + j["scene"] = next(); + else if (arg == "--out") { + j["out"] = ResolveUserPath(next()).string(); + } + else if (arg == "--name") + j["name"] = next(); + else if (arg == "--resolution") { + auto value = next(); + auto parts = SplitList(value, 'x'); + if (parts.size() != 2) + throw std::runtime_error("--resolution expects WIDTHxHEIGHT"); + j["resolution"] = json::array({ std::stoi(parts[0]), std::stoi(parts[1]) }); + } + else if (arg == "--settle") + j["settleFrames"] = std::stoi(next()); + else if (arg == "--timeout") + j["loadTimeout"] = std::stof(next()); + else if (arg == "--show") + j["showWindow"] = true; + else if (arg == "--hidden") + j["showWindow"] = false; + else if (arg == "--overlay") + j["overlay"] = true; + else if (arg == "--validation") + validation = true; + else if (arg == "--inspect") + j["inspect"] = hasValue() ? json(next()) : json(true); + else if (arg == "--play") { + j["play"] = true; + j["duration"] = std::stof(next()); + } + else if (arg == "--camera") { + cliCamera["position"] = ParseVec3Argument(next(), arg); + } + else if (arg == "--look-at") + cliCamera["lookAt"] = ParseVec3Argument(next(), arg); + else if (arg == "--yaw") + cliCamera["yaw"] = std::stof(next()); + else if (arg == "--pitch") + cliCamera["pitch"] = std::stof(next()); + else if (arg == "--fov") + cliCamera["fov"] = std::stof(next()); + else if (arg == "--focus") + cliCamera["entity"] = next(); + else if (arg == "--distance") + cliCamera["distance"] = std::stof(next()); + else if (arg == "--overview") + cliCamera["mode"] = "overview"; + else if (arg == "--views") + cliShot["views"] = SplitList(next()); + else if (arg == "--passes") + cliShot["passes"] = SplitList(next()); + else if (arg == "--shot") + cliShot["name"] = next(); + else if (arg == "--set") { + // --set fog.density=0.02, the value is parsed as JSON if possible + auto assignment = next(); + auto equals = assignment.find('='); + if (equals == std::string::npos) + throw std::runtime_error("--set expects path=value"); + + auto path = assignment.substr(0, equals); + auto valueText = assignment.substr(equals + 1); + json value; + try { + value = json::parse(valueText); + } + catch (const json::exception&) { + value = valueText; + } + + json* node = &j["settings"]; + for (const auto& key : SplitList(path, '.')) + node = &(*node)[key]; + *node = value; + } + else { + throw std::runtime_error("Unknown argument '" + arg + "'\n\n" + GetUsage()); + } + } + + if (!cliCamera.empty()) + cliShot["camera"] = cliCamera; + if (!cliShot.empty()) { + if (!j.contains("shots")) + j["shots"] = json::array(); + j["shots"].push_back(cliShot); + } + + if (!j.contains("scene")) + throw std::runtime_error("No scene given\n\n" + GetUsage()); + + auto job = ParseJob(j, baseDirectory); + job.validation = validation; + return job; + + } + + std::string GetUsage() { + + return R"(Usage: + AtlasEngineCapture [options] + AtlasEngineCapture --scene [options] + AtlasEngineCapture --compose [--title ] [--columns ]