diff --git a/src/AcDream.Core.Net/Messages/ChatRequests.cs b/src/AcDream.Core.Net/Messages/ChatRequests.cs new file mode 100644 index 0000000..daebbfd --- /dev/null +++ b/src/AcDream.Core.Net/Messages/ChatRequests.cs @@ -0,0 +1,99 @@ +using System; +using System.Buffers.Binary; +using System.Text; + +namespace AcDream.Core.Net.Messages; + +/// +/// Outbound chat GameActions — Talk (local /say), Tell (whisper), +/// ChatChannel (allegiance / general). +/// +/// +/// All three ride inside the 0xF7B1 GameAction envelope with +/// the same leading fields: +/// +/// u32 0xF7B1 +/// u32 gameActionSequence +/// u32 subOpcode +/// <payload> +/// +/// +/// +/// +/// String16L wire shape mirrors the other outbound AC messages: +/// +/// u16 length // byte count (not char count) +/// byte[] ascii // ASCII bytes, no terminator +/// pad to 4-byte boundary +/// +/// +/// +/// +/// Source of truth: r08 §3 rows 0x0015 / 0x005D / 0x0147. +/// +/// +public static class ChatRequests +{ + public const uint GameActionEnvelope = 0xF7B1u; + public const uint TalkOpcode = 0x0015u; + public const uint TellOpcode = 0x005Du; + public const uint ChatChannelOpcode = 0x0147u; + + /// Send a local /say message (heard by anyone within ~20m). + public static byte[] BuildTalk(uint gameActionSequence, string message) + { + ArgumentNullException.ThrowIfNull(message); + byte[] msg = PackString16L(message); + byte[] body = new byte[12 + msg.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(body, GameActionEnvelope); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(4), gameActionSequence); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(8), TalkOpcode); + Array.Copy(msg, 0, body, 12, msg.Length); + return body; + } + + /// Send a /tell (whisper) by target character name. + public static byte[] BuildTell(uint gameActionSequence, string targetName, string message) + { + ArgumentNullException.ThrowIfNull(targetName); + ArgumentNullException.ThrowIfNull(message); + byte[] name = PackString16L(targetName); + byte[] msg = PackString16L(message); + byte[] body = new byte[12 + name.Length + msg.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(body, GameActionEnvelope); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(4), gameActionSequence); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(8), TellOpcode); + Array.Copy(name, 0, body, 12, name.Length); + Array.Copy(msg, 0, body, 12 + name.Length, msg.Length); + return body; + } + + /// Send to a chat channel (allegiance, general, trade, etc). + public static byte[] BuildChatChannel(uint gameActionSequence, uint channelId, string message) + { + ArgumentNullException.ThrowIfNull(message); + byte[] msg = PackString16L(message); + byte[] body = new byte[16 + msg.Length]; + BinaryPrimitives.WriteUInt32LittleEndian(body, GameActionEnvelope); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(4), gameActionSequence); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(8), ChatChannelOpcode); + BinaryPrimitives.WriteUInt32LittleEndian(body.AsSpan(12), channelId); + Array.Copy(msg, 0, body, 16, msg.Length); + return body; + } + + private static byte[] PackString16L(string s) + { + byte[] data = Encoding.ASCII.GetBytes(s); + if (data.Length > ushort.MaxValue) + throw new ArgumentException("String too long for 16-bit length prefix.", nameof(s)); + + int recordSize = 2 + data.Length; + int padding = (4 - (recordSize & 3)) & 3; + byte[] result = new byte[recordSize + padding]; + BinaryPrimitives.WriteUInt16LittleEndian(result, (ushort)data.Length); + Array.Copy(data, 0, result, 2, data.Length); + // trailing bytes are already zero from new[] + return result; + } +} diff --git a/src/AcDream.Core.Net/Messages/HearSpeech.cs b/src/AcDream.Core.Net/Messages/HearSpeech.cs new file mode 100644 index 0000000..d918e13 --- /dev/null +++ b/src/AcDream.Core.Net/Messages/HearSpeech.cs @@ -0,0 +1,85 @@ +using System; +using System.Buffers.Binary; +using System.Text; + +namespace AcDream.Core.Net.Messages; + +/// +/// Inbound 0x02BB HearSpeech + 0x02BC HearRangedSpeech +/// GameMessages. Local-area / shout chat heard by the player. These +/// do NOT ride the 0xF7B0 GameEvent envelope — they're standalone +/// GameMessages dispatched the same way as CreateObject / UpdateMotion. +/// +/// +/// Wire layout: +/// +/// u32 opcode // 0x02BB or 0x02BC +/// string16L text +/// string16L senderName +/// u32 senderGuid +/// u32 chatType +/// +/// +/// +/// +/// ChatType (from ACE): +/// +/// 0x01 = Broadcast +/// 0x02 = Combat +/// 0x0B = Speech +/// 0x0F = Emote +/// 0x10 = Tell +/// 0x11 = Syllables (spell casting) +/// other values in ACE ChatMessageType.cs +/// +/// +/// +public static class HearSpeech +{ + public const uint LocalOpcode = 0x02BBu; + public const uint RangedOpcode = 0x02BCu; + + public readonly record struct Parsed( + string Text, + string SenderName, + uint SenderGuid, + uint ChatType, + bool IsRanged); + + public static Parsed? TryParse(byte[] body) + { + if (body is null || body.Length < 16) return null; + + uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body); + bool isRanged; + if (opcode == LocalOpcode) isRanged = false; + else if (opcode == RangedOpcode) isRanged = true; + else return null; + + int pos = 4; + try + { + string text = ReadString16L(body, ref pos); + string sender = ReadString16L(body, ref pos); + if (body.Length - pos < 8) return null; + uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos)); pos += 4; + uint chatType = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos)); pos += 4; + return new Parsed(text, sender, senderGuid, chatType, isRanged); + } + catch { return null; } + } + + private static string ReadString16L(ReadOnlySpan source, ref int pos) + { + if (source.Length - pos < 2) throw new FormatException("truncated String16L length"); + ushort length = BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(pos)); + pos += 2; + if (source.Length - pos < length) throw new FormatException("truncated String16L body"); + string result = Encoding.ASCII.GetString(source.Slice(pos, length)); + pos += length; + int recordSize = 2 + length; + int padding = (4 - (recordSize & 3)) & 3; + pos += padding; + return result; + } +} diff --git a/src/AcDream.Core.Net/WorldSession.cs b/src/AcDream.Core.Net/WorldSession.cs index 1a102e5..c39bacf 100644 --- a/src/AcDream.Core.Net/WorldSession.cs +++ b/src/AcDream.Core.Net/WorldSession.cs @@ -102,6 +102,13 @@ public sealed class WorldSession : IDisposable /// public event Action? TeleportStarted; + /// + /// Phase H.1: fires when a local or ranged speech message (0x02BB / + /// 0x02BC) is received. Subscribers typically feed these into a + /// ChatLog. + /// + public event Action? SpeechHeard; + /// /// Allow re-sending LoginComplete after a portal teleport. The normal /// _loginCompleteSent latch prevents duplicate sends on the initial spawn @@ -487,6 +494,15 @@ public sealed class WorldSession : IDisposable posUpdate.Value.Velocity)); } } + else if (op == HearSpeech.LocalOpcode || op == HearSpeech.RangedOpcode) + { + // Phase H.1: local/ranged chat. Standalone GameMessage + // (NOT wrapped in 0xF7B0). Payload layout is documented + // on HearSpeech.TryParse. + var parsed = HearSpeech.TryParse(body); + if (parsed is not null) + SpeechHeard?.Invoke(parsed.Value); + } else if (op == GameEventEnvelope.Opcode) { // Phase F.1: 0xF7B0 is the GameEvent envelope. Parse the diff --git a/src/AcDream.Core/Chat/ChatLog.cs b/src/AcDream.Core/Chat/ChatLog.cs new file mode 100644 index 0000000..115d379 --- /dev/null +++ b/src/AcDream.Core/Chat/ChatLog.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Collections.Concurrent; + +namespace AcDream.Core.Chat; + +/// +/// Unified chat log — mirrors every chat-bearing message the server +/// sends (local HearSpeech, broadcast ChannelBroadcast, whispered +/// Tell, system TransientMessage, PopupString). +/// +/// +/// Sits behind the UI chat panel (Phase D.2) and the scripting +/// plugin API so plugins can react to chat (e.g. auto-reply, loot +/// logging). +/// +/// +/// +/// Retail keeps ~200 lines of scrollback. Our ring buffer defaults to +/// 500 and is configurable. +/// +/// +public sealed class ChatLog +{ + private readonly ConcurrentQueue _buffer = new(); + private readonly int _maxEntries; + + public ChatLog(int maxEntries = 500) + { + if (maxEntries < 1) throw new ArgumentOutOfRangeException(nameof(maxEntries)); + _maxEntries = maxEntries; + } + + /// Fires every time a new entry is appended. + public event Action? EntryAppended; + + /// Snapshot of all current entries, oldest first. + public ChatEntry[] Snapshot() => _buffer.ToArray(); + + public int Count => _buffer.Count; + + // ── Inbound adapters ───────────────────────────────────────────────────── + + /// Local or ranged HearSpeech (0x02BB / 0x02BC). + public void OnLocalSpeech(string sender, string text, uint senderGuid, bool isRanged) + { + Append(new ChatEntry( + Kind: isRanged ? ChatKind.RangedSpeech : ChatKind.LocalSpeech, + Sender: sender, + Text: text, + SenderGuid: senderGuid, + ChannelId: 0)); + } + + /// GameEvent ChannelBroadcast (0x0147). + public void OnChannelBroadcast(uint channelId, string sender, string text) + { + Append(new ChatEntry( + Kind: ChatKind.Channel, + Sender: sender, + Text: text, + SenderGuid: 0, + ChannelId: channelId)); + } + + /// GameEvent Tell (0x02BD) — whisper received. + public void OnTellReceived(string sender, string text, uint senderGuid) + { + Append(new ChatEntry( + Kind: ChatKind.Tell, + Sender: sender, + Text: text, + SenderGuid: senderGuid, + ChannelId: 0)); + } + + /// GameEvent CommunicationTransientString (0x02EB) — e.g. "Your spell fizzled!" + public void OnSystemMessage(string text, uint chatType) + { + Append(new ChatEntry( + Kind: ChatKind.System, + Sender: "", + Text: text, + SenderGuid: 0, + ChannelId: chatType)); + } + + /// GameEvent PopupString (0x0004) — modal dialog text. + public void OnPopup(string text) + { + Append(new ChatEntry( + Kind: ChatKind.Popup, + Sender: "", + Text: text, + SenderGuid: 0, + ChannelId: 0)); + } + + /// Echo the player's own outbound message after local send. + public void OnSelfSent(ChatKind kind, string text, string targetOrChannel = "") + { + Append(new ChatEntry( + Kind: kind, + Sender: targetOrChannel, // used as "to whom" for Tell / channel name for Channel + Text: text, + SenderGuid: 0, + ChannelId: 0)); + } + + private void Append(ChatEntry entry) + { + _buffer.Enqueue(entry); + while (_buffer.Count > _maxEntries) + _buffer.TryDequeue(out _); + EntryAppended?.Invoke(entry); + } + + public void Clear() + { + while (_buffer.TryDequeue(out _)) { /* drain */ } + } +} + +public enum ChatKind +{ + LocalSpeech, + RangedSpeech, + Channel, + Tell, + System, + Popup, +} + +public readonly record struct ChatEntry( + ChatKind Kind, + string Sender, + string Text, + uint SenderGuid, + uint ChannelId) +{ + public DateTime Received { get; init; } = DateTime.UtcNow; +} diff --git a/tests/AcDream.Core.Net.Tests/Messages/ChatTests.cs b/tests/AcDream.Core.Net.Tests/Messages/ChatTests.cs new file mode 100644 index 0000000..8d39425 --- /dev/null +++ b/tests/AcDream.Core.Net.Tests/Messages/ChatTests.cs @@ -0,0 +1,133 @@ +using System; +using System.Buffers.Binary; +using System.Text; +using AcDream.Core.Net.Messages; +using Xunit; + +namespace AcDream.Core.Net.Tests.Messages; + +public sealed class ChatTests +{ + [Fact] + public void BuildTalk_EmitsOpcodeAndString16L() + { + byte[] body = ChatRequests.BuildTalk(gameActionSequence: 3, message: "hi"); + + Assert.Equal(ChatRequests.TalkOpcode, + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8))); + + // Verify the string16L starts at offset 12. + ushort len = BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(12)); + Assert.Equal(2, len); + Assert.Equal("hi", Encoding.ASCII.GetString(body.AsSpan(14, 2))); + + // Record size = 2+2 = 4, no padding needed. + Assert.Equal(16, body.Length); + } + + [Fact] + public void BuildTalk_EmitsPadding_WhenMessageLengthRequiresIt() + { + byte[] body = ChatRequests.BuildTalk(gameActionSequence: 3, message: "h"); + // 2+1=3 bytes record → pad 1 byte. + // Total body = 12 (envelope) + 4 (str16L aligned) = 16. + Assert.Equal(16, body.Length); + } + + [Fact] + public void BuildTell_IncludesBothStrings() + { + byte[] body = ChatRequests.BuildTell( + gameActionSequence: 5, targetName: "Alice", message: "hey"); + + Assert.Equal(ChatRequests.TellOpcode, + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8))); + + int pos = 12; + ushort len1 = BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos)); + Assert.Equal(5, len1); + Assert.Equal("Alice", Encoding.ASCII.GetString(body.AsSpan(pos + 2, 5))); + + // "Alice" record = 2+5=7, pad 1 → advance by 8. + pos += 8; + ushort len2 = BinaryPrimitives.ReadUInt16LittleEndian(body.AsSpan(pos)); + Assert.Equal(3, len2); + Assert.Equal("hey", Encoding.ASCII.GetString(body.AsSpan(pos + 2, 3))); + } + + [Fact] + public void BuildChatChannel_IncludesChannelId() + { + byte[] body = ChatRequests.BuildChatChannel( + gameActionSequence: 1, channelId: 42, message: "tell me the good dungeons"); + + Assert.Equal(ChatRequests.ChatChannelOpcode, + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8))); + Assert.Equal(42u, + BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(12))); + } + + [Fact] + public void HearSpeech_TryParse_LocalRoundTrip() + { + // Build a 0x02BB message and re-parse it. + byte[] talkBody = ChatRequests.BuildTalk(gameActionSequence: 0, message: "hello"); + + // Now synthesize the inbound HearSpeech format. + byte[] msg = PackString16L("hello"); + byte[] sender = PackString16L("Alice"); + byte[] inbound = new byte[4 + msg.Length + sender.Length + 8]; + int pos = 0; + BinaryPrimitives.WriteUInt32LittleEndian(inbound, HearSpeech.LocalOpcode); + pos += 4; + Array.Copy(msg, 0, inbound, pos, msg.Length); pos += msg.Length; + Array.Copy(sender, 0, inbound, pos, sender.Length); pos += sender.Length; + BinaryPrimitives.WriteUInt32LittleEndian(inbound.AsSpan(pos), 0xCAFEu); pos += 4; + BinaryPrimitives.WriteUInt32LittleEndian(inbound.AsSpan(pos), 0x0B); pos += 4; // Speech + + var parsed = HearSpeech.TryParse(inbound); + Assert.NotNull(parsed); + Assert.Equal("hello", parsed!.Value.Text); + Assert.Equal("Alice", parsed.Value.SenderName); + Assert.Equal(0xCAFEu, parsed.Value.SenderGuid); + Assert.Equal(0x0Bu, parsed.Value.ChatType); + Assert.False(parsed.Value.IsRanged); + } + + [Fact] + public void HearSpeech_TryParse_RangedFlag() + { + byte[] msg = PackString16L("X"); + byte[] sender = PackString16L("Y"); + byte[] inbound = new byte[4 + msg.Length + sender.Length + 8]; + BinaryPrimitives.WriteUInt32LittleEndian(inbound, HearSpeech.RangedOpcode); + int pos = 4; + Array.Copy(msg, 0, inbound, pos, msg.Length); pos += msg.Length; + Array.Copy(sender, 0, inbound, pos, sender.Length); pos += sender.Length; + BinaryPrimitives.WriteUInt32LittleEndian(inbound.AsSpan(pos), 0); pos += 4; + BinaryPrimitives.WriteUInt32LittleEndian(inbound.AsSpan(pos), 0); pos += 4; + + var parsed = HearSpeech.TryParse(inbound); + Assert.NotNull(parsed); + Assert.True(parsed!.Value.IsRanged); + } + + [Fact] + public void HearSpeech_TryParse_WrongOpcode_ReturnsNull() + { + byte[] body = new byte[16]; + BinaryPrimitives.WriteUInt32LittleEndian(body, 0xDEADBEEFu); + Assert.Null(HearSpeech.TryParse(body)); + } + + private static byte[] PackString16L(string s) + { + byte[] data = Encoding.ASCII.GetBytes(s); + int recordSize = 2 + data.Length; + int padding = (4 - (recordSize & 3)) & 3; + byte[] result = new byte[recordSize + padding]; + BinaryPrimitives.WriteUInt16LittleEndian(result, (ushort)data.Length); + Array.Copy(data, 0, result, 2, data.Length); + return result; + } +} diff --git a/tests/AcDream.Core.Tests/Chat/ChatLogTests.cs b/tests/AcDream.Core.Tests/Chat/ChatLogTests.cs new file mode 100644 index 0000000..0418f1a --- /dev/null +++ b/tests/AcDream.Core.Tests/Chat/ChatLogTests.cs @@ -0,0 +1,93 @@ +using AcDream.Core.Chat; +using Xunit; + +namespace AcDream.Core.Tests.Chat; + +public sealed class ChatLogTests +{ + [Fact] + public void OnLocalSpeech_AppendsEntry_FiresEvent() + { + var log = new ChatLog(); + ChatEntry? seen = null; + log.EntryAppended += e => seen = e; + + log.OnLocalSpeech("Alice", "hi", 0xAA, isRanged: false); + + Assert.Equal(1, log.Count); + Assert.NotNull(seen); + Assert.Equal(ChatKind.LocalSpeech, seen!.Value.Kind); + Assert.Equal("Alice", seen.Value.Sender); + Assert.Equal("hi", seen.Value.Text); + } + + [Fact] + public void OnLocalSpeech_Ranged_SetsRangedKind() + { + var log = new ChatLog(); + log.OnLocalSpeech("Bob", "SHOUT", 0xBB, isRanged: true); + Assert.Equal(ChatKind.RangedSpeech, log.Snapshot()[0].Kind); + } + + [Fact] + public void OnChannelBroadcast_SetsChannelId() + { + var log = new ChatLog(); + log.OnChannelBroadcast(channelId: 42, sender: "Alice", text: "allegiance motd"); + var e = log.Snapshot()[0]; + Assert.Equal(42u, e.ChannelId); + Assert.Equal(ChatKind.Channel, e.Kind); + } + + [Fact] + public void OnTellReceived_SetsTellKind() + { + var log = new ChatLog(); + log.OnTellReceived("Alice", "psst", 0xAA); + Assert.Equal(ChatKind.Tell, log.Snapshot()[0].Kind); + } + + [Fact] + public void OnSystemMessage_EncodesChatType_AsChannelId() + { + var log = new ChatLog(); + log.OnSystemMessage("Your spell fizzled!", chatType: 5); + var e = log.Snapshot()[0]; + Assert.Equal(ChatKind.System, e.Kind); + Assert.Equal(5u, e.ChannelId); + } + + [Fact] + public void OnSelfSent_EchoesOutbound() + { + var log = new ChatLog(); + log.OnSelfSent(ChatKind.Tell, "hey", targetOrChannel: "Alice"); + var e = log.Snapshot()[0]; + Assert.Equal("Alice", e.Sender); + Assert.Equal("hey", e.Text); + } + + [Fact] + public void RingBuffer_DropsOldestBeyondCapacity() + { + var log = new ChatLog(maxEntries: 3); + log.OnLocalSpeech("A", "1", 0, false); + log.OnLocalSpeech("B", "2", 0, false); + log.OnLocalSpeech("C", "3", 0, false); + log.OnLocalSpeech("D", "4", 0, false); + + var snap = log.Snapshot(); + Assert.Equal(3, snap.Length); + Assert.Equal("2", snap[0].Text); // "1" was dropped + Assert.Equal("4", snap[2].Text); + } + + [Fact] + public void Clear_EmptiesBuffer() + { + var log = new ChatLog(); + log.OnLocalSpeech("A", "1", 0, false); + log.Clear(); + Assert.Equal(0, log.Count); + } +}