RynthCore as of 2026-10-05 evening (internal 0a2043e): release 2026.10.5.20 - own dat reader, plugin manifests, UI/login hooks with Loot Editor drag-and-drop, server-message stream (API v78), raise attributes and skills (API v79), nameplate sizing and overlay opacity, engine reload held while a plugin is fighting, StatusAgent character sheet, world map and travel for DrakRemote
This commit is contained in:
parent
c3e15480e5
commit
913a2a00b6
110 changed files with 12560 additions and 1151 deletions
196
src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs
Normal file
196
src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Manifest/PluginManifestReader.cs
|
||||
// Reads a plugin's embedded manifest straight from the DLL file: the PE
|
||||
// resource directory, RCDATA "RYNTH_PLUGIN_MANIFEST". Nothing is loaded or run,
|
||||
// so the engine can refuse a plugin before LoadLibrary (a NativeAOT plugin
|
||||
// can never be unloaded) and the launcher can read one it would never load.
|
||||
//
|
||||
// Works on NativeAOT and managed (IL) plugin DLLs, PE32 and PE32+.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.PluginSdk.Manifest;
|
||||
|
||||
public static class PluginManifestReader
|
||||
{
|
||||
private const int MaxManifestBytes = 64 * 1024;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's manifest; null when the DLL has none (a plugin from before manifests: it
|
||||
/// keeps working as before). Throws <see cref="InvalidDataException"/> when there is one but
|
||||
/// it is broken, and IO exceptions when the file can't be read.
|
||||
/// </summary>
|
||||
public static RynthPluginManifest? Read(string dllPath)
|
||||
{
|
||||
string? json = ReadJson(dllPath);
|
||||
return json == null ? null : RynthPluginManifest.Parse(json);
|
||||
}
|
||||
|
||||
/// <summary>The embedded manifest's text, or null when the file has none.</summary>
|
||||
public static string? ReadJson(string dllPath)
|
||||
{
|
||||
using var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return ReadJson(fs);
|
||||
}
|
||||
|
||||
/// <summary>The embedded manifest's text, or null when the image has none.</summary>
|
||||
public static string? ReadJson(Stream pe)
|
||||
{
|
||||
byte[]? data = PeResources.Find(pe, RynthPluginManifest.ResourceType, RynthPluginManifest.ResourceName, MaxManifestBytes);
|
||||
if (data == null) return null;
|
||||
int start = data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF ? 3 : 0;
|
||||
int end = data.Length;
|
||||
while (end > start && data[end - 1] == 0) end--; // UpdateResource data is exact, but tolerate padding
|
||||
return Encoding.UTF8.GetString(data, start, end - start);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A minimal reader for a PE file's resource directory (no Win32 calls).</summary>
|
||||
public static class PeResources
|
||||
{
|
||||
/// <summary>
|
||||
/// The data of resource <paramref name="type"/>/<paramref name="name"/> (first language), or null
|
||||
/// when the file has no such resource. Throws <see cref="InvalidDataException"/> on a malformed image.
|
||||
/// </summary>
|
||||
public static byte[]? Find(Stream pe, int type, string name, int maxBytes)
|
||||
{
|
||||
var r = new BinaryReader(pe, Encoding.Unicode, leaveOpen: true);
|
||||
long len = pe.Length;
|
||||
if (len < 0x40) throw Bad("too small for a PE file");
|
||||
pe.Position = 0;
|
||||
if (r.ReadUInt16() != 0x5A4D) throw Bad("no MZ header");
|
||||
pe.Position = 0x3C;
|
||||
uint peOff = r.ReadUInt32();
|
||||
if (peOff > len - 24) throw Bad("PE header offset out of range");
|
||||
pe.Position = peOff;
|
||||
if (r.ReadUInt32() != 0x00004550) throw Bad("no PE signature");
|
||||
r.ReadUInt16(); // machine
|
||||
ushort sections = r.ReadUInt16();
|
||||
pe.Position += 12; // timestamp, symbol table, symbol count
|
||||
ushort optSize = r.ReadUInt16();
|
||||
r.ReadUInt16(); // characteristics
|
||||
long opt = pe.Position;
|
||||
ushort magic = r.ReadUInt16();
|
||||
long dirs = magic switch
|
||||
{
|
||||
0x10B => opt + 96, // PE32
|
||||
0x20B => opt + 112, // PE32+
|
||||
_ => throw Bad($"unknown optional header magic 0x{magic:X}"),
|
||||
};
|
||||
pe.Position = dirs - 4;
|
||||
uint dirCount = r.ReadUInt32();
|
||||
if (dirCount < 3 || dirs + 3 * 8 > opt + optSize) return null;
|
||||
pe.Position = dirs + 2 * 8; // IMAGE_DIRECTORY_ENTRY_RESOURCE
|
||||
uint rsrcRva = r.ReadUInt32();
|
||||
uint rsrcSize = r.ReadUInt32();
|
||||
if (rsrcRva == 0 || rsrcSize == 0) return null;
|
||||
|
||||
var table = new (uint Va, uint VSize, uint Raw, uint RawSize)[sections];
|
||||
pe.Position = opt + optSize;
|
||||
for (int i = 0; i < sections; i++)
|
||||
{
|
||||
pe.Position += 8; // name
|
||||
uint vsize = r.ReadUInt32();
|
||||
uint va = r.ReadUInt32();
|
||||
uint rawSize = r.ReadUInt32();
|
||||
uint raw = r.ReadUInt32();
|
||||
pe.Position += 16;
|
||||
table[i] = (va, vsize, raw, rawSize);
|
||||
}
|
||||
|
||||
long ToOffset(uint rva, uint size)
|
||||
{
|
||||
foreach (var s in table)
|
||||
{
|
||||
uint span = Math.Max(s.VSize, s.RawSize);
|
||||
if (rva >= s.Va && rva < s.Va + span)
|
||||
{
|
||||
long off = s.Raw + (long)(rva - s.Va);
|
||||
if (rva - s.Va + (long)size > s.RawSize || off + size > len) throw Bad("resource data outside its section");
|
||||
return off;
|
||||
}
|
||||
}
|
||||
throw Bad($"RVA 0x{rva:X} is in no section");
|
||||
}
|
||||
|
||||
long root = ToOffset(rsrcRva, 16);
|
||||
long rootEnd = root + rsrcSize;
|
||||
|
||||
// Level 1: type (by id), level 2: name (by string), level 3: language (first).
|
||||
long? typeDir = FindEntry(r, root, rootEnd, root, id: type, name: null);
|
||||
if (typeDir is not { } td || td >= 0) { if (typeDir == null) return null; throw Bad("resource type entry is not a directory"); }
|
||||
long? nameDir = FindEntry(r, root, rootEnd, root + (~td), id: -1, name: name);
|
||||
if (nameDir is not { } nd) return null;
|
||||
long langDir = nd < 0 ? root + (~nd) : throw Bad("resource name entry is not a directory");
|
||||
long dataEntry = FirstEntry(r, root, rootEnd, langDir);
|
||||
if (dataEntry < 0) throw Bad("resource language entry is a directory");
|
||||
pe.Position = root + dataEntry;
|
||||
uint dataRva = r.ReadUInt32();
|
||||
uint dataSize = r.ReadUInt32();
|
||||
if (dataSize > maxBytes) throw Bad($"resource is {dataSize} bytes (at most {maxBytes})");
|
||||
pe.Position = ToOffset(dataRva, dataSize);
|
||||
byte[] data = r.ReadBytes((int)dataSize);
|
||||
if (data.Length != dataSize) throw Bad("resource data truncated");
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an entry in the directory at <paramref name="dir"/> by id (or, with <paramref name="name"/>,
|
||||
/// by name, case-insensitive). Returns the entry's OffsetToData relative to the resource root:
|
||||
/// a subdirectory comes back as ~offset (negative), a data entry as the offset; null if absent.
|
||||
/// </summary>
|
||||
private static long? FindEntry(BinaryReader r, long root, long rootEnd, long dir, int id, string? name)
|
||||
{
|
||||
Stream s = r.BaseStream;
|
||||
if (dir + 16 > rootEnd) throw Bad("resource directory out of range");
|
||||
s.Position = dir + 12;
|
||||
int named = r.ReadUInt16();
|
||||
int ids = r.ReadUInt16();
|
||||
if (dir + 16 + (long)(named + ids) * 8 > rootEnd) throw Bad("resource directory entries out of range");
|
||||
for (int i = 0; i < named + ids; i++)
|
||||
{
|
||||
s.Position = dir + 16 + i * 8L;
|
||||
uint nameField = r.ReadUInt32();
|
||||
uint dataField = r.ReadUInt32();
|
||||
bool isNamed = (nameField & 0x80000000) != 0;
|
||||
bool match;
|
||||
if (name != null)
|
||||
{
|
||||
if (!isNamed) continue;
|
||||
long strAt = root + (nameField & 0x7FFFFFFF);
|
||||
if (strAt + 2 > rootEnd) throw Bad("resource name out of range");
|
||||
s.Position = strAt;
|
||||
int chars = r.ReadUInt16();
|
||||
if (strAt + 2 + chars * 2L > rootEnd) throw Bad("resource name out of range");
|
||||
string entryName = Encoding.Unicode.GetString(r.ReadBytes(chars * 2));
|
||||
match = string.Equals(entryName, name, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
else
|
||||
{
|
||||
match = !isNamed && (nameField & 0xFFFF) == id;
|
||||
}
|
||||
if (!match) continue;
|
||||
long off = dataField & 0x7FFFFFFF;
|
||||
return (dataField & 0x80000000) != 0 ? ~off : off;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static long FirstEntry(BinaryReader r, long root, long rootEnd, long dir)
|
||||
{
|
||||
Stream s = r.BaseStream;
|
||||
if (dir + 16 > rootEnd) throw Bad("resource directory out of range");
|
||||
s.Position = dir + 12;
|
||||
int count = r.ReadUInt16() + r.ReadUInt16();
|
||||
if (count == 0) throw Bad("empty resource language directory");
|
||||
s.Position = dir + 16 + 4;
|
||||
uint dataField = r.ReadUInt32();
|
||||
long off = dataField & 0x7FFFFFFF;
|
||||
return (dataField & 0x80000000) != 0 ? ~off : off;
|
||||
}
|
||||
|
||||
private static InvalidDataException Bad(string why) => new("not a readable PE file: " + why);
|
||||
}
|
||||
180
src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs
Normal file
180
src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Manifest/PluginManifestResolver.cs
|
||||
// Decides which of a set of plugins can start on an engine, and in what order:
|
||||
// - a plugin whose manifest needs a newer (or older) engine API is refused;
|
||||
// - a plugin whose REQUIRED dependency is missing, too old or refused is refused
|
||||
// (and so on down the chain);
|
||||
// - required dependencies start before the plugins that need them. Optional
|
||||
// dependencies never refuse anything and never reorder: plugins look each other
|
||||
// up lazily (GetPluginInterface), and a pair of plugins that can use each other
|
||||
// would otherwise form a cycle.
|
||||
// A plugin without a manifest is never refused and keeps its place, so a set with no
|
||||
// manifests at all comes out exactly as it went in.
|
||||
//
|
||||
// Pure logic, used by the engine's PluginManager and by tools\PluginManifestTests.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.PluginSdk.Manifest;
|
||||
|
||||
/// <summary>One plugin to consider: its path (or any key), and its manifest if it has one.</summary>
|
||||
public sealed class PluginCandidate
|
||||
{
|
||||
/// <param name="fileVersion">The DLL's version resource (ProductVersion), used when the manifest has no version or there is no manifest.</param>
|
||||
public PluginCandidate(string key, RynthPluginManifest? manifest, string? fileVersion = null)
|
||||
{
|
||||
Key = key;
|
||||
Manifest = manifest;
|
||||
Name = manifest?.Name is { Length: > 0 } n ? n : RynthPluginManifest.NameFromFile(key);
|
||||
Version = manifest?.Version is { Length: > 0 } v ? v : fileVersion ?? "";
|
||||
}
|
||||
|
||||
public string Key { get; }
|
||||
public RynthPluginManifest? Manifest { get; }
|
||||
/// <summary>The manifest name, or for a plugin without one the name from its file.</summary>
|
||||
public string Name { get; }
|
||||
public string Version { get; }
|
||||
}
|
||||
|
||||
public sealed class PluginRefusal
|
||||
{
|
||||
public PluginRefusal(PluginCandidate plugin, string reason, bool engine)
|
||||
{
|
||||
Plugin = plugin;
|
||||
Reason = reason;
|
||||
IsEngineMismatch = engine;
|
||||
}
|
||||
|
||||
public PluginCandidate Plugin { get; }
|
||||
/// <summary>One sentence, fit for chat: "RynthOracle needs a newer RynthCore (API 77)".</summary>
|
||||
public string Reason { get; }
|
||||
/// <summary>True for an engine API mismatch, false for a dependency problem.</summary>
|
||||
public bool IsEngineMismatch { get; }
|
||||
}
|
||||
|
||||
public sealed class PluginResolution
|
||||
{
|
||||
/// <summary>The plugins to load and start, in order.</summary>
|
||||
public List<PluginCandidate> Order { get; } = new();
|
||||
public List<PluginRefusal> Refused { get; } = new();
|
||||
/// <summary>Things worth a log line that refuse nothing (a missing optional dependency, a dev build, a cycle).</summary>
|
||||
public List<string> Notes { get; } = new();
|
||||
}
|
||||
|
||||
public static class PluginManifestResolver
|
||||
{
|
||||
public static PluginResolution Resolve(IReadOnlyList<PluginCandidate> candidates, uint engineApi)
|
||||
{
|
||||
var result = new PluginResolution();
|
||||
var refused = new Dictionary<PluginCandidate, string>();
|
||||
|
||||
// 1. The engine API.
|
||||
foreach (PluginCandidate c in candidates)
|
||||
{
|
||||
if (c.Manifest?.CheckEngine(engineApi) is { } why)
|
||||
Refuse(result, refused, c, why, engine: true);
|
||||
}
|
||||
|
||||
// 2. Required dependencies, until nothing more falls.
|
||||
bool changed = true;
|
||||
while (changed)
|
||||
{
|
||||
changed = false;
|
||||
foreach (PluginCandidate c in candidates)
|
||||
{
|
||||
if (refused.ContainsKey(c) || c.Manifest == null) continue;
|
||||
foreach (RynthPluginDependency d in c.Manifest.Dependencies)
|
||||
{
|
||||
if (d.Optional) continue;
|
||||
string? why = CheckDependency(candidates, refused, c, d);
|
||||
if (why == null) continue;
|
||||
Refuse(result, refused, c, why, engine: false);
|
||||
changed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Notes on optional dependencies and dev builds (refuse nothing).
|
||||
foreach (PluginCandidate c in candidates)
|
||||
{
|
||||
if (refused.ContainsKey(c) || c.Manifest == null) continue;
|
||||
foreach (RynthPluginDependency d in c.Manifest.Dependencies)
|
||||
{
|
||||
PluginCandidate? dep = Find(candidates, d.Name);
|
||||
if (d.Optional && (dep == null || refused.ContainsKey(dep)))
|
||||
result.Notes.Add($"{c.Name}: optional plugin {d.Name} is not loaded; the features that use it are off.");
|
||||
else if (d.Optional && !PluginVersion.Satisfies(dep!.Version, d.MinVersion))
|
||||
result.Notes.Add($"{c.Name}: optional plugin {d.Name} is older ({dep.Version}) than it can use ({d.MinVersion}).");
|
||||
else if (dep != null && d.MinVersion.Length > 0 && PluginVersion.IsDevBuild(dep.Version))
|
||||
result.Notes.Add($"{c.Name}: {d.Name} is a dev build ({dep.Version}); taken as satisfying {d.MinVersion}.");
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Order: each plugin after its required dependencies, otherwise as given.
|
||||
var accepted = new List<PluginCandidate>();
|
||||
foreach (PluginCandidate c in candidates)
|
||||
if (!refused.ContainsKey(c)) accepted.Add(c);
|
||||
|
||||
var placed = new HashSet<PluginCandidate>();
|
||||
var visiting = new HashSet<PluginCandidate>();
|
||||
void Place(PluginCandidate c)
|
||||
{
|
||||
if (placed.Contains(c)) return;
|
||||
if (!visiting.Add(c))
|
||||
{
|
||||
result.Notes.Add($"{c.Name}: its required dependencies form a cycle; started in list order.");
|
||||
return;
|
||||
}
|
||||
if (c.Manifest != null)
|
||||
{
|
||||
foreach (RynthPluginDependency d in c.Manifest.Dependencies)
|
||||
{
|
||||
if (d.Optional) continue;
|
||||
PluginCandidate? dep = Find(accepted, d.Name);
|
||||
if (dep != null) Place(dep);
|
||||
}
|
||||
}
|
||||
visiting.Remove(c);
|
||||
if (placed.Add(c)) result.Order.Add(c);
|
||||
}
|
||||
foreach (PluginCandidate c in accepted) Place(c);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when <paramref name="d"/> is satisfied by a plugin in <paramref name="available"/>
|
||||
/// (by name; a dev build satisfies any version), else why not.
|
||||
/// </summary>
|
||||
public static string? CheckDependency(IReadOnlyList<PluginCandidate> available, IReadOnlyDictionary<PluginCandidate, string>? refused,
|
||||
PluginCandidate owner, RynthPluginDependency d)
|
||||
{
|
||||
PluginCandidate? dep = Find(available, d.Name);
|
||||
string needs = d.MinVersion.Length > 0 ? $"{d.Name} {d.MinVersion} or newer" : $"the {d.Name} plugin";
|
||||
if (dep == null)
|
||||
return $"{owner.Name} needs {needs}, which is not in the plugin list";
|
||||
if (refused != null && refused.ContainsKey(dep))
|
||||
return $"{owner.Name} needs {d.Name}, which was not loaded";
|
||||
if (!PluginVersion.Satisfies(dep.Version, d.MinVersion))
|
||||
return dep.Version.Length > 0
|
||||
? $"{owner.Name} needs {d.Name} {d.MinVersion} or newer (this one is {dep.Version})"
|
||||
: $"{owner.Name} needs {d.Name} {d.MinVersion} or newer (this one has no version)";
|
||||
return null;
|
||||
}
|
||||
|
||||
public static PluginCandidate? Find(IReadOnlyList<PluginCandidate> list, string name)
|
||||
{
|
||||
foreach (PluginCandidate c in list)
|
||||
if (string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase)) return c;
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void Refuse(PluginResolution result, Dictionary<PluginCandidate, string> refused, PluginCandidate c, string why, bool engine)
|
||||
{
|
||||
if (refused.ContainsKey(c)) return;
|
||||
refused[c] = why;
|
||||
result.Refused.Add(new PluginRefusal(c, why, engine));
|
||||
}
|
||||
}
|
||||
232
src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs
Normal file
232
src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Manifest/RynthPluginManifest.cs
|
||||
// A plugin's manifest: who it is, which engine API it needs, which plugins it
|
||||
// needs. Built from the plugin's csproj at build time (build\RynthCore.PluginSdk
|
||||
// .targets) and embedded in the DLL as a Windows resource (RCDATA
|
||||
// "RYNTH_PLUGIN_MANIFEST"), so it travels with the binary and is read without
|
||||
// loading it (PluginManifestReader).
|
||||
//
|
||||
// Compiled into the SDK, the engine (PluginManager) and the launcher (updater);
|
||||
// keep it free of anything but the BCL.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.PluginSdk.Manifest;
|
||||
|
||||
/// <summary>One plugin another needs (or can use).</summary>
|
||||
public sealed class RynthPluginDependency
|
||||
{
|
||||
/// <summary>The other plugin's manifest name (for a plugin without a manifest: its file name without "RynthCore.Plugin." and ".dll").</summary>
|
||||
public string Name { get; set; } = "";
|
||||
/// <summary>The lowest version that will do; empty for any.</summary>
|
||||
public string MinVersion { get; set; } = "";
|
||||
/// <summary>True: used when present, the plugin still runs without it. False: required, the plugin isn't started without it.</summary>
|
||||
public bool Optional { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A plugin's manifest (schema 1). Unknown JSON fields are ignored, so later schemas can add fields.</summary>
|
||||
public sealed class RynthPluginManifest
|
||||
{
|
||||
/// <summary>Windows resource type the manifest is stored under (RT_RCDATA).</summary>
|
||||
public const int ResourceType = 10;
|
||||
/// <summary>Windows resource name the manifest is stored under.</summary>
|
||||
public const string ResourceName = "RYNTH_PLUGIN_MANIFEST";
|
||||
public const int CurrentSchema = 1;
|
||||
|
||||
public int Schema { get; set; } = CurrentSchema;
|
||||
public string Name { get; set; } = "";
|
||||
public string Version { get; set; } = "";
|
||||
/// <summary>The oldest engine API the plugin runs on: its highest unguarded API use.</summary>
|
||||
public uint MinEngineApi { get; set; }
|
||||
/// <summary>The newest engine API the plugin is known to work with; 0 = no upper limit (the usual case: the table is append-only).</summary>
|
||||
public uint MaxEngineApi { get; set; }
|
||||
public List<RynthPluginDependency> Dependencies { get; set; } = new();
|
||||
public string Author { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string Homepage { get; set; } = "";
|
||||
public string License { get; set; } = "";
|
||||
|
||||
/// <summary>Parses a manifest; throws <see cref="InvalidDataException"/> with the reason when it isn't one.</summary>
|
||||
public static RynthPluginManifest Parse(string json)
|
||||
{
|
||||
JsonDocument doc;
|
||||
try { doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); }
|
||||
catch (JsonException ex) { throw new InvalidDataException("the plugin manifest is not valid JSON: " + ex.Message); }
|
||||
|
||||
using (doc)
|
||||
{
|
||||
JsonElement r = doc.RootElement;
|
||||
if (r.ValueKind != JsonValueKind.Object)
|
||||
throw new InvalidDataException("the plugin manifest is not a JSON object");
|
||||
|
||||
var m = new RynthPluginManifest();
|
||||
if (r.TryGetProperty("schema", out JsonElement s))
|
||||
{
|
||||
if (s.ValueKind != JsonValueKind.Number || !s.TryGetInt32(out int schema) || schema < 1)
|
||||
throw new InvalidDataException("the plugin manifest's schema is not a positive number");
|
||||
m.Schema = schema;
|
||||
}
|
||||
m.Name = Str(r, "name").Trim();
|
||||
if (m.Name.Length == 0)
|
||||
throw new InvalidDataException("the plugin manifest has no name");
|
||||
m.Version = Str(r, "version").Trim();
|
||||
m.MinEngineApi = Api(r, "minEngineApi");
|
||||
m.MaxEngineApi = Api(r, "maxEngineApi");
|
||||
if (m.MaxEngineApi != 0 && m.MaxEngineApi < m.MinEngineApi)
|
||||
throw new InvalidDataException($"the plugin manifest's maxEngineApi ({m.MaxEngineApi}) is below its minEngineApi ({m.MinEngineApi})");
|
||||
m.Author = Str(r, "author");
|
||||
m.Description = Str(r, "description");
|
||||
m.Homepage = Str(r, "homepage");
|
||||
m.License = Str(r, "license");
|
||||
|
||||
if (r.TryGetProperty("dependencies", out JsonElement deps) && deps.ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
if (deps.ValueKind != JsonValueKind.Array)
|
||||
throw new InvalidDataException("the plugin manifest's dependencies is not an array");
|
||||
foreach (JsonElement d in deps.EnumerateArray())
|
||||
{
|
||||
var dep = new RynthPluginDependency();
|
||||
if (d.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
// Shorthand: "RynthNav" or "RynthNav@2026.10.1.1" (required).
|
||||
string text = d.GetString() ?? "";
|
||||
int at = text.IndexOf('@');
|
||||
dep.Name = (at >= 0 ? text[..at] : text).Trim();
|
||||
dep.MinVersion = at >= 0 ? text[(at + 1)..].Trim() : "";
|
||||
}
|
||||
else if (d.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
dep.Name = Str(d, "name").Trim();
|
||||
dep.MinVersion = Str(d, "minVersion").Trim();
|
||||
dep.Optional = d.TryGetProperty("optional", out JsonElement o) && o.ValueKind == JsonValueKind.True;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidDataException("a plugin manifest dependency is neither a name nor an object");
|
||||
}
|
||||
if (dep.Name.Length == 0)
|
||||
throw new InvalidDataException("a plugin manifest dependency has no name");
|
||||
if (dep.MinVersion.Length > 0 && !PluginVersion.TryParse(dep.MinVersion, out _))
|
||||
throw new InvalidDataException($"dependency {dep.Name}: minVersion '{dep.MinVersion}' is not a version");
|
||||
if (string.Equals(dep.Name, m.Name, StringComparison.OrdinalIgnoreCase))
|
||||
throw new InvalidDataException("the plugin manifest lists the plugin as its own dependency");
|
||||
m.Dependencies.Add(dep);
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses, or returns null with the reason in <paramref name="error"/>.</summary>
|
||||
public static RynthPluginManifest? TryParse(string json, out string error)
|
||||
{
|
||||
try { error = ""; return Parse(json); }
|
||||
catch (InvalidDataException ex) { error = ex.Message; return null; }
|
||||
}
|
||||
|
||||
/// <summary>The manifest as JSON (UTF-8, indented): what the build embeds.</summary>
|
||||
public string ToJson()
|
||||
{
|
||||
using var ms = new MemoryStream();
|
||||
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteNumber("schema", Schema);
|
||||
w.WriteString("name", Name);
|
||||
if (Version.Length > 0) w.WriteString("version", Version);
|
||||
w.WriteNumber("minEngineApi", MinEngineApi);
|
||||
if (MaxEngineApi != 0) w.WriteNumber("maxEngineApi", MaxEngineApi);
|
||||
w.WriteStartArray("dependencies");
|
||||
foreach (RynthPluginDependency d in Dependencies)
|
||||
{
|
||||
w.WriteStartObject();
|
||||
w.WriteString("name", d.Name);
|
||||
if (d.MinVersion.Length > 0) w.WriteString("minVersion", d.MinVersion);
|
||||
if (d.Optional) w.WriteBoolean("optional", true);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
w.WriteEndArray();
|
||||
if (Author.Length > 0) w.WriteString("author", Author);
|
||||
if (Description.Length > 0) w.WriteString("description", Description);
|
||||
if (Homepage.Length > 0) w.WriteString("homepage", Homepage);
|
||||
if (License.Length > 0) w.WriteString("license", License);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
return Encoding.UTF8.GetString(ms.ToArray());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when this engine API can run the plugin, else why not, in a form fit for chat:
|
||||
/// "RynthOracle needs a newer RynthCore (API 77)".
|
||||
/// </summary>
|
||||
public string? CheckEngine(uint engineApi)
|
||||
{
|
||||
if (MinEngineApi > engineApi)
|
||||
return $"{Name} needs a newer RynthCore (API {MinEngineApi})";
|
||||
if (MaxEngineApi != 0 && MaxEngineApi < engineApi)
|
||||
return $"{Name} is too old for this RynthCore (it works up to API {MaxEngineApi}, this is API {engineApi})";
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>"RynthCore.Plugin.RynthNav.dll" -> "RynthNav": the name a plugin without a manifest goes by.</summary>
|
||||
public static string NameFromFile(string path)
|
||||
{
|
||||
string name = Path.GetFileNameWithoutExtension(path) ?? "";
|
||||
const string prefix = "RynthCore.Plugin.";
|
||||
return name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? name[prefix.Length..] : name;
|
||||
}
|
||||
|
||||
private static string Str(JsonElement o, string name) =>
|
||||
o.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() ?? "" : "";
|
||||
|
||||
private static uint Api(JsonElement o, string name)
|
||||
{
|
||||
if (!o.TryGetProperty(name, out JsonElement e) || e.ValueKind == JsonValueKind.Null) return 0;
|
||||
if (e.ValueKind == JsonValueKind.Number && e.TryGetUInt32(out uint v)) return v;
|
||||
if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), out uint sv)) return sv;
|
||||
throw new InvalidDataException($"the plugin manifest's {name} is not a whole number");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plugin version strings: "2026.10.5.1", "1.2", "2026.10.5.1+8ca322f".</summary>
|
||||
public static class PluginVersion
|
||||
{
|
||||
/// <summary>Parses the numeric part (build metadata after '+' and a '-prerelease' tail are ignored).</summary>
|
||||
public static bool TryParse(string? text, out Version version)
|
||||
{
|
||||
version = new Version(0, 0);
|
||||
if (string.IsNullOrWhiteSpace(text)) return false;
|
||||
string t = text.Trim();
|
||||
if (t.StartsWith("v", StringComparison.OrdinalIgnoreCase)) t = t[1..];
|
||||
int cut = t.IndexOfAny(new[] { '+', '-', ' ' });
|
||||
if (cut >= 0) t = t[..cut];
|
||||
if (t.Length == 0) return false;
|
||||
if (!t.Contains('.')) t += ".0";
|
||||
return System.Version.TryParse(t, out version!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An unstamped build: the SDK's default version, 1.0.0 (Deploy-RynthCore.ps1, IDE builds).
|
||||
/// It satisfies any minimum version, so dev setups keep working; the engine logs it.
|
||||
/// </summary>
|
||||
public static bool IsDevBuild(string? text) =>
|
||||
TryParse(text, out Version v) && v.Major == 1 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
|
||||
|
||||
/// <summary>True when <paramref name="actual"/> is at least <paramref name="minimum"/> (or either is missing, or actual is a dev build).</summary>
|
||||
public static bool Satisfies(string? actual, string? minimum)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(minimum)) return true;
|
||||
if (!TryParse(minimum, out Version min)) return true;
|
||||
if (!TryParse(actual, out Version have)) return false;
|
||||
if (IsDevBuild(actual)) return true;
|
||||
return Normalize(have) >= Normalize(min);
|
||||
}
|
||||
|
||||
private static Version Normalize(Version v) =>
|
||||
new(v.Major, v.Minor, Math.Max(v.Build, 0), Math.Max(v.Revision, 0));
|
||||
}
|
||||
350
src/RynthCore.PluginSdk/Net/Messages.cs
Normal file
350
src/RynthCore.PluginSdk/Net/Messages.cs
Normal file
|
|
@ -0,0 +1,350 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Net/Messages.cs
|
||||
// Typed, read-only parsers for server messages the engine doesn't already turn into
|
||||
// plugin events: chat with sender ids (speech, ranged speech, tells, emotes, channel
|
||||
// broadcasts), fellowship, friends, allegiance logins, confirmation prompts, and popup
|
||||
// and transient system text.
|
||||
//
|
||||
// Layouts written for RynthCore from general knowledge of the AC wire format (field
|
||||
// order and sizes); no generated definitions or copied code. Each TryParse takes the
|
||||
// bytes after the opcode (top-level messages) or after the event type (game events),
|
||||
// never throws, and returns false for data that doesn't fit the layout. Consumed
|
||||
// says how many bytes the parse used, so a mismatch with the real server shows up as
|
||||
// leftover bytes (the engine's /rc netmsg log reports it).
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.PluginSdk.Net;
|
||||
|
||||
// ─── chat ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>0x02BB: local speech. Text, sender name, sender id, chat type.</summary>
|
||||
public sealed record HearSpeech(string Text, string SenderName, uint SenderId, uint ChatType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearSpeech msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.String16L(out string text) || !r.String16L(out string name) ||
|
||||
!r.U32(out uint sender) || !r.U32(out uint type))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new HearSpeech(text, name, sender, type);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>0x02BC: ranged speech (shouts, NPC speech). Text, sender name, sender id, range, chat type.</summary>
|
||||
public sealed record HearRangedSpeech(string Text, string SenderName, uint SenderId, float Range, uint ChatType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearRangedSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearRangedSpeech msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.String16L(out string text) || !r.String16L(out string name) ||
|
||||
!r.U32(out uint sender) || !r.F32(out float range) || !r.U32(out uint type))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new HearRangedSpeech(text, name, sender, range, type);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>0x01E0 (emote) and 0x01E2 (soul emote): sender id, sender name, text.</summary>
|
||||
public sealed record HearEmote(uint SenderId, string SenderName, string Text, bool Soul)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool soul, out HearEmote msg) => TryParse(body, soul, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool soul, out HearEmote msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.U32(out uint sender) || !r.String16L(out string name) || !r.String16L(out string text))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new HearEmote(sender, name, text, soul);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02BD: a tell. Text, sender name, sender id, target id, chat type, then a u32 of flags.</summary>
|
||||
public sealed record HearDirectSpeech(string Text, string SenderName, uint SenderId, uint TargetId, uint ChatType, uint Flags)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearDirectSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearDirectSpeech msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.String16L(out string text) || !r.String16L(out string name) || !r.U32(out uint sender) ||
|
||||
!r.U32(out uint target) || !r.U32(out uint type) || !r.U32(out uint flags))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new HearDirectSpeech(text, name, sender, target, type, flags);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x0147: a chat channel line (allegiance, fellowship, ...). Channel id, sender name (empty for your own), text.</summary>
|
||||
public sealed record ChannelBroadcast(uint Channel, string SenderName, string Text)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ChannelBroadcast msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ChannelBroadcast msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.U32(out uint channel) || !r.String16L(out string name) || !r.String16L(out string text))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new ChannelBroadcast(channel, name, text);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game events 0x0004 (popup box) and 0x02EB (transient text): one string.</summary>
|
||||
public sealed record SystemText(string Text, bool Transient)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool transient, out SystemText msg) => TryParse(body, transient, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool transient, out SystemText msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.String16L(out string text))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new SystemText(text, transient);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x0274: a yes/no prompt (fellowship invite, swear allegiance, crafting...). Type, context id, text.</summary>
|
||||
public sealed record ConfirmationRequest(uint ConfirmationType, uint ContextId, string Text)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ConfirmationRequest msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ConfirmationRequest msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.U32(out uint type) || !r.U32(out uint context) || !r.String16L(out string text))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new ConfirmationRequest(type, context, text);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── allegiance, friends ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Game event 0x027A: an allegiance member logged in or out. Character id, logged in (u32 flag).</summary>
|
||||
public sealed record AllegianceLoginNotification(uint CharacterId, bool LoggedIn)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out AllegianceLoginNotification msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out AllegianceLoginNotification msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
if (!r.U32(out uint id) || !r.Bool32(out bool on))
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
msg = new AllegianceLoginNotification(id, on);
|
||||
consumed = r.Position;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One friends-list entry: id, online, appearing offline, name, and the two id lists the server keeps with it.</summary>
|
||||
public sealed record FriendData(uint Id, bool Online, bool AppearOffline, string Name, uint[] OutFriends, uint[] InFriends);
|
||||
|
||||
/// <summary>Game event 0x0021: the friends list, whole or changed. A packed list of entries, then the update type.</summary>
|
||||
public sealed record FriendsUpdate(IReadOnlyList<FriendData> Friends, uint UpdateType)
|
||||
{
|
||||
public const uint Full = 0, Added = 1, Removed = 2, LoginChange = 4;
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FriendsUpdate msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FriendsUpdate msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
bool ok = r.ListCount(out int n, 4 + 4 + 4 + 4 + 4 + 4);
|
||||
var list = new List<FriendData>(ok ? n : 0);
|
||||
for (int i = 0; ok && i < n; i++)
|
||||
{
|
||||
if (r.U32(out uint id) && r.Bool32(out bool online) && r.Bool32(out bool appearOffline) &&
|
||||
r.String16L(out string name) && r.U32List(out uint[] outs) && r.U32List(out uint[] ins))
|
||||
list.Add(new FriendData(id, online, appearOffline, name, outs, ins));
|
||||
else
|
||||
ok = false;
|
||||
}
|
||||
uint type = 0;
|
||||
ok = ok && r.U32(out type);
|
||||
consumed = r.Position;
|
||||
if (!ok) return false;
|
||||
msg = new FriendsUpdate(list, type);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── fellowship ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A fellowship member: cached XP and luminance shares, level, max and current vitals, share-loot flag, name.</summary>
|
||||
public sealed record Fellow(uint Id, string Name, uint Level, uint XpCached, uint LumCached,
|
||||
uint MaxHealth, uint MaxStamina, uint MaxMana, uint Health, uint Stamina, uint Mana, bool ShareLoot)
|
||||
{
|
||||
/// <summary>Fellow body: 9 u32 (xp, lum, level, max h/s/m, current h/s/m), u32 share-loot flag, name.</summary>
|
||||
internal static bool Read(ref NetReader r, uint id, out Fellow fellow)
|
||||
{
|
||||
fellow = null!;
|
||||
if (!r.U32(out uint xp) || !r.U32(out uint lum) || !r.U32(out uint level) ||
|
||||
!r.U32(out uint maxH) || !r.U32(out uint maxS) || !r.U32(out uint maxM) ||
|
||||
!r.U32(out uint h) || !r.U32(out uint s) || !r.U32(out uint m) ||
|
||||
!r.Bool32(out bool shareLoot) || !r.String16L(out string name))
|
||||
return false;
|
||||
fellow = new Fellow(id, name, level, xp, lum, maxH, maxS, maxM, h, s, m, shareLoot);
|
||||
return true;
|
||||
}
|
||||
|
||||
internal const int MinSize = 10 * 4 + 4;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Game event 0x02BE: the whole fellowship. Members (packed table id to fellow), name,
|
||||
/// leader id, then four u32 flags: share XP, even XP split, open, locked. After that the
|
||||
/// server sends the recently departed members and the fellowship locks; those are read
|
||||
/// when they fit (<see cref="TailParsed"/>), and the members are returned either way.
|
||||
/// </summary>
|
||||
public sealed record FellowshipFullUpdate(string Name, uint LeaderId, bool ShareXp, bool EvenXpSplit, bool Open, bool Locked,
|
||||
IReadOnlyList<Fellow> Fellows, IReadOnlyDictionary<uint, int> RecentlyDeparted, IReadOnlyList<string> LockNames, bool TailParsed)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipFullUpdate msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipFullUpdate msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
bool ok = r.TableCount(out int n, 4 + Fellow.MinSize);
|
||||
var fellows = new List<Fellow>(ok ? n : 0);
|
||||
for (int i = 0; ok && i < n; i++)
|
||||
{
|
||||
if (r.U32(out uint id) && Fellow.Read(ref r, id, out Fellow f))
|
||||
fellows.Add(f);
|
||||
else
|
||||
ok = false;
|
||||
}
|
||||
string name = string.Empty;
|
||||
uint leader = 0;
|
||||
bool shareXp = false, even = false, open = false, locked = false;
|
||||
ok = ok && r.String16L(out name) && r.U32(out leader) &&
|
||||
r.Bool32(out shareXp) && r.Bool32(out even) && r.Bool32(out open) && r.Bool32(out locked);
|
||||
if (!ok)
|
||||
{
|
||||
consumed = r.Position;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tail: recently departed (id -> i32), then locks (name -> 5 x u32 of lock data).
|
||||
int mainEnd = r.Position;
|
||||
var departed = new Dictionary<uint, int>();
|
||||
var locks = new List<string>();
|
||||
bool tail = r.TableCount(out int d, 8);
|
||||
for (int i = 0; tail && i < d; i++)
|
||||
{
|
||||
if (r.U32(out uint id) && r.I32(out int t))
|
||||
departed[id] = t;
|
||||
else
|
||||
tail = false;
|
||||
}
|
||||
int l = 0;
|
||||
tail = tail && r.TableCount(out l, 4 + 20);
|
||||
for (int i = 0; tail && i < l; i++)
|
||||
{
|
||||
if (r.String16L(out string lockName) && r.Skip(20))
|
||||
locks.Add(lockName);
|
||||
else
|
||||
tail = false;
|
||||
}
|
||||
if (!tail)
|
||||
{
|
||||
departed.Clear();
|
||||
locks.Clear();
|
||||
}
|
||||
consumed = tail ? r.Position : mainEnd;
|
||||
msg = new FellowshipFullUpdate(name, leader, shareXp, even, open, locked, fellows, departed, locks, tail);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02C0: one member changed. Fellow id, the fellow, update type (1 full, 2 stats, 3 vitals).</summary>
|
||||
public sealed record FellowshipUpdateFellow(Fellow Fellow, uint UpdateType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipUpdateFellow msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipUpdateFellow msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
Fellow f = null!;
|
||||
uint type = 0;
|
||||
bool ok = r.U32(out uint id) && Fellow.Read(ref r, id, out f) && r.U32(out type);
|
||||
consumed = r.Position;
|
||||
if (!ok) return false;
|
||||
msg = new FellowshipUpdateFellow(f, type);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game events 0x00A3 (a member quit) and 0x00A4 (a member was dismissed): the member's id.</summary>
|
||||
public sealed record FellowshipMemberLeft(uint FellowId, bool Dismissed)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool dismissed, out FellowshipMemberLeft msg) => TryParse(body, dismissed, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool dismissed, out FellowshipMemberLeft msg, out int consumed)
|
||||
{
|
||||
msg = null!;
|
||||
var r = new NetReader(body);
|
||||
bool ok = r.U32(out uint id);
|
||||
consumed = r.Position;
|
||||
if (!ok) return false;
|
||||
msg = new FellowshipMemberLeft(id, dismissed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02BF: the fellowship was disbanded (no body).</summary>
|
||||
public sealed record FellowshipDisband
|
||||
{
|
||||
public static readonly FellowshipDisband Instance = new();
|
||||
}
|
||||
121
src/RynthCore.PluginSdk/Net/NetMessages.cs
Normal file
121
src/RynthCore.PluginSdk/Net/NetMessages.cs
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Net/NetMessages.cs
|
||||
// One entry point over the typed parsers: which message is this, did it parse, how
|
||||
// many bytes were left over, and a one-line summary. Used by the engine's
|
||||
// /rc netmsg log (to check the layouts against a live server) and by the replay runner.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.PluginSdk.Net;
|
||||
|
||||
/// <summary>The result of <see cref="NetMessages.Inspect"/>.</summary>
|
||||
public readonly record struct NetMessageInfo(string Kind, bool Known, bool Parsed, int Leftover, string Summary, object? Value);
|
||||
|
||||
public static class NetMessages
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses <paramref name="m"/> if the SDK knows it. Leftover is the bytes the layout
|
||||
/// didn't account for (non-zero means the layout and the server disagree).
|
||||
/// </summary>
|
||||
public static NetMessageInfo Inspect(ServerMessage m)
|
||||
{
|
||||
if (m.Opcode == ServerMessage.GameEventOpcode)
|
||||
{
|
||||
if (!m.IsGameEvent)
|
||||
return new("GameEvent(short)", true, false, m.Body.Length, "", null);
|
||||
return InspectEvent(m.EventType, m.EventBody);
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> b = m.Body;
|
||||
switch (m.Opcode)
|
||||
{
|
||||
case ServerOpcode.HearSpeech:
|
||||
{
|
||||
bool ok = HearSpeech.TryParse(b, out var v, out int used);
|
||||
return Done("HearSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) type {v.ChatType}: {v.Text}" : "", v);
|
||||
}
|
||||
case ServerOpcode.HearRangedSpeech:
|
||||
{
|
||||
bool ok = HearRangedSpeech.TryParse(b, out var v, out int used);
|
||||
return Done("HearRangedSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) range {v.Range.ToString("0.#", CultureInfo.InvariantCulture)} type {v.ChatType}: {v.Text}" : "", v);
|
||||
}
|
||||
case ServerOpcode.HearEmote:
|
||||
case ServerOpcode.HearSoulEmote:
|
||||
{
|
||||
bool soul = m.Opcode == ServerOpcode.HearSoulEmote;
|
||||
bool ok = HearEmote.TryParse(b, soul, out var v, out int used);
|
||||
return Done(soul ? "HearSoulEmote" : "HearEmote", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}): {v.Text}" : "", v);
|
||||
}
|
||||
}
|
||||
return new($"0x{m.Opcode:X4}", false, false, 0, "", null);
|
||||
}
|
||||
|
||||
private static NetMessageInfo InspectEvent(uint type, ReadOnlySpan<byte> b)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case GameEventType.HearDirectSpeech:
|
||||
{
|
||||
bool ok = HearDirectSpeech.TryParse(b, out var v, out int used);
|
||||
return Done("HearDirectSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) -> 0x{v.TargetId:X8} type {v.ChatType}: {v.Text}" : "", v);
|
||||
}
|
||||
case GameEventType.ChannelBroadcast:
|
||||
{
|
||||
bool ok = ChannelBroadcast.TryParse(b, out var v, out int used);
|
||||
return Done("ChannelBroadcast", ok, b, used, ok ? $"channel {v.Channel} {v.SenderName}: {v.Text}" : "", v);
|
||||
}
|
||||
case GameEventType.PopUpString:
|
||||
case GameEventType.TransientString:
|
||||
{
|
||||
bool transient = type == GameEventType.TransientString;
|
||||
bool ok = SystemText.TryParse(b, transient, out var v, out int used);
|
||||
return Done(transient ? "TransientString" : "PopUpString", ok, b, used, ok ? v.Text : "", v);
|
||||
}
|
||||
case GameEventType.ConfirmationRequest:
|
||||
{
|
||||
bool ok = ConfirmationRequest.TryParse(b, out var v, out int used);
|
||||
return Done("ConfirmationRequest", ok, b, used, ok ? $"type {v.ConfirmationType} context 0x{v.ContextId:X8}: {v.Text}" : "", v);
|
||||
}
|
||||
case GameEventType.AllegianceLoginNotification:
|
||||
{
|
||||
bool ok = AllegianceLoginNotification.TryParse(b, out var v, out int used);
|
||||
return Done("AllegianceLoginNotification", ok, b, used, ok ? $"0x{v.CharacterId:X8} {(v.LoggedIn ? "logged in" : "logged out")}" : "", v);
|
||||
}
|
||||
case GameEventType.FriendsUpdate:
|
||||
{
|
||||
bool ok = FriendsUpdate.TryParse(b, out var v, out int used);
|
||||
return Done("FriendsUpdate", ok, b, used, ok ? $"type {v.UpdateType}, {v.Friends.Count} friend(s){FirstFriend(v)}" : "", v);
|
||||
}
|
||||
case GameEventType.FellowshipFullUpdate:
|
||||
{
|
||||
bool ok = FellowshipFullUpdate.TryParse(b, out var v, out int used);
|
||||
return Done("FellowshipFullUpdate", ok, b, used,
|
||||
ok ? $"'{v.Name}' leader 0x{v.LeaderId:X8}, {v.Fellows.Count} member(s), shareXp={v.ShareXp} even={v.EvenXpSplit} open={v.Open} locked={v.Locked} tail={(v.TailParsed ? "ok" : "unread")}" : "", v);
|
||||
}
|
||||
case GameEventType.FellowshipUpdateFellow:
|
||||
{
|
||||
bool ok = FellowshipUpdateFellow.TryParse(b, out var v, out int used);
|
||||
return Done("FellowshipUpdateFellow", ok, b, used,
|
||||
ok ? $"{v.Fellow.Name} (0x{v.Fellow.Id:X8}) L{v.Fellow.Level} hp {v.Fellow.Health}/{v.Fellow.MaxHealth} update {v.UpdateType}" : "", v);
|
||||
}
|
||||
case GameEventType.FellowshipQuit:
|
||||
case GameEventType.FellowshipDismiss:
|
||||
{
|
||||
bool dismissed = type == GameEventType.FellowshipDismiss;
|
||||
bool ok = FellowshipMemberLeft.TryParse(b, dismissed, out var v, out int used);
|
||||
return Done(dismissed ? "FellowshipDismiss" : "FellowshipQuit", ok, b, used, ok ? $"0x{v.FellowId:X8}" : "", v);
|
||||
}
|
||||
case GameEventType.FellowshipDisband:
|
||||
return Done("FellowshipDisband", true, b, 0, "", FellowshipDisband.Instance);
|
||||
}
|
||||
return new($"GameEvent 0x{type:X4}", false, false, 0, "", null);
|
||||
}
|
||||
|
||||
private static string FirstFriend(FriendsUpdate v)
|
||||
=> v.Friends.Count == 0 ? "" : $", first {v.Friends[0].Name} online={v.Friends[0].Online}";
|
||||
|
||||
private static NetMessageInfo Done(string kind, bool ok, ReadOnlySpan<byte> body, int used, string summary, object? value)
|
||||
=> new(kind, true, ok, ok ? body.Length - used : body.Length, summary, ok ? value : null);
|
||||
}
|
||||
160
src/RynthCore.PluginSdk/Net/NetReader.cs
Normal file
160
src/RynthCore.PluginSdk/Net/NetReader.cs
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Net/NetReader.cs
|
||||
// Bounds-checked little-endian reader for server message bodies.
|
||||
//
|
||||
// Every read returns false instead of throwing when the data runs out, so a parser
|
||||
// given a short or unexpected message fails cleanly. Written for RynthCore (same rules
|
||||
// as the engine's PropertyWire reader); also compiled into the engine.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.PluginSdk.Net;
|
||||
|
||||
/// <summary>Reads AC wire types from a span: u16/u32/f32/f64, 16-bit-length strings, packed lists and tables.</summary>
|
||||
public ref struct NetReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _s;
|
||||
private int _pos;
|
||||
|
||||
public NetReader(ReadOnlySpan<byte> data)
|
||||
{
|
||||
_s = data;
|
||||
_pos = 0;
|
||||
}
|
||||
|
||||
public int Position => _pos;
|
||||
public int Length => _s.Length;
|
||||
public int Remaining => _s.Length - _pos;
|
||||
|
||||
public bool Has(int n) => n >= 0 && _pos + n <= _s.Length && _pos + n >= _pos;
|
||||
|
||||
public bool Skip(int n)
|
||||
{
|
||||
if (!Has(n)) return false;
|
||||
_pos += n;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool U8(out byte v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(1)) return false;
|
||||
v = _s[_pos++];
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool U16(out ushort v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(2)) return false;
|
||||
v = BinaryPrimitives.ReadUInt16LittleEndian(_s.Slice(_pos));
|
||||
_pos += 2;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool U32(out uint v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(4)) return false;
|
||||
v = BinaryPrimitives.ReadUInt32LittleEndian(_s.Slice(_pos));
|
||||
_pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool I32(out int v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(4)) return false;
|
||||
v = BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos));
|
||||
_pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool U64(out ulong v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(8)) return false;
|
||||
v = BinaryPrimitives.ReadUInt64LittleEndian(_s.Slice(_pos));
|
||||
_pos += 8;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool F32(out float v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(4)) return false;
|
||||
v = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos)));
|
||||
_pos += 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool F64(out double v)
|
||||
{
|
||||
v = 0;
|
||||
if (!Has(8)) return false;
|
||||
v = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(_s.Slice(_pos)));
|
||||
_pos += 8;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A u32 used as a flag: any non-zero value is true.</summary>
|
||||
public bool Bool32(out bool v)
|
||||
{
|
||||
v = false;
|
||||
if (!U32(out uint raw)) return false;
|
||||
v = raw != 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AC's 16-bit-length string: u16 length, that many single-byte characters, then zero
|
||||
/// padding so that 2 + length is a multiple of 4. The long form (length 0xFFFF followed
|
||||
/// by a u32) isn't used by the messages parsed here and is refused.
|
||||
/// </summary>
|
||||
public bool String16L(out string v)
|
||||
{
|
||||
v = string.Empty;
|
||||
if (!U16(out ushort len) || len == 0xFFFF || !Has(len)) return false;
|
||||
v = len == 0 ? string.Empty : Encoding.Latin1.GetString(_s.Slice(_pos, len));
|
||||
_pos += len;
|
||||
return Skip((4 - ((2 + len) & 3)) & 3);
|
||||
}
|
||||
|
||||
/// <summary>A packed list's header: u32 count, sanity-checked against the bytes left (each item at least <paramref name="minItemSize"/> bytes).</summary>
|
||||
public bool ListCount(out int count, int minItemSize)
|
||||
{
|
||||
count = 0;
|
||||
if (!U32(out uint n)) return false;
|
||||
if (minItemSize < 1) minItemSize = 1;
|
||||
if (n > (uint)(Remaining / minItemSize)) return false;
|
||||
count = (int)n;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A packed hash table's header: u16 count, u16 bucket count (ignored), sanity-checked like <see cref="ListCount"/>.</summary>
|
||||
public bool TableCount(out int count, int minEntrySize)
|
||||
{
|
||||
count = 0;
|
||||
if (!U16(out ushort n) || !U16(out _)) return false;
|
||||
if (minEntrySize < 1) minEntrySize = 1;
|
||||
if (n > Remaining / minEntrySize) return false;
|
||||
count = n;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>A packed list of u32 (u32 count, then the values).</summary>
|
||||
public bool U32List(out uint[] values)
|
||||
{
|
||||
values = Array.Empty<uint>();
|
||||
if (!ListCount(out int n, 4)) return false;
|
||||
if (n == 0) return true;
|
||||
var a = new uint[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
if (!U32(out a[i])) return false;
|
||||
values = a;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
104
src/RynthCore.PluginSdk/Net/ServerMessage.cs
Normal file
104
src/RynthCore.PluginSdk/Net/ServerMessage.cs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
// ============================================================================
|
||||
// RynthCore.PluginSdk - Net/ServerMessage.cs
|
||||
// One reassembled server-to-client message, as RynthPluginOnServerMessage gets it.
|
||||
//
|
||||
// Plugin side (API v78+):
|
||||
// 1. In Init (or Tick), tell the engine what you want:
|
||||
// Host.SetServerMessageInterest(
|
||||
// new uint[] { ServerOpcode.HearEmote, ServerOpcode.HearSoulEmote },
|
||||
// new uint[] { GameEventType.FellowshipFullUpdate, GameEventType.FriendsUpdate });
|
||||
// 2. Export the callback (NativeAOT plugin):
|
||||
// [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage",
|
||||
// CallConvs = new[] { typeof(CallConvCdecl) })]
|
||||
// static unsafe void OnServerMessage(uint opcode, byte* data, int length)
|
||||
// {
|
||||
// var msg = ServerMessage.FromCallback(opcode, data, length);
|
||||
// if (msg.IsGameEvent && msg.EventType == GameEventType.FellowshipFullUpdate
|
||||
// && FellowshipFullUpdate.TryParse(msg.EventBody, out var f)) { ... }
|
||||
// }
|
||||
// `data` is the message after its u32 opcode and is valid only during the call; copy
|
||||
// what you keep. Messages arrive on the plugin pump, in the order they finished
|
||||
// arriving, possibly before the client itself has applied them.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
|
||||
namespace RynthCore.PluginSdk.Net;
|
||||
|
||||
/// <summary>A server message: its opcode and the bytes after the opcode. For game events (0xF7B0) also the event header.</summary>
|
||||
public readonly ref struct ServerMessage
|
||||
{
|
||||
public const uint GameEventOpcode = 0xF7B0;
|
||||
|
||||
public uint Opcode { get; }
|
||||
|
||||
/// <summary>The bytes after the u32 opcode.</summary>
|
||||
public ReadOnlySpan<byte> Body { get; }
|
||||
|
||||
public ServerMessage(uint opcode, ReadOnlySpan<byte> body)
|
||||
{
|
||||
Opcode = opcode;
|
||||
Body = body;
|
||||
}
|
||||
|
||||
/// <summary>Wraps RynthPluginOnServerMessage's arguments (no copy).</summary>
|
||||
public static unsafe ServerMessage FromCallback(uint opcode, byte* data, int length)
|
||||
=> new(opcode, data != null && length > 0 ? new ReadOnlySpan<byte>(data, length) : ReadOnlySpan<byte>.Empty);
|
||||
|
||||
/// <summary>From a whole message as it is on the wire (u32 opcode first).</summary>
|
||||
public static bool TryFromWire(ReadOnlySpan<byte> message, out ServerMessage m)
|
||||
{
|
||||
if (message.Length < 4)
|
||||
{
|
||||
m = default;
|
||||
return false;
|
||||
}
|
||||
m = new ServerMessage(BinaryPrimitives.ReadUInt32LittleEndian(message), message.Slice(4));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True for a game event (opcode 0xF7B0) with its 12-byte event header.</summary>
|
||||
public bool IsGameEvent => Opcode == GameEventOpcode && Body.Length >= 12;
|
||||
|
||||
/// <summary>Game event: the object it is for (the player).</summary>
|
||||
public uint EventObjectId => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body) : 0;
|
||||
|
||||
/// <summary>Game event: the server's per-player game event sequence.</summary>
|
||||
public uint EventSequence => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(4)) : 0;
|
||||
|
||||
/// <summary>Game event: its type (see <see cref="GameEventType"/>); 0 for other messages.</summary>
|
||||
public uint EventType => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(8)) : 0;
|
||||
|
||||
/// <summary>Game event: the bytes after the event type.</summary>
|
||||
public ReadOnlySpan<byte> EventBody => IsGameEvent ? Body.Slice(12) : ReadOnlySpan<byte>.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Top-level server message opcodes the SDK parses (and a few landmarks).</summary>
|
||||
public static class ServerOpcode
|
||||
{
|
||||
public const uint HearEmote = 0x01E0;
|
||||
public const uint HearSoulEmote = 0x01E2;
|
||||
public const uint HearSpeech = 0x02BB;
|
||||
public const uint HearRangedSpeech = 0x02BC;
|
||||
public const uint GameEvent = 0xF7B0;
|
||||
/// <summary>Pass in the opcode list to get every message.</summary>
|
||||
public const uint All = 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
/// <summary>Game event types (inside opcode 0xF7B0) the SDK parses.</summary>
|
||||
public static class GameEventType
|
||||
{
|
||||
public const uint PopUpString = 0x0004;
|
||||
public const uint FriendsUpdate = 0x0021;
|
||||
public const uint FellowshipQuit = 0x00A3;
|
||||
public const uint FellowshipDismiss = 0x00A4;
|
||||
public const uint ChannelBroadcast = 0x0147;
|
||||
public const uint ConfirmationRequest = 0x0274;
|
||||
public const uint AllegianceLoginNotification = 0x027A;
|
||||
public const uint HearDirectSpeech = 0x02BD;
|
||||
public const uint FellowshipFullUpdate = 0x02BE;
|
||||
public const uint FellowshipDisband = 0x02BF;
|
||||
public const uint FellowshipUpdateFellow = 0x02C0;
|
||||
public const uint TransientString = 0x02EB;
|
||||
}
|
||||
|
|
@ -18,4 +18,16 @@
|
|||
<AssemblyName>RynthCore.PluginSdk</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The engine's API version, compiled in so RynthCoreHost.CurrentApiVersion can't drift from it. -->
|
||||
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Plugin manifests: generated from the plugin's csproj and embedded in its DLL (see the file).
|
||||
Packed as build\RynthCore.PluginSdk.targets so a PackageReference imports it by itself; with
|
||||
a ProjectReference, Directory.Build.targets imports it (RynthSuite\Plugins does). -->
|
||||
<None Include="build\RynthCore.PluginSdk.targets" Pack="true" PackagePath="build\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -153,6 +153,15 @@ public struct RynthCoreApiNative
|
|||
public IntPtr GetServerInfoFn; // int GetServerInfo(byte* worldName, int capacity) -> flags (bit0 Aelrynth, bit1 staging, bit2 world name known)
|
||||
// v76: close an external container (corpse, chest) like the client's window close
|
||||
public IntPtr CloseContainerFn; // int CloseContainer(uint containerId) -> 1 sent or queued
|
||||
// v77: the client's screen (UIFlow mode) and which UI hooks (screen, cleanup, tooltip, drag, drop) are live
|
||||
public IntPtr GetScreenModeFn; // int GetScreenMode(int* previousMode) -> mode, 0 unknown
|
||||
public IntPtr GetUiHookFlagsFn; // uint GetUiHookFlags(void) -> RynthUiHookFlags
|
||||
// v78: reassembled server messages (RynthPluginOnServerMessage export; see Net\ServerMessage.cs)
|
||||
public IntPtr SetServerMessageInterestFn; // int SetServerMessageInterest(uint* opcodes, int n, uint* gameEvents, int m) -> 1 streaming, 2 stream off, 0 no export, -1 unknown caller, -3 bad args
|
||||
// v79: spending experience like the character window's "+" (see TrainingTypes.cs)
|
||||
public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are
|
||||
public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult
|
||||
public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,13 @@ namespace RynthCore.PluginSdk;
|
|||
|
||||
public readonly unsafe struct RynthCoreHost
|
||||
{
|
||||
public const uint CurrentApiVersion = 68;
|
||||
/// <summary>
|
||||
/// The engine API this SDK's table (<see cref="RynthCoreApiNative"/>) covers. It is the engine's
|
||||
/// own constant, compiled in from src\RynthCore.Engine\Plugins\PluginContractVersion.cs, so the
|
||||
/// two can't drift (this said 68 for eight versions); tools\PluginManifestTests checks the
|
||||
/// SDK's table really reaches it.
|
||||
/// </summary>
|
||||
public const uint CurrentApiVersion = RynthCore.Engine.Plugins.PluginContractVersion.Current;
|
||||
|
||||
/// <summary>
|
||||
/// The oldest engine API a plugin built on this SDK loads on by default
|
||||
|
|
@ -138,6 +144,17 @@ public readonly unsafe struct RynthCoreHost
|
|||
public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero;
|
||||
/// <summary>v76: <see cref="CloseContainer"/> (close a corpse or chest like the client's window close).</summary>
|
||||
public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero;
|
||||
/// <summary>v77: <see cref="GetScreenMode"/>, <see cref="GetUiHookFlags"/> and the UI callbacks
|
||||
/// (OnScreenChanged, OnClientCleanup, OnTooltipShow/Hide, OnDragStart, OnItemDropped).</summary>
|
||||
public bool HasUiHooks => _api.Version >= 77 && _api.GetScreenModeFn != IntPtr.Zero && _api.GetUiHookFlagsFn != IntPtr.Zero;
|
||||
|
||||
/// <summary>v78: <see cref="SetServerMessageInterest"/> (reassembled server messages on RynthPluginOnServerMessage).</summary>
|
||||
public bool HasServerMessages => _api.Version >= 78 && _api.SetServerMessageInterestFn != IntPtr.Zero;
|
||||
|
||||
/// <summary>v79: <see cref="TryGetTrainingInfo"/>, <see cref="Raise"/> and <see cref="TrainSkill"/>
|
||||
/// (spend unassigned XP and skill credits like the character window).</summary>
|
||||
public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero
|
||||
&& _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero;
|
||||
public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero;
|
||||
public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero;
|
||||
public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero;
|
||||
|
|
@ -1687,6 +1704,110 @@ public readonly unsafe struct RynthCoreHost
|
|||
((delegate* unmanaged[Cdecl]<uint, int>)_api.CloseContainerFn)(containerId) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v77: the client's screen, the UIFlow mode (<see cref="RynthScreenMode"/>): the world,
|
||||
/// character select, the intro... <see cref="RynthScreenMode.Unknown"/> before the engine
|
||||
/// has seen one, and on an engine before v77 (check <see cref="HasUiHooks"/>).
|
||||
/// <paramref name="previousMode"/> is the screen before it. Any thread.
|
||||
/// </summary>
|
||||
public int GetScreenMode(out int previousMode)
|
||||
{
|
||||
previousMode = 0;
|
||||
if (!HasUiHooks) return 0;
|
||||
int prev = 0;
|
||||
int mode = ((delegate* unmanaged[Cdecl]<int*, int>)_api.GetScreenModeFn)(&prev);
|
||||
previousMode = prev;
|
||||
return mode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v77: which UI hooks are live on this client (<see cref="RynthUiHookFlags"/>), i.e. which of
|
||||
/// the v77 callbacks can arrive. <see cref="RynthUiHookFlags.None"/> on an engine before v77.
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public RynthUiHookFlags GetUiHookFlags()
|
||||
=> HasUiHooks ? (RynthUiHookFlags)((delegate* unmanaged[Cdecl]<uint>)_api.GetUiHookFlagsFn)() : RynthUiHookFlags.None;
|
||||
|
||||
// ─── Spending experience (API v79) ─────────────────────────────────────
|
||||
// See TrainingTypes.cs. The engine reads the player's numbers on AC's main thread every
|
||||
// 2 s while a plugin keeps asking (TryGetTrainingInfo), and raises only against numbers
|
||||
// at most info.StaleAfterMs old: a Stale result means "ask again in a moment".
|
||||
|
||||
/// <summary>
|
||||
/// v79: unassigned XP, credits and, in <paramref name="entries"/> (may be null), one entry per
|
||||
/// attribute, vital and skill with the XP for +1 and +10. <paramref name="entryCount"/> = the
|
||||
/// entries there are (at most entries.Length are written). False on an engine before v79 or
|
||||
/// while there are no numbers yet (not in the world, or the first read is still coming).
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public bool TryGetTrainingInfo(out TrainingInfoNative info, TrainingEntryNative[]? entries, out int entryCount)
|
||||
{
|
||||
info = default;
|
||||
entryCount = 0;
|
||||
if (!HasTraining) return false;
|
||||
TrainingInfoNative raw = default;
|
||||
raw.Size = (uint)sizeof(TrainingInfoNative);
|
||||
var fn = (delegate* unmanaged[Cdecl]<TrainingInfoNative*, TrainingEntryNative*, int, int>)_api.GetTrainingInfoFn;
|
||||
int n;
|
||||
if (entries is { Length: > 0 })
|
||||
fixed (TrainingEntryNative* p = entries) n = fn(&raw, p, entries.Length);
|
||||
else
|
||||
n = fn(&raw, null, 0);
|
||||
info = raw;
|
||||
entryCount = Math.Max(0, n);
|
||||
return raw.Size >= 8 && (raw.Flags & TrainingInfoFlags.HaveNumbers) != 0 && n > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79: raise one attribute (1..6), vital (1 health, 3 stamina, 5 mana) or trained/specialized
|
||||
/// skill by <paramref name="ranks"/> (1..100) with unassigned XP, like the character window's
|
||||
/// "+". <paramref name="expectedXp"/> is the cost the user confirmed (the entry's CostOne /
|
||||
/// CostTen); the engine refuses with <see cref="RaiseResult.CostChanged"/> when the cost now
|
||||
/// differs (0 skips that check). <paramref name="xpSent"/> = the XP sent. Any thread.
|
||||
/// </summary>
|
||||
public RaiseResult Raise(TrainingKind kind, uint stype, uint ranks, long expectedXp, out long xpSent)
|
||||
{
|
||||
xpSent = 0;
|
||||
if (!HasTraining) return RaiseResult.EngineTooOld;
|
||||
long sent = 0;
|
||||
int r = ((delegate* unmanaged[Cdecl]<uint, uint, uint, long, long*, int>)_api.RaiseFn)((uint)kind, stype, ranks, expectedXp, &sent);
|
||||
xpSent = sent;
|
||||
return (RaiseResult)r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79: train an untrained skill with skill credits (exactly the entry's TrainCredits, which
|
||||
/// the caller passes as <paramref name="expectedCredits"/>; 0 skips that check). Any thread.
|
||||
/// </summary>
|
||||
public RaiseResult TrainSkill(uint stype, int expectedCredits)
|
||||
=> HasTraining
|
||||
? (RaiseResult)((delegate* unmanaged[Cdecl]<uint, int, int>)_api.TrainSkillFn)(stype, expectedCredits)
|
||||
: RaiseResult.EngineTooOld;
|
||||
|
||||
/// <summary>
|
||||
/// v78: which reassembled server messages this plugin wants on its
|
||||
/// <c>RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
|
||||
/// see <see cref="Net.ServerMessage"/> for the export and <see cref="Net.ServerOpcode"/> /
|
||||
/// <see cref="Net.GameEventType"/> for the ids the SDK parses). Replaces the previous set;
|
||||
/// two empty lists turn it off. <paramref name="opcodes"/>: top-level opcodes, 0xF7B0 for
|
||||
/// every game event, <see cref="Net.ServerOpcode.All"/> for everything.
|
||||
/// <paramref name="gameEvents"/>: single game event types. Call from Init, Tick or an event
|
||||
/// handler (the engine identifies the plugin by the call). Returns 1 streaming, 2 accepted
|
||||
/// but the engine's stream is switched off, 0 no export, -1 unknown caller, -3 bad
|
||||
/// arguments, -4 engine predates v78. Check <see cref="HasServerMessages"/>.
|
||||
/// </summary>
|
||||
public int SetServerMessageInterest(ReadOnlySpan<uint> opcodes, ReadOnlySpan<uint> gameEvents)
|
||||
{
|
||||
if (!HasServerMessages)
|
||||
return -4;
|
||||
fixed (uint* ops = opcodes)
|
||||
fixed (uint* evs = gameEvents)
|
||||
{
|
||||
return ((delegate* unmanaged[Cdecl]<uint*, int, uint*, int, int>)_api.SetServerMessageInterestFn)(
|
||||
ops, opcodes.Length, evs, gameEvents.Length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v71: submits this plugin's complete set of script windows (display-list format 1,
|
||||
/// RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2). Call only from the plugin's own tick or
|
||||
|
|
|
|||
18
src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs
Normal file
18
src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.PluginSdk;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's manifest minimum, as an assembly attribute: build\RynthCore.PluginSdk.targets adds
|
||||
/// it from RynthPluginMinEngineApi alongside the embedded manifest. RynthPluginBase.MinimumApiVersion
|
||||
/// defaults to it, so the plugin's own check (which also guards engines from before manifests) and
|
||||
/// the engine's/launcher's manifest check use the same number. Works under NativeAOT.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
|
||||
public sealed class RynthPluginManifestAttribute : Attribute
|
||||
{
|
||||
public RynthPluginManifestAttribute(uint minEngineApi) => MinEngineApi = minEngineApi;
|
||||
|
||||
/// <summary>The manifest's minEngineApi.</summary>
|
||||
public uint MinEngineApi { get; }
|
||||
}
|
||||
158
src/RynthCore.PluginSdk/TrainingTypes.cs
Normal file
158
src/RynthCore.PluginSdk/TrainingTypes.cs
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace RynthCore.PluginSdk;
|
||||
|
||||
// ─── Spending experience (engine API v79) ──────────────────────────────────
|
||||
// What the retail character window's "+" does: raise an attribute, a vital or a
|
||||
// trained skill with unassigned XP, or train an untrained skill with credits.
|
||||
// RynthCoreHost.TryGetTrainingInfo reports the numbers and costs; Raise / TrainSkill
|
||||
// send the client's own CM_Train game actions on AC's main thread.
|
||||
//
|
||||
// if (Host.HasTraining && Host.TryGetTrainingInfo(out var info, entries, out int n))
|
||||
// {
|
||||
// var focus = Array.Find(entries, e => e.Kind == TrainingKind.Attribute && e.Stype == 5);
|
||||
// if (focus.CostOne > 0 && focus.CostOne <= info.UnassignedXp)
|
||||
// Host.Raise(TrainingKind.Attribute, 5, 1, focus.CostOne, out long sent);
|
||||
// }
|
||||
//
|
||||
// Pass the cost the user saw as expectedXp: the engine works the XP out again from
|
||||
// fresh numbers and refuses (CostChanged) when they differ, so a stale screen never
|
||||
// spends a different amount. Spent XP can't be taken back.
|
||||
|
||||
/// <summary>What a raise targets (the API's kind numbers).</summary>
|
||||
public enum TrainingKind : uint
|
||||
{
|
||||
/// <summary>Strength 1, Endurance 2, Quickness 3, Coordination 4, Focus 5, Self 6.</summary>
|
||||
Attribute = 1,
|
||||
/// <summary>A vital's maximum: 1 health, 3 stamina, 5 mana.</summary>
|
||||
Vital = 2,
|
||||
/// <summary>A skill by its id (trained or specialized to raise; untrained to train).</summary>
|
||||
Skill = 3,
|
||||
}
|
||||
|
||||
/// <summary>The engine's answer to <see cref="RynthCoreHost.Raise"/> / <see cref="RynthCoreHost.TrainSkill"/>.</summary>
|
||||
public enum RaiseResult
|
||||
{
|
||||
/// <summary>Sent, or queued for AC's main thread. The new numbers follow within a second or two.</summary>
|
||||
Sent = 1,
|
||||
/// <summary>The client's raise (or train) sender isn't bound on this client build.</summary>
|
||||
Unavailable = 0,
|
||||
NotInWorld = -1,
|
||||
BadArguments = -2,
|
||||
/// <summary>No numbers yet (the engine is reading them); try again in a second.</summary>
|
||||
NotReady = -3,
|
||||
/// <summary>The numbers were too old; a fresh read was asked for. Try again in a moment.</summary>
|
||||
Stale = -4,
|
||||
/// <summary>The cost isn't the one the caller passed: something changed. Refresh and confirm again.</summary>
|
||||
CostChanged = -5,
|
||||
/// <summary>Not enough unassigned XP (or skill credits).</summary>
|
||||
NotEnough = -6,
|
||||
/// <summary>At the top rank, an untrained skill (raise), an already trained skill (train), or no price.</summary>
|
||||
NotRaisable = -7,
|
||||
/// <summary>An earlier raise or train hasn't shown up in the numbers yet (up to 5 s).</summary>
|
||||
Busy = -8,
|
||||
/// <summary>The send failed or the engine's action queue was full.</summary>
|
||||
SendFailed = -9,
|
||||
/// <summary>The engine predates API v79 (SDK-side; the engine never returns it).</summary>
|
||||
EngineTooOld = -100,
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
||||
public static class TrainingInfoFlags
|
||||
{
|
||||
public const uint InWorld = 1u << 0;
|
||||
/// <summary>The attribute, vital and skill raise senders are bound.</summary>
|
||||
public const uint RaiseBound = 1u << 1;
|
||||
/// <summary>The train-with-credits sender is bound.</summary>
|
||||
public const uint TrainBound = 1u << 2;
|
||||
/// <summary>The player's numbers have been read (entries follow).</summary>
|
||||
public const uint HaveNumbers = 1u << 3;
|
||||
/// <summary>The portal SkillTable and XpTable are loaded.</summary>
|
||||
public const uint HaveTables = 1u << 4;
|
||||
/// <summary>A raise or train from the API hasn't landed yet.</summary>
|
||||
public const uint Busy = 1u << 5;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
|
||||
public static class TrainingEntryFlags
|
||||
{
|
||||
/// <summary>Can be raised with XP (attribute, vital, trained or specialized skill below the top).</summary>
|
||||
public const uint Raisable = 1u << 0;
|
||||
public const uint AtTop = 1u << 1;
|
||||
/// <summary>Skills: usable untrained.</summary>
|
||||
public const uint UsableUntrained = 1u << 2;
|
||||
/// <summary>Skills: untrained and trainable with <see cref="TrainingEntryNative.TrainCredits"/> credits.</summary>
|
||||
public const uint Trainable = 1u << 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 GetTrainingInfo header (Pack 4, 64 bytes; later versions only append).
|
||||
/// Mirrors RynthCore.Engine/Plugins/PluginContract.cs TrainingInfoNative exactly.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public unsafe struct TrainingInfoNative
|
||||
{
|
||||
/// <summary>In: sizeof(TrainingInfoNative). Out: bytes the engine wrote.</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="TrainingInfoFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>Changes whenever any number changes.</summary>
|
||||
public uint SnapshotVersion;
|
||||
/// <summary>Milliseconds since the numbers were read; 0xFFFFFFFF = never.</summary>
|
||||
public uint AgeMs;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long UnassignedXp;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long TotalXp;
|
||||
public int Level;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public int SkillCredits;
|
||||
public int EntryCount;
|
||||
/// <summary>Raise refuses numbers older than this (<see cref="RaiseResult.Stale"/>).</summary>
|
||||
public int StaleAfterMs;
|
||||
public fixed uint Reserved[4];
|
||||
|
||||
public readonly bool InWorld => (Flags & TrainingInfoFlags.InWorld) != 0;
|
||||
public readonly bool RaiseBound => (Flags & TrainingInfoFlags.RaiseBound) != 0;
|
||||
public readonly bool TrainBound => (Flags & TrainingInfoFlags.TrainBound) != 0;
|
||||
public readonly bool HaveNumbers => (Flags & TrainingInfoFlags.HaveNumbers) != 0;
|
||||
public readonly bool Busy => (Flags & TrainingInfoFlags.Busy) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 GetTrainingInfo entry: one attribute, vital or skill (Pack 4, 64 bytes; later
|
||||
/// versions only append). Mirrors the engine's TrainingEntryNative exactly.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public struct TrainingEntryNative
|
||||
{
|
||||
/// <summary>1 attribute, 2 vital, 3 skill (<see cref="TrainingKind"/>).</summary>
|
||||
public TrainingKind Kind;
|
||||
/// <summary>Attribute 1..6, vital maximum 1 / 3 / 5, skill id.</summary>
|
||||
public uint Stype;
|
||||
/// <summary>Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise.</summary>
|
||||
public uint Class;
|
||||
public uint Ranks;
|
||||
public uint XpSpent;
|
||||
/// <summary>The innate (starting) level.</summary>
|
||||
public uint Innate;
|
||||
/// <summary>Without enchantments (a vital's maximum).</summary>
|
||||
public int Base;
|
||||
public int Buffed;
|
||||
/// <summary>XP for one more rank; -1 at the top or not raisable.</summary>
|
||||
public long CostOne;
|
||||
/// <summary>XP for ten more ranks; -1 when fewer than ten are left or not raisable.</summary>
|
||||
public long CostTen;
|
||||
public int RanksLeft;
|
||||
/// <summary>Ranks in a row the unassigned XP buys now.</summary>
|
||||
public int Affordable;
|
||||
/// <summary>Untrained skills: the credits to train it (0 = not trainable from the client).</summary>
|
||||
public int TrainCredits;
|
||||
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
|
||||
public readonly bool Raisable => (Flags & TrainingEntryFlags.Raisable) != 0;
|
||||
public readonly bool AtTop => (Flags & TrainingEntryFlags.AtTop) != 0;
|
||||
public readonly bool Trainable => (Flags & TrainingEntryFlags.Trainable) != 0;
|
||||
}
|
||||
59
src/RynthCore.PluginSdk/UiTypes.cs
Normal file
59
src/RynthCore.PluginSdk/UiTypes.cs
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.PluginSdk;
|
||||
|
||||
// ─── The client's screens and UI hooks (engine API v77) ─────────────────────
|
||||
// RynthCoreHost.GetScreenMode / GetUiHookFlags, and the callbacks
|
||||
// RynthPluginBase.OnScreenChanged, OnClientCleanup, OnTooltipShow, OnTooltipHide,
|
||||
// OnDragStart and OnItemDropped. Check RynthCoreHost.HasUiHooks first: an engine
|
||||
// before v77 has neither the functions nor the callbacks.
|
||||
|
||||
/// <summary>The client's screen: its UIFlow mode (the client's own ids).</summary>
|
||||
public static class RynthScreenMode
|
||||
{
|
||||
/// <summary>Not known yet (or an engine before v77).</summary>
|
||||
public const int Unknown = 0;
|
||||
public const int Intro = 0x10000001;
|
||||
public const int Disconnected = 0x10000002;
|
||||
public const int DataPatch = 0x10000003;
|
||||
public const int Credits = 0x10000005;
|
||||
/// <summary>The world: the character is logged in.</summary>
|
||||
public const int World = 0x10000008;
|
||||
public const int Epilogue = 0x10000009;
|
||||
public const int CharacterSelect = 0x1000000A;
|
||||
public const int CharacterCreation = 0x1000000B;
|
||||
|
||||
/// <summary>A short name for logs.</summary>
|
||||
public static string Name(int mode) => mode switch
|
||||
{
|
||||
Unknown => "unknown",
|
||||
Intro => "Intro",
|
||||
Disconnected => "Disconnected",
|
||||
DataPatch => "DataPatch",
|
||||
Credits => "Credits",
|
||||
World => "World",
|
||||
Epilogue => "Epilogue",
|
||||
CharacterSelect => "CharacterSelect",
|
||||
CharacterCreation => "CharacterCreation",
|
||||
_ => $"0x{mode:X8}",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Which UI hooks are live (RynthCoreHost.GetUiHookFlags), so which callbacks can arrive.</summary>
|
||||
[Flags]
|
||||
public enum RynthUiHookFlags : uint
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>OnScreenChanged comes from the screen-change hook, as it happens.</summary>
|
||||
ScreenHook = 1u << 0,
|
||||
/// <summary>OnScreenChanged comes from the engine's mode poll instead (a tick late).</summary>
|
||||
ScreenPoll = 1u << 1,
|
||||
/// <summary>OnClientCleanup will come when the client shuts down.</summary>
|
||||
ClientCleanup = 1u << 2,
|
||||
TooltipShow = 1u << 3,
|
||||
TooltipHide = 1u << 4,
|
||||
DragStart = 1u << 5,
|
||||
ItemDropped = 1u << 6,
|
||||
/// <summary>The client's cleanup has started: no more ticks or events.</summary>
|
||||
CleanupStarted = 1u << 7,
|
||||
}
|
||||
259
src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets
Normal file
259
src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
<Project>
|
||||
<!--
|
||||
RynthCore plugin manifests, generated from the plugin's csproj.
|
||||
|
||||
A plugin opts in by setting RynthPluginMinEngineApi (the oldest engine API it runs on: its
|
||||
highest API use that is NOT behind a Has*/version check). The build then
|
||||
1. writes obj\...\rynth-plugin.json from the csproj:
|
||||
name RynthPluginName (default: AssemblyName without "RynthCore.Plugin.")
|
||||
version Version (Publish-Update.ps1 passes -p:Version=yyyy.m.d.n)
|
||||
minEngineApi RynthPluginMinEngineApi
|
||||
maxEngineApi RynthPluginMaxEngineApi (optional; leave unset - the table is append-only)
|
||||
dependencies @(RynthPluginDependency) Include = plugin name, metadata MinVersion, Optional="true"
|
||||
author RynthPluginAuthor (default: Authors, then Company)
|
||||
description RynthPluginDescription (default: Description)
|
||||
homepage RynthPluginHomepage (default: PackageProjectUrl)
|
||||
license RynthPluginLicense (default: PackageLicenseExpression)
|
||||
2. adds [assembly: RynthPluginManifest(minEngineApi)], which RynthPluginBase.MinimumApiVersion
|
||||
defaults to (the plugin's own runtime check, which also covers engines from before
|
||||
manifests), and generates RynthPluginInfo (Name, Version, MinEngineApi constants) in the
|
||||
plugin's root namespace for code that wants them;
|
||||
3. embeds the JSON in the compiled assembly as a Windows resource (RCDATA
|
||||
"RYNTH_PLUGIN_MANIFEST"). NativeAOT copies the assembly's Windows resources into the
|
||||
native DLL, so the published plugin carries it too. The engine and the launcher read it
|
||||
from the file without loading the DLL (RynthCore.PluginSdk.Manifest.PluginManifestReader).
|
||||
|
||||
Example:
|
||||
<RynthPluginMinEngineApi>71</RynthPluginMinEngineApi>
|
||||
<ItemGroup><RynthPluginDependency Include="RynthAi" Optional="true" /></ItemGroup>
|
||||
|
||||
RynthPluginManifest=false turns it off. A PackageReference to RynthCore.PluginSdk imports this
|
||||
file by itself (build\); a ProjectReference needs an Import (RynthSuite\Plugins\Directory.Build.targets).
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
|
||||
<RynthCoreSdkApiVersion>79</RynthCoreSdkApiVersion>
|
||||
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<RynthPluginName Condition="'$(RynthPluginName)' == ''">$([System.Text.RegularExpressions.Regex]::Replace('$(AssemblyName)', '^RynthCore\.Plugin\.', ''))</RynthPluginName>
|
||||
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == '' and '$(Authors)' != '' and '$(Authors)' != '$(AssemblyName)'">$(Authors)</RynthPluginAuthor>
|
||||
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == ''">$(Company)</RynthPluginAuthor>
|
||||
<RynthPluginDescription Condition="'$(RynthPluginDescription)' == ''">$(Description)</RynthPluginDescription>
|
||||
<RynthPluginHomepage Condition="'$(RynthPluginHomepage)' == ''">$(PackageProjectUrl)</RynthPluginHomepage>
|
||||
<RynthPluginLicense Condition="'$(RynthPluginLicense)' == ''">$(PackageLicenseExpression)</RynthPluginLicense>
|
||||
<_RynthPluginManifestJson>$(IntermediateOutputPath)rynth-plugin.json</_RynthPluginManifestJson>
|
||||
<_RynthPluginManifestEmbedded>$(IntermediateOutputPath)rynth-plugin.embedded</_RynthPluginManifestEmbedded>
|
||||
<_RynthPluginInfoSource>$(IntermediateOutputPath)RynthPluginInfo.g.cs</_RynthPluginInfoSource>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- [assembly: RynthPluginManifest(min)]: RynthPluginBase.MinimumApiVersion's default, so the
|
||||
plugin's own check matches its manifest without any code in the plugin. -->
|
||||
<ItemGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<AssemblyAttribute Include="RynthCore.PluginSdk.RynthPluginManifestAttribute">
|
||||
<_Parameter1>$(RynthPluginMinEngineApi)</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<UsingTask TaskName="RynthWritePluginManifest" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
|
||||
<Task>
|
||||
<Code Type="Class" Language="cs"><![CDATA[
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.Build.Framework;
|
||||
using Microsoft.Build.Utilities;
|
||||
|
||||
public class RynthWritePluginManifest : Task
|
||||
{
|
||||
[Required] public string Name { get; set; }
|
||||
public string Version { get; set; }
|
||||
[Required] public string MinEngineApi { get; set; }
|
||||
public string MaxEngineApi { get; set; }
|
||||
[Required] public string SdkApiVersion { get; set; }
|
||||
public string Author { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Homepage { get; set; }
|
||||
public string License { get; set; }
|
||||
public ITaskItem[] Dependencies { get; set; }
|
||||
public string RootNamespace { get; set; }
|
||||
[Required] public string JsonPath { get; set; }
|
||||
[Required] public string InfoSourcePath { get; set; }
|
||||
|
||||
public override bool Execute()
|
||||
{
|
||||
uint min, max = 0, sdk;
|
||||
if (!uint.TryParse(MinEngineApi.Trim(), out min) || min == 0)
|
||||
{ Log.LogError("RynthPluginMinEngineApi must be a positive whole number (got '{0}').", MinEngineApi); return false; }
|
||||
if (!uint.TryParse(SdkApiVersion.Trim(), out sdk)) sdk = 0;
|
||||
if (sdk != 0 && min > sdk)
|
||||
{ Log.LogError("RynthPluginMinEngineApi {0} is newer than this SDK's engine API ({1}): update RynthCore.PluginSdk.", min, sdk); return false; }
|
||||
if (!string.IsNullOrWhiteSpace(MaxEngineApi) && (!uint.TryParse(MaxEngineApi.Trim(), out max) || max < min))
|
||||
{ Log.LogError("RynthPluginMaxEngineApi '{0}' must be a whole number no lower than RynthPluginMinEngineApi ({1}).", MaxEngineApi, min); return false; }
|
||||
if (Name.Trim().Length == 0) { Log.LogError("RynthPluginName is empty."); return false; }
|
||||
|
||||
var sb = new StringBuilder();
|
||||
sb.Append("{\n");
|
||||
sb.Append(" \"schema\": 1,\n");
|
||||
sb.Append(" \"name\": ").Append(Q(Name.Trim())).Append(",\n");
|
||||
if (!string.IsNullOrWhiteSpace(Version)) sb.Append(" \"version\": ").Append(Q(Version.Trim())).Append(",\n");
|
||||
sb.Append(" \"minEngineApi\": ").Append(min).Append(",\n");
|
||||
if (max != 0) sb.Append(" \"maxEngineApi\": ").Append(max).Append(",\n");
|
||||
sb.Append(" \"dependencies\": [");
|
||||
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
bool first = true;
|
||||
foreach (ITaskItem d in Dependencies ?? new ITaskItem[0])
|
||||
{
|
||||
string dn = d.ItemSpec.Trim();
|
||||
if (dn.Length == 0 || !seen.Add(dn)) continue;
|
||||
if (string.Equals(dn, Name.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{ Log.LogError("RynthPluginDependency '{0}' is the plugin itself.", dn); return false; }
|
||||
string mv = (d.GetMetadata("MinVersion") ?? "").Trim();
|
||||
bool opt = string.Equals((d.GetMetadata("Optional") ?? "").Trim(), "true", StringComparison.OrdinalIgnoreCase);
|
||||
sb.Append(first ? "\n" : ",\n");
|
||||
first = false;
|
||||
sb.Append(" { \"name\": ").Append(Q(dn));
|
||||
if (mv.Length > 0) sb.Append(", \"minVersion\": ").Append(Q(mv));
|
||||
if (opt) sb.Append(", \"optional\": true");
|
||||
sb.Append(" }");
|
||||
}
|
||||
sb.Append(first ? "]" : "\n ]");
|
||||
AppendOpt(sb, "author", Author);
|
||||
AppendOpt(sb, "description", Description);
|
||||
AppendOpt(sb, "homepage", Homepage);
|
||||
AppendOpt(sb, "license", License);
|
||||
sb.Append("\n}\n");
|
||||
WriteIfChanged(JsonPath, sb.ToString());
|
||||
|
||||
string ns = string.IsNullOrWhiteSpace(RootNamespace) ? "" : RootNamespace.Trim();
|
||||
var cs = new StringBuilder();
|
||||
cs.Append("// <auto-generated>RynthCore.PluginSdk.targets, from the csproj's plugin manifest properties.</auto-generated>\n");
|
||||
if (ns.Length > 0) cs.Append("namespace ").Append(ns).Append(";\n\n");
|
||||
cs.Append("/// <summary>This plugin's manifest (embedded in the DLL as RYNTH_PLUGIN_MANIFEST).</summary>\n");
|
||||
cs.Append("internal static class RynthPluginInfo\n{\n");
|
||||
cs.Append(" public const string Name = ").Append(Q(Name.Trim())).Append(";\n");
|
||||
cs.Append(" public const string Version = ").Append(Q((Version ?? "").Trim())).Append(";\n");
|
||||
cs.Append(" /// <summary>The oldest engine API this plugin runs on (its manifest's minEngineApi).</summary>\n");
|
||||
cs.Append(" public const uint MinEngineApi = ").Append(min).Append(";\n");
|
||||
cs.Append("}\n");
|
||||
WriteIfChanged(InfoSourcePath, cs.ToString());
|
||||
return !Log.HasLoggedErrors;
|
||||
}
|
||||
|
||||
private static void AppendOpt(StringBuilder sb, string key, string value)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return;
|
||||
sb.Append(",\n ").Append(Q(key)).Append(": ").Append(Q(value.Trim()));
|
||||
}
|
||||
|
||||
private static void WriteIfChanged(string path, string text)
|
||||
{
|
||||
if (File.Exists(path) && File.ReadAllText(path) == text) return;
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
|
||||
File.WriteAllText(path, text, new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
private static string Q(string s)
|
||||
{
|
||||
var sb = new StringBuilder("\"");
|
||||
foreach (char c in s)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
]]></Code>
|
||||
</Task>
|
||||
</UsingTask>
|
||||
|
||||
<UsingTask TaskName="RynthEmbedPluginManifest" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
|
||||
<Task>
|
||||
<Code Type="Class" Language="cs"><![CDATA[
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Build.Framework;
|
||||
using Microsoft.Build.Utilities;
|
||||
|
||||
public class RynthEmbedPluginManifest : Task
|
||||
{
|
||||
[Required] public string AssemblyPath { get; set; }
|
||||
[Required] public string ManifestPath { get; set; }
|
||||
[Required] public string MarkerPath { get; set; }
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr BeginUpdateResourceW(string pFileName, bool bDeleteExistingResources);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool UpdateResourceW(IntPtr hUpdate, IntPtr lpType, string lpName, ushort wLanguage, byte[] lpData, uint cb);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool EndUpdateResourceW(IntPtr hUpdate, bool fDiscard);
|
||||
|
||||
public override bool Execute()
|
||||
{
|
||||
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
Log.LogWarning("RynthCore plugin manifest: embedding needs Windows (UpdateResource); '{0}' has no manifest.", AssemblyPath);
|
||||
return true;
|
||||
}
|
||||
byte[] data = File.ReadAllBytes(ManifestPath);
|
||||
IntPtr h = BeginUpdateResourceW(AssemblyPath, false);
|
||||
if (h == IntPtr.Zero)
|
||||
{ Log.LogError("RynthCore plugin manifest: BeginUpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(Marshal.GetLastWin32Error()).Message); return false; }
|
||||
// RT_RCDATA (10), "RYNTH_PLUGIN_MANIFEST", language neutral.
|
||||
if (!UpdateResourceW(h, (IntPtr)10, "RYNTH_PLUGIN_MANIFEST", 0, data, (uint)data.Length))
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
EndUpdateResourceW(h, true);
|
||||
Log.LogError("RynthCore plugin manifest: UpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(err).Message);
|
||||
return false;
|
||||
}
|
||||
if (!EndUpdateResourceW(h, false))
|
||||
{ Log.LogError("RynthCore plugin manifest: EndUpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(Marshal.GetLastWin32Error()).Message); return false; }
|
||||
File.WriteAllText(MarkerPath, DateTime.UtcNow.ToString("o"));
|
||||
Log.LogMessage(MessageImportance.Normal, "RynthCore plugin manifest embedded in {0}", AssemblyPath);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]]></Code>
|
||||
</Task>
|
||||
</UsingTask>
|
||||
|
||||
<!-- 1 + 2: the JSON and RynthPluginInfo, before compiling (RynthPluginInfo is compiled in). -->
|
||||
<Target Name="RynthGeneratePluginManifest" BeforeTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(RynthPluginMinEngineApi)"
|
||||
MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)"
|
||||
Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)"
|
||||
Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)"
|
||||
Dependencies="@(RynthPluginDependency)" RootNamespace="$(RootNamespace)"
|
||||
JsonPath="$(_RynthPluginManifestJson)" InfoSourcePath="$(_RynthPluginInfoSource)" />
|
||||
<ItemGroup>
|
||||
<Compile Include="$(_RynthPluginInfoSource)" />
|
||||
<FileWrites Include="$(_RynthPluginManifestJson);$(_RynthPluginInfoSource);$(_RynthPluginManifestEmbedded)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<!-- 3: into the compiled assembly, before it is copied to bin or compiled by NativeAOT (ILC reads
|
||||
@(IntermediateAssembly)). Incremental: again only when the assembly or the JSON changed. -->
|
||||
<Target Name="RynthEmbedPluginManifest" AfterTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'"
|
||||
Inputs="@(IntermediateAssembly);$(_RynthPluginManifestJson)" Outputs="$(_RynthPluginManifestEmbedded)">
|
||||
<RynthEmbedPluginManifest AssemblyPath="@(IntermediateAssembly->'%(FullPath)')" ManifestPath="$(_RynthPluginManifestJson)"
|
||||
MarkerPath="$(_RynthPluginManifestEmbedded)" />
|
||||
</Target>
|
||||
</Project>
|
||||
Loading…
Reference in a new issue