RynthCore as of 2026-10-05 evening (internal 0a2043e): release 2026.10.5.20 - own dat reader, plugin manifests, UI/login hooks with Loot Editor drag-and-drop, server-message stream (API v78), raise attributes and skills (API v79), nameplate sizing and overlay opacity, engine reload held while a plugin is fighting, StatusAgent character sheet, world map and travel for DrakRemote
This commit is contained in:
parent
c3e15480e5
commit
913a2a00b6
110 changed files with 12560 additions and 1151 deletions
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/AcPacketWire.cs
|
||||
// Where the message fragments sit in one server-to-client UDP datagram.
|
||||
//
|
||||
// Written from the AC wire format as the engine already reads it (RawPacketParser's
|
||||
// 20-byte header + 16-byte fragment headers) and general knowledge of the protocol;
|
||||
// no generated definitions. Pure code: no engine state, compiled into the
|
||||
// NetMessageTests replay runner as is.
|
||||
//
|
||||
// Datagram:
|
||||
// header (20 bytes)
|
||||
// +0 u32 sequence
|
||||
// +4 u32 flags (PacketFlags below)
|
||||
// +8 u32 checksum (not checked: we only read)
|
||||
// +12 u16 recipient id
|
||||
// +14 u16 time
|
||||
// +16 u16 size bytes after the header (optional headers + fragments)
|
||||
// +18 u16 iteration
|
||||
// optional headers, one per flag bit set, in ascending bit order
|
||||
// fragments, back to back, when flags has BlobFragments
|
||||
//
|
||||
// Fragment (16-byte header, then its share of the message):
|
||||
// +0 u32 sequence the message's id: every fragment of one message shares it
|
||||
// +4 u32 id
|
||||
// +8 u16 count fragments in the message
|
||||
// +10 u16 size this fragment INCLUDING its 16-byte header
|
||||
// +12 u16 index 0..count-1
|
||||
// +14 u16 queue the client's dispatch queue (not the opcode)
|
||||
//
|
||||
// The walk is self-checking: the optional headers and the fragments must end exactly at
|
||||
// 20 + header.size. A datagram that doesn't is counted as malformed and skipped whole,
|
||||
// so a wrong guess about an optional header shows up as a counter, never as garbage.
|
||||
// ============================================================================
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
/// <summary>Packet header flag bits the reader needs.</summary>
|
||||
internal static class PacketFlags
|
||||
{
|
||||
public const uint Retransmission = 0x00000001;
|
||||
public const uint EncryptedChecksum = 0x00000002;
|
||||
public const uint BlobFragments = 0x00000004;
|
||||
public const uint ServerSwitch = 0x00000100; // 8 bytes
|
||||
public const uint LogonServerAddr = 0x00000200; // size unknown here: skip the datagram
|
||||
public const uint EmptyHeader1 = 0x00000400; // 0 bytes
|
||||
public const uint Referral = 0x00000800; // size unknown here: skip the datagram
|
||||
public const uint RequestRetransmit = 0x00001000; // u32 count + count * u32
|
||||
public const uint RejectRetransmit = 0x00002000; // u32 count + count * u32
|
||||
public const uint AckSequence = 0x00004000; // 4 bytes
|
||||
public const uint Disconnect = 0x00008000; // 0 bytes
|
||||
public const uint LoginRequest = 0x00010000; // client to server only: skip
|
||||
public const uint WorldLoginRequest = 0x00020000; // 8 bytes
|
||||
public const uint ConnectRequest = 0x00040000; // 32 bytes; starts a new session
|
||||
public const uint ConnectResponse = 0x00080000; // 8 bytes
|
||||
public const uint NetError = 0x00100000; // 8 bytes
|
||||
public const uint NetErrorDisconnect = 0x00200000; // 8 bytes
|
||||
public const uint CICMDCommand = 0x00400000; // 8 bytes
|
||||
public const uint TimeSync = 0x01000000; // 8 bytes
|
||||
public const uint EchoRequest = 0x02000000; // 4 bytes
|
||||
public const uint EchoResponse = 0x04000000; // 8 bytes
|
||||
public const uint Flow = 0x08000000; // 6 bytes
|
||||
|
||||
/// <summary>Flags whose optional header this reader can't size; a fragment datagram carrying one is skipped.</summary>
|
||||
public const uint Unsized = LogonServerAddr | Referral | LoginRequest | 0x00800000u | 0xF0000000u | 0x000000F8u;
|
||||
}
|
||||
|
||||
internal enum PacketWalk : byte
|
||||
{
|
||||
/// <summary>Fragments located.</summary>
|
||||
Ok,
|
||||
/// <summary>No BlobFragments flag: nothing to reassemble (acks, pings, time sync...).</summary>
|
||||
NoFragments,
|
||||
/// <summary>Shorter than a header, or the sizes don't add up.</summary>
|
||||
Malformed,
|
||||
/// <summary>Carries an optional header this reader can't size.</summary>
|
||||
UnknownOptional,
|
||||
}
|
||||
|
||||
internal static unsafe class AcPacketWire
|
||||
{
|
||||
public const int HeaderSize = 20;
|
||||
public const int FragmentHeaderSize = 16;
|
||||
|
||||
public static uint ReadU32(byte* p) => (uint)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
|
||||
public static ushort ReadU16(byte* p) => (ushort)(p[0] | (p[1] << 8));
|
||||
|
||||
/// <summary>The datagram's flags, or 0 when it is shorter than a header.</summary>
|
||||
public static uint Flags(byte* data, int length) => length >= HeaderSize ? ReadU32(data + 4) : 0;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the fragment area of one datagram: [fragStart, fragEnd). Never reads past
|
||||
/// <paramref name="length"/>. Ok only when the optional headers sized and fragEnd is
|
||||
/// exactly where the header's size says the datagram ends.
|
||||
/// </summary>
|
||||
public static PacketWalk LocateFragments(byte* data, int length, out int fragStart, out int fragEnd)
|
||||
{
|
||||
fragStart = fragEnd = 0;
|
||||
if (data == null || length < HeaderSize)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
uint flags = ReadU32(data + 4);
|
||||
if ((flags & PacketFlags.BlobFragments) == 0)
|
||||
return PacketWalk.NoFragments;
|
||||
if ((flags & PacketFlags.Unsized) != 0)
|
||||
return PacketWalk.UnknownOptional;
|
||||
|
||||
int end = HeaderSize + ReadU16(data + 16);
|
||||
if (end > length)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
int pos = HeaderSize;
|
||||
if ((flags & PacketFlags.ServerSwitch) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.RequestRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
|
||||
if ((flags & PacketFlags.RejectRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
|
||||
if ((flags & PacketFlags.AckSequence) != 0) pos += 4;
|
||||
if ((flags & PacketFlags.WorldLoginRequest) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.ConnectRequest) != 0) pos += 32;
|
||||
if ((flags & PacketFlags.ConnectResponse) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.NetError) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.NetErrorDisconnect) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.CICMDCommand) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.TimeSync) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.EchoRequest) != 0) pos += 4;
|
||||
if ((flags & PacketFlags.EchoResponse) != 0) pos += 8;
|
||||
if ((flags & PacketFlags.Flow) != 0) pos += 6;
|
||||
if (pos > end)
|
||||
return PacketWalk.Malformed;
|
||||
|
||||
// The fragments must tile [pos, end) exactly.
|
||||
int walk = pos;
|
||||
int guard = 0;
|
||||
while (walk < end)
|
||||
{
|
||||
if (walk + FragmentHeaderSize > end || ++guard > 64)
|
||||
return PacketWalk.Malformed;
|
||||
int size = ReadU16(data + walk + 10);
|
||||
if (size < FragmentHeaderSize || walk + size > end)
|
||||
return PacketWalk.Malformed;
|
||||
walk += size;
|
||||
}
|
||||
if (walk == pos)
|
||||
return PacketWalk.Malformed; // the flag promised fragments
|
||||
|
||||
fragStart = pos;
|
||||
fragEnd = end;
|
||||
return PacketWalk.Ok;
|
||||
}
|
||||
|
||||
private static bool SkipU32List(byte* data, int end, ref int pos)
|
||||
{
|
||||
if (pos + 4 > end) return false;
|
||||
uint n = ReadU32(data + pos);
|
||||
if (n > 256) return false;
|
||||
pos += 4 + (int)n * 4;
|
||||
return pos <= end;
|
||||
}
|
||||
}
|
||||
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
|
|
@ -0,0 +1,307 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/FragmentReassembler.cs
|
||||
// Turns server-to-client datagrams into whole messages (u32 opcode + body).
|
||||
//
|
||||
// Runs on the consumer side of PacketRing (the plugin pump), never in the RecvFrom
|
||||
// detour. Read-only: it sees copies of the client's datagrams.
|
||||
//
|
||||
// Bounded:
|
||||
// - at most MaxPartials messages in progress; the least recently touched one is
|
||||
// dropped when another starts, and any untouched for StaleMs is dropped (either
|
||||
// way its sequence counts as done, so its late fragments are ignored);
|
||||
// - at most MaxFragments fragments (MaxFragments * FragmentStride bytes) per message;
|
||||
// a bigger one is dropped and its sequence remembered as done;
|
||||
// - a window of the last DoneWindow completed sequences rejects retransmitted copies.
|
||||
// Slot buffers are pinned arrays reused from one message to the next, so a steady
|
||||
// stream allocates nothing; a one-fragment message is handed over straight from the
|
||||
// datagram without a copy.
|
||||
//
|
||||
// Messages are delivered in the order they complete (a long message completes after
|
||||
// shorter ones that started later). The client applies them in its own order.
|
||||
//
|
||||
// Pure code; compiled into the NetMessageTests replay runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
/// <summary>Receives each completed message. <paramref name="message"/> starts with the u32 opcode and is valid only during the call.</summary>
|
||||
internal unsafe interface IServerMessageSink
|
||||
{
|
||||
void OnServerMessage(uint fragmentSequence, byte* message, int length);
|
||||
}
|
||||
|
||||
internal sealed unsafe class FragmentReassembler
|
||||
{
|
||||
public const int FragmentStride = 512; // > the largest fragment body a 484-byte datagram can carry
|
||||
public const int MaxFragments = 256; // 256 * 448 = ~112 KB of message
|
||||
public const int MaxPartials = 16;
|
||||
public const int DoneWindow = 4096; // power of two
|
||||
public const long StaleMs = 30_000;
|
||||
|
||||
private sealed class Slot
|
||||
{
|
||||
public bool InUse;
|
||||
public uint Sequence;
|
||||
public int Count;
|
||||
public int Received;
|
||||
public int Bytes;
|
||||
public long TouchedMs;
|
||||
public byte[]? Buffer; // pinned; Count * FragmentStride
|
||||
public readonly ushort[] Lengths = new ushort[MaxFragments];
|
||||
public readonly ulong[] Have = new ulong[MaxFragments / 64];
|
||||
}
|
||||
|
||||
private readonly Slot[] _slots = new Slot[MaxPartials];
|
||||
private readonly ulong[] _done = new ulong[DoneWindow / 64];
|
||||
private uint _maxDone;
|
||||
private bool _anyDone;
|
||||
|
||||
// ── counters (read by /rc netmsg; written on the consumer thread only) ──
|
||||
public long Packets, PacketsNoFragments, PacketsMalformed, PacketsUnknownOptional;
|
||||
public long Fragments, Messages, MultiFragmentMessages, DuplicateFragments, DuplicateMessages;
|
||||
public long BadFragments, Oversized, EvictedStale, EvictedFull, SessionResets;
|
||||
public uint LastUnknownFlags;
|
||||
|
||||
public FragmentReassembler()
|
||||
{
|
||||
for (int i = 0; i < _slots.Length; i++)
|
||||
_slots[i] = new Slot();
|
||||
}
|
||||
|
||||
public int PartialCount
|
||||
{
|
||||
get
|
||||
{
|
||||
int n = 0;
|
||||
foreach (Slot s in _slots) if (s.InUse) n++;
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget everything in progress and the done window (a new session, or the stream switched on).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
s.InUse = false;
|
||||
Array.Clear(_done);
|
||||
_maxDone = 0;
|
||||
_anyDone = false;
|
||||
}
|
||||
|
||||
/// <summary>One received datagram. <paramref name="nowMs"/> is any monotonic millisecond clock.</summary>
|
||||
public void ProcessDatagram(byte* data, int length, long nowMs, IServerMessageSink sink)
|
||||
{
|
||||
Packets++;
|
||||
uint flags = AcPacketWire.Flags(data, length);
|
||||
if ((flags & PacketFlags.ConnectRequest) != 0)
|
||||
{
|
||||
// The server's half of a new connection: fragment sequences start over.
|
||||
Reset();
|
||||
SessionResets++;
|
||||
}
|
||||
|
||||
PacketWalk walk = AcPacketWire.LocateFragments(data, length, out int pos, out int end);
|
||||
switch (walk)
|
||||
{
|
||||
case PacketWalk.NoFragments: PacketsNoFragments++; return;
|
||||
case PacketWalk.Malformed: PacketsMalformed++; return;
|
||||
case PacketWalk.UnknownOptional: PacketsUnknownOptional++; LastUnknownFlags = flags; return;
|
||||
}
|
||||
|
||||
while (pos < end)
|
||||
{
|
||||
byte* f = data + pos;
|
||||
int size = AcPacketWire.ReadU16(f + 10);
|
||||
Fragments++;
|
||||
Fragment(AcPacketWire.ReadU32(f), AcPacketWire.ReadU16(f + 8), AcPacketWire.ReadU16(f + 12),
|
||||
f + AcPacketWire.FragmentHeaderSize, size - AcPacketWire.FragmentHeaderSize, nowMs, sink);
|
||||
pos += size;
|
||||
}
|
||||
|
||||
EvictStale(nowMs);
|
||||
}
|
||||
|
||||
private void Fragment(uint seq, int count, int index, byte* body, int bodyLen, long nowMs, IServerMessageSink sink)
|
||||
{
|
||||
if (count == 0 || index >= count)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
if (IsDone(seq))
|
||||
{
|
||||
DuplicateFragments++;
|
||||
if (count == 1) DuplicateMessages++;
|
||||
return;
|
||||
}
|
||||
|
||||
if (count == 1)
|
||||
{
|
||||
if (bodyLen < 4)
|
||||
{
|
||||
BadFragments++;
|
||||
MarkDone(seq);
|
||||
return;
|
||||
}
|
||||
MarkDone(seq);
|
||||
Messages++;
|
||||
sink.OnServerMessage(seq, body, bodyLen);
|
||||
return;
|
||||
}
|
||||
|
||||
if (count > MaxFragments || bodyLen > FragmentStride)
|
||||
{
|
||||
Oversized++;
|
||||
DropSequence(seq);
|
||||
return;
|
||||
}
|
||||
|
||||
Slot? slot = FindSlot(seq) ?? StartSlot(seq, count, nowMs);
|
||||
if (slot.Count != count)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
int word = index >> 6;
|
||||
ulong bit = 1UL << (index & 63);
|
||||
if ((slot.Have[word] & bit) != 0)
|
||||
{
|
||||
DuplicateFragments++;
|
||||
return;
|
||||
}
|
||||
|
||||
slot.Have[word] |= bit;
|
||||
slot.Lengths[index] = (ushort)bodyLen;
|
||||
slot.Received++;
|
||||
slot.Bytes += bodyLen;
|
||||
slot.TouchedMs = nowMs;
|
||||
fixed (byte* dst = slot.Buffer)
|
||||
Buffer.MemoryCopy(body, dst + index * FragmentStride, bodyLen, bodyLen);
|
||||
|
||||
if (slot.Received < slot.Count)
|
||||
return;
|
||||
|
||||
// Complete: pack the fragments together in place (fragment i moves down, never up).
|
||||
fixed (byte* buf = slot.Buffer)
|
||||
{
|
||||
int at = 0;
|
||||
for (int i = 0; i < slot.Count; i++)
|
||||
{
|
||||
int len = slot.Lengths[i];
|
||||
if (at != i * FragmentStride)
|
||||
Buffer.MemoryCopy(buf + i * FragmentStride, buf + at, len, len);
|
||||
at += len;
|
||||
}
|
||||
slot.InUse = false;
|
||||
MarkDone(seq);
|
||||
if (at < 4)
|
||||
{
|
||||
BadFragments++;
|
||||
return;
|
||||
}
|
||||
Messages++;
|
||||
MultiFragmentMessages++;
|
||||
sink.OnServerMessage(seq, buf, at);
|
||||
}
|
||||
}
|
||||
|
||||
private Slot? FindSlot(uint seq)
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
if (s.InUse && s.Sequence == seq)
|
||||
return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
private Slot StartSlot(uint seq, int count, long nowMs)
|
||||
{
|
||||
Slot? pick = null;
|
||||
foreach (Slot s in _slots)
|
||||
{
|
||||
if (!s.InUse) { pick = s; break; }
|
||||
}
|
||||
if (pick == null)
|
||||
{
|
||||
// All busy: drop the one touched longest ago.
|
||||
pick = _slots[0];
|
||||
foreach (Slot s in _slots)
|
||||
if (s.TouchedMs < pick.TouchedMs) pick = s;
|
||||
EvictedFull++;
|
||||
MarkDone(pick.Sequence); // its stragglers are ignored, not given a new slot
|
||||
}
|
||||
|
||||
int need = count * FragmentStride;
|
||||
if (pick.Buffer == null || pick.Buffer.Length < need)
|
||||
{
|
||||
// Rounded up so a slot settles at the size it needs; at most MaxFragments * 512.
|
||||
int cap = 4096;
|
||||
while (cap < need) cap <<= 1;
|
||||
pick.Buffer = GC.AllocateUninitializedArray<byte>(cap, pinned: true);
|
||||
}
|
||||
pick.InUse = true;
|
||||
pick.Sequence = seq;
|
||||
pick.Count = count;
|
||||
pick.Received = 0;
|
||||
pick.Bytes = 0;
|
||||
pick.TouchedMs = nowMs;
|
||||
Array.Clear(pick.Have);
|
||||
return pick;
|
||||
}
|
||||
|
||||
private void DropSequence(uint seq)
|
||||
{
|
||||
Slot? s = FindSlot(seq);
|
||||
if (s != null) s.InUse = false;
|
||||
MarkDone(seq);
|
||||
}
|
||||
|
||||
private void EvictStale(long nowMs)
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
{
|
||||
if (s.InUse && nowMs - s.TouchedMs > StaleMs)
|
||||
{
|
||||
s.InUse = false;
|
||||
MarkDone(s.Sequence); // a straggler can't start it again
|
||||
EvictedStale++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── done window: the last DoneWindow sequences, by bit ──────────────────
|
||||
|
||||
private bool IsDone(uint seq)
|
||||
{
|
||||
if (!_anyDone) return false;
|
||||
if (seq > _maxDone) return false;
|
||||
if (_maxDone - seq >= DoneWindow) return true; // too old to still be in flight
|
||||
return (_done[(seq & (DoneWindow - 1)) >> 6] & (1UL << (int)(seq & 63))) != 0;
|
||||
}
|
||||
|
||||
private void MarkDone(uint seq)
|
||||
{
|
||||
if (!_anyDone)
|
||||
{
|
||||
_anyDone = true;
|
||||
_maxDone = seq;
|
||||
}
|
||||
else if (seq > _maxDone)
|
||||
{
|
||||
// Clear the bits of the sequences the window slides over.
|
||||
uint advance = seq - _maxDone;
|
||||
if (advance >= DoneWindow)
|
||||
Array.Clear(_done);
|
||||
else
|
||||
for (uint s = _maxDone + 1; s != seq; s++)
|
||||
_done[(s & (DoneWindow - 1)) >> 6] &= ~(1UL << (int)(s & 63));
|
||||
_maxDone = seq;
|
||||
}
|
||||
else if (_maxDone - seq >= DoneWindow)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_done[(seq & (DoneWindow - 1)) >> 6] |= 1UL << (int)(seq & 63);
|
||||
}
|
||||
}
|
||||
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/PacketRing.cs
|
||||
// Hand-off of received datagrams from the RecvFrom detour to the plugin pump.
|
||||
//
|
||||
// The producer (the detour) only copies the datagram: no allocation, no lock, no
|
||||
// wait. A full ring, or a second producer arriving while one is writing, drops the
|
||||
// datagram and counts it; the client's own copy is never touched either way. The
|
||||
// consumer (the single TickAll driver) reads records in place and releases them.
|
||||
//
|
||||
// Records are 8-byte aligned: [i32 length][u32 stamp ms][bytes][pad]. A length of -1
|
||||
// means "the rest of the buffer is unused, continue at 0". Capacity is a power of two
|
||||
// and a multiple of 8, so a wrap marker always fits.
|
||||
//
|
||||
// Pure code (native memory, no engine state); compiled into the NetMessageTests runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal sealed unsafe class PacketRing
|
||||
{
|
||||
private const int RecordHeader = 8;
|
||||
private const int WrapMarker = -1;
|
||||
|
||||
private readonly byte* _buf;
|
||||
private readonly int _capacity;
|
||||
private readonly int _mask;
|
||||
// Byte counters that wrap (int, so reads and writes are single instructions on x86);
|
||||
// only their difference and their low bits are used.
|
||||
private int _head; // bytes written (producer)
|
||||
private int _tail; // bytes released (consumer)
|
||||
private int _writing; // producer claim
|
||||
|
||||
/// <summary>Largest datagram accepted; anything longer is dropped (AC's are under 500 bytes).</summary>
|
||||
public const int MaxDatagram = 2048;
|
||||
|
||||
public long Written;
|
||||
public long DroppedFull;
|
||||
public long DroppedContended;
|
||||
public long DroppedTooLong;
|
||||
|
||||
/// <summary>The ring's memory is never freed: the detour may still be running at teardown.</summary>
|
||||
/// <param name="startCounter">Where the wrapping byte counters start (tests start them near int.MaxValue).</param>
|
||||
public PacketRing(int capacityPow2, int startCounter = 0)
|
||||
{
|
||||
_head = _tail = startCounter & ~7;
|
||||
if (capacityPow2 < 4096 || (capacityPow2 & (capacityPow2 - 1)) != 0)
|
||||
throw new ArgumentOutOfRangeException(nameof(capacityPow2));
|
||||
_capacity = capacityPow2;
|
||||
_mask = capacityPow2 - 1;
|
||||
_buf = (byte*)NativeMemory.AllocZeroed((nuint)capacityPow2);
|
||||
}
|
||||
|
||||
public int Capacity => _capacity;
|
||||
|
||||
/// <summary>Bytes in use (approximate when read from another thread).</summary>
|
||||
public int Used => unchecked(Volatile.Read(ref _head) - Volatile.Read(ref _tail));
|
||||
|
||||
/// <summary>Producer: copy one datagram in. Never blocks; false = dropped (counted).</summary>
|
||||
public bool TryWrite(byte* data, int length, uint stampMs)
|
||||
{
|
||||
if (length <= 0 || length > MaxDatagram)
|
||||
{
|
||||
DroppedTooLong++;
|
||||
return false;
|
||||
}
|
||||
if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0)
|
||||
{
|
||||
Interlocked.Increment(ref DroppedContended);
|
||||
return false;
|
||||
}
|
||||
try
|
||||
{
|
||||
int need = RecordHeader + ((length + 7) & ~7);
|
||||
int head = _head;
|
||||
int used = unchecked(head - Volatile.Read(ref _tail));
|
||||
int pos = head & _mask;
|
||||
int toEnd = _capacity - pos;
|
||||
int skip = need > toEnd ? toEnd : 0;
|
||||
if (used + skip + need > _capacity)
|
||||
{
|
||||
DroppedFull++;
|
||||
return false;
|
||||
}
|
||||
if (skip != 0)
|
||||
{
|
||||
*(int*)(_buf + pos) = WrapMarker;
|
||||
pos = 0;
|
||||
}
|
||||
*(int*)(_buf + pos) = length;
|
||||
*(uint*)(_buf + pos + 4) = stampMs;
|
||||
Buffer.MemoryCopy(data, _buf + pos + RecordHeader, length, length);
|
||||
Written++;
|
||||
Volatile.Write(ref _head, unchecked(head + skip + need)); // publish after the bytes
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _writing, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consumer: the oldest record, in place. Call <see cref="Release"/> with the returned
|
||||
/// token when done with it (the bytes stay valid until then).
|
||||
/// </summary>
|
||||
public bool TryPeek(out byte* data, out int length, out uint stampMs, out int releaseTo)
|
||||
{
|
||||
data = null;
|
||||
length = 0;
|
||||
stampMs = 0;
|
||||
releaseTo = 0;
|
||||
int tail = _tail;
|
||||
int head = Volatile.Read(ref _head);
|
||||
if (tail == head)
|
||||
return false;
|
||||
int pos = tail & _mask;
|
||||
int len = *(int*)(_buf + pos);
|
||||
if (len == WrapMarker)
|
||||
{
|
||||
tail = unchecked(tail + _capacity - pos);
|
||||
pos = 0;
|
||||
len = *(int*)_buf;
|
||||
}
|
||||
data = _buf + pos + RecordHeader;
|
||||
length = len;
|
||||
stampMs = *(uint*)(_buf + pos + 4);
|
||||
releaseTo = unchecked(tail + RecordHeader + ((len + 7) & ~7));
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Release(int releaseTo) => Volatile.Write(ref _tail, releaseTo);
|
||||
|
||||
/// <summary>Consumer: drop everything queued (used when the stream is switched on again).</summary>
|
||||
public void Clear() => Volatile.Write(ref _tail, Volatile.Read(ref _head));
|
||||
}
|
||||
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/ServerMessageInterest.cs
|
||||
// Which server messages one plugin asked for (PluginContract.SetServerMessageInterestFn).
|
||||
//
|
||||
// Opcodes and game event types are 16-bit on the wire in practice; each set is a
|
||||
// 65536-bit map (8 KB), so a check is one load. Special entries:
|
||||
// opcode 0xFFFFFFFF every message;
|
||||
// opcode 0xF7B0 every game event (otherwise only the listed event types).
|
||||
// Pure code; compiled into the NetMessageTests runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal sealed class ServerMessageInterest
|
||||
{
|
||||
public const uint GameEventOpcode = 0xF7B0;
|
||||
public const uint AllMessages = 0xFFFFFFFF;
|
||||
public const int MaxEntries = 4096;
|
||||
|
||||
private readonly ulong[] _opcodes = new ulong[65536 / 64];
|
||||
private readonly ulong[] _events = new ulong[65536 / 64];
|
||||
|
||||
public bool All { get; private set; }
|
||||
public bool AllGameEvents { get; private set; }
|
||||
public int OpcodeCount { get; private set; }
|
||||
public int EventCount { get; private set; }
|
||||
public bool IsEmpty => !All && OpcodeCount == 0 && EventCount == 0;
|
||||
|
||||
/// <summary>Replaces the set. False (set left empty) for an entry out of range or too many entries.</summary>
|
||||
public unsafe bool Set(uint* opcodes, int opcodeCount, uint* events, int eventCount)
|
||||
{
|
||||
Clear();
|
||||
if (opcodeCount < 0 || eventCount < 0 || opcodeCount > MaxEntries || eventCount > MaxEntries)
|
||||
return false;
|
||||
if ((opcodeCount > 0 && opcodes == null) || (eventCount > 0 && events == null))
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < opcodeCount; i++)
|
||||
{
|
||||
uint op = opcodes[i];
|
||||
if (op == AllMessages) { All = true; continue; }
|
||||
if (op > 0xFFFF) { Clear(); return false; }
|
||||
if (op == GameEventOpcode) AllGameEvents = true;
|
||||
if (Add(_opcodes, op)) OpcodeCount++;
|
||||
}
|
||||
for (int i = 0; i < eventCount; i++)
|
||||
{
|
||||
uint ev = events[i];
|
||||
if (ev > 0xFFFF) { Clear(); return false; }
|
||||
if (Add(_events, ev)) EventCount++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
Array.Clear(_opcodes);
|
||||
Array.Clear(_events);
|
||||
All = AllGameEvents = false;
|
||||
OpcodeCount = EventCount = 0;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="eventType"/> is only looked at for opcode 0xF7B0.</summary>
|
||||
public bool Wants(uint opcode, uint eventType)
|
||||
{
|
||||
if (All) return true;
|
||||
if (opcode > 0xFFFF) return false;
|
||||
if (opcode == GameEventOpcode)
|
||||
return AllGameEvents || (eventType <= 0xFFFF && Has(_events, eventType));
|
||||
return Has(_opcodes, opcode);
|
||||
}
|
||||
|
||||
private static bool Has(ulong[] map, uint v) => (map[v >> 6] & (1UL << (int)(v & 63))) != 0;
|
||||
|
||||
private static bool Add(ulong[] map, uint v)
|
||||
{
|
||||
ulong bit = 1UL << (int)(v & 63);
|
||||
if ((map[v >> 6] & bit) != 0) return false;
|
||||
map[v >> 6] |= bit;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Net/ServerMessageStream.cs
|
||||
// The reassembled server-message stream for plugins (API v78).
|
||||
//
|
||||
// RecvFrom detour (RawPacketHooks) plugin pump (PluginManager.ProcessPendingActions)
|
||||
// OnDatagram: one volatile check; while Pump: drains the ring through the
|
||||
// capturing, copies fragment datagrams -> FragmentReassembler; each whole message goes
|
||||
// into PacketRing (no alloc, no lock, to the plugins that asked for it (and to the
|
||||
// never waits; full = dropped + counted) /rc netmsg log tap and capture file).
|
||||
//
|
||||
// Strictly read-only: the detour copies the client's bytes after the real recvfrom
|
||||
// returned them; it never alters, delays or drops anything the client gets.
|
||||
//
|
||||
// Capturing runs only while it is wanted: a plugin with a non-empty interest, or
|
||||
// /rc netmsg log / capture. engine.json "ServerMessageStream": false (or /rc netmsg off)
|
||||
// keeps it off whatever is wanted, and the detour is then exactly what it was before.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using RynthCore.Engine.Plugins;
|
||||
using RynthCore.PluginSdk.Net;
|
||||
|
||||
namespace RynthCore.Engine.Net;
|
||||
|
||||
internal static unsafe class ServerMessageStream
|
||||
{
|
||||
private const int RingBytes = 512 * 1024;
|
||||
private const int MaxPacketsPerPump = 8192;
|
||||
private const long MaxCaptureBytes = 32L * 1024 * 1024;
|
||||
private const int MaxLogLinesPerKind = 5;
|
||||
private const int MaxLogLines = 300;
|
||||
|
||||
private static PacketRing? _ring; // created on first use, never freed (see PacketRing)
|
||||
private static readonly FragmentReassembler Reassembler = new();
|
||||
private static readonly Sink MessageSink = new();
|
||||
private static volatile bool _capturing;
|
||||
private static bool _sessionOff;
|
||||
private static bool _pluginsWant;
|
||||
|
||||
// Delivery counters (pump thread).
|
||||
private static long _delivered, _dispatchedToPlugins;
|
||||
private static long _pumpTicksTotal, _pumpTicksMax, _pumps;
|
||||
|
||||
// /rc netmsg log: check the SDK parsers against the live server.
|
||||
private static bool _logOn;
|
||||
private static int _logLines;
|
||||
private static readonly Dictionary<string, KindStats> Kinds = new();
|
||||
private static readonly Dictionary<uint, long> Opcodes = new();
|
||||
private static readonly object LogLock = new(); // Kinds/Opcodes: pump writes, chat commands read
|
||||
|
||||
// /rc netmsg capture: raw fragment datagrams for tools\NetMessageTests.
|
||||
private static volatile FileStream? _capture; // opened by the command, written and closed by the pump
|
||||
private static volatile bool _captureStopRequested;
|
||||
private static string _capturePath = "";
|
||||
private static long _captureBytes;
|
||||
|
||||
private sealed class KindStats
|
||||
{
|
||||
public long Ok, Failed, Leftover;
|
||||
public int Logged;
|
||||
}
|
||||
|
||||
/// <summary>True while the detour copies datagrams.</summary>
|
||||
public static bool Capturing => _capturing;
|
||||
|
||||
// ── receive hook side ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Called by the RecvFrom detour after the real recvfrom, with the bytes it returned.</summary>
|
||||
public static void OnDatagram(byte* data, int length)
|
||||
{
|
||||
if (!_capturing)
|
||||
return;
|
||||
PacketRing? ring = _ring;
|
||||
if (ring == null || length < AcPacketWire.HeaderSize)
|
||||
return;
|
||||
uint flags = AcPacketWire.ReadU32(data + 4);
|
||||
if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) == 0)
|
||||
return; // acks, pings, time sync: nothing to reassemble
|
||||
ring.TryWrite(data, length, (uint)Environment.TickCount);
|
||||
}
|
||||
|
||||
// ── pump side ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Once per ProcessPendingActions (the single TickAll driver). <paramref name="pluginsWant"/>:
|
||||
/// some initialized plugin has a non-empty interest.
|
||||
/// </summary>
|
||||
public static void Pump(bool pluginsWant)
|
||||
{
|
||||
_pluginsWant = pluginsWant;
|
||||
if (_captureStopRequested)
|
||||
{
|
||||
_captureStopRequested = false;
|
||||
StopCapture("stopped");
|
||||
}
|
||||
bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || _logOn || _capture != null);
|
||||
if (want != _capturing)
|
||||
{
|
||||
if (want)
|
||||
{
|
||||
_ring ??= new PacketRing(RingBytes);
|
||||
_ring.Clear();
|
||||
Reassembler.Reset();
|
||||
}
|
||||
_capturing = want;
|
||||
RynthLog.Compat($"ServerMessageStream: capture {(want ? "on" : "off")} (plugins={pluginsWant} log={_logOn} file={_capture != null})");
|
||||
}
|
||||
|
||||
PacketRing? ring = _ring;
|
||||
if (ring == null)
|
||||
return;
|
||||
if (!_capturing)
|
||||
{
|
||||
if (ring.Used != 0) ring.Clear();
|
||||
return;
|
||||
}
|
||||
|
||||
long start = System.Diagnostics.Stopwatch.GetTimestamp();
|
||||
long now = Environment.TickCount64;
|
||||
int n = 0;
|
||||
while (n < MaxPacketsPerPump && ring.TryPeek(out byte* data, out int len, out uint stamp, out int releaseTo))
|
||||
{
|
||||
n++;
|
||||
try
|
||||
{
|
||||
if (_capture != null) WriteCapture(data, len, stamp);
|
||||
Reassembler.ProcessDatagram(data, len, now, MessageSink);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Compat($"ServerMessageStream: datagram failed - {ex.GetType().Name}: {ex.Message}");
|
||||
}
|
||||
ring.Release(releaseTo);
|
||||
}
|
||||
if (n > 0)
|
||||
{
|
||||
long ticks = System.Diagnostics.Stopwatch.GetTimestamp() - start;
|
||||
_pumps++;
|
||||
_pumpTicksTotal += ticks;
|
||||
if (ticks > _pumpTicksMax) _pumpTicksMax = ticks;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Sink : IServerMessageSink
|
||||
{
|
||||
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
|
||||
{
|
||||
_delivered++;
|
||||
uint opcode = AcPacketWire.ReadU32(message);
|
||||
uint eventType = opcode == ServerMessage.GameEventOpcode && length >= 16 ? AcPacketWire.ReadU32(message + 12) : 0;
|
||||
if (_logOn)
|
||||
{
|
||||
try { LogTap(opcode, eventType, message, length); }
|
||||
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: log tap failed - {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
if (_pluginsWant)
|
||||
_dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4);
|
||||
}
|
||||
}
|
||||
|
||||
// ── /rc netmsg ──────────────────────────────────────────────────────────
|
||||
|
||||
public static string[] HandleCommand(string args)
|
||||
{
|
||||
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
|
||||
string arg = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
|
||||
switch (verb)
|
||||
{
|
||||
case "on":
|
||||
_sessionOff = false;
|
||||
return new[] { EngineSettings.ServerMessageStream
|
||||
? "Server message stream allowed for this session (it runs while a plugin, the log or a capture wants it)."
|
||||
: "engine.json has \"ServerMessageStream\": false - the stream stays off. Remove it (or set true) and restart." };
|
||||
case "off":
|
||||
_sessionOff = true;
|
||||
return new[] { "Server message stream off for this session (plugins get nothing until /rc netmsg on)." };
|
||||
case "log":
|
||||
if (arg is "on" or "")
|
||||
{
|
||||
lock (LogLock) { _logLines = 0; Kinds.Clear(); Opcodes.Clear(); }
|
||||
_logOn = true;
|
||||
return new[] { "Server message log on: parsed messages go to the RynthCore log (NetMsg:), counts to /rc netmsg." };
|
||||
}
|
||||
if (arg == "off") { _logOn = false; return new[] { "Server message log off." }; }
|
||||
return new[] { "Usage: /rc netmsg log on|off" };
|
||||
case "capture":
|
||||
if (arg is "on" or "") return new[] { StartCapture() };
|
||||
if (arg == "off")
|
||||
{
|
||||
if (_capture == null) return new[] { "Not capturing." };
|
||||
_captureStopRequested = true; // the pump closes it after its current write
|
||||
return new[] { $"Capture stopping: {_capturePath}." };
|
||||
}
|
||||
return new[] { "Usage: /rc netmsg capture on|off" };
|
||||
case "status":
|
||||
return StatusLines();
|
||||
default:
|
||||
return new[] { "Usage: /rc netmsg [status|on|off|log on|off|capture on|off]" };
|
||||
}
|
||||
}
|
||||
|
||||
public static string[] StatusLines()
|
||||
{
|
||||
var r = Reassembler;
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"Server messages: setting {(EngineSettings.ServerMessageStream ? "on" : "OFF (engine.json)")}, session {(_sessionOff ? "off" : "on")}, " +
|
||||
$"capturing {(_capturing ? "yes" : "no")}, hook {(Compatibility.RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}; " +
|
||||
$"plugins {PluginManager.ServerMessageSubscriberCount()} subscribed",
|
||||
};
|
||||
if (_ring != null)
|
||||
lines.Add($"Ring: {_ring.Written} datagrams copied, dropped {_ring.DroppedFull} full / {_ring.DroppedContended} contended / {_ring.DroppedTooLong} too long, {_ring.Used / 1024} KB queued");
|
||||
lines.Add($"Reassembly: {r.Packets} packets ({r.PacketsNoFragments} no fragments, {r.PacketsMalformed} malformed, {r.PacketsUnknownOptional} unknown header" +
|
||||
(r.PacketsUnknownOptional > 0 ? $" last flags 0x{r.LastUnknownFlags:X8}" : "") + $"), {r.Fragments} fragments, " +
|
||||
$"{r.Messages} messages ({r.MultiFragmentMessages} multi-fragment), dup {r.DuplicateFragments} fragments / {r.DuplicateMessages} messages, " +
|
||||
$"bad {r.BadFragments}, oversized {r.Oversized}, evicted {r.EvictedStale} stale / {r.EvictedFull} full, {r.PartialCount} partial, {r.SessionResets} session resets");
|
||||
double tickUs = 1_000_000.0 / System.Diagnostics.Stopwatch.Frequency;
|
||||
lines.Add($"Delivered {_delivered}, plugin calls {_dispatchedToPlugins}; drain (incl. plugin calls) avg {(_pumps > 0 ? _pumpTicksTotal * tickUs / _pumps : 0):0.0} us, max {_pumpTicksMax * tickUs:0} us over {_pumps} drains");
|
||||
lock (LogLock)
|
||||
if (_logOn || Kinds.Count > 0)
|
||||
{
|
||||
string kinds = string.Join(", ", Kinds.OrderBy(k => k.Key).Select(k => $"{k.Key} {k.Value.Ok} ok" +
|
||||
(k.Value.Failed > 0 ? $"/{k.Value.Failed} FAILED" : "") + (k.Value.Leftover > 0 ? $"/{k.Value.Leftover} leftover" : "")));
|
||||
lines.Add($"Parsed ({(_logOn ? "log on" : "log off")}): {(kinds.Length > 0 ? kinds : "none yet")}");
|
||||
string top = string.Join(" ", Opcodes.OrderByDescending(o => o.Value).Take(12).Select(o => $"{FormatKey(o.Key)}x{o.Value}"));
|
||||
if (top.Length > 0) lines.Add($"Top opcodes: {top}");
|
||||
}
|
||||
if (_capture != null)
|
||||
lines.Add($"Capturing to {_capturePath} ({_captureBytes / 1024} KB)");
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
private static string FormatKey(uint key) => key >= 0x10000 ? $"F7B0/{key & 0xFFFF:X4}" : $"{key:X4}";
|
||||
|
||||
// ── log tap ─────────────────────────────────────────────────────────────
|
||||
|
||||
private static void LogTap(uint opcode, uint eventType, byte* message, int length)
|
||||
{
|
||||
uint key = opcode == ServerMessage.GameEventOpcode ? 0x10000u | (eventType & 0xFFFF) : opcode & 0xFFFF;
|
||||
var msg = new ServerMessage(opcode, new ReadOnlySpan<byte>(message + 4, length - 4));
|
||||
NetMessageInfo info = NetMessages.Inspect(msg);
|
||||
bool interesting = !info.Parsed || info.Leftover != 0;
|
||||
bool log;
|
||||
lock (LogLock)
|
||||
{
|
||||
Opcodes[key] = Opcodes.TryGetValue(key, out long c) ? c + 1 : 1;
|
||||
if (!info.Known)
|
||||
return;
|
||||
if (!Kinds.TryGetValue(info.Kind, out KindStats? k))
|
||||
Kinds[info.Kind] = k = new KindStats();
|
||||
if (info.Parsed) k.Ok++; else k.Failed++;
|
||||
if (info.Parsed && info.Leftover != 0) k.Leftover++;
|
||||
log = _logLines < MaxLogLines && (k.Logged < MaxLogLinesPerKind || interesting);
|
||||
if (log)
|
||||
{
|
||||
_logLines++;
|
||||
k.Logged++;
|
||||
}
|
||||
}
|
||||
if (log)
|
||||
{
|
||||
string hex = interesting ? " bytes=" + Convert.ToHexString(new ReadOnlySpan<byte>(message, Math.Min(length, 96))) : "";
|
||||
RynthLog.Compat($"NetMsg: {info.Kind} len={length} {(info.Parsed ? "ok" : "FAILED")}" +
|
||||
(info.Leftover != 0 ? $" leftover={info.Leftover}" : "") + $" {info.Summary}{hex}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── capture file ────────────────────────────────────────────────────────
|
||||
// Format "RNC1": the 4 magic bytes, then per datagram [u32 stamp ms][u16 length][bytes].
|
||||
|
||||
private static string StartCapture()
|
||||
{
|
||||
if (_capture != null)
|
||||
return $"Already capturing to {_capturePath}.";
|
||||
if (!EngineSettings.ServerMessageStream || _sessionOff)
|
||||
return "The server message stream is off; /rc netmsg on first (engine.json must allow it).";
|
||||
try
|
||||
{
|
||||
LogPaths.EnsureLogDirectory();
|
||||
_capturePath = Path.Combine(LogPaths.LogDirectory, $"netcapture-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}.rnc");
|
||||
_capture = new FileStream(_capturePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 64 * 1024);
|
||||
_capture.Write("RNC1"u8);
|
||||
_captureBytes = 4;
|
||||
return $"Capturing server datagrams to {_capturePath} (stops at {MaxCaptureBytes / (1024 * 1024)} MB; holds chat text, keep it local).";
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_capture = null;
|
||||
return $"Capture failed: {ex.Message}";
|
||||
}
|
||||
}
|
||||
|
||||
private static string StopCapture(string why)
|
||||
{
|
||||
if (_capture == null)
|
||||
return "Not capturing.";
|
||||
try { _capture.Dispose(); } catch { }
|
||||
_capture = null;
|
||||
string msg = $"Capture {why}: {_capturePath} ({_captureBytes / 1024} KB).";
|
||||
RynthLog.Compat("ServerMessageStream: " + msg);
|
||||
return msg;
|
||||
}
|
||||
|
||||
private static void WriteCapture(byte* data, int len, uint stamp)
|
||||
{
|
||||
FileStream? f = _capture;
|
||||
if (f == null) return;
|
||||
Span<byte> head = stackalloc byte[6];
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(head, stamp);
|
||||
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(head.Slice(4), (ushort)len);
|
||||
try
|
||||
{
|
||||
f.Write(head);
|
||||
f.Write(new ReadOnlySpan<byte>(data, len));
|
||||
_captureBytes += 6 + len;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StopCapture($"failed ({ex.Message})");
|
||||
return;
|
||||
}
|
||||
if (_captureBytes >= MaxCaptureBytes)
|
||||
StopCapture("reached its size cap");
|
||||
}
|
||||
|
||||
/// <summary>Engine shutdown: close a capture file. The ring stays allocated (see PacketRing).</summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
_capturing = false;
|
||||
if (_capture != null) StopCapture("closed at shutdown");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue