Snapshot for release 2026.10.11.1 (internal 4eca83a)

This commit is contained in:
Tom Bohar 2026-10-11 15:00:53 -04:00
commit 08b80eed86
94 changed files with 11103 additions and 567 deletions

View file

@ -32,8 +32,10 @@
// (0x0083E03C, CreateUIElementManager 0x0045F900) is not used, to ship no fixed
// address. No manager (tooltip hooks off or not found) = Unknown = fail open.
//
// Not confirmed in game yet: that the element under the mouse over open
// ground is the SmartBox wrapper itself rather than a child. `/rc acmouse`
// In game (2026-10-10 logs) the element under the mouse over open ground is
// NOT the wrapper but gmSmartBoxUI, element 0x1000049A, type 0x10000014
// (gmSmartBoxUI::Register 0x004D71E0; gmGamePlayUI's "<SBOX>"). Both types
// count as the world (AcMouseOverRules.IsWorldType). `/rc acmouse`
// (or `/rc acmouse watch` for 20 s of changes in chat) names what AC has
// under the cursor; Identify is the one place that decides.
//
@ -110,7 +112,7 @@ internal static unsafe class AcMouseOver
}
/// <summary>
/// The one decision: the 3D view is the SmartBox wrapper element (type 0x10000030);
/// The one decision: the 3D view is gmSmartBoxUI (type 0x10000014) or its SmartBox wrapper (0x10000030);
/// any other element AC reports is one of its windows; nothing readable is Unknown.
/// </summary>
private static AcMouseTarget Identify(bool readable, bool outside, IntPtr element, bool typeKnown, int type)

View file

@ -19,7 +19,7 @@ internal enum AcMouseTarget
Unknown,
/// <summary>AC reports nothing under the mouse (cursor outside the client, or no element took it).</summary>
Nothing,
/// <summary>The 3D view: AC's SmartBox wrapper element (UIElement type 0x10000030).</summary>
/// <summary>The 3D view: AC's gmSmartBoxUI panel (type 0x10000014) or its SmartBox wrapper (0x10000030).</summary>
World,
/// <summary>Any other AC element: a window (inventory, chat, radar, vitals, the selected-object bar...).</summary>
AcWindow,
@ -30,6 +30,19 @@ internal static class AcMouseOverRules
/// <summary>UIElement_SmartBoxWrapper::GetUIElementType (0x004E5E80) returns this; it is the 3D view.</summary>
public const int UIElementTypeSmartBoxWrapper = 0x10000030;
/// <summary>
/// gmSmartBoxUI::Register (0x004D71E0) registers this type: the game-play 3D view panel,
/// element 0x1000049A (gmGamePlayUI::SetupChildren 0x004EAB50; SaveScreenLayout 0x004EB9E0
/// writes its rect as "&lt;SBOX&gt;"). In game it is what AC reports under the cursor over open
/// ground (2026-10-10 client logs), not the wrapper: missing it here sent every plate's
/// click to AC.
/// </summary>
public const int UIElementTypeGmSmartBoxUI = 0x10000014;
/// <summary>One of the 3D view's element types.</summary>
public static bool IsWorldType(int elementType) =>
elementType == UIElementTypeSmartBoxWrapper || elementType == UIElementTypeGmSmartBoxUI;
/// <summary>
/// Classifies one read of UIElementManager. <paramref name="stateReadable"/>: the manager
/// was known and its fields readable. <paramref name="mouseOutside"/>: its +0x2D4 flag (the
@ -42,7 +55,7 @@ internal static class AcMouseOverRules
if (!stateReadable) return AcMouseTarget.Unknown;
if (mouseOutside || element == 0) return AcMouseTarget.Nothing;
if (!typeKnown) return AcMouseTarget.Unknown;
return elementType == UIElementTypeSmartBoxWrapper ? AcMouseTarget.World : AcMouseTarget.AcWindow;
return IsWorldType(elementType) ? AcMouseTarget.World : AcMouseTarget.AcWindow;
}
/// <summary>

View file

@ -203,9 +203,11 @@ internal static unsafe class ChatCommandDispatcher
if (StartsWithCmd(trimmed, "/tell "))
return DispatchTell(trimmed.Substring(6));
// /a message (allegiance channel broadcast)
// /a message (allegiance): AC's own chat command, like /f. Event_ChannelBroadcast(1)
// got "You do not have permission to talk in that channel" (2026-10-11): the server
// gives each allegiance its own Turbine chat room, which only AC's /a knows.
if (StartsWithCmd(trimmed, "/a "))
return DispatchChannelBroadcast(1, trimmed.Substring(3));
return DispatchRaw(trimmed);
// /f message (fellowship — no direct Event_*; use the raw chat path)
if (StartsWithCmd(trimmed, "/f "))

View file

@ -0,0 +1,169 @@
// ============================================================================
// RynthCore.Engine - Compatibility/IltDetect.cs
//
// Pure detection for Infinite Leaftide (ILT), the ACECustom server: no AC, no
// engine state, so the offline tests (tools/IltTests) compile this file as is.
// The stateful side (command line, announced world name, engine.json lists,
// the /rc ilt override) is IltInfo.cs.
//
// Signals, either one is enough:
// - the launch command line's -h host: game.infiniteleaftide.online, as the
// public AC server list (acresources/serverslist Servers.xml) gives it, or
// any other host under infiniteleaftide.online;
// - the world name the server announced at login: "InfiniteLeaftide" (the
// name UtilityBelt's Leaftide tools and SilentKelpie's ILT Hub check for),
// or anything with "Leaftide" in it.
// Both lists can be replaced in engine.json ("IltServerNames", "IltHosts").
//
// Unlike Aelrynth detection nothing here unlocks a server-side action that
// could hurt another server: a false positive only shows the ILT bar button,
// and the Bounties window's "/bounty list" gets "Unknown command" (after which
// RynthILT stops reading). So one signal is enough, and a dev copy on
// localhost counts when it announces an ILT world name.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>One ILT detection result. Immutable.</summary>
internal sealed class IltVerdict
{
public bool IsIlt { get; init; }
/// <summary>Plain-English why, for /rc ilt and the log.</summary>
public string Reason { get; init; } = "";
public static readonly IltVerdict Unknown = new() { Reason = "nothing known yet" };
}
internal static class IltDetect
{
/// <summary>World-name patterns used when engine.json has no "IltServerNames" ('*' = any run of characters, case-insensitive).</summary>
public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" };
/// <summary>Host names used when engine.json has no "IltHosts": the domain and every host under it ('*' allowed too).</summary>
public static readonly string[] DefaultHosts = { "infiniteleaftide.online" };
/// <summary>True when <paramref name="world"/> matches one of <paramref name="patterns"/>.</summary>
public static bool WorldNameMatches(string? world, IEnumerable<string>? patterns, out string matched)
{
matched = "";
if (string.IsNullOrWhiteSpace(world) || patterns == null) return false;
string w = world.Trim();
foreach (string p in patterns)
{
if (string.IsNullOrWhiteSpace(p)) continue;
if (!Matches(w, p.Trim())) continue;
matched = p.Trim();
return true;
}
return false;
}
/// <summary>
/// True when <paramref name="host"/> is one of <paramref name="patterns"/>: the same name, a
/// host under it ("game.infiniteleaftide.online" for "infiniteleaftide.online"), or a '*'
/// pattern match. An IP address matches only itself. Case and a trailing dot are ignored.
/// </summary>
public static bool HostMatches(string? host, IEnumerable<string>? patterns, out string matched)
{
matched = "";
if (string.IsNullOrWhiteSpace(host) || patterns == null) return false;
string h = host.Trim().TrimEnd('.').ToLowerInvariant();
foreach (string raw in patterns)
{
if (string.IsNullOrWhiteSpace(raw)) continue;
string p = raw.Trim().TrimEnd('.').ToLowerInvariant();
bool hit = p.Contains('*')
? Matches(h, p)
: h == p || (!IsIpv4(p) && h.EndsWith("." + p, StringComparison.Ordinal));
if (!hit) continue;
matched = raw.Trim();
return true;
}
return false;
}
/// <summary>
/// Combines the signals: ILT when the launch host or the announced world name matches.
/// Null lists mean the defaults; an empty list turns that signal off.
/// </summary>
public static IltVerdict Decide(string? host, string? announcedWorld,
IReadOnlyList<string>? serverNames, IReadOnlyList<string>? hosts)
{
IReadOnlyList<string> names = serverNames ?? DefaultServerNames;
IReadOnlyList<string> hostList = hosts ?? DefaultHosts;
string where = host is { Length: > 0 } ? host : "no host on the command line";
string world = announcedWorld is { Length: > 0 } ? $"world \"{announcedWorld}\"" : "no world name yet";
bool byHost = HostMatches(host, hostList, out string hostHit);
bool byWorld = WorldNameMatches(announcedWorld, names, out string worldHit);
if (byHost && byWorld)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {where} matches \"{hostHit}\" and {world} matches \"{worldHit}\"" };
if (byHost)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {where} matches \"{hostHit}\" ({world})" };
if (byWorld)
return new IltVerdict { IsIlt = true, Reason = $"Infinite Leaftide: {world} matches \"{worldHit}\" (host {where})" };
return new IltVerdict { Reason = $"not Infinite Leaftide: {where}, {world}" };
}
/// <summary>Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern).</summary>
public static bool Matches(string text, string pattern)
{
if (pattern.Length == 0) return false;
if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);
string[] parts = pattern.Split('*');
int pos = 0;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part.Length == 0) continue;
if (i == 0)
{
if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false;
pos = part.Length;
continue;
}
if (i == parts.Length - 1)
return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase);
int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
pos = at + part.Length;
}
return true;
}
/// <summary>"InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive). Null for null.</summary>
public static List<string>? ParseList(IEnumerable<string?>? items)
{
if (items == null) return null;
var list = new List<string>();
foreach (string? raw in items)
{
if (string.IsNullOrWhiteSpace(raw)) continue;
foreach (string piece in raw.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
{
string p = piece.Trim();
if (p.Length == 0) continue;
bool dup = false;
foreach (string have in list)
if (have.Equals(p, StringComparison.OrdinalIgnoreCase)) { dup = true; break; }
if (!dup) list.Add(p);
}
}
return list;
}
private static bool IsIpv4(string s)
{
int dots = 0;
foreach (char c in s)
{
if (c == '.') dots++;
else if (c < '0' || c > '9') return false;
}
return dots == 3;
}
}

View file

@ -0,0 +1,103 @@
// ============================================================================
// RynthCore.Engine - Compatibility/IltInfo.cs
//
// Is this client on Infinite Leaftide (ILT, the ACECustom server)? IltInfo.IsIlt
// is the one flag the ILT section checks (the bar's ILT button, /rc bounties,
// the Bounties window's reads through the RynthILT plugin).
//
// Signals (combined by IltDetect.Decide, IltDetect.cs):
// - the launch command line's -h host (ServerInfo reads it once);
// - the world name the server announced at login (AccountHooks);
// - the engine.json lists "IltServerNames" / "IltHosts" replace the
// defaults (InfiniteLeaftide / *Leaftide* and infiniteleaftide.online).
// Unknown means not ILT. "/rc ilt on|off|auto" overrides it for this session
// (testing), never saved.
//
// Threads: any. Re-evaluated at most once a second; each read in between is a
// volatile load and a compare. Never touches AC.
// ============================================================================
using System;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class IltInfo
{
public enum Mode { Auto, ForceIlt, ForceOther }
private const int RefreshMs = 1000;
private static volatile IltVerdict _verdict = IltVerdict.Unknown;
private static long _nextRefreshMs;
private static int _mode; // Mode
private static volatile bool _lastIlt;
/// <summary>True when the client is on Infinite Leaftide - or the override says so. Any thread.</summary>
public static bool IsIlt => Current.IsIlt;
public static Mode Override
{
get => (Mode)Volatile.Read(ref _mode);
set
{
Volatile.Write(ref _mode, (int)value);
Volatile.Write(ref _nextRefreshMs, 0);
}
}
/// <summary>The current verdict (re-evaluated at most once a second). Any thread.</summary>
public static IltVerdict Current
{
get
{
long now = Environment.TickCount64;
if (now >= Volatile.Read(ref _nextRefreshMs))
{
Volatile.Write(ref _nextRefreshMs, now + RefreshMs);
Refresh();
}
return _verdict;
}
}
/// <summary>The lists in force, for /rc ilt.</summary>
public static string ListsDescription
{
get
{
var names = EngineSettings.IltServerNames;
var hosts = EngineSettings.IltHosts;
return $"world names {(names == null ? "default " + string.Join(", ", IltDetect.DefaultServerNames) : "engine.json " + Join(names))}; "
+ $"hosts {(hosts == null ? "default " + string.Join(", ", IltDetect.DefaultHosts) : "engine.json " + Join(hosts))}";
}
}
private static string Join(System.Collections.Generic.IReadOnlyList<string> list)
=> list.Count == 0 ? "(none)" : string.Join(", ", list);
private static void Refresh()
{
try
{
IltVerdict v = Override switch
{
Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on with /rc ilt on (testing)" },
Mode.ForceOther => new IltVerdict { Reason = "forced off with /rc ilt off (testing)" },
_ => IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName,
EngineSettings.IltServerNames, EngineSettings.IltHosts),
};
_verdict = v;
if (v.IsIlt != _lastIlt)
{
_lastIlt = v.IsIlt;
RynthLog.Compat($"IltInfo: {v.Reason}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"IltInfo: refresh failed - {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,143 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Rewrites acclient's signed "pointer % 4" padding (<see cref="LargeAddressAlignmentScan"/>)
/// to <c>and r, 3</c> in memory, so pack/unpack of buffers above 2 GB pads 0..3 bytes like
/// it does below 2 GB. Without it, a large-address-aware client corrupts dat and network
/// unpacks whenever the heap hands AC a buffer above 0x80000000 (long open-world sessions).
///
/// The patch is never undone: an unloading engine generation leaves it in place and the next
/// generation finds every site already patched. acclient.exe on disk is not touched.
/// </summary>
internal static class LargeAddressAlignmentPatch
{
private const uint PAGE_EXECUTE_READWRITE = 0x40;
private const ushort ImageDosSignature = 0x5A4D;
private const uint ImageNtSignature = 0x00004550;
private const int SectionHeaderSize = 40;
private static string _statusMessage = "Not applied yet.";
public static string StatusMessage => _statusMessage;
/// <summary>Sites rewritten by this engine generation.</summary>
public static int PatchedCount { get; private set; }
/// <summary>Sites a previous engine generation had already rewritten.</summary>
public static int AlreadyPatchedCount { get; private set; }
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushInstructionCache(IntPtr hProcess, IntPtr lpBaseAddress, UIntPtr dwSize);
public static void Initialize()
{
if (!Plugins.EngineSettings.EnableLargeAddressAlignmentFix)
{
_statusMessage = "Disabled via engine.json (EnableLargeAddressAlignmentFix=false).";
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
return;
}
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
if (moduleBase == IntPtr.Zero || !TryGetTextSection(moduleBase, out int textRva, out int textSize))
{
_statusMessage = "acclient .text section not found.";
RynthLog.Compat($"Compat: large-address alignment fix skipped - {_statusMessage}");
return;
}
IntPtr textBase = IntPtr.Add(moduleBase, textRva);
byte[] text = new byte[textSize];
Marshal.Copy(textBase, text, 0, textSize);
List<AlignmentSite> sites = LargeAddressAlignmentScan.Find(text, textBase.ToInt32());
int patched = 0, already = 0, failed = 0;
foreach (AlignmentSite site in sites)
{
if (site.AlreadyPatched)
{
already++;
continue;
}
if (TryWriteHighByte(new IntPtr(site.ImmHighByteVa)))
patched++;
else
failed++;
}
if (patched > 0)
FlushInstructionCache(GetCurrentProcess(), textBase, (UIntPtr)(uint)textSize);
PatchedCount = patched;
AlreadyPatchedCount = already;
_statusMessage = $"{patched} site(s) patched, {already} already patched, {failed} failed ({sites.Count} found).";
if (sites.Count == 0 || failed > 0)
RynthLog.Compat($"Compat: large-address alignment fix - {_statusMessage}");
else
RynthLog.Info($"Compat: large-address alignment fix - {_statusMessage}");
}
// One byte, protection restored per site: other hooks may hold different protections on
// neighbouring .text pages, so the whole section is never flipped at once.
private static bool TryWriteHighByte(IntPtr address)
{
if (!VirtualProtect(address, (UIntPtr)1u, PAGE_EXECUTE_READWRITE, out uint oldProtect))
{
RynthLog.Compat($"Compat: large-address alignment fix - VirtualProtect 0x{address.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
return false;
}
try
{
// Re-check the live byte: the scan worked on a copy.
if (Marshal.ReadByte(address) != LargeAddressAlignmentScan.StockHighByte)
return false;
Marshal.WriteByte(address, LargeAddressAlignmentScan.PatchedHighByte);
return true;
}
finally
{
VirtualProtect(address, (UIntPtr)1u, oldProtect, out _);
}
}
private static bool TryGetTextSection(IntPtr moduleBase, out int rva, out int size)
{
rva = 0;
size = 0;
if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature)
return false;
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
IntPtr nt = IntPtr.Add(moduleBase, peOffset);
if (peOffset <= 0 || (uint)Marshal.ReadInt32(nt) != ImageNtSignature)
return false;
int sectionCount = (ushort)Marshal.ReadInt16(nt, 6);
int optionalHeaderSize = (ushort)Marshal.ReadInt16(nt, 20);
IntPtr section = IntPtr.Add(nt, 24 + optionalHeaderSize);
for (int i = 0; i < sectionCount; i++, section = IntPtr.Add(section, SectionHeaderSize))
{
if (Marshal.PtrToStringAnsi(section, 8).TrimEnd('\0') != ".text")
continue;
size = Marshal.ReadInt32(section, 8);
rva = Marshal.ReadInt32(section, 12);
return size > 0 && rva > 0;
}
return false;
}
}

View file

@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>One signed "pointer % 4" padding site in acclient's code.</summary>
/// <param name="AndVa">VA of the <c>and r32, imm32</c> instruction.</param>
/// <param name="ImmHighByteVa">VA of the immediate's top byte (0x80 stock, 0x00 once patched).</param>
/// <param name="Register">x86 register number (0 = eax ... 7 = edi).</param>
/// <param name="AlreadyPatched">True when the immediate is already 0x00000003.</param>
internal readonly record struct AlignmentSite(int AndVa, int ImmHighByteVa, int Register, bool AlreadyPatched);
/// <summary>
/// Finds AC's 4-byte pack/unpack padding code, which MSVC compiled from a signed
/// <c>(int)ptr % 4</c>:
/// <code>
/// and r, 0x80000003 ; keep the sign bit
/// ... (0-12 bytes, no flag writes)
/// jns +5
/// dec r / or r, -4 / inc r ; negative remainder fix-up
/// [pop r32]
/// je skip ; remainder 0: already aligned
/// ... pad 4 - r bytes
/// </code>
/// With large-address-aware acclient a buffer above 2 GB is a negative int, the remainder
/// comes out -3..-1, and AC pads 4 - r = 5..7 bytes instead of 1..3: the cursor runs 4 bytes
/// past the field, zeroes live data and parses garbage counts (kelpie's motion-table crashes).
/// Clearing the immediate's sign bit (<c>and r, 3</c>) makes the remainder 0..3 at any address.
/// Requiring the trailing <c>je</c> limits the patch to padding code: a signed modulo of a value
/// that can really be negative is left alone.
/// </summary>
internal static class LargeAddressAlignmentScan
{
private const byte StockImmHighByte = 0x80;
private const byte PatchedImmHighByte = 0x00;
// and r32, imm32 to the jns: MSVC interleaves at most a few movs; the largest gap in
// the retail client is 5 bytes.
private const int MaxGapBeforeJns = 12;
/// <summary>Scans <paramref name="text"/> (the bytes of .text, which starts at
/// <paramref name="textVa"/>) for stock and already-patched padding sites.</summary>
public static List<AlignmentSite> Find(ReadOnlySpan<byte> text, int textVa)
{
var sites = new List<AlignmentSite>();
// Leave room for the longest match: 6 (and) + 12 (gap) + 7 (fix-up) + 1 (pop) + 2 (je).
int last = text.Length - 28;
for (int i = 0; i < last; i++)
{
int reg, immOffset;
if (text[i] == 0x25)
{
reg = 0; // and eax, imm32 (short form)
immOffset = 1;
}
else if (text[i] == 0x81 && (text[i + 1] & 0xF8) == 0xE0)
{
reg = text[i + 1] & 0x07; // and r32, imm32 (81 /4, mod=11)
immOffset = 2;
}
else
{
continue;
}
if (text[i + immOffset] != 0x03 || text[i + immOffset + 1] != 0x00 || text[i + immOffset + 2] != 0x00)
continue;
byte high = text[i + immOffset + 3];
if (high != StockImmHighByte && high != PatchedImmHighByte)
continue;
int andEnd = i + immOffset + 4;
if (!HasSignedFixupThenJe(text, andEnd, reg))
continue;
sites.Add(new AlignmentSite(textVa + i, textVa + i + immOffset + 3, reg, high == PatchedImmHighByte));
}
return sites;
}
/// <summary>The immediate's top byte value a site must hold before it is patched.</summary>
public static byte StockHighByte => StockImmHighByte;
/// <summary>The immediate's top byte value after the patch (<c>and r, 3</c>).</summary>
public static byte PatchedHighByte => PatchedImmHighByte;
// jns +5 ; dec r ; or r, 0xFC ; inc r ; [pop r32] ; je rel8|rel32
private static bool HasSignedFixupThenJe(ReadOnlySpan<byte> text, int from, int reg)
{
for (int k = from; k <= from + MaxGapBeforeJns; k++)
{
if (text[k] != 0x79 || text[k + 1] != 0x05 ||
text[k + 2] != 0x48 + reg ||
text[k + 3] != 0x83 || text[k + 4] != 0xC8 + reg || text[k + 5] != 0xFC ||
text[k + 6] != 0x40 + reg)
{
continue;
}
int m = k + 7;
if (text[m] >= 0x58 && text[m] <= 0x5F)
m++;
return text[m] == 0x74 || (text[m] == 0x0F && text[m + 1] == 0x84);
}
return false;
}
}

View file

@ -27,6 +27,9 @@ namespace RynthCore.Engine.Compatibility;
/// <item><c>/rc ui retailvitals [on|off|status]</c> — hide AC's own
/// health/stamina/mana bars (<see cref="RetailVitalsHooks"/>; saved for the
/// PC, also in Settings &gt; UI). Alone it reports the state.</item>
/// <item><c>/rc ui barsize [0-10|+|-|status]</c> - the RynthCore bar's size (its own text
/// size step, <see cref="UI.PanelTextScale"/>; saved for the PC, also in Settings &gt;
/// Display). Alone it reports the size.</item>
/// <item><c>/rc vendor [list|info|status|buy &lt;id|sel&gt; [n]|sell &lt;id|sel&gt; [id ...]]</c>
/// — read / trade with the open vendor through the engine's vendor
/// primitives (<see cref="VendorTrade"/>); a manual test hook for the
@ -34,6 +37,10 @@ namespace RynthCore.Engine.Compatibility;
/// <item><c>/rc chathold [on|off|status]</c> — incoming chat waits for the plugins'
/// verdict before AC prints it, so a line a plugin eats is kept out of AC's chat
/// window too (<see cref="ChatCallbackHooks"/>). On at every start; not saved.</item>
/// <item><c>/rc discord [on|off|status|window|test [route]|resume [route]]</c> — RynthChat's
/// Discord relay (<see cref="UI.Data.Discord.ChatDiscord"/>): switch it on or off for the
/// character you're playing (off for every character by default), list the routes,
/// post a test line, clear a pause; window opens its panel (Chat &gt; gear &gt; Discord).</item>
/// <item><c>/rv plates</c> (aliases <c>/rv nameplates</c>, <c>/rc plates</c>) — the
/// RynthVision nameplates and combat text: monster plates on|off, self, debuffs,
/// numbers, gains [on|off] (with their sub-switches), all on|off, all|engaged,
@ -70,6 +77,9 @@ namespace RynthCore.Engine.Compatibility;
/// the last minutes of client/server messages and engine markers) to
/// Logs\flight-&lt;pid&gt;-&lt;time&gt;.txt; <c>/rc flightdump auto &lt;reason&gt;</c> is the rate-limited
/// automatic form. <c>/rc flight [status|mark &lt;text&gt;|on|off|auto on|off]</c>.</item>
/// <item><c>/rc report [text]</c> - "Report a problem" (<see cref="Report.ProblemReport"/>): alone it
/// opens the panel; with text it sends that report now, with the recent log attached
/// (the panel is where the log can be left out). One report a minute.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -142,6 +152,14 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc discord [on|off|status|window|test [route]|resume [route]] : RynthChat's Discord relay
if (IsVerb(sub, "discord", out string discordArgs))
{
try { HandleDiscordCommand(discordArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc discord failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc plates [on|off|all|engaged|dist N|max N|scale X|opacity X|lift X|names|hp|level|weak|distance|fade|reset|status]
if (IsVerb(sub, "plates", out string platesArgs) || IsVerb(sub, "nameplates", out platesArgs))
{
@ -158,6 +176,14 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a testing override
if (IsVerb(sub, "ilt", out string iltArgs))
{
try { HandleIltCommand(iltArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc ilt failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc mastery : the Aelrynth mastery feed's state, and ask the server again
if (IsVerb(sub, "mastery", out _))
{
@ -228,6 +254,18 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc report [text] : Report a problem - alone it opens the panel; with text it sends now (with the log)
if (IsVerb(sub, "report", out string reportArgs))
{
try
{
foreach (string l in Report.ProblemReport.HandleCommand(reportArgs))
Reply(l);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc report failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc flight [status|mark <text>|on|off|auto on|off] : the flight recorder
if (IsVerb(sub, "flight", out string flightArgs))
{
@ -299,6 +337,19 @@ internal static class RynthCoreChatCommands
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ItemCountFace.Title);
return true;
case "bounties":
case "bounty":
case "bountys":
// The ImGui Bounties panel (ILT section: ACECustom bounties, the RynthILT plugin's
// tracker), like the ILT bar button. Only on Infinite Leaftide with RynthILT installed.
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title))
Reply("The Bounties panel isn't available (the RynthILT plugin isn't installed, or the ImGui layer is off).");
else if (!IltInfo.IsIlt && !ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.BountiesFace.Title))
Reply("Bounties are an Infinite Leaftide feature, and this isn't Infinite Leaftide (/rc ilt for why).");
else
UI.PanelRouter.Toggle(ImGuiBackend.Panels.BountiesFace.Title);
return true;
case "remote":
case "miniremote":
// The ImGui Mini Remote panel (open/close), like its bar button.
@ -383,6 +434,29 @@ internal static class RynthCoreChatCommands
return;
}
// /rc ui barsize [0-10|+|-|status]: the bar's size. Alone it reports it.
if (parts[0].Equals("barsize", StringComparison.OrdinalIgnoreCase))
{
int cur = UI.PanelTextScale.GetChrome();
if (parts.Length >= 2 && !parts[1].Equals("status", StringComparison.OrdinalIgnoreCase))
{
int next;
// Bare + / -: one step. +n / -n: that many steps. Plain n: that size.
if (parts[1] == "+") next = cur + 1;
else if (parts[1] == "-") next = cur - 1;
else if (!int.TryParse(parts[1], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out next))
{
Reply("Usage: /rc ui barsize [0-10|+|-|status]");
return;
}
else if (parts[1][0] is '+' or '-')
next += cur;
UI.PanelTextScale.SetChrome(next);
}
Reply("Bar size: " + UI.PanelTextScale.Describe(UI.PanelTextScale.GetChrome()) + ".");
return;
}
// /rc ui open|close|popout|redock|snap <Panel>: drive a panel by name (tests,
// dispatch.txt). Names may have spaces ("Monster Detail").
string verb = parts[0].ToLowerInvariant();
@ -415,7 +489,7 @@ internal static class RynthCoreChatCommands
if (parts.Length != 2 || !UI.PanelFaceStore.TryParseFace(parts[1], out UI.PanelFace face))
{
Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off]");
Reply("Usage: /rc ui list | /rc ui <Panel|bar> avalonia|imgui|both | /rc ui open|close|popout|redock|snap <Panel> | /rc ui retailvitals [on|off] | /rc ui barsize [0-10|+|-|status]");
return;
}
@ -519,6 +593,32 @@ internal static class RynthCoreChatCommands
Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}.");
}
/// <summary>
/// /rc ilt: the Infinite Leaftide verdict, its signals and the lists in force. "on" /
/// "off" force it for this session (testing the ILT section anywhere); "auto" goes back
/// to detecting. Never saved; the lists are engine.json's IltServerNames / IltHosts.
/// </summary>
private static void HandleIltCommand(string args)
{
switch (args.Trim().ToLowerInvariant())
{
case "on": case "ilt": IltInfo.Override = IltInfo.Mode.ForceIlt; break;
case "off": case "other": IltInfo.Override = IltInfo.Mode.ForceOther; break;
case "auto": IltInfo.Override = IltInfo.Mode.Auto; break;
case "": break;
default:
Reply("Usage: /rc ilt [auto|on|off]");
return;
}
IltVerdict v = IltInfo.Current;
Reply($"ILT: {(v.IsIlt ? "Infinite Leaftide" : "not Infinite Leaftide")} - {v.Reason}.");
Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; "
+ $"override {IltInfo.Override}. Lists: {IltInfo.ListsDescription}.");
Reply(ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.BountiesFace.Title)
? "RynthILT: installed (Bounties: the ILT bar button or /rc bounties)."
: "RynthILT: not installed, so there is no ILT section.");
}
private static void HandleMasteryCommand()
{
if (!ServerInfo.IsAelrynth)
@ -737,6 +837,7 @@ internal static class RynthCoreChatCommands
break;
case "players":
S.PlayerNames = Flag(value, S.PlayerNames); break;
case "playerbars": S.PlayerBars = Flag(value, S.PlayerBars); break;
case "names": S.ShowNames = Flag(value, S.ShowNames); break;
case "hp": S.ShowHpNumbers = Flag(value, S.ShowHpNumbers); break;
case "level": S.ShowLevel = Flag(value, S.ShowLevel); break;
@ -805,6 +906,28 @@ internal static class RynthCoreChatCommands
private static bool Flag(string? value, bool current) =>
value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current };
/// <summary>
/// /rc discord: the relay's switch, status, test and resume (UI.Data.Discord.ChatDiscord);
/// "window" opens its panel, like Chat > gear > Discord settings.
/// </summary>
private static void HandleDiscordCommand(string args)
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.ChatDiscordFace.Title))
{
Reply("The Discord relay needs the RynthChat plugin.");
return;
}
string verb = args.Trim();
if (verb.Equals("window", StringComparison.OrdinalIgnoreCase) || verb.Equals("show", StringComparison.OrdinalIgnoreCase)
|| verb.Equals("settings", StringComparison.OrdinalIgnoreCase))
{
UI.PanelRouter.Toggle(ImGuiBackend.Panels.ChatDiscordFace.Title);
return;
}
foreach (string line in UI.Data.Discord.ChatDiscord.HandleCommand(verb))
Reply(line);
}
private static void Reply(string text)
{
RynthLog.Compat($"RynthCoreChatCommands: {text}");

View file

@ -84,6 +84,16 @@ internal static class ServerInfo
}
}
/// <summary>The connect host from the command line, lower case ("" when none). Any thread (IltInfo).</summary>
public static string LaunchHost
{
get
{
ReadHostOnce();
return _host;
}
}
private static void Refresh()
{
try

View file

@ -62,6 +62,10 @@ internal static class EngineLifecycle
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private static long _lastSignalReloadMs;
/// <summary>Environment.TickCount64 of this engine's last SignalReload (0 = none).</summary>
internal static long LastSignalReloadMs => Interlocked.Read(ref _lastSignalReloadMs);
internal static bool IsShuttingDown => Volatile.Read(ref _shuttingDown) != 0;
internal static bool HasShutDown => Volatile.Read(ref _hasShutDown) != 0;
@ -72,6 +76,9 @@ internal static class EngineLifecycle
/// </summary>
public static bool SignalReload()
{
// Every caller is a player's request (RL, ERl, /rc rl): the reload cap's chat notice
// answers those each time (EntryPoint.ReloadCapped).
Interlocked.Exchange(ref _lastSignalReloadMs, Environment.TickCount64);
IntPtr hEvent = OpenEventW(EVENT_MODIFY_STATE, false, ReloadEventName);
if (hEvent == IntPtr.Zero)
{
@ -174,8 +181,12 @@ internal static class EngineLifecycle
// The chat log is written on the tick pump (UiDataHub), now stopped. Left open,
// it outlived this generation and locked the next one out of the file.
Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog());
// Discord posts still in flight would finish in this dying generation's code.
Step("ChatDiscord.Shutdown", () => UI.Data.Discord.ChatDiscord.Shutdown());
Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown());
Step("FlightRecorder.Shutdown", () => Net.FlightRecorder.Shutdown());
// A report still being sent: cancel it and dispose its HttpClient (nothing may outlive this generation).
Step("ProblemReport.Shutdown", () => Report.ProblemReport.Shutdown());
Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());

View file

@ -84,6 +84,42 @@ public static class EntryPoint
return 0;
}
/// <summary>
/// The reload cap (ReloadCapNotice): the loader asks this before every hot reload, and
/// refuses the reload once this client has done that many. engine.json MaxHotReloads,
/// default 3; negative = no cap. Loader thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthCoreMaxHotReloads")]
public static int MaxHotReloads()
{
try { return EngineSettings.MaxHotReloads; }
catch { return ReloadCapNotice.DefaultMaxHotReloads; }
}
private static readonly ReloadCapNotice s_reloadCapNotice = new();
/// <summary>
/// The loader refused a hot reload because this client has done <paramref name="reloads"/>
/// of them (the cap is <paramref name="cap"/>). The client stays on this engine. Logs it,
/// and says so in chat once, and again when the player asked for the reload by hand.
/// Loader thread.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthCoreReloadCapped")]
public static uint ReloadCapped(int reloads, int cap)
{
try
{
bool byHand = ReloadCapNotice.IsRecentManualSignal(EngineLifecycle.LastSignalReloadMs, Environment.TickCount64);
RynthLog.Warn(ReloadCapNotice.LogText(reloads, cap, byHand));
bool chat;
lock (s_reloadCapNotice) chat = s_reloadCapNotice.ShouldChat(byHand);
if (chat)
Compatibility.AcMainThreadQueue.EnqueueWriteToChat(ReloadCapNotice.ChatText(reloads), 2);
}
catch { }
return 0;
}
[UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")]
public static uint Shutdown(IntPtr lpParam)
{
@ -195,6 +231,9 @@ public static class EntryPoint
RynthLog.Info("Early-init: could not resolve engine directory — minhook may not be preloaded before MultiClientHooks.");
RunInitStep("early multi-client hooks", MultiClientHooks.Initialize);
// Before AC's main thread resumes, so no dat or network unpack runs the stock
// signed padding; a hot reload finds every site already patched.
RunInitStep("large-address alignment fix", LargeAddressAlignmentPatch.Initialize);
// DatFileShareHooks force-shares AC's data files at the CreateFile
// layer so we can coexist with Decal-injected clients that other
// launchers (Thwargle etc.) have already opened against the same
@ -941,6 +980,9 @@ public static class EntryPoint
{
UI.Data.ChatModel.EnsureSettingsLoaded();
UI.Data.ChatModel.InstallInput();
// Discord relay settings (file read here, not on AC's thread); a relay left
// on keeps the chat feed running with the Chat panel closed.
UI.Data.Discord.ChatDiscord.EnsureLoaded();
}
// ImGui faces for panels docked in the client (UI.PanelRouter
// picks the face). Registered even while the ImGui layer is off,
@ -951,10 +993,15 @@ public static class EntryPoint
ImGuiBackend.Panels.VisionFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthNav.dll"))
ImGuiBackend.Panels.RynthNavFace.Register();
// The ILT section (Infinite Leaftide): its faces exist only with RynthILT
// installed, and the bar's ILT button shows them only on ILT (IltInfo).
if (HasPluginDll("RynthCore.Plugin.RynthILT.dll"))
ImGuiBackend.Panels.BountiesFace.Register();
if (HasPluginDll("RynthCore.Plugin.RynthChat.dll"))
{
ImGuiBackend.Panels.ChatFace.Register();
ImGuiBackend.Panels.ChatFiltersFace.Register();
ImGuiBackend.Panels.ChatDiscordFace.Register();
}
ImGuiBackend.Panels.RadarFace.Register();
ImGuiBackend.Panels.SettingsFace.Register();

View file

@ -8,11 +8,17 @@
// an unknown panel shows its first letter), reload (RL) and pop out.
// Dragging the grip moves the bar; the position is the shared bar= row in
// panel_state.txt. Right-click a panel button (or the grip for the bar
// itself) to choose which face shows it docked. Pop out moves the ImGui bar
// itself) to choose which face shows it docked; the grip's menu also has the
// bar's size and "Report a problem". Pop out moves the ImGui bar
// into its own window (ImGuiPopOuts, sized to its content; dock back
// returns it); a bar whose face is Avalonia/Both still pops out as the
// Avalonia bar.
//
// The bar's size is its own text size step (PanelTextScale chrome row): the bar's
// fonts come from that baked set and its metrics scale by the step's factor. Set it
// from the grip's right-click menu, Ctrl+wheel over the bar, Settings > Display or
// /rc ui barsize.
//
// Face key "__bar" in panel_faces.txt; code default Avalonia. While the ImGui
// bar shows, the docked Avalonia bar is hidden and takes no clicks
// (AvaloniaOverlay.DockedBarSuppressed). AC thread except where noted.
@ -23,6 +29,7 @@ using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using ImGuiNET;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
@ -48,6 +55,11 @@ internal static class ImGuiBar
private static readonly string[] ImGuiOnlyBarPanels =
{ Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title };
// The ILT section: the RynthILT plugin's ImGui-only panels. They never get buttons of their
// own; one ILT button stands for them, shown only on Infinite Leaftide (IltInfo.IsIlt) and
// only for the ones registered (EntryPoint registers them when RynthILT is installed).
private static readonly string[] IltPanels = { Panels.BountiesFace.Title };
// Known panels' icons (DrakBot's where the same window exists); others show their first letter.
private static readonly Dictionary<string, string> PanelIcons = new(StringComparer.OrdinalIgnoreCase)
{
@ -87,10 +99,26 @@ internal static class ImGuiBar
// Square buttons, logical px (x the DPI scale).
private const float ButtonSize = 20f, ButtonGap = 3f;
/// <summary>
/// The bar's text size step (the nearest one already baked) and its scale factor. The one
/// place either is worked out, so the bar's fonts and its metrics always agree.
/// </summary>
private static int ChromeStep(out float factor)
{
int step = ImGuiFonts.BakedStepNear(PanelTextScale.GetChrome());
factor = PanelTextScale.Factor(step);
return step;
}
private static ButtonInfo[]? _buttons;
private static string _tooltip = "";
private static bool _placed;
private static Vector2 _pos, _persistedPos;
// What may write a new position to the bar= row: the user dragging the grip, or the bar being
// pulled back on screen by a size change (a few frames: the window grows a frame late). A clamp
// from a smaller AC window leaves the saved position alone.
private static bool _userMoved;
private static int _lastStep, _sizeWatch;
private const string PopOutTitle = "__bar";
// Popped out (the ImGui bar in its own window). Read from panel_state once,
@ -173,12 +201,15 @@ internal static class ImGuiBar
private static void DrawPopped(float s, Vector2 display)
{
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
ImGuiNET.ImGui.SetNextWindowPos(ImGuiPopOuts.PanelOrigin, ImGuiCond.Always);
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiFonts.CurrentStep = step;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: true);
ImGuiNET.ImGui.PopFont();
@ -189,6 +220,7 @@ internal static class ImGuiBar
}
finally
{
ImGuiFonts.CurrentStep = 0;
ImGuiNET.ImGui.End();
PopBarWindowStyle();
}
@ -218,6 +250,8 @@ internal static class ImGuiBar
public static void Draw(float s)
{
EnsureButtons();
int step = ChromeStep(out float factor);
s *= factor;
float place = AvaloniaOverlay.InputScale > 0 ? AvaloniaOverlay.InputScale : 1f;
bool both = ResolveFace() == PanelFace.Both;
@ -229,18 +263,23 @@ internal static class ImGuiBar
_pos = _persistedPos = logical * place;
ImGuiNET.ImGui.SetNextWindowPos(_pos, ImGuiCond.Always);
_placed = true;
_lastStep = step; // the size the bar loads at is the baseline, not a change
}
if (step != _lastStep) { _lastStep = step; _sizeWatch = 4; }
PushBarWindowStyle(s);
ImGuiNET.ImGui.Begin("##rc_bar", BarFlags);
try
{
ImGuiFonts.CurrentStep = step;
ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11));
DrawContent(s, place, popped: false);
ImGuiNET.ImGui.PopFont();
KeepOnScreen();
}
finally
{
ImGuiFonts.CurrentStep = 0;
_pos = ImGuiNET.ImGui.GetWindowPos();
ImGuiNET.ImGui.End();
PopBarWindowStyle();
@ -249,15 +288,35 @@ internal static class ImGuiBar
if (!ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left) && _pos != _persistedPos)
{
_persistedPos = _pos;
Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero);
double left = logical.X, top = logical.Y;
UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top));
if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top);
if (_userMoved || _sizeWatch > 0)
{
Vector2 logical = _pos / place - (both ? new Vector2(24, 24) : Vector2.Zero);
double left = logical.X, top = logical.Y;
UiBackgroundWriter.Enqueue("persist bar", () => PanelStateStore.SetBarPosition(left, top));
if (!both) AvaloniaOverlay.SyncDockedBarPosition(left, top);
}
_userMoved = false;
}
if (_sizeWatch > 0) _sizeWatch--;
}
/// <summary>A bigger size can push the bar's right end off the screen: pull it back (not while it is being dragged).</summary>
private static void KeepOnScreen()
{
Vector2 display = ImGuiNET.ImGui.GetIO().DisplaySize;
if (display.X <= 1 || ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return;
Vector2 pos = ImGuiNET.ImGui.GetWindowPos();
Vector2 next = Vector2.Clamp(pos, Vector2.Zero, Vector2.Max(Vector2.Zero, display - ImGuiNET.ImGui.GetWindowSize()));
if (next != pos) ImGuiNET.ImGui.SetWindowPos(next);
}
private static void DrawContent(float s, float place, bool popped)
{
// Ctrl+wheel over the bar steps its size (the panels' title bars do the same).
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
if (io.KeyCtrl && io.MouseWheel != 0f && ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem))
PanelTextScale.SetChrome(PanelTextScale.GetChrome() + (io.MouseWheel > 0f ? 1 : -1));
var square = new Vector2(ButtonSize, ButtonSize) * s;
var dl = ImGuiNET.ImGui.GetWindowDrawList();
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14);
@ -280,12 +339,13 @@ internal static class ImGuiBar
if (display.X > 1)
next = Vector2.Clamp(next, Vector2.Zero, Vector2.Max(Vector2.Zero, display - size));
ImGuiNET.ImGui.SetWindowPos(next);
_userMoved = true;
}
ImGuiNET.ImGui.SetItemTooltip(_tooltip);
if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right))
ImGuiNET.ImGui.OpenPopup("##face_bar");
PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel);
FacePopup("##face_bar", FaceKey, hasImGuiFace: true);
FacePopup("##face_bar", FaceKey, hasImGuiFace: true, s);
// Collapse: the bar folds to its grip and this caret.
bool collapsed = RynthAiDashboardState.BarCollapsed;
@ -314,6 +374,21 @@ internal static class ImGuiBar
FacePopup(b.PopupId, b.Title, ImGuiPanelHost.HasFace(b.Title));
}
// The ILT section: one button, only on Infinite Leaftide with RynthILT's panels
// registered. With one panel it toggles that panel; with more it opens a menu.
int iltCount = IltPanelCount();
if (iltCount > 0)
{
ImGuiNET.ImGui.SameLine();
string? only = iltCount == 1 ? FirstIltPanel() : null;
if (IconButton("##ilt", iconFont, PhosphorIcons.Leaf, square, RynthTheme.BarText))
{
if (only != null) PanelRouter.Toggle(only);
else ImGuiNET.ImGui.OpenPopup("##ilt_menu");
}
ImGuiNET.ImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide");
}
// Script windows (decision 2): one button with a menu, only while a ShowInBar
// script window exists. They never get buttons of their own (EnsureButtons
// lists OverlayHost's engine panels only; script windows are dynamic entries).
@ -352,6 +427,44 @@ internal static class ImGuiBar
// Drawn after the bar buttons' style is popped, so the menu has the normal look.
ScriptsMenu(scripts);
IltMenu();
}
/// <summary>The ILT panels the bar offers now: 0 off Infinite Leaftide or without RynthILT. AC thread.</summary>
private static int IltPanelCount()
{
int n = 0;
foreach (string title in IltPanels)
if (ImGuiPanelHost.HasFace(title)) n++;
return n > 0 && IltInfo.IsIlt ? n : 0;
}
private static string? FirstIltPanel()
{
foreach (string title in IltPanels)
if (ImGuiPanelHost.HasFace(title)) return title;
return null;
}
/// <summary>The ILT button's menu (two or more ILT panels): a checkbox item each for open.</summary>
private static void IltMenu()
{
if (!ImGuiNET.ImGui.BeginPopup("##ilt_menu")) return;
try
{
ImGuiNET.ImGui.TextDisabled("Infinite Leaftide");
foreach (string title in IltPanels)
{
if (!ImGuiPanelHost.HasFace(title)) continue;
bool open = ImGuiPanelHost.IsOpen(title);
if (ImGuiNET.ImGui.MenuItem(title, "", open))
PanelRouter.Toggle(title);
}
}
finally
{
ImGuiNET.ImGui.EndPopup();
}
}
/// <summary>
@ -394,7 +507,7 @@ internal static class ImGuiBar
return clicked;
}
private static void FacePopup(string popupId, string title, bool hasImGuiFace)
private static void FacePopup(string popupId, string title, bool hasImGuiFace, float s = 1f)
{
if (!ImGuiNET.ImGui.BeginPopup(popupId)) return;
ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as");
@ -407,9 +520,59 @@ internal static class ImGuiBar
}
if (!hasImGuiFace)
ImGuiNET.ImGui.TextDisabled("(no ImGui version yet)");
if (title == FaceKey)
{
BarSizeRows(s);
ReportRow();
}
ImGuiNET.ImGui.EndPopup();
}
/// <summary>The bar's own popup: smaller / bigger, the current size, reset (the panels' text size popup, for the bar).</summary>
private static void BarSizeRows(float s)
{
int step = PanelTextScale.GetChrome();
int max = PanelTextScale.SizeNames.Length - 1;
float btn = ButtonSize * s;
ImFontPtr iconFont = ImGuiFonts.Get(UiFont.Ui14);
uint text = ImGuiNET.ImGui.GetColorU32(ImGuiCol.Text);
ImGuiNET.ImGui.Separator();
ImGuiNET.ImGui.TextUnformatted("Bar size");
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
ImGuiNET.ImGui.BeginDisabled(step <= 0);
if (IconButton("##bs_smaller", iconFont, PhosphorIcons.Minus, new Vector2(btn, btn), text))
PanelTextScale.SetChrome(step - 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Smaller");
ImGuiNET.ImGui.SameLine(0, 4 * s);
ImGuiNET.ImGui.BeginDisabled(step >= max);
if (IconButton("##bs_bigger", iconFont, PhosphorIcons.Plus, new Vector2(btn, btn), text))
PanelTextScale.SetChrome(step + 1);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Bigger");
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.SameLine(0, 8 * s);
ImGuiNET.ImGui.AlignTextToFramePadding();
ImGuiNET.ImGui.TextUnformatted(PanelTextScale.Describe(step));
ImGuiNET.ImGui.BeginDisabled(step == 0);
if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset"))
PanelTextScale.SetChrome(0);
ImGuiNET.ImGui.EndDisabled();
ImGuiNET.ImGui.SetItemTooltip("Back to normal size");
}
/// <summary>The grip menu's "Report a problem" entry (Report/ProblemReport.cs).</summary>
private static void ReportRow()
{
if (!ImGuiPanelHost.HasFace(Panels.ReportFace.Title)) return;
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.MenuItem(PhosphorIcons.Warning + " Report a problem..."))
Report.ProblemReport.OpenPanel();
ImGuiNET.ImGui.SetItemTooltip("Tell the staff what went wrong (also /rc report).");
}
private static void PushBarButtonStyle(float s)
{
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
@ -446,6 +609,6 @@ internal static class ImGuiBar
list.Add(new ButtonInfo(title, "##bar_" + title, "##face_" + title, icon, letter, title, ImGuiOnly: true));
}
_buttons = list.ToArray();
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face.";
_tooltip = $"RynthCore {EntryPoint.BuildStamp}\nDrag here to move the bar. Right-click: bar face and size. Ctrl+wheel over the bar: size.";
}
}

View file

@ -0,0 +1,30 @@
// ============================================================================
// RynthCore.Engine - ImGui/MonsterHud/CreatureSizes.cs
// How tall each kind of creature is, for the plates that hang above its head.
//
// The table (CreatureSizes.g.cs) is generated by tools/CreatureSizes from the ACE world database and
// client_portal.dat: weenie class id -> model height x default scale, in centimetres. A creature that is
// not in it (a custom weenie that was not exported, a model with no height) is unknown, and the HUD
// falls back to its estimate by creature type and name. Pure code; tools/CreatureSizesTests compiles it in.
// ============================================================================
using System;
namespace RynthCore.Engine.ImGuiBackend.Hud;
internal static partial class CreatureSizes
{
/// <summary>Creatures in the table.</summary>
public static int Count => Wcids.Length;
/// <summary>Metres from the creature's feet to the top of its model, for a weenie class id; false when the table has none.</summary>
public static bool TryGetTop(uint wcid, out float metres)
{
metres = 0f;
if (wcid > int.MaxValue) return false;
int i = Array.BinarySearch(Wcids, (int)wcid);
if (i < 0) return false;
metres = TopCm[i] / 100f;
return true;
}
}

File diff suppressed because it is too large Load diff

View file

@ -126,6 +126,10 @@ internal static class MonsterHud
/// <summary>RadarKind.Monster: a full monster plate. Npc / Vendor / Player: a name-only label.</summary>
public byte Kind = RadarKind.Monster;
public bool IsLabel => Kind != RadarKind.Monster;
/// <summary>A name label with a thin health bar under it (players, when "Player health bars" is on).</summary>
public bool WithBar;
public bool HpFresh; // the last health observation is recent enough to draw a bar from
public bool HasBar => WithBar && HpKnown && HpFresh;
public int Level; // 0 = unknown
public string LevelText = "";
public float HeadHeight = DefaultHeadHeight;
@ -177,6 +181,10 @@ internal static class MonsterHud
private sealed record WeakTag(string Label, uint Color, string Icon);
private const float DefaultHeadHeight = 2.0f;
// A player's health is only known from what the game happened to tell us; a reading older than this is not drawn.
private const long PlayerBarMemorySec = 90;
// A size from the table is the top of the model: a hand's width above it for the plate, within sane bounds.
private const float HeadMargin = 0.12f, MinKnownHeadHeight = 0.3f, MaxKnownHeadHeight = 120f;
private static readonly Dictionary<uint, Plate> Plates = new(64);
private static readonly List<Plate> DrawOrder = new(64);
private static readonly List<Plate> Placed = new(64);
@ -277,7 +285,7 @@ internal static class MonsterHud
bool monsters = MonsterHudSettings.Enabled;
bool trackMonsters = monsters || MonsterHudSettings.Numbers;
// Name-only labels over NPCs (and, if asked, players): their own switches and cap.
bool track = trackMonsters || MonsterHudSettings.NpcNames || MonsterHudSettings.PlayerNames;
bool track = trackMonsters || MonsterHudSettings.NpcNames || MonsterHudSettings.PlayerNames || MonsterHudSettings.PlayerBars;
if (!track) ClearPlates();
SetDamageSubscription(monsters && MonsterHudSettings.ShowWeakness);
if (monsters && MonsterHudSettings.ShowDebuffs) PortalSpellTable.EnsureLoadQueued();
@ -373,7 +381,8 @@ internal static class MonsterHud
float maxD2 = maxD * maxD;
float targetD2 = MathF.Max(maxD2, 100f * 100f); // the target keeps its plate a bit further out
bool engagedOnly = MonsterHudSettings.Filter == PlateFilter.Engaged && MonsterHudSettings.Enabled;
bool npcNames = MonsterHudSettings.NpcNames, playerNames = MonsterHudSettings.PlayerNames;
bool npcNames = MonsterHudSettings.NpcNames, playerBars = MonsterHudSettings.PlayerBars,
playerNames = MonsterHudSettings.PlayerNames || playerBars; // a bar comes with the name
float npcD = MonsterHudSettings.NpcMaxDistance;
float npcD2 = npcD * npcD;
float npcTargetD2 = MathF.Max(npcD2, 100f * 100f); // a selected NPC keeps its name further out too
@ -491,6 +500,7 @@ internal static class MonsterHud
byte cls = Classes.TryGetValue(id, out ObjClass oc) ? oc.Cls : ClsCreature;
byte kind = cls == ClsPlayer ? RadarKind.Player : cls == ClsVendor ? RadarKind.Vendor : RadarKind.Npc;
Plate plate = GetPlate(id, kind);
plate.WithBar = playerBars && kind == RadarKind.Player;
// Head height once per name; again while selected (selecting appraises: CreatureType may arrive).
if (name != plate.Name || isTarget)
{
@ -586,11 +596,16 @@ internal static class MonsterHud
/// <summary>
/// Metres from the feet to just above the head. The client's own model
/// height isn't read (its CPartArray/CSetup layout isn't mapped here), so
/// this goes by CreatureType from the appraisal cache, then by name, then
/// a humanoid default; "Height lift" in the settings corrects the rest.
/// this goes by the creature's weenie class id against the generated size
/// table (CreatureSizes: model height x scale), then CreatureType from the
/// appraisal cache, then by name, then a humanoid default; "Height lift"
/// in the settings corrects the rest.
/// </summary>
internal static float EstimateHeadHeight(uint id, string name)
{
if (ClientObjectHooks.TryGetObjectWcid(id, out uint wcid) && CreatureSizes.TryGetTop(wcid, out float top))
return Math.Clamp(top, MinKnownHeadHeight, MaxKnownHeadHeight) + HeadMargin;
if (AppraisalHooks.TryGetCachedIntProperty(id, 2, out int ct) && ct > 0 && ct < CreatureTypeHeights.Length &&
CreatureTypeHeights[ct] > 0)
return CreatureTypeHeights[ct];
@ -925,8 +940,8 @@ internal static class MonsterHud
// Appearing: start at the right size; visible: ease (target pop, distance).
p.Scale = wasVisible ? p.Scale + (scaleTarget - p.Scale) * kScale : scaleTarget;
// ── Health (monster plates only) ──
if (!label) UpdateHealth(p, f.Now, kBar, dt);
// ── Health (monster plates, and player labels with a bar) ──
if (!label || p.WithBar) UpdateHealth(p, f.Now, kBar, dt);
if (!show && p.Alpha < 0.01f)
{
@ -979,6 +994,7 @@ internal static class MonsterHud
if (MonsterHudData.TryGetHealth(p.Id, out HealthObservation h))
{
p.HpKnown = true;
p.HpFresh = (now - h.Ticks) < PlayerBarMemorySec * Stopwatch.Frequency;
p.Ratio = h.Ratio;
uint max = h.Max;
if (ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) && v.MaxHealth > 0)
@ -990,6 +1006,7 @@ internal static class MonsterHud
{
// Never observed: an untouched monster is at full health in practice.
p.HpKnown = false;
p.HpFresh = false;
p.Ratio = 1f;
p.HpMax = ObjectQualityCache.TryGetCreatureVitals(p.Id, out CreatureVitals v) ? v.MaxHealth : 0;
p.HpCur = p.HpMax;
@ -1043,10 +1060,20 @@ internal static class MonsterHud
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name);
p.BadgeW = 0f;
p.BarW = p.BarH = 0f;
p.IconSize = 0f;
p.BelowBar = p.IsTarget ? 9f * k : 3f * k; // the target pointer hangs under the name
p.Width = p.NameW + 8f * k;
if (p.HasBar)
{
// A thin bar under the name, at least the name's width.
p.BarW = MathF.Round(MathF.Max(p.NameW, 64f * k));
p.BarH = MathF.Max(3f, MathF.Round(4f * k));
}
else
{
p.BarW = p.BarH = 0f;
}
float barRow = p.BarH > 0f ? p.BarH + MathF.Round(2f * k) : 0f;
p.BelowBar = (p.IsTarget ? 9f * k : 3f * k) + barRow; // the target pointer hangs under the name (and bar)
p.Width = MathF.Max(p.NameW, p.BarW) + 8f * k;
p.Height = p.NameSize + 2f * k + p.BelowBar;
return;
}
@ -1329,6 +1356,16 @@ internal static class MonsterHud
float x = MathF.Round(cx - p.NameW * 0.5f);
float pointerTop = baseY + 2f * k;
if (p.BarH > 0f)
{
// The player's health under the name.
float barTop = MathF.Round(baseY + 2f * k);
float barL = MathF.Round(cx - p.BarW * 0.5f);
PaintBar(dl, new Vector2(barL, barTop), new Vector2(barL + p.BarW, barTop + p.BarH), MathF.Max(1f, 1.5f * k), a,
p.ShownRatio, p.TrailRatio, HealthColor(p.Ratio), ticks: false);
pointerTop = barTop + p.BarH + 2f * k;
}
if (p.Nudge > 10f * uiScale)
dl.AddLine(new Vector2(cx, pointerTop - 1), new Vector2(cx, p.Anchor.Y - 2f * k), Mul(Leader, a), 1f);

View file

@ -56,6 +56,8 @@ internal static class MonsterHudSettings
public static float NpcMaxDistance = 30f; // yards; short so a town isn't a wall of text
public static int MaxNpcLabels = 15;
public static bool PlayerNames = false;
/// <summary>A health bar under other players' names, for those whose health the client has been told (selected, fellowship).</summary>
public static bool PlayerBars = false;
// Debuff icons on the monster plates (PlateDebuffs).
public static bool ShowDebuffs = true;
@ -196,6 +198,7 @@ internal static class MonsterHudSettings
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
break;
case "playerNames": PlayerNames = val == "1"; break;
case "playerBars": PlayerBars = val == "1"; break;
case "showDebuffs": ShowDebuffs = val == "1"; break;
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
case "selfPlate": SelfPlate = val == "1"; break;
@ -277,6 +280,7 @@ internal static class MonsterHudSettings
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
sw.WriteLine($"playerNames={B(PlayerNames)}");
sw.WriteLine($"playerBars={B(PlayerBars)}");
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
sw.WriteLine($"selfPlate={B(SelfPlate)}");
@ -322,7 +326,7 @@ internal static class MonsterHudSettings
ShowNames = true; ShowHpNumbers = true; ShowDistance = false; ShowLevel = true; ShowWeakness = true;
FadeWithDistance = true; Scale = 1.0f; Opacity = 0.9f; HeightLift = 0f; ClickToSelect = true;
ShowDebuffs = true; ShowOthersDebuff = true;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false;
NpcNames = true; NpcMaxDistance = 30f; MaxNpcLabels = 15; PlayerNames = false; PlayerBars = false;
SelfPlate = true; SelfNumbers = false; SelfName = false; SelfHideFirstPerson = true;
SelfPlacement = SelfPlacement.Fixed; SelfLocked = true; SelfFixedX = DefaultSelfFixedX; SelfFixedY = DefaultSelfFixedY;
Numbers = true; NumDealt = true; NumTaken = true; NumHeals = true; NumKills = true;
@ -359,7 +363,7 @@ internal static class MonsterHudSettings
public static void SetAll(bool on)
{
Enabled = on; ShowDebuffs = on; SelfPlate = on; Numbers = on; Gains = on; NpcNames = on;
if (!on) PlayerNames = false; // "all on" leaves player names as chosen (off by default)
if (!on) { PlayerNames = false; PlayerBars = false; } // "all on" leaves player names and bars as chosen (off by default)
}
/// <summary>One line for chat: the current state.</summary>
@ -368,7 +372,7 @@ internal static class MonsterHudSettings
$"{MaxDistance:0}yd, max {MaxPlates}, scale {Scale:0.##}, opacity {Opacity:0.##}, lift {HeightLift:0.#}m; " +
$"names {OnOff(ShowNames)}, hp {OnOff(ShowHpNumbers)}, level {OnOff(ShowLevel)}, weak {OnOff(ShowWeakness)}, " +
$"distance {OnOff(ShowDistance)}, fade {OnOff(FadeWithDistance)}, click to select {OnOff(ClickToSelect)}), debuffs {OnOff(ShowDebuffs)} (others {OnOff(ShowOthersDebuff)}); " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)}; " +
$"NPC names {OnOff(NpcNames)} ({NpcMaxDistance:0}yd, max {MaxNpcLabels}), player names {OnOff(PlayerNames)} (bars {OnOff(PlayerBars)}); " +
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +
$"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " +
$"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " +

View file

@ -87,6 +87,9 @@ internal static class MonsterHudSettingsUi
"Text size of the names over NPCs and vendors (1.00x = the default). Names have no bar.");
changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames,
"The name over other players too (blue), within the same distance and count. Chat: /rv plates players.");
changed |= Toggle("Player health bars", ref MonsterHudSettings.PlayerBars,
"A health bar under other players' names (and their name, even with Player names off). The game only tells you a player's health " +
"once you select them or they share it (fellowship), so a bar shows from then on; others keep just the name. Chat: /rv plates playerbars.");
changed |= SizeSlider("Player name size", ref MonsterHudSettings.PlayerTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"Text size of the names over other players (1.00x = the default). Names have no bar.");
Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w);

View file

@ -0,0 +1,312 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/BountiesFace.cs
// ACECustom bounties: every active bounty on the server and this character's
// progress on each (kills, cooldown or QB requirement), from the RynthILT
// plugin's tracker (UI/Data/BountiesData.cs). Part of the ILT section: only
// registered when RynthILT is installed, opened from the bar's ILT button or
// "/rc bounties" on Infinite Leaftide only. ImGui-only. Ported from
// SilentKelpie's rynth/RynthCore PR #5.
//
// The plugin reads /bounty list (quietly) only while this face is shown on
// ILT: on open, a moment after each kill, after bounty chat events and every
// few minutes, never more than once per MinRefreshSeconds. Options, Hide
// QB-locked and Closest first live in the plugin (per character); the text
// filter is this face's own.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class BountiesFace : IImGuiPanel
{
public const string Title = "Bounties";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(560, 420), new Vector2(360, 220), EdgeToEdge: true),
() => new BountiesFace());
private const float RowH = 24, ProgressW = 160, FooterH = 18;
private const int MinRefreshFloor = 5, MinRefreshCeiling = 300, PeriodicCeiling = 60;
private static readonly uint OnBg = RynthTheme.Argb(0xFF104010), OnText = RynthTheme.Argb(0xFF33FF33);
private static readonly uint BarFill = RynthTheme.Argb(0xFF2E8C4A), BarChanged = RynthTheme.Argb(0xFF26C8D9),
BarTrack = RynthTheme.Argb(0xFF0E1A24);
private readonly byte[] _filter = new byte[64];
private bool _showOptions;
public void OnShown()
{
UiSources.Bounties.Subscribe();
UiSources.Bounties.RequestRefresh();
}
public void OnHidden() => UiSources.Bounties.Unsubscribe();
public void Draw()
{
// Off Infinite Leaftide the source stops polling; never show its last list there.
BountiesSnapshot? data = UiSources.Bounties.NotIlt ? null : UiSources.Bounties.Current?.Value;
float w = Begin(out Vector2 origin, out Vector2 size);
DrawToolbar(data, w);
if (data != null)
{
if (_showOptions) DrawOptions(data, w);
DrawFilterRow(data, w);
if (data.LastEvent.Length > 0)
{
Label(data.LastEvent + (data.LastEventAgoSec >= 0 ? " (" + Ago(data.LastEventAgoSec) + " ago)" : ""), Amber);
}
}
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0));
ImGuiNET.ImGui.BeginChild("##bounties_body", new Vector2(w, Math.Max(60, Remaining(origin, size) - FooterH - GripOverlap())));
float bw = ImGuiNET.ImGui.GetContentRegionAvail().X;
DrawBody(data, bw);
ImGuiNET.ImGui.EndChild();
ImGuiNET.ImGui.PopStyleVar();
ImGuiNET.ImGui.PopStyleColor();
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
Vector2 fp = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, fp + new Vector2(2, 3), Mute,
"Kills count in the bounty's own area only (XP/lum mobs you did the most damage to).");
End(origin, size);
}
// ── Header ───────────────────────────────────────────────────────────
private void DrawToolbar(BountiesSnapshot? data, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
bool ready = data != null;
if (Button("##bounty_refresh", PhosphorIcons.ArrowsClockwise + " Refresh", p, new Vector2(90, 22), Teal, BtnFill, ready))
BountiesCommands.Refresh();
string state = !ready
? (UiSources.Bounties.NotIlt ? "not Infinite Leaftide"
: UiSources.Bounties.ExportMissing ? "this RynthILT build has no bounty tracker" : "waiting for RynthILT (log in)")
: data!.Reading ? "reading /bounty list..."
: data.Status.Length > 0 ? data.Status
: data.ListedAgoSec < 0 ? "not read yet"
: "updated " + Ago(data.ListedAgoSec) + " ago";
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(p.X + 98, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, state);
Vector2 op = new(p.X + w - 26, p.Y);
if (IconButton("##bounty_opts", PhosphorIcons.Gear, op, new Vector2(24, 22), _showOptions ? Teal : Mute, _showOptions ? Selected : BtnFill, ready))
_showOptions = !_showOptions;
ImGuiNET.ImGui.SetItemTooltip("Options");
NextLine(p, 26);
}
private static void DrawOptions(BountiesSnapshot d, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 82), PanelBg, 3);
float ty = (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
float x = p.X + 6, y = p.Y + 4;
dl.AddText(new Vector2(x, y + ty), Text, "Update after my kills");
float bx = x + ImGuiNET.ImGui.CalcTextSize("Update after my kills").X + 8;
if (Button("##bounty_onkills", d.RefreshOnKills ? "ON" : "OFF", new Vector2(bx, y), new Vector2(50, 22),
d.RefreshOnKills ? OnText : Mute, d.RefreshOnKills ? OnBg : BtnFill))
BountiesCommands.Set("refreshonkills", !d.RefreshOnKills);
y += 26;
dl.AddText(new Vector2(x, y + ty), Text, "At most every (sec)");
int min = Spinner("##bounty_min", d.MinRefreshSeconds, MinRefreshFloor, MinRefreshCeiling, 5,
new Vector2(x + 150, y));
if (min != d.MinRefreshSeconds) BountiesCommands.Set("minrefreshseconds", min.ToString(CultureInfo.InvariantCulture));
y += 26;
dl.AddText(new Vector2(x, y + ty), Text, "Re-read every (min, 0 = off)");
int per = Spinner("##bounty_per", d.PeriodicRefreshMinutes, 0, PeriodicCeiling, 1,
new Vector2(x + 190, y));
if (per != d.PeriodicRefreshMinutes) BountiesCommands.Set("periodicminutes", per.ToString(CultureInfo.InvariantCulture));
ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9);
dl.AddText(f9, f9.FontSize, new Vector2(x + 310, p.Y + 8), Mute, "Reads run only while this\nwindow is open; the reply\nis hidden from chat.");
NextLine(p, 86);
}
private void DrawFilterRow(BountiesSnapshot d, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float filterW = Math.Clamp(w - 250, 120, 260);
TextBox("##bounty_filter", _filter, p, filterW, "filter by area or reward", out _);
float x = p.X + filterW + 6;
const string hideLabel = "Hide QB-locked";
float hw = ButtonWidth(hideLabel);
if (Button("##bounty_hideqb", hideLabel, new Vector2(x, p.Y), new Vector2(hw, 22),
d.HideQbLocked ? OnText : Mute, d.HideQbLocked ? OnBg : BtnFill))
BountiesCommands.Set("hideqblocked", !d.HideQbLocked);
if (d.HiddenCount > 0) ImGuiNET.ImGui.SetItemTooltip($"{d.HiddenCount} hidden");
x += hw + 4;
const string sortLabel = "Closest first";
if (Button("##bounty_sort", sortLabel, new Vector2(x, p.Y), new Vector2(ButtonWidth(sortLabel), 22),
d.SortByProgress ? OnText : Mute, d.SortByProgress ? OnBg : BtnFill))
BountiesCommands.Set("sortbyprogress", !d.SortByProgress);
ImGuiNET.ImGui.SetItemTooltip("Nearest to a reward first, then cooldowns, then QB-locked");
NextLine(p, 26);
}
// ── Rows ─────────────────────────────────────────────────────────────
private void DrawBody(BountiesSnapshot? d, float w)
{
if (d == null)
{
Empty(UiSources.Bounties.NotIlt ? "Bounties are an Infinite Leaftide feature (/rc ilt for why)."
: "Log in with RynthILT loaded to track bounties.", w);
return;
}
if (d.Unsupported) { Empty("This server has no /bounty command. Press Refresh to check again.", w); return; }
if (d.Rows.Count == 0)
{
Empty(d.NoneAnywhere ? "No bounties are active anywhere right now."
: d.HiddenCount > 0 ? "Every bounty is QB-locked (Hide QB-locked is on)."
: d.Reading ? "Reading the server's bounties..."
: "No bounties read yet. Press Refresh.", w);
return;
}
float areaW = (w - ProgressW) * 0.42f, rewardW = w - ProgressW - areaW;
TableHeader(areaW, rewardW, w);
string filter = Utf8(_filter).Trim();
int shown = 0;
for (int i = 0; i < d.Rows.Count; i++)
{
BountyRowJson r = d.Rows[i];
if (filter.Length > 0 && !r.Where.Contains(filter, StringComparison.OrdinalIgnoreCase)
&& !r.Item.Contains(filter, StringComparison.OrdinalIgnoreCase)) continue;
ImGuiNET.ImGui.PushID(i);
DrawRow(r, shown++, areaW, rewardW, w);
ImGuiNET.ImGui.PopID();
}
if (shown == 0) Empty("No bounty matches the filter.", w);
}
private static void TableHeader(float areaW, float rewardW, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, 22), Selected);
ImFontPtr bold = ImGuiFonts.Get(UiFont.UiBold11);
float ty = p.Y + (22 - bold.FontSize) * 0.5f;
dl.AddText(bold, bold.FontSize, new Vector2(p.X + 6, ty), Text, "Area");
dl.AddText(bold, bold.FontSize, new Vector2(p.X + areaW + 6, ty), Text, "Reward");
dl.AddText(bold, bold.FontSize, new Vector2(p.X + areaW + rewardW + 6, ty), Text, "Progress");
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
private static void DrawRow(BountyRowJson r, int index, float areaW, float rewardW, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRectFilled(p, p + new Vector2(w, RowH), index % 2 == 0 ? RowAlt : PanelBg);
float ty = p.Y + (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.PushClipRect(p, p + new Vector2(areaW - 4, RowH), true);
dl.AddText(new Vector2(p.X + 6, ty), Text, r.Where);
dl.PopClipRect();
float rx = p.X + areaW;
dl.PushClipRect(new Vector2(rx, p.Y), new Vector2(rx + rewardW - 4, p.Y + RowH), true);
dl.AddText(new Vector2(rx + 6, ty), Text, N0(r.Amount) + " " + r.Item);
dl.PopClipRect();
float px = rx + rewardW;
var status = (BountyRowStatus)r.Status;
switch (status)
{
case BountyRowStatus.Counting:
{
Vector2 b0 = new(px + 4, p.Y + 4), b1 = new(p.X + w - 6, p.Y + RowH - 4);
float frac = r.KillsRequired > 0 ? Math.Clamp(r.Kills / (float)r.KillsRequired, 0f, 1f) : 0f;
dl.AddRectFilled(b0, b1, BarTrack, 3);
if (frac > 0) dl.AddRectFilled(b0, new Vector2(b0.X + (b1.X - b0.X) * frac, b1.Y), r.Changed ? BarChanged : BarFill, 3);
dl.AddRect(b0, b1, BtnBord, 3);
string text = N0(r.Kills) + " / " + N0(r.KillsRequired);
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(text);
dl.AddText(new Vector2((b0.X + b1.X - ts.X) * 0.5f, ty), Text, text);
break;
}
case BountyRowStatus.Cooldown:
dl.AddText(new Vector2(px + 6, ty), Amber, "unlocks in " + Ago(r.UnlockInSec));
break;
default:
dl.AddText(new Vector2(px + 6, ty), Mute, "needs " + Compact(r.QbRequired) + " QB");
break;
}
ImGuiNET.ImGui.SetCursorScreenPos(p);
ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, RowH));
if (ImGuiNET.ImGui.IsItemHovered())
{
string every = $"Every {N0(r.KillsRequired)} kill(s)"
+ (r.CooldownSeconds > 0 ? ", at most every " + Ago(r.CooldownSeconds) : "");
string detail = status switch
{
BountyRowStatus.Cooldown => $"\nKills don't count for {Ago(r.UnlockInSec)}; after that {N0(r.KillsRequired)} kill(s).",
BountyRowStatus.NeedsQb => $"\nNeeds {N0(r.QbRequired)} QB; you have {N0(r.QbHave)}.",
_ => string.Empty,
};
ImGuiNET.ImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}");
}
NextLine(p, RowH);
}
private static void Empty(string message, float w)
{
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.GetWindowDrawList().AddRectFilled(p, p + new Vector2(w, 22), RowAlt);
ImGuiNET.ImGui.GetWindowDrawList().AddText(p + new Vector2(8, (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, message);
ImGuiNET.ImGui.Dummy(new Vector2(w, 22));
}
/// <summary>[-] value [+]; returns the new value (same when nothing was clicked).</summary>
private static int Spinner(string id, int value, int min, int max, int step, Vector2 pos)
{
int v = value;
ImGuiNET.ImGui.PushID(id);
if (IconButton("##dec", PhosphorIcons.Minus, pos, new Vector2(22, 22), Teal, BtnFill)) v = Math.Max(min, v - step);
string text = v.ToString(CultureInfo.InvariantCulture);
float tw = ImGuiNET.ImGui.CalcTextSize(text).X;
ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + 24 + (40 - tw) * 0.5f, pos.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Text, text);
if (IconButton("##inc", PhosphorIcons.Plus, new Vector2(pos.X + 66, pos.Y), new Vector2(22, 22), Teal, BtnFill)) v = Math.Min(max, v + step);
ImGuiNET.ImGui.PopID();
return v;
}
// ── Formatting ───────────────────────────────────────────────────────
private static string N0(long v) => v.ToString("N0", CultureInfo.InvariantCulture);
/// <summary>1.2M, 350k, 900.</summary>
private static string Compact(long v) =>
v >= 1_000_000 ? (v / 1_000_000d).ToString("0.#", CultureInfo.InvariantCulture) + "M"
: v >= 10_000 ? (v / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k"
: N0(v);
/// <summary>"45 sec", "2 min 30 sec", "1 hr 5 min", "2 days 3 hr".</summary>
private static string Ago(int seconds)
{
long s = Math.Max(0, seconds);
if (s >= 86400) return $"{s / 86400} day{(s / 86400 == 1 ? "" : "s")}" + (s % 86400 >= 3600 ? $" {s % 86400 / 3600} hr" : "");
if (s >= 3600) return $"{s / 3600} hr" + (s % 3600 >= 60 ? $" {s % 3600 / 60} min" : "");
if (s >= 60) return $"{s / 60} min" + (s % 60 > 0 ? $" {s % 60} sec" : "");
return $"{s} sec";
}
}

View file

@ -0,0 +1,485 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ChatDiscordFace.cs
// The Discord panel: everything about copying chat to Discord
// (UI/Data/Discord/ChatDiscord.cs). Opened from the Chat panel's gear menu
// (Discord settings...) or /rc discord window.
//
// Routes one tab per destination: webhook URL, or bot token + channel ID;
// which speech channels and which chat tabs it gets, keywords,
// and optionally its own pacing; Send test / Resume
// Settings who relays (the characters it's on for, your own lines, hidden lines),
// the message format, and the default pacing and limits
// Log messages sent, rate limits and errors
//
// Settings fields are edited in place (single-value writes the pump
// tolerates); adding or removing a route replaces the Routes array, and a
// route's tab list is replaced too. Each change saves (ChatDiscord.Save, on
// the background writer). Secrets go to ChatDiscord, which encrypts them off
// this thread; the box is cleared at once and the text is never shown again.
// AC's render thread only.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
using RynthCore.Engine.UI.Data.Discord;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ChatDiscordFace : IImGuiPanel
{
public const string Title = "Discord";
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(560, 520), new Vector2(420, 300)),
() => new ChatDiscordFace());
private string _secretInput = string.Empty;
private string _secretMessage = string.Empty;
private bool _secretMessageIsError;
private DiscordRoute? _secretFor;
private DiscordRoute? _confirmRemove;
private int _lastLogCount;
public void OnShown()
{
ChatModel.EnsureSettingsLoaded();
ChatDiscord.EnsureLoaded();
ChatDiscord.PanelShown(true);
}
public void OnHidden()
{
_confirmRemove = null;
ChatDiscord.PanelShown(false);
}
public void Draw()
{
var s = ChatDiscord.Settings;
DrawSwitch();
ImGuiNET.ImGui.SameLine();
Label("| " + ChatDiscord.StatusLine(), Mute);
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.BeginTabBar("##dc_tabs"))
{
if (ImGuiNET.ImGui.BeginTabItem("Routes")) { DrawRoutes(s); ImGuiNET.ImGui.EndTabItem(); }
if (ImGuiNET.ImGui.BeginTabItem("Settings")) { DrawSettings(s); ImGuiNET.ImGui.EndTabItem(); }
if (ImGuiNET.ImGui.BeginTabItem("Log")) { DrawLog(); ImGuiNET.ImGui.EndTabItem(); }
ImGuiNET.ImGui.EndTabBar();
}
}
/// <summary>
/// This character's switch (the relay is off for every character until each is switched on).
/// Shared by the Chat panel's gear menu.
/// </summary>
internal static void DrawSwitch()
{
DiscordCharacter? me = ChatDiscord.CurrentCharacter();
bool on = ChatDiscord.IsOn(me);
ImGuiNET.ImGui.BeginDisabled(me == null);
if (ImGuiNET.ImGui.Checkbox("Copy this character's chat to Discord##dc_on", ref on)) ChatDiscord.SetEnabled(on);
ImGuiNET.ImGui.EndDisabled();
if (me == null)
ImGuiNET.ImGui.SetItemTooltip("Log in first: the relay is switched on for one character at a time.");
else
ImGuiNET.ImGui.SetItemTooltip("On for this character only; every other character stays off until it's switched on too.\n" +
"Off: nothing from this character is queued or sent (Send test still works).");
}
// ── Routes ───────────────────────────────────────────────────────────
private void DrawRoutes(ChatDiscordSettings s)
{
if (ImGuiNET.ImGui.SmallButton("Add route"))
{
var r = new DiscordRoute { Name = $"Route {s.Routes.Length + 1}" };
ChatDiscordStore.NormalizeRoute(r);
s.Routes = new List<DiscordRoute>(s.Routes) { r }.ToArray();
ChatDiscord.Save();
}
ImGuiNET.ImGui.SetItemTooltip("A route is one Discord channel and the chat it receives.");
if (s.Routes.Length == 0)
{
ImGuiNET.ImGui.Spacing();
Wrapped("No routes yet. Add one, then paste a webhook URL from Discord: Server Settings > Integrations > "
+ "Webhooks > New Webhook > pick the channel > Copy Webhook URL.", Text);
return;
}
if (!ImGuiNET.ImGui.BeginTabBar("##dc_routes", ImGuiTabBarFlags.FittingPolicyScroll)) return;
DiscordRoute? remove = null;
for (int i = 0; i < s.Routes.Length; i++)
{
DiscordRoute r = s.Routes[i];
string label = (r.Status?.Paused == true ? "! " : r.Enabled ? "" : "(off) ") + r.Name + "###dc_route" + i;
if (!ImGuiNET.ImGui.BeginTabItem(label)) continue;
ImGuiNET.ImGui.PushID(i);
if (DrawRoute(s, r)) remove = r;
ImGuiNET.ImGui.PopID();
ImGuiNET.ImGui.EndTabItem();
}
ImGuiNET.ImGui.EndTabBar();
if (remove != null)
{
var list = new List<DiscordRoute>(s.Routes);
list.Remove(remove);
s.Routes = list.ToArray();
if (ReferenceEquals(_secretFor, remove)) ClearSecretBox(null);
ChatDiscord.Save();
}
}
/// <summary>One route's editor; true when the player asked to remove it.</summary>
private bool DrawRoute(ChatDiscordSettings s, DiscordRoute r)
{
if (!ReferenceEquals(_secretFor, r)) ClearSecretBox(r);
DiscordRouteStatus? st = r.Status;
if (st != null)
{
if (st.Paused) Wrapped("Paused: " + st.LastError, Red);
else if (st.LastError.Length > 0) Wrapped("Last problem: " + st.LastError, Amber);
Label($"{st.MessagesSent} message(s), {st.LinesSent} line(s) sent, {st.Queued} queued, {st.Dropped} dropped"
+ (st.LastSent != default ? $", last {st.LastSent:HH:mm:ss}" : string.Empty), Mute);
}
if (ImGuiNET.ImGui.Checkbox("Enabled##r_on", ref r.Enabled)) ChatDiscord.Save();
ImGuiNET.ImGui.SameLine();
ImGuiNET.ImGui.SetNextItemWidth(200f);
string name = r.Name;
if (Input("Name##r_name", "route name", ref name, 40)) r.Name = name;
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit())
{
if (string.IsNullOrWhiteSpace(r.Name)) r.Name = "Discord";
ChatDiscord.Save();
}
// Connection
Heading("Connection");
int mode = Math.Max(0, Array.IndexOf(DiscordRoute.Modes, r.Mode));
ImGuiNET.ImGui.SetNextItemWidth(220f);
if (ImGuiNET.ImGui.Combo("Send with##r_mode", ref mode, DiscordRoute.ModeNames, DiscordRoute.ModeNames.Length))
{
r.Mode = DiscordRoute.Modes[mode];
ClearSecretBox(r);
ChatDiscord.Resume(r);
ChatDiscord.Save();
}
ImGuiNET.ImGui.SetItemTooltip("Webhook: simplest, one URL per channel, posts under any name.\n"
+ "Bot: your own Discord bot posts it (it must be in the server with Send Messages there).");
bool bot = r.Mode == DiscordRoute.ModeBot;
bool saved = bot ? r.BotTokenProtected.Length > 0 : r.WebhookProtected.Length > 0;
ImGuiNET.ImGui.SetNextItemWidth(330f);
Input((bot ? "Bot token" : "Webhook URL") + "##r_secret",
saved ? "saved (paste a new one to replace it)" : bot ? "paste the bot token" : "https://discord.com/api/webhooks/...",
ref _secretInput, 512, ImGuiInputTextFlags.Password);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Save##r_secret_save") && _secretInput.Trim().Length > 0)
{
string err = bot ? ChatDiscord.SetBotToken(r, _secretInput) : ChatDiscord.SetWebhook(r, _secretInput);
_secretInput = string.Empty;
_secretMessageIsError = err.Length > 0;
_secretMessage = err.Length > 0 ? err : "Saved, encrypted for this Windows user. Use Send test to check it.";
}
if (saved)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Clear##r_secret_clear"))
{
if (bot) r.BotTokenProtected = string.Empty; else r.WebhookProtected = string.Empty;
_secretMessage = "Cleared.";
_secretMessageIsError = false;
ChatDiscord.Save();
}
}
if (_secretMessage.Length > 0) Wrapped(_secretMessage, _secretMessageIsError ? Red : Green);
if (bot)
{
ImGuiNET.ImGui.SetNextItemWidth(200f);
string chId = r.ChannelId;
if (Input("Channel ID##r_chid", "e.g. 123456789012345678", ref chId, 24, ImGuiInputTextFlags.CharsDecimal))
{
r.ChannelId = chId.Trim();
ChatDiscord.Resume(r);
}
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Discord: User Settings > Advanced > Developer Mode on, then right-click the channel > Copy Channel ID.");
if (r.ChannelId.Length > 0 && !DiscordFormat.IsSnowflake(r.ChannelId))
Label("A channel ID is 15-22 digits.", Red);
}
else
{
ImGuiNET.ImGui.SetNextItemWidth(200f);
Input("Post as##r_name_as", "character name", ref r.DisplayName, 80);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Name shown on the webhook's messages. Blank uses the character's name.\n"
+ "Discord refuses names containing \"discord\" or \"clyde\"; those fall back to the webhook's own name.");
}
if (ImGuiNET.ImGui.Button("Send test##r_test")) ChatDiscord.SendTest(r);
ImGuiNET.ImGui.SetItemTooltip("Posts one test line to this route now (also clears a pause).");
if (st?.Paused == true)
{
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.Button("Resume##r_resume")) ChatDiscord.Resume(r);
}
DrawSpeech(r);
DrawTabs(r);
Heading("Filter");
ImGuiNET.ImGui.SetNextItemWidth(330f);
Input("Keywords##r_kw", "blank = every line; e.g. rare, Asheron", ref r.Keywords, 300);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Comma-separated. When set, only lines containing one of these words (any case) are relayed.");
Heading("How often");
if (ImGuiNET.ImGui.Checkbox("Own pacing for this route##r_pace", ref r.CustomPace)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Off: the route uses the pacing on the Settings tab.");
if (r.CustomPace)
DrawPacing(ref r.BatchMs, ref r.MinIntervalMs, "##r");
else
Label($"Using the default: batch {s.BatchMs / 1000.0:0.#} s, at most one message every {s.MinIntervalMs / 1000.0:0.#} s.", Mute);
ImGuiNET.ImGui.Spacing();
ImGuiNET.ImGui.Separator();
bool remove = false;
if (ReferenceEquals(_confirmRemove, r))
{
// The saved webhook URL / bot token goes with the route; there's no undo.
Label("Delete this route and its saved credential?", Amber);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Delete##r_remove_yes"))
{
remove = true;
_confirmRemove = null;
}
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Cancel##r_remove_no")) _confirmRemove = null;
}
else
{
if (ImGuiNET.ImGui.SmallButton("Remove route##r_remove")) _confirmRemove = r;
ImGuiNET.ImGui.SetItemTooltip("Deletes this route and its saved credential (asks first).");
}
return remove;
}
private static void DrawSpeech(DiscordRoute r)
{
Heading("Speech channels");
if (ImGuiNET.ImGui.SmallButton("All##sp_all")) SetSpeech(r, DiscordRoute.AllSpeechMask());
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("None##sp_none")) SetSpeech(r, 0);
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Defaults##sp_def")) SetSpeech(r, DiscordRoute.DefaultSpeechMask());
ImGuiNET.ImGui.SameLine();
Label("what players say, by channel", Mute);
if (!ImGuiNET.ImGui.BeginTable("##sp_grid", 4, ImGuiTableFlags.SizingStretchSame)) return;
foreach (SpeechChannel ch in ChatSpeech.All)
{
ImGuiNET.ImGui.TableNextColumn();
uint bit = ChatSpeech.Bit(ch);
bool ticked = (r.SpeechMask & bit) != 0;
if (ImGuiNET.ImGui.Checkbox(ChatSpeech.Name(ch) + "##sp" + (int)ch, ref ticked))
SetSpeech(r, ticked ? r.SpeechMask | bit : r.SpeechMask & ~bit);
if (ch == SpeechChannel.Local) ImGuiNET.ImGui.SetItemTooltip("Local speech includes every NPC and player near you; it can be busy.");
}
ImGuiNET.ImGui.EndTable();
}
private static void SetSpeech(DiscordRoute r, uint mask)
{
r.SpeechMask = mask;
ChatDiscord.Save();
}
/// <summary>Chat tabs: every line that shows in a ticked tab goes, whatever it is.</summary>
private static void DrawTabs(DiscordRoute r)
{
Heading("Chat tabs");
Label("every line that shows in the tab (System, Combat, or tabs your chat rules fill)", Mute);
string[] all = ChatModel.AllTabs();
var shown = new List<string>(all);
foreach (string t in r.Tabs)
if (!shown.Exists(x => string.Equals(x, t, StringComparison.OrdinalIgnoreCase))) shown.Add(t);
if (!ImGuiNET.ImGui.BeginTable("##tab_grid", 4, ImGuiTableFlags.SizingStretchSame)) return;
for (int i = 0; i < shown.Count; i++)
{
string tab = shown[i];
ImGuiNET.ImGui.TableNextColumn();
bool ticked = Array.Exists(r.Tabs, t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase));
bool missing = Array.IndexOf(all, tab) < 0;
if (ImGuiNET.ImGui.Checkbox((missing ? tab + " (gone)" : tab) + "##tab" + i, ref ticked))
{
var list = new List<string>(r.Tabs);
list.RemoveAll(t => string.Equals(t, tab, StringComparison.OrdinalIgnoreCase));
if (ticked) list.Add(tab);
r.Tabs = list.ToArray();
ChatDiscord.Save();
}
if (tab == "All") ImGuiNET.ImGui.SetItemTooltip("Every line in the All tab: very busy. Pair it with keywords.");
else if (missing) ImGuiNET.ImGui.SetItemTooltip("This tab no longer exists; untick it to drop it.");
}
ImGuiNET.ImGui.EndTable();
}
private void ClearSecretBox(DiscordRoute? forRoute)
{
_secretFor = forRoute;
_secretInput = string.Empty;
_secretMessage = string.Empty;
_secretMessageIsError = false;
}
// ── Settings ─────────────────────────────────────────────────────────
private static void DrawSettings(ChatDiscordSettings s)
{
Heading("Who relays");
Label(ChatDiscord.SwitchLine(), Text);
DiscordCharacter[] on = s.Characters;
if (on.Length == 0)
Label("Off for every character.", Mute);
else
{
Label("On for:", Mute);
DiscordCharacter? me = ChatDiscord.CurrentCharacter();
for (int i = 0; i < on.Length; i++)
{
DiscordCharacter c = on[i];
ImGuiNET.ImGui.PushID(i);
if (ImGuiNET.ImGui.SmallButton("Turn off##s_char_off")) ChatDiscord.TurnOffFor(c);
ImGuiNET.ImGui.SameLine();
Label(c.ToString() + (c.Same(me) ? " (this client)" : string.Empty), c.Same(me) ? Green : Text);
ImGuiNET.ImGui.PopID();
}
}
Wrapped("Each character is switched on by itself (the checkbox at the top while you play it, or /rc discord on). "
+ "With several clients in one allegiance or fellowship, switch on just one of them so each line is posted once.", Mute);
if (ImGuiNET.ImGui.Checkbox("Skip lines I type##s_own", ref s.SkipOwn)) ChatDiscord.Save();
if (ImGuiNET.ImGui.Checkbox("Skip lines my chat rules hide##s_hidden", ref s.SkipHidden)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines a Hide rule or standard filter hides in the chat aren't sent either.");
Heading("Message format");
if (ImGuiNET.ImGui.Checkbox("Timestamp (HH:mm:ss)##s_ts", ref s.IncludeTimestamp)) ChatDiscord.Save();
if (ImGuiNET.ImGui.Checkbox("Start lines with [Character]##s_tag", ref s.TagCharacter)) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Useful when several characters post into the same Discord channel.");
Heading("How often (default for every route)");
DrawPacing(ref s.BatchMs, ref s.MinIntervalMs, "##s");
Heading("Limits");
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderInt("Queue limit (lines)##s_queue", ref s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax))
s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines waiting per route; past this the oldest are dropped.");
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderInt("Log size##s_log", ref s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax))
s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.Spacing();
Wrapped("Routes and settings are shared by every client and character (%AppData%\\RynthCore\\rynthchat_discord.json); "
+ "the on / off switch is per character. Webhook URLs and bot tokens "
+ "are encrypted for this Windows user; on another PC or user they must be pasted again.", Mute);
Wrapped("Relayed text never pings: @everyone, @here and user mentions are sent as plain text, and links don't unfurl.", Mute);
}
/// <summary>Batch window and message spacing sliders (seconds on screen, ms stored).</summary>
private static void DrawPacing(ref int batchMs, ref int intervalMs, string id)
{
float batch = batchMs / 1000f;
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderFloat("Batch window" + id + "_batch", ref batch, ChatDiscordSettings.BatchMinMs / 1000f,
ChatDiscordSettings.BatchMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic))
batchMs = Math.Clamp((int)MathF.Round(batch * 1000f), ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Lines arriving this close together go out as one Discord message.\n"
+ "Longer = fewer, bigger messages (a digest); 0 = each line as soon as allowed.");
float interval = intervalMs / 1000f;
ImGuiNET.ImGui.SetNextItemWidth(200f);
if (ImGuiNET.ImGui.SliderFloat("At most one message every" + id + "_interval", ref interval, ChatDiscordSettings.IntervalMinMs / 1000f,
ChatDiscordSettings.IntervalMaxMs / 1000f, "%.1f s", ImGuiSliderFlags.Logarithmic))
intervalMs = Math.Clamp((int)MathF.Round(interval * 1000f), ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) ChatDiscord.Save();
ImGuiNET.ImGui.SetItemTooltip("Spacing between messages to one route. Discord allows about 30 a minute per channel;\n"
+ "2 s stays under it. Lines that arrive meanwhile wait and go in the next message.");
Label($"Up to {60000.0 / Math.Max(1, intervalMs):0.#} messages a minute per route.", Mute);
}
// ── Log ──────────────────────────────────────────────────────────────
private void DrawLog()
{
DiscordLogEntry[] log = ChatDiscord.LogSnapshot();
if (ImGuiNET.ImGui.SmallButton("Clear##log_clear")) ChatDiscord.ClearLog();
ImGuiNET.ImGui.SameLine();
Label($"{log.Length} entries", Mute);
if (!ImGuiNET.ImGui.BeginChild("##dc_log", new Vector2(0, 0), ImGuiChildFlags.Borders)) { ImGuiNET.ImGui.EndChild(); return; }
foreach (DiscordLogEntry e in log)
{
uint col = e.Kind switch { DiscordLogKind.Sent => Green, DiscordLogKind.Error => Red, _ => Amber };
Label(e.Time.ToString("HH:mm:ss"), Mute);
ImGuiNET.ImGui.SameLine();
Label(e.Route, col);
ImGuiNET.ImGui.SameLine();
// Relayed chat and Discord's replies: never a format string (see Wrapped).
WrappedUnformatted(e.Text);
}
// Follow new lines unless the player scrolled up.
if (log.Length != _lastLogCount && ImGuiNET.ImGui.GetScrollY() >= ImGuiNET.ImGui.GetScrollMaxY() - 20f)
ImGuiNET.ImGui.SetScrollHereY(1f);
_lastLogCount = log.Length;
ImGuiNET.ImGui.EndChild();
}
// ── Helpers ──────────────────────────────────────────────────────────
private static void Heading(string text)
{
ImGuiNET.ImGui.Spacing();
Label(text, Teal);
}
/// <summary>
/// Wrapped text in <paramref name="color"/>. ImGui.NET's TextWrapped / Text / TextColored pass
/// their string to ImGui as a printf format, so chat or an error Discord sent back holding
/// "%s" would crash the client. Everything here goes through TextUnformatted.
/// </summary>
private static void Wrapped(string text, uint color)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
WrappedUnformatted(text);
ImGuiNET.ImGui.PopStyleColor();
}
private static void WrappedUnformatted(string text)
{
ImGuiNET.ImGui.PushTextWrapPos(0f);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
}
/// <summary>A text box that keeps the keyboard from AC while it's being typed in.</summary>
private static bool Input(string label, string hint, ref string value, uint maxLength,
ImGuiInputTextFlags flags = ImGuiInputTextFlags.None)
{
bool changed = ImGuiNET.ImGui.InputTextWithHint(label, hint, ref value, maxLength, flags);
if (ImGuiNET.ImGui.IsItemActive()) ImGuiTextFocus.NoteActive(label);
return changed;
}
}

View file

@ -900,7 +900,7 @@ internal sealed class ChatFace : IImGuiPanel
ChatModel.LogEnabled = log;
ChatModel.SaveSettings();
}
ImGuiNET.ImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\<character>.log");
ImGuiNET.ImGui.SetItemTooltip("%%AppData%%\\RynthCore\\ChatLogs\\<character>.log"); // a format string: %% is a literal %
bool through = ChatModel.CtrlGatedClickThrough;
if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through))
ChatModel.SetCtrlGatedClickThrough(through);
@ -934,6 +934,8 @@ internal sealed class ChatFace : IImGuiPanel
ChatModel.SaveSettings();
}
}
// Discord above the colours: the colour grid opens downward, so it stays last.
DrawDiscordSettings();
ImGuiNET.ImGui.Separator();
if (ImGuiNET.ImGui.CollapsingHeader("Line colours")) DrawLineColours();
@ -1024,6 +1026,25 @@ internal sealed class ChatFace : IImGuiPanel
ImGuiNET.ImGui.PopID();
}
/// <summary>
/// Settings menu: this character's Discord relay switch, its status and the way into the
/// Discord panel, in two compact rows like the rest of the menu.
/// </summary>
private static void DrawDiscordSettings()
{
ImGuiNET.ImGui.Separator();
ChatDiscordFace.DrawSwitch();
ImGuiNET.ImGui.SameLine();
if (ImGuiNET.ImGui.SmallButton("Discord…##chat_discord"))
{
if (!ImGuiPanelHost.IsOpen(ChatDiscordFace.Title)) PanelRouter.Toggle(ChatDiscordFace.Title);
ImGuiNET.ImGui.CloseCurrentPopup();
}
ImGuiNET.ImGui.SetItemTooltip("Discord panel: connection (webhook or bot), which channels and tabs go where,\n" +
"keywords, how often, and the send log.");
Label(UI.Data.Discord.ChatDiscord.SwitchLine() + " " + UI.Data.Discord.ChatDiscord.StatusLine(), Mute);
}
private void DrawNewTabPopup()
{
if (!ImGuiNET.ImGui.BeginPopup("##chat_newtab"))

View file

@ -269,9 +269,11 @@ internal sealed class LootAddDialog
}
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip(
"Also require this item's T11 tier, weapon grade, damage %, every modifier, slot special\n" +
"and Cast on Strike, each at least as good as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character) and Zone Locked (depends on where it was assessed).");
"Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" +
"damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" +
"as this one. Works with any match.\n" +
"Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" +
"and property slots / Tainted (bag state, not quality).");
if (!d.IsT11)
{
ImGuiNET.ImGui.SameLine();

View file

@ -40,6 +40,9 @@ internal static class P1Faces
// items to use): ImGui only, saved per character in item_huds.txt.
ItemCountFace.Register();
MiniRemoteFace.Register();
// Report a problem (Report/ProblemReport.cs): ImGui only, opened from the bar's grip
// menu, Settings and /rc report (no bar button of its own).
ReportFace.Register();
}
}

View file

@ -0,0 +1,241 @@
// ============================================================================
// RynthCore.Engine - ImGui/Panels/ReportFace.cs
// The "Report a problem" panel (Report/ProblemReport.cs). ImGui only.
//
// What went wrong? required, 2,500 bytes of UTF-8 at most
// What were you doing? optional, 1,500 bytes
// [x] Attach my recent RynthCore log ticked each time the panel opens
// its size, View (opens exactly what will be sent) and Refresh
// what else is sent, the Send button and the result
//
// Opened from the bar's grip menu, Settings' sidebar and /rc report. Draw reads
// ProblemReport's state and calls Send / RefreshTail / ViewTail, which do their
// work off AC's thread. The log tail is read when the panel opens (and on
// Refresh); Send sends that same tail, so what View showed is what goes.
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using System.Text;
using ImGuiNET;
using RynthCore.Engine.Report;
using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit;
namespace RynthCore.Engine.ImGuiBackend.Panels;
internal sealed class ReportFace : IImGuiPanel
{
public const string Title = ProblemReport.PanelTitle;
public static void Register() => ImGuiPanelHost.Register(Title,
new PanelSpec(new Vector2(390, 490), new Vector2(300, 440), EdgeToEdge: true, GripInBody: true),
() => new ReportFace());
private const string DescId = "##report_desc", DoingId = "##report_doing";
private static readonly byte[] DescLabel = Encoding.UTF8.GetBytes(DescId + "\0");
private static readonly byte[] DoingLabel = Encoding.UTF8.GetBytes(DoingId + "\0");
private readonly byte[] _desc = new byte[ProblemReportCore.MaxDescriptionBytes + 1];
private readonly byte[] _doing = new byte[ProblemReportCore.MaxDoingBytes + 1];
private bool _attachLog = true;
private long _messageSeqAtOpen;
private long _resultSeqAtSend = -1; // >= 0 while a send this panel started is out
private string _localError = "";
private LogTail? _describedTail; // the tail _tailText describes (built when the tail changes, not per frame)
private string _tailText = "";
private static readonly string LogToggleLabel =
$"Attach my recent RynthCore log (last {ProblemReportCore.TailLines:N0} lines)";
public void OnShown()
{
_attachLog = true; // ticked by default, every time
_localError = "";
_messageSeqAtOpen = ProblemReport.MessageSeq;
ProblemReport.RefreshTail();
}
public void Draw()
{
// A send this panel started finished: clear the form when it was taken.
if (_resultSeqAtSend >= 0 && ProblemReport.ResultSeq != _resultSeqAtSend)
{
if (ProblemReport.State == ReportState.Sent)
{
WriteUtf8(_desc, "");
WriteUtf8(_doing, "");
}
_resultSeqAtSend = -1;
}
float w = Begin(out Vector2 origin, out Vector2 size);
Label("What went wrong? (required)", Text);
MultiLine(DescId, DescLabel, _desc, w, 92, "What happened, and what did you expect?");
Label("What were you doing? (optional)", Mute);
MultiLine(DoingId, DoingLabel, _doing, w, 56, "e.g. hunting in a dungeon with the bot on");
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
Separator(w);
LogRow(w);
Separator(w);
Note("Also sent: your character, server, RynthCore / RynthAi / plugin versions, where you are (landblock and cell) " +
"and the client's process id. Reports go to the staff only.", w);
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
SendRow(w);
End(origin, size);
}
// ── The log ─────────────────────────────────────────────────────────
private void LogRow(float w)
{
// Square toggle + label; the whole row toggles (Settings' look).
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
float labelW = ImGuiNET.ImGui.CalcTextSize(LogToggleLabel).X;
if (ImGuiNET.ImGui.InvisibleButton("##report_attach", new Vector2(Math.Min(w, 18 + labelW), 18)))
_attachLog = !_attachLog;
bool hot = ImGuiNET.ImGui.IsItemHovered();
if (hot) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand);
ImGuiNET.ImGui.SetItemTooltip("Your RynthCore log helps us see what happened. Untick it to send only what you wrote.");
dl.AddRectFilled(p + new Vector2(0, 3), p + new Vector2(12, 15), _attachLog ? Green : C(0xFF334455), 2);
dl.AddText(p + new Vector2(18, (18 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), hot ? Teal : Text, LogToggleLabel);
LogTail? tail = ProblemReport.Tail;
if (!ReferenceEquals(tail, _describedTail))
{
_describedTail = tail;
_tailText = tail != null ? ProblemReportCore.DescribeTail(tail) : "";
}
string info = ProblemReport.TailLoading ? "Reading the log..."
: tail != null ? _tailText
: ProblemReport.TailError.Length > 0 ? ProblemReport.TailError : "Reading the log...";
Wrapped(info, _attachLog ? Mute : Faded(Mute), w);
Vector2 row = ImGuiNET.ImGui.GetCursorScreenPos();
string view = PhosphorIcons.Eye + " View what will be sent";
string refresh = PhosphorIcons.ArrowsClockwise + " Refresh";
float vw = ButtonWidth(view), rw = ButtonWidth(refresh);
bool canView = tail != null && !ProblemReport.TailLoading;
if (Button("##report_view", view, row, new Vector2(vw, 22), Text, BtnFill, enabled: canView))
ProblemReport.ViewTail(tail!);
ImGuiNET.ImGui.SetItemTooltip("Opens the exact log text that will be sent, in your text editor.");
if (Button("##report_refresh", refresh, new Vector2(row.X + vw + 4, row.Y), new Vector2(rw, 22), Text, BtnFill,
enabled: !ProblemReport.TailLoading))
ProblemReport.RefreshTail();
ImGuiNET.ImGui.SetItemTooltip("Take the log again, up to now.");
NextLine(row, 26);
Note("The log has your character names and some chat in it (your account, Windows user and PC names are hidden). View shows exactly what will be sent.", w);
}
// ── Send ────────────────────────────────────────────────────────────
private void SendRow(float w)
{
ReportState state = ProblemReport.State;
long cooldown = ProblemReport.CooldownLeftMs;
bool sending = state == ReportState.Sending;
bool hasText = _desc[0] != 0;
Vector2 row = ImGuiNET.ImGui.GetCursorScreenPos();
string label = sending ? "Sending..." : "Send report";
float bw = Math.Max(110, ButtonWidth(label));
bool enabled = hasText && !sending && cooldown == 0 && !(_attachLog && ProblemReport.TailLoading);
if (Button("##report_send", label, row, new Vector2(bw, 24), Text, StartBg, enabled: enabled))
StartSend();
if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled | ImGuiHoveredFlags.ForTooltip))
ImGuiNET.ImGui.SetTooltip(!hasText ? "Write what went wrong first."
: cooldown > 0 ? "One report a minute: " + CooldownText(cooldown)
: "Send this report to the staff.");
NextLine(row, 28);
// The result (only ones from since the panel opened), then the cooldown.
if (_localError.Length > 0)
Wrapped(_localError, Amber, w);
else if (sending || ProblemReport.MessageSeq != _messageSeqAtOpen)
Wrapped(ProblemReport.Message, state switch
{
ReportState.Sent => Green,
ReportState.Failed => Red,
_ => Mute,
}, w);
if (!sending && cooldown > 0)
Wrapped(CooldownText(cooldown), Faded(Mute), w);
}
// "You can send another report in 42 s.", rebuilt once a second rather than every frame.
private long _cooldownShownS = -1;
private string _cooldownText = "";
private string CooldownText(long ms)
{
long sec = (ms + 999) / 1000;
if (sec != _cooldownShownS)
{
_cooldownShownS = sec;
_cooldownText = $"You can send another report in {ProblemReportCore.FormatWait(ms)}.";
}
return _cooldownText;
}
private void StartSend()
{
string description = Utf8(_desc), doing = Utf8(_doing);
LogTail? tail = _attachLog ? ProblemReport.Tail : null;
long seq = ProblemReport.ResultSeq;
if (ProblemReport.Send(description, doing, tail, readTailIfNull: false, announceInChat: false, out string error))
{
_localError = "";
_resultSeqAtSend = seq;
}
else
{
_localError = error;
}
}
// ── Widgets ─────────────────────────────────────────────────────────
/// <summary>A bordered multi-line text box (FaceKit.TextBox's look) with a grey hint while empty.</summary>
private unsafe void MultiLine(string id, byte[] label, byte[] buffer, float width, float height, string hint)
{
Vector2 pos = ImGuiNET.ImGui.GetCursorScreenPos();
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Text);
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, BtnBord);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameBorderSize, 1f);
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(4, 3));
ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.FrameRounding, 3f);
fixed (byte* l = label)
fixed (byte* b = buffer)
{
if (ImGuiNative.igInputTextMultiline(l, b, (uint)buffer.Length, new Vector2(width, height),
ImGuiInputTextFlags.None, null, null) != 0)
_localError = "";
}
bool active = ImGuiNET.ImGui.IsItemActive();
if (active) ImGuiTextFocus.NoteActive(id); // keys stay out of AC
ImGuiNET.ImGui.PopStyleVar(3);
ImGuiNET.ImGui.PopStyleColor(3);
if (buffer[0] == 0 && !active)
ImGuiNET.ImGui.GetWindowDrawList().AddText(pos + new Vector2(5, 3), Faded(Mute), hint);
}
private static void Wrapped(string text, uint color, float w)
{
ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, color);
ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w);
ImGuiNET.ImGui.TextUnformatted(text);
ImGuiNET.ImGui.PopTextWrapPos();
ImGuiNET.ImGui.PopStyleColor();
}
private static void Note(string text, float w) => Wrapped(text, Faded(Mute), w);
private static uint C(uint argb) => RynthTheme.Argb(argb);
}

View file

@ -115,9 +115,30 @@ internal sealed class SettingsFace : IImGuiPanel
float ty = p.Y + (26 - ImGuiNET.ImGui.GetFontSize()) * 0.5f;
dl.AddText(new Vector2(p.X + 8, ty), sel ? Teal : Mute, TabLabel(tabName));
}
ReportButton(w);
ImGuiNET.ImGui.EndChild();
}
// At the sidebar's foot (below the tabs when they fill it): opens Report a problem.
private static void ReportButton(float w)
{
if (!ImGuiPanelHost.HasFace(ReportFace.Title)) return;
const float h = 26;
float bottom = ImGuiNET.ImGui.GetWindowHeight() - ImGuiNET.ImGui.GetStyle().WindowPadding.Y - h;
ImGuiNET.ImGui.Dummy(new Vector2(0, 6));
if (ImGuiNET.ImGui.GetCursorPosY() < bottom) ImGuiNET.ImGui.SetCursorPosY(bottom);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos();
if (ImGuiNET.ImGui.InvisibleButton("##report", new Vector2(w, h)))
Report.ProblemReport.OpenPanel();
bool hot = ImGuiNET.ImGui.IsItemHovered();
ImGuiNET.ImGui.SetItemTooltip("Tell the staff what went wrong (also /rc report).");
dl.AddRectFilled(p, p + new Vector2(w, h), hot ? Lighten(BtnFill) : BtnFill);
dl.AddRect(p, p + new Vector2(w, h), BtnBord);
dl.AddText(new Vector2(p.X + 8, p.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), hot ? Amber : Mute,
PhosphorIcons.Warning + " Report a problem");
}
// ── Content: header + the tab's rows ───────────────────────────────────
private void Content(Vector2 size)

View file

@ -92,6 +92,7 @@ internal static unsafe class PhosphorIcons
public const string Info = "\uE2CE";
public const string Knife = "\uE636";
public const string Lightning = "\uE2DE";
public const string Leaf = "\uE2DA";
public const string ListChecks = "\uEADC";
public const string Lock = "\uE2FA";
public const string LockOpen = "\uE306";
@ -167,7 +168,7 @@ internal static unsafe class PhosphorIcons
+ ArrowCircleUp + Barbell + Brain + GraduationCap + Hourglass + SortDescending + Package
+ Binoculars + Crown + Sun
+ CastleTurret + ClockCounterClockwise + GlobeHemisphereWest + Path + Star + Target + User
+ TextAa;
+ TextAa + Leaf;
/// <summary>
/// Draws <paramref name="glyph"/> (one icon) centred in the box at

View file

@ -21,6 +21,8 @@ internal static class EngineSettings
private static bool _enableImGuiShell = true;
private static bool _enablePlugins = true;
private static bool _enableDatShareHook = true;
// Owned since f81fc8d: Save() writes it only when false (a hand-set false survives saves).
private static bool _enableLargeAddressAlignmentFix = true;
private static bool _enableAvaloniaOverlay = true;
private static bool _enableD3D9Hook = true;
private static bool _enableEngine = true;
@ -36,6 +38,15 @@ internal static class EngineSettings
private static bool _serverMessageStream = true;
private static bool _flightRecorder = true;
private static bool _insertReleasesUi;
// Read-only, like EnableLargeAddressAlignmentFix: only a hand-set value is written back.
private static int _maxHotReloads = ReloadCapNotice.DefaultMaxHotReloads;
// "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs).
// null = not in the file: IltDetect's defaults.
private static List<string>? _iltServerNames;
private static List<string>? _iltHosts;
// "ReportEndpoint": where "Report a problem" posts (Report/ProblemReport.cs); null = the built-in URL.
// For testing only (https, or http to this PC); read only, like MaxHotReloads.
private static string? _reportEndpoint;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -82,6 +93,19 @@ internal static class EngineSettings
}
}
/// <summary>When false, LargeAddressAlignmentPatch leaves acclient's signed "pointer % 4"
/// padding code alone (stock AC behaviour, which corrupts unpacks of buffers above 2 GB).
/// Default true. Diagnostic kill-switch only: set "EnableLargeAddressAlignmentFix": false
/// in engine.json by hand.</summary>
public static bool EnableLargeAddressAlignmentFix
{
get
{
EnsureLoaded();
return _enableLargeAddressAlignmentFix;
}
}
/// <summary>When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread,
/// the offscreen overlay window, and all OverlayHost-registered panels never instantiate.
/// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and
@ -323,6 +347,55 @@ internal static class EngineSettings
}
}
/// <summary>"MaxHotReloads" in engine.json (default 3, 2026-10-11): how many engine hot reloads
/// one client takes; the loader asks before each one (RynthCoreMaxHotReloads) and refuses the
/// rest, so a newer engine then needs a client restart. Clients died with CoreCLR fatal error
/// 0x80131506 after 4+ reloads in one process. Negative = no cap (test clients soaking
/// reloads), 0 = no hot reloads at all. Read at each engine init; edited in the file.</summary>
public static int MaxHotReloads
{
get
{
EnsureLoaded();
return _maxHotReloads;
}
}
/// <summary>"ReportEndpoint" in engine.json: a test URL for "Report a problem" instead of the
/// built-in https://aelrynth.com/rynth/report (ProblemReportCore.ResolveEndpoint accepts https,
/// or http to this PC; anything else is ignored). Null when the file has none. Edited in the file.</summary>
public static string? ReportEndpoint
{
get
{
EnsureLoaded();
return _reportEndpoint;
}
}
/// <summary>"IltServerNames" in engine.json: world-name patterns ('*' wildcard, case-insensitive)
/// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultServerNames).
/// An empty array turns the world-name signal off. Read only: edited in the file.</summary>
public static IReadOnlyList<string>? IltServerNames
{
get
{
EnsureLoaded();
return _iltServerNames;
}
}
/// <summary>"IltHosts" in engine.json: launch hosts (a domain covers its subdomains, '*' allowed)
/// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultHosts).</summary>
public static IReadOnlyList<string>? IltHosts
{
get
{
EnsureLoaded();
return _iltHosts;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -390,6 +463,12 @@ internal static class EngineSettings
_enableDatShareHook = datEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableLargeAddressAlignmentFix", out var laaEl) &&
(laaEl.ValueKind == JsonValueKind.True || laaEl.ValueKind == JsonValueKind.False))
{
_enableLargeAddressAlignmentFix = laaEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) &&
(avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False))
{
@ -457,12 +536,30 @@ internal static class EngineSettings
(iruEl.ValueKind == JsonValueKind.True || iruEl.ValueKind == JsonValueKind.False))
_insertReleasesUi = iruEl.GetBoolean();
if (doc.RootElement.TryGetProperty("MaxHotReloads", out var mhrEl) &&
mhrEl.ValueKind == JsonValueKind.Number &&
mhrEl.TryGetInt32(out int mhr))
_maxHotReloads = mhr;
if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) &&
repEl.ValueKind == JsonValueKind.String &&
repEl.GetString() is { Length: > 0 } rep)
_reportEndpoint = rep.Trim();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("IltServerNames", out var ilnEl) &&
ilnEl.ValueKind == JsonValueKind.Array)
_iltServerNames = ReadStringList(ilnEl);
if (doc.RootElement.TryGetProperty("IltHosts", out var ilhEl) &&
ilhEl.ValueKind == JsonValueKind.Array)
_iltHosts = ReadStringList(ilhEl);
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
duhEl.ValueKind == JsonValueKind.Array)
{
@ -479,6 +576,20 @@ internal static class EngineSettings
}
}
private static List<string> ReadStringList(JsonElement arr)
{
// Trimmed, blanks dropped, case-insensitive duplicates dropped (the file stays as the player wrote it).
var list = new List<string>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var el in arr.EnumerateArray())
{
if (el.ValueKind != JsonValueKind.String) continue;
string v = (el.GetString() ?? "").Trim();
if (v.Length > 0 && seen.Add(v)) list.Add(v);
}
return list;
}
/// <summary>Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from
/// memory (one written only when not the default is left out, as before) and keeps every
/// other key as the file had it. A new engine.json setting goes here too
@ -489,7 +600,8 @@ internal static class EngineSettings
"EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount",
"EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge",
"DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream",
"FlightRecorder", "InsertReleasesUi",
"FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix",
"MaxHotReloads", "ReportEndpoint",
};
private static void Save()
@ -534,8 +646,16 @@ internal static class EngineSettings
w.WriteBoolean("ServerMessageStream", false);
if (!_flightRecorder) // default true: leave the file as it was
w.WriteBoolean("FlightRecorder", false);
if (!_enableLargeAddressAlignmentFix) // default true: only a hand-set false is written
w.WriteBoolean("EnableLargeAddressAlignmentFix", false);
if (_insertReleasesUi) // default false: leave the file as it was
w.WriteBoolean("InsertReleasesUi", true);
if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written
w.WriteNumber("MaxHotReloads", _maxHotReloads);
if (_reportEndpoint != null) // only a hand-set value is written
w.WriteString("ReportEndpoint", _reportEndpoint);
WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out
WriteStringList(w, "IltHosts", _iltHosts);
w.WriteEndObject();
}
@ -554,6 +674,15 @@ internal static class EngineSettings
RynthLog.Plugin($"EngineSettings: Failed to save: {ex.Message}");
}
}
private static void WriteStringList(Utf8JsonWriter w, string name, List<string>? list)
{
if (list == null) return;
w.WriteStartArray(name);
foreach (string v in list)
w.WriteStringValue(v);
w.WriteEndArray();
}
}
/// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary>

View file

@ -0,0 +1,49 @@
namespace RynthCore.Engine;
/// <summary>
/// The engine's side of the hot-reload cap (2026-10-11). The native loader (native/Loader/Loader.c,
/// ReloadWatcher) asks the engine for engine.json MaxHotReloads before every hot reload and refuses
/// the reload once this client has done that many; the client keeps running on the current engine
/// and the loader tells the engine (RynthCoreReloadCapped), which logs it and says so in chat: once
/// on its own, and again whenever the player asks for a reload by hand (RL, /rc rl), so a button
/// press never goes unanswered. Clients died with CoreCLR fatal error 0x80131506 after 4+ engine
/// reloads in one process. No engine state here: tools/ReloadCapTests compiles this file in.
/// </summary>
internal sealed class ReloadCapNotice
{
/// <summary>engine.json MaxHotReloads when the file doesn't set it (and the loader's own
/// default for an engine without the export, DEFAULT_MAX_HOT_RELOADS in Loader.c).</summary>
public const int DefaultMaxHotReloads = 3;
/// <summary>How recent the engine's own reload signal must be to count as "asked by hand".</summary>
public const long ManualWindowMs = 10_000;
private bool _told;
/// <summary>The chat line for the player.</summary>
public static string ChatText(int reloads) =>
$"RynthCore: this client has hot reloaded {reloads} {(reloads == 1 ? "time" : "times")}; restart the client to pick up the new engine.";
/// <summary>The engine log line.</summary>
public static string LogText(int reloads, int cap, bool askedByHand) =>
$"Hot reload refused by the loader: this client has hot reloaded {reloads} time(s) and engine.json MaxHotReloads is {cap}" +
(askedByHand ? " (asked for by hand)" : "") + ". Staying on this engine; a client restart picks up the new one.";
/// <summary>True when the refusal should go to chat: the first one, and any the player asked
/// for by hand. Later automatic ones (an engine publish) are logged only.</summary>
public bool ShouldChat(bool askedByHand)
{
if (!_told)
{
_told = true;
return true;
}
return askedByHand;
}
/// <summary>True when a reload signal the engine sent at <paramref name="signaledAtMs"/>
/// (Environment.TickCount64; 0 = never) is recent enough at <paramref name="nowMs"/> to count
/// as the player's.</summary>
public static bool IsRecentManualSignal(long signaledAtMs, long nowMs) =>
signaledAtMs != 0 && nowMs - signaledAtMs >= 0 && nowMs - signaledAtMs < ManualWindowMs;
}

View file

@ -0,0 +1,429 @@
// ============================================================================
// RynthCore.Engine - Report/ProblemReport.cs
// "Report a problem": the player writes what went wrong and it reaches a
// private staff channel on Discord. The engine posts to our server
// (ProblemReportCore.DefaultEndpoint, https://aelrynth.com/rynth/report); the
// server holds the Discord webhook, rate-limits, keeps a copy and posts it
// (C:\Aeshnidae\ops\report-endpoint). The client holds no secret.
//
// Opened from the bar's grip menu, Settings (the sidebar's foot), "/rc report";
// "/rc report <text>" sends at once (with the log, the default).
//
// What is sent: the player's text; character, world, connect host, RynthCore /
// RynthAi / plugin versions, landcell, pid, engine generation; and - ticked by
// default, the player can untick it - the last 2,000 lines of this client's
// RynthCore.<pid>.log (it holds character names and some chat; the account,
// Windows user and PC names are hidden, ProblemReportCore.Redact; View opens
// exactly what will be sent).
//
// Threads:
// Send / RefreshTail / ViewTail / HandleCommand any thread (the panel calls them on AC's).
// The request runs on its own EngineThreads thread with a short-lived HttpClient,
// disposed when it finishes; Shutdown cancels and disposes one still in flight
// (the engine hot-reloads into a collectible context: nothing may outlive it).
// The log tail and the preview file are read / written on UiBackgroundWriter.
// One report per 60 s per client (ProblemReportCore.CooldownMs), kept in a process
// environment variable so an engine reload doesn't reset it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.Report;
internal enum ReportState { Idle, Sending, Sent, Failed }
internal static class ProblemReport
{
public const string PanelTitle = "Report a problem";
// Process-wide, so a hot reload (a new engine generation) keeps the cooldown.
private const string NextAllowedEnv = "RYNTHCORE_REPORT_NEXT_MS";
private static readonly object Sync = new();
private static int _state; // ReportState
private static string _message = "";
private static long _resultSeq; // bumps on every finished send (the panel clears its text on success)
private static long _messageSeq; // bumps on every new message (the panel shows only ones newer than its opening)
private static CancellationTokenSource _cts = new();
private static HttpClient? _inFlight;
private static volatile bool _shutdown;
private static volatile LogTail? _tail;
private static volatile string _tailError = "";
private static int _tailLoading;
public static ReportState State => (ReportState)Volatile.Read(ref _state);
public static string Message { get { lock (Sync) return _message; } }
public static long ResultSeq => Interlocked.Read(ref _resultSeq);
public static long MessageSeq => Interlocked.Read(ref _messageSeq);
/// <summary>The log tail the panel shows and sends (null until read, or when there's no log).</summary>
public static LogTail? Tail => _tail;
public static string TailError => _tailError;
public static bool TailLoading => Volatile.Read(ref _tailLoading) != 0;
/// <summary>Milliseconds until another report may be sent (0 = now).</summary>
public static long CooldownLeftMs => ProblemReportCore.CooldownLeft(Environment.TickCount64, NextAllowedMs());
// ── The log tail ─────────────────────────────────────────────────────
/// <summary>Reads this client's log tail again (background). Any thread.</summary>
public static void RefreshTail()
{
if (Interlocked.Exchange(ref _tailLoading, 1) != 0) return;
UI.UiBackgroundWriter.Enqueue("report log tail", static () =>
{
try
{
LogTail? t = ReadTailNow();
_ = t?.Gzip; // compressed here, not on AC's thread when the panel first shows the size
_tail = t;
_tailError = _tail == null ? "There's no RynthCore log for this client yet." : "";
}
catch (Exception ex)
{
_tail = null;
_tailError = "Couldn't read the log: " + ex.Message;
RynthLog.Warn($"ProblemReport: reading the log tail failed - {ex.GetType().Name}: {ex.Message}");
}
finally
{
Volatile.Write(ref _tailLoading, 0);
}
});
}
// The account (login) name, the Windows user name and the PC's name are hidden from the tail
// (ProblemReportCore.Redact), so neither View nor the report shows them.
private static LogTail? ReadTailNow() => ProblemReportCore.ReadTail(LogPaths.LogFilePath, LogPaths.RotatedLogFilePath,
hide: new[]
{
(SessionStateRegistry.LastAccountName ?? "", ProblemReportCore.HiddenAccount),
(SafeEnv(() => Environment.UserName), ProblemReportCore.HiddenUser),
(SafeEnv(() => Environment.MachineName), "<pc>"),
});
private static string SafeEnv(Func<string> read)
{
try { return read() ?? ""; }
catch { return ""; }
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile,
string? lpParameters, string? lpDirectory, int nShowCmd);
/// <summary>
/// Writes <paramref name="tail"/> - exactly the bytes a report would carry - to
/// Logs\report-preview-&lt;pid&gt;.txt and opens it (the default text editor). Any thread.
/// ShellExecute, not Process.Start (the Process API is an AV hazard inside acclient.exe).
/// </summary>
public static void ViewTail(LogTail tail)
{
UI.UiBackgroundWriter.Enqueue("report log preview", () =>
{
try
{
string path = Path.Combine(LogPaths.LogDirectory, $"report-preview-{Environment.ProcessId}.txt");
File.WriteAllBytes(path, tail.Text);
IntPtr r = ShellExecuteW(IntPtr.Zero, "open", path, null, LogPaths.LogDirectory, 1 /* SW_SHOWNORMAL */);
if (r.ToInt64() <= 32)
SetMessage(State, $"Couldn't open the preview (code {r.ToInt64()}); it is at {path}");
}
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: preview failed - {ex.GetType().Name}: {ex.Message}");
SetMessage(State, "Couldn't write the preview: " + ex.Message);
}
});
}
// ── Sending ──────────────────────────────────────────────────────────
/// <summary>
/// Starts sending a report. <paramref name="tail"/> is the log to attach (null = none;
/// <paramref name="readTailIfNull"/> reads it fresh on the send thread, for /rc report text).
/// False with <paramref name="error"/> when it can't start (no text, cooldown, already
/// sending). <paramref name="announceInChat"/> = also say the result in chat. Any thread.
/// </summary>
public static bool Send(string description, string doing, LogTail? tail, bool readTailIfNull, bool announceInChat, out string error)
{
error = ProblemReportCore.ValidateDescription(description);
if (error.Length > 0) return false;
if (_shutdown) { error = "RynthCore is shutting down."; return false; }
ReportContext ctx;
try { ctx = GatherContext(); }
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: gathering the client details failed - {ex.GetType().Name}: {ex.Message}");
ctx = new ReportContext { Pid = Environment.ProcessId, RynthCoreVersion = EntryPoint.BuildStamp };
}
CancellationToken token;
lock (Sync)
{
if ((ReportState)_state == ReportState.Sending) { error = "A report is already being sent."; return false; }
long left = CooldownLeftMs;
if (left > 0) { error = $"You can send another report in {ProblemReportCore.FormatWait(left)}."; return false; }
_state = (int)ReportState.Sending;
_message = "Sending...";
Interlocked.Increment(ref _messageSeq);
SetNextAllowed(Environment.TickCount64 + ProblemReportCore.CooldownMs);
token = _cts.Token;
}
string endpoint = ProblemReportCore.ResolveEndpoint(Plugins.EngineSettings.ReportEndpoint, out string? rejected);
if (rejected != null)
RynthLog.Warn($"ProblemReport: engine.json ReportEndpoint '{rejected}' ignored (https only, or http to this PC); using {endpoint}.");
try
{
EngineThreads.Start("ProblemReport send", () => SendWorker(endpoint, description, doing, ctx, tail, readTailIfNull, announceInChat, token));
}
catch (Exception ex)
{
Finish(false, "Couldn't start sending: " + ex.Message, announceInChat, reachedServer: false);
error = "Couldn't start sending: " + ex.Message;
return false;
}
return true;
}
private static void SendWorker(string endpoint, string description, string doing, ReportContext ctx, LogTail? tail,
bool readTailIfNull, bool announceInChat, CancellationToken token)
{
HttpClient? http = null;
try
{
if (tail == null && readTailIfNull)
{
try { tail = ReadTailNow(); }
catch (Exception ex) { RynthLog.Warn($"ProblemReport: reading the log tail failed - {ex.GetType().Name}: {ex.Message}; sending without it."); }
}
if (tail != null && tail.Gzip.Length > ProblemReportCore.MaxGzipBytes)
{
RynthLog.Warn($"ProblemReport: the log is {tail.Gzip.Length} bytes gzipped (limit {ProblemReportCore.MaxGzipBytes}); sending without it.");
tail = null;
}
byte[] body = ProblemReportCore.BuildPayload(description, doing, ctx, tail, DateTime.UtcNow);
var handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
UseCookies = false,
ConnectTimeout = TimeSpan.FromSeconds(10),
PooledConnectionLifetime = TimeSpan.FromSeconds(30),
};
http = new HttpClient(handler, disposeHandler: true) { Timeout = TimeSpan.FromSeconds(45) };
lock (Sync)
{
if (_shutdown) return;
_inFlight = http;
}
using var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new ByteArrayContent(body) };
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
req.Headers.UserAgent.ParseAdd("RynthCore-Report/1");
req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using HttpResponseMessage resp = http.Send(req, HttpCompletionOption.ResponseHeadersRead, token);
int status = (int)resp.StatusCode;
string answer = ReadSmall(resp, token);
bool ok = ProblemReportCore.ReadResponse(status, answer, out string message, out string id);
RynthLog.Info($"ProblemReport: HTTP {status} from {endpoint} - {(ok ? "taken" + (id.Length > 0 ? " as " + id : "") : message)} " +
$"(body {body.Length} bytes, log {(tail == null ? "not attached" : $"{tail.Lines} lines")}).");
Finish(ok, message, announceInChat, reachedServer: true);
}
catch (OperationCanceledException) when (_shutdown || token.IsCancellationRequested)
{
Finish(false, "Cancelled (RynthCore was reloading).", announceInChat, reachedServer: false);
}
catch (OperationCanceledException)
{
Finish(false, "The report service didn't answer in time. Please try again in a moment.", announceInChat, reachedServer: false);
}
catch (HttpRequestException ex)
{
RynthLog.Warn($"ProblemReport: network error - {ex.Message}");
Finish(false, "Couldn't reach the report service (" + ex.Message + "). Check your connection and try again.", announceInChat, reachedServer: false);
}
catch (Exception ex)
{
RynthLog.Warn($"ProblemReport: send failed - {ex.GetType().Name}: {ex.Message}");
Finish(false, $"Couldn't send the report ({ex.GetType().Name}).", announceInChat, reachedServer: false);
}
finally
{
lock (Sync)
{
if (ReferenceEquals(_inFlight, http)) _inFlight = null;
}
try { http?.Dispose(); } catch { }
}
}
/// <summary>The answer's first 8 KB as text (the server's answers are tiny).</summary>
private static string ReadSmall(HttpResponseMessage resp, CancellationToken token)
{
try
{
using Stream s = resp.Content.ReadAsStream(token);
var buf = new byte[8192];
int total = 0, n;
while (total < buf.Length && (n = s.Read(buf, total, buf.Length - total)) > 0) total += n;
return Encoding.UTF8.GetString(buf, 0, total);
}
catch
{
return "";
}
}
private static void Finish(bool ok, string message, bool announceInChat, bool reachedServer)
{
lock (Sync)
{
_state = (int)(ok ? ReportState.Sent : ReportState.Failed);
_message = message;
// A send that never reached the server may be retried soon; one that did keeps the full minute.
if (!ok && !reachedServer)
SetNextAllowed(Environment.TickCount64 + ProblemReportCore.RetryAfterFailureMs);
Interlocked.Increment(ref _resultSeq);
Interlocked.Increment(ref _messageSeq);
}
if (announceInChat && !_shutdown)
AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Report: " + message, 1);
}
private static void SetMessage(ReportState state, string message)
{
lock (Sync)
{
_state = (int)state;
_message = message;
Interlocked.Increment(ref _messageSeq);
}
}
// Read from the process environment once per engine generation; the panel reads the field each frame.
private static long _nextAllowedMs = ReadNextAllowedEnv();
private static long NextAllowedMs() => Interlocked.Read(ref _nextAllowedMs);
private static long ReadNextAllowedEnv()
{
try
{
return long.TryParse(Environment.GetEnvironmentVariable(NextAllowedEnv), out long v) ? v : 0;
}
catch { return 0; }
}
private static void SetNextAllowed(long tickMs)
{
Interlocked.Exchange(ref _nextAllowedMs, tickMs);
try { Environment.SetEnvironmentVariable(NextAllowedEnv, tickMs.ToString(System.Globalization.CultureInfo.InvariantCulture)); }
catch { }
}
// ── What the report says about the client ───────────────────────────
/// <summary>Character, world, versions, landcell, pid. Any thread (cached reads only).</summary>
public static ReportContext GatherContext()
{
var ctx = new ReportContext
{
Pid = Environment.ProcessId,
RynthCoreVersion = EntryPoint.BuildStamp,
ApiVersion = (int)Plugins.PluginContractVersion.Current,
Generation = EntryPoint.InitCount,
};
string character = "";
uint player = ClientHelperHooks.GetPlayerId();
if (player != 0 && ClientObjectHooks.TryGetSnapshotName(player, out string live)) character = live;
if (string.IsNullOrWhiteSpace(character)) character = SessionStateRegistry.LastCharacterName ?? "";
ctx.Character = character;
string world = AccountHooks.AnnouncedWorldName ?? "";
if (string.IsNullOrWhiteSpace(world)) world = SessionStateRegistry.LastServerName ?? "";
ctx.World = world;
string host = ServerInfo.HostDescription;
ctx.Connect = host == "(none)" ? "" : host;
ctx.Aelrynth = ServerInfo.IsAelrynth;
try
{
// A copy (the list changes only on load / unload / RL; a copy taken mid-change just lists less).
Plugins.LoadedPlugin[] plugins = System.Linq.Enumerable.ToArray(Plugins.PluginManager.Plugins);
foreach (Plugins.LoadedPlugin p in plugins)
{
string name = p.DisplayName.Length > 0 ? p.DisplayName : Path.GetFileNameWithoutExtension(p.FileName);
string version = p.VersionString + (p.Failed ? " (failed)" : p.NotStartedReason.Length > 0 ? " (not started)" : "");
ctx.Plugins.Add((name, version));
if (ctx.RynthAiVersion.Length == 0 && !p.Failed
&& (name.Equals("RynthAi", StringComparison.OrdinalIgnoreCase)
|| p.FileName.Equals("RynthCore.Plugin.RynthAi.dll", StringComparison.OrdinalIgnoreCase)))
ctx.RynthAiVersion = p.VersionString.Length > 0 ? p.VersionString : "loaded";
}
}
catch (Exception ex)
{
RynthLog.Verbose($"ProblemReport: plugin list unavailable - {ex.Message}");
}
if (ClientObjectHooks.TryGetPlayerStats(out _, out _, out _, out _, out _, out _, out uint landcell, out _, out _, out _))
ctx.Landcell = landcell;
return ctx;
}
// ── /rc report ───────────────────────────────────────────────────────
/// <summary>"/rc report" opens the panel; "/rc report &lt;text&gt;" sends it now (with the log). Lines for chat.</summary>
public static IEnumerable<string> HandleCommand(string args)
{
if (string.IsNullOrWhiteSpace(args))
{
if (!ImGuiBackend.ImGuiPanelHost.HasFace(PanelTitle))
return new[] { "The Report a problem panel isn't available (the ImGui layer is off?). Use /rc report <what went wrong> to send one from chat." };
OpenPanel();
return Array.Empty<string>();
}
if (!Send(args, "", tail: null, readTailIfNull: true, announceInChat: true, out string error))
return new[] { "Report not sent: " + error };
return new[] { "Sending your report (with your recent RynthCore log; use the panel, /rc report, to leave the log out)..." };
}
/// <summary>Opens the panel (it reads the log tail when it opens). Any thread.</summary>
public static void OpenPanel()
{
if (!ImGuiBackend.ImGuiPanelHost.IsOpen(PanelTitle))
UI.PanelRouter.Toggle(PanelTitle);
}
// ── Shutdown ─────────────────────────────────────────────────────────
/// <summary>Cancels a send in flight and disposes its HttpClient (engine shutdown / hot reload).</summary>
public static void Shutdown()
{
HttpClient? http;
lock (Sync)
{
_shutdown = true;
http = _inFlight;
_inFlight = null;
}
try { _cts.Cancel(); } catch { }
try { http?.Dispose(); } catch { }
_tail = null;
}
}

View file

@ -0,0 +1,462 @@
// ============================================================================
// RynthCore.Engine - Report/ProblemReportCore.cs
// The pure half of "Report a problem" (ProblemReport.cs is the engine half):
// the text limits, the log tail, the request body, the client's cooldown and
// the reading of the server's answer. No engine state, no AC, no network, so
// tools/ProblemReportTests compiles this file and checks it offline.
//
// Wire format (POST https://aelrynth.com/rynth/report, application/json; the
// server side is C:\Aeshnidae\ops\report-endpoint\app.py, which refuses any
// other shape):
// { "schema": 1,
// "description": "...", "doing": "...", the player's text
// "character": "...", "world": "...", "connect": "host:port", "aelrynth": true,
// "rynthcore": "2026.10.9.3 (194ea47)", "api": 81, "generation": 1,
// "rynthai": "2026.10.9.3 (e6fffb0)" | "",
// "plugins": [ { "name": "RynthAi", "version": "..." } ],
// "landcell": "0x12340105" | "",
// "pid": 1234, "clientTime": "2026-10-11T12:00:00Z",
// "log": null | { "name": "RynthCore.1234.log", "lines": 2000, "bytes": 214000,
// "gzip": "<base64 of the gzipped tail>" } }
// The server answers JSON: { "ok": true, "id": "R-..." } or { "error": "..." }.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.Report;
/// <summary>What the report says about the client, gathered when it is sent.</summary>
internal sealed class ReportContext
{
public string Character = "";
public string World = "";
public string Connect = "";
public bool Aelrynth;
public string RynthCoreVersion = "";
public int ApiVersion;
public int Generation;
public string RynthAiVersion = "";
public List<(string Name, string Version)> Plugins = new();
public uint Landcell;
public int Pid;
}
/// <summary>The end of a log file, exactly as it will be sent (and shown by View).</summary>
internal sealed class LogTail
{
public string FileName = "";
public byte[] Text = Array.Empty<byte>();
public int Lines;
/// <summary>The tail began in the rotated .old file (the current one was shorter than asked).</summary>
public bool IncludesOld;
public DateTime TakenLocal;
private byte[]? _gzip;
/// <summary>The gzipped text (made once).</summary>
public byte[] Gzip => _gzip ??= ProblemReportCore.Gzip(Text);
}
internal static class ProblemReportCore
{
public const string DefaultEndpoint = "https://aelrynth.com/rynth/report";
// Text limits (UTF-8 bytes). The server takes no more (app.py MAX_DESCRIPTION / MAX_DOING).
public const int MaxDescriptionBytes = 2500;
public const int MaxDoingBytes = 1500;
public const int MinDescriptionChars = 3;
// The log: the last 2,000 lines, at most 1.5 MB of them (the end is kept). The server
// takes 2 MB of gzip; 1.5 MB of log text gzips to a few hundred KB.
public const int TailLines = 2000;
public const int MaxTailBytes = 1_500_000;
public const int MaxGzipBytes = 2_000_000;
// Short strings the server checks the same way.
public const int MaxShortField = 64;
public const int MaxConnectField = 100;
public const int MaxPlugins = 32;
/// <summary>One report per minute per client; a send that never reached the server waits only this.</summary>
public const int CooldownMs = 60_000;
public const int RetryAfterFailureMs = 10_000;
// ── Text ─────────────────────────────────────────────────────────────
/// <summary>
/// <paramref name="text"/> trimmed, CR LF made LF, other control characters (except tab)
/// dropped, then cut to <paramref name="maxBytes"/> of UTF-8 at a character boundary.
/// </summary>
public static string CleanText(string? text, int maxBytes)
{
if (string.IsNullOrEmpty(text)) return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text.Replace("\r\n", "\n").Replace('\r', '\n'))
{
if (c == '\n' || c == '\t' || !char.IsControl(c)) sb.Append(c);
}
return TrimUtf8(sb.ToString().Trim(), maxBytes);
}
/// <summary>A one-line field: control characters dropped, trimmed, cut to <paramref name="maxChars"/>.</summary>
public static string CleanShort(string? text, int maxChars)
{
if (string.IsNullOrEmpty(text)) return "";
var sb = new StringBuilder(text.Length);
foreach (char c in text)
if (!char.IsControl(c)) sb.Append(c);
string s = sb.ToString().Trim();
if (s.Length > maxChars)
{
int n = maxChars;
if (char.IsHighSurrogate(s[n - 1])) n--;
s = s.Substring(0, n);
}
return s;
}
/// <summary>Cuts <paramref name="s"/> to at most <paramref name="maxBytes"/> of UTF-8, never inside a character.</summary>
public static string TrimUtf8(string s, int maxBytes)
{
if (Encoding.UTF8.GetByteCount(s) <= maxBytes) return s;
int bytes = 0, i = 0;
while (i < s.Length)
{
int len = char.IsHighSurrogate(s[i]) && i + 1 < s.Length && char.IsLowSurrogate(s[i + 1]) ? 2 : 1;
int cb = Encoding.UTF8.GetByteCount(s.AsSpan(i, len));
if (bytes + cb > maxBytes) break;
bytes += cb;
i += len;
}
return s.Substring(0, i);
}
/// <summary>Why <paramref name="description"/> can't be sent, or "" when it can.</summary>
public static string ValidateDescription(string description)
{
string d = CleanText(description, MaxDescriptionBytes);
if (d.Length == 0) return "Write what went wrong first.";
if (d.Length < MinDescriptionChars) return "Say a little more about what went wrong.";
return "";
}
// ── The log tail ─────────────────────────────────────────────────────
/// <summary>
/// The last <paramref name="maxLines"/> lines of <paramref name="path"/> (at most
/// <paramref name="maxBytes"/>; a cut first line is dropped), read while the engine
/// may be appending to it: the file is opened for shared read/write and read up to the
/// length it had when opened. When it holds fewer lines than asked and
/// <paramref name="olderPath"/> exists (the rotated .old), the rest comes from there.
/// Null when the file doesn't exist. Throws on other I/O errors.
/// </summary>
public static LogTail? ReadTail(string path, string? olderPath, int maxLines = TailLines, int maxBytes = MaxTailBytes,
DateTime? now = null, IReadOnlyList<(string Name, string Replacement)>? hide = null)
{
if (!File.Exists(path)) return null;
byte[] current = TailBytes(path, maxLines, maxBytes, out int lines);
bool includesOld = false;
if (lines < maxLines && current.Length < maxBytes && !string.IsNullOrEmpty(olderPath) && File.Exists(olderPath))
{
byte[] older = TailBytes(olderPath, maxLines - lines, maxBytes - current.Length, out int olderLines);
if (older.Length > 0)
{
// The older file's last line may lack its newline; keep the lines apart.
bool needNewline = older[^1] != (byte)'\n';
var merged = new byte[older.Length + (needNewline ? 1 : 0) + current.Length];
Buffer.BlockCopy(older, 0, merged, 0, older.Length);
if (needNewline) merged[older.Length] = (byte)'\n';
Buffer.BlockCopy(current, 0, merged, merged.Length - current.Length, current.Length);
current = merged;
lines += olderLines;
includesOld = true;
}
}
current = Redact(current, hide);
return new LogTail
{
FileName = Path.GetFileName(path),
Text = current,
Lines = lines,
IncludesOld = includesOld,
TakenLocal = now ?? DateTime.Now,
};
}
/// <summary>The last <paramref name="maxLines"/> whole lines of a file, at most <paramref name="maxBytes"/>.</summary>
internal static byte[] TailBytes(string path, int maxLines, int maxBytes, out int lines)
{
lines = 0;
if (maxLines <= 0 || maxBytes <= 0) return Array.Empty<byte>();
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
bufferSize: 1, FileOptions.None);
long length = fs.Length;
if (length == 0) return Array.Empty<byte>();
// Read backwards in chunks until there are enough newlines or the byte cap is reached.
const int Chunk = 64 * 1024;
long start = length;
var chunks = new List<byte[]>();
int newlines = 0;
long have = 0;
// A last line still being written (no newline yet) counts as a line; a trailing newline doesn't start one.
while (start > 0 && have < maxBytes)
{
int size = (int)Math.Min(Chunk, Math.Min(start, maxBytes - have + 1));
start -= size;
var buf = new byte[size];
fs.Position = start;
int read = 0;
while (read < size)
{
int n = fs.Read(buf, read, size - read);
if (n <= 0) break; // the file shrank under us (rotated): use what came
read += n;
}
if (read < size) Array.Resize(ref buf, read);
chunks.Insert(0, buf);
have += buf.Length;
foreach (byte b in buf) if (b == (byte)'\n') newlines++;
if (newlines > maxLines) break;
}
var all = new byte[have];
int at = 0;
foreach (byte[] c in chunks) { Buffer.BlockCopy(c, 0, all, at, c.Length); at += c.Length; }
int end = all.Length;
int scanEnd = end > 0 && all[end - 1] == (byte)'\n' ? end - 1 : end;
// Walk back over maxLines newlines (from the end, not counting the trailing one).
int from = 0;
int seen = 0;
bool cut = false;
for (int i = scanEnd - 1; i >= 0; i--)
{
if (all[i] != (byte)'\n') continue;
seen++;
if (seen == maxLines) { from = i + 1; cut = true; break; }
}
if (!cut && start > 0)
{
// Stopped by the byte cap mid-file: drop the partial first line.
int nl = Array.IndexOf(all, (byte)'\n');
from = nl < 0 ? end : nl + 1;
}
// The byte cap: keep the end, starting at a line.
if (end - from > maxBytes)
{
int nl = Array.IndexOf(all, (byte)'\n', end - maxBytes);
from = nl < 0 ? end : nl + 1;
}
byte[] result = from == 0 ? all : all.AsSpan(from, end - from).ToArray();
lines = CountLines(result);
return result;
}
// SessionStateRegistry logs "account='<login name>'" at login; the login name is half a credential.
private static readonly Regex AccountField = new(@"account='[^'\r\n]*'", RegexOptions.CultureInvariant);
// Paths under the Windows profile (C:\Users\<name>\AppData\...) carry the Windows user name.
private static readonly Regex ProfilePath = new(@"(?i)\b([A-Z]:[\\/]Users[\\/])[^\\/\r\n'""<>|]+", RegexOptions.CultureInvariant);
public const string HiddenAccount = "<account>";
public const string HiddenUser = "<user>";
/// <summary>
/// The log text with private names hidden: every account='...' field and every occurrence (any
/// case) of each name in <paramref name="hide"/> (3 characters or more) become its replacement
/// (&lt;account&gt;, &lt;user&gt;, ...), and the folder after X:\Users\ becomes &lt;user&gt;.
/// Done before the size is shown and before View, so View shows what is sent.
/// </summary>
public static byte[] Redact(byte[] text, IReadOnlyList<(string Name, string Replacement)>? hide)
{
if (text.Length == 0) return text;
string s = Encoding.UTF8.GetString(text);
string r = AccountField.Replace(s, "account='" + HiddenAccount + "'");
r = ProfilePath.Replace(r, "$1" + HiddenUser);
if (hide != null)
{
foreach (var (name, replacement) in hide)
{
string w = (name ?? "").Trim();
if (w.Length < 3) continue;
r = Regex.Replace(r, Regex.Escape(w), replacement.Replace("$", "$$"), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
}
return string.Equals(r, s, StringComparison.Ordinal) ? text : Encoding.UTF8.GetBytes(r);
}
/// <summary>Lines in a text: newlines, plus one for a last line without one.</summary>
public static int CountLines(ReadOnlySpan<byte> text)
{
if (text.Length == 0) return 0;
int n = 0;
foreach (byte b in text) if (b == (byte)'\n') n++;
return text[^1] == (byte)'\n' ? n : n + 1;
}
public static byte[] Gzip(byte[] data)
{
using var ms = new MemoryStream(data.Length / 4 + 64);
using (var gz = new GZipStream(ms, CompressionLevel.Optimal, leaveOpen: true))
gz.Write(data, 0, data.Length);
return ms.ToArray();
}
// ── The request body ─────────────────────────────────────────────────
/// <summary>The JSON body (see the file header). <paramref name="log"/> null = not attached.</summary>
public static byte[] BuildPayload(string description, string doing, ReportContext ctx, LogTail? log, DateTime utcNow)
{
using var ms = new MemoryStream(1024 + (log == null ? 0 : log.Gzip.Length * 4 / 3 + 256));
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteNumber("schema", 1);
w.WriteString("description", CleanText(description, MaxDescriptionBytes));
w.WriteString("doing", CleanText(doing, MaxDoingBytes));
w.WriteString("character", CleanShort(ctx.Character, MaxShortField));
w.WriteString("world", CleanShort(ctx.World, MaxShortField));
w.WriteString("connect", CleanShort(ctx.Connect, MaxConnectField));
w.WriteBoolean("aelrynth", ctx.Aelrynth);
w.WriteString("rynthcore", CleanShort(ctx.RynthCoreVersion, MaxShortField));
w.WriteNumber("api", Math.Clamp(ctx.ApiVersion, 0, 1_000_000));
w.WriteNumber("generation", Math.Clamp(ctx.Generation, 0, 1_000_000));
w.WriteString("rynthai", CleanShort(ctx.RynthAiVersion, MaxShortField));
w.WriteStartArray("plugins");
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var (name, version) in ctx.Plugins)
{
string n = PluginName(name);
if (n.Length == 0 || !seen.Add(n)) continue;
if (seen.Count > MaxPlugins) break;
w.WriteStartObject();
w.WriteString("name", n);
w.WriteString("version", CleanShort(version, MaxShortField));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteString("landcell", ctx.Landcell != 0 ? "0x" + ctx.Landcell.ToString("X8", CultureInfo.InvariantCulture) : "");
w.WriteNumber("pid", Math.Max(0, ctx.Pid));
w.WriteString("clientTime", utcNow.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture));
if (log == null || log.Text.Length == 0)
{
w.WriteNull("log");
}
else
{
w.WriteStartObject("log");
w.WriteString("name", CleanShort(log.FileName, MaxShortField));
w.WriteNumber("lines", log.Lines);
w.WriteNumber("bytes", log.Text.Length);
w.WriteBase64String("gzip", log.Gzip);
w.WriteEndObject();
}
w.WriteEndObject();
}
return ms.ToArray();
}
/// <summary>A plugin name as the server accepts it: letters, digits, space . _ - (40 at most).</summary>
public static string PluginName(string? name)
{
if (string.IsNullOrEmpty(name)) return "";
var sb = new StringBuilder();
foreach (char c in name)
if (c is (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or ' ' or '.' or '_' or '-')
sb.Append(c);
string s = sb.ToString().Trim();
return s.Length > 40 ? s.Substring(0, 40).Trim() : s;
}
// ── The endpoint ─────────────────────────────────────────────────────
/// <summary>
/// The URL reports go to: <paramref name="overrideUrl"/> (engine.json "ReportEndpoint", for
/// testing) when it is https, or http to this PC; otherwise the built-in one.
/// </summary>
public static string ResolveEndpoint(string? overrideUrl, out string? rejected)
{
rejected = null;
if (string.IsNullOrWhiteSpace(overrideUrl)) return DefaultEndpoint;
if (Uri.TryCreate(overrideUrl.Trim(), UriKind.Absolute, out Uri? u) && string.IsNullOrEmpty(u.UserInfo)
&& (u.Scheme == Uri.UriSchemeHttps
|| (u.Scheme == Uri.UriSchemeHttp && (u.IsLoopback || u.Host.Equals("localhost", StringComparison.OrdinalIgnoreCase)))))
return u.AbsoluteUri;
rejected = overrideUrl;
return DefaultEndpoint;
}
// ── The answer ───────────────────────────────────────────────────────
/// <summary>
/// What the player is told about the server's answer. True when the report was taken;
/// <paramref name="id"/> is its id (may be empty). Never throws.
/// </summary>
public static bool ReadResponse(int status, string? body, out string message, out string id)
{
id = "";
string serverError = "";
try
{
if (!string.IsNullOrWhiteSpace(body) && body.TrimStart().StartsWith('{'))
{
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
if (root.ValueKind == JsonValueKind.Object)
{
if (root.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.String)
id = CleanShort(idEl.GetString(), 40);
if (root.TryGetProperty("error", out var errEl) && errEl.ValueKind == JsonValueKind.String)
serverError = CleanShort(errEl.GetString(), 200);
}
}
}
catch (JsonException) { }
if (status is >= 200 and < 300)
{
message = id.Length > 0 ? $"Sent. Thank you! (report {id})" : "Sent. Thank you!";
return true;
}
message = status switch
{
429 => serverError.Length > 0 ? serverError : "Too many reports from here right now. Please try again later.",
413 => "The report is too large to send. Untick the log and try again.",
400 or 415 or 422 => serverError.Length > 0 ? "The server refused the report: " + serverError : "The server refused the report.",
404 => "The report service isn't available yet (HTTP 404).",
>= 500 => "The report service has a problem right now (HTTP " + status + "). Please try again later.",
_ => serverError.Length > 0 ? $"HTTP {status}: {serverError}" : $"The report service answered HTTP {status}.",
};
return false;
}
// ── The cooldown ─────────────────────────────────────────────────────
/// <summary>Milliseconds until the next report may be sent (0 = now). <paramref name="nextAllowedMs"/> is a TickCount64 value.</summary>
public static long CooldownLeft(long nowMs, long nextAllowedMs) => Math.Max(0, nextAllowedMs - nowMs);
/// <summary>"42 s" / "1 min 5 s".</summary>
public static string FormatWait(long ms)
{
long s = (ms + 999) / 1000;
return s < 60 ? $"{s} s" : $"{s / 60} min {s % 60} s";
}
/// <summary>"812 bytes" / "214 KB" / "1.4 MB".</summary>
public static string FormatSize(long bytes)
{
if (bytes < 1024) return bytes.ToString(CultureInfo.InvariantCulture) + " bytes";
if (bytes < 1024 * 1024) return ((bytes + 512) / 1024).ToString(CultureInfo.InvariantCulture) + " KB";
return (bytes / (1024.0 * 1024.0)).ToString("0.0", CultureInfo.InvariantCulture) + " MB";
}
/// <summary>The panel's line about the log: "RynthCore.1234.log: 1,987 lines, 214 KB (31 KB compressed), taken 14:02:11".</summary>
public static string DescribeTail(LogTail t) =>
$"{t.FileName}{(t.IncludesOld ? " (+ .old)" : "")}: {t.Lines.ToString("N0", CultureInfo.InvariantCulture)} lines, " +
$"{FormatSize(t.Text.Length)} ({FormatSize(t.Gzip.Length)} compressed), taken {t.TakenLocal:HH:mm:ss}";
}

View file

@ -67,6 +67,8 @@
<PackageReference Include="Avalonia.Skia" Version="11.2.3" />
<PackageReference Include="Avalonia.Themes.Simple" Version="11.2.3" />
<PackageReference Include="Avalonia.AvaloniaEdit" Version="11.2.0" />
<!-- Avalonia pulls Tmds.DBus.Protocol 0.20.0 (GHSA-xrw6-gwf8-vvr9; D-Bus is Linux-only, but pin the fixed version). -->
<PackageReference Include="Tmds.DBus.Protocol" Version="0.21.3" />
</ItemGroup>
<ItemGroup>

View file

@ -0,0 +1,103 @@
// ============================================================================
// RynthCore.Engine - UI/Data/BountiesData.cs
// The RynthILT plugin's ACECustom bounty tracker for the Bounties face (the
// ILT section; ported from SilentKelpie's rynth/RynthCore PR #5, where it
// read RynthAi).
//
// RynthILTGetBountiesJson frees its previous buffer on each call, so the hub
// is its only caller (BountiesSource, 1 s). The plugin also reads those polls
// as "the window is open": its quiet /bounty list reads run only while this
// source is subscribed AND polling. The source polls only on Infinite
// Leaftide (IltInfo.IsIlt), so a Bounties window left open anywhere else
// never makes RynthILT send anything. RynthILTBountyCommand runs on the pump
// (it changes state the plugin's tick uses) and refreshes the snapshot.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.UI.Data;
/// <summary>RynthILTGetBountiesJson while the Bounties face is open on ILT (1 s, and after each command).</summary>
internal sealed unsafe class BountiesSource : UiSource<BountiesSnapshot>
{
/// <summary>The plugin's display name (PluginExportBinder matches on it).</summary>
public const string PluginName = "RynthILT";
private delegate* unmanaged[Cdecl]<IntPtr> _get;
private string? _lastJson;
private volatile bool _exportMissing;
private volatile bool _notIlt;
public BountiesSource() : base("Bounties", periodMs: 1000) { }
/// <summary>True when RynthILT is loaded but has no RynthILTGetBountiesJson (an older or broken build).</summary>
public bool ExportMissing => _exportMissing;
/// <summary>True when the last poll was skipped because this isn't Infinite Leaftide.</summary>
public bool NotIlt => _notIlt;
protected internal override void Poll()
{
// Off ILT nothing is polled, so the plugin never thinks the window is open there.
if (!IltInfo.IsIlt)
{
_notIlt = true;
return;
}
_notIlt = false;
if (_get == null)
_get = (delegate* unmanaged[Cdecl]<IntPtr>)PluginExportBinder.Resolve(PluginName, "RynthILTGetBountiesJson");
_exportMissing = _get == null && PluginExportBinder.Resolve(PluginName, "RynthPluginTick") != IntPtr.Zero;
if (_get == null) return;
IntPtr ptr = _get();
string? json = ptr == IntPtr.Zero ? null : Marshal.PtrToStringUTF8(ptr);
if (string.IsNullOrEmpty(json) || json == _lastJson) return;
BountiesSnapshot? parsed;
try { parsed = BountiesSnapshot.Parse(json); }
catch { return; }
if (parsed == null) return;
_lastJson = json;
Publish(parsed);
}
protected internal override void Reset()
{
_get = null;
_lastJson = null;
_exportMissing = false;
ClearSnapshot();
}
}
internal static unsafe class BountiesCommands
{
private static delegate* unmanaged[Cdecl]<IntPtr, void> _command;
static BountiesCommands()
{
PluginManager.PluginsUnloaded += () => _command = null;
}
/// <summary>Re-reads /bounty list (the plugin keeps its own minimum interval).</summary>
public static void Refresh() => Send("refresh");
/// <summary>Sets one tracker option (refreshonkills, minrefreshseconds, periodicminutes, hideqblocked, sortbyprogress).</summary>
public static void Set(string option, string value) => Send($"set {option} {value}");
public static void Set(string option, bool on) => Send($"set {option} {(on ? "1" : "0")}");
private static void Send(string text) => UiDataHub.Post("Bounties " + text, () =>
{
if (!IltInfo.IsIlt) return;
if (_command == null)
_command = (delegate* unmanaged[Cdecl]<IntPtr, void>)PluginExportBinder.Resolve(BountiesSource.PluginName, "RynthILTBountyCommand");
if (_command == null) return;
IntPtr utf8 = Marshal.StringToCoTaskMemUTF8(text);
try { _command(utf8); }
finally { Marshal.FreeCoTaskMem(utf8); }
UiSources.Bounties.RequestRefresh();
});
}

View file

@ -0,0 +1,70 @@
// ============================================================================
// RynthCore.Engine - UI/Data/BountiesSnapshotJson.cs
// The Bounties window's JSON shape, as the RynthILT plugin's
// RynthILTGetBountiesJson writes it (mirrors
// RynthCore.Plugin.RynthILT.Bounty.BountyBridgePayload). Self-contained:
// RynthSuite's Tools/RynthILT.Tests links this file to check the plugin's
// output parses here.
//
// Compatibility: unknown properties are skipped and missing ones keep their
// defaults, so either side can add fields without breaking the other.
// ============================================================================
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Engine.UI.Data;
/// <summary>Where the player stands on one reward (the plugin's BountyStatus).</summary>
internal enum BountyRowStatus
{
Counting = 0,
Cooldown = 1,
NeedsQb = 2,
}
internal sealed class BountiesSnapshot
{
[JsonPropertyName("unsupported")] public bool Unsupported { get; set; }
[JsonPropertyName("reading")] public bool Reading { get; set; }
[JsonPropertyName("status")] public string Status { get; set; } = string.Empty;
/// <summary>Seconds since the last list read; -1 = never.</summary>
[JsonPropertyName("listedAgoSec")] public int ListedAgoSec { get; set; } = -1;
[JsonPropertyName("noneAnywhere")] public bool NoneAnywhere { get; set; }
[JsonPropertyName("lastEvent")] public string LastEvent { get; set; } = string.Empty;
[JsonPropertyName("lastEventAgoSec")] public int LastEventAgoSec { get; set; } = -1;
[JsonPropertyName("refreshOnKills")] public bool RefreshOnKills { get; set; }
[JsonPropertyName("minRefreshSeconds")] public int MinRefreshSeconds { get; set; }
[JsonPropertyName("periodicRefreshMinutes")] public int PeriodicRefreshMinutes { get; set; }
[JsonPropertyName("hideQbLocked")] public bool HideQbLocked { get; set; }
[JsonPropertyName("sortByProgress")] public bool SortByProgress { get; set; }
/// <summary>Rows the plugin left out because of HideQbLocked.</summary>
[JsonPropertyName("hiddenCount")] public int HiddenCount { get; set; }
[JsonPropertyName("rows")] public List<BountyRowJson> Rows { get; set; } = new();
/// <summary>Parses one RynthILTGetBountiesJson reply; null for "null". Throws on malformed JSON.</summary>
public static BountiesSnapshot? Parse(string json) =>
JsonSerializer.Deserialize(json, BountiesJsonContext.Default.BountiesSnapshot);
}
/// <summary>One reward of one bounty area, with the status as of the plugin's poll.</summary>
internal sealed class BountyRowJson
{
[JsonPropertyName("where")] public string Where { get; set; } = string.Empty;
[JsonPropertyName("amount")] public long Amount { get; set; }
[JsonPropertyName("item")] public string Item { get; set; } = string.Empty;
[JsonPropertyName("killsRequired")] public int KillsRequired { get; set; }
[JsonPropertyName("cooldownSeconds")] public int CooldownSeconds { get; set; }
/// <summary>A <see cref="BountyRowStatus"/> value; an ended cooldown already reads Counting.</summary>
[JsonPropertyName("status")] public int Status { get; set; }
[JsonPropertyName("kills")] public int Kills { get; set; }
[JsonPropertyName("unlockInSec")] public int UnlockInSec { get; set; }
[JsonPropertyName("qbRequired")] public long QbRequired { get; set; }
[JsonPropertyName("qbHave")] public long QbHave { get; set; }
/// <summary>Kills went up (or an award reset them) in the last 15 seconds.</summary>
[JsonPropertyName("changed")] public bool Changed { get; set; }
}
[JsonSerializable(typeof(BountiesSnapshot))]
internal partial class BountiesJsonContext : JsonSerializerContext { }

View file

@ -5,7 +5,9 @@
//
// • ChatSource (hub, 100 ms) pulls new lines from RynthChatGetScrollbackJson
// on the pump thread, keeps the newest 500, routes and colours them with
// the rules, and writes the chat log.
// the rules, and writes the chat log. It also hands each new line to the
// Discord relay and ticks it (UI/Data/Discord/ChatDiscord.cs), which keeps
// this source subscribed while it is on.
// • ChatModel holds the settings (rynthchat_settings.json), the regex
// rules and custom tabs, and the chat input line.
//
@ -82,6 +84,9 @@ internal sealed class ChatLine
/// <summary>Engine-assigned, increasing for the whole session (the plugin's own
/// seq restarts after RL).</summary>
public long Id { get; }
/// <summary>RynthChat's own number for the line (restarts when its plugin reloads); 0 when not
/// from RynthChat. The Discord relay tells news from scrollback by it.</summary>
public ulong Seq { get; init; }
public string Timestamp { get; }
/// <summary>The channel tab it belongs to (ChatClassifier in the plugin).</summary>
public string Channel { get; }
@ -247,7 +252,7 @@ internal sealed class ChatFilterRule
}
}
/// <summary>New RynthChat lines while a chat face is open (100 ms). Publishes the newest 500, routed.</summary>
/// <summary>New RynthChat lines while a chat face or the Discord relay holds it (100 ms). Publishes the newest 500, routed.</summary>
internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
{
private const int MaxLines = 500;
@ -261,6 +266,17 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
public ChatSource() : base("Chat", periodMs: 100) { }
protected internal override void Poll()
{
try { PollLines(); }
finally
{
// Every poll, new lines or not: due Discord posts, results, retries.
try { Discord.ChatDiscord.PumpTick(); }
catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay tick failed ({ex.GetType().Name}: {ex.Message})."); }
}
}
private void PollLines()
{
if (_get == null)
{
@ -300,12 +316,20 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
IntPtr ptr = _get(_sinceSeq);
if (ptr == IntPtr.Zero) return;
string? json = Marshal.PtrToStringAnsi(ptr);
if (string.IsNullOrEmpty(json) || json == "[]") return;
if (string.IsNullOrEmpty(json) || json == "[]")
{
RelayRead(Array.Empty<ChatLine>());
return;
}
RynthChatLineDto[]? dtos = ParseLines(json, out ulong skippedSeq);
// Lines that couldn't be read still move the mark past them, or they'd come back every poll.
if (skippedSeq > _sinceSeq) _sinceSeq = skippedSeq;
if (dtos == null || dtos.Length == 0) return;
if (dtos == null || dtos.Length == 0)
{
RelayRead(Array.Empty<ChatLine>());
return;
}
var added = new List<ChatLine>(dtos.Length);
foreach (RynthChatLineDto dto in dtos)
@ -314,12 +338,19 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
_sinceSeq = dto.Seq;
string text = StripAcLinks(dto.Text ?? "", out string? linkedName);
var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type,
dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text);
dto.Sender is { Length: > 0 } s ? StripAcLinks(s, out _) : linkedName, text)
{
Seq = dto.Seq,
};
line.Route = router.Evaluate(line, null);
if (line.Route.Mention) ChatModel.PumpMentionSound();
added.Add(line);
}
if (added.Count == 0) return;
if (added.Count == 0)
{
RelayRead(added);
return;
}
ChatLine[] old = Current?.Value ?? Array.Empty<ChatLine>();
int keepOld = Math.Max(0, Math.Min(old.Length, MaxLines - added.Count));
@ -329,6 +360,14 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
added.CopyTo(skipAdded, lines, keepOld, added.Count - skipAdded);
Publish(lines);
ChatModel.PumpLog(added);
RelayRead(added);
}
/// <summary>Every scrollback read goes to the Discord relay, empty or not (its first read is a baseline).</summary>
private static void RelayRead(IReadOnlyList<ChatLine> added)
{
try { Discord.ChatDiscord.PumpRead(added); }
catch (Exception ex) { RynthLog.UI($"ChatSource: Discord relay skipped {added.Count} line(s) ({ex.GetType().Name}: {ex.Message})."); }
}
private int _badLinesLogged;
@ -413,6 +452,7 @@ internal sealed unsafe class ChatSource : UiSource<ChatLine[]>
// The lines already shown stay.
_get = null;
_sinceSeq = 0;
Discord.ChatDiscord.PumpSourceReset();
ChatModel.SendLinePtr = IntPtr.Zero;
ChatModel.PluginBound = false;
}

View file

@ -0,0 +1,664 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscord.cs
// RynthChat's Discord relay: copies chosen chat (speech channels, or every
// line that shows in a chat tab) to Discord channels by webhook or bot.
// Configured in the Chat panel's settings (gear > Discord) and its Discord
// panel (ImGui/Panels/ChatDiscordFace.cs); /rc discord for quick control.
//
// Threads
// • ChatSource.Poll (the pump) hands every scrollback read to PumpRead and
// calls PumpTick each poll: routing, batching, at most one HTTP post per
// route in flight, applying results. The relay keeps the chat feed
// subscribed while it is on (or its panel is open), so it runs with the
// Chat panel closed.
// • The panel and /rc discord (AC's thread) edit Settings in place and
// queue Resume / Send test / Clear log; secrets are encrypted and the
// file written on UiBackgroundWriter, never on AC's thread.
// • HTTP posts run on the thread pool and hand results back through a queue.
//
// Per route, lines arriving within the batch window go out as one message
// (<= 2000 characters), spaced by the route's minimum interval or whatever
// Discord's rate limit asks for. Network / 5xx failures retry with backoff;
// 400 / 401 / 403 / 404 pause the route until it's resumed or its
// credential changes. Scrollback read when the relay starts (engine start,
// hot reload, switching it on) is not sent: the first read after it comes
// on is a baseline, judged by RynthChat's line seq (DiscordBacklogGate).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.UI.Data.Discord;
internal enum DiscordLogKind { Sent, Error, Info }
/// <summary>One line in the Discord panel's log (immutable once added).</summary>
internal sealed record DiscordLogEntry(DateTime Time, DiscordLogKind Kind, string Route, string Text);
internal static class ChatDiscord
{
private static ChatDiscordSettings _settings = new();
private static int _loaded;
private static readonly string FilePath = ChatDiscordStore.DefaultPath;
// Any thread -> pump.
private static readonly ConcurrentQueue<(DiscordRoute Route, DiscordBatch Batch, DiscordSendResult Result)> Done = new();
private static readonly ConcurrentQueue<DiscordRoute> ResumeQueue = new();
private static readonly ConcurrentQueue<DiscordRoute> TestQueue = new();
private static volatile bool _clearLog;
private static volatile bool _shutdown;
private static readonly CancellationTokenSource Cts = new();
private static int _postsRunning;
// Pump only.
private static readonly Dictionary<DiscordRoute, DiscordRouteQueue> States = new(ReferenceEqualityComparer.Instance);
private static readonly List<DiscordLogEntry> Log = new();
// Pump writes, panel reads.
private static DiscordLogEntry[] _logSnapshot = Array.Empty<DiscordLogEntry>();
// The chat feed (UiSources.Chat) is held while some character has the relay on, or its panel is open.
private static int _feedHeld, _panelsOpen;
// Pump only: keeps the scrollback read when the relay comes on out of Discord.
private static readonly DiscordBacklogGate Backlog = new();
// The character playing, as the pump last saw it (the panel can't ask: the lookup may read a file).
private static string _characterName = string.Empty;
// Per-character switch. A switch is applied to the in-memory list at once and queued as an
// op; the next save (background writer) merges the queued ops into the file's list. Until
// that save lands, _pending says what this client's character asked for, so an older
// merge or refresh can't switch it back on (or off) meanwhile.
private sealed record SelfPending(DiscordCharacter Character, bool On);
private static readonly ConcurrentQueue<(DiscordCharacterOp Op, SelfPending? Pending)> CharacterOps = new();
private static SelfPending? _pending;
// Another client may switch characters in the file: the pump looks at its time every few
// seconds and re-reads the list (only the list) when it changed.
private const int FileCheckMs = 3000;
private static long _nextFileCheckMs;
private static long _fileStampTicks;
private static int _refreshQueued;
/// <summary>The live settings. Any thread; fields are edited in place (see ChatDiscordSettings).</summary>
public static ChatDiscordSettings Settings => Volatile.Read(ref _settings);
/// <summary>The character this client relays as ("" before login). Any thread.</summary>
public static string CharacterName => Volatile.Read(ref _characterName);
/// <summary>The character logged in on this client (server + name), or null before login. Any thread.</summary>
public static DiscordCharacter? CurrentCharacter()
=> DiscordCharacter.Of(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName);
/// <summary>True when the relay is on for <paramref name="character"/>. Any thread.</summary>
public static bool IsOn(DiscordCharacter? character)
{
if (character == null) return false;
SelfPending? p = Volatile.Read(ref _pending);
if (p != null && p.Character.Same(character)) return p.On;
return Settings.IsOnFor(character);
}
/// <summary>True when the relay is on for the character logged in here. Any thread.</summary>
public static bool IsOnHere => IsOn(CurrentCharacter());
// ── Setup (InitWorker / panel) ───────────────────────────────────────
/// <summary>Loads the settings once (file I/O: InitWorker or a background thread) and opens the feed if on.</summary>
public static void EnsureLoaded()
{
if (Interlocked.Exchange(ref _loaded, 1) != 0) return;
ChatDiscordSettings s = ChatDiscordStore.Load(FilePath, out string note);
Volatile.Write(ref _settings, s);
Interlocked.Exchange(ref _fileStampTicks, FileStampTicks());
if (note.Length > 0) RynthLog.UI($"ChatDiscord: {note}.");
// Subscribing touches UiSources; done on the pump, like every other hub change.
UiDataHub.Post("chat discord feed", SyncFeed);
}
/// <summary>
/// Turns the relay on or off for the character logged in here (and saves). False before
/// login: there is no character to switch. Any thread.
/// </summary>
public static bool SetEnabled(bool on)
{
DiscordCharacter? me = CurrentCharacter();
if (me == null) return false;
if (IsOn(me) == on) return true;
var pending = new SelfPending(me, on);
Volatile.Write(ref _pending, pending);
SwitchCharacter(new DiscordCharacterOp(me, on), pending);
return true;
}
/// <summary>Turns the relay off for another character (the panel's list). Any thread.</summary>
public static void TurnOffFor(DiscordCharacter character)
{
DiscordCharacter? me = CurrentCharacter();
if (character.Same(me)) { SetEnabled(false); return; }
SwitchCharacter(new DiscordCharacterOp(character, false), null);
}
private static void SwitchCharacter(DiscordCharacterOp op, SelfPending? pending)
{
var s = Settings;
s.Characters = ChatDiscordStore.ApplyCharacterOps(s.Characters, new[] { op });
CharacterOps.Enqueue((op, pending));
Save();
SyncFeed();
}
/// <summary>The Discord panel opened / closed: it keeps the feed (and so the relay's tick) running. AC thread.</summary>
public static void PanelShown(bool shown)
{
int n = shown ? Interlocked.Increment(ref _panelsOpen) : Interlocked.Decrement(ref _panelsOpen);
if (n < 0) Interlocked.Exchange(ref _panelsOpen, 0);
SyncFeed();
}
/// <summary>
/// Holds the chat feed while any character on this PC has the relay on (the pump then decides
/// for the one logged in, who may only be known after login or a hot reload) or the panel is open.
/// </summary>
private static void SyncFeed()
{
bool want = !_shutdown
&& (Settings.Characters.Length > 0 || Volatile.Read(ref _pending) is { On: true }
|| Volatile.Read(ref _panelsOpen) > 0);
if (want)
{
if (Interlocked.CompareExchange(ref _feedHeld, 1, 0) == 0)
{
UiSources.Chat.Subscribe();
UiSources.Chat.RequestRefresh();
}
}
else if (Interlocked.CompareExchange(ref _feedHeld, 0, 1) == 1)
UiSources.Chat.Unsubscribe();
}
/// <summary>Saves in the background (the JSON is taken now; the character list is merged then). Any thread.</summary>
public static void Save()
{
string json;
try { json = ChatDiscordStore.Serialize(Settings); }
catch (Exception ex)
{
RynthLog.UI($"ChatDiscord: settings not saved ({ex.GetType().Name}: {ex.Message}).");
return;
}
UiBackgroundWriter.Enqueue("persist chat discord", () => WriteMerged(json));
}
/// <summary>
/// Background writer: re-reads the file, applies this client's queued character switches to
/// its list, writes our settings with that list, and takes the list back. Other clients'
/// switches survive; ours win for our own character.
/// </summary>
private static void WriteMerged(string ours)
{
var ops = new List<(DiscordCharacterOp Op, SelfPending? Pending)>();
while (CharacterOps.TryDequeue(out var o)) ops.Add(o);
var plain = new List<DiscordCharacterOp>(ops.Count);
foreach (var o in ops) plain.Add(o.Op);
try
{
string? disk = null;
try { if (File.Exists(FilePath)) disk = File.ReadAllText(FilePath); }
catch (IOException) { }
string json = ChatDiscordStore.MergeForSave(ours, disk, plain, out DiscordCharacter[] merged);
ChatDiscordStore.Write(FilePath, json);
Interlocked.Exchange(ref _fileStampTicks, FileStampTicks());
Settings.Characters = merged;
}
catch
{
// Not written: keep the switches for the next save.
foreach (var o in ops) CharacterOps.Enqueue(o);
throw;
}
// Saved: the file now says what our character asked for (unless it asked again since).
foreach (var o in ops)
if (o.Pending != null) Interlocked.CompareExchange(ref _pending, null, o.Pending);
SyncFeed();
}
/// <summary>Pump: every few seconds, re-reads the character list if another client changed the file.</summary>
private static void CheckFile(long now)
{
if (now < Volatile.Read(ref _nextFileCheckMs)) return;
Volatile.Write(ref _nextFileCheckMs, now + FileCheckMs);
if (FileStampTicks() == Interlocked.Read(ref _fileStampTicks)) return;
if (Interlocked.Exchange(ref _refreshQueued, 1) != 0) return;
// On the writer, so it can't land between a save's read and write.
UiBackgroundWriter.Enqueue("refresh chat discord characters", () =>
{
try
{
long stamp = FileStampTicks();
string? disk = File.Exists(FilePath) ? File.ReadAllText(FilePath) : null;
DiscordCharacter[]? list = ChatDiscordStore.ReadCharacters(disk);
Interlocked.Exchange(ref _fileStampTicks, stamp);
// Switches still queued here go in with the next save; keep them in view.
if (list != null)
{
var queued = new List<DiscordCharacterOp>();
foreach (var o in CharacterOps) queued.Add(o.Op);
Settings.Characters = ChatDiscordStore.ApplyCharacterOps(list, queued);
}
}
finally { Interlocked.Exchange(ref _refreshQueued, 0); }
SyncFeed();
});
}
private static long FileStampTicks()
{
try { return File.Exists(FilePath) ? File.GetLastWriteTimeUtc(FilePath).Ticks : 0; }
catch (Exception) { return 0; }
}
/// <summary>
/// Engine shutdown, after the pump stopped: cancels posts in flight, gives them a moment to
/// unwind (they'd otherwise finish in this dying generation's code), then disposes the HTTP
/// client so nothing of it keeps the generation from unloading.
/// </summary>
public static void Shutdown()
{
_shutdown = true;
try { Cts.Cancel(); } catch { }
var wait = System.Diagnostics.Stopwatch.StartNew();
while (Volatile.Read(ref _postsRunning) > 0 && wait.ElapsedMilliseconds < 1000) Thread.Sleep(10);
int left = Volatile.Read(ref _postsRunning);
if (left > 0) RynthLog.UI($"ChatDiscord: {left} post(s) still running at shutdown; closing the HTTP client under them.");
DiscordClient.Shutdown();
while (Done.TryDequeue(out _)) { }
try { Cts.Dispose(); } catch { }
}
// ── Panel / command requests (any thread) ────────────────────────────
/// <summary>Clears a pause on <paramref name="route"/> (the Resume button, or a credential change).</summary>
public static void Resume(DiscordRoute route) => ResumeQueue.Enqueue(route);
/// <summary>Posts a test line to <paramref name="route"/> (ignoring its filters) and resumes it.</summary>
public static void SendTest(DiscordRoute route)
{
ResumeQueue.Enqueue(route);
TestQueue.Enqueue(route);
}
public static void ClearLog() => _clearLog = true;
public static DiscordLogEntry[] LogSnapshot() => Volatile.Read(ref _logSnapshot);
/// <summary>
/// Stores a pasted webhook URL on <paramref name="route"/>, encrypted on the background writer.
/// Returns an error for the panel, or empty when accepted. The plain text is not kept.
/// </summary>
public static string SetWebhook(DiscordRoute route, string url)
{
if (!DiscordFormat.TryNormalizeWebhookUrl(url, out string normalized))
return "That isn't a Discord webhook URL (https://discord.com/api/webhooks/<id>/<token>).";
UiBackgroundWriter.Enqueue("protect discord webhook", () =>
{
route.WebhookProtected = DiscordSecrets.Protect(normalized);
Save();
Resume(route);
});
return string.Empty;
}
/// <summary>Stores a pasted bot token (encrypted on the background writer). Returns an error, or empty.</summary>
public static string SetBotToken(DiscordRoute route, string token)
{
if (!DiscordFormat.LooksLikeBotToken(token))
return "That doesn't look like a bot token (Developer Portal > Bot > Reset Token).";
string trimmed = token.Trim();
UiBackgroundWriter.Enqueue("protect discord bot token", () =>
{
route.BotTokenProtected = DiscordSecrets.Protect(trimmed);
Save();
Resume(route);
});
return string.Empty;
}
// ── Pump ─────────────────────────────────────────────────────────────
/// <summary>
/// One read of RynthChat's scrollback (the new lines, already routed by the chat rules; empty
/// when nothing was new). ChatSource.Poll, pump thread, after every read, so the first read
/// after the relay comes on can be taken as the baseline (DiscordBacklogGate).
/// </summary>
internal static void PumpRead(IReadOnlyList<ChatLine> added)
{
if (_shutdown) return;
var seqs = new ulong[added.Count];
for (int i = 0; i < seqs.Length; i++) seqs[i] = added[i].Seq;
bool baseline = !Backlog.Live;
bool[] post = Backlog.Admit(RelayOn(), seqs);
if (baseline && Backlog.Live && added.Count > 0)
RynthLog.UI($"ChatDiscord: {added.Count} line(s) of scrollback not relayed (relay started).");
if (Array.IndexOf(post, true) < 0) return;
var s = Settings;
DiscordRoute[] routes = s.Routes;
if (routes.Length == 0) return;
string me = SafeName(ChatModel.PumpCharacterName());
// Lines reach here within a poll (100 ms) of being printed: now is their time.
DateTime time = DateTime.Now;
long nowMs = Environment.TickCount64;
// Keyword lists parsed once per batch of lines (the panel may edit them between polls).
var keywords = new List<string>[routes.Length];
for (int i = 0; i < routes.Length; i++) keywords[i] = DiscordFormat.SplitList(routes[i].Keywords);
for (int n = 0; n < added.Count; n++)
{
if (!post[n]) continue;
ChatLine line = added[n];
ChatRoute chatRoute = line.Route;
if (s.SkipHidden && chatRoute.Hidden) continue;
if (!ChatDiscordLogic.TryClassify(line.Text, line.ChatType, me, out DiscordLineParts parts)) continue;
if (parts.Own && s.SkipOwn) continue;
string channel = line.Channel;
bool ShowsIn(string tab) => chatRoute.ShowsIn(tab, channel);
for (int i = 0; i < routes.Length; i++)
{
DiscordRoute route = routes[i];
if (!route.Enabled || !route.HasSecret) continue;
if (!ChatDiscordLogic.Wants(route, parts.Speech, ShowsIn, out string label)) continue;
if (!DiscordFormat.MatchesKeywords(parts.Haystack, keywords[i])) continue;
DiscordRouteQueue q = State(route);
NoteRetargeted(route, Retarget(q, route));
if (q.Paused) continue;
if (!q.NoteFresh(ChatDiscordLogic.DedupKey(parts, label), nowMs)) continue;
q.Add(ChatDiscordLogic.Format(s, time, parts, label, me), nowMs, s.MaxQueue);
}
}
}
/// <summary>RynthChat's scrollback numbering restarted (ChatSource.Reset, its plugin reloaded). Pump thread.</summary>
internal static void PumpSourceReset() => Backlog.SourceReset();
/// <summary>Applies requests and results, starts due posts, publishes status. ChatSource.Poll, pump thread.</summary>
internal static void PumpTick()
{
if (_shutdown) return;
long now = Environment.TickCount64;
var s = Settings;
DiscordRoute[] routes = s.Routes;
Volatile.Write(ref _characterName, SafeName(ChatModel.PumpCharacterName()));
CheckFile(now);
bool relayOn = RelayOn();
if (!relayOn) Backlog.Off();
PruneStates(routes);
while (ResumeQueue.TryDequeue(out var r))
if (States.TryGetValue(r, out var q)) q.Resume();
while (Done.TryDequeue(out var d)) ApplyResult(d.Route, d.Batch, d.Result, now);
while (TestQueue.TryDequeue(out var t)) QueueTest(t);
if (_clearLog)
{
_clearLog = false;
Log.Clear();
Volatile.Write(ref _logSnapshot, Array.Empty<DiscordLogEntry>());
}
foreach (var route in routes)
{
// Off means off: the relay or the route switched off drops what the route had
// queued, the batch waiting to retry and the post in flight. Only a test goes.
if (!States.TryGetValue(route, out var q)) continue;
if (!(relayOn && route.Enabled)) NoteStopped(route, q.Stop());
// A new webhook / token / channel: what was queued for the old one isn't sent to it.
NoteRetargeted(route, Retarget(q, route));
StartNextPost(s, route, relayOn, now);
}
PublishStatus(routes);
}
/// <summary>Whether this client relays at all right now: the relay is on for the character logged in.</summary>
private static bool RelayOn() => IsOnHere;
private static DiscordRouteQueue State(DiscordRoute route)
{
if (!States.TryGetValue(route, out var q)) States[route] = q = new DiscordRouteQueue();
return q;
}
private static void PruneStates(DiscordRoute[] routes)
{
if (States.Count <= routes.Length) return;
var live = new HashSet<DiscordRoute>(routes, ReferenceEqualityComparer.Instance);
var gone = new List<DiscordRoute>();
foreach (var r in States.Keys) if (!live.Contains(r)) gone.Add(r);
foreach (var r in gone)
{
// A removed route's post in flight (test or not) is cancelled; its result then finds
// no queue and is dropped.
DiscordRouteQueue q = States[r];
q.Stop();
if (q.InFlight is { } flying)
{
try { flying.Cancel?.Cancel(); } catch (ObjectDisposedException) { }
}
States.Remove(r);
}
}
/// <summary>
/// Tells <paramref name="q"/> where <paramref name="route"/> sends now (its mode, channel and
/// saved, encrypted credential); a change drops what was queued for the old destination.
/// </summary>
private static int Retarget(DiscordRouteQueue q, DiscordRoute route)
=> q.Retarget(route.Mode, route.ChannelId,
route.Mode == DiscordRoute.ModeBot ? route.BotTokenProtected : route.WebhookProtected);
private static void NoteRetargeted(DiscordRoute route, int dropped)
{
if (dropped > 0) AddLog(Settings, DiscordLogKind.Info, route.Name, $"Destination changed: {dropped} line(s) queued for the old one dropped.");
}
private static void NoteStopped(DiscordRoute route, int dropped)
{
if (dropped > 0) AddLog(Settings, DiscordLogKind.Info, route.Name, $"Off: {dropped} queued line(s) dropped.");
}
private static void QueueTest(DiscordRoute route)
{
string me = SafeName(ChatModel.PumpCharacterName());
string line = DiscordFormat.FormatLine(DateTime.Now, null, null,
$"RynthChat Discord relay test from {(me.Length > 0 ? me : "RynthCore")} (route \"{route.Name}\").",
Settings.IncludeTimestamp, null);
State(route).QueueTest(line);
}
private static void StartNextPost(ChatDiscordSettings s, DiscordRoute route, bool relayOn, long now)
{
if (!States.TryGetValue(route, out var q)) return;
DiscordBatch? batch = q.Next(now, relayOn && route.Enabled, s.BatchFor(route), s.IntervalFor(route));
if (batch == null) return;
// Decrypt only now, on the way out; the plain text lives in the request task alone.
string mode = route.Mode, channelId = route.ChannelId;
string blob = mode == DiscordRoute.ModeBot ? route.BotTokenProtected : route.WebhookProtected;
if (blob.Length == 0)
{
ApplyResult(route, batch, DiscordSendResult.Fail(
mode == DiscordRoute.ModeBot ? "no bot token saved" : "no webhook URL saved", permanent: true), now);
return;
}
if (!DiscordSecrets.TryUnprotect(blob, out string secret))
{
ApplyResult(route, batch, DiscordSendResult.Fail(
"the saved credential can't be read on this Windows user; paste it again", permanent: true), now);
return;
}
string displayName = route.DisplayName.Length > 0 ? route.DisplayName : SafeName(ChatModel.PumpCharacterName());
// Each post can be cancelled on its own (Stop, a removed route) or with the engine.
CancellationTokenSource cts;
try { cts = CancellationTokenSource.CreateLinkedTokenSource(Cts.Token); }
catch (ObjectDisposedException) { return; } // shutting down
batch.Cancel = cts;
Interlocked.Increment(ref _postsRunning);
_ = Task.Run(async () =>
{
DiscordSendResult r;
try
{
r = mode == DiscordRoute.ModeBot
? await DiscordClient.PostBotAsync(secret, channelId, batch.Content, cts.Token).ConfigureAwait(false)
: await DiscordClient.PostWebhookAsync(secret, batch.Content, displayName, cts.Token).ConfigureAwait(false);
}
catch (Exception ex) { r = DiscordSendResult.Fail(DiscordFormat.Redact(ex.Message, secret)); }
finally
{
batch.Cancel = null;
cts.Dispose();
Interlocked.Decrement(ref _postsRunning);
}
Done.Enqueue((route, batch, r));
});
}
private static void ApplyResult(DiscordRoute route, DiscordBatch batch, DiscordSendResult r, long now)
{
// A route removed meanwhile has no queue: nothing to retry, nothing to report.
if (!States.TryGetValue(route, out var q)) return;
var s = Settings;
switch (q.Apply(batch, r, now, s.IntervalFor(route)))
{
case DiscordOutcome.Sent:
AddLog(s, DiscordLogKind.Sent, route.Name, batch.IsTest ? "Test message sent." : $"{batch.Lines.Count} line(s): {batch.Content}");
break;
case DiscordOutcome.Paused:
AddLog(s, DiscordLogKind.Error, route.Name, $"Paused: {r.Error}");
RynthLog.UI($"ChatDiscord: route '{route.Name}' paused: {r.Error}");
break;
case DiscordOutcome.RateLimited:
AddLog(s, DiscordLogKind.Info, route.Name, r.Error);
break;
case DiscordOutcome.GaveUp:
AddLog(s, DiscordLogKind.Error, route.Name, $"Gave up after {batch.Attempts} tries ({r.Error}); {batch.Lines.Count} line(s) dropped.");
RynthLog.UI($"ChatDiscord: route '{route.Name}' dropped a batch: {r.Error}");
break;
case DiscordOutcome.Retrying:
AddLog(s, DiscordLogKind.Error, route.Name, $"{r.Error}; retrying in {q.BackoffMs / 1000}s.");
break;
case DiscordOutcome.Retargeted:
AddLog(s, DiscordLogKind.Info, route.Name, $"{r.Error}; the destination changed meanwhile, so {batch.Lines.Count} line(s) dropped.");
break;
}
}
private static void PublishStatus(DiscordRoute[] routes)
{
foreach (var route in routes)
{
if (!States.TryGetValue(route, out var q)) continue;
int queued = q.Queued;
DiscordRouteStatus? old = route.Status;
if (old != null && old.Queued == queued && old.MessagesSent == q.MessagesSent && old.Dropped == q.Dropped
&& old.Paused == q.Paused && ReferenceEquals(old.LastError, q.LastError) && old.LastSent == q.LastSent)
continue;
route.Status = new DiscordRouteStatus(queued, q.MessagesSent, q.LinesSent, q.Dropped, q.Paused, q.LastError, q.LastSent);
}
}
private static void AddLog(ChatDiscordSettings s, DiscordLogKind kind, string route, string text)
{
Log.Add(new DiscordLogEntry(DateTime.Now, kind, route, text));
if (Log.Count > s.MaxLog) Log.RemoveRange(0, Log.Count - s.MaxLog);
Volatile.Write(ref _logSnapshot, Log.ToArray());
}
private static string SafeName(string? name) => (name ?? string.Empty).Trim().TrimStart('+');
// ── Status and /rc discord ───────────────────────────────────────────
/// <summary>"2 of 3 route(s) ready." Any thread.</summary>
public static string StatusLine()
{
var s = Settings;
int ready = 0;
foreach (var r in s.Routes) if (r.Enabled && r.HasSecret) ready++;
return $"{ready} of {s.Routes.Length} route(s) ready.";
}
/// <summary>"On for Bob (Aelrynth)." / "Off for Bob (Aelrynth)." / "Log in to switch it on." Any thread.</summary>
public static string SwitchLine()
{
DiscordCharacter? me = CurrentCharacter();
if (me == null) return "Log in to switch it on for a character.";
return $"{(IsOn(me) ? "On" : "Off")} for {me}.";
}
/// <summary>
/// /rc discord [on|off|status|test [route]|resume [route]]. Returns the reply lines ("window"
/// is handled by the caller: it opens the panel). AC's thread.
/// </summary>
public static List<string> HandleCommand(string args)
{
var reply = new List<string>();
var s = Settings;
string[] parts = (args ?? string.Empty).Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
string rest = parts.Length > 1 ? parts[1] : string.Empty;
switch (verb)
{
case "on":
case "off":
if (!SetEnabled(verb == "on"))
{
reply.Add("Log in first: the relay is switched on or off for the character you're playing.");
break;
}
reply.Add($"Discord relay {verb} for {CurrentCharacter()}. {StatusLine()}");
break;
case "test":
case "resume":
// The relay's tick runs while the chat feed is held (a character on, or the panel open).
if (verb == "test" && Volatile.Read(ref _feedHeld) == 0)
{
reply.Add("The relay is off: /rc discord on, or use Send test in the Discord panel (/rc discord window).");
break;
}
int n = 0;
foreach (var r in s.Routes)
{
if (rest.Length > 0 && !r.Name.Equals(rest, StringComparison.OrdinalIgnoreCase)) continue;
if (verb == "test") SendTest(r); else Resume(r);
n++;
}
reply.Add(n == 0
? $"No route{(rest.Length > 0 ? $" named '{rest}'" : "s")}. Add one in Chat > gear > Discord (or /rc discord window)."
: $"{(verb == "test" ? "Test sent to" : "Resumed")} {n} route(s).");
break;
default:
reply.Add($"Discord relay: {SwitchLine()} {StatusLine()}");
if (s.Characters.Length > 0)
reply.Add(" On for: " + string.Join(", ", Array.ConvertAll(s.Characters, c => c.ToString())));
foreach (var r in s.Routes)
{
var st = r.Status;
reply.Add($" {r.Name}: {(r.Enabled ? "on" : "off")}, {(r.HasSecret ? r.Mode : "no destination set")}"
+ (st == null ? string.Empty
: $", {st.MessagesSent} sent, {st.Queued} queued, {st.Dropped} dropped{(st.Paused ? ", PAUSED" : string.Empty)}"
+ (st.LastError.Length > 0 ? $" - {st.LastError}" : string.Empty)));
}
reply.Add("/rc discord on|off (this character) | window | test [route] | resume [route] | status");
break;
}
return reply;
}
}

View file

@ -0,0 +1,134 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscordLogic.cs
// The relay's per-line decisions, kept free of engine state so
// tools/ChatDiscordTests can run them: what a chat line is (speech on a
// channel, or plain text), whether a route wants it and under which label,
// how it is written for Discord, and whether it is scrollback from before
// the relay started (DiscordBacklogGate, by RynthChat's line seq).
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>A chat line split for the relay. <see cref="Speech"/> null: not player speech.</summary>
internal readonly record struct DiscordLineParts(SpeechChannel? Speech, string Speaker, string Message, bool Own)
{
/// <summary>"Speaker message" (or the message alone): what route keywords are matched against.</summary>
public string Haystack => Speaker.Length > 0 ? Speaker + " " + Message : Message;
}
internal static class ChatDiscordLogic
{
/// <summary>
/// Splits <paramref name="text"/> (AC's name links already stripped). Player speech gets its
/// channel and speaker (yours as <paramref name="me"/> when known); anything else is the text
/// alone. False for blank lines.
/// </summary>
public static bool TryClassify(string? text, int chatType, string me, out DiscordLineParts parts)
{
parts = default;
if (string.IsNullOrWhiteSpace(text)) return false;
if (ChatSpeech.TryParse(text, chatType, out var ch, out string who, out string msg, out bool own))
{
parts = new DiscordLineParts(ch, own && me.Length > 0 ? me : who, msg, own);
return true;
}
string plain = ChatSpeech.Decode(text).Trim();
if (plain.Length == 0) return false;
parts = new DiscordLineParts(null, string.Empty, plain, false);
return true;
}
/// <summary>
/// True when <paramref name="route"/> takes the line: its speech channel is ticked, or the line
/// shows in one of the route's tabs (<paramref name="showsInTab"/>). <paramref name="label"/> is
/// what the Discord line is tagged with: the speech channel, else the tab that matched.
/// </summary>
public static bool Wants(DiscordRoute route, SpeechChannel? speech, Func<string, bool> showsInTab, out string label)
{
label = string.Empty;
if (speech is { } ch && route.RelaysSpeech(ch))
{
label = ChatSpeech.Name(ch);
return true;
}
foreach (string tab in route.Tabs)
{
if (!showsInTab(tab)) continue;
label = speech is { } c ? ChatSpeech.Name(c) : tab;
return true;
}
return false;
}
/// <summary>The Discord text for one relayed line.</summary>
public static string Format(ChatDiscordSettings s, DateTime time, in DiscordLineParts parts, string label, string me)
=> DiscordFormat.FormatLine(time, label.Length > 0 ? label : null,
parts.Speech != null && parts.Speaker.Length > 0 ? parts.Speaker : null,
parts.Message, s.IncludeTimestamp, s.TagCharacter && me.Length > 0 ? me : null);
/// <summary>Key for the per-route repeat filter (the same line twice within a few seconds).</summary>
public static string DedupKey(in DiscordLineParts parts, string label) => $"{label}|{parts.Speaker}|{parts.Message}";
/// <summary>Drops dedup entries older than <paramref name="windowMs"/>.</summary>
public static void PruneRecent(Dictionary<string, long> recent, long now, int windowMs)
{
List<string>? stale = null;
foreach (var kv in recent)
if (now - kv.Value > windowMs) (stale ??= new List<string>()).Add(kv.Key);
if (stale != null) foreach (string k in stale) recent.Remove(k);
}
}
/// <summary>
/// Keeps scrollback out of Discord, by RynthChat's line numbers (seq), not by clock time.
/// ChatSource reads RynthChat's scrollback by seq; the first read after the relay comes on
/// for this character (engine start, hot reload, switching it on, logging in a character that
/// has it on) or after RynthChat's numbering restarts is the baseline: up to 500 lines that were
/// already sent, or are history, so none of it is posted. After that a line is posted only if
/// its seq is newer than any seen. Pump thread only.
/// </summary>
internal sealed class DiscordBacklogGate
{
private bool _live;
private ulong _newestSeq;
/// <summary>True once a baseline read has been taken while on.</summary>
public bool Live => _live;
/// <summary>The relay is off for this character: the next read while on is a baseline again.</summary>
public void Off() => _live = false;
/// <summary>RynthChat's scrollback numbering restarted (its plugin was reloaded): re-baseline.</summary>
public void SourceReset()
{
_live = false;
_newestSeq = 0;
}
/// <summary>
/// One scrollback read (possibly empty) with the seq of each line in it. Returns which lines
/// to post: none while off or for the baseline read, else those newer than any seen.
/// </summary>
public bool[] Admit(bool on, IReadOnlyList<ulong> seqs)
{
var post = new bool[seqs.Count];
if (!on)
{
_live = false;
return post;
}
bool baseline = !_live;
_live = true;
for (int i = 0; i < seqs.Count; i++)
{
ulong seq = seqs[i];
bool newer = seq > _newestSeq;
if (newer) _newestSeq = seq;
post[i] = newer && !baseline;
}
return post;
}
}

View file

@ -0,0 +1,380 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatDiscordSettings.cs
// RynthChat's Discord relay settings, shared by every client and character
// (%AppData%\RynthCore\rynthchat_discord.json, beside rynthchat_settings.json).
// The routes and options are shared; the switch is per character
// (Characters): a character not on the list relays nothing, and the list
// starts empty. Saves merge each client's switch into the file's list.
//
// Threads: the Discord panel (AC's render thread) edits fields in place, each
// a single reference or 32-bit value, so the pump's reads never tear. Arrays
// (Routes, a route's Tabs) are replaced, never changed in place, so the pump
// can walk the one it read without a lock.
//
// Secrets (webhook URL, bot token) are stored only as DPAPI blobs
// (DiscordSecrets); the JSON never holds them in plain text.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>Route state the panel shows; replaced as a whole by the pump.</summary>
internal sealed record DiscordRouteStatus(int Queued, int MessagesSent, int LinesSent, int Dropped, bool Paused,
string LastError, DateTime LastSent);
/// <summary>One Discord destination and the chat it receives.</summary>
internal sealed class DiscordRoute
{
public const string ModeWebhook = "webhook";
public const string ModeBot = "bot";
public static readonly string[] Modes = { ModeWebhook, ModeBot };
public static readonly string[] ModeNames = { "Webhook URL", "Bot token + channel ID" };
/// <summary>Label shown in the panel, the log and /rc discord.</summary>
public string Name = "Discord";
public bool Enabled = true;
public string Mode = ModeWebhook;
/// <summary>DPAPI blob of the webhook URL (the URL embeds the webhook token).</summary>
public string WebhookProtected = string.Empty;
/// <summary>DPAPI blob of the bot token (bot mode).</summary>
public string BotTokenProtected = string.Empty;
/// <summary>Target channel snowflake (bot mode). Not secret.</summary>
public string ChannelId = string.Empty;
/// <summary>Webhook display name; blank uses the character's name. Ignored in bot mode.</summary>
public string DisplayName = string.Empty;
/// <summary>Speech channels relayed (names, <see cref="ChatSpeech.Name"/>). Saved form of <see cref="SpeechMask"/>.</summary>
public string[]? Speech;
/// <summary>
/// Chat tabs relayed: every line that shows in one of them (channel tabs like System, or
/// tabs the chat rules fill). Replaced, never changed in place.
/// </summary>
public string[] Tabs = Array.Empty<string>();
/// <summary>Comma-separated words; when set, only lines containing one of them are relayed.</summary>
public string Keywords = string.Empty;
/// <summary>Use this route's own pacing instead of the relay's.</summary>
public bool CustomPace;
/// <summary>With <see cref="CustomPace"/>: lines arriving within this window go out in one message.</summary>
public int BatchMs = 1500;
/// <summary>With <see cref="CustomPace"/>: minimum spacing between this route's messages.</summary>
public int MinIntervalMs = 2000;
// ── Runtime only ─────────────────────────────────────────────────────
/// <summary>Bits of <see cref="SpeechChannel"/> (<see cref="ChatSpeech.Bit"/>).</summary>
[JsonIgnore] public uint SpeechMask;
/// <summary>Written by the pump, read by the panel.</summary>
[JsonIgnore] public volatile DiscordRouteStatus? Status;
/// <summary>True when a send secret is stored for the current mode (the plain text is never kept here).</summary>
[JsonIgnore]
public bool HasSecret => Mode == ModeBot
? BotTokenProtected.Length > 0 && ChannelId.Length > 0
: WebhookProtected.Length > 0;
public bool RelaysSpeech(SpeechChannel ch) => (SpeechMask & ChatSpeech.Bit(ch)) != 0;
/// <summary>Tells, fellowship and the allegiance channels: private chat a player usually wants on their phone.</summary>
public static uint DefaultSpeechMask()
{
uint m = 0;
foreach (var ch in new[]
{
SpeechChannel.Tell, SpeechChannel.Fellowship, SpeechChannel.Allegiance,
SpeechChannel.Patron, SpeechChannel.Vassals, SpeechChannel.Covassals, SpeechChannel.Monarch,
})
m |= ChatSpeech.Bit(ch);
return m;
}
public static uint AllSpeechMask()
{
uint m = 0;
foreach (var ch in ChatSpeech.All) m |= ChatSpeech.Bit(ch);
return m;
}
public static string[] NamesFromMask(uint mask)
{
var names = new List<string>();
foreach (var ch in ChatSpeech.All)
if ((mask & ChatSpeech.Bit(ch)) != 0) names.Add(ChatSpeech.Name(ch));
return names.ToArray();
}
/// <summary>The mask for <paramref name="names"/>; <paramref name="fallback"/> when there is no list at all.</summary>
public static uint MaskFromNames(IEnumerable<string>? names, uint fallback)
{
if (names == null) return fallback;
uint m = 0;
foreach (string n in names)
if (ChatSpeech.TryParseName(n, out var ch)) m |= ChatSpeech.Bit(ch);
return m;
}
}
/// <summary>A character the relay is switched on for (server + name, any case).</summary>
internal sealed class DiscordCharacter
{
public string Server = string.Empty;
public string Name = string.Empty;
/// <summary>The character, or null without a name (not logged in yet).</summary>
public static DiscordCharacter? Of(string? server, string? name)
{
string n = (name ?? string.Empty).Trim().TrimStart('+').Trim();
if (n.Length == 0) return null;
return new DiscordCharacter { Server = (server ?? string.Empty).Trim(), Name = n };
}
public bool Same(DiscordCharacter? other)
=> other != null
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Server, other.Server, StringComparison.OrdinalIgnoreCase);
/// <summary>"Bob (Aelrynth)", or "Bob" when the server isn't known.</summary>
public override string ToString() => Server.Length > 0 ? $"{Name} ({Server})" : Name;
}
/// <summary>Turns the relay on or off for one character; applied to the file's list when saving.</summary>
internal sealed record DiscordCharacterOp(DiscordCharacter Character, bool On);
internal sealed class ChatDiscordSettings
{
/// <summary>2: the relay is switched on per character (<see cref="Characters"/>), not for everyone.</summary>
public const int CurrentVersion = 2;
public int Version = CurrentVersion;
/// <summary>
/// The characters the relay is on for; every other character relays nothing. Each client
/// switches only its own character, and a save merges that change into the file's list
/// (ChatDiscordStore.MergeForSave), so clients don't undo each other. Replaced, never
/// changed in place. Empty (the default): off for everyone.
/// </summary>
public DiscordCharacter[] Characters = Array.Empty<DiscordCharacter>();
/// <summary>Destinations, shared by every character. Replaced (copy-on-write) when one is added or removed.</summary>
public DiscordRoute[] Routes = Array.Empty<DiscordRoute>();
/// <summary>True when the relay is switched on for <paramref name="character"/>.</summary>
public bool IsOnFor(DiscordCharacter? character)
{
if (character == null) return false;
foreach (var c in Characters) if (c.Same(character)) return true;
return false;
}
/// <summary>Leave out lines you typed yourself ("You say", "You tell").</summary>
public bool SkipOwn;
/// <summary>Leave out lines a chat rule hides.</summary>
public bool SkipHidden = true;
/// <summary>Start each relayed line with the game time (HH:mm:ss).</summary>
public bool IncludeTimestamp = true;
/// <summary>Start each relayed line with "[Character]" (useful when several characters share a channel).</summary>
public bool TagCharacter;
/// <summary>Lines arriving within this window go out in one Discord message.</summary>
public int BatchMs = 1500;
/// <summary>Minimum spacing between messages to one route (Discord allows about 30 per minute per channel).</summary>
public int MinIntervalMs = 2000;
/// <summary>Lines waiting per route; the oldest are dropped beyond this.</summary>
public int MaxQueue = 200;
/// <summary>Entries kept in the panel's log.</summary>
public int MaxLog = 200;
// Pacing limits, shared by the panel's sliders and Normalize.
public const int BatchMinMs = 0, BatchMaxMs = 60_000;
public const int IntervalMinMs = 1000, IntervalMaxMs = 600_000;
public const int QueueMin = 20, QueueMax = 2000;
public const int LogMin = 20, LogMax = 2000;
/// <summary>The batch window <paramref name="route"/> uses.</summary>
public int BatchFor(DiscordRoute route) => route.CustomPace ? route.BatchMs : BatchMs;
/// <summary>The message spacing <paramref name="route"/> uses.</summary>
public int IntervalFor(DiscordRoute route) => route.CustomPace ? route.MinIntervalMs : MinIntervalMs;
}
/// <summary>Loads / saves <see cref="ChatDiscordSettings"/>.</summary>
internal static class ChatDiscordStore
{
public static string DefaultPath =>
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "rynthchat_discord.json");
/// <summary>
/// Reads the settings (or the defaults: off, no routes). <paramref name="note"/> says what
/// happened, for the log. Never throws.
/// </summary>
public static ChatDiscordSettings Load(string path, out string note)
{
note = string.Empty;
ChatDiscordSettings? s = null;
try
{
if (File.Exists(path))
s = JsonSerializer.Deserialize(File.ReadAllText(path), ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
catch (Exception ex)
{
note = $"settings unreadable ({ex.GetType().Name}: {ex.Message}); using defaults";
KeepUnreadable(path);
s = null;
}
s ??= new ChatDiscordSettings();
Normalize(s);
return s;
}
/// <summary>The settings as JSON (speech names refreshed from the masks first). Any thread.</summary>
public static string Serialize(ChatDiscordSettings s)
{
foreach (var r in s.Routes) r.Speech = DiscordRoute.NamesFromMask(r.SpeechMask);
return JsonSerializer.Serialize(s, ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
/// <summary>Writes <paramref name="json"/> beside the file and swaps it in. Background writer thread.</summary>
public static void Write(string path, string json)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file
try
{
File.WriteAllText(tmp, json);
File.Move(tmp, path, overwrite: true);
}
catch
{
try { File.Delete(tmp); } catch { }
throw;
}
}
/// <summary>Repairs missing / out-of-range values and builds the runtime speech masks.</summary>
internal static void Normalize(ChatDiscordSettings s)
{
s.Version = ChatDiscordSettings.CurrentVersion;
s.Routes = (s.Routes ?? Array.Empty<DiscordRoute>()).Where(r => r != null).ToArray();
foreach (var r in s.Routes) NormalizeRoute(r);
s.Characters = NormalizeCharacters(s.Characters);
s.BatchMs = Math.Clamp(s.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
s.MinIntervalMs = Math.Clamp(s.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
s.MaxQueue = Math.Clamp(s.MaxQueue, ChatDiscordSettings.QueueMin, ChatDiscordSettings.QueueMax);
s.MaxLog = Math.Clamp(s.MaxLog, ChatDiscordSettings.LogMin, ChatDiscordSettings.LogMax);
}
internal static void NormalizeRoute(DiscordRoute r)
{
r.Name = string.IsNullOrWhiteSpace(r.Name) ? "Discord" : r.Name.Trim();
if (Array.IndexOf(DiscordRoute.Modes, r.Mode ?? string.Empty) < 0) r.Mode = DiscordRoute.ModeWebhook;
r.WebhookProtected ??= string.Empty;
r.BotTokenProtected ??= string.Empty;
r.ChannelId = (r.ChannelId ?? string.Empty).Trim();
r.DisplayName ??= string.Empty;
r.Keywords ??= string.Empty;
r.SpeechMask = DiscordRoute.MaskFromNames(r.Speech, DiscordRoute.DefaultSpeechMask());
r.Tabs = (r.Tabs ?? Array.Empty<string>())
.Where(t => !string.IsNullOrWhiteSpace(t)).Select(t => t.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
r.BatchMs = Math.Clamp(r.BatchMs, ChatDiscordSettings.BatchMinMs, ChatDiscordSettings.BatchMaxMs);
r.MinIntervalMs = Math.Clamp(r.MinIntervalMs, ChatDiscordSettings.IntervalMinMs, ChatDiscordSettings.IntervalMaxMs);
}
/// <summary>Drops nameless and repeated entries (same server + name, any case).</summary>
internal static DiscordCharacter[] NormalizeCharacters(DiscordCharacter[]? list)
{
var result = new List<DiscordCharacter>();
foreach (var c in list ?? Array.Empty<DiscordCharacter>())
{
DiscordCharacter? n = c == null ? null : DiscordCharacter.Of(c.Server, c.Name);
if (n != null && !result.Exists(x => x.Same(n))) result.Add(n);
}
return result.ToArray();
}
/// <summary><paramref name="list"/> with each switch in <paramref name="ops"/> applied, in order.</summary>
public static DiscordCharacter[] ApplyCharacterOps(DiscordCharacter[]? list, IEnumerable<DiscordCharacterOp> ops)
{
var result = new List<DiscordCharacter>(NormalizeCharacters(list));
foreach (var op in ops)
{
result.RemoveAll(c => c.Same(op.Character));
if (op.On) result.Add(op.Character);
}
return result.ToArray();
}
/// <summary>The character list in a settings file, or null when it can't be read.</summary>
public static DiscordCharacter[]? ReadCharacters(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
var s = JsonSerializer.Deserialize(json, ChatDiscordJsonContext.Default.ChatDiscordSettings);
return s == null ? null : NormalizeCharacters(s.Characters);
}
catch (Exception) { return null; }
}
/// <summary>
/// What a client writes when it saves: its own settings (<paramref name="ours"/>, from
/// <see cref="Serialize"/>), except the character list, which is the one in the file now
/// (<paramref name="disk"/>, re-read just before) with this client's switches applied. So one
/// client saving can't switch another client's character on or off. When the file is missing
/// or unreadable, our own list is the base. <paramref name="merged"/> is the list written.
/// </summary>
public static string MergeForSave(string ours, string? disk, IReadOnlyList<DiscordCharacterOp> ops, out DiscordCharacter[] merged)
{
var mine = JsonSerializer.Deserialize(ours, ChatDiscordJsonContext.Default.ChatDiscordSettings)
?? throw new InvalidOperationException("settings JSON is empty");
DiscordCharacter[] baseList = ReadCharacters(disk) ?? NormalizeCharacters(mine.Characters);
merged = ApplyCharacterOps(baseList, ops);
mine.Characters = merged;
mine.Version = ChatDiscordSettings.CurrentVersion;
// Not Serialize(): mine has no runtime speech masks; its speech lists are already right.
return JsonSerializer.Serialize(mine, ChatDiscordJsonContext.Default.ChatDiscordSettings);
}
private static void KeepUnreadable(string path)
{
try
{
if (!File.Exists(path)) return;
File.Copy(path, Path.ChangeExtension(path, $".unreadable-{DateTime.Now:yyyyMMdd-HHmmss}.json"), overwrite: false);
}
catch { }
}
}
// JsonSerializerContext must be at namespace scope (not nested) for source generation.
[JsonSerializable(typeof(ChatDiscordSettings))]
[JsonSourceGenerationOptions(
WriteIndented = true,
IncludeFields = true,
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true)]
internal partial class ChatDiscordJsonContext : JsonSerializerContext { }

View file

@ -0,0 +1,213 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/ChatSpeech.cs
// Player speech in a chat line: which channel it was said on (local, tell,
// fellowship, the allegiance channels, the global chat channels), who said
// it and what. The Discord relay uses it to pick lines finer than a chat tab
// ("tells and fellowship only") and to print them as [Channel] Speaker: text.
//
// Ported from RynthAi's translator (ChatTranslator.TryParseInbound) when the
// relay moved into RynthChat (2026-10-11). Pure; covered by
// tools/ChatDiscordTests.
// ============================================================================
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>Speech channels. Saved by name (<see cref="ChatSpeech.Name"/>), never by number.</summary>
internal enum SpeechChannel
{
Local = 0,
Tell,
Fellowship,
Allegiance,
Patron,
Vassals,
Covassals,
Monarch,
General,
Trade,
Lfg,
Roleplay,
Society,
Olthoi,
}
internal static class ChatSpeech
{
public static readonly SpeechChannel[] All = Enum.GetValues<SpeechChannel>();
/// <summary>AC's ChatMessageType for spell words ("Zojak Bor"): speech-shaped, never relayed as speech.</summary>
public const int ChatTypeSpellcasting = 0x11;
public static uint Bit(SpeechChannel ch) => 1u << (int)ch;
public static string Name(SpeechChannel ch) => ch switch
{
SpeechChannel.Lfg => "LFG",
_ => ch.ToString(),
};
/// <summary>Accepts channel names and the usual short forms (case-insensitive).</summary>
public static bool TryParseName(string? text, out SpeechChannel ch)
{
ch = SpeechChannel.Local;
if (string.IsNullOrWhiteSpace(text)) return false;
switch (text.Trim().ToLowerInvariant())
{
case "local": case "say": case "area": ch = SpeechChannel.Local; return true;
case "tell": case "tells": case "t": ch = SpeechChannel.Tell; return true;
case "fellowship": case "fellow": case "f": ch = SpeechChannel.Fellowship; return true;
case "allegiance": case "alleg": case "a": ch = SpeechChannel.Allegiance; return true;
case "patron": case "p": ch = SpeechChannel.Patron; return true;
case "vassals": case "vassal": case "v": ch = SpeechChannel.Vassals; return true;
case "covassals": case "covassal": case "c": ch = SpeechChannel.Covassals; return true;
case "monarch": case "m": ch = SpeechChannel.Monarch; return true;
case "general": case "cg": case "g": ch = SpeechChannel.General; return true;
case "trade": case "ct": ch = SpeechChannel.Trade; return true;
case "lfg": case "looking for group": case "clfg": ch = SpeechChannel.Lfg; return true;
case "roleplay": case "rp": case "crp": ch = SpeechChannel.Roleplay; return true;
case "society": case "cs": ch = SpeechChannel.Society; return true;
case "olthoi": case "co": ch = SpeechChannel.Olthoi; return true;
default: return false;
}
}
/// <summary>Channel implied by an inbound chat type; null for generic types (Channels / Social).</summary>
public static SpeechChannel? FromChatType(int chatType) => chatType switch
{
0x02 => SpeechChannel.Local,
0x03 => SpeechChannel.Tell,
0x12 => SpeechChannel.Allegiance,
0x13 => SpeechChannel.Fellowship,
0x1B => SpeechChannel.General,
0x1C => SpeechChannel.Trade,
0x1D => SpeechChannel.Lfg,
0x1E => SpeechChannel.Roleplay,
0x20 => SpeechChannel.Olthoi,
0x21 => SpeechChannel.Society,
_ => null,
};
// "[General] " style tab prefix some servers / chat options put in front of channel lines.
private static readonly Regex RxBracket = new(@"^\[(?<b>[A-Za-z ]{1,24})\]\s*", RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(20));
// "You say ...", "You tell Bob, ..." - the server echo of your own lines.
private static readonly Regex RxOwn = new(@"^You\s+(?:say|tell)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
// "Bob says, "..."" / "Bob says on the General channel, "..."" / "Bob tells you, "...""
private static readonly Regex RxSpeech = new(@"^(?<name>.+?)\s+(?<verb>says|tells)\b(?<mid>[^""]*)""(?<msg>.*)""\s*$",
RegexOptions.Singleline | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
private static readonly Regex RxOnChannel = new(@"on the (?<ch>[A-Za-z ]+?) channel",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromMilliseconds(20));
private static readonly Regex RxEscape = new(@"<([0-9a-fA-F]{4})>", RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(20));
/// <summary>
/// Splits a chat line (AC's name links already stripped) into channel, speaker and message.
/// The channel comes from, in order: a "[Name]" prefix, "on the X channel", "tells you", the
/// chat type, then words like "patron" / "vassal". False for anything that isn't player speech,
/// and for spell words.
/// </summary>
public static bool TryParse(string? text, int chatType, out SpeechChannel channel,
out string speaker, out string message, out bool own)
{
channel = SpeechChannel.Local;
speaker = message = string.Empty;
own = false;
if (chatType == ChatTypeSpellcasting || string.IsNullOrEmpty(text)) return false;
string t = text.Trim();
if (t.Length < 6 || t.IndexOf('"') < 0) return false;
try
{
SpeechChannel? hint = null;
var b = RxBracket.Match(t);
if (b.Success && TryParseName(b.Groups["b"].Value, out var bc))
{
hint = bc;
t = t.Substring(b.Length);
}
string mid;
bool tellsYou;
var mo = RxOwn.Match(t);
if (mo.Success)
{
own = true;
speaker = "You";
mid = mo.Groups["mid"].Value;
message = mo.Groups["msg"].Value;
tellsYou = t.StartsWith("You tell", StringComparison.OrdinalIgnoreCase);
}
else
{
var m = RxSpeech.Match(t);
if (!m.Success) return false;
speaker = m.Groups["name"].Value.Trim().TrimStart('+');
mid = m.Groups["mid"].Value;
message = m.Groups["msg"].Value;
tellsYou = m.Groups["verb"].Value == "tells" && mid.TrimStart().StartsWith("you", StringComparison.OrdinalIgnoreCase);
if (speaker.Length == 0 || speaker.Length > 40) return false;
}
SpeechChannel? ch = hint;
if (ch == null)
{
var oc = RxOnChannel.Match(mid);
if (oc.Success && TryParseName(oc.Groups["ch"].Value, out var named)) ch = named;
}
if (ch == null && tellsYou) ch = SpeechChannel.Tell;
ch ??= FromChatType(chatType);
ch ??= FromWords(mid);
if (ch == null) return false;
channel = ch.Value;
message = Decode(message).Trim();
return message.Length > 0;
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
private static SpeechChannel? FromWords(string mid)
{
string m = mid.ToLowerInvariant();
if (m.Contains("covassal")) return SpeechChannel.Covassals;
if (m.Contains("vassal")) return SpeechChannel.Vassals;
if (m.Contains("patron")) return SpeechChannel.Patron;
if (m.Contains("monarch")) return SpeechChannel.Monarch;
if (m.Contains("fellowship")) return SpeechChannel.Fellowship;
if (m.Contains("allegiance")) return SpeechChannel.Allegiance;
return null;
}
/// <summary>
/// Expands AC's "&lt;c2dc&gt;" escapes (characters above Latin-1 travel as UTF-16 hex in chat)
/// into the characters they stand for.
/// </summary>
public static string Decode(string text)
{
if (string.IsNullOrEmpty(text) || text.IndexOf('<') < 0) return text ?? string.Empty;
try
{
return RxEscape.Replace(text, m =>
{
int cp = int.Parse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
return cp is > 0 and <= 0xFFFF ? ((char)cp).ToString() : m.Value;
});
}
catch (RegexMatchTimeoutException)
{
return text;
}
}
}

View file

@ -0,0 +1,254 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordClient.cs
// Posts relay messages to Discord. NativeAOT-safe: request JSON is written
// with Utf8JsonWriter and responses are read with JsonDocument (no
// reflection serialization).
//
// webhook POST {webhook url} (no auth header; the URL is the secret)
// bot POST https://discord.com/api/v10/channels/{id}/messages Authorization: Bot {token}
//
// Every message sets allowed_mentions.parse = [] (nobody is pinged) and
// SUPPRESS_EMBEDS (no link previews). 429 returns the wait Discord asks for.
// 400 / 401 / 403 / 404 are permanent: the relay pauses the route so a bad
// credential isn't retried (Discord temporarily bans clients that keep
// sending invalid requests).
// ============================================================================
using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>
/// Outcome of one post. <see cref="RetryAfterMs"/> is how long to wait before the next post to
/// this route (rate limit or bucket exhausted); <see cref="Permanent"/> means stop until the
/// settings change.
/// </summary>
internal readonly record struct DiscordSendResult(bool Ok, int Status, int RetryAfterMs, bool Permanent, string Error)
{
public static DiscordSendResult Fail(string error, bool permanent = false, int status = 0, int retryAfterMs = 0)
=> new(false, status, retryAfterMs, permanent, error);
}
internal static class DiscordClient
{
public const string ApiBase = "https://discord.com/api/v10";
/// <summary>MessageFlags.SUPPRESS_EMBEDS: chat links don't unfurl into previews.</summary>
private const int FlagSuppressEmbeds = 1 << 2;
// Built on first post, so an engine that never relays never opens a socket. Disposed by
// Shutdown (engine shutdown / hot reload): the engine loads into a collectible context, and a
// live client (its handler's pool timer, open connections, pending callbacks) must not
// outlive the generation that made it. After Shutdown no new client is built.
private static readonly object HttpLock = new();
private static HttpClient? _http;
private static bool _closed;
private static HttpClient Http()
{
lock (HttpLock)
{
if (_closed) throw new ObjectDisposedException(nameof(DiscordClient), "the relay is shutting down");
return _http ??= CreateHttp();
}
}
/// <summary>Disposes the HTTP client (cancelling anything still using it) and refuses new posts. Engine shutdown.</summary>
public static void Shutdown()
{
HttpClient? http;
lock (HttpLock)
{
_closed = true;
http = _http;
_http = null;
}
try { http?.Dispose(); } catch (Exception) { }
}
private static HttpClient CreateHttp()
{
var handler = new SocketsHttpHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
AllowAutoRedirect = false,
};
var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) };
// Discord asks bots to send "DiscordBot (url, version)"; webhooks accept it too.
http.DefaultRequestHeaders.UserAgent.ParseAdd("DiscordBot (https://aelrynth.com, 1.0) RynthChat-Relay");
http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return http;
}
/// <summary>
/// Posts <paramref name="content"/> through a webhook. <paramref name="webhookUrl"/> must
/// already be validated by <see cref="DiscordFormat.TryNormalizeWebhookUrl"/>. Never throws.
/// </summary>
public static Task<DiscordSendResult> PostWebhookAsync(string webhookUrl, string content, string displayName, CancellationToken ct)
{
if (!DiscordFormat.TryNormalizeWebhookUrl(webhookUrl, out string url))
return Task.FromResult(DiscordSendResult.Fail("the saved webhook URL is not a Discord webhook URL", permanent: true));
string body = BuildBody(content, DiscordFormat.SafeWebhookName(displayName));
var req = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
return SendAsync(req, url, ct);
}
/// <summary>Posts <paramref name="content"/> as a bot to <paramref name="channelId"/>. Never throws.</summary>
public static Task<DiscordSendResult> PostBotAsync(string botToken, string channelId, string content, CancellationToken ct)
{
if (!DiscordFormat.LooksLikeBotToken(botToken))
return Task.FromResult(DiscordSendResult.Fail("the saved bot token doesn't look like a Discord bot token", permanent: true));
if (!DiscordFormat.IsSnowflake(channelId))
return Task.FromResult(DiscordSendResult.Fail("the channel ID must be the channel's number (Developer Mode > Copy Channel ID)", permanent: true));
string body = BuildBody(content, string.Empty);
var req = new HttpRequestMessage(HttpMethod.Post, $"{ApiBase}/channels/{channelId.Trim()}/messages")
{
Content = new StringContent(body, Encoding.UTF8, "application/json"),
};
req.Headers.TryAddWithoutValidation("Authorization", "Bot " + botToken.Trim());
return SendAsync(req, botToken.Trim(), ct);
}
/// <summary>{"content":..., "username":..., "allowed_mentions":{"parse":[]}, "flags":4}</summary>
internal static string BuildBody(string content, string username)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteString("content", content);
if (username.Length > 0) w.WriteString("username", username);
w.WriteStartObject("allowed_mentions");
w.WriteStartArray("parse");
w.WriteEndArray();
w.WriteEndObject();
w.WriteNumber("flags", FlagSuppressEmbeds);
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
private static async Task<DiscordSendResult> SendAsync(HttpRequestMessage req, string secret, CancellationToken ct)
{
try
{
using (req)
using (var resp = await Http().SendAsync(req, ct).ConfigureAwait(false))
{
int status = (int)resp.StatusCode;
string json = await resp.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
int bucketWait = BucketWaitMs(resp.Headers);
if (resp.IsSuccessStatusCode) return new DiscordSendResult(true, status, bucketWait, false, string.Empty);
if (status == 429)
{
int wait = ParseRetryAfterMs(json, HeaderValue(resp.Headers, "Retry-After"));
return DiscordSendResult.Fail($"rate limited, waiting {wait / 1000.0:0.0}s", status: status, retryAfterMs: Math.Max(wait, bucketWait));
}
string msg = DiscordFormat.Redact(ErrorText(status, json), secret);
return DiscordSendResult.Fail(msg, permanent: IsPermanent(status), status: status, retryAfterMs: bucketWait);
}
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
return DiscordSendResult.Fail("request timed out");
}
catch (OperationCanceledException)
{
return DiscordSendResult.Fail("cancelled");
}
catch (HttpRequestException ex)
{
return DiscordSendResult.Fail("network error: " + DiscordFormat.Redact(ex.Message, secret));
}
catch (Exception ex)
{
return DiscordSendResult.Fail($"{ex.GetType().Name}: {DiscordFormat.Redact(ex.Message, secret)}");
}
}
/// <summary>
/// 400 (bad body), 401 (bad token), 403 (no permission), 404 (webhook / channel deleted):
/// retrying the same request can't succeed.
/// </summary>
internal static bool IsPermanent(int status) => status is 400 or 401 or 403 or 404;
/// <summary>
/// Wait for a 429, in ms: the JSON "retry_after" (seconds, may be fractional), else the
/// Retry-After header (seconds), else 5 s. Clamped to 0.25 s .. 10 min.
/// </summary>
internal static int ParseRetryAfterMs(string? json, string? header)
{
double seconds = -1;
if (!string.IsNullOrWhiteSpace(json))
{
try
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind == JsonValueKind.Object
&& doc.RootElement.TryGetProperty("retry_after", out var ra)
&& ra.ValueKind == JsonValueKind.Number)
seconds = ra.GetDouble();
}
catch (JsonException) { }
}
if (seconds < 0 && double.TryParse(header, NumberStyles.Float, CultureInfo.InvariantCulture, out double h)) seconds = h;
if (seconds < 0) seconds = 5;
return (int)Math.Clamp(seconds * 1000.0, 250.0, 600_000.0);
}
/// <summary>When the route's bucket is empty (X-RateLimit-Remaining: 0), ms until it resets.</summary>
private static int BucketWaitMs(HttpResponseHeaders headers)
{
if (HeaderValue(headers, "X-RateLimit-Remaining") != "0") return 0;
return double.TryParse(HeaderValue(headers, "X-RateLimit-Reset-After"), NumberStyles.Float, CultureInfo.InvariantCulture, out double s)
? (int)Math.Clamp(s * 1000.0, 0.0, 600_000.0)
: 0;
}
private static string? HeaderValue(HttpResponseHeaders headers, string name)
{
if (!headers.TryGetValues(name, out var values)) return null;
foreach (string v in values) return v.Trim();
return null;
}
private static string ErrorText(int status, string json)
{
string detail = string.Empty;
try
{
if (!string.IsNullOrWhiteSpace(json))
{
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind == JsonValueKind.Object && doc.RootElement.TryGetProperty("message", out var m))
detail = m.GetString() ?? string.Empty;
}
}
catch (JsonException) { }
string hint = status switch
{
401 => " (the token or webhook is invalid)",
403 => " (the bot can't post in that channel; check its permissions)",
404 => " (the webhook or channel no longer exists)",
_ => string.Empty,
};
return $"HTTP {status}{(detail.Length > 0 ? ": " + detail : string.Empty)}{hint}";
}
}

View file

@ -0,0 +1,211 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordFormat.cs
// Pure helpers for the Discord relay: Markdown escaping, line formatting,
// message packing, credential-shape checks and the keyword filter.
// No I/O; covered by
// tools/ChatDiscordTests.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Engine.UI.Data.Discord;
internal static class DiscordFormat
{
/// <summary>Discord rejects message content over 2000 characters.</summary>
public const int MaxContent = 2000;
/// <summary>Longest single relayed line; longer chat is cut with an ellipsis.</summary>
public const int MaxLine = 1900;
// discord.com / discordapp.com, optional ptb. / canary., optional /v{n}, then /webhooks/{id}/{token}.
private static readonly Regex RxWebhook = new(
@"^https://(?:(?:ptb|canary)\.)?discord(?:app)?\.com/api/(?:v\d{1,2}/)?webhooks/(?<id>\d{15,22})/(?<token>[A-Za-z0-9_\-]{30,100})/?$",
RegexOptions.CultureInvariant);
private static readonly Regex RxSnowflake = new(@"^\d{15,22}$", RegexOptions.CultureInvariant);
// Bot tokens are three base64url segments separated by dots.
private static readonly Regex RxBotToken = new(@"^[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{20,}$",
RegexOptions.CultureInvariant);
/// <summary>
/// Checks a pasted webhook URL. Only Discord's own webhook endpoints are accepted, so a typo
/// can't send chat to some other server. Returns the URL without any query string.
/// </summary>
public static bool TryNormalizeWebhookUrl(string? url, out string normalized)
{
normalized = string.Empty;
if (string.IsNullOrWhiteSpace(url)) return false;
string u = url.Trim();
int q = u.IndexOfAny(new[] { '?', '#' });
if (q >= 0) u = u.Substring(0, q);
if (!RxWebhook.IsMatch(u)) return false;
normalized = u.TrimEnd('/');
return true;
}
public static bool IsSnowflake(string? id) => !string.IsNullOrWhiteSpace(id) && RxSnowflake.IsMatch(id.Trim());
public static bool LooksLikeBotToken(string? token) => !string.IsNullOrWhiteSpace(token) && RxBotToken.IsMatch(token.Trim());
/// <summary>
/// Escapes inline Discord Markdown so chat text shows literally: emphasis, code, spoilers,
/// quotes, masked links, and the &lt;@id&gt; / &lt;#id&gt; / &lt;t:..&gt; tags. Newlines become
/// spaces. "@everyone" / "@here" also get a zero-width space; allowed_mentions already blocks
/// the ping, this keeps the text from looking live.
/// </summary>
public static string Escape(string? text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var sb = new StringBuilder(text.Length + 8);
foreach (char c in text)
{
switch (c)
{
case '\\': case '*': case '_': case '~': case '`': case '|':
case '>': case '<': case '[': case ']':
sb.Append('\\').Append(c);
break;
case '\r': case '\n':
sb.Append(' ');
break;
default:
sb.Append(c);
break;
}
}
return sb.Replace("@everyone", "@\u200Beveryone").Replace("@here", "@\u200Bhere").ToString();
}
/// <summary>
/// One relayed line: optional `HH:mm:ss`, optional [Character], **[Channel] Speaker:** message.
/// A line with no channel or speaker is relayed as plain text.
/// </summary>
public static string FormatLine(DateTime time, string? channel, string? speaker, string message,
bool timestamp, string? characterTag)
{
var sb = new StringBuilder(message.Length + 48);
if (timestamp) sb.Append('`').Append(time.ToString("HH:mm:ss", CultureInfo.InvariantCulture)).Append("` ");
if (!string.IsNullOrEmpty(characterTag)) sb.Append('\\').Append('[').Append(Escape(characterTag)).Append("\\] ");
bool hasChannel = !string.IsNullOrEmpty(channel);
bool hasSpeaker = !string.IsNullOrEmpty(speaker);
if (hasChannel || hasSpeaker)
{
sb.Append("**");
if (hasChannel) sb.Append("\\[").Append(Escape(channel)).Append("\\]");
if (hasChannel && hasSpeaker) sb.Append(' ');
if (hasSpeaker) sb.Append(Escape(speaker)).Append(':');
sb.Append("** ");
}
string body = Escape(message);
// Headings, lists and subtext only parse at the start of a line.
if (sb.Length == 0) body = EscapeLineStart(body);
sb.Append(body);
return Truncate(sb.ToString(), MaxLine);
}
// "# x", "-# x", "- x", "+ x" and "1. x" are block syntax when they open a line.
private static readonly Regex RxBlockStart = new(@"^(?:#{1,3}\s|-#\s|[-+]\s|\d+\.\s)", RegexOptions.CultureInvariant);
private static string EscapeLineStart(string s) => RxBlockStart.IsMatch(s) ? "\\" + s : s;
/// <summary>Cuts <paramref name="s"/> to <paramref name="max"/> characters, ending with an ellipsis.</summary>
public static string Truncate(string s, int max)
{
if (s.Length <= max) return s;
int cut = max - 1;
// Don't leave a dangling escape backslash or split a surrogate pair at the cut.
if (cut > 0 && char.IsHighSurrogate(s[cut - 1])) cut--;
if (cut > 0 && s[cut - 1] == '\\') cut--;
return s.Substring(0, cut) + "\u2026";
}
/// <summary>
/// Takes lines from the front of <paramref name="lines"/> while they fit one message (newline
/// separated, at most <see cref="MaxContent"/> characters). Always takes at least one line.
/// </summary>
public static string Pack(List<string> lines, out int taken)
{
taken = 0;
if (lines.Count == 0) return string.Empty;
var sb = new StringBuilder();
foreach (string line in lines)
{
string l = Truncate(line, MaxContent);
int add = l.Length + (sb.Length > 0 ? 1 : 0);
if (taken > 0 && sb.Length + add > MaxContent) break;
if (sb.Length > 0) sb.Append('\n');
sb.Append(l);
taken++;
}
return sb.ToString();
}
/// <summary>
/// Webhook display name: Discord refuses names containing "discord" or "clyde" and limits them
/// to 1-80 characters. Returns empty (use the webhook's own name) when the name can't be used.
/// </summary>
public static string SafeWebhookName(string? name)
{
if (string.IsNullOrWhiteSpace(name)) return string.Empty;
string n = name.Trim().TrimStart('+');
if (n.Contains("discord", StringComparison.OrdinalIgnoreCase) || n.Contains("clyde", StringComparison.OrdinalIgnoreCase))
return string.Empty;
if (n.Equals("everyone", StringComparison.OrdinalIgnoreCase) || n.Equals("here", StringComparison.OrdinalIgnoreCase))
return string.Empty;
return n.Length > 80 ? n.Substring(0, 80) : n;
}
/// <summary>Splits a comma-separated list into trimmed, non-empty entries.</summary>
public static List<string> SplitList(string? csv)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(csv)) return list;
foreach (string part in csv.Split(','))
{
string p = part.Trim();
if (p.Length > 0) list.Add(p);
}
return list;
}
/// <summary>True when <paramref name="text"/> contains any keyword (case-insensitive), or there are none.</summary>
public static bool MatchesKeywords(string text, List<string> keywords)
{
if (keywords.Count == 0) return true;
foreach (string k in keywords)
if (text.Contains(k, StringComparison.OrdinalIgnoreCase)) return true;
return false;
}
// Unanchored: a webhook's token after /webhooks/{id}/, and anything shaped like a bot token.
private static readonly Regex RxWebhookTokenAnywhere = new(
@"(?<=webhooks/\d{15,22}/)[A-Za-z0-9_\-]{30,100}", RegexOptions.CultureInvariant);
private static readonly Regex RxBotTokenAnywhere = new(
@"(?<![A-Za-z0-9_\-])[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{4,}\.[A-Za-z0-9_\-]{20,}(?![A-Za-z0-9_\-])", RegexOptions.CultureInvariant);
/// <summary>
/// Removes credentials from an error text before it is shown or logged: <paramref name="secret"/>
/// (the webhook URL or bot token in use) whole, the webhook's bare token on its own, and anything
/// else shaped like a webhook token or a bot token.
/// </summary>
public static string Redact(string text, string? secret)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
string t = text;
if (!string.IsNullOrEmpty(secret))
{
string sec = secret.Trim();
if (sec.Length > 0) t = t.Replace(sec, "***", StringComparison.Ordinal);
Match m = RxWebhook.Match(sec.TrimEnd('/'));
if (m.Success) t = t.Replace(m.Groups["token"].Value, "***", StringComparison.Ordinal);
}
t = RxWebhookTokenAnywhere.Replace(t, "***");
return RxBotTokenAnywhere.Replace(t, "***");
}
}

View file

@ -0,0 +1,282 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordRouteQueue.cs
// One route's send queue, kept free of engine state so
// tools/ChatDiscordTests can drive it: lines waiting for the batch window,
// the post in flight, a batch waiting to retry, pacing, pause and counters.
// ChatDiscord owns one per route and calls it on the pump thread only; it
// does the decrypting, the HTTP and the log.
//
// Off means off: when the relay is off for this character or the route is
// switched off, Stop drops everything queued for it (pending lines, the
// retry, the post in flight, whose result is then ignored). Only an explicit
// test message gets past the switches.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Engine.UI.Data.Discord;
/// <summary>A packed message waiting for, or in, an HTTP post.</summary>
internal sealed class DiscordBatch
{
public required List<string> Lines;
public required string Content;
public bool IsTest;
public int Attempts;
/// <summary>The route's destination when the batch was made (<see cref="DiscordRouteQueue.Credential"/>).</summary>
public string Credential = string.Empty;
/// <summary>Cancels this batch's request (set by ChatDiscord while it's in flight).</summary>
public CancellationTokenSource? Cancel;
}
/// <summary>What <see cref="DiscordRouteQueue.Apply"/> did with a post's result.</summary>
internal enum DiscordOutcome
{
/// <summary>The batch was no longer in flight (stopped, route removed): result dropped.</summary>
Ignored,
Sent,
Paused,
RateLimited,
Retrying,
GaveUp,
/// <summary>The route's destination changed while the post was out: a failure is dropped, not retried or paused.</summary>
Retargeted,
}
internal sealed class DiscordRouteQueue
{
public const int DedupWindowMs = 3000;
public const int MaxTransientRetries = 5;
public const int MaxBackoffMs = 60000;
public readonly List<string> Pending = new();
public long FirstPendingMs;
public long NextAllowedMs;
public DiscordBatch? InFlight;
public DiscordBatch? Retry;
public int BackoffMs;
public bool Paused;
public string LastError = string.Empty;
public int MessagesSent, LinesSent, Dropped;
public DateTime LastSent;
public readonly Dictionary<string, long> Recent = new(StringComparer.Ordinal);
/// <summary>
/// The destination the queued lines are for: the route's mode and its saved (encrypted)
/// webhook or bot token + channel. Set by <see cref="Retarget"/>.
/// </summary>
public string Credential = string.Empty;
/// <summary>Lines waiting, in flight or waiting to retry.</summary>
public int Queued => Pending.Count + (InFlight?.Lines.Count ?? 0) + (Retry?.Lines.Count ?? 0);
/// <summary>
/// Called with the route's current destination before lines are added or a post started.
/// When it changed (a new webhook URL or token pasted, the channel or mode changed), chat
/// queued for the old destination is dropped rather than sent to the new one: the pending
/// lines and a batch waiting to retry. A post already in flight went to the old one; if it
/// fails it isn't retried (<see cref="Apply"/>). A test is kept: it's meant for whatever the
/// route points at now. Returns the number of lines dropped.
/// </summary>
public int Retarget(string credential)
{
_mode = _channel = _blob = null;
return RetargetTo(credential);
}
// The route fields the credential was last built from (compared by reference: the pump
// calls this every tick, and the route's strings are replaced, never edited, on a change).
private string? _mode, _channel, _blob;
/// <summary><see cref="Retarget(string)"/> from a route's mode, channel and saved blob (webhook or bot token).</summary>
public int Retarget(string mode, string channel, string blob)
{
if (ReferenceEquals(mode, _mode) && ReferenceEquals(channel, _channel) && ReferenceEquals(blob, _blob)) return 0;
int dropped = RetargetTo(mode == DiscordRoute.ModeBot ? $"bot|{channel}|{blob}" : $"webhook|{blob}");
(_mode, _channel, _blob) = (mode, channel, blob);
return dropped;
}
private int RetargetTo(string credential)
{
if (string.Equals(credential, Credential, StringComparison.Ordinal)) return 0;
bool first = Credential.Length == 0 && Queued == 0;
Credential = credential;
if (first) return 0;
int dropped = Pending.Count;
Pending.Clear();
if (Retry is { IsTest: false } retry)
{
dropped += retry.Lines.Count;
Retry = null;
}
if (Retry is { } test) test.Credential = credential;
if (dropped > 0)
{
Dropped += dropped;
BackoffMs = 0;
}
return dropped;
}
/// <summary>Adds a relayed line; the oldest are dropped past <paramref name="maxQueue"/>.</summary>
public void Add(string line, long now, int maxQueue)
{
if (Pending.Count == 0) FirstPendingMs = now;
Pending.Add(line);
int over = Pending.Count - maxQueue;
if (over > 0)
{
Pending.RemoveRange(0, over);
Dropped += over;
}
}
/// <summary>
/// True (and remembered) unless the same line went to this route within the dedup window.
/// </summary>
public bool NoteFresh(string key, long now)
{
if (Recent.TryGetValue(key, out long seen) && now - seen < DedupWindowMs) return false;
Recent[key] = now;
if (Recent.Count > 256) ChatDiscordLogic.PruneRecent(Recent, now, DedupWindowMs);
return true;
}
/// <summary>Queues a test line to go next (it replaces a waiting retry: that is dropped).</summary>
public void QueueTest(string line)
{
if (Retry is { IsTest: false } old) Dropped += old.Lines.Count;
Retry = new DiscordBatch { Lines = new List<string> { line }, Content = line, IsTest = true };
NextAllowedMs = 0;
}
/// <summary>Clears a pause (Resume, a credential change, a test).</summary>
public void Resume()
{
Paused = false;
LastError = string.Empty;
BackoffMs = 0;
NextAllowedMs = 0;
}
/// <summary>
/// The relay is off for this character, or the route is: drops the pending lines, the batch
/// waiting to retry and the post in flight (cancelled; its result will be ignored). A test
/// message is kept. Returns the number of lines dropped. Pump thread.
/// </summary>
public int Stop()
{
int dropped = Pending.Count;
Pending.Clear();
if (Retry is { IsTest: false } retry)
{
dropped += retry.Lines.Count;
Retry = null;
}
if (InFlight is { IsTest: false } flying)
{
dropped += flying.Lines.Count;
InFlight = null;
try { flying.Cancel?.Cancel(); } catch (ObjectDisposedException) { }
}
if (dropped > 0)
{
Dropped += dropped;
BackoffMs = 0;
}
return dropped;
}
/// <summary>
/// The next batch to post now, or null. <paramref name="on"/> is the relay's switch for this
/// character and the route's own switch together: off, only a test may go (anything else is
/// dropped, as in <see cref="Stop"/>). The batch becomes <see cref="InFlight"/>.
/// </summary>
public DiscordBatch? Next(long now, bool on, int batchMs, int intervalMs)
{
if (!on) Stop();
if (InFlight != null || Paused || now < NextAllowedMs) return null;
DiscordBatch? batch = Retry;
if (batch == null)
{
if (!on || Pending.Count == 0) return null;
// Wait out the batch window unless the pending text already fills a message.
int chars = 0;
foreach (string l in Pending) chars += l.Length + 1;
if (now - FirstPendingMs < batchMs && chars < DiscordFormat.MaxContent) return null;
string content = DiscordFormat.Pack(Pending, out int taken);
batch = new DiscordBatch { Lines = Pending.GetRange(0, taken), Content = content, Credential = Credential };
Pending.RemoveRange(0, taken);
FirstPendingMs = now;
}
if (batch.IsTest) batch.Credential = Credential;
Retry = null;
InFlight = batch;
NextAllowedMs = now + intervalMs;
return batch;
}
/// <summary>
/// Applies a post's result. A result for a batch that is no longer in flight (stopped, or
/// the route was removed) is ignored: it must not come back as a retry.
/// </summary>
public DiscordOutcome Apply(DiscordBatch batch, DiscordSendResult r, long now, int intervalMs)
{
if (!ReferenceEquals(InFlight, batch)) return DiscordOutcome.Ignored;
InFlight = null;
if (r.Ok)
{
LastError = string.Empty;
BackoffMs = 0;
MessagesSent++;
LinesSent += batch.Lines.Count;
LastSent = DateTime.Now;
NextAllowedMs = Math.Max(NextAllowedMs, now + Math.Max(intervalMs, r.RetryAfterMs));
return DiscordOutcome.Sent;
}
if (!batch.IsTest && !string.Equals(batch.Credential, Credential, StringComparison.Ordinal))
{
// Sent to the old destination; the new one gets neither the retry nor a pause.
Dropped += batch.Lines.Count;
return DiscordOutcome.Retargeted;
}
LastError = r.Error;
if (r.Permanent)
{
Paused = true;
Dropped += batch.Lines.Count + Pending.Count;
Pending.Clear();
return DiscordOutcome.Paused;
}
if (r.Status == 429)
{
// Rate limits don't count as a failed attempt; Discord says exactly when to come back.
Retry = batch;
NextAllowedMs = now + Math.Max(r.RetryAfterMs, intervalMs);
return DiscordOutcome.RateLimited;
}
batch.Attempts++;
if (batch.Attempts >= MaxTransientRetries)
{
Dropped += batch.Lines.Count;
BackoffMs = 0;
return DiscordOutcome.GaveUp;
}
BackoffMs = BackoffMs == 0 ? 2000 : Math.Min(BackoffMs * 2, MaxBackoffMs);
Retry = batch;
NextAllowedMs = now + Math.Max(BackoffMs, r.RetryAfterMs);
return DiscordOutcome.Retrying;
}
}

View file

@ -0,0 +1,115 @@
// ============================================================================
// RynthCore.Engine - UI/Data/Discord/DiscordSecrets.cs
// Windows DPAPI (CurrentUser) protection for the Discord relay's webhook URLs
// and bot tokens.
//
// A webhook URL is itself a credential: anyone holding it can post to the
// channel. Both secrets are kept in rynthchat_discord.json only as base64
// DPAPI blobs, readable by the Windows user who saved them. Decrypt at the
// moment of use; never log, display or echo the plain text.
// ============================================================================
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
namespace RynthCore.Engine.UI.Data.Discord;
internal static class DiscordSecrets
{
// Changing this makes every saved secret unreadable. Change it only with a migration.
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("RynthCore.RynthChat.DiscordRelay.v1");
private const int CryptProtectUiForbidden = 0x1;
/// <summary>Encrypts <paramref name="plainText"/> for this Windows user. Empty in, empty out.</summary>
public static string Protect(string? plainText)
{
if (string.IsNullOrEmpty(plainText)) return string.Empty;
byte[] plain = Encoding.UTF8.GetBytes(plainText);
try { return Convert.ToBase64String(Transform(plain, protect: true)); }
finally { Array.Clear(plain); }
}
/// <summary>
/// Decrypts a value written by <see cref="Protect"/>. False when it can't be read on this
/// Windows user (copied from another user or PC, damaged base64, wrong entropy).
/// </summary>
public static bool TryUnprotect(string? protectedBase64, out string plainText)
{
plainText = string.Empty;
if (string.IsNullOrEmpty(protectedBase64)) return false;
byte[] blob;
try { blob = Convert.FromBase64String(protectedBase64); }
catch (FormatException) { return false; }
byte[]? plain = null;
try
{
plain = Transform(blob, protect: false);
plainText = Encoding.UTF8.GetString(plain);
return true;
}
catch (Exception ex) when (ex is Win32Exception or PlatformNotSupportedException or EntryPointNotFoundException or DllNotFoundException)
{
return false;
}
finally
{
if (plain != null) Array.Clear(plain);
}
}
private static byte[] Transform(byte[] input, bool protect)
{
GCHandle inputHandle = GCHandle.Alloc(input, GCHandleType.Pinned);
GCHandle entropyHandle = GCHandle.Alloc(Entropy, GCHandleType.Pinned);
var output = new DataBlob();
try
{
var inputBlob = new DataBlob { cbData = input.Length, pbData = inputHandle.AddrOfPinnedObject() };
var entropyBlob = new DataBlob { cbData = Entropy.Length, pbData = entropyHandle.AddrOfPinnedObject() };
bool ok = 0 != (protect
? CryptProtectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output)
: CryptUnprotectData(ref inputBlob, IntPtr.Zero, ref entropyBlob, IntPtr.Zero, IntPtr.Zero, CryptProtectUiForbidden, ref output));
if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error());
byte[] result = new byte[output.cbData];
if (output.cbData > 0) Marshal.Copy(output.pbData, result, 0, output.cbData);
return result;
}
finally
{
if (output.pbData != IntPtr.Zero)
{
// Wipe the native copy (the plain text, when decrypting) before freeing it.
for (int i = 0; i < output.cbData; i++) Marshal.WriteByte(output.pbData, i, 0);
LocalFree(output.pbData);
}
inputHandle.Free();
entropyHandle.Free();
}
}
[StructLayout(LayoutKind.Sequential)]
private struct DataBlob
{
public int cbData;
public IntPtr pbData;
}
// Win32 BOOL is returned as int so the signatures stay blittable under NativeAOT.
[DllImport("crypt32.dll", SetLastError = true)]
private static extern int CryptProtectData(ref DataBlob pDataIn, IntPtr szDataDescr, ref DataBlob pOptionalEntropy,
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
[DllImport("crypt32.dll", SetLastError = true)]
private static extern int CryptUnprotectData(ref DataBlob pDataIn, IntPtr ppszDataDescr, ref DataBlob pOptionalEntropy,
IntPtr pvReserved, IntPtr pPromptStruct, int dwFlags, ref DataBlob pDataOut);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr hMem);
}

View file

@ -462,6 +462,8 @@ internal static class SettingsSchema
Section("Text Size (in-game panels)"),
Combo("All Panels", PanelTextScale.SizeNames, _ => PanelTextScale.GetAll(), (_, v) => PanelTextScale.SetAll(v),
"Text size for every in-game panel: 0 = normal, each step 10% bigger, yourjokin = 2.5x."),
Combo("Toolbar", PanelTextScale.SizeNames, _ => PanelTextScale.GetChrome(), (_, v) => PanelTextScale.SetChrome(v),
"Size of the RynthCore icon bar (its icons and tooltips), separate from the panels: 0 = normal, each step 10% bigger.\nAlso: right-click the bar's grip, Ctrl+wheel over the bar, or /rc ui barsize."),
Bool("Size Each Panel Separately", _ => PanelTextScale.PerPanel, (_, v) => PanelTextScale.PerPanel = v,
"Off: every panel uses All Panels. On: set each panel's text size below.", gates: true),
TextSize("RynthAi Dashboard", "RynthAi"),

View file

@ -32,9 +32,11 @@ internal static class UiSources
public static readonly MonsterDetailSource MonsterDetail = new();
public static readonly LootEditSource LootEdit = new();
public static readonly SenseSource Sense = new();
public static readonly BountiesSource Bounties = new();
static UiSources()
{
UiDataHub.Register(Bounties);
UiDataHub.Register(Settings);
UiDataHub.Register(Meta);
UiDataHub.Register(LootEdit);

View file

@ -6,7 +6,9 @@
// as "Title=size" lines; set from Settings > Display or from a window's own
// title bar (the text size button, Ctrl+wheel; ImGuiPanelHost). One size
// ("All Panels") applies to every panel unless "Size each panel separately"
// is on.
// is on. The toolbar (the icon bar, ImGuiBar) has its own size, the "chrome"
// row (Settings > Display > Toolbar, the bar's right-click menu, Ctrl+wheel on
// the bar, /rc ui barsize); it is independent of All Panels and per-panel sizes.
// ============================================================================
using System;
@ -27,11 +29,16 @@ internal static class PanelTextScale
private static readonly Dictionary<string, int> Sizes = new(StringComparer.OrdinalIgnoreCase);
private static bool _loaded;
private static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt");
// RYNTHCORE_PANEL_TEXT_SIZE points a test at its own file instead of the real one.
private static readonly string FilePath =
Environment.GetEnvironmentVariable("RYNTHCORE_PANEL_TEXT_SIZE") is { Length: > 0 } overridePath
? overridePath
: Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "panel_text_size.txt");
private const string AllKey = "__all";
private const string PerPanelKey = "__perPanel";
private const string ChromeKey = "__chrome";
/// <summary>The size (0-10) a panel is drawn at: its own when sizing per panel, else All Panels.</summary>
public static int Get(string title)
@ -59,6 +66,18 @@ internal static class PanelTextScale
public static int GetAll() => GetOwn(AllKey);
public static void SetAll(int size) => Set(AllKey, size);
/// <summary>The toolbar's size (0-10): its own row, 0 unless set; never All Panels.</summary>
public static int GetChrome()
{
lock (Sync)
{
Load();
return Sizes.TryGetValue(ChromeKey, out int c) ? c : 0;
}
}
public static void SetChrome(int size) => Set(ChromeKey, size);
/// <summary>Off: every panel uses All Panels. On: each panel has its own size.</summary>
public static bool PerPanel
{
@ -108,7 +127,7 @@ internal static class PanelTextScale
// effect: start them from what every panel shows now.
var keys = new List<string>(Sizes.Keys);
foreach (string k in keys)
if (k != AllKey && k != PerPanelKey) Sizes[k] = all;
if (k != AllKey && k != PerPanelKey && k != ChromeKey) Sizes[k] = all;
Sizes[PerPanelKey] = 1;
}
Sizes[title] = size;
@ -145,7 +164,7 @@ internal static class PanelTextScale
/// <summary>Font size factor for a size step.</summary>
public static float Factor(int step) => Scales[Math.Clamp(step, 0, Scales.Length - 1)];
/// <summary>The distinct non-zero sizes any panel uses (fonts are baked for these).</summary>
/// <summary>The distinct non-zero sizes any panel or the toolbar uses (fonts are baked for these).</summary>
public static List<int> StepsInUse()
{
lock (Sync)
@ -156,7 +175,7 @@ internal static class PanelTextScale
foreach (var kv in Sizes)
{
if (kv.Key == PerPanelKey) continue;
if (!perPanel && kv.Key != AllKey) continue; // only All Panels is in use
if (!perPanel && kv.Key != AllKey && kv.Key != ChromeKey) continue; // All Panels and the toolbar are in use
if (kv.Value > 0 && !steps.Contains(kv.Value)) steps.Add(kv.Value);
}
return steps;