Snapshot for release 2026.10.6.1 (internal 1cbe514)

This commit is contained in:
Tom Bohar 2026-10-06 08:47:11 -04:00
commit abf9146a5b
93 changed files with 10168 additions and 597 deletions

View file

@ -0,0 +1,932 @@
// ============================================================================
// RynthCore.Engine - Net/FlightCapture.cs
// What the flight recorder keeps from each datagram, and its stall detectors.
//
// Runs inside the sendto/recvfrom detours (Compatibility/RawPacketHooks.cs), after the
// real call, on the bytes the client sent or got. Per datagram: the header walk
// (AcPacketWire.LocateFragments), then for every fragment that starts a message, the
// opcode decides whether the message is kept. A kept message is its first
// FlightEntry.DataCap bytes, copied into the ring; decoding into text happens only when
// the ring is dumped (FlightFormat). No allocation, no lock on the datagram path
// (the engine-call table and the detectors take a small lock on the few messages
// they care about).
//
// Kept, client to server: every game action (0xF7B1) - AutonomousPosition at most one
// per AutoPosIntervalMs unless a sequence or the cell changed - and any other message.
// Kept, server to client: the game events in WantedEvent, the player's motion,
// position (rate-limited like AutonomousPosition), vector and effect messages,
// teleports, system text, and object messages (delete, pickup, state, motion) about
// the objects the character just used.
//
// Strictly read-only: nothing here changes, delays or drops traffic.
// Pure code (no engine state); compiled into tools/FlightRecorderTests.
// ============================================================================
using System;
using System.Buffers.Binary;
using System.Threading;
namespace RynthCore.Engine.Net;
/// <summary>Opcodes, game event types and game action types the recorder knows.</summary>
internal static class FlightOp
{
// Top-level messages.
public const uint GameEvent = 0xF7B0, GameAction = 0xF7B1;
public const uint UpdateMotion = 0xF74C, UpdatePosition = 0xF748, PlayerTeleport = 0xF751, VectorUpdate = 0xF74E;
public const uint PlayEffect = 0xF755, PlayScriptId = 0xF754, ObjectDelete = 0xF747, PickupEvent = 0xF74A, SetState = 0xF74B;
public const uint ParentEvent = 0xF749, ServerMessage = 0xF7E0, PlayerCreate = 0xF746, CharacterLogOff = 0xF653;
public const uint InventoryRemoveObject = 0x0024, PlayerKilled = 0x019E, SetStackSize = 0x0197;
// Game events (inside 0xF7B0).
public const uint EvPopupString = 0x0004, EvInventoryPutObjInContainer = 0x0022, EvWieldObject = 0x0023;
public const uint EvCloseGroundContainer = 0x0052, EvInventoryServerSaveFailed = 0x00A0, EvViewContents = 0x0196;
public const uint EvInventoryPutObjectIn3D = 0x019A, EvAttackDone = 0x01A7, EvMagicRemoveSpell = 0x01A8;
public const uint EvVictimNotification = 0x01AC, EvKillerNotification = 0x01AD, EvAttackerNotification = 0x01B1;
public const uint EvDefenderNotification = 0x01B2, EvEvasionAttacker = 0x01B3, EvEvasionDefender = 0x01B4;
public const uint EvCombatCommenceAttack = 0x01B8, EvUseDone = 0x01C7, EvConfirmationRequest = 0x0274;
public const uint EvWeenieError = 0x028A, EvWeenieErrorWithString = 0x028B;
public const uint EvMagicUpdateSpell = 0x02C1, EvMagicUpdateEnchantment = 0x02C2, EvMagicRemoveEnchantment = 0x02C3;
public const uint EvMagicUpdateMultipleEnchantments = 0x02C4, EvMagicRemoveMultipleEnchantments = 0x02C5;
public const uint EvMagicPurgeEnchantments = 0x02C6, EvMagicDispelEnchantment = 0x02C7;
public const uint EvMagicDispelMultipleEnchantments = 0x02C8, EvTransientString = 0x02EB, EvMagicPurgeBadEnchantments = 0x0312;
// Game actions (inside 0xF7B1).
public const uint AcTargetedMeleeAttack = 0x0008, AcTargetedMissileAttack = 0x000A, AcTalk = 0x0015;
public const uint AcPutItemInContainer = 0x0019, AcGetAndWieldItem = 0x001A, AcDropItem = 0x001B;
public const uint AcTalkDirect = 0x0032, AcUseWithTarget = 0x0035, AcUse = 0x0036;
public const uint AcRaiseVital = 0x0044, AcRaiseAttribute = 0x0045, AcRaiseSkill = 0x0046, AcTrainSkill = 0x0047;
public const uint AcCastUntargetedSpell = 0x0048, AcCastTargetedSpell = 0x004A, AcChangeCombatMode = 0x0053;
public const uint AcStackableMerge = 0x0054, AcStackableSplitToContainer = 0x0055, AcStackableSplitTo3D = 0x0056;
public const uint AcTell = 0x005D, AcLoginComplete = 0x00A1, AcIdentifyObject = 0x00C8, AcGiveObjectRequest = 0x00CD;
public const uint AcChatChannel = 0x0147, AcNoLongerViewingContents = 0x0195, AcStackableSplitToWield = 0x019B;
public const uint AcCancelAttack = 0x01B7, AcQueryHealth = 0x01BF;
public const uint AcJump = 0xF61B, AcMoveToState = 0xF61C, AcDoMovementCommand = 0xF61E, AcTurnTo = 0xF649;
public const uint AcStopMovementCommand = 0xF661, AcAutonomyLevel = 0xF752, AcAutonomousPosition = 0xF753;
public const uint AcJumpNonAutonomous = 0xF7C9;
// WeenieError codes the detectors look at.
public const uint ErrYoureTooBusy = 0x001D;
/// <summary>The server-to-client game events the recorder keeps.</summary>
public static bool WantedEvent(uint ev) => ev switch
{
EvPopupString or EvInventoryPutObjInContainer or EvWieldObject or EvCloseGroundContainer
or EvInventoryServerSaveFailed or EvViewContents or EvInventoryPutObjectIn3D or EvAttackDone
or EvMagicRemoveSpell or EvVictimNotification or EvKillerNotification or EvAttackerNotification
or EvDefenderNotification or EvEvasionAttacker or EvEvasionDefender or EvCombatCommenceAttack
or EvUseDone or EvConfirmationRequest or EvWeenieError or EvWeenieErrorWithString
or EvMagicUpdateSpell or EvMagicUpdateEnchantment or EvMagicRemoveEnchantment
or EvMagicUpdateMultipleEnchantments or EvMagicRemoveMultipleEnchantments or EvMagicPurgeEnchantments
or EvMagicDispelEnchantment or EvMagicDispelMultipleEnchantments or EvTransientString
or EvMagicPurgeBadEnchantments => true,
_ => false,
};
/// <summary>Actions whose first argument (and for some the second) names the object the character uses.</summary>
public static bool UsesObject(uint action) => action is AcUse or AcUseWithTarget or AcPutItemInContainer
or AcNoLongerViewingContents or AcGiveObjectRequest or AcDropItem or AcGetAndWieldItem or AcIdentifyObject;
}
/// <summary>The per-second marker's numbers (FlightMark.Summary), packed into the entry's Data.</summary>
internal struct FlightSummary
{
public const int Size = 40;
public const int Unknown = int.MinValue;
public int RealBusy; // AC's m_cBusy; Unknown when unreadable
public int ShadowBusy; // the engine's counter
public uint PendingType; // ClientActionGates pending item request type; 0xFFFFFFFF unknown
public uint PendingObject;
public byte Attacking; // 0/1, 255 unknown
public byte Gesture; // cast/action gesture animating: 0/1, 255 unknown
public ushort InPackets, InMessages, InKept, InRetransmits, InResendRequests;
public ushort OutPackets, OutMessages, OutKept, OutRetransmits, OutResendRequests;
public ushort SendErrors;
public readonly void Write(Span<byte> d)
{
BinaryPrimitives.WriteInt32LittleEndian(d, RealBusy);
BinaryPrimitives.WriteInt32LittleEndian(d[4..], ShadowBusy);
BinaryPrimitives.WriteUInt32LittleEndian(d[8..], PendingType);
BinaryPrimitives.WriteUInt32LittleEndian(d[12..], PendingObject);
d[16] = Attacking;
d[17] = Gesture;
W(d, 0, InPackets); W(d, 1, InMessages); W(d, 2, InKept); W(d, 3, InRetransmits); W(d, 4, InResendRequests);
W(d, 5, OutPackets); W(d, 6, OutMessages); W(d, 7, OutKept); W(d, 8, OutRetransmits); W(d, 9, OutResendRequests);
W(d, 10, SendErrors);
}
private static ushort R(ReadOnlySpan<byte> d, int i) => BinaryPrimitives.ReadUInt16LittleEndian(d[(18 + 2 * i)..]);
private static void W(Span<byte> d, int i, ushort v) => BinaryPrimitives.WriteUInt16LittleEndian(d[(18 + 2 * i)..], v);
public static FlightSummary Read(ReadOnlySpan<byte> d)
{
var s = new FlightSummary();
if (d.Length < Size) { s.RealBusy = s.ShadowBusy = Unknown; s.PendingType = 0xFFFFFFFF; s.Attacking = s.Gesture = 255; return s; }
s.RealBusy = BinaryPrimitives.ReadInt32LittleEndian(d);
s.ShadowBusy = BinaryPrimitives.ReadInt32LittleEndian(d[4..]);
s.PendingType = BinaryPrimitives.ReadUInt32LittleEndian(d[8..]);
s.PendingObject = BinaryPrimitives.ReadUInt32LittleEndian(d[12..]);
s.Attacking = d[16];
s.Gesture = d[17];
s.InPackets = R(d, 0); s.InMessages = R(d, 1); s.InKept = R(d, 2); s.InRetransmits = R(d, 3); s.InResendRequests = R(d, 4);
s.OutPackets = R(d, 5); s.OutMessages = R(d, 6); s.OutKept = R(d, 7); s.OutRetransmits = R(d, 8); s.OutResendRequests = R(d, 9);
s.SendErrors = R(d, 10);
return s;
}
}
internal sealed unsafe class FlightCapture
{
public const int AutoPosIntervalMs = 2000; // AutonomousPosition / the player's UpdatePosition
public const int EngineMatchMs = 1500; // an engine call explains an action sent this soon after
public const int EngineRepeatMs = 1000; // identical engine calls this close are folded into one line
public const int TargetMemoryMs = 20_000; // objects used this recently have their messages kept
public const int ResendMarkIntervalMs = 500; // resend-request markers per direction
public const int UseSettleMs = 1500; // UseDone(0) with nothing else this long after = refused
public const int UseRefusalStreak = 4; // refused uses in a row that trigger a dump
public const int UseUnansweredMs = 5000; // a use with no UseDone this long = unanswered
public const int UseUnansweredStreak = 3;
public const int TooBusyWindowMs = 20_000;
public const int TooBusyStreak = 3;
public readonly FlightRing Ring;
private readonly Func<long> _clock;
private readonly long _ticksPerSecond;
private volatile uint _playerId;
public uint PlayerId => _playerId;
// ── per direction (each touched by its own detour only) ────────────────
private sealed class Side
{
public readonly uint[] Seen = new uint[256]; // fragment sequences of recent messages
public int SeenNext;
public long PosStamp; // last kept position message
public uint PosCell;
public ushort PosA, PosB, PosC, PosD; // its four sequence numbers
public uint PosSuppressed;
public long ResendStamp;
public uint ResendSuppressed;
// counters since the last summary
public int Packets, Messages, Kept, Retransmits, ResendRequests, SendErrors;
}
private readonly Side _in = new(), _out = new();
// ── objects the character used (written by outbound, read by inbound) ──
private readonly uint[] _targets = new uint[8];
private readonly long[] _targetAt = new long[8];
private int _targetNext;
// ── engine calls waiting for their action ──────────────────────────────
private readonly object _engineLock = new();
private struct PendingCall { public string? Name; public uint A, B; public long Stamp; public bool Used; }
private readonly PendingCall[] _pending = new PendingCall[16];
private int _pendingNext;
private string? _repeatName;
private uint _repeatA, _repeatB, _repeatCount;
private long _repeatStamp;
// ── stall detectors ────────────────────────────────────────────────────
private readonly object _detectLock = new();
private struct UseTrack { public uint Target; public bool Counted; public long Sent; public bool Answered; public uint Err; public long AnsweredAt; public bool Responded; public bool Settled; }
private readonly UseTrack[] _uses = new UseTrack[8];
private int _useCount;
private int _refusedStreak, _unansweredStreak;
private readonly uint[] _refusedTargets = new uint[UseRefusalStreak];
private readonly long[] _tooBusy = new long[TooBusyStreak];
private int _tooBusyNext;
private string? _trigger;
public FlightCapture(int capacityPow2, Func<long> clock, long ticksPerSecond)
{
Ring = new FlightRing(capacityPow2);
_clock = clock;
_ticksPerSecond = ticksPerSecond;
}
public long Now() => _clock();
private long Ms(long ticks) => ticks * 1000 / _ticksPerSecond;
private long TicksFromMs(long ms) => ms * _ticksPerSecond / 1000;
/// <summary>Set the player id when it is known some other way (also learned from game event headers).</summary>
public void SetPlayerId(uint id) { if (id != 0) _playerId = id; }
// ── datagrams ──────────────────────────────────────────────────────────
/// <summary>One datagram the client sent (<paramref name="outbound"/>) or got.</summary>
public void OnDatagram(bool outbound, byte* data, int length, bool sendFailed = false)
{
if (data == null || length < AcPacketWire.HeaderSize)
return;
Side side = outbound ? _out : _in;
side.Packets++;
if (sendFailed) side.SendErrors++;
uint flags = AcPacketWire.ReadU32(data + 4);
bool retransmit = (flags & PacketFlags.Retransmission) != 0;
if (retransmit) side.Retransmits++;
long now = 0;
if ((flags & (PacketFlags.RequestRetransmit | PacketFlags.Disconnect)) != 0)
{
now = _clock();
NoteControl(outbound, side, flags, data, length, now);
}
if (AcPacketWire.LocateFragments(data, length, out int pos, out int end) != PacketWalk.Ok)
return;
int guard = 0;
while (pos + AcPacketWire.FragmentHeaderSize <= end && ++guard <= 64)
{
byte* frag = data + pos;
int size = AcPacketWire.ReadU16(frag + 10);
if (size < AcPacketWire.FragmentHeaderSize || pos + size > end)
break;
pos += size;
ushort index = AcPacketWire.ReadU16(frag + 12);
if (index != 0)
continue;
int msgLen = size - AcPacketWire.FragmentHeaderSize;
if (msgLen < 4)
continue;
uint seq = AcPacketWire.ReadU32(frag);
ushort count = AcPacketWire.ReadU16(frag + 8);
if (retransmit && Seen(side, seq))
continue; // the first copy was already handled
Remember(side, seq);
side.Messages++;
if (now == 0) now = _clock();
FlightFlags f = FlightFlags.None;
if (count > 1) f |= FlightFlags.MultiFragment;
if (retransmit) f |= FlightFlags.Retransmit;
if (sendFailed) f |= FlightFlags.SendFailed;
int fullLen = count > 1 ? count * msgLen : msgLen;
byte* msg = frag + AcPacketWire.FragmentHeaderSize;
if (outbound) Outbound(msg, msgLen, fullLen, seq, f, now);
else Inbound(msg, msgLen, fullLen, seq, f, now);
}
}
private static bool Seen(Side side, uint seq)
{
uint[] seen = side.Seen;
for (int i = 0; i < seen.Length; i++)
if (seen[i] == seq) return true;
return false;
}
private static void Remember(Side side, uint seq)
{
side.Seen[side.SeenNext] = seq;
side.SeenNext = (side.SeenNext + 1) & (side.Seen.Length - 1);
}
private void NoteControl(bool outbound, Side side, uint flags, byte* data, int length, long now)
{
uint bit = (flags & PacketFlags.Disconnect) != 0 ? PacketFlags.Disconnect : PacketFlags.RequestRetransmit;
uint count = 0, first = 0;
if (bit == PacketFlags.RequestRetransmit)
{
side.ResendRequests++;
// The resend list is the first optional header when ServerSwitch is absent (it is
// between ServerSwitch and the rest). Read it only when it is plainly there.
int p = AcPacketWire.HeaderSize + ((flags & PacketFlags.ServerSwitch) != 0 ? 8 : 0);
if (p + 8 <= length)
{
count = AcPacketWire.ReadU32(data + p);
first = count > 0 ? AcPacketWire.ReadU32(data + p + 4) : 0;
}
if (Ms(now - side.ResendStamp) < ResendMarkIntervalMs)
{
side.ResendSuppressed++;
return;
}
side.ResendStamp = now;
}
Span<byte> dirByte = stackalloc byte[4];
dirByte[0] = (byte)(outbound ? FlightDir.Out : FlightDir.In);
BinaryPrimitives.WriteUInt16LittleEndian(dirByte[2..], (ushort)Math.Min(side.ResendSuppressed, ushort.MaxValue));
Ring.WriteMarkBytes(now, FlightMark.NetControl, bit, count, first, dirByte);
side.ResendSuppressed = 0;
}
// ── client to server ───────────────────────────────────────────────────
private void Outbound(byte* msg, int len, int fullLen, uint seq, FlightFlags f, long now)
{
uint opcode = AcPacketWire.ReadU32(msg);
if (opcode != FlightOp.GameAction || len < 12)
{
Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0);
return;
}
uint action = AcPacketWire.ReadU32(msg + 8);
uint arg0 = len >= 16 ? AcPacketWire.ReadU32(msg + 12) : 0;
uint arg1 = len >= 20 ? AcPacketWire.ReadU32(msg + 16) : 0;
if (action == FlightOp.AcAutonomousPosition)
{
// Position(cell, xyz, wxyz) = 32 bytes after the action header, then 4 u16 sequences.
if (len >= 12 + 32 + 8)
{
uint cell = arg0;
byte* s = msg + 12 + 32;
if (!PositionChanged(_out, now, cell, AcPacketWire.ReadU16(s), AcPacketWire.ReadU16(s + 2), AcPacketWire.ReadU16(s + 4), AcPacketWire.ReadU16(s + 6)))
return;
}
Keep(_out, now, FlightDir.Out, f | FlightFlags.Client, msg, len, fullLen, seq, TakePosSuppressed(_out));
return;
}
if (FlightOp.UsesObject(action))
{
NoteTarget(arg0, now);
if (action is FlightOp.AcUseWithTarget or FlightOp.AcPutItemInContainer or FlightOp.AcGiveObjectRequest)
NoteTarget(arg1, now);
}
f |= MatchEngineCall(action, arg0, arg1, now) ? FlightFlags.Engine : FlightFlags.Client;
Keep(_out, now, FlightDir.Out, f, msg, len, fullLen, seq, 0);
if (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget)
DetectUseSent(action == FlightOp.AcUse ? arg0 : arg1, counted: action == FlightOp.AcUse, now);
}
// ── server to client ───────────────────────────────────────────────────
private void Inbound(byte* msg, int len, int fullLen, uint seq, FlightFlags f, long now)
{
uint opcode = AcPacketWire.ReadU32(msg);
uint obj = len >= 8 ? AcPacketWire.ReadU32(msg + 4) : 0;
switch (opcode)
{
case FlightOp.GameEvent:
{
if (len < 16) return;
if (obj != 0 && obj != _playerId) _playerId = obj; // game events are addressed to the player
uint ev = AcPacketWire.ReadU32(msg + 12);
if (!FlightOp.WantedEvent(ev)) return;
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
uint a = len >= 20 ? AcPacketWire.ReadU32(msg + 16) : 0;
if (ev == FlightOp.EvUseDone) DetectUseDone(a, now);
else if (ev == FlightOp.EvViewContents) DetectOpened(a, now);
else if ((ev == FlightOp.EvWeenieError || ev == FlightOp.EvWeenieErrorWithString) && a == FlightOp.ErrYoureTooBusy)
DetectTooBusy(now);
return;
}
case FlightOp.UpdateMotion:
if (obj == _playerId && obj != 0)
{
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
DetectPlayerMotion(msg, len, now);
}
else if (IsTarget(obj, now))
{
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
DetectResponse(obj, now);
}
return;
case FlightOp.UpdatePosition:
if (obj == 0 || obj != _playerId) return;
if (TryPositionPackSequences(msg + 8, len - 8, out uint cell, out ushort s1, out ushort s2, out ushort s3, out ushort s4)
&& !PositionChanged(_in, now, cell, s1, s2, s3, s4))
return;
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, TakePosSuppressed(_in));
return;
case FlightOp.VectorUpdate:
case FlightOp.PlayEffect:
case FlightOp.PlayScriptId:
case FlightOp.ParentEvent:
if (obj != 0 && (obj == _playerId || IsTarget(obj, now)))
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
return;
case FlightOp.ObjectDelete:
case FlightOp.PickupEvent:
case FlightOp.SetState:
case FlightOp.InventoryRemoveObject:
case FlightOp.SetStackSize:
if (obj != 0 && (obj == _playerId || IsTarget(obj, now)))
{
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
DetectResponse(obj, now);
}
return;
case FlightOp.PlayerCreate:
if (obj != 0) _playerId = obj;
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
return;
case FlightOp.PlayerTeleport:
case FlightOp.CharacterLogOff:
case FlightOp.PlayerKilled:
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
return;
case FlightOp.ServerMessage:
Keep(_in, now, FlightDir.In, f, msg, len, fullLen, seq, 0);
if (ContainsTooBusy(msg + 4, len - 4))
DetectTooBusy(now);
return;
}
}
private void Keep(Side side, long now, FlightDir dir, FlightFlags f, byte* msg, int len, int fullLen, uint seq, uint suppressed)
{
side.Kept++;
Ring.WriteMessage(now, dir, f, msg, len, fullLen, seq, suppressed);
}
// ── positions ──────────────────────────────────────────────────────────
/// <summary>True when this position message should be kept (and remembers it as the last kept).</summary>
private bool PositionChanged(Side side, long now, uint cell, ushort a, ushort b, ushort c, ushort d)
{
bool keep = side.PosStamp == 0 || cell != side.PosCell || a != side.PosA || c != side.PosC || d != side.PosD
|| Ms(now - side.PosStamp) >= AutoPosIntervalMs;
if (!keep)
{
side.PosSuppressed++;
return false;
}
side.PosStamp = now;
side.PosCell = cell;
side.PosA = a; side.PosB = b; side.PosC = c; side.PosD = d;
return true;
}
private static uint TakePosSuppressed(Side side)
{
uint n = side.PosSuppressed;
side.PosSuppressed = 0;
return n;
}
/// <summary>
/// PositionPack: flags, cell, xyz, the rotation parts the flags don't drop, velocity when
/// flagged, placement when flagged, then four u16 sequences (instance, position, teleport,
/// force position).
/// </summary>
public static bool TryPositionPackSequences(byte* p, int len, out uint cell, out ushort s1, out ushort s2, out ushort s3, out ushort s4)
{
cell = 0; s1 = s2 = s3 = s4 = 0;
if (len < 20) return false;
uint flags = AcPacketWire.ReadU32(p);
cell = AcPacketWire.ReadU32(p + 4);
int pos = 20;
for (uint bit = 0x08; bit <= 0x40; bit <<= 1)
if ((flags & bit) == 0) pos += 4;
if ((flags & 0x01) != 0) pos += 12;
if ((flags & 0x02) != 0) pos += 4;
if (pos + 8 > len) return false;
s1 = AcPacketWire.ReadU16(p + pos);
s2 = AcPacketWire.ReadU16(p + pos + 2);
s3 = AcPacketWire.ReadU16(p + pos + 4);
s4 = AcPacketWire.ReadU16(p + pos + 6);
return true;
}
// ── objects the character used ─────────────────────────────────────────
private void NoteTarget(uint id, long now)
{
if (id == 0 || id == _playerId) return;
for (int i = 0; i < _targets.Length; i++)
{
if (_targets[i] == id) { _targetAt[i] = now; return; }
}
int k = _targetNext;
_targets[k] = id;
_targetAt[k] = now;
_targetNext = (k + 1) & (_targets.Length - 1);
}
private bool IsTarget(uint id, long now)
{
if (id == 0) return false;
for (int i = 0; i < _targets.Length; i++)
if (_targets[i] == id) return Ms(now - _targetAt[i]) <= TargetMemoryMs;
return false;
}
// ── engine calls ───────────────────────────────────────────────────────
/// <summary>
/// The engine made a direct action call (AcActionTrace names). Writes a marker (identical
/// calls within EngineRepeatMs fold into one "repeated" line) and remembers the call so
/// the action it produces is tagged as the engine's.
/// </summary>
public void EngineCall(string name, uint a, uint b)
{
long now = _clock();
lock (_engineLock)
{
if (Expects(name))
{
ref PendingCall p = ref FindPending(name, a, b, now);
p.Name = name; p.A = a; p.B = b; p.Stamp = now; p.Used = false;
}
if (name == _repeatName)
{
if (a == _repeatA && b == _repeatB && Ms(now - _repeatStamp) < EngineRepeatMs)
{
_repeatCount++;
_repeatStamp = now;
return;
}
}
FlushRepeat();
_repeatName = name; _repeatA = a; _repeatB = b; _repeatStamp = now; _repeatCount = 0;
}
Ring.WriteMark(now, FlightMark.EngineCall, name, a, b, 0, default);
}
/// <summary>Writes the "repeated N more times" line for folded calls, if any (call under _engineLock).</summary>
private void FlushRepeat()
{
if (_repeatCount > 0 && _repeatName != null)
Ring.WriteMark(_repeatStamp, FlightMark.EngineCall, _repeatName, _repeatA, _repeatB, _repeatCount, default);
_repeatCount = 0;
}
/// <summary>Flush a pending "repeated" line (before a dump).</summary>
public void FlushEngineRepeats()
{
lock (_engineLock)
{
FlushRepeat();
_repeatName = null;
}
}
private ref PendingCall FindPending(string name, uint a, uint b, long now)
{
for (int i = 0; i < _pending.Length; i++)
{
ref PendingCall p = ref _pending[i];
if (p.Name == name && p.A == a && p.B == b) return ref p;
}
int k = _pendingNext;
_pendingNext = (k + 1) % _pending.Length;
return ref _pending[k];
}
private bool MatchEngineCall(uint action, uint arg0, uint arg1, long now)
{
lock (_engineLock)
{
int best = -1;
for (int i = 0; i < _pending.Length; i++)
{
ref PendingCall p = ref _pending[i];
if (p.Name == null || p.Used || now < p.Stamp || Ms(now - p.Stamp) > EngineMatchMs) continue;
if (!Produces(p.Name, p.A, p.B, action, arg0, arg1)) continue;
if (best < 0 || p.Stamp < _pending[best].Stamp) best = i; // oldest first
}
if (best < 0) return false;
_pending[best].Used = true;
return true;
}
}
/// <summary>Engine calls that send something to the server.</summary>
private static bool Expects(string name) => name switch
{
"SelectItem" or "SelectItem-dedup" or "OverlaySelect" => false,
_ => true,
};
/// <summary>Would engine call <paramref name="name"/>(a, b) send this action?</summary>
public static bool Produces(string name, uint a, uint b, uint action, uint arg0, uint arg1)
{
switch (name)
{
case "UseObject":
return (action == FlightOp.AcUse || action == FlightOp.AcUseWithTarget) && arg0 == a;
case "UseObjectOn":
case "UseEquippedItem":
return (action == FlightOp.AcUseWithTarget && arg0 == a && (b == 0 || arg1 == b))
|| (action == FlightOp.AcUse && arg0 == a);
case "CastSpell":
return (action == FlightOp.AcCastTargetedSpell && arg1 == b)
|| (action == FlightOp.AcCastUntargetedSpell && arg0 == b);
case "ChangeCombatMode":
return action == FlightOp.AcChangeCombatMode && arg0 == a;
case "MeleeAttack":
return action == FlightOp.AcTargetedMeleeAttack && arg0 == a;
case "MissileAttack":
return action == FlightOp.AcTargetedMissileAttack && arg0 == a;
case "NativeAttack":
return action is FlightOp.AcTargetedMeleeAttack or FlightOp.AcTargetedMissileAttack;
case "CloseContainer":
return action == FlightOp.AcNoLongerViewingContents && arg0 == a;
case "MoveItemExternal":
case "MoveItemInternal":
return (action is FlightOp.AcPutItemInContainer or FlightOp.AcDropItem or FlightOp.AcGetAndWieldItem
or FlightOp.AcStackableMerge or FlightOp.AcStackableSplitToContainer or FlightOp.AcStackableSplitTo3D
or FlightOp.AcStackableSplitToWield && arg0 == a)
|| (action == FlightOp.AcGiveObjectRequest && arg1 == a);
case "SplitStackInternal":
return action is FlightOp.AcStackableSplitToContainer or FlightOp.AcStackableSplitTo3D or FlightOp.AcStackableSplitToWield
&& arg0 == a;
case "MergeStackInternal":
return action == FlightOp.AcStackableMerge && arg0 == a;
case "GiveObjectTo":
return action == FlightOp.AcGiveObjectRequest && arg1 == a;
case "WieldItem":
return action == FlightOp.AcGetAndWieldItem && arg0 == a;
case "CancelAttack":
return action == FlightOp.AcCancelAttack;
case "Raise":
return action is FlightOp.AcRaiseVital or FlightOp.AcRaiseAttribute or FlightOp.AcRaiseSkill;
case "TrainSkill":
return action == FlightOp.AcTrainSkill;
case "DoMovement":
case "StopMovement":
case "SetMotion":
case "SetAutoRun":
case "StopCompletely":
case "TurnToHeading":
return action is FlightOp.AcMoveToState or FlightOp.AcDoMovementCommand or FlightOp.AcStopMovementCommand or FlightOp.AcTurnTo;
case "TapJump":
case "DoJump":
case "CommenceJump":
case "LaunchJumpWithMotion":
case "JumpNonAutonomous":
return action is FlightOp.AcJump or FlightOp.AcJumpNonAutonomous or FlightOp.AcMoveToState;
default:
return false;
}
}
// ── markers ────────────────────────────────────────────────────────────
public void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null)
=> Ring.WriteMark(_clock(), kind, null, a, b, c, text.AsSpan());
// ── summary ────────────────────────────────────────────────────────────
/// <summary>Fills the link counters since the last call and resets them.</summary>
public void TakeCounters(ref FlightSummary s)
{
static ushort C(ref int v) { int x = Interlocked.Exchange(ref v, 0); return (ushort)Math.Clamp(x, 0, ushort.MaxValue); }
s.InPackets = C(ref _in.Packets); s.InMessages = C(ref _in.Messages); s.InKept = C(ref _in.Kept);
s.InRetransmits = C(ref _in.Retransmits); s.InResendRequests = C(ref _in.ResendRequests);
s.OutPackets = C(ref _out.Packets); s.OutMessages = C(ref _out.Messages); s.OutKept = C(ref _out.Kept);
s.OutRetransmits = C(ref _out.Retransmits); s.OutResendRequests = C(ref _out.ResendRequests);
s.SendErrors = C(ref _out.SendErrors);
}
public void WriteSummary(in FlightSummary s)
{
Span<byte> d = stackalloc byte[FlightSummary.Size];
s.Write(d);
Ring.WriteMarkBytes(_clock(), FlightMark.Summary, 0, 0, 0, d);
}
// ── stall detectors ────────────────────────────────────────────────────
// use refusal: a Use answered by UseDone(0) with nothing about it afterwards (no
// ViewContents, no message about the object, no player motion with an action in it)
// for UseSettleMs; UseRefusalStreak of those in a row. A ViewContents resets it.
// use unanswered: UseUnansweredStreak uses in a row with no UseDone for UseUnansweredMs.
// too busy: TooBusyStreak "You're too busy" (WeenieError 0x1D or the system text)
// within TooBusyWindowMs.
/// <summary>A dump reason the detectors raised since the last call, or null.</summary>
public string? TakeTrigger()
{
lock (_detectLock)
{
string? t = _trigger;
_trigger = null;
return t;
}
}
public int RefusedStreak { get { lock (_detectLock) return _refusedStreak; } }
private void DetectUseSent(uint target, bool counted, long now)
{
lock (_detectLock)
{
SettleUses(now);
if (_useCount == _uses.Length)
{
Array.Copy(_uses, 1, _uses, 0, _uses.Length - 1);
_useCount--;
}
_uses[_useCount++] = new UseTrack { Target = target, Counted = counted, Sent = now };
}
}
private void DetectUseDone(uint err, long now)
{
lock (_detectLock)
{
for (int i = 0; i < _useCount; i++)
{
if (_uses[i].Answered) continue;
_uses[i].Answered = true;
_uses[i].Err = err;
_uses[i].AnsweredAt = now;
break;
}
}
}
private void DetectOpened(uint container, long now)
{
lock (_detectLock)
{
for (int i = 0; i < _useCount; i++)
if (_uses[i].Target == container) _uses[i].Responded = true;
_refusedStreak = 0;
_unansweredStreak = 0;
}
}
private void DetectResponse(uint obj, long now)
{
lock (_detectLock)
{
for (int i = 0; i < _useCount; i++)
if (_uses[i].Target == obj && now >= _uses[i].Sent) _uses[i].Responded = true;
}
}
/// <summary>The player's motion: one carrying actions (a command list: eat, drink, a cast...) or a
/// server move/turn to an object answers the uses still open.</summary>
private void DetectPlayerMotion(byte* msg, int len, long now)
{
// opcode, guid, u16 instance, u16 movement, u16 server control, u8 autonomous, pad to 16,
// then u8 movement type, u8 flags, u16 style, then the type's data.
if (len < 24) return;
byte type = msg[16];
uint target = 0;
bool action = false;
if (type == 0)
{
uint packed = AcPacketWire.ReadU32(msg + 20);
action = (packed >> 7) != 0; // number of commands
}
else if ((type == 6 || type == 8) && len >= 24)
{
target = AcPacketWire.ReadU32(msg + 20);
}
if (!action && target == 0) return;
lock (_detectLock)
{
for (int i = 0; i < _useCount; i++)
{
ref UseTrack u = ref _uses[i];
if (u.Settled || now < u.Sent) continue;
if (action || u.Target == target) u.Responded = true;
}
}
}
private void DetectTooBusy(long now)
{
lock (_detectLock)
{
_tooBusy[_tooBusyNext] = now;
_tooBusyNext = (_tooBusyNext + 1) % _tooBusy.Length;
long oldest = long.MaxValue;
foreach (long t in _tooBusy)
{
if (t == 0) return;
if (t < oldest) oldest = t;
}
if (Ms(now - oldest) <= TooBusyWindowMs)
{
_trigger ??= $"too-busy: {TooBusyStreak} \"You're too busy\" answers within {Ms(now - oldest) / 1000.0:0.0} s";
Array.Clear(_tooBusy);
}
}
}
/// <summary>Settle uses whose time is up (call regularly; also runs on every Use sent).</summary>
public void Tick()
{
long now = _clock();
lock (_detectLock) SettleUses(now);
}
private void SettleUses(long now)
{
int keep = 0;
for (int i = 0; i < _useCount; i++)
{
UseTrack u = _uses[i];
bool done = false;
if (u.Answered)
{
if (!u.Counted)
{
done = u.Responded || u.Err != 0 || Ms(now - u.AnsweredAt) >= UseSettleMs;
}
else if (u.Responded || u.Err != 0)
{
done = true;
if (u.Responded) _refusedStreak = 0;
_unansweredStreak = 0;
}
else if (Ms(now - u.AnsweredAt) >= UseSettleMs)
{
done = true;
_unansweredStreak = 0;
_refusedTargets[_refusedStreak % _refusedTargets.Length] = u.Target;
_refusedStreak++;
if (_refusedStreak >= UseRefusalStreak)
{
_trigger ??= $"use-refusal: {_refusedStreak} uses in a row answered UseDone(0) with nothing opened ({TargetList()})";
_refusedStreak = 0;
}
}
}
else if (Ms(now - u.Sent) >= UseUnansweredMs)
{
done = true;
if (!u.Counted) continue; // a use-with-target nobody answered: just drop it
_unansweredStreak++;
if (_unansweredStreak >= UseUnansweredStreak)
{
_trigger ??= $"use-unanswered: {_unansweredStreak} uses in a row got no UseDone within {UseUnansweredMs / 1000} s";
_unansweredStreak = 0;
}
}
if (!done)
_uses[keep++] = u;
}
for (int i = keep; i < _useCount; i++) _uses[i] = default;
_useCount = keep;
}
/// <summary>The refused objects, each once (trigger time only).</summary>
private string TargetList()
{
int n = Math.Min(_refusedStreak, _refusedTargets.Length);
var parts = new System.Collections.Generic.List<string>(n);
for (int i = 0; i < n; i++)
{
string id = $"0x{_refusedTargets[i]:X8}";
if (!parts.Contains(id)) parts.Add(id);
}
return string.Join(", ", parts);
}
/// <summary>"too busy" in a u16-length-prefixed Latin-1 string, without allocating.</summary>
private static bool ContainsTooBusy(byte* p, int len)
{
if (len < 2) return false;
int n = Math.Min(AcPacketWire.ReadU16(p), len - 2);
byte* s = p + 2;
ReadOnlySpan<byte> needle = "too busy"u8;
for (int i = 0; i + needle.Length <= n; i++)
{
int k = 0;
while (k < needle.Length)
{
byte c = s[i + k];
if (c >= (byte)'A' && c <= (byte)'Z') c = (byte)(c + 32);
if (c != needle[k]) break;
k++;
}
if (k == needle.Length) return true;
}
return false;
}
}
/// <summary>At most one automatic dump per cooldown; manual dumps don't go through this.</summary>
internal sealed class FlightDumpPolicy
{
private readonly long _cooldownMs;
private long _lastMs;
private bool _any;
private readonly object _lock = new();
public FlightDumpPolicy(long cooldownMs) { _cooldownMs = cooldownMs; }
public long CooldownMs => _cooldownMs;
public int Refused { get; private set; }
/// <summary>True (and the cooldown starts) when an automatic dump may be written now;
/// otherwise <paramref name="waitMs"/> is how long until one may.</summary>
public bool TryAccept(long nowMs, out long waitMs)
{
lock (_lock)
{
if (_any && nowMs - _lastMs < _cooldownMs)
{
waitMs = _cooldownMs - (nowMs - _lastMs);
Refused++;
return false;
}
_any = true;
_lastMs = nowMs;
waitMs = 0;
return true;
}
}
}

View file

@ -0,0 +1,805 @@
// ============================================================================
// RynthCore.Engine - Net/FlightFormat.cs
// Turns flight recorder entries into one text line each, and writes a dump.
//
// Runs only when a dump is written (never on the game's hot path). Message layouts are
// the AC wire format as the Aelrynth/ACE server writes it: little-endian, strings are a
// u16 length + Latin-1 bytes padded to 4, "align" pads to 4 from the start of the
// message. An entry holds only the first FlightEntry.DataCap bytes of a message, so
// every read is bounds-checked and a cut-off message ends with "...".
//
// Chat the player says or reads (talk, tells, channels) is never written: only its length.
//
// Pure code (no engine state); compiled into tools/FlightRecorderTests.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace RynthCore.Engine.Net;
/// <summary>Bounds-checked little-endian reader over a kept message.</summary>
internal ref struct FlightReader
{
private readonly ReadOnlySpan<byte> _b;
public int Pos;
public bool Ok;
public FlightReader(ReadOnlySpan<byte> b, int pos = 0) { _b = b; Pos = pos; Ok = true; }
public int Remaining => Math.Max(0, _b.Length - Pos);
private bool Need(int n)
{
if (Ok && Pos + n <= _b.Length) return true;
Ok = false;
Pos = _b.Length;
return false;
}
public byte U8() => Need(1) ? _b[Pos++] : (byte)0;
public ushort U16() { if (!Need(2)) return 0; ushort v = (ushort)(_b[Pos] | (_b[Pos + 1] << 8)); Pos += 2; return v; }
public uint U32() { if (!Need(4)) return 0; uint v = (uint)(_b[Pos] | (_b[Pos + 1] << 8) | (_b[Pos + 2] << 16) | (_b[Pos + 3] << 24)); Pos += 4; return v; }
public int I32() => unchecked((int)U32());
public float F32() => BitConverter.UInt32BitsToSingle(U32());
public double F64() { uint lo = U32(); uint hi = U32(); return BitConverter.UInt64BitsToDouble(((ulong)hi << 32) | lo); }
public void Skip(int n) { if (Need(n)) Pos += n; }
public void Align() { int pad = (4 - (Pos & 3)) & 3; if (pad > 0 && Pos + pad <= _b.Length) Pos += pad; else if (pad > 0) Pos = _b.Length; }
/// <summary>u16 length, Latin-1 bytes, padding to 4 from the string's start. Long text is cut to <paramref name="max"/>.</summary>
public string Str(int max = 96)
{
int start = Pos;
ushort n = U16();
if (!Ok) return "";
int have = Math.Min(n, Remaining);
int show = Math.Min(have, max);
var sb = new StringBuilder(show + 3);
for (int i = 0; i < show; i++)
{
byte c = _b[Pos + i];
sb.Append(c < 32 ? ' ' : (char)c);
}
if (show < n) sb.Append("...");
if (have < n) { Ok = false; Pos = _b.Length; return sb.ToString(); }
Pos += n;
int pad = (4 - ((Pos - start) & 3)) & 3;
if (Pos + pad <= _b.Length) Pos += pad; else Pos = _b.Length;
return sb.ToString();
}
}
internal static class FlightFormat
{
private static readonly CultureInfo Inv = CultureInfo.InvariantCulture;
// ── names ──────────────────────────────────────────────────────────────
public static string ActionName(uint a) => a switch
{
0x0005 => "SetSingleCharacterOption",
FlightOp.AcTargetedMeleeAttack => "MeleeAttack",
FlightOp.AcTargetedMissileAttack => "MissileAttack",
FlightOp.AcTalk => "Talk",
FlightOp.AcPutItemInContainer => "PutItemInContainer",
FlightOp.AcGetAndWieldItem => "GetAndWieldItem",
FlightOp.AcDropItem => "DropItem",
FlightOp.AcTalkDirect => "TalkDirect",
FlightOp.AcUseWithTarget => "UseWithTarget",
FlightOp.AcUse => "Use",
FlightOp.AcRaiseVital => "RaiseVital",
FlightOp.AcRaiseAttribute => "RaiseAttribute",
FlightOp.AcRaiseSkill => "RaiseSkill",
FlightOp.AcTrainSkill => "TrainSkill",
FlightOp.AcCastUntargetedSpell => "CastUntargetedSpell",
FlightOp.AcCastTargetedSpell => "CastTargetedSpell",
FlightOp.AcChangeCombatMode => "ChangeCombatMode",
FlightOp.AcStackableMerge => "StackableMerge",
FlightOp.AcStackableSplitToContainer => "StackableSplitToContainer",
FlightOp.AcStackableSplitTo3D => "StackableSplitTo3D",
FlightOp.AcTell => "Tell",
0x005F => "Buy",
0x0060 => "Sell",
0x0063 => "TeleToLifestone",
FlightOp.AcLoginComplete => "LoginComplete",
FlightOp.AcIdentifyObject => "IdentifyObject",
FlightOp.AcGiveObjectRequest => "GiveObjectRequest",
FlightOp.AcChatChannel => "ChatChannel",
FlightOp.AcNoLongerViewingContents => "NoLongerViewingContents",
FlightOp.AcStackableSplitToWield => "StackableSplitToWield",
0x01A1 => "SetCharacterOptions",
FlightOp.AcCancelAttack => "CancelAttack",
FlightOp.AcQueryHealth => "QueryHealth",
0x01DF => "Emote",
0x01E1 => "SoulEmote",
0x01E9 => "PingRequest",
0x01F6 => "OpenTradeNegotiations",
0x01F7 => "CloseTradeNegotiations",
0x01F8 => "AddToTrade",
0x01FA => "AcceptTrade",
0x01FB => "DeclineTrade",
0x0204 => "ResetTrade",
0x0263 => "QueryItemMana",
0x0275 => "ConfirmationResponse",
0x0279 => "Suicide",
FlightOp.AcJump => "Jump",
FlightOp.AcMoveToState => "MoveToState",
FlightOp.AcDoMovementCommand => "DoMovementCommand",
FlightOp.AcTurnTo => "TurnTo",
FlightOp.AcStopMovementCommand => "StopMovementCommand",
0xF6EA => "ForceObjectDescSend",
FlightOp.AcAutonomyLevel => "AutonomyLevel",
FlightOp.AcAutonomousPosition => "AutonomousPosition",
FlightOp.AcJumpNonAutonomous => "JumpNonAutonomous",
_ => $"action 0x{a:X4}",
};
public static string EventName(uint e) => e switch
{
FlightOp.EvPopupString => "PopupString",
FlightOp.EvInventoryPutObjInContainer => "InventoryPutObjInContainer",
FlightOp.EvWieldObject => "WieldObject",
FlightOp.EvCloseGroundContainer => "CloseGroundContainer",
FlightOp.EvInventoryServerSaveFailed => "InventoryServerSaveFailed",
FlightOp.EvViewContents => "ViewContents",
FlightOp.EvInventoryPutObjectIn3D => "InventoryPutObjectIn3D",
FlightOp.EvAttackDone => "AttackDone",
FlightOp.EvMagicRemoveSpell => "MagicRemoveSpell",
FlightOp.EvVictimNotification => "VictimNotification",
FlightOp.EvKillerNotification => "KillerNotification",
FlightOp.EvAttackerNotification => "AttackerNotification",
FlightOp.EvDefenderNotification => "DefenderNotification",
FlightOp.EvEvasionAttacker => "EvasionAttackerNotification",
FlightOp.EvEvasionDefender => "EvasionDefenderNotification",
FlightOp.EvCombatCommenceAttack => "CombatCommenceAttack",
FlightOp.EvUseDone => "UseDone",
FlightOp.EvConfirmationRequest => "ConfirmationRequest",
FlightOp.EvWeenieError => "WeenieError",
FlightOp.EvWeenieErrorWithString => "WeenieErrorWithString",
FlightOp.EvMagicUpdateSpell => "MagicUpdateSpell",
FlightOp.EvMagicUpdateEnchantment => "MagicUpdateEnchantment",
FlightOp.EvMagicRemoveEnchantment => "MagicRemoveEnchantment",
FlightOp.EvMagicUpdateMultipleEnchantments => "MagicUpdateMultipleEnchantments",
FlightOp.EvMagicRemoveMultipleEnchantments => "MagicRemoveMultipleEnchantments",
FlightOp.EvMagicPurgeEnchantments => "MagicPurgeEnchantments",
FlightOp.EvMagicDispelEnchantment => "MagicDispelEnchantment",
FlightOp.EvMagicDispelMultipleEnchantments => "MagicDispelMultipleEnchantments",
FlightOp.EvTransientString => "TransientString",
FlightOp.EvMagicPurgeBadEnchantments => "MagicPurgeBadEnchantments",
_ => $"event 0x{e:X4}",
};
public static string OpcodeName(uint op) => op switch
{
FlightOp.GameEvent => "GameEvent",
FlightOp.GameAction => "GameAction",
FlightOp.UpdateMotion => "UpdateMotion",
FlightOp.UpdatePosition => "UpdatePosition",
FlightOp.PlayerTeleport => "PlayerTeleport",
FlightOp.VectorUpdate => "VectorUpdate",
FlightOp.PlayEffect => "PlayEffect",
FlightOp.PlayScriptId => "PlayScriptId",
FlightOp.ObjectDelete => "ObjectDelete",
FlightOp.PickupEvent => "PickupEvent",
FlightOp.SetState => "SetState",
FlightOp.ParentEvent => "ParentEvent",
FlightOp.ServerMessage => "ServerMessage",
FlightOp.PlayerCreate => "PlayerCreate",
FlightOp.CharacterLogOff => "CharacterLogOff",
FlightOp.InventoryRemoveObject => "InventoryRemoveObject",
FlightOp.SetStackSize => "SetStackSize",
FlightOp.PlayerKilled => "PlayerKilled",
0xF7C8 => "CharacterEnterWorldRequest",
0xF657 => "CharacterEnterWorld",
0xF7DE => "TurbineChat",
0xF7E6 => "DDD_InterrogationResponse",
0xF7EA => "DDD_EndDDD",
_ => $"msg 0x{op:X4}",
};
/// <summary>The WeenieError codes worth naming here (others print as hex).</summary>
public static string ErrorName(uint e) => e switch
{
0x0000 => "none",
0x001D => "YoureTooBusy",
0x001B => "PhysicsCantTransition",
0x001C => "PhysicsMaxDistanceExceeded",
0x0020 => "IllegalInventoryTransaction",
0x0023 => "MotionFailure",
0x0024 => "YouCantJumpWhileInTheAir",
0x0027 => "CarryingItem",
0x0028 => "Frozen",
0x0029 => "Stuck",
0x002A => "YouAreTooEncumbered",
0x0036 => "ActionCancelled",
0x0037 => "ObjectGone",
0x0038 => "NoObject",
0x003D => "YouChargedTooFar",
0x0400 => "YouDontHaveAllTheComponents",
0x0401 => "YouDontHaveEnoughManaToCast",
0x0402 => "YourSpellFizzled",
0x0403 => "YourSpellTargetIsMissing",
0x0404 => "YourProjectileSpellMislaunched",
0x0406 => "MagicTargetOutOfRange",
0x0409 => "MagicGeneralFailure",
0x040A => "YouAreUnpreparedToCastASpell",
0x042A => "CurrentlyAttacking",
0x042B => "MissileAttackNotOk",
0x042C => "TargetNotAcquired",
0x043C => "YourHandsMustBeFree",
0x0498 => "YouHaveMovedTooFar",
_ => "",
};
private static string Err(uint e)
{
string n = ErrorName(e);
return n.Length > 0 ? $"0x{e:X4} {n}" : $"0x{e:X4}";
}
/// <summary>Motion commands and stances by their low 16 bits (the interpreted state sends only those).</summary>
public static string MotionName(uint cmd)
{
uint k = cmd & 0xFFFF;
string? n = k switch
{
0x0000 => "Invalid",
0x0001 => "HoldRun", 0x0002 => "HoldSidestep", 0x0003 => "Ready", 0x0004 => "Stop",
0x0005 => "WalkForward", 0x0006 => "WalkBackwards", 0x0007 => "RunForward", 0x0008 => "Fallen",
0x0009 => "Interpolating", 0x000D => "TurnRight", 0x000E => "TurnLeft", 0x000F => "SideStepRight",
0x0010 => "SideStepLeft", 0x0011 => "Dead", 0x0012 => "Crouch", 0x0013 => "Sitting", 0x0014 => "Sleeping",
0x0015 => "Falling", 0x0016 => "Reload", 0x0017 => "Unload", 0x0018 => "Pickup", 0x0019 => "StoreInBackpack",
0x001A => "Eat", 0x001B => "Drink", 0x001C => "Reading", 0x001D => "JumpCharging",
0x002B => "MagicBlast", 0x002C => "MagicSelfHead", 0x002D => "MagicSelfHeart", 0x002E => "MagicBonus",
0x002F => "MagicClap", 0x0030 => "MagicHarm", 0x0031 => "MagicHeal", 0x0032 => "MagicThrowMissile",
0x0033 => "MagicRecoilMissile", 0x0034 => "MagicPenalty", 0x0035 => "MagicTransfer", 0x0036 => "MagicVision",
0x0037 => "MagicEnchantItem", 0x0038 => "MagicPortal", 0x0039 => "MagicPray", 0x003A => "StopTurning",
0x003B => "Jump", 0x003C => "HandCombat", 0x003D => "NonCombat", 0x003E => "SwordCombat", 0x003F => "BowCombat",
0x0040 => "SwordShieldCombat", 0x0041 => "CrossbowCombat", 0x0043 => "SlingCombat",
0x0044 => "TwoHandedSwordCombat", 0x0045 => "TwoHandedStaffCombat", 0x0046 => "DualWieldCombat",
0x0047 => "ThrownWeaponCombat", 0x0049 => "Magic", 0x0050 => "FallDown", 0x0055 => "StaggerBackward",
0x0056 => "StaggerForward", 0x0057 => "Sanctuary",
0x0058 => "ThrustMed", 0x0059 => "ThrustLow", 0x005A => "ThrustHigh", 0x005B => "SlashHigh", 0x005C => "SlashMed",
0x005D => "SlashLow", 0x005E => "BackhandHigh", 0x005F => "BackhandMed", 0x0060 => "BackhandLow", 0x0061 => "Shoot",
0x0062 => "AttackHigh1", 0x0063 => "AttackMed1", 0x0064 => "AttackLow1", 0x0065 => "AttackHigh2",
0x0066 => "AttackMed2", 0x0067 => "AttackLow2", 0x0068 => "AttackHigh3", 0x0069 => "AttackMed3", 0x006A => "AttackLow3",
0x009C => "EnterGame", 0x009D => "ExitGame", 0x00A0 => "EnterPortal", 0x00A1 => "ExitPortal",
0x00D3 => "CastSpell", 0x00E0 => "UseMagicStaff", 0x00E8 => "BowNoAmmo", 0x00E9 => "CrossBowNoAmmo",
0x013B => "AtlatlCombat", 0x013C => "ThrownShieldCombat",
_ => null,
};
if (n == null && k >= 0x006F && k <= 0x0078) n = $"MagicPowerUp{k - 0x006E:00}";
return n ?? $"0x{cmd:X}";
}
private static string CombatMode(uint m) => m switch
{
1 => "NonCombat", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {m}",
};
private static string HoldKey(uint h) => h switch { 0 => "Invalid", 1 => "None", 2 => "Run", _ => $"hold{h}" };
private static string MovementType(byte t) => t switch
{
0 => "State", 1 => "RawCommand", 2 => "InterpretedCommand", 3 => "StopRawCommand", 4 => "StopInterpretedCommand",
5 => "StopCompletely", 6 => "MoveToObject", 7 => "MoveToPosition", 8 => "TurnToObject", 9 => "TurnToHeading",
_ => $"type{t}",
};
private static string F(float v) => float.IsFinite(v) ? v.ToString("0.##", Inv) : "nan";
private static string Id(uint id) => $"0x{id:X8}";
/// <summary>Yaw in degrees from the (w, x, y, z) rotation (rotation about the vertical axis).</summary>
private static string Yaw(float w, float z)
{
double deg = 2 * Math.Atan2(z, w) * 180 / Math.PI;
deg %= 360; if (deg < 0) deg += 360;
return deg.ToString("0", Inv);
}
// ── entries ────────────────────────────────────────────────────────────
/// <summary>The text after the direction arrow for one entry.</summary>
public static string Describe(in FlightRecord r)
{
try
{
FlightEntry e = r.Entry;
ReadOnlySpan<byte> data;
unsafe { data = new ReadOnlySpan<byte>(e.Data, e.Len).ToArray(); }
string s = e.Dir switch
{
FlightDir.Out => DescribeOut(data, e),
FlightDir.In => DescribeIn(data, e),
FlightDir.Mark => DescribeMark(data, e, r.Name),
_ => "?",
};
return s;
}
catch (Exception ex)
{
return $"(undecodable: {ex.GetType().Name})";
}
}
private static string Tail(in FlightReader rd, FlightEntry e)
{
var sb = new StringBuilder();
if (!rd.Ok) sb.Append(" ...");
if ((e.Flags & FlightFlags.MultiFragment) != 0) sb.Append(" [multi-fragment]");
if ((e.Flags & FlightFlags.Retransmit) != 0) sb.Append(" [retransmitted]");
if ((e.Flags & FlightFlags.SendFailed) != 0) sb.Append(" [SEND FAILED]");
if (e.Dir != FlightDir.Mark && e.B > 0) sb.Append($" (+{e.B} like it not kept)");
return sb.ToString();
}
public static string DescribeOut(ReadOnlySpan<byte> d, FlightEntry e)
{
var rd = new FlightReader(d);
uint op = rd.U32();
if (op != FlightOp.GameAction)
return $"{OpcodeName(op)} len={e.FullLen}" + Tail(rd, e);
uint seq = rd.U32();
uint action = rd.U32();
string tag = (e.Flags & FlightFlags.Engine) != 0 ? "[eng] " : (e.Flags & FlightFlags.Client) != 0 ? "[cli] " : "";
string body = action switch
{
FlightOp.AcUse => $"{Id(rd.U32())}",
FlightOp.AcUseWithTarget => $"{Id(rd.U32())} on {Id(rd.U32())}",
FlightOp.AcCastUntargetedSpell => $"spell {rd.U32()}",
FlightOp.AcCastTargetedSpell => Cast(ref rd),
FlightOp.AcChangeCombatMode => CombatMode(rd.U32()),
FlightOp.AcTargetedMeleeAttack => $"{Id(rd.U32())} height {rd.U32()} power {F(rd.F32())}",
FlightOp.AcTargetedMissileAttack => $"{Id(rd.U32())} height {rd.U32()} accuracy {F(rd.F32())}",
FlightOp.AcPutItemInContainer => $"{Id(rd.U32())} into {Id(rd.U32())} slot {rd.I32()}",
FlightOp.AcGetAndWieldItem => $"{Id(rd.U32())} mask 0x{rd.U32():X}",
FlightOp.AcDropItem => Id(rd.U32()),
FlightOp.AcGiveObjectRequest => Give(ref rd),
FlightOp.AcStackableMerge => $"{Id(rd.U32())} into {Id(rd.U32())} amount {rd.I32()}",
FlightOp.AcStackableSplitToContainer => $"{Id(rd.U32())} to {Id(rd.U32())} slot {rd.I32()} amount {rd.I32()}",
FlightOp.AcStackableSplitTo3D => $"{Id(rd.U32())} amount {rd.I32()}",
FlightOp.AcStackableSplitToWield => $"{Id(rd.U32())} mask 0x{rd.U32():X} amount {rd.I32()}",
FlightOp.AcNoLongerViewingContents => Id(rd.U32()),
FlightOp.AcIdentifyObject => Id(rd.U32()),
FlightOp.AcQueryHealth => Id(rd.U32()),
FlightOp.AcCancelAttack => "",
FlightOp.AcLoginComplete => "",
FlightOp.AcAutonomyLevel => $"level {rd.U32()}",
FlightOp.AcTalk or FlightOp.AcTell or FlightOp.AcTalkDirect or FlightOp.AcChatChannel or 0x01DF or 0x01E1
=> $"({e.FullLen} bytes, text not recorded)",
FlightOp.AcMoveToState => MoveToState(ref rd),
FlightOp.AcAutonomousPosition => AutonomousPosition(ref rd),
FlightOp.AcJump => Jump(ref rd),
FlightOp.AcJumpNonAutonomous => $"extent {F(rd.F32())}",
FlightOp.AcDoMovementCommand => $"{MotionName(rd.U32())} speed {F(rd.F32())} hold {HoldKey(rd.U32())}",
FlightOp.AcStopMovementCommand => $"{MotionName(rd.U32())} hold {HoldKey(rd.U32())}",
_ => RawArgs(ref rd),
};
if (action is FlightOp.AcTalk or FlightOp.AcTell or FlightOp.AcTalkDirect or FlightOp.AcChatChannel or 0x01DF or 0x01E1)
rd.Ok = true; // the text is skipped on purpose
return $"{tag}{ActionName(action)} {body}".TrimEnd() + $" #{seq}" + Tail(rd, e);
}
private static string Cast(ref FlightReader rd) { uint t = rd.U32(); uint s = rd.U32(); return $"spell {s} on {Id(t)}"; }
private static string Give(ref FlightReader rd) { uint t = rd.U32(); uint o = rd.U32(); int n = rd.I32(); return $"{Id(o)} x{n} to {Id(t)}"; }
private static string RawArgs(ref FlightReader rd)
{
var sb = new StringBuilder();
for (int i = 0; i < 4 && rd.Remaining >= 4; i++)
sb.Append(i == 0 ? "args " : " ").Append($"0x{rd.U32():X}");
return sb.ToString();
}
private static string Position(ref FlightReader rd, bool rotation)
{
uint cell = rd.U32();
float x = rd.F32(), y = rd.F32(), z = rd.F32();
string s = $"@{Id(cell)} ({F(x)},{F(y)},{F(z)})";
if (rotation)
{
float w = rd.F32(); rd.F32(); rd.F32(); float qz = rd.F32();
s += $" yaw {Yaw(w, qz)}";
}
return s;
}
private static string Seqs(ref FlightReader rd) => $"seq i{rd.U16()}/s{rd.U16()}/t{rd.U16()}/f{rd.U16()}";
private static string MoveToState(ref FlightReader rd)
{
uint packed = rd.U32();
uint flags = packed & 0x7FF;
uint ncmd = packed >> 11;
var sb = new StringBuilder();
if ((flags & 0x001) != 0) sb.Append($"hold={HoldKey(rd.U32())} ");
if ((flags & 0x002) != 0) sb.Append($"style={MotionName(rd.U32())} ");
string fwd = (flags & 0x004) != 0 ? MotionName(rd.U32()) : "";
string fwdHold = (flags & 0x008) != 0 ? HoldKey(rd.U32()) : "";
string fwdSpeed = (flags & 0x010) != 0 ? F(rd.F32()) : "";
if (fwd.Length > 0 || fwdHold.Length > 0 || fwdSpeed.Length > 0)
sb.Append($"fwd={(fwd.Length > 0 ? fwd : "-")}{(fwdHold.Length > 0 ? "(" + fwdHold + ")" : "")}{(fwdSpeed.Length > 0 ? "@" + fwdSpeed : "")} ");
string side = (flags & 0x020) != 0 ? MotionName(rd.U32()) : "";
string sideHold = (flags & 0x040) != 0 ? HoldKey(rd.U32()) : "";
string sideSpeed = (flags & 0x080) != 0 ? F(rd.F32()) : "";
if (side.Length > 0 || sideHold.Length > 0 || sideSpeed.Length > 0)
sb.Append($"side={(side.Length > 0 ? side : "-")}{(sideHold.Length > 0 ? "(" + sideHold + ")" : "")}{(sideSpeed.Length > 0 ? "@" + sideSpeed : "")} ");
string turn = (flags & 0x100) != 0 ? MotionName(rd.U32()) : "";
string turnHold = (flags & 0x200) != 0 ? HoldKey(rd.U32()) : "";
string turnSpeed = (flags & 0x400) != 0 ? F(rd.F32()) : "";
if (turn.Length > 0 || turnHold.Length > 0 || turnSpeed.Length > 0)
sb.Append($"turn={(turn.Length > 0 ? turn : "-")}{(turnHold.Length > 0 ? "(" + turnHold + ")" : "")}{(turnSpeed.Length > 0 ? "@" + turnSpeed : "")} ");
if (flags == 0) sb.Append("(no motion: stand still) ");
if (ncmd > 0)
{
sb.Append("cmds=[");
for (uint i = 0; i < ncmd && i < 8 && rd.Ok; i++)
{
ushort c = rd.U16(); ushort ps = rd.U16(); float sp = rd.F32();
sb.Append(i > 0 ? " " : "").Append($"{MotionName(c)}@{F(sp)}#{ps & 0x7FFF}{((ps & 0x8000) != 0 ? "a" : "")}");
}
if (ncmd > 8) { rd.Skip((int)(ncmd - 8) * 8); sb.Append(" ..."); }
sb.Append("] ");
}
sb.Append(Position(ref rd, rotation: true)).Append(' ');
sb.Append(Seqs(ref rd));
byte contact = rd.U8();
sb.Append($" contact={contact & 1}{((contact & 2) != 0 ? " longjump" : "")}");
return sb.ToString();
}
private static string AutonomousPosition(ref FlightReader rd)
{
string pos = Position(ref rd, rotation: true);
string seqs = Seqs(ref rd);
byte contact = rd.U8();
return $"{pos} {seqs} contact={contact & 1}";
}
private static string Jump(ref FlightReader rd)
{
float extent = rd.F32();
float vx = rd.F32(), vy = rd.F32(), vz = rd.F32();
return $"extent {F(extent)} velocity ({F(vx)},{F(vy)},{F(vz)}) {Seqs(ref rd)}";
}
public static string DescribeIn(ReadOnlySpan<byte> d, FlightEntry e)
{
var rd = new FlightReader(d);
uint op = rd.U32();
string s;
switch (op)
{
case FlightOp.GameEvent:
{
rd.U32(); // player guid
uint seq = rd.U32();
uint ev = rd.U32();
s = $"{EventName(ev)} {DescribeEvent(ev, ref rd, e)}".TrimEnd() + $" #{seq}";
break;
}
case FlightOp.UpdateMotion: s = "UpdateMotion " + UpdateMotion(ref rd); break;
case FlightOp.UpdatePosition: s = "UpdatePosition " + UpdatePosition(ref rd); break;
case FlightOp.PlayerTeleport: s = $"PlayerTeleport seq t{rd.U16()}"; break;
case FlightOp.VectorUpdate:
{
uint id = rd.U32();
float vx = rd.F32(), vy = rd.F32(), vz = rd.F32(), ox = rd.F32(), oy = rd.F32(), oz = rd.F32();
s = $"VectorUpdate {Id(id)} velocity ({F(vx)},{F(vy)},{F(vz)}) omega ({F(ox)},{F(oy)},{F(oz)})";
break;
}
case FlightOp.PlayEffect: { uint id = rd.U32(); uint sc = rd.U32(); float sp = rd.F32(); s = $"PlayEffect {Id(id)} script 0x{sc:X} speed {F(sp)}"; break; }
case FlightOp.PlayScriptId: { uint id = rd.U32(); uint sc = rd.U32(); s = $"PlayScriptId {Id(id)} script 0x{sc:X}"; break; }
case FlightOp.ObjectDelete: { uint id = rd.U32(); s = $"ObjectDelete {Id(id)} i{rd.U16()}"; break; }
case FlightOp.PickupEvent: { uint id = rd.U32(); s = $"PickupEvent {Id(id)} i{rd.U16()} p{rd.U16()}"; break; }
case FlightOp.SetState: { uint id = rd.U32(); uint st = rd.U32(); s = $"SetState {Id(id)} state 0x{st:X}"; break; }
case FlightOp.ParentEvent: { uint p = rd.U32(); uint c = rd.U32(); s = $"ParentEvent {Id(c)} onto {Id(p)} loc {rd.I32()}"; break; }
case FlightOp.InventoryRemoveObject: s = $"InventoryRemoveObject {Id(rd.U32())}"; break;
case FlightOp.SetStackSize: { rd.U8(); uint id = rd.U32(); uint n = rd.U32(); s = $"SetStackSize {Id(id)} size {n}"; break; }
case FlightOp.ServerMessage: { string t = rd.Str(); uint ct = rd.U32(); s = $"ServerMessage \"{t}\" (chat type {ct})"; break; }
case FlightOp.PlayerCreate: s = $"PlayerCreate {Id(rd.U32())}"; break;
case FlightOp.CharacterLogOff: s = "CharacterLogOff"; break;
case FlightOp.PlayerKilled: { string t = rd.Str(); uint v = rd.U32(); uint k = rd.U32(); s = $"PlayerKilled \"{t}\" victim {Id(v)} killer {Id(k)}"; break; }
default: s = $"{OpcodeName(op)} len={e.FullLen}"; break;
}
return s + Tail(rd, e);
}
private static string DescribeEvent(uint ev, ref FlightReader rd, FlightEntry e)
{
switch (ev)
{
case FlightOp.EvUseDone: return $"err {Err(rd.U32())}";
case FlightOp.EvWeenieError: return Err(rd.U32());
case FlightOp.EvWeenieErrorWithString: { uint c = rd.U32(); return $"{Err(c)} \"{rd.Str()}\""; }
case FlightOp.EvViewContents:
{
uint c = rd.U32();
uint n = rd.U32();
var sb = new StringBuilder($"{Id(c)} items {n}");
for (uint i = 0; i < n && i < 6 && rd.Remaining >= 8; i++)
{
uint id = rd.U32(); rd.U32();
sb.Append(i == 0 ? ": " : " ").Append(Id(id));
}
if (n > 6) sb.Append(" ...");
rd.Ok = true; // the item list is cut on purpose
return sb.ToString();
}
case FlightOp.EvCloseGroundContainer: return Id(rd.U32());
case FlightOp.EvInventoryServerSaveFailed: { uint i = rd.U32(); return $"{Id(i)} err {Err(rd.U32())}"; }
case FlightOp.EvInventoryPutObjInContainer: { uint i = rd.U32(); uint c = rd.U32(); int p = rd.I32(); uint t = rd.U32(); return $"{Id(i)} in {Id(c)} slot {p} type {t}"; }
case FlightOp.EvWieldObject: { uint i = rd.U32(); return $"{Id(i)} mask 0x{rd.U32():X}"; }
case FlightOp.EvInventoryPutObjectIn3D: return Id(rd.U32());
case FlightOp.EvAttackDone: return $"err {Err(rd.U32())}";
case FlightOp.EvCombatCommenceAttack: return "";
case FlightOp.EvAttackerNotification:
{
string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32(); uint crit = rd.U32();
return $"hit '{who}' for {dmg}{(crit != 0 ? " (crit)" : "")}, {pct * 100:0}% left";
}
case FlightOp.EvDefenderNotification:
{
string who = rd.Str(40); rd.U32(); double pct = rd.F64(); uint dmg = rd.U32();
return $"'{who}' hit you for {dmg}, {pct * 100:0}% left";
}
case FlightOp.EvEvasionAttacker: return $"'{rd.Str(40)}' evaded";
case FlightOp.EvEvasionDefender: return $"evaded '{rd.Str(40)}'";
case FlightOp.EvKillerNotification:
case FlightOp.EvVictimNotification:
case FlightOp.EvPopupString:
case FlightOp.EvTransientString:
return $"\"{rd.Str()}\"";
case FlightOp.EvConfirmationRequest: { uint t = rd.U32(); uint ctx = rd.U32(); return $"type {t} context {ctx} \"{rd.Str(60)}\""; }
case FlightOp.EvMagicUpdateEnchantment:
{
ushort spell = rd.U16(); ushort layer = rd.U16(); rd.U16(); rd.U16(); rd.U32(); rd.F64();
double dur = rd.F64(); uint caster = rd.U32();
return $"spell {spell} layer {layer} duration {dur.ToString("0", Inv)} s caster {Id(caster)}";
}
case FlightOp.EvMagicRemoveEnchantment:
case FlightOp.EvMagicDispelEnchantment:
case FlightOp.EvMagicUpdateSpell:
case FlightOp.EvMagicRemoveSpell:
{
ushort spell = rd.U16(); ushort layer = rd.U16();
return $"spell {spell} layer {layer}";
}
case FlightOp.EvMagicUpdateMultipleEnchantments:
{
uint n = rd.U32(); ushort first = rd.U16();
rd.Ok = true;
return $"{n} enchantments (first spell {first})";
}
case FlightOp.EvMagicRemoveMultipleEnchantments:
case FlightOp.EvMagicDispelMultipleEnchantments:
{
uint n = rd.U32();
var sb = new StringBuilder($"{n}:");
for (uint i = 0; i < n && i < 6 && rd.Remaining >= 4; i++) { ushort sp = rd.U16(); rd.U16(); sb.Append($" {sp}"); }
rd.Ok = true;
return sb.ToString();
}
case FlightOp.EvMagicPurgeEnchantments:
case FlightOp.EvMagicPurgeBadEnchantments:
return "";
default:
return RawArgs(ref rd);
}
}
private static string UpdateMotion(ref FlightReader rd)
{
uint id = rd.U32();
ushort inst = rd.U16(), mov = rd.U16(), srv = rd.U16();
byte auton = rd.U8();
rd.Align();
byte type = rd.U8();
byte mflags = rd.U8();
ushort style = rd.U16();
var sb = new StringBuilder();
sb.Append($"{Id(id)} {(auton != 0 ? "autonomous " : "server ")}{MovementType(type)} style={MotionName(style)}");
switch (type)
{
case 0:
{
uint packed = rd.U32();
uint fl = packed & 0x7F;
uint ncmd = packed >> 7;
string cur = (fl & 0x01) != 0 ? MotionName(rd.U16()) : "";
string fwd = (fl & 0x02) != 0 ? MotionName(rd.U16()) : "";
string side = (fl & 0x08) != 0 ? MotionName(rd.U16()) : "";
string turn = (fl & 0x20) != 0 ? MotionName(rd.U16()) : "";
string fs = (fl & 0x04) != 0 ? F(rd.F32()) : "";
string ss = (fl & 0x10) != 0 ? F(rd.F32()) : "";
string ts = (fl & 0x40) != 0 ? F(rd.F32()) : "";
if (cur.Length > 0 && cur != MotionName(style)) sb.Append($" state.style={cur}");
sb.Append($" fwd={(fwd.Length > 0 ? fwd : "Ready")}{(fs.Length > 0 ? "@" + fs : "")}");
if (side.Length > 0) sb.Append($" side={side}{(ss.Length > 0 ? "@" + ss : "")}");
if (turn.Length > 0) sb.Append($" turn={turn}{(ts.Length > 0 ? "@" + ts : "")}");
if (ncmd > 0)
{
sb.Append(" cmds=[");
for (uint i = 0; i < ncmd && i < 8 && rd.Ok; i++)
{
ushort c = rd.U16(); ushort ps = rd.U16(); float sp = rd.F32();
sb.Append(i > 0 ? " " : "").Append($"{MotionName(c)}@{F(sp)}#{ps & 0x7FFF}{((ps & 0x8000) != 0 ? "a" : "")}");
}
sb.Append(']');
}
rd.Align();
if ((mflags & 1) != 0) sb.Append($" stick to {Id(rd.U32())}");
break;
}
case 6:
case 7:
{
if (type == 6) sb.Append($" target {Id(rd.U32())}");
uint cell = rd.U32(); float x = rd.F32(), y = rd.F32(), z = rd.F32();
uint pf = rd.U32(); float dist = rd.F32(), min = rd.F32(), fail = rd.F32(), speed = rd.F32(), wr = rd.F32(), hd = rd.F32();
float run = rd.F32();
sb.Append($" origin @{Id(cell)} ({F(x)},{F(y)},{F(z)}) params 0x{pf:X} dist {F(dist)} min {F(min)} fail {F(fail)} speed {F(speed)} walkrun {F(wr)} heading {F(hd)} runrate {F(run)}");
break;
}
case 8:
{
uint target = rd.U32(); float want = rd.F32();
uint pf = rd.U32(); float speed = rd.F32(); float hd = rd.F32();
sb.Append($" target {Id(target)} heading {F(want)} params 0x{pf:X} speed {F(speed)} ({F(hd)})");
break;
}
case 9:
{
uint pf = rd.U32(); float speed = rd.F32(); float hd = rd.F32();
sb.Append($" heading {F(hd)} params 0x{pf:X} speed {F(speed)}");
break;
}
}
sb.Append($" seq i{inst}/m{mov}/c{srv}");
return sb.ToString();
}
private static string UpdatePosition(ref FlightReader rd)
{
uint id = rd.U32();
uint flags = rd.U32();
uint cell = rd.U32();
float x = rd.F32(), y = rd.F32(), z = rd.F32();
float w = (flags & 0x08) == 0 ? rd.F32() : 0;
if ((flags & 0x10) == 0) rd.F32();
if ((flags & 0x20) == 0) rd.F32();
float qz = (flags & 0x40) == 0 ? rd.F32() : 0;
string vel = "";
if ((flags & 0x01) != 0) { float vx = rd.F32(), vy = rd.F32(), vz = rd.F32(); vel = $" velocity ({F(vx)},{F(vy)},{F(vz)})"; }
if ((flags & 0x02) != 0) rd.U32();
string seqs = $"seq i{rd.U16()}/p{rd.U16()}/t{rd.U16()}/f{rd.U16()}";
return $"{Id(id)} @{Id(cell)} ({F(x)},{F(y)},{F(z)}) yaw {Yaw(w, qz)}{vel}{((flags & 0x04) != 0 ? " grounded" : "")} {seqs}";
}
public static string DescribeMark(ReadOnlySpan<byte> d, FlightEntry e, string? name)
{
string text = Latin1(d);
if ((e.Flags & FlightFlags.Truncated) != 0) text += "...";
switch ((FlightMark)e.Kind)
{
case FlightMark.Note: return $"note: {text}";
case FlightMark.EngineCall:
return e.C > 0
? $"engine {name}({Hex(e.A)}, {Hex(e.B)}) repeated {e.C} more time(s), last here"
: $"engine {name}({Hex(e.A)}, {Hex(e.B)})";
case FlightMark.BusyIncrement: return $"m_cBusy +1 -> real {Busy(e.A)} (engine count {(int)e.B})";
case FlightMark.BusyDecrement: return $"m_cBusy -1 -> real {Busy(e.A)} (engine count {(int)e.B})";
case FlightMark.BusyForceClear: return $"m_cBusy force-cleared (was real {Busy(e.A)}, engine count {(int)e.B}){(text.Length > 0 ? " - " + text : "")}";
case FlightMark.BusyForceClearAsk: return $"m_cBusy force-clear asked: {text}";
case FlightMark.BusyReconcile: return $"m_cBusy reconcile: {e.A} decrement(s) for the engine's own action, real now {Busy(e.B)}";
case FlightMark.BusyNegativeRepair: return $"m_cBusy was negative ({(int)e.A}) - reset to 0";
case FlightMark.BusyWatchdog: return $"busy watchdog ({text}): real {Busy(e.A)}, engine count {(int)e.B}, stuck {e.C} ms";
case FlightMark.GateCleared:
return e.A == 0
? $"action gate cleared: attacking flag ({text})"
: $"action gate cleared: pending item request type {e.A} on {Id(e.B)} ({text})";
case FlightMark.EngineInit: return $"engine generation {e.A} started{(e.A >= 2 ? " (hot reload: everything before this was in the previous generation's buffer)" : "")}";
case FlightMark.EngineShutdown: return $"engine shutting down{(text.Length > 0 ? " (" + text + ")" : "")}";
case FlightMark.PluginReload: return $"plugin reload: {text}";
case FlightMark.Trigger: return $"AUTO DUMP TRIGGER: {text}";
case FlightMark.Dump: return $"DUMP REQUESTED{(text.Length > 0 ? ": " + text : "")}";
case FlightMark.Summary: return Summary(d);
case FlightMark.NetControl:
{
string who = d.Length > 0 && d[0] == (byte)FlightDir.Out ? "client" : "server";
ushort more = d.Length >= 4 ? (ushort)(d[2] | (d[3] << 8)) : (ushort)0;
string extra = more > 0 ? $" (+{more} more not marked)" : "";
if (e.A == PacketFlags.Disconnect) return $"{who} sent DISCONNECT";
return $"{who} asks for {e.B} lost packet(s) again (first seq {e.C}){extra}";
}
default: return $"marker {e.Kind} {Hex(e.A)} {Hex(e.B)} {Hex(e.C)} {text}".TrimEnd();
}
}
private static string Summary(ReadOnlySpan<byte> d)
{
FlightSummary s = FlightSummary.Read(d);
string busy = s.RealBusy == FlightSummary.Unknown ? "?" : s.RealBusy.ToString(Inv);
string req = s.PendingType == 0xFFFFFFFF ? "?" : s.PendingType == 0 ? "none" : $"type {s.PendingType} on {Id(s.PendingObject)}";
string atk = s.Attacking == 255 ? "?" : s.Attacking.ToString(Inv);
string ges = s.Gesture == 255 ? "?" : s.Gesture.ToString(Inv);
string loss = "";
if (s.InRetransmits + s.OutRetransmits + s.InResendRequests + s.OutResendRequests + s.SendErrors > 0)
loss = $" | resent in {s.InRetransmits} out {s.OutRetransmits}, resend asks server {s.InResendRequests} client {s.OutResendRequests}" +
(s.SendErrors > 0 ? $", SEND ERRORS {s.SendErrors}" : "");
return $"-- 1s: in {s.InPackets} pk/{s.InMessages} msg ({s.InKept} kept), out {s.OutPackets} pk/{s.OutMessages} msg ({s.OutKept} kept){loss}" +
$" | m_cBusy {busy} (engine {s.ShadowBusy}) | item request {req} | attacking {atk} | gesture {ges}";
}
private static string Busy(uint v) => unchecked((int)v) == FlightSummary.Unknown ? "?" : unchecked((int)v).ToString(Inv);
private static string Hex(uint v) => v == 0 ? "0" : $"0x{v:X}";
private static string Latin1(ReadOnlySpan<byte> d)
{
var sb = new StringBuilder(d.Length);
foreach (byte b in d) sb.Append(b < 32 ? ' ' : (char)b);
return sb.ToString();
}
// ── dump ───────────────────────────────────────────────────────────────
public static string Arrow(FlightDir dir) => dir switch
{
FlightDir.Out => "->",
FlightDir.In => "<-",
_ => "**",
};
/// <summary>
/// Writes the dump: a header, a legend, then one line per entry with its time relative to
/// <paramref name="zeroStamp"/> (the moment the dump was asked for), the wall clock, the
/// arrow and the text.
/// </summary>
public static void WriteDump(TextWriter w, FlightRecord[] records, long zeroStamp, DateTime zeroLocal,
long ticksPerSecond, IEnumerable<string> header)
{
w.WriteLine("RynthCore flight recorder dump");
foreach (string h in header) w.WriteLine(h);
if (records.Length > 0)
{
double first = (records[0].Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond;
double last = (records[^1].Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond;
w.WriteLine($"Entries: {records.Length}, from {first / 1000.0:0.0} s to {last / 1000.0:+0.0;-0.0;0.0} s around the request.");
}
else
{
w.WriteLine("Entries: none.");
}
w.WriteLine();
foreach (string l in Legend) w.WriteLine(l);
w.WriteLine();
foreach (FlightRecord r in records)
w.WriteLine(Line(r, zeroStamp, zeroLocal, ticksPerSecond));
}
public static string Line(in FlightRecord r, long zeroStamp, DateTime zeroLocal, long ticksPerSecond)
{
double ms = (r.Entry.Stamp - zeroStamp) * 1000.0 / ticksPerSecond;
DateTime at = zeroLocal.AddMilliseconds(ms);
return $"{ms.ToString("+0;-0;0", Inv),9} ms {at.ToString("HH:mm:ss.fff", Inv)} {Arrow(r.Entry.Dir)} {Describe(r)}";
}
public static readonly string[] Legend =
{
"How to read: one line per message or marker, oldest first.",
" column 1: milliseconds relative to the dump request (negative = before it); column 2: local time.",
" -> client to server (what this client sent). [eng] = matches an engine direct-action call just before",
" (the 'engine ...' marker above it); [cli] = no engine call to match: the client's own path",
" (keyboard/mouse, or a plugin calling AC some other way). Movement matches are by time only.",
" <- server to client: game events (UseDone, ViewContents, errors, magic, combat), the player's own",
" motion/position/teleport, system text, and messages about objects the character just used.",
" ** engine markers: engine calls, m_cBusy changes and resets, action-gate clears, a per-second link",
" and client-state summary ('-- 1s'), hot reloads, notes and dump triggers.",
" '#n' is the action/event sequence; 'seq i/s/t/f' are the instance/server-control/teleport/force-position",
" sequences; '(+N like it not kept)' counts position updates skipped by the rate limit; '...' = cut off.",
" Chat text the player says or reads is not recorded.",
};
}

View file

@ -0,0 +1,383 @@
// ============================================================================
// RynthCore.Engine - Net/FlightRecorder.cs
// Always-on flight recorder: the last minutes of client<->server traffic that matters
// for "the character stopped doing things", plus the engine's own markers, dumped to
// a text file on request or when a stall is detected.
//
// Feeds (all cheap, none allocates on the hot path):
// - RawPacketHooks: every datagram sent (sendto detour, new) and received (the
// existing recvfrom detour) -> FlightCapture.OnDatagram;
// - AcActionTrace.Record (every engine direct-action call) -> EngineCall markers,
// used to tag the action that call sends as [eng];
// - BusyCountHooks / ClientActionGates: m_cBusy changes, force-clears (plugin asks
// included), reconciles, negative repairs, gate clears;
// - GameTickHooks (AC's main thread, every tick) -> MainTick: a one-line summary per
// second (link counters, m_cBusy, the item-action gates, the cast gesture), the
// stall detectors, and starting a scheduled automatic dump.
//
// Dumps: /rc flightdump [note] (any time), /rc flightdump auto <reason> and the plugin
// command (SendPluginCommand("RynthCore.FlightRecorder", "dump", reason)) for automatic
// ones - at most one per AutoDumpCooldownMs, written AutoDumpDelayMs after the trigger so
// the aftermath is in it too. Files: Logs\flight-<pid>-<yyyyMMdd-HHmmss>.txt, written on
// a short-lived engine thread.
//
// engine.json "FlightRecorder": false turns it off at the next client start (no sendto
// hook, nothing recorded); /rc flight off|on pauses it for the session.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Net;
internal static unsafe class FlightRecorder
{
public const int Capacity = 16384; // entries (152 bytes each, ~2.5 MB)
public const long AutoDumpCooldownMs = 10 * 60 * 1000;
public const int AutoDumpDelayMs = 3000;
public const int PruneDays = 14;
/// <summary>The plugin name plugins pass to SendPluginCommand to reach the recorder.</summary>
public const string PluginCommandTarget = "RynthCore.FlightRecorder";
private static FlightCapture? _cap;
private static volatile bool _paused;
private static volatile bool _autoOff;
private static readonly FlightDumpPolicy Policy = new(AutoDumpCooldownMs);
private static long _lastSummaryMs;
private static int _lastSendErrors;
private static readonly object ScheduleLock = new();
private static string? _scheduledReason;
private static long _scheduledAtMs, _scheduledZeroStamp;
private static DateTime _scheduledZeroLocal;
private static int _dumping;
private static string _lastDump = "";
private static int _dumpsWritten;
public static bool Enabled => _cap != null && !_paused;
// ── setup ──────────────────────────────────────────────────────────────
public static void Initialize()
{
if (_cap != null) return;
if (!EngineSettings.FlightRecorder)
{
RynthLog.Compat("FlightRecorder: off (engine.json \"FlightRecorder\": false).");
return;
}
_cap = new FlightCapture(Capacity, Stopwatch.GetTimestamp, Stopwatch.Frequency);
uint gen = (uint)Math.Max(1, EntryPoint.InitCount);
_cap.Mark(FlightMark.EngineInit, gen);
RynthLog.Compat($"FlightRecorder: on ({Capacity} entries, {_cap.Ring.Bytes / 1024} KB); /rc flightdump writes it.");
if (gen <= 1)
PruneOldDumps();
}
public static void Shutdown()
{
FlightCapture? c = _cap;
if (c == null) return;
c.FlushEngineRepeats();
c.Mark(FlightMark.EngineShutdown, text: EngineThreads.Stopping ? "hot reload or exit" : "");
}
// ── feeds ──────────────────────────────────────────────────────────────
/// <summary>RecvFrom detour, after the real call, with the bytes the client got.</summary>
public static void OnInbound(byte* data, int length)
{
FlightCapture? c = _cap;
if (c == null || _paused) return;
c.OnDatagram(false, data, length);
}
/// <summary>SendTo detour, before the real call, with the bytes the client sends.</summary>
public static void OnOutbound(byte* data, int length)
{
FlightCapture? c = _cap;
if (c == null || _paused) return;
c.OnDatagram(true, data, length);
}
/// <summary>An engine direct-action call (AcActionTrace.Record). <paramref name="name"/> is a literal.</summary>
public static void EngineCall(string name, uint a, uint b)
{
FlightCapture? c = _cap;
if (c == null || _paused) return;
try { c.EngineCall(name, a, b); } catch { }
}
public static void Mark(FlightMark kind, uint a = 0, uint b = 0, uint c = 0, string? text = null)
{
FlightCapture? cap = _cap;
if (cap == null || _paused) return;
try { cap.Mark(kind, a, b, c, text); } catch { }
}
/// <summary>AC's main thread, every game tick (GameTickHooks, post-tick).</summary>
public static void MainTick()
{
FlightCapture? c = _cap;
if (c == null) return;
long now = Environment.TickCount64;
if (!_paused && now - _lastSummaryMs >= 1000)
{
_lastSummaryMs = now;
WriteSummary(c);
c.Tick();
string? trigger = c.TakeTrigger();
if (trigger != null)
RequestAuto(trigger, "engine");
}
string? reason = null;
long zero = 0;
DateTime zeroLocal = default;
lock (ScheduleLock)
{
if (_scheduledReason != null && now >= _scheduledAtMs)
{
reason = _scheduledReason;
zero = _scheduledZeroStamp;
zeroLocal = _scheduledZeroLocal;
_scheduledReason = null;
}
}
if (reason != null)
StartDump("auto: " + reason, zero, zeroLocal, announce: true);
}
private static void WriteSummary(FlightCapture c)
{
var s = new FlightSummary
{
RealBusy = FlightSummary.Unknown,
PendingType = 0xFFFFFFFF,
Attacking = 255,
Gesture = 255,
};
try { if (BusyCountHooks.TryReadRealBusy(out int real)) s.RealBusy = real; } catch { }
s.ShadowBusy = BusyCountHooks.ShadowBusyCount;
try
{
if (ClientActionGates.TryReadPending(out uint type, out uint obj, out _)) { s.PendingType = type; s.PendingObject = obj; }
if (ClientActionGates.TryReadAttacking(out bool atk)) s.Attacking = atk ? (byte)1 : (byte)0;
}
catch { }
try { if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool g)) s.Gesture = g ? (byte)1 : (byte)0; } catch { }
c.TakeCounters(ref s);
int sendErrors = RawPacketHooks.SendErrors;
s.SendErrors = (ushort)Math.Clamp(sendErrors - _lastSendErrors, 0, ushort.MaxValue);
_lastSendErrors = sendErrors;
c.WriteSummary(s);
}
// ── dumps ──────────────────────────────────────────────────────────────
/// <summary>An automatic dump request (detector, plugin, /rc flightdump auto). Rate-limited.</summary>
public static string RequestAuto(string reason, string source)
{
FlightCapture? c = _cap;
if (c == null) return "Flight recorder is off.";
reason = Clean(reason, 100);
if (_autoOff)
{
c.Mark(FlightMark.Trigger, text: $"{source}: {reason} (automatic dumps are off: /rc flight auto on)");
return "Automatic flight dumps are off for this session.";
}
long now = Environment.TickCount64;
if (!Policy.TryAccept(now, out long waitMs))
{
c.Mark(FlightMark.Trigger, text: $"{source}: {reason} (no dump: one was written {(Policy.CooldownMs - waitMs) / 1000} s ago)");
return $"Not dumped: the last automatic dump was {(Policy.CooldownMs - waitMs) / 1000} s ago (one per {Policy.CooldownMs / 60000} min).";
}
c.Mark(FlightMark.Trigger, text: $"{source}: {reason}");
lock (ScheduleLock)
{
_scheduledReason = $"{source}: {reason}";
_scheduledAtMs = now + AutoDumpDelayMs;
_scheduledZeroStamp = Stopwatch.GetTimestamp();
_scheduledZeroLocal = DateTime.Now;
}
RynthLog.Compat($"FlightRecorder: automatic dump in {AutoDumpDelayMs / 1000} s ({source}: {reason}).");
return $"Automatic flight dump in {AutoDumpDelayMs / 1000} s.";
}
/// <summary>A manual dump now. Returns the file it is being written to.</summary>
public static string DumpNow(string note)
{
FlightCapture? c = _cap;
if (c == null) return "Flight recorder is off (engine.json \"FlightRecorder\": false).";
note = Clean(note, 100);
c.Mark(FlightMark.Dump, text: note);
string? path = StartDump(note.Length > 0 ? "manual: " + note : "manual", Stopwatch.GetTimestamp(), DateTime.Now, announce: false);
return path == null ? "A dump is already being written; try again in a moment." : $"Flight recorder dump: {path}";
}
private static string? StartDump(string why, long zeroStamp, DateTime zeroLocal, bool announce)
{
FlightCapture? c = _cap;
if (c == null) return null;
if (Interlocked.CompareExchange(ref _dumping, 1, 0) != 0)
return null;
string path;
try
{
LogPaths.EnsureLogDirectory();
string stem = $"flight-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}";
path = Path.Combine(LogPaths.LogDirectory, stem + ".txt");
for (int i = 2; File.Exists(path) && i < 100; i++)
path = Path.Combine(LogPaths.LogDirectory, $"{stem}-{i}.txt");
}
catch (Exception ex)
{
Volatile.Write(ref _dumping, 0);
RynthLog.Compat($"FlightRecorder: dump failed - {ex.Message}");
return null;
}
c.FlushEngineRepeats();
string file = path;
try
{
EngineThreads.Start("RynthCore.FlightDump", () => WriteDumpFile(c, file, why, zeroStamp, zeroLocal, announce));
}
catch (Exception ex)
{
Volatile.Write(ref _dumping, 0);
RynthLog.Compat($"FlightRecorder: dump thread failed - {ex.Message}");
return null;
}
return path;
}
private static void WriteDumpFile(FlightCapture c, string path, string why, long zeroStamp, DateTime zeroLocal, bool announce)
{
try
{
FlightRecord[] records = c.Ring.Snapshot();
var header = new List<string>
{
$"Reason: {why}",
$"Requested: {zeroLocal:yyyy-MM-dd HH:mm:ss.fff} (time 0 below)",
$"Client pid {Environment.ProcessId}, engine build {EntryPoint.BuildStamp}, generation {EntryPoint.InitCount}, player 0x{c.PlayerId:X8}",
$"Ring: {c.Ring.Capacity} entries, {c.Ring.Total} recorded since this engine generation started.",
};
using (var w = new StreamWriter(path, false, new System.Text.UTF8Encoding(false), 256 * 1024))
FlightFormat.WriteDump(w, records, zeroStamp, zeroLocal, Stopwatch.Frequency, header);
_lastDump = path;
Interlocked.Increment(ref _dumpsWritten);
RynthLog.Compat($"FlightRecorder: wrote {path} ({records.Length} entries; {why}).");
if (announce)
AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Flight recorder saved ({why}): {path}", 1);
}
catch (Exception ex)
{
RynthLog.Compat($"FlightRecorder: writing {path} failed - {ex.GetType().Name}: {ex.Message}");
}
finally
{
Volatile.Write(ref _dumping, 0);
}
}
private static void PruneOldDumps()
{
try
{
if (!Directory.Exists(LogPaths.LogDirectory)) return;
DateTime cutoff = DateTime.Now.AddDays(-PruneDays);
foreach (string f in Directory.GetFiles(LogPaths.LogDirectory, "flight-*.txt"))
{
try { if (File.GetLastWriteTime(f) < cutoff) File.Delete(f); } catch { }
}
}
catch { }
}
private static string Clean(string? s, int max)
{
if (string.IsNullOrWhiteSpace(s)) return "";
s = s.Trim().Replace('\r', ' ').Replace('\n', ' ');
return s.Length > max ? s.Substring(0, max) : s;
}
// ── commands ───────────────────────────────────────────────────────────
/// <summary>/rc flightdump [note] | /rc flightdump auto &lt;reason&gt;</summary>
public static string[] HandleDumpCommand(string args)
{
args = args.Trim();
if (args.StartsWith("auto", StringComparison.OrdinalIgnoreCase) && (args.Length == 4 || args[4] == ' '))
return new[] { RequestAuto(args.Length > 4 ? args.Substring(5) : "chat command", "command") };
return new[] { DumpNow(args) };
}
/// <summary>/rc flight [status|mark &lt;text&gt;|on|off|auto on|off]</summary>
public static string[] HandleCommand(string args)
{
string[] parts = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
string rest = parts.Length > 1 ? parts[1].Trim() : "";
switch (verb)
{
case "mark":
case "note":
if (_cap == null) return new[] { "Flight recorder is off." };
Mark(FlightMark.Note, text: Clean(rest, 100));
return new[] { "Marked." };
case "off":
_paused = true;
return new[] { "Flight recorder paused for this session (/rc flight on resumes)." };
case "on":
_paused = false;
return new[] { _cap == null ? "Flight recorder is off in engine.json (\"FlightRecorder\": false); restart the client after changing it." : "Flight recorder recording." };
case "auto":
if (rest.Equals("off", StringComparison.OrdinalIgnoreCase)) { _autoOff = true; return new[] { "Automatic flight dumps off for this session." }; }
if (rest.Equals("on", StringComparison.OrdinalIgnoreCase)) { _autoOff = false; return new[] { "Automatic flight dumps on." }; }
return new[] { "Usage: /rc flight auto on|off" };
default:
return StatusLines();
}
}
public static string[] StatusLines()
{
FlightCapture? c = _cap;
if (c == null)
return new[] { "Flight recorder: off (engine.json \"FlightRecorder\": false)." };
return new[]
{
$"Flight recorder: {(_paused ? "PAUSED" : "recording")}, {c.Ring.Total} entries recorded (ring {c.Ring.Capacity}, {c.Ring.Bytes / 1024} KB), " +
$"send hook {(RawPacketHooks.IsSendInstalled ? "installed" : "NOT installed")}, receive hook {(RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}, player 0x{c.PlayerId:X8}",
$"Automatic dumps {(_autoOff ? "OFF" : "on")} (one per {AutoDumpCooldownMs / 60000} min, {Policy.Refused} refused by the limit); " +
$"refused-use streak {c.RefusedStreak}; dumps written {_dumpsWritten}{(_lastDump.Length > 0 ? ", last " + _lastDump : "")}",
"/rc flightdump [note] writes it now; /rc flight mark <text> adds a note; /rc flight off|on|auto off|on.",
};
}
/// <summary>SendPluginCommand("RynthCore.FlightRecorder", action, value): "dump" (automatic,
/// rate-limited; value = reason) or "mark" (value = note). Any thread.</summary>
public static bool HandlePluginCommand(string? action, string? value)
{
if (_cap == null) return false;
switch ((action ?? "").Trim().ToLowerInvariant())
{
case "dump":
RequestAuto(value ?? "", "plugin");
return true;
case "mark":
case "note":
Mark(FlightMark.Note, text: Clean("plugin: " + value, 100));
return true;
default:
return false;
}
}
}

View file

@ -0,0 +1,258 @@
// ============================================================================
// RynthCore.Engine - Net/FlightRing.cs
// The flight recorder's ring: a fixed number of fixed-size entries, allocated once.
//
// Writers (the send/receive detours, the busy-count hooks, engine calls, any thread)
// claim a slot with one Interlocked.Increment and fill it in place: no allocation, no
// lock, never waits. A writer takes its slot by swapping the slot's Serial to minus its
// record number (compare-exchange), fills it, and publishes the record number; a reader
// copies a slot only when Serial is the number it expects before and after the copy, so a
// slot being rewritten is skipped (it was about to be overwritten anyway).
//
// An entry is a message (its first DataCap bytes, decoded only when dumped) or a
// marker (kind + three numbers, optional short text, optional string-literal name).
//
// Pure code (no engine state); compiled into tools/FlightRecorderTests.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Net;
internal enum FlightDir : byte
{
None = 0,
/// <summary>Server to client.</summary>
In = 1,
/// <summary>Client to server.</summary>
Out = 2,
/// <summary>Engine-side marker.</summary>
Mark = 3,
}
[Flags]
internal enum FlightFlags : byte
{
None = 0,
/// <summary>Outbound action matched an engine direct-action call made just before.</summary>
Engine = 0x01,
/// <summary>Only the first DataCap bytes were kept.</summary>
Truncated = 0x02,
/// <summary>The message spans several fragments; only the first was seen.</summary>
MultiFragment = 0x04,
/// <summary>A retransmitted copy of a message not seen before.</summary>
Retransmit = 0x08,
/// <summary>sendto returned an error for the datagram carrying this message.</summary>
SendFailed = 0x10,
/// <summary>Outbound action with no engine call to match: the client's own path.</summary>
Client = 0x20,
}
/// <summary>Marker kinds (FlightEntry.Kind when Dir == Mark).</summary>
internal enum FlightMark : ushort
{
Note = 1, // text: a manual or plugin note
EngineCall = 2, // Name = call, A/B = args, C = collapsed repeats before it
BusyIncrement = 3, // A = real m_cBusy after, B = shadow after
BusyDecrement = 4, // A = real m_cBusy after, B = shadow after
BusyForceClear = 5, // A = real before, B = shadow before; text = who
BusyForceClearAsk = 6, // text = who asked (plugin host API, off-thread latch)
BusyReconcile = 7, // A = decrements done, B = real after
BusyNegativeRepair = 8, // A = value found (as int)
BusyWatchdog = 9, // A = real, B = shadow, C = ms stuck; text = which watchdog
GateCleared = 10, // A = request type (0 = attacking flag), B = object; text = why
EngineInit = 11, // A = engine generation (init count)
EngineShutdown = 12,
Summary = 13, // Data = FlightSummary
Trigger = 14, // text = reason (auto dump requested)
NetControl = 15, // A = flag bit, B = count, C = first sequence; dir byte in Data[0]
Dump = 16, // text = note (manual dump requested)
PluginReload = 17, // text = plugin
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct FlightEntry
{
public const int DataCap = 120;
/// <summary>Stopwatch timestamp.</summary>
public long Stamp;
/// <summary>1-based record number once written; minus the number while being written; 0 never written.</summary>
public int Serial;
public FlightDir Dir;
public FlightFlags Flags;
/// <summary>Marker kind (FlightMark) for markers; 0 for messages.</summary>
public ushort Kind;
/// <summary>Bytes kept in Data.</summary>
public ushort Len;
/// <summary>Message length as seen (first fragment's payload, or count * size for multi-fragment), clamped.</summary>
public ushort FullLen;
/// <summary>Messages: fragment sequence. Markers: first number.</summary>
public uint A;
/// <summary>Messages: rate-limited copies dropped before this one. Markers: second number.</summary>
public uint B;
/// <summary>Messages: unused. Markers: third number.</summary>
public uint C;
public fixed byte Data[DataCap];
}
/// <summary>A copied, consistent entry plus the marker's name (string literal) if any.</summary>
internal struct FlightRecord
{
public FlightEntry Entry;
public string? Name;
}
internal sealed unsafe class FlightRing
{
private readonly FlightEntry[] _slots;
private readonly string?[] _names;
private readonly int _mask;
private int _next; // records claimed (Interlocked)
public FlightRing(int capacityPow2)
{
if (capacityPow2 < 16 || (capacityPow2 & (capacityPow2 - 1)) != 0)
throw new ArgumentOutOfRangeException(nameof(capacityPow2));
_slots = new FlightEntry[capacityPow2];
_names = new string?[capacityPow2];
_mask = capacityPow2 - 1;
}
public int Capacity => _slots.Length;
/// <summary>Records ever written (2^31 is years of play; dumps use the last Capacity).</summary>
public int Total => Volatile.Read(ref _next);
/// <summary>Approximate memory held by the ring, for status lines.</summary>
public int Bytes => _slots.Length * (sizeof(FlightEntry) + IntPtr.Size);
/// <summary>Records dropped because their slot was still being written by a writer a whole
/// lap behind (a thread stalled for Capacity records; practically never).</summary>
public long Dropped => Interlocked.Read(ref _dropped);
private long _dropped;
/// <summary>
/// Claims the next record number and takes its slot: the slot's Serial goes from its last
/// published value to -serial with one compare-exchange, so two writers never fill one slot
/// at once; a slot still owned by a stalled writer is skipped (counted in Dropped).
/// </summary>
private bool Own(out int i, out int serial)
{
serial = Interlocked.Increment(ref _next);
i = (serial - 1) & _mask;
int prev = Volatile.Read(ref _slots[i].Serial);
if (prev < 0 || Interlocked.CompareExchange(ref _slots[i].Serial, -serial, prev) != prev)
{
Interlocked.Increment(ref _dropped);
return false;
}
return true;
}
/// <summary>A message: its first DataCap bytes.</summary>
public void WriteMessage(long stamp, FlightDir dir, FlightFlags flags, byte* msg, int len, int fullLen, uint fragSeq, uint suppressed)
{
if (!Own(out int i, out int serial)) return;
ref FlightEntry e = ref _slots[i];
_names[i] = null;
int keep = len < 0 ? 0 : Math.Min(len, FlightEntry.DataCap);
e.Stamp = stamp;
e.Dir = dir;
e.Flags = keep < len ? flags | FlightFlags.Truncated : flags;
e.Kind = 0;
e.Len = (ushort)keep;
e.FullLen = (ushort)Math.Clamp(fullLen, 0, ushort.MaxValue);
e.A = fragSeq;
e.B = suppressed;
e.C = 0;
fixed (byte* d = e.Data)
{
if (keep > 0) Buffer.MemoryCopy(msg, d, FlightEntry.DataCap, keep);
}
Volatile.Write(ref e.Serial, serial);
}
/// <summary>A marker. <paramref name="name"/> must be a string literal (or otherwise long-lived);
/// <paramref name="text"/> is copied (Latin-1, truncated to DataCap).</summary>
public void WriteMark(long stamp, FlightMark kind, string? name, uint a, uint b, uint c, ReadOnlySpan<char> text)
{
if (!Own(out int i, out int serial)) return;
ref FlightEntry e = ref _slots[i];
_names[i] = name;
int keep = Math.Min(text.Length, FlightEntry.DataCap);
e.Stamp = stamp;
e.Dir = FlightDir.Mark;
e.Flags = keep < text.Length ? FlightFlags.Truncated : FlightFlags.None;
e.Kind = (ushort)kind;
e.Len = (ushort)keep;
e.FullLen = (ushort)Math.Min(text.Length, ushort.MaxValue);
e.A = a;
e.B = b;
e.C = c;
fixed (byte* d = e.Data)
{
for (int k = 0; k < keep; k++)
{
char ch = text[k];
d[k] = ch < 256 ? (byte)ch : (byte)'?';
}
}
Volatile.Write(ref e.Serial, serial);
}
/// <summary>A marker carrying raw bytes (the per-second summary).</summary>
public void WriteMarkBytes(long stamp, FlightMark kind, uint a, uint b, uint c, ReadOnlySpan<byte> bytes)
{
if (!Own(out int i, out int serial)) return;
ref FlightEntry e = ref _slots[i];
_names[i] = null;
int keep = Math.Min(bytes.Length, FlightEntry.DataCap);
e.Stamp = stamp;
e.Dir = FlightDir.Mark;
e.Flags = FlightFlags.None;
e.Kind = (ushort)kind;
e.Len = (ushort)keep;
e.FullLen = (ushort)keep;
e.A = a;
e.B = b;
e.C = c;
fixed (byte* d = e.Data)
{
for (int k = 0; k < keep; k++) d[k] = bytes[k];
}
Volatile.Write(ref e.Serial, serial);
}
/// <summary>
/// Copies every complete entry, oldest first. Entries being written while this runs are
/// skipped. Allocates (dump time only).
/// </summary>
public FlightRecord[] Snapshot()
{
int total = Volatile.Read(ref _next);
int count = Math.Min(total, _slots.Length);
var list = new FlightRecord[count];
int n = 0;
for (int s = total - count + 1; s <= total; s++)
{
int i = (s - 1) & _mask;
int before = Volatile.Read(ref _slots[i].Serial);
if (before != s)
continue;
FlightEntry copy = _slots[i];
string? name = _names[i];
Interlocked.MemoryBarrier();
if (Volatile.Read(ref _slots[i].Serial) != s)
continue;
list[n].Entry = copy;
list[n].Name = name;
n++;
}
if (n != list.Length)
Array.Resize(ref list, n);
return list;
}
}