acdream/src/AcDream.App/RuntimeOptions.cs
Erik e8a4c1af3f feat(render): Campaign V slice V5 - Vulkan bring-up, dark
Instance, physical-device selection, logical device, queues, swapchain, and the
three-layer capability gate, behind ACDREAM_RENDER_BACKEND=vulkan. Nothing of
the game renders through it. OpenGL stays the default and the only live backend
until V10, and with the variable unset or set to gl the GL path executes not one
new statement.

The shape of the slice. Plan §4.11 asks the Vulkan gate to mirror the GL one
exactly - passive record, active probes, an Evaluate producing operator-facing
sentences, NotSupportedException into Program.cs's exit-code-4 contract, and an
atomic JSON report. The harder question was where to put the seam, because a
capability gate is precisely the code you cannot exercise on the machine that
already passes it: this box has one discrete GPU, so device ranking, the split-
queue path, an sRGB-only surface, a minimised window and a device missing
descriptorBindingVariableDescriptorCount are all unreachable by running the
client. So every decision the gate makes is a pure function over plain records,
and the Silk interop layer only has to be right about which Vulkan field feeds
which property. VulkanPhysicalDeviceSelection ranks candidates,
VulkanExtensionSelection does the required-versus-optional set arithmetic,
VulkanSwapchainConfigurationFactory chooses format, present mode, image count,
extent, usage, transform and composite alpha, VulkanSwapchainRecreationPolicy
classifies every acquire and present result, and
VulkanCapabilityRequirements.Evaluate turns a captured record into failure
sentences. All of it is unit-tested with no driver, no device and no window.

This commit is the integration of that work onto the post-revert tree. The V5
branch was written on b064668b, before V4c/V4d were reverted, so GameWindow.cs
had to be merged rather than taken: the file here is eb2ba4e5's GameWindow plus
V5's fifteen-line backend branch, and it keeps _terrainModernShader, which the
revert restored and which the V5 branch never had. Every other file is byte-
identical to the branch - git diff e1ef4313 over Rendering/Gpu/Vk,
tests/.../Gpu/Vk and RenderBackendKind.cs is empty, no BOM was introduced, and
CRLF is uniform across all seventeen files.

Gate results, recorded verbatim.

Release build: succeeded, 0 warnings, 0 errors.

App tests, Release: Failed 0, Passed 3981, Skipped 3, Total 3984 - the 3,866
baseline plus V5's 115 new tests, exactly.

Offline pixel gate against eb2ba4e5: PASS world-offline.png, differing fraction
1.06534090909091E-05, which is 6 differing pixels out of the 563,200 compared
after the top 280 sky rows are masked. §5.1's re-measured same-commit control
band is 15-23 pixels at fraction <= 4.1e-05, so this sits below the noise floor
rather than merely inside it - the expected result for a slice that adds no
statement to the GL path.

Vulkan check (a), ACDREAM_RENDER_BACKEND=vulkan on the RX 9070 XT with an
automation artifact directory:

  vulkan: capability gate passed (Windows, AMD Radeon RX 9070 XT, Vulkan
  1.4.349, vendor 0x1002, device 0x7550, driver 2.0.395 (raw 0x0080018B));
  swapchain B8G8R8A8Unorm/PresentModeImmediateKhr 1280x720 x3
  vulkan: device selection - automatic: 'AMD Radeon RX 9070 XT' (DiscreteGpu,
  15.92 GiB device-local) ranked first of 2 enumerated device(s).
  [world-gate] screenshot-complete name=vulkan-bringup path=...
  artifacts\vk-bringup\vulkan-bringup.png size=1280x720
  vulkan: presented 64609 clear-colour frame(s); shutting down.

Exit code 0 on CloseMainWindow. The PNG is 5,238 bytes, 1280x720, and uniformly
RGBA(11,19,39,255) - exactly ClearColor [0.043, 0.075, 0.153, 1] scaled to
UNORM. Orientation is right-side-up by construction rather than by inspection,
which a uniform clear could not show: VulkanBackbufferSwizzle.ToGlOriginRgba
writes source row y into destination row height-1-y precisely because
FrameScreenshotController flips again on the way to the PNG, so the two
cancel. That double-flip is unit-tested.

Vulkan check (b), ACDREAM_VULKAN_FORCE_UNSUPPORTED=timelineSemaphore:

  [ERR] acdream's Vulkan renderer is unsupported by the selected device.
  Platform: win-x64, Windows, AMD Radeon RX 9070 XT (DiscreteGpu), Vulkan
  1.4.349, vendor 0x1002, device 0x7550, driver 2.0.395 (raw 0x0080018B)
   - timelineSemaphore is required; the frame serial is the semaphore value.
  Full capability report: ...\diagnostics\graphical-capabilities-vulkan.json

Exit code 4. The report records ForcedUnsupportedFeature timelineSemaphore,
TimelineSemaphore false against an otherwise complete feature set, and the
matching SupportFailures sentence, so the injected rejection is distinguishable
from a genuinely absent feature. Both enumerated devices, all five surface
formats, all four present modes and a clean FunctionProbe with no failures are
recorded beside it.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 07:11:50 +02:00

173 lines
8.1 KiB
C#

using System;
using System.Globalization;
using System.IO;
using AcDream.App.Rendering.Residency;
using AcDream.App.Streaming;
namespace AcDream.App;
/// <summary>
/// Typed bundle of startup-time configuration read from the process
/// environment. Built once in <c>Program.cs</c> and passed to
/// <c>GameWindow</c> so the rest of the app reads its config through
/// strongly-typed fields instead of scattered
/// <c>Environment.GetEnvironmentVariable</c> calls.
/// </summary>
/// <remarks>
/// <para>
/// <strong>Scope:</strong> startup-time only — values that don't change
/// once the window is up. Runtime diagnostic toggles
/// (e.g. <c>ACDREAM_DUMP_MOTION</c>, <c>ACDREAM_PROBE_*</c>) belong in
/// diagnostic owner classes (see <c>AcDream.Core.Physics.PhysicsDiagnostics</c>
/// for the template), not here.
/// </para>
/// <para>
/// See <c>docs/architecture/code-structure.md</c> §2 Rule 4 for the
/// rule that drove this extraction, and §4 Step 1 for the broader
/// extraction sequence this is the first cut of.
/// </para>
/// </remarks>
public sealed record RuntimeOptions(
string DatDir,
string PreparedAssetPath,
bool LiveMode,
string LiveHost,
int LivePort,
string? LiveUser,
string? LivePass,
bool DevTools,
bool UncappedRendering,
bool DumpMoveTruth,
bool DumpSky,
bool NoAudio,
bool EnableSkyPesDebug,
int HidePartIndex,
bool RetailCloseDegrades,
bool DumpSceneryZ,
bool DumpLiveSpawns,
bool DumpClothing,
int? LegacyStreamRadius,
bool RetailUi,
string? AcDir,
bool UiProbeDump,
string? UiProbeScript,
string? AutomationArtifactDirectory,
int? ForcedDayGroupIndex,
float FogStartMultiplier,
float FogEndMultiplier,
ResidencyBudgetOptions ResidencyBudgets,
StreamingWorkBudgetOptions StreamingWorkBudgets,
RenderBackendKind RenderBackend,
string? VulkanDeviceOverride,
string? VulkanForcedUnsupportedFeature)
{
/// <summary>
/// Build options from the process environment. Used by
/// <c>Program.cs</c> at startup.
/// </summary>
public static RuntimeOptions FromEnvironment(string datDir)
=> Parse(datDir, Environment.GetEnvironmentVariable);
/// <summary>
/// Build options from a custom environment getter. Used by tests to
/// inject controlled env values without touching the process
/// environment.
/// </summary>
/// <param name="datDir">Resolved dat-file directory.</param>
/// <param name="env">Function returning the value for an env-var
/// name, or <c>null</c> when unset.</param>
public static RuntimeOptions Parse(string datDir, Func<string, string?> env)
{
if (datDir is null) throw new ArgumentNullException(nameof(datDir));
if (env is null) throw new ArgumentNullException(nameof(env));
return new RuntimeOptions(
DatDir: datDir,
PreparedAssetPath: NullIfEmpty(env("ACDREAM_PAK_PATH"))
?? Path.Combine(datDir, "acdream.pak"),
LiveMode: IsExactlyOne(env("ACDREAM_LIVE")),
LiveHost: env("ACDREAM_TEST_HOST") ?? "127.0.0.1",
LivePort: TryParseInt(env("ACDREAM_TEST_PORT")) ?? 9000,
LiveUser: NullIfEmpty(env("ACDREAM_TEST_USER")),
LivePass: NullIfEmpty(env("ACDREAM_TEST_PASS")),
DevTools: IsExactlyOne(env("ACDREAM_DEVTOOLS")),
// Normal presentation is always bounded by VSync or a
// refresh-rate software pacer. This explicit diagnostic is the
// sole way to measure truly uncapped renderer throughput.
UncappedRendering: IsExactlyOne(env("ACDREAM_UNCAPPED_RENDER")),
DumpMoveTruth: IsExactlyOne(env("ACDREAM_DUMP_MOVE_TRUTH")),
DumpSky: IsExactlyOne(env("ACDREAM_DUMP_SKY")),
NoAudio: IsExactlyOne(env("ACDREAM_NO_AUDIO")),
EnableSkyPesDebug: IsExactlyOne(env("ACDREAM_ENABLE_SKY_PES")),
HidePartIndex: TryParseInt(env("ACDREAM_HIDE_PART")) ?? -1,
// Default-on: any value other than the literal string "0" enables
// retail close-detail degrades. Set ACDREAM_RETAIL_CLOSE_DEGRADES=0
// only for before/after diagnostic comparisons.
RetailCloseDegrades: !string.Equals(env("ACDREAM_RETAIL_CLOSE_DEGRADES"), "0", StringComparison.Ordinal),
DumpSceneryZ: IsExactlyOne(env("ACDREAM_DUMP_SCENERY_Z")),
DumpLiveSpawns: IsExactlyOne(env("ACDREAM_DUMP_LIVE_SPAWNS")),
DumpClothing: IsExactlyOne(env("ACDREAM_DUMP_CLOTHING")),
// Legacy override for ACDREAM_STREAM_RADIUS. Caller applies it on
// top of the quality preset's radii. Null when unset or invalid.
LegacyStreamRadius: TryParseNonNegativeInt(env("ACDREAM_STREAM_RADIUS")),
RetailUi: IsExactlyOne(env("ACDREAM_RETAIL_UI")),
AcDir: NullIfEmpty(env("ACDREAM_AC_DIR")),
UiProbeDump: IsExactlyOne(env("ACDREAM_UI_PROBE_DUMP")),
UiProbeScript: NullIfEmpty(env("ACDREAM_UI_PROBE_SCRIPT")),
AutomationArtifactDirectory:
NullIfEmpty(env("ACDREAM_AUTOMATION_ARTIFACT_DIR")),
ForcedDayGroupIndex:
TryParseNonNegativeInt(env("ACDREAM_DAY_GROUP")),
FogStartMultiplier: TryParseFloat(env("ACDREAM_FOG_START_MULT")) ?? 0.7f,
FogEndMultiplier: TryParseFloat(env("ACDREAM_FOG_END_MULT")) ?? 0.95f,
ResidencyBudgets: ResidencyBudgetOptions.Parse(env),
StreamingWorkBudgets: StreamingWorkBudgetOptions.Parse(env),
// Campaign V slice V5. Unset, empty, or any unrecognised value means
// OpenGL: a typo must never silently start the dark Vulkan host.
RenderBackend: ParseRenderBackend(env("ACDREAM_RENDER_BACKEND")),
// Physical-device override, matched as a decimal index first and then
// as a case-insensitive device-name substring. Recorded verbatim in
// graphical-capabilities-vulkan.json whether or not it matched.
VulkanDeviceOverride:
NullIfEmpty(env("ACDREAM_VULKAN_DEVICE")),
// Slice V5 gate knob: names one required capability to report as
// absent so the NotSupportedException -> exit-code-4 -> report path
// can be exercised on hardware that actually supports everything.
VulkanForcedUnsupportedFeature:
NullIfEmpty(env("ACDREAM_VULKAN_FORCE_UNSUPPORTED")));
}
/// <summary>
/// Startup backend request. Only the exact lower-case token <c>vulkan</c>
/// selects Vulkan; everything else — unset, <c>gl</c>, or a typo — is
/// OpenGL, which is the shipping backend until Campaign V slice V10.
/// </summary>
private static RenderBackendKind ParseRenderBackend(string? value)
=> string.Equals(value, "vulkan", StringComparison.OrdinalIgnoreCase)
? RenderBackendKind.Vulkan
: RenderBackendKind.Gl;
/// <summary>True iff live-mode credentials are present and valid for connecting.</summary>
public bool HasLiveCredentials =>
LiveMode && !string.IsNullOrEmpty(LiveUser) && !string.IsNullOrEmpty(LivePass);
/// <summary>True when the opt-in retail UI automation probe should be constructed.</summary>
public bool UiProbeEnabled => UiProbeDump || !string.IsNullOrEmpty(UiProbeScript);
private static bool IsExactlyOne(string? s)
=> string.Equals(s, "1", StringComparison.Ordinal);
private static string? NullIfEmpty(string? s)
=> string.IsNullOrEmpty(s) ? null : s;
private static int? TryParseInt(string? s)
=> int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v : null;
private static int? TryParseNonNegativeInt(string? s)
=> TryParseInt(s) is { } v && v >= 0 ? v : null;
private static float? TryParseFloat(string? s)
=> float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out float value)
? value
: null;
}