acdream/src/AcDream.App/Rendering/ChargenPreviewAnimator.cs
Erik 1ba22a01a8 fix(chargen): Campaign CC CC6b-PRE review fix round — F1-F7 + F11 concession rewrite
F1 (BLOCKING, doc-only) — the idle-by-default rationale rested on an unsound
"uninitialized C++ member defaults to 0" argument (heap operator-new memory
is indeterminate, not zero). Verified and replaced with the real evidence:
gmCGAppearancePage::InitializePage @0x0047FDD0 writes an EXPLICIT
this->m_bZoomedIn = 0; at 0x004802C3, immediately after that same function
points the camera at the zoomed-IN per-heritage eye (0x00480286-0x0048029E).
Fixed in all three places: the register's TS-83 retirement clause,
ChargenPreviewAnimator's class doc, ChargenPreviewZoomController.IsZoomedIn's
doc. Recorded the retail quirk this implies: the character starts framed
close-up while not-zoomed-in, so the first Zoom In click (once mounted)
tweens close-eye->close-eye (visually null) while still freezing the
animation — the port reproduces this faithfully.

F2 — ChargenPreviewZoomController and ChargenPreviewAnimator kept
independent _zoomedIn bools synced only via a nullable animator parameter,
risking desync. Retail's m_bZoomedIn is a single field gating both camera
and animation, so the fix makes the animator the sole state owner:
ChargenPreviewZoomController now takes its ChargenPreviewAnimator as a
required constructor dependency, IsZoomedIn reads straight through to it,
and ZoomIn/ZoomOut no longer take a parameter at all — there is no second
bool left to disagree.

F3 — documented the DoRotation counter-clockwise branch's x87-stack
decompiler artifact (BN renders x87_r7_1 = x87_r6_3 at 0x0047CAEB, which
would store delta-degrees instead of the timestamp for CCW only); the port
already stores "now" in both branches, cited against
feedback_bn_decomp_field_names.md.

F4 — ChargenPreviewAnimator.ApplyIdleFrame now double-buffers two
List<MeshRef> instead of allocating fresh every 30fps tick.

F5 — filed docs/ISSUES.md #402 tracking the RetailAnimationCyclePlayback /
LiveEntityAnimationPresenter duplication as an owned post-CC follow-up,
referenced from the new type's own doc.

F6 — reworded the ChargenPreviewEntityBuilder.TryBuild "byte-identical"
claim to result-identical (TryBuildAnimated now also resolves the idle DID
and loads the idle Animation before the wrapper discards them).

F7 — added the missing clockwise >360 clamp test (readable decomp
polarity, unlike F3's CCW artifact).

ALSO — rewrote the CC6b ledger row's m_alternateSetupID MUST-COVER note per
the reviewer's F11 concession: all five write sites belong to gmBarberUI
(the post-creation barber shop), not gmCGAppearancePage, which has no
option-checkbox-equivalent field at all. Added the enclosing-function
citations and an explicit directive that CC6b-mount must NOT build a
crown/no-flame checkbox on the Appearance page.

Tests: ChargenPreviewRotationControllerTests +1 (10 total),
ChargenPreviewZoomControllerTests +2 and every case rewritten for the
required-animator constructor (9 total). Core.Tests 4786/1 skip (unchanged),
Content.Tests 147/0, App.Tests 5152/6 skips (+3) — zero failures in
isolation, full solution Release build green. Two pre-existing flakes
observed across repeated full-solution runs, neither caused by this round
and neither reproducing standalone: Core.Net.Tests' NakEmissionTests loss
soak, and Content.Tests' DecodedTextureCacheTests concurrency race.

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

157 lines
7.1 KiB
C#

using System.Collections.Generic;
using System.Numerics;
using AcDream.Core.Physics;
using AcDream.Core.World;
namespace AcDream.App.Rendering;
/// <summary>
/// Owns the chargen preview's per-frame idle-loop ↔ rest-pose playback,
/// mirroring <c>gmCG3DView::StartAnimation</c>/<c>StopAnimation</c>'s swap
/// (<c>0x004EE600</c>/<c>0x004EE640</c>) and
/// <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>'s immediate call into it
/// (<c>0x0047D024</c>/<c>0x0047D160</c> — the swap happens the instant the
/// button is pressed, NOT once the camera's own 0.6s tween finishes).
///
/// <para>
/// <b>Retail default is idle-PLAYING, not frozen</b> — see
/// <see cref="ChargenPreviewEntityBuilder"/>'s class doc for the decomp
/// citations. This class's own default (<see cref="IsZoomedIn"/> starts
/// <c>false</c>) reproduces that: its constructor immediately plays the
/// idle animation's frame 0 when one resolved, matching
/// <c>gmCGAppearancePage::Update</c>'s own trailing
/// <c>if (m_bZoomedIn == 0) StartAnimation()</c> gate
/// (~0x0047EF01-0x0047EF12), which re-fires on every heritage/gender/
/// appearance change too — <see cref="SetZoomedIn"/> restarts the idle loop
/// at frame 0 on every transition INTO the playing state for the same
/// reason: <c>set_sequence_animation</c>'s <c>arg3=1</c> clears the sequence
/// before appending, so every <c>StartAnimation</c> call restarts the clip.
/// The DEFAULT-false claim itself rests on <c>gmCGAppearancePage::InitializePage
/// @ 0x0047FDD0</c>'s explicit <c>this-&gt;m_bZoomedIn = 0;</c> at
/// <c>0x004802C3</c> — written immediately after that same function sets the
/// camera to the zoomed-IN per-heritage eye (<c>0x00480286-0x0048029E</c>),
/// not from the ctor simply never touching the field (heap <c>operator new</c>
/// memory is indeterminate, not zero — that argument doesn't hold on its
/// own). One retail quirk this implies: the character starts framed close-up
/// AND not-zoomed-in at the same time, so the FIRST Zoom In click (once
/// mounted) tweens close-eye→close-eye — visually null — while still
/// freezing the animation; the port reproduces this faithfully rather than
/// treating it as a bug.
/// </para>
///
/// <para>
/// The page-mount half (CC6b, after CC4 merges) wires the Zoom In/Out
/// buttons to <see cref="SetZoomedIn"/> and the render loop to
/// <see cref="Tick"/>; nothing in this repository calls either yet.
/// </para>
/// </summary>
internal sealed class ChargenPreviewAnimator
{
/// <summary>
/// <c>gmCG3DView::StartAnimation</c>'s literal framerate argument
/// (<c>set_sequence_animation(this->m_pPlayerObject,
/// this->m_didAnimation.id, 1, 0, 30f)</c>, pseudo-C ~0x004ee61b).
/// </summary>
public const float IdleFramerate = 30f;
private readonly ChargenPreviewAnimatedBuild _build;
private float _currFrame;
private bool _zoomedIn;
// Double-buffered so a 30fps Tick doesn't allocate a fresh List<MeshRef>
// every frame: one buffer is whatever Entity.MeshRefs currently points
// at (potentially still being read by the renderer's own Render() call
// for this frame), the other is safe to Clear()+refill for the NEXT
// tick and only gets published once fully populated.
private readonly List<MeshRef> _meshRefsBufferA = [];
private readonly List<MeshRef> _meshRefsBufferB = [];
private bool _nextBufferIsA = true;
public ChargenPreviewAnimator(ChargenPreviewAnimatedBuild build)
{
_build = build ?? throw new ArgumentNullException(nameof(build));
_currFrame = build.IdleLowFrame;
if (build.IdleAnimation is not null)
ApplyIdleFrame(); // retail's true default: idle playing, frame 0.
// Else: Entity.MeshRefs already holds RestMeshRefs (set by
// TryBuildAnimated) as the best available fallback.
}
/// <summary>The live preview entity — mutated in place by <see cref="Tick"/>
/// and <see cref="SetZoomedIn"/>; the renderer never needs to re-call
/// <c>SetPreview</c> after the first assignment (<c>WorldEntity.MeshRefs</c>
/// is read fresh every draw — see its own doc comment).</summary>
public WorldEntity Entity => _build.Entity;
public bool IsZoomedIn => _zoomedIn;
/// <summary>
/// <c>gmCGAppearancePage::ZoomIn</c>/<c>ZoomOut</c>'s
/// <c>StopAnimation</c>/<c>StartAnimation</c> call, applied immediately
/// (retail does not wait for the camera tween to finish before swapping
/// animation state — see this class's own doc comment). No-op if
/// already in the requested state, matching retail's own early-return
/// guards (<c>ZoomIn</c>'s <c>if (m_bZoomedIn != 0) return</c>,
/// <c>ZoomOut</c>'s mirror).
/// </summary>
public void SetZoomedIn(bool zoomedIn)
{
if (_zoomedIn == zoomedIn)
return;
_zoomedIn = zoomedIn;
if (zoomedIn)
{
_build.Entity.MeshRefs = _build.RestMeshRefs;
}
else
{
_currFrame = _build.IdleLowFrame;
if (_build.IdleAnimation is not null)
ApplyIdleFrame();
}
}
/// <summary>
/// Advances the idle loop by <paramref name="elapsedSeconds"/>. No-op
/// while zoomed in (the rest pose is frozen — retail's framerate-0
/// <c>set_sequence_animation</c> call never advances) or when no idle
/// Animation resolved (heritage/DID gap; the entity keeps whatever pose
/// the constructor seeded).
/// </summary>
public void Tick(float elapsedSeconds)
{
if (_zoomedIn || _build.IdleAnimation is null || elapsedSeconds <= 0f)
return;
_currFrame = RetailAnimationCyclePlayback.Advance(
_currFrame, _build.IdleLowFrame, _build.IdleHighFrame, IdleFramerate, elapsedSeconds);
ApplyIdleFrame();
}
private void ApplyIdleFrame()
{
DatReaderWriter.DBObjs.Animation animation = _build.IdleAnimation!;
IReadOnlyList<ChargenPreviewDrawablePart> parts = _build.DrawableParts;
List<MeshRef> meshRefs = _nextBufferIsA ? _meshRefsBufferA : _meshRefsBufferB;
_nextBufferIsA = !_nextBufferIsA;
meshRefs.Clear();
foreach (ChargenPreviewDrawablePart part in parts)
{
bool resolved = RetailAnimationCyclePlayback.TryInterpolatePart(
animation, _currFrame, _build.IdleLowFrame, _build.IdleHighFrame,
part.SetupPartIndex, out Vector3 origin, out Quaternion orientation);
// Same defensive default as ApplyHeldPoseTransforms: a part
// index the bracketing frame doesn't cover (a Setup/Animation
// part-count mismatch, never expected in practice) keeps
// identity rather than a degenerate zero quaternion.
if (!resolved)
{
origin = Vector3.Zero;
orientation = Quaternion.Identity;
}
Matrix4x4 transform = RetailHeldPose.ComposePartTransform(part.DefaultScale, origin, orientation);
meshRefs.Add(new MeshRef(part.GfxObjId, transform) { SurfaceOverrides = part.SurfaceOverrides });
}
_build.Entity.MeshRefs = meshRefs;
}
}