acdream/src/AcDream.Core.Net/GameEventWiring.cs
Erik f416c577d6 fix(net): stop dropping every transient string on a chat type that isn't sent
CommunicationTransientString (0x02EB) required a trailing u32 chat type after
the message. The server does not send one. Because the string is padded to a
four-byte boundary, the remaining length after reading it was always zero, the
guard tripped, and the parser returned null for every transient string the
server has ever sent. Not most. Every one.

Three oracles agree there is no such field. ACE's
GameEventCommunicationTransientString writes exactly one WriteString16L and
stops. Retail's ClientCommunicationSystem::Handle_Communication__TransientString
at 0x0057d460 takes a single PStringBase<char> argument. holtburger carries no
type field for the event either.

ParseTransient now returns the string. The wiring supplies chat type 0, which
is ACE's ChatMessageType.Broadcast and which ACE's own LogTextTypeEnumMapper
comment names "Default" — the honest stand-in for a message the server sends
untyped. What retail's transient strings should actually look like is a
rendering question and belongs with the chat colour work, not here.

The existing round-trip test was itself appending the phantom trailing dword,
which is exactly why the wrong guard looked correct for as long as it did. It
is corrected to the real payload and joined by a case sweeping string lengths
zero through four, so no future padding-residue assumption can hide here again.

Core.Net tests go 654 to 655.

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

758 lines
37 KiB
C#

using System;
using System.Linq;
using AcDream.Core.Chat;
using AcDream.Core.Combat;
using AcDream.Core.Items;
using AcDream.Core.Net.Messages;
using AcDream.Core.Player;
using AcDream.Core.Spells;
using AcDream.Core.Social;
namespace AcDream.Core.Net;
/// <summary>
/// Central registration point that wires every parsed GameEvent from
/// <see cref="GameEventDispatcher"/> into the appropriate Core state
/// class (<see cref="ClientObjectTable"/>, <see cref="CombatState"/>,
/// <see cref="Spellbook"/>, <see cref="ChatLog"/>).
///
/// <para>
/// Call once at startup (or on reconnect) passing the session's
/// dispatcher + the state instances you want to feed. The returned
/// subscription owns exactly these registrations and must be disposed
/// before the session is replaced. A later legacy registration still
/// overrides the corresponding default without becoming owned here.
/// </para>
///
/// <para>
/// This is the piece that makes Phase F.1's dispatcher go from "a
/// thing that routes opcodes" to "a thing that actually populates
/// client state so the UI can redraw". Without this glue every
/// dispatcher handler had to be written by hand at each call site.
/// </para>
/// </summary>
public static class GameEventWiring
{
public static IDisposable WireAll(
GameEventDispatcher dispatcher,
ClientObjectTable items,
CombatState combat,
Spellbook spellbook,
ChatLog chat,
LocalPlayerState? localPlayer = null,
TurbineChatState? turbineChat = null,
// K-fix7 (2026-04-26): server-sent skill update callback. Fires
// whenever PlayerDescription's skill table arrives with Run (24)
// or Jump (22) entries — we only care about those two for
// movement physics. Caller (GameWindow) plumbs this into the
// active PlayerMovementController + caches it for the next
// EnterPlayerModeNow construction.
//
// K-fix13 (2026-04-26): the wire's `init` field is ONLY
// InitLevel (training tier from chargen, per ACE
// GameEventPlayerDescription.cs:317 "init_level, for
// training/specialized bonus"). The AttributeFormula
// contribution (Strength/Quickness/etc-derived) is computed
// by ACE at runtime via portal.dat's SkillTable + attribute
// currents. Without it our totals undershoot the real
// Current skill by 50-100 points for movement skills, which
// is why jumps looked too short. The optional
// <c>resolveSkillFormulaBonus</c> callback lets the caller
// (GameWindow) plug in the AttributeFormula contribution
// using its cached SkillTable + attribute currents — when
// present, total skill = formulaBonus + init + ranks
// (matching ACE's CreatureSkill.Current minus
// augs/multipliers/vitae which we still don't model).
Action<int /*runSkill*/, int /*jumpSkill*/>? onSkillsUpdated = null,
Func<uint /*skillId*/, IReadOnlyDictionary<uint, uint> /*attrCurrents*/, uint /*formulaBonus*/>? resolveSkillFormulaBonus = null,
// D.5.1 Task 4: persists Shortcuts from each PlayerDescription so the
// toolbar can populate itself at login without keeping a parser reference.
// Optional so all existing callers and tests compile unchanged.
Action<IReadOnlyList<ShortcutEntry>>? onShortcuts = null,
// B-Wire: the local player's server guid. When provided, the PD handler upserts
// the player's own PropertyBundle (EncumbranceVal etc.) into the player ClientObject.
Func<uint>? playerGuid = null,
Action<uint /*weenieError*/>? onUseDone = null,
Action<AppraiseInfoParser.Parsed>? onAppraisal = null,
ItemManaState? itemMana = null,
Action<GameEvents.CharacterConfirmationRequest>? onConfirmationRequest = null,
Action<GameEvents.CharacterConfirmationDone>? onConfirmationDone = null,
FriendsState? friends = null,
SquelchState? squelch = null,
Action<IReadOnlyList<(uint Id, uint Amount)>>? onDesiredComponents = null,
Action<uint /*options1*/, uint /*options2*/>? onCharacterOptions = null,
Func<double>? clientTime = null,
ExternalContainerState? externalContainers = null,
Func<bool>? accepting = null)
{
ArgumentNullException.ThrowIfNull(dispatcher);
ArgumentNullException.ThrowIfNull(items);
ArgumentNullException.ThrowIfNull(combat);
ArgumentNullException.ThrowIfNull(spellbook);
ArgumentNullException.ThrowIfNull(chat);
clientTime ??= static () => 0d;
var registrar = new OwnedGameEventRegistrar(dispatcher, accepting);
using var construction = new RegistrationBuildScope(registrar);
// ── Chat ──────────────────────────────────────────────────
registrar.Register(GameEventType.ChannelBroadcast, e =>
{
var p = GameEvents.ParseChannelBroadcast(e.Payload.Span);
if (p is not null) chat.OnChannelBroadcast(p.Value.ChannelId, p.Value.SenderName, p.Value.Message);
});
registrar.Register(GameEventType.Tell, e =>
{
var p = GameEvents.ParseTell(e.Payload.Span);
if (p is not null) chat.OnTellReceived(p.Value.SenderName, p.Value.Message, p.Value.SenderGuid);
});
registrar.Register(GameEventType.CommunicationTransientString, e =>
{
// 0x02EB carries no chat type on the wire (see ParseTransient).
// 0 is ACE's ChatMessageType.Broadcast, which its own
// LogTextTypeEnumMapper comment names "Default" — the right
// stand-in for a message the server sends untyped. The exact
// retail rendering style for transient strings belongs to the
// chat colour/text work, not to this parser.
var s = GameEvents.ParseTransient(e.Payload.Span);
if (s is not null) chat.OnSystemMessage(s, chatType: 0u);
});
registrar.Register(GameEventType.PopupString, e =>
{
var s = GameEvents.ParsePopupString(e.Payload.Span);
if (s is not null) chat.OnPopup(s);
});
registrar.Register(GameEventType.QueryAgeResponse, e =>
{
var p = GameEvents.ParseQueryAgeResponse(e.Payload.Span);
if (p is null) return;
string text = string.IsNullOrEmpty(p.Value.Name)
? $"You have played for {p.Value.Age}."
: $"{p.Value.Name} has played for {p.Value.Age}.";
chat.OnSystemMessage(text, chatType: 0u);
});
if (onConfirmationRequest is not null)
{
registrar.Register(GameEventType.CharacterConfirmationRequest, e =>
{
var request = GameEvents.ParseCharacterConfirmationRequest(e.Payload.Span);
if (request is not null)
onConfirmationRequest(request.Value);
});
}
if (onConfirmationDone is not null)
{
registrar.Register(GameEventType.CharacterConfirmationDone, e =>
{
var done = GameEvents.ParseCharacterConfirmationDone(e.Payload.Span);
if (done is not null)
onConfirmationDone(done.Value);
});
}
if (friends is not null)
{
registrar.Register(GameEventType.FriendsListUpdate, e =>
{
FriendsUpdate? update = SocialStateMessages.ParseFriendsUpdate(e.Payload.Span);
if (update is not null) friends.Apply(update);
});
}
if (squelch is not null)
{
registrar.Register(GameEventType.SetSquelchDB, e =>
{
SquelchDatabase? database = SocialStateMessages.ParseSquelchDatabase(e.Payload.Span);
if (database is not null) squelch.Replace(database);
});
}
// ── TurbineChat channel list (0x0295 SetTurbineChatChannels) ─────
// Phase I.6: arrives once at login (and after chat-server reconnect)
// listing the per-session room ids assigned to General / Trade /
// LFG / Roleplay / Society / Olthoi (and the optional Allegiance
// Turbine room). Without this the TurbineChat outbound path stays
// disabled and the chat panel falls back to the legacy ChatChannel
// GameAction. See holtburger client/messages.rs:220-223 for the
// server-message handling pattern.
if (turbineChat is not null)
{
registrar.Register(GameEventType.SetTurbineChatChannels, e =>
{
var p = SetTurbineChatChannels.TryParse(e.Payload.Span);
if (p is null) return;
turbineChat.OnChannelsReceived(
allegianceRoom: p.Value.AllegianceRoom,
generalRoom: p.Value.GeneralRoom,
tradeRoom: p.Value.TradeRoom,
lfgRoom: p.Value.LfgRoom,
roleplayRoom: p.Value.RoleplayRoom,
olthoiRoom: p.Value.OlthoiRoom,
societyRoom: p.Value.SocietyRoom,
societyCelestialHandRoom: p.Value.SocietyCelestialHandRoom,
societyEldrytchWebRoom: p.Value.SocietyEldrytchWebRoom,
societyRadiantBloodRoom: p.Value.SocietyRadiantBloodRoom);
// Diagnostic: confirm the channel ids landed. Without
// this print there's no easy way to tell from the live
// log whether ACE actually sent 0x0295 or whether
// outbound /g /trade /lfg are silently falling back to
// the (broken) legacy ChatChannel path.
Console.WriteLine(
$"chat: SetTurbineChatChannels parsed enabled={turbineChat.Enabled} " +
$"general=0x{p.Value.GeneralRoom:X8} trade=0x{p.Value.TradeRoom:X8} " +
$"lfg=0x{p.Value.LfgRoom:X8} roleplay=0x{p.Value.RoleplayRoom:X8} " +
$"society=0x{p.Value.SocietyRoom:X8} olthoi=0x{p.Value.OlthoiRoom:X8} " +
$"allegiance=0x{p.Value.AllegianceRoom:X8}");
});
}
// ── Errors ───────────────────────────────────────────────
// Phase I.5: WeenieError + WeenieErrorWithString parsers existed
// (GameEvents.ParseWeenieError(WithString)) but were never registered.
// The server fires these for game-logic failures: "not enough mana",
// "can't pick that up", "your spell fizzled". Routed to chat.
registrar.Register(GameEventType.WeenieError, e =>
{
var code = GameEvents.ParseWeenieError(e.Payload.Span);
if (code is not null) chat.OnWeenieError(code.Value, param: null);
});
registrar.Register(GameEventType.WeenieErrorWithString, e =>
{
var p = GameEvents.ParseWeenieErrorWithString(e.Payload.Span);
if (p is not null) chat.OnWeenieError(p.Value.ErrorCode, p.Value.Interpolation);
});
// ── Combat ────────────────────────────────────────────────
registrar.Register(GameEventType.UpdateHealth, e =>
{
var p = GameEvents.ParseUpdateHealth(e.Payload.Span);
if (p is not null) combat.OnUpdateHealth(p.Value.TargetGuid, p.Value.HealthPercent);
});
if (itemMana is not null)
{
registrar.Register(GameEventType.QueryItemManaResponse, e =>
{
var p = GameEvents.ParseQueryItemManaResponse(e.Payload.Span);
if (p is not null)
itemMana.OnQueryItemManaResponse(
p.Value.ItemGuid, p.Value.ManaPercent, p.Value.Valid);
});
}
registrar.Register(GameEventType.VictimNotification, e =>
{
var p = GameEvents.ParseVictimNotification(e.Payload.Span);
if (p is not null) chat.OnCombatLine(p.Value.DeathMessage, CombatLineKind.Error);
});
registrar.Register(GameEventType.DefenderNotification, e =>
{
var p = GameEvents.ParseDefenderNotification(e.Payload.Span);
if (p is not null) combat.OnDefenderNotification(
p.Value.AttackerName, 0u, p.Value.DamageType,
p.Value.Damage, p.Value.HitQuadrant, p.Value.Critical);
});
registrar.Register(GameEventType.AttackerNotification, e =>
{
var p = GameEvents.ParseAttackerNotification(e.Payload.Span);
if (p is not null) combat.OnAttackerNotification(
p.Value.DefenderName, p.Value.DamageType, p.Value.Damage, (float)p.Value.HealthPercent);
});
registrar.Register(GameEventType.EvasionAttackerNotification, e =>
{
var name = GameEvents.ParseEvasionAttackerNotification(e.Payload.Span);
if (name is not null) combat.OnEvasionAttackerNotification(name);
});
registrar.Register(GameEventType.EvasionDefenderNotification, e =>
{
var name = GameEvents.ParseEvasionDefenderNotification(e.Payload.Span);
if (name is not null) combat.OnEvasionDefenderNotification(name);
});
registrar.Register(GameEventType.AttackDone, e =>
{
var p = GameEvents.ParseAttackDone(e.Payload.Span);
if (p is not null) combat.OnAttackDone(p.Value.AttackSequence, p.Value.WeenieError);
});
registrar.Register(GameEventType.CombatCommenceAttack, e =>
{
if (GameEvents.ParseCombatCommenceAttack(e.Payload.Span))
combat.OnCombatCommenceAttack();
});
registrar.Register(GameEventType.KillerNotification, e =>
{
var p = GameEvents.ParseKillerNotification(e.Payload.Span);
if (p is not null) chat.OnCombatLine(p.Value.DeathMessage, CombatLineKind.Info);
});
// ── Spells ────────────────────────────────────────────────
registrar.Register(GameEventType.MagicUpdateSpell, e =>
{
var spellId = GameEvents.ParseMagicUpdateSpell(e.Payload.Span);
if (spellId is not null) spellbook.OnSpellLearned(spellId.Value);
});
registrar.Register(GameEventType.MagicRemoveSpell, e =>
{
var spellId = GameEvents.ParseMagicRemoveSpell(e.Payload.Span);
if (spellId is not null) spellbook.OnSpellForgotten(spellId.Value);
});
registrar.Register(GameEventType.MagicUpdateEnchantment, e =>
{
var p = GameEvents.ParseMagicUpdateEnchantment(e.Payload.Span);
if (p is not null) spellbook.OnEnchantmentAdded(ToActiveEnchantment(p.Value, clientTime()));
});
registrar.Register(GameEventType.MagicUpdateMultipleEnchantments, e =>
{
var entries = GameEvents.ParseMagicUpdateMultipleEnchantments(e.Payload.Span);
if (entries is not null)
{
double receivedAt = clientTime();
spellbook.OnEnchantmentsAdded(entries.Select(entry =>
ToActiveEnchantment(entry, receivedAt)));
}
});
registrar.Register(GameEventType.MagicRemoveEnchantment, e =>
{
var p = GameEvents.ParseMagicRemoveEnchantment(e.Payload.Span);
if (p is not null) spellbook.OnEnchantmentRemoved(p.Value.Layer, p.Value.SpellId);
});
registrar.Register(GameEventType.MagicRemoveMultipleEnchantments, e =>
{
var entries = GameEvents.ParseMagicLayeredSpellList(e.Payload.Span);
if (entries is not null)
spellbook.OnEnchantmentsRemoved(entries.Select(item => ((uint)item.SpellId, (uint)item.Layer)));
});
registrar.Register(GameEventType.MagicDispelEnchantment, e =>
{
var p = GameEvents.ParseMagicDispelEnchantment(e.Payload.Span);
if (p is not null) spellbook.OnEnchantmentRemoved(p.Value.Layer, p.Value.SpellId);
});
registrar.Register(GameEventType.MagicDispelMultipleEnchantments, e =>
{
var entries = GameEvents.ParseMagicLayeredSpellList(e.Payload.Span);
if (entries is not null)
spellbook.OnEnchantmentsRemoved(entries.Select(item => ((uint)item.SpellId, (uint)item.Layer)));
});
registrar.Register(GameEventType.MagicPurgeEnchantments,
_ => spellbook.OnPurgeAll());
registrar.Register(GameEventType.MagicPurgeBadEnchantments,
_ => spellbook.OnPurgeBadEnchantments());
// ── Inventory ─────────────────────────────────────────────
registrar.Register(GameEventType.WieldObject, e =>
{
var p = GameEvents.ParseWieldObject(e.Payload.Span);
if (p is null) return;
uint wielderGuid = playerGuid?.Invoke() ?? 0u;
items.ApplyConfirmedServerWield(
p.Value.ItemGuid,
wielderGuid,
(AcDream.Core.Items.EquipMask)p.Value.EquipLoc);
});
registrar.Register(GameEventType.InventoryPutObjInContainer, e =>
{
var p = GameEvents.ParsePutObjInContainer(e.Payload.Span);
if (p is null) return;
items.ApplyConfirmedServerMove(
p.Value.ItemGuid,
p.Value.ContainerGuid,
newWielderId: 0u,
newSlot: (int)p.Value.Placement,
containerTypeHint: p.Value.ContainerType);
});
// ViewContents (0x0196) — the server's AUTHORITATIVE full contents list for a container you
// opened (Use 0x0036). Treat it as a full projection-only REPLACE: update membership without
// inventing ContainerSlot values, then publish one ContainerContentsReplaced notification so
// every UI consumer repaints from the same snapshot. Retail: ClientUISystem::OnViewContents.
registrar.Register(GameEventType.ViewContents, e =>
{
var p = GameEvents.ParseViewContents(e.Payload.Span);
if (p is null) return;
var entries = new ContainerContentEntry[p.Value.Items.Count];
for (int i = 0; i < entries.Length; i++)
entries[i] = new ContainerContentEntry(
p.Value.Items[i].Guid,
p.Value.Items[i].ContainerType);
items.ReplaceContents(p.Value.ContainerGuid, entries);
externalContainers?.ApplyViewContents(p.Value.ContainerGuid);
});
// B-Wire: InventoryPutObjectIn3D (0x019A) — server confirms an item dropped
// to the world. Unparent it from its container (it's now a ground object) so
// the inventory grid drops the cell; the object itself survives.
registrar.Register(GameEventType.InventoryPutObjectIn3D, e =>
{
var guid = GameEvents.ParsePutObjectIn3D(e.Payload.Span);
if (guid is not null)
{
items.ApplyConfirmedServerMove(
guid.Value,
newContainerId: 0u,
newWielderId: 0u);
}
});
// B-Drag: InventoryServerSaveFailed (0x00A0) — server rejected an optimistic move.
// Snap the item back to its pre-move slot. Log only when there was no pending move
// (a server-initiated failure on a non-optimistic path).
registrar.Register(GameEventType.InventoryServerSaveFailed, e =>
{
var p = GameEvents.ParseInventoryServerSaveFailed(e.Payload.Span);
if (p is null) return;
// B-Drag: the server rejected an optimistic move — snap the item back to its pre-move slot.
var item = items.Get(p.Value.ItemGuid);
string itemInfo = item is null
? "unknown"
: $"'{item.Name}' valid=0x{(uint)item.ValidLocations:X8} equip=0x{(uint)item.CurrentlyEquippedLocation:X8} priority=0x{item.Priority:X8} container=0x{item.ContainerId:X8} wielder=0x{item.WielderId:X8}";
bool rolledBack = items.RejectMove(p.Value.ItemGuid, p.Value.WeenieError);
Console.WriteLine($"[B-Drag] InventoryServerSaveFailed guid=0x{p.Value.ItemGuid:X8} err=0x{p.Value.WeenieError:X} rolledBack={rolledBack} item={itemInfo}");
});
// UseDone (0x01C7) — the Use/UseWithTarget completion signal. A non-zero
// code is a WeenieError refusal ("You are not trained in healing!" etc.);
// retail surfaces the string-table text as a chat line. Interim text map:
// WeenieErrorText (#202 / register AP-74). Without this line a refused
// kit-heal looks like "nothing happened" — the 2026-07-03 session bug.
registrar.Register(GameEventType.UseDone, e =>
{
uint? err = GameEvents.ParseUseDone(e.Payload.Span);
if (err is null) return;
Console.WriteLine($"[use-done] err=0x{err.Value:X4}");
onUseDone?.Invoke(err.Value);
if (err.Value != 0)
chat.OnSystemMessage(WeenieErrorText.For(err.Value), chatType: 0);
});
// CloseGroundContainer (0x0052): clear ClientUISystem::groundObject and
// retire the root plus nested temporary ViewContents projections. Child
// objects remain until authoritative move/delete wire says otherwise.
registrar.Register(GameEventType.CloseGroundContainer, e =>
{
var guid = GameEvents.ParseCloseGroundContainer(e.Payload.Span);
if (guid is null) return;
externalContainers?.ApplyClose(guid.Value);
items.StopViewingContentsTree(guid.Value);
});
registrar.Register(GameEventType.IdentifyObjectResponse, e =>
{
var p = AppraiseInfoParser.TryParse(e.Payload.Span);
if (p is null) return;
// Merge parsed properties into the item if we know about it.
if (p.Value.Success && items.Get(p.Value.Guid) is not null)
items.UpdateProperties(p.Value.Guid, p.Value.Properties);
if (p.Value.CreatureProfile is { HealthMax: > 0u } creature)
combat.OnUpdateHealth(
p.Value.Guid,
Math.Clamp(
(float)creature.Health / creature.HealthMax,
0f,
1f));
onAppraisal?.Invoke(p.Value);
// Spellbook from appraise: for caster items / scrolls this is
// the cast-on-use list. The local player's full learned
// spellbook arrives via PlayerDescription (0x0013), which uses
// a different wire format (see WorldSession + LocalPlayerState
// — feeds vitals from PrivateUpdateVital instead).
// The appraised spellbook belongs to that item. The local player's
// learned spell manifest arrives only in PlayerDescription.
});
// ── Player ────────────────────────────────────────────────
// PlayerDescription (0x0013) — full local-player snapshot at
// login. Distinct wire format from IdentifyObjectResponse
// (0x00C9): hand-written body with property hashtables,
// vector-flag-gated blocks, attribute block (where vitals 7/8/9
// carry their absolute current values), skills, spells, and a
// long trailer of options + inventory. See
// PlayerDescriptionParser for the full layout reference (mirrors
// holtburger events.rs:220-625).
//
// Two outputs from each parsed PlayerDescription:
// 1. LocalPlayerState absorbs vital ids 7/8/9 (Health/Stam/Mana).
// This is the ONLY way these arrive at login; PrivateUpdateVital
// delta opcodes only fire on rank-up / Enlightenment / admin
// changes — not initial sync.
// 2. Spellbook absorbs the learned spell list — for the local
// player this is the authoritative source (the per-item
// SpellBook flag in IdentifyObjectResponse is for caster
// items / scrolls only).
bool dumpPd = Environment.GetEnvironmentVariable("ACDREAM_DUMP_VITALS") == "1";
registrar.Register(GameEventType.PlayerDescription, e =>
{
var p = PlayerDescriptionParser.TryParse(e.Payload.Span);
if (dumpPd)
Console.WriteLine($"vitals: PlayerDescription body.len={e.Payload.Length} parsed={(p is null ? "NULL" : $"vec={p.Value.VectorFlags} attrs={p.Value.Attributes.Count} spells={p.Value.Spells.Count}")}");
if (p is null) return;
onCharacterOptions?.Invoke(p.Value.Options1, p.Value.Options2);
onDesiredComponents?.Invoke(p.Value.DesiredComps);
double receivedAt = clientTime();
ActiveEnchantmentRecord[] enchantments = p.Value.Enchantments
.Select(entry => ToActiveEnchantment(entry, receivedAt))
.ToArray();
spellbook.ReplaceManifest(
p.Value.Spells,
enchantments,
p.Value.HotbarSpells,
p.Value.DesiredComps,
p.Value.SpellbookFilters);
// B-Wire: deliver the player's OWN properties to the player ClientObject.
// (PD's "membership manifest" rule is about ITEMS, whose data comes from
// CreateObject; the player's own stats legitimately come from PD.) Upsert
// because PD can arrive before the player's CreateObject. Retires AP-48/AP-49.
if (playerGuid is not null)
items.UpsertProperties(playerGuid(), p.Value.Properties);
// K-fix13 (2026-04-26): build attrId → current map while
// iterating attributes so the skill-formula resolver below
// can apply (attr1.current * mult1 + attr2.current * mult2)
// / divisor + additive. "current" here = ranks + start
// (the formula-relevant attribute level pre-augs / pre-buffs).
// Built unconditionally (not inside the localPlayer guard)
// because the skill-formula resolver needs it even if no
// LocalPlayerState is wired.
var attrCurrents = new Dictionary<uint, uint>();
foreach (var attr in p.Value.Attributes)
{
// PD-attr ids 1-6 are primary attributes (Str / End
// / Coord / Quick / Focus / Self). 7/8/9 are vitals.
if (attr.AtType >= 1 && attr.AtType <= 6)
attrCurrents[attr.AtType] = attr.Ranks + attr.Start;
}
if (localPlayer is not null)
{
localPlayer.OnProperties(p.Value.Properties);
localPlayer.OnPositions(p.Value.Positions.ToDictionary(
static pair => pair.Key,
static pair => new AcDream.Core.Physics.Position(
pair.Value.LandblockId,
new System.Numerics.Vector3(
pair.Value.X, pair.Value.Y, pair.Value.Z),
new System.Numerics.Quaternion(
pair.Value.Qx, pair.Value.Qy,
pair.Value.Qz, pair.Value.Qw))));
foreach (var attr in p.Value.Attributes)
{
if (attr.Current is uint cur)
{
// Vital entry (id 7/8/9) — has absolute current.
if (dumpPd)
Console.WriteLine($"vitals: PD-vital id={attr.AtType} ranks={attr.Ranks} start={attr.Start} cur={cur}");
localPlayer.OnVitalUpdate(
vitalId: attr.AtType,
ranks: attr.Ranks,
start: attr.Start,
xp: attr.Xp,
current: cur);
}
else
{
// Primary attribute (id 1..6) — Endurance+Self feed
// the vital max formula (Endurance/2 for Health,
// Endurance for Stamina, Self for Mana).
if (dumpPd)
Console.WriteLine($"vitals: PD-attr id={attr.AtType} ranks={attr.Ranks} start={attr.Start}");
localPlayer.OnAttributeUpdate(
atType: attr.AtType,
ranks: attr.Ranks,
start: attr.Start,
xp: attr.Xp);
}
}
}
// K-fix7 (2026-04-26): push Run + Jump skill values to the
// PlayerMovementController so the runRate / jump-arc formulas
// use the SERVER's authoritative skill instead of our
// hardcoded ACDREAM_*_SKILL defaults. ACE Skill enum
// ordinals (Skill.cs:11-37): Jump = 22, Run = 24. The
// SkillEntry.Init field is the attribute-derived initial
// component; .Ranks is XP-bought additions. Their sum is
// the closest we get to ACE's CreatureSkill.Current short
// of porting the full Aug/Multiplier/Vitae chain.
if (localPlayer is not null || onSkillsUpdated is not null)
{
int runSkill = -1;
int jumpSkill = -1;
foreach (var s in p.Value.Skills)
{
// K-fix13: total = AttributeFormula(skill, attrs)
// + InitLevel (s.Init from wire)
// + Ranks (s.Ranks from wire)
// matches ACE CreatureSkill.Current minus
// augs/multipliers/vitae. The attribute-formula
// contribution is the dominant term for movement
// skills (typically 50-100 points) and was being
// dropped pre-fix13 — that's the root cause of
// jumps being too short relative to retail.
uint formulaBonus = resolveSkillFormulaBonus is not null
? resolveSkillFormulaBonus(s.SkillId, attrCurrents)
: 0u;
localPlayer?.OnSkillUpdate(
skillId: s.SkillId,
ranks: s.Ranks,
status: s.Status,
xp: s.Xp,
init: s.Init,
resistance: s.Resistance,
lastUsed: s.LastUsed,
formulaBonus: formulaBonus);
if (s.SkillId != 22u && s.SkillId != 24u) continue;
int total = (int)(formulaBonus + s.Init + s.Ranks);
if (s.SkillId == 24u) runSkill = total;
else if (s.SkillId == 22u) jumpSkill = total;
if (dumpPd)
Console.WriteLine(
$"vitals: PD-skill id={s.SkillId} init={s.Init} ranks={s.Ranks} formulaBonus={formulaBonus} total={total}");
}
if (runSkill >= 0 || jumpSkill >= 0)
onSkillsUpdated?.Invoke(runSkill, jumpSkill);
}
// Issue #7 — enchantment block: feed each entry into the
// Spellbook with full StatMod data so EnchantmentMath can
// aggregate buffs in vital-max calc (issue #6 lights up).
// D.5.4: PlayerDescription is a membership MANIFEST, not the data
// source. Record existence (+ equip slot); CreateObject fills the
// actual weenie data via ObjectTableWiring. (Previously this seeded
// stubs with WeenieClassId = ContainerType, a misuse — ContainerType
// is a 0/1/2 container-kind discriminator, not a weenie class id.)
uint ownerGuid = playerGuid?.Invoke() ?? 0u;
if (ownerGuid != 0u)
{
var entries = new ContainerContentEntry[p.Value.Inventory.Count];
for (int i = 0; i < entries.Length; i++)
entries[i] = new ContainerContentEntry(
p.Value.Inventory[i].Guid,
p.Value.Inventory[i].ContainerType);
items.InitializeInventoryManifest(ownerGuid, entries);
}
else
{
foreach (var inv in p.Value.Inventory)
items.RecordMembership(inv.Guid, containerTypeHint: inv.ContainerType);
}
if (ownerGuid != 0u)
{
var equipment = new EquipmentManifestEntry[p.Value.Equipped.Count];
for (int i = 0; i < equipment.Length; i++)
{
var eq = p.Value.Equipped[i];
equipment[i] = new EquipmentManifestEntry(
eq.Guid,
(EquipMask)eq.EquipLocation,
eq.Priority);
}
items.InitializeEquipmentManifest(ownerGuid, equipment);
}
else
{
foreach (var eq in p.Value.Equipped)
{
items.RecordMembership(
eq.Guid,
equip: (EquipMask)eq.EquipLocation,
priority: eq.Priority);
}
}
// D.5.1 Task 4: forward shortcut bar entries to the caller so the
// toolbar can read them without holding a parser reference.
onShortcuts?.Invoke(p.Value.Shortcuts);
});
return construction.Complete();
}
private sealed class OwnedGameEventRegistrar(
GameEventDispatcher dispatcher,
Func<bool>? accepting) : IDisposable
{
private readonly SubscriptionSet _subscriptions = new();
public void Register(
GameEventType type,
GameEventDispatcher.EventHandler handler)
{
GameEventDispatcher.EventHandler registered = accepting is null
? handler
: envelope =>
{
if (accepting()) handler(envelope);
};
_subscriptions.Add(dispatcher.RegisterOwned(type, registered));
}
public void Dispose() => _subscriptions.Dispose();
}
private sealed class RegistrationBuildScope(
OwnedGameEventRegistrar registration) : IDisposable
{
private bool _complete;
public IDisposable Complete()
{
_complete = true;
return registration;
}
public void Dispose()
{
if (!_complete)
registration.Dispose();
}
}
private static ActiveEnchantmentRecord ToActiveEnchantment(
PlayerDescriptionParser.EnchantmentEntry enchantment,
double receivedAt) => new(
SpellId: enchantment.SpellId,
LayerId: enchantment.Layer,
Duration: enchantment.Duration,
CasterGuid: enchantment.CasterGuid,
StatModType: enchantment.StatModType,
StatModKey: enchantment.StatModKey,
StatModValue: enchantment.StatModValue,
Bucket: enchantment.Bucket == 0
? ClassifyLiveEnchantmentBucket(enchantment.StatModType)
: (uint)enchantment.Bucket,
// Retail Enchantment::UnPack (0x005CB040) converts both relative
// wire timestamps to the monotonic client Timer domain at receipt.
StartTime: receivedAt + enchantment.StartTime,
SpellCategory: enchantment.SpellCategory,
PowerLevel: enchantment.PowerLevel,
DegradeModifier: enchantment.DegradeModifier,
DegradeLimit: enchantment.DegradeLimit,
LastTimeDegraded: receivedAt + enchantment.LastTimeDegraded,
SpellSetId: enchantment.SpellSetId);
/// <summary>
/// Live 0x02C2/0x02C4 records do not carry PlayerDescription's outer
/// EnchantmentMask bucket. Retail reconstructs the registry list from the
/// StatMod type flags; this is the same ordering used by ACE's
/// EnchantmentRegistry.BuildCategories.
/// </summary>
private static uint ClassifyLiveEnchantmentBucket(uint statModType)
{
const uint Multiplicative = 0x00004000u;
const uint Additive = 0x00008000u;
const uint Vitae = 0x00800000u;
const uint Cooldown = 0x01000000u;
if ((statModType & Vitae) != 0) return 4u;
if ((statModType & Cooldown) != 0) return 8u;
if ((statModType & Multiplicative) != 0) return 1u;
if ((statModType & Additive) != 0) return 2u;
return 0u;
}
}