From 43801fdaab81521f9bd802d15a0370160090174a Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Wed, 25 Nov 2026 18:50:59 +0100 Subject: [PATCH 1/2] D3D12.X: rectangle-list variants build off the game's threads A rectangle-list draw built its pipeline's variant on the drawing thread, outside the compile budget and the in-flight list. The variant of a tiled-lighting pipeline is a full compile of its pixel program. In a run that reached the opening cutscene, a game job thread sat in CreatePipelineState inside the driver's compiler for over 25 s: a ninth driver compile next to the eight budgeted builds in flight, all of them tiled-lighting pipelines taking 1 to 21 s each. The frame waited for that job, and the game's 30 s hang watchdog ended the run. The first draw now starts the variant's build on a thread of its own, within the compile budget, and is skipped; later draws bind the variant once it is built. A build that finishes after its pipeline address was remembered again is released. The rectangle-list count line adds the draws skipped while a variant built. Test: the first rectangle-list draw is skipped and draws nothing; once the variant is built, the draw covers the whole rectangle. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12x-shim.md | 8 +- .../Binding/CommandListBindingMethods.cs | 16 +++- .../D3D12X/Pipelines/RectanglePipelines.cs | 84 +++++++++++++++---- .../Shims/D3D12X/Pipelines/VariantBuild.cs | 12 +++ .../Shims/D3D12X/RectangleDraws.cs | 37 +++++--- .../D3D12XRectangleListTests.cs | 9 +- 6 files changed, 135 insertions(+), 31 deletions(-) create mode 100644 src/FiveStar.Loader/Shims/D3D12X/Pipelines/VariantBuild.cs diff --git a/docs/d3d12x-shim.md b/docs/d3d12x-shim.md index 226f3cf4..86a21639 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: start the variant's build on a thread of its own (within the compile budget) and skip the draw; once built, bind it | `RectangleDraws.BeforeDraw` (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..fe477ee4 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 (bound otherwise). + if (ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self)) + { + return; + } + if (DepthTwins.Any) { CopyTwin(self); @@ -349,7 +355,6 @@ public static void DrawInstanced(XboxObject* self, uint vertices, uint instances GpuBreadcrumbs.Before(self, MarkedKind.Draw, vertices, instances, 0); BeforeWork(self, false); - ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); ShimContext.Runtime.D3D12X.DrawTrace?.Draw(self, vertices, instances); nint inner = self->Inner; ((delegate* unmanaged)ComObject.Slot(inner, DesktopDrawInstanced))(inner, vertices, instances, firstVertex, firstInstance); @@ -372,6 +377,12 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins return; } + // A rectangle-list draw whose variant still builds is skipped (bound otherwise). + if (ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self)) + { + return; + } + if (DepthTwins.Any) { CopyTwin(self); @@ -382,7 +393,6 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins GpuBreadcrumbs.Before(self, MarkedKind.Draw, indices, instances, 0); BeforeWork(self, false); - ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); ShimContext.Runtime.D3D12X.DrawTrace?.Draw(self, indices, instances); nint inner = self->Inner; ((delegate* unmanaged)ComObject.Slot(inner, DesktopDrawIndexedInstanced))(inner, indices, instances, firstIndex, baseVertex, firstInstance); @@ -592,7 +602,7 @@ internal static void RestoreCompute(XboxObject* self) if (rectangles->Topology == PrimitiveTopologies.RectangleList) { - ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); + _ = ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); } } diff --git a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs index 494b3670..79d28ce9 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,6 +23,9 @@ 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; @@ -30,6 +33,7 @@ internal sealed unsafe class RectanglePipelines private readonly OnceLog _warnings; 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). @@ -103,7 +107,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 starts + /// the build on a thread of its own 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 +121,65 @@ 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 started and . + private nint Start(nint pipeline) { - nint variant = 0; - - if (_recipes.TryGetValue(pipeline, out var recipe)) + if (!_recipes.TryGetValue(pipeline, out var recipe)) { - variant = Build(recipe); + _variants.TryAdd(pipeline, 0); + + return _variants[pipeline]; } - if (_variants.TryAdd(pipeline, variant)) + var build = new VariantBuild(recipe); + + if (_building.TryAdd(pipeline, build)) { - return variant; + var thread = new Thread(() => Finish(pipeline, build)) { IsBackground = true, Name = "fivestar rectangle variant" }; + thread.Start(); } - if (variant != 0) + 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); + } + + /// Builds the variant within the compile budget, then keeps it unless the pipeline was remembered again since. + private void Finish(nint pipeline, VariantBuild build) + { + nint variant = 0; + + try { - DesktopDevice.Release(variant); + variant = Build(build.Recipe); } + finally + { + if (_recipes.TryGetValue(pipeline, out var current) && ReferenceEquals(current, build.Recipe) && _variants.TryAdd(pipeline, variant)) + { + variant = 0; + } - return _variants[pipeline]; + if (variant != 0) + { + DesktopDevice.Release(variant); + } + + _building.TryRemove(new KeyValuePair(pipeline, build)); + build.Done.Set(); + } } private nint Build(RectangleRecipe recipe) @@ -166,7 +211,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..f9476c10 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,20 +81,25 @@ public void Reset(XboxObject* list, nint pipeline) state->Pipeline = pipeline; } - /// Before a draw: under the rectangle list, binds the variant and counts the draw. + /// + /// Before a draw: under the rectangle list, binds the variant and counts the draw. True when the draw is to be + /// skipped: its variant is still building (off the game's threads), and half of each rectangle is not drawn instead. + /// [HotPath] - public void BeforeDraw(XboxObject* list) + public bool BeforeDraw(XboxObject* list) { var state = RectangleListState.Of(list); if (state->Topology != PrimitiveTopologies.RectangleList) { - return; + return false; } - if (state->VariantBound == 0) + if (state->VariantBound == 0 && BindVariant(list, state) == RectanglePipelines.Pending) { - BindVariant(list, state); + Interlocked.Increment(ref _pending); + + return true; } if (state->VariantBound == 0) @@ -99,32 +109,37 @@ public void BeforeDraw(XboxObject* list) Warn(state->Pipeline); } - return; + return false; } if ((Interlocked.Increment(ref _expanded) & (ReportInterval - 1)) == 0) { Report(); } + + return false; } + /// Binds the variant when it is built; returns what gave (0 without pipelines). [HotPath] - private void BindVariant(XboxObject* list, RectangleListState* state) + private nint BindVariant(XboxObject* list, RectangleListState* state) { var pipelines = Pipelines; if (pipelines is null || state->Pipeline == 0) { - return; + return 0; } nint variant = pipelines.Variant(state->Pipeline); - if (variant != 0) + if (variant != 0 && variant != RectanglePipelines.Pending) { Bind(list, variant); state->VariantBound = 1; } + + return variant; } [HotPath] @@ -141,6 +156,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/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs b/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs index ccfbb179..f7f5bb85 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 { @@ -78,6 +79,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. From a041f48617e6f530df5df4af08b5df0ef7bc0b22 Mon Sep 17 00:00:00 2001 From: Robin Snyders Date: Wed, 25 Nov 2026 22:19:41 +0100 Subject: [PATCH 2/2] D3D12.X: rectangle variants build on the pipeline build queue and bind after the depth-twin copy Review of #49: - A draw checks first whether its variant still builds (RectangleDraws.Building) and is skipped then; the variant is bound right before the draw as before, after CopyTwin, which binds the game's pipeline again (--depth-twins). - Variants are urgent creations on the pipeline build queue, not a thread each. - A build that throws is reported once and keeps 0 (drawn as triangles): it no longer ends the build thread. - Start checks the variants again once its build is registered: a build that finished between Variant's two lookups no longer starts a second one. Co-Authored-By: Claude Opus 5.5 --- docs/d3d12x-shim.md | 2 +- .../Binding/CommandListBindingMethods.cs | 12 +++-- .../D3D12X/Pipelines/RectanglePipelines.cs | 46 +++++++++++++----- .../Shims/D3D12X/RectangleDraws.cs | 47 +++++++++++++------ .../Shims/D3D12X/XboxDeviceFactory.cs | 4 +- .../D3D12XRectangleListTests.cs | 40 ++++++++++++++-- .../Support/ThrowingProgramLibrary.cs | 18 +++++++ 7 files changed, 132 insertions(+), 37 deletions(-) create mode 100644 tests/FiveStar.Loader.Tests/Support/ThrowingProgramLibrary.cs diff --git a/docs/d3d12x-shim.md b/docs/d3d12x-shim.md index 86a21639..0c9a8780 100644 --- a/docs/d3d12x-shim.md +++ b/docs/d3d12x-shim.md @@ -721,7 +721,7 @@ 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: start the variant's build on a thread of its own (within the compile budget) and skip the draw; once built, bind it | `RectangleDraws.BeforeDraw` (slots 12, 13), `RectanglePipelines.Variant` | +| 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 diff --git a/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs b/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs index fe477ee4..dbd518a1 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/Binding/CommandListBindingMethods.cs @@ -339,8 +339,8 @@ public static void DrawInstanced(XboxObject* self, uint vertices, uint instances return; } - // A rectangle-list draw whose variant still builds is skipped (bound otherwise). - if (ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self)) + // A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin. + if (ShimContext.Runtime.D3D12X.Rectangles.Building(self)) { return; } @@ -355,6 +355,7 @@ public static void DrawInstanced(XboxObject* self, uint vertices, uint instances GpuBreadcrumbs.Before(self, MarkedKind.Draw, vertices, instances, 0); BeforeWork(self, false); + ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); ShimContext.Runtime.D3D12X.DrawTrace?.Draw(self, vertices, instances); nint inner = self->Inner; ((delegate* unmanaged)ComObject.Slot(inner, DesktopDrawInstanced))(inner, vertices, instances, firstVertex, firstInstance); @@ -377,8 +378,8 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins return; } - // A rectangle-list draw whose variant still builds is skipped (bound otherwise). - if (ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self)) + // A rectangle-list draw whose variant still builds is skipped; the variant is bound after CopyTwin. + if (ShimContext.Runtime.D3D12X.Rectangles.Building(self)) { return; } @@ -393,6 +394,7 @@ public static void DrawIndexedInstanced(XboxObject* self, uint indices, uint ins GpuBreadcrumbs.Before(self, MarkedKind.Draw, indices, instances, 0); BeforeWork(self, false); + ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); ShimContext.Runtime.D3D12X.DrawTrace?.Draw(self, indices, instances); nint inner = self->Inner; ((delegate* unmanaged)ComObject.Slot(inner, DesktopDrawIndexedInstanced))(inner, indices, instances, firstIndex, baseVertex, firstInstance); @@ -602,7 +604,7 @@ internal static void RestoreCompute(XboxObject* self) if (rectangles->Topology == PrimitiveTopologies.RectangleList) { - _ = ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); + ShimContext.Runtime.D3D12X.Rectangles.BeforeDraw(self); } } diff --git a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs index 79d28ce9..368d0ae9 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/Pipelines/RectanglePipelines.cs @@ -31,6 +31,7 @@ internal sealed unsafe class RectanglePipelines 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(); @@ -41,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; @@ -108,10 +111,10 @@ public static bool Derived(string name) } /// - /// The variant of a desktop pipeline; 0 when it has none; while it builds. The first call starts - /// the build on a thread of its own 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. + /// 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) @@ -129,7 +132,7 @@ public nint Variant(nint pipeline) return Start(pipeline); } - /// The first call for a pipeline: 0 without a recipe, otherwise its build started and . + /// The first call for a pipeline: 0 without a recipe, otherwise its build queued and . private nint Start(nint pipeline) { if (!_recipes.TryGetValue(pipeline, out var recipe)) @@ -141,12 +144,22 @@ private nint Start(nint pipeline) var build = new VariantBuild(recipe); - if (_building.TryAdd(pipeline, build)) + if (!_building.TryAdd(pipeline, build)) { - var thread = new Thread(() => Finish(pipeline, build)) { IsBackground = true, Name = "fivestar rectangle variant" }; - thread.Start(); + return Pending; + } + + // A build that finished between the caller's two lookups left its variant: no second build. + if (_variants.TryGetValue(pipeline, out var built)) + { + _building.TryRemove(new KeyValuePair(pipeline, build)); + build.Done.Set(); + + return built; } + _builds.Queue(() => Finish(pipeline, build), urgent: true); + return Pending; } @@ -156,19 +169,28 @@ public bool WaitBuilt(nint pipeline, TimeSpan timeout) return !_building.TryGetValue(pipeline, out var build) || build.Done.Wait(timeout); } - /// Builds the variant within the compile budget, then keeps it unless the pipeline was remembered again since. - private void Finish(nint pipeline, VariantBuild build) + /// + /// 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 { 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; } @@ -180,6 +202,8 @@ private void Finish(nint pipeline, VariantBuild build) _building.TryRemove(new KeyValuePair(pipeline, build)); build.Done.Set(); } + + return new PipelineResult(HResult.Ok, kept); } private nint Build(RectangleRecipe recipe) diff --git a/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs b/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs index f9476c10..825bf248 100644 --- a/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs +++ b/src/FiveStar.Loader/Shims/D3D12X/RectangleDraws.cs @@ -82,24 +82,45 @@ public void Reset(XboxObject* list, nint pipeline) } /// - /// Before a draw: under the rectangle list, binds the variant and counts the draw. True when the draw is to be - /// skipped: its variant is still building (off the game's threads), and half of each rectangle is not drawn instead. + /// 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 BeforeDraw(XboxObject* list) + public bool Building(XboxObject* list) { var state = RectangleListState.Of(list); + var pipelines = Pipelines; - if (state->Topology != PrimitiveTopologies.RectangleList) + 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; } - if (state->VariantBound == 0 && BindVariant(list, state) == RectanglePipelines.Pending) + 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) + { + var state = RectangleListState.Of(list); + + if (state->Topology != PrimitiveTopologies.RectangleList) { - Interlocked.Increment(ref _pending); + return; + } - return true; + if (state->VariantBound == 0) + { + BindVariant(list, state); } if (state->VariantBound == 0) @@ -109,37 +130,33 @@ public bool BeforeDraw(XboxObject* list) Warn(state->Pipeline); } - return false; + return; } if ((Interlocked.Increment(ref _expanded) & (ReportInterval - 1)) == 0) { Report(); } - - return false; } - /// Binds the variant when it is built; returns what gave (0 without pipelines). [HotPath] - private nint BindVariant(XboxObject* list, RectangleListState* state) + private void BindVariant(XboxObject* list, RectangleListState* state) { var pipelines = Pipelines; if (pipelines is null || state->Pipeline == 0) { - return 0; + return; } nint variant = pipelines.Variant(state->Pipeline); + // 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; } - - return variant; } [HotPath] 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 f7f5bb85..65d7ed6c 100644 --- a/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs +++ b/tests/FiveStar.Loader.Tests/D3D12XRectangleListTests.cs @@ -65,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(); @@ -104,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)) }; @@ -122,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; +}