acdream/tests/AcDream.App.Tests/Rendering/ChargenPreviewControllerTests.cs
Erik d2a71152d2 fix(chargen): Campaign CC CC6b-MOUNT review fix round — F1-F13
Fixes every finding from the dual-lens review of 34c6fceab0 (architectural
PASS-with-items, retail-fidelity FAIL). Re-derived every decomp citation
against docs/research/named-retail/acclient_2013_pseudo_c.txt directly
rather than trusting the reviewer's transcription.

Wrap/normalize semantics (F1): CycleIndex's decrement-from-Unset landed on
0; the decomp's shared decrement tail (label_47f065/label_47f6d9, the same
switch the headgear ring was ported from) computes new=cur-1=-2 on the raw
signed int32, which wraps to count-1 — matching headgear's own ring shape.
Also ports the spin body-click normalize-and-write-back retail's cases
0xa5-0xae all share (NormalizeChoiceOnSelect), which acdream had dropped
entirely. Flips the one test that pinned the wrong expectation and adds
select-zone coverage no prior test isolated.

Heritage gate (F3): Update's Gearknight/Olthoi/OlthoiAcid branches reset
SetChoice(FACE)/SetSelection(HAIR) unconditionally, not only when Clothes
was showing — a conditional gate stranded Nose/Mouth as the current part
under a Face-tab session.

Doc corrections propagated everywhere they repeated (F4, F5, F6, plus the
plan doc's own CC6b-MOUNT ledger row for F1/F3): the gmBarberUI heading
citation conflated PostInit with InitializePage; Random's Appearance
disable was mislabeled a placeholder when it's really AP-212's unported
RandomizeAppearance/RandomizeClothing gap; the master-page doc still called
the Appearance page content-inert after this campaign made it real.

Visual substitutions widened (F2): AP-215 named only two of the Appearance
page's swatch/spin substitutions. Ports the two cheap ones directly —
current-part highlight via SetSelection's SetState(1)/SetState(6), routed
through the existing UiButtonStateMachine.Normal/Highlight ids and
IUiDatStateful.TrySetRetailState seam (installed-DAT-confirmed
ToggleBehavior=true on all nine spins); the shade scrollbar's SetVisible(0)
for Eyes vs acdream's Enabled=false. Files the other five (DoColorSpots,
the inert GradCircle, spin-caption/heritage-caption loss, the Skin-spin
MoveTo reposition, the Gearknight-boundary randomize calls) as new register
rows AP-216..AP-220 and corrects the plan doc's false claim that AP-215
already named the GradCircle.

Unlocked DAT read (F7, BLOCKER): ChargenPreviewController.Rebuild called
ChargenAppearanceFactory.TryCompose outside _datLock while the very next
line correctly locked TryBuildAnimated — CC6a's own F4 class of bug,
reintroduced at this catalog's first production call site. Wrapped in the
same lock; documented the invariant on ChargenAppearanceCatalog itself.

One-shot preview mount (F8): LivePresentationComposition reads
ChargenPreviewViewportWidget once, but its underlying mount
(CharacterCreationUiMountCoordinator) is explicitly retryable while this
GPU-resource composition pass is not — unlike PaperdollViewportWidget,
which IS eager/non-retryable, so the "mirrors Paperdoll" doc claim was
false. Retrofitting cross-frame retry here would mean restructuring this
composition's one-shot contract for every private viewport (paperdoll,
creature appraisal) and FrameRootComposition's fixed frame-group array —
out of this round's blast radius. Corrected the doc and made the failure
loud (a diagnostic log) instead of silent.

Dispose leak (F9): ChargenPreviewController.Dispose left the preview
WorldEntity referenced by the leased renderer until the renderer's own,
later disposal. Releases it on its own teardown now.

Test-quality items (F10, F11, F13): pinned the spin arrow widths
(47px, both arrows) the 174 zone boundary is derived from, plus a
controller test for the previously-uncovered select zone. Measured the
shade scrollbar's authored orientation instead of assuming it — it is
VERTICAL (33x85) — which is a real production bug: UiScrollbar only routed
scalar-mode mouse events when Horizontal was true, so the shade control
never fired in production. Added OnVerticalScalarEvent/DrawVerticalScalar
mirroring the existing horizontal scalar path. Converted
ChargenPreviewControllerTests from silent-pass [Fact] to the shared
InstalledDatFactAttribute skip-reporting pattern.

Adjudication (F12): AD-101's retirement leaves TryBeginFinish's four local
refusals (NoName/AttributeCreditsUnspent/AlreadyPending/RosterFull) with no
heritage/gender gate — currently latent since Finish stays hard-disabled
this round. Amended the campaign plan's CC5 slice scope to require BOTH a
heritage/gender refusal AND a real RandomizeCharacter port before the
connected user gate opens Finish; noted the interaction on AP-214's own
register row. No CC5 implementation in this commit.

Gates: dotnet build -c Release green across the full solution. App suite
(Release, ACDREAM_PROBE_LIVE_MOUNT=1) 5223/3 skips, Runtime suite
1713/0 — both clean across repeated runs. A full-solution run surfaced
three pre-existing, previously-documented flakes unrelated to this change
(Streaming.LandblockBuildFactoryTests/LandblockPresentationPipelineTests
#402, Core.Net.Tests.NakEmissionTests loss soak) — each confirmed passing
in isolation, consistent with their known full-suite-parallelism-timing
history; none touch any file this commit changes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-15 22:19:02 +02:00

304 lines
13 KiB
C#

using System.Numerics;
using AcDream.App.Rendering;
using AcDream.App.Tests.UI.Layout; // InstalledDatFactAttribute (fix round F13)
using AcDream.Content;
using AcDream.Content.CharGen;
using AcDream.Content.Vfx;
using AcDream.Core.CharGen;
using AcDream.Core.Physics.Motion;
using AcDream.Core.World;
using DatReaderWriter;
using DatReaderWriter.Options;
using Xunit;
using Xunit.Abstractions;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Campaign CC slice CC6b-MOUNT — installed-DAT gate for
/// <see cref="ChargenPreviewController"/>'s rebuild/render logic, using fake
/// <see cref="IChargenPreviewRenderer"/>/<see cref="IChargenPreviewFrameView"/>
/// implementations (no live GPU device needed — mirrors
/// <c>PaperdollFramePresenterTests</c>'s recording-fake pattern) against a
/// REAL dat-backed <see cref="ChargenOptions"/>/<see cref="ChargenAppearanceCatalog"/>
/// so <c>ChargenAppearanceFactory.TryCompose</c> and
/// <c>ChargenPreviewEntityBuilder.TryBuildAnimated</c> actually run.
///
/// <para>
/// Fix round F13: every case uses
/// <see cref="InstalledDatFactAttribute"/> (shared with
/// <c>CharacterCreationLiveDatTests</c>/<c>CharacterManagementLiveDatTests</c>)
/// instead of plain <c>[Fact]</c>. Before this fix, a bare <c>[Fact]</c> plus
/// <see cref="TryOpen"/>'s own <c>if (!TryOpen(...)) return;</c> guard made
/// all six cases pass SILENTLY with zero assertions run whenever
/// <c>ACDREAM_DAT_DIR</c> was unavailable — indistinguishable in the test
/// runner's summary from an actual passing run. The attribute now reports
/// those runs as Skipped so the counts show "ran" separately from "no-op'd".
/// </para>
/// </summary>
public sealed class ChargenPreviewControllerTests
{
private readonly ITestOutputHelper _out;
public ChargenPreviewControllerTests(ITestOutputHelper output) => _out = output;
private const uint AluvianId = 1u;
private const uint GearknightId = 6u;
[InstalledDatFact]
public void Rebuild_SameSelectionTwice_IsANoOpSecondTime()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView();
var controller = new ChargenPreviewController(
renderer, new ChargenPreviewCamera(), view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
ChargenAppearanceSelection selection = DefaultSelection(options, AluvianId, 1);
Assert.True(controller.Rebuild(options, AluvianId, 1, selection));
Assert.True(controller.Rebuild(options, AluvianId, 1, selection));
Assert.Equal(1, renderer.SetPreviewCallCount);
}
}
[InstalledDatFact]
public void Rebuild_HeritageChange_ResetsCameraToTheNewHeritagesDefaultEye()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView();
var camera = new ChargenPreviewCamera();
var controller = new ChargenPreviewController(
renderer, camera, view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
Assert.True(controller.Rebuild(
options, AluvianId, 1, DefaultSelection(options, AluvianId, 1)));
// Poke the SAME camera instance the controller shares (this is
// exactly the injection seam ChargenPreviewController's own doc
// comment describes) — simulates the camera having drifted away
// from the heritage default (e.g. mid zoom-out tween).
camera.Eye = new Vector3(0f, -99f, 99f);
if (!options.TryGetHeritage(GearknightId, out ChargenHeritageOptions? gearknight)
|| gearknight!.GendersByKey.Count == 0)
{
_out.WriteLine("SKIP: installed dat has no Gearknight gender to switch to.");
return;
}
int gearknightGender = gearknight.GendersByKey.Keys.First();
Assert.True(controller.Rebuild(
options, GearknightId, gearknightGender,
DefaultSelection(options, GearknightId, gearknightGender)));
Assert.Equal(ChargenPreviewCamera.ResolveDefaultEye(GearknightId), controller.CameraEye);
}
}
/// <summary>
/// Decomp-cited (<c>gmCGAppearancePage::Update</c>'s two confirmed direct
/// call sites — <c>InitializePage</c> and the gender-button handlers —
/// vs the narrower <c>SetSelection</c>/<c>SetColor</c>/<c>SetShade</c>
/// every spin/color/shade change goes through instead): a rebuild that
/// changes ONLY the appearance selection (same heritage, same gender)
/// must NOT snap the camera back to the heritage default.
/// </summary>
[InstalledDatFact]
public void Rebuild_AppearanceOnlyChange_LeavesTheCameraUntouched()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView();
var camera = new ChargenPreviewCamera();
var controller = new ChargenPreviewController(
renderer, camera, view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
ChargenAppearanceSelection first = DefaultSelection(options, AluvianId, 1);
Assert.True(controller.Rebuild(options, AluvianId, 1, first));
var pokedEye = new Vector3(0f, -99f, 99f);
camera.Eye = pokedEye;
ChargenAppearanceSelection second = first with { SkinShade = 0.9 };
Assert.True(controller.Rebuild(options, AluvianId, 1, second));
Assert.Equal(pokedEye, controller.CameraEye);
}
}
[InstalledDatFact]
public void Rebuild_PreservesZoomState_AcrossAnAppearanceOnlyChange()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView();
var controller = new ChargenPreviewController(
renderer, new ChargenPreviewCamera(), view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
ChargenAppearanceSelection first = DefaultSelection(options, AluvianId, 1);
Assert.True(controller.Rebuild(options, AluvianId, 1, first));
controller.ZoomIn();
Assert.True(controller.IsZoomedIn);
// A DIFFERENT selection, same heritage/gender — retail's
// gmCGAppearancePage::Update only resets the camera POSITION on
// heritage/gender change; m_bZoomedIn is untouched by spin/color/
// shade edits.
ChargenAppearanceSelection second = first with { SkinShade = 0.9 };
Assert.True(controller.Rebuild(options, AluvianId, 1, second));
Assert.True(controller.IsZoomedIn);
}
}
[InstalledDatFact]
public void Rebuild_ThenRender_SeedsTheEntityHeadingToTheRetailDefault180Degrees()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView();
var controller = new ChargenPreviewController(
renderer, new ChargenPreviewCamera(), view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
Assert.True(controller.Rebuild(
options, AluvianId, 1, DefaultSelection(options, AluvianId, 1)));
Assert.NotNull(renderer.LastEntity);
controller.Render();
Quaternion expected = MoveToMath.SetHeading(
Quaternion.Identity, ChargenPreviewRotationController.RetailDefaultHeadingDegrees);
Quaternion actual = renderer.LastEntity!.Rotation;
Assert.Equal(expected.X, actual.X, 4);
Assert.Equal(expected.Y, actual.Y, 4);
Assert.Equal(expected.Z, actual.Z, 4);
Assert.Equal(expected.W, actual.W, 4);
}
}
[InstalledDatFact]
public void Render_WhilePageInvisible_SkipsRenderAndTexturePublication()
{
if (!TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter))
return;
using (dats)
using (adapter)
{
(ChargenOptions options, ChargenAppearanceCatalog catalog) = LoadFixture(adapter!);
var renderer = new FakeChargenRenderer();
var view = new FakeChargenView { Visible = false };
var controller = new ChargenPreviewController(
renderer, new ChargenPreviewCamera(), view,
adapter!, new RetailAnimationLoader(adapter!), catalog, catalog, new object());
Assert.True(controller.Rebuild(
options, AluvianId, 1, DefaultSelection(options, AluvianId, 1)));
controller.Render();
Assert.Equal(0, renderer.RenderCallCount);
Assert.Null(view.LastTextureHandle);
}
}
private static ChargenAppearanceSelection DefaultSelection(
ChargenOptions options, uint heritageId, int genderKey)
{
Assert.True(options.TryGetHeritage(heritageId, out ChargenHeritageOptions? heritage));
Assert.True(heritage!.GendersByKey.TryGetValue(genderKey, out ChargenGenderOptions? gender));
return ChargenAppearanceSelection.Default with
{
HairStyle = gender!.HairStyles.Count > 0 ? 0u : ChargenAppearanceSelection.Unset,
SkinShade = 0.5,
};
}
private static (ChargenOptions, ChargenAppearanceCatalog) LoadFixture(IDatReaderWriter dats) =>
(ChargenTableReader.Load(dats), new ChargenAppearanceCatalog(dats));
/// <summary>
/// Fix round F13: <see cref="InstalledDatFactAttribute"/> already gates
/// every case above this call, so <c>datDir is null</c> should not be
/// reachable in practice once a case actually runs — this stays as
/// defense-in-depth (a DAT directory that exists but a corrupt/renamed
/// <c>client_portal.dat</c> the attribute's own lighter check missed)
/// rather than a silent no-assertions pass.
/// </summary>
private bool TryOpen(out DatCollection? dats, out DatCollectionAdapter? adapter)
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null)
{
_out.WriteLine("SKIP: dats unavailable");
dats = null;
adapter = null;
return false;
}
dats = new DatCollection(datDir, DatAccessType.Read);
adapter = new DatCollectionAdapter(dats);
return true;
}
private sealed class FakeChargenRenderer : IChargenPreviewRenderer
{
public WorldEntity? LastEntity { get; private set; }
public int SetPreviewCallCount { get; private set; }
public int RenderCallCount { get; private set; }
public void SetPreview(WorldEntity? entity)
{
LastEntity = entity;
SetPreviewCallCount++;
}
public uint Render(int width, int height)
{
RenderCallCount++;
return 42u;
}
}
private sealed class FakeChargenView : IChargenPreviewFrameView
{
public bool Visible { get; set; } = true;
public int Width { get; set; } = 128;
public int Height { get; set; } = 128;
public uint? LastTextureHandle { get; private set; }
public bool TryGetVisibleSize(out int width, out int height)
{
width = Width;
height = Height;
return Visible;
}
public void SetTextureHandle(uint textureHandle) => LastTextureHandle = textureHandle;
}
}