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,29 @@
// PetCaptureLines.cs - The chat lines that mean an ACECustom siphon-lens capture worked.
//
// RynthILT's (linked source): its siphon auto-capture (IltPetAutomation, RynthAi's Pets tab's until
// 2026-10-20) reads them to time the next lens (success -> short cooldown), and its Vaulted Dungeons
// keeper counts a capture as a kill for its "Kill Client" timer (a hunter who captures instead of
// killing is not idle). They are the MonsterCapture success replies; nothing new is guessed here.
using System;
namespace RynthCore.Plugin.Shared;
internal static class PetCaptureLines
{
/// <summary>Substrings of the success replies (matched case-insensitively).</summary>
private static readonly string[] Success =
{
"successfully siphoned the essence",
"The echo resonates perfectly",
"The essence is captured",
};
/// <summary>True when <paramref name="text"/> is a capture-success reply.</summary>
public static bool IsSuccess(string? text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (string part in Success)
if (text.IndexOf(part, StringComparison.OrdinalIgnoreCase) >= 0) return true;
return false;
}
}

View file

@ -0,0 +1,723 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltDataApi.cs
// The "RynthILT.Data" interface: the Infinite Leaftide data RynthILT's Mini Remote Charms
// and Banking tabs show, for other plugins to draw. RynthOracle (charms, Pet Breeding, the
// Temple guardians) and RynthInventory (Banking) read it until 2026-10-21, when those screens
// became RynthILT's own (a shared plugin never shows one server's data); no RynthSuite plugin
// reads it now, and it stays for any other reader:
// - the registry charms and Guardian Hands (GetCharmsJson, ToggleCharm);
// - the bank balances of every character RynthILT has seen on this server, and
// deposits, withdrawals, transfers and balance reads (GetBankJson, BankCommand);
// - version 2: the pet breeding tracker (GetPetBreedingJson, PetBreedingCommand).
// Separate from "RynthServer.Profile" (the server's settings) and "RynthILT.Hub" (RynthAi's
// exact-version table) so neither has to change for this.
// Compiled into RynthILT and its readers (linked source), so the layout can't drift.
//
// Rules (as the other shared interfaces):
// - Append-only: new functions go at the end, and Version goes up.
// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII.
// - Every function returns safely (no exception crosses the boundary).
// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown
// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that.
// - Reading a JSON says "someone is looking": RynthILT rebuilds that snapshot on its pump
// (every couple of seconds) only while it is being read, so an idle reader costs nothing.
//
// GetCharmsJson payload (IltCharms.BuildReaderJson; read leniently):
// { "available": true, "world": "InfiniteLeaftide", "total": 28, "acquiredCount": 5, "activeCount": 3,
// "charms": [ { "name": "Mana Barrier", "effect": "...", "acquired": "carried"|"seen"|"no",
// "count": 1, "tier": 3, "maxTier": 5, "active": "on"|"off"|"unknown",
// "server": "on"|"off"|"unknown", "lastSeen": "2026-10-13", "toggleId": 1234567 } ],
// "hands": [ { "id": 1234568, "name": "Guardian Hand", "active": "on"|"off"|"unknown",
// "server": "on"|"off"|"unknown" } ] }
// "hands" are the Guardian Hands carried now (not a registry charm); "id" is their Toggle id.
//
// GetBankJson payload (IltBankExport.Build; read leniently):
// { "available": true, "enabled": 1, "world": "InfiniteLeaftide", "character": "Name",
// "characters": [ { "name": "Name", "current": true, "pyreals": 0, "luminance": 0,
// "legendaryKeys": 0, "mythicalKeys": 0, "enlightenedCoins": 0,
// "weaklyEnlightenedCoins": 0, "prestigeCoins": 0, "updated": "2026-10-13T21:25:37Z" } ],
// "deposits": ["Everything", ...], "withdrawals": [ { "label": "Pyreals", "notes": false } ],
// "transfers": [ { "label": "Pyreals", "notes": false } ], "notes": [ { "label": "MMD", "value": 250000 } ],
// "result": "Deposited ...", "transactions": [ { "when": "...", "type": "Sent", "amount": 1,
// "currency": "Pyreals", "player": "Who" } ] }
// "enabled": 1 the server has /bank, 0 it doesn't, -1 not known yet.
//
// BankCommand verbs (ASCII, space separated; the reply lands in "result"):
// refresh quiet /bank balance read
// deposit <depositIndex>
// withdraw <withdrawIndex> <amount> <noteIndex> (amount = note count for trade notes)
// transfer <currencyIndex> <amount> <noteIndex> <recipient name...>
// The reader confirms a transfer with the player before sending it (RynthILT doesn't ask again).
//
// Version 2 (RynthILT 0.3.1) appends GetPetBreedingJson and PetBreedingCommand: the data of the
// pet breeding tracker RynthILT draws in the Mini Remote's Pets > Breeding sub-tab (and, until
// 2026-10-21, RynthOracle's Pet Breeding tab). Readers still query version 1 and accept a version-1 table, so charms
// and the bank keep working with an older RynthILT; they use the breeding functions only when
// the table says Version >= 2 and is that big (HasPetBreeding).
//
// GetPetBreedingJson payload (IltPetBreeding.BuildJson; read leniently):
// { "available": true, "world": "...", "enabled": "on"|"off"|"unknown", "maturity": "...", "bond": "...",
// "room": "landblock 0x0106 variant 2", "freeSlots": 12, "message": "...",
// "essences": [ { "id": 1234, "name": "...", "sex": "M"|"F", "tier": 150, "bond": 120, "ready": true,
// "status": "Ready (9/10)", "readyIn": 0, "charges": 9, "chargesMax": 10, "juvenile": false,
// "stage": "Adult", "kills": 300, "killsRequired": 300, "mutations": 2, "potencyMutations": 1,
// "problems": ["..."], "boosters": ["..."] } ],
// "pairs": [ { "stud": "...", "dam": "...", "chanceBest": 0.05, "chanceWorst": 0.04, "inheritMin": 0, "inheritMax": 2 } ],
// "supplies": [ { "key": "incense2", "name": "...", "effect": "...", "count": 1, "price": 2500000, "apply": true,
// "targets": [1234] } ],
// "rules": [ { "label": "...", "value": "10", "source": "seen on server", "help": "..." } ],
// "events": [ { "when": "2026-10-15 20:15", "kind": "birth", "text": "..." } ], newest first
// "debug": { "when": "...", "enabled": "on", "location": "...", "match": "valid"|"invalid"|"", "pet": "...",
// "sex": "...", "partners": 1 } }
// PetBreedingCommand verbs (ASCII): refresh | debug | dance | apply <supplyKey> <essenceId>
// The reader confirms "apply" and "dance" with the player first (RynthILT doesn't ask again).
//
// Version 3 (RynthILT 0.2.20) appends GetGuardianJson and GuardianCommand (the Temple guardians,
// on RynthOracle's Quests tab until 2026-10-21). Readers use them only when Version >= 3 and the table is that big
// (HasGuardian); a version-2 table still answers charms, the bank and breeding (V2Size).
//
// GetGuardianJson payload (IltGuardian.BuildJson; read leniently):
// { "available": true, "world": "...", "chat": true, "auto": false, "buy": true, "cooldownHours": 20,
// "answer": "Pyreal", "npc": "Guardian of ...", "answerAgeSec": 42 (-1 none yet), "heard": "...",
// "running": false, "status": "idle", "synced": "2026-10-18T19:05:00Z" ("" /qb not read),
// "rows": [ { "attribute": "Strength", "npc": "...", "count": 3, "status": "Ready", "eta": "",
// "ready": true, "exact": true } ] } exact = from /myquests (else /qb estimates)
// GuardianCommand verbs (ASCII): handin | stop | refresh | chat on|off | auto on|off | buy on|off
// Auto hand-in and buying a missing Temple item run inside RynthILT whatever the reader shows.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.Shared;
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthIltDataApiV1
{
public const string InterfaceName = "RynthILT.Data";
public const uint InterfaceVersion = 3;
/// <summary>The size of a version-1 table (everything before GetPetBreedingJson) on this platform.</summary>
public static uint V1Size
{
get
{
RynthIltDataApiV1 t = default;
return (uint)((byte*)&t.GetPetBreedingJson - (byte*)&t);
}
}
/// <summary>The size of a version-2 table (everything before GetGuardianJson) on this platform.</summary>
public static uint V2Size
{
get
{
RynthIltDataApiV1 t = default;
return (uint)((byte*)&t.GetGuardianJson - (byte*)&t);
}
}
public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down
public uint StructSize; // sizeof(RynthIltDataApiV1) as RynthILT built it
/// <summary>
/// GetCharmsJson(buffer, capacity): the charms JSON (UTF-8, NUL-terminated) when it fits; returns
/// its length without the NUL (capacity or more = too small, nothing written; 0 = nothing to report).
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetCharmsJson;
/// <summary>GetBankJson(buffer, capacity): the bank JSON, same contract as GetCharmsJson.</summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetBankJson;
/// <summary>
/// ToggleCharm(objectId): uses the carried charm with that id (a "toggleId" from the charms JSON).
/// RynthILT checks it is one of the player's charms before using it. 1 = queued, 0 = refused.
/// </summary>
public delegate* unmanaged[Cdecl]<uint, int> ToggleCharm;
/// <summary>BankCommand(utf8 verb line): queues a bank verb (header above). 1 = queued, 0 = refused.</summary>
public delegate* unmanaged[Cdecl]<byte*, int> BankCommand;
// ── Version 2 ───────────────────────────────────────────────────────────
/// <summary>GetPetBreedingJson(buffer, capacity): the pet breeding JSON, same contract as GetCharmsJson.</summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetPetBreedingJson;
/// <summary>PetBreedingCommand(utf8 verb line): queues a breeding verb (header above). 1 = queued, 0 = refused.</summary>
public delegate* unmanaged[Cdecl]<byte*, int> PetBreedingCommand;
// ── Version 3 ───────────────────────────────────────────────────────────
/// <summary>GetGuardianJson(buffer, capacity): the Temple guardian JSON, same contract as GetCharmsJson.</summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetGuardianJson;
/// <summary>GuardianCommand(utf8 verb line): queues a guardian verb (header above). 1 = queued, 0 = refused.</summary>
public delegate* unmanaged[Cdecl]<byte*, int> GuardianCommand;
}
/// <summary>
/// A reader of "RynthILT.Data". Looks the table up through the host,
/// re-queried while RynthILT is missing or after it unloads (Version 0), and copies a JSON out on
/// request. Pump thread only.
/// </summary>
public sealed unsafe class RynthIltDataClient
{
private const long RequeryMs = 10_000;
private const int MaxBuffer = 256 * 1024;
private const string PluginName = "RynthILT";
private RynthIltDataApiV1* _table;
private long _nextQueryAt;
private byte[] _buffer = new byte[8192];
/// <summary>RynthILT answered with the table (last lookup).</summary>
public bool Connected => _table != null && _table->Version >= 1;
/// <summary>The charms JSON now ("" without RynthILT).</summary>
public string ReadCharms(RynthCoreHost host, long now)
{
RynthIltDataApiV1* t = Table(host, now);
return t == null || t->GetCharmsJson == null ? "" : Read(t->GetCharmsJson);
}
/// <summary>The bank JSON now ("" without RynthILT).</summary>
public string ReadBank(RynthCoreHost host, long now)
{
RynthIltDataApiV1* t = Table(host, now);
return t == null || t->GetBankJson == null ? "" : Read(t->GetBankJson);
}
/// <summary>The pet breeding JSON now ("" without a RynthILT that has the tracker).</summary>
public string ReadPetBreeding(RynthCoreHost host, long now)
{
RynthIltDataApiV1* t = Table(host, now);
return !HasPetBreeding(t) || t->GetPetBreedingJson == null ? "" : Read(t->GetPetBreedingJson);
}
/// <summary>The loaded RynthILT has the breeding tracker (table version 2 or later).</summary>
public bool PetBreedingSupported => HasPetBreeding(_table);
/// <summary>Queues a breeding verb line (see the header). False without RynthILT or when it refused.</summary>
public bool PetBreedingCommand(RynthCoreHost host, long now, string verbLine)
{
RynthIltDataApiV1* t = Table(host, now);
if (!HasPetBreeding(t) || t->PetBreedingCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false;
byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0");
try
{
fixed (byte* p = bytes) return t->PetBreedingCommand(p) == 1;
}
catch { return false; }
}
private static bool HasPetBreeding(RynthIltDataApiV1* t)
=> t != null && t->Version >= 2 && t->StructSize >= RynthIltDataApiV1.V2Size;
/// <summary>The Temple guardian JSON now ("" without a RynthILT that has it, version 3).</summary>
public string ReadGuardian(RynthCoreHost host, long now)
{
RynthIltDataApiV1* t = Table(host, now);
return !HasGuardian(t) || t->GetGuardianJson == null ? "" : Read(t->GetGuardianJson);
}
/// <summary>The loaded RynthILT has the guardian functions (table version 3 or later).</summary>
public bool GuardianSupported => HasGuardian(_table);
/// <summary>Queues a guardian verb line (see the header). False without RynthILT or when it refused.</summary>
public bool GuardianCommand(RynthCoreHost host, long now, string verbLine)
{
RynthIltDataApiV1* t = Table(host, now);
if (!HasGuardian(t) || t->GuardianCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false;
byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0");
try
{
fixed (byte* p = bytes) return t->GuardianCommand(p) == 1;
}
catch { return false; }
}
private static bool HasGuardian(RynthIltDataApiV1* t)
=> t != null && t->Version >= 3 && t->StructSize >= (uint)sizeof(RynthIltDataApiV1);
/// <summary>Asks RynthILT to use a carried charm. False without RynthILT or when it refused.</summary>
public bool ToggleCharm(RynthCoreHost host, long now, uint objectId)
{
RynthIltDataApiV1* t = Table(host, now);
if (t == null || t->ToggleCharm == null || objectId == 0) return false;
try { return t->ToggleCharm(objectId) == 1; }
catch { return false; }
}
/// <summary>Queues a bank verb line (see the header). False without RynthILT or when it refused.</summary>
public bool BankCommand(RynthCoreHost host, long now, string verbLine)
{
RynthIltDataApiV1* t = Table(host, now);
if (t == null || t->BankCommand == null || string.IsNullOrWhiteSpace(verbLine)) return false;
byte[] bytes = Encoding.UTF8.GetBytes(verbLine + "\0");
try
{
fixed (byte* p = bytes) return t->BankCommand(p) == 1;
}
catch { return false; }
}
/// <summary>The table, re-queried when it is missing or RynthILT has shut down (Version 0).</summary>
private RynthIltDataApiV1* Table(RynthCoreHost host, long now)
{
if (_table != null && _table->Version >= 1) return _table;
_table = null;
if (now < _nextQueryAt || !host.HasGetPluginInterface) return null;
_nextQueryAt = now + RequeryMs;
// Version 1 is asked for and a version-1-sized table taken, so an older RynthILT still answers.
var p = (RynthIltDataApiV1*)host.GetPluginInterface(PluginName, RynthIltDataApiV1.InterfaceName, 1);
if (p != null && p->Version >= 1 && p->StructSize >= RynthIltDataApiV1.V1Size)
_table = p;
return _table;
}
/// <summary>Copies a JSON out, growing the buffer once when RynthILT says it didn't fit.</summary>
private string Read(delegate* unmanaged[Cdecl]<byte*, int, int> get)
{
for (int attempt = 0; attempt < 2; attempt++)
{
int len;
try
{
fixed (byte* b = _buffer) len = get(b, _buffer.Length);
}
catch { return ""; }
if (len <= 0) return "";
if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len);
if (len + 1 > MaxBuffer) return "";
_buffer = new byte[len + 1024];
}
return "";
}
}
/// <summary>One registry charm from the charms JSON.</summary>
public sealed record IltCharmRow(string Name, string Effect, string Acquired, int Count, int Tier, int MaxTier,
string Active, string Server, string LastSeen, uint ToggleId)
{
/// <summary>Carried now (in the pack or equipped).</summary>
public bool Carried => Acquired == "carried";
}
/// <summary>A Guardian Hand carried now: its object id (the Toggle's id), name, status and the server's switch.</summary>
public sealed record IltHandRow(uint Id, string Name, string Active, string Server);
/// <summary>The charms JSON parsed. <see cref="None"/> without RynthILT; every field read leniently.</summary>
public sealed class IltCharmsView
{
public static readonly IltCharmsView None = new();
/// <summary>RynthILT answered.</summary>
public bool Loaded { get; private init; }
/// <summary>An Infinite Leaftide world (charms exist).</summary>
public bool Available { get; private init; }
public string World { get; private init; } = "";
public int Acquired { get; private init; }
public int Active { get; private init; }
public IReadOnlyList<IltCharmRow> Charms { get; private init; } = Array.Empty<IltCharmRow>();
/// <summary>The Guardian Hands carried now (none from an older RynthILT).</summary>
public IReadOnlyList<IltHandRow> Hands { get; private init; } = Array.Empty<IltHandRow>();
public static IltCharmsView Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var rows = new List<IltCharmRow>();
if (root.TryGetProperty("charms", out JsonElement cs) && cs.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement c in cs.EnumerateArray())
{
if (c.ValueKind != JsonValueKind.Object) continue;
string name = IltJson.Str(c, "name");
if (name.Length == 0) continue;
rows.Add(new IltCharmRow(name, IltJson.Str(c, "effect"), IltJson.Str(c, "acquired", "no"),
(int)IltJson.Long(c, "count"), (int)IltJson.Long(c, "tier"), (int)IltJson.Long(c, "maxTier"),
IltJson.Str(c, "active", "unknown"), IltJson.Str(c, "server", "unknown"), IltJson.Str(c, "lastSeen"),
(uint)Math.Clamp(IltJson.Long(c, "toggleId"), 0, uint.MaxValue)));
}
}
var hands = new List<IltHandRow>();
foreach (JsonElement h in IltJson.Array(root, "hands"))
{
uint id = (uint)Math.Clamp(IltJson.Long(h, "id"), 0, uint.MaxValue);
if (id == 0) continue; // no id = nothing a Toggle could use
hands.Add(new IltHandRow(id, IltJson.Str(h, "name", "Guardian Hand"), IltJson.Str(h, "active", "unknown"),
IltJson.Str(h, "server", "unknown")));
}
return new IltCharmsView
{
Loaded = true,
Available = IltJson.Bool(root, "available"),
World = IltJson.Str(root, "world"),
Acquired = (int)IltJson.Long(root, "acquiredCount"),
Active = (int)IltJson.Long(root, "activeCount"),
Charms = rows,
Hands = hands,
};
}
catch (JsonException) { return None; }
}
}
/// <summary>One character's saved bank balances from the bank JSON.</summary>
public sealed record IltBankRow(string Name, bool Current, long Pyreals, long Luminance, long LegendaryKeys, long MythicalKeys,
long EnlightenedCoins, long WeaklyEnlightenedCoins, long PrestigeCoins, DateTime UpdatedUtc);
/// <summary>A bank form choice: its label and whether the amount is a trade-note count.</summary>
public sealed record IltBankChoice(string Label, bool Notes);
/// <summary>A trade-note denomination: label and pyreal value.</summary>
public sealed record IltBankNote(string Label, long Value);
/// <summary>One logged transfer.</summary>
public sealed record IltBankTx(string When, string Type, long Amount, string Currency, string Player);
/// <summary>The bank JSON parsed. <see cref="None"/> without RynthILT; every field read leniently.</summary>
public sealed class IltBankView
{
public static readonly IltBankView None = new();
/// <summary>RynthILT answered.</summary>
public bool Loaded { get; private init; }
/// <summary>An Infinite Leaftide world (bank commands exist).</summary>
public bool Available { get; private init; }
/// <summary>1 the server has /bank, 0 not, -1 not known yet.</summary>
public int Enabled { get; private init; } = -1;
public string World { get; private init; } = "";
public string Character { get; private init; } = "";
public string Result { get; private init; } = "";
public IReadOnlyList<IltBankRow> Characters { get; private init; } = Array.Empty<IltBankRow>();
public IReadOnlyList<string> Deposits { get; private init; } = Array.Empty<string>();
public IReadOnlyList<IltBankChoice> Withdrawals { get; private init; } = Array.Empty<IltBankChoice>();
public IReadOnlyList<IltBankChoice> Transfers { get; private init; } = Array.Empty<IltBankChoice>();
public IReadOnlyList<IltBankNote> Notes { get; private init; } = Array.Empty<IltBankNote>();
public IReadOnlyList<IltBankTx> Transactions { get; private init; } = Array.Empty<IltBankTx>();
public static IltBankView Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var chars = new List<IltBankRow>();
foreach (JsonElement c in IltJson.Array(root, "characters"))
{
string name = IltJson.Str(c, "name");
if (name.Length == 0) continue;
DateTime updated = DateTime.MinValue;
string when = IltJson.Str(c, "updated");
if (when.Length > 0
&& DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t))
updated = t;
chars.Add(new IltBankRow(name, IltJson.Bool(c, "current"), IltJson.Long(c, "pyreals"), IltJson.Long(c, "luminance"),
IltJson.Long(c, "legendaryKeys"), IltJson.Long(c, "mythicalKeys"), IltJson.Long(c, "enlightenedCoins"),
IltJson.Long(c, "weaklyEnlightenedCoins"), IltJson.Long(c, "prestigeCoins"), updated));
}
var deposits = new List<string>();
if (root.TryGetProperty("deposits", out JsonElement ds) && ds.ValueKind == JsonValueKind.Array)
foreach (JsonElement d in ds.EnumerateArray())
if (d.ValueKind == JsonValueKind.String) deposits.Add(d.GetString() ?? "");
var notes = new List<IltBankNote>();
foreach (JsonElement n in IltJson.Array(root, "notes"))
notes.Add(new IltBankNote(IltJson.Str(n, "label"), IltJson.Long(n, "value")));
var tx = new List<IltBankTx>();
foreach (JsonElement x in IltJson.Array(root, "transactions"))
tx.Add(new IltBankTx(IltJson.Str(x, "when"), IltJson.Str(x, "type"), IltJson.Long(x, "amount"),
IltJson.Str(x, "currency"), IltJson.Str(x, "player")));
return new IltBankView
{
Loaded = true,
Available = IltJson.Bool(root, "available"),
Enabled = (int)Math.Clamp(IltJson.Long(root, "enabled", -1), -1, 1),
World = IltJson.Str(root, "world"),
Character = IltJson.Str(root, "character"),
Result = IltJson.Str(root, "result"),
Characters = chars,
Deposits = deposits,
Withdrawals = Choices(root, "withdrawals"),
Transfers = Choices(root, "transfers"),
Notes = notes,
Transactions = tx,
};
}
catch (JsonException) { return None; }
}
private static List<IltBankChoice> Choices(JsonElement root, string name)
{
var list = new List<IltBankChoice>();
foreach (JsonElement c in IltJson.Array(root, name))
list.Add(new IltBankChoice(IltJson.Str(c, "label"), IltJson.Bool(c, "notes")));
return list;
}
/// <summary>The bank verb lines (header of this file); pure so the tests check them.</summary>
public static string RefreshVerb() => "refresh";
public static string DepositVerb(int index) => "deposit " + index.ToString(CultureInfo.InvariantCulture);
public static string WithdrawVerb(int index, long amount, int note)
=> string.Join(' ', "withdraw", index.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture),
note.ToString(CultureInfo.InvariantCulture));
public static string TransferVerb(int currency, long amount, int note, string recipient)
=> string.Join(' ', "transfer", currency.ToString(CultureInfo.InvariantCulture), amount.ToString(CultureInfo.InvariantCulture),
note.ToString(CultureInfo.InvariantCulture), (recipient ?? "").Trim());
}
/// <summary>One carried combat essence from the pet breeding JSON.</summary>
public sealed record IltBreedEssenceRow(int Id, string Name, bool Male, int Tier, int Bond, bool Ready, string Status, long ReadyIn,
int Charges, int ChargesMax, bool Juvenile, string Stage, int Kills, int KillsRequired,
int Mutations, int PotencyMutations, IReadOnlyList<string> Problems, IReadOnlyList<string> Boosters);
/// <summary>A ready stud + dam pairing and its stat mutation odds (0..1).</summary>
public sealed record IltBreedPairRow(string Stud, string Dam, double ChanceBest, double ChanceWorst, int InheritMin, int InheritMax);
/// <summary>A breeding supply: count carried, Ivo's price, and the essence ids the server would take it on now.</summary>
public sealed record IltBreedSupplyRow(string Key, string Name, string Effect, long Count, long Price, bool Apply, IReadOnlyList<int> Targets);
/// <summary>One breeding rule: its value and where it came from ("seen on server", "ILT profile", "ACE default").</summary>
public sealed record IltBreedRuleRow(string Label, string Value, string Source, string Help);
/// <summary>One breeding event (newest first in the view).</summary>
public sealed record IltBreedEventRow(string When, string Kind, string Text);
/// <summary>The last "@breed-debug" reply: when, the switch, where you were, the room check, your pet, partners nearby.</summary>
public sealed record IltBreedDebugRow(string When, string Enabled, string Location, string Match, string Pet, string Sex, int Partners);
/// <summary>The pet breeding JSON parsed. <see cref="None"/> without RynthILT; every field read leniently.</summary>
public sealed class IltBreedingView
{
public static readonly IltBreedingView None = new();
/// <summary>RynthILT answered.</summary>
public bool Loaded { get; private init; }
public bool Available { get; private init; }
public string World { get; private init; } = "";
/// <summary>"on", "off" or "unknown": the server's pet breeding switch as RynthILT knows it.</summary>
public string Enabled { get; private init; } = "unknown";
public string Maturity { get; private init; } = "unknown";
public string Bond { get; private init; } = "unknown";
public string Room { get; private init; } = "";
/// <summary>Free main-pack slots (-1 unknown).</summary>
public int FreeSlots { get; private init; } = -1;
public string Message { get; private init; } = "";
public IReadOnlyList<IltBreedEssenceRow> Essences { get; private init; } = Array.Empty<IltBreedEssenceRow>();
public IReadOnlyList<IltBreedPairRow> Pairs { get; private init; } = Array.Empty<IltBreedPairRow>();
public IReadOnlyList<IltBreedSupplyRow> Supplies { get; private init; } = Array.Empty<IltBreedSupplyRow>();
public IReadOnlyList<IltBreedRuleRow> Rules { get; private init; } = Array.Empty<IltBreedRuleRow>();
public IReadOnlyList<IltBreedEventRow> Events { get; private init; } = Array.Empty<IltBreedEventRow>();
public IltBreedDebugRow? Debug { get; private init; }
public static IltBreedingView Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var essences = new List<IltBreedEssenceRow>();
foreach (JsonElement e in IltJson.Array(root, "essences"))
{
string name = IltJson.Str(e, "name");
if (name.Length == 0) continue;
essences.Add(new IltBreedEssenceRow((int)IltJson.Long(e, "id"), name, IltJson.Str(e, "sex") == "M",
(int)IltJson.Long(e, "tier"), (int)IltJson.Long(e, "bond"), IltJson.Bool(e, "ready"), IltJson.Str(e, "status"),
IltJson.Long(e, "readyIn"), (int)IltJson.Long(e, "charges"), (int)IltJson.Long(e, "chargesMax"),
IltJson.Bool(e, "juvenile"), IltJson.Str(e, "stage"), (int)IltJson.Long(e, "kills"), (int)IltJson.Long(e, "killsRequired"),
(int)IltJson.Long(e, "mutations"), (int)IltJson.Long(e, "potencyMutations"),
IltJson.Strings(e, "problems"), IltJson.Strings(e, "boosters")));
}
var pairs = new List<IltBreedPairRow>();
foreach (JsonElement p in IltJson.Array(root, "pairs"))
pairs.Add(new IltBreedPairRow(IltJson.Str(p, "stud"), IltJson.Str(p, "dam"), IltJson.Double(p, "chanceBest"),
IltJson.Double(p, "chanceWorst"), (int)IltJson.Long(p, "inheritMin"), (int)IltJson.Long(p, "inheritMax")));
var supplies = new List<IltBreedSupplyRow>();
foreach (JsonElement s in IltJson.Array(root, "supplies"))
{
var targets = new List<int>();
if (s.TryGetProperty("targets", out JsonElement ts) && ts.ValueKind == JsonValueKind.Array)
foreach (JsonElement t in ts.EnumerateArray())
if (t.ValueKind == JsonValueKind.Number && t.TryGetInt32(out int id)) targets.Add(id);
supplies.Add(new IltBreedSupplyRow(IltJson.Str(s, "key"), IltJson.Str(s, "name"), IltJson.Str(s, "effect"),
IltJson.Long(s, "count"), IltJson.Long(s, "price"), IltJson.Bool(s, "apply"), targets));
}
var rules = new List<IltBreedRuleRow>();
foreach (JsonElement r in IltJson.Array(root, "rules"))
rules.Add(new IltBreedRuleRow(IltJson.Str(r, "label"), IltJson.Str(r, "value"), IltJson.Str(r, "source"), IltJson.Str(r, "help")));
var events = new List<IltBreedEventRow>();
foreach (JsonElement ev in IltJson.Array(root, "events"))
events.Add(new IltBreedEventRow(IltJson.Str(ev, "when"), IltJson.Str(ev, "kind"), IltJson.Str(ev, "text")));
IltBreedDebugRow? debug = null;
if (root.TryGetProperty("debug", out JsonElement d) && d.ValueKind == JsonValueKind.Object)
debug = new IltBreedDebugRow(IltJson.Str(d, "when"), IltJson.Str(d, "enabled", "unknown"), IltJson.Str(d, "location"),
IltJson.Str(d, "match"), IltJson.Str(d, "pet"), IltJson.Str(d, "sex"), (int)IltJson.Long(d, "partners", -1));
return new IltBreedingView
{
Loaded = true,
Available = IltJson.Bool(root, "available"),
World = IltJson.Str(root, "world"),
Enabled = IltJson.Str(root, "enabled", "unknown"),
Maturity = IltJson.Str(root, "maturity", "unknown"),
Bond = IltJson.Str(root, "bond", "unknown"),
Room = IltJson.Str(root, "room"),
FreeSlots = (int)IltJson.Long(root, "freeSlots", -1),
Message = IltJson.Str(root, "message"),
Essences = essences,
Pairs = pairs,
Supplies = supplies,
Rules = rules,
Events = events,
Debug = debug,
};
}
catch (JsonException) { return None; }
}
/// <summary>The breeding verb lines (header of this file); pure so the tests check them.</summary>
public static string RefreshVerb() => "refresh";
public static string DebugVerb() => "debug";
public static string DanceVerb() => "dance";
public static string ApplyVerb(string supplyKey, int essenceId)
=> string.Join(' ', "apply", (supplyKey ?? "").Trim(), essenceId.ToString(CultureInfo.InvariantCulture));
}
/// <summary>One Temple attribute turn-in from the guardian JSON.</summary>
public sealed record IltGuardianRow(string Attribute, string Npc, int Count, string Status, string Eta, bool Ready, bool Exact);
/// <summary>The Temple guardian JSON parsed. <see cref="None"/> without RynthILT; every field read leniently.</summary>
public sealed class IltGuardianView
{
public static readonly IltGuardianView None = new();
/// <summary>RynthILT answered.</summary>
public bool Loaded { get; private init; }
public bool Available { get; private init; }
public string World { get; private init; } = "";
/// <summary>Translate the guardians' tells as they arrive.</summary>
public bool Chat { get; private init; }
/// <summary>Give the answer item to the guardian automatically after a chat answer.</summary>
public bool Auto { get; private init; }
/// <summary>Buy a missing Temple item from the nearest vendor first.</summary>
public bool Buy { get; private init; }
public int CooldownHours { get; private init; }
public string Answer { get; private init; } = "";
public string Npc { get; private init; } = "";
/// <summary>Seconds since the last answer (-1 none yet).</summary>
public long AnswerAgeSec { get; private init; } = -1;
public string Heard { get; private init; } = "";
/// <summary>A hand-in is running.</summary>
public bool Running { get; private init; }
public string Status { get; private init; } = "";
/// <summary>When /qb was last read (MinValue never).</summary>
public DateTime SyncedUtc { get; private init; } = DateTime.MinValue;
public IReadOnlyList<IltGuardianRow> Rows { get; private init; } = Array.Empty<IltGuardianRow>();
public static IltGuardianView Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return None;
try
{
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return None;
var rows = new List<IltGuardianRow>();
foreach (JsonElement r in IltJson.Array(root, "rows"))
{
string attr = IltJson.Str(r, "attribute");
if (attr.Length == 0) continue;
rows.Add(new IltGuardianRow(attr, IltJson.Str(r, "npc"), (int)IltJson.Long(r, "count"), IltJson.Str(r, "status"),
IltJson.Str(r, "eta"), IltJson.Bool(r, "ready"), IltJson.Bool(r, "exact")));
}
DateTime synced = DateTime.MinValue;
string when = IltJson.Str(root, "synced");
if (when.Length > 0
&& DateTime.TryParse(when, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime t))
synced = t;
return new IltGuardianView
{
Loaded = true,
Available = IltJson.Bool(root, "available"),
World = IltJson.Str(root, "world"),
Chat = IltJson.Bool(root, "chat"),
Auto = IltJson.Bool(root, "auto"),
Buy = IltJson.Bool(root, "buy"),
CooldownHours = (int)IltJson.Long(root, "cooldownHours"),
Answer = IltJson.Str(root, "answer"),
Npc = IltJson.Str(root, "npc"),
AnswerAgeSec = IltJson.Long(root, "answerAgeSec", -1),
Heard = IltJson.Str(root, "heard"),
Running = IltJson.Bool(root, "running"),
Status = IltJson.Str(root, "status"),
SyncedUtc = synced,
Rows = rows,
};
}
catch (JsonException) { return None; }
}
/// <summary>The guardian verb lines (header of this file); pure so the tests check them.</summary>
public static string HandInVerb() => "handin";
public static string StopVerb() => "stop";
public static string RefreshVerb() => "refresh";
/// <summary>"chat on", "auto off", "buy on": <paramref name="name"/> is chat, auto or buy.</summary>
public static string SwitchVerb(string name, bool on) => (name ?? "").Trim().ToLowerInvariant() + (on ? " on" : " off");
}
/// <summary>Lenient JSON field reads shared by the views above.</summary>
internal static class IltJson
{
public static string Str(JsonElement o, string name, string fallback = "") =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? fallback : fallback;
public static bool Bool(JsonElement o, string name) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
public static long Long(JsonElement o, string name, long fallback = 0) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt64(out long l) ? l : fallback;
public static double Double(JsonElement o, string name, double fallback = 0) =>
o.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) ? d : fallback;
/// <summary>The string items of an array field (other kinds skipped).</summary>
public static List<string> Strings(JsonElement o, string name)
{
var list = new List<string>();
if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.String) list.Add(e.GetString() ?? "");
return list;
}
public static IEnumerable<JsonElement> Array(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break;
foreach (JsonElement e in a.EnumerateArray())
if (e.ValueKind == JsonValueKind.Object) yield return e;
}
}

View file

@ -0,0 +1,45 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltHubApi.cs
// RynthILT's own names around the server hub (Shared/RynthServerHubApi.cs).
// RynthILT serves the "RynthServer.Hub" table (RynthServerHubApiV1) under that
// neutral name and under its older one, "RynthILT.Hub" (every RynthILT since the
// interface's first release answers that one). The section, tab, text, feature
// and setting ids RynthAi uses are RynthServerHub's; the ids here are Infinite
// Leaftide's alone (its sub-tab, its quest list, ACECustom's feature keys).
// Until 2026-10-21 this file held the whole interface (class RynthIltHub,
// structs RynthIltHubApiV1 / IltTabV1); the ids kept their values.
// Compiled into RynthILT only (linked source).
// ============================================================================
namespace RynthCore.Plugin.Shared;
/// <summary>RynthILT's constants around the "RynthServer.Hub" interface.</summary>
public static class RynthIltHub
{
/// <summary>The providing plugin's display name.</summary>
public const string PluginName = "RynthILT";
/// <summary>
/// RynthILT's own name for the RynthServer.Hub table (the same table; RynthServerHubApiV1 is its layout).
/// Older RynthAi asked for this name first.
/// </summary>
public const string InterfaceName = "RynthILT.Hub";
/// <summary>Quests tab: the "Quest bonus (/qb)" list.</summary>
public const string SectionQuestBonus = "quests-qb";
/// <summary>
/// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+;
/// older copies draw nothing). Since 2026-10-20 RynthAi shows it because GetSubTabs(TabParentPets)
/// lists it (RynthILT: an ILT world unless FeaturePetBreeding is off); older RynthAi decided itself.
/// </summary>
public const string SectionPetBreeding = "pets-breeding";
/// <summary>ACECustom feature keys (GetFeature) beside RynthServerHub.FeatureQuests.</summary>
public const string FeaturePetRefill = "pet_refill";
public const string FeatureUniversalMastery = "universal_mastery";
/// <summary>ACECustom siphon lenses (monster capture into a pet essence).</summary>
public const string FeatureMonsterCapture = "monster_capture";
public const string FeatureRequireComps = "require_spell_comps";
/// <summary>Pet breeding (the Pets tab's Breeding sub-tab is hidden while the server reports it off).</summary>
public const string FeaturePetBreeding = "pet_breeding";
}

View file

@ -0,0 +1,75 @@
// ============================================================================
// RynthSuite - Plugins/Shared/RynthIltServerApi.cs
// The "RynthILT.Server" interface: what RynthILT knows about the Infinite Leaftide
// server, for any plugin that wants it without drawing RynthILT's UI (RynthOracle read it
// for its About and Quests tabs until 2026-10-21; RynthILT's settings window and Quests
// section show the same now, and no RynthSuite plugin reads it). One call hands out a JSON snapshot: whether this is an
// ILT world, every Leaftide feature RynthILT supports with the server's state for it,
// and the server's fellowship rules.
// Separate from "RynthILT.Hub" (RynthIltHubApi.cs) so that interface, which RynthAi asks
// for at an exact version, never has to change for this.
// Compiled into RynthILT and its readers (linked source), so the layout can't drift.
//
// Rules (as the other shared interfaces):
// - Append-only: new functions go at the end, and Version goes up.
// - Strings are UTF-8, NUL-terminated. The JSON itself is plain ASCII.
// - Every function returns safely (no exception crosses the boundary).
// - The table is allocated once per loaded copy of RynthILT and never freed; shutdown
// sets Version to 0, and a reader re-queries (host GetPluginInterface) when it sees that.
//
// GetProfileJson payload (every field may be missing on an older RynthILT; read leniently):
// {
// "ilt": true, // ILT world (its world list, or the character's override)
// "world": "InfiniteLeaftide", // the world name the server announced ("" before login)
// "forced": false, // "Treat this world as ILT" is on
// "source": "probe", // where the feature bits came from ("ilt-features", "probe", "")
// "checked": "2026-10-13T21:25:37Z", // last server-options check (UTC), "" = never
// "features": [ { "key": "bank", "label": "Banking", "group": "Character",
// "state": 1, "where": "Mini Remote > Banking tab" }, ... ],
// // state: 1 on, 0 off, -1 not known yet
// "fellowship": { "maxMembers": 29, "zoneShare": 1, "blackjack": 0, "luminanceShare": 1 },
// "questBonus": { "disabled": false, "generation": 2, "count": 41, "status": "12 completed, 3 incomplete",
// "completed": [ "flag", ... ], "incomplete": [ "flag", ... ] }
// // the /qb list; ILT worlds only (generation 0 = not loaded yet)
// }
// ============================================================================
using System.Runtime.InteropServices;
namespace RynthCore.Plugin.Shared;
/// <summary>Constants of the "RynthILT.Server" interface.</summary>
public static class RynthIltServer
{
/// <summary>The providing plugin's display name.</summary>
public const string PluginName = "RynthILT";
/// <summary>Feature state in the profile JSON: the server reports it on.</summary>
public const int StateOn = 1;
/// <summary>Feature state: the server reports it off.</summary>
public const int StateOff = 0;
/// <summary>Feature state: not known yet (not checked, not an ILT world, or no RynthILT).</summary>
public const int StateUnknown = -1;
/// <summary>A retail fellowship's member limit (what a reader assumes without RynthILT).</summary>
public const int RetailFellowshipMax = 9;
}
[StructLayout(LayoutKind.Sequential)]
public unsafe struct RynthIltServerApiV1
{
public const string InterfaceName = "RynthILT.Server";
public const uint InterfaceVersion = 1;
public uint Version; // InterfaceVersion of the table RynthILT filled; 0 once it has shut down
public uint StructSize; // sizeof(RynthIltServerApiV1) as RynthILT built it
/// <summary>
/// GetProfileJson(buffer, capacity): writes the profile JSON (UTF-8, NUL-terminated) into
/// buffer when it fits, and returns its length in bytes without the NUL. A return value of
/// capacity or more means nothing was written: call again with a bigger buffer. 0 = nothing
/// to report (RynthILT shutting down). Any thread (it hands out a snapshot RynthILT's pump
/// rebuilds about once a second).
/// </summary>
public delegate* unmanaged[Cdecl]<byte*, int, int> GetProfileJson;
}

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>