Snapshot for release 2026.10.21.1 (internal 32a418d)

This commit is contained in:
Tom Bohar 2026-10-21 09:35:08 -04:00
commit 6fe5630e8c
202 changed files with 43765 additions and 0 deletions

View file

@ -0,0 +1,23 @@
// ServerChatRequest.cs - "the server plugin just sent this command": a short time window in which the
// command's reply counts as the plugin's own, so the server's code (ServerPackPlugin.ServerChatText)
// can hide replies to its own requests and still show the same command typed by hand. A time window,
// as RynthOracle has always done it (ported from Oracle of Dereth by Advis Eveldan, MIT): these replies
// carry nothing tying them to the request. Each reply line extends it, so a long reply stays ours to its end.
// Pure: RynthServerPack.Tests covers it.
namespace RynthCore.Plugin.ServerPack;
internal sealed class ServerChatRequest
{
public const long WindowMs = 5000;
private long _untilMs;
public void Sent(long nowMs) => _untilMs = nowMs + WindowMs;
public void Clear() => _untilMs = 0;
public bool Awaiting(long nowMs) => nowMs < _untilMs;
/// <summary>A reply line arrived: keep the window open a little longer.</summary>
public void Extend(long nowMs)
{
if (Awaiting(nowMs)) _untilMs = nowMs + 2000 > _untilMs ? nowMs + 2000 : _untilMs;
}
}

View file

@ -0,0 +1,159 @@
// ServerPackExports.cs - The native exports every server plugin has (compiled into each one).
// UnmanagedCallersOnly entry points can't live in a generic or shared assembly, so each server
// plugin compiles this file itself, around its own ServerPackPlugin.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.ServerPack;
public static unsafe class ServerPackExports
{
private static readonly RynthPluginRuntime<ServerPackPlugin> Runtime = new();
/// <summary>The live plugin (null before init and after shutdown).</summary>
internal static ServerPackPlugin? Plugin => Runtime.Plugin;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
/// <summary>
/// Plugin API v68 plugin-to-plugin interfaces: "RynthServer.Profile" v1 (ServerPackInterface),
/// the server's settings for any plugin RynthCore's GetServerStateJson points at this one, and
/// "RynthServer.QuestPack" v1, the server's own quest list when the plugin has one.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginQueryInterface", CallConvs = new[] { typeof(CallConvCdecl) })]
private static IntPtr QueryInterface(IntPtr ifaceAnsi, uint version)
{
try
{
string iface = ifaceAnsi == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(ifaceAnsi) ?? "";
return ServerPackInterface.Query(iface, version);
}
catch
{
return IntPtr.Zero; // an exception crossing UnmanagedCallersOnly would fail-fast the client
}
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown()
{
try { ServerPackInterface.Release(); } catch { }
Runtime.Shutdown();
IntPtr old = Interlocked.Exchange(ref _sectionsPtr, IntPtr.Zero);
if (old != IntPtr.Zero) Marshal.FreeCoTaskMem(old);
_sectionsJson = null;
}
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => ServerPackPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => ServerPackPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
// "/rserver ..." commands.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
// Incoming chat, for the server's own code (ServerPackPlugin.ServerChatText). Pump thread.
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) => Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
/// <summary>The standalone server card ("/rserver"). Render thread.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render()
{
try { Runtime.OnRender(); }
catch { /* an exception crossing UnmanagedCallersOnly would fail-fast the client */ }
}
/// <summary>
/// The engine's plugin-command broker: "servermenu" from RynthCore (2026.10.5.48+). The ANSI
/// strings are copied before returning (the caller frees them); the payload is only parsed, so
/// any thread is fine.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginApplyRemoteCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void ApplyRemoteCommand(IntPtr actionAnsi, IntPtr valueAnsi)
{
try
{
string action = actionAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(actionAnsi) ?? string.Empty) : string.Empty;
if (action.Length == 0 || action.Length > 32) return;
string value = valueAnsi != IntPtr.Zero ? (Marshal.PtrToStringAnsi(valueAnsi) ?? string.Empty) : string.Empty;
Runtime.Plugin?.ApplyRemoteCommand(action, value);
}
catch { /* never let a managed exception cross the native boundary */ }
}
/// <summary>
/// RynthCore's Mini Remote sections: "section:server-&lt;id&gt;" (":popout" added in a popped-out
/// window) draws the server card into the engine's current window, "section:server-&lt;id&gt;.&lt;page&gt;"
/// one of the server's own pages (ServerPackPages). 1 = drawn, 0 = not ready or not ours.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRenderEmbed", CallConvs = new[] { typeof(CallConvCdecl) })]
public static int RenderEmbed(byte* surface, float width, float height, float* wantWidth, float* wantHeight)
{
try
{
if (surface == null) return 0;
string name = Marshal.PtrToStringUTF8((IntPtr)surface) ?? string.Empty;
if (name.EndsWith(":popout", StringComparison.Ordinal)) name = name[..^":popout".Length];
var plugin = Runtime.Plugin;
if (plugin == null) return 0;
float wantH;
if (name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal))
{
if (!plugin.RenderEmbeddedCard(out wantH)) return 0;
}
else
{
string? page = ServerPackPages.PageIdOf(name, RynthPluginInfo.ServerId);
if (page == null || !plugin.RenderEmbeddedPage(page, out wantH)) return 0;
}
if (wantWidth != null) *wantWidth = width;
if (wantHeight != null) *wantHeight = wantH;
return 1;
}
catch
{
return 0; // an exception crossing UnmanagedCallersOnly would fail-fast the client
}
}
private static IntPtr _sectionsPtr = IntPtr.Zero;
private static string? _sectionsJson;
/// <summary>
/// RynthCore 2026.10.5.46+: the server and the card's Mini Remote spot (UTF-8 JSON, schema 1).
/// Null before login. An unchanged manifest keeps the same buffer.
/// </summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetSectionsJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetSectionsJson()
{
try
{
string? json = Runtime.Plugin?.BuildSectionsJson();
if (json == null) return IntPtr.Zero;
if (json == _sectionsJson && _sectionsPtr != IntPtr.Zero) return _sectionsPtr;
_sectionsJson = json;
IntPtr newPtr = Marshal.StringToCoTaskMemUTF8(json);
IntPtr oldPtr = Interlocked.Exchange(ref _sectionsPtr, newPtr);
if (oldPtr != IntPtr.Zero) Marshal.FreeCoTaskMem(oldPtr);
return newPtr;
}
catch { return IntPtr.Zero; }
}
}

View file

@ -0,0 +1,110 @@
// ServerPackInfo.cs - What a server plugin knows about its game server (shared by every server plugin).
//
// Identity (id, name, hosts, world names) comes from the plugin's csproj through RynthPluginInfo, the
// same values the engine reads from the embedded manifest, so detection has one source. The rest is
// what is publicly known about the server (ServerData.cs in each project): connection, rule set,
// summary, links, account limits and the botting policy. Unknown stays empty; nothing is guessed.
// Pure: RynthServerPack.Tests compiles it.
using System;
namespace RynthCore.Plugin.ServerPack;
/// <summary>What the server's rules say about bots (RynthAi automation).</summary>
internal enum BottingPolicy
{
/// <summary>Not published here: check the server's own rules.</summary>
Unknown,
Allowed,
/// <summary>Allowed with limits (attended only, a client cap, ...): see <see cref="ServerPackInfo.BottingNote"/>.</summary>
Restricted,
/// <summary>The server forbids bots.</summary>
Forbidden,
}
/// <summary>A chat command the server adds, and what it does.</summary>
internal sealed record ServerCommand(string Command, string What);
/// <summary>
/// A salvage the server's own recipes apply (beyond retail tinkering), shown on the Mini Remote's
/// Crafting tab under "Server tinkering".
/// </summary>
/// <param name="Bench">The Crafting tab: "armor", "melee", "missile", "caster", "jewelry", "items" or "trinkets".</param>
/// <param name="Material">The bag's MaterialType (131), e.g. 64 = Steel.</param>
/// <param name="Effect">What it does, one short line.</param>
/// <param name="Kind">"tink" (repeatable), "imbue" (one per item) or "once" (one application).</param>
/// <param name="UsesTinkSlot">Counts toward the item's 10 tinks.</param>
/// <param name="NameMatch">The bag's name must contain this (bags that share a material id); "" = any.</param>
/// <param name="AppliedInt">An int property of the item that reads 2 once this salvage is on it (0 = none).</param>
/// <param name="Prepared">The bag must first be prepared on the chosen tier's Ammunition (its name then carries the tier).</param>
/// <param name="Order">Apply order on the tab (lower first); 0 = by kind (imbues, then tinks, then one-application rows).</param>
/// <param name="AfterCap">Applied last, and only once the item's tink slots are full.</param>
/// <param name="StackGroup">Rows with the same group share one cap per item (<paramref name="StackCap"/>); "" = none.</param>
/// <param name="StackCap">The group's combined cap per item (with <paramref name="StackGroup"/>).</param>
internal sealed record ServerSalvage(string Bench, int Material, string Effect, string Kind = "tink",
bool UsesTinkSlot = true, string NameMatch = "", int AppliedInt = 0,
bool Prepared = false, int Order = 0, bool AfterCap = false,
string StackGroup = "", int StackCap = 0);
internal sealed class ServerPackInfo
{
public ServerPackInfo(string id, string name, string[] hosts, string[] worldNames)
{
Id = (id ?? string.Empty).Trim().ToLowerInvariant();
Name = string.IsNullOrWhiteSpace(name) ? Id : name.Trim();
Hosts = hosts ?? Array.Empty<string>();
WorldNames = worldNames ?? Array.Empty<string>();
}
/// <summary>The engine's id for the server ("coldeve"); a built-in one ("ilt", "aelrynth") keeps the engine's own detection.</summary>
public string Id { get; }
public string Name { get; }
/// <summary>Connect hosts (the first is the one players are given).</summary>
public string[] Hosts { get; }
/// <summary>World names the server announces at login.</summary>
public string[] WorldNames { get; }
public int Port { get; init; } = 9000;
/// <summary>"ACE" or "GDLE" (the launcher's emulator setting).</summary>
public string Emulator { get; init; } = "ACE";
/// <summary>"PvE" or "PvP".</summary>
public string Ruleset { get; init; } = "PvE";
/// <summary>"Stable", "Development", ... as the server list says.</summary>
public string Status { get; init; } = string.Empty;
/// <summary>The server's own one-paragraph description.</summary>
public string Summary { get; init; } = string.Empty;
/// <summary>Notable rules and features, one line each.</summary>
public string[] Facts { get; init; } = Array.Empty<string>();
/// <summary>Chat commands the server adds (only ones known to exist).</summary>
public ServerCommand[] Commands { get; init; } = Array.Empty<ServerCommand>();
/// <summary>The server's own tinkering salvage (only recipes known to exist); empty = none defined.</summary>
public ServerSalvage[] Salvage { get; init; } = Array.Empty<ServerSalvage>();
/// <summary>
/// Jewelry that is a trinket on this server (the Crafting tab's Trinkets bench, not Jewelry): name
/// words, case-insensitive, and words that rule a name out again ("top" but not "topaz"). Empty:
/// the server has no trinkets (retail: every jewelry piece is Jewelry).
/// </summary>
public string[] TrinketNames { get; init; } = Array.Empty<string>();
public string[] TrinketExcept { get; init; } = Array.Empty<string>();
/// <summary>"3 accounts", "3 active characters", ...; empty when not published.</summary>
public string AccountLimit { get; init; } = string.Empty;
public BottingPolicy Botting { get; init; } = BottingPolicy.Unknown;
/// <summary>The rule in the server's words, when there is one.</summary>
public string BottingNote { get; init; } = string.Empty;
public string Discord { get; init; } = string.Empty;
public string Website { get; init; } = string.Empty;
public string Wiki { get; init; } = string.Empty;
/// <summary>Where the facts come from, and when they were checked.</summary>
public string Source { get; init; } = string.Empty;
/// <summary>"play.coldeve.ac:9000" (the first host), or "" with none.</summary>
public string Address => Hosts.Length == 0 ? string.Empty : Hosts[0] + ":" + Port;
/// <summary>The botting line for the card.</summary>
public string BottingText => Botting switch
{
BottingPolicy.Allowed => "Allowed" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty),
BottingPolicy.Restricted => "Restricted" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty),
BottingPolicy.Forbidden => "Forbidden" + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty),
_ => "Not published here - check the server's rules" + (Discord.Length > 0 ? " (Discord)" : string.Empty),
};
}

View file

@ -0,0 +1,138 @@
// ServerPackInterface.cs - A server plugin's side of "RynthServer.Profile"
// (Plugins/Shared/RynthServerProfileApi.cs): the server's settings as JSON (ServerPackProfile) for
// other plugins, answered through RynthPluginQueryInterface (ServerPackExports). Since 2026-10-21 also
// "RynthServer.QuestPack" (Plugins/Shared/RynthServerQuestPackApi.cs): the server's own quest list
// (ServerPackQuestPack), offered only by a plugin whose project has one.
//
// The tables are allocated once per loaded copy of the plugin and never freed (a plugin DLL is never
// unloaded); after Release() they report Version 0 and their functions answer 0. Before the plugin is
// up, or between characters, the profile still describes the server (active false, no world).
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.ServerPack;
internal static unsafe class ServerPackInterface
{
private static RynthServerProfileApiV1* _table;
private static RynthServerQuestPackApiV1* _packTable;
private static volatile bool _released;
// The quest pack's info JSON, built once (the pack is embedded and never changes).
private static string? _packInfo;
/// <summary>The last JSON handed out, and what it was built for (rebuilt only when that changes).</summary>
private sealed record Snapshot(bool Active, string World, int ValuesRevision, string Json);
private static Snapshot? _last;
/// <summary>The table for (<paramref name="iface"/>, <paramref name="version"/>), or 0 when it isn't ours.</summary>
public static IntPtr Query(string iface, uint version)
{
if (iface == RynthServerQuestPackApiV1.InterfaceName) return QueryQuestPack(version);
if (iface != RynthServerProfileApiV1.InterfaceName || version < 1 || version > RynthServerProfileApiV1.InterfaceVersion || _released)
return IntPtr.Zero;
if (_table == null)
{
var t = (RynthServerProfileApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerProfileApiV1));
t->StructSize = (uint)sizeof(RynthServerProfileApiV1);
t->GetProfileJson = &GetProfileJson;
t->Version = RynthServerProfileApiV1.InterfaceVersion;
_table = t;
}
return (IntPtr)_table;
}
/// <summary>
/// "RynthServer.QuestPack": the table when this plugin has a pack (Resources\quests.&lt;id&gt;.csv),
/// else 0, so a reader sees "no pack" the same way as "no such plugin".
/// </summary>
private static IntPtr QueryQuestPack(uint version)
{
if (version < 1 || version > RynthServerQuestPackApiV1.InterfaceVersion || _released) return IntPtr.Zero;
if (PackInfoJson().Length == 0) return IntPtr.Zero;
if (_packTable == null)
{
var t = (RynthServerQuestPackApiV1*)NativeMemory.AllocZeroed((nuint)sizeof(RynthServerQuestPackApiV1));
t->StructSize = (uint)sizeof(RynthServerQuestPackApiV1);
t->GetPackInfoJson = &GetPackInfoJson;
t->GetPackCsv = &GetPackCsv;
t->Version = RynthServerQuestPackApiV1.InterfaceVersion;
_packTable = t;
}
return (IntPtr)_packTable;
}
/// <summary>The pack's info JSON ("" without a pack). Any thread.</summary>
private static string PackInfoJson() =>
_packInfo ??= ServerPackQuestPack.BuildInfoJson(ServerPackPlugin.StaticInfo, RynthPluginInfo.Name,
RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0", ServerPackQuestPack.Csv);
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPackInfoJson(byte* buffer, int capacity)
{
try { return _released ? 0 : Write(PackInfoJson(), buffer, capacity); }
catch { return 0; }
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetPackCsv(byte* buffer, int capacity)
{
try { return _released || PackInfoJson().Length == 0 ? 0 : Write(ServerPackQuestPack.Csv, buffer, capacity); }
catch { return 0; }
}
/// <summary>Plugin shutdown: readers see Version 0 and re-query; the functions answer 0.</summary>
public static void Release()
{
_released = true;
if (_table != null) _table->Version = 0;
if (_packTable != null) _packTable->Version = 0;
}
/// <summary>The JSON to hand out now. Any thread: the plugin's state is read through volatile fields.</summary>
internal static string CurrentJson(ServerPackPlugin? plugin)
{
ServerPackInfo info = plugin?.Info ?? ServerPackPlugin.StaticInfo;
bool active = plugin?.Active ?? false;
string world = plugin?.World ?? string.Empty;
int valuesRevision = plugin?.ProfileValues.Revision ?? -1;
Snapshot? last = Volatile.Read(ref _last);
if (last != null && last.Active == active && last.World == world && last.ValuesRevision == valuesRevision) return last.Json;
KeyValuePair<string, double>[] values = plugin != null
? plugin.ProfileValues.Snapshot(out valuesRevision)
: Array.Empty<KeyValuePair<string, double>>();
string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world, values);
Volatile.Write(ref _last, new Snapshot(active, world, valuesRevision, json));
return json;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int GetProfileJson(byte* buffer, int capacity)
{
try
{
if (_released) return 0;
return Write(CurrentJson(ServerPackExports.Plugin), buffer, capacity);
}
catch { return 0; }
}
/// <summary>
/// Copies <paramref name="json"/> as NUL-terminated UTF-8 into the caller's buffer when it fits,
/// and returns its byte length either way (length >= capacity: too small, nothing written).
/// The quest pack's CSV goes the same way.
/// </summary>
internal static int Write(string json, byte* buffer, int capacity)
{
int length = Encoding.UTF8.GetByteCount(json);
if (buffer == null || capacity <= length) return length;
fixed (char* src = json)
Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity);
buffer[length] = 0;
return length;
}
}

View file

@ -0,0 +1,242 @@
// ServerPackModel.cs - A server plugin's view of "is this my server", and what it tells RynthCore.
//
// RynthCore owns the verdict. Each server plugin declares its server in its Mini Remote sections
// manifest (RynthPluginGetSectionsJson, "servers"), so RynthCore detects it (connect host, then the
// announced world name), applies this character's Auto / On / Off override, and pushes the result
// to the plugin as "servermenu" (RynthCore UI/ServerMenus.cs):
// V id name active 0/1 force auto|on|off detected 0/1 reason
// Other line kinds are RynthAi's menus and are skipped. Until a push arrives (an engine older than
// 2026.10.5.48), the plugin falls back to matching the world name itself.
//
// Pushes arrive on whichever thread sent them; each is parsed into one immutable view and published
// with a single reference write, so the render thread always reads a whole one.
// Pure (no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace RynthCore.Plugin.ServerPack;
/// <summary>RynthCore's verdict for this plugin's server.</summary>
internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason);
internal sealed class ServerPackModel
{
/// <summary>Payloads longer than this are not ours (a push is a few hundred bytes).</summary>
public const int MaxPayload = 64 * 1024;
private readonly ServerPackInfo _info;
private ServerVerdictView? _engine;
private long _engineAtMs;
public ServerPackModel(ServerPackInfo info) => _info = info;
public ServerPackInfo Info => _info;
/// <summary>The last RynthCore verdict for this server (null until a push lists it). Any thread.</summary>
public ServerVerdictView? Engine => Volatile.Read(ref _engine);
/// <summary>When the last push arrived (Environment.TickCount64), 0 for never.</summary>
public long EngineAtMs => Interlocked.Read(ref _engineAtMs);
/// <summary>A RynthCore "servermenu" push. Any thread. False when it was not usable.</summary>
public bool ApplyEngine(string? payload, long nowMs)
{
ServerVerdictView? view = ParseEngine(payload, _info.Id, out bool listed);
if (!listed) return false;
Volatile.Write(ref _engine, view);
Interlocked.Exchange(ref _engineAtMs, nowMs);
return true;
}
/// <summary>Logout: the next character's verdict comes fresh.</summary>
public void Clear()
{
Volatile.Write(ref _engine, null);
Interlocked.Exchange(ref _engineAtMs, 0);
}
/// <summary>
/// True when this plugin should act: RynthCore's verdict when it sent one, else the world
/// name (<paramref name="world"/>) against the plugin's own list.
/// </summary>
public bool IsActive(string? world)
{
ServerVerdictView? v = Engine;
return v != null ? v.Active : WorldMatches(world, _info.WorldNames);
}
/// <summary>
/// The verdict for <paramref name="serverId"/> in a "servermenu" payload. <paramref name="listed"/>
/// is false when the payload has no server lines at all (not a push); the view is null when it has
/// some but not this server (RynthCore hasn't read this plugin's manifest yet).
/// </summary>
public static ServerVerdictView? ParseEngine(string? payload, string serverId, out bool listed)
{
listed = false;
if (string.IsNullOrEmpty(payload) || payload.Length > MaxPayload || string.IsNullOrEmpty(serverId)) return null;
ServerVerdictView? view = null;
foreach (string raw in payload.Split('\n'))
{
string[] f = raw.TrimEnd('\r').Split('\t');
if (f[0] != "V" || f.Length < 6) continue;
listed = true;
if (!f[1].Equals(serverId, StringComparison.OrdinalIgnoreCase)) continue;
view = new ServerVerdictView(f[2], f[3] == "1", NormalizeForce(f[4]), f[5] == "1", f.Length >= 7 ? f[6] : string.Empty);
}
return view;
}
/// <summary>"auto", "on" or "off" (anything else reads as auto).</summary>
public static string NormalizeForce(string? text)
{
string t = (text ?? string.Empty).Trim().ToLowerInvariant();
return t is "on" or "off" ? t : "auto";
}
/// <summary>"/rc server {id} {mode}" for auto / on / off; "" for anything else.</summary>
public static string ForceCommand(string serverId, string mode)
{
string m = (mode ?? string.Empty).Trim().ToLowerInvariant();
if (m is not ("auto" or "on" or "off") || !IsSafeId(serverId)) return string.Empty;
return "/rc server " + serverId + " " + m;
}
/// <summary>True for an id RynthCore accepts in a command: 1-32 of a-z, 0-9 and '-'.</summary>
public static bool IsSafeId(string? id)
{
if (string.IsNullOrEmpty(id) || id.Length > 32) return false;
foreach (char c in id)
if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false;
return true;
}
/// <summary>Case-insensitive world-name match, '*' standing for any text (RynthCore's rules).</summary>
public static bool WorldMatches(string? world, string[] patterns)
{
if (string.IsNullOrWhiteSpace(world)) return false;
string w = world.Trim();
foreach (string p in patterns)
if (!string.IsNullOrWhiteSpace(p) && Glob(w, p.Trim())) return true;
return false;
}
private static bool Glob(string text, string pattern)
{
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;
}
// ── RynthPluginGetSectionsJson ────────────────────────────────────────
/// <summary>The Mini Remote surface of the server card.</summary>
public static string SurfaceFor(string serverId) => "section:server-" + serverId;
/// <summary>
/// The Mini Remote section the server cards share: right after Session Stats (core order 0) and
/// before Map (100). Every server plugin declares it the same way; the first declaration wins.
/// </summary>
public const string SectionId = "server";
public const string SectionLabel = "Server";
public const int SectionOrder = 50;
/// <summary>
/// The plugin's sections manifest (schema 1): its server, for RynthCore to detect, and the server
/// card in the shared "Server" section, shown only while that server is active (detected or
/// forced in RynthCore Options > Diagnostics). The card left the Char section on 2026-10-13: that
/// section is Session Stats now, session stats only.
/// <paramref name="pages"/> (ServerPackPages, already validated) are the server's own views:
/// primary views of the same section, so each gets a sub-tab there, also only on that server.
/// </summary>
public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList<ServerPage>? pages = null)
{
var sb = new StringBuilder(512);
sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name));
sb.Append(",\"worldNames\":[");
AppendList(sb, info.WorldNames);
sb.Append("],\"hosts\":[");
AppendList(sb, info.Hosts);
sb.Append("]}],\"sections\":[{\"id\":").Append(Q(SectionId)).Append(",\"label\":").Append(Q(SectionLabel));
sb.Append(",\"order\":").Append(SectionOrder).Append("}],\"contributions\":[{\"section\":").Append(Q(SectionId));
sb.Append(",\"server\":").Append(Q(info.Id));
sb.Append(",\"label\":").Append(Q(info.Name + " server (" + pluginName + ")"));
sb.Append(",\"surface\":").Append(Q(SurfaceFor(info.Id)));
sb.Append(",\"primary\":false,\"height\":320,\"enabled\":true,\"tooltip\":");
sb.Append(Q("What is known about " + info.Name + ": rules, account limits, botting policy, links and setup ("
+ pluginName + "; also /rserver)."));
sb.Append(",\"order\":130}");
if (pages != null)
{
for (int i = 0; i < pages.Count; i++)
{
ServerPage p = pages[i];
sb.Append(",{\"section\":").Append(Q(SectionId));
sb.Append(",\"server\":").Append(Q(info.Id));
sb.Append(",\"label\":").Append(Q(p.Label));
sb.Append(",\"surface\":").Append(Q(ServerPackPages.SurfaceFor(info.Id, p.Id)));
sb.Append(",\"primary\":true,\"width\":").Append(ServerPackPages.Width).Append(",\"height\":").Append(ServerPackPages.Height);
sb.Append(",\"enabled\":true,\"tooltip\":").Append(Q(p.Tooltip.Length > 0 ? p.Tooltip : p.Label + " (" + pluginName + ")"));
sb.Append(",\"order\":").Append(100 + i).Append('}');
}
}
sb.Append("]}");
return sb.ToString();
}
private static void AppendList(StringBuilder sb, string[] values)
{
for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ",").Append(Q(values[i]));
}
/// <summary>A JSON string literal.</summary>
public static string Q(string? s)
{
var sb = new StringBuilder((s?.Length ?? 0) + 2).Append('"');
foreach (char c in s ?? string.Empty)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
break;
}
}
return sb.Append('"').ToString();
}
// ── The launcher side ─────────────────────────────────────────────────
/// <summary>How to set up an account for this server in the RynthCore launcher.</summary>
public static string[] LauncherSteps(ServerPackInfo info) => new[]
{
"1. Launcher > Servers > Add: pick \"" + info.Name + "\" under Known server. It fills in "
+ (info.Address.Length > 0 ? info.Address : "the host and port") + " (" + info.Emulator + ").",
"2. Launcher > Accounts > Add: choose that server, then the account and character.",
"3. Launch: RynthCore loads this plugin only for clients connecting to " + info.Name + ".",
};
}

View file

@ -0,0 +1,86 @@
// ServerPackPages.cs - Pages a server plugin adds beside its server card (RynthConquest's Conquest and
// Leaderboards pages, RynthAelrynth's Leaderboards, ...).
//
// A server's own features need somewhere to show. The ServerPackPlugin.ServerPages hook lists them
// once, at construction; the shared code then
// * declares each one in the sections manifest as a primary view of the shared "Server" section,
// shown only while this plugin's server is active (contribution "server": <id>), so RynthCore's
// Mini Remote gives it a sub-tab next to the server card;
// * draws it through RynthPluginRenderEmbed under the surface "section:server-<id>.<page>"
// (":popout" added in a popped-out window), into the engine's current window and context;
// * shows the same pages as tabs of the standalone "/rserver" window, after the card.
// Draw runs on the render thread: a page reads its state under its own lock and queues anything it
// sends for the plugin tick (ServerPackPlugin.RunOnTick).
// Pure (no ImGui, no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.ServerPack;
/// <summary>
/// One page a server plugin adds. <paramref name="Id"/> is 1-16 of a-z, 0-9 and '-' (part of the
/// surface name); <paramref name="Draw"/> draws the body into the current ImGui window (render thread).
/// </summary>
internal sealed record ServerPage(string Id, string Label, string Tooltip, Action Draw);
internal static class ServerPackPages
{
/// <summary>At most this many pages per plugin (the Mini Remote shows them as one row of tabs).</summary>
public const int MaxPages = 6;
/// <summary>The longest page id (keeps "section:server-&lt;32-char id&gt;.&lt;page&gt;" under the engine's 64).</summary>
public const int MaxIdLength = 16;
/// <summary>The engine caps contribution labels at 48 characters.</summary>
public const int MaxLabelLength = 48;
/// <summary>Page views open at this size in the Mini Remote (it fits the window to the view).</summary>
public const int Width = 540, Height = 520;
/// <summary>True for a page id: 1-16 of a-z, 0-9 and '-'.</summary>
public static bool IsValidId(string? id)
{
if (string.IsNullOrEmpty(id) || id.Length > MaxIdLength) return false;
foreach (char c in id)
if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) return false;
return true;
}
/// <summary>"section:server-conquest.bank": the page's surface.</summary>
public static string SurfaceFor(string serverId, string pageId) => ServerPackModel.SurfaceFor(serverId) + "." + pageId;
/// <summary>
/// The page id a surface names for this server ("section:server-conquest.bank" -> "bank"), or
/// null for the card, another server's surface or anything else. ":popout" is ignored.
/// </summary>
public static string? PageIdOf(string? surface, string serverId)
{
if (string.IsNullOrEmpty(surface)) return null;
string name = surface.EndsWith(":popout", StringComparison.Ordinal) ? surface[..^":popout".Length] : surface;
string prefix = ServerPackModel.SurfaceFor(serverId) + ".";
if (!name.StartsWith(prefix, StringComparison.Ordinal)) return null;
string id = name[prefix.Length..];
return IsValidId(id) ? id : null;
}
/// <summary>
/// The pages kept from what a plugin listed: valid, unique ids, a label, at most
/// <see cref="MaxPages"/>; each one dropped is reported to <paramref name="log"/>.
/// </summary>
public static List<ServerPage> Validate(IEnumerable<ServerPage>? pages, Action<string>? log = null)
{
var kept = new List<ServerPage>();
if (pages == null) return kept;
foreach (ServerPage p in pages)
{
if (p == null) continue;
string why = !IsValidId(p.Id) ? "its id isn't 1-16 of a-z, 0-9 and '-'"
: string.IsNullOrWhiteSpace(p.Label) ? "it has no label"
: p.Draw == null ? "it has nothing to draw"
: kept.Exists(k => k.Id == p.Id) ? "another page has its id"
: kept.Count >= MaxPages ? $"a plugin has at most {MaxPages} pages"
: string.Empty;
if (why.Length > 0) { log?.Invoke($"Page '{p.Id}' left out: {why}."); continue; }
string label = p.Label.Trim();
kept.Add(p with { Label = label.Length <= MaxLabelLength ? label : label[..MaxLabelLength], Tooltip = p.Tooltip ?? string.Empty });
}
return kept;
}
}

View file

@ -0,0 +1,400 @@
// ServerPackPlugin.cs - The shared body of every server plugin (RynthColdeve, RynthAelrynth, ...),
// built like RynthILT: one plugin per game server, so each one ships and updates on its own.
//
// What it does for its server:
// * declares the server to RynthCore (RynthPluginGetSectionsJson "servers": its hosts and world
// names), so RynthCore detects it and puts this plugin's views in the right Mini Remote spots
// (contributions with "server": <id> show only while that server is active);
// * shows the server card (ServerPackUi): RynthCore's verdict, this character's override, what is
// known about the server, and how to set an account up for it in the launcher;
// * stays quiet anywhere else. RynthCore usually doesn't even load it there: the embedded manifest
// names the server's hosts, and the engine loads only the plugin for the host the client
// connects to (PluginManifestGate.SelectServerPlugins).
//
// Server-specific features: add files to the server's project implementing the partial hooks below
// (ServerLoginComplete, ServerTick, ServerChatCommand, ...). Unimplemented hooks compile away.
//
// What the shared code gives a server's own features (added 2026-10-20, when RynthOracle's and
// RynthInventory's Conquest and Aelrynth features moved into RynthConquest and RynthAelrynth, so a
// shared plugin carries nothing for one server):
// ServerPages(list) pages of its own (ServerPackPages.cs): sub-tabs of the Mini Remote's
// Server section, only while its server is active, and tabs of the
// /rserver window. Draw runs on the render thread.
// ServerChatText(...) every incoming chat line (pump thread), to read the server's replies
// and hide the ones answering the plugin's own requests (eat).
// ServerChatBar(text) every line sent through the chat bar (AC's thread: note it only),
// to tell the player's typed command from the plugin's own.
// Settings the plugin's own settings file (ServerPackSettings.cs), loaded before
// ServerInitialize; MigrateOnce imports a setting from its old home.
// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other
// plugins that apply a server rule without knowing the server.
// ServerCommandVerbs(list) its own "/rserver <verb>" words, handled in ServerChatCommand.
// RunOnTick(action) work for the next tick (a page's button, on the render thread).
// Send(command) a chat command as if typed (pump thread, logged in only);
// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window.
// Resources\quests.<id>.csv (no code) the server's own quest list: embedded by ServerPlugin.props and
// offered to RynthOracle through "RynthServer.QuestPack" (ServerPackQuestPack.cs,
// added 2026-10-21 when the packs left RynthOracle).
// The tick, chat and command hooks only run while a character is logged in; each
// should check Active itself, since the plugin can be loaded for a world that isn't its server.
//
// Threads: OnTick, login/logout, chat lines and the engine's export calls run on the plugin pump.
// OnChatBarEnter runs on AC's main thread, so it only queues. The card and the pages draw on the
// render thread (OnRender, RynthPluginRenderEmbed) and queue their commands for the tick.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.ServerPack;
public sealed partial class ServerPackPlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi(RynthPluginInfo.Name);
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi(
RynthPluginInfo.Version.Length > 0 ? RynthPluginInfo.Version : "0.1.0");
/// <summary>The chat command every server plugin answers ("/rserver [show|hide|toggle|info]").</summary>
internal const string ChatCommand = "/rserver";
/// <summary>The card's surface in RynthCore's Mini Remote sections ("section:server-coldeve").</summary>
internal static readonly string SettingsSurface = ServerPackModel.SurfaceFor(RynthPluginInfo.ServerId);
private readonly ServerPackModel _model;
private readonly ServerPackUi _ui;
private readonly string _sectionsJson;
// The server's own pages (ServerPages), validated; what was left out is logged at Initialize.
private readonly List<ServerPage> _pages;
private readonly List<string> _pageNotes = new();
private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name));
private readonly ServerProfileValues _profileValues = new();
// RynthCore commands from the card (render thread), run on the next tick.
private readonly ConcurrentQueue<string> _engineCommands = new();
// "/rserver ..." lines from OnChatBarEnter, run on the next tick.
private readonly ConcurrentQueue<string[]> _commands = new();
// The server code's work for the tick (RunOnTick: its pages' buttons).
private readonly ConcurrentQueue<Action> _tickActions = new();
// The server's own "/rserver" verbs (ServerCommandVerbs).
private readonly HashSet<string> _serverVerbs = new(StringComparer.OrdinalIgnoreCase);
private volatile bool _loginComplete;
private volatile string? _world;
private bool _wasActive;
public ServerPackPlugin()
{
ServerPackInfo info = ServerData.Create();
_model = new ServerPackModel(info);
var pages = new List<ServerPage>();
ServerPages(pages);
_pages = ServerPackPages.Validate(pages, _pageNotes.Add);
var verbs = new List<string>();
ServerCommandVerbs(verbs);
foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim());
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages);
_sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name, _pages);
}
internal ServerPackInfo Info => _model.Info;
private static ServerPackInfo? _staticInfo;
/// <summary>The server's facts before the plugin object exists ("RynthServer.Profile" asked early).</summary>
internal static ServerPackInfo StaticInfo => _staticInfo ??= ServerData.Create();
/// <summary>RynthCore (or the world name) says this is the plugin's server now.</summary>
internal bool Active => _loginComplete && _model.IsActive(_world);
/// <summary>The world name the client reports ("" before login). Any thread.</summary>
internal string World => _world ?? string.Empty;
// ── Hooks for a server's own features (implement in the server's project) ──
partial void ServerInitialize();
partial void ServerLoginComplete();
partial void ServerLogout();
partial void ServerShutdown();
/// <summary>Every plugin tick while logged in; <paramref name="active"/> = this is the plugin's server.</summary>
partial void ServerTick(bool active);
/// <summary>"/rserver &lt;verb&gt; ..." verbs the shared code doesn't know; set handled to stop the help text.</summary>
partial void ServerChatCommand(string[] parts, ref bool handled);
/// <summary>
/// The server's own "/rserver" verbs (lower case), so "/rserver vault" reaches ServerChatCommand
/// instead of being read as another server's id. Called once, from the constructor.
/// </summary>
partial void ServerCommandVerbs(List<string> verbs);
/// <summary>Extra lines for "/rserver info".</summary>
partial void ServerInfoLines(Action<string> line);
/// <summary>The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet).</summary>
partial void ServerPages(List<ServerPage> pages);
/// <summary>
/// An incoming chat line (pump thread, logged in only): set <paramref name="eat"/> to keep it out of
/// the chat window (it comes in true when an earlier plugin already ate it).
/// </summary>
partial void ServerChatText(string text, int chatType, ref bool eat);
/// <summary>
/// A line sent through the chat bar, typed or another plugin's command (trimmed), before
/// "/rserver" is looked at. AC's main thread: only note it (interlocked state or a queue).
/// </summary>
partial void ServerChatBar(string text);
// ── What the server's own code uses ──────────────────────────────────
/// <summary>The plugin's settings file (loaded before ServerInitialize). Pump thread.</summary>
internal ServerPackSettings Settings => _settings;
/// <summary>The live numbers of the profile ("values"). Any thread.</summary>
internal ServerProfileValues ProfileValues => _profileValues;
/// <summary>The pages this plugin draws.</summary>
internal IReadOnlyList<ServerPage> Pages => _pages;
/// <summary>Publishes a live number in the "RynthServer.Profile" JSON ("values"). Any thread.</summary>
internal void SetProfileValue(string key, double value) => _profileValues.Set(key, value);
/// <summary>Runs <paramref name="action"/> on the next tick while logged in (dropped at logout). Any thread.</summary>
internal void RunOnTick(Action action)
{
if (action != null) _tickActions.Enqueue(action);
}
/// <summary>Sends a chat command as if typed; false when nothing went out. Pump thread.</summary>
internal bool Send(string command)
=> _loginComplete && !string.IsNullOrWhiteSpace(command) && Host.HasInvokeChatParser && Host.InvokeChatParser(command);
/// <summary>The plugin's log, tagged with its name.</summary>
internal void LogTagged(string message) => Host.Log($"[{RynthPluginInfo.Name}] {message}");
public override int Initialize()
{
Host.Log($"[{RynthPluginInfo.Name}] Plugin initialized for {Info.Name} ({Info.Id}).");
// The server card draws through the engine's cimgui (and so in its current context, a popped-out
// Mini Remote's included), never a second copy of ImGui (ImGuiNativeBinding.cs). Found and fixed
// by SilentKelpie (rynth PR #12); re-implemented here.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log($"[{RynthPluginInfo.Name}] {msg}"));
foreach (string note in _pageNotes) LogTagged(note);
_settings.Load();
if (_settings.LastError.Length > 0) LogTagged($"Settings ({_settings.FilePath}) not read: {_settings.LastError}; using defaults.");
ServerInitialize();
return 0;
}
// Also called on a freshly (re)loaded plugin while already in game.
public override void OnLoginComplete()
{
_loginComplete = true;
_wasActive = false;
RefreshWorld();
ServerLoginComplete();
}
public override void OnLogout()
{
_loginComplete = false;
_world = null;
while (_commands.TryDequeue(out _)) { }
while (_engineCommands.TryDequeue(out _)) { }
while (_tickActions.TryDequeue(out _)) { }
_model.Clear();
_profileValues.Clear();
ServerLogout();
}
public override void Shutdown() => ServerShutdown();
public override void OnTick()
{
if (!_loginComplete) return;
if (_world == null) RefreshWorld();
while (_commands.TryDequeue(out string[]? parts)) RunCommand(parts);
while (_engineCommands.TryDequeue(out string? command))
{
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
ChatLine($"[{RynthPluginInfo.Name}] RynthCore didn't take: " + command);
}
while (_tickActions.TryDequeue(out Action? action))
{
try { action(); }
catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); }
}
bool active = Active;
if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden)
ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here.");
_wasActive = active;
ServerTick(active);
}
/// <summary>The world name the client reports (the server's own once logged in).</summary>
private void RefreshWorld()
{
if (Host.HasGetWorldName && Host.TryGetWorldName(out string w) && !string.IsNullOrWhiteSpace(w))
_world = w.Trim();
}
// ── RynthCore's verdict ──────────────────────────────────────────────
/// <summary>RynthPluginApplyRemoteCommand: "servermenu" from RynthCore. Any thread: parsed and published only.</summary>
internal void ApplyRemoteCommand(string action, string value)
{
if (action.Equals("servermenu", StringComparison.OrdinalIgnoreCase))
_model.ApplyEngine(value, Environment.TickCount64);
}
/// <summary>
/// RynthPluginGetSectionsJson: the server and the card's Mini Remote spot. Always declared
/// (the manifest is static): the engine only collects it once in game, and keeping it across
/// logout and character switches stops the server dropping out of Options > Diagnostics.
/// </summary>
internal string? BuildSectionsJson() => _sectionsJson;
// ── Drawing ──────────────────────────────────────────────────────────
/// <summary>The standalone card window. Render thread.</summary>
public override void OnRender()
{
if (!_loginComplete || !_ui.WindowOpen || Host.ImGuiContext == IntPtr.Zero) return;
IntPtr previous = ImGui.GetCurrentContext();
ImGui.SetCurrentContext(Host.ImGuiContext);
try { _ui.RenderWindow(); }
catch (Exception ex) { Host.Log($"[{RynthPluginInfo.Name}] Server window failed: {ex.Message}"); _ui.WindowOpen = false; }
finally { ImGui.SetCurrentContext(previous); }
}
/// <summary>
/// RynthPluginRenderEmbed "section:server-&lt;id&gt;": the card in RynthCore's Mini Remote, drawn
/// into the engine's current window and context (popped-out windows have their own).
/// <paramref name="wantHeight"/> is the height it used. False until login. Render thread.
/// </summary>
internal bool RenderEmbeddedCard(out float wantHeight) => RenderEmbedded(_ui.RenderBody, "Server card", out wantHeight);
/// <summary>
/// RynthPluginRenderEmbed "section:server-&lt;id&gt;.&lt;page&gt;": one of the server's pages
/// (ServerPages) in RynthCore's Mini Remote. False for a page this plugin doesn't have, or before login.
/// </summary>
internal bool RenderEmbeddedPage(string pageId, out float wantHeight)
{
wantHeight = 0;
ServerPage? page = _pages.Find(p => p.Id == pageId);
return page != null && RenderEmbedded(page.Draw, "Page " + page.Label, out wantHeight);
}
private bool RenderEmbedded(Action draw, string what, out float wantHeight)
{
wantHeight = 0;
if (!_loginComplete) return false;
IntPtr previous = ImGui.GetCurrentContext();
IntPtr context = previous != IntPtr.Zero ? previous : Host.ImGuiContext;
if (context == IntPtr.Zero) return false;
ImGui.SetCurrentContext(context);
try
{
float startY = ImGui.GetCursorPosY();
draw();
wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f);
return true;
}
catch (Exception ex)
{
Host.Log($"[{RynthPluginInfo.Name}] {what} failed: {ex.Message}");
return false;
}
finally { ImGui.SetCurrentContext(previous); }
}
// ── Chat ─────────────────────────────────────────────────────────────
/// <summary>Incoming chat (pump thread): the server's own code reads it (ServerChatText).</summary>
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
bool eaten = eat != 0;
ServerChatText(text, chatType, ref eaten);
if (eaten) eat = 1;
}
// ── Commands ─────────────────────────────────────────────────────────
public override void OnChatBarEnter(string? text, ref int eat)
{
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
string trimmed = text.Trim();
ServerChatBar(trimmed);
if (!trimmed.Equals(ChatCommand, StringComparison.OrdinalIgnoreCase)
&& !trimmed.StartsWith(ChatCommand + " ", StringComparison.OrdinalIgnoreCase))
return;
string[] parts = trimmed.Split(' ', StringSplitOptions.RemoveEmptyEntries);
// "/rserver <id> ...": only that server's plugin answers (several load when the host is unknown).
if (parts.Length >= 2 && ServerPackModel.IsSafeId(parts[1].ToLowerInvariant()) && !IsVerb(parts[1]))
{
if (!parts[1].Equals(Info.Id, StringComparison.OrdinalIgnoreCase)) return;
parts = Shift(parts);
}
eat = 1;
_commands.Enqueue(parts);
}
private bool IsVerb(string word) =>
word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto"
|| _serverVerbs.Contains(word);
/// <summary>Drops the server id: "/rserver coldeve info" -> "/rserver info".</summary>
private static string[] Shift(string[] parts)
{
var rest = new string[parts.Length - 1];
rest[0] = parts[0];
Array.Copy(parts, 2, rest, 1, parts.Length - 2);
return rest;
}
private void RunCommand(string[] parts)
{
string verb = parts.Length >= 2 ? parts[1].ToLowerInvariant() : "toggle";
switch (verb)
{
case "show":
_ui.WindowOpen = true;
return;
case "hide":
_ui.WindowOpen = false;
return;
case "toggle":
_ui.WindowOpen = !_ui.WindowOpen;
return;
case "auto":
case "on":
case "off":
_engineCommands.Enqueue(ServerPackModel.ForceCommand(Info.Id, verb));
return;
case "info":
PrintInfo();
return;
}
bool handled = false;
ServerChatCommand(parts, ref handled);
if (handled) return;
ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} [show|hide|toggle] - the {Info.Name} server card (also in the Mini Remote's Char section).");
ChatLine($"[{RynthPluginInfo.Name}] {ChatCommand} info - what is known about {Info.Name}; {ChatCommand} auto|on|off - this character's override.");
}
private void PrintInfo()
{
string tag = $"[{RynthPluginInfo.Name}] ";
ServerVerdictView? v = _model.Engine;
string verdict = v != null
? (v.Active ? "on for this world" : "not this world") + (v.Reason.Length > 0 ? " (" + v.Reason + ")" : "")
: (_model.IsActive(_world) ? "this world, by its name" : "not this world, by its name") + " (no RynthCore verdict yet)";
ChatLine(tag + Info.Name + ": " + verdict);
if (Info.Address.Length > 0) ChatLine(tag + "Address " + Info.Address + " (" + Info.Emulator + ", " + Info.Ruleset + ")");
if (Info.AccountLimit.Length > 0) ChatLine(tag + "Account limit: " + Info.AccountLimit);
ChatLine(tag + "Botting: " + Info.BottingText);
ServerInfoLines(line => ChatLine(tag + line));
}
internal void ChatLine(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat(text, 1);
}
}

View file

@ -0,0 +1,252 @@
// ServerPackProfile.cs - A server plugin's settings as JSON, for other plugins ("RynthServer.Profile",
// Plugins/Shared/RynthServerProfileApi.cs, served by ServerPackExports' RynthPluginQueryInterface).
//
// RynthCore's GetServerStateJson (plugin API v86) names the active server and the plugin that owns
// it; a reader (RynthOracle, RynthAi's "/ra server", ...) asks that plugin for this profile to get
// the server's rules without knowing the server: connection, rule set, botting policy, account
// limits, commands, tinkering salvage and links. Everything ServerPackInfo holds, nothing guessed.
//
// The JSON is plain ASCII (anything else is \u-escaped), so a reader can show it in the AC client.
// Pure (no host calls): RynthServerPack.Tests covers it.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.ServerPack;
/// <summary>
/// Live numbers a server plugin publishes in its profile ("values"), for other plugins that apply a
/// server rule without knowing the server: e.g. RynthConquest's "voidDotDurationScale" (how much
/// longer this character's Void damage-over-time lasts there), which RynthOracle's Void timers use.
/// Set from the server's own code (ServerPackPlugin.SetProfileValue), read by the profile interface
/// on any thread; <see cref="Revision"/> goes up on every change, so the JSON is rebuilt only then.
/// </summary>
internal sealed class ServerProfileValues
{
private readonly object _gate = new();
private readonly List<KeyValuePair<string, double>> _values = new();
private volatile int _revision;
/// <summary>Goes up whenever a value changes.</summary>
public int Revision => _revision;
/// <summary>1-48 of letters, digits, '.', '_' and '-'.</summary>
public static bool IsValidKey(string? key)
{
if (string.IsNullOrEmpty(key) || key.Length > 48) return false;
foreach (char c in key)
if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false;
return true;
}
/// <summary>Sets (or adds) a value; false for a bad key or a number that isn't finite. Any thread.</summary>
public bool Set(string key, double value)
{
if (!IsValidKey(key) || !double.IsFinite(value)) return false;
lock (_gate)
{
int i = _values.FindIndex(v => v.Key == key);
if (i >= 0)
{
if (_values[i].Value.Equals(value)) return true;
_values[i] = new KeyValuePair<string, double>(key, value);
}
else _values.Add(new KeyValuePair<string, double>(key, value));
_revision++;
}
return true;
}
/// <summary>Drops one value (true when it was there). Any thread.</summary>
public bool Remove(string key)
{
lock (_gate)
{
int i = _values.FindIndex(v => v.Key == key);
if (i < 0) return false;
_values.RemoveAt(i);
_revision++;
return true;
}
}
/// <summary>Drops every value (logout: the next character publishes its own). Any thread.</summary>
public void Clear()
{
lock (_gate)
{
if (_values.Count == 0) return;
_values.Clear();
_revision++;
}
}
/// <summary>A copy of the values and the revision it belongs to. Any thread.</summary>
public KeyValuePair<string, double>[] Snapshot(out int revision)
{
lock (_gate)
{
revision = _revision;
return _values.ToArray();
}
}
}
internal static class ServerPackProfile
{
/// <summary>The profile JSON's schema (RynthServerProfile.Schema).</summary>
public const int Schema = 1;
/// <summary>The "botting" value for a policy.</summary>
public static string BottingName(BottingPolicy policy) => policy switch
{
BottingPolicy.Allowed => "allowed",
BottingPolicy.Restricted => "restricted",
BottingPolicy.Forbidden => "forbidden",
_ => "unknown",
};
/// <summary>
/// The profile for <paramref name="info"/>: <paramref name="active"/> is this plugin's verdict
/// (RynthCore's when it pushed one), <paramref name="world"/> the world name the client reports,
/// <paramref name="values"/> the live numbers the server's own code published (ServerProfileValues).
/// </summary>
public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world,
IReadOnlyList<KeyValuePair<string, double>>? values = null)
{
var sb = new StringBuilder(1024);
sb.Append("{\"schema\":").Append(Schema);
Field(sb, "id", info.Id);
Field(sb, "name", info.Name);
Field(sb, "plugin", pluginName);
Field(sb, "version", pluginVersion);
sb.Append(",\"active\":").Append(active ? "true" : "false");
Field(sb, "world", world ?? string.Empty);
List(sb, "hosts", info.Hosts);
List(sb, "worldNames", info.WorldNames);
sb.Append(",\"port\":").Append(info.Port);
Field(sb, "emulator", info.Emulator);
Field(sb, "ruleset", info.Ruleset);
Field(sb, "status", info.Status);
Field(sb, "botting", BottingName(info.Botting));
Field(sb, "bottingNote", info.BottingNote);
Field(sb, "accountLimit", info.AccountLimit);
Field(sb, "summary", info.Summary);
List(sb, "facts", info.Facts);
sb.Append(",\"commands\":[");
for (int i = 0; i < info.Commands.Length; i++)
{
if (i > 0) sb.Append(',');
sb.Append("{\"command\":");
Str(sb, info.Commands[i].Command);
sb.Append(",\"what\":");
Str(sb, info.Commands[i].What);
sb.Append('}');
}
sb.Append(']');
// Added within schema 1: readers that don't know "salvage" skip it. The optional row fields
// (applied, prepared, order, afterCap, stackGroup + stackCap) are written only when set.
sb.Append(",\"salvage\":[");
for (int i = 0; i < info.Salvage.Length; i++)
{
ServerSalvage s = info.Salvage[i];
if (i > 0) sb.Append(',');
sb.Append("{\"bench\":");
Str(sb, s.Bench);
sb.Append(",\"material\":").Append(s.Material);
sb.Append(",\"kind\":");
Str(sb, s.Kind);
sb.Append(",\"effect\":");
Str(sb, s.Effect);
sb.Append(",\"slot\":").Append(s.UsesTinkSlot ? "true" : "false");
sb.Append(",\"nameMatch\":");
Str(sb, s.NameMatch);
if (s.AppliedInt != 0) sb.Append(",\"applied\":").Append(s.AppliedInt);
if (s.Prepared) sb.Append(",\"prepared\":true");
if (s.Order != 0) sb.Append(",\"order\":").Append(s.Order);
if (s.AfterCap) sb.Append(",\"afterCap\":true");
if (!string.IsNullOrEmpty(s.StackGroup))
{
sb.Append(",\"stackGroup\":");
Str(sb, s.StackGroup);
sb.Append(",\"stackCap\":").Append(s.StackCap);
}
sb.Append('}');
}
sb.Append(']');
// Added within schema 1 (2026-10-20), only when the server has trinkets.
if (info.TrinketNames.Length > 0)
{
sb.Append(",\"trinkets\":{");
sb.Append("\"names\":[");
for (int i = 0; i < info.TrinketNames.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketNames[i]); }
sb.Append("],\"except\":[");
for (int i = 0; i < info.TrinketExcept.Length; i++) { if (i > 0) sb.Append(','); Str(sb, info.TrinketExcept[i]); }
sb.Append("]}");
}
Field(sb, "discord", info.Discord);
Field(sb, "website", info.Website);
Field(sb, "wiki", info.Wiki);
Field(sb, "source", info.Source);
// Added within schema 1: live numbers for this character on this server ({} when none).
sb.Append(",\"values\":{");
if (values != null)
{
bool first = true;
foreach (KeyValuePair<string, double> v in values)
{
if (!ServerProfileValues.IsValidKey(v.Key) || !double.IsFinite(v.Value)) continue;
if (!first) sb.Append(',');
first = false;
Str(sb, v.Key);
sb.Append(':').Append(v.Value.ToString("R", CultureInfo.InvariantCulture));
}
}
sb.Append('}');
sb.Append('}');
return sb.ToString();
}
private static void Field(StringBuilder sb, string name, string? value)
{
sb.Append(",\"").Append(name).Append("\":");
Str(sb, value);
}
private static void List(StringBuilder sb, string name, string[]? values)
{
sb.Append(",\"").Append(name).Append("\":[");
if (values != null)
{
for (int i = 0; i < values.Length; i++)
{
if (i > 0) sb.Append(',');
Str(sb, values[i]);
}
}
sb.Append(']');
}
/// <summary>A JSON string literal in plain ASCII (control and non-ASCII characters \u-escaped).</summary>
private static void Str(StringBuilder sb, string? s)
{
sb.Append('"');
foreach (char c in s ?? string.Empty)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
break;
}
}
sb.Append('"');
}
}

View file

@ -0,0 +1,121 @@
// ServerPackQuestPack.cs - A server plugin's own quest list, offered to quest readers such as RynthOracle
// through "RynthServer.QuestPack" (Plugins/Shared/RynthServerQuestPackApi.cs; the table is in
// ServerPackInterface.cs, answered by ServerPackExports' RynthPluginQueryInterface).
//
// A server plugin has a pack when its project has Resources\quests.<server id>.csv: ServerPlugin.props
// embeds it as "ServerPack.quests.csv", and this file serves it. The pack is the server's data, kept
// with the server's plugin (the Conquest, Levistras and Aelrynth packs lived in RynthOracle until
// 2026-10-21); RynthOracle merges whichever pack the active server's plugin offers and names no server.
// Its "tag" is the server's display name, which is also what the master quest list's Server column
// calls it ("Conquest", "Levistras").
// Pure apart from the embedded resource read: RynthServerPack.Tests covers it.
using System;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.ServerPack;
internal static class ServerPackQuestPack
{
/// <summary>The embedded pack's resource name (ServerPlugin.props).</summary>
public const string ResourceName = "ServerPack.quests.csv";
/// <summary>The info JSON's schema (RynthServerQuestPack.Schema).</summary>
public const int Schema = 1;
/// <summary>The pack never changes while the plugin runs (it is embedded): one revision.</summary>
public const int Revision = 1;
private static string? _csv;
private static bool _loaded;
/// <summary>The embedded pack's CSV, or "" when this plugin has none. Read once. Any thread.</summary>
public static string Csv
{
get
{
if (_loaded) return _csv ?? string.Empty;
string text = string.Empty;
try
{
using Stream? s = typeof(ServerPackQuestPack).Assembly.GetManifestResourceStream(ResourceName);
if (s != null)
{
using var r = new StreamReader(s, Encoding.UTF8);
text = r.ReadToEnd();
}
}
catch
{
text = string.Empty; // an unreadable pack is no pack: never take the plugin down
}
_csv = Usable(text) ? text : string.Empty;
_loaded = true;
return _csv;
}
}
/// <summary>True when the text looks like a quest list: a header with a QuestFlag column and a row.</summary>
public static bool Usable(string? csv)
{
if (string.IsNullOrEmpty(csv)) return false;
int end = csv.IndexOf('\n');
string header = (end < 0 ? csv : csv[..end]).TrimStart('').Trim();
bool hasFlag = false;
foreach (string col in header.Split(','))
{
string c = col.Trim().Trim('"').Replace(" ", string.Empty);
if (c.Equals("QuestFlag", StringComparison.OrdinalIgnoreCase) || c.Equals("Flag", StringComparison.OrdinalIgnoreCase)) hasFlag = true;
}
return hasFlag && CountRows(csv) > 0;
}
/// <summary>Non-blank lines after the header (a quoted field never spans lines in these lists).</summary>
public static int CountRows(string? csv)
{
if (string.IsNullOrEmpty(csv)) return 0;
int rows = 0;
bool header = true;
foreach (string line in csv.Split('\n'))
{
if (header) { header = false; continue; }
if (line.Trim().Length > 0) rows++;
}
return rows;
}
/// <summary>The info JSON for a pack (plain ASCII), or "" when <paramref name="csv"/> is no pack.</summary>
public static string BuildInfoJson(ServerPackInfo info, string pluginName, string pluginVersion, string? csv)
{
if (!Usable(csv)) return string.Empty;
var sb = new StringBuilder(256);
sb.Append("{\"schema\":").Append(Schema);
Field(sb, "server", info.Id);
Field(sb, "tag", info.Name);
Field(sb, "plugin", pluginName);
Field(sb, "version", pluginVersion);
sb.Append(",\"rows\":").Append(CountRows(csv));
sb.Append(",\"bytes\":").Append(Encoding.UTF8.GetByteCount(csv!));
sb.Append(",\"revision\":").Append(Revision);
sb.Append('}');
return sb.ToString();
}
private static void Field(StringBuilder sb, string name, string? value)
{
sb.Append(",\"").Append(name).Append("\":\"");
foreach (char c in value ?? string.Empty)
{
switch (c)
{
case '"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
default:
if (c < 0x20 || c > 0x7e) sb.Append("\\u").Append(((int)c).ToString("x4"));
else sb.Append(c);
break;
}
}
sb.Append('"');
}
}

View file

@ -0,0 +1,88 @@
// ServerPackRefresh.cs - The Refresh button a server page starts with, and the status line beside it
// (as RynthOracle's pages have it): the page's own command is asked for again, refused for a few
// seconds after it went out (so the button can't spam the server), and the line waits for the reply
// ("Waiting...", then "Updated hh:mm:ss", or "No reply yet" after a while).
// Render thread: Draw runs inside the page's own lock; the page's refresh callback only decides and
// queues what to send (ServerPackPlugin.RunOnTick).
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.ServerPack;
/// <summary>What a Refresh did, and (when it asked the server) how to tell the reply has landed.</summary>
internal sealed record ServerRefreshResult(string What, Func<bool>? Done = null);
internal sealed class ServerRefreshRow
{
public const long CooldownMs = 3000;
public const long ReplyWaitMs = 15_000;
public const string TooSoon = "That was just asked for; wait a few seconds before asking again.";
private static readonly Vector4 Yellow = new(0.95f, 0.85f, 0.35f, 1f);
private static readonly Vector4 Red = new(0.95f, 0.45f, 0.40f, 1f);
private readonly Dictionary<string, long> _sent = new();
private string _scope = string.Empty, _what = string.Empty;
private Func<bool>? _done;
private bool _doneSeen;
private long _atMs;
private DateTime _atLocal, _doneLocal;
/// <summary>The same request (by <paramref name="key"/>) twice within <see cref="CooldownMs"/> is refused.</summary>
public bool CoolingDown(string key, long nowMs)
{
if (_sent.TryGetValue(key, out long t) && nowMs - t < CooldownMs) return true;
_sent[key] = nowMs;
return false;
}
/// <summary>Forgets the status line and the cooldowns (logout).</summary>
public void Reset()
{
_sent.Clear();
_scope = _what = string.Empty;
_done = null;
}
/// <summary>
/// The row: Refresh (tooltip <paramref name="help"/>) and, for the page that last refreshed
/// (<paramref name="scope"/>), what happened.
/// </summary>
public void Draw(string scope, string help, Func<ServerRefreshResult> refresh)
{
long now = Environment.TickCount64;
if (ImGui.SmallButton("Refresh##refresh_" + scope))
{
ServerRefreshResult r;
try { r = refresh(); }
catch (Exception ex) { r = new ServerRefreshResult("Couldn't refresh: " + ex.Message); }
_scope = scope;
_what = r.What;
_done = r.Done;
_doneSeen = false;
_atMs = now;
_atLocal = DateTime.Now;
}
if (help.Length > 0 && ImGui.IsItemHovered()) SafeImGui.SetTooltip(help);
if (_scope != scope || _what.Length == 0) return;
ImGui.SameLine();
if (_done != null && !_doneSeen && _done())
{
_doneSeen = true;
_doneLocal = DateTime.Now;
}
if (_done != null && !_doneSeen)
{
if (now - _atMs > ReplyWaitMs) SafeImGui.TextColored(Red, "No reply yet. Press Refresh to ask again.");
else SafeImGui.TextColored(Yellow, _what + " Waiting for the reply...");
}
else if (_done != null)
SafeImGui.TextDisabled($"Updated {_doneLocal:HH:mm:ss}. {_what}");
else
SafeImGui.TextDisabled($"Refreshed {_atLocal:HH:mm:ss}. {_what}");
}
}

View file

@ -0,0 +1,158 @@
// ServerPackSettings.cs - A server plugin's own settings file, %APPDATA%\RynthCore\<plugin>.json
// (rynthconquest.json, ...), for the server's features (ServerPackPlugin.Settings).
//
// Flat named values (true/false, text), written by hand and read with JsonDocument: plugin types
// never go through System.Text.Json's serializer, which roots them across hot reloads. Values the
// plugin doesn't ask for are kept as they were written, so an older or newer copy of the plugin
// never drops another's. MigrateOnce imports settings that used to live elsewhere (another
// plugin's file) exactly once, and remembers that it did.
// Pure (file I/O only): RynthServerPack.Tests covers it. Pump thread only.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.ServerPack;
internal sealed class ServerPackSettings
{
// name -> the value's JSON text, in file order.
private readonly List<KeyValuePair<string, string>> _values = new();
public ServerPackSettings(string path) => FilePath = path;
/// <summary>%APPDATA%\RynthCore\&lt;plugin name, lower case&gt;.json.</summary>
public static string DefaultPath(string pluginName) => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", pluginName.ToLowerInvariant() + ".json");
public string FilePath { get; }
/// <summary>Why the last Load or Save failed ("" when it didn't).</summary>
public string LastError { get; private set; } = string.Empty;
/// <summary>Reads the file; a missing or broken one means defaults (the next save rewrites it).</summary>
public void Load()
{
_values.Clear();
LastError = string.Empty;
try
{
if (!File.Exists(FilePath)) return;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(FilePath));
if (doc.RootElement.ValueKind != JsonValueKind.Object) { LastError = "not a JSON object"; return; }
foreach (JsonProperty p in doc.RootElement.EnumerateObject())
Put(p.Name, p.Value.GetRawText());
}
catch (Exception ex)
{
_values.Clear();
LastError = ex.Message;
}
}
/// <summary>Writes the file (through a temporary file, so a crash never leaves half of one). False on failure.</summary>
public bool Save()
{
try
{
var sb = new StringBuilder("{\n");
for (int i = 0; i < _values.Count; i++)
{
sb.Append(" ").Append(Quote(_values[i].Key)).Append(": ").Append(_values[i].Value);
sb.Append(i + 1 < _values.Count ? ",\n" : "\n");
}
sb.Append("}\n");
Directory.CreateDirectory(Path.GetDirectoryName(FilePath)!);
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, sb.ToString());
File.Move(tmp, FilePath, overwrite: true);
LastError = string.Empty;
return true;
}
catch (Exception ex)
{
LastError = ex.Message;
return false;
}
}
public bool Has(string name) => Find(name) >= 0;
public bool GetBool(string name, bool fallback)
{
int i = Find(name);
return i < 0 ? fallback : _values[i].Value switch { "true" => true, "false" => false, _ => fallback };
}
/// <summary>Sets a value; true when it changed (the caller saves).</summary>
public bool SetBool(string name, bool value) => Put(name, value ? "true" : "false");
public string GetString(string name, string fallback)
{
int i = Find(name);
if (i < 0) return fallback;
try
{
using JsonDocument doc = JsonDocument.Parse(_values[i].Value);
return doc.RootElement.ValueKind == JsonValueKind.String ? doc.RootElement.GetString() ?? fallback : fallback;
}
catch (JsonException) { return fallback; }
}
public bool SetString(string name, string value) => Put(name, Quote(value ?? string.Empty));
/// <summary>
/// Runs <paramref name="migrate"/> once per settings file: unless <paramref name="marker"/> is
/// already set, it runs, the marker is set and the file saved. True when it ran now.
/// </summary>
public bool MigrateOnce(string marker, Action<ServerPackSettings> migrate)
{
if (GetBool(marker, false)) return false;
migrate(this);
SetBool(marker, true);
Save();
return true;
}
/// <summary>
/// A true/false value from another JSON settings file (an old home of a moved setting), or null
/// when the file, the value or its type isn't there. Never throws.
/// </summary>
public static bool? ReadBoolFrom(string path, string name)
{
try
{
if (!File.Exists(path)) return null;
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(path));
if (doc.RootElement.ValueKind != JsonValueKind.Object || !doc.RootElement.TryGetProperty(name, out JsonElement v)) return null;
return v.ValueKind switch { JsonValueKind.True => true, JsonValueKind.False => false, _ => null };
}
catch
{
return null;
}
}
private int Find(string name)
{
for (int i = 0; i < _values.Count; i++)
if (string.Equals(_values[i].Key, name, StringComparison.Ordinal)) return i;
return -1;
}
private bool Put(string name, string json)
{
int i = Find(name);
if (i >= 0)
{
if (_values[i].Value == json) return false;
_values[i] = new KeyValuePair<string, string>(name, json);
return true;
}
_values.Add(new KeyValuePair<string, string>(name, json));
return true;
}
private static string Quote(string s) => "\"" + JsonEncodedText.Encode(s).ToString() + "\"";
}

View file

@ -0,0 +1,240 @@
// ServerPackUi.cs - A server plugin's "server card".
//
// Drawn in two places: RynthCore's Mini Remote, the shared "Server" section, this server's area
// (the surface "section:server-<id>" through RynthPluginRenderEmbed), and its own window ("/rserver").
// Shows RynthCore's verdict and this character's Auto / On / Off override (read only: it is set in
// RynthCore Options > Diagnostics, 2026-10-13), what is known about the server (address, rule set,
// account limit, botting policy, its features), the commands it adds, its links, and how to set an
// account up for it in the launcher. Render thread only.
using System;
using System.Collections.Generic;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.ServerPack;
internal sealed class ServerPackUi
{
private static readonly Vector4 Teal = new(0.30f, 0.85f, 0.80f, 1f);
private static readonly Vector4 Mute = new(0.60f, 0.62f, 0.66f, 1f);
private static readonly Vector4 Warn = new(0.95f, 0.55f, 0.45f, 1f);
private static readonly Vector4 Good = new(0.55f, 0.85f, 0.45f, 1f);
private readonly ServerPackModel _model;
private readonly string _pluginLabel;
private readonly Func<string?> _world;
private readonly string _windowTitle;
private readonly IReadOnlyList<ServerPage> _pages;
private string _status = string.Empty;
/// <summary>The standalone window is open ("/rserver").</summary>
public bool WindowOpen;
/// <param name="pluginLabel">"RynthColdeve 0.1.0", for the title and the card.</param>
/// <param name="world">The world name the client reports now (null when unknown).</param>
/// <param name="pages">The server's own pages: tabs of the window after the card.</param>
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null)
{
_model = model;
_pluginLabel = pluginLabel;
_world = world;
_pages = pages ?? Array.Empty<ServerPage>();
_windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id;
}
/// <summary>The standalone window, while open: the card, and the server's pages as tabs when it has some.</summary>
public void RenderWindow()
{
if (!WindowOpen) return;
ImGui.SetNextWindowSize(new Vector2(_pages.Count > 0 ? 560 : 460, 520), ImGuiCond.FirstUseEver);
bool open = WindowOpen;
if (ImGui.Begin(_windowTitle, ref open))
{
if (_pages.Count == 0) RenderBody();
else if (ImGui.BeginTabBar("##server_tabs_" + _model.Info.Id))
{
if (ImGui.BeginTabItem("Server##card"))
{
RenderBody();
ImGui.EndTabItem();
}
foreach (ServerPage page in _pages)
{
if (!ImGui.BeginTabItem(page.Label + "##page_" + page.Id)) continue;
if (ImGui.BeginChild("##page_body_" + page.Id)) page.Draw();
ImGui.EndChild();
ImGui.EndTabItem();
}
ImGui.EndTabBar();
}
}
ImGui.End();
WindowOpen = open;
}
/// <summary>The card's content, into the current window.</summary>
public void RenderBody()
{
ServerPackInfo info = _model.Info;
RenderVerdict(info);
ImGui.Separator();
RenderFacts(info);
if (info.Commands.Length > 0)
{
ImGui.Separator();
RenderCommands(info);
}
ImGui.Separator();
RenderLinks(info);
ImGui.Separator();
RenderSetup(info);
if (info.Source.Length > 0)
{
ImGui.Spacing();
SafeImGui.TextDisabled("Server data: " + info.Source);
}
if (_status.Length > 0)
{
ImGui.Separator();
SafeImGui.TextWrapped(_status);
}
}
private void RenderVerdict(ServerPackInfo info)
{
ServerVerdictView? v = _model.Engine;
if (v == null)
{
bool byName = _model.IsActive(_world());
SafeImGui.TextColored(byName ? Teal : Mute, byName
? info.Name + ": this world (by its name)"
: info.Name + ": not this world (by its name)");
ImGui.PushStyleColor(ImGuiCol.Text, Mute);
ImGui.TextWrapped("Waiting for RynthCore's verdict and the override (RynthCore 2026.10.5.48 or later sends them).");
ImGui.PopStyleColor();
return;
}
SafeImGui.TextColored(v.Active ? Teal : Mute, v.Active ? info.Name + ": on for this world" : info.Name + ": not this world");
if (v.Reason.Length > 0)
{
ImGui.PushStyleColor(ImGuiCol.Text, Mute);
SafeImGui.TextWrapped(v.Reason);
ImGui.PopStyleColor();
}
// Read only: a server is forced in one place, RynthCore Options > Diagnostics (2026-10-13).
SafeImGui.TextDisabled("This character: " + ForceText(ServerPackModel.NormalizeForce(v.Force))
+ " (change it in RynthCore Options > Diagnostics)");
if (ImGui.IsItemHovered())
SafeImGui.SetTooltip("RynthCore's server selection (Options > Diagnostics) forces a server for this character,\n"
+ "or /rc server " + info.Id + " auto|on|off in chat.");
}
/// <summary>The override as words: Auto (detected), On (forced on) or Off (forced off).</summary>
private static string ForceText(string force) => force switch
{
"on" => "forced on",
"off" => "forced off",
_ => "auto (detected)",
};
private static void RenderFacts(ServerPackInfo info)
{
if (ImGui.BeginTable("##facts_" + info.Id, 2, ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp))
{
ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 110);
ImGui.TableSetupColumn("Value");
Row("Address", info.Address.Length > 0 ? info.Address : "(not published)");
Row("Emulator", info.Emulator);
Row("Rule set", info.Ruleset);
if (info.Status.Length > 0) Row("Status", info.Status);
Row("Account limit", info.AccountLimit.Length > 0 ? info.AccountLimit : "(not published)");
ImGui.TableNextRow();
ImGui.TableNextColumn();
ImGui.TextUnformatted("Botting");
ImGui.TableNextColumn();
Vector4 color = info.Botting switch
{
BottingPolicy.Forbidden => Warn,
BottingPolicy.Restricted => Warn,
BottingPolicy.Allowed => Good,
_ => Mute,
};
ImGui.PushStyleColor(ImGuiCol.Text, color);
SafeImGui.TextWrapped(info.BottingText);
ImGui.PopStyleColor();
ImGui.EndTable();
}
if (info.Botting == BottingPolicy.Forbidden)
SafeImGui.TextColored(Warn, "This server forbids bots: don't run RynthAi's combat, navigation or looting here.");
if (info.Summary.Length > 0)
{
ImGui.Spacing();
SafeImGui.TextWrapped(info.Summary);
}
foreach (string fact in info.Facts)
SafeImGui.BulletText(fact);
}
private static void Row(string label, string value)
{
ImGui.TableNextRow();
ImGui.TableNextColumn();
SafeImGui.Text(label);
ImGui.TableNextColumn();
SafeImGui.TextWrapped(value);
}
private void RenderCommands(ServerPackInfo info)
{
ImGui.TextUnformatted("Server commands");
for (int i = 0; i < info.Commands.Length; i++)
{
ServerCommand c = info.Commands[i];
ImGui.PushID(i);
if (ImGui.SmallButton("Copy")) Copy(c.Command);
ImGui.PopID();
ImGui.SameLine();
SafeImGui.Text(c.Command);
ImGui.SameLine();
SafeImGui.TextDisabled("- " + c.What);
}
}
private void RenderLinks(ServerPackInfo info)
{
ImGui.TextUnformatted("Links");
bool any = false;
any |= Link("Discord", info.Discord);
any |= Link("Website", info.Website);
any |= Link("Wiki", info.Wiki);
if (!any) ImGui.TextDisabled("(none published)");
}
private bool Link(string label, string url)
{
if (url.Length == 0) return false;
ImGui.PushID(label);
if (ImGui.SmallButton("Copy")) Copy(url);
ImGui.PopID();
ImGui.SameLine();
SafeImGui.Text(label + ": " + url);
return true;
}
private static void RenderSetup(ServerPackInfo info)
{
ImGui.TextUnformatted("Account setup (RynthCore launcher)");
foreach (string step in ServerPackModel.LauncherSteps(info))
SafeImGui.TextWrapped(step);
}
private void Copy(string text)
{
ImGui.SetClipboardText(text);
_status = "Copied: " + text;
}
}

View file

@ -0,0 +1,93 @@
<Project>
<!--
The common build of a server plugin (RynthColdeve, RynthAelrynth, ...): one NativeAOT plugin
per game server, built like RynthILT, so each server's plugin ships and updates on its own
(its own DLL, feed entry and C:\Games\RynthSuite\<Name>\ folder).
A server plugin's csproj sets, then imports this file:
AssemblyName RynthCore.Plugin.Rynth<Server> (plugin name = without the prefix)
Version its own version (Publish-Update.ps1 overrides it for a release)
RynthPluginServerId lower-case id (a-z 0-9 -); the Mini Remote's server id
RynthPluginServerName display name
RynthPluginServerHosts connect hosts, '|'-separated (a name matches hosts under it)
RynthPluginServerWorldNames world names the server announces, '|'-separated ('*' wildcards)
RynthPluginDescription one line for the launcher's plugin list
and keeps one source file, ServerData.cs (ServerData.Create: what is known about the server).
Detection data lives only in the csproj: the SDK writes it into the embedded manifest (the
engine loads the plugin only for its server) and into RynthPluginInfo (the plugin's own use).
Server-specific features go in the project as more files, through the partial hooks in
ServerPackPlugin.cs (ServerTick, ServerChatCommand, ServerChatText, ServerPages, ...), so the
shared code stays the same for all (the hooks and helpers are listed at the top of that file).
A server's quest pack is Resources\quests.<server id>.csv in its project: embedded below and
offered to RynthOracle through "RynthServer.QuestPack" (ServerPackQuestPack.cs).
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.ServerPack</RootNamespace>
<Platforms>x86</Platforms>
<!-- Nothing above the v66 baseline: chat commands, world names and the plugin-command broker
are behind HasInvokeChatParser / HasGetWorldName / HasWriteToChat. -->
<RynthPluginMinEngineApi Condition="'$(RynthPluginMinEngineApi)' == ''">66</RynthPluginMinEngineApi>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- ImGui.NET bound to the engine's cimgui: one ImGui, one current context, pop-outs included. -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInfo.cs" Link="ServerPack\ServerPackInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackModel.cs" Link="ServerPack\ServerPackModel.cs" />
<!-- The server's own pages, settings file, reply window and Refresh row (ServerPackPlugin.cs lists the hooks). -->
<Compile Include="$(MSBuildThisFileDirectory)ServerPackPages.cs" Link="ServerPack\ServerPackPages.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackSettings.cs" Link="ServerPack\ServerPackSettings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerChatRequest.cs" Link="ServerPack\ServerChatRequest.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackRefresh.cs" Link="ServerPack\ServerPackRefresh.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackUi.cs" Link="ServerPack\ServerPackUi.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackPlugin.cs" Link="ServerPack\ServerPackPlugin.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackExports.cs" Link="ServerPack\ServerPackExports.cs" />
<!-- "RynthServer.Profile": the server's settings for other plugins (RynthPluginQueryInterface). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackProfile.cs" Link="ServerPack\ServerPackProfile.cs" />
<!-- "RynthServer.QuestPack": the server's own quest list for RynthOracle (and any quest reader). -->
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerQuestPackApi.cs" Link="Shared\RynthServerQuestPackApi.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackQuestPack.cs" Link="ServerPack\ServerPackQuestPack.cs" />
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" />
</ItemGroup>
<ItemGroup>
<!-- The server's quest pack, when the project has one: Resources\quests.<server id>.csv (RynthOracle's
quest list columns), served through "RynthServer.QuestPack" (ServerPackQuestPack.cs). -->
<EmbeddedResource Include="$(MSBuildProjectDirectory)\Resources\quests.$(RynthPluginServerId).csv"
Condition="Exists('$(MSBuildProjectDirectory)\Resources\quests.$(RynthPluginServerId).csv')"
LogicalName="ServerPack.quests.csv" Link="Resources\quests.$(RynthPluginServerId).csv" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(MSBuildThisFileDirectory)..\..\..\..\RynthCore\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\..\..\..\RynthCore\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<!-- The engine already loaded cimgui.dll into the client; a second copy next to the plugin is never used. -->
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>