feat(chargen): Campaign CC slice CC6a — index→ObjDesc factory + preview renderer foundation

Delivers the CC6a foundation half of the chargen 3D preview: the missing
index->ObjDesc appearance factory the campaign plan's acdream-seams
section named, plus a static-pose offscreen renderer following
PrivateEntityViewportRenderer's proven paperdoll/appraisal architecture.
Page mount, spin/color-wheel controls, and rotate/zoom behavior stay out
of scope per the CC4-parallel worktree contract (CC6b, after CC4 merges).

Core (src/AcDream.Core/CharGen/, pure, no Chorizite on public surfaces):
ChargenAppearanceFactory.TryCompose ports gmCG3DView::Update @0x004EE9D0's
ObjDesc rebuild in its exact decompiled order - base body, hair style,
clothing in retail's own Headgear/Trousers/Shirt/Footwear order (not the
UI tab order or the wire's field order, both of which differ), eyes
(bald-aware), nose, mouth, then the unconditional skin subpalette, hair
color, eye color. ChargenPalSetMath ports PalSet::GetPaletteID's
shade-to-index formula, cross-checked three ways (decomp control flow,
ACE's PaletteSet.GetPaletteID "Taken from acclient.c" citation, ACViewer's
identical slider math). ChargenPalSet/ChargenClothingTable are pure
projections behind IChargenPalSetSource/IChargenClothingTableSource so the
factory itself never touches a dat.

Content (src/AcDream.Content/CharGen/): ChargenAppearanceCatalog is the
cached dat-backed implementation of those two source interfaces, mirroring
ChargenTableReader's no-leak discipline.

App (src/AcDream.App/Rendering/): ChargenPreviewRenderer is a third facade
over PrivateEntityViewportRenderer beside PaperdollViewportRenderer and
CreatureAppraisalViewportRenderer - no existing rendering file touched.
ChargenPreviewCamera carries the four retail-verbatim per-heritage eye
profiles from gmCGAppearancePage::Update @0x0047E8F0 (cross-checked
against ZoomIn/ZoomOut's identical literals) plus the recovered rotation
(3.0 s/revolution) and zoom-tween (0.6 s, reconstructed from the
decompiler's garbled float literals - the plan's own "measure if it
matters" note is resolved, not garbled beyond recovery). Rotation applies
to the character model, not the camera, per gmCGAppearancePage::DoRotation.
ChargenPreviewEntityBuilder resolves Setup/GfxObj/Surface/Animation itself
(there is no live entity yet), reusing DatLiveEntityProjectionMaterializer's
surface-override algorithm and RetailPaperdollPoseApplicator's held-pose
technique, generalized to chargen's per-heritage rest-pose DID.

Two register rows filed: TS-83 (the plan-named CC6a static-pose-vs-retail-
idle-loop staging, CC6b to retire) and TS-82 (measured, not assumed - the
un-ported clothing Setup-substitution fallback chain costs nothing for the
9 standard heritages with clothing UI, but Undead's default gear choices
genuinely lack ClothingBaseEffects coverage for Undead's own body Setup).

Tests: ChargenPalSetMathTests, ChargenAppearanceFactoryTests (hand-built
fixtures), ChargenAppearanceCatalogInstalledDatTests (installed-DAT sweep,
all 26 heritage/gender combinations, zero missing PalSet/ClothingTable
ids), ChargenPreviewCameraTests, ChargenPreviewEntityBuilderTests
(installed-DAT-gated, proves a real 34-part Aluvian mesh resolves).
Core.Tests 4767/1 skip, Content.Tests 146/0, App.Tests 5121/6 skips - all
pre-existing skips, zero failures, full solution Release build green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-15 17:21:34 +02:00
parent 3a6b7e3115
commit 55bfd9ca82
16 changed files with 2131 additions and 2 deletions

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,127 @@
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);
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);
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);
// 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);
}
}

View file

@ -0,0 +1,155 @@
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 records (without asserting
/// zero — see the class doc on <see cref="ChargenClothingTable"/>'s
/// deliberate scope cut) how many clothing slots have no
/// <c>ClothingBaseEffects</c> entry for their own gender's body Setup, so a
/// future session can see at a glance whether CC6a's decision to skip
/// retail's Setup-substitution fallback chain ever actually costs
/// coverage on the real dat.
/// </summary>
public sealed class ChargenAppearanceCatalogInstalledDatTests
{
private readonly ITestOutputHelper _out;
public ChargenAppearanceCatalogInstalledDatTests(ITestOutputHelper output) => _out = output;
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;
int absentBaseEffectTotal = 0;
var missingSummaries = 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}"))}]");
}
absentBaseEffectTotal += result.ClothingTablesMissingBaseEffectForSetup.Count;
if (result.ClothingTablesMissingBaseEffectForSetup.Count > 0)
{
_out.WriteLine(
$"heritage={heritage.Name} 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}"))}]");
}
}
}
_out.WriteLine($"composed {composed} heritage/gender selections; {absentBaseEffectTotal} absent-base-effect slots total.");
Assert.True(
missingSummaries.Count == 0,
"Missing dat ids found:\n" + string.Join('\n', missingSummaries));
Assert.True(composed >= 13, $"Expected at least 13 heritage/gender combinations, composed {composed}.");
}
/// <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,436 @@
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);
}
[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);
}
[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;
}
}
}