Snapshot for release 2026.10.15.2 (internal 2d4b0af)
This commit is contained in:
parent
a89ae04005
commit
d5e0b50de7
224 changed files with 17914 additions and 1182 deletions
56
Plugins/Shared/ChatSource.cs
Normal file
56
Plugins/Shared/ChatSource.cs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ChatSource.cs
|
||||
// Telling a server line from a player's imitation of one.
|
||||
//
|
||||
// Some chat lines are signals: "Your missile attack hit the environment." moves
|
||||
// the combat target, a "~ael1 " data line feeds the vault view. Another player
|
||||
// can type the same words, so a reader of a signal needs both checks here:
|
||||
// - the chat type is not one a player writes in (ACE ChatMessageType, which
|
||||
// is the client's eChatTypes: ACE.Entity/Enum/ChatMessageType.cs);
|
||||
// - the line STARTS with the marker. The client puts the speaker in front
|
||||
// of player text ("Name says, ...", "Name tells you, ...", "Name waves"),
|
||||
// so a player's copy never starts with it.
|
||||
// Compiled into each plugin that reads a signal (linked source).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class ChatSource
|
||||
{
|
||||
// Chat types whose text another player writes.
|
||||
public const int Speech = 0x02;
|
||||
public const int Tell = 0x03;
|
||||
public const int OutgoingTell = 0x04;
|
||||
public const int Channel = 0x08;
|
||||
public const int ChannelSend = 0x09;
|
||||
public const int Social = 0x0A;
|
||||
public const int SocialSend = 0x0B;
|
||||
public const int Emote = 0x0C;
|
||||
public const int Allegiance = 0x12;
|
||||
public const int Fellowship = 0x13;
|
||||
|
||||
/// <summary>
|
||||
/// True when a line of this chat type is a player's words. A caller that
|
||||
/// doesn't know the type passes -1 (false), and then only the anchor protects it.
|
||||
/// </summary>
|
||||
public static bool IsPlayerAuthored(int chatType) => chatType switch
|
||||
{
|
||||
Speech or Tell or OutgoingTell or Channel or ChannelSend
|
||||
or Social or SocialSend or Emote or Allegiance or Fellowship => true,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>The index just past <paramref name="line"/>'s leading whitespace.</summary>
|
||||
public static int ContentStart(string line)
|
||||
{
|
||||
int i = 0;
|
||||
while (i < line.Length && char.IsWhiteSpace(line[i])) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="line"/>, past leading whitespace, starts with <paramref name="marker"/>.</summary>
|
||||
public static bool StartsWithMarker(string? line, string marker, StringComparison comparison = StringComparison.Ordinal)
|
||||
=> line != null && line.AsSpan(ContentStart(line)).StartsWith(marker.AsSpan(), comparison);
|
||||
}
|
||||
260
Plugins/Shared/EngineServerState.cs
Normal file
260
Plugins/Shared/EngineServerState.cs
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/EngineServerState.cs
|
||||
// RynthCore's answer to "which server is this?" (plugin API v86,
|
||||
// GetServerStateJson), parsed: every server the engine knows (built-in ILT and
|
||||
// Aelrynth, plus each loaded server plugin's declaration), whether it is
|
||||
// active, this character's override, and which plugin owns it (the one to ask
|
||||
// for its settings through "RynthServer.Profile"; RynthILT answers it for "ilt").
|
||||
// The same verdict the Mini Remote, the menus and the Diagnostics server
|
||||
// picker use, so every plugin follows one choice, overrides included.
|
||||
//
|
||||
// Pure (BCL only): the plugins' test tools compile it. ServerStateClient.cs
|
||||
// polls the engine and the owner plugin.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>One server in the engine's list.</summary>
|
||||
internal sealed record EngineServer(string Id, string Name, bool Active, bool Detected, string Force, bool BuiltIn,
|
||||
string Plugin, string Reason);
|
||||
|
||||
/// <summary>The engine's server list at one moment (GetServerStateJson, schema 1).</summary>
|
||||
internal sealed class EngineServerState
|
||||
{
|
||||
/// <summary>Engine server ids with a meaning across RynthSuite.</summary>
|
||||
public const string IltId = "ilt";
|
||||
public const string AelrynthId = "aelrynth";
|
||||
|
||||
public int Revision { get; private init; }
|
||||
/// <summary>The connect host the client was launched with ("" when not known).</summary>
|
||||
public string Host { get; private init; } = string.Empty;
|
||||
/// <summary>The world name the server announced at login ("" before, or without the hook).</summary>
|
||||
public string World { get; private init; } = string.Empty;
|
||||
/// <summary>"auto", a server id (picked on the Diagnostics page or "/rc server pick"), or "mixed".</summary>
|
||||
public string Pick { get; private init; } = "auto";
|
||||
/// <summary>The active server's id, "" when none is (a retail-like world).</summary>
|
||||
public string Active { get; private init; } = string.Empty;
|
||||
public string ActiveName { get; private init; } = string.Empty;
|
||||
/// <summary>The plugin that owns the active server ("" when none is loaded).</summary>
|
||||
public string ActivePlugin { get; private init; } = string.Empty;
|
||||
public IReadOnlyList<EngineServer> Servers { get; private init; } = Array.Empty<EngineServer>();
|
||||
|
||||
/// <summary>True when a server is active.</summary>
|
||||
public bool HasActive => Active.Length > 0;
|
||||
|
||||
/// <summary>True when the active server was chosen by hand (a pick), not detected.</summary>
|
||||
public bool Picked => !Pick.Equals("auto", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>The server with <paramref name="id"/>, or null when the engine doesn't list it.</summary>
|
||||
public EngineServer? Find(string id)
|
||||
{
|
||||
foreach (EngineServer s in Servers)
|
||||
if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="id"/> is the active server.</summary>
|
||||
public bool IsActive(string id) => Active.Equals(id, StringComparison.OrdinalIgnoreCase) && Active.Length > 0;
|
||||
|
||||
/// <summary>
|
||||
/// Whether this world is one of <paramref name="names"/> (a user's server list, "InfiniteLeaftide,
|
||||
/// Conquest"): names compare case- and space-insensitively against server ids, names and the world.
|
||||
/// Without the engine (<paramref name="engine"/> null) the world name decides. With it, an active
|
||||
/// server decides ("ilt" counts as any Leaftide name); with none active the world name still counts,
|
||||
/// unless it names a server the engine lists, which is then off on purpose (not detected, or this
|
||||
/// character's override).
|
||||
/// </summary>
|
||||
public static bool MatchesNameList(EngineServerState? engine, string? world, IReadOnlyList<string> names)
|
||||
{
|
||||
bool Named(string? s)
|
||||
{
|
||||
string n = Norm(s);
|
||||
if (n.Length == 0) return false;
|
||||
foreach (string name in names)
|
||||
if (Norm(name) == n) return true;
|
||||
return false;
|
||||
}
|
||||
bool anyLeaftide = false;
|
||||
foreach (string name in names)
|
||||
if (Norm(name).Contains("leaftide", StringComparison.Ordinal)) anyLeaftide = true;
|
||||
|
||||
if (engine == null) return Named(world);
|
||||
if (engine.HasActive)
|
||||
return Named(engine.Active) || Named(engine.ActiveName) || (anyLeaftide && engine.IsActive(IltId));
|
||||
if (!Named(world)) return false;
|
||||
string w = Norm(world);
|
||||
foreach (EngineServer s in engine.Servers)
|
||||
{
|
||||
if (Norm(s.Id) == w || Norm(s.Name) == w) return false;
|
||||
// ILT's world names ("InfiniteLeaftide") are the engine's own ILT detection.
|
||||
if (s.Id.Equals(IltId, StringComparison.OrdinalIgnoreCase) && w.Contains("leaftide", StringComparison.Ordinal)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Lower case without spaces, so "Infinite Leaftide" equals "InfiniteLeaftide".</summary>
|
||||
private static string Norm(string? s) => (s ?? string.Empty).Replace(" ", string.Empty).Trim().ToLowerInvariant();
|
||||
|
||||
/// <summary>
|
||||
/// Parses GetServerStateJson output. Null for empty or unusable text, or another schema's.
|
||||
/// Missing fields read as empty; nothing throws.
|
||||
/// </summary>
|
||||
public static EngineServerState? Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return null;
|
||||
if (Int(root, "schema") != 1) return null;
|
||||
|
||||
var servers = new List<EngineServer>();
|
||||
if (root.TryGetProperty("servers", out JsonElement list) && list.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
foreach (JsonElement e in list.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object) continue;
|
||||
string id = Str(e, "id");
|
||||
if (id.Length == 0) continue;
|
||||
servers.Add(new EngineServer(id, Str(e, "name"), Bool(e, "active"), Bool(e, "detected"),
|
||||
Str(e, "force"), Bool(e, "builtIn"), Str(e, "plugin"), Str(e, "reason")));
|
||||
}
|
||||
}
|
||||
|
||||
return new EngineServerState
|
||||
{
|
||||
Revision = Int(root, "revision"),
|
||||
Host = Str(root, "host"),
|
||||
World = Str(root, "world"),
|
||||
Pick = Str(root, "pick") is { Length: > 0 } pick ? pick : "auto",
|
||||
Active = Str(root, "active"),
|
||||
ActiveName = Str(root, "activeName"),
|
||||
ActivePlugin = Str(root, "activePlugin"),
|
||||
Servers = servers,
|
||||
};
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
internal static string Str(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? (v.GetString() ?? string.Empty) : string.Empty;
|
||||
|
||||
internal static bool Bool(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.True;
|
||||
|
||||
internal static int Int(JsonElement e, string name)
|
||||
=> e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) ? n : 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The headline facts of a server owner's profile JSON ("RynthServer.Profile" from the plugin that
|
||||
/// owns the server), read leniently: a field the owner doesn't send stays "".
|
||||
/// </summary>
|
||||
internal sealed record ServerProfileView(string Id, string Name, string Plugin, string Ruleset, string Emulator,
|
||||
string Botting, string BottingNote, string AccountLimit, bool Ilt, int FeaturesOn)
|
||||
{
|
||||
/// <summary>Null for empty or unusable text.</summary>
|
||||
public static ServerProfileView? Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return null;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object) return null;
|
||||
// RynthILT's profile: its feature list, state 1 = on.
|
||||
int on = 0;
|
||||
if (root.TryGetProperty("features", out JsonElement features) && features.ValueKind == JsonValueKind.Array)
|
||||
foreach (JsonElement f in features.EnumerateArray())
|
||||
if (f.ValueKind == JsonValueKind.Object && EngineServerState.Int(f, "state") == 1) on++;
|
||||
return new ServerProfileView(
|
||||
EngineServerState.Str(root, "id"), EngineServerState.Str(root, "name"), EngineServerState.Str(root, "plugin"),
|
||||
EngineServerState.Str(root, "ruleset"), EngineServerState.Str(root, "emulator"),
|
||||
EngineServerState.Str(root, "botting"), EngineServerState.Str(root, "bottingNote"),
|
||||
EngineServerState.Str(root, "accountLimit"), EngineServerState.Bool(root, "ilt"), on);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One plain-ASCII line for a status report ("PvE, ACE; botting forbidden - ...").</summary>
|
||||
public string Summary()
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (Ruleset.Length > 0 || Emulator.Length > 0)
|
||||
parts.Add(Ruleset.Length > 0 && Emulator.Length > 0 ? Ruleset + ", " + Emulator : Ruleset + Emulator);
|
||||
if (Botting.Length > 0) parts.Add("botting " + Botting + (BottingNote.Length > 0 ? " - " + BottingNote : string.Empty));
|
||||
if (AccountLimit.Length > 0) parts.Add("accounts: " + AccountLimit);
|
||||
if (Ilt || FeaturesOn > 0) parts.Add((Ilt ? "ILT world" : "not ILT") + ", " + FeaturesOn + " Leaftide features on");
|
||||
return parts.Count == 0 ? "no details" : string.Join("; ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One salvage from a server plugin's profile "salvage" list (ServerPackInfo.Salvage): a tinkering
|
||||
/// recipe the server adds, for the Mini Remote's Crafting tab. The fields after
|
||||
/// <paramref name="NameMatch"/> are optional in the JSON; absent, a row behaves as before them.
|
||||
/// </summary>
|
||||
/// <param name="AppliedInt">"applied": an int property of the item that reads 2 once the row is on it (0 = none).</param>
|
||||
/// <param name="Prepared">"prepared": the bag must first be prepared on the chosen tier's Ammunition.</param>
|
||||
/// <param name="Order">"order": apply order (lower first); 0 = the kind-based default.</param>
|
||||
/// <param name="AfterCap">"afterCap": applied last, only once the item's tink slots are full.</param>
|
||||
/// <param name="StackGroup">"stackGroup": rows in one group share <paramref name="StackCap"/> per item ("" = none).</param>
|
||||
/// <param name="StackCap">"stackCap": the group's combined cap per item.</param>
|
||||
internal sealed record ServerSalvageView(string Bench, int Material, string Kind, string Effect, bool UsesTinkSlot, string NameMatch,
|
||||
int AppliedInt = 0, bool Prepared = false, int Order = 0, bool AfterCap = false,
|
||||
string StackGroup = "", int StackCap = 0)
|
||||
{
|
||||
/// <summary>
|
||||
/// The profile's salvage rows, read leniently: a missing list (an older plugin) is empty; a row
|
||||
/// without a bench or a material id is skipped; "slot" defaults to true, the optional fields to
|
||||
/// none (a stack group without a positive cap is no group).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<ServerSalvageView> ParseList(string? json)
|
||||
{
|
||||
var rows = new List<ServerSalvageView>();
|
||||
if (string.IsNullOrWhiteSpace(json)) return rows;
|
||||
try
|
||||
{
|
||||
using JsonDocument doc = JsonDocument.Parse(json);
|
||||
JsonElement root = doc.RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object
|
||||
|| !root.TryGetProperty("salvage", out JsonElement list) || list.ValueKind != JsonValueKind.Array)
|
||||
return rows;
|
||||
foreach (JsonElement e in list.EnumerateArray())
|
||||
{
|
||||
if (e.ValueKind != JsonValueKind.Object) continue;
|
||||
string bench = EngineServerState.Str(e, "bench").Trim().ToLowerInvariant();
|
||||
int material = EngineServerState.Int(e, "material");
|
||||
if (bench.Length == 0 || material <= 0) continue;
|
||||
string kind = EngineServerState.Str(e, "kind").Trim().ToLowerInvariant();
|
||||
bool slot = !(e.TryGetProperty("slot", out JsonElement s) && s.ValueKind == JsonValueKind.False);
|
||||
string group = EngineServerState.Str(e, "stackGroup").Trim();
|
||||
int cap = EngineServerState.Int(e, "stackCap");
|
||||
if (cap <= 0) group = string.Empty;
|
||||
rows.Add(new ServerSalvageView(bench, material, kind.Length > 0 ? kind : "tink",
|
||||
EngineServerState.Str(e, "effect"), slot, EngineServerState.Str(e, "nameMatch"),
|
||||
AppliedInt: EngineServerState.Int(e, "applied"),
|
||||
Prepared: EngineServerState.Bool(e, "prepared"),
|
||||
Order: EngineServerState.Int(e, "order"),
|
||||
AfterCap: EngineServerState.Bool(e, "afterCap"),
|
||||
StackGroup: group, StackCap: group.Length > 0 ? cap : 0));
|
||||
}
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
rows.Clear();
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
|
@ -75,12 +75,45 @@ public struct SessionStatsV1
|
|||
public double KillsPerHour;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest of the Mini Remote's session (SessionStatsMore, appended 2026-10-13): what RynthTracker's
|
||||
/// panel shows beyond <see cref="SessionStatsV1"/>, so it can show RynthAi's session whole. Blittable.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct SessionStatsMoreV1
|
||||
{
|
||||
/// <summary>XP per kill of your own kills (0 = none yet).</summary>
|
||||
public long XpPerKill;
|
||||
public int Deaths;
|
||||
/// <summary>1 at the level cap (experience can't rise).</summary>
|
||||
public int MaxLevel;
|
||||
/// <summary>Radiance (Aelrynth); 0 elsewhere.</summary>
|
||||
public long Rad;
|
||||
public double RadPerHour;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public unsafe struct RynthAiHubApiV1
|
||||
{
|
||||
public const string InterfaceName = "RynthAi.Hub";
|
||||
public const uint InterfaceVersion = 1;
|
||||
|
||||
/// <summary>
|
||||
/// The table's size up to and including SessionReset, as every RynthAi since the interface's
|
||||
/// first release fills it. Readers check StructSize against this (not sizeof, which grows as
|
||||
/// functions are appended) and check for the appended functions with <see cref="Has"/>.
|
||||
/// </summary>
|
||||
public static uint BaseStructSize => (uint)(2 * sizeof(uint) + 10 * sizeof(nint));
|
||||
|
||||
/// <summary>Whether a table RynthAi built is big enough to hold the function at <paramref name="offset"/>.</summary>
|
||||
public static bool Has(RynthAiHubApiV1* t, int offset) => t != null && t->StructSize >= (uint)(offset + sizeof(nint));
|
||||
|
||||
/// <summary>
|
||||
/// The byte offset of <see cref="SessionStatsMore"/> (for <see cref="Has"/>): the first function
|
||||
/// appended after the base table. Sequential layout of 4-byte fields and pointers has no padding.
|
||||
/// </summary>
|
||||
public static int SessionStatsMoreOffset => (int)BaseStructSize;
|
||||
|
||||
public uint Version; // InterfaceVersion of the table RynthAi filled; 0 once it has shut down
|
||||
public uint StructSize; // sizeof(RynthAiHubApiV1) as RynthAi built it
|
||||
|
||||
|
|
@ -125,4 +158,12 @@ public unsafe struct RynthAiHubApiV1
|
|||
|
||||
/// <summary>SessionReset(): starts the Mini Remote's session over (as its Reset XP button). Any thread.</summary>
|
||||
public delegate* unmanaged[Cdecl]<void> SessionReset;
|
||||
|
||||
// ── Appended 2026-10-13 (check with Has before calling) ─────────────────
|
||||
|
||||
/// <summary>
|
||||
/// SessionStatsMore(more): the rest of the same session (XP per kill, deaths, Radiance, level
|
||||
/// cap); 0 before login. RynthTracker shows RynthAi's session through this and SessionStats. Any thread.
|
||||
/// </summary>
|
||||
public delegate* unmanaged[Cdecl]<SessionStatsMoreV1*, int> SessionStatsMore;
|
||||
}
|
||||
|
|
|
|||
100
Plugins/Shared/RynthAiSessionClient.cs
Normal file
100
Plugins/Shared/RynthAiSessionClient.cs
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/RynthAiSessionClient.cs
|
||||
// A read-only reader of RynthAi's session stats through the "RynthAi.Hub" interface
|
||||
// (Shared/RynthAiHubApi.cs, SessionStats / SessionReset). Since 2026-10-13 RynthAi's
|
||||
// session is the one XP / luminance / kills session every tracker shows: the Mini Remote's
|
||||
// Session Stats, RynthOracle's Character tab, RynthILT's rates and RynthTracker (which
|
||||
// falls back to its own session only when RynthAi isn't loaded).
|
||||
// Linked into each reader (with RynthAiHubApi.cs); pure lookup, no state beyond the table.
|
||||
//
|
||||
// The table is looked up through the host (API v68) at most every RecheckMs, and again at
|
||||
// once when RynthAi has shut down (Version 0): RynthAi loading later, reloading or missing
|
||||
// are all handled, every call then just answers "no session". Pump thread.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>RynthAi's session stats for another plugin (pump thread).</summary>
|
||||
public sealed unsafe class RynthAiSessionClient
|
||||
{
|
||||
private const long RecheckMs = 3000;
|
||||
|
||||
private RynthAiHubApiV1* _table;
|
||||
private long _nextQueryAt;
|
||||
|
||||
/// <summary>RynthAi answered with its hub table (last lookup).</summary>
|
||||
public bool Connected => _table != null && _table->Version >= 1;
|
||||
|
||||
/// <summary>Forget the table; the next call looks it up again (login, logout).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
_table = null;
|
||||
_nextQueryAt = 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RynthAi's session now. False without RynthAi, before its login or before it has a session,
|
||||
/// so the caller can fall back to its own count.
|
||||
/// </summary>
|
||||
public bool TryGet(RynthCoreHost host, long now, out SessionStatsV1 stats)
|
||||
{
|
||||
stats = default;
|
||||
RynthAiHubApiV1* t = Table(host, now);
|
||||
if (t == null || t->SessionStats == null) return false;
|
||||
SessionStatsV1 s = default;
|
||||
try
|
||||
{
|
||||
if (t->SessionStats(&s) == 0) return false;
|
||||
}
|
||||
catch { return false; }
|
||||
if (s.StartUtcTicks <= 0) return false;
|
||||
stats = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Starts RynthAi's session over (its Reset XP button). False without RynthAi.</summary>
|
||||
public bool ResetSession(RynthCoreHost host, long now)
|
||||
{
|
||||
RynthAiHubApiV1* t = Table(host, now);
|
||||
if (t == null || t->SessionReset == null) return false;
|
||||
try { t->SessionReset(); }
|
||||
catch { return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The table, re-queried when it is missing or RynthAi has shut down (Version 0).</summary>
|
||||
private RynthAiHubApiV1* Table(RynthCoreHost host, long now)
|
||||
{
|
||||
if (_table != null && _table->Version >= 1) return _table;
|
||||
_table = null;
|
||||
if (now < _nextQueryAt || !host.HasGetPluginInterface) return null;
|
||||
_nextQueryAt = now + RecheckMs;
|
||||
var p = (RynthAiHubApiV1*)host.GetPluginInterface(RynthAiHub.PluginName, RynthAiHubApiV1.InterfaceName, RynthAiHubApiV1.InterfaceVersion);
|
||||
// The base size, not sizeof: an older RynthAi without the appended functions still gives SessionStats.
|
||||
if (p != null && p->Version >= 1 && p->StructSize >= RynthAiHubApiV1.BaseStructSize)
|
||||
_table = p;
|
||||
return _table;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The rest of RynthAi's session (XP per kill, deaths, Radiance, level cap). False without
|
||||
/// RynthAi, before its login, or from a RynthAi older than SessionStatsMore (2026-10-13).
|
||||
/// </summary>
|
||||
public bool TryGetMore(RynthCoreHost host, long now, out SessionStatsMoreV1 more)
|
||||
{
|
||||
more = default;
|
||||
RynthAiHubApiV1* t = Table(host, now);
|
||||
if (!RynthAiHubApiV1.Has(t, RynthAiHubApiV1.SessionStatsMoreOffset) || t->SessionStatsMore == null) return false;
|
||||
SessionStatsMoreV1 m = default;
|
||||
try
|
||||
{
|
||||
if (t->SessionStatsMore(&m) == 0) return false;
|
||||
}
|
||||
catch { return false; }
|
||||
more = m;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
582
Plugins/Shared/RynthIltDataApi.cs
Normal file
582
Plugins/Shared/RynthIltDataApi.cs
Normal file
|
|
@ -0,0 +1,582 @@
|
|||
// ============================================================================
|
||||
// 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 (SilentKelpie's RynthOracle Character
|
||||
// tab and RynthInventory Global Inventory "Banking" tab read it; neither is in this tree yet):
|
||||
// - 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 (no plugin in
|
||||
// this tree reads it yet). 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).
|
||||
// ============================================================================
|
||||
|
||||
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 = 2;
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/// <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 >= (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>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;
|
||||
}
|
||||
}
|
||||
|
|
@ -46,6 +46,11 @@ public static class RynthIltHub
|
|||
public const string SectionQuestBonus = "quests-qb";
|
||||
/// <summary>Pets tab: the /pets and /shinies logs.</summary>
|
||||
public const string SectionPetLogs = "pets-logs";
|
||||
/// <summary>
|
||||
/// Pets tab, Breeding sub-tab: the pet breeding tracker, the sub-tab's whole body (RynthILT 0.3.1+;
|
||||
/// older copies draw nothing). RynthAi shows the sub-tab on an ILT world unless FeaturePetBreeding is off.
|
||||
/// </summary>
|
||||
public const string SectionPetBreeding = "pets-breeding";
|
||||
/// <summary>Mini Remote menu, under Infinite Leaftide: why no ILT feature is on, the Force-ILT override, Refresh.</summary>
|
||||
public const string SectionIltStatus = "ilt-status";
|
||||
/// <summary>Mini Remote menu without RynthCore's server list: RynthILT's own Infinite Leaftide items.</summary>
|
||||
|
|
@ -56,6 +61,8 @@ public static class RynthIltHub
|
|||
public const string FeaturePetRefill = "pet_refill";
|
||||
public const string FeatureUniversalMastery = "universal_mastery";
|
||||
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";
|
||||
}
|
||||
|
||||
/// <summary>One ILT tab as GetTabs hands it out. Blittable.</summary>
|
||||
|
|
|
|||
80
Plugins/Shared/RynthServerProfileApi.cs
Normal file
80
Plugins/Shared/RynthServerProfileApi.cs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/RynthServerProfileApi.cs
|
||||
// The "RynthServer.Profile" interface: what a server plugin (RynthColdeve,
|
||||
// RynthConquest, ... - Plugins/Shared/ServerPack) knows about its game server,
|
||||
// for any plugin that wants the server's settings without drawing the card.
|
||||
// RynthCore says which server is active and which plugin owns it (plugin API
|
||||
// v86, GetServerStateJson: "active", "activePlugin"); the reader then asks that
|
||||
// plugin for this interface (host GetPluginInterface). RynthILT answers it too,
|
||||
// for "ilt" (RynthILT/ProfileInterface.cs).
|
||||
// Compiled into the server plugins, RynthILT and their 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 the plugin and never freed;
|
||||
// shutdown sets Version to 0, and a reader re-queries when it sees that.
|
||||
//
|
||||
// GetProfileJson payload (schema 1; read leniently, fields may be added):
|
||||
// {
|
||||
// "schema": 1, "id": "coldeve", "name": "Coldeve", "plugin": "RynthColdeve",
|
||||
// "version": "0.1.3",
|
||||
// "active": true, // RynthCore's verdict (or the world name before one)
|
||||
// "world": "Coldeve", // the world name the client reports ("" before login)
|
||||
// "hosts": [ "play.coldeve.ac" ], "worldNames": [ "Coldeve" ],
|
||||
// "port": 9000, "emulator": "ACE", "ruleset": "PvE", "status": "Stable",
|
||||
// "botting": "unknown|allowed|restricted|forbidden", "bottingNote": "",
|
||||
// "accountLimit": "", "summary": "",
|
||||
// "facts": [ "..." ], "commands": [ { "command": "/x", "what": "..." } ],
|
||||
// "salvage": [ { // the server's own tinkering (the Mini Remote's Crafting tab)
|
||||
// "bench": "melee", // armor, melee, missile, caster, jewelry, items, trinkets
|
||||
// "material": 52, "kind": "tink|imbue|once", "effect": "...",
|
||||
// "slot": true, // counts toward the item's 10 tinks
|
||||
// "nameMatch": "", // the bag's name must contain this
|
||||
// // optional (absent = off / the default):
|
||||
// "applied": 370, // item int that reads 2 once the row is on it
|
||||
// "prepared": true, // the bag is first prepared on the tier's Ammunition
|
||||
// "order": 10, // apply order, lower first (else imbue, tink, once)
|
||||
// "afterCap": true, // last, only once the item's tink slots are full
|
||||
// "stackGroup": "x", "stackCap": 10 // rows of one group share this cap per item
|
||||
// } ],
|
||||
// "discord": "", "website": "", "wiki": "", "source": ""
|
||||
// }
|
||||
// ============================================================================
|
||||
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>Constants of the "RynthServer.Profile" interface.</summary>
|
||||
public static class RynthServerProfile
|
||||
{
|
||||
/// <summary>The profile JSON's schema.</summary>
|
||||
public const int Schema = 1;
|
||||
|
||||
/// <summary>"botting" values in the profile JSON.</summary>
|
||||
public const string BottingUnknown = "unknown";
|
||||
public const string BottingAllowed = "allowed";
|
||||
public const string BottingRestricted = "restricted";
|
||||
public const string BottingForbidden = "forbidden";
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public unsafe struct RynthServerProfileApiV1
|
||||
{
|
||||
public const string InterfaceName = "RynthServer.Profile";
|
||||
public const uint InterfaceVersion = 1;
|
||||
|
||||
public uint Version; // InterfaceVersion of the table the plugin filled; 0 once it has shut down
|
||||
public uint StructSize; // sizeof(RynthServerProfileApiV1) as the plugin 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 (the plugin is shutting down). Any thread.
|
||||
/// </summary>
|
||||
public delegate* unmanaged[Cdecl]<byte*, int, int> GetProfileJson;
|
||||
}
|
||||
45
Plugins/Shared/SafeImGui.cs
Normal file
45
Plugins/Shared/SafeImGui.cs
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/SafeImGui.cs
|
||||
// ImGui text calls for text that isn't a literal: chat lines, item and player
|
||||
// names, server replies, settings values, interpolated strings.
|
||||
//
|
||||
// ImGui.NET passes the string of Text / TextColored / TextWrapped /
|
||||
// TextDisabled / BulletText / SetTooltip / SetItemTooltip / LabelText to
|
||||
// native ImGui as a printf format with no arguments, so a '%' in it reads
|
||||
// arguments that were never passed (garbage, or a crash on %s / %n). These
|
||||
// wrappers double every '%' so the text draws exactly as given. Same
|
||||
// signatures as ImGui's, so a call site only changes "ImGui." to "SafeImGui.".
|
||||
// Compiled into each plugin that draws (linked source). Render thread only.
|
||||
// ============================================================================
|
||||
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal static class SafeImGui
|
||||
{
|
||||
/// <summary>The text as a printf format that prints it unchanged ('%' doubled); null is empty.</summary>
|
||||
internal static string Escape(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return string.Empty;
|
||||
return text.IndexOf('%') < 0 ? text : text.Replace("%", "%%");
|
||||
}
|
||||
|
||||
public static void Text(string? text) => ImGui.Text(Escape(text));
|
||||
|
||||
public static void TextColored(Vector4 color, string? text) => ImGui.TextColored(color, Escape(text));
|
||||
|
||||
public static void TextWrapped(string? text) => ImGui.TextWrapped(Escape(text));
|
||||
|
||||
public static void TextDisabled(string? text) => ImGui.TextDisabled(Escape(text));
|
||||
|
||||
public static void BulletText(string? text) => ImGui.BulletText(Escape(text));
|
||||
|
||||
public static void SetTooltip(string? text) => ImGui.SetTooltip(Escape(text));
|
||||
|
||||
public static void SetItemTooltip(string? text) => ImGui.SetItemTooltip(Escape(text));
|
||||
|
||||
/// <summary>The label is drawn as text, not used as a format; only the value is escaped.</summary>
|
||||
public static void LabelText(string label, string? text) => ImGui.LabelText(label, Escape(text));
|
||||
}
|
||||
95
Plugins/Shared/ServerCommandPanel.cs
Normal file
95
Plugins/Shared/ServerCommandPanel.cs
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ServerCommandPanel.cs
|
||||
// Draws a ServerCommandSet (ServerCommandShare.cs) as buttons: one name box for the
|
||||
// commands that take an argument, then a wrapped row of buttons. A command flagged 'c'
|
||||
// turns its button into "Confirm ..." on the first click and runs on the second (within
|
||||
// ConfirmMs). Clicks hand the chat line to the caller's send, which runs it on the plugin
|
||||
// tick. Compiled into each plugin that draws server commands. Render thread only.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Numerics;
|
||||
using ImGuiNET;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal sealed class ServerCommandPanel
|
||||
{
|
||||
private const long ConfirmMs = 4000;
|
||||
|
||||
private static readonly Vector4 ColConfirm = new(0.95f, 0.45f, 0.35f, 1f);
|
||||
|
||||
private readonly string _id;
|
||||
private string _argument = string.Empty;
|
||||
// The command waiting for its second click, and when that offer ends.
|
||||
private string _armed = string.Empty;
|
||||
private long _armedUntil;
|
||||
private string _lastSent = string.Empty;
|
||||
|
||||
/// <param name="id">ImGui id suffix; unique per panel drawn in the same window.</param>
|
||||
public ServerCommandPanel(string id) => _id = id;
|
||||
|
||||
/// <summary>
|
||||
/// Draws <paramref name="set"/>'s commands into the current window. <paramref name="send"/>
|
||||
/// gets the chat line (it should queue it, not run it here) and returns false when it can't.
|
||||
/// </summary>
|
||||
public void Render(ServerCommandSet set, Func<string, bool> send, string argumentHint = "name (blank = selected player)")
|
||||
{
|
||||
if (set.Commands.Count == 0) return;
|
||||
long now = Environment.TickCount64;
|
||||
if (_armed.Length > 0 && now > _armedUntil) _armed = string.Empty;
|
||||
|
||||
bool anyArgument = false;
|
||||
foreach (ServerCommand c in set.Commands)
|
||||
if (c.TakesArgument) { anyArgument = true; break; }
|
||||
if (anyArgument)
|
||||
{
|
||||
ImGui.SetNextItemWidth(MathF.Min(260f, ImGui.GetContentRegionAvail().X));
|
||||
ImGui.InputTextWithHint("##scarg" + _id, argumentHint, ref _argument, (uint)ServerCommandShare.MaxArgument);
|
||||
}
|
||||
|
||||
ImGuiStylePtr style = ImGui.GetStyle();
|
||||
// The row's right edge, taken at the start of a line (ImGui 1.91 has no GetWindowContentRegionMax).
|
||||
float right = ImGui.GetCursorScreenPos().X + ImGui.GetContentRegionAvail().X;
|
||||
for (int i = 0; i < set.Commands.Count; i++)
|
||||
{
|
||||
ServerCommand c = set.Commands[i];
|
||||
bool armed = c.Confirm && _armed == c.Command;
|
||||
string label = armed ? "Confirm " + c.Label + "?" : c.Label;
|
||||
|
||||
// Wraps to a new line when this button wouldn't fit after the previous one.
|
||||
if (i > 0)
|
||||
{
|
||||
float width = ImGui.CalcTextSize(label).X + style.FramePadding.X * 2f;
|
||||
float lastRight = ImGui.GetItemRectMax().X;
|
||||
if (lastRight + style.ItemSpacing.X + width <= right) ImGui.SameLine();
|
||||
}
|
||||
|
||||
string? line = ServerCommandShare.Compose(c, _argument);
|
||||
bool disabled = line == null;
|
||||
if (disabled) ImGui.BeginDisabled();
|
||||
if (armed) ImGui.PushStyleColor(ImGuiCol.Text, ColConfirm);
|
||||
bool clicked = ImGui.Button(label + "##sc" + _id + i);
|
||||
if (armed) ImGui.PopStyleColor();
|
||||
if (disabled) ImGui.EndDisabled();
|
||||
|
||||
if (ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled))
|
||||
{
|
||||
string preview = line ?? "Type a name first.";
|
||||
SafeImGui.SetTooltip(c.Tooltip.Length > 0 ? c.Tooltip + "\n\n" + preview : preview);
|
||||
}
|
||||
if (!clicked || line == null) continue;
|
||||
|
||||
if (c.Confirm && !armed)
|
||||
{
|
||||
_armed = c.Command;
|
||||
_armedUntil = now + ConfirmMs;
|
||||
continue;
|
||||
}
|
||||
_armed = string.Empty;
|
||||
_lastSent = send(line) ? "Sent: " + line : "Couldn't send: " + line;
|
||||
}
|
||||
|
||||
if (_lastSent.Length > 0) SafeImGui.TextDisabled(_lastSent);
|
||||
}
|
||||
}
|
||||
184
Plugins/Shared/ServerCommandShare.cs
Normal file
184
Plugins/Shared/ServerCommandShare.cs
Normal file
|
|
@ -0,0 +1,184 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ServerCommandShare.cs
|
||||
// Server chat commands one plugin hands another for a RynthCore section, through the
|
||||
// plugin-command broker (Host.SendPluginCommand, action "servercommands").
|
||||
//
|
||||
// A server plugin (RynthILT for Infinite Leaftide's /fship) knows its server's extra
|
||||
// commands and keeps them as a ServerCommandSet; it draws them itself (ServerCommandPanel.cs).
|
||||
// For another plugin's view of that section (SilentKelpie's RynthAi Fellowship tab, not in
|
||||
// this tree yet) the sender re-sends every few seconds while its server is active and sends
|
||||
// an empty list when it isn't, so the receiver drops a list that stops arriving (the sender
|
||||
// unloaded).
|
||||
//
|
||||
// Payload: ANSI text, one record per line, fields split by tabs:
|
||||
// S <tab> section <tab> serverId <tab> serverName
|
||||
// C <tab> label <tab> command <tab> flags <tab> tooltip (0..MaxCommands lines)
|
||||
// Flags: 'a' takes an optional argument, 'A' needs one, 'c' asks before it runs.
|
||||
// The receiver checks every field again: a command is one /word line of printable text.
|
||||
// Pure (no ImGui, no host); compiled into each plugin that uses it and into the tests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
/// <summary>One server command: a button label, the chat command and how it takes an argument.</summary>
|
||||
internal sealed record ServerCommand(string Label, string Command, string Flags, string Tooltip)
|
||||
{
|
||||
/// <summary>True when the command can take an argument (the name box).</summary>
|
||||
public bool TakesArgument => Flags.IndexOf('a') >= 0 || Flags.IndexOf('A') >= 0;
|
||||
|
||||
/// <summary>True when the command can't run without an argument.</summary>
|
||||
public bool NeedsArgument => Flags.IndexOf('A') >= 0;
|
||||
|
||||
/// <summary>True when a click asks before running (the second click runs it).</summary>
|
||||
public bool Confirm => Flags.IndexOf('c') >= 0;
|
||||
}
|
||||
|
||||
/// <summary>The commands one server plugin gives a section; empty Commands means none.</summary>
|
||||
internal sealed record ServerCommandSet(string Section, string ServerId, string ServerName, IReadOnlyList<ServerCommand> Commands);
|
||||
|
||||
internal static class ServerCommandShare
|
||||
{
|
||||
/// <summary>The broker action the receiver handles.</summary>
|
||||
public const string Action = "servercommands";
|
||||
|
||||
/// <summary>Most commands a set carries.</summary>
|
||||
public const int MaxCommands = 24;
|
||||
|
||||
/// <summary>Longest section id, server id and flags field.</summary>
|
||||
public const int MaxId = 32;
|
||||
|
||||
/// <summary>Longest label and server name.</summary>
|
||||
public const int MaxLabel = 48;
|
||||
|
||||
/// <summary>Longest command (before its argument).</summary>
|
||||
public const int MaxCommand = 96;
|
||||
|
||||
/// <summary>Longest tooltip.</summary>
|
||||
public const int MaxTooltip = 300;
|
||||
|
||||
/// <summary>Longest argument (a player or fellowship name).</summary>
|
||||
public const int MaxArgument = 64;
|
||||
|
||||
/// <summary>The payload for <paramref name="set"/>; commands that don't pass <see cref="IsValid"/> are left out.</summary>
|
||||
public static string Build(ServerCommandSet set)
|
||||
{
|
||||
var sb = new StringBuilder(256);
|
||||
sb.Append('S').Append('\t').Append(Clean(set.Section, MaxId))
|
||||
.Append('\t').Append(Clean(set.ServerId, MaxId))
|
||||
.Append('\t').Append(Clean(set.ServerName, MaxLabel)).Append('\n');
|
||||
int n = 0;
|
||||
foreach (ServerCommand c in set.Commands)
|
||||
{
|
||||
if (n >= MaxCommands) break;
|
||||
ServerCommand clean = Normalize(c);
|
||||
if (!IsValid(clean)) continue;
|
||||
sb.Append('C').Append('\t').Append(clean.Label)
|
||||
.Append('\t').Append(clean.Command)
|
||||
.Append('\t').Append(clean.Flags)
|
||||
.Append('\t').Append(clean.Tooltip).Append('\n');
|
||||
n++;
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The set in <paramref name="payload"/>, or null when it has no S line with a section.
|
||||
/// Bad C lines are skipped; at most <see cref="MaxCommands"/> are kept.
|
||||
/// </summary>
|
||||
public static ServerCommandSet? Parse(string? payload)
|
||||
{
|
||||
if (string.IsNullOrEmpty(payload) || payload.Length > 32_768) return null;
|
||||
string section = string.Empty, serverId = string.Empty, serverName = string.Empty;
|
||||
bool haveHeader = false;
|
||||
var commands = new List<ServerCommand>();
|
||||
foreach (string raw in payload.Split('\n'))
|
||||
{
|
||||
string line = raw.TrimEnd('\r');
|
||||
if (line.Length < 2 || line[1] != '\t') continue;
|
||||
string[] f = line.Split('\t');
|
||||
if (line[0] == 'S' && !haveHeader && f.Length >= 4)
|
||||
{
|
||||
section = Clean(f[1], MaxId).ToLowerInvariant();
|
||||
serverId = Clean(f[2], MaxId).ToLowerInvariant();
|
||||
serverName = Clean(f[3], MaxLabel);
|
||||
haveHeader = section.Length > 0;
|
||||
}
|
||||
else if (line[0] == 'C' && f.Length >= 5 && commands.Count < MaxCommands)
|
||||
{
|
||||
ServerCommand c = Normalize(new ServerCommand(f[1], f[2], f[3], f[4]));
|
||||
if (IsValid(c)) commands.Add(c);
|
||||
}
|
||||
}
|
||||
return haveHeader ? new ServerCommandSet(section, serverId, serverName, commands) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// True when <paramref name="c"/> (normalized) can run: a label, and a command that is one
|
||||
/// "/word ..." line of printable text with no quotes.
|
||||
/// </summary>
|
||||
public static bool IsValid(ServerCommand c)
|
||||
{
|
||||
if (c.Label.Length == 0 || c.Command.Length < 2 || c.Command.Length > MaxCommand) return false;
|
||||
if (c.Command[0] != '/' || !char.IsLetter(c.Command[1])) return false;
|
||||
foreach (char ch in c.Command)
|
||||
if (char.IsControl(ch) || ch == '"') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chat line for <paramref name="c"/> with <paramref name="argument"/>, or null when the
|
||||
/// command needs an argument and has none. A multi-word argument is quoted (ACE's command
|
||||
/// parser joins "two words"); quotes inside it are dropped.
|
||||
/// </summary>
|
||||
public static string? Compose(ServerCommand c, string? argument)
|
||||
{
|
||||
string arg = CleanArgument(argument);
|
||||
if (arg.Length == 0) return c.NeedsArgument ? null : c.Command;
|
||||
if (!c.TakesArgument) return c.Command;
|
||||
return c.Command + " " + (arg.IndexOf(' ') >= 0 ? "\"" + arg + "\"" : arg);
|
||||
}
|
||||
|
||||
/// <summary>The argument with control characters and quotes removed, spaces collapsed and trimmed, at most <see cref="MaxArgument"/> characters.</summary>
|
||||
public static string CleanArgument(string? argument)
|
||||
{
|
||||
if (string.IsNullOrEmpty(argument)) return string.Empty;
|
||||
var sb = new StringBuilder(argument.Length);
|
||||
bool space = false;
|
||||
foreach (char ch in argument)
|
||||
{
|
||||
if (char.IsControl(ch) || ch == '"') continue;
|
||||
if (char.IsWhiteSpace(ch)) { space = sb.Length > 0; continue; }
|
||||
if (space) { sb.Append(' '); space = false; }
|
||||
sb.Append(ch);
|
||||
if (sb.Length >= MaxArgument) break;
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>One field: tabs, newlines and control characters become spaces, trimmed, cut to <paramref name="max"/>.</summary>
|
||||
public static string Clean(string? text, int max)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return string.Empty;
|
||||
var sb = new StringBuilder(Math.Min(text.Length, max));
|
||||
foreach (char ch in text)
|
||||
{
|
||||
sb.Append(char.IsControl(ch) ? ' ' : ch);
|
||||
if (sb.Length >= max) break;
|
||||
}
|
||||
return sb.ToString().Trim();
|
||||
}
|
||||
|
||||
// Every field cleaned; flags keep only the known letters. The command is cut one past its
|
||||
// limit so an over-long one fails IsValid instead of running cut short.
|
||||
private static ServerCommand Normalize(ServerCommand c)
|
||||
{
|
||||
var flags = new StringBuilder(4);
|
||||
foreach (char ch in c.Flags ?? string.Empty)
|
||||
if ((ch == 'a' || ch == 'A' || ch == 'c') && flags.ToString().IndexOf(ch) < 0) flags.Append(ch);
|
||||
return new ServerCommand(Clean(c.Label, MaxLabel), Clean(c.Command, MaxCommand + 1), flags.ToString(), Clean(c.Tooltip, MaxTooltip));
|
||||
}
|
||||
}
|
||||
145
Plugins/Shared/ServerPack/ServerPackExports.cs
Normal file
145
Plugins/Shared/ServerPack/ServerPackExports.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// 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.
|
||||
/// </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);
|
||||
|
||||
/// <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-<id>" (":popout" added in a popped-out
|
||||
/// window) draws the server card into the engine's current window. 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];
|
||||
if (!name.Equals(ServerPackPlugin.SettingsSurface, StringComparison.Ordinal)) return 0;
|
||||
var plugin = Runtime.Plugin;
|
||||
if (plugin == null || !plugin.RenderEmbeddedCard(out float 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; }
|
||||
}
|
||||
}
|
||||
103
Plugins/Shared/ServerPack/ServerPackInfo.cs
Normal file
103
Plugins/Shared/ServerPack/ServerPackInfo.cs
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
// 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>"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),
|
||||
};
|
||||
}
|
||||
86
Plugins/Shared/ServerPack/ServerPackInterface.cs
Normal file
86
Plugins/Shared/ServerPack/ServerPackInterface.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
// 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).
|
||||
//
|
||||
// The table is allocated once per loaded copy of the plugin and never freed (a plugin DLL is never
|
||||
// unloaded); after Release() it reports Version 0 and GetProfileJson answers 0. Before the plugin is
|
||||
// up, or between characters, the profile still describes the server (active false, no world).
|
||||
using System;
|
||||
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 volatile bool _released;
|
||||
|
||||
/// <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, 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 != 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>Plugin shutdown: readers see Version 0 and re-query; GetProfileJson answers 0.</summary>
|
||||
public static void Release()
|
||||
{
|
||||
_released = true;
|
||||
if (_table != null) _table->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;
|
||||
Snapshot? last = Volatile.Read(ref _last);
|
||||
if (last != null && last.Active == active && last.World == world) return last.Json;
|
||||
string json = ServerPackProfile.BuildJson(info, RynthPluginInfo.Name, RynthPluginInfo.Version, active, world);
|
||||
Volatile.Write(ref _last, new Snapshot(active, world, 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).
|
||||
/// </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;
|
||||
}
|
||||
}
|
||||
224
Plugins/Shared/ServerPack/ServerPackModel.cs
Normal file
224
Plugins/Shared/ServerPack/ServerPackModel.cs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
// 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.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.
|
||||
/// </summary>
|
||||
public static string BuildSectionsJson(ServerPackInfo info, string pluginName)
|
||||
{
|
||||
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}]}");
|
||||
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 + ".",
|
||||
};
|
||||
}
|
||||
276
Plugins/Shared/ServerPack/ServerPackPlugin.cs
Normal file
276
Plugins/Shared/ServerPack/ServerPackPlugin.cs
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
// 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.
|
||||
//
|
||||
// Threads: OnTick, login/logout and the engine's export calls run on the plugin pump. OnChatBarEnter
|
||||
// runs on AC's main thread, so it only queues. The card draws on the render thread (OnRender,
|
||||
// RynthPluginRenderEmbed) and queues its commands for the tick.
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
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;
|
||||
// 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();
|
||||
private volatile bool _loginComplete;
|
||||
private volatile string? _world;
|
||||
private bool _wasActive;
|
||||
|
||||
public ServerPackPlugin()
|
||||
{
|
||||
ServerPackInfo info = ServerData.Create();
|
||||
_model = new ServerPackModel(info);
|
||||
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world);
|
||||
_sectionsJson = ServerPackModel.BuildSectionsJson(info, RynthPluginInfo.Name);
|
||||
}
|
||||
|
||||
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 <verb> ..." verbs the shared code doesn't know; set handled to stop the help text.</summary>
|
||||
partial void ServerChatCommand(string[] parts, ref bool handled);
|
||||
/// <summary>Extra lines for "/rserver info".</summary>
|
||||
partial void ServerInfoLines(Action<string> line);
|
||||
|
||||
public override int Initialize()
|
||||
{
|
||||
Host.Log($"[{RynthPluginInfo.Name}] Plugin initialized for {Info.Name} ({Info.Id}).");
|
||||
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 _)) { }
|
||||
_model.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);
|
||||
}
|
||||
|
||||
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-<id>": 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)
|
||||
{
|
||||
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();
|
||||
_ui.RenderBody();
|
||||
wantHeight = MathF.Max(40f, ImGui.GetCursorPosY() - startY + 4f);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Host.Log($"[{RynthPluginInfo.Name}] Server card failed: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally { ImGui.SetCurrentContext(previous); }
|
||||
}
|
||||
|
||||
// ── Commands ─────────────────────────────────────────────────────────
|
||||
|
||||
public override void OnChatBarEnter(string? text, ref int eat)
|
||||
{
|
||||
if (!_loginComplete || string.IsNullOrEmpty(text)) return;
|
||||
string trimmed = text.Trim();
|
||||
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 static bool IsVerb(string word) =>
|
||||
word.ToLowerInvariant() is "show" or "hide" or "toggle" or "info" or "help" or "on" or "off" or "auto";
|
||||
|
||||
/// <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);
|
||||
}
|
||||
}
|
||||
145
Plugins/Shared/ServerPack/ServerPackProfile.cs
Normal file
145
Plugins/Shared/ServerPack/ServerPackProfile.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// 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.Text;
|
||||
|
||||
namespace RynthCore.Plugin.ServerPack;
|
||||
|
||||
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.
|
||||
/// </summary>
|
||||
public static string BuildJson(ServerPackInfo info, string pluginName, string pluginVersion, bool active, string? world)
|
||||
{
|
||||
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(']');
|
||||
Field(sb, "discord", info.Discord);
|
||||
Field(sb, "website", info.Website);
|
||||
Field(sb, "wiki", info.Wiki);
|
||||
Field(sb, "source", info.Source);
|
||||
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('"');
|
||||
}
|
||||
}
|
||||
217
Plugins/Shared/ServerPack/ServerPackUi.cs
Normal file
217
Plugins/Shared/ServerPack/ServerPackUi.cs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
// 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.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 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>
|
||||
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world)
|
||||
{
|
||||
_model = model;
|
||||
_pluginLabel = pluginLabel;
|
||||
_world = world;
|
||||
_windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id;
|
||||
}
|
||||
|
||||
/// <summary>The standalone window, while open.</summary>
|
||||
public void RenderWindow()
|
||||
{
|
||||
if (!WindowOpen) return;
|
||||
ImGui.SetNextWindowSize(new Vector2(460, 520), ImGuiCond.FirstUseEver);
|
||||
bool open = WindowOpen;
|
||||
if (ImGui.Begin(_windowTitle, ref open)) RenderBody();
|
||||
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;
|
||||
}
|
||||
}
|
||||
72
Plugins/Shared/ServerPack/ServerPlugin.props
Normal file
72
Plugins/Shared/ServerPack/ServerPlugin.props
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<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, ...), so the shared code stays the same for all.
|
||||
-->
|
||||
<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="$(MSBuildThisFileDirectory)..\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInfo.cs" Link="ServerPack\ServerPackInfo.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackModel.cs" Link="ServerPack\ServerPackModel.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="$(MSBuildThisFileDirectory)..\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackProfile.cs" Link="ServerPack\ServerPackProfile.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" />
|
||||
</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>
|
||||
145
Plugins/Shared/ServerStateClient.cs
Normal file
145
Plugins/Shared/ServerStateClient.cs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
// ============================================================================
|
||||
// RynthSuite - Plugins/Shared/ServerStateClient.cs
|
||||
// A plugin's live view of "which server is this, and what are its settings":
|
||||
// 1. RynthCore's server list (plugin API v86 GetServerStateJson, parsed by
|
||||
// EngineServerState.cs): the active server, overrides and the Diagnostics
|
||||
// pick included, and the plugin that owns it;
|
||||
// 2. that plugin's profile JSON through "RynthServer.Profile"
|
||||
// (RynthServerProfileApi.cs): a server plugin for its server, RynthILT
|
||||
// for "ilt".
|
||||
// Both are polled (every 2 s, cheap when not due) and Revision goes up when
|
||||
// either changes, so a reader re-applies its server-specific state then.
|
||||
//
|
||||
// Needs, linked into the reader: EngineServerState.cs, RynthServerProfileApi.cs.
|
||||
// Engines older than v86 report Supported = false (the reader keeps its own
|
||||
// detection).
|
||||
// Pump thread only.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Text;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.Shared;
|
||||
|
||||
internal sealed unsafe class ServerStateClient
|
||||
{
|
||||
private const long PollMs = 2000;
|
||||
private const long RequeryMs = 10_000;
|
||||
private const int MaxBuffer = 512 * 1024;
|
||||
|
||||
private long _nextPollAt, _nextQueryAt;
|
||||
private string _stateJson = string.Empty;
|
||||
// The owner's "RynthServer.Profile" table.
|
||||
private string _tableOwner = string.Empty;
|
||||
private uint* _tableVersion;
|
||||
private delegate* unmanaged[Cdecl]<byte*, int, int> _getProfileJson;
|
||||
private byte[] _buffer = new byte[4096];
|
||||
|
||||
/// <summary>The engine has GetServerStateJson (API v86+). False until the first poll.</summary>
|
||||
public bool Supported { get; private set; }
|
||||
/// <summary>The engine's server list, null before the first answer (or without v86).</summary>
|
||||
public EngineServerState? State { get; private set; }
|
||||
/// <summary>The active server owner's profile JSON ("" when none is active, or its plugin has none).</summary>
|
||||
public string ProfileJson { get; private set; } = string.Empty;
|
||||
/// <summary>The plugin <see cref="ProfileJson"/> came from ("" with none).</summary>
|
||||
public string ProfilePlugin { get; private set; } = string.Empty;
|
||||
/// <summary>Goes up whenever <see cref="State"/> or <see cref="ProfileJson"/> changes.</summary>
|
||||
public int Revision { get; private set; }
|
||||
|
||||
/// <summary>Logout: forget everything; the next poll reads fresh.</summary>
|
||||
public void Clear()
|
||||
{
|
||||
_nextPollAt = 0;
|
||||
_nextQueryAt = 0;
|
||||
DropTable();
|
||||
bool changed = State != null || ProfileJson.Length > 0;
|
||||
_stateJson = string.Empty;
|
||||
State = null;
|
||||
ProfileJson = ProfilePlugin = string.Empty;
|
||||
if (changed) Revision++;
|
||||
}
|
||||
|
||||
/// <summary>Polls when due; <paramref name="force"/> polls now (login). Pump thread.</summary>
|
||||
public void Poll(RynthCoreHost host, long now, bool force = false)
|
||||
{
|
||||
if (!force && now < _nextPollAt) return;
|
||||
_nextPollAt = now + PollMs;
|
||||
|
||||
Supported = host.HasGetServerStateJson;
|
||||
bool changed = false;
|
||||
string json = Supported && host.TryGetServerStateJson(out string j) ? j : string.Empty;
|
||||
if (json != _stateJson)
|
||||
{
|
||||
_stateJson = json;
|
||||
State = EngineServerState.Parse(json);
|
||||
changed = true;
|
||||
}
|
||||
|
||||
string owner = State?.ActivePlugin ?? string.Empty;
|
||||
string profile = owner.Length > 0 ? ReadProfile(host, owner, now) : string.Empty;
|
||||
if (owner.Length == 0) DropTable();
|
||||
if (profile != ProfileJson)
|
||||
{
|
||||
ProfileJson = profile;
|
||||
changed = true;
|
||||
}
|
||||
ProfilePlugin = profile.Length > 0 ? owner : string.Empty;
|
||||
if (changed) Revision++;
|
||||
}
|
||||
|
||||
/// <summary>The owner's profile JSON, querying (or re-querying) its table as needed.</summary>
|
||||
private string ReadProfile(RynthCoreHost host, string owner, long now)
|
||||
{
|
||||
if (!owner.Equals(_tableOwner, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
DropTable();
|
||||
_tableOwner = owner;
|
||||
_nextQueryAt = 0;
|
||||
}
|
||||
if (_tableVersion != null && *_tableVersion == 0) DropTableKeepOwner();
|
||||
if (_getProfileJson == null)
|
||||
{
|
||||
if (now < _nextQueryAt || !host.HasGetPluginInterface) return string.Empty;
|
||||
_nextQueryAt = now + RequeryMs;
|
||||
if (!Query(host, owner)) return string.Empty;
|
||||
}
|
||||
return Read();
|
||||
}
|
||||
|
||||
private bool Query(RynthCoreHost host, string owner)
|
||||
{
|
||||
var p = (RynthServerProfileApiV1*)host.GetPluginInterface(owner, RynthServerProfileApiV1.InterfaceName, RynthServerProfileApiV1.InterfaceVersion);
|
||||
if (p == null || p->Version < 1 || p->StructSize < (uint)sizeof(RynthServerProfileApiV1) || p->GetProfileJson == null) return false;
|
||||
_tableVersion = &p->Version;
|
||||
_getProfileJson = p->GetProfileJson;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Copies the JSON out, growing the buffer once when the owner says it didn't fit.</summary>
|
||||
private string Read()
|
||||
{
|
||||
for (int attempt = 0; attempt < 2; attempt++)
|
||||
{
|
||||
int len;
|
||||
fixed (byte* b = _buffer) len = _getProfileJson(b, _buffer.Length);
|
||||
if (len <= 0) return string.Empty;
|
||||
if (len < _buffer.Length) return Encoding.UTF8.GetString(_buffer, 0, len);
|
||||
if (len + 1 > MaxBuffer) return string.Empty;
|
||||
_buffer = new byte[len + 1024];
|
||||
}
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private void DropTable()
|
||||
{
|
||||
DropTableKeepOwner();
|
||||
_tableOwner = string.Empty;
|
||||
}
|
||||
|
||||
private void DropTableKeepOwner()
|
||||
{
|
||||
_tableVersion = null;
|
||||
_getProfileJson = null;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue