diff --git a/docs/d3d12x-shim.md b/docs/d3d12x-shim.md index 226f3cf4..0c9a8780 100644 --- a/docs/d3d12x-shim.md +++ b/docs/d3d12x-shim.md @@ -721,11 +721,15 @@ viewport indices stay the corner's) and emits a strip of two triangles with the | Compile one geometry shader per distinct output signature into `/rect-gs/gs_.dxil` | `fivestar shader rect-gs ` (2,191 vertex programs, 211 shaders) | | Keep each created pipeline's description and programs | `RectanglePipelines.Remember` (pipeline factory) | | Record the pipeline (slot 25), the console topology (slot 20); clear on Reset | `RectangleDraws`, state at wrapper +0xF00 | -| First draw under topology 17: build the variant once (by the same hash), bind it | `RectangleDraws.BeforeDraw` (slots 12, 13) | +| First draw under topology 17: queue the variant's build on the pipeline build threads (urgent, within the compile budget) and skip the draw; once built, bind it after any depth-twin copy (which binds the game's pipeline again); a build that throws is reported once and leaves triangles | `RectangleDraws.Building` (skip), `RectangleDraws.BeforeDraw` (bind; slots 12, 13), `RectanglePipelines.Variant` | | Another topology: bind the game's pipeline again | slot 20 | A pipeline with a mesh or geometry stage, or without its `rect-gs` file, has no variant: its rectangle-list draws -stay triangles (warned once). The log counts expanded draws every 4,096. +stay triangles (warned once). The log counts expanded draws every 4,096, with the draws skipped while a variant +built. The variant of a tiled-lighting pipeline is a full compile of its pixel program: built on the drawing game +thread, one held a frame's job for over 25 s while eight other compiles ran, and the game's hang watchdog ended a run +in the opening cutscene. + ### Debug layer `--d3d12-debug` turns on the D3D12 debug layer before the device is created (`--d3d12-gpu-validation` adds diff --git a/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs b/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs index c58f9547..dbd518a1 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs @@ -339,6 +339,12 @@ public static void DrawInstanced(XboxObject* self, uint vertices, uint instances return; } + // A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin. + if (ShimContext.Runtime.D3D12X.Rectangles.Building(self)) + { + return; + } + if (DepthTwins.Any) { CopyTwin(self); @@ -372,6 +378,12 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins return; } + // A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin. + if (ShimContext.Runtime.D3D12X.Rectangles.Building(self)) + { + return; + } + if (DepthTwins.Any) { CopyTwin(self); diff --git a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs index 494b3670..368d0ae9 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs @@ -12,7 +12,7 @@ namespace FiveStar.Loader.Shims.D3D12X.Pipelines; /// /// The rectangle-list variant of each graphics pipeline (docs/d3d12x-shim.md, Rectangle lists): the same pipeline with /// the geometry shader of its vertex program's output signature added, read from rect-gs/ of the translate -/// output (fivestar shader rect-gs; never compiled here). A variant is built on the first rectangle-list draw with +/// output (fivestar shader rect-gs; never compiled here). A variant is built off the game's threads, started by the first rectangle-list draw with /// its pipeline; 0 stands for a pipeline that has none (mesh or geometry stage, no shader file, creation failed). /// internal sealed unsafe class RectanglePipelines @@ -23,13 +23,18 @@ internal sealed unsafe class RectanglePipelines /// Leading D3D12_RASTERIZER_DESC and D3D12_DEPTH_STENCIL_DESC1 bytes a trace shows (fill, cull; depth enable, write mask, function). private const int StateTraceBytes = 12; + /// What returns while the variant builds: its draws are skipped meanwhile. + public const nint Pending = -1; + private readonly nint _device2; private readonly nint _rootSignature; private readonly string _folder; private readonly IProgramLibrary _programs; private readonly OnceLog _warnings; + private readonly PipelineBuildQueue _builds; private readonly ConcurrentDictionary _recipes = new(); private readonly ConcurrentDictionary _variants = new(); + private readonly ConcurrentDictionary _building = new(); private readonly ConcurrentDictionary _shaders = new(StringComparer.Ordinal); /// A desktop ID3D12Device2 (the caller keeps it alive). @@ -37,8 +42,10 @@ internal sealed unsafe class RectanglePipelines /// The compiled geometry shaders (<translated>/rect-gs). /// Where a variant's programs are read again by name. /// Where missing shaders and failures are reported, once each. - public RectanglePipelines(nint device2, nint rootSignature, string folder, IProgramLibrary programs, OnceLog warnings) + /// The build threads that create the variants, as urgent creations (a draw waits for each). + public RectanglePipelines(nint device2, nint rootSignature, string folder, IProgramLibrary programs, OnceLog warnings, PipelineBuildQueue builds) { + _builds = builds; _device2 = device2; _rootSignature = rootSignature; _folder = folder; @@ -103,7 +110,12 @@ public static bool Derived(string name) return $"{programs}; inputs [{inputs}]; targets [{string.Join(", ", description.RenderTargetFormats)}] depth {description.DepthStencilFormat}; blend {blend}; raster {raster}; depth state {depth}; sample mask 0x{description.SampleMask:x}, samples {description.SampleCount}.{description.SampleQuality}, raster all {Convert.ToHexString(description.Rasterizer)}"; } - /// The variant of a desktop pipeline, built on the first call; 0 when it has none. + /// + /// The variant of a desktop pipeline; 0 when it has none; while it builds. The first call queues + /// the build on the pipeline build threads (urgent) and never waits for it: the variant of a tiled-lighting pipeline + /// is a full compile of its pixel program, and built on the drawing game thread it held a frame's job for over 25 s, + /// until the game's hang watchdog ended the run in the opening cutscene. + /// [HotPath] public nint Variant(nint pipeline) { @@ -112,29 +124,86 @@ public nint Variant(nint pipeline) return variant; } - return Create(pipeline); + if (_building.ContainsKey(pipeline)) + { + return Pending; + } + + return Start(pipeline); } - private nint Create(nint pipeline) + /// The first call for a pipeline: 0 without a recipe, otherwise its build queued and . + private nint Start(nint pipeline) { - nint variant = 0; + if (!_recipes.TryGetValue(pipeline, out var recipe)) + { + _variants.TryAdd(pipeline, 0); + + return _variants[pipeline]; + } - if (_recipes.TryGetValue(pipeline, out var recipe)) + var build = new VariantBuild(recipe); + + if (!_building.TryAdd(pipeline, build)) { - variant = Build(recipe); + return Pending; } - if (_variants.TryAdd(pipeline, variant)) + // A build that finished between the caller's two lookups left its variant: no second build. + if (_variants.TryGetValue(pipeline, out var built)) { - return variant; + _building.TryRemove(new KeyValuePair(pipeline, build)); + build.Done.Set(); + + return built; } - if (variant != 0) + _builds.Queue(() => Finish(pipeline, build), urgent: true); + + return Pending; + } + + /// Waits until the variant of is no longer building; false on timeout. + public bool WaitBuilt(nint pipeline, TimeSpan timeout) + { + return !_building.TryGetValue(pipeline, out var build) || build.Done.Wait(timeout); + } + + /// + /// On a build thread: builds the variant within the compile budget, then keeps it unless the pipeline was remembered + /// again since. A failure keeps 0 (drawn as triangles) and is reported once; an exception would end the build thread. + /// + private PipelineResult Finish(nint pipeline, VariantBuild build) + { + nint variant = 0; + nint kept = 0; + + try { - DesktopDevice.Release(variant); + variant = Build(build.Recipe); } + catch (Exception exception) + { + _warnings.Warn($"rect-throw-{build.Recipe.Vertex}", $"[d3d12_xs] rectangle-list pipeline for {build.Recipe.Vertex}: {exception.GetType().Name}: {exception.Message}; drawn as triangles"); + } + finally + { + if (_recipes.TryGetValue(pipeline, out var current) && ReferenceEquals(current, build.Recipe) && _variants.TryAdd(pipeline, variant)) + { + kept = variant; + variant = 0; + } - return _variants[pipeline]; + if (variant != 0) + { + DesktopDevice.Release(variant); + } + + _building.TryRemove(new KeyValuePair(pipeline, build)); + build.Done.Set(); + } + + return new PipelineResult(HResult.Ok, kept); } private nint Build(RectangleRecipe recipe) @@ -166,7 +235,18 @@ private nint Build(RectangleRecipe recipe) programs.Add(TranslatedProgram.Of(vertex.Name, HardwareStage.Geometry, shader)); var iid = DesktopDevice.PipelineStateIid; nint variant = 0; - var hr = DesktopPipelineBuilder.Graphics(_device2, _rootSignature, recipe.Description, programs, &iid, &variant); + long shaderBytes = programs.Sum(program => (long)program.Dxil.Length); + int hr; + CompileBudget.Enter(shaderBytes); + + try + { + hr = DesktopPipelineBuilder.Graphics(_device2, _rootSignature, recipe.Description, programs, &iid, &variant); + } + finally + { + CompileBudget.Exit(shaderBytes); + } if (HResult.Failed(hr)) { diff --git a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/VariantBuild.cs b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/VariantBuild.cs new file mode 100644 index 00000000..23d0d2e9 --- /dev/null +++ b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/VariantBuild.cs @@ -0,0 +1,12 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +namespace FiveStar.Loader.Shims.D3D12X.Pipelines; + +/// A rectangle-list variant being built (): its recipe, and set once it is done. +internal sealed class VariantBuild(RectangleRecipe recipe) +{ + public RectangleRecipe Recipe { get; } = recipe; + + public ManualResetEventSlim Done { get; } = new(); +} diff --git a/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs b/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs index 7922d7be..825bf248 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs @@ -11,7 +11,8 @@ namespace FiveStar.Loader.Shims.D3D12X; /// Draws under the console rectangle list (topology 17; docs/d3d12x-shim.md, Rectangle lists). The topology itself /// becomes a triangle list; a draw under it binds the rectangle-list variant of the list's pipeline /// (), whose geometry shader adds each rectangle's fourth corner. The variant stays -/// bound until the game sets another pipeline or topology. Without a variant the draw covers half of each rectangle. +/// bound until the game sets another pipeline or topology. While the variant builds the draw is skipped; without one it +/// covers half of each rectangle. /// internal sealed unsafe class RectangleDraws { @@ -24,6 +25,7 @@ internal sealed unsafe class RectangleDraws private readonly LoaderLog _log; private long _expanded; private long _triangles; + private long _pending; public RectangleDraws(LoaderLog log) { @@ -39,6 +41,9 @@ public RectangleDraws(LoaderLog log) /// Rectangle-list draws drawn as triangles, for want of a variant. public long AsTriangles => Interlocked.Read(ref _triangles); + /// Rectangle-list draws skipped while their variant was building. + public long WhileBuilding => Interlocked.Read(ref _pending); + public void Attach(RectanglePipelines pipelines) { Pipelines = pipelines; @@ -76,7 +81,33 @@ public void Reset(XboxObject* list, nint pipeline) state->Pipeline = pipeline; } - /// Before a draw: under the rectangle list, binds the variant and counts the draw. + /// + /// First thing before a draw: true when it is to be skipped, since it is under the rectangle list and the variant of + /// its pipeline is still building (off the game's threads; the first call starts the build). The variant is bound + /// later, by , after anything that binds the game's pipeline again (a depth-twin copy). + /// + [HotPath] + public bool Building(XboxObject* list) + { + var state = RectangleListState.Of(list); + var pipelines = Pipelines; + + if (state->Topology != PrimitiveTopologies.RectangleList || state->VariantBound != 0 || pipelines is null || state->Pipeline == 0) + { + return false; + } + + if (pipelines.Variant(state->Pipeline) != RectanglePipelines.Pending) + { + return false; + } + + Interlocked.Increment(ref _pending); + + return true; + } + + /// Right before a draw: under the rectangle list, binds the variant and counts the draw. [HotPath] public void BeforeDraw(XboxObject* list) { @@ -120,7 +151,8 @@ private void BindVariant(XboxObject* list, RectangleListState* state) nint variant = pipelines.Variant(state->Pipeline); - if (variant != 0) + // Pending only if the pipeline was remembered again since Building: the draw then covers half of each rectangle. + if (variant != 0 && variant != RectanglePipelines.Pending) { Bind(list, variant); state->VariantBound = 1; @@ -141,6 +173,6 @@ private void Warn(nint pipeline) private void Report() { - _log.Info($" [d3d12_xs] rectangle lists: {Expanded} draws expanded, {AsTriangles} drawn as triangles"); + _log.Info($" [d3d12_xs] rectangle lists: {Expanded} draws expanded, {AsTriangles} drawn as triangles, {WhileBuilding} skipped while their variant built"); } } diff --git a/src/FiveStar.Loader/Shims/D3D12X/XboxDeviceFactory.cs b/src/FiveStar.Loader/Shims/D3D12X/XboxDeviceFactory.cs index 17349667..db654f10 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/XboxDeviceFactory.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/XboxDeviceFactory.cs @@ -307,8 +307,6 @@ private void CreatePipelines(nint inner) WaitForProgramIndex(); var onDemand = _pipelineFolders.OnDemand?.Open(_programIndex!, programs!, translated, device2, warnings, _log); IProgramLibrary library = onDemand ?? (IProgramLibrary)TranslatedProgramLibrary.Open(_programIndex!, translated!, device2, warnings, _log); - var rectangles = new RectanglePipelines(device2, root, RectangleFolder(translated), library, warnings) { Compiler = _pipelineFolders.OnDemand?.RectangleCompiler }; - Rectangles.Attach(rectangles); // Builds start only while the machine has the memory; heavy ones on their own thread (docs/d3d12x-pipelines.md#stand-ins). // The queues keep only the machine's reserves: each compile's own need is the compile budget's to count. Counting @@ -318,6 +316,8 @@ private void CreatePipelines(nint inner) var heavyBuilds = new PipelineBuildQueue(1, _ => WarmMemoryGuard.RoomForHeavyBuild(0)); builds.Start(); heavyBuilds.Start(); + var rectangles = new RectanglePipelines(device2, root, RectangleFolder(translated), library, warnings, builds) { Compiler = _pipelineFolders.OnDemand?.RectangleCompiler }; + Rectangles.Attach(rectangles); var standIns = new StandInPipelines(PipelineSlots.CreationBudget, builds, heavyBuilds, warnings); var cache = OpenCache(device2); diff --git a/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs b/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs index ccfbb179..65d7ed6c 100644 --- a/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs +++ b/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs @@ -21,7 +21,8 @@ namespace FiveStar.Loader.Tests; /// /// A console rectangle-list draw through the D3D12.X slots (25 SetPipelineState, 20 topology 17, 12 DrawInstanced) on -/// the default adapter: three vertices cover the whole rectangle, and the fourth corner's colour is extrapolated. +/// the default adapter: the first draw is skipped while the variant builds off the drawing thread; then three vertices +/// cover the whole rectangle, and the fourth corner's colour is extrapolated. /// public sealed unsafe class D3D12XRectangleListTests { @@ -64,6 +65,38 @@ public void A_rectangle_list_draw_of_a_linked_producer_the_library_cannot_reload CoversTheWholeRectangle("vs.link-beb72bb57485"); } + [DxcFact] + public void A_variant_build_that_throws_draws_the_rectangle_as_triangles() + { + using var test = TestRuntime.Create(); + var device = new XboxDevice(test); + var folder = Directory.CreateTempSubdirectory("fivestar-rect-"); + + try + { + var desktop = new ID3D12Device(test.Runtime.D3D12X.Objects.DesktopDevice); + desktop.AddRef(); + + using (desktop) + { + // The build thread's program load throws: the build thread survives and the variant stays 0. + nint pipeline = Pipelines(test, folder.FullName, "vs", new ThrowingProgramLibrary()); + _ = Draw(device, desktop, pipeline, test.Runtime.D3D12X.Bindings.Root); + Assert.True(test.Runtime.D3D12X.Rectangles.Pipelines!.WaitBuilt(pipeline, TimeSpan.FromMinutes(1))); + + var pixels = Draw(device, desktop, pipeline, test.Runtime.D3D12X.Bindings.Root); + + Assert.Equal(0, test.Runtime.D3D12X.Rectangles.Expanded); + Assert.Equal(1, test.Runtime.D3D12X.Rectangles.AsTriangles); + Assert.Contains(pixels, pixel => pixel != 0); + } + } + finally + { + folder.Delete(recursive: true); + } + } + private static void CoversTheWholeRectangle(string vertexName) { using var test = TestRuntime.Create(); @@ -78,6 +111,12 @@ private static void CoversTheWholeRectangle(string vertexName) using (desktop) { nint pipeline = Pipelines(test, folder.FullName, vertexName); + // The first draw starts the variant's build off this thread and is skipped: nothing is drawn. + var skipped = Draw(device, desktop, pipeline, test.Runtime.D3D12X.Bindings.Root); + Assert.All(skipped, pixel => Assert.Equal(0u, pixel)); + Assert.Equal(1, test.Runtime.D3D12X.Rectangles.WhileBuilding); + Assert.True(test.Runtime.D3D12X.Rectangles.Pipelines!.WaitBuilt(pipeline, TimeSpan.FromMinutes(1))); + var pixels = Draw(device, desktop, pipeline, test.Runtime.D3D12X.Bindings.Root); // The middle half is covered (all four quarters, the extrapolated one included), the border is not. @@ -97,7 +136,7 @@ private static void CoversTheWholeRectangle(string vertexName) } /// The base pipeline, and its rectangle-list variant's geometry shader compiled as fivestar shader rect-gs does. - private static nint Pipelines(TestRuntime test, string folder, string vertexName) + private static nint Pipelines(TestRuntime test, string folder, string vertexName, IProgramLibrary? library = null) { var vertex = Compile(folder, "vs", Vertex); var programs = new List { TranslatedProgram.Of(vertexName, HardwareStage.Vertex, vertex), TranslatedProgram.Of("ps", HardwareStage.Pixel, Compile(folder, "ps", Pixel)) }; @@ -115,8 +154,10 @@ private static nint Pipelines(TestRuntime test, string folder, string vertexName nint pipeline; Assert.Equal(0, DesktopPipelineBuilder.Graphics(device2, root, description, programs, &iid, &pipeline)); - var library = new FixedProgramLibrary([.. programs.Where(program => !RectanglePipelines.Derived(program.Name))]); - var rectangles = new RectanglePipelines(device2, root, folder, library, new OnceLog(new LoaderLog(new StringWriter(), null, false))); + library ??= new FixedProgramLibrary([.. programs.Where(program => !RectanglePipelines.Derived(program.Name))]); + var builds = new PipelineBuildQueue(1, PipelineBuildQueue.AnyTime); + builds.Start(); + var rectangles = new RectanglePipelines(device2, root, folder, library, new OnceLog(new LoaderLog(new StringWriter(), null, false)), builds); rectangles.Remember(pipeline, description, programs); test.Runtime.D3D12X.Rectangles.Attach(rectangles); diff --git a/tests/FiveStar.Loader.Tests/Support/ThrowingProgramLibrary.cs b/tests/FiveStar.Loader.Tests/Support/ThrowingProgramLibrary.cs new file mode 100644 index 00000000..a23f8341 --- /dev/null +++ b/tests/FiveStar.Loader.Tests/Support/ThrowingProgramLibrary.cs @@ -0,0 +1,18 @@ +// Copyright (c) 2026 Five Star Recomp contributors. +// SPDX-License-Identifier: GPL-3.0-or-later + +using FiveStar.Loader.Shims.D3D12X.Pipelines; + +namespace FiveStar.Loader.Tests.Support; + +/// A program library whose every read throws, as a corrupt program file would. +internal sealed class ThrowingProgramLibrary : IProgramLibrary +{ + public TranslatedProgram? Find(ReadOnlySpan prefix) => throw new InvalidDataException("unreadable program"); + + public IReadOnlyList Names(ReadOnlySpan prefix) => throw new InvalidDataException("unreadable program"); + + public TranslatedProgram? Load(string name) => throw new InvalidDataException("unreadable program"); + + public long HeldBytes => 0; +}