acdream/tests/AcDream.App.Tests/Rendering/GlTextureOwnershipTests.cs
Erik 9aaf97e785 Revert "Campaign V slice V4a" - it lost world multisampling
This reverts ceec3bc4. Two independent reasons, either sufficient.

The rendering regression. The slice deleted TextRenderGlStateScope, which
saved GL_MULTISAMPLE and GL_SAMPLE_ALPHA_TO_COVERAGE on entry, disabled them
for the text pass, and restored them on exit (TextRenderGlStateScope.cs:111-112
and 153-154 at the parent commit). Its replacement bakes that state into the
text pipeline but nothing restores it, and GlGpuPassEncoder.Dispose does not
either. Every world renderer is still raw GL at this point in the campaign, so
from the first UI frame onward the world drew with multisampling disabled.

The offline pixel gate caught it: 1,791 of 563,200 compared pixels differed,
0.318% against a 0.001 threshold. The commit message attributed this to
wall-clock-driven ambient animation shifting phase, and committed through the
failure. That explanation does not survive its own control: capturing twice at
the reverted-to commit differs by 19 pixels and twice at the slice's own commit
by 8, while base-versus-head differs by 1,791 - a 224x gap that no shared-noise
source explains. An amplified difference image settles it visually: the changed
pixels are the silhouette edges of every tree, building and rock, with terrain
interiors, water and the entire UI untouched. That is the signature of losing
edge antialiasing, not of animated sprites.

This is the exact failure mode two existing memory notes already warn about -
a mid-frame renderer must set every GL state it uses rather than inherit it,
and issue #52's lesson that a rendering migration must audit per-pass GL state
before declaring itself done.

The scope. The brief was three small leaf renderers plus additive frame-
lifecycle wiring, roughly ten files. The commit changed 334 files with 3,665
insertions and 3,845 deletions, including 323 public-to-internal visibility
conversions across the App assembly, 55 test files, two retired conformance
tests, and a self-described temporary escape hatch for bridging raw-GL viewport
textures. Even without the regression, that is not separable into the part
worth keeping and the part worth dropping.

Reverting rather than patching because the good work here - the RHI frame
lifecycle wiring and a genuine render-state-cache staleness fix - is small
enough to redo cleanly against a tightened spec, while untangling it from 300+
files of unrelated churn is not.

Post-revert: Release build clean, App suite back to 3,843 passed / 3 skipped,
offline pixel gate passing at 19 differing pixels.

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

396 lines
14 KiB
C#

using AcDream.App.Rendering;
namespace AcDream.App.Tests.Rendering;
public sealed class GlTextureOwnershipTests
{
[Fact]
public void ConstructionRollbackDeletesAllNamesInReverseOrder()
{
var api = new FakeTextureNameApi();
var transaction = new GlTextureConstructionTransaction(api);
Assert.Equal(1u, transaction.Allocate());
Assert.Equal(2u, transaction.Allocate());
Assert.Equal(3u, transaction.Allocate());
transaction.Rollback();
transaction.Rollback();
Assert.Equal([3u, 2u, 1u], api.DeleteAttempts);
}
[Fact]
public void ConstructionRollbackAttemptsEveryNameAndReportsFailures()
{
var api = new FakeTextureNameApi { FailingDelete = 2 };
var transaction = new GlTextureConstructionTransaction(api);
_ = transaction.Allocate();
_ = transaction.Allocate();
_ = transaction.Allocate();
AggregateException failure = Assert.Throws<AggregateException>(transaction.Rollback);
Assert.Single(failure.InnerExceptions);
Assert.Equal([3u, 2u, 1u], api.DeleteAttempts);
Assert.Equal([3u, 1u], api.Deleted);
api.FailingDelete = null;
transaction.RetryCleanup();
Assert.True(transaction.IsCleanupComplete);
Assert.Equal([3u, 2u, 1u, 2u], api.DeleteAttempts);
Assert.Equal([3u, 1u, 2u], api.Deleted);
}
[Fact]
public void CommittedNamesAreNeverDeletedByConstructionTransaction()
{
var api = new FakeTextureNameApi();
var transaction = new GlTextureConstructionTransaction(api);
_ = transaction.Allocate();
_ = transaction.Allocate();
transaction.Commit();
transaction.Rollback();
Assert.Empty(api.DeleteAttempts);
Assert.Throws<InvalidOperationException>(() => transaction.Allocate());
}
[Fact]
public void TrackedTextureUploadFailureLeavesEveryActualBranchNameInTransaction()
{
var api = new FakeTextureNameApi();
var transaction = new GlTextureConstructionTransaction(api);
uint first = TrackedTextureConstruction.Create(transaction, _ => { });
Assert.Throws<InvalidOperationException>(() =>
TrackedTextureConstruction.Create(
transaction,
_ => throw new InvalidOperationException("upload failed")));
transaction.Rollback();
Assert.Equal(1u, first);
Assert.Equal([2u, 1u], api.DeleteAttempts);
}
[Fact]
public void TerrainAtlasRoutesEveryTerrainAlphaAndFallbackUploadThroughTracker()
{
string source = File.ReadAllText(Path.Combine(
FindRepoRoot(),
"src",
"AcDream.App",
"Rendering",
"TerrainAtlas.cs"));
Assert.Equal(5, CountOccurrences(source, "TrackedTextureConstruction.Create("));
Assert.Equal(
5,
System.Text.RegularExpressions.Regex.Matches(
source,
"TrackedTextureConstruction\\.Create\\(\\s*textures,\\s*gl,\\s*\\\"").Count);
Assert.DoesNotContain("textures.Allocate()", source, StringComparison.Ordinal);
}
[Fact]
public void ProductionGlResourcePathsUseAlwaysOnCheckedCommitBoundaries()
{
string root = FindRepoRoot();
string textureNames = File.ReadAllText(Path.Combine(
root, "src", "AcDream.App", "Rendering", "GlTextureConstructionTransaction.cs"));
string shaderPrograms = File.ReadAllText(Path.Combine(
root, "src", "AcDream.App", "Rendering", "ShaderProgramConstruction.cs"));
string terrain = File.ReadAllText(Path.Combine(
root, "src", "AcDream.App", "Rendering", "TerrainAtlas.cs"));
string text = File.ReadAllText(Path.Combine(
root, "src", "AcDream.App", "Rendering", "TextRenderer.cs"));
string bindless = File.ReadAllText(Path.Combine(
root, "src", "AcDream.App", "Rendering", "Wb", "BindlessSupport.cs"));
Assert.Contains("GlResourceCommand.CreateTexture", textureNames, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.DeleteTexture", textureNames, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.CreateName", shaderPrograms, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.DeleteShader", shaderPrograms, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.DeleteProgram", shaderPrograms, StringComparison.Ordinal);
Assert.Contains("_anisotropyBindingMutation.Execute", terrain, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.DeleteTexture", terrain, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.CreateTexture", text, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.Execute", text, StringComparison.Ordinal);
Assert.Contains("make bindless handle", bindless, StringComparison.Ordinal);
Assert.Contains("GlResourceCommand.Execute", bindless, StringComparison.Ordinal);
}
[Fact]
public void SecondBindlessAcquireFailureRollsBackFirstHandle()
{
var residency = new FakeResidency { FailingAcquireTexture = 20 };
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
Assert.Throws<InvalidOperationException>(() => pair.Acquire());
Assert.False(pair.IsFullyResident);
Assert.Equal([10u, 20u], residency.AcquireAttempts);
Assert.Equal([1010ul], residency.ReleaseAttempts);
}
[Fact]
public void FailedPrefixRollbackRemainsOwnedAndRetryDoesNotReacquireIt()
{
var residency = new FakeResidency
{
FailingAcquireTexture = 20,
FailingReleaseHandle = 1010,
};
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
Assert.Throws<AggregateException>(() => pair.Acquire());
residency.FailingAcquireTexture = null;
residency.FailingReleaseHandle = null;
Assert.Equal((1010ul, 1020ul), pair.Acquire());
Assert.True(pair.IsFullyResident);
Assert.Equal([10u, 20u, 20u], residency.AcquireAttempts);
Assert.Equal([1010ul], residency.ReleaseAttempts);
}
[Fact]
public void BindlessReleaseAttemptsBothAndRetriesOnlyPendingHandle()
{
var residency = new FakeResidency();
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
_ = pair.Acquire();
residency.FailingReleaseHandle = 1010;
Assert.Throws<AggregateException>(pair.Release);
Assert.False(pair.IsFullyResident);
Assert.True(pair.HasAnyResident);
Assert.Equal([1010ul, 1020ul], residency.ReleaseAttempts);
residency.FailingReleaseHandle = null;
pair.Release();
pair.Release();
Assert.False(pair.HasAnyResident);
Assert.Equal([1010ul, 1020ul, 1010ul], residency.ReleaseAttempts);
}
[Fact]
public void MutationFailureStillRestoresThePreviouslyResidentPair()
{
var residency = new FakeResidency();
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
var guard = new BindlessTextureMutationGuard(pair);
_ = pair.Acquire();
Assert.Throws<InvalidOperationException>(() =>
guard.Execute(() => throw new InvalidOperationException("mutation failed")));
Assert.True(pair.IsFullyResident);
Assert.False(guard.RestoreRequired);
Assert.Equal([10u, 20u, 10u, 20u], residency.AcquireAttempts);
}
[Fact]
public void FailedReacquireKeepsRestoreIntentUntilALaterMutationRetry()
{
var residency = new FakeResidency();
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
var guard = new BindlessTextureMutationGuard(pair);
_ = pair.Acquire();
residency.FailingAcquireTexture = 20;
Assert.Throws<InvalidOperationException>(() => guard.Execute(() => { }));
Assert.True(guard.RestoreRequired);
Assert.False(pair.HasAnyResident);
residency.FailingAcquireTexture = null;
guard.Execute(() => { });
Assert.False(guard.RestoreRequired);
Assert.True(pair.IsFullyResident);
Assert.Equal([10u, 20u, 10u, 20u, 10u, 20u], residency.AcquireAttempts);
}
[Fact]
public void PartialReleaseFailurePreventsMutationAndRestoresPairBeforeThrowing()
{
var residency = new FakeResidency();
var pair = new BindlessTexturePair(10, 20, residency.Acquire, residency.Release);
var guard = new BindlessTextureMutationGuard(pair);
_ = pair.Acquire();
residency.FailingReleaseHandle = 1010;
int mutations = 0;
Assert.Throws<AggregateException>(() => guard.Execute(() => mutations++));
Assert.Equal(0, mutations);
Assert.True(pair.IsFullyResident);
Assert.False(guard.RestoreRequired);
}
[Fact]
public void FailedTextureMutationRestoresTheExactPriorBinding()
{
var bindings = new List<uint>();
var owner = new RestoredTextureBindingMutation();
InvalidOperationException failure = Assert.Throws<InvalidOperationException>(() =>
owner.Execute(
() => 77,
bindings.Add,
42,
() => throw new InvalidOperationException("mutation failed")));
Assert.Equal("mutation failed", failure.Message);
Assert.Equal([42u, 77u], bindings);
}
[Fact]
public void TextureMutationReportsBothMutationAndBindingRestoreFailure()
{
int bindCalls = 0;
var owner = new RestoredTextureBindingMutation();
AggregateException failure = Assert.Throws<AggregateException>(() =>
owner.Execute(
() => 77,
_ =>
{
bindCalls++;
if (bindCalls == 2)
throw new InvalidOperationException("restore failed");
},
42,
() => throw new InvalidOperationException("mutation failed")));
Assert.Equal(2, failure.InnerExceptions.Count);
Assert.Equal(2, bindCalls);
Assert.True(owner.HasPendingRestore);
}
[Fact]
public void FailedBindingRestoreRetriesTheOriginalBindingBeforeAnotherMutation()
{
var owner = new RestoredTextureBindingMutation();
var bindings = new List<uint>();
int restoreFailures = 1;
int mutations = 0;
Assert.Throws<InvalidOperationException>(() =>
owner.Execute(
() => 77,
binding =>
{
bindings.Add(binding);
if (binding == 77 && restoreFailures-- > 0)
throw new InvalidOperationException("restore failed");
},
42,
() => mutations++));
Assert.True(owner.HasPendingRestore);
owner.Execute(
() => 77,
bindings.Add,
42,
() => mutations++);
Assert.False(owner.HasPendingRestore);
Assert.Equal([42u, 77u, 77u, 42u, 77u], bindings);
Assert.Equal(2, mutations);
}
[Fact]
public void ConstructionCleanupLedgerRetainsNestedFailureUntilRetryCompletes()
{
var api = new FakeTextureNameApi { FailingDelete = 1 };
var transaction = new GlTextureConstructionTransaction(api);
_ = transaction.Allocate();
AggregateException cleanupFailure = Assert.Throws<AggregateException>(
transaction.Rollback);
var constructionFailure = new GlResourceConstructionException(
"synthetic construction failure",
transaction,
[new InvalidOperationException("build failed"), cleanupFailure]);
var ledger = new GlConstructionCleanupLedger();
Assert.True(ledger.RetainFrom(constructionFailure));
Assert.Throws<AggregateException>(ledger.Dispose);
Assert.False(ledger.IsComplete);
api.FailingDelete = null;
ledger.Dispose();
Assert.True(ledger.IsComplete);
Assert.True(constructionFailure.IsCleanupComplete);
}
private sealed class FakeTextureNameApi : IGlTextureNameApi
{
private uint _nextName = 1;
public uint? FailingDelete { get; set; }
public List<uint> DeleteAttempts { get; } = [];
public List<uint> Deleted { get; } = [];
public uint GenTexture() => _nextName++;
public void DeleteTexture(uint texture)
{
DeleteAttempts.Add(texture);
if (FailingDelete == texture)
throw new InvalidOperationException("delete failed");
Deleted.Add(texture);
}
}
private static int CountOccurrences(string source, string value)
{
int count = 0;
int cursor = 0;
while ((cursor = source.IndexOf(value, cursor, StringComparison.Ordinal)) >= 0)
{
count++;
cursor += value.Length;
}
return count;
}
private static string FindRepoRoot()
{
DirectoryInfo? directory = new(AppContext.BaseDirectory);
while (directory is not null)
{
if (File.Exists(Path.Combine(directory.FullName, "AcDream.slnx")))
return directory.FullName;
directory = directory.Parent;
}
throw new DirectoryNotFoundException("Could not find AcDream.slnx.");
}
private sealed class FakeResidency
{
public uint? FailingAcquireTexture { get; set; }
public ulong? FailingReleaseHandle { get; set; }
public List<uint> AcquireAttempts { get; } = [];
public List<ulong> ReleaseAttempts { get; } = [];
public ulong Acquire(uint texture)
{
AcquireAttempts.Add(texture);
if (FailingAcquireTexture == texture)
throw new InvalidOperationException("acquire failed");
return 1000ul + texture;
}
public void Release(ulong handle)
{
ReleaseAttempts.Add(handle);
if (FailingReleaseHandle == handle)
throw new InvalidOperationException("release failed");
}
}
}