Merge campaign-cc6a: CC6a preview foundation + CC6b-PRE animation half, review-closed

CC6a (index->ObjDesc factory + static-pose offscreen renderer) and
CC6b-PRE (idle loop, rotation, zoom, alternate-setup plumbing) both
closed through dual-lens review -> fix round -> narrow re-review. The
branch carries its own cross-branch renumbering (TS-84, ISSUES #403) so
this merge is number-clean against the CC4 rows.

Notable review outcomes carried in: the barber refutation (chargen has
NO alternate-setup checkbox — all five write sites are gmBarberUI), the
idle-by-default finding with its corrected InitializePage evidence, and
the 180-degree initial heading owed to the mount half.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

# Conflicts:
#	docs/ISSUES.md
#	docs/architecture/retail-divergence-register.md
This commit is contained in:
Erik 2026-08-15 19:40:15 +02:00
commit 11374484dc
27 changed files with 4294 additions and 28 deletions

View file

@ -0,0 +1,154 @@
using System.Collections.Generic;
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Core.World;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Hand-built-fixture tests for <see cref="ChargenPreviewAnimator"/> — no dat
/// access needed, since a <see cref="ChargenPreviewAnimatedBuild"/> can be
/// constructed entirely in memory. Installed-DAT coverage for the RESOLUTION
/// half (<c>ChargenPreviewEntityBuilder.TryBuildAnimated</c> actually finding
/// the idle DID against real dat data) lives in
/// <c>ChargenPreviewEntityBuilderTests</c>.
/// </summary>
public sealed class ChargenPreviewAnimatorTests
{
private static Animation MakeTwoFrameAnim(Vector3 frame0Origin, Vector3 frame1Origin)
{
var anim = new Animation();
var pf0 = new AnimationFrame(1);
pf0.Frames.Add(new Frame { Origin = frame0Origin, Orientation = Quaternion.Identity });
var pf1 = new AnimationFrame(1);
pf1.Frames.Add(new Frame { Origin = frame1Origin, Orientation = Quaternion.Identity });
anim.PartFrames.Add(pf0);
anim.PartFrames.Add(pf1);
return anim;
}
private static ChargenPreviewAnimatedBuild MakeBuild(Animation? idleAnimation, int idleLow = 0, int idleHigh = 1)
{
const uint gfxObjId = 0x0100_0001u;
var restMeshRefs = new List<MeshRef>
{
new(gfxObjId, Matrix4x4.CreateTranslation(new Vector3(99f, 99f, 99f))), // distinct from any idle frame, so tests can tell them apart.
};
var drawableParts = new List<ChargenPreviewDrawablePart>
{
new(SetupPartIndex: 0, GfxObjId: gfxObjId, DefaultScale: Vector3.One, SurfaceOverrides: null),
};
var entity = new WorldEntity
{
Id = ChargenPreviewEntityBuilder.PreviewRenderId,
ServerGuid = ChargenPreviewEntityBuilder.PreviewServerGuid,
SourceGfxObjOrSetupId = 0x0200_0001u,
Position = Vector3.Zero,
Rotation = Quaternion.Identity,
MeshRefs = restMeshRefs,
};
return new ChargenPreviewAnimatedBuild
{
Entity = entity,
DrawableParts = drawableParts,
RestMeshRefs = restMeshRefs,
IdleAnimation = idleAnimation,
IdleLowFrame = idleLow,
IdleHighFrame = idleHigh,
};
}
[Fact]
public void Constructor_WithIdleAnimation_SeedsFrameZeroPose_NotTheRestPose()
{
// Retail's true default is the idle loop PLAYING, not the rest pose
// — see ChargenPreviewEntityBuilder's class doc.
var origin0 = new Vector3(1f, 0f, 0f);
var origin1 = new Vector3(5f, 0f, 0f);
var build = MakeBuild(MakeTwoFrameAnim(origin0, origin1));
var animator = new ChargenPreviewAnimator(build);
Assert.False(animator.IsZoomedIn);
Assert.Equal(origin0, animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void Constructor_WithNoIdleAnimation_KeepsTheRestPoseFallback()
{
var build = MakeBuild(idleAnimation: null);
var animator = new ChargenPreviewAnimator(build);
Assert.Equal(new Vector3(99f, 99f, 99f), animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void Tick_AdvancesTheIdleFrame_InterpolatingBetweenFrames()
{
var origin0 = new Vector3(0f, 0f, 0f);
var origin1 = new Vector3(10f, 0f, 0f);
var build = MakeBuild(MakeTwoFrameAnim(origin0, origin1));
var animator = new ChargenPreviewAnimator(build);
// 30fps, half a frame's worth of elapsed time -> currFrame 0.5, lerp halfway.
animator.Tick(1f / 60f);
Assert.Equal(5f, animator.Entity.MeshRefs[0].PartTransform.Translation.X, 3);
}
[Fact]
public void SetZoomedIn_True_SwapsToTheFrozenRestPoseImmediately()
{
var build = MakeBuild(MakeTwoFrameAnim(new Vector3(1f, 0f, 0f), new Vector3(5f, 0f, 0f)));
var animator = new ChargenPreviewAnimator(build);
animator.SetZoomedIn(true);
Assert.True(animator.IsZoomedIn);
Assert.Equal(new Vector3(99f, 99f, 99f), animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void Tick_WhileZoomedIn_DoesNotAdvanceTheFrozenPose()
{
var build = MakeBuild(MakeTwoFrameAnim(new Vector3(1f, 0f, 0f), new Vector3(5f, 0f, 0f)));
var animator = new ChargenPreviewAnimator(build);
animator.SetZoomedIn(true);
animator.Tick(10f); // large elapsed time — must still be a no-op while zoomed in.
Assert.Equal(new Vector3(99f, 99f, 99f), animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void SetZoomedIn_False_RestartsTheIdleLoopAtFrameZero()
{
var origin0 = new Vector3(1f, 0f, 0f);
var origin1 = new Vector3(5f, 0f, 0f);
var build = MakeBuild(MakeTwoFrameAnim(origin0, origin1));
var animator = new ChargenPreviewAnimator(build);
animator.Tick(1f / 30f); // advance to frame 1.
animator.SetZoomedIn(true);
animator.SetZoomedIn(false); // gmCG3DView::StartAnimation restarts the clip (clear-then-append).
Assert.Equal(origin0, animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void SetZoomedIn_SameStateTwice_IsANoOp()
{
var build = MakeBuild(MakeTwoFrameAnim(new Vector3(1f, 0f, 0f), new Vector3(5f, 0f, 0f)));
var animator = new ChargenPreviewAnimator(build);
animator.Tick(1f / 60f); // partway through frame 0->1.
Vector3 beforeX = animator.Entity.MeshRefs[0].PartTransform.Translation;
animator.SetZoomedIn(false); // already not zoomed in — must not restart the loop.
Assert.Equal(beforeX, animator.Entity.MeshRefs[0].PartTransform.Translation);
}
}

View file

@ -0,0 +1,110 @@
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Core.CharGen;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Pins <see cref="ChargenPreviewCamera"/>'s retail-verbatim per-heritage
/// eye positions (<c>gmCGAppearancePage::Update @ 0x0047E8F0</c>,
/// cross-checked against the identical literals in <c>ZoomIn</c>/<c>ZoomOut
/// @ 0x0047CF00</c>/<c>0x0047D050</c>) and the zero-yaw/zero-pitch look
/// convention DollCameraTests already established for the shared private
/// viewport.
/// </summary>
public class ChargenPreviewCameraTests
{
[Theory]
[InlineData((uint)ChargenHeritageGroup.Aluvian, 0f, -0.550000012f, 1.64999998f)]
[InlineData((uint)ChargenHeritageGroup.Gharundim, 0f, -0.550000012f, 1.64999998f)]
[InlineData((uint)ChargenHeritageGroup.Gearknight, 0f, -0.550000012f, 1.64999998f)]
[InlineData((uint)ChargenHeritageGroup.Undead, 0f, -0.550000012f, 1.64999998f)]
[InlineData((uint)ChargenHeritageGroup.Tumerok, 0f, -0.850000024f, 1.64999998f)]
[InlineData((uint)ChargenHeritageGroup.Olthoi, 0f, -1.85000002f, 1.85000002f)]
[InlineData((uint)ChargenHeritageGroup.OlthoiAcid, 0f, -3.04999995f, 2.75f)]
public void ResolveDefaultEye_MatchesRetailPerHeritageLiterals(uint heritageId, float x, float y, float z)
{
Vector3 eye = ChargenPreviewCamera.ResolveDefaultEye(heritageId);
Assert.Equal(x, eye.X, 4);
Assert.Equal(y, eye.Y, 4);
Assert.Equal(z, eye.Z, 4);
}
[Theory]
[InlineData((uint)ChargenHeritageGroup.Aluvian, 0f, -2.5f, 0.95f)]
[InlineData((uint)ChargenHeritageGroup.Tumerok, 0f, -2.5f, 0.95f)] // ZoomOut has NO Tumerok special case, unlike the zoomed-in default.
[InlineData((uint)ChargenHeritageGroup.Olthoi, 0f, -3.79999995f, 1.14999998f)]
[InlineData((uint)ChargenHeritageGroup.OlthoiAcid, 0f, -5.69999981f, 1.64999998f)]
public void ResolveZoomedOutEye_MatchesRetailPerHeritageLiterals(uint heritageId, float x, float y, float z)
{
Vector3 eye = ChargenPreviewCamera.ResolveZoomedOutEye(heritageId);
Assert.Equal(x, eye.X, 4);
Assert.Equal(y, eye.Y, 4);
Assert.Equal(z, eye.Z, 4);
}
[Fact]
public void Constructor_DefaultsToStandardHeritageEye_ForUnknownHeritageId()
{
var cam = new ChargenPreviewCamera(heritageId: 0u);
Assert.Equal(ChargenPreviewCamera.ResolveDefaultEye(0u), cam.Eye);
}
[Fact]
public void SetHeritage_UpdatesEyeToTheNewHeritagesProfile()
{
var cam = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
cam.SetHeritage((uint)ChargenHeritageGroup.Olthoi);
Assert.Equal(ChargenPreviewCamera.ResolveDefaultEye((uint)ChargenHeritageGroup.Olthoi), cam.Eye);
}
[Fact]
public void View_LooksStraightDownPlusY_ZeroYawZeroPitch()
{
// Same identity-direction convention DollCameraTests pins for the paperdoll:
// retail SetCameraDirection(0,0,0) resets the view frame to IDENTITY.
var cam = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian) { Aspect = 1f };
var forward = -new Vector3(cam.View.M13, cam.View.M23, cam.View.M33);
Assert.Equal(0f, forward.X, 4);
Assert.Equal(1f, forward.Y, 4);
Assert.Equal(0f, forward.Z, 4);
}
[Fact]
public void Eye_RoundTripsThroughViewMatrixInversion()
{
var cam = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Olthoi) { Aspect = 1f };
Assert.True(Matrix4x4.Invert(cam.View, out var inv));
Vector3 eye = inv.Translation;
Assert.Equal(cam.Eye.X, eye.X, 3);
Assert.Equal(cam.Eye.Y, eye.Y, 3);
Assert.Equal(cam.Eye.Z, eye.Z, 3);
}
[Fact]
public void Projection_IsFiniteAndUsesAspect()
{
var cam = new ChargenPreviewCamera { Aspect = 1.5f };
Assert.True(float.IsFinite(cam.Projection.M11));
Assert.NotEqual(0f, cam.Projection.M34);
}
[Fact]
public void RotationSecondsPerRevolution_IsExactlyThreeSeconds()
{
// Raw double bits low32=0x00000000, high32=0x40080000 — no
// reconstruction needed, the decompiler shows this one cleanly.
Assert.Equal(3.0f, ChargenPreviewCamera.RotationSecondsPerRevolution);
}
[Fact]
public void ZoomTweenDurationSeconds_IsExactlyZeroPointSix()
{
// Recovered by reinterpreting the decompiler's garbled float literal
// as the raw low-32-bit store and pairing it with the (clean) high
// dword; cross-confirmed via the -0.1 sentinel in ZoomIn/ZoomOut
// reconstructing to the well-known IEEE-754 bit pattern for -0.1.
Assert.Equal(0.6f, ChargenPreviewCamera.ZoomTweenDurationSeconds);
}
}

View file

@ -0,0 +1,278 @@
using System.Linq;
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Content;
using AcDream.Content.CharGen;
using AcDream.Content.Vfx;
using AcDream.Core.CharGen;
using DatReaderWriter;
using DatReaderWriter.Options;
using Xunit;
using Xunit.Abstractions;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Installed-DAT gate for <see cref="ChargenPreviewEntityBuilder"/> —
/// mirrors <see cref="CornerFloodReplayTests"/>'s env-gated skip pattern
/// (no unit-testable pure surface exists here the way
/// <see cref="DollEntityBuilder"/> has one, because THIS builder's whole job
/// is resolving Setup/GfxObj/Surface/Animation dat data that
/// <see cref="DollEntityBuilder"/> receives pre-resolved).
/// </summary>
public sealed class ChargenPreviewEntityBuilderTests
{
private readonly ITestOutputHelper _out;
public ChargenPreviewEntityBuilderTests(ITestOutputHelper output) => _out = output;
[Fact]
public void TryBuild_AluvianMaleDefaultSelection_ProducesANonEmptyStaticPoseEntity()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(1u, out ChargenHeritageOptions? aluvian)); // Aluvian.
Assert.True(aluvian!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male));
var catalog = new ChargenAppearanceCatalog(adapter);
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default with
{
HairStyle = male!.HairStyles.Count > 0 ? 0u : ChargenAppearanceSelection.Unset,
SkinShade = 0.5,
};
bool composed = ChargenAppearanceFactory.TryCompose(
options, 1u, 1, selection, catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
Assert.Empty(appearance.MissingPalSetIds);
Assert.Empty(appearance.MissingClothingTableIds);
var animations = new RetailAnimationLoader(adapter);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, appearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.NotNull(entity);
Assert.NotEmpty(entity!.MeshRefs);
Assert.Equal(appearance.SetupId, entity.SourceGfxObjOrSetupId);
Assert.Equal(ChargenPreviewEntityBuilder.PreviewServerGuid, entity.ServerGuid);
Assert.Equal(ChargenPreviewEntityBuilder.PreviewRenderId, entity.Id);
Assert.NotNull(entity.PaletteOverride);
Assert.Equal(appearance.BasePaletteId, entity.PaletteOverride!.BasePaletteId);
_out.WriteLine($"setup=0x{appearance.SetupId:X8} meshRefs={entity.MeshRefs.Count} subPalettes={entity.PaletteOverride.SubPalettes.Count}");
}
[Fact]
public void TryBuild_UnknownSetupId_ReturnsNull()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
var animations = new RetailAnimationLoader(adapter);
var bogusAppearance = new ChargenAppearanceResult(
SetupId: 0x0200_FFFFu, // Not a real installed Setup id.
BasePaletteId: 0u,
ObjDesc: ChargenObjDesc.Empty,
MissingPalSetIds: [],
MissingClothingTableIds: [],
ClothingTablesMissingBaseEffectForSetup: []);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, bogusAppearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.Null(entity);
}
[Fact]
public void TryBuild_OlthoiHeritage_ResolvesADifferentRestPoseDidThanStandardHeritages()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(12u, out ChargenHeritageOptions? olthoi)); // Olthoi.
Assert.True(olthoi!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male)
|| olthoi.GendersByKey.TryGetValue(2, out male));
Assert.NotNull(male);
int genderKey = olthoi.GendersByKey.First(kv => ReferenceEquals(kv.Value, male)).Key;
var catalog = new ChargenAppearanceCatalog(adapter);
var animations = new RetailAnimationLoader(adapter);
bool composed = ChargenAppearanceFactory.TryCompose(
options, 12u, genderKey, ChargenAppearanceSelection.Default with { SkinShade = 0.5 },
catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
var entity = ChargenPreviewEntityBuilder.TryBuild(
adapter, animations, appearance, heritageId: 12u, Quaternion.Identity, new object());
// Just proves the Olthoi branch doesn't throw / silently fall through to
// "no mesh" — the exact pose DID differs internally (0x10000011 vs
// 0x10000005) but both should still resolve a drawable mesh from Olthoi's
// own Setup.
Assert.NotNull(entity);
Assert.NotEmpty(entity!.MeshRefs);
}
/// <summary>
/// CC6b: <c>TryBuildAnimated</c> resolves a real idle Animation (retail's
/// <c>m_didAnimation</c>) against the installed EoR dat, with a usable
/// frame range and a non-empty drawable-part list a
/// <c>ChargenPreviewAnimator</c> can drive.
/// </summary>
[Fact]
public void TryBuildAnimated_AluvianMaleDefaultSelection_ResolvesARealIdleCycle()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(1u, out ChargenHeritageOptions? aluvian));
Assert.True(aluvian!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male));
var catalog = new ChargenAppearanceCatalog(adapter);
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default with
{
HairStyle = male!.HairStyles.Count > 0 ? 0u : ChargenAppearanceSelection.Unset,
SkinShade = 0.5,
};
bool composed = ChargenAppearanceFactory.TryCompose(
options, 1u, 1, selection, catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
var animations = new RetailAnimationLoader(adapter);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, appearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.NotNull(build);
Assert.NotEmpty(build!.DrawableParts);
Assert.NotEmpty(build.RestMeshRefs);
Assert.NotNull(build.IdleAnimation);
Assert.True(build.IdleHighFrame >= build.IdleLowFrame);
Assert.True(build.IdleAnimation!.PartFrames.Count > build.IdleHighFrame);
// Live end-to-end: an Animator built from this resolves a non-empty,
// playable preview — retail's true default (idle playing), not the
// frozen rest pose TryBuild alone still returns.
var animator = new ChargenPreviewAnimator(build);
Assert.False(animator.IsZoomedIn);
Assert.NotEmpty(animator.Entity.MeshRefs);
animator.Tick(1f / 30f); // one frame's worth — must not throw or empty the mesh.
Assert.NotEmpty(animator.Entity.MeshRefs);
}
[Fact]
public void TryBuildAnimated_UnknownSetupId_ReturnsNull()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
var animations = new RetailAnimationLoader(adapter);
var bogusAppearance = new ChargenAppearanceResult(
SetupId: 0x0200_FFFFu,
BasePaletteId: 0u,
ObjDesc: ChargenObjDesc.Empty,
MissingPalSetIds: [],
MissingClothingTableIds: [],
ClothingTablesMissingBaseEffectForSetup: []);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, bogusAppearance, heritageId: 1u, Quaternion.Identity, new object());
Assert.Null(build);
}
/// <summary>
/// Decomp-verified quirk (<c>gmCG3DView</c>'s ctor / <c>::Update</c>,
/// pseudo-C ~0x004ee7e9/0x004ee7ff and ~0x004ee892/0x004ee8a8): Olthoi
/// and OlthoiAcid use the SAME enum key (0x10000011 / 0x10000013) for
/// BOTH the live idle DID (<c>m_didAnimation</c>) and the rest DID
/// (<c>m_didAnimationRest</c>) — every standard heritage uses two
/// DIFFERENT keys (0x10000006 idle vs 0x10000005 rest). This proves the
/// SHARED enum key resolves to a real installed Animation DID (the same
/// <c>RetailHeldPose.ResolvePoseDid</c> call
/// <c>ChargenPreviewEntityBuilder</c>'s <c>ResolveIdleAnimEnum</c> AND
/// <c>ResolveRestPoseEnum</c> both return for these two heritages) — the
/// enum-key identity itself is source-verified (both private methods
/// literally return the SAME numeric constant for Olthoi/OlthoiAcid, see
/// their own doc comments), so a single resolution here is enough to
/// confirm the shared key is not a dead/unresolvable id.
/// </summary>
[Theory]
[InlineData(0x10000011u)] // Olthoi's shared idle/rest enum key.
[InlineData(0x10000013u)] // OlthoiAcid's shared idle/rest enum key.
public void OlthoiFamily_SharedIdleRestEnumKey_ResolvesToARealInstalledDid(uint sharedEnumKey)
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
uint did = RetailHeldPose.ResolvePoseDid(adapter, sharedEnumKey);
Assert.NotEqual(0u, did);
Assert.Equal(0x03u, did >> 24); // resolves to a real Animation DID.
}
/// <summary>
/// Extends <see cref="TryBuild_OlthoiHeritage_ResolvesADifferentRestPoseDidThanStandardHeritages"/>
/// to the idle side: <c>TryBuildAnimated</c> resolves a real idle
/// Animation for Olthoi too (not just the rest pose the older
/// <c>TryBuild</c>-only test covers), so an Olthoi
/// <c>ChargenPreviewAnimator</c> actually plays instead of silently
/// falling back to the rest-only pose.
/// </summary>
[Fact]
public void TryBuildAnimated_OlthoiHeritage_ResolvesARealIdleAnimationToo()
{
string? datDir = CornerFloodReplayTests.ResolveDatDir();
if (datDir is null) { _out.WriteLine("SKIP: dats unavailable"); return; }
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.True(options.TryGetHeritage(12u, out ChargenHeritageOptions? olthoi));
Assert.True(olthoi!.GendersByKey.TryGetValue(1, out ChargenGenderOptions? male)
|| olthoi.GendersByKey.TryGetValue(2, out male));
Assert.NotNull(male);
int genderKey = olthoi.GendersByKey.First(kv => ReferenceEquals(kv.Value, male)).Key;
var catalog = new ChargenAppearanceCatalog(adapter);
var animations = new RetailAnimationLoader(adapter);
bool composed = ChargenAppearanceFactory.TryCompose(
options, 12u, genderKey, ChargenAppearanceSelection.Default with { SkinShade = 0.5 },
catalog, catalog, out ChargenAppearanceResult appearance);
Assert.True(composed);
ChargenPreviewAnimatedBuild? build = ChargenPreviewEntityBuilder.TryBuildAnimated(
adapter, animations, appearance, heritageId: 12u, Quaternion.Identity, new object());
Assert.NotNull(build);
Assert.NotNull(build!.IdleAnimation);
var animator = new ChargenPreviewAnimator(build);
Assert.False(animator.IsZoomedIn);
Assert.NotEmpty(animator.Entity.MeshRefs);
}
}

View file

@ -0,0 +1,135 @@
using System.Numerics;
using AcDream.App.Rendering;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Pure (no dat access) tests for <see cref="ChargenPreviewRotationController"/>
/// — the port of <c>gmCGAppearancePage::Rotate</c>/<c>DoRotation</c>
/// (<c>0x0047CB50</c>/<c>0x0047CA80</c>).
/// </summary>
public sealed class ChargenPreviewRotationControllerTests
{
[Fact]
public void Toggle_StartsRotatingInTheGivenDirection()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
Assert.True(controller.IsRotating);
Assert.Equal(ChargenRotateDirection.Clockwise, controller.Direction);
}
[Fact]
public void Toggle_SameDirectionWhileRotating_Stops()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Toggle(ChargenRotateDirection.Clockwise);
Assert.False(controller.IsRotating);
}
[Fact]
public void Toggle_OppositeDirectionWhileRotating_SwitchesDirectionAndKeepsRotating()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Toggle(ChargenRotateDirection.CounterClockwise);
Assert.True(controller.IsRotating);
Assert.Equal(ChargenRotateDirection.CounterClockwise, controller.Direction);
}
[Fact]
public void Tick_WhileNotRotating_IsANoOp()
{
var controller = new ChargenPreviewRotationController();
controller.Tick(100.0);
Assert.Equal(0f, controller.HeadingDegrees);
}
[Fact]
public void Tick_FirstCallAfterToggle_ContributesZeroDelta()
{
// Rotate() invalidates m_dLastRotateTime so the very first DoRotation
// tick resets it to "now" rather than computing a huge jump from a
// stale/never-set timestamp.
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Tick(1000.0);
Assert.Equal(0f, controller.HeadingDegrees);
}
[Fact]
public void Tick_ClockwiseAdvance_AddsTheExactPerTickFormula()
{
// deltaDegrees = ((now - last) / RotationSecondsPerRevolution) * 360.
// Seed "now" nonzero (0.0 collides with the <= 0 reset-if-invalid
// guard, same as retail's own sentinel check would if Timer::cur_time
// could ever read exactly zero — never in practice, so tests avoid
// it too).
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Tick(10.0); // seeds lastRotateTime = 10, zero delta.
controller.Tick(11.5); // half a revolution at 3 s/rev.
Assert.Equal(180f, controller.HeadingDegrees, 3);
}
[Fact]
public void Tick_CounterClockwiseAdvance_SubtractsAndWrapsPositive()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.CounterClockwise);
controller.Tick(10.0);
controller.Tick(11.5); // would go to -180, wraps to +180.
Assert.Equal(180f, controller.HeadingDegrees, 3);
}
[Fact]
public void Tick_AccumulatesAcrossMultipleTicks()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Tick(10.0);
controller.Tick(10.5); // +60 deg.
controller.Tick(11.0); // +60 deg more.
Assert.Equal(120f, controller.HeadingDegrees, 3);
}
/// <summary>
/// F7: exercises the <c>&gt;360 -&gt; -360</c> clamp arm (pseudo-C
/// ~0x0047cb1e-0x0047cb31), the one with readable decomp polarity —
/// unlike the CCW-branch FPU-stack artifact F3 documents, this branch's
/// test/subtract shape is unambiguous. One large clockwise tick pushes
/// heading past 360 in a single call.
/// </summary>
[Fact]
public void Tick_ClockwiseAdvancePast360_ClampsBackBySubtracting360()
{
var controller = new ChargenPreviewRotationController();
controller.Toggle(ChargenRotateDirection.Clockwise);
controller.Tick(10.0); // seeds lastRotateTime = 10, zero delta.
controller.Tick(10.0 + 3.5); // 3.5s at 3s/rev = 420 deg -> 420, clamped to 60.
Assert.Equal(60f, controller.HeadingDegrees, 3);
}
[Fact]
public void ToOrientation_AtZeroHeading_IsIdentity()
{
var controller = new ChargenPreviewRotationController();
Quaternion orientation = controller.ToOrientation();
Assert.Equal(Quaternion.Identity.X, orientation.X, 4);
Assert.Equal(Quaternion.Identity.Y, orientation.Y, 4);
Assert.Equal(Quaternion.Identity.Z, orientation.Z, 4);
Assert.Equal(Quaternion.Identity.W, orientation.W, 4);
}
}

View file

@ -0,0 +1,194 @@
using System.Numerics;
using AcDream.App.Rendering;
using AcDream.Core.CharGen;
using AcDream.Core.World;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.App.Tests.Rendering;
/// <summary>
/// Pure (no dat access) tests for <see cref="ChargenPreviewZoomController"/>
/// — the port of <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>/
/// <c>DoZoomAnimation</c> (<c>0x0047CF00</c>/<c>0x0047D050</c>/<c>0x0047C960</c>)
/// including its immediate wiring into <see cref="ChargenPreviewAnimator"/>'s
/// idle-loop ↔ rest-pose swap. Fix round F2: the controller now takes its
/// <see cref="ChargenPreviewAnimator"/> as a required constructor dependency
/// and owns no independent zoom-state bool of its own — every test here
/// builds a real (hand-fixture) animator rather than exercising a
/// camera-only path that no longer exists.
/// </summary>
public sealed class ChargenPreviewZoomControllerTests
{
private static ChargenPreviewAnimator MakeAnimator()
{
const uint gfxObjId = 0x0100_0001u;
var restMeshRefs = new System.Collections.Generic.List<MeshRef>
{
new(gfxObjId, Matrix4x4.CreateTranslation(new Vector3(99f, 99f, 99f))),
};
var drawableParts = new System.Collections.Generic.List<ChargenPreviewDrawablePart>
{
new(SetupPartIndex: 0, GfxObjId: gfxObjId, DefaultScale: Vector3.One, SurfaceOverrides: null),
};
var anim = new Animation();
var pf0 = new AnimationFrame(1);
pf0.Frames.Add(new Frame { Origin = new Vector3(1f, 0f, 0f), Orientation = Quaternion.Identity });
anim.PartFrames.Add(pf0);
var entity = new WorldEntity
{
Id = ChargenPreviewEntityBuilder.PreviewRenderId,
ServerGuid = ChargenPreviewEntityBuilder.PreviewServerGuid,
SourceGfxObjOrSetupId = 0x0200_0001u,
Position = Vector3.Zero,
Rotation = Quaternion.Identity,
MeshRefs = restMeshRefs,
};
var build = new ChargenPreviewAnimatedBuild
{
Entity = entity,
DrawableParts = drawableParts,
RestMeshRefs = restMeshRefs,
IdleAnimation = anim,
IdleLowFrame = 0,
IdleHighFrame = 0,
};
return new ChargenPreviewAnimator(build);
}
[Fact]
public void Constructor_NullAnimator_Throws()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
Assert.Throws<ArgumentNullException>(
() => new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, animator: null!));
}
[Fact]
public void IsZoomedIn_ReadsThroughToTheAnimator_NoIndependentState()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
var animator = MakeAnimator();
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, animator);
Assert.False(controller.IsZoomedIn);
// Flip the animator's OWN state directly (bypassing the controller
// entirely) — since the controller now reads straight through, there
// is nothing to desync.
animator.SetZoomedIn(true);
Assert.True(controller.IsZoomedIn);
}
[Fact]
public void ZoomIn_StartsATweenTowardTheDefaultEye_AndMarksZoomedIn()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
camera.Eye = ChargenPreviewCamera.ResolveZoomedOutEye((uint)ChargenHeritageGroup.Aluvian);
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, MakeAnimator());
controller.ZoomIn();
Assert.True(controller.IsZoomedIn);
// Tween in progress — eye hasn't jumped yet (Tick hasn't run).
Assert.Equal(ChargenPreviewCamera.ResolveZoomedOutEye((uint)ChargenHeritageGroup.Aluvian), camera.Eye);
}
[Fact]
public void ZoomIn_WhileAlreadyZoomedIn_IsANoOp()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
camera.Eye = ChargenPreviewCamera.ResolveZoomedOutEye((uint)ChargenHeritageGroup.Aluvian);
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, MakeAnimator());
controller.ZoomIn(); // real tween: zoomed-out eye -> default eye.
controller.Tick(10.0);
controller.Tick(10.0 + ChargenPreviewCamera.ZoomTweenDurationSeconds + 1.0); // fully complete it.
Vector3 eyeAfterCompletion = camera.Eye;
controller.ZoomIn(); // second call — retail's own early-return guard.
controller.Tick(9999.0); // if ZoomIn wrongly armed a tween, this would move the eye.
Assert.Equal(eyeAfterCompletion, camera.Eye);
}
[Fact]
public void ZoomOut_WhileNotZoomedIn_IsANoOp()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
Vector3 startEye = camera.Eye;
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, MakeAnimator());
controller.ZoomOut();
Assert.False(controller.IsZoomedIn);
Assert.Equal(startEye, camera.Eye);
}
[Fact]
public void Tick_LinearlyInterpolatesTheEye_HalfwayAtHalfTheDuration()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
Vector3 startEye = camera.Eye; // ctor default == the zoomed-IN eye.
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, MakeAnimator());
controller.ZoomIn(); // reach the "zoomed in" state (zero-distance tween — Eye already there).
Vector3 targetEye = ChargenPreviewCamera.ResolveZoomedOutEye((uint)ChargenHeritageGroup.Aluvian);
controller.ZoomOut(); // NOW arms a real tween: default eye -> zoomed-out eye.
controller.Tick(100.0); // seeds the tween's own start time (first tick of a fresh -0.1 sentinel).
controller.Tick(100.0 + ChargenPreviewCamera.ZoomTweenDurationSeconds / 2.0);
Vector3 expectedHalfway = Vector3.Lerp(startEye, targetEye, 0.5f);
Assert.Equal(expectedHalfway.X, camera.Eye.X, 3);
Assert.Equal(expectedHalfway.Y, camera.Eye.Y, 3);
Assert.Equal(expectedHalfway.Z, camera.Eye.Z, 3);
}
[Fact]
public void Tick_PastTheFullDuration_ClampsExactlyToTheTargetEye_AndStopsAnimating()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, MakeAnimator());
controller.ZoomIn(); // reach "zoomed in" (zero-distance).
Vector3 targetEye = ChargenPreviewCamera.ResolveZoomedOutEye((uint)ChargenHeritageGroup.Aluvian);
controller.ZoomOut(); // arms the real tween toward targetEye.
controller.Tick(0.0);
controller.Tick(100.0); // way past the 0.6s duration.
Assert.Equal(targetEye, camera.Eye);
Vector3 eyeAfterCompletion = camera.Eye;
controller.Tick(200.0); // tween finished — further ticks must not move the eye.
Assert.Equal(eyeAfterCompletion, camera.Eye);
}
[Fact]
public void ZoomIn_ImmediatelyFreezesTheAnimatorToTheRestPose_BeforeTheTweenCompletes()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
var animator = MakeAnimator();
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, animator);
controller.ZoomIn();
// No Tick() call at all — retail's ZoomIn calls StopAnimation
// synchronously, before the camera tween has advanced a single frame.
Assert.True(animator.IsZoomedIn);
Assert.Equal(new Vector3(99f, 99f, 99f), animator.Entity.MeshRefs[0].PartTransform.Translation);
}
[Fact]
public void ZoomOut_ImmediatelyResumesTheAnimatorsIdleLoop()
{
var camera = new ChargenPreviewCamera((uint)ChargenHeritageGroup.Aluvian);
var animator = MakeAnimator();
var controller = new ChargenPreviewZoomController((uint)ChargenHeritageGroup.Aluvian, camera, animator);
controller.ZoomIn();
controller.ZoomOut();
Assert.False(animator.IsZoomedIn);
Assert.Equal(new Vector3(1f, 0f, 0f), animator.Entity.MeshRefs[0].PartTransform.Translation);
}
}

View file

@ -0,0 +1,299 @@
using AcDream.Content.CharGen;
using AcDream.Core.CharGen;
using DatReaderWriter;
using DatReaderWriter.Options;
using Xunit.Abstractions;
namespace AcDream.Content.Tests.CharGen;
/// <summary>
/// Installed-DAT gate for <see cref="ChargenAppearanceCatalog"/> +
/// <see cref="ChargenAppearanceFactory"/> together: for every one of the 13
/// installed heritages' genders, composes a "pick the first offered option
/// everywhere, mid shade" selection and asserts it resolves with no missing
/// PalSet or ClothingTable dat ids — the CC6a task's explicit acceptance
/// bar ("every heritage/gender's default selection resolves to a complete
/// description with no missing dat ids"). ALSO pins the TS-82 measurement
/// with real assertions (not WriteLine-only diagnostics, per the CC6a
/// review fix round F7): the nine standard heritages with clothing UI shown
/// resolve zero <c>ClothingBaseEffects</c> gaps, and Undead resolves
/// EXACTLY the four measured gaps on both genders — see the class doc on
/// <see cref="ChargenClothingTable"/>'s deliberate scope cut.
///
/// <para>Env-gated skip (house pattern, matched from
/// <c>ChargenTableReaderInstalledDatTests</c>/<c>ContentConformanceDats</c>):
/// returns green with a console SKIP note when no installed dat directory is
/// configured, rather than a true xUnit Skipped status — no other Content
/// installed-DAT test in this project uses <c>Assert.Skip</c>, so this stays
/// consistent with the rest of the suite rather than introducing a new
/// convention.</para>
/// </summary>
public sealed class ChargenAppearanceCatalogInstalledDatTests
{
private readonly ITestOutputHelper _out;
public ChargenAppearanceCatalogInstalledDatTests(ITestOutputHelper output) => _out = output;
// ACE ACE.Entity.Enum.HeritageGroup ids. Gearknight (6)/Olthoi (12)/
// OlthoiAcid (13) are deliberately not named here — see the WriteLine-only
// comment in the loop below for why they carry no pinned expectation.
private const uint TumerokId = 7u;
private const uint UndeadId = 11u;
/// <summary>
/// The 9 standard heritages whose UI actually shows clothing controls
/// AND whose default gear resolves with zero <c>ClothingBaseEffects</c>
/// gaps (measured, not the full "clothing UI shown" set — Undead is
/// ALSO clothing-UI-shown but is the one real gap, asserted separately
/// below). Aluvian/Gharu'ndim/Sho/Viamontian/Shadowbound/Tumerok/Lugian/
/// Empyrean/Penumbraen = every heritage id 1-10 except Gearknight (6).
/// </summary>
private static readonly uint[] StandardZeroGapHeritageIds = [1u, 2u, 3u, 4u, 5u, TumerokId, 8u, 9u, 10u];
/// <summary>
/// Measured (installed EoR dat, both genders, identical order): Undead's
/// default headgear/trousers/shirt/footwear choices' clothing tables, in
/// the factory's own Headgear→Trousers→Shirt→Footwear composition order.
/// ALL FOUR slots miss — not "headgear/trousers/footwear" (a three-slot
/// undercount an earlier draft of this row stated in error).
/// </summary>
private static readonly uint[] UndeadMeasuredMissingClothingTableIds =
[0x10000009u, 0x100000F9u, 0x10000001u, 0x10000007u];
private static string? ResolveDatDir()
{
string? fromEnv = Environment.GetEnvironmentVariable("ACDREAM_DAT_DIR");
if (!string.IsNullOrWhiteSpace(fromEnv) && Directory.Exists(fromEnv))
return fromEnv;
string def = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
"Documents", "Asheron's Call");
return Directory.Exists(def) ? def : null;
}
[Fact]
public void EveryHeritageGendersDefaultSelection_ResolvesWithNoMissingDatIds()
{
string? datDir = ResolveDatDir();
if (datDir is null)
{
_out.WriteLine("SKIP: installed retail DAT directory is unavailable.");
return;
}
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.NotEmpty(options.HeritagesById);
var catalog = new ChargenAppearanceCatalog(adapter);
int composed = 0;
var missingSummaries = new List<string>();
var baseEffectGapFailures = new List<string>();
foreach (ChargenHeritageOptions heritage in options.HeritagesById.Values)
{
foreach ((int genderKey, ChargenGenderOptions gender) in heritage.GendersByKey)
{
ChargenAppearanceSelection selection = MakeDefaultSelection(gender);
bool ok = ChargenAppearanceFactory.TryCompose(
options, heritage.HeritageId, genderKey, selection,
catalog, catalog, out ChargenAppearanceResult result);
Assert.True(ok, $"heritage=0x{heritage.HeritageId:X} gender={genderKey} failed to resolve heritage/gender");
composed++;
if (result.MissingPalSetIds.Count > 0 || result.MissingClothingTableIds.Count > 0)
{
missingSummaries.Add(
$"heritage={heritage.Name} gender={genderKey}: "
+ $"missingPalSets=[{string.Join(",", result.MissingPalSetIds.Select(id => $"0x{id:X8}"))}] "
+ $"missingClothingTables=[{string.Join(",", result.MissingClothingTableIds.Select(id => $"0x{id:X8}"))}]");
}
_out.WriteLine(
$"heritage={heritage.Name} (0x{heritage.HeritageId:X}) gender={genderKey} setup=0x{result.SetupId:X8}: "
+ $"{result.ClothingTablesMissingBaseEffectForSetup.Count} clothing table(s) with no "
+ "ClothingBaseEffects entry for this body setup "
+ $"[{string.Join(",", result.ClothingTablesMissingBaseEffectForSetup.Select(id => $"0x{id:X8}"))}]");
// TS-82's pinned measurement — real assertions, not WriteLine-only.
if (StandardZeroGapHeritageIds.Contains(heritage.HeritageId))
{
if (result.ClothingTablesMissingBaseEffectForSetup.Count != 0)
{
baseEffectGapFailures.Add(
$"heritage={heritage.Name} gender={genderKey}: expected ZERO ClothingBaseEffects "
+ $"gaps (a standard heritage with clothing UI shown), measured "
+ $"{result.ClothingTablesMissingBaseEffectForSetup.Count}: "
+ $"[{string.Join(",", result.ClothingTablesMissingBaseEffectForSetup.Select(id => $"0x{id:X8}"))}]");
}
}
else if (heritage.HeritageId == UndeadId)
{
if (!result.ClothingTablesMissingBaseEffectForSetup.SequenceEqual(UndeadMeasuredMissingClothingTableIds))
{
baseEffectGapFailures.Add(
$"heritage=Undead gender={genderKey}: expected EXACTLY "
+ $"[{string.Join(",", UndeadMeasuredMissingClothingTableIds.Select(id => $"0x{id:X8}"))}], measured "
+ $"[{string.Join(",", result.ClothingTablesMissingBaseEffectForSetup.Select(id => $"0x{id:X8}"))}]");
}
}
// Gearknight/Olthoi/OlthoiAcid: retail hides the clothing UI
// entirely for these three (gmCGAppearancePage::Update
// @0x0047E8F0's SetVisible(0) branches), so a real chargen
// selection never reaches this composer's clothing slots for
// them — no pinned expectation either way, WriteLine above
// is diagnostic only.
}
}
_out.WriteLine($"composed {composed} heritage/gender selections.");
Assert.True(
missingSummaries.Count == 0,
"Missing dat ids found:\n" + string.Join('\n', missingSummaries));
Assert.True(
baseEffectGapFailures.Count == 0,
"TS-82 measurement drifted from its pinned expectation:\n" + string.Join('\n', baseEffectGapFailures));
Assert.True(composed >= 13, $"Expected at least 13 heritage/gender combinations, composed {composed}.");
}
/// <summary>
/// CC6a review fix round F1: retail's Setup-id "unset" sentinel is
/// <c>INVALID_DID</c> (0xFFFFFFFF), not 0
/// (<c>CharGenState::GetSetupID @ 0x005C5B22</c>). Sweeps EVERY hair
/// style of all 26 heritage/gender combinations and asserts the composed
/// SetupId always resolves to a REAL installed Setup dat entry — proving
/// neither sentinel value, wherever a hair style's <c>AlternateSetup</c>
/// field happens to store one, ever reaches <c>Get&lt;Setup&gt;</c> as a
/// literal id.
/// </summary>
[Fact]
public void EveryHairStyleOfEveryHeritageGender_ComposesToARealInstalledSetupId()
{
string? datDir = ResolveDatDir();
if (datDir is null)
{
_out.WriteLine("SKIP: installed retail DAT directory is unavailable.");
return;
}
using var dats = new DatCollection(datDir, DatAccessType.Read);
using var adapter = new DatCollectionAdapter(dats);
ChargenOptions options = ChargenTableReader.Load(adapter);
Assert.NotEmpty(options.HeritagesById);
var catalog = new ChargenAppearanceCatalog(adapter);
int sweptHairStyles = 0;
var unresolvedSetups = new List<string>();
foreach (ChargenHeritageOptions heritage in options.HeritagesById.Values)
{
foreach ((int genderKey, ChargenGenderOptions gender) in heritage.GendersByKey)
{
for (uint hairStyleIndex = 0; hairStyleIndex < (uint)gender.HairStyles.Count; hairStyleIndex++)
{
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default with
{
HairStyle = hairStyleIndex,
SkinShade = 0.5,
};
bool ok = ChargenAppearanceFactory.TryCompose(
options, heritage.HeritageId, genderKey, selection,
catalog, catalog, out ChargenAppearanceResult result);
Assert.True(ok);
sweptHairStyles++;
if (adapter.Get<DatReaderWriter.DBObjs.Setup>(result.SetupId) is null)
{
unresolvedSetups.Add(
$"heritage={heritage.Name} gender={genderKey} hairStyle={hairStyleIndex}: "
+ $"composed SetupId=0x{result.SetupId:X8} does not resolve to an installed Setup");
}
}
// Every gender is swept even with zero hair styles (still
// exercises the "no hair style selected" default-setup path).
if (gender.HairStyles.Count == 0)
{
bool ok = ChargenAppearanceFactory.TryCompose(
options, heritage.HeritageId, genderKey,
ChargenAppearanceSelection.Default with { SkinShade = 0.5 },
catalog, catalog, out ChargenAppearanceResult result);
Assert.True(ok);
sweptHairStyles++;
if (adapter.Get<DatReaderWriter.DBObjs.Setup>(result.SetupId) is null)
{
unresolvedSetups.Add(
$"heritage={heritage.Name} gender={genderKey} (no hair styles): "
+ $"composed SetupId=0x{result.SetupId:X8} does not resolve to an installed Setup");
}
}
}
}
_out.WriteLine($"swept {sweptHairStyles} hair-style/no-hair-style selections across 26 heritage/gender combinations.");
Assert.True(
unresolvedSetups.Count == 0,
"Composed SetupId(s) that don't resolve to a real installed Setup:\n" + string.Join('\n', unresolvedSetups));
Assert.True(sweptHairStyles > 26, $"Expected more than 26 swept selections (multiple hair styles per gender), got {sweptHairStyles}.");
}
/// <summary>
/// "Pick the first offered option everywhere, mid shade" — CC6a's own
/// default policy for exercising the factory end-to-end, NOT a claim
/// about retail's own CharGenState default selection (that policy is
/// CC3/CC6b's concern). Every index/shade starts at
/// <see cref="ChargenAppearanceSelection.Unset"/>/<see cref="ChargenAppearanceSelection.UnsetShade"/>
/// and is only set when the gender's own list actually offers an
/// option, so a heritage with e.g. no headgear choices exercises the
/// factory's "slot not selected" path rather than an out-of-range index.
/// </summary>
private static ChargenAppearanceSelection MakeDefaultSelection(ChargenGenderOptions gender)
{
const double midShade = 0.5;
ChargenAppearanceSelection selection = ChargenAppearanceSelection.Default;
if (gender.HairStyles.Count > 0)
selection = selection with { HairStyle = 0u };
if (gender.EyeStrips.Count > 0)
selection = selection with { EyesStrip = 0u };
if (gender.NoseStrips.Count > 0)
selection = selection with { NoseStrip = 0u };
if (gender.MouthStrips.Count > 0)
selection = selection with { MouthStrip = 0u };
if (gender.HairColors.Count > 0)
selection = selection with { HairColor = 0u, HairShade = midShade };
if (gender.EyeColors.Count > 0)
selection = selection with { EyeColor = 0u };
if (gender.Headgears.Count > 0)
selection = selection with { HeadgearStyle = 0u };
if (gender.Shirts.Count > 0)
selection = selection with { ShirtStyle = 0u };
if (gender.Pants.Count > 0)
selection = selection with { TrousersStyle = 0u };
if (gender.Footwear.Count > 0)
selection = selection with { FootwearStyle = 0u };
if (gender.ClothingColors.Count > 0)
{
selection = selection with
{
HeadgearColor = 0u,
HeadgearShade = midShade,
ShirtColor = 0u,
ShirtShade = midShade,
TrousersColor = 0u,
TrousersShade = midShade,
FootwearColor = 0u,
FootwearShade = midShade,
};
}
return selection with { SkinShade = midShade };
}
}

View file

@ -0,0 +1,686 @@
using AcDream.Core.CharGen;
namespace AcDream.Core.Tests.CharGen;
/// <summary>
/// Hand-built-fixture tests for <see cref="ChargenAppearanceFactory.TryCompose"/>.
/// Real installed-DAT coverage (every heritage/gender's default selection,
/// verifying no missing PalSet/ClothingTable ids) lives in
/// AcDream.Content.Tests.CharGen.ChargenAppearanceCatalogInstalledDatTests.
/// </summary>
public sealed class ChargenAppearanceFactoryTests
{
private const uint HeritageId = 1u;
private const int GenderKey = 1;
private const uint BodySetupId = 0x0200_0001u;
private const uint AlternateBodySetupId = 0x0200_00FFu;
private const uint BasePaletteId = 0x0400_0001u;
private const uint SkinPalSetId = 0x0F00_0001u;
private const uint HairColorPalSetId = 0x0F00_0002u;
private const uint EyeColorPaletteId = 0x0400_0099u; // direct palette id, no PalSet indirection.
private const uint HeadgearClothingTableId = 0x1900_0001u;
private const uint TrousersClothingTableId = 0x1900_0002u;
private const uint ShirtClothingTableId = 0x1900_0003u;
private const uint FootwearClothingTableId = 0x1900_0004u;
private static ChargenObjDesc MakeObjDesc(uint tag) => new(
0u,
[],
[new ChargenTextureChange((byte)tag, 0x0500_0000u + tag, 0x0500_1000u + tag)],
[new ChargenAnimPartChange((byte)tag, 0x0100_0000u + tag)]);
private static ChargenGenderOptions MakeGender(uint alternateHairSetup = 0u, bool baldHairStyle = false) => new(
GenderKey: GenderKey,
Name: "Male",
Scale: 100u,
SetupId: BodySetupId,
SoundTableId: 0x0900_0001u,
IconId: 0x0600_0001u,
BasePaletteId: BasePaletteId,
SkinPalSetId: SkinPalSetId,
PhysicsTableId: 0x0D00_0001u,
MotionTableId: 0x0900_0002u,
CombatTableId: 0x0000_0001u,
BaseObjDesc: MakeObjDesc(0),
HairColors: [HairColorPalSetId],
HairStyles:
[
new ChargenHairStyle(0x0600_0002u, baldHairStyle, alternateHairSetup, MakeObjDesc(1)),
],
EyeColors: [EyeColorPaletteId],
EyeStrips:
[
new ChargenEyeStrip(0x0600_0003u, 0x0600_0004u, MakeObjDesc(2), MakeObjDesc(20)),
],
NoseStrips: [new ChargenFaceStrip(0x0600_0005u, MakeObjDesc(3))],
MouthStrips: [new ChargenFaceStrip(0x0600_0006u, MakeObjDesc(4))],
Headgears: [new ChargenGearOption("Cap", HeadgearClothingTableId, 0x3000_0001u)],
Shirts: [new ChargenGearOption("Shirt", ShirtClothingTableId, 0x3000_0002u)],
Pants: [new ChargenGearOption("Pants", TrousersClothingTableId, 0x3000_0003u)],
Footwear: [new ChargenGearOption("Boots", FootwearClothingTableId, 0x3000_0004u)],
ClothingColors: [7u]);
private static ChargenOptions MakeOptions(ChargenGenderOptions gender)
{
var heritage = new ChargenHeritageOptions(
HeritageId, "Test", 0x0600_0001u, BodySetupId, BodySetupId,
180u, 100u, [0], [],
new Dictionary<uint, ChargenSkillCost>(), [],
new Dictionary<int, ChargenGenderOptions> { [GenderKey] = gender });
return new ChargenOptions(
[],
new Dictionary<uint, ChargenHeritageOptions> { [HeritageId] = heritage },
new Dictionary<uint, ChargenSkillCost>());
}
/// <summary>One dye choice per clothing table: palette-template id 7,
/// one PalSet, one range (real units 80/16 → packed (10,2)).</summary>
private static ChargenClothingTable MakeClothingTable(uint clothingTableId, uint palSetId, uint bodySetupId)
{
var partChanges = new[] { new ChargenAnimPartChange(5, 0x0100_5000u + clothingTableId) };
var textureChanges = new[] { new ChargenTextureChange(5, 0x0500_5000u, 0x0500_6000u) };
var baseEffects = new Dictionary<uint, ChargenClothingBaseEffect>
{
[bodySetupId] = new ChargenClothingBaseEffect(partChanges, textureChanges),
};
var choice = new ChargenClothingSubPaletteChoice(
palSetId, [new ChargenClothingSubPaletteRange(80u, 16u)]);
var templates = new Dictionary<uint, ChargenClothingPaletteTemplate>
{
[7u] = new ChargenClothingPaletteTemplate([choice]),
};
return new ChargenClothingTable(baseEffects, templates);
}
private sealed class FakePalSetSource : IChargenPalSetSource
{
private readonly Dictionary<uint, ChargenPalSet> _sets = new();
public void Add(uint id, params uint[] paletteIds) => _sets[id] = new ChargenPalSet(paletteIds);
public ChargenPalSet? TryGetPalSet(uint palSetId) => _sets.TryGetValue(palSetId, out var s) ? s : null;
}
private sealed class FakeClothingTableSource : IChargenClothingTableSource
{
private readonly Dictionary<uint, ChargenClothingTable> _tables = new();
public void Add(uint id, ChargenClothingTable table) => _tables[id] = table;
public ChargenClothingTable? TryGetClothingTable(uint clothingTableId) =>
_tables.TryGetValue(clothingTableId, out var t) ? t : null;
}
private static (FakePalSetSource pal, FakeClothingTableSource clothing) MakeSources(uint bodySetupId = BodySetupId)
{
var pal = new FakePalSetSource();
pal.Add(SkinPalSetId, 0x0400_0010u, 0x0400_0011u, 0x0400_0012u);
pal.Add(HairColorPalSetId, 0x0400_0020u, 0x0400_0021u);
var clothingDyePalSetId = 0x0F00_0003u;
pal.Add(clothingDyePalSetId, 0x0400_0030u, 0x0400_0031u);
var clothing = new FakeClothingTableSource();
clothing.Add(HeadgearClothingTableId, MakeClothingTable(HeadgearClothingTableId, clothingDyePalSetId, bodySetupId));
clothing.Add(TrousersClothingTableId, MakeClothingTable(TrousersClothingTableId, clothingDyePalSetId, bodySetupId));
clothing.Add(ShirtClothingTableId, MakeClothingTable(ShirtClothingTableId, clothingDyePalSetId, bodySetupId));
clothing.Add(FootwearClothingTableId, MakeClothingTable(FootwearClothingTableId, clothingDyePalSetId, bodySetupId));
return (pal, clothing);
}
[Fact]
public void TryCompose_ReturnsFalse_WhenHeritageIsUnknown()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
bool ok = ChargenAppearanceFactory.TryCompose(
options, heritageId: 999u, GenderKey, ChargenAppearanceSelection.Default,
pal, clothing, out _);
Assert.False(ok);
}
[Fact]
public void TryCompose_ReturnsFalse_WhenGenderIsUnknown()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, genderKey: 999, ChargenAppearanceSelection.Default,
pal, clothing, out _);
Assert.False(ok);
}
[Fact]
public void TryCompose_DefaultSelection_ResolvesBodySetupAndUnconditionalSkinSubpalette()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default,
pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.Equal(BodySetupId, result.SetupId);
Assert.Equal(BasePaletteId, result.BasePaletteId);
Assert.Empty(result.MissingPalSetIds);
Assert.Empty(result.MissingClothingTableIds);
// UnsetShade (-1.0) is out of [0,1], so GetPaletteIndex returns -1 and
// the skin block is skipped for THIS test's default selection — the
// "unconditional" behavior is that the block always RUNS (always
// attempts the PalSet lookup), not that it always emits an entry.
Assert.DoesNotContain(result.ObjDesc.SubPalettes, sp => sp.Offset == 0);
// Base body's own ObjDesc still lands (tag 0's texture/anim change).
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 0);
}
[Fact]
public void TryCompose_SkinShadeSelected_EmitsSkinSubpaletteAtPackedOffsetZeroCountTwentyFour()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { SkinShade = 0.5 };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
ChargenSubPalette skin = Assert.Single(result.ObjDesc.SubPalettes, sp => sp.Offset == 0 && sp.NumColors == 24);
Assert.Equal(0x0400_0011u, skin.SubPaletteId); // index 1 of 3 at shade 0.5.
}
[Fact]
public void TryCompose_HairColorSelected_EmitsHairSubpaletteAtPackedOffsetTwentyFourCountEight()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairColor = 0u, HairShade = 1.0 };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
ChargenSubPalette hair = Assert.Single(result.ObjDesc.SubPalettes, sp => sp.Offset == 24 && sp.NumColors == 8);
Assert.Equal(0x0400_0021u, hair.SubPaletteId); // last of the two at shade 1.0.
}
[Fact]
public void TryCompose_EyeColorSelected_UsesRawPaletteIdDirectlyNoShadeIndirection()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { EyeColor = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
ChargenSubPalette eye = Assert.Single(result.ObjDesc.SubPalettes, sp => sp.Offset == 32 && sp.NumColors == 8);
Assert.Equal(EyeColorPaletteId, eye.SubPaletteId);
}
[Fact]
public void TryCompose_HairStyleSelected_AppendsHairObjDescAfterBase()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Equal(0u, (uint)result.ObjDesc.AnimPartChanges[0].PartIndex); // base first.
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 1); // hair style second.
}
[Fact]
public void TryCompose_HairStyleWithAlternateSetup_OverridesBodySetupId()
{
ChargenOptions options = MakeOptions(MakeGender(alternateHairSetup: AlternateBodySetupId));
var (pal, clothing) = MakeSources(bodySetupId: AlternateBodySetupId);
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Equal(AlternateBodySetupId, result.SetupId);
}
[Fact]
public void TryCompose_BothSetupSourcesZero_FallsBackToHumanSetupId()
{
ChargenGenderOptions gender = MakeGender() with { SetupId = 0u };
ChargenOptions options = MakeOptions(gender);
var (pal, clothing) = MakeSources(bodySetupId: 0u);
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default,
pal, clothing, out ChargenAppearanceResult result);
Assert.Equal(ChargenAppearanceFactory.HumanSetupId, result.SetupId);
}
/// <summary>
/// CC6a review fix round F1: retail's "unset" sentinel for a Setup id is
/// <c>INVALID_DID</c> (0xFFFFFFFF — <c>CharGenState::GetSetupID @
/// 0x005C5B22</c>), not 0. A hair style whose <c>AlternateSetup</c> field
/// stores 0xFFFFFFFF must NOT be adopted as the body Setup id — before
/// this fix the factory would hand 0xFFFFFFFF straight to a caller's
/// <c>Get&lt;Setup&gt;</c>, which nulls, and the whole preview build
/// would fail silently.
/// </summary>
[Fact]
public void TryCompose_HairStyleAlternateSetupIsInvalidDid_IsTreatedAsUnsetNotAdopted()
{
ChargenOptions options = MakeOptions(MakeGender(alternateHairSetup: 0xFFFFFFFFu));
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Equal(BodySetupId, result.SetupId); // gender.SetupId, NOT the INVALID_DID sentinel.
}
/// <summary>
/// Companion to <see cref="TryCompose_BothSetupSourcesZero_FallsBackToHumanSetupId"/>:
/// the resolved Setup id can ALSO be stuck at INVALID_DID (rather than 0)
/// when the gender's own <c>SetupId</c> dat field happens to be
/// 0xFFFFFFFF — the fallback to <see cref="ChargenAppearanceFactory.HumanSetupId"/>
/// must catch that case too.
/// </summary>
[Fact]
public void TryCompose_GenderSetupIdIsInvalidDid_FallsBackToHumanSetupId()
{
ChargenGenderOptions gender = MakeGender() with { SetupId = 0xFFFFFFFFu };
ChargenOptions options = MakeOptions(gender);
var (pal, clothing) = MakeSources(bodySetupId: 0xFFFFFFFFu);
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default,
pal, clothing, out ChargenAppearanceResult result);
Assert.Equal(ChargenAppearanceFactory.HumanSetupId, result.SetupId);
}
/// <summary>
/// CC6b MUST-COVER item 4 — <c>alternateSetupIdOverride</c> (retail's
/// <c>m_alternateSetupID</c>) must WIN outright over the hairstyle's own
/// <c>AlternateSetup</c> when both are supplied, matching
/// <c>gmCG3DView::Update</c>'s replace-not-combine precedence
/// (~0x004EEA46-0x004EEA53).
/// </summary>
[Fact]
public void TryCompose_AlternateSetupIdOverride_WinsOverHairStyleAlternateSetup()
{
const uint hairStyleSetup = 0x0200_00AAu;
const uint pageLevelOverride = 0x0200_00BBu;
ChargenOptions options = MakeOptions(MakeGender(alternateHairSetup: hairStyleSetup));
var (pal, clothing) = MakeSources(bodySetupId: pageLevelOverride);
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result,
alternateSetupIdOverride: pageLevelOverride);
Assert.Equal(pageLevelOverride, result.SetupId);
}
/// <summary>
/// Companion: with NO hair style selected at all (so there is nothing for
/// the page-level override to out-rank), the override still replaces the
/// plain gender.SetupId.
/// </summary>
[Fact]
public void TryCompose_AlternateSetupIdOverride_WinsOverPlainGenderSetupId()
{
const uint pageLevelOverride = 0x0200_00CCu;
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources(bodySetupId: pageLevelOverride);
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default, pal, clothing,
out ChargenAppearanceResult result,
alternateSetupIdOverride: pageLevelOverride);
Assert.Equal(pageLevelOverride, result.SetupId);
}
/// <summary>
/// The default (no override supplied) call shape is unaffected — proves
/// the new trailing parameter is additive, not a behavior change for
/// every existing caller.
/// </summary>
[Fact]
public void TryCompose_NoAlternateSetupIdOverrideSupplied_ResolvesAsBefore()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default, pal, clothing,
out ChargenAppearanceResult result);
Assert.Equal(BodySetupId, result.SetupId);
}
/// <summary>
/// An override equal to retail's <c>INVALID_DID</c> sentinel means "no
/// override" (the field's own default), not "adopt 0xFFFFFFFF as the
/// Setup id" — same sentinel discipline as the hairstyle source (F1).
/// </summary>
[Fact]
public void TryCompose_AlternateSetupIdOverrideIsInvalidDid_IsTreatedAsNoOverride()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, ChargenAppearanceSelection.Default, pal, clothing,
out ChargenAppearanceResult result,
alternateSetupIdOverride: 0xFFFFFFFFu);
Assert.Equal(BodySetupId, result.SetupId);
}
[Fact]
public void TryCompose_EyeStripSelected_UsesNonBaldObjDesc_WhenHairStyleIsNotBald()
{
ChargenOptions options = MakeOptions(MakeGender(baldHairStyle: false));
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u, EyesStrip = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
// tag 2 = non-bald eye ObjDesc, tag 20 = bald eye ObjDesc.
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_0002u);
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_0014u);
}
[Fact]
public void TryCompose_EyeStripSelected_UsesBaldObjDesc_WhenHairStyleIsBald()
{
ChargenOptions options = MakeOptions(MakeGender(baldHairStyle: true));
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairStyle = 0u, EyesStrip = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_0014u); // tag 20, bald.
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_0002u); // tag 2, non-bald.
}
[Fact]
public void TryCompose_NoseAndMouthStripsSelected_AppendBothObjDescs()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { NoseStrip = 0u, MouthStrip = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 3); // nose tag.
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 4); // mouth tag.
}
[Fact]
public void TryCompose_AllFourClothingSlotsSelected_AppearInRetailOrderHeadgearTrousersShirtFootwear()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with
{
HeadgearStyle = 0u,
TrousersStyle = 0u,
ShirtStyle = 0u,
FootwearStyle = 0u,
};
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
// Only the base body's own tag (PartIndex 0) and the four clothing
// slots' PartIndex-5 overrides are present (no hair style/strips
// selected) — asserting the full ordered sequence pins retail's
// Headgear → Trousers → Shirt → Footwear append order directly.
uint[] expectedPartIds =
[
0x0100_0000u, // base body tag.
0x0100_5000u + HeadgearClothingTableId,
0x0100_5000u + TrousersClothingTableId,
0x0100_5000u + ShirtClothingTableId,
0x0100_5000u + FootwearClothingTableId,
];
Assert.Equal(expectedPartIds, result.ObjDesc.AnimPartChanges.Select(c => c.PartId).ToArray());
}
[Fact]
public void TryCompose_ClothingSlotWithColor_EmitsPartTextureAndDyeSubpalette()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with
{
HeadgearStyle = 0u,
HeadgearColor = 0u, // gender.ClothingColors[0] = 7u == the fixture's palette-template key.
HeadgearShade = 0.0,
};
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_5000u + HeadgearClothingTableId);
Assert.Contains(result.ObjDesc.TextureChanges, c => c.PartIndex == 5 && c.NewTextureId == 0x0500_6000u);
// Real range (80, 16) packed by /8 => (10, 2).
Assert.Contains(result.ObjDesc.SubPalettes, sp => sp.Offset == 10 && sp.NumColors == 2);
}
[Fact]
public void TryCompose_ClothingSlotWithoutColor_SkipsDyeSubpaletteButKeepsPartTextureChanges()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HeadgearStyle = 0u };
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Contains(result.ObjDesc.AnimPartChanges, c => c.PartId == 0x0100_5000u + HeadgearClothingTableId);
Assert.DoesNotContain(result.ObjDesc.SubPalettes, sp => sp.Offset == 10 && sp.NumColors == 2);
}
/// <summary>
/// CC6a review fix round F8: retail's inner subpalette loop
/// (<c>ClothingTable::BuildObjDesc</c> ~0x005A7B24-0x005A7BD3) returns 0
/// IMMEDIATELY when a PalSet read fails for one choice (~0x005A7B32),
/// aborting every REMAINING choice in that garment's palette template —
/// not merely skipping the failed one and continuing. A two-choice
/// template with the FIRST choice's PalSet missing must therefore emit
/// NEITHER choice's subpalette, even though the second choice's own
/// PalSet is present and would resolve fine on its own.
/// </summary>
[Fact]
public void TryCompose_PalSetMissingMidLoop_AbortsRemainingChoicesInThatGarment()
{
const uint missingPalSetId = 0x0F00_00AAu;
const uint presentPalSetId = 0x0F00_00BBu;
var firstChoice = new ChargenClothingSubPaletteChoice(
missingPalSetId, [new ChargenClothingSubPaletteRange(80u, 16u)]);
var secondChoice = new ChargenClothingSubPaletteChoice(
presentPalSetId, [new ChargenClothingSubPaletteRange(160u, 8u)]);
var baseEffects = new Dictionary<uint, ChargenClothingBaseEffect>
{
[BodySetupId] = ChargenClothingBaseEffect.Empty,
};
var templates = new Dictionary<uint, ChargenClothingPaletteTemplate>
{
[7u] = new ChargenClothingPaletteTemplate([firstChoice, secondChoice]),
};
var table = new ChargenClothingTable(baseEffects, templates);
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
clothing.Add(HeadgearClothingTableId, table); // override the shared fixture's single-choice table.
pal.Add(presentPalSetId, 0x0400_0055u); // deliberately NOT adding missingPalSetId.
var selection = ChargenAppearanceSelection.Default with
{
HeadgearStyle = 0u,
HeadgearColor = 0u,
HeadgearShade = 0.0,
};
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.Contains(missingPalSetId, result.MissingPalSetIds);
// Real range (160, 8) would pack to (20, 1) if the second choice were
// (incorrectly) still applied after the first choice's miss.
Assert.DoesNotContain(result.ObjDesc.SubPalettes, sp => sp.Offset == 20 && sp.NumColors == 1);
// Nothing from EITHER choice's own range landed.
Assert.DoesNotContain(result.ObjDesc.SubPalettes, sp => sp.Offset == 10 && sp.NumColors == 2);
}
/// <summary>
/// CC6a review fix round F10: a real dat <c>NumColors</c> of exactly
/// 2048 (256*8) is retail's own "whole palette" value spelled out in
/// real units — it packs to the byte 0 sentinel
/// (<see cref="AcDream.Core.World.PaletteOverride"/>'s documented
/// "Length=0 means entire palette") EXPLICITLY, not via an unchecked
/// narrowing coincidence.
/// </summary>
[Fact]
public void TryCompose_ClothingRangeNumColorsIsWholePaletteSentinel_PacksToZeroExplicitly()
{
var choice = new ChargenClothingSubPaletteChoice(
0x0F00_0003u, [new ChargenClothingSubPaletteRange(0u, 2048u)]);
var baseEffects = new Dictionary<uint, ChargenClothingBaseEffect>
{
[BodySetupId] = ChargenClothingBaseEffect.Empty,
};
var table = new ChargenClothingTable(
baseEffects,
new Dictionary<uint, ChargenClothingPaletteTemplate> { [7u] = new([choice]) });
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
clothing.Add(HeadgearClothingTableId, table);
var selection = ChargenAppearanceSelection.Default with
{
HeadgearStyle = 0u,
HeadgearColor = 0u,
HeadgearShade = 0.0,
};
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.Contains(result.ObjDesc.SubPalettes, sp => sp.Offset == 0 && sp.NumColors == 0);
}
/// <summary>
/// CC6a review fix round F10: a shape the packed *8 byte convention
/// cannot represent losslessly (not a multiple of 8, and not the 2048
/// whole-palette sentinel) must THROW rather than silently truncate via
/// an unchecked <c>(byte)</c> cast.
/// </summary>
[Fact]
public void TryCompose_ClothingRangeDoesNotFitThePackedByteConvention_Throws()
{
var choice = new ChargenClothingSubPaletteChoice(
0x0F00_0003u, [new ChargenClothingSubPaletteRange(0u, 2041u)]); // not a multiple of 8, not 2048.
var baseEffects = new Dictionary<uint, ChargenClothingBaseEffect>
{
[BodySetupId] = ChargenClothingBaseEffect.Empty,
};
var table = new ChargenClothingTable(
baseEffects,
new Dictionary<uint, ChargenClothingPaletteTemplate> { [7u] = new([choice]) });
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
clothing.Add(HeadgearClothingTableId, table);
var selection = ChargenAppearanceSelection.Default with
{
HeadgearStyle = 0u,
HeadgearColor = 0u,
HeadgearShade = 0.0,
};
Assert.Throws<ArgumentOutOfRangeException>(() =>
ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out _));
}
[Fact]
public void TryCompose_UnknownClothingTableId_IsRecordedAsMissingAndSkipped()
{
ChargenGenderOptions gender = MakeGender();
gender = gender with
{
Headgears = [new ChargenGearOption("Missing", 0x1900_00FFu, 0x3000_0099u)],
};
ChargenOptions options = MakeOptions(gender);
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HeadgearStyle = 0u };
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.Contains(0x1900_00FFu, result.MissingClothingTableIds);
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 5);
}
[Fact]
public void TryCompose_UnknownHairColorPalSetId_IsRecordedAsMissingAndSkipped()
{
ChargenGenderOptions gender = MakeGender() with { HairColors = [0x0F00_00FFu] };
ChargenOptions options = MakeOptions(gender);
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairColor = 0u, HairShade = 0.5 };
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.Contains(0x0F00_00FFu, result.MissingPalSetIds);
Assert.DoesNotContain(result.ObjDesc.SubPalettes, sp => sp.Offset == 24);
}
[Fact]
public void TryCompose_BodySetupAbsentFromClothingBaseEffects_IsRecordedButDoesNotThrow()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources(bodySetupId: 0x0200_DEADu); // different from the resolved body setup.
var selection = ChargenAppearanceSelection.Default with { HeadgearStyle = 0u };
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.Contains(HeadgearClothingTableId, result.ClothingTablesMissingBaseEffectForSetup);
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 5);
}
[Fact]
public void TryCompose_OutOfRangeStyleIndex_IsTreatedAsUnselected()
{
ChargenOptions options = MakeOptions(MakeGender());
var (pal, clothing) = MakeSources();
var selection = ChargenAppearanceSelection.Default with { HairStyle = 999u, EyesStrip = 999u };
bool ok = ChargenAppearanceFactory.TryCompose(
options, HeritageId, GenderKey, selection, pal, clothing, out ChargenAppearanceResult result);
Assert.True(ok);
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 1);
Assert.DoesNotContain(result.ObjDesc.AnimPartChanges, c => c.PartIndex == 2);
}
}

View file

@ -0,0 +1,63 @@
using AcDream.Core.CharGen;
namespace AcDream.Core.Tests.CharGen;
/// <summary>
/// Pins <see cref="ChargenPalSetMath.GetPaletteIndex"/> against the exact
/// formula ACE's <c>PaletteSet.GetPaletteID</c> cites as "Taken from
/// acclient.c (PalSet::GetPaletteID)": <c>(int)((count - 0.000001) * shade)</c>,
/// clamped to <c>[0, count-1]</c>, with an out-of-<c>[0,1]</c> shade (or a
/// non-positive count) returning -1.
/// </summary>
public class ChargenPalSetMathTests
{
[Theory]
[InlineData(5, 0.0, 0)]
[InlineData(5, 1.0, 4)]
[InlineData(5, 0.5, 2)]
[InlineData(1, 0.0, 0)]
[InlineData(1, 1.0, 0)]
public void GetPaletteIndex_matches_the_cited_acclient_formula(int count, double shade, int expected)
{
Assert.Equal(expected, ChargenPalSetMath.GetPaletteIndex(count, shade));
}
[Theory]
[InlineData(0, 0.5)]
[InlineData(-1, 0.5)]
public void GetPaletteIndex_returns_negative_one_for_non_positive_count(int count, double shade)
{
Assert.Equal(-1, ChargenPalSetMath.GetPaletteIndex(count, shade));
}
[Theory]
[InlineData(5, -0.0001)]
[InlineData(5, 1.0001)]
[InlineData(5, ChargenAppearanceSelection.UnsetShade)] // retail's own "unset" sentinel is out of [0,1].
public void GetPaletteIndex_returns_negative_one_for_out_of_range_shade(int count, double shade)
{
Assert.Equal(-1, ChargenPalSetMath.GetPaletteIndex(count, shade));
}
[Fact]
public void GetPaletteIndex_never_exceeds_count_minus_one_near_the_upper_bound()
{
// shade == 1.0 exactly must land on the LAST index, not overflow past it —
// the (count - 0.000001) fudge factor exists precisely to guarantee this.
for (int count = 1; count <= 64; count++)
Assert.Equal(count - 1, ChargenPalSetMath.GetPaletteIndex(count, 1.0));
}
[Fact]
public void GetPaletteIndex_is_monotonic_non_decreasing_in_shade()
{
const int count = 13;
int previous = -1;
for (double shade = 0.0; shade <= 1.0; shade += 0.01)
{
int index = ChargenPalSetMath.GetPaletteIndex(count, shade);
Assert.True(index >= previous, $"index regressed at shade={shade}");
previous = index;
}
}
}

View file

@ -0,0 +1,153 @@
using System.Numerics;
using AcDream.Core.Physics;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
using Xunit;
namespace AcDream.Core.Tests.Physics;
/// <summary>
/// <see cref="RetailAnimationCyclePlayback"/> is the shared advance-with-wrap
/// + lerp/slerp primitive behind the chargen preview's idle loop
/// (<c>ChargenPreviewAnimator</c>) — the SAME arithmetic
/// <c>LiveEntityAnimationPresenter.Present</c>'s legacy (no-
/// <see cref="AnimationSequencer"/>) branch already carries for NPC idle
/// cycles, extracted here so a second, live-entity-free consumer (the
/// chargen preview, which has no <c>LiveEntityRuntime</c> membership to hang
/// a sequencer off of) doesn't retype the formula.
/// </summary>
public sealed class RetailAnimationCyclePlaybackTests
{
private static Animation MakeAnim(int numFrames, int numParts, Vector3 origin, Quaternion orientation)
{
var anim = new Animation();
for (int f = 0; f < numFrames; f++)
{
var pf = new AnimationFrame((uint)numParts);
for (int p = 0; p < numParts; p++)
pf.Frames.Add(new Frame { Origin = origin, Orientation = orientation });
anim.PartFrames.Add(pf);
}
return anim;
}
[Fact]
public void Advance_WithinSpan_AddsElapsedTimesFramerate()
{
float result = RetailAnimationCyclePlayback.Advance(
currFrame: 5f, lowFrame: 0, highFrame: 29, framerate: 30f, elapsedSeconds: 0.1f);
Assert.Equal(8f, result, precision: 4); // 5 + 0.1*30 = 8.
}
[Fact]
public void Advance_PastHighFrame_WrapsBackToLowFrame()
{
// 29-frame span (0..29 inclusive = 30 frames), advancing from frame
// 28 by one second at 30fps overshoots by (28+30)-29 = 29, wrapping
// to lowFrame + (29 % 30) = 29... use a case with a clean wrap.
float result = RetailAnimationCyclePlayback.Advance(
currFrame: 25f, lowFrame: 0, highFrame: 29, framerate: 30f, elapsedSeconds: 0.2f);
// 25 + 6 = 31, over highFrame(29) by span+1=30: over = 31-0 = 31,
// wrapped = 0 + (31 % 30) = 1.
Assert.Equal(1f, result, precision: 4);
}
[Fact]
public void Advance_BelowLowFrame_ClampsToLowFrame()
{
float result = RetailAnimationCyclePlayback.Advance(
currFrame: -5f, lowFrame: 0, highFrame: 29, framerate: 30f, elapsedSeconds: 0.05f);
// -5 + 1.5 = -3.5, still below lowFrame(0) -> clamp.
Assert.Equal(0f, result);
}
[Theory]
[InlineData(0, 0)] // degenerate span (highFrame == lowFrame).
[InlineData(0, -1)] // inverted span.
public void Advance_DegenerateSpan_ReturnsCurrFrameUnchanged(int lowFrame, int highFrame)
{
float result = RetailAnimationCyclePlayback.Advance(
currFrame: 3f, lowFrame, highFrame, framerate: 30f, elapsedSeconds: 1f);
Assert.Equal(3f, result);
}
[Fact]
public void Advance_NonPositiveFramerateOrElapsed_ReturnsCurrFrameUnchanged()
{
Assert.Equal(3f, RetailAnimationCyclePlayback.Advance(3f, 0, 29, framerate: 0f, elapsedSeconds: 1f));
Assert.Equal(3f, RetailAnimationCyclePlayback.Advance(3f, 0, 29, framerate: 30f, elapsedSeconds: 0f));
Assert.Equal(3f, RetailAnimationCyclePlayback.Advance(3f, 0, 29, framerate: 30f, elapsedSeconds: -1f));
}
[Fact]
public void TryInterpolatePart_ExactFrame_ReturnsThatFramesPose()
{
Animation anim = MakeAnim(3, 2, new Vector3(1f, 2f, 3f), Quaternion.Identity);
bool ok = RetailAnimationCyclePlayback.TryInterpolatePart(
anim, currFrame: 1f, lowFrame: 0, highFrame: 2, partIndex: 0,
out Vector3 origin, out Quaternion orientation);
Assert.True(ok);
Assert.Equal(new Vector3(1f, 2f, 3f), origin);
Assert.Equal(Quaternion.Identity, orientation);
}
[Fact]
public void TryInterpolatePart_BetweenFrames_LerpsOriginHalfway()
{
var anim = new Animation();
var pf0 = new AnimationFrame(1);
pf0.Frames.Add(new Frame { Origin = Vector3.Zero, Orientation = Quaternion.Identity });
var pf1 = new AnimationFrame(1);
pf1.Frames.Add(new Frame { Origin = new Vector3(10f, 0f, 0f), Orientation = Quaternion.Identity });
anim.PartFrames.Add(pf0);
anim.PartFrames.Add(pf1);
bool ok = RetailAnimationCyclePlayback.TryInterpolatePart(
anim, currFrame: 0.5f, lowFrame: 0, highFrame: 1, partIndex: 0,
out Vector3 origin, out _);
Assert.True(ok);
Assert.Equal(new Vector3(5f, 0f, 0f), origin);
}
[Fact]
public void TryInterpolatePart_AtHighFrame_WrapsNextFrameToLowFrame()
{
var anim = new Animation();
var pf0 = new AnimationFrame(1);
pf0.Frames.Add(new Frame { Origin = new Vector3(1f, 0f, 0f), Orientation = Quaternion.Identity });
var pf1 = new AnimationFrame(1);
pf1.Frames.Add(new Frame { Origin = new Vector3(2f, 0f, 0f), Orientation = Quaternion.Identity });
anim.PartFrames.Add(pf0);
anim.PartFrames.Add(pf1);
// currFrame exactly at highFrame(1): frameIndex=1, nextIndex would be
// 2 which is > highFrame -> wraps to lowFrame(0). t=0 so origin==frame[1].
bool ok = RetailAnimationCyclePlayback.TryInterpolatePart(
anim, currFrame: 1f, lowFrame: 0, highFrame: 1, partIndex: 0,
out Vector3 origin, out _);
Assert.True(ok);
Assert.Equal(new Vector3(2f, 0f, 0f), origin);
}
[Fact]
public void TryInterpolatePart_PartIndexOutOfRange_ReturnsFalse()
{
Animation anim = MakeAnim(2, 1, Vector3.Zero, Quaternion.Identity);
bool ok = RetailAnimationCyclePlayback.TryInterpolatePart(
anim, currFrame: 0f, lowFrame: 0, highFrame: 1, partIndex: 5,
out Vector3 origin, out Quaternion orientation);
Assert.False(ok);
Assert.Equal(default(Vector3), origin);
Assert.Equal(default(Quaternion), orientation);
}
}