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:
Tom Bohar 2026-10-05 14:59:43 -04:00
commit 913a2a00b6
110 changed files with 12560 additions and 1151 deletions

View file

@ -32,3 +32,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Chorizite DatReaderWriter (format reference for the dat readers)
- What: the layout of Asheron's Call .dat files (header, block chains, the directory B-tree) and of the Texture and Palette files, used as the reference when RynthCore's own dat reader and icon decoder were written (2026-10-05). The code is RynthCore's own (MIT); this notice is kept because the library was the format reference.
- Where: `src/RynthCore.StatusAgent/Dat/DatDatabase.cs` and `Dat/IconDecoder.cs`, and `src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs`. The notice is also in `DatDatabase.cs`'s header. The DXT decoder (`Dat/DxtUtil.cs`) was written from the public S3TC block-compression format.
- Source: https://github.com/Chorizite/DatReaderWriter (ACClientLib)
- Licence: MIT, reproduced below.
```
MIT License
Copyright 2024 ACClientLib
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

View file

@ -205,6 +205,24 @@ A simple phone view: green if every client is `healthy`, red if any is
---
## Raising from the phone (`raiseXp`)
With the RynthRemote plugin 0.4 on an engine with plugin API v79, DrakRemote's Skills tab can spend
unassigned XP (and skill credits) the way the character window's "+" does:
- The plugin's character sheet (`GET /character`, passed through as the plugin wrote it) carries
`ranks`, `xpSpent`, `cost1`, `cost10`, `affordable` (and `trainCredits` on skills) per row and a
`raise` block (`available`, `reason`, `busy`, `last` = the last result). Its status file says
`"raiseXp": true` when the client can.
- The agent sends `capabilities.raiseXp` (remote control on, character sheets, and a client that
can) and `clients[].raiseXp`.
- `POST /command` `{"pid":N,"action":"raise","value":"{\"kind\":\"attribute|vital|skill|train\",\"id\":..,\"count\":1..100,\"cost\":N,\"nonce\":..}"}`
needs the token like every command, and is accepted only for a pid the last cycle read whose
plugin reports `raiseXp` (404 unknown client, 409 not available). The value is checked and
rewritten in that fixed shape (`RemoteParity.CheckRaise`); `cost` is the cost the user confirmed
and is required. The plugin refuses commands over 30 s old and repeated nonces; the engine works
the cost out again from fresh numbers and refuses when it differs.
## Removing the feature entirely
Everything is tagged `[status-export]` in the engine — `grep -r "[status-export]"

View file

@ -0,0 +1,86 @@
#Requires -Version 7
<#
.SYNOPSIS
Reads RynthCore plugin manifests and the engine's plugin API version, for Publish-Update.ps1.
.DESCRIPTION
Dot-source it: . (Join-Path $PSScriptRoot "PluginManifest.ps1")
Get-RynthPluginManifest <dll> the manifest embedded in a plugin DLL (RCDATA resource
RYNTH_PLUGIN_MANIFEST, written by the SDK's build targets)
as an object, or $null when the DLL has none. The DLL is
mapped as a data file only (LOAD_LIBRARY_AS_DATAFILE): none
of its code runs.
Get-RynthEngineApi <repoRoot> PluginContractVersion.Current from the engine's source.
Read-only; safe to run on its own (tools\PluginManifestTests\Test-PluginManifestPs.ps1 does).
#>
if (-not ('RynthCore.Publish.PeResource' -as [type])) {
Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Publish
{
public static class PeResource
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr LoadLibraryExW(string path, IntPtr file, uint flags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary(IntPtr module);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr FindResourceW(IntPtr module, string name, IntPtr type);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadResource(IntPtr module, IntPtr res);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LockResource(IntPtr data);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint SizeofResource(IntPtr module, IntPtr res);
private const uint LOAD_LIBRARY_AS_DATAFILE = 0x2;
private const uint LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x20;
/// <summary>RCDATA resource <paramref name="name"/> of a PE file, or null if it has none.</summary>
public static byte[] ReadRcData(string path, string name)
{
IntPtr module = LoadLibraryExW(path, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE);
if (module == IntPtr.Zero)
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "can't map " + path);
try
{
IntPtr res = FindResourceW(module, name, (IntPtr)10); // RT_RCDATA
if (res == IntPtr.Zero) return null;
uint size = SizeofResource(module, res);
IntPtr data = LockResource(LoadResource(module, res));
if (data == IntPtr.Zero) return null;
byte[] bytes = new byte[size];
Marshal.Copy(data, bytes, 0, (int)size);
return bytes;
}
finally
{
FreeLibrary(module);
}
}
}
}
'@
}
function Get-RynthPluginManifest([Parameter(Mandatory)][string]$Path) {
$bytes = [RynthCore.Publish.PeResource]::ReadRcData((Resolve-Path $Path).Path, "RYNTH_PLUGIN_MANIFEST")
if ($null -eq $bytes) { return $null }
$json = [Text.Encoding]::UTF8.GetString($bytes).TrimStart([char]0xFEFF).TrimEnd([char]0)
$m = $json | ConvertFrom-Json
if (-not $m.name) { throw "$Path has a plugin manifest without a name" }
if ($null -ne $m.minEngineApi -and -not ("$($m.minEngineApi)" -match '^\d+$')) { throw "$Path has a plugin manifest with a bad minEngineApi '$($m.minEngineApi)'" }
return $m
}
function Get-RynthEngineApi([Parameter(Mandatory)][string]$RepoRoot) {
$file = Join-Path $RepoRoot "src\RynthCore.Engine\Plugins\PluginContractVersion.cs"
$m = [regex]::Match((Get-Content $file -Raw), 'const\s+uint\s+Current\s*=\s*(\d+)')
if (-not $m.Success) { throw "No PluginContractVersion.Current in $file" }
return [int]$m.Groups[1].Value
}

View file

@ -267,6 +267,13 @@ $pluginDescriptions = @{
RynthOracle = "Quests, character, titles and leaderboards."
RynthInventory = "Search every character's items."
}
# Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi
# goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers
# (from plugin manifests on) don't install a plugin build the installed engine would refuse; they
# say "needs RynthCore <version>" instead. Older launchers ignore both fields.
. (Join-Path $ScriptDir "PluginManifest.ps1")
$engineApi = Get-RynthEngineApi $RepoRoot
Write-Host " engine plugin API: $engineApi"
$plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) {
$pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', ''
$entry = [ordered]@{
@ -278,6 +285,17 @@ $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Nam
}
if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] }
else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." }
$pm = Get-RynthPluginManifest $dll.FullName
if ($pm) {
if ($pm.name -ne $pluginName) { throw "$($dll.Name): its manifest says '$($pm.name)', the feed would say '$pluginName'." }
if ($pm.version -and $pm.version -ne $Version) { throw "$($dll.Name): its manifest is version $($pm.version), not $Version (stale build?)." }
$min = [int]$pm.minEngineApi
if ($min -gt $engineApi) { throw "$($dll.Name) needs engine API $min but this release's engine is $engineApi - it would never load." }
if ($min -gt 0) { $entry.minEngineApi = $min }
Write-Host " $pluginName $($pm.version): engine API $min+"
} else {
Write-Warning "$($dll.Name) has no plugin manifest - launchers install it on any engine."
}
$entry
}
$manifest = [ordered]@{
@ -295,6 +313,8 @@ $manifest = [ordered]@{
url = "$BaseUrl/releases/$release/RynthCore-Setup.exe"
size = $setup.Length
sha256 = Sha256 $setup.FullName
# The plugin API of the engine in this installer (see the plugins' minEngineApi above).
engineApi = $engineApi
}
plugins = @($plugins)
}

View file

@ -456,15 +456,34 @@ internal partial class MainWindow : Window
Foreground = Brush.Parse("#6F7F8A"),
});
var install = new Button
Control install;
if (!a.CanInstall)
{
Content = "Install",
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0),
IsEnabled = !_updateBusy,
};
ToolTip.SetTip(install, $"Download {a.Entry.Name} (checked against the signed update feed) into {Path.GetDirectoryName(a.Path)} and add it to your plugins.");
install.Click += async (_, _) => await InstallAvailablePluginAsync(a);
// Its manifest needs a newer engine than this RynthCore: say so instead of offering it.
install = new TextBlock
{
Text = a.Blocker,
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0),
Foreground = Brush.Parse("#F2C14E"),
TextWrapping = TextWrapping.Wrap,
MaxWidth = 200,
};
ToolTip.SetTip(install, $"This {a.Entry.Name} build needs a newer RynthCore than the one installed. Update RynthCore, then install it.");
}
else
{
var button = new Button
{
Content = "Install",
VerticalAlignment = VerticalAlignment.Center,
Margin = new Thickness(12, 0, 0, 0),
IsEnabled = !_updateBusy,
};
ToolTip.SetTip(button, $"Download {a.Entry.Name} (checked against the signed update feed) into {Path.GetDirectoryName(a.Path)} and add it to your plugins.");
button.Click += async (_, _) => await InstallAvailablePluginAsync(a);
install = button;
}
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*, Auto") };
Grid.SetColumn(stack, 0);
@ -2270,6 +2289,8 @@ internal partial class MainWindow : Window
lines.Add($"Updated this session: {string.Join(", ", _pluginsUpdatedThisSession)}. Loads the next time AC starts.");
var local = c?.Plugins.Where(p => p.State == RynthUpdater.PluginState.LocalBuild).Select(p => p.Entry.Name).Distinct().ToList();
if (local is { Count: > 0 }) lines.Add($"Left alone (newer local builds): {string.Join(", ", local)}.");
var waiting = c?.PluginsWaitingForCore.GroupBy(p => p.Entry.Name).Select(g => $"{g.Key} ({g.First().Blocker})").ToList();
if (waiting is { Count: > 0 }) lines.Add($"Waiting for a RynthCore update: {string.Join(", ", waiting)}.");
UpdateStatusText.Text = string.Join("\n", lines);
PluginsTabProgressBar.IsVisible = card.ShowProgress;
PluginsTabProgressBar.IsIndeterminate = card.ShowProgress && card.ProgressPercent == null;

View file

@ -47,6 +47,8 @@
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
<!-- The plugin API of the engine installed with this launcher (RynthUpdater.InstalledEngineApi). -->
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />
</ItemGroup>

View file

@ -37,7 +37,15 @@ internal sealed partial class RynthUpdater
private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant);
/// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary>
public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew);
public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew)
{
/// <summary>
/// Empty when it can be installed; otherwise shown instead of the Install button: the feed's
/// build needs a newer engine than the one installed ("needs RynthCore 2026.10.6.1").
/// </summary>
public string Blocker { get; init; } = "";
public bool CanInstall => Blocker.Length == 0;
}
/// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary>
public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded);
@ -119,7 +127,7 @@ internal sealed partial class RynthUpdater
if (listed.Contains(e.File) || skip.Contains(e.File)) continue;
if (TargetPath(e, suite) is not { } target) continue;
bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor;
result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew));
result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew) { Blocker = EngineBlocker(e, manifest) });
}
// New ones first, then by name.
return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList();
@ -145,6 +153,9 @@ internal sealed partial class RynthUpdater
throw new InvalidOperationException($"{e.Name} is already in your plugin list");
string target = TargetPath(e, SuiteDir(check.Manifest, paths))
?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed");
// A build the installed engine would refuse (its manifest's minEngineApi) isn't installed.
if (EngineBlocker(e, check.Manifest) is { Length: > 0 } blocker)
throw new InvalidOperationException($"{e.Name} {blocker}");
if (File.Exists(target))
{
@ -181,6 +192,17 @@ internal sealed partial class RynthUpdater
return OneLine(d.GetString(), MaxDescriptionLength);
}
/// <summary>
/// An optional engine API number ("minEngineApi" on a plugin, "engineApi" on the core; written
/// since plugin manifests). Missing or unreadable: 0, no limit, as with older feeds.
/// </summary>
private static uint ReadApi(JsonElement o, string name)
{
if (!o.TryGetProperty(name, out JsonElement v)) return 0;
if (v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint n)) return n;
return 0;
}
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
private static IReadOnlyList<string> ReadChanges(JsonElement r)
{

View file

@ -42,9 +42,14 @@ internal sealed partial class RynthUpdater
/// One plugin in the feed. <paramref name="Description"/> is the optional one-line "description"
/// (written since 2026.10.5); older feeds have none and the launcher's own table fills in
/// (<see cref="DescribePlugin"/>). Launchers before it ignore the field.
/// <paramref name="MinEngineApi"/> is the optional "minEngineApi", from the plugin's embedded
/// manifest (Publish-Update.ps1 copies it): the oldest engine plugin API the build runs on.
/// 0 (older feeds, plugins without a manifest) means no limit. See <see cref="EngineBlocker"/>.
/// </summary>
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = "");
public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256);
public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = "",
uint MinEngineApi = 0);
/// <summary>The core release. <paramref name="EngineApi"/>: the optional "engineApi", its engine's plugin API (0 = not said).</summary>
public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256, uint EngineApi = 0);
public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes,
InstallerEntry Core, IReadOnlyList<PluginEntry> Plugins, NavDataEntry? NavData = null)
{
@ -56,8 +61,17 @@ internal sealed partial class RynthUpdater
}
/// <summary>One installed copy of a plugin the feed knows.</summary>
public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State);
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild }
public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State)
{
/// <summary>For <see cref="PluginState.NeedsNewerEngine"/>: "needs RynthCore 2026.10.6.1".</summary>
public string Blocker { get; init; } = "";
}
/// <summary>
/// NeedsNewerEngine: the feed's build needs a newer engine plugin API than the RynthCore installed
/// here, so the installed copy is kept until RynthCore itself is updated (the engine would refuse
/// the new build and the player would lose the plugin meanwhile).
/// </summary>
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild, NeedsNewerEngine }
/// <summary>A plugin split out of one the player has, to be installed beside it (see <see cref="Companions"/>).</summary>
public sealed record CompanionInstall(PluginEntry Entry, string Path, string Reason);
@ -66,6 +80,8 @@ internal sealed partial class RynthUpdater
{
public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease;
public IEnumerable<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
/// <summary>Plugin updates held back until RynthCore is updated (<see cref="PluginState.NeedsNewerEngine"/>).</summary>
public IEnumerable<PluginStatus> PluginsWaitingForCore => Plugins.Where(p => p.State == PluginState.NeedsNewerEngine);
/// <summary>New plugins that came out of an installed one; installed with the plugin updates.</summary>
public IReadOnlyList<CompanionInstall> Companions { get; init; } = Array.Empty<CompanionInstall>();
/// <summary>Feed plugins not in the plugin list, for the player to install or not (see <see cref="GetAvailable"/>).</summary>
@ -113,6 +129,26 @@ internal sealed partial class RynthUpdater
_appDir = appDir ?? AppContext.BaseDirectory;
}
/// <summary>
/// The plugin API of the engine installed with this launcher. The installer ships the launcher and
/// the engine together (a core update replaces both), so it is the engine's own constant,
/// compiled in from PluginContractVersion.cs. Tests set it.
/// </summary>
internal uint InstalledEngineApi { get; set; } = RynthCore.Engine.Plugins.PluginContractVersion.Current;
/// <summary>
/// Empty when the installed engine runs <paramref name="e"/>; otherwise what the player needs, shown
/// in place of the Install button: "needs RynthCore 2026.10.6.1" when the feed's own core release
/// brings a new enough engine, else "needs a newer RynthCore (API 77)".
/// </summary>
public string EngineBlocker(PluginEntry e, Manifest manifest)
{
if (e.MinEngineApi == 0 || e.MinEngineApi <= InstalledEngineApi) return "";
InstallerEntry core = manifest.Core;
bool coreBringsIt = core.EngineApi >= e.MinEngineApi && core.Release > InstalledCoreRelease && core.Version.Length > 0;
return coreBringsIt ? $"needs RynthCore {core.Version}" : $"needs a newer RynthCore (API {e.MinEngineApi})";
}
/// <summary>False until the signing keys exist: with no trusted key nothing can verify.</summary>
public bool IsConfigured => _trustedKeys.Count > 0;
@ -158,13 +194,16 @@ internal sealed partial class RynthUpdater
continue; // not a plugin this feed ships (a private or third-party one): never touched
PluginState state;
string blocker = "";
if (string.Equals(Sha256File(path), entry.Sha256, StringComparison.OrdinalIgnoreCase))
state = PluginState.UpToDate;
else if (File.GetLastWriteTimeUtc(path) > manifest.PublishedUtc.AddMinutes(1))
state = PluginState.LocalBuild; // newer than the release: someone's own build, leave it
else if ((blocker = EngineBlocker(entry, manifest)).Length > 0)
state = PluginState.NeedsNewerEngine; // keep the copy that runs until RynthCore catches up
else
state = PluginState.NeedsUpdate;
statuses.Add(new PluginStatus(entry, path, state));
statuses.Add(new PluginStatus(entry, path, state) { Blocker = blocker });
}
List<CompanionInstall> companions = FindCompanions(manifest, pluginPaths);
@ -191,6 +230,7 @@ internal sealed partial class RynthUpdater
string.Equals(Path.GetFileName(p), parentFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p));
PluginEntry? child = manifest.Plugins.FirstOrDefault(e => string.Equals(e.Name, childName, StringComparison.OrdinalIgnoreCase));
if (parent == null || child == null) continue;
if (EngineBlocker(child, manifest).Length > 0) continue; // not yet: offered once RynthCore is updated
if (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase)))
{
MarkCompanionOffered(childName); // already there: nothing to do, ever
@ -336,7 +376,8 @@ internal sealed partial class RynthUpdater
JsonElement c = r.GetProperty("core");
var core = new InstallerEntry(c.GetProperty("release").GetInt32(), c.GetProperty("version").GetString() ?? "",
CheckUrl(c.GetProperty("url").GetString()), c.GetProperty("size").GetInt64(), c.GetProperty("sha256").GetString() ?? "");
CheckUrl(c.GetProperty("url").GetString()), c.GetProperty("size").GetInt64(), c.GetProperty("sha256").GetString() ?? "",
ReadApi(c, "engineApi"));
var plugins = new List<PluginEntry>();
foreach (JsonElement p in r.GetProperty("plugins").EnumerateArray())
@ -346,7 +387,7 @@ internal sealed partial class RynthUpdater
throw new InvalidDataException($"bad plugin file name '{file}'");
plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file,
CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "",
ReadDescription(p)));
ReadDescription(p), ReadApi(p, "minEngineApi")));
}
return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "",

View file

@ -419,6 +419,9 @@ internal static class AcMainThreadQueue
// writes its own lines, so the chat window keeps the order lines arrived in.
try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { }
// Keep the off-thread combat-mode cache true to the client (stale after a hot reload).
CombatModeHooks.MainThreadRefresh();
// Deep-audit finding #22 (2026-06-18): these three queues are
// documented as deliberately separate from the gesture-gated action
// ring below specifically so appraisals/chat "can never get

View file

@ -144,6 +144,8 @@ internal static class CharacterManagementHooks
{
Volatile.Write(ref _publishedMode, mode);
Volatile.Write(ref _modePublished, 1);
// Seeds UiFlowHooks' mode; drives its screen events when the UseNewMode hook isn't live.
UiFlowHooks.OnModePolled(mode);
}
else
{

View file

@ -106,19 +106,30 @@ internal static class ClientActionHooks
return CombatActionHooks.CastSpell(targetId, spellId);
}
// Movement calls below are the plugin API's only way in (PluginManager's callbacks), so each
// one is traced here with the calling plugin: RynthLog.Move, behind RynthLog.MoveTraceEnabled.
private static string MoveArg(System.FormattableString s) =>
RynthLog.MoveTraceEnabled ? System.FormattableString.Invariant(s) : "";
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = MovementActionHooks.HoldKeyRun)
{
return MovementActionHooks.DoMovement(motion, speed, holdKey);
bool ok = MovementActionHooks.DoMovement(motion, speed, holdKey);
RynthLog.Move("DoMovement", MoveArg($"0x{motion:X8}, {speed:0.##}, {holdKey}"), ok, a: motion, b: (uint)holdKey);
return ok;
}
public static bool StopMovement(uint motion, int holdKey = MovementActionHooks.HoldKeyRun)
{
return MovementActionHooks.StopMovement(motion, holdKey);
bool ok = MovementActionHooks.StopMovement(motion, holdKey);
RynthLog.Move("StopMovement", MoveArg($"0x{motion:X8}, {holdKey}"), ok, a: motion, b: (uint)holdKey);
return ok;
}
public static bool JumpNonAutonomous(float extent)
{
return MovementActionHooks.JumpNonAutonomous(extent);
bool ok = MovementActionHooks.JumpNonAutonomous(extent);
RynthLog.Move("JumpNonAutonomous", MoveArg($"{extent:0.##}"), ok);
return ok;
}
public static bool SetAutonomyLevel(uint level)
@ -128,37 +139,51 @@ internal static class ClientActionHooks
public static bool SetAutoRun(bool enabled)
{
return CommandInterpreterHooks.SetAutoRun(enabled);
bool ok = CommandInterpreterHooks.SetAutoRun(enabled);
RynthLog.Move("SetAutoRun", enabled ? "True" : "False", ok, a: enabled ? 1u : 0u);
return ok;
}
public static bool TapJump()
{
return CommandInterpreterHooks.TapJump();
bool ok = CommandInterpreterHooks.TapJump();
RynthLog.Move("TapJump", "", ok);
return ok;
}
public static bool CommenceJump()
{
return CommandInterpreterHooks.CommenceJump();
bool ok = CommandInterpreterHooks.CommenceJump();
RynthLog.Move("CommenceJump", "", ok);
return ok;
}
public static bool DoJump(bool autonomous)
{
return CommandInterpreterHooks.DoJump(autonomous);
bool ok = CommandInterpreterHooks.DoJump(autonomous);
RynthLog.Move("DoJump", autonomous ? "True" : "False", ok);
return ok;
}
public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
{
return PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
bool ok = PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC);
RynthLog.Move("LaunchJumpWithMotion", MoveArg($"shift={shift}, w={holdW}, x={holdX}, z={holdZ}, c={holdC}"), ok);
return ok;
}
public static bool SetMotion(uint motion, bool enabled)
{
return CommandInterpreterHooks.SetMotion(motion, enabled);
bool ok = CommandInterpreterHooks.SetMotion(motion, enabled);
RynthLog.Move("SetMotion", MoveArg($"0x{motion:X8}, {enabled}"), ok, a: motion, b: enabled ? 1u : 0u);
return ok;
}
public static bool StopCompletely()
{
return CommandInterpreterHooks.StopCompletely();
bool ok = CommandInterpreterHooks.StopCompletely();
RynthLog.Move("StopCompletely", "", ok);
return ok;
}
public static bool TurnToHeading(float headingDegrees)
@ -168,11 +193,12 @@ internal static class ClientActionHooks
// Off AC's main thread (plugin pump) SetPlayerHeadingDirect only parks the
// heading in AcMainThreadQueue's coalesced slot and returns true; the snap
// (and the no-player CommandInterpreter fallback below) run in Drain.
if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees))
return true;
// Fallback: command interpreter gradual turn
return CommandInterpreterHooks.TurnToHeading(headingDegrees);
bool ok = PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees)
// Fallback: command interpreter gradual turn
|| CommandInterpreterHooks.TurnToHeading(headingDegrees);
// Successive turns from one caller collapse into one line whatever the angle (nav steers every tick).
RynthLog.Move("TurnToHeading", MoveArg($"{headingDegrees:0.0}"), ok, collapseByKind: true);
return ok;
}
public static bool TryGetPlayerHeading(out float headingDegrees)

View file

@ -301,6 +301,44 @@ internal static class CombatModeHooks
PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode);
}
// Main-thread refresh of the off-thread cache (2026-10-05). After the engine hot reload at
// 13:42:55 Drakkon was in Magic (he had just cast Heal Self), but _lastObservedCombatMode
// starts at NonCombat in a new engine and only the SetCombatMode detour (a mode CHANGE) or a
// main-thread ReadCurrentCombatMode moved it. The plugin pump reads off the main thread, so
// the engine synced "combat mode 1" to the plugins at 13:43:03 and RynthAi's heal at 13:43:12
// asked for a Magic stance the client already had (RequestCombatMode req=8 clientField=8),
// then waited out the stance settle. Drain calls this every frame; it reads the client's field
// at most every MainThreadRefreshMs and, when the cache was wrong, heals it and tells the
// plugins the way the detour does.
private static long _lastMainThreadRefreshMs;
private const long MainThreadRefreshMs = 250;
/// <summary>AC's main thread only (AcMainThreadQueue.Drain).</summary>
internal static unsafe void MainThreadRefresh()
{
if (!IsInstalled) return;
long now = Environment.TickCount64;
if (now - _lastMainThreadRefreshMs < MainThreadRefreshMs) return;
_lastMainThreadRefreshMs = now;
try
{
IntPtr slot = (IntPtr)_combatSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(slot)) return;
IntPtr combatSystem = *(IntPtr*)slot;
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset)) return;
int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset));
if (raw is not (CombatActionHooks.CombatModeNonCombat or CombatActionHooks.CombatModeMelee
or CombatActionHooks.CombatModeMissile or CombatActionHooks.CombatModeMagic))
return; // not a mode (a singleton being torn down): leave the cache alone
int previous = Interlocked.Exchange(ref _lastObservedCombatMode, raw);
if (raw == previous) return;
RynthLog.Compat($"CombatModeHooks: the cached combat mode was {previous} but the client reads {raw} " +
"(no SetCombatMode seen since this engine started, e.g. after a hot reload): cache healed, plugins told.");
PluginManager.QueueCombatModeChange(raw, previous);
}
catch { }
}
private static int NormalizeCombatMode(int combatMode)
{
return combatMode switch

View file

@ -12,7 +12,8 @@
// Want / Current / RefreshSoon any thread (the panel: AC's render thread).
//
// Demand-driven: nothing is read unless a reader called Want in the last 2 s,
// then at most every 500 ms. Reads go into one preallocated work buffer; a new
// then at most every 500 ms (WantSlow, the plugin API's GetTrainingInfo: in the
// last 5 s, then at most every 2 s). Reads go into one preallocated work buffer; a new
// snapshot object is published (and allocated) only when something changed,
// so an idle open panel costs a compare every half second.
// ============================================================================
@ -173,6 +174,8 @@ internal static class PlayerProgressHooks
{
private const int RefreshMs = 500;
private const int WantWindowMs = 2000;
private const int SlowRefreshMs = 2000;
private const int SlowWantWindowMs = 5000;
// StatMod type flags (ACE EnchantmentTypeFlags) that mark a buff on a stat.
internal const uint ModAttribute = 0x1, ModSecondAttribute = 0x2, ModSkill = 0x10;
@ -180,7 +183,9 @@ internal static class PlayerProgressHooks
private const uint ModAnyStat = ModAttribute | ModSecondAttribute | ModSkill;
private static long _wantedUntilMs;
private static long _slowWantedUntilMs;
private static long _nextReadMs;
private static long _lastReadMs;
private static int _version;
private static PlayerProgress? _published;
@ -198,9 +203,23 @@ internal static class PlayerProgressHooks
public static void Want() =>
Volatile.Write(ref _wantedUntilMs, Environment.TickCount64 + WantWindowMs);
/// <summary>
/// A background reader (the plugin API, TrainingApi) wants data for the next 5 s, read at
/// most every 2 s, so a plugin polling every few seconds doesn't keep the 2 Hz panel rate up.
/// Any thread.
/// </summary>
public static void WantSlow() =>
Volatile.Write(ref _slowWantedUntilMs, Environment.TickCount64 + SlowWantWindowMs);
/// <summary>Read again at the next main-thread tick (after a raise). Any thread.</summary>
public static void RefreshSoon() => Volatile.Write(ref _nextReadMs, 0);
/// <summary>
/// Environment.TickCount64 of the last successful read, changed or not (0 = never), so a
/// reader can tell how old <see cref="Current"/>'s numbers are. Any thread.
/// </summary>
public static long LastReadMs => Volatile.Read(ref _lastReadMs);
/// <summary>The last published read, or null. Never written again once published. Any thread.</summary>
public static PlayerProgress? Current => Volatile.Read(ref _published);
@ -213,21 +232,25 @@ internal static class PlayerProgressHooks
if (!MainThreadGuard.IsOnMainThread())
return;
long now = Environment.TickCount64;
if (now > Volatile.Read(ref _wantedUntilMs) || now < Volatile.Read(ref _nextReadMs))
bool panel = now <= Volatile.Read(ref _wantedUntilMs);
if ((!panel && now > Volatile.Read(ref _slowWantedUntilMs)) || now < Volatile.Read(ref _nextReadMs))
return;
Volatile.Write(ref _nextReadMs, now + RefreshMs);
Volatile.Write(ref _nextReadMs, now + (panel ? RefreshMs : SlowRefreshMs));
if (!ClientObjectHooks.ReadPlayerProgressLive(Work))
return;
CopyStatBuffs(Work);
PlayerProgress? current = Volatile.Read(ref _published);
if (current != null && current.SameAs(Work))
return;
var snapshot = new PlayerProgress();
snapshot.CopyFrom(Work);
snapshot.Version = ++_version;
Volatile.Write(ref _published, snapshot);
if (current == null || !current.SameAs(Work))
{
var snapshot = new PlayerProgress();
snapshot.CopyFrom(Work);
snapshot.Version = ++_version;
Volatile.Write(ref _published, snapshot);
}
// After publishing: a reader that sees this time sees this read's numbers.
Volatile.Write(ref _lastReadMs, Environment.TickCount64);
}
/// <summary>The player's enchantments that change a skill, attribute or vital (not vitae).</summary>

View file

@ -31,6 +31,10 @@
//
// Every call runs on AC's main thread: off it (or with defer) the request goes
// through AcMainThreadQueue (ActionKind.Train) and the drain calls back in.
// Only in the world (TrainingApi.InWorld), checked again when the drain sends:
// a raise queued just before a logout is dropped, not sent to the next screen.
// The plugin API (v79) reaches these through TrainingApi, which also works the
// XP out and checks it (TrainingCosts).
// ============================================================================
using System;
@ -112,6 +116,11 @@ internal static unsafe class PlayerTraining
{
if (!Bound(kind) || !ValidTarget(kind, stype) || xp == 0)
return false;
if (!TrainingApi.InWorld)
{
RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world");
return false;
}
if (defer || !MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp);

View file

@ -320,6 +320,9 @@ internal static class RadarHooks
IntPtr inst = _gmRadarUIInstance;
if (inst == IntPtr.Zero)
return false;
// Outside the world AC has freed the radar panel this points at (UiFlowHooks).
if (!UiFlowHooks.InWorldOrUnknown || UiFlowHooks.ClientCleanupStarted)
return false;
if (_uiElementGetSurfaceBoxAddress == IntPtr.Zero)
return false;

View file

@ -15,6 +15,8 @@ namespace RynthCore.Engine.Compatibility;
/// We read the function address, install a MinHook detour, call through to the
/// original on every receive, then hand the buffer to RawPacketParser for
/// opcode extraction. The hook is purely read-only and never modifies traffic.
/// It also feeds Net.ServerMessageStream (API v78), which copies fragment datagrams
/// for reassembly on the plugin pump while a plugin wants server messages.
/// </summary>
internal static class RawPacketHooks
{
@ -82,6 +84,11 @@ internal static class RawPacketHooks
// This guard prevents any parser bug from crashing the client.
try
{
// v78 server-message stream: a volatile check, and while a plugin wants
// messages, one copy into a ring for the pump (never blocks, never allocates).
// A MSG_PEEK (0x2) read leaves the datagram queued; the real read copies it.
if ((flags & 0x2) == 0)
Net.ServerMessageStream.OnDatagram((byte*)buf, bytesRead);
RawPacketParser.Parse((byte*)buf, bytesRead);
}
catch

View file

@ -43,12 +43,20 @@ namespace RynthCore.Engine.Compatibility;
/// never sees it; every other "/rv" line still goes to the plugin.</item>
/// <item><c>/rc server [auto|aelrynth|other]</c> — which server the engine detects
/// (<see cref="ServerInfo"/>) and why; aelrynth/other force it for this session.</item>
/// <item><c>/rc hooks [on|off &lt;name&gt;]</c> (alias <c>/rc uihooks</c>) — the UI hooks
/// (screen mode, client cleanup, tooltip, drag/drop; <see cref="UiHookRegistry"/>):
/// status, or switch one off/on (now and in engine.json).</item>
/// <item><c>/rc mastery</c> — the Aelrynth mastery feed's state (<see cref="MasteryFeed"/>),
/// and ask the server for /mastery-data again.</item>
/// <item><c>/rc worldlayer [auto|uipass|transition|endscene]</c> — where the world overlays
/// (nameplates, combat text, Nav3D markers) draw in AC's frame
/// (<see cref="D3D9.Nav3DRenderInjector"/>): alone it reports the path and counters;
/// a mode forces it for this session (A/B checks). Auto at every start; not saved.</item>
/// <item><c>/rc netmsg [status|on|off|log on|off|capture on|off]</c> - the reassembled
/// server-message stream for plugins (<see cref="Net.ServerMessageStream"/>, API v78):
/// counters; on/off for this session (engine.json "ServerMessageStream": false is the
/// kill switch); log = the SDK parsers run on live messages, results to the log;
/// capture = raw datagrams to a .rnc file for tools/NetMessageTests.</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
@ -153,6 +161,26 @@ internal static class RynthCoreChatCommands
return true;
}
// /rc hooks [on|off <name>] : the UI hooks (screen mode, client cleanup, tooltip, drag/drop)
if (IsVerb(sub, "hooks", out string hooksArgs) || IsVerb(sub, "uihooks", out hooksArgs))
{
try { HandleHooksCommand(hooksArgs); }
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hooks failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream
if (IsVerb(sub, "netmsg", out string netArgs))
{
try
{
foreach (string l in Net.ServerMessageStream.HandleCommand(netArgs))
Reply(l);
}
catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc netmsg failed - {ex.GetType().Name}: {ex.Message}"); }
return true;
}
// /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only);
// clear = VTank was stopped with its own button, which the engine can't see.
if (IsVerb(sub, "vtank", out string vtankArgs))
@ -660,6 +688,30 @@ internal static class RynthCoreChatCommands
return s != null && float.TryParse(s, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out v);
}
/// <summary>
/// /rc hooks: one line per UI hook (UiHookRegistry: UseNewMode, ClientCleanup,
/// StartTooltip, ResetTooltip, CheckTooltip, StartDragandDrop, CatchDroppedItem) with
/// its address, how it was found, on/off and how often it fired, then the screen and
/// tooltip/drag state. "/rc hooks off &lt;name&gt;" makes that hook pass straight to AC
/// now and leaves it out at the next start (engine.json DisabledUiHooks); "on" undoes it.
/// </summary>
private static void HandleHooksCommand(string args)
{
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length == 2 && (parts[0].Equals("on", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("off", StringComparison.OrdinalIgnoreCase)))
{
Reply(UiHookRegistry.SetEnabled(parts[1], parts[0].Equals("on", StringComparison.OrdinalIgnoreCase)));
return;
}
if (parts.Length != 0 && !(parts.Length == 1 && parts[0].Equals("status", StringComparison.OrdinalIgnoreCase)))
{
Reply("Usage: /rc hooks [status] | /rc hooks on|off <name>");
return;
}
foreach (string line in UiHookRegistry.DescribeLines())
Reply(line);
}
/// <summary>"on"/"off" sets; anything else (or nothing) toggles.</summary>
private static bool Flag(string? value, bool current) =>
value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current };

View file

@ -347,10 +347,12 @@ internal static class SmartBoxHooks
// v70: the sequence and its error code as one 64-bit value, so a reader
// on the plugin pump never pairs one UseDone's number with another's code.
System.Threading.Interlocked.Exchange(ref _useDoneLast, ((long)(uint)seq << 32) | err);
if (_useDoneLogCount < 25)
// Every one while RynthLog.ActionDoneTraceEnabled (the default; 2026-10-05: the
// first 25 of a session couldn't show which completion a held cast was waiting on).
if (RynthLog.ActionDoneTraceEnabled || _useDoneLogCount < 25)
{
_useDoneLogCount++;
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}");
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}{(err == 0x1D ? " (too busy)" : err == 0 ? " (done)" : "")}");
}
break;
}

View file

@ -0,0 +1,278 @@
// ============================================================================
// RynthCore.Engine - Compatibility/TrainingApi.cs
//
// Plugin API v79: spending experience the way the retail character window's
// "+" does (docs/IMGUI_SKILLS.md "Raising"), for plugins (the RynthRemote
// plugin, so the DrakRemote phone app can raise from the Skills tab).
//
// GetTrainingInfo the numbers a raise needs and what it costs: unassigned XP,
// skill credits, and per attribute / vital / skill the ranks,
// XP spent, base and buffed value, the XP for +1 and +10, how
// many ranks the unassigned XP buys, the credits to train.
// Raise n ranks of one attribute, vital or trained skill. The engine
// works the XP out from the same numbers (portal XpTable) and
// refuses unless it equals what the caller confirmed.
// TrainSkill an untrained skill -> trained, for exactly the SkillTable's
// credit price.
//
// Sources: PlayerProgressHooks (the player's qualities, read on AC's main thread;
// WantSlow keeps them coming every 2 s while a plugin asks) and SkillDat (the
// portal SkillTable and XpTable, read once in the background). The sends are
// PlayerTraining's: the client's own CM_Train senders, on AC's main thread
// (queued in AcMainThreadQueue from any other thread).
//
// Guards: in the world only (login complete, the world screen, no logout, no
// teardown, the snapshot is this character's); numbers at most 3 s old (else
// a read is asked for and Stale comes back: try again a moment later); one
// raise at a time (Busy until the unassigned XP or the credits change, or 5 s).
// Any thread.
// ============================================================================
using System;
using RynthCore.Engine.ImGuiBackend.Panels;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class TrainingApi
{
/// <summary>Numbers older than this are not raised against.</summary>
internal const int StaleAfterMs = 3000;
private const int BusyMs = 5000;
public const uint KindAttribute = 1, KindVital = 2, KindSkill = 3;
private static readonly object Gate = new();
private static long _busyUntilMs;
private static long _busyUnassigned;
private static int _busyCredits;
/// <summary>The player is in the world and its objects are live (same test as the
/// main-thread snapshots, plus the world screen and no client cleanup). Any thread.</summary>
public static bool InWorld =>
LoginLifecycleHooks.HasObservedLoginComplete
&& UiFlowHooks.InWorldOrUnknown
&& !UiFlowHooks.ClientCleanupStarted
&& !LogoutLifecycleHooks.HasObservedLogout
&& !DbCacheTeardownHooks.TeardownActive
&& ClientHelperHooks.GetPlayerId() != 0;
/// <summary>v79 GetTrainingInfo. Returns the number of entries there are (entries may be null to
/// ask; at most maxEntries are written). 0 while there is nothing to report.</summary>
public static int GetInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
{
PlayerProgressHooks.WantSlow();
SkillDat.EnsureLoadQueued();
bool inWorld = InWorld;
uint playerId = inWorld ? ClientHelperHooks.GetPlayerId() : 0;
PlayerProgress? s = PlayerProgressHooks.Current;
if (s != null && (s.PlayerId != playerId || !inWorld)) s = null;
SkillDatTables? dat = SkillDat.Tables;
long now = Environment.TickCount64;
long readAt = PlayerProgressHooks.LastReadMs;
int count = 0;
if (s != null && dat != null)
{
count = 6 + 3;
for (uint id = 1; id <= PlayerProgress.MaxSkill; id++)
if (dat.Skills.ContainsKey(id)) count++;
}
if (info != null && info->Size >= 8)
{
TrainingInfoNative o = default;
uint flags = 0;
if (inWorld) flags |= TrainingInfoFlags.InWorld;
if (PlayerTraining.Available) flags |= TrainingInfoFlags.RaiseBound;
if (PlayerTraining.TrainAvailable) flags |= TrainingInfoFlags.TrainBound;
if (s != null) flags |= TrainingInfoFlags.HaveNumbers;
if (dat != null) flags |= TrainingInfoFlags.HaveTables;
if (IsBusy(s, now)) flags |= TrainingInfoFlags.Busy;
o.Flags = flags;
o.SnapshotVersion = s != null ? (uint)s.Version : 0;
o.AgeMs = s != null && readAt > 0 ? (uint)Math.Clamp(now - readAt, 0, uint.MaxValue - 1) : uint.MaxValue;
o.UnassignedXp = s?.UnassignedXp ?? -1;
o.TotalXp = s?.TotalXp ?? -1;
o.Level = s?.Level ?? 0;
o.SkillCredits = s?.SkillCredits ?? -1;
o.EntryCount = count;
o.StaleAfterMs = StaleAfterMs;
uint n = Math.Min(info->Size, (uint)sizeof(TrainingInfoNative));
Buffer.MemoryCopy(&o, info, n, n);
info->Size = n;
}
if (entries == null || maxEntries <= 0 || s == null || dat == null)
return count;
int w = 0;
for (uint a = 1; a <= 6 && w < maxEntries; a++)
entries[w++] = Entry(KindAttribute, a, 0, s.AttrRanks[a], s.AttrXpSpent[a], s.AttrInit[a],
(int)s.AttrBase[a], (int)s.AttrBuffed[a], dat.Xp.AttributeXp, s.UnassignedXp);
for (uint v = 1; v <= 3 && w < maxEntries; v++)
entries[w++] = Entry(KindVital, v * 2 - 1, 0, s.VitalRanks[v], s.VitalXpSpent[v], s.VitalInit[v],
(int)s.VitalBase[v], (int)s.VitalBuffed[v], dat.Xp.VitalXp, s.UnassignedXp);
for (uint id = 1; id <= PlayerProgress.MaxSkill && w < maxEntries; id++)
{
if (!dat.Skills.TryGetValue(id, out SkillDatEntry? e)) continue;
uint cls = s.SkillClass[id];
TrainingEntryNative x = Entry(KindSkill, id, cls, s.SkillRanks[id], s.SkillXpSpent[id], s.SkillInit[id],
s.SkillBase[id], s.SkillBuffed[id], TrainingCosts.TableFor(dat.Xp, KindSkill, cls), s.UnassignedXp);
if (e.UsableUntrained) x.Flags |= TrainingEntryFlags.UsableUntrained;
if (cls < 2)
{
x.TrainCredits = Math.Max(0, e.TrainedCost);
if (x.TrainCredits > 0) x.Flags |= TrainingEntryFlags.Trainable;
}
entries[w++] = x;
}
return count;
}
private static TrainingEntryNative Entry(uint kind, uint stype, uint cls, uint ranks, uint spent, uint init,
int baseValue, int buffed, uint[]? table, long unassigned)
{
var x = new TrainingEntryNative
{
Kind = kind, Stype = stype, Class = cls, Ranks = ranks, XpSpent = spent, Innate = init,
Base = baseValue, Buffed = buffed, CostOne = -1, CostTen = -1,
};
if (table != null && table.Length > 0)
{
x.RanksLeft = TrainingCosts.RanksLeft(table, ranks);
if (x.RanksLeft == 0) x.Flags |= TrainingEntryFlags.AtTop;
else x.Flags |= TrainingEntryFlags.Raisable;
x.CostOne = TrainingCosts.CostOf(table, ranks, spent, 1);
x.CostTen = TrainingCosts.CostOf(table, ranks, spent, 10);
x.Affordable = TrainingCosts.Affordable(table, ranks, spent, Math.Max(0, unassigned));
}
return x;
}
private static bool IsBusy(PlayerProgress? s, long now)
{
lock (Gate)
{
if (now >= _busyUntilMs) return false;
// The server answered: the unassigned XP or the credits moved.
if (s != null && (s.UnassignedXp != _busyUnassigned || s.SkillCredits != _busyCredits))
{
_busyUntilMs = 0;
return false;
}
return true;
}
}
/// <summary>The snapshot to act on, or why not.</summary>
private static RaiseStatus Ready(out PlayerProgress? s, out SkillDatTables? dat)
{
PlayerProgressHooks.WantSlow();
SkillDat.EnsureLoadQueued();
s = null;
dat = SkillDat.Tables;
if (!InWorld) return RaiseStatus.NotInWorld;
uint playerId = ClientHelperHooks.GetPlayerId();
s = PlayerProgressHooks.Current;
if (s == null || s.PlayerId != playerId || dat == null || !s.AttributeCacheRead || !s.SkillTableRead)
{
PlayerProgressHooks.RefreshSoon();
return RaiseStatus.NotReady;
}
long read = PlayerProgressHooks.LastReadMs;
if (read <= 0 || Environment.TickCount64 - read > StaleAfterMs)
{
PlayerProgressHooks.RefreshSoon();
return RaiseStatus.Stale;
}
if (IsBusy(s, Environment.TickCount64)) return RaiseStatus.Busy;
return RaiseStatus.Sent;
}
/// <summary>v79 Raise: <paramref name="ranks"/> ranks of one attribute (1..6), vital (1 health,
/// 3 stamina, 5 mana) or trained/specialized skill. <paramref name="xpSent"/> = the XP sent.</summary>
public static RaiseStatus Raise(uint kind, uint stype, uint ranks, long expectedXp, out long xpSent)
{
xpSent = 0;
if (kind is < KindAttribute or > KindSkill || ranks < 1 || ranks > TrainingCosts.MaxRanksPerRaise || expectedXp < 0
|| !ValidTarget(kind, stype))
return RaiseStatus.BadArguments;
if (!PlayerTraining.Available) return RaiseStatus.Unavailable;
RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat);
if (ready != RaiseStatus.Sent) return ready;
uint[]? table;
uint have, spent;
switch (kind)
{
case KindAttribute:
table = dat!.Xp.AttributeXp; have = s!.AttrRanks[stype]; spent = s.AttrXpSpent[stype];
break;
case KindVital:
uint v = (stype + 1) / 2;
table = dat!.Xp.VitalXp; have = s!.VitalRanks[v]; spent = s.VitalXpSpent[v];
break;
default:
table = TrainingCosts.TableFor(dat!.Xp, KindSkill, s!.SkillClass[stype]); have = s.SkillRanks[stype]; spent = s.SkillXpSpent[stype];
break;
}
RaiseStatus check = TrainingCosts.CheckRaise(table, have, spent, s.UnassignedXp, (int)ranks, expectedXp, out long cost);
if (check != RaiseStatus.Sent) return check;
var trainKind = kind switch
{
KindAttribute => PlayerTraining.TrainKind.Attribute,
KindVital => PlayerTraining.TrainKind.Vital,
_ => PlayerTraining.TrainKind.Skill,
};
AcActionTrace.Record("Raise", kind << 16 | stype, (uint)cost);
if (!PlayerTraining.Raise(trainKind, stype, (uint)cost)) return RaiseStatus.SendFailed;
MarkBusy(s);
xpSent = cost;
RynthLog.Compat($"TrainingApi: raise {trainKind} {stype} +{ranks} for {cost:N0} XP (plugin)");
return RaiseStatus.Sent;
}
/// <summary>v79 TrainSkill: untrained -> trained for exactly the SkillTable's credit price.</summary>
public static RaiseStatus TrainSkill(uint stype, int expectedCredits)
{
if (stype < 1 || stype > PlayerProgress.MaxSkill || expectedCredits < 0) return RaiseStatus.BadArguments;
if (!PlayerTraining.TrainAvailable) return RaiseStatus.Unavailable;
RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat);
if (ready != RaiseStatus.Sent) return ready;
if (!dat!.Skills.TryGetValue(stype, out SkillDatEntry? e)) return RaiseStatus.NotRaisable;
RaiseStatus check = TrainingCosts.CheckTrain(s!.SkillClass[stype], e.TrainedCost, s.SkillCredits, expectedCredits);
if (check != RaiseStatus.Sent) return check;
AcActionTrace.Record("TrainSkill", stype, (uint)e.TrainedCost);
if (!PlayerTraining.TrainSkill(stype, (uint)e.TrainedCost)) return RaiseStatus.SendFailed;
MarkBusy(s);
RynthLog.Compat($"TrainingApi: train skill {stype} for {e.TrainedCost} credits (plugin)");
return RaiseStatus.Sent;
}
private static bool ValidTarget(uint kind, uint stype) => kind switch
{
KindAttribute => stype >= 1 && stype <= 6,
KindVital => stype is 1 or 3 or 5,
KindSkill => stype >= 1 && stype <= PlayerProgress.MaxSkill,
_ => false,
};
private static void MarkBusy(PlayerProgress s)
{
lock (Gate)
{
_busyUntilMs = Environment.TickCount64 + BusyMs;
_busyUnassigned = s.UnassignedXp;
_busyCredits = s.SkillCredits;
}
PlayerProgressHooks.RefreshSoon();
}
}

View file

@ -0,0 +1,191 @@
// ============================================================================
// RynthCore.Engine - Compatibility/TrainingCosts.cs
//
// The XP arithmetic behind raising an attribute, a vital or a skill, and the
// checks a raise from the plugin API passes before anything is sent. Pure code
// (no AC memory, no engine state), so tools/TrainingCostTests compiles it in and
// runs it against the XpTable of a real client_portal.dat.
//
// XpTable 0x0E000018 (ACE.DatLoader XpTable; the server raises against the same
// table): file id u32; counts i32 for attributes, vitals, trained skills,
// specialized skills, then the level count u32; then count+1 u32 each for
// attributes, vitals, trained and specialized skills, count+1 u64 levels and
// count+1 u32 skill credits per level. Entry n is the total XP spent at rank n.
//
// Cost of n raises: table[ranks + n] - xpSpent (ACE Player.SpendAttributeXp /
// SpendSkillXp take an XP amount and raise as many ranks as it covers; the retail
// character window sends exactly this for "+1" and "+10": gmAttributeUI /
// gmSkillUI GetCostToRaise / GetCostToRaise10 -> CM_Train::Event_Train*).
// ============================================================================
using System;
using System.Buffers.Binary;
namespace RynthCore.Engine.Compatibility;
/// <summary>The four raise tables of the portal XpTable (index = rank, value = total XP at that rank).</summary>
internal sealed class XpTableData
{
public uint[] AttributeXp = Array.Empty<uint>();
public uint[] VitalXp = Array.Empty<uint>();
public uint[] TrainedXp = Array.Empty<uint>();
public uint[] SpecializedXp = Array.Empty<uint>();
public ulong[] LevelXp = Array.Empty<ulong>();
}
/// <summary>The plugin API's raise and train results (RynthCoreAPI.RaiseFn / TrainSkillFn, v79).</summary>
internal enum RaiseStatus
{
Sent = 1,
/// <summary>The client's raise senders aren't bound on this build.</summary>
Unavailable = 0,
NotInWorld = -1,
BadArguments = -2,
/// <summary>No player snapshot or no XP table yet (both are being fetched; try again in a second).</summary>
NotReady = -3,
/// <summary>The numbers are older than the freshness limit; a new read was asked for. Try again in a second.</summary>
Stale = -4,
/// <summary>The cost the caller expected isn't the cost now (something changed: refresh and ask again).</summary>
CostChanged = -5,
/// <summary>Not enough unassigned XP (or skill credits for a train).</summary>
NotEnough = -6,
/// <summary>Can't be raised: at or past the top rank, an untrained skill, or a skill that can't be trained.</summary>
NotRaisable = -7,
/// <summary>An earlier raise or train hasn't shown up in the numbers yet (5 s at most).</summary>
Busy = -8,
/// <summary>The send failed or the action queue was full.</summary>
SendFailed = -9,
}
internal static class TrainingCosts
{
/// <summary>Most ranks one API raise may buy (the retail window offers 1 and 10).</summary>
public const int MaxRanksPerRaise = 100;
// ── the XpTable ──────────────────────────────────────────────────────
/// <summary>Reads the portal XpTable file (0x0E000018). False when it is short or the counts are absurd.</summary>
public static bool TryParseXpTable(ReadOnlySpan<byte> raw, out XpTableData table)
{
table = new XpTableData();
int p = 0;
if (!U32(raw, ref p, out _)) return false; // file id
if (!U32(raw, ref p, out uint attrs) || !U32(raw, ref p, out uint vitals)
|| !U32(raw, ref p, out uint trained) || !U32(raw, ref p, out uint spec)
|| !U32(raw, ref p, out uint levels))
return false;
if (attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
return false;
if (!U32s(raw, ref p, (int)attrs + 1, out table.AttributeXp)
|| !U32s(raw, ref p, (int)vitals + 1, out table.VitalXp)
|| !U32s(raw, ref p, (int)trained + 1, out table.TrainedXp)
|| !U32s(raw, ref p, (int)spec + 1, out table.SpecializedXp))
return false;
var lv = new ulong[levels + 1];
for (int i = 0; i <= levels; i++)
{
if (p + 8 > raw.Length) return false;
lv[i] = BinaryPrimitives.ReadUInt64LittleEndian(raw.Slice(p, 8));
p += 8;
}
table.LevelXp = lv;
return true;
}
private static bool U32(ReadOnlySpan<byte> b, ref int p, out uint v)
{
v = 0;
if (p + 4 > b.Length) return false;
v = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4));
p += 4;
return true;
}
private static bool U32s(ReadOnlySpan<byte> b, ref int p, int n, out uint[] a)
{
a = Array.Empty<uint>();
if (n < 0 || p + (long)n * 4 > b.Length) return false;
a = new uint[n];
for (int i = 0; i < n; i++) { a[i] = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4)); p += 4; }
return true;
}
// ── arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
/// <summary>The table a stat raises against: attributes, vitals, trained (2) or specialized (3+) skills;
/// null for an untrained or unknown skill (those aren't raised with XP).</summary>
public static uint[]? TableFor(XpTableData t, uint kind, uint skillClass) => kind switch
{
1 => t.AttributeXp,
2 => t.VitalXp,
3 => skillClass >= 3 ? t.SpecializedXp : skillClass == 2 ? t.TrainedXp : null,
_ => null,
};
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1L >= table.Length;
/// <summary>Ranks left to the top of the table.</summary>
public static int RanksLeft(uint[] table, uint ranks) => (int)Math.Max(0L, table.Length - 1L - ranks);
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with
/// <paramref name="spent"/> already spent; -1 past the top; 0 for n &lt; 1.</summary>
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
{
if (n < 1) return 0;
long target = (long)ranks + n;
if (target >= table.Length) return -1;
return Math.Max(0L, (long)table[target] - spent);
}
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top.</summary>
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
{
int lo = 0, hi = RanksLeft(table, ranks);
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
long c = CostOf(table, ranks, spent, mid);
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
}
return lo;
}
// ── the checks before a raise is sent ──────────────────────────────────
/// <summary>
/// Everything a raise of <paramref name="count"/> ranks must pass, given the numbers now:
/// a table (null = untrained/unknown skill), not past the top, a cost that equals what the
/// caller confirmed (<paramref name="expectedXp"/> &gt; 0; 0 = don't compare), enough
/// unassigned XP, and an amount the 32-bit game action can carry.
/// <paramref name="cost"/> is the XP to send when the result is <see cref="RaiseStatus.Sent"/>.
/// </summary>
public static RaiseStatus CheckRaise(uint[]? table, uint ranks, uint spent, long unassignedXp,
int count, long expectedXp, out long cost)
{
cost = -1;
if (count < 1 || count > MaxRanksPerRaise || expectedXp < 0) return RaiseStatus.BadArguments;
if (table == null || table.Length == 0) return RaiseStatus.NotRaisable;
cost = CostOf(table, ranks, spent, count);
if (cost <= 0) return RaiseStatus.NotRaisable; // past the top (-1) or nothing to buy (0)
if (expectedXp != 0 && expectedXp != cost) return RaiseStatus.CostChanged;
if (cost > unassignedXp) return RaiseStatus.NotEnough;
if (cost > uint.MaxValue) return RaiseStatus.NotRaisable; // more than one game action can carry
return RaiseStatus.Sent;
}
/// <summary>
/// The checks for training an untrained skill with credits: the skill must be untrained
/// (class 1, or 0 = not in the table), the dat must price it (&gt; 0), the price must be what
/// the caller confirmed (<paramref name="expectedCredits"/> &gt; 0; 0 = don't compare) and
/// the player must have the credits.
/// </summary>
public static RaiseStatus CheckTrain(uint skillClass, int trainedCost, int credits, int expectedCredits)
{
if (expectedCredits < 0) return RaiseStatus.BadArguments;
if (skillClass >= 2 || trainedCost <= 0) return RaiseStatus.NotRaisable;
if (expectedCredits != 0 && expectedCredits != trainedCost) return RaiseStatus.CostChanged;
if (trainedCost > credits) return RaiseStatus.NotEnough;
return RaiseStatus.Sent;
}
}

View file

@ -0,0 +1,480 @@
// ============================================================================
// RynthCore.Engine - Compatibility/UiElementHooks.cs
//
// Tooltip and drag/drop hooks on AC's own UI (Chorizite comparison gap #5,
// 2026-10-05). Every address and offset below was checked offline against our
// client (tools/ui_hooks_check.py; report in ops/overnight/2026-10-05-ui-hooks.md):
//
// UIElementManager (the UI singleton; `this` of the first four):
// StartTooltip(StringInfo*, UIElement* owner, uint, uint, uint) 0x0045DF70, ret 14h
// stores the owner at +0x2F4, builds the tooltip element into +0x2F8.
// ResetTooltip() 0x0045C440 frees +0x2F8, then tail-jumps into CheckTooltip.
// CheckTooltip() 0x0045B7C0 per-frame tooltip timer (+0x325, +0x2D4, +0x24C).
// StartDragandDrop(UIElement*, int x, int y) -> bool 0x0045E120, ret 0Ch
// on success the drag icon is at +0x31C and its owner at +0x320; it calls
// itself once for a drag proxy (we report only the outermost call).
// UIElement::CatchDroppedItem(DragDropInfo*) -> bool 0x00461860, ret 4
// the catcher's virtual (vtable +0xD8), called from StopDragandDrop
// (0x00459880). All 113 UIElement vtables in the client route it here:
// 36 directly, 77 through UIElement_Field::CatchDroppedItem, which calls
// it. It broadcasts element message 0x15 (drop release) to the catcher;
// that message is what drops an item on the ground (SmartBoxWrapper),
// moves it into a pack (ItemList) and so on. DragDropInfo: +0x08 the
// drag icon, +0x0C its owner, +0x10 the catcher, +0x14 success.
// Not hooked, called: UIElement_ItemList::InqDropIconInfo(UIElement*, uint* item,
// uint* spell, uint* flags), cdecl, 0x004E3380: AC's own "which object or
// spell is this icon" (13 callers in the client; reads element properties
// only, null-safe).
// UIElement offsets: +0x2E4 element id (GetAncestorByID compares it), vtable
// +0xA0 GetParent, +0x98 GetUIElementType (UIElement_ItemList: 0x10000031).
//
// Events, on AC's main thread, queued to plugins (API v77):
// tooltip shown (object id or spell id of the hovered icon), tooltip hidden,
// drag started (object/spell id, icon), item dropped (object/spell id, the
// catcher's element id).
// Drop claims: an item dragged out of an AC item list and let go over an engine
// panel that takes drops (ImGui/UiDropTargets: the Loot Editor) never reaches
// AC: CatchDroppedItem answers false without running, which is AC's own
// "not caught" path (StopDragandDrop then tells the source list the drop
// failed; ItemList::HandleDropRelease ignores a failed drop whose catcher isn't
// inside it). Not claimed when the catcher is inside the source list itself.
//
// Not done (needs in-game checks): adding lines to AC's own tooltip text. That
// means building an AC StringInfo/PStringBase and editing the tooltip element
// AC just made, inside its allocator - see the report.
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class UiElementHooks
{
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int StartTooltipFallbackVa = 0x0045DF70;
private const int ResetTooltipFallbackVa = 0x0045C440;
private const int CheckTooltipFallbackVa = 0x0045B7C0;
private const int StartDragandDropFallbackVa = 0x0045E120;
private const int CatchDroppedItemFallbackVa = 0x00461860;
private const int InqDropIconInfoFallbackVa = 0x004E3380;
private const int MgrTooltipOwner = 0x2F4;
private const int MgrTooltipElement = 0x2F8;
private const int MgrDragIcon = 0x31C;
private const int MgrDragOwner = 0x320;
private const int ElementId = 0x2E4;
private const int VtGetUIElementType = 0x98;
private const int VtGetParent = 0xA0;
private const int DdiElement = 0x08;
private const int DdiOwner = 0x0C;
private const int UIElementTypeItemList = 0x10000031;
// StartTooltip: sub esp,10h / push ebp / push esi / mov esi,ecx / mov ecx,[esi+2F8h] /
// xor ebp,ebp / cmp ecx,ebp / push edi / mov [esp+18h],esi / jz +0Bh / call rel32 /
// mov [esi+2F8h],ebp - frees an old tooltip element first. Unique, lands at 0x0045DF70.
private static readonly byte?[] StartTooltipPattern =
[
0x83, 0xEC, 0x10, 0x55, 0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00,
0x33, 0xED, 0x3B, 0xCD, 0x57, 0x89, 0x74, 0x24, 0x18, 0x74, 0x0B,
0xE8, null, null, null, null, 0x89, 0xAE, 0xF8, 0x02, 0x00, 0x00
];
// ResetTooltip: push esi / mov esi,ecx / mov ecx,[esi+2F8h] / test ecx,ecx / jz +0Fh /
// call rel32 / mov dword [esi+2F8h],0 / mov al,[esi+325h]. Unique, lands at 0x0045C440.
private static readonly byte?[] ResetTooltipPattern =
[
0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00, 0x85, 0xC9, 0x74, 0x0F,
0xE8, null, null, null, null, 0xC7, 0x86, 0xF8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x8A, 0x86, 0x25, 0x03, 0x00, 0x00
];
// CheckTooltip: sub esp,0Ch / mov eax,[imm32] / push esi / mov esi,ecx / mov ecx,[imm32] /
// mov [esp+8],eax / mov al,[esi+325h] / test al,al / mov [esp+0Ch],ecx / jnz +79h /
// mov al,[esi+2D4h]. The two timer globals wildcarded. Unique, lands at 0x0045B7C0.
private static readonly byte?[] CheckTooltipPattern =
[
0x83, 0xEC, 0x0C, 0xA1, null, null, null, null, 0x56, 0x8B, 0xF1, 0x8B, 0x0D, null, null, null, null,
0x89, 0x44, 0x24, 0x08, 0x8A, 0x86, 0x25, 0x03, 0x00, 0x00, 0x84, 0xC0, 0x89, 0x4C, 0x24, 0x0C,
0x75, 0x79, 0x8A, 0x86, 0xD4, 0x02, 0x00, 0x00
];
// StartDragandDrop: sub esp,34h / push ebx,ebp,esi,edi / mov edi,[esp+48h] / test edi,edi /
// mov esi,ecx / jz rel32 / mov eax,[imm32] / test eax,eax / jz rel32 / mov ebx,[imm32] /
// test ebx,ebx. Unique, lands at 0x0045E120.
private static readonly byte?[] StartDragandDropPattern =
[
0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1,
0x0F, 0x84, null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0,
0x0F, 0x84, null, null, null, null, 0x8B, 0x1D, null, null, null, null, 0x85, 0xDB
];
// UIElement::CatchDroppedItem, the whole function: mov eax,[esp+4] / push 0 / push eax /
// push 15h / call BroadcastElementMessage / mov al,1 / ret 4. Unique, lands at 0x00461860.
private static readonly byte?[] CatchDroppedItemPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x6A, 0x00, 0x50, 0x6A, 0x15, 0xE8, null, null, null, null,
0xB0, 0x01, 0xC2, 0x04, 0x00
];
// UIElement_ItemList::InqDropIconInfo: mov eax,[esp+10h] / sub esp,3Ch / push ebx / push ebp /
// mov ebp,[esp+50h] / push esi / mov esi,[esp+4Ch] / xor ebx,ebx / cmp esi,ebx / push edi /
// mov edi,[esp+54h] / mov [edi],ebx / mov [ebp],ebx / mov [eax],ebx. Unique, lands at 0x004E3380.
private static readonly byte?[] InqDropIconInfoPattern =
[
0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56,
0x8B, 0x74, 0x24, 0x4C, 0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54,
0x89, 0x1F, 0x89, 0x5D, 0x00, 0x89, 0x18
];
private static readonly UiHookSlot StartTooltipSlot =
UiHookRegistry.Register("StartTooltip", "UIElementManager::StartTooltip - tooltip shown", StartTooltipFallbackVa);
private static readonly UiHookSlot ResetTooltipSlot =
UiHookRegistry.Register("ResetTooltip", "UIElementManager::ResetTooltip - tooltip reset", ResetTooltipFallbackVa);
private static readonly UiHookSlot CheckTooltipSlot =
UiHookRegistry.Register("CheckTooltip", "UIElementManager::CheckTooltip - tooltip expired", CheckTooltipFallbackVa);
private static readonly UiHookSlot StartDragSlot =
UiHookRegistry.Register("StartDragandDrop", "UIElementManager::StartDragandDrop - drag started", StartDragandDropFallbackVa);
private static readonly UiHookSlot CatchDropSlot =
UiHookRegistry.Register("CatchDroppedItem", "UIElement::CatchDroppedItem - item dropped", CatchDroppedItemFallbackVa);
private static IntPtr _origStartTooltip, _origResetTooltip, _origCheckTooltip, _origStartDrag, _origCatchDrop;
private static IntPtr _inqDropIconInfo;
private static int _initialized;
// AC's main thread only (every detour runs there; faces draw there).
private static IntPtr _mgr;
private static bool _dead; // Client::Cleanup started: touch nothing of AC's UI
private static bool _tooltipShown;
private static IntPtr _tooltipOwner;
private static uint _tooltipObject, _tooltipSpell;
private static int _dragDepth;
private static uint _dragObject, _dragSpell;
private static int _claimed;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot })
s.Reason = "acclient.exe not available";
RynthLog.Compat("UiElementHooks: acclient.exe not available - tooltip and drag/drop hooks left out.");
return;
}
// Every event names its object through InqDropIconInfo: without it, none goes in.
HookResolver.ResolveResult inq = HookResolver.Resolve(text, "UiElement.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoFallbackVa);
if (!inq.Success)
{
foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot })
s.Reason = "UIElement_ItemList::InqDropIconInfo not found (names the objects)";
RynthLog.Compat("UiElementHooks: InqDropIconInfo not found - tooltip and drag/drop hooks left out.");
return;
}
_inqDropIconInfo = inq.Address;
if (UiHookRegistry.SwitchedOn(StartTooltipSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartTooltip", StartTooltipPattern, StartTooltipFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void> d = &StartTooltipDetour;
if (UiHookRegistry.TryInstall(StartTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origStartTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartTooltipSlot); }
}
if (UiHookRegistry.SwitchedOn(ResetTooltipSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.ResetTooltip", ResetTooltipPattern, ResetTooltipFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, void> d = &ResetTooltipDetour;
if (UiHookRegistry.TryInstall(ResetTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origResetTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(ResetTooltipSlot); }
}
if (UiHookRegistry.SwitchedOn(CheckTooltipSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CheckTooltip", CheckTooltipPattern, CheckTooltipFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, void> d = &CheckTooltipDetour;
if (UiHookRegistry.TryInstall(CheckTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origCheckTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CheckTooltipSlot); }
}
if (UiHookRegistry.SwitchedOn(StartDragSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartDragandDrop", StartDragandDropPattern, StartDragandDropFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte> d = &StartDragandDropDetour;
if (UiHookRegistry.TryInstall(StartDragSlot, r, (IntPtr)d, out IntPtr t)) { _origStartDrag = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartDragSlot); }
}
if (UiHookRegistry.SwitchedOn(CatchDropSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CatchDroppedItem", CatchDroppedItemPattern, CatchDroppedItemFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, byte> d = &CatchDroppedItemDetour;
if (UiHookRegistry.TryInstall(CatchDropSlot, r, (IntPtr)d, out IntPtr t)) { _origCatchDrop = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CatchDropSlot); }
}
RynthLog.Compat($"UiElementHooks: tooltip {On(StartTooltipSlot)}/{On(ResetTooltipSlot)}/{On(CheckTooltipSlot)}, " +
$"drag {On(StartDragSlot)}, drop {On(CatchDropSlot)} (InqDropIconInfo @ 0x{_inqDropIconInfo.ToInt32():X8}).");
}
private static string On(UiHookSlot s) => s.Installed ? "hooked" : "out";
// ── What plugins and faces read ─────────────────────────────────────
/// <summary>Tooltip/drag/drop hooks a plugin can rely on (GetUiHookFlags bits 3-6).</summary>
public static bool TooltipShowLive => StartTooltipSlot.Live;
public static bool TooltipHideLive => ResetTooltipSlot.Live || CheckTooltipSlot.Live;
public static bool DragStartLive => StartDragSlot.Live;
public static bool DropLive => CatchDropSlot.Live;
/// <summary>
/// AC's main thread: the object being dragged out of AC's UI right now, or 0. Checks
/// the UI manager's drag icon (+0x31C) so a drag that ended without a catch (let go
/// outside every element) clears too.
/// </summary>
public static uint CurrentDragObject
{
get
{
if (_dragObject == 0)
return 0;
if (_dead || _mgr == IntPtr.Zero || !MainThreadGuard.IsOnMainThread())
return _dead ? 0 : _dragObject;
if (*(IntPtr*)(_mgr + MgrDragIcon) == IntPtr.Zero)
{
_dragObject = _dragSpell = 0;
return 0;
}
return _dragObject;
}
}
/// <summary>The object whose tooltip AC shows, or 0 (any thread; a plain field).</summary>
public static uint CurrentTooltipObject => _tooltipShown ? _tooltipObject : 0;
/// <summary>UiFlowHooks, leaving the world (main thread): forget tooltip/drag state; no events.</summary>
public static void OnScreenLeaving()
{
_tooltipShown = false;
_tooltipOwner = IntPtr.Zero;
_tooltipObject = _tooltipSpell = 0;
_dragObject = _dragSpell = 0;
}
/// <summary>UiFlowHooks, Client::Cleanup (main thread): AC's UI is about to go; never touch it again.</summary>
public static void OnClientCleanup()
{
_dead = true;
_mgr = IntPtr.Zero;
OnScreenLeaving();
}
// ── Detours ──────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static void StartTooltipDetour(IntPtr mgr, IntPtr stringInfo, IntPtr owner, uint idTooltip, uint idLayout, uint idText)
{
((delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void>)_origStartTooltip)(mgr, stringInfo, owner, idTooltip, idLayout, idText);
if (!StartTooltipSlot.Enabled || _dead || mgr == IntPtr.Zero)
return;
try
{
_mgr = mgr;
if (*(IntPtr*)(mgr + MgrTooltipElement) == IntPtr.Zero)
return; // AC decided not to show one
IntPtr shownOwner = *(IntPtr*)(mgr + MgrTooltipOwner);
if (shownOwner == IntPtr.Zero) shownOwner = owner;
Identify(shownOwner, 2, out uint obj, out uint spell);
bool same = _tooltipShown && shownOwner == _tooltipOwner && obj == _tooltipObject && spell == _tooltipSpell;
_tooltipShown = true;
_tooltipOwner = shownOwner;
_tooltipObject = obj;
_tooltipSpell = spell;
if (same)
return;
StartTooltipSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element");
Plugins.PluginManager.QueueTooltipShown(obj, spell);
}
catch (Exception ex)
{
LogOnce("StartTooltip", ex);
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static void ResetTooltipDetour(IntPtr mgr)
{
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origResetTooltip)(mgr);
if (ResetTooltipSlot.Enabled)
AfterTooltipCheck(mgr, ResetTooltipSlot);
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static void CheckTooltipDetour(IntPtr mgr)
{
((delegate* unmanaged[Thiscall]<IntPtr, void>)_origCheckTooltip)(mgr);
if (CheckTooltipSlot.Enabled)
AfterTooltipCheck(mgr, CheckTooltipSlot);
}
// A tooltip we reported is gone when AC's tooltip element pointer is clear again.
private static void AfterTooltipCheck(IntPtr mgr, UiHookSlot slot)
{
if (!_tooltipShown || _dead || mgr == IntPtr.Zero)
return;
try
{
if (*(IntPtr*)(mgr + MgrTooltipElement) != IntPtr.Zero)
return;
uint obj = _tooltipObject;
_tooltipShown = false;
_tooltipOwner = IntPtr.Zero;
_tooltipObject = _tooltipSpell = 0;
slot.Note(obj != 0 ? $"hid object 0x{obj:X8}" : "hid");
Plugins.PluginManager.QueueTooltipHidden();
}
catch (Exception ex)
{
LogOnce(slot.Name, ex);
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static byte StartDragandDropDetour(IntPtr mgr, IntPtr element, int x, int y)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, int, byte>)_origStartDrag;
byte result;
_dragDepth++;
try { result = original(mgr, element, x, y); }
finally { _dragDepth--; }
// The original calls itself once for a drag proxy: report the outermost call only.
if (result == 0 || _dragDepth > 0 || !StartDragSlot.Enabled || _dead || mgr == IntPtr.Zero)
return result;
try
{
_mgr = mgr;
IntPtr icon = *(IntPtr*)(mgr + MgrDragIcon);
if (icon == IntPtr.Zero)
return result;
Identify(icon, 0, out uint obj, out uint spell);
if (obj == 0 && spell == 0)
Identify(element, 2, out obj, out spell);
_dragObject = obj;
_dragSpell = spell;
uint iconId = 0;
if (obj != 0)
ClientObjectHooks.TryGetObjectDataIdProperty(obj, 8 /* Icon */, out iconId);
StartDragSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element");
Plugins.PluginManager.QueueDragStarted(obj, spell, iconId);
}
catch (Exception ex)
{
LogOnce("StartDragandDrop", ex);
}
return result;
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static byte CatchDroppedItemDetour(IntPtr catcher, IntPtr dragDropInfo)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, byte>)_origCatchDrop;
if (!CatchDropSlot.Enabled || _dead || dragDropInfo == IntPtr.Zero)
return original(catcher, dragDropInfo);
uint obj = 0, spell = 0;
try
{
IntPtr dragged = *(IntPtr*)(dragDropInfo + DdiElement);
IntPtr owner = *(IntPtr*)(dragDropInfo + DdiOwner);
if (dragged != IntPtr.Zero)
Identify(dragged, 0, out obj, out spell);
// An item out of an AC item list, let go over an engine panel that takes it.
if (obj != 0 && IsItemList(owner) && !IsWithin(catcher, owner)
&& ImGuiBackend.UiDropTargets.TryClaim(obj, spell, out string target))
{
Interlocked.Increment(ref _claimed);
_dragObject = _dragSpell = 0;
CatchDropSlot.Note($"object 0x{obj:X8} -> RynthCore {target} (kept from AC)");
RynthLog.Compat($"UiElementHooks: object 0x{obj:X8} dropped on RynthCore {target}; AC's drop skipped (not caught).");
return 0;
}
}
catch (Exception ex)
{
LogOnce("CatchDroppedItem", ex);
}
byte result = original(catcher, dragDropInfo);
try
{
_dragObject = _dragSpell = 0;
uint targetId = catcher != IntPtr.Zero ? *(uint*)(catcher + ElementId) : 0;
CatchDropSlot.Note($"{(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "no object")} on element 0x{targetId:X8}");
if (obj != 0 || spell != 0)
Plugins.PluginManager.QueueItemDropped(obj, spell, targetId);
}
catch (Exception ex)
{
LogOnce("CatchDroppedItem", ex);
}
return result;
}
// ── AC UI helpers (main thread) ──────────────────────────────────────
/// <summary>AC's InqDropIconInfo on <paramref name="element"/>, then up to <paramref name="parents"/> parents.</summary>
private static void Identify(IntPtr element, int parents, out uint objectId, out uint spellId)
{
objectId = spellId = 0;
var inq = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)_inqDropIconInfo;
for (int i = 0; i <= parents && element != IntPtr.Zero; i++)
{
uint item = 0, spell = 0, flags = 0;
inq(element, &item, &spell, &flags);
if (item != 0 || spell != 0)
{
objectId = item;
spellId = spell;
return;
}
element = Parent(element);
}
}
private static IntPtr Parent(IntPtr element)
{
IntPtr vtable = *(IntPtr*)element;
var getParent = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr>)(*(IntPtr*)(vtable + VtGetParent));
return getParent(element);
}
private static bool IsItemList(IntPtr element)
{
if (element == IntPtr.Zero)
return false;
IntPtr vtable = *(IntPtr*)element;
var getType = (delegate* unmanaged[Thiscall]<IntPtr, int>)(*(IntPtr*)(vtable + VtGetUIElementType));
return getType(element) == UIElementTypeItemList;
}
private static bool IsWithin(IntPtr element, IntPtr ancestor)
{
for (int i = 0; i < 32 && element != IntPtr.Zero; i++)
{
if (element == ancestor)
return true;
element = Parent(element);
}
return false;
}
private static int _loggedErrors;
private static void LogOnce(string where, Exception ex)
{
if (Interlocked.Increment(ref _loggedErrors) <= 5)
try { RynthLog.Compat($"UiElementHooks: {where} threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
public static string DescribeState()
=> $"UI elements: tooltip {(_tooltipShown ? (_tooltipObject != 0 ? $"on object 0x{_tooltipObject:X8}" : "shown") : "none")}, " +
$"drag {(_dragObject != 0 ? $"object 0x{_dragObject:X8}" : "none")}, {Volatile.Read(ref _claimed)} drop(s) kept for RynthCore. " +
ImGuiBackend.UiDropTargets.Describe();
}

View file

@ -0,0 +1,334 @@
// ============================================================================
// RynthCore.Engine - Compatibility/UiFlowHooks.cs
//
// Screen-mode and teardown hooks (Chorizite comparison gap #4, 2026-10-05):
//
// UIFlow::UseNewMode (fallback 0x00479AA0) void __thiscall(UIFlow*)
// AC switches screens here: intro, character select, the world, char gen,
// disconnected... It copies the pending mode (+0x90) into the current mode
// (+0x8C), destroys the old screen's UI object (+0x94) and builds the new
// one. Read offline from our client: 0x00479B13..0x00479B35 (mov [esi+8C],ecx
// from [esi+90]; old UI at +94 released with vfunc +0x24/+0x00).
// Client::Cleanup (fallback 0x004118D0) void __thiscall(Client*)
// The client's shutdown: tears down UI, net, database and preferences
// (virtual calls at its top). Called once, from gmClient::Cleanup.
//
// Events (all raised on AC's main thread):
// ScreenLeaving(old, new) - inside UseNewMode, BEFORE AC destroys the old
// screen's UI. Leaving the world, the engine drops
// every cached gameplay-UI pointer right here.
// ScreenChanged(old, new) - after AC built the new screen (plugins get
// RynthPluginOnScreenChanged on the next pump frame).
// ClientCleanup - before AC tears anything down; plugins get
// RynthPluginOnClientCleanup (bounded wait), then the
// plugin pump stops ticking and the panels stop drawing.
//
// Fallback: until the hook is live (failed to resolve, switched off), the UIFlow
// mode the engine already polls at +0x8C (CharacterManagementHooks.MainThreadTick)
// drives the same events, one tick late and without the "before" guarantee.
// ============================================================================
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static unsafe class UiFlowHooks
{
// UIFlow modes (UIFlow+0x8C), the client's own data ids.
public const int ModeNone = 0;
public const int ModeIntro = 0x10000001;
public const int ModeDisconnected = 0x10000002;
public const int ModeDataPatch = 0x10000003;
public const int ModeCredits = 0x10000005;
public const int ModeGamePlay = 0x10000008;
public const int ModeEpilogue = 0x10000009;
public const int ModeCharacterManagement = 0x1000000A;
public const int ModeCharGen = 0x1000000B;
private const int UIFlowCurModeOffset = 0x8C;
private const int UIFlowNewModeOffset = 0x90;
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int UseNewModeFallbackVa = 0x00479AA0;
private const int ClientCleanupFallbackVa = 0x004118D0;
// UIFlow::UseNewMode: sub esp,0x90 / push esi / mov esi,ecx / mov eax,[esi+0x90] /
// test eax,eax / jz rel32 / mov ecx,eax / xor edx,edx / div [imm32] / mov eax,[imm32].
// The +0x90 pending-mode read and the hash-bucket div are the anchor. Unique, lands
// at 0x00479AA0 (tools/pe_pattern.py CHECK, tools/ui_hooks_check.py).
private static readonly byte?[] UseNewModePattern =
[
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B, 0xF1, 0x8B, 0x86, 0x90, 0x00, 0x00, 0x00,
0x85, 0xC0, 0x0F, 0x84, null, null, null, null,
0x8B, 0xC8, 0x33, 0xD2, 0xF7, 0x35, null, null, null, null,
0xA1, null, null, null, null
];
// Client::Cleanup: push esi / mov esi,ecx / mov eax,[esi] / call [eax+0x28] / call rel32 /
// mov edx,[esi] / mov ecx,esi / call [edx+0x8C] / call rel32 / mov eax,[esi] / mov ecx,esi /
// call [eax+0x84]: its run of virtual cleanups. Unique, lands at 0x004118D0.
private static readonly byte?[] ClientCleanupPattern =
[
0x56, 0x8B, 0xF1, 0x8B, 0x06, 0xFF, 0x50, 0x28, 0xE8, null, null, null, null,
0x8B, 0x16, 0x8B, 0xCE, 0xFF, 0x92, 0x8C, 0x00, 0x00, 0x00, 0xE8, null, null, null, null,
0x8B, 0x06, 0x8B, 0xCE, 0xFF, 0x90, 0x84, 0x00, 0x00, 0x00
];
private static readonly UiHookSlot UseNewModeSlot =
UiHookRegistry.Register("UseNewMode", "UIFlow::UseNewMode - screen changes", UseNewModeFallbackVa);
private static readonly UiHookSlot CleanupSlot =
UiHookRegistry.Register("ClientCleanup", "Client::Cleanup - client teardown", ClientCleanupFallbackVa);
private static IntPtr _originalUseNewMode;
private static IntPtr _originalCleanup;
private static int _initialized;
private static int _mode; // current UIFlow mode as last observed (0 = not known yet)
private static int _previousMode;
private static int _changes;
private static string _lastSource = "none";
private static int _cleanupStarted;
private static int _useNewModeDepth;
/// <summary>AC's main thread, inside UseNewMode before the old screen's UI is destroyed (hook only).</summary>
public static event Action<int, int>? ScreenLeaving;
/// <summary>AC's main thread, after the new screen was built (hook) or on the next tick (poll fallback).</summary>
public static event Action<int, int>? ScreenChanged;
/// <summary>AC's main thread, before Client::Cleanup runs. Once.</summary>
public static event Action? ClientCleanup;
/// <summary>The UIFlow mode as last observed; 0 until the first observation.</summary>
public static int CurrentMode => Volatile.Read(ref _mode);
public static int PreviousMode => Volatile.Read(ref _previousMode);
/// <summary>True while AC shows the world, or while the mode isn't known yet (no change
/// from the old behaviour then). Gate cached-AC-UI-pointer use on this.</summary>
public static bool InWorldOrUnknown
{
get
{
int m = Volatile.Read(ref _mode);
return m == ModeNone || m == ModeGamePlay;
}
}
/// <summary>Client::Cleanup has started: AC is tearing its UI down. Never cleared.</summary>
public static bool ClientCleanupStarted => Volatile.Read(ref _cleanupStarted) != 0;
/// <summary>The UseNewMode detour is installed and switched on (else the poll drives the events).</summary>
public static bool ScreenHookLive => UseNewModeSlot.Live;
public static bool CleanupHookLive => CleanupSlot.Live;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
UseNewModeSlot.Reason = CleanupSlot.Reason = "acclient.exe not available";
RynthLog.Compat("UiFlowHooks: acclient.exe not available - screen-mode and cleanup hooks left out (the mode poll stays).");
return;
}
if (UiHookRegistry.SwitchedOn(UseNewModeSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.UseNewMode", UseNewModePattern, UseNewModeFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, void> detour = &UseNewModeDetour;
if (UiHookRegistry.TryInstall(UseNewModeSlot, r, (IntPtr)detour, out IntPtr tramp))
{
_originalUseNewMode = tramp;
Thread.MemoryBarrier();
UiHookRegistry.Enable(UseNewModeSlot);
}
}
if (UiHookRegistry.SwitchedOn(CleanupSlot))
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.ClientCleanup", ClientCleanupPattern, ClientCleanupFallbackVa);
delegate* unmanaged[Thiscall]<IntPtr, void> detour = &ClientCleanupDetour;
if (UiHookRegistry.TryInstall(CleanupSlot, r, (IntPtr)detour, out IntPtr tramp))
{
_originalCleanup = tramp;
Thread.MemoryBarrier();
UiHookRegistry.Enable(CleanupSlot);
}
}
RynthLog.Compat($"UiFlowHooks: UseNewMode {(UseNewModeSlot.Installed ? "hooked" : "not hooked (" + UseNewModeSlot.Reason + ") - the +0x8C poll drives screen events")}, " +
$"Client::Cleanup {(CleanupSlot.Installed ? "hooked" : "not hooked (" + CleanupSlot.Reason + ")")}.");
}
// ── Detours ──────────────────────────────────────────────────────────
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static void UseNewModeDetour(IntPtr uiFlow)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, void>)_originalUseNewMode;
if (!UseNewModeSlot.Enabled || uiFlow == IntPtr.Zero || _useNewModeDepth > 0)
{
original(uiFlow);
return;
}
int oldMode = 0, pending = 0;
bool read = false;
try
{
MainThreadGuard.RecordIfFirst();
oldMode = *(int*)(uiFlow + UIFlowCurModeOffset);
pending = *(int*)(uiFlow + UIFlowNewModeOffset);
read = true;
// AC destroys the old screen's UI inside the original: drop what points into it first.
if (pending != 0 && pending != oldMode)
RaiseLeaving(oldMode, pending, "hook");
}
catch (Exception ex)
{
try { RynthLog.Compat($"UiFlowHooks: UseNewMode pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
_useNewModeDepth++;
try { original(uiFlow); }
finally { _useNewModeDepth--; }
if (!read)
return;
try
{
int newMode = *(int*)(uiFlow + UIFlowCurModeOffset);
if (newMode != oldMode)
Observe(oldMode, newMode, "hook");
else if (Volatile.Read(ref _mode) == ModeNone && newMode != ModeNone)
Volatile.Write(ref _mode, newMode);
}
catch (Exception ex)
{
try { RynthLog.Compat($"UiFlowHooks: UseNewMode post-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static void ClientCleanupDetour(IntPtr client)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, void>)_originalCleanup;
if (CleanupSlot.Enabled)
{
try { RaiseCleanup(); }
catch (Exception ex)
{
try { RynthLog.Compat($"UiFlowHooks: Client::Cleanup pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
}
original(client);
}
// ── Poll fallback ────────────────────────────────────────────────────
/// <summary>
/// AC's main thread (CharacterManagementHooks.MainThreadTick): the UIFlow mode it just
/// read at +0x8C. Seeds the mode; when the UseNewMode hook isn't live, a change here
/// raises the screen events instead (after the fact: the old screen is already gone).
/// </summary>
public static void OnModePolled(int mode)
{
int known = Volatile.Read(ref _mode);
if (mode == known)
return;
if (known == ModeNone || UseNewModeSlot.Live)
{
// Seed (late attach, hot reload). With the hook live a difference here means the
// hook missed a change (it was switched off for a while): correct it quietly.
Volatile.Write(ref _mode, mode);
return;
}
try
{
RaiseLeaving(known, mode, "poll");
Observe(known, mode, "poll");
}
catch (Exception ex)
{
RynthLog.Compat($"UiFlowHooks: poll fallback threw {ex.GetType().Name}: {ex.Message}");
}
}
// ── Raising ──────────────────────────────────────────────────────────
private static void RaiseLeaving(int oldMode, int newMode, string source)
{
if (oldMode == ModeGamePlay)
OnLeavingWorld();
try { ScreenLeaving?.Invoke(oldMode, newMode); }
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenLeaving handler threw {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>
/// Leaving the world: AC is about to free gmGamePlayUI and every panel in it. The
/// engine's per-frame users of cached panel pointers (EndScene TickHide for chat,
/// radar, powerbar, retail vitals) run on this same thread, so clearing them here
/// closes the window the pump-thread logout dispatch left open (it clears them a
/// frame or more later). Idempotent: the logout dispatch clears them again.
/// </summary>
private static void OnLeavingWorld()
{
try { ChatHooks.ResetCachedInstance(); } catch { }
try { RadarHooks.ResetCachedInstance(); } catch { }
try { PowerbarHooks.ResetCachedInstance(); } catch { }
try { RetailVitalsHooks.ResetCachedInstance(); } catch { }
try { UiElementHooks.OnScreenLeaving(); } catch { }
}
private static void Observe(int oldMode, int newMode, string source)
{
Volatile.Write(ref _previousMode, oldMode);
Volatile.Write(ref _mode, newMode);
Interlocked.Increment(ref _changes);
_lastSource = source;
string note = $"{ModeName(oldMode)} -> {ModeName(newMode)} ({source})";
UseNewModeSlot.LastNote = note;
if (source == "hook") Interlocked.Increment(ref UseNewModeSlot.Fired);
RynthLog.Compat($"UiFlowHooks: screen {note}.");
try { ScreenChanged?.Invoke(oldMode, newMode); }
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenChanged handler threw {ex.GetType().Name}: {ex.Message}"); }
try { Plugins.PluginManager.QueueScreenChanged(oldMode, newMode); }
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: queueing OnScreenChanged threw {ex.GetType().Name}: {ex.Message}"); }
}
private static void RaiseCleanup()
{
if (Interlocked.Exchange(ref _cleanupStarted, 1) != 0)
return;
CleanupSlot.Note("Client::Cleanup entered");
RynthLog.Compat("UiFlowHooks: Client::Cleanup - the client is tearing down; telling plugins, then stopping plugin ticks and panels.");
try { UiElementHooks.OnClientCleanup(); } catch { }
try { ClientCleanup?.Invoke(); }
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ClientCleanup handler threw {ex.GetType().Name}: {ex.Message}"); }
try { Plugins.PluginManager.DispatchClientCleanup(500); }
catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: plugin cleanup dispatch threw {ex.GetType().Name}: {ex.Message}"); }
}
// ── Status ───────────────────────────────────────────────────────────
public static string ModeName(int mode) => mode switch
{
ModeNone => "unknown",
ModeIntro => "Intro",
ModeDisconnected => "Disconnected",
ModeDataPatch => "DataPatch",
ModeCredits => "Credits",
ModeGamePlay => "World",
ModeEpilogue => "Epilogue",
ModeCharacterManagement => "CharacterSelect",
ModeCharGen => "CharGen",
_ => $"0x{mode:X8}",
};
public static string DescribeState()
=> $"Screen: {ModeName(CurrentMode)} (before: {ModeName(PreviousMode)}), {Volatile.Read(ref _changes)} change(s), last via {_lastSource}; " +
$"driven by {(UseNewModeSlot.Live ? "the UseNewMode hook" : "the +0x8C poll (fallback)")}; " +
$"client cleanup {(ClientCleanupStarted ? "STARTED" : "not started")}.";
}

View file

@ -0,0 +1,215 @@
// ============================================================================
// RynthCore.Engine - Compatibility/UiHookRegistry.cs
//
// Status and kill switches for the UI hooks of 2026-10-05 (Chorizite gaps #4
// and #5): UiFlowHooks (UIFlow::UseNewMode, Client::Cleanup) and UiElementHooks
// (tooltip start/reset/check, drag start, item drop).
//
// Every hook has its own switch, two ways:
// - engine.json "DisabledUiHooks": ["StartTooltip", ...] - not installed at
// the next start (EngineSettings.IsUiHookEnabled);
// - /rc hooks off <name> - the detour turns into a plain pass-through at
// once (it still calls AC's original), and the name is saved to
// engine.json for the next start. /rc hooks on <name> undoes both.
// /rc hooks (alone) lists every hook: address, how it was found, on/off,
// how many times it fired and the last thing it saw.
//
// A hook that fails to resolve or install logs once (HookResolver /
// TryInstall) and stays out: its slot says why, and nothing else changes.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal sealed class UiHookSlot
{
public UiHookSlot(string name, string what, int fallbackVa)
{
Name = name;
What = what;
FallbackVa = fallbackVa;
}
/// <summary>The switch name (engine.json DisabledUiHooks, /rc hooks on|off).</summary>
public string Name { get; }
/// <summary>The AC function, for people.</summary>
public string What { get; }
public int FallbackVa { get; }
public IntPtr Address;
/// <summary>"pattern", "fallback", or empty when not installed.</summary>
public string Source = string.Empty;
public bool Installed;
/// <summary>Why it isn't installed ("off in engine.json", "pattern and fallback both failed", ...).</summary>
public string Reason = "not probed yet";
public int Fired;
public string LastNote = string.Empty;
private int _enabled = 1;
/// <summary>Runtime switch: false = the detour only calls AC's original.</summary>
public bool Enabled
{
get => Volatile.Read(ref _enabled) != 0;
set => Volatile.Write(ref _enabled, value ? 1 : 0);
}
/// <summary>Installed and switched on: the detour does its work.</summary>
public bool Live => Installed && Enabled;
public void Note(string note)
{
Interlocked.Increment(ref Fired);
LastNote = note;
}
public string Describe()
{
string state = Installed
? (Enabled ? "on" : "OFF (pass-through)")
: "not installed: " + Reason;
string addr = Installed ? $"0x{Address.ToInt32():X8} via {Source}" : $"(fallback 0x{FallbackVa:X8})";
string last = LastNote.Length > 0 ? $" last: {LastNote}" : string.Empty;
return $"{Name} [{What}] {addr} - {state}; fired {Fired}x.{last}";
}
}
internal static class UiHookRegistry
{
private static readonly List<UiHookSlot> Slots = new();
private static readonly object Sync = new();
public static UiHookSlot Register(string name, string what, int fallbackVa)
{
lock (Sync)
{
foreach (UiHookSlot s in Slots)
if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))
return s;
var slot = new UiHookSlot(name, what, fallbackVa);
Slots.Add(slot);
return slot;
}
}
public static UiHookSlot? Find(string name)
{
lock (Sync)
{
foreach (UiHookSlot s in Slots)
if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase))
return s;
}
return null;
}
public static List<UiHookSlot> All()
{
lock (Sync) return new List<UiHookSlot>(Slots);
}
/// <summary>
/// The engine.json switch, checked before resolving (so a switched-off hook leaves
/// no HookResolver line): false = leave the hook out; the slot says why.
/// </summary>
public static bool SwitchedOn(UiHookSlot slot)
{
if (EngineSettings.IsUiHookEnabled(slot.Name))
return true;
slot.Reason = "off in engine.json (DisabledUiHooks)";
slot.Enabled = false;
RynthLog.Compat($"UiHooks: {slot.Name} switched off in engine.json - not installed.");
return false;
}
/// <summary>
/// Installs one UI hook from its HookResolver result: the Decal guard, then MinHook
/// (created, not yet enabled: the caller stores the trampoline, then calls Enable).
/// Never throws; on any failure the slot says why and the caller leaves the hook out.
/// <paramref name="trampoline"/> is AC's original.
/// </summary>
public static bool TryInstall(UiHookSlot slot, HookResolver.ResolveResult resolved, IntPtr detour, out IntPtr trampoline)
{
trampoline = IntPtr.Zero;
try
{
if (!resolved.Success)
{
slot.Reason = "pattern and fallback address both failed (see the HookResolver line)";
return false;
}
// A Decal client on its first engine load: a pattern miss there means someone
// else (Decal, a Decal plugin) already patched the prologue. Don't stack on it.
// (A hot reload misses the pattern too, on our own stub, and installs as usual.)
if (resolved.Source == HookResolver.ResolveSource.FallbackVa
&& DecalBridgeHost.Active && EntryPoint.InitCount < 2)
{
slot.Reason = "pattern missed in a Decal client (prologue already patched?) - left out";
RynthLog.Compat($"UiHooks: {slot.Name} - pattern missed with Decal in the process; not hooking over someone else's patch.");
return false;
}
trampoline = Hooking.MinHook.HookCreate(resolved.Address, detour);
Thread.MemoryBarrier();
slot.Address = resolved.Address;
slot.Source = resolved.Source == HookResolver.ResolveSource.PatternScan ? "pattern" : "fallback";
slot.Installed = true;
slot.Reason = string.Empty;
return true;
}
catch (Exception ex)
{
trampoline = IntPtr.Zero;
slot.Installed = false;
slot.Reason = $"install threw {ex.GetType().Name}: {ex.Message}";
RynthLog.Compat($"UiHooks: {slot.Name} install threw {ex.GetType().Name}: {ex.Message} - left out.");
return false;
}
}
/// <summary>Enables a hook TryInstall created (after the caller stored the trampoline).</summary>
public static bool Enable(UiHookSlot slot)
{
try
{
Hooking.MinHook.Enable(slot.Address);
RynthLog.Compat($"UiHooks: {slot.Name} ready @ 0x{slot.Address.ToInt32():X8} ({slot.Source}).");
return true;
}
catch (Exception ex)
{
slot.Installed = false;
slot.Reason = $"enable threw {ex.GetType().Name}: {ex.Message}";
RynthLog.Compat($"UiHooks: {slot.Name} enable threw {ex.GetType().Name}: {ex.Message} - left out.");
return false;
}
}
/// <summary>/rc hooks on|off &lt;name&gt;: runtime pass-through plus engine.json for the next start.</summary>
public static string SetEnabled(string name, bool enabled)
{
UiHookSlot? slot = Find(name);
if (slot == null)
return $"No UI hook called '{name}'. Names: {string.Join(", ", All().ConvertAll(s => s.Name))}.";
EngineSettings.SetUiHookEnabled(slot.Name, enabled);
slot.Enabled = enabled;
if (enabled && !slot.Installed)
return $"{slot.Name}: switched on in engine.json; it installs at the next client start.";
return enabled
? $"{slot.Name}: on (now, and at the next start)."
: $"{slot.Name}: off - passes straight to AC now, and isn't installed at the next start.";
}
public static List<string> DescribeLines()
{
var lines = new List<string>();
foreach (UiHookSlot s in All())
lines.Add(s.Describe());
lines.Add(UiFlowHooks.DescribeState());
lines.Add(UiElementHooks.DescribeState());
return lines;
}
}

View file

@ -327,14 +327,21 @@ internal static class EndSceneHook
_renderCount++;
_frameCount++;
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals").
try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// These four call into gameplay-UI panels they cached (gmMainChatUI, the radar, the
// powerbar, the vitals bars). AC frees those when it leaves the world; outside the
// world (UiFlowHooks: a screen change seen by the UseNewMode hook or the mode poll)
// they don't run. Mode not known yet = as before.
if (UiFlowHooks.InWorldOrUnknown && !UiFlowHooks.ClientCleanupStarted)
{
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals").
try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
}
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
{

View file

@ -172,6 +172,7 @@ internal static class EngineLifecycle
// The chat log is written on the tick pump (UiDataHub), now stopped. Left open,
// it outlived this generation and locked the next one out of the file.
Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog());
Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown());
Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());

View file

@ -87,6 +87,10 @@ public static class EntryPoint
[UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")]
public static uint Shutdown(IntPtr lpParam)
{
// Only the loader's hot reload calls this export (process exit and the engine's own
// teardowns call EngineLifecycle.Shutdown directly), on its reload thread: wait here,
// with the game running on this engine, while a plugin says a reload now would hurt.
try { DeferReloadWhilePluginsObject(); } catch { }
try
{
EngineLifecycle.Shutdown();
@ -102,6 +106,39 @@ public static class EntryPoint
}
}
// The shell's ERl button: a reload asked for by hand isn't held for the plugins. Only the
// reload that follows within ManualReloadWindowMs counts (a refused or coalesced signal
// must not exempt the next file-watcher reload).
private static long _manualReloadAtMs;
private const long ManualReloadWindowMs = 10_000;
internal static void NoteManualReload() => Interlocked.Exchange(ref _manualReloadAtMs, Environment.TickCount64);
/// <summary>
/// Reload deferral (2026-10-05, see ReloadDeferral.cs): asks the plugins
/// (RynthPluginReloadBlocker) and waits up to ReloadDeferral.DefaultCap while one objects,
/// e.g. "engine reload waiting: RynthAi in combat (a monster engaged, ...)". Says so in chat
/// once. Never throws; a query that fails counts as "nothing objects".
/// </summary>
private static void DeferReloadWhilePluginsObject()
{
long manualAt = Interlocked.Exchange(ref _manualReloadAtMs, 0);
if (manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs)
{
RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins.");
return;
}
var deferral = new ReloadDeferral
{
Query = PluginManager.QueryReloadBlockers,
Log = msg => RynthLog.Info(msg),
Notify = why => Compatibility.AcMainThreadQueue.EnqueueWriteToChat(
$"[RynthCore] A new RynthCore build is ready. It loads when this is clear: {why} (at most {ReloadDeferral.DefaultCap.TotalMinutes:0} minutes).", 1),
};
ReloadDeferral.Outcome outcome = deferral.Run(out TimeSpan waited);
if (outcome != ReloadDeferral.Outcome.Clear)
RynthLog.Info($"engine reload: deferral {outcome} after {waited.TotalSeconds:0.0} s.");
}
private static uint InitializeCore(IntPtr lpParam)
{
if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
@ -666,6 +703,12 @@ public static class EntryPoint
Step("raw packet hooks", RawPacketHooks.Initialize);
Step("property-update hooks", PropertyUpdateHooks.Initialize);
Step("auto-id service", AutoIdService.Start);
// Screen-mode + client-teardown hooks (UIFlow::UseNewMode, Client::Cleanup) and
// AC's tooltip / drag / drop (2026-10-05, Chorizite gaps #4-#5). Each hook has its
// own switch (engine.json DisabledUiHooks, /rc hooks); one that doesn't resolve
// stays out and says why in /rc hooks.
Step("UI flow hooks", UiFlowHooks.Initialize);
Step("UI element hooks", UiElementHooks.Initialize);
// Bridge mode: wait (bounded) for the bridge's hello. In Auto mode a bridge that
// never shows up means the old coexistence mode: install what was skipped.
if (bridgeSkipped != null && !DecalBridgeHost.WaitForBridge(InitAborted))

View file

@ -459,6 +459,10 @@ internal static class EngineFrameController
if (Compatibility.DecalBridgeHost.Active)
Compatibility.DecalBridgeHost.Drain();
PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd);
// Client::Cleanup started (UiFlowHooks): the call above told the plugins; from
// here on no plugin tick and no plugin export for the panels' data.
if (Compatibility.UiFlowHooks.ClientCleanupStarted)
return;
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
PluginManager.TickAll();
// Panel data: plugin exports for the UI are called here, on the same
@ -475,6 +479,21 @@ internal static class EngineFrameController
}
}
/// <summary>
/// Runs <paramref name="action"/> on the calling thread while no plugin pump frame runs,
/// holding the pump's frame guard so it can't start one meanwhile. False (not run) when a
/// frame is running. For Client::Cleanup (UiFlowHooks): AC's main thread tells the
/// plugins itself when the pump is idle or no longer running frames.
/// </summary>
internal static bool TryRunOutsidePumpFrame(Action action)
{
if (System.Threading.Interlocked.CompareExchange(ref _pluginPumpInFrame, 1, 0) != 0)
return false;
try { action(); }
finally { System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0); }
return true;
}
/// <summary>True when anything ImGui should be drawn this frame.</summary>
private static bool HasImGuiContent()
{
@ -486,9 +505,13 @@ internal static class EngineFrameController
/// <summary>
/// Panel faces show only in the world, like the Avalonia overlay (hidden
/// between characters, not closed).
/// between characters, not closed). Also off as soon as AC leaves the world screen
/// (UiFlowHooks, before the logout dispatch catches up) and for good once
/// Client::Cleanup starts.
/// </summary>
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete
&& Compatibility.UiFlowHooks.InWorldOrUnknown
&& !Compatibility.UiFlowHooks.ClientCleanupStarted;
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
private static float _uiScale = 1f;

View file

@ -123,6 +123,17 @@ internal static unsafe class ImGuiPopOuts
/// <summary>The pop-out typing into a text box, or null (for the input log). AC thread.</summary>
public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null;
/// <summary>
/// True when the cursor is over <paramref name="title"/>'s pop-out window right now
/// (UiDropTargets: an AC item released over a popped-out panel). AC thread.
/// </summary>
public static bool IsCursorOver(string title)
{
if (!Pops.TryGetValue(title, out PopOut? pop) || pop.Window == null || pop.Window.Hwnd == IntPtr.Zero)
return false;
return GetCursorPos(out POINT cursor) && WindowFromPoint(cursor) == pop.Window.Hwnd;
}
/// <summary>The screen position of the game window's client origin (to place a pop-out where the docked panel was).</summary>
public static Vector2 ClientOriginOnScreen()
{

View file

@ -858,9 +858,12 @@ internal static class MonsterHud
const float margin = 60f;
if (MonsterHudSettings.KeepOnScreen)
{
// Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name).
Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale,
(label ? 22f : 56f) * f.UiScale * userScale);
// Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name),
// grown with the plate type's bar / text size.
float sideMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MonsterTextSize);
float topMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MonsterTextSize);
Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale * sideMul,
(label ? 22f : 56f) * f.UiScale * userScale * topMul);
p.Anchor = new Vector2(MathF.Round(c.X), MathF.Round(c.Y));
p.OnScreen = true;
}
@ -1004,7 +1007,7 @@ internal static class MonsterHud
if (p.IsLabel)
{
// Name only: the same bold bake as a monster's name, no bar, badge or icons.
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s);
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * LabelTextSize(p.Kind));
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name);
p.BadgeW = 0f;
@ -1016,14 +1019,17 @@ internal static class MonsterHud
return;
}
p.BarW = MathF.Round(112f * k);
p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k);
// Bar width / height and text size each have their own multiplier (1 = the default look).
float text = MonsterHudSettings.MonsterTextSize;
p.BarW = MathF.Round(112f * k * MonsterHudSettings.MonsterBarWidth);
p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k * MonsterHudSettings.MonsterBarHeight);
// Sizes follow the 11 px bold / 9 px regular bakes; the font drawn is the smallest bake at
// least that big, so a scaled-up plate shrinks a bigger bake instead of stretching (blur).
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s);
// Picking a baked font per size: nothing is re-baked when a text size changes.
p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * text);
p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true);
p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s);
p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s * text);
p.SmallFont = ImGuiFonts.Sharp(p.SmallSize, bold: false);
p.NameW = MonsterHudSettings.ShowNames && p.Name.Length > 0 ? TextWidth(p.NameFont, p.NameSize, p.Name) : 0f;
@ -1039,11 +1045,15 @@ internal static class MonsterHud
float nameH = (p.NameW > 0 || p.BadgeW > 0) ? p.NameSize + 2f * k : 0f;
// The weak pill (left) and distance (right) hang off the bar's ends: keep them
// inside the crowd-avoidance box, symmetric so the plate stays centred.
float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k : 0f;
float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k * text : 0f;
p.Width = MathF.Max(p.BarW + side, nameLine) + 8f * k;
p.Height = nameH + p.BarH + p.BelowBar;
}
/// <summary>A name label's text size: players' or NPCs' (vendors count as NPCs).</summary>
private static float LabelTextSize(byte kind) =>
kind == RadarKind.Player ? MonsterHudSettings.PlayerTextSize : MonsterHudSettings.NpcTextSize;
/// <summary>Screen rect of a plate at a given upward nudge: (x0, y0, x1, y1).</summary>
private static Vector4 RectAt(Plate p, float nudge, float uiScale)
{

View file

@ -102,6 +102,21 @@ internal static class MonsterHudSettings
public static bool GainLum = true;
public static bool GainRadiance = true;
// Per-plate-type sizing (2026-10-05), multipliers on today's look (1 = unchanged), applied on
// top of Scale. Bar width / height and the text drawn in or over the plate, each on its own.
// NPC and player names are name-only labels (no bar), so they only have a text size.
/// <summary>Monster plates: the health bar's width and height, and their text (name, level, HP, weak-to, distance).</summary>
public static float MonsterBarWidth = 1.0f, MonsterBarHeight = 1.0f, MonsterTextSize = 1.0f;
/// <summary>Name labels over NPCs and vendors.</summary>
public static float NpcTextSize = 1.0f;
/// <summary>Name labels over other players.</summary>
public static float PlayerTextSize = 1.0f;
/// <summary>Your own plate: the three bars' width and height, and their text (cur / max numbers, your name).</summary>
public static float SelfBarWidth = 1.0f, SelfBarHeight = 1.0f, SelfTextSize = 1.0f;
public const float MinBarWidth = 0.5f, MaxBarWidth = 2.5f;
public const float MinBarHeight = 0.5f, MaxBarHeight = 3.0f;
public const float MinTextSize = 0.5f, MaxTextSize = 2.0f;
// ── Ranges (shared by the Settings face, the command and Load) ──────
public const float MinDistance = 5f, MaxDistanceLimit = 120f;
public const int MinPlates = 1, MaxPlatesLimit = 60;
@ -137,74 +152,88 @@ internal static class MonsterHudSettings
{
string path = FilePath;
if (!File.Exists(path)) return;
foreach (string raw in File.ReadAllLines(path))
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string val = line[(eq + 1)..].Trim();
switch (key)
{
case "enabled": Enabled = val == "1"; break;
case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break;
case "maxPlates":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit);
break;
case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break;
case "showNames": ShowNames = val == "1"; break;
case "showHp": ShowHpNumbers = val == "1"; break;
case "showDistance": ShowDistance = val == "1"; break;
case "showLevel": ShowLevel = val == "1"; break;
case "showWeakness": ShowWeakness = val == "1"; break;
case "fade": FadeWithDistance = val == "1"; break;
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
case "clickSelect": ClickToSelect = val == "1"; break;
case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
case "npcNames": NpcNames = val == "1"; break;
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
case "npcMax":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm))
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
break;
case "playerNames": PlayerNames = val == "1"; break;
case "showDebuffs": ShowDebuffs = val == "1"; break;
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
case "selfPlate": SelfPlate = val == "1"; break;
case "selfNumbers": SelfNumbers = val == "1"; break;
case "selfName": SelfName = val == "1"; break;
case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break;
case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break;
case "selfLocked": SelfLocked = val == "1"; break;
case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break;
case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break;
case "numbers": Numbers = val == "1"; break;
case "numDealt": NumDealt = val == "1"; break;
case "numTaken": NumTaken = val == "1"; break;
case "numHeals": NumHeals = val == "1"; break;
case "numKills": NumKills = val == "1"; break;
case "keepOnScreen": KeepOnScreen = val == "1"; break;
case "numRestores": NumRestores = val == "1"; break;
case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break;
case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break;
case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break;
case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break;
case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break;
case "gains": Gains = val == "1"; break;
case "gainXp": GainXp = val == "1"; break;
case "gainLum": GainLum = val == "1"; break;
case "gainRadiance": GainRadiance = val == "1"; break;
}
}
ApplyLines(File.ReadAllLines(path));
}
catch { /* best-effort: defaults stay */ }
finally { _loaded = true; }
}
}
/// <summary>Applies the file's key=value lines (unknown keys and bad values are skipped). Also the tests' entry.</summary>
internal static void ApplyLines(string[] lines)
{
foreach (string raw in lines)
{
string line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#')) continue;
int eq = line.IndexOf('=');
if (eq <= 0) continue;
string key = line[..eq].Trim();
string val = line[(eq + 1)..].Trim();
switch (key)
{
case "enabled": Enabled = val == "1"; break;
case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break;
case "maxPlates":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n))
MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit);
break;
case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break;
case "showNames": ShowNames = val == "1"; break;
case "showHp": ShowHpNumbers = val == "1"; break;
case "showDistance": ShowDistance = val == "1"; break;
case "showLevel": ShowLevel = val == "1"; break;
case "showWeakness": ShowWeakness = val == "1"; break;
case "fade": FadeWithDistance = val == "1"; break;
case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break;
case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break;
case "clickSelect": ClickToSelect = val == "1"; break;
case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break;
case "npcNames": NpcNames = val == "1"; break;
case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break;
case "npcMax":
if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm))
MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit);
break;
case "playerNames": PlayerNames = val == "1"; break;
case "showDebuffs": ShowDebuffs = val == "1"; break;
case "showOthersDebuff": ShowOthersDebuff = val == "1"; break;
case "selfPlate": SelfPlate = val == "1"; break;
case "selfNumbers": SelfNumbers = val == "1"; break;
case "selfName": SelfName = val == "1"; break;
case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break;
case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break;
case "selfLocked": SelfLocked = val == "1"; break;
case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break;
case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break;
case "numbers": Numbers = val == "1"; break;
case "numDealt": NumDealt = val == "1"; break;
case "numTaken": NumTaken = val == "1"; break;
case "numHeals": NumHeals = val == "1"; break;
case "numKills": NumKills = val == "1"; break;
case "keepOnScreen": KeepOnScreen = val == "1"; break;
case "numRestores": NumRestores = val == "1"; break;
case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break;
case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break;
case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break;
case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break;
case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break;
case "gains": Gains = val == "1"; break;
case "gainXp": GainXp = val == "1"; break;
case "gainLum": GainLum = val == "1"; break;
case "gainRadiance": GainRadiance = val == "1"; break;
case "monsterBarWidth": if (TryF(val, out float mbw)) MonsterBarWidth = Math.Clamp(mbw, MinBarWidth, MaxBarWidth); break;
case "monsterBarHeight": if (TryF(val, out float mbh)) MonsterBarHeight = Math.Clamp(mbh, MinBarHeight, MaxBarHeight); break;
case "monsterTextSize": if (TryF(val, out float mts)) MonsterTextSize = Math.Clamp(mts, MinTextSize, MaxTextSize); break;
case "npcTextSize": if (TryF(val, out float nts)) NpcTextSize = Math.Clamp(nts, MinTextSize, MaxTextSize); break;
case "playerTextSize": if (TryF(val, out float pts)) PlayerTextSize = Math.Clamp(pts, MinTextSize, MaxTextSize); break;
case "selfBarWidth": if (TryF(val, out float sbw)) SelfBarWidth = Math.Clamp(sbw, MinBarWidth, MaxBarWidth); break;
case "selfBarHeight": if (TryF(val, out float sbh)) SelfBarHeight = Math.Clamp(sbh, MinBarHeight, MaxBarHeight); break;
case "selfTextSize": if (TryF(val, out float sts)) SelfTextSize = Math.Clamp(sts, MinTextSize, MaxTextSize); break;
}
}
}
private static bool TryF(string s, out float v) => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v);
/// <summary>Writes the settings in the background. Any thread.</summary>
@ -220,56 +249,70 @@ internal static class MonsterHudSettings
string? dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using var sw = new StreamWriter(path, append: false);
sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.");
sw.WriteLine($"enabled={B(Enabled)}");
sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}"));
sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}");
sw.WriteLine($"showNames={B(ShowNames)}");
sw.WriteLine($"showHp={B(ShowHpNumbers)}");
sw.WriteLine($"showDistance={B(ShowDistance)}");
sw.WriteLine($"showLevel={B(ShowLevel)}");
sw.WriteLine($"showWeakness={B(ShowWeakness)}");
sw.WriteLine($"fade={B(FadeWithDistance)}");
sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}"));
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
sw.WriteLine($"npcNames={B(NpcNames)}");
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
sw.WriteLine($"playerNames={B(PlayerNames)}");
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
sw.WriteLine($"selfPlate={B(SelfPlate)}");
sw.WriteLine($"selfNumbers={B(SelfNumbers)}");
sw.WriteLine($"selfName={B(SelfName)}");
sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}");
sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}");
sw.WriteLine($"selfLocked={B(SelfLocked)}");
sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}"));
sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}"));
sw.WriteLine($"numbers={B(Numbers)}");
sw.WriteLine($"numDealt={B(NumDealt)}");
sw.WriteLine($"numTaken={B(NumTaken)}");
sw.WriteLine($"numHeals={B(NumHeals)}");
sw.WriteLine($"numKills={B(NumKills)}");
sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}");
sw.WriteLine($"numRestores={B(NumRestores)}");
sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}"));
sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}"));
sw.WriteLine($"selfPosition={SelfPosition}");
sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}"));
sw.WriteLine($"gains={B(Gains)}");
sw.WriteLine($"gainXp={B(GainXp)}");
sw.WriteLine($"gainLum={B(GainLum)}");
sw.WriteLine($"gainRadiance={B(GainRadiance)}");
WriteAll(sw);
}
catch { /* non-fatal */ }
}
}
/// <summary>Every setting as the file's key=value lines. Also the tests' entry.</summary>
internal static void WriteAll(TextWriter sw)
{
sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.");
sw.WriteLine($"enabled={B(Enabled)}");
sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}"));
sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}");
sw.WriteLine($"showNames={B(ShowNames)}");
sw.WriteLine($"showHp={B(ShowHpNumbers)}");
sw.WriteLine($"showDistance={B(ShowDistance)}");
sw.WriteLine($"showLevel={B(ShowLevel)}");
sw.WriteLine($"showWeakness={B(ShowWeakness)}");
sw.WriteLine($"fade={B(FadeWithDistance)}");
sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}"));
sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}"));
sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}"));
sw.WriteLine($"clickSelect={B(ClickToSelect)}");
sw.WriteLine($"npcNames={B(NpcNames)}");
sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}"));
sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}"));
sw.WriteLine($"playerNames={B(PlayerNames)}");
sw.WriteLine($"showDebuffs={B(ShowDebuffs)}");
sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}");
sw.WriteLine($"selfPlate={B(SelfPlate)}");
sw.WriteLine($"selfNumbers={B(SelfNumbers)}");
sw.WriteLine($"selfName={B(SelfName)}");
sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}");
sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}");
sw.WriteLine($"selfLocked={B(SelfLocked)}");
sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}"));
sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}"));
sw.WriteLine($"numbers={B(Numbers)}");
sw.WriteLine($"numDealt={B(NumDealt)}");
sw.WriteLine($"numTaken={B(NumTaken)}");
sw.WriteLine($"numHeals={B(NumHeals)}");
sw.WriteLine($"numKills={B(NumKills)}");
sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}");
sw.WriteLine($"numRestores={B(NumRestores)}");
sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}"));
sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}"));
sw.WriteLine($"selfPosition={SelfPosition}");
sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}"));
sw.WriteLine($"gains={B(Gains)}");
sw.WriteLine($"gainXp={B(GainXp)}");
sw.WriteLine($"gainLum={B(GainLum)}");
sw.WriteLine($"gainRadiance={B(GainRadiance)}");
sw.WriteLine(FormattableString.Invariant($"monsterBarWidth={MonsterBarWidth:0.##}"));
sw.WriteLine(FormattableString.Invariant($"monsterBarHeight={MonsterBarHeight:0.##}"));
sw.WriteLine(FormattableString.Invariant($"monsterTextSize={MonsterTextSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"npcTextSize={NpcTextSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"playerTextSize={PlayerTextSize:0.##}"));
sw.WriteLine(FormattableString.Invariant($"selfBarWidth={SelfBarWidth:0.##}"));
sw.WriteLine(FormattableString.Invariant($"selfBarHeight={SelfBarHeight:0.##}"));
sw.WriteLine(FormattableString.Invariant($"selfTextSize={SelfTextSize:0.##}"));
}
private static string B(bool v) => v ? "1" : "0";
/// <summary>Back to the defaults (and saved). Render / chat thread.</summary>
@ -286,9 +329,24 @@ internal static class MonsterHudSettings
NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true;
GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above;
Gains = true; GainXp = true; GainLum = true; GainRadiance = true;
ResetSizesNoSave();
Save();
}
/// <summary>Every plate type's bar and text size back to 1 (and saved). Render / chat thread.</summary>
public static void ResetSizes()
{
ResetSizesNoSave();
Save();
}
private static void ResetSizesNoSave()
{
MonsterBarWidth = 1.0f; MonsterBarHeight = 1.0f; MonsterTextSize = 1.0f;
NpcTextSize = 1.0f; PlayerTextSize = 1.0f;
SelfBarWidth = 1.0f; SelfBarHeight = 1.0f; SelfTextSize = 1.0f;
}
/// <summary>The fixed plate back to its default spot (and saved). Render / chat thread.</summary>
public static void ResetSelfPosition()
{
@ -314,7 +372,10 @@ internal static class MonsterHudSettings
$"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " +
$"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " +
$"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " +
$"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}).");
$"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}); " +
$"sizes: monster bar {MonsterBarWidth:0.##}x{MonsterBarHeight:0.##} text {MonsterTextSize:0.##}, " +
$"NPC text {NpcTextSize:0.##}, player text {PlayerTextSize:0.##}, " +
$"your bars {SelfBarWidth:0.##}x{SelfBarHeight:0.##} text {SelfTextSize:0.##}.");
private static string OnOff(bool v) => v ? "on" : "off";
}

View file

@ -68,6 +68,12 @@ internal static class MonsterHudSettingsUi
changed |= Toggle("Weak-to element", ref MonsterHudSettings.ShowWeakness,
"What the monster takes most damage from, from RynthAi's Damage data (needs RynthAi).");
changed |= Toggle("Distance", ref MonsterHudSettings.ShowDistance, null);
changed |= SizeSlider("Bar width", ref MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w,
"How wide a monster's health bar is (1.00x = the default). On top of Look > Scale.");
changed |= SizeSlider("Bar height", ref MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w,
"How tall (thick) a monster's health bar is (1.00x = the default). HP numbers need a bar at least 9 px tall.");
changed |= SizeSlider("Text size", ref MonsterHudSettings.MonsterTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"The monster plate's text: name, level badge, HP numbers, weak-to pill and distance (1.00x = the default).");
Section("Names over NPCs and players", w);
changed |= Toggle("NPC names", ref MonsterHudSettings.NpcNames,
@ -77,8 +83,12 @@ internal static class MonsterHudSettingsUi
MonsterHudSettings.MinNpcDistance, MonsterHudSettings.MaxNpcDistanceLimit, "%.0f", w);
changed |= SliderI("Max names", ref MonsterHudSettings.MaxNpcLabels,
MonsterHudSettings.MinNpcLabels, MonsterHudSettings.MaxNpcLabelsLimit, w);
changed |= SizeSlider("NPC name size", ref MonsterHudSettings.NpcTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"Text size of the names over NPCs and vendors (1.00x = the default). Names have no bar.");
changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames,
"The name over other players too (blue), within the same distance and count. Chat: /rv plates players.");
changed |= SizeSlider("Player name size", ref MonsterHudSettings.PlayerTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"Text size of the names over other players (1.00x = the default). Names have no bar.");
Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w);
Section("Debuffs", w);
@ -94,6 +104,12 @@ internal static class MonsterHudSettingsUi
"Your own health, stamina and mana bars: fixed on screen, or following your character. Chat: /rv plates self.");
changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true);
changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true);
changed |= SizeSlider("Your bar width", ref MonsterHudSettings.SelfBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w,
"How wide your health, stamina and mana bars are (1.00x = the default).");
changed |= SizeSlider("Your bar height", ref MonsterHudSettings.SelfBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w,
"How tall (thick) each of your bars is (1.00x = the default). The numbers need a bar at least 8 px tall.");
changed |= SizeSlider("Your text size", ref MonsterHudSettings.SelfTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w,
"Your plate's text: the cur / max numbers and your name (1.00x = the default).");
bool fixedOn = MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed;
if (Toggle("Fixed on screen", ref fixedOn,
@ -151,6 +167,14 @@ internal static class MonsterHudSettingsUi
changed |= Toggle("Fade and shrink with distance", ref MonsterHudSettings.FadeWithDistance, null);
ImGuiNET.ImGui.Dummy(new Vector2(0, 8));
if (SmallButton("Reset bar and text sizes"))
{
MonsterHudSettings.ResetSizes(); // saves
changed = false;
}
if (ImGuiNET.ImGui.IsItemHovered())
ImGuiNET.ImGui.SetTooltip("Every plate type's bar width, bar height and text size back to 1.00x.");
ImGuiNET.ImGui.Dummy(new Vector2(0, 2));
if (SmallButton("Reset all to defaults"))
{
MonsterHudSettings.ResetToDefaults();
@ -238,6 +262,15 @@ internal static class MonsterHudSettingsUi
return EndSliderRow(changed);
}
/// <summary>A size multiplier slider ("1.00x" = the default look) with a tooltip. Labels are the ids: keep them unique.</summary>
private static bool SizeSlider(string label, ref float value, float min, float max, float w, string tip)
{
BeginSliderRow(label, w);
bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, "%.2fx", ImGuiSliderFlags.AlwaysClamp);
if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tip);
return EndSliderRow(changed);
}
private static bool SliderI(string label, ref int value, int min, int max, float w)
{
BeginSliderRow(label, w);

View file

@ -280,15 +280,18 @@ internal static class PlayerPlate
float k = l.K = MonsterHudSettings.Scale * uiScale;
bool numbers = l.Numbers = MonsterHudSettings.SelfNumbers;
// With numbers on, the bars grow to fit bold, outlined text that reads over any fill.
l.BarW = MathF.Round((numbers ? 124f : 96f) * k);
l.BarH = MathF.Round((numbers ? 15f : 5f) * k);
// Width, height and text each have their own multiplier on top (1 = the default look).
l.BarW = MathF.Round((numbers ? 124f : 96f) * k * MonsterHudSettings.SelfBarWidth);
l.BarH = MathF.Round((numbers ? 15f : 5f) * k * MonsterHudSettings.SelfBarHeight);
l.Gap = MathF.Max(2f, MathF.Round(2f * k));
l.Round = MathF.Max(1f, 1.5f * k);
// Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up).
l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
// Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up;
// nothing is re-baked when the text size changes).
float text = MonsterHudSettings.Scale * MonsterHudSettings.SelfTextSize;
l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text);
l.Small = ImGuiFonts.Sharp(l.SmallSize, bold: true);
l.BlockH = 3 * l.BarH + 2 * l.Gap;
l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale);
l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text);
l.NameFont = ImGuiFonts.Sharp(l.NameSize, bold: true);
l.NameH = MonsterHudSettings.SelfName ? l.NameSize + 3f * k : 0f;
return l;
@ -358,7 +361,9 @@ internal static class PlayerPlate
float tw = MonsterHud.TextWidth(font, size, text);
var pos = new Vector2(MathF.Round(left + (w - tw) * 0.5f), MathF.Round(top + (h - size) * 0.5f));
// A dark band behind the text, then an outline, so it reads over bright and dark fills alike.
dl.AddRectFilled(new Vector2(pos.X - 3f, top + 1f), new Vector2(pos.X + tw + 3f, top + h - 1f), MonsterHud.Mul(0x70000000u, a), 2f);
// (Text sized bigger than the bar: the band grows to the text.)
dl.AddRectFilled(new Vector2(pos.X - 3f, MathF.Min(top + 1f, pos.Y)), new Vector2(pos.X + tw + 3f, MathF.Max(top + h - 1f, pos.Y + size)),
MonsterHud.Mul(0x70000000u, a), 2f);
MonsterHud.OutlinedText(dl, font, size, pos, a, text);
dl.AddText(font, size, pos, MonsterHud.Mul(NumCol, a), text);
}

View file

@ -205,6 +205,7 @@ internal sealed class LootEditorFace : IImGuiPanel
else RuleView(origin, size, w);
}
End(origin, size);
AcceptAcDrops(origin, size);
_lootAdd.Draw();
// An item rule added to the open profile: show it (the state already carries it and its Focus).
if (_lootAdd.TakeAdded() && _mode == Mode.List && _state != null && _state.Focus >= 0 && _state.Focus < _state.Rules.Count)
@ -212,6 +213,39 @@ internal sealed class LootEditorFace : IImGuiPanel
_picker.Draw();
}
// ── Drop an item from AC's own inventory on the editor (2026-10-05) ──
// Compatibility/UiElementHooks keeps a drop over this body from AC (AC's own
// "not caught" path, the item stays put) and hands the item here; it opens the
// same "Add to loot profile" popup as "Add selected item", for that item.
private const string DropKey = "LootEditor";
private void AcceptAcDrops(Vector2 origin, Vector2 size)
{
LootEditStateDto? s = _state;
bool can = !_unavailable && s != null && s.Path.Length > 0 && !s.Dirty
&& (!s.ReadOnly || s.Format == "json") && !_lootAdd.IsOpen;
UiDropTargets.Publish(DropKey, Title, origin, origin + size, can);
if (UiDropTargets.TryTake(DropKey, out uint itemId) && can)
{
Compatibility.ClientObjectHooks.TryGetObjectName(itemId, out string name);
_lootAdd.Open(itemId, name ?? string.Empty, toOpenProfile: true);
}
// While AC drags an item: show that letting go here adds a rule.
if (!can || Compatibility.UiElementHooks.CurrentDragObject == 0)
return;
bool over = UiDropTargets.IsCursorOver(DropKey);
var dl = ImGuiNET.ImGui.GetWindowDrawList();
dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f);
string hint = over ? "Let go: add a loot rule for this item" : "Drop an item here to add a loot rule";
Vector2 ts = ImGuiNET.ImGui.CalcTextSize(hint);
Vector2 at = new(origin.X + (size.X - ts.X) * 0.5f, origin.Y + size.Y - ts.Y - 10);
dl.AddRectFilled(at - new Vector2(6, 3), at + ts + new Vector2(6, 3), ShellBg, 4);
dl.AddText(at, over ? Green : Teal, hint);
}
private void RequestOpen(string path)
{
if (_state != null && _state.Dirty && path.Length > 0 && !SamePath(path, _state.Path))

View file

@ -25,6 +25,7 @@ using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI;
using RynthCore.Engine.UI.ScriptWindows;
@ -53,6 +54,8 @@ internal sealed class SkillDatTables
public uint[] TrainedXp = Array.Empty<uint>();
public uint[] SpecializedXp = Array.Empty<uint>();
public ulong[] LevelXp = Array.Empty<ulong>();
/// <summary>The same arrays as one object (Compatibility/TrainingCosts).</summary>
public XpTableData Xp = new();
}
internal static class SkillDat
@ -137,51 +140,31 @@ internal static class SkillDat
return r.Ok && t.Skills.Count > 0;
}
// The XpTable layout and the cost arithmetic live in Compatibility/TrainingCosts.cs (shared
// with the plugin API's raise calls and tested against a real portal.dat).
private static bool ParseXp(byte[] raw, SkillDatTables t)
{
var r = new Reader(raw);
r.U32(); // file id
int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32();
int levels = (int)r.U32();
if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0
|| attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000)
return false;
t.AttributeXp = r.U32s(attrs + 1);
t.VitalXp = r.U32s(vitals + 1);
t.TrainedXp = r.U32s(trained + 1);
t.SpecializedXp = r.U32s(spec + 1);
var lv = new ulong[levels + 1];
for (int i = 0; i <= levels; i++) lv[i] = r.U64();
t.LevelXp = lv;
return r.Ok;
if (!TrainingCosts.TryParseXpTable(raw, out XpTableData xp)) return false;
t.Xp = xp;
t.AttributeXp = xp.AttributeXp;
t.VitalXp = xp.VitalXp;
t.TrainedXp = xp.TrainedXp;
t.SpecializedXp = xp.SpecializedXp;
t.LevelXp = xp.LevelXp;
return true;
}
// ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ──
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length;
public static bool IsMax(uint[] table, uint ranks) => TrainingCosts.IsMax(table, ranks);
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary>
public static long CostOf(uint[] table, uint ranks, uint spent, int n)
{
if (n < 1) return 0;
long target = (long)ranks + n;
if (target >= table.Length) return -1;
return Math.Max(0L, (long)table[target] - spent);
}
public static long CostOf(uint[] table, uint ranks, uint spent, int n) => TrainingCosts.CostOf(table, ranks, spent, n);
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary>
public static int Affordable(uint[] table, uint ranks, uint spent, long available)
{
int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue));
while (lo < hi)
{
int mid = (lo + hi + 1) / 2;
long c = CostOf(table, ranks, spent, mid);
if (c >= 0 && c <= available) lo = mid; else hi = mid - 1;
}
return lo;
}
public static int Affordable(uint[] table, uint ranks, uint spent, long available) =>
TrainingCosts.Affordable(table, ranks, spent, available);
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
private ref struct Reader

View file

@ -3,7 +3,8 @@
// ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs),
// in three tabs:
// Terrain the plugin's overlays (radar ring, unclimbable slopes,
// impassable water), colours (AARRGGBB hex + swatch), tuning
// impassable water), colours (AARRGGBB hex + swatch) each
// with an opacity slider (the colour's alpha byte), tuning
// sliders (Ctrl+click to type a value), water terrain types,
// and "Log terrain types here";
// Nameplates the RynthVision nameplates (monster plates, debuff icons,
@ -115,10 +116,15 @@ internal sealed class VisionFace : IImGuiPanel
if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes);
if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water);
Header("Colors (hex AARRGGBB)");
Header("Colors (hex AARRGGBB) and opacity");
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor);
busy |= OpacitySlider(SlopeOpacityF, _slopeHex, ref s.SlopeColor);
busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor);
busy |= OpacitySlider(WaterOpacityF, _waterHex, ref s.WaterColor);
busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor);
busy |= OpacitySlider(RadarOpacityF, _radarHex, ref s.RadarColor);
ImGuiNET.ImGui.PopItemWidth();
Header("Tuning");
ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8));
@ -188,6 +194,10 @@ internal sealed class VisionFace : IImGuiPanel
private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor);
private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor);
private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor);
// Opacity is the colour's alpha byte: the slider saves the colour field.
private static readonly Field SlopeOpacityF = Field.Slider("Slope opacity", VisionKeys.SlopeColor);
private static readonly Field WaterOpacityF = Field.Slider("Water opacity", VisionKeys.WaterColor);
private static readonly Field RadarOpacityF = Field.Slider("Radar ring opacity", VisionKeys.RadarColor);
private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange);
private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick);
private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight);
@ -227,6 +237,24 @@ internal sealed class VisionFace : IImGuiPanel
return typing;
}
/// <summary>
/// The colour's alpha as 0-100 %: label, then the slider. Rewrites the alpha byte (RGB kept) and the hex
/// box as it moves, saves the colour on release. Untouched, the colour is never rewritten. True while in use.
/// </summary>
private bool OpacitySlider(Field f, byte[] hex, ref uint argb)
{
ImGuiNET.ImGui.TextUnformatted(f.Label);
float pct = ArgbOpacity.Percent(argb);
if (ImGuiNET.ImGui.SliderFloat(f.Id, ref pct, 0f, 100f, "%.0f%%", ImGuiSliderFlags.AlwaysClamp))
{
argb = ArgbOpacity.WithPercent(argb, pct);
WriteUtf8(hex, argb.ToString("X8"));
}
if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key);
ImGuiNET.ImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value");
return ImGuiNET.ImGui.IsItemActive();
}
/// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary>
private bool Slider(Field f, ref double value, double min, double max, string format)
{

View file

@ -369,6 +369,8 @@ internal static class RynthCoreShell
new System.Threading.Thread(() =>
{
System.Threading.Thread.Sleep(120);
// Asked for by hand: the reload deferral (EntryPoint.Shutdown) doesn't hold it.
EntryPoint.NoteManualReload();
bool ok = EngineLifecycle.SignalReload();
RynthLog.Info($"ERl: SignalReload returned {ok}.");
})

View file

@ -0,0 +1,135 @@
// ============================================================================
// RynthCore.Engine - ImGui/UiDropTargets.cs
//
// AC items dropped on the engine's ImGui panels (2026-10-05). A face that takes
// drops publishes its body rect every frame it draws (Publish); when the player
// drags an item out of an AC item list (a pack, the main inventory) and lets go
// over that rect, Compatibility/UiElementHooks' UIElement::CatchDroppedItem
// detour asks TryClaim. A claimed drop never reaches AC: the detour answers
// "not caught" (false), which is AC's own drop-rejected path, so the item stays
// where it was. The face picks the item up with TryTake on its next draw.
//
// All on AC's main thread: faces draw in EndScene, the detour runs inside AC's
// StopDragandDrop. A target not published for StaleMs (panel closed, hidden,
// between characters) never claims.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.ImGuiBackend;
internal static class UiDropTargets
{
private const long StaleMs = 500;
private sealed class Target
{
public required string Key;
public required string PanelTitle;
public bool Popped;
public Vector2 Min, Max; // ImGui coordinates of the game window's client area (docked)
public long SeenMs;
public bool Accepting;
public bool HasDrop;
public uint ItemId, SpellId;
}
[StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; }
[DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p);
private static readonly Dictionary<string, Target> Targets = new(StringComparer.Ordinal);
private static readonly object Sync = new();
/// <summary>
/// Once per frame from a face's Draw: <paramref name="min"/>..<paramref name="max"/> is the
/// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size).
/// <paramref name="accepting"/> false: drawn, but a drop now wouldn't be used (it then
/// goes to AC as usual). Popped-out faces hit-test against their own window.
/// </summary>
public static void Publish(string key, string panelTitle, Vector2 min, Vector2 max, bool accepting)
{
lock (Sync)
{
if (!Targets.TryGetValue(key, out Target? t))
Targets[key] = t = new Target { Key = key, PanelTitle = panelTitle };
t.Popped = ImGuiPopOuts.InPopOutFrame;
t.Min = min;
t.Max = max;
t.Accepting = accepting;
t.SeenMs = Environment.TickCount64;
}
}
/// <summary>
/// UIElement::CatchDroppedItem detour, AC's main thread: is the cursor over a live,
/// accepting target? Then that target takes the item and the caller keeps it from AC.
/// </summary>
public static bool TryClaim(uint itemId, uint spellId, out string key)
{
key = string.Empty;
if (itemId == 0)
return false;
long now = Environment.TickCount64;
lock (Sync)
{
foreach (Target t in Targets.Values)
{
if (!t.Accepting || now - t.SeenMs > StaleMs || !IsCursorOver(t))
continue;
t.HasDrop = true;
t.ItemId = itemId;
t.SpellId = spellId;
key = t.Key;
return true;
}
}
return false;
}
/// <summary>The face's draw: an item dropped on it since the last call.</summary>
public static bool TryTake(string key, out uint itemId)
{
itemId = 0;
lock (Sync)
{
if (!Targets.TryGetValue(key, out Target? t) || !t.HasDrop)
return false;
t.HasDrop = false;
itemId = t.ItemId;
return itemId != 0;
}
}
/// <summary>The cursor is over the target now (the face's "drop here" highlight).</summary>
public static bool IsCursorOver(string key)
{
lock (Sync)
return Targets.TryGetValue(key, out Target? t) && IsCursorOver(t);
}
private static bool IsCursorOver(Target t)
{
if (t.Popped)
return ImGuiPopOuts.IsCursorOver(t.PanelTitle);
if (!GetCursorPos(out POINT p))
return false;
Vector2 local = new Vector2(p.X, p.Y) - ImGuiPopOuts.ClientOriginOnScreen();
return local.X >= t.Min.X && local.Y >= t.Min.Y && local.X < t.Max.X && local.Y < t.Max.Y;
}
public static string Describe()
{
long now = Environment.TickCount64;
lock (Sync)
{
if (Targets.Count == 0)
return "Drop targets: none drawn yet.";
var parts = new List<string>();
foreach (Target t in Targets.Values)
parts.Add($"{t.Key} ({(now - t.SeenMs <= StaleMs ? (t.Accepting ? "live" : "drawn, not accepting") : "not drawn")}{(t.Popped ? ", popped out" : string.Empty)})");
return "Drop targets: " + string.Join(", ", parts) + ".";
}
}
}

View file

@ -898,6 +898,15 @@ internal static unsafe class Win32Backend
}
}
// ── Remote tap-to-click (the phone, via the StatusAgent's PostMessage) ──
// A posted mouse message whose point is not where the cursor was when it was queued did not come
// from the mouse: it is the StatusAgent clicking where the phone tapped. Without this, the ImGui
// capture below judged it by the REAL cursor (NewFrame's GetCursorPos): on the focused client,
// with the PC's mouse parked over a RynthCore panel, every remote click was eaten, and the
// phone's tap still fed ImGui a fake cursor. Hand it straight to AC instead.
if (IsRemoteClientMouse(hWnd, msg, lParam))
return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam);
// ── Chat capture: consume all key input for the chat TextBox ────
// Game HWND keeps Win32 focus throughout; callbacks dispatch Text
// updates to the panel on Avalonia's UI thread — no Avalonia focus needed.
@ -1486,6 +1495,29 @@ internal static unsafe class Win32Backend
};
}
[DllImport("user32.dll")]
private static extern uint GetMessagePos();
/// <summary>
/// True for a client-area mouse message another process posted (the StatusAgent's remote click):
/// Windows stamps every queued message with the cursor position at the time it was queued
/// (GetMessagePos). Mouse input carries that same point in lParam; a PostMessage from elsewhere
/// carries its own point while the stamp is wherever the real cursor sat. A 2 px slack covers
/// rounding. Only the move/click messages whose lParam is client coordinates are tested (the wheel's
/// lParam is screen coordinates).
/// </summary>
private static bool IsRemoteClientMouse(IntPtr hWnd, uint msg, IntPtr lParam)
{
if (msg != WM_MOUSEMOVE && msg != WM_LBUTTONDOWN && msg != WM_LBUTTONUP && msg != WM_RBUTTONDOWN && msg != WM_RBUTTONUP)
return false;
uint pos = GetMessagePos();
var stamp = new POINT { X = (short)(pos & 0xFFFF), Y = (short)((pos >> 16) & 0xFFFF) };
if (!ScreenToClient(hWnd, ref stamp))
return false;
int x = (short)((long)lParam & 0xFFFF), y = (short)(((long)lParam >> 16) & 0xFFFF);
return Math.Abs(stamp.X - x) > 2 || Math.Abs(stamp.Y - y) > 2;
}
private static bool IsMouseMessage(uint msg)
{
return msg >= WM_MOUSEMOVE && msg <= WM_MBUTTONUP

View file

@ -0,0 +1,157 @@
// ============================================================================
// RynthCore.Engine - Net/AcPacketWire.cs
// Where the message fragments sit in one server-to-client UDP datagram.
//
// Written from the AC wire format as the engine already reads it (RawPacketParser's
// 20-byte header + 16-byte fragment headers) and general knowledge of the protocol;
// no generated definitions. Pure code: no engine state, compiled into the
// NetMessageTests replay runner as is.
//
// Datagram:
// header (20 bytes)
// +0 u32 sequence
// +4 u32 flags (PacketFlags below)
// +8 u32 checksum (not checked: we only read)
// +12 u16 recipient id
// +14 u16 time
// +16 u16 size bytes after the header (optional headers + fragments)
// +18 u16 iteration
// optional headers, one per flag bit set, in ascending bit order
// fragments, back to back, when flags has BlobFragments
//
// Fragment (16-byte header, then its share of the message):
// +0 u32 sequence the message's id: every fragment of one message shares it
// +4 u32 id
// +8 u16 count fragments in the message
// +10 u16 size this fragment INCLUDING its 16-byte header
// +12 u16 index 0..count-1
// +14 u16 queue the client's dispatch queue (not the opcode)
//
// The walk is self-checking: the optional headers and the fragments must end exactly at
// 20 + header.size. A datagram that doesn't is counted as malformed and skipped whole,
// so a wrong guess about an optional header shows up as a counter, never as garbage.
// ============================================================================
namespace RynthCore.Engine.Net;
/// <summary>Packet header flag bits the reader needs.</summary>
internal static class PacketFlags
{
public const uint Retransmission = 0x00000001;
public const uint EncryptedChecksum = 0x00000002;
public const uint BlobFragments = 0x00000004;
public const uint ServerSwitch = 0x00000100; // 8 bytes
public const uint LogonServerAddr = 0x00000200; // size unknown here: skip the datagram
public const uint EmptyHeader1 = 0x00000400; // 0 bytes
public const uint Referral = 0x00000800; // size unknown here: skip the datagram
public const uint RequestRetransmit = 0x00001000; // u32 count + count * u32
public const uint RejectRetransmit = 0x00002000; // u32 count + count * u32
public const uint AckSequence = 0x00004000; // 4 bytes
public const uint Disconnect = 0x00008000; // 0 bytes
public const uint LoginRequest = 0x00010000; // client to server only: skip
public const uint WorldLoginRequest = 0x00020000; // 8 bytes
public const uint ConnectRequest = 0x00040000; // 32 bytes; starts a new session
public const uint ConnectResponse = 0x00080000; // 8 bytes
public const uint NetError = 0x00100000; // 8 bytes
public const uint NetErrorDisconnect = 0x00200000; // 8 bytes
public const uint CICMDCommand = 0x00400000; // 8 bytes
public const uint TimeSync = 0x01000000; // 8 bytes
public const uint EchoRequest = 0x02000000; // 4 bytes
public const uint EchoResponse = 0x04000000; // 8 bytes
public const uint Flow = 0x08000000; // 6 bytes
/// <summary>Flags whose optional header this reader can't size; a fragment datagram carrying one is skipped.</summary>
public const uint Unsized = LogonServerAddr | Referral | LoginRequest | 0x00800000u | 0xF0000000u | 0x000000F8u;
}
internal enum PacketWalk : byte
{
/// <summary>Fragments located.</summary>
Ok,
/// <summary>No BlobFragments flag: nothing to reassemble (acks, pings, time sync...).</summary>
NoFragments,
/// <summary>Shorter than a header, or the sizes don't add up.</summary>
Malformed,
/// <summary>Carries an optional header this reader can't size.</summary>
UnknownOptional,
}
internal static unsafe class AcPacketWire
{
public const int HeaderSize = 20;
public const int FragmentHeaderSize = 16;
public static uint ReadU32(byte* p) => (uint)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24));
public static ushort ReadU16(byte* p) => (ushort)(p[0] | (p[1] << 8));
/// <summary>The datagram's flags, or 0 when it is shorter than a header.</summary>
public static uint Flags(byte* data, int length) => length >= HeaderSize ? ReadU32(data + 4) : 0;
/// <summary>
/// Finds the fragment area of one datagram: [fragStart, fragEnd). Never reads past
/// <paramref name="length"/>. Ok only when the optional headers sized and fragEnd is
/// exactly where the header's size says the datagram ends.
/// </summary>
public static PacketWalk LocateFragments(byte* data, int length, out int fragStart, out int fragEnd)
{
fragStart = fragEnd = 0;
if (data == null || length < HeaderSize)
return PacketWalk.Malformed;
uint flags = ReadU32(data + 4);
if ((flags & PacketFlags.BlobFragments) == 0)
return PacketWalk.NoFragments;
if ((flags & PacketFlags.Unsized) != 0)
return PacketWalk.UnknownOptional;
int end = HeaderSize + ReadU16(data + 16);
if (end > length)
return PacketWalk.Malformed;
int pos = HeaderSize;
if ((flags & PacketFlags.ServerSwitch) != 0) pos += 8;
if ((flags & PacketFlags.RequestRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
if ((flags & PacketFlags.RejectRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed;
if ((flags & PacketFlags.AckSequence) != 0) pos += 4;
if ((flags & PacketFlags.WorldLoginRequest) != 0) pos += 8;
if ((flags & PacketFlags.ConnectRequest) != 0) pos += 32;
if ((flags & PacketFlags.ConnectResponse) != 0) pos += 8;
if ((flags & PacketFlags.NetError) != 0) pos += 8;
if ((flags & PacketFlags.NetErrorDisconnect) != 0) pos += 8;
if ((flags & PacketFlags.CICMDCommand) != 0) pos += 8;
if ((flags & PacketFlags.TimeSync) != 0) pos += 8;
if ((flags & PacketFlags.EchoRequest) != 0) pos += 4;
if ((flags & PacketFlags.EchoResponse) != 0) pos += 8;
if ((flags & PacketFlags.Flow) != 0) pos += 6;
if (pos > end)
return PacketWalk.Malformed;
// The fragments must tile [pos, end) exactly.
int walk = pos;
int guard = 0;
while (walk < end)
{
if (walk + FragmentHeaderSize > end || ++guard > 64)
return PacketWalk.Malformed;
int size = ReadU16(data + walk + 10);
if (size < FragmentHeaderSize || walk + size > end)
return PacketWalk.Malformed;
walk += size;
}
if (walk == pos)
return PacketWalk.Malformed; // the flag promised fragments
fragStart = pos;
fragEnd = end;
return PacketWalk.Ok;
}
private static bool SkipU32List(byte* data, int end, ref int pos)
{
if (pos + 4 > end) return false;
uint n = ReadU32(data + pos);
if (n > 256) return false;
pos += 4 + (int)n * 4;
return pos <= end;
}
}

View file

@ -0,0 +1,307 @@
// ============================================================================
// RynthCore.Engine - Net/FragmentReassembler.cs
// Turns server-to-client datagrams into whole messages (u32 opcode + body).
//
// Runs on the consumer side of PacketRing (the plugin pump), never in the RecvFrom
// detour. Read-only: it sees copies of the client's datagrams.
//
// Bounded:
// - at most MaxPartials messages in progress; the least recently touched one is
// dropped when another starts, and any untouched for StaleMs is dropped (either
// way its sequence counts as done, so its late fragments are ignored);
// - at most MaxFragments fragments (MaxFragments * FragmentStride bytes) per message;
// a bigger one is dropped and its sequence remembered as done;
// - a window of the last DoneWindow completed sequences rejects retransmitted copies.
// Slot buffers are pinned arrays reused from one message to the next, so a steady
// stream allocates nothing; a one-fragment message is handed over straight from the
// datagram without a copy.
//
// Messages are delivered in the order they complete (a long message completes after
// shorter ones that started later). The client applies them in its own order.
//
// Pure code; compiled into the NetMessageTests replay runner.
// ============================================================================
using System;
namespace RynthCore.Engine.Net;
/// <summary>Receives each completed message. <paramref name="message"/> starts with the u32 opcode and is valid only during the call.</summary>
internal unsafe interface IServerMessageSink
{
void OnServerMessage(uint fragmentSequence, byte* message, int length);
}
internal sealed unsafe class FragmentReassembler
{
public const int FragmentStride = 512; // > the largest fragment body a 484-byte datagram can carry
public const int MaxFragments = 256; // 256 * 448 = ~112 KB of message
public const int MaxPartials = 16;
public const int DoneWindow = 4096; // power of two
public const long StaleMs = 30_000;
private sealed class Slot
{
public bool InUse;
public uint Sequence;
public int Count;
public int Received;
public int Bytes;
public long TouchedMs;
public byte[]? Buffer; // pinned; Count * FragmentStride
public readonly ushort[] Lengths = new ushort[MaxFragments];
public readonly ulong[] Have = new ulong[MaxFragments / 64];
}
private readonly Slot[] _slots = new Slot[MaxPartials];
private readonly ulong[] _done = new ulong[DoneWindow / 64];
private uint _maxDone;
private bool _anyDone;
// ── counters (read by /rc netmsg; written on the consumer thread only) ──
public long Packets, PacketsNoFragments, PacketsMalformed, PacketsUnknownOptional;
public long Fragments, Messages, MultiFragmentMessages, DuplicateFragments, DuplicateMessages;
public long BadFragments, Oversized, EvictedStale, EvictedFull, SessionResets;
public uint LastUnknownFlags;
public FragmentReassembler()
{
for (int i = 0; i < _slots.Length; i++)
_slots[i] = new Slot();
}
public int PartialCount
{
get
{
int n = 0;
foreach (Slot s in _slots) if (s.InUse) n++;
return n;
}
}
/// <summary>Forget everything in progress and the done window (a new session, or the stream switched on).</summary>
public void Reset()
{
foreach (Slot s in _slots)
s.InUse = false;
Array.Clear(_done);
_maxDone = 0;
_anyDone = false;
}
/// <summary>One received datagram. <paramref name="nowMs"/> is any monotonic millisecond clock.</summary>
public void ProcessDatagram(byte* data, int length, long nowMs, IServerMessageSink sink)
{
Packets++;
uint flags = AcPacketWire.Flags(data, length);
if ((flags & PacketFlags.ConnectRequest) != 0)
{
// The server's half of a new connection: fragment sequences start over.
Reset();
SessionResets++;
}
PacketWalk walk = AcPacketWire.LocateFragments(data, length, out int pos, out int end);
switch (walk)
{
case PacketWalk.NoFragments: PacketsNoFragments++; return;
case PacketWalk.Malformed: PacketsMalformed++; return;
case PacketWalk.UnknownOptional: PacketsUnknownOptional++; LastUnknownFlags = flags; return;
}
while (pos < end)
{
byte* f = data + pos;
int size = AcPacketWire.ReadU16(f + 10);
Fragments++;
Fragment(AcPacketWire.ReadU32(f), AcPacketWire.ReadU16(f + 8), AcPacketWire.ReadU16(f + 12),
f + AcPacketWire.FragmentHeaderSize, size - AcPacketWire.FragmentHeaderSize, nowMs, sink);
pos += size;
}
EvictStale(nowMs);
}
private void Fragment(uint seq, int count, int index, byte* body, int bodyLen, long nowMs, IServerMessageSink sink)
{
if (count == 0 || index >= count)
{
BadFragments++;
return;
}
if (IsDone(seq))
{
DuplicateFragments++;
if (count == 1) DuplicateMessages++;
return;
}
if (count == 1)
{
if (bodyLen < 4)
{
BadFragments++;
MarkDone(seq);
return;
}
MarkDone(seq);
Messages++;
sink.OnServerMessage(seq, body, bodyLen);
return;
}
if (count > MaxFragments || bodyLen > FragmentStride)
{
Oversized++;
DropSequence(seq);
return;
}
Slot? slot = FindSlot(seq) ?? StartSlot(seq, count, nowMs);
if (slot.Count != count)
{
BadFragments++;
return;
}
int word = index >> 6;
ulong bit = 1UL << (index & 63);
if ((slot.Have[word] & bit) != 0)
{
DuplicateFragments++;
return;
}
slot.Have[word] |= bit;
slot.Lengths[index] = (ushort)bodyLen;
slot.Received++;
slot.Bytes += bodyLen;
slot.TouchedMs = nowMs;
fixed (byte* dst = slot.Buffer)
Buffer.MemoryCopy(body, dst + index * FragmentStride, bodyLen, bodyLen);
if (slot.Received < slot.Count)
return;
// Complete: pack the fragments together in place (fragment i moves down, never up).
fixed (byte* buf = slot.Buffer)
{
int at = 0;
for (int i = 0; i < slot.Count; i++)
{
int len = slot.Lengths[i];
if (at != i * FragmentStride)
Buffer.MemoryCopy(buf + i * FragmentStride, buf + at, len, len);
at += len;
}
slot.InUse = false;
MarkDone(seq);
if (at < 4)
{
BadFragments++;
return;
}
Messages++;
MultiFragmentMessages++;
sink.OnServerMessage(seq, buf, at);
}
}
private Slot? FindSlot(uint seq)
{
foreach (Slot s in _slots)
if (s.InUse && s.Sequence == seq)
return s;
return null;
}
private Slot StartSlot(uint seq, int count, long nowMs)
{
Slot? pick = null;
foreach (Slot s in _slots)
{
if (!s.InUse) { pick = s; break; }
}
if (pick == null)
{
// All busy: drop the one touched longest ago.
pick = _slots[0];
foreach (Slot s in _slots)
if (s.TouchedMs < pick.TouchedMs) pick = s;
EvictedFull++;
MarkDone(pick.Sequence); // its stragglers are ignored, not given a new slot
}
int need = count * FragmentStride;
if (pick.Buffer == null || pick.Buffer.Length < need)
{
// Rounded up so a slot settles at the size it needs; at most MaxFragments * 512.
int cap = 4096;
while (cap < need) cap <<= 1;
pick.Buffer = GC.AllocateUninitializedArray<byte>(cap, pinned: true);
}
pick.InUse = true;
pick.Sequence = seq;
pick.Count = count;
pick.Received = 0;
pick.Bytes = 0;
pick.TouchedMs = nowMs;
Array.Clear(pick.Have);
return pick;
}
private void DropSequence(uint seq)
{
Slot? s = FindSlot(seq);
if (s != null) s.InUse = false;
MarkDone(seq);
}
private void EvictStale(long nowMs)
{
foreach (Slot s in _slots)
{
if (s.InUse && nowMs - s.TouchedMs > StaleMs)
{
s.InUse = false;
MarkDone(s.Sequence); // a straggler can't start it again
EvictedStale++;
}
}
}
// ── done window: the last DoneWindow sequences, by bit ──────────────────
private bool IsDone(uint seq)
{
if (!_anyDone) return false;
if (seq > _maxDone) return false;
if (_maxDone - seq >= DoneWindow) return true; // too old to still be in flight
return (_done[(seq & (DoneWindow - 1)) >> 6] & (1UL << (int)(seq & 63))) != 0;
}
private void MarkDone(uint seq)
{
if (!_anyDone)
{
_anyDone = true;
_maxDone = seq;
}
else if (seq > _maxDone)
{
// Clear the bits of the sequences the window slides over.
uint advance = seq - _maxDone;
if (advance >= DoneWindow)
Array.Clear(_done);
else
for (uint s = _maxDone + 1; s != seq; s++)
_done[(s & (DoneWindow - 1)) >> 6] &= ~(1UL << (int)(s & 63));
_maxDone = seq;
}
else if (_maxDone - seq >= DoneWindow)
{
return;
}
_done[(seq & (DoneWindow - 1)) >> 6] |= 1UL << (int)(seq & 63);
}
}

View file

@ -0,0 +1,139 @@
// ============================================================================
// RynthCore.Engine - Net/PacketRing.cs
// Hand-off of received datagrams from the RecvFrom detour to the plugin pump.
//
// The producer (the detour) only copies the datagram: no allocation, no lock, no
// wait. A full ring, or a second producer arriving while one is writing, drops the
// datagram and counts it; the client's own copy is never touched either way. The
// consumer (the single TickAll driver) reads records in place and releases them.
//
// Records are 8-byte aligned: [i32 length][u32 stamp ms][bytes][pad]. A length of -1
// means "the rest of the buffer is unused, continue at 0". Capacity is a power of two
// and a multiple of 8, so a wrap marker always fits.
//
// Pure code (native memory, no engine state); compiled into the NetMessageTests runner.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Net;
internal sealed unsafe class PacketRing
{
private const int RecordHeader = 8;
private const int WrapMarker = -1;
private readonly byte* _buf;
private readonly int _capacity;
private readonly int _mask;
// Byte counters that wrap (int, so reads and writes are single instructions on x86);
// only their difference and their low bits are used.
private int _head; // bytes written (producer)
private int _tail; // bytes released (consumer)
private int _writing; // producer claim
/// <summary>Largest datagram accepted; anything longer is dropped (AC's are under 500 bytes).</summary>
public const int MaxDatagram = 2048;
public long Written;
public long DroppedFull;
public long DroppedContended;
public long DroppedTooLong;
/// <summary>The ring's memory is never freed: the detour may still be running at teardown.</summary>
/// <param name="startCounter">Where the wrapping byte counters start (tests start them near int.MaxValue).</param>
public PacketRing(int capacityPow2, int startCounter = 0)
{
_head = _tail = startCounter & ~7;
if (capacityPow2 < 4096 || (capacityPow2 & (capacityPow2 - 1)) != 0)
throw new ArgumentOutOfRangeException(nameof(capacityPow2));
_capacity = capacityPow2;
_mask = capacityPow2 - 1;
_buf = (byte*)NativeMemory.AllocZeroed((nuint)capacityPow2);
}
public int Capacity => _capacity;
/// <summary>Bytes in use (approximate when read from another thread).</summary>
public int Used => unchecked(Volatile.Read(ref _head) - Volatile.Read(ref _tail));
/// <summary>Producer: copy one datagram in. Never blocks; false = dropped (counted).</summary>
public bool TryWrite(byte* data, int length, uint stampMs)
{
if (length <= 0 || length > MaxDatagram)
{
DroppedTooLong++;
return false;
}
if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0)
{
Interlocked.Increment(ref DroppedContended);
return false;
}
try
{
int need = RecordHeader + ((length + 7) & ~7);
int head = _head;
int used = unchecked(head - Volatile.Read(ref _tail));
int pos = head & _mask;
int toEnd = _capacity - pos;
int skip = need > toEnd ? toEnd : 0;
if (used + skip + need > _capacity)
{
DroppedFull++;
return false;
}
if (skip != 0)
{
*(int*)(_buf + pos) = WrapMarker;
pos = 0;
}
*(int*)(_buf + pos) = length;
*(uint*)(_buf + pos + 4) = stampMs;
Buffer.MemoryCopy(data, _buf + pos + RecordHeader, length, length);
Written++;
Volatile.Write(ref _head, unchecked(head + skip + need)); // publish after the bytes
return true;
}
finally
{
Volatile.Write(ref _writing, 0);
}
}
/// <summary>
/// Consumer: the oldest record, in place. Call <see cref="Release"/> with the returned
/// token when done with it (the bytes stay valid until then).
/// </summary>
public bool TryPeek(out byte* data, out int length, out uint stampMs, out int releaseTo)
{
data = null;
length = 0;
stampMs = 0;
releaseTo = 0;
int tail = _tail;
int head = Volatile.Read(ref _head);
if (tail == head)
return false;
int pos = tail & _mask;
int len = *(int*)(_buf + pos);
if (len == WrapMarker)
{
tail = unchecked(tail + _capacity - pos);
pos = 0;
len = *(int*)_buf;
}
data = _buf + pos + RecordHeader;
length = len;
stampMs = *(uint*)(_buf + pos + 4);
releaseTo = unchecked(tail + RecordHeader + ((len + 7) & ~7));
return true;
}
public void Release(int releaseTo) => Volatile.Write(ref _tail, releaseTo);
/// <summary>Consumer: drop everything queued (used when the stream is switched on again).</summary>
public void Clear() => Volatile.Write(ref _tail, Volatile.Read(ref _head));
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthCore.Engine - Net/ServerMessageInterest.cs
// Which server messages one plugin asked for (PluginContract.SetServerMessageInterestFn).
//
// Opcodes and game event types are 16-bit on the wire in practice; each set is a
// 65536-bit map (8 KB), so a check is one load. Special entries:
// opcode 0xFFFFFFFF every message;
// opcode 0xF7B0 every game event (otherwise only the listed event types).
// Pure code; compiled into the NetMessageTests runner.
// ============================================================================
using System;
namespace RynthCore.Engine.Net;
internal sealed class ServerMessageInterest
{
public const uint GameEventOpcode = 0xF7B0;
public const uint AllMessages = 0xFFFFFFFF;
public const int MaxEntries = 4096;
private readonly ulong[] _opcodes = new ulong[65536 / 64];
private readonly ulong[] _events = new ulong[65536 / 64];
public bool All { get; private set; }
public bool AllGameEvents { get; private set; }
public int OpcodeCount { get; private set; }
public int EventCount { get; private set; }
public bool IsEmpty => !All && OpcodeCount == 0 && EventCount == 0;
/// <summary>Replaces the set. False (set left empty) for an entry out of range or too many entries.</summary>
public unsafe bool Set(uint* opcodes, int opcodeCount, uint* events, int eventCount)
{
Clear();
if (opcodeCount < 0 || eventCount < 0 || opcodeCount > MaxEntries || eventCount > MaxEntries)
return false;
if ((opcodeCount > 0 && opcodes == null) || (eventCount > 0 && events == null))
return false;
for (int i = 0; i < opcodeCount; i++)
{
uint op = opcodes[i];
if (op == AllMessages) { All = true; continue; }
if (op > 0xFFFF) { Clear(); return false; }
if (op == GameEventOpcode) AllGameEvents = true;
if (Add(_opcodes, op)) OpcodeCount++;
}
for (int i = 0; i < eventCount; i++)
{
uint ev = events[i];
if (ev > 0xFFFF) { Clear(); return false; }
if (Add(_events, ev)) EventCount++;
}
return true;
}
public void Clear()
{
Array.Clear(_opcodes);
Array.Clear(_events);
All = AllGameEvents = false;
OpcodeCount = EventCount = 0;
}
/// <summary><paramref name="eventType"/> is only looked at for opcode 0xF7B0.</summary>
public bool Wants(uint opcode, uint eventType)
{
if (All) return true;
if (opcode > 0xFFFF) return false;
if (opcode == GameEventOpcode)
return AllGameEvents || (eventType <= 0xFFFF && Has(_events, eventType));
return Has(_opcodes, opcode);
}
private static bool Has(ulong[] map, uint v) => (map[v >> 6] & (1UL << (int)(v & 63))) != 0;
private static bool Add(ulong[] map, uint v)
{
ulong bit = 1UL << (int)(v & 63);
if ((map[v >> 6] & bit) != 0) return false;
map[v >> 6] |= bit;
return true;
}
}

View file

@ -0,0 +1,336 @@
// ============================================================================
// RynthCore.Engine - Net/ServerMessageStream.cs
// The reassembled server-message stream for plugins (API v78).
//
// RecvFrom detour (RawPacketHooks) plugin pump (PluginManager.ProcessPendingActions)
// OnDatagram: one volatile check; while Pump: drains the ring through the
// capturing, copies fragment datagrams -> FragmentReassembler; each whole message goes
// into PacketRing (no alloc, no lock, to the plugins that asked for it (and to the
// never waits; full = dropped + counted) /rc netmsg log tap and capture file).
//
// Strictly read-only: the detour copies the client's bytes after the real recvfrom
// returned them; it never alters, delays or drops anything the client gets.
//
// Capturing runs only while it is wanted: a plugin with a non-empty interest, or
// /rc netmsg log / capture. engine.json "ServerMessageStream": false (or /rc netmsg off)
// keeps it off whatever is wanted, and the detour is then exactly what it was before.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using RynthCore.Engine.Plugins;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Engine.Net;
internal static unsafe class ServerMessageStream
{
private const int RingBytes = 512 * 1024;
private const int MaxPacketsPerPump = 8192;
private const long MaxCaptureBytes = 32L * 1024 * 1024;
private const int MaxLogLinesPerKind = 5;
private const int MaxLogLines = 300;
private static PacketRing? _ring; // created on first use, never freed (see PacketRing)
private static readonly FragmentReassembler Reassembler = new();
private static readonly Sink MessageSink = new();
private static volatile bool _capturing;
private static bool _sessionOff;
private static bool _pluginsWant;
// Delivery counters (pump thread).
private static long _delivered, _dispatchedToPlugins;
private static long _pumpTicksTotal, _pumpTicksMax, _pumps;
// /rc netmsg log: check the SDK parsers against the live server.
private static bool _logOn;
private static int _logLines;
private static readonly Dictionary<string, KindStats> Kinds = new();
private static readonly Dictionary<uint, long> Opcodes = new();
private static readonly object LogLock = new(); // Kinds/Opcodes: pump writes, chat commands read
// /rc netmsg capture: raw fragment datagrams for tools\NetMessageTests.
private static volatile FileStream? _capture; // opened by the command, written and closed by the pump
private static volatile bool _captureStopRequested;
private static string _capturePath = "";
private static long _captureBytes;
private sealed class KindStats
{
public long Ok, Failed, Leftover;
public int Logged;
}
/// <summary>True while the detour copies datagrams.</summary>
public static bool Capturing => _capturing;
// ── receive hook side ───────────────────────────────────────────────────
/// <summary>Called by the RecvFrom detour after the real recvfrom, with the bytes it returned.</summary>
public static void OnDatagram(byte* data, int length)
{
if (!_capturing)
return;
PacketRing? ring = _ring;
if (ring == null || length < AcPacketWire.HeaderSize)
return;
uint flags = AcPacketWire.ReadU32(data + 4);
if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) == 0)
return; // acks, pings, time sync: nothing to reassemble
ring.TryWrite(data, length, (uint)Environment.TickCount);
}
// ── pump side ───────────────────────────────────────────────────────────
/// <summary>
/// Once per ProcessPendingActions (the single TickAll driver). <paramref name="pluginsWant"/>:
/// some initialized plugin has a non-empty interest.
/// </summary>
public static void Pump(bool pluginsWant)
{
_pluginsWant = pluginsWant;
if (_captureStopRequested)
{
_captureStopRequested = false;
StopCapture("stopped");
}
bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || _logOn || _capture != null);
if (want != _capturing)
{
if (want)
{
_ring ??= new PacketRing(RingBytes);
_ring.Clear();
Reassembler.Reset();
}
_capturing = want;
RynthLog.Compat($"ServerMessageStream: capture {(want ? "on" : "off")} (plugins={pluginsWant} log={_logOn} file={_capture != null})");
}
PacketRing? ring = _ring;
if (ring == null)
return;
if (!_capturing)
{
if (ring.Used != 0) ring.Clear();
return;
}
long start = System.Diagnostics.Stopwatch.GetTimestamp();
long now = Environment.TickCount64;
int n = 0;
while (n < MaxPacketsPerPump && ring.TryPeek(out byte* data, out int len, out uint stamp, out int releaseTo))
{
n++;
try
{
if (_capture != null) WriteCapture(data, len, stamp);
Reassembler.ProcessDatagram(data, len, now, MessageSink);
}
catch (Exception ex)
{
RynthLog.Compat($"ServerMessageStream: datagram failed - {ex.GetType().Name}: {ex.Message}");
}
ring.Release(releaseTo);
}
if (n > 0)
{
long ticks = System.Diagnostics.Stopwatch.GetTimestamp() - start;
_pumps++;
_pumpTicksTotal += ticks;
if (ticks > _pumpTicksMax) _pumpTicksMax = ticks;
}
}
private sealed class Sink : IServerMessageSink
{
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
{
_delivered++;
uint opcode = AcPacketWire.ReadU32(message);
uint eventType = opcode == ServerMessage.GameEventOpcode && length >= 16 ? AcPacketWire.ReadU32(message + 12) : 0;
if (_logOn)
{
try { LogTap(opcode, eventType, message, length); }
catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: log tap failed - {ex.GetType().Name}: {ex.Message}"); }
}
if (_pluginsWant)
_dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4);
}
}
// ── /rc netmsg ──────────────────────────────────────────────────────────
public static string[] HandleCommand(string args)
{
string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status";
string arg = parts.Length > 1 ? parts[1].ToLowerInvariant() : "";
switch (verb)
{
case "on":
_sessionOff = false;
return new[] { EngineSettings.ServerMessageStream
? "Server message stream allowed for this session (it runs while a plugin, the log or a capture wants it)."
: "engine.json has \"ServerMessageStream\": false - the stream stays off. Remove it (or set true) and restart." };
case "off":
_sessionOff = true;
return new[] { "Server message stream off for this session (plugins get nothing until /rc netmsg on)." };
case "log":
if (arg is "on" or "")
{
lock (LogLock) { _logLines = 0; Kinds.Clear(); Opcodes.Clear(); }
_logOn = true;
return new[] { "Server message log on: parsed messages go to the RynthCore log (NetMsg:), counts to /rc netmsg." };
}
if (arg == "off") { _logOn = false; return new[] { "Server message log off." }; }
return new[] { "Usage: /rc netmsg log on|off" };
case "capture":
if (arg is "on" or "") return new[] { StartCapture() };
if (arg == "off")
{
if (_capture == null) return new[] { "Not capturing." };
_captureStopRequested = true; // the pump closes it after its current write
return new[] { $"Capture stopping: {_capturePath}." };
}
return new[] { "Usage: /rc netmsg capture on|off" };
case "status":
return StatusLines();
default:
return new[] { "Usage: /rc netmsg [status|on|off|log on|off|capture on|off]" };
}
}
public static string[] StatusLines()
{
var r = Reassembler;
var lines = new List<string>
{
$"Server messages: setting {(EngineSettings.ServerMessageStream ? "on" : "OFF (engine.json)")}, session {(_sessionOff ? "off" : "on")}, " +
$"capturing {(_capturing ? "yes" : "no")}, hook {(Compatibility.RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}; " +
$"plugins {PluginManager.ServerMessageSubscriberCount()} subscribed",
};
if (_ring != null)
lines.Add($"Ring: {_ring.Written} datagrams copied, dropped {_ring.DroppedFull} full / {_ring.DroppedContended} contended / {_ring.DroppedTooLong} too long, {_ring.Used / 1024} KB queued");
lines.Add($"Reassembly: {r.Packets} packets ({r.PacketsNoFragments} no fragments, {r.PacketsMalformed} malformed, {r.PacketsUnknownOptional} unknown header" +
(r.PacketsUnknownOptional > 0 ? $" last flags 0x{r.LastUnknownFlags:X8}" : "") + $"), {r.Fragments} fragments, " +
$"{r.Messages} messages ({r.MultiFragmentMessages} multi-fragment), dup {r.DuplicateFragments} fragments / {r.DuplicateMessages} messages, " +
$"bad {r.BadFragments}, oversized {r.Oversized}, evicted {r.EvictedStale} stale / {r.EvictedFull} full, {r.PartialCount} partial, {r.SessionResets} session resets");
double tickUs = 1_000_000.0 / System.Diagnostics.Stopwatch.Frequency;
lines.Add($"Delivered {_delivered}, plugin calls {_dispatchedToPlugins}; drain (incl. plugin calls) avg {(_pumps > 0 ? _pumpTicksTotal * tickUs / _pumps : 0):0.0} us, max {_pumpTicksMax * tickUs:0} us over {_pumps} drains");
lock (LogLock)
if (_logOn || Kinds.Count > 0)
{
string kinds = string.Join(", ", Kinds.OrderBy(k => k.Key).Select(k => $"{k.Key} {k.Value.Ok} ok" +
(k.Value.Failed > 0 ? $"/{k.Value.Failed} FAILED" : "") + (k.Value.Leftover > 0 ? $"/{k.Value.Leftover} leftover" : "")));
lines.Add($"Parsed ({(_logOn ? "log on" : "log off")}): {(kinds.Length > 0 ? kinds : "none yet")}");
string top = string.Join(" ", Opcodes.OrderByDescending(o => o.Value).Take(12).Select(o => $"{FormatKey(o.Key)}x{o.Value}"));
if (top.Length > 0) lines.Add($"Top opcodes: {top}");
}
if (_capture != null)
lines.Add($"Capturing to {_capturePath} ({_captureBytes / 1024} KB)");
return lines.ToArray();
}
private static string FormatKey(uint key) => key >= 0x10000 ? $"F7B0/{key & 0xFFFF:X4}" : $"{key:X4}";
// ── log tap ─────────────────────────────────────────────────────────────
private static void LogTap(uint opcode, uint eventType, byte* message, int length)
{
uint key = opcode == ServerMessage.GameEventOpcode ? 0x10000u | (eventType & 0xFFFF) : opcode & 0xFFFF;
var msg = new ServerMessage(opcode, new ReadOnlySpan<byte>(message + 4, length - 4));
NetMessageInfo info = NetMessages.Inspect(msg);
bool interesting = !info.Parsed || info.Leftover != 0;
bool log;
lock (LogLock)
{
Opcodes[key] = Opcodes.TryGetValue(key, out long c) ? c + 1 : 1;
if (!info.Known)
return;
if (!Kinds.TryGetValue(info.Kind, out KindStats? k))
Kinds[info.Kind] = k = new KindStats();
if (info.Parsed) k.Ok++; else k.Failed++;
if (info.Parsed && info.Leftover != 0) k.Leftover++;
log = _logLines < MaxLogLines && (k.Logged < MaxLogLinesPerKind || interesting);
if (log)
{
_logLines++;
k.Logged++;
}
}
if (log)
{
string hex = interesting ? " bytes=" + Convert.ToHexString(new ReadOnlySpan<byte>(message, Math.Min(length, 96))) : "";
RynthLog.Compat($"NetMsg: {info.Kind} len={length} {(info.Parsed ? "ok" : "FAILED")}" +
(info.Leftover != 0 ? $" leftover={info.Leftover}" : "") + $" {info.Summary}{hex}");
}
}
// ── capture file ────────────────────────────────────────────────────────
// Format "RNC1": the 4 magic bytes, then per datagram [u32 stamp ms][u16 length][bytes].
private static string StartCapture()
{
if (_capture != null)
return $"Already capturing to {_capturePath}.";
if (!EngineSettings.ServerMessageStream || _sessionOff)
return "The server message stream is off; /rc netmsg on first (engine.json must allow it).";
try
{
LogPaths.EnsureLogDirectory();
_capturePath = Path.Combine(LogPaths.LogDirectory, $"netcapture-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}.rnc");
_capture = new FileStream(_capturePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 64 * 1024);
_capture.Write("RNC1"u8);
_captureBytes = 4;
return $"Capturing server datagrams to {_capturePath} (stops at {MaxCaptureBytes / (1024 * 1024)} MB; holds chat text, keep it local).";
}
catch (Exception ex)
{
_capture = null;
return $"Capture failed: {ex.Message}";
}
}
private static string StopCapture(string why)
{
if (_capture == null)
return "Not capturing.";
try { _capture.Dispose(); } catch { }
_capture = null;
string msg = $"Capture {why}: {_capturePath} ({_captureBytes / 1024} KB).";
RynthLog.Compat("ServerMessageStream: " + msg);
return msg;
}
private static void WriteCapture(byte* data, int len, uint stamp)
{
FileStream? f = _capture;
if (f == null) return;
Span<byte> head = stackalloc byte[6];
System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(head, stamp);
System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(head.Slice(4), (ushort)len);
try
{
f.Write(head);
f.Write(new ReadOnlySpan<byte>(data, len));
_captureBytes += 6 + len;
}
catch (Exception ex)
{
StopCapture($"failed ({ex.Message})");
return;
}
if (_captureBytes >= MaxCaptureBytes)
StopCapture("reached its size cap");
}
/// <summary>Engine shutdown: close a capture file. The ring stays allocated (see PacketRing).</summary>
public static void Shutdown()
{
_capturing = false;
if (_capture != null) StopCapture("closed at shutdown");
}
}

View file

@ -31,6 +31,9 @@ internal static class EngineSettings
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
// "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name.
private static readonly HashSet<string> _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase);
private static bool _serverMessageStream = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -252,6 +255,39 @@ internal static class EngineSettings
}
}
/// <summary>"DisabledUiHooks" in engine.json: an array of UI hook names
/// (Compatibility/UiHookRegistry: UseNewMode, ClientCleanup, StartTooltip, ResetTooltip,
/// CheckTooltip, StartDragandDrop, CatchDroppedItem). A listed hook is not installed at
/// the next start. Missing = every hook on. /rc hooks on|off &lt;name&gt; edits it.</summary>
public static bool IsUiHookEnabled(string name)
{
EnsureLoaded();
return !_disabledUiHooks.Contains(name);
}
/// <summary>Switches a UI hook on or off for the next start, and saves engine.json.</summary>
public static void SetUiHookEnabled(string name, bool enabled)
{
EnsureLoaded();
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
if (changed)
Save();
}
/// <summary>"ServerMessageStream" in engine.json (default true): the kill switch for the
/// reassembled server-message stream (Net/ServerMessageStream.cs, plugin API v78). Even when
/// true, nothing is copied off the receive hook until a plugin asks for messages (or
/// /rc netmsg log|capture is on). false = the RecvFrom detour does exactly what it did
/// before the stream existed; /rc netmsg on can't override it.</summary>
public static bool ServerMessageStream
{
get
{
EnsureLoaded();
return _serverMessageStream;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -374,11 +410,25 @@ internal static class EngineSettings
(dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False))
_decalStandDown = dsdEl.GetBoolean();
if (doc.RootElement.TryGetProperty("ServerMessageStream", out var smsEl) &&
(smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False))
_serverMessageStream = smsEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
duhEl.ValueKind == JsonValueKind.Array)
{
foreach (var el in duhEl.EnumerateArray())
{
if (el.ValueKind == JsonValueKind.String && el.GetString() is { Length: > 0 } hookName)
_disabledUiHooks.Add(hookName.Trim());
}
}
}
catch (Exception ex)
{
@ -417,6 +467,15 @@ internal static class EngineSettings
w.WriteBoolean("DecalInGameImGui", false);
if (!_decalStandDown) // default true: leave the file as it was
w.WriteBoolean("DecalStandDown", false);
if (_disabledUiHooks.Count > 0) // default none: leave the file as it was
{
w.WriteStartArray("DisabledUiHooks");
foreach (string hookName in _disabledUiHooks)
w.WriteStringValue(hookName);
w.WriteEndArray();
}
if (!_serverMessageStream) // default true: leave the file as it was
w.WriteBoolean("ServerMessageStream", false);
w.WriteEndObject();
}
File.WriteAllBytes(SettingsPath, ms.ToArray());

View file

@ -55,6 +55,21 @@ internal sealed class LoadedPlugin
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
public bool UiExportsResolved { get; set; }
public IntPtr OnScreenChangedPtr { get; set; }
public IntPtr OnClientCleanupPtr { get; set; }
public IntPtr OnTooltipShowPtr { get; set; }
public IntPtr OnTooltipHidePtr { get; set; }
public IntPtr OnDragStartPtr { get; set; }
public IntPtr OnItemDroppedPtr { get; set; }
// ─── v78 server messages (resolved when the plugin calls SetServerMessageInterest) ──
/// <summary><c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c>, Cdecl.</summary>
public IntPtr OnServerMessagePtr { get; set; }
/// <summary>What the plugin asked for; null or empty = nothing.</summary>
public Net.ServerMessageInterest? ServerMessageInterest { get; set; }
// ─── Runtime state ───────────────────────────────────────────────
public bool Initialized { get; set; }
public bool LoginCompleteDispatched { get; set; }
@ -62,4 +77,12 @@ internal sealed class LoadedPlugin
public bool Failed { get; set; }
public string DisplayName { get; set; } = "";
public string VersionString { get; set; } = "";
/// <summary>
/// The manifest embedded in the DLL (read before loading it; see PluginManifestGate), or null
/// for a plugin without one. Set by PluginManager after PluginLoader loads the plugin.
/// </summary>
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
public string NotStartedReason { get; set; } = "";
}

View file

@ -11,6 +11,9 @@
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
// void RynthPluginTick() — per-frame logic (before render)
// void RynthPluginRender() — per-frame ImGui drawing
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn
// ============================================================================
using System;
@ -780,6 +783,156 @@ internal struct RynthCoreAPI
/// AC's main thread (queued in the action ring from other threads, ahead of anything queued
/// after it). Returns 1 if sent or queued. Requires API v76+.</summary>
public IntPtr CloseContainerFn;
/// <summary>v77: <c>int GetScreenMode(int* previousMode)</c>: the client's screen (UIFlow mode,
/// Compatibility/UiFlowHooks.cs): 0x10000001 intro, 0x10000002 disconnected, 0x10000008 the
/// world, 0x10000009 epilogue, 0x1000000A character select, 0x1000000B character creation;
/// 0 = not known yet. *previousMode (may be null) = the screen before. Any thread.
/// Requires API v77+.</summary>
public IntPtr GetScreenModeFn;
/// <summary>v77: <c>uint GetUiHookFlags(void)</c>: which UI hooks are live, so a plugin knows
/// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook,
/// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup,
/// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart,
/// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread.
/// Requires API v77+.</summary>
public IntPtr GetUiHookFlagsFn;
/// <summary>v78: <c>int SetServerMessageInterest(uint* opcodes, int opcodeCount, uint* gameEvents,
/// int eventCount)</c>: which reassembled server messages the calling plugin wants on its
/// <c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
/// data = the message after its u32 opcode, valid only during the call; for 0xF7B0 it starts
/// with object id, sequence, event type). Replaces the plugin's previous set; both counts 0 =
/// none. Opcodes are 16-bit; 0xF7B0 = every game event, 0xFFFFFFFF = every message;
/// gameEvents lists single event types. Read-only: the client's packets are never changed.
/// Call from the plugin's Init, Tick or an event (the engine finds the caller that way).
/// Returns 1 = streaming, 2 = accepted but the stream is off (engine.json
/// "ServerMessageStream": false or /rc netmsg off), 0 = the plugin has no
/// RynthPluginOnServerMessage export, -1 = caller unknown (another thread), -3 = bad
/// arguments. Requires API v78+.</summary>
public IntPtr SetServerMessageInterestFn;
/// <summary>v79: <c>int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries,
/// int maxEntries)</c>: what spending experience would do (Compatibility/TrainingApi.cs): the
/// unassigned XP, skill credits and level, and one entry per attribute (1..6), vital maximum
/// (1 health, 3 stamina, 5 mana) and portal-SkillTable skill with ranks, XP spent, base and
/// buffed value and the XP for +1 / +10 from the portal XpTable. Set info->Size to sizeof
/// before the call (info may be null; entries may be null to ask for the count). Returns the
/// number of entries there are (at most maxEntries written), 0 when there are no numbers yet
/// (not in the world, or the first read hasn't happened: it is asked for by this call and
/// comes within a couple of seconds). Asking keeps the numbers coming every 2 s for 5 s.
/// Any thread. Requires API v79+.</summary>
public IntPtr GetTrainingInfoFn;
/// <summary>v79: <c>int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)</c>:
/// spend unassigned XP like the character window's "+": kind 1 attribute (stype 1..6), 2 vital
/// (1 health, 3 stamina, 5 mana), 3 trained or specialized skill; ranks 1..100. The engine works
/// the XP out from the numbers GetTrainingInfo reports and sends it with the client's own
/// CM_Train sender (0x0045 / 0x0044 / 0x0046) on AC's main thread. expectedXp &gt; 0 must equal
/// that XP (the cost the user confirmed), else nothing is sent; 0 skips the comparison.
/// *xpSent (may be null) = the XP sent. Returns 1 sent or queued, 0 the senders aren't bound,
/// -1 not in the world, -2 bad arguments, -3 no numbers yet, -4 the numbers are over 3 s old
/// (a read was asked for: call again shortly), -5 the cost changed, -6 not enough XP, -7 not
/// raisable (top rank, untrained skill), -8 an earlier raise hasn't landed yet, -9 the send
/// failed. Any thread. Requires API v79+.</summary>
public IntPtr RaiseFn;
/// <summary>v79: <c>int TrainSkill(uint stype, int expectedCredits)</c>: train an untrained
/// skill with skill credits, as the skills window's train dialog does (0x0047, exactly the
/// portal SkillTable's TrainedCost; the server refuses anything else). expectedCredits &gt; 0
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
/// Requires API v79+.</summary>
public IntPtr TrainSkillFn;
}
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
internal static class TrainingInfoFlags
{
public const uint InWorld = 1u << 0;
/// <summary>The attribute, vital and skill raise senders are bound on this client.</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 shown up in the numbers yet.</summary>
public const uint Busy = 1u << 5;
}
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
internal static class TrainingEntryFlags
{
/// <summary>Can be raised with XP (an attribute, a vital, a trained or specialized skill below the top rank).</summary>
public const uint Raisable = 1u << 0;
public const uint AtTop = 1u << 1;
/// <summary>Skills: usable untrained (the SkillTable's min level 1).</summary>
public const uint UsableUntrained = 1u << 2;
/// <summary>Skills: untrained, and the SkillTable prices training it (TrainCredits).</summary>
public const uint Trainable = 1u << 3;
}
/// <summary>
/// v79 <c>GetTrainingInfo</c> header. Pack 4, 64 bytes; later versions only append.
/// Mirrored by RynthCore.PluginSdk (TrainingInfoNative in RynthCoreApiNative.cs).
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct TrainingInfoNative
{
/// <summary>In: the caller's sizeof. Out: bytes written.</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 (Stale).</summary>
public int StaleAfterMs;
public fixed uint Reserved[4];
}
/// <summary>
/// v79 <c>GetTrainingInfo</c> entry: one attribute, vital or skill. Pack 4, 64 bytes; later
/// versions only append. Mirrored by RynthCore.PluginSdk (TrainingEntryNative).
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct TrainingEntryNative
{
/// <summary>1 attribute, 2 vital, 3 skill.</summary>
public uint 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 = can't be trained from the client).</summary>
public int TrainCredits;
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
public uint Flags;
}
/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary>
@ -964,11 +1117,8 @@ internal unsafe struct VendorTradeStatusNative
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 76;
}
// PluginContractVersion (the current API version) lives in PluginContractVersion.cs, which
// the SDK and the launcher compile in too, so their copies can't drift from the engine's.
internal static class ClientActionHookFlags
{
@ -1077,6 +1227,17 @@ internal delegate void PluginTickDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginRenderDelegate();
// v77 callbacks (exports resolved by PluginManager.ResolveUiExports, not PluginLoader):
// void RynthPluginOnScreenChanged(int oldMode, int newMode) - UIFlow mode change (GetScreenModeFn values)
// void RynthPluginOnClientCleanup(void) - Client::Cleanup starting; no ticks after it
// void RynthPluginOnTooltipShow(uint objectId, uint spellId) - AC shows a tooltip (0/0: not an item or spell)
// void RynthPluginOnTooltipHide(void) - that tooltip is gone
// void RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId) - a drag out of AC's UI began
// void RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId) - AC caught a drop
// All cdecl, all on the plugin pump like the other events, except OnClientCleanup (see
// PluginManager.DispatchClientCleanup).
// ─── Log callback that plugins can call ─────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
@ -1485,3 +1646,21 @@ internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CloseContainerCallbackDelegate(uint containerId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetScreenModeCallbackDelegate(int* previousMode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate uint GetUiHookFlagsCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int SetServerMessageInterestCallbackDelegate(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetTrainingInfoCallbackDelegate(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);

View file

@ -0,0 +1,19 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginContractVersion.cs
// The plugin API's version: the number of the last table (RynthCoreAPI) layout.
//
// One file, compiled into three assemblies so they can't disagree:
// - the engine (this folder), which hands it to plugins in RynthCoreAPI.Version;
// - the SDK (RynthCore.PluginSdk), as RynthCoreHost.CurrentApiVersion;
// - the launcher (RynthCore.App.Avalonia), as the API of the engine it installed,
// to hold back feed plugins whose minEngineApi is newer.
// tools\PluginManifestTests also checks the SDK's table covers this version.
// ============================================================================
namespace RynthCore.Engine.Plugins;
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
internal static class PluginContractVersion
{
public const uint Current = 79;
}

View file

@ -0,0 +1,282 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginManager.UiHooks.cs
//
// API v77 (2026-10-05): the plugin side of Compatibility/UiFlowHooks and
// Compatibility/UiElementHooks.
//
// Callbacks (optional plugin exports, cdecl; looked up here on first use, not by
// PluginLoader):
// RynthPluginOnScreenChanged(int oldMode, int newMode)
// RynthPluginOnClientCleanup()
// RynthPluginOnTooltipShow(uint objectId, uint spellId)
// RynthPluginOnTooltipHide()
// RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId)
// RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId)
// The hooks queue them from AC's main thread; ProcessPendingActions delivers them
// on the plugin pump in the order they happened (one queue), like every other
// event. OnClientCleanup is the exception: it must arrive while AC's UI still
// stands, so the Client::Cleanup detour (AC's main thread) waits, bounded, for the
// pump to deliver it, and delivers it itself (under the pump's frame guard) if the
// pump doesn't come. After it the pump delivers no more events and TickAll stops
// ticking. Plugins: keep OnClientCleanup short and never wait on AC's main thread
// inside it (it may be running on it, or waiting for you).
//
// Table functions: GetScreenModeFn, GetUiHookFlagsFn (PluginContract.cs).
// Older engines have neither the table fields nor the callbacks: a plugin checks
// RynthCoreAPI.Version >= 77 before reading the fields (RynthCoreHost.HasUiHooks).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.Plugins;
internal static partial class PluginManager
{
private static GetScreenModeCallbackDelegate? _getScreenModeCallback; // v77
private static GetUiHookFlagsCallbackDelegate? _getUiHookFlagsCallback; // v77
/// <summary>The thread that ran TickAll last (the plugin pump).</summary>
private static int _tickThread;
private enum UiEventKind : byte { ScreenChanged, TooltipShow, TooltipHide, DragStart, ItemDropped }
private readonly record struct PendingUiEvent(UiEventKind Kind, uint A, uint B, uint C);
private const int MaxPendingUiEvents = 256;
private static readonly Queue<PendingUiEvent> _pendingUiEvents = new();
private static readonly object PendingUiEventsLock = new();
// Client::Cleanup: 0 nothing, 1 waiting for the pump, 2 delivered (or nobody to tell).
private static int _cleanupState;
// ── Queueing (AC's main thread) ──────────────────────────────────────
public static void QueueScreenChanged(int oldMode, int newMode) => QueueUiEvent(UiEventKind.ScreenChanged, (uint)oldMode, (uint)newMode, 0);
public static void QueueTooltipShown(uint objectId, uint spellId) => QueueUiEvent(UiEventKind.TooltipShow, objectId, spellId, 0);
public static void QueueTooltipHidden() => QueueUiEvent(UiEventKind.TooltipHide, 0, 0, 0);
public static void QueueDragStarted(uint objectId, uint spellId, uint iconId) => QueueUiEvent(UiEventKind.DragStart, objectId, spellId, iconId);
public static void QueueItemDropped(uint objectId, uint spellId, uint targetElementId) => QueueUiEvent(UiEventKind.ItemDropped, objectId, spellId, targetElementId);
private static void QueueUiEvent(UiEventKind kind, uint a, uint b, uint c)
{
if (!_initialized || _plugins.Count == 0 || Volatile.Read(ref _cleanupState) != 0)
return;
lock (PendingUiEventsLock)
{
if (_pendingUiEvents.Count >= MaxPendingUiEvents)
_pendingUiEvents.Dequeue();
_pendingUiEvents.Enqueue(new PendingUiEvent(kind, a, b, c));
}
}
// ── Delivery (plugin pump) ───────────────────────────────────────────
private static void ResolveUiExports(LoadedPlugin plugin)
{
if (plugin.UiExportsResolved || plugin.ModuleHandle == IntPtr.Zero)
return;
plugin.UiExportsResolved = true;
plugin.OnScreenChangedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnScreenChanged");
plugin.OnClientCleanupPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnClientCleanup");
plugin.OnTooltipShowPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipShow");
plugin.OnTooltipHidePtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipHide");
plugin.OnDragStartPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnDragStart");
plugin.OnItemDroppedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnItemDropped");
int count = (plugin.OnScreenChangedPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnClientCleanupPtr != IntPtr.Zero ? 1 : 0)
+ (plugin.OnTooltipShowPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnTooltipHidePtr != IntPtr.Zero ? 1 : 0)
+ (plugin.OnDragStartPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnItemDroppedPtr != IntPtr.Zero ? 1 : 0);
if (count > 0)
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} takes {count} v77 UI callback(s).");
}
private static unsafe void DispatchQueuedUiEvents()
{
if (!_initialized || _plugins.Count == 0)
return;
PendingUiEvent[] pending;
lock (PendingUiEventsLock)
{
if (_pendingUiEvents.Count == 0)
return;
pending = _pendingUiEvents.ToArray();
_pendingUiEvents.Clear();
}
foreach (PendingUiEvent evt in pending)
{
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed)
continue;
ResolveUiExports(plugin);
IntPtr fn = evt.Kind switch
{
UiEventKind.ScreenChanged => plugin.OnScreenChangedPtr,
UiEventKind.TooltipShow => plugin.OnTooltipShowPtr,
UiEventKind.TooltipHide => plugin.OnTooltipHidePtr,
UiEventKind.DragStart => plugin.OnDragStartPtr,
_ => plugin.OnItemDroppedPtr,
};
if (fn == IntPtr.Zero)
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
switch (evt.Kind)
{
case UiEventKind.ScreenChanged:
((delegate* unmanaged[Cdecl]<int, int, void>)fn)((int)evt.A, (int)evt.B);
break;
case UiEventKind.TooltipShow:
((delegate* unmanaged[Cdecl]<uint, uint, void>)fn)(evt.A, evt.B);
break;
case UiEventKind.TooltipHide:
((delegate* unmanaged[Cdecl]<void>)fn)();
break;
case UiEventKind.DragStart:
case UiEventKind.ItemDropped:
((delegate* unmanaged[Cdecl]<uint, uint, uint, void>)fn)(evt.A, evt.B, evt.C);
break;
}
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} On{evt.Kind} threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
}
finally
{
LeaveDispatch(outer);
}
}
}
}
// ── Client::Cleanup ──────────────────────────────────────────────────
/// <summary>
/// AC's main thread, inside the Client::Cleanup detour before AC tears anything down.
/// Plugins are called from the plugin pump (a managed thread: a NativeAOT engine must not
/// run plugin code on AC's threads, the 2026-05-16 fail-fast), never from two threads at
/// once. So: the pump delivers RynthPluginOnClientCleanup at the top of its next frame
/// (ProcessClientCleanup, every ~16 ms) while this waits for up to half of
/// <paramref name="timeoutMs"/>. A pump that doesn't come (no frames: the device is
/// gone) leaves it to this thread, which delivers it holding the pump's frame guard
/// (EngineFrameController.TryRunOutsidePumpFrame). Exactly once either way; after the
/// full timeout AC's cleanup goes ahead regardless.
/// </summary>
public static void DispatchClientCleanup(int timeoutMs)
{
if (!_initialized || _plugins.Count == 0)
{
Volatile.Write(ref _cleanupState, 2);
return;
}
if (Interlocked.CompareExchange(ref _cleanupState, 1, 0) != 0)
return;
int pump = Volatile.Read(ref _tickThread);
if (pump == 0 || pump == Environment.CurrentManagedThreadId)
{
TakeAndDeliverClientCleanup("the calling thread (no separate pump)");
return;
}
long start = Environment.TickCount64;
long pumpUntil = start + timeoutMs / 2, until = start + timeoutMs;
while (Volatile.Read(ref _cleanupState) != 2)
{
long now = Environment.TickCount64;
if (now >= pumpUntil
&& ImGuiBackend.EngineFrameController.TryRunOutsidePumpFrame(() => TakeAndDeliverClientCleanup("AC's main thread (the pump didn't come)")))
return;
if (now >= until)
{
RynthLog.Plugin($"PluginManager: OnClientCleanup not delivered within {timeoutMs} ms (a pump frame is running); AC's cleanup goes ahead, the pump delivers it at its next frame.");
return;
}
Thread.Sleep(5);
}
}
/// <summary>
/// Plugin pump, top of ProcessPendingActions. True once Client::Cleanup started: the
/// rest of the frame's events are dropped (AC is tearing down what they describe).
/// </summary>
private static bool ProcessClientCleanup()
{
if (Volatile.Read(ref _cleanupState) == 0)
return UiFlowHooks.ClientCleanupStarted;
TakeAndDeliverClientCleanup("the plugin pump");
return true;
}
// 1 -> 2 exactly once, whoever gets there first.
private static void TakeAndDeliverClientCleanup(string where)
{
if (Interlocked.CompareExchange(ref _cleanupState, 2, 1) != 1)
return;
DeliverClientCleanup(where);
}
private static unsafe void DeliverClientCleanup(string where)
{
lock (PendingUiEventsLock)
_pendingUiEvents.Clear();
int told = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed)
continue;
ResolveUiExports(plugin);
if (plugin.OnClientCleanupPtr == IntPtr.Zero)
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
((delegate* unmanaged[Cdecl]<void>)plugin.OnClientCleanupPtr)();
told++;
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnClientCleanup threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
}
finally
{
LeaveDispatch(outer);
}
}
RynthLog.Plugin($"PluginManager: OnClientCleanup delivered to {told} plugin(s) from {where}; no more plugin ticks or events.");
}
// ── Table functions ──────────────────────────────────────────────────
/// <summary>v77: see PluginContract.GetScreenModeFn.</summary>
private static unsafe int GetScreenModeAction(int* previousMode)
{
if (previousMode != null)
*previousMode = UiFlowHooks.PreviousMode;
return UiFlowHooks.CurrentMode;
}
/// <summary>v77: see PluginContract.GetUiHookFlagsFn.</summary>
private static uint GetUiHookFlagsAction()
{
uint flags = 0;
if (UiFlowHooks.ScreenHookLive) flags |= 1u << 0;
else flags |= 1u << 1; // the +0x8C poll drives OnScreenChanged
if (UiFlowHooks.CleanupHookLive) flags |= 1u << 2;
if (UiElementHooks.TooltipShowLive) flags |= 1u << 3;
if (UiElementHooks.TooltipHideLive) flags |= 1u << 4;
if (UiElementHooks.DragStartLive) flags |= 1u << 5;
if (UiElementHooks.DropLive) flags |= 1u << 6;
if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7;
return flags;
}
}

View file

@ -12,10 +12,11 @@ using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Engine.D3D9;
using RynthCore.PluginSdk.Manifest;
namespace RynthCore.Engine.Plugins;
internal static class PluginManager
internal static partial class PluginManager
{
// Held: set when AC hasn't printed the line yet (ChatCallbackHooks holds it until the
// plugins' verdict is in; see IncomingChatHold.cs). Null for lines AC already printed.
@ -259,6 +260,10 @@ internal static class PluginManager
private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75
private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75
private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76
private static SetServerMessageInterestCallbackDelegate? _setServerMessageInterestCallback; // v78
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
private static RaiseCallbackDelegate? _raiseCallback; // v79
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
@ -521,6 +526,10 @@ internal static class PluginManager
public static void ProcessPendingActions(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd)
{
// v77: Client::Cleanup started (UiFlowHooks): tell the plugins once, then no more events.
if (ProcessClientCleanup())
return;
UiLifecycleHooks.Poll();
LoginLifecycleHooks.Poll();
SessionStateRegistry.Poll();
@ -539,6 +548,11 @@ internal static class PluginManager
// • View BEFORE Stop — a container open-then-close in one frame must
// end "closed"; draining Stop-then-View left the plugin believing the
// container was still open.
// v78 server messages first: the wire comes before the client's handling of it,
// which is what the queued events below report. Cheap when nobody asked for any.
try { Net.ServerMessageStream.Pump(_initialized && ServerMessageSubscriberCount() > 0); }
catch (Exception ex) { RynthLog.Compat($"PluginManager: server message pump failed - {ex.GetType().Name}: {ex.Message}"); }
DispatchQueuedBusyCountIncremented();
DispatchQueuedBusyCountDecremented();
DispatchQueuedCombatModeChange();
@ -558,6 +572,7 @@ internal static class PluginManager
DispatchQueuedEnchantmentAdded();
DispatchQueuedEnchantmentRemoved();
DispatchQueuedChatWindowText();
DispatchQueuedUiEvents(); // v77 screen / tooltip / drag / drop (PluginManager.UiHooks.cs)
if (_rescanRequested)
{
@ -1004,6 +1019,10 @@ internal static class PluginManager
public static void TickAll()
{
TickCount++;
Volatile.Write(ref _tickThread, Environment.CurrentManagedThreadId);
// v77: after Client::Cleanup no plugin ticks (AC is tearing its UI down); Shutdown still comes.
if (UiFlowHooks.ClientCleanupStarted)
return;
// Fire the delayed login self-identify once AC's vitals UI has settled
// (armed in DispatchLoginCompleteToLoadedPlugins; deferred past the
@ -1219,6 +1238,35 @@ internal static class PluginManager
return IntPtr.Zero;
}
/// <summary>
/// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional
/// <c>const char* RynthPluginReloadBlocker(void)</c> export whether a hot reload now would
/// hurt. Null or "" = safe; a plugin without the export never objects. Fixed signature, so no
/// mismatch can reach the stack; the plugin owns the buffer and it is copied at once. Called
/// on the loader's reload thread before the engine tears down, while every plugin is loaded.
/// </summary>
internal static unsafe IReadOnlyList<(string Plugin, string Reason)> QueryReloadBlockers()
{
var result = new List<(string, string)>();
LoadedPlugin[] plugins;
try { plugins = _plugins.ToArray(); }
catch { return result; } // the list changed under us (a plugin loading): don't hold the reload on it
foreach (var p in plugins)
{
try
{
if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) continue;
IntPtr fn = GetProcAddress(p.ModuleHandle, "RynthPluginReloadBlocker");
if (fn == IntPtr.Zero) continue;
IntPtr text = ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
string? reason = text != IntPtr.Zero ? Marshal.PtrToStringAnsi(text) : null;
if (!string.IsNullOrWhiteSpace(reason)) result.Add((p.DisplayName, reason.Trim()));
}
catch { /* a plugin that can't answer doesn't hold the reload */ }
}
return result;
}
private static void LogFromPlugin(IntPtr messageUtf8)
{
string? msg = Marshal.PtrToStringAnsi(messageUtf8);
@ -2286,6 +2334,7 @@ internal static class PluginManager
// bundled Plugins\ folder — that historically caused stray DLLs to
// load on next start (or after hot-reload) without the user knowing.
var extraPaths = EngineSettings.PluginPaths;
var candidates = new List<string>(extraPaths.Count);
for (int i = 0; i < extraPaths.Count; i++)
{
string dllPath = extraPaths[i];
@ -2308,21 +2357,109 @@ internal static class PluginManager
break;
}
}
for (int j = 0; j < candidates.Count && !alreadyLoaded; j++)
{
if (string.Equals(Path.GetFileName(candidates[j]), extraFileName, StringComparison.OrdinalIgnoreCase))
alreadyLoaded = true;
}
if (alreadyLoaded)
{
RynthLog.Plugin($"PluginManager: Extra plugin {extraFileName} already loaded from default directory — skipping.");
continue;
}
candidates.Add(dllPath);
}
// Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs
// a newer engine API or a missing plugin, and put required plugins first. Without
// manifests the list loads exactly as before.
PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion);
foreach (string line in plan.Log)
RynthLog.Plugin($"PluginManager: {line}");
foreach (PluginRefusal refusal in plan.Refused)
RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason);
foreach ((string dllPath, RynthPluginManifest? manifest) in plan.Load)
{
// A required plugin that failed to load (PluginLoader said no) takes its dependents with it.
string? missing = PluginManifestGate.CheckRequiredStarted(manifest, name => FindPlugin(name) != null ? true : null);
if (missing != null)
{
RefusePlugin(Path.GetFileName(dllPath), missing);
continue;
}
RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}");
var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration);
if (plugin != null)
{
plugin.Manifest = manifest;
if (manifest != null && !string.Equals(manifest.Name, plugin.DisplayName, StringComparison.OrdinalIgnoreCase))
RynthLog.Plugin($"PluginManager: {plugin.FileName}: manifest name '{manifest.Name}' differs from RynthPluginName '{plugin.DisplayName}'; dependencies use the manifest's.");
_plugins.Add(plugin);
}
}
PublishPluginsRenderSnapshot();
}
// ── Plugin manifests ─────────────────────────────────────────────────
/// <summary>Refusals not yet said in chat; said once each, at login (see AnnouncePluginRefusals).</summary>
private static readonly List<string> _pendingRefusalNotices = new();
private static readonly HashSet<string> _announcedRefusals = new(StringComparer.Ordinal);
private static void RefusePlugin(string fileName, string reason)
{
RynthLog.Plugin($"PluginManager: NOT starting {fileName}: {reason} (this RynthCore is plugin API {PluginContractVersion.Current}).");
lock (_pendingRefusalNotices)
{
if (!_announcedRefusals.Contains(reason) && !_pendingRefusalNotices.Contains(reason))
_pendingRefusalNotices.Add(reason);
}
if (_loginCompleteObserved)
AnnouncePluginRefusals();
}
/// <summary>Says each refusal once in chat ("[RynthCore] RynthOracle needs a newer RynthCore (API 77) - not started."). Pump thread.</summary>
private static void AnnouncePluginRefusals()
{
List<string> lines;
lock (_pendingRefusalNotices)
{
if (_pendingRefusalNotices.Count == 0) return;
lines = new List<string>(_pendingRefusalNotices);
_pendingRefusalNotices.Clear();
foreach (string l in lines) _announcedRefusals.Add(l);
}
foreach (string line in lines)
AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {line} - not started.", 1);
}
/// <summary>The loaded plugin going by <paramref name="name"/>: manifest name, else its file's name, else RynthPluginName.</summary>
private static LoadedPlugin? FindPlugin(string name)
{
for (int i = 0; i < _plugins.Count; i++)
{
LoadedPlugin p = _plugins[i];
if (p.Manifest != null && string.Equals(p.Manifest.Name, name, StringComparison.OrdinalIgnoreCase)) return p;
}
for (int i = 0; i < _plugins.Count; i++)
{
LoadedPlugin p = _plugins[i];
if (string.Equals(RynthPluginManifest.NameFromFile(p.SourceFilePath), name, StringComparison.OrdinalIgnoreCase)
|| string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase))
return p;
}
return null;
}
private static string RawFileVersion(string path)
{
try { return System.Diagnostics.FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
catch { return ""; }
}
private static void InitializeLoadedPlugins()
{
if (_plugins.Count == 0)
@ -2337,6 +2474,20 @@ internal static class PluginManager
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
// Manifest: a plugin whose required plugin didn't start isn't started either (they
// come first: LoadPluginsFromDisk ordered them). No manifest, no check.
string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name =>
FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null);
if (blocked != null)
{
plugin.Failed = true;
plugin.NotStartedReason = blocked;
RefusePlugin(plugin.FileName, blocked);
continue;
}
plugin.NotStartedReason = "";
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
@ -2451,6 +2602,7 @@ internal static class PluginManager
return;
_loginDispatchPending = false;
AnnouncePluginRefusals(); // plugins the manifests kept out, once each, now that chat is up
for (int i = 0; i < _plugins.Count; i++)
{
@ -2633,6 +2785,12 @@ internal static class PluginManager
unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; }
unsafe { _getServerInfoCallback ??= GetServerInfoAction; }
_closeContainerCallback ??= CloseContainerAction;
unsafe { _getScreenModeCallback ??= GetScreenModeAction; } // v77 (PluginManager.UiHooks.cs)
_getUiHookFlagsCallback ??= GetUiHookFlagsAction;
unsafe { _setServerMessageInterestCallback ??= SetServerMessageInterestAction; }
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
unsafe { _raiseCallback ??= RaiseAction; }
_trainSkillCallback ??= TrainSkillAction;
_getVendorInfoCallback ??= GetVendorInfoAction;
_getVendorItemsCallback ??= GetVendorItemsAction;
_vendorBuyCallback ??= VendorBuyAction;
@ -2770,6 +2928,12 @@ internal static class PluginManager
_api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback);
_api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback);
_api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback);
_api.GetScreenModeFn = Marshal.GetFunctionPointerForDelegate(_getScreenModeCallback);
_api.GetUiHookFlagsFn = Marshal.GetFunctionPointerForDelegate(_getUiHookFlagsCallback);
_api.SetServerMessageInterestFn = Marshal.GetFunctionPointerForDelegate(_setServerMessageInterestCallback);
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
@ -3828,6 +3992,133 @@ internal static class PluginManager
/// <summary>v72: see PluginContract.TradeCloseFn.</summary>
private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close());
// ── v79: spending experience (Compatibility/TrainingApi.cs) ─────────
/// <summary>v79: see PluginContract.GetTrainingInfoFn.</summary>
private static unsafe int GetTrainingInfoAction(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
{
try
{
return TrainingApi.GetInfo(info, entries, maxEntries);
}
catch
{
return 0;
}
}
/// <summary>v79: see PluginContract.RaiseFn.</summary>
private static unsafe int RaiseAction(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)
{
try
{
RaiseStatus r = TrainingApi.Raise(kind, stype, ranks, expectedXp, out long sent);
if (xpSent != null) *xpSent = sent;
return (int)r;
}
catch (Exception ex)
{
RynthLog.Compat($"Raise failed - {ex.GetType().Name}: {ex.Message}");
return (int)RaiseStatus.SendFailed;
}
}
/// <summary>v79: see PluginContract.TrainSkillFn.</summary>
private static int TrainSkillAction(uint stype, int expectedCredits)
{
try
{
return (int)TrainingApi.TrainSkill(stype, expectedCredits);
}
catch (Exception ex)
{
RynthLog.Compat($"TrainSkill failed - {ex.GetType().Name}: {ex.Message}");
return (int)RaiseStatus.SendFailed;
}
}
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
{
try
{
LoadedPlugin? owner = CurrentDispatch;
if (owner == null)
return -1;
if (opcodeCount == 0 && eventCount == 0)
{
owner.ServerMessageInterest?.Clear();
RynthLog.Plugin($"PluginManager: {owner.DisplayName} stopped server messages.");
return 1;
}
if (owner.OnServerMessagePtr == IntPtr.Zero)
owner.OnServerMessagePtr = GetProcAddress(owner.ModuleHandle, "RynthPluginOnServerMessage");
if (owner.OnServerMessagePtr == IntPtr.Zero)
return 0;
var interest = owner.ServerMessageInterest ??= new Net.ServerMessageInterest();
if (!interest.Set(opcodes, opcodeCount, gameEvents, eventCount))
return -3;
RynthLog.Plugin($"PluginManager: {owner.DisplayName} wants server messages: " +
(interest.All ? "all" : $"{interest.OpcodeCount} opcode(s), {interest.EventCount} game event(s){(interest.AllGameEvents ? " + all game events" : "")}"));
return EngineSettings.ServerMessageStream ? 1 : 2;
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginManager: SetServerMessageInterest failed - {ex.GetType().Name}: {ex.Message}");
return -3;
}
}
/// <summary>v78: initialized, healthy plugins with a non-empty server-message interest.</summary>
internal static int ServerMessageSubscriberCount()
{
int n = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var p = _plugins[i];
if (p.Initialized && !p.Failed && p.OnServerMessagePtr != IntPtr.Zero &&
p.ServerMessageInterest is { IsEmpty: false })
n++;
}
return n;
}
/// <summary>
/// v78: one reassembled server message to the plugins that asked for it (called from
/// ServerMessageStream.Pump, on this pump). <paramref name="body"/> is the message after
/// its opcode, valid only during the call. Returns how many plugins were called.
/// </summary>
internal static unsafe int DispatchServerMessage(uint opcode, uint eventType, byte* body, int length)
{
int called = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed || plugin.OnServerMessagePtr == IntPtr.Zero)
continue;
var interest = plugin.ServerMessageInterest;
if (interest == null || !interest.Wants(opcode, eventType))
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
((delegate* unmanaged[Cdecl]<uint, byte*, int, void>)plugin.OnServerMessagePtr)(opcode, body, length);
called++;
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Error($"PluginManager: {plugin.DisplayName} OnServerMessage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled.");
}
finally
{
LeaveDispatch(outer);
}
}
return called;
}
/// <summary>v76: close an external container (see PluginContract.CloseContainerFn).</summary>
private static int CloseContainerAction(uint containerId)
{

View file

@ -0,0 +1,119 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginManifestGate.cs
// The engine's use of plugin manifests (RynthCore.PluginSdk.Manifest, compiled in):
// - before any plugin DLL is loaded, read each one's embedded manifest from the
// file (no LoadLibrary: a refused NativeAOT plugin would otherwise keep a whole
// runtime in acclient's 4 GB for good) and decide which may load, in what order;
// - before a plugin's Init, check the plugins it requires started.
// A plugin without a manifest is never refused and keeps its place in the list,
// so a plugin list with no manifests loads exactly as before.
//
// BCL + the manifest files only, so tools\PluginManifestTests compiles it too.
// PluginManager owns the logging and the chat notice.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.PluginSdk.Manifest;
namespace RynthCore.Engine.Plugins;
internal static class PluginManifestGate
{
internal sealed class LoadPlan
{
/// <summary>Paths to load, in order, with their manifests (null for a plugin without one).</summary>
public List<(string Path, RynthPluginManifest? Manifest)> Load { get; } = new();
/// <summary>Plugins not loaded, with the reason (one sentence, fit for chat).</summary>
public List<PluginRefusal> Refused { get; } = new();
/// <summary>Log lines: manifests found, broken manifests, notes.</summary>
public List<string> Log { get; } = new();
}
/// <summary>
/// Reads the manifests of <paramref name="paths"/> and resolves them against
/// <paramref name="engineApi"/>. <paramref name="fileVersion"/> gives a DLL's version resource
/// (for dependency versions of plugins whose manifest has none); null skips it.
/// </summary>
public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null)
{
var plan = new LoadPlan();
var candidates = new List<PluginCandidate>(paths.Count);
int withManifest = 0;
foreach (string path in paths)
{
RynthPluginManifest? manifest = null;
try
{
manifest = PluginManifestReader.Read(path);
}
catch (InvalidDataException ex)
{
// A broken manifest is a build problem, not the player's: load it the old way.
plan.Log.Add($"{Path.GetFileName(path)}: manifest unreadable ({ex.Message}) - loading it as a plugin without one.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
plan.Log.Add($"{Path.GetFileName(path)}: could not read its manifest ({ex.Message}) - loading it as a plugin without one.");
}
string fv = "";
if (fileVersion != null && string.IsNullOrEmpty(manifest?.Version))
{
try { fv = fileVersion(path) ?? ""; } catch { fv = ""; }
}
if (manifest != null)
{
withManifest++;
plan.Log.Add($"{Path.GetFileName(path)}: manifest {Describe(manifest)}.");
}
candidates.Add(new PluginCandidate(path, manifest, fv));
}
PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi);
foreach (PluginCandidate c in res.Order)
plan.Load.Add((c.Key, c.Manifest));
plan.Refused.AddRange(res.Refused);
foreach (string note in res.Notes)
plan.Log.Add(note);
if (withManifest == 0 && paths.Count > 0)
plan.Log.Add("no plugin has a manifest; loading them as listed.");
return plan;
}
/// <summary>
/// Null when every plugin <paramref name="manifest"/> requires has started; otherwise why not.
/// <paramref name="started"/> answers by plugin name: true started, false loaded but not
/// started (failed or refused at Init), null not loaded at all.
/// </summary>
public static string? CheckRequiredStarted(RynthPluginManifest? manifest, Func<string, bool?> started)
{
if (manifest == null) return null;
foreach (RynthPluginDependency d in manifest.Dependencies)
{
if (d.Optional) continue;
bool? s = started(d.Name);
if (s == true) continue;
return s == false
? $"{manifest.Name} needs {d.Name}, which failed to start"
: $"{manifest.Name} needs {d.Name}, which is not loaded";
}
return null;
}
/// <summary>"RynthOracle 2026.10.5.1, API 71+, needs RynthAi (optional)".</summary>
public static string Describe(RynthPluginManifest m)
{
string api = m.MaxEngineApi != 0 ? $"API {m.MinEngineApi}-{m.MaxEngineApi}" : $"API {m.MinEngineApi}+";
string s = $"{m.Name}{(m.Version.Length > 0 ? " " + m.Version : "")}, {api}";
if (m.Dependencies.Count > 0)
{
var parts = new List<string>(m.Dependencies.Count);
foreach (RynthPluginDependency d in m.Dependencies)
parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : ""));
s += ", needs " + string.Join(", ", parts);
}
return s;
}
}

View file

@ -0,0 +1,113 @@
// ============================================================================
// RynthCore.Engine - ReloadDeferral.cs
// Holds a hot reload while a plugin says one now would hurt (2026-10-05).
//
// Drakkon died on DreamWeave at 13:43:20 after the loader's file watcher saw a
// new RynthCore.Engine.dll at 13:42:54 and reloaded the engine mid-fight: every
// plugin was down for about 8 s, then RynthAi came back as if it had just logged
// in. The loader (native\Loader, off-limits here) decides to reload and calls
// RynthCoreShutdown on its own reload thread; nothing in the game waits on that
// thread. So the engine's side of the handshake is: before tearing down, ask
// every plugin's optional RynthPluginReloadBlocker export, and while one answers
// with a reason, wait and ask again, up to Cap. The game keeps running on the
// old engine meanwhile; the loader stages the new one after Shutdown returns, so
// the newest file on disk is what loads.
//
// Pure: the plugin query, the clock, the sleep and the log are injected, so the
// loop is tested offline (tools\ReloadDeferralTests). EntryPoint wires it.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
namespace RynthCore.Engine;
internal sealed class ReloadDeferral
{
/// <summary>Longest a reload waits for the plugins (then it goes ahead, and says so).</summary>
public static readonly TimeSpan DefaultCap = TimeSpan.FromMinutes(2);
/// <summary>How often the plugins are asked again while one blocks.</summary>
public static readonly TimeSpan DefaultPoll = TimeSpan.FromMilliseconds(500);
/// <summary>While waiting, the "still waiting" line repeats this often (the first line is at once).</summary>
public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(15);
public enum Outcome
{
/// <summary>No plugin objected: reload at once.</summary>
Clear,
/// <summary>A plugin objected, then cleared within the cap.</summary>
ClearedAfterWait,
/// <summary>Still objecting at the cap: reload anyway.</summary>
TimedOut,
}
/// <summary>The plugins that object now, each with its reason (empty = safe).</summary>
public required Func<IReadOnlyList<(string Plugin, string Reason)>> Query { get; init; }
public required Action<string> Log { get; init; }
/// <summary>Told once, when the wait starts (the engine puts it in chat).</summary>
public Action<string>? Notify { get; init; }
public Func<DateTime> Clock { get; init; } = () => DateTime.UtcNow;
public Action<TimeSpan> Sleep { get; init; } = t => Thread.Sleep(t);
public TimeSpan Cap { get; init; } = DefaultCap;
public TimeSpan Poll { get; init; } = DefaultPoll;
public TimeSpan LogEvery { get; init; } = DefaultLogEvery;
/// <summary>Asks the plugins until none objects or <see cref="Cap"/> has passed.</summary>
public Outcome Run(out TimeSpan waited)
{
DateTime start = Clock();
waited = TimeSpan.Zero;
var blockers = SafeQuery();
if (blockers.Count == 0) return Outcome.Clear;
string first = Describe(blockers);
Log($"engine reload waiting: {first} (asking again every {Poll.TotalSeconds:0.#} s, at most {Cap.TotalSeconds:0} s).");
try { Notify?.Invoke(first); } catch { }
DateTime lastLog = start;
while (true)
{
DateTime now = Clock();
waited = now - start;
if (waited >= Cap)
{
Log($"engine reload: waited {waited.TotalSeconds:0} s and {Describe(blockers)} still; reloading anyway.");
return Outcome.TimedOut;
}
Sleep(Poll);
blockers = SafeQuery();
now = Clock();
waited = now - start;
if (blockers.Count == 0)
{
Log($"engine reload: the plugins are clear after {waited.TotalSeconds:0.0} s; reloading now.");
return Outcome.ClearedAfterWait;
}
if (now - lastLog >= LogEvery)
{
lastLog = now;
Log($"engine reload waiting: {Describe(blockers)} ({waited.TotalSeconds:0} s of at most {Cap.TotalSeconds:0} s).");
}
}
}
/// <summary>"RynthAi in combat (a monster engaged)", several joined with "; ".</summary>
public static string Describe(IReadOnlyList<(string Plugin, string Reason)> blockers)
{
var parts = new List<string>(blockers.Count);
foreach (var (plugin, reason) in blockers) parts.Add($"{plugin} {reason}");
return string.Join("; ", parts);
}
// A plugin query that throws must never hold a reload: count it as "nothing objects".
private IReadOnlyList<(string Plugin, string Reason)> SafeQuery()
{
try { return Query() ?? Array.Empty<(string, string)>(); }
catch (Exception ex)
{
try { Log($"engine reload: asking the plugins failed ({ex.GetType().Name}: {ex.Message}); not waiting."); } catch { }
return Array.Empty<(string, string)>();
}
}
}

View file

@ -73,10 +73,14 @@
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" />
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's copy (MonoGame, Ms-PL). -->
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's decoder (RynthCore's own, MIT). -->
<Compile Include="..\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Shared\DxtUtil.cs" />
<!-- The byte-ring protocol shared with the Decal bridge plugin (docs/DECAL_BRIDGE_PLAN.md). -->
<Compile Include="..\RynthCore.DecalBridge\BridgeProtocol.cs" Link="Shared\BridgeProtocol.cs" />
<!-- Plugin manifests: read from each plugin DLL before loading it (Plugins/PluginManifestGate.cs). -->
<Compile Include="..\RynthCore.PluginSdk\Manifest\*.cs" Link="Shared\Manifest\%(Filename)%(Extension)" />
<!-- The SDK's server-message parsers: /rc netmsg log checks them against the live server (Net/ServerMessageStream.cs). -->
<Compile Include="..\RynthCore.PluginSdk\Net\*.cs" Link="Shared\Net\%(Filename)%(Extension)" />
</ItemGroup>
<!-- Prevent trimmer from removing ImGui.NET's DllImport methods -->

View file

@ -77,6 +77,83 @@ internal static class RynthLog
EntryPoint.LogTagged("engine", msg, "ERR");
}
// ── Diagnostic traces (2026-10-05, Drakkon's held casts on DreamWeave) ──
// A movement packet sent while a cast winds up can cancel the cast or leave the server
// holding it open, and the old movement lines were 1 in 8 with no caller. Both switches
// are on by default; each costs one bool test when off.
/// <summary>Every plugin movement call (SetAutoRun, SetMotion, DoMovement/StopMovement,
/// StopCompletely, TurnToHeading, jumps), one "Move:" line each with the calling plugin.
/// Identical calls in a row from one caller (turns: any angle) are counted, not written,
/// for up to MoveRepeatWindowMs; the count rides on the next line written.</summary>
internal static bool MoveTraceEnabled = true;
/// <summary>Every server UseDone (0x01C7) with its sequence number and error code
/// (before: the first 25 of a session).</summary>
internal static bool ActionDoneTraceEnabled = true;
private const long MoveRepeatWindowMs = 1000;
private static readonly object _moveGate = new();
private static string _moveLastKey = "";
private static long _moveLastWrittenMs = long.MinValue;
private static int _moveRepeats;
private static long _moveRepeatFirstMs;
private static string _moveRepeatLastArg = "";
/// <summary>
/// One plugin movement call (see <see cref="MoveTraceEnabled"/>). <paramref name="name"/>
/// must be a string literal (it also goes into AcActionTrace, which keeps the last 256
/// actions for crash dumps); <paramref name="a"/>/<paramref name="b"/> are its trace args.
/// </summary>
internal static void Move(string name, string arg, bool ok, bool collapseByKind = false, uint a = 0, uint b = 0)
{
Compatibility.AcActionTrace.Record(name, a, b);
if (!MoveTraceEnabled) return;
string? line = null;
try
{
string caller = MoveCaller();
lock (_moveGate)
{
long now = Environment.TickCount64;
string key = collapseByKind ? $"{caller}|{name}" : $"{caller}|{name}({arg})|{ok}";
if (key == _moveLastKey && now - _moveLastWrittenMs < MoveRepeatWindowMs)
{
if (_moveRepeats == 0) _moveRepeatFirstMs = now;
_moveRepeats++;
_moveRepeatLastArg = arg;
return;
}
string more = "";
if (_moveRepeats > 0)
{
string[] parts = _moveLastKey.Split('|');
string what = parts.Length > 1 ? parts[1] : "?";
string last = parts.Length > 2 ? "" : $", last {_moveRepeatLastArg}";
more = $" (+{_moveRepeats} more {what}{last} by {parts[0]} before this, over {now - _moveRepeatFirstMs} ms)";
}
line = $"Move: {name}({arg}) by {caller} -> {(ok ? "ok" : "FAILED")}{more}";
_moveLastKey = key;
_moveLastWrittenMs = now;
_moveRepeats = 0;
_moveRepeatLastArg = "";
}
}
catch { return; }
Write(line);
}
/// <summary>The plugin whose tick or event is calling, else the thread.</summary>
private static string MoveCaller()
{
var plugin = Plugins.PluginManager.CurrentDispatch;
if (plugin != null)
return string.IsNullOrEmpty(plugin.DisplayName) ? plugin.FileName : plugin.DisplayName;
return Compatibility.MainThreadGuard.IsOnMainThread()
? "AC main thread"
: $"thread {Environment.CurrentManagedThreadId}";
}
// ── Sink ─────────────────────────────────────────────────────────────
private static void Write(string message) => EntryPoint.Log(message);

View file

@ -0,0 +1,28 @@
// ============================================================================
// RynthCore.Engine - UI/Data/ArgbOpacity.cs
// An AARRGGBB colour's alpha as an opacity percentage, for the Vision face's
// overlay opacity sliders (slopes, water, radar ring). The opacity lives in the
// colour the RynthVision plugin already saves, so the slider needs no new
// setting and no plugin change: moving it rewrites the colour's alpha byte.
//
// Percent is a float so an untouched value round-trips exactly
// (0x60 -> 37.65 % -> 0x60); only a slider move changes the byte.
// ============================================================================
using System;
namespace RynthCore.Engine.UI.Data;
internal static class ArgbOpacity
{
/// <summary>The colour's alpha as 0..100 %.</summary>
public static float Percent(uint argb) => (argb >> 24) * 100f / 255f;
/// <summary>The colour with its alpha set from <paramref name="percent"/> (clamped to 0..100); RGB kept.</summary>
public static uint WithPercent(uint argb, float percent)
{
float p = float.IsNaN(percent) ? 0f : Math.Clamp(percent, 0f, 100f);
uint a = (uint)Math.Clamp((int)MathF.Round(p * 255f / 100f), 0, 255);
return (argb & 0x00FFFFFFu) | (a << 24);
}
}

View file

@ -156,6 +156,9 @@ internal sealed class RynthAiSettings
public bool RebuffWhenIdle { get; set; }
public int RebuffSecondsRemaining { get; set; } = 300;
public int RebuffTopOffSecondsRemaining { get; set; } = 1200;
// Cast our own buff even when gear already gives it (servers with buff augments). Default
// on; a RynthAi that predates it doesn't send it, and must not read as off.
public bool CastBuffsOverItemBuffs { get; set; } = true;
public int BuffMinSkillLevelTier1 { get; set; } = 35;
public int BuffMinSkillLevelTier2 { get; set; } = 85;
public int BuffMinSkillLevelTier3 { get; set; } = 135;
@ -176,6 +179,10 @@ internal sealed class RynthAiSettings
public bool LootJumpEnabled { get; set; }
public int LootJumpHeight { get; set; } = 10;
public int LootOwnership { get; set; }
// Recover your own death corpse whole (default on), and travel back to it after a death
// (default off). A RynthAi that predates them doesn't send them; on must not read as off.
public bool LootOwnCorpse { get; set; } = true;
public bool TravelToOwnCorpse { get; set; }
public bool EnableAutostack { get; set; } = true;
public bool ReadUnknownScrolls { get; set; } = true; // VTank's default
public bool EnableCombineSalvage { get; set; } = true;
@ -646,6 +653,8 @@ internal static class SettingsSchema
"Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."),
Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60,
"When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast."),
Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v,
"Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."),
Spacer(),
Section("Buff Difficulty (Min Buffed Skill)"),
Tiers(
@ -678,6 +687,10 @@ internal static class SettingsSchema
Spacer(),
Section("Corpse Ownership"),
Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v),
Bool("Recover My Corpse", s => s.LootOwnCorpse, (s, v) => s.LootOwnCorpse = v,
"When your own corpse (\"Corpse of <you>\") is within loot range, open it and take every\nitem on it, whatever the loot profile and Loot From say. Needs Enable Looting.\n/ra owncorpse says where your last corpse is."),
Bool("Travel Back To My Corpse", s => s.TravelToOwnCorpse, (s, v) => s.TravelToOwnCorpse = v,
"After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."),
Spacer(),
Section("Inventory Management"),
Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v),

View file

@ -5,13 +5,20 @@
// into one picture. Pure code: no AC memory, no D3D, no engine state, so the
// RynthSuite offline tests compile it in and decode real icons.
//
// The texture formats and their byte layouts are the ones RynthCore.StatusAgent
// (Dat/IconDecoder.cs, the phone remote's icons) decodes, ported from
// ACEmulator's DatLoader; DXT1/3/5 use the StatusAgent's DxtUtil.cs (MonoGame,
// Ms-PL), linked into the engine project. The dat reader is the on-demand
// B-tree walk of ImGui/MonsterHud/PortalSpellTable.cs over one open stream:
// header at 0x140, a B-tree searched by file id, block chains whose first
// dword is the next block's offset.
// Written for RynthCore (MIT); the dat reader and the texture decoding were
// rewritten on 2026-10-05 from the public dat container layout and the
// Texture / Palette layouts as Chorizite's DatReaderWriter (MIT) describes
// them (its notice is in RynthCore.StatusAgent/Dat/DatDatabase.cs):
// - header at 0x140: magic, block size, file size, ..., root node offset
// (uint32 at 0x160); a block starts with the next block's offset (0 =
// last); the directory is a B-tree of nodes (62 child offsets, an entry
// count, entries of 24 bytes: flags, id, offset, size, date, iteration);
// - Texture: id u32, data category u32, width i32, height i32, format u32,
// length i32, data[length], and for P8 / INDEX16 a palette id u32;
// Palette: id u32, count i32, count x u32 A8R8G8B8.
// DXT1/3/5 use the StatusAgent's DxtUtil.cs, linked into the engine project.
// The pixels are the same as the StatusAgent's Dat/IconDecoder.cs (the phone
// remote's icons) produces.
//
// Threads: whatever thread owns the AcDatFile (the icon worker). Every read is
// bounds-checked; a bad file returns null, never throws out of Decode/Compose.
@ -21,26 +28,30 @@ using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using ACE.DatLoader;
using RynthCore.Imaging;
namespace RynthCore.Engine.UI.ScriptWindows;
/// <summary>A read-only portal.dat opened for a batch of reads. Not thread-safe.</summary>
internal sealed class AcDatFile : IDisposable
{
private const int HeaderOffset = 0x140;
private const int Branches = 62, MaxEntries = 61, EntrySize = 24;
private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716
private const int MaxDepth = 16;
private const long HeaderOffset = 0x140;
private const int ChildSlots = 62, MaxEntries = 61, EntryBytes = 24;
private const int EntriesOffset = ChildSlots * 4 + 4; // 252
private const int NodeBytes = EntriesOffset + MaxEntries * EntryBytes; // 1716
private const int DepthLimit = 16;
private readonly FileStream _fs;
private readonly uint _blockSize;
private readonly long _length;
private readonly int _payload; // block size - 4
private readonly uint _root;
private readonly byte[] _node = new byte[NodeBytes];
private AcDatFile(FileStream fs, uint blockSize, uint root)
{
_fs = fs;
_blockSize = blockSize;
_length = fs.Length;
_payload = (int)blockSize - 4;
_root = root;
}
@ -52,24 +63,24 @@ internal sealed class AcDatFile : IDisposable
{
fs = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
Span<byte> hdr = stackalloc byte[36];
fs.Seek(HeaderOffset, SeekOrigin.Begin);
if (!ReadFully(fs, hdr)) { why = "short header"; fs.Dispose(); return null; }
uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
uint root = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(32, 4));
Span<byte> header = stackalloc byte[36];
fs.Position = HeaderOffset;
if (!ReadFully(fs, header)) { why = "short header"; fs.Dispose(); return null; }
uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(4));
uint root = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(32));
if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length)
{
why = "bad header";
why = $"not a dat file (block size {blockSize}, root 0x{root:X8})";
fs.Dispose();
return null;
}
why = string.Empty;
why = "";
return new AcDatFile(fs, blockSize, root);
}
catch (Exception ex)
{
fs?.Dispose();
why = $"{ex.GetType().Name}: {ex.Message}";
why = ex.Message;
return null;
}
}
@ -104,26 +115,34 @@ internal sealed class AcDatFile : IDisposable
{
try
{
uint offset = _root;
for (int depth = 0; depth < MaxDepth && offset != 0; depth++)
uint at = _root;
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
{
byte[]? node = ReadChain(offset, NodeSize);
if (node == null) return null;
uint count = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches));
if (count > MaxEntries) return null;
int i = 0;
while (i < count && EntryId(node, i) < fileId) i++;
if (i < count && EntryId(node, i) == fileId)
int got = ReadChain(at, _node);
if (got < EntriesOffset) return null;
int count = BinaryPrimitives.ReadInt32LittleEndian(_node.AsSpan(EntriesOffset - 4));
if (count < 0 || count > MaxEntries || got < EntriesOffset + count * EntryBytes) return null;
// Entries are sorted by id: binary search for the first id >= fileId.
int lo = 0, hi = count;
while (lo < hi)
{
int e = 4 * Branches + 4 + i * EntrySize;
uint fileOffset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 8));
uint fileSize = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 12));
if (fileSize == 0 || fileSize > (uint)maxSize) return null;
return ReadChain(fileOffset, (int)fileSize);
int mid = (lo + hi) >> 1;
if (IdAt(mid) < fileId) lo = mid + 1; else hi = mid;
}
bool leaf = BinaryPrimitives.ReadUInt32LittleEndian(node) == 0;
if (leaf || i >= Branches) return null;
offset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(i * 4));
if (lo < count && IdAt(lo) == fileId)
{
var e = _node.AsSpan(EntriesOffset + lo * EntryBytes);
uint offset = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(8));
uint size = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(12));
if (size == 0 || size > (uint)maxSize || size > _length) return null;
var data = new byte[size];
return ReadChain(offset, data) == data.Length ? data : null;
}
// Not in this node: a leaf (first child offset 0) ends the search; otherwise
// child `lo` holds the ids between entries lo-1 and lo.
if (BinaryPrimitives.ReadUInt32LittleEndian(_node) == 0) return null;
at = BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(lo * 4));
}
return null;
}
@ -133,41 +152,36 @@ internal sealed class AcDatFile : IDisposable
}
}
private static uint EntryId(byte[] node, int i) =>
BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches + 4 + i * EntrySize + 4));
private uint IdAt(int i) => BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(EntriesOffset + i * EntryBytes + 4));
/// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary>
private byte[]? ReadChain(uint offset, int size)
// Copies the block chain at byte offset `first` into `dest`; returns the bytes
// filled (fewer than dest.Length when the chain ends first), -1 on a bad link.
private int ReadChain(uint first, Span<byte> dest)
{
if ((long)offset + 4 > _fs.Length) return null;
var buffer = new byte[size];
Span<byte> next = stackalloc byte[4];
_fs.Seek(offset, SeekOrigin.Begin);
if (!ReadFully(_fs, next)) return null;
uint nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
long block = first;
int done = 0;
int guard = 0;
while (done < size)
Span<byte> link = stackalloc byte[4];
while (done < dest.Length)
{
int take = Math.Min((int)_blockSize - 4, size - done);
if (!ReadFully(_fs, buffer.AsSpan(done, take))) return null;
if (block == 0) return done;
if (block + 4 > _length) return -1;
int take = Math.Min(_payload, dest.Length - done);
_fs.Position = block;
if (!ReadFully(_fs, link) || !ReadFully(_fs, dest.Slice(done, take))) return -1;
done += take;
if (done >= size) break;
if (nextAddr == 0 || nextAddr >= _fs.Length || ++guard > 1_000_000) return null;
_fs.Seek(nextAddr, SeekOrigin.Begin);
if (!ReadFully(_fs, next)) return null;
nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next);
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
}
return buffer;
return done;
}
private static bool ReadFully(FileStream fs, Span<byte> dest)
{
while (dest.Length > 0)
int got = 0;
while (got < dest.Length)
{
int n = fs.Read(dest);
int n = fs.Read(dest.Slice(got));
if (n <= 0) return false;
dest = dest.Slice(n);
got += n;
}
return true;
}
@ -251,7 +265,7 @@ internal static class AcIconDecoder
/// <summary>
/// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, unknown i32, width i32,
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, data category u32, width i32,
/// height i32, format u32, length i32, data[length], then for INDEX16/P8 a palette id u32.
/// </summary>
public static AcIconImage? Decode(AcDatFile dat, uint textureId) => Decode(dat, textureId, MaxSide);
@ -274,106 +288,109 @@ internal static class AcIconDecoder
}
}
private const uint FmtR8G8B8 = 0x14, FmtA8R8G8B8 = 0x15, FmtR5G6B5 = 0x17, FmtA4R4G4B4 = 0x1A, FmtA8 = 0x1C,
FmtP8 = 0x29, FmtIndex16 = 0x65, FmtLscapeR8G8B8 = 0xF3, FmtLscapeAlpha = 0xF4,
FmtDxt1 = 0x31545844, FmtDxt3 = 0x33545844, FmtDxt5 = 0x35545844;
/// <summary>A Texture file's bytes as RGBA (see <see cref="Decode(AcDatFile, uint)"/>); <paramref name="readPalette"/> loads a 0x04 palette.</summary>
internal static AcIconImage? DecodeTextureFile(byte[] data, Func<uint, byte[]?> readPalette, int maxSide = MaxSide)
{
if (data.Length < 24) return null;
maxSide = Math.Clamp(maxSide, 1, MaxUiSide);
ReadOnlySpan<byte> d = data;
int w = BinaryPrimitives.ReadInt32LittleEndian(d[8..]);
int h = BinaryPrimitives.ReadInt32LittleEndian(d[12..]);
uint fmt = BinaryPrimitives.ReadUInt32LittleEndian(d[16..]);
int len = BinaryPrimitives.ReadInt32LittleEndian(d[20..]);
if (w <= 0 || h <= 0 || w > maxSide || h > maxSide || len < 0 || len > data.Length - 24) return null;
byte[] src = d.Slice(24, len).ToArray();
var file = new ReadOnlySpan<byte>(data);
int w = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(8));
int h = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(12));
uint format = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(16));
int length = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(20));
int limit = Math.Min(maxSide, MaxUiSide);
if (w <= 0 || h <= 0 || w > limit || h > limit) return null;
if (length < 0 || 24L + length > data.Length) return null;
var src = file.Slice(24, length);
int n = w * h;
switch (fmt)
switch (format)
{
case 827611204: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); // DXT1
case 861165636: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); // DXT3
case 894720068: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); // DXT5
case FmtDxt1: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1);
case FmtDxt3: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3);
case FmtDxt5: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5);
}
var rgba = new byte[n * 4];
void Px(int i, int r, int g, int b, int a)
var px = new byte[n * 4];
switch (format)
{
int o = i * 4;
rgba[o] = (byte)r; rgba[o + 1] = (byte)g; rgba[o + 2] = (byte)b; rgba[o + 3] = (byte)a;
}
switch (fmt)
{
case 20: // R8G8B8, stored B, G, R
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
case FmtA8R8G8B8: // memory order B, G, R, A
if (length < n * 4) return null;
for (int i = 0; i < n; i++) Set(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]);
break;
case 243: // CUSTOM_LSCAPE_R8G8B8, stored R, G, B
for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
case FmtR8G8B8: // B, G, R
if (length < n * 3) return null;
for (int i = 0; i < n; i++) Set(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
break;
case 21: // A8R8G8B8, stored B, G, R, A
case 22: // X8R8G8B8
for (int i = 0; i < n && i * 4 + 3 < src.Length; i++)
Px(i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], fmt == 22 ? 255 : src[i * 4 + 3]);
case FmtLscapeR8G8B8: // R, G, B
if (length < n * 3) return null;
for (int i = 0; i < n; i++) Set(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
break;
case 23: // R5G6B5
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255);
}
break;
case 26: // A4R4G4B4
for (int i = 0; i < n && i * 2 + 1 < src.Length; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17);
}
break;
case 28: // A8 (greyscale)
case 244: // LSCAPE_ALPHA
for (int i = 0; i < n && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
break;
case 101: // INDEX16
case 41: // P8
{
if (data.Length < 24 + len + 4) return null;
uint paletteId = BinaryPrimitives.ReadUInt32LittleEndian(d[(24 + len)..]);
uint[]? pal = Palette(readPalette(paletteId));
if (pal == null || pal.Length == 0) return null;
bool p8 = fmt == 41;
case FmtR5G6B5: // top bits only, as the StatusAgent's decoder
if (length < n * 2) return null;
for (int i = 0; i < n; i++)
{
int idx;
if (p8) { if (i >= src.Length) break; idx = src[i]; }
else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); }
uint c = pal[idx % pal.Length];
Px(i, (int)((c >> 16) & 0xFF), (int)((c >> 8) & 0xFF), (int)(c & 0xFF), (int)((c >> 24) & 0xFF));
int v = src[i * 2] | (src[i * 2 + 1] << 8);
Set(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255);
}
break;
case FmtA4R4G4B4:
if (length < n * 2) return null;
for (int i = 0; i < n; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
Set(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17));
}
break;
case FmtA8: // one byte a pixel: an opaque grey level
case FmtLscapeAlpha:
if (length < n) return null;
for (int i = 0; i < n; i++) Set(px, i, src[i], src[i], src[i], 255);
break;
case FmtP8:
case FmtIndex16:
{
int bytesPer = format == FmtP8 ? 1 : 2;
if (length < n * bytesPer || 24L + length + 4 > data.Length) return null;
uint[]? palette = Palette(readPalette(BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(24 + length))));
if (palette == null) return null;
for (int i = 0; i < n; i++)
{
int idx = bytesPer == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8);
uint argb = idx < palette.Length ? palette[idx] : 0;
Set(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24));
}
break;
}
default:
return null; // a format icons don't use
return null; // raw JPEG, anything else
}
return new AcIconImage { Width = w, Height = h, Pixels = rgba };
return new AcIconImage { Width = w, Height = h, Pixels = px };
}
private static AcIconImage? Dxt(byte[] src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress)
private static void Set(byte[] px, int i, byte r, byte g, byte b, byte a)
{
px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a;
}
private static AcIconImage? Dxt(ReadOnlySpan<byte> src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> decompress)
{
long need = (long)((w + 3) / 4) * ((h + 3) / 4) * blockBytes;
if (src.Length < need) return null; // DxtUtil would read past the end
byte[] rgba = decompress(src, w, h);
return rgba.Length == w * h * 4 ? new AcIconImage { Width = w, Height = h, Pixels = rgba } : null;
if (src.Length < need) return null;
return new AcIconImage { Width = w, Height = h, Pixels = decompress(src.Slice(0, (int)need).ToArray(), w, h) };
}
/// <summary>Palette (0x04): id u32, count i32, count x u32 ARGB.</summary>
private static uint[]? Palette(byte[]? data)
{
if (data == null || data.Length < 8) return null;
int n = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
if (n <= 0 || n > 65536) return null;
n = Math.Min(n, (data.Length - 8) / 4);
var pal = new uint[n];
for (int i = 0; i < n; i++) pal[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4));
return pal;
int count = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4));
if (count < 0 || 8L + count * 4L > data.Length) return null;
var colours = new uint[count];
for (int i = 0; i < count; i++) colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4));
return colours;
}
}

View file

@ -6,7 +6,25 @@ namespace RynthCore.PluginCore;
public abstract class RynthPluginBase
{
public virtual uint MinimumApiVersion => RynthCoreHost.BaselineApiVersion;
/// <summary>
/// The oldest engine API the plugin starts on (RynthPluginRuntime refuses older ones). Defaults to
/// the plugin's manifest minimum (RynthPluginMinEngineApi in its csproj, compiled in as
/// [assembly: RynthPluginManifest]) so the plugin's own check and the engine's/launcher's manifest
/// check agree; without a manifest, the SDK baseline.
/// </summary>
public virtual uint MinimumApiVersion => ManifestMinimum(GetType()) ?? RynthCoreHost.BaselineApiVersion;
private static uint? ManifestMinimum(Type pluginType)
{
try
{
return System.Reflection.CustomAttributeExtensions.GetCustomAttribute<RynthPluginManifestAttribute>(pluginType.Assembly)?.MinEngineApi;
}
catch
{
return null;
}
}
protected RynthCoreApiNative Api { get; private set; }
protected RynthCoreHost Host { get; private set; }
@ -68,4 +86,21 @@ public abstract class RynthPluginBase
public virtual void OnKillNotification(string? deathMessage) { }
public virtual void OnEnchantmentAdded(uint spellId, double durationSeconds) { }
public virtual void OnEnchantmentRemoved(uint enchantmentId) { }
// v77 (RynthCoreHost.HasUiHooks): the client's screens and AC's own tooltips and drag/drop.
// The plugin's exports call these through RynthPluginRuntime; an older engine never calls them.
/// <summary>The client changed screens (<see cref="RynthScreenMode"/>): e.g. World to CharacterSelect at logout.</summary>
public virtual void OnScreenChanged(int oldMode, int newMode) { }
/// <summary>The client is shutting down and about to tear its UI down. Last chance to read AC
/// state; no ticks or events follow (Shutdown still does).</summary>
public virtual void OnClientCleanup() { }
/// <summary>AC shows a tooltip for an item (objectId) or a spell icon (spellId); both 0 for any other element.</summary>
public virtual void OnTooltipShow(uint objectId, uint spellId) { }
/// <summary>The tooltip from <see cref="OnTooltipShow"/> is gone.</summary>
public virtual void OnTooltipHide() { }
/// <summary>The player started dragging an item (objectId, its icon) or a spell (spellId) in AC's UI.</summary>
public virtual void OnDragStart(uint objectId, uint spellId, uint iconId) { }
/// <summary>AC took a dropped item or spell; targetElementId is the AC UI element it landed on.</summary>
public virtual void OnItemDropped(uint objectId, uint spellId, uint targetElementId) { }
}

View file

@ -279,6 +279,53 @@ public unsafe sealed class RynthPluginRuntime<TPlugin>
catch (Exception ex) { LogException("OnEnchantmentRemoved", ex); }
}
// ── v77 UI callbacks ─────────────────────────────────────────────────
// Exports: RynthPluginOnScreenChanged(int, int), RynthPluginOnClientCleanup(),
// RynthPluginOnTooltipShow(uint, uint), RynthPluginOnTooltipHide(),
// RynthPluginOnDragStart(uint, uint, uint), RynthPluginOnItemDropped(uint, uint, uint); all cdecl.
public void OnScreenChanged(int oldMode, int newMode)
{
if (!IsInitialized) return;
try { _plugin!.OnScreenChanged(oldMode, newMode); }
catch (Exception ex) { LogException("OnScreenChanged", ex); }
}
public void OnClientCleanup()
{
if (!IsInitialized) return;
try { _plugin!.OnClientCleanup(); }
catch (Exception ex) { LogException("OnClientCleanup", ex); }
}
public void OnTooltipShow(uint objectId, uint spellId)
{
if (!IsInitialized) return;
try { _plugin!.OnTooltipShow(objectId, spellId); }
catch (Exception ex) { LogException("OnTooltipShow", ex); }
}
public void OnTooltipHide()
{
if (!IsInitialized) return;
try { _plugin!.OnTooltipHide(); }
catch (Exception ex) { LogException("OnTooltipHide", ex); }
}
public void OnDragStart(uint objectId, uint spellId, uint iconId)
{
if (!IsInitialized) return;
try { _plugin!.OnDragStart(objectId, spellId, iconId); }
catch (Exception ex) { LogException("OnDragStart", ex); }
}
public void OnItemDropped(uint objectId, uint spellId, uint targetElementId)
{
if (!IsInitialized) return;
try { _plugin!.OnItemDropped(objectId, spellId, targetElementId); }
catch (Exception ex) { LogException("OnItemDropped", ex); }
}
private void LogException(string method, Exception ex)
{
if (Interlocked.Increment(ref _exceptionCount) > MaxLoggedExceptions)

View 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);
}

View 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));
}
}

View 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));
}

View 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();
}

View 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);
}

View 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;
}
}

View 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;
}

View file

@ -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>

View file

@ -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>

View file

@ -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

View 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; }
}

View 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;
}

View 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,
}

View 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>

View file

@ -104,6 +104,14 @@ internal sealed class AgentConfig
/// /maps returns an empty list and /map 404s — no other feature is affected.</summary>
[JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = @"C:\Games\RynthSuite\RynthAi\Maps";
/// <summary>cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in
/// <see cref="StatusDirectory"/>. Absent = no world map (capabilities.worldMap false); nothing else changes.</summary>
[JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_cell_1.dat";
/// <summary>RynthNav's Atlas (NavData\locations.json), searched by GET /nav/search for the phone's Travel tab.
/// Absent = no travel (capabilities.travel false). The travel itself also needs EnableRemoteControl.</summary>
[JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = @"C:\Games\RynthCore\NavData\locations.json";
public static string DefaultConfigPath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore", "statusagent.json");

View file

@ -1,41 +1,89 @@
// ============================================================================
// RynthCore.StatusAgent - Dat/DatDatabase.cs
// Read-only access to Asheron's Call .dat archives (the agent reads item
// icons from client_portal.dat). Written for RynthCore (MIT) on 2026-10-05;
// the same design as RynthSuite's Shared/RynthCore.TerrainData/DatDatabase.cs.
//
// Written from the dat container format as it is publicly documented, with
// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference:
// - file header at byte 0x140: magic, block size, file size, data set,
// subset, free head / tail / count, then the byte offset of the root
// B-tree node (all little-endian uint32);
// - storage is fixed-size blocks; a block's first uint32 is the byte offset
// of the next block of the same chain (0 ends the chain), the remaining
// BlockSize - 4 bytes are payload;
// - the directory is a B-tree whose nodes are stored as block chains: 62
// uint32 child offsets, a uint32 entry count (at most 61), then the
// entries, 24 bytes each: flags/version, id, byte offset of the file's
// first block, size, timestamp, iteration. Entries are sorted by id,
// child i holds the ids between entry i-1 and entry i, and a node whose
// first child offset is 0 is a leaf.
//
// Lookups descend the tree from the root; interior nodes are kept once read
// and leaves go through a small LRU. Every call takes one lock, so a database
// can be shared between threads.
//
// Chorizite DatReaderWriter notice (format reference):
// Copyright 2024 ACClientLib
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions: The above copyright notice and this permission
// notice shall be included in all copies or substantial portions of the
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// ============================================================================
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
namespace RynthCore2.TerrainData;
/// <summary>
/// AC .dat file reader — ported directly from ACEmulator's DatLoader.
///
/// Key format details (from ACE source):
/// - Header at file offset 0x140
/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset)
/// Remaining (BlockSize - 4) bytes = data
/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total
/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets
/// A read-only .dat archive. <see cref="Open"/> reads the header, checks the
/// root directory node and counts the files; files are then found by id by
/// searching the on-disk B-tree. Methods return null / empty when the database
/// isn't open or the file isn't there; nothing throws for a damaged file.
/// </summary>
public class DatDatabase : IDisposable
{
private FileStream? _stream;
private readonly object _lock = new();
private const long HeaderOffset = 0x140;
private const int HeaderBytes = 9 * 4; // magic .. root offset
private const int ChildSlots = 62;
private const int MaxEntriesPerNode = 61;
private const int EntryBytes = 24;
private const int CountOffset = ChildSlots * 4; // 248
private const int EntriesOffset = CountOffset + 4; // 252
private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716
private const int DepthLimit = 16; // real trees are 4 deep; stops a looping child pointer
private const int LeafLruSize = 128;
private const int InteriorCap = 4096;
private const uint DAT_HEADER_OFFSET = 0x140;
private readonly object _gate = new();
private FileStream? _file;
private long _length;
private readonly byte[] _nodeBuf = new byte[NodeBytes];
private readonly Dictionary<uint, Node> _interior = new();
private readonly Dictionary<uint, LinkedListNode<(uint At, Node Node)>> _leafMap = new();
private readonly LinkedList<(uint At, Node Node)> _leafOrder = new();
// B-tree geometry (from ACE DatDirectoryHeader.cs):
// 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes
// ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716
private const int BTREE_BRANCH_COUNT = 0x3E; // 62
private const int BTREE_MAX_ENTRIES = 0x3D; // 61
private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32
private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716
/// <summary>Dat header FileType field.</summary>
/// <summary>Header word at 0x140 (the dat magic).</summary>
public uint FileType { get; private set; }
/// <summary>Block size in bytes (typical: 1024).</summary>
public uint BlockSize { get; private set; }
/// <summary>Total file size from header.</summary>
/// <summary>File size recorded in the header.</summary>
public uint FileSize { get; private set; }
/// <summary>DataSet field from header.</summary>
/// <summary>The header's data set (database type) word.</summary>
public uint DataSet { get; private set; }
/// <summary>Byte offset of the root B-tree node.</summary>
public uint BTreeRoot { get; private set; }
@ -44,326 +92,75 @@ public class DatDatabase : IDisposable
public bool IsLoaded { get; private set; }
/// <summary>Source file path passed to <see cref="Open"/>.</summary>
public string? FilePath { get; private set; }
/// <summary>Number of files indexed from the B-tree.</summary>
/// <summary>Number of files in the dat (counted at <see cref="Open"/>).</summary>
public int RecordCount { get; private set; }
// All files indexed by ObjectId (populated during Open)
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new();
/// <summary>Most-recent diagnostic messages (capped at 100).</summary>
public List<string> DiagLog { get; } = new();
private sealed class Node
{
public uint[]? Children; // entry count + 1 offsets; null for a leaf
public DatBTreeEntry[] Entries = []; // ascending ObjectId
}
// ---------------------------------------------------------------- open / close
/// <summary>
/// Opens the .dat file at <paramref name="path"/> for read-only random access and
/// indexes every entry in the B-tree. Returns false on any failure.
/// Opens the .dat file at <paramref name="path"/> for read-only random access.
/// Returns false on any failure.
/// </summary>
public bool Open(string path)
{
try
lock (_gate)
{
if (!File.Exists(path))
{
Log($"File not found: {path}");
return false;
}
CloseLocked();
FilePath = path;
// Plugin init runs *before* acclient.exe opens its own DAT files,
// so our handle is the first one Windows sees on the file. Our
// share-mode dictates what AC's subsequent open can request — if
// we omit FileShare.Delete, AC's open (which needs delete-rename
// semantics for DDD/patcher) fails with a sharing violation and
// the AC client errors out with "cannot access the data files."
//
// FileShare.ReadWrite | FileShare.Delete = permit other openers
// to read, write, and delete-mark the file. RandomAccess hint +
// 4 KB buffer keeps the .dat B-tree reads efficient.
_stream = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete,
bufferSize: 4096,
options: FileOptions.RandomAccess);
Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes");
if (!ReadHeader())
try
{
Close();
if (!File.Exists(path)) { Log($"Not found: {path}"); return false; }
// AC keeps its own handles on its dats: share everything,
// including delete (the client's own open asks for it).
_file = new FileStream(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess);
_length = _file.Length;
Span<byte> h = stackalloc byte[HeaderBytes];
if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; }
FileType = BinaryPrimitives.ReadUInt32LittleEndian(h);
BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4));
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8));
DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12));
BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32));
if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; }
if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; }
IsLoaded = true;
if (GetNode(BTreeRoot) == null)
{
Log($"Root node at 0x{BTreeRoot:X8} doesn't parse");
CloseLocked();
return false;
}
RecordCount = CountUnder(BTreeRoot, 0);
Log($"Opened {Path.GetFileName(path)}: {RecordCount} files, block size {BlockSize}");
return true;
}
catch (Exception ex)
{
Log($"Open failed: {ex.Message}");
CloseLocked();
return false;
}
// Read the entire B-tree directory and index all files
ReadDirectory(BTreeRoot);
RecordCount = _allFiles.Count;
IsLoaded = true;
Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}");
return true;
}
catch (Exception ex)
{
Log($"Error: {ex.Message}");
Close();
return false;
}
}
/// <summary>
/// Reads the dat header from offset 0x140.
/// Format matches ACE's DatDatabaseHeader.Unpack().
/// </summary>
private bool ReadHeader()
{
if (_stream == null) return false;
if (_stream.Length < DAT_HEADER_OFFSET + 64)
{
Log("File too small");
return false;
}
_stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin);
using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true))
{
FileType = reader.ReadUInt32();
BlockSize = reader.ReadUInt32();
FileSize = reader.ReadUInt32();
DataSet = reader.ReadUInt32();
_ = reader.ReadUInt32(); // dataSubset (unused)
_ = reader.ReadUInt32(); // freeHead (unused)
_ = reader.ReadUInt32(); // freeTail (unused)
_ = reader.ReadUInt32(); // freeCount (unused)
BTreeRoot = reader.ReadUInt32();
}
Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}");
if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length)
{
Log("Invalid header values");
return false;
}
return true;
}
/// <summary>
/// Reads data from the dat file following the block chain.
/// Matches ACE's DatReader.ReadDat() exactly.
///
/// Block format:
/// [4 bytes: next block address] [BlockSize - 4 bytes: data]
///
/// The FIRST 4 bytes of each block are the chain pointer (next block address).
/// If 0, this is the last block.
/// </summary>
private byte[]? ReadDatData(uint offset, int size)
{
if (_stream == null) return null;
if (offset + BlockSize > (uint)_stream.Length || size <= 0)
return null;
byte[] buffer = new byte[size];
_stream.Seek(offset, SeekOrigin.Begin);
// Read first 4 bytes = next block address
byte[] addrBuf = new byte[4];
_ = _stream.Read(addrBuf, 0, 4);
uint nextAddress = BitConverter.ToUInt32(addrBuf, 0);
int bufferOffset = 0;
int remaining = size;
while (remaining > 0)
{
if (nextAddress == 0)
{
// Last block — read remaining data directly
int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position));
if (toRead <= 0) break;
_ = _stream.Read(buffer, bufferOffset, toRead);
remaining = 0;
}
else
{
// Read data portion of this block (BlockSize - 4 bytes)
int dataInBlock = (int)BlockSize - 4;
int toRead = Math.Min(dataInBlock, remaining);
_ = _stream.Read(buffer, bufferOffset, toRead);
bufferOffset += toRead;
remaining -= toRead;
if (remaining > 0)
{
// Follow chain to next block
if (nextAddress >= (uint)_stream.Length) break;
_stream.Seek(nextAddress, SeekOrigin.Begin);
// Read next block's chain pointer
_ = _stream.Read(addrBuf, 0, 4);
nextAddress = BitConverter.ToUInt32(addrBuf, 0);
}
}
}
return buffer;
}
/// <summary>
/// Recursively reads the B-tree directory and indexes all files.
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
/// </summary>
private void ReadDirectory(uint sectorOffset)
{
if (_stream == null) return;
if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length)
return;
// Read the directory header (B-tree node)
byte[]? nodeData;
lock (_lock)
{
nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE);
}
if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE)
return;
// Parse branches (62 × uint32)
uint[] branches = new uint[BTREE_BRANCH_COUNT];
for (int i = 0; i < BTREE_BRANCH_COUNT; i++)
branches[i] = BitConverter.ToUInt32(nodeData, i * 4);
// Parse entry count
int countOffset = BTREE_BRANCH_COUNT * 4; // 248
uint entryCount = BitConverter.ToUInt32(nodeData, countOffset);
if (entryCount > BTREE_MAX_ENTRIES)
return; // Invalid node
// Parse entries
int entriesOffset = countOffset + 4; // 252
var entries = new DatBTreeEntry[entryCount];
for (int i = 0; i < entryCount; i++)
{
int eOff = entriesOffset + i * BTREE_ENTRY_SIZE;
entries[i] = new DatBTreeEntry
{
BitFlags = BitConverter.ToUInt32(nodeData, eOff),
ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4),
FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8),
FileSize = BitConverter.ToUInt32(nodeData, eOff + 12),
};
}
// Recurse into child directories (if branches[0] != 0, node has children)
if (branches[0] != 0)
{
for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++)
{
if (branches[i] != 0)
ReadDirectory(branches[i]);
}
}
// Add entries to the file index
for (int i = 0; i < entryCount; i++)
{
if (entries[i].ObjectId != 0)
_allFiles[entries[i].ObjectId] = entries[i];
}
}
/// <summary>
/// Finds a file by ID. O(1) lookup from the pre-built index.
/// </summary>
public DatBTreeEntry? FindFile(uint fileId)
{
if (!IsLoaded) return null;
_allFiles.TryGetValue(fileId, out var entry);
return entry;
}
/// <summary>
/// Reads file data for a given entry.
/// </summary>
public byte[]? ReadFileData(DatBTreeEntry? entry)
{
if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null)
return null;
lock (_lock)
{
return ReadDatData(entry.FileOffset, (int)entry.FileSize);
}
}
/// <summary>Convenience: find by id then read.</summary>
public byte[]? GetFileData(uint fileId)
{
var entry = FindFile(fileId);
return entry != null ? ReadFileData(entry) : null;
}
/// <summary>Returns (fileId, storedSize) for every indexed file whose id is in [lo, hi], sorted by size desc.</summary>
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
{
var list = new List<(uint, uint)>();
if (!IsLoaded) return list;
foreach (var kv in _allFiles)
if (kv.Key >= lo && kv.Key <= hi)
list.Add((kv.Key, kv.Value.FileSize));
list.Sort((a, b) => b.Item2.CompareTo(a.Item2));
return list;
}
/// <summary>
/// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index.
/// This avoids the sequential scan gap cutoff that misses cells in large dungeons.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var cellIds = new List<uint>();
if (!IsLoaded) return cellIds;
uint prefix = landblockKey << 16;
foreach (var id in _allFiles.Keys)
{
if ((id & 0xFFFF0000) != prefix) continue;
uint cell = id & 0xFFFF;
if (cell >= 0x0100 && cell <= 0xFFFD)
cellIds.Add(id);
}
return cellIds;
}
/// <summary>
/// Returns sample file IDs from the index for diagnostics.
/// </summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
foreach (var kvp in _allFiles)
{
ids.Add(kvp.Key);
if (ids.Count >= maxCount) break;
}
return ids;
}
/// <summary>Closes the underlying file handle and clears the index.</summary>
/// <summary>Closes the underlying file handle and drops the cached directory nodes.</summary>
public void Close()
{
_stream?.Dispose();
_stream = null;
IsLoaded = false;
_allFiles.Clear();
lock (_gate) CloseLocked();
}
/// <inheritdoc/>
@ -373,15 +170,266 @@ public class DatDatabase : IDisposable
GC.SuppressFinalize(this);
}
private void CloseLocked()
{
IsLoaded = false;
_file?.Dispose();
_file = null;
_length = 0;
RecordCount = 0;
_interior.Clear();
_leafMap.Clear();
_leafOrder.Clear();
}
// ---------------------------------------------------------------- lookups
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
public DatBTreeEntry? FindFile(uint fileId)
{
lock (_gate)
{
if (!IsLoaded) return null;
uint at = BTreeRoot;
for (int depth = 0; depth < DepthLimit && at != 0; depth++)
{
Node? n = GetNode(at);
if (n == null) return null;
int i = LowerBound(n.Entries, fileId);
if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i];
if (n.Children == null) return null;
at = n.Children[i];
}
return null;
}
}
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
public byte[]? ReadFileData(DatBTreeEntry? entry)
{
if (entry == null) return null;
lock (_gate)
{
if (!IsLoaded) return null;
if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; }
var data = new byte[entry.FileSize];
if (ReadChain(entry.FileOffset, data) != data.Length)
{
Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken");
return null;
}
return data;
}
}
/// <summary>Convenience: find by id then read.</summary>
public byte[]? GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
/// <summary>
/// (fileId, storedSize) for every file whose id is in [lo, hi], largest first
/// (ties by ascending id).
/// </summary>
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
{
var found = new List<DatBTreeEntry>();
lock (_gate)
{
if (IsLoaded && lo <= hi) Collect(BTreeRoot, lo, hi, found, 0);
}
var result = new List<(uint id, uint size)>(found.Count);
foreach (var e in found) result.Add((e.ObjectId, e.FileSize));
result.Sort((a, b) => a.size != b.size ? b.size.CompareTo(a.size) : a.id.CompareTo(b.id));
return result;
}
/// <summary>
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
/// <paramref name="landblockKey"/> (0xXXYY), ascending.
/// </summary>
public List<uint> GetLandblockCellIds(uint landblockKey)
{
var found = new List<DatBTreeEntry>();
lock (_gate)
{
if (IsLoaded) Collect(BTreeRoot, (landblockKey << 16) | 0x0100, (landblockKey << 16) | 0xFFFD, found, 0);
}
var ids = new List<uint>(found.Count);
foreach (var e in found) ids.Add(e.ObjectId);
return ids;
}
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
public List<uint> GetSampleIds(int maxCount = 20)
{
var ids = new List<uint>();
if (maxCount <= 0) return ids;
var found = new List<DatBTreeEntry>();
lock (_gate)
{
if (IsLoaded) Collect(BTreeRoot, 0, uint.MaxValue, found, 0, maxCount);
}
foreach (var e in found) ids.Add(e.ObjectId);
return ids;
}
// In-order walk of the subtree at `at`, adding the entries with ids in
// [lo, hi] (stops once `into` holds `limit`). Caller holds _gate.
private void Collect(uint at, uint lo, uint hi, List<DatBTreeEntry> into, int depth, int limit = int.MaxValue)
{
if (at == 0 || depth >= DepthLimit || into.Count >= limit) return;
Node? n = GetNode(at);
if (n == null) return;
var e = n.Entries;
for (int i = 0; i <= e.Length; i++)
{
if (n.Children != null)
{
// Child i holds the ids between e[i-1] and e[i].
bool aboveLo = i == e.Length || e[i].ObjectId > lo;
bool belowHi = i == 0 || e[i - 1].ObjectId < hi;
if (aboveLo && belowHi) Collect(n.Children[i], lo, hi, into, depth + 1, limit);
}
if (i == e.Length || into.Count >= limit) break;
uint id = e[i].ObjectId;
if (id > hi) break;
if (id >= lo) into.Add(e[i]);
}
}
// ---------------------------------------------------------------- nodes
private static int LowerBound(DatBTreeEntry[] e, uint id)
{
int a = 0, b = e.Length;
while (a < b)
{
int m = (a + b) >> 1;
if (e[m].ObjectId < id) a = m + 1; else b = m;
}
return a;
}
// Cached node: interior nodes kept (capped), leaves in a small LRU. Caller holds _gate.
private Node? GetNode(uint at)
{
if (_interior.TryGetValue(at, out Node? n)) return n;
if (_leafMap.TryGetValue(at, out var hit))
{
_leafOrder.Remove(hit);
_leafOrder.AddFirst(hit);
return hit.Value.Node;
}
n = ParseNode(at);
if (n == null) return null;
if (n.Children != null)
{
if (_interior.Count < InteriorCap) _interior[at] = n;
}
else
{
if (_leafMap.Count >= LeafLruSize && _leafOrder.Last != null)
{
_leafMap.Remove(_leafOrder.Last.Value.At);
_leafOrder.RemoveLast();
}
_leafMap[at] = _leafOrder.AddFirst((at, n));
}
return n;
}
private Node? ParseNode(uint at)
{
int got = ReadChain(at, _nodeBuf);
if (got < EntriesOffset) return null;
ReadOnlySpan<byte> s = _nodeBuf;
int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null;
var entries = new DatBTreeEntry[count];
for (int i = 0; i < count; i++)
{
var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes);
entries[i] = new DatBTreeEntry
{
BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r),
ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)),
FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)),
FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)),
};
}
uint[]? children = null;
if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0)
{
children = new uint[count + 1];
for (int i = 0; i <= count; i++) children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4));
}
return new Node { Children = children, Entries = entries };
}
// Entry counts under `at`, reading only each node's child table and count. Caller holds _gate.
private int CountUnder(uint at, int depth)
{
if (at == 0 || depth >= DepthLimit) return 0;
Span<byte> head = stackalloc byte[EntriesOffset];
if (ReadChain(at, head) != EntriesOffset) return 0;
int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset));
if (count < 0 || count > MaxEntriesPerNode) return 0;
int total = count;
if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0)
{
Span<uint> kids = stackalloc uint[count + 1];
for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4));
for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1);
}
return total;
}
// ---------------------------------------------------------------- blocks
// Copies the block chain starting at byte offset `first` into `dest` and
// returns how many bytes it filled: dest.Length, or less when the chain
// ends (a 0 link) first; -1 when a link points outside the file.
private int ReadChain(uint first, Span<byte> dest)
{
int payload = (int)BlockSize - 4;
long block = first;
int done = 0;
Span<byte> link = stackalloc byte[4];
while (done < dest.Length)
{
if (block == 0) return done;
if (block + 4 > _length) return -1;
int take = Math.Min(payload, dest.Length - done);
if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1;
done += take;
block = BinaryPrimitives.ReadUInt32LittleEndian(link);
}
return done;
}
private bool ReadAt(long offset, Span<byte> into)
{
if (_file == null || offset < 0 || offset + into.Length > _length) return false;
_file.Position = offset;
int got = 0;
while (got < into.Length)
{
int n = _file.Read(into.Slice(got));
if (n <= 0) return false;
got += n;
}
return true;
}
private void Log(string msg)
{
string line = $"[DatDB] {msg}";
string line = "[DatDB] " + msg;
System.Diagnostics.Debug.WriteLine(line);
if (DiagLog.Count < 100) DiagLog.Add(line);
}
}
/// <summary>Indexed B-tree entry for one file inside a .dat archive.</summary>
/// <summary>One directory entry of a .dat archive.</summary>
public class DatBTreeEntry
{
/// <summary>Raw flag bits from the B-tree.</summary>

View file

@ -1,442 +1,172 @@
// #region License
// /*
// Microsoft Public License (Ms-PL)
// MonoGame - Copyright © 2009 The MonoGame Team
//
// All rights reserved.
//
// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not
// accept the license, do not use the software.
//
// 1. Definitions
// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under
// U.S. copyright law.
//
// A "contribution" is the original software, or any additions or changes to the software.
// A "contributor" is any person that distributes its contribution under this license.
// "Licensed patents" are a contributor's patent claims that read directly on its contribution.
//
// 2. Grant of Rights
// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.
// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3,
// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.
//
// 3. Conditions and Limitations
// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software,
// your patent license from such contributor to the software ends automatically.
// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution
// notices that are present in the software.
// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including
// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object
// code form, you may only do so under a license that complies with this license.
// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees
// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent
// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular
// purpose and non-infringement.
// */
// #endregion License
// ============================================================================
// RynthCore.StatusAgent - Dat/DxtUtil.cs
// DXT1 / DXT3 / DXT5 (BC1 / BC2 / BC3) block decompression to RGBA bytes.
// Written for RynthCore (MIT) on 2026-10-05 from the public S3TC / DirectX
// block-compression format description:
//
// Images are stored as 4 x 4 pixel blocks, left to right, top to bottom.
// Colour block (8 bytes, the whole of a DXT1 block and the second half of
// a DXT3/DXT5 block): two RGB565 end-point colours c0, c1 (uint16 each),
// then 16 two-bit indices, one per pixel, row by row, low bits first.
// DXT1, c0 > c1: index 2 = (2*c0 + c1) / 3, index 3 = (c0 + 2*c1) / 3
// DXT1, c0 <= c1: index 2 = (c0 + c1) / 2, index 3 = transparent black
// DXT3 / DXT5 always use the four-colour form.
// DXT3 alpha (first 8 bytes): 16 explicit four-bit alphas, low nibble first.
// DXT5 alpha (first 8 bytes): end points a0, a1 (one byte each), then 16
// three-bit indices (48 bits, little-endian, low bits first):
// a0 > a1: indices 2..7 = 6 interpolated values between a0 and a1
// a0 <= a1: indices 2..5 = 4 interpolated values, 6 = 0, 7 = 255
//
// Used by the agent's IconDecoder and, linked, by the engine's
// UI/ScriptWindows/AcIconDecoder.cs (and RynthSuite's ScriptWindows tests).
// ============================================================================
namespace ACE.DatLoader
using System;
using System.IO;
namespace RynthCore.Imaging
{
using System.IO;
/// <summary>DXT1/3/5 decompression; output is width * height * 4 bytes, R, G, B, A.</summary>
public static class DxtUtil
{
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height)
internal static byte[] DecompressDxt1(byte[] imageData, int width, int height) =>
Decompress(imageData, width, height, BlockKind.Dxt1);
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height) =>
DecompressDxt1(ReadAll(imageStream), width, height);
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height) =>
Decompress(imageData, width, height, BlockKind.Dxt3);
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height) =>
DecompressDxt3(ReadAll(imageStream), width, height);
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height) =>
Decompress(imageData, width, height, BlockKind.Dxt5);
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height) =>
DecompressDxt5(ReadAll(imageStream), width, height);
private enum BlockKind { Dxt1, Dxt3, Dxt5 }
private static byte[] ReadAll(Stream s)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt1(imageStream, width, height);
using var ms = new MemoryStream();
s.CopyTo(ms);
return ms.ToArray();
}
internal static byte[] DecompressDxt1(Stream imageStream, int width, int height)
private static byte[] Decompress(byte[] src, int width, int height, BlockKind kind)
{
byte[] imageData = new byte[width * height * 4];
if (width <= 0 || height <= 0) return Array.Empty<byte>();
var rgba = new byte[width * height * 4];
int blockBytes = kind == BlockKind.Dxt1 ? 8 : 16;
int blocksX = (width + 3) / 4, blocksY = (height + 3) / 4;
using (BinaryReader imageReader = new BinaryReader(imageStream))
Span<byte> palette = stackalloc byte[16]; // 4 colours x RGBA
Span<byte> alpha = stackalloc byte[16]; // per pixel (DXT3/5)
Span<byte> alphaTable = stackalloc byte[8]; // DXT5 end points + interpolated
int at = 0;
for (int by = 0; by < blocksY; by++)
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
for (int bx = 0; bx < blocksX; bx++, at += blockBytes)
{
for (int x = 0; x < blockCountX; x++)
if (at + blockBytes > src.Length) return rgba; // short data: the rest stays clear
int colourAt = at;
bool hasAlphaBlock = kind != BlockKind.Dxt1;
if (kind == BlockKind.Dxt3)
{
DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
if (c0 > c1)
{
switch (index)
for (int i = 0; i < 16; i++)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
int nibble = (src[at + (i >> 1)] >> ((i & 1) * 4)) & 0xF;
alpha[i] = (byte)(nibble * 17);
}
colourAt += 8;
}
else if (kind == BlockKind.Dxt5)
{
byte a0 = src[at], a1 = src[at + 1];
alphaTable[0] = a0;
alphaTable[1] = a1;
if (a0 > a1)
{
for (int i = 1; i <= 6; i++) alphaTable[i + 1] = (byte)(((7 - i) * a0 + i * a1) / 7);
}
else
{
for (int i = 1; i <= 4; i++) alphaTable[i + 1] = (byte)(((5 - i) * a0 + i * a1) / 5);
alphaTable[6] = 0;
alphaTable[7] = 255;
}
ulong bits = 0;
for (int i = 0; i < 6; i++) bits |= (ulong)src[at + 2 + i] << (8 * i);
for (int i = 0; i < 16; i++) alpha[i] = alphaTable[(int)((bits >> (3 * i)) & 7)];
colourAt += 8;
}
ushort c0 = (ushort)(src[colourAt] | (src[colourAt + 1] << 8));
ushort c1 = (ushort)(src[colourAt + 2] | (src[colourAt + 3] << 8));
Expand565(c0, palette.Slice(0, 4));
Expand565(c1, palette.Slice(4, 4));
if (kind != BlockKind.Dxt1 || c0 > c1)
{
for (int ch = 0; ch < 3; ch++)
{
palette[8 + ch] = (byte)((2 * palette[ch] + palette[4 + ch]) / 3);
palette[12 + ch] = (byte)((palette[ch] + 2 * palette[4 + ch]) / 3);
}
palette[11] = 255;
palette[15] = 255;
}
else
{
switch (index)
for (int ch = 0; ch < 3; ch++)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((r0 + r1) / 2);
g = (byte)((g0 + g1) / 2);
b = (byte)((b0 + b1) / 2);
break;
case 3:
r = 0;
g = 0;
b = 0;
a = 0;
break;
palette[8 + ch] = (byte)((palette[ch] + palette[4 + ch]) / 2);
palette[12 + ch] = 0;
}
palette[11] = 255;
palette[15] = 0;
}
uint indices = (uint)(src[colourAt + 4] | (src[colourAt + 5] << 8) | (src[colourAt + 6] << 16) | (src[colourAt + 7] << 24));
for (int py = 0; py < 4; py++)
{
int y = by * 4 + py;
if (y >= height) break;
for (int px = 0; px < 4; px++)
{
int x = bx * 4 + px;
if (x >= width) continue;
int p = py * 4 + px;
int idx = (int)((indices >> (2 * p)) & 3);
int o = (y * width + x) * 4;
rgba[o] = palette[idx * 4];
rgba[o + 1] = palette[idx * 4 + 1];
rgba[o + 2] = palette[idx * 4 + 2];
rgba[o + 3] = hasAlphaBlock ? alpha[p] : palette[idx * 4 + 3];
}
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
return rgba;
}
internal static byte[] DecompressDxt3(byte[] imageData, int width, int height)
// RGB565 to 8-bit channels: v * 255 / max, rounded with the (t + t / 2^n) / 2^n
// approximation (t = v * 255 + 2^(n-1)), so the output matches, bit for bit,
// the decoder this file replaced.
private static void Expand565(ushort c, Span<byte> rgba)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt3(imageStream, width, height);
rgba[0] = Scale((c >> 11) & 0x1F, 5);
rgba[1] = Scale((c >> 5) & 0x3F, 6);
rgba[2] = Scale(c & 0x1F, 5);
rgba[3] = 255;
}
internal static byte[] DecompressDxt3(Stream imageStream, int width, int height)
private static byte Scale(int v, int bits)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte a0 = imageReader.ReadByte();
byte a1 = imageReader.ReadByte();
byte a2 = imageReader.ReadByte();
byte a3 = imageReader.ReadByte();
byte a4 = imageReader.ReadByte();
byte a5 = imageReader.ReadByte();
byte a6 = imageReader.ReadByte();
byte a7 = imageReader.ReadByte();
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
int alphaIndex = 0;
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 0;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
switch (alphaIndex)
{
case 0:
a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4));
break;
case 1:
a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4));
break;
case 2:
a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4));
break;
case 3:
a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4));
break;
case 4:
a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4));
break;
case 5:
a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4));
break;
case 6:
a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4));
break;
case 7:
a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4));
break;
case 8:
a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4));
break;
case 9:
a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4));
break;
case 10:
a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4));
break;
case 11:
a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4));
break;
case 12:
a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4));
break;
case 13:
a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4));
break;
case 14:
a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4));
break;
case 15:
a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4));
break;
}
++alphaIndex;
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
internal static byte[] DecompressDxt5(byte[] imageData, int width, int height)
{
using (MemoryStream imageStream = new MemoryStream(imageData))
return DecompressDxt5(imageStream, width, height);
}
internal static byte[] DecompressDxt5(Stream imageStream, int width, int height)
{
byte[] imageData = new byte[width * height * 4];
using (BinaryReader imageReader = new BinaryReader(imageStream))
{
int blockCountX = (width + 3) / 4;
int blockCountY = (height + 3) / 4;
for (int y = 0; y < blockCountY; y++)
{
for (int x = 0; x < blockCountX; x++)
{
DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData);
}
}
}
return imageData;
}
private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData)
{
byte alpha0 = imageReader.ReadByte();
byte alpha1 = imageReader.ReadByte();
ulong alphaMask = (ulong)imageReader.ReadByte();
alphaMask += (ulong)imageReader.ReadByte() << 8;
alphaMask += (ulong)imageReader.ReadByte() << 16;
alphaMask += (ulong)imageReader.ReadByte() << 24;
alphaMask += (ulong)imageReader.ReadByte() << 32;
alphaMask += (ulong)imageReader.ReadByte() << 40;
ushort c0 = imageReader.ReadUInt16();
ushort c1 = imageReader.ReadUInt16();
byte r0, g0, b0;
byte r1, g1, b1;
ConvertRgb565ToRgb888(c0, out r0, out g0, out b0);
ConvertRgb565ToRgb888(c1, out r1, out g1, out b1);
uint lookupTable = imageReader.ReadUInt32();
for (int blockY = 0; blockY < 4; blockY++)
{
for (int blockX = 0; blockX < 4; blockX++)
{
byte r = 0, g = 0, b = 0, a = 255;
uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03;
uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07);
if (alphaIndex == 0)
{
a = alpha0;
}
else if (alphaIndex == 1)
{
a = alpha1;
}
else if (alpha0 > alpha1)
{
a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7);
}
else if (alphaIndex == 6)
{
a = 0;
}
else if (alphaIndex == 7)
{
a = 0xff;
}
else
{
a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5);
}
switch (index)
{
case 0:
r = r0;
g = g0;
b = b0;
break;
case 1:
r = r1;
g = g1;
b = b1;
break;
case 2:
r = (byte)((2 * r0 + r1) / 3);
g = (byte)((2 * g0 + g1) / 3);
b = (byte)((2 * b0 + b1) / 3);
break;
case 3:
r = (byte)((r0 + 2 * r1) / 3);
g = (byte)((g0 + 2 * g1) / 3);
b = (byte)((b0 + 2 * b1) / 3);
break;
}
int px = (x << 2) + blockX;
int py = (y << 2) + blockY;
if ((px < width) && (py < height))
{
int offset = ((py * width) + px) << 2;
imageData[offset] = r;
imageData[offset + 1] = g;
imageData[offset + 2] = b;
imageData[offset + 3] = a;
}
}
}
}
private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b)
{
int temp;
temp = (color >> 11) * 255 + 16;
r = (byte)((temp / 32 + temp) / 32);
temp = ((color & 0x07E0) >> 5) * 255 + 32;
g = (byte)((temp / 64 + temp) / 64);
temp = (color & 0x001F) * 255 + 16;
b = (byte)((temp / 32 + temp) / 32);
int t = v * 255 + (1 << (bits - 1));
return (byte)(((t >> bits) + t) >> bits);
}
}
}

View file

@ -1,14 +1,26 @@
using ACE.DatLoader;
// ============================================================================
// RynthCore.StatusAgent - Dat/IconDecoder.cs
// An item icon (a 0x06 Texture in client_portal.dat) as RGBA pixels, for the
// phone remote. Written for RynthCore (MIT) on 2026-10-05.
//
// Written from the Texture file layout as Chorizite's DatReaderWriter (MIT,
// see the notice in Dat/DatDatabase.cs) describes it (RenderSurface and
// Palette) and the Direct3D pixel-format definitions:
// Texture 0x06: id u32, data category u32, width i32, height i32,
// format u32, length i32, data[length], and for the palette
// formats (P8, INDEX16) the default palette id u32.
// Palette 0x04: id u32, colour count i32, colours (u32 A8R8G8B8 each).
// Formats in the retail portal dat: A8R8G8B8, R8G8B8, R5G6B5, A4R4G4B4, A8,
// P8, INDEX16, the landscape R8G8B8 / alpha customs and DXT1/3/5 (DxtUtil.cs).
// Raw JPEG textures are not decoded.
// ============================================================================
using RynthCore.Imaging;
using RynthCore2.TerrainData;
namespace RynthCore.StatusAgent;
/// <summary>
/// Decodes an AC item ICON to RGBA pixels. An item's icon DID (PWD _iconID, range 0x06xxxxxx) points
/// straight at a 0x06 Texture in portal.dat, so this is the Texture path only — trimmed from
/// AcClientReborn's AcTextureDecoder (no Surface/SurfaceTexture/clothing). Format byte-layout + the
/// format constants are ported verbatim from ACEmulator's DatLoader.
/// </summary>
/// <summary>Decodes an AC item icon (a 0x06 Texture in portal.dat) to RGBA pixels.</summary>
internal sealed class IconDecoder
{
private readonly DatDatabase _portal;
@ -22,94 +34,113 @@ internal sealed class IconDecoder
public byte[] Pixels = System.Array.Empty<byte>();
}
// Palette (0x04): Id(u32), Colors(List<uint>: i32 count + u32[] ARGB).
private uint[]? LoadPalette(uint paletteId)
{
byte[]? data = _portal.GetFileData(paletteId);
if (data == null || data.Length < 8) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32();
int n = r.ReadInt32();
if (n <= 0 || n > 100000) return null;
var pal = new uint[n];
for (int i = 0; i < n; i++)
{
if (ms.Position + 4 > ms.Length) { System.Array.Resize(ref pal, i); break; }
pal[i] = r.ReadUInt32();
}
return pal;
}
private const uint A8R8G8B8 = 0x15, R8G8B8 = 0x14, R5G6B5 = 0x17, A4R4G4B4 = 0x1A, A8 = 0x1C,
P8 = 0x29, Index16 = 0x65, LscapeR8G8B8 = 0xF3, LscapeAlpha = 0xF4,
Dxt1 = 0x31545844, Dxt3 = 0x33545844, Dxt5 = 0x35545844;
// Texture (0x06): Id(u32),Unknown(i32),Width(i32),Height(i32),Format(u32),Length(i32),Source[Length],
// if INDEX16/P8: DefaultPaletteId(u32).
/// <summary>The texture <paramref name="textureId"/> as RGBA, or null (missing, unsupported or damaged).</summary>
public Rgba? Decode(uint textureId)
{
byte[]? data = _portal.GetFileData(textureId);
if (data == null || data.Length < 24) return null;
using var ms = new MemoryStream(data);
using var r = new BinaryReader(ms);
r.ReadUInt32(); r.ReadInt32();
int w = r.ReadInt32(), h = r.ReadInt32();
uint fmt = r.ReadUInt32();
int len = r.ReadInt32();
if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || len < 0 || ms.Position + len > ms.Length) return null;
byte[] src = r.ReadBytes(len);
uint defPal = 0;
if (fmt == 101 /*INDEX16*/ || fmt == 41 /*P8*/) { if (ms.Position + 4 <= ms.Length) defPal = r.ReadUInt32(); }
var rgba = new byte[w * h * 4];
void Px(int i, int rr, int gg, int bb, int aa) { int o = i * 4; rgba[o] = (byte)rr; rgba[o + 1] = (byte)gg; rgba[o + 2] = (byte)bb; rgba[o + 3] = (byte)aa; }
switch (fmt)
try
{
case 827611204: return Wrap(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1
case 861165636: return Wrap(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3
case 894720068: return Wrap(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5
case 20: // R8G8B8 (stored B,G,R)
for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
break;
case 243: // CUSTOM_LSCAPE_R8G8B8 (stored R,G,B)
for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
break;
case 21: // A8R8G8B8
case 22: // X8R8G8B8
for (int i = 0; i < w * h && i * 4 + 3 < src.Length; i++)
{ int b = src[i * 4], g = src[i * 4 + 1], rr = src[i * 4 + 2], a = fmt == 22 ? 255 : src[i * 4 + 3]; Px(i, rr, g, b, a); }
break;
case 23: // R5G6B5
for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++)
{ ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255); }
break;
case 26: // A4R4G4B4
for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++)
{ ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17); }
break;
case 28: // A8 (greyscale)
case 244: // LSCAPE_ALPHA
for (int i = 0; i < w * h && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255);
break;
case 101: // INDEX16
case 41: // P8
byte[]? file = _portal.GetFileData(textureId);
if (file == null || file.Length < 24) return null;
var r = new ReadOnlySpan<byte>(file);
int w = I32(r, 8), h = I32(r, 12);
uint format = U32(r, 16);
int length = I32(r, 20);
if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || length < 0 || 24L + length > file.Length) return null;
var src = r.Slice(24, length);
int n = w * h;
switch (format)
{
uint[]? pal = LoadPalette(defPal);
if (pal == null || pal.Length == 0) return null;
bool p8 = fmt == 41;
for (int i = 0; i < w * h; i++)
{
int idx;
if (p8) { if (i >= src.Length) break; idx = src[i]; }
else { if (i * 2 + 1 >= src.Length) break; idx = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); }
uint cc = pal[idx % pal.Length];
Px(i, (int)((cc >> 16) & 0xFF), (int)((cc >> 8) & 0xFF), (int)(cc & 0xFF), (int)((cc >> 24) & 0xFF));
}
break;
case Dxt1: return Make(w, h, DxtUtil.DecompressDxt1(src.ToArray(), w, h));
case Dxt3: return Make(w, h, DxtUtil.DecompressDxt3(src.ToArray(), w, h));
case Dxt5: return Make(w, h, DxtUtil.DecompressDxt5(src.ToArray(), w, h));
}
default:
return null; // unhandled format
var px = new byte[n * 4];
switch (format)
{
case A8R8G8B8: // B, G, R, A in memory
if (length < n * 4) return null;
for (int i = 0; i < n; i++) Put(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]);
break;
case R8G8B8: // B, G, R
if (length < n * 3) return null;
for (int i = 0; i < n; i++) Put(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255);
break;
case LscapeR8G8B8: // R, G, B
if (length < n * 3) return null;
for (int i = 0; i < n; i++) Put(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255);
break;
case R5G6B5:
if (length < n * 2) return null;
for (int i = 0; i < n; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
// Top bits only (low bits left 0), as the decoder this replaced did.
Put(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255);
}
break;
case A4R4G4B4:
if (length < n * 2) return null;
for (int i = 0; i < n; i++)
{
int v = src[i * 2] | (src[i * 2 + 1] << 8);
Put(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17));
}
break;
case A8: // one byte a pixel, shown as an opaque grey level
case LscapeAlpha:
if (length < n) return null;
for (int i = 0; i < n; i++) Put(px, i, src[i], src[i], src[i], 255);
break;
case P8:
case Index16:
{
int bpp = format == P8 ? 1 : 2;
if (length < n * bpp || 24L + length + 4 > file.Length) return null;
uint[]? palette = LoadPalette(U32(r, 24 + length));
if (palette == null) return null;
for (int i = 0; i < n; i++)
{
int idx = bpp == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8);
uint argb = idx < palette.Length ? palette[idx] : 0;
Put(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24));
}
break;
}
default:
return null;
}
return Make(w, h, px);
}
catch
{
return null;
}
return new Rgba { Width = w, Height = h, Pixels = rgba };
}
private static Rgba Wrap(byte[] rgba, int w, int h) => new Rgba { Width = w, Height = h, Pixels = rgba }; // DxtUtil already RGBA
// A 0x04 Palette's colours (A8R8G8B8), or null.
private uint[]? LoadPalette(uint paletteId)
{
byte[]? file = _portal.GetFileData(paletteId);
if (file == null || file.Length < 8) return null;
int count = I32(file, 4);
if (count < 0 || 8L + count * 4L > file.Length) return null;
var colours = new uint[count];
for (int i = 0; i < count; i++) colours[i] = U32(file, 8 + i * 4);
return colours;
}
private static void Put(byte[] px, int i, byte r, byte g, byte b, byte a)
{
px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a;
}
private static Rgba Make(int w, int h, byte[] rgba) => new() { Width = w, Height = h, Pixels = rgba };
private static int I32(ReadOnlySpan<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(s.Slice(at));
private static uint U32(ReadOnlySpan<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at));
}

View file

@ -28,6 +28,11 @@ internal sealed class LocalStatusServer : IDisposable
private readonly string? _statusDir; // GET /inventory reads RynthCore.<pid>.inventory.json from here
private readonly IconService? _icons; // GET /icon?did=N (portal.dat → PNG); null = disabled
private readonly MapService? _maps; // GET /maps + /map?lb&layer (baked dungeon .bin → PNG); null = disabled
private readonly WorldMapService? _worldMap; // GET /worldmap (landscape map from cell.dat, JPEG); null = disabled
private readonly NavAtlasService? _navAtlas; // GET /nav/search (RynthNav's Atlas, the Travel tab); null = disabled
// pid -> the plugin reports raiseXp, from the last status cycle (UpdateRaiseClients). A raise is accepted only
// for a client in here (POST /command action "raise"); everything else ignores it.
private volatile IReadOnlyDictionary<int, bool> _raiseClients = new Dictionary<int, bool>();
private volatile byte[] _latest =
Encoding.UTF8.GetBytes("{\"schema\":\"rynthcore.status-agent/1\",\"clientCount\":0,\"clients\":[]}");
private CancellationTokenSource? _cts;
@ -43,7 +48,8 @@ internal sealed class LocalStatusServer : IDisposable
bool enableStream = false, int streamQuality = 55, int streamIntervalMs = 400,
WebRtcVideoService? video = null, VideoSocketService? videoSocket = null,
RunArchive? runArchive = null, string? statusDirectory = null,
IconService? icons = null, MapService? maps = null)
IconService? icons = null, MapService? maps = null, WorldMapService? worldMap = null,
NavAtlasService? navAtlas = null)
{
_prefix = prefix.EndsWith('/') ? prefix : prefix + "/";
_token = string.IsNullOrWhiteSpace(token) ? null : token;
@ -57,6 +63,8 @@ internal sealed class LocalStatusServer : IDisposable
_statusDir = string.IsNullOrWhiteSpace(statusDirectory) ? null : statusDirectory;
_icons = icons;
_maps = maps;
_worldMap = worldMap;
_navAtlas = navAtlas;
_listener.Prefixes.Add(_prefix);
}
@ -73,6 +81,15 @@ internal sealed class LocalStatusServer : IDisposable
}
}
/// <summary>The clients the last cycle read, and which take the raise command (thread-safe swap).</summary>
public void UpdateRaiseClients(IEnumerable<ClientStatus> clients)
{
var map = new Dictionary<int, bool>();
foreach (var c in clients)
if (c.Pid > 0 && c.Source == "status-file" && c.State != "dead") map[c.Pid] = c.RaiseXp;
_raiseClients = map;
}
public bool TryStart(out string error)
{
// Never serve without a token, loopback included: every route but /healthz is behind it.
@ -285,7 +302,8 @@ internal sealed class LocalStatusServer : IDisposable
foreach (var e in entries)
payload.Maps.Add(new MapEntryDto
{
Landblock = e.Landblock.ToString("X8"),
// Full "XXYY0000" form: what DrakRemote matches a client's landblock against.
Landblock = RemoteParity.LandblockFull(e.Landblock.ToString("X8")),
Layer = e.Layer, Bytes = e.Bytes, Mtime = e.MtimeUtc,
W = e.W, H = e.H, XMin = e.XMin, YMin = e.YMin,
Name = "Dungeon " + (e.Landblock & 0xFFFF).ToString("X4"),
@ -380,8 +398,8 @@ internal sealed class LocalStatusServer : IDisposable
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
if (_token != null && !Authorized(req))
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
if (!uint.TryParse(req.QueryString["lb"], System.Globalization.NumberStyles.HexNumber,
System.Globalization.CultureInfo.InvariantCulture, out uint lb)
// lb in either form: "00005A48" (the file name) or "5A480000" (what /maps lists and the app sends).
if (!RemoteParity.TryLandblockShort(req.QueryString["lb"], out uint lb)
|| !int.TryParse(req.QueryString["layer"], out int layer))
{ Write(res, 400, "application/json", "{\"error\":\"lb (hex) and layer required\"}"u8.ToArray()); return; }
var r = _maps?.GetPng(lb, layer);
@ -402,6 +420,68 @@ internal sealed class LocalStatusServer : IDisposable
return;
}
// ── Character sheet: GET /character?pid=N — attributes, vitals, skills (the phone's Skills tab) ──
if (path == "/character" || path == "/character.json")
{
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
if (_token != null && !Authorized(req))
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
int cpid = int.TryParse(req.QueryString["pid"], out int cp) ? cp : 0;
if (cpid <= 0)
{ Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; }
byte[]? sheet = ReadClientFile(cpid, "character");
if (sheet == null)
{ Write(res, 404, "application/json", "{\"error\":\"no character sheet from that client yet (needs the RynthRemote plugin 0.3)\"}"u8.ToArray()); return; }
res.Headers["Cache-Control"] = "no-cache";
Write(res, 200, "application/json", sheet);
return;
}
// ── Travel search: GET /nav/search?q=&type=&ns=&ew=&max= — RynthNav's Atlas, best matches first ──
if (path == "/nav/search")
{
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
if (_token != null && !Authorized(req))
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
if (_navAtlas == null || !_navAtlas.Available)
{ Write(res, 404, "application/json", "{\"error\":\"RynthNav's Atlas (NavData locations.json) isn't on this PC\"}"u8.ToArray()); return; }
var ci = System.Globalization.CultureInfo.InvariantCulture;
double? fromNs = double.TryParse(req.QueryString["ns"], System.Globalization.NumberStyles.Float, ci, out double fn) ? fn : null;
double? fromEw = double.TryParse(req.QueryString["ew"], System.Globalization.NumberStyles.Float, ci, out double fe) ? fe : null;
int max = ClampQuery(req, "max", 40, 1, 100);
Write(res, 200, "application/json", _navAtlas.SearchJson(req.QueryString["q"] ?? "", req.QueryString["type"], fromNs, fromEw, max));
return;
}
// ── Landscape map: GET /worldmap — Dereth from cell.dat, 2040 px square, 24 units a pixel, north up ──
if (path == "/worldmap" || path == "/worldmap.jpg")
{
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
{ Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; }
if (_token != null && !Authorized(req))
{ Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; }
if (_worldMap == null || !_worldMap.Available)
{ Write(res, 404, "application/json", "{\"error\":\"world map unavailable (no cell.dat on this PC)\"}"u8.ToArray()); return; }
byte[]? jpg = _worldMap.GetJpeg();
if (jpg == null)
{
res.Headers["Retry-After"] = "5";
Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"world map " + _worldMap.State + ", try again shortly\"}"));
return;
}
string wmTag = "\"worldmap-v1-" + jpg.Length + "\"";
res.Headers["X-Map-Size"] = WorldMapService.Size.ToString(System.Globalization.CultureInfo.InvariantCulture);
res.Headers["X-Map-Units-Per-Pixel"] = WorldMapService.UnitsPerPixel.ToString(System.Globalization.CultureInfo.InvariantCulture);
if (string.Equals(req.Headers["If-None-Match"], wmTag, StringComparison.Ordinal))
{ res.Headers["ETag"] = wmTag; Write(res, 304, "image/jpeg", Array.Empty<byte>()); return; }
res.Headers["Cache-Control"] = "public, max-age=604800";
res.Headers["ETag"] = wmTag;
Write(res, 200, "image/jpeg", jpg);
return;
}
if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase))
{
Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray());
@ -431,10 +511,14 @@ internal sealed class LocalStatusServer : IDisposable
"navProfile", "lootProfile", "metaProfile", "settingsProfile",
"forceRebuff", "cancelRebuff", "clearBusy", "hideUi", "sendChat",
"moveStart", "moveStop",
"moveKeepAlive", // hold-to-move protocol 2 (RynthRemote 0.4+): {"dirs":[...]} every ~200 ms while held
"setSetting", // change ONE advanced setting (value = {"key":..,"value":..}); RynthAi clamps + persists
"click", // mouse click in the stream (value = {"u":..,"v":..,"button":..}); handled by the agent (PostMessage)
"travel", // RynthNav: go somewhere (value = {"name":..,"ns":..,"ew":..}); the plugin sends /rnav go
"travelStop", // RynthNav: stop travelling (/rnav stop)
"assess", // request an Assess/Identify of one item (value = item id) — fills inventory appraisal
"raise", // spend XP / skill credits (value = {"kind","id","count","cost","nonce"}); known raise-capable pid only
"closeClient",
};
@ -488,12 +572,33 @@ internal sealed class LocalStatusServer : IDisposable
}
}
catch { }
bool clicked = ScreenCapture.TryClick(pid, u, v, button);
Write(res, clicked ? 202 : 503, "application/json",
clicked ? "{\"ok\":true}"u8.ToArray() : "{\"error\":\"click failed (window missing or minimized)\"}"u8.ToArray());
var click = ScreenCapture.TryClick(pid, u, v, button);
// One line per tap (no token, no query string): which window, where, and what happened, so a
// tap that does nothing in game can be told apart from one that never reached the window.
AgentLog.Info($"click pid={pid} u={u:0.###} v={v:0.###} {button} -> {click.Result} at {click.X},{click.Y} of {click.Width}x{click.Height}");
if (click.Result == ScreenCapture.ClickResult.Posted)
Write(res, 202, "application/json", Encoding.UTF8.GetBytes(
"{\"ok\":true,\"x\":" + click.X + ",\"y\":" + click.Y + ",\"w\":" + click.Width + ",\"h\":" + click.Height + "}"));
else
Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"click failed: " + click.Reason + "\"}"));
return;
}
// Raise spends experience, which can't be undone: only for a client this agent reads whose plugin
// takes it, and only in the fixed shape (the plugin and the engine check it all again).
if (string.Equals(action, "raise", StringComparison.OrdinalIgnoreCase))
{
int code = RemoteParity.CheckRaise(pid, value, _raiseClients, out string normalized, out string why);
if (code != 202)
{
AgentLog.Warn($"raise refused: pid={pid} {why}");
Write(res, code, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"" + why + "\"}"));
return;
}
action = "raise";
value = normalized;
}
Directory.CreateDirectory(_commandDir!);
PruneStaleCommands();
@ -507,7 +612,11 @@ internal sealed class LocalStatusServer : IDisposable
File.WriteAllText(tmp, payload, Encoding.UTF8);
File.Move(tmp, dest, overwrite: true);
AgentLog.Info($"command queued: pid={pid} {action}={value}");
// Keep-alives arrive ~5 a second per held client: debug only, so the log keeps the presses and releases.
if (string.Equals(action, "moveKeepAlive", StringComparison.OrdinalIgnoreCase))
AgentLog.Debug($"command queued: pid={pid} {action}={value}");
else
AgentLog.Info($"command queued: pid={pid} {action}={value}");
Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray());
}
catch (Exception ex)
@ -571,7 +680,7 @@ internal sealed class LocalStatusServer : IDisposable
{
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.inventory.json");
if (!File.Exists(path)) return EmptyInventory;
byte[] bytes = File.ReadAllBytes(path);
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
return bytes.Length >= 2 ? bytes : EmptyInventory;
}
catch { return EmptyInventory; }
@ -586,12 +695,26 @@ internal sealed class LocalStatusServer : IDisposable
{
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.settings.json");
if (!File.Exists(path)) return "{}"u8.ToArray();
byte[] bytes = File.ReadAllBytes(path);
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
return bytes.Length >= 2 ? bytes : "{}"u8.ToArray();
}
catch { return "{}"u8.ToArray(); }
}
/// Read RynthCore.<pid>.<kind>.json (written atomically by the RynthRemote plugin); null when absent.
private byte[]? ReadClientFile(int pid, string kind)
{
if (_statusDir == null) return null;
try
{
string path = Path.Combine(_statusDir, $"RynthCore.{pid}.{kind}.json");
if (!File.Exists(path)) return null;
byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile
return bytes.Length >= 2 ? bytes : null;
}
catch { return null; }
}
private static int ClampQuery(HttpListenerRequest req, string key, int def, int lo, int hi)
=> int.TryParse(req.QueryString[key], out int v) ? Math.Clamp(v, lo, hi) : def;

View file

@ -40,6 +40,107 @@ internal sealed class StatusFileModel
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
[JsonPropertyName("bot")] public BotSnapshot? Bot { get; set; }
// Added by the RynthRemote plugin 0.3 (DrakRemote parity): the player's enchantments (ids + seconds
// left; the agent adds names/icons from portal.dat) and where the character stands, outdoors too.
[JsonPropertyName("enchantments")] public List<EnchantmentIn>? Enchantments { get; set; }
[JsonPropertyName("opos")] public PositionIn? Opos { get; set; }
// RynthRemote 0.3: the last travel the phone asked RynthNav for (destination, what the plugin did).
[JsonPropertyName("travel")] public TravelIn? Travel { get; set; }
// RynthRemote 0.4: the phone may raise attributes, vitals and skills on this client (engine API v79,
// the client's raise senders bound, in the world). The costs ride the character sheet.
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
// RynthRemote 0.4: the hold-to-move protocol it speaks (2 = moveStart {"dir","deadmanMs"} + moveKeepAlive).
[JsonPropertyName("moveProto")] public int MoveProto { get; set; }
}
/// <summary>The plugin's record of the last phone travel: where to, and "sent" / "stopped" / "refused".</summary>
internal sealed class TravelIn
{
[JsonPropertyName("dest")] public string Dest { get; set; } = "";
[JsonPropertyName("ns")] public double? Ns { get; set; }
[JsonPropertyName("ew")] public double? Ew { get; set; }
[JsonPropertyName("state")] public string State { get; set; } = "";
[JsonPropertyName("detail")] public string Detail { get; set; } = "";
[JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; }
}
/// <summary>The phone's travel status: the plugin's record, RynthNav's latest chat note, and how far is left.</summary>
internal sealed class TravelOut
{
[JsonPropertyName("dest")] public string Dest { get; set; } = "";
[JsonPropertyName("ns")] public double? Ns { get; set; }
[JsonPropertyName("ew")] public double? Ew { get; set; }
/// <summary>sent | arrived | stopped | refused (and "unavailable" when RynthNav isn't loaded).</summary>
[JsonPropertyName("state")] public string State { get; set; } = "";
[JsonPropertyName("detail")] public string Detail { get; set; } = "";
[JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; }
/// <summary>RynthNav's latest "[RynthNav] ..." chat line, without the tag ("walking to Holtburg — ...").</summary>
[JsonPropertyName("note")] public string Note { get; set; } = "";
/// <summary>Straight-line distance left in RynthNav's units (yd); null indoors or with no target position.</summary>
[JsonPropertyName("distance")] public double? Distance { get; set; }
}
/// <summary>One enchantment as the plugin writes it: spell id + seconds left (-1 = never lapses).</summary>
internal sealed class EnchantmentIn
{
[JsonPropertyName("spellId")] public uint SpellId { get; set; }
[JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; }
}
/// <summary>Where the character stands (plugin "opos"): absolute world units, the dungeon-map frame.</summary>
internal sealed class PositionIn
{
[JsonPropertyName("cell")] public string Cell { get; set; } = "";
[JsonPropertyName("indoor")] public bool Indoor { get; set; }
[JsonPropertyName("wx")] public double Wx { get; set; }
[JsonPropertyName("wy")] public double Wy { get; set; }
[JsonPropertyName("z")] public double Z { get; set; }
[JsonPropertyName("heading")] public double? Heading { get; set; }
}
/// <summary>One enchantment as the phone reads it (DrakBot Remote's "enchantments" entry).</summary>
internal sealed class EnchantmentOut
{
[JsonPropertyName("spellId")] public uint SpellId { get; set; }
[JsonPropertyName("name")] public string Name { get; set; } = "";
[JsonPropertyName("family")] public uint Family { get; set; }
[JsonPropertyName("tier")] public int Tier { get; set; }
[JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; }
[JsonPropertyName("beneficial")] public bool Beneficial { get; set; } = true;
[JsonPropertyName("school")] public uint School { get; set; }
[JsonPropertyName("iconId")] public uint IconId { get; set; }
}
/// <summary>
/// What this agent can actually do, sent as "capabilities" so the phone hides what doesn't work here
/// (without it the app assumes everything the old agent offered). Same names as DrakBot Remote's, plus
/// "character" (GET /character, the Skills tab) and "worldMap" (GET /worldmap, the landscape map).
/// </summary>
internal sealed class AgentCapabilities
{
[JsonPropertyName("inventory")] public bool Inventory { get; set; }
[JsonPropertyName("settings")] public bool Settings { get; set; }
[JsonPropertyName("movement")] public bool Movement { get; set; }
[JsonPropertyName("chat")] public bool Chat { get; set; }
[JsonPropertyName("icons")] public bool Icons { get; set; }
[JsonPropertyName("closeClient")] public bool CloseClient { get; set; }
[JsonPropertyName("video")] public bool Video { get; set; }
[JsonPropertyName("videoMinimized")] public bool VideoMinimized { get; set; }
[JsonPropertyName("videoHd")] public bool VideoHd { get; set; }
[JsonPropertyName("click")] public bool Click { get; set; }
[JsonPropertyName("runs")] public bool Runs { get; set; }
[JsonPropertyName("maps")] public bool Maps { get; set; }
[JsonPropertyName("dungeon")] public bool Dungeon { get; set; }
[JsonPropertyName("act")] public bool Act { get; set; }
[JsonPropertyName("nearby")] public bool Nearby { get; set; }
[JsonPropertyName("pick")] public bool Pick { get; set; }
[JsonPropertyName("character")] public bool Character { get; set; }
[JsonPropertyName("worldMap")] public bool WorldMap { get; set; }
/// <summary>GET /nav/search + the travel / travelStop commands (RynthNav through the RynthRemote plugin).</summary>
[JsonPropertyName("travel")] public bool Travel { get; set; }
/// <summary>The raise command: spend unassigned XP (and skill credits) from the Skills tab. Needs remote
/// control and a client whose RynthRemote plugin reports raiseXp (engine API v79).</summary>
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
}
/// <summary>The subset of the RynthAi snapshot the agent surfaces.</summary>
@ -228,6 +329,17 @@ internal sealed class ClientStatus
[JsonPropertyName("recentChat")] public List<ChatLine>? RecentChat { get; set; }
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
/// <summary>Every enchantment on the character, soonest to lapse first (null = the plugin doesn't say).</summary>
[JsonPropertyName("enchantments")] public List<EnchantmentOut>? Enchantments { get; set; }
/// <summary>Facing in degrees (0 = north, clockwise) when the plugin reports it, for the map's arrow.</summary>
[JsonPropertyName("heading")] public double? Heading { get; set; }
/// <summary>The last phone travel and how it stands (null when none this session).</summary>
[JsonPropertyName("travel")] public TravelOut? Travel { get; set; }
/// <summary>This client takes the raise command (its plugin says so and remote control is on).</summary>
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
/// <summary>The hold-to-move protocol this client's plugin speaks: 2 = keep-alives and a dead-man
/// (the phone then sends moveKeepAlive), 0 = the old repeated moveStart.</summary>
[JsonPropertyName("moveProto")] public int MoveProto { get; set; }
}
internal sealed class AggregatePayload
@ -237,6 +349,7 @@ internal sealed class AggregatePayload
[JsonPropertyName("agentVersion")] public string AgentVersion { get; set; } = "";
[JsonPropertyName("generatedAtUtc")] public DateTimeOffset GeneratedAtUtc { get; set; }
[JsonPropertyName("clientCount")] public int ClientCount { get; set; }
[JsonPropertyName("capabilities")] public AgentCapabilities? Capabilities { get; set; }
[JsonPropertyName("clients")] public List<ClientStatus> Clients { get; set; } = new();
}

View file

@ -0,0 +1,218 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
namespace RynthCore.StatusAgent;
/// <summary>
/// The phone's destination search (GET /nav/search) over RynthNav's own Atlas file, NavData\locations.json
/// (towns, dungeons, portals, lifestones, NPCs, vendors...), read here rather than copied: one file, the
/// one the in-game Atlas searches. Ranking is RynthNav's (Atlas.MatchScore / TypeRank, copied), so the phone
/// lists places in the order the in-game search does; "area" is the nearest town for a place on the map.
/// Reloaded when the file changes (NavData updates). The travel itself goes to RynthNav as a /rnav "go"
/// through the RynthRemote plugin - the agent never touches RynthNav.
/// </summary>
internal sealed class NavAtlasService
{
/// <summary>RynthNav's NavCoords.UnitsPerDegree: one degree of N/S or E/W is 240 units ("yd").</summary>
public const double UnitsPerDegree = 240.0;
internal sealed record Place(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, string Area,
bool Closed, bool Quest, int MinLevel, string DestName);
private readonly string _path;
private readonly object _gate = new();
private List<Place>? _places;
private DateTime _loadedMtime;
private string _generated = "";
public NavAtlasService(string path) => _path = path;
public bool Available => File.Exists(_path);
// ── loading ─────────────────────────────────────────────────────────────
private List<Place> Places()
{
lock (_gate)
{
DateTime mtime;
try { mtime = File.GetLastWriteTimeUtc(_path); } catch { mtime = default; }
if (_places != null && mtime == _loadedMtime) return _places;
try
{
var (places, generated) = Parse(File.ReadAllText(_path));
_places = places; _generated = generated; _loadedMtime = mtime;
AgentLog.Info($"[nav] Atlas read: {places.Count:N0} places ({generated}).");
}
catch (Exception ex)
{
AgentLog.Warn($"[nav] Atlas unreadable ({_path}): {ex.GetType().Name}: {ex.Message}");
_places ??= new List<Place>();
}
return _places;
}
}
/// <summary>locations.json -> places, each on-map one with its nearest town as the area.</summary>
internal static (List<Place> Places, string Generated) Parse(string json)
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
string generated = root.TryGetProperty("generated", out var g) && g.ValueKind == JsonValueKind.String ? g.GetString() ?? "" : "";
var raw = new List<(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, bool Closed, bool Quest, int MinLevel, string Dest)>();
if (root.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array)
{
foreach (var e in arr.EnumerateArray())
{
bool onMap = TryNum(e, "ns", out double ns) & TryNum(e, "ew", out double ew);
string dest = e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object ? Str(d, "name") : "";
raw.Add((Int(e, "id"), Str(e, "name"), Str(e, "type"), Str(e, "place"), onMap, ns, ew, Bool(e, "closed"), Bool(e, "quest"), Int(e, "minLevel"), dest));
}
}
var towns = raw.Where(r => r.OnMap && r.Type == "Town").ToList();
var places = new List<Place>(raw.Count);
foreach (var r in raw)
{
string area = "";
if (r.OnMap && towns.Count > 0)
{
var near = towns.MinBy(t => Distance(r.Ns, r.Ew, t.Ns, t.Ew));
double dist = Distance(r.Ns, r.Ew, near.Ns, near.Ew);
area = r.Type == "Town" && near.Name == r.Name ? "" : dist < 1200 ? "near " + near.Name : "";
}
places.Add(new Place(r.Id, r.Name, r.Type, r.Where, r.OnMap, r.Ns, r.Ew, area, r.Closed, r.Quest, r.MinLevel, r.Dest));
}
return (places, generated);
}
// ── search ──────────────────────────────────────────────────────────────
/// <summary>RynthNav's Atlas.MatchScore: 0 = not a match.</summary>
public static int MatchScore(string name, string q)
{
if (q.Length == 0) return 1;
if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100;
int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase);
if (at == 0) return 80;
if (at > 0) return char.IsLetterOrDigit(name[at - 1]) ? 40 : 60;
string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (words.Length < 2) return 0;
foreach (string w in words)
if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0;
return 30;
}
/// <summary>RynthNav's Atlas.TypeRank: places before people.</summary>
public static int TypeRank(string type) => type switch
{
"Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4,
"Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8,
};
public static double Distance(double ns1, double ew1, double ns2, double ew2)
{
double dn = (ns2 - ns1) * UnitsPerDegree, de = (ew2 - ew1) * UnitsPerDegree;
return Math.Sqrt(dn * dn + de * de);
}
/// <summary>
/// The best matches for <paramref name="query"/> (at least 2 characters), optionally of one type: best name
/// match, then type, then nearest to (<paramref name="fromNs"/>, <paramref name="fromEw"/>) when given,
/// then name. At most <paramref name="max"/>.
/// </summary>
internal static List<(Place Place, double? Distance)> Search(IReadOnlyList<Place> places, string query, string? type, double? fromNs, double? fromEw, int max)
{
string q = (query ?? "").Trim();
var hits = new List<(Place P, int S, double? D)>();
if (q.Length < 2) return new();
foreach (var p in places)
{
if (!string.IsNullOrEmpty(type) && !p.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue;
int s = MatchScore(p.Name, q);
if (s == 0) continue;
double? d = p.OnMap && fromNs is double fn && fromEw is double fe ? Distance(fn, fe, p.Ns, p.Ew) : null;
hits.Add((p, s, d));
}
hits.Sort((a, b) =>
{
int c = b.S.CompareTo(a.S);
if (c != 0) return c;
c = TypeRank(a.P.Type).CompareTo(TypeRank(b.P.Type));
if (c != 0) return c;
c = (a.D ?? double.MaxValue).CompareTo(b.D ?? double.MaxValue);
return c != 0 ? c : string.Compare(a.P.Name, b.P.Name, StringComparison.OrdinalIgnoreCase);
});
return hits.Take(Math.Clamp(max, 1, 100)).Select(h => (h.P, h.D)).ToList();
}
/// <summary>GET /nav/search's body (schema rynthcore.nav-search/1).</summary>
public byte[] SearchJson(string query, string? type, double? fromNs, double? fromEw, int max)
{
var places = Places();
var hits = Search(places, query, type, fromNs, fromEw, max);
return Encoding.UTF8.GetBytes(SearchJson(hits, query, places.Count, _generated));
}
internal static string SearchJson(List<(Place Place, double? Distance)> hits, string query, int atlasCount, string generated)
{
var ci = CultureInfo.InvariantCulture;
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
w.WriteString("schema", "rynthcore.nav-search/1");
w.WriteString("query", query ?? "");
w.WriteNumber("atlasCount", atlasCount);
w.WriteString("generated", generated);
w.WriteNumber("count", hits.Count);
w.WriteStartArray("results");
foreach (var (p, d) in hits)
{
w.WriteStartObject();
w.WriteNumber("id", p.Id);
w.WriteString("name", p.Name);
w.WriteString("type", p.Type);
w.WriteString("area", p.Area);
w.WriteString("where", p.Where);
w.WriteBoolean("onMap", p.OnMap);
if (p.OnMap)
{
w.WriteNumber("ns", Math.Round(p.Ns, 2));
w.WriteNumber("ew", Math.Round(p.Ew, 2));
w.WriteString("coords", Fmt(p.Ns, p.Ew));
}
if (d is double dist) w.WriteNumber("distance", Math.Round(dist));
if (p.DestName.Length > 0) w.WriteString("dest", p.DestName);
if (p.MinLevel > 0) w.WriteNumber("minLevel", p.MinLevel);
if (p.Quest) w.WriteBoolean("quest", true);
if (p.Closed) w.WriteBoolean("closed", true);
// RynthNav walks only to places with a map position; a place inside a dungeon has none.
w.WriteBoolean("canTravel", p.OnMap && !p.Closed);
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
/// <summary>RynthNav's NavCoords.Fmt: "42.1N, 33.6E".</summary>
public static string Fmt(double ns, double ew)
{
var ci = CultureInfo.InvariantCulture;
return Math.Abs(ns).ToString("F1", ci) + (ns >= 0 ? "N" : "S") + ", " + Math.Abs(ew).ToString("F1", ci) + (ew >= 0 ? "E" : "W");
}
/// <summary>The status frame's absolute world units to map coordinates (RynthNav's own conversion).</summary>
public static (double Ns, double Ew) FromWorld(double wx, double wy) => ((wy / 24.0 - 1019.5) / 10.0, (wx / 24.0 - 1019.5) / 10.0);
private static string Str(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static int Int(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0;
private static bool Bool(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.True;
private static bool TryNum(JsonElement e, string n, out double d)
{
d = 0;
return e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d);
}
}

View file

@ -53,6 +53,13 @@ if (publisher.Enabled)
else
AgentLog.Info("No endpoint configured -> LOCAL PRINT-ONLY mode (nothing is sent anywhere).");
// The client's spell table (portal.dat), loaded once in the background: names + icons for the Buffs tab.
var spells = new SpellTableService(cfg.IconDatPath);
// The landscape map (cell.dat -> one cached JPEG), rendered on the first /worldmap request.
var worldMap = new WorldMapService(cfg.CellDatPath, cfg.StatusDirectory);
// RynthNav's Atlas (NavData\locations.json), searched for the phone's Travel tab.
var navAtlas = new NavAtlasService(cfg.NavAtlasPath);
// Opt-in pull endpoint: an app can fetch status with no backend.
LocalStatusServer? server = null;
WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally
@ -80,7 +87,7 @@ else if (cfg.ServeHttp)
MapService maps = new MapService(cfg.MapsDirectory);
server = new LocalStatusServer(cfg.ServePrefix, cfg.ServeToken, commandDir,
cfg.EnableScreenStream, cfg.StreamQuality, cfg.StreamIntervalMs, video, videoSocket,
runArchive, cfg.StatusDirectory, icons, maps);
runArchive, cfg.StatusDirectory, icons, maps, worldMap, navAtlas);
if (server.TryStart(out string serveErr))
{
AgentLog.Info($"Serving status at {cfg.ServePrefix}status (GET){(string.IsNullOrEmpty(cfg.ServeToken) ? "" : ", token required")}.");
@ -159,7 +166,7 @@ return 0;
// One status cycle: read all client status, roll it up, and serve / file / POST it.
async Task RunCycleAsync()
{
List<ClientStatus> clients = StatusReader.ReadAll(cfg);
List<ClientStatus> clients = StatusReader.ReadAll(cfg, spells);
runArchive.Observe(clients); // fold this cycle into per-session run history (started/updated/finished)
var payload = new AggregatePayload
{
@ -167,6 +174,14 @@ async Task RunCycleAsync()
AgentVersion = version,
GeneratedAtUtc = DateTimeOffset.UtcNow,
ClientCount = clients.Count,
// What works on this PC, so the phone stops assuming DrakBot-era "everything".
Capabilities = RemoteParity.Capabilities(cfg,
iconDat: File.Exists(cfg.IconDatPath),
dungeonMaps: Directory.Exists(cfg.MapsDirectory),
worldMap: worldMap.Available,
characterSheets: clients.Any(c => File.Exists(Path.Combine(cfg.StatusDirectory, $"RynthCore.{c.Pid}.character.json"))),
navAtlas: navAtlas.Available,
raiseXp: clients.Any(c => c.RaiseXp)),
Clients = clients,
};
@ -178,6 +193,7 @@ async Task RunCycleAsync()
AgentLog.Debug(System.Text.Encoding.UTF8.GetString(bytes));
server?.UpdateLatest(bytes);
server?.UpdateRaiseClients(clients);
if (cfg.WriteAggregateFile)
{

View file

@ -0,0 +1,223 @@
using System.Globalization;
namespace RynthCore.StatusAgent;
/// <summary>
/// The pieces that make a RynthCore client look to DrakRemote the way a DrakBot client does
/// (2026-10-05 parity work): landblock ids in the form the app matches on, the capabilities block,
/// enchantments with names and icons, and the tap-to-click coordinate mapping. Pure functions, so the
/// agent tests (tools\StatusAgentTests) cover them without a game running.
/// </summary>
internal static class RemoteParity
{
// ── landblocks ──────────────────────────────────────────────────────────
/// <summary>
/// A landblock as DrakRemote matches it: the full cell-style id "XXYY0000". The engine (and the baked
/// floor-plan file names) write the short form "0000XXYY"; DrakBot writes the full one, and since
/// DrakRemote f87130c the app reads a short map id as full (shifts it) but takes the client's id as
/// written - so a RynthCore client never matched its own dungeon's maps. Writing both full fixes it
/// for the phone already installed. Empty or unparseable stays as it was.
/// </summary>
public static string LandblockFull(string? landblock)
{
if (string.IsNullOrWhiteSpace(landblock)) return "";
if (!uint.TryParse(landblock.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return landblock;
if (v == 0) return "";
uint full = v <= 0xFFFF ? v << 16 : v & 0xFFFF0000u;
return full.ToString("X8", CultureInfo.InvariantCulture);
}
/// <summary>The short landblock (0xXXYY) from either form ("5A48", "00005A48", "5A480000", "5A48013F").</summary>
public static bool TryLandblockShort(string? s, out uint lb)
{
lb = 0;
if (string.IsNullOrWhiteSpace(s)
|| !uint.TryParse(s.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return false;
lb = v > 0xFFFF ? v >> 16 : v;
return lb != 0;
}
// ── capabilities ────────────────────────────────────────────────────────
/// <summary>What the agent offers, from its config and what is on this box. act / nearby / pick /
/// dungeon are DrakBot's (no RynthCore route for them yet), and a scraped window has no picture while
/// minimized, so those stay off.</summary>
public static AgentCapabilities Capabilities(AgentConfig cfg, bool iconDat, bool dungeonMaps, bool worldMap, bool characterSheets, bool navAtlas = false, bool raiseXp = false)
{
bool control = cfg.EnableRemoteControl;
return new AgentCapabilities
{
Inventory = true,
Settings = true,
Movement = control,
Chat = true,
Icons = iconDat,
CloseClient = control,
Video = cfg.EnableScreenStream,
VideoMinimized = false,
VideoHd = cfg.EnableVideoStream,
Click = control && cfg.EnableScreenStream,
Runs = true,
Maps = dungeonMaps || worldMap,
Dungeon = false,
Act = false,
Nearby = false,
Pick = false,
Character = characterSheets,
WorldMap = worldMap,
// Searching needs the Atlas; going needs the command channel the travel rides on.
Travel = navAtlas && control,
// Spending XP rides the command channel and needs a client whose plugin can (engine API v79).
RaiseXp = raiseXp && control && characterSheets,
};
}
// ── raise (spend XP / skill credits from the Skills tab) ────────────────
/// <summary>
/// Checks a phone raise before it becomes a command file and rewrites the value in a fixed shape:
/// {"kind":"attribute|vital|skill|train","id":N or "health|stamina|mana","count":1..100,"cost":N,"nonce":".."}.
/// The pid must be a client this agent reads whose plugin reports raiseXp (<paramref name="raiseClients"/>:
/// pid -> raiseXp). Returns the HTTP status to answer with (202 = write the command) and why not.
/// The plugin and the engine check everything again (the engine against fresh numbers and the cost).
/// </summary>
public static int CheckRaise(int pid, string? value, IReadOnlyDictionary<int, bool> raiseClients, out string normalized, out string error)
{
normalized = "";
error = "";
if (!raiseClients.TryGetValue(pid, out bool can)) { error = "unknown client"; return 404; }
if (!can) { error = "raising isn't available on that client (needs the RynthRemote plugin 0.4 and a RynthCore engine with plugin API 79)"; return 409; }
if (string.IsNullOrWhiteSpace(value)) { error = "bad raise"; return 400; }
try
{
using var doc = System.Text.Json.JsonDocument.Parse(value);
var r = doc.RootElement;
if (r.ValueKind != System.Text.Json.JsonValueKind.Object) { error = "bad raise"; return 400; }
string kind = r.TryGetProperty("kind", out var k) && k.ValueKind == System.Text.Json.JsonValueKind.String ? (k.GetString() ?? "").ToLowerInvariant() : "";
if (kind is not ("attribute" or "vital" or "skill" or "train")) { error = "bad raise kind"; return 400; }
string id;
if (!r.TryGetProperty("id", out var idEl)) { error = "bad raise id"; return 400; }
if (idEl.ValueKind == System.Text.Json.JsonValueKind.Number && idEl.TryGetInt32(out int n))
{
bool ok = kind switch { "attribute" => n is >= 1 and <= 6, "vital" => n is 1 or 3 or 5, _ => n is >= 1 and <= 54 };
if (!ok) { error = "bad raise id"; return 400; }
id = n.ToString(CultureInfo.InvariantCulture);
}
else if (kind == "vital" && idEl.ValueKind == System.Text.Json.JsonValueKind.String
&& (idEl.GetString() ?? "").ToLowerInvariant() is "health" or "stamina" or "mana")
id = "\"" + idEl.GetString()!.ToLowerInvariant() + "\"";
else { error = "bad raise id"; return 400; }
int count = 1;
if (kind != "train" && r.TryGetProperty("count", out var c)
&& (c.ValueKind != System.Text.Json.JsonValueKind.Number || !c.TryGetInt32(out count) || count < 1 || count > 100))
{ error = "bad raise count"; return 400; }
if (!r.TryGetProperty("cost", out var costEl) || costEl.ValueKind != System.Text.Json.JsonValueKind.Number
|| !costEl.TryGetInt64(out long cost) || cost <= 0 || cost > uint.MaxValue)
{ error = "a raise needs the confirmed cost"; return 400; }
string nonce = "";
if (r.TryGetProperty("nonce", out var nEl) && nEl.ValueKind == System.Text.Json.JsonValueKind.String)
foreach (char ch in nEl.GetString() ?? "")
if (nonce.Length < 40 && (char.IsAsciiLetterOrDigit(ch) || ch == '-' || ch == '_')) nonce += ch;
normalized = "{\"kind\":\"" + kind + "\",\"id\":" + id
+ ",\"count\":" + count.ToString(CultureInfo.InvariantCulture)
+ ",\"cost\":" + cost.ToString(CultureInfo.InvariantCulture)
+ ",\"nonce\":\"" + nonce + "\"}";
return 202;
}
catch (System.Text.Json.JsonException) { error = "bad raise"; return 400; }
}
// ── travel ──────────────────────────────────────────────────────────────
private const string NavTag = "[RynthNav] ";
/// <summary>
/// The phone's travel status: the plugin's record of what it sent, RynthNav's latest chat note (its
/// "[RynthNav] ..." lines reach the status's recent chat), "arrived" when that note says so, and the
/// straight-line distance left while outdoors. RynthNav's own progress line and ETA are not reachable
/// from another plugin (its status export isn't a RynthPluginGet*Json), so the note stands in for them.
/// </summary>
public static TravelOut? Travel(TravelIn? t, IReadOnlyList<ChatLine>? recentChat, bool indoor, double wx, double wy)
{
if (t == null || string.IsNullOrEmpty(t.State)) return null;
string note = "";
if (recentChat != null)
for (int i = recentChat.Count - 1; i >= 0; i--)
{
string line = recentChat[i].Text ?? "";
if (line.StartsWith(NavTag, StringComparison.Ordinal)) { note = line[NavTag.Length..].Trim(); break; }
}
string state = t.State;
if (state == "sent" && note.StartsWith("Arrived at ", StringComparison.Ordinal)
&& (t.Dest.Length == 0 || note.Contains(t.Dest, StringComparison.OrdinalIgnoreCase)))
state = "arrived";
double? left = null;
if (!indoor && (wx != 0 || wy != 0) && t.Ns is double dns && t.Ew is double dew)
{
var (ns, ew) = NavAtlasService.FromWorld(wx, wy);
left = Math.Round(NavAtlasService.Distance(ns, ew, dns, dew));
}
return new TravelOut { Dest = t.Dest, Ns = t.Ns, Ew = t.Ew, State = state, Detail = t.Detail, SentAt = t.SentAt, Note = note, Distance = left };
}
// ── enchantments ────────────────────────────────────────────────────────
/// <summary>The plugin's bare enchantments with the spell table's name, family, tier, school,
/// beneficial flag and icon; "Spell N" (beneficial, no icon) for one the table doesn't know.</summary>
public static List<EnchantmentOut>? Enchantments(List<EnchantmentIn>? input, Func<uint, SpellTableService.SpellInfo?> lookup)
{
if (input == null) return null;
var list = new List<EnchantmentOut>(input.Count);
foreach (var e in input)
{
if (e.SpellId == 0) continue;
var info = lookup(e.SpellId);
string name = info is { Name.Length: > 0 } i ? i.Name : "Spell " + e.SpellId.ToString(CultureInfo.InvariantCulture);
list.Add(new EnchantmentOut
{
SpellId = e.SpellId,
Name = name,
Family = info?.Category ?? 0,
Tier = SpellTableService.TierFromName(name),
SecondsRemaining = double.IsFinite(e.SecondsRemaining) ? e.SecondsRemaining : -1,
Beneficial = info?.Beneficial ?? true,
School = info?.School ?? 0,
IconId = info?.Icon ?? 0,
});
}
// Soonest first; the never-lapsing ones (-1) last, as DrakBot orders them for the countdown.
list.Sort(static (a, b) =>
{
bool ap = a.SecondsRemaining < 0, bp = b.SecondsRemaining < 0;
if (ap != bp) return ap ? 1 : -1;
int c = a.SecondsRemaining.CompareTo(b.SecondsRemaining);
return c != 0 ? c : a.SpellId.CompareTo(b.SpellId);
});
return list;
}
// ── tap-to-click ────────────────────────────────────────────────────────
/// <summary>
/// The client-area pixel a phone tap lands on: (u, v) in 0..1 of the frame the stream shows (the
/// window's client area, origin top-left, same aspect - a downscaled stream keeps it), so x = u * (w-1),
/// y = v * (h-1), clamped. The app has already taken the letterbox out (rynthTap.normalize).
/// </summary>
public static (int X, int Y) ClickPoint(double u, double v, int clientWidth, int clientHeight)
{
if (!double.IsFinite(u)) u = 0;
if (!double.IsFinite(v)) v = 0;
int x = (int)Math.Round(Math.Clamp(u, 0, 1) * Math.Max(0, clientWidth - 1));
int y = (int)Math.Round(Math.Clamp(v, 0, 1) * Math.Max(0, clientHeight - 1));
return (x, y);
}
/// <summary>A mouse message's lParam: y in the high word, x in the low.</summary>
public static IntPtr MouseLParam(int x, int y) => (IntPtr)unchecked((int)(((uint)(y & 0xFFFF) << 16) | (uint)(x & 0xFFFF)));
}

View file

@ -123,26 +123,49 @@ internal static class ScreenCapture
/// Device::WndProc dispatches WM_LBUTTONDOWN/etc by lParam, never GetCursorPos), so this drives both the
/// 2D UI and 3D-world hit-test WITHOUT moving the real cursor or stealing focus, even when the window is
/// backgrounded/occluded — multibox-safe. Returns false if the window is missing or minimized.
public static bool TryClick(int pid, double u, double v, string? button)
public enum ClickResult { Posted, NotFound, Minimized, NoClientArea, PostFailed }
/// <summary>What one tap did: where it went in the client area (and how big that is), or why not.</summary>
public readonly record struct ClickOutcome(ClickResult Result, int X, int Y, int Width, int Height)
{
public string Reason => Result switch
{
ClickResult.Posted => "posted",
ClickResult.NotFound => "no game window for that pid",
ClickResult.Minimized => "the game window is minimized",
ClickResult.NoClientArea => "the game window has no client area",
_ => "PostMessage failed",
};
}
// Give the game a frame between the move and the press, and between press and release: RynthCore
// can throttle a background client (Background FPS, 5..60), and a move + press + release that all land
// inside one frame can read to AC as a press at the old cursor spot, or as nothing at all.
private const int MoveSettleMs = 60;
private const int PressHoldMs = 90;
public static ClickOutcome TryClick(int pid, double u, double v, string? button)
{
EnsureDpiAware();
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || minimized || hwnd == IntPtr.Zero) return false;
if (!GetClientRect(hwnd, out RECT cr)) return false;
if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || hwnd == IntPtr.Zero)
return new ClickOutcome(minimized ? ClickResult.Minimized : ClickResult.NotFound, 0, 0, 0, 0);
if (!GetClientRect(hwnd, out RECT cr)) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, 0, 0);
int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top;
if (cw < 2 || ch < 2) return false;
int x = (int)Math.Round(Math.Clamp(u, 0, 1) * (cw - 1));
int y = (int)Math.Round(Math.Clamp(v, 0, 1) * (ch - 1));
IntPtr lParam = (IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
if (cw < 2 || ch < 2) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, cw, ch);
var (x, y) = RemoteParity.ClickPoint(u, v, cw, ch);
IntPtr lParam = RemoteParity.MouseLParam(x, y);
bool right = string.Equals(button, "right", StringComparison.OrdinalIgnoreCase);
IntPtr held = (IntPtr)(right ? MK_RBUTTON : MK_LBUTTON);
try
{
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, (IntPtr)(right ? 0x0002 : 0x0001), lParam);
System.Threading.Thread.Sleep(80); // brief down→up so AC registers a click, not a drag
if (!PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam)) return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch);
System.Threading.Thread.Sleep(MoveSettleMs);
PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, held, lParam);
System.Threading.Thread.Sleep(PressHoldMs); // down→up apart so AC registers a click, not a drag
PostMessage(hwnd, right ? WM_RBUTTONUP : WM_LBUTTONUP, IntPtr.Zero, lParam);
return true;
return new ClickOutcome(ClickResult.Posted, x, y, cw, ch);
}
catch { return false; }
catch { return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); }
}
/// Pick the game window for this pid: the largest visible, non-minimized acclient-class window. The
@ -198,6 +221,7 @@ internal static class ScreenCapture
[DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r);
[DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205;
private const int MK_LBUTTON = 0x0001, MK_RBUTTON = 0x0002;
[DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);

View file

@ -0,0 +1,150 @@
using RynthCore2.TerrainData;
namespace RynthCore.StatusAgent;
/// <summary>
/// The client's spell table (portal.dat file 0x0E00000E), read once in the background so the agent can
/// turn the plugin's bare enchantment ids into what the phone's Buffs tab shows: name, family (category),
/// tier, school, beneficial or not, and the spell's icon. Same layout and parse as the engine's
/// RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs (ACE.DatLoader SpellTable/SpellBase); this
/// copy keeps every spell, not just the debuffs. Until it is loaded (or if portal.dat is missing) a
/// lookup misses and the agent writes "Spell N" with no icon - the countdown still works.
/// </summary>
internal sealed class SpellTableService
{
private const uint SpellTableFileId = 0x0E00000E;
private const uint FlagBeneficial = 0x4;
private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12;
internal readonly record struct SpellInfo(uint Id, string Name, uint School, uint Icon, uint Category, uint Flags)
{
public bool Beneficial => (Flags & FlagBeneficial) != 0;
}
private readonly string _datPath;
private volatile Dictionary<uint, SpellInfo>? _table;
private int _queued;
public SpellTableService(string portalDatPath) => _datPath = portalDatPath;
public bool Ready => _table != null;
/// <summary>A spell by id, once the table is in; queues the one-time load on first use. Any thread.</summary>
public bool TryGet(uint spellId, out SpellInfo info)
{
var t = _table;
if (t == null)
{
EnsureLoadQueued();
info = default;
return false;
}
return t.TryGetValue(spellId, out info);
}
public void EnsureLoadQueued()
{
if (_table != null || Interlocked.Exchange(ref _queued, 1) == 1) return;
_ = Task.Run(Load);
}
private void Load()
{
try
{
if (!File.Exists(_datPath)) { AgentLog.Warn($"[spells] portal.dat not found at '{_datPath}'; buff names fall back to spell ids."); return; }
using var db = new DatDatabase();
if (!db.Open(_datPath)) { AgentLog.Warn($"[spells] could not open '{_datPath}'."); return; }
byte[]? raw = db.GetFileData(SpellTableFileId);
if (raw == null) { AgentLog.Warn("[spells] spell table 0x0E00000E not in portal.dat."); return; }
var t = Parse(raw, out int total);
_table = t;
AgentLog.Info($"[spells] spell table read: {t.Count:N0} of {total:N0} spells.");
}
catch (Exception ex) { AgentLog.Warn($"[spells] spell table read failed: {ex.GetType().Name}: {ex.Message}"); }
}
/// <summary>Parse the SpellTable file. Public for the agent tests (a hand-built table).</summary>
internal static Dictionary<uint, SpellInfo> Parse(byte[] raw, out int total)
{
var t = new Dictionary<uint, SpellInfo>();
var r = new SpanReader(raw);
r.U32(); // file id
total = r.U16();
r.U16(); // bucket count
for (int i = 0; i < total && r.Ok; i++)
{
uint id = r.U32();
string name = r.ObfuscatedString();
r.ObfuscatedString(); // description
uint school = r.U32();
uint icon = r.U32();
uint category = r.U32();
uint flags = r.U32();
r.U32(); // base mana
r.Skip(8); // range constant, range mod
r.U32(); // power
r.Skip(12); // economy mod, formula version, component loss
uint meta = r.U32();
r.U32(); // meta spell id
if (meta == MetaEnchantment || meta == MetaFellowEnchantment) r.Skip(16); // duration f64, degrade mod, degrade limit
else if (meta == MetaPortalSummon) r.Skip(8); // portal lifetime
r.Skip(8 * 4 + 12 + 8 + 4 + 12); // components, effects, recovery, display order, target type, mana mod
if (!r.Ok) break;
t[id] = new SpellInfo(id, name, school, icon, category, flags);
}
return t;
}
/// <summary>The spell's level 1-8 from its name: a Roman suffix ("... VII"), "Incantation of" = 8,
/// otherwise 0 (unknown). Matches RynthAi's SpellInfo.ComputeLevel closely enough for display.</summary>
internal static int TierFromName(string name)
{
if (string.IsNullOrEmpty(name)) return 0;
if (name.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) return 8;
int sp = name.LastIndexOf(' ');
string last = sp >= 0 ? name[(sp + 1)..] : name;
return last switch
{
"I" => 1, "II" => 2, "III" => 3, "IV" => 4, "V" => 5, "VI" => 6, "VII" => 7, "VIII" => 8,
_ => 0,
};
}
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
private ref struct SpanReader
{
private readonly ReadOnlySpan<byte> _b;
private int _p;
public bool Ok;
public SpanReader(byte[] b) { _b = b; _p = 0; Ok = true; }
private bool Has(int n)
{
if (Ok && _p + n <= _b.Length) return true;
Ok = false;
return false;
}
public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; }
public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; }
public void Skip(int n) { if (Has(n)) _p += n; }
/// <summary>u16 length + bytes with nibbles swapped, then aligned to 4 from the file start (as ACE does).</summary>
public string ObfuscatedString()
{
int n = U16();
if (!Has(n)) return "";
var chars = new char[n];
for (int i = 0; i < n; i++)
{
byte x = _b[_p + i];
chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point
}
_p += n;
_p = (_p + 3) & ~3;
return new string(chars);
}
}
}

View file

@ -0,0 +1,75 @@
using System.Collections.Concurrent;
using System.Text;
namespace RynthCore.StatusAgent;
/// <summary>
/// Reading the per-client files the RynthRemote plugin rewrites several times a second, without ever
/// dropping a client from a snapshot.
///
/// <para>Before (2026-10-05): while the agent was reading a status file, the plugin's atomic replace
/// (File.Move over it) failed (Windows won't replace an open file), and RynthRemote 0.3 then fell back to
/// overwriting the file in place; the next read caught it empty or half-written and the parse failed.
/// That client was left out of that one snapshot (StatusAgent.log: "1 client(s)" for ~60 ms, several
/// times a minute), and the phone's open deck for it unmounted and came back: the screen flashed and
/// scrolled to the top. RynthRemote 0.4 skips such a write instead of overwriting in place.</para>
///
/// <para>Here: a status file that can't be read or parsed is answered with the last good parse of that
/// file for up to <see cref="KeepLastGood"/> (its own timestamp stays in the model, so its age still shows
/// honestly), and files are read with ReadWrite|Delete sharing so a reader never makes a writer fail.</para>
/// </summary>
internal static class StatusFileCache
{
public static readonly TimeSpan KeepLastGood = TimeSpan.FromSeconds(3);
private static readonly ConcurrentDictionary<string, (object Model, DateTime AtUtc)> LastGood = new(StringComparer.OrdinalIgnoreCase);
/// <summary>Read a whole file while letting the writer replace or rewrite it underneath.</summary>
public static byte[] ReadAllBytesShared(string path)
{
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.SequentialScan);
using var ms = new MemoryStream(fs.CanSeek ? (int)Math.Min(fs.Length, int.MaxValue) : 4096);
fs.CopyTo(ms);
return ms.ToArray();
}
public static string ReadAllTextShared(string path) => Encoding.UTF8.GetString(ReadAllBytesShared(path)).TrimStart('');
/// <summary>
/// Parse <paramref name="path"/> with <paramref name="parse"/>; on any read or parse failure (or a null
/// parse) answer the last good result for that path if it is younger than <see cref="KeepLastGood"/>.
/// <paramref name="read"/> is the file reader (tests pass their own).
/// </summary>
public static T? Read<T>(string path, Func<string, T?> parse, DateTime nowUtc, Func<string, string>? read = null) where T : class
{
try
{
T? model = parse((read ?? ReadAllTextShared)(path));
if (model != null)
{
LastGood[path] = (model, nowUtc);
return model;
}
}
catch (Exception ex)
{
AgentLog.Debug($"status file '{path}' unreadable: {ex.GetType().Name}: {ex.Message}");
}
if (LastGood.TryGetValue(path, out var lg) && nowUtc - lg.AtUtc <= KeepLastGood && lg.Model is T t)
return t;
return null;
}
/// <summary>Drop what is remembered for a file that is gone (a retired dead client) or for every file
/// not in <paramref name="keep"/>.</summary>
public static void Forget(string path) => LastGood.TryRemove(path, out _);
public static void ForgetAllBut(IReadOnlyCollection<string> keep)
{
var set = new HashSet<string>(keep, StringComparer.OrdinalIgnoreCase);
foreach (var k in LastGood.Keys)
if (!set.Contains(k)) LastGood.TryRemove(k, out _);
}
internal static int CountForTests => LastGood.Count;
}

View file

@ -17,12 +17,12 @@ internal static partial class StatusReader
[GeneratedRegex(@"hb #\d+ up=(\d+)s fps=(-?\d+) plug=(-?\d+)/s ws=(\d+)MB login=(\d+)")]
private static partial Regex HeartbeatRegex();
public static List<ClientStatus> ReadAll(AgentConfig cfg)
public static List<ClientStatus> ReadAll(AgentConfig cfg, SpellTableService? spells = null)
{
var clients = new List<ClientStatus>();
var seenPids = new HashSet<int>();
ReadStatusFiles(cfg, clients, seenPids);
ReadStatusFiles(cfg, clients, seenPids, spells);
if (cfg.UseHeartbeatLogFallback)
ReadHeartbeatLogs(cfg, clients, seenPids);
@ -33,27 +33,23 @@ internal static partial class StatusReader
// ── Rich source: per-client status JSON files ───────────────────────────
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids)
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids, SpellTableService? spells)
{
string dir = cfg.StatusDirectory;
if (!Directory.Exists(dir))
return;
var listed = new List<string>();
foreach (string path in SafeEnumerate(dir, "RynthCore.*.status.json"))
{
int pid = ParsePidFromName(Path.GetFileName(path), ".status.json");
if (pid <= 0) continue;
listed.Add(path);
StatusFileModel? model;
try
{
model = JsonSerializer.Deserialize(File.ReadAllText(path), AgentJsonContext.Default.StatusFileModel);
}
catch (Exception ex)
{
AgentLog.Debug($"status file '{path}' unreadable: {ex.Message}");
continue;
}
// Shared read, and the last good parse when this one catches the file mid-write: a client is
// never left out of a snapshot just because its file was being replaced (see StatusFileCache).
StatusFileModel? model = StatusFileCache.Read(path,
text => JsonSerializer.Deserialize(text, AgentJsonContext.Default.StatusFileModel), DateTime.UtcNow);
if (model == null) continue;
double ageSec = AgeSeconds(model.Ts, path);
@ -64,6 +60,7 @@ internal static partial class StatusReader
if (!alive && ageSec > cfg.DropDeadAfterSeconds)
{
try { File.Delete(path); } catch { }
StatusFileCache.Forget(path);
continue;
}
@ -149,8 +146,22 @@ internal static partial class StatusReader
cs.XpSession = model.XpSession;
cs.BurdenPct = model.BurdenPct;
cs.Area = model.Area;
cs.Landblock = model.Landblock; cs.Indoor = model.Indoor; // [status-export] live map-dot
// [status-export] live map-dot. The landblock goes out in DrakBot's full form ("XXYY0000"), the
// one DrakRemote matches against its floor plans (see RemoteParity.LandblockFull).
cs.Landblock = RemoteParity.LandblockFull(model.Landblock); cs.Indoor = model.Indoor;
cs.Wx = model.Wx; cs.Wy = model.Wy; cs.Pz = model.Pz;
// The engine writes wx/wy indoors only; the plugin's "opos" has them outdoors too (world map dot).
if (!model.Indoor && model.Opos is { } pos && (pos.Wx != 0 || pos.Wy != 0)) { cs.Wx = pos.Wx; cs.Wy = pos.Wy; }
cs.Heading = model.Opos?.Heading;
// The player's enchantments, named from portal.dat's spell table (the Buffs tab).
cs.Enchantments = RemoteParity.Enchantments(model.Enchantments,
id => spells != null && spells.TryGet(id, out var info) ? info : null);
// The last phone travel (RynthNav) and how it stands.
cs.Travel = RemoteParity.Travel(model.Travel, cs.RecentChat, cs.Indoor, cs.Wx, cs.Wy);
// Raising from the Skills tab: what the plugin reports; Program clears it without remote control.
cs.RaiseXp = model.RaiseXp && cfg.EnableRemoteControl;
// RynthRemote 0.4+: the movement protocol it speaks (2 = keep-alives + dead-man); 0 when absent.
cs.MoveProto = model.MoveProto;
cs.LastIssue = model.LastIssue;
cs.LastIssueAgeSec = model.LastIssueAgeSec;
// Window state (for the app to show a "minimized — restore on PC" placeholder instead of a
@ -160,6 +171,7 @@ internal static partial class StatusReader
clients.Add(cs);
seenPids.Add(pid);
}
StatusFileCache.ForgetAllBut(listed);
}
// ── Basic fallback: tail each per-client heartbeat log ──────────────────

View file

@ -0,0 +1,231 @@
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using RynthCore2.TerrainData;
namespace RynthCore.StatusAgent;
/// <summary>
/// A landscape map of Dereth for the phone (GET /worldmap): every outdoor landblock of the client's
/// cell.dat (record 0xXXYYFFFF: 9x9 terrain words + height indices), one pixel per 24-unit terrain cell,
/// coloured by terrain type, roads drawn, hills shaded from the height indices. 255 landblocks x 8 cells
/// = 2040 pixels square, north up. Rendered once in the background on the first request (the world does
/// not change) and cached as a JPEG next to the agent's other files, so later starts serve it at once.
///
/// Frame (shared with the status "wx"/"wy" and the dungeon floor plans): absolute world units, x west to
/// east, y south to north, 192 units a landblock. Pixel = (wx / 24, 2040 - wy / 24).
/// </summary>
internal sealed class WorldMapService
{
public const int CellsPerLandblock = 8;
public const int Landblocks = 255;
public const int Size = Landblocks * CellsPerLandblock; // 2040
public const double UnitsPerPixel = 24.0;
private const string CacheName = "worldmap-v1.jpg";
private readonly string _cellDatPath;
private readonly string _cacheDir;
private volatile byte[]? _jpeg;
private int _started;
private volatile string _state = "idle";
public WorldMapService(string cellDatPath, string cacheDir)
{
_cellDatPath = cellDatPath;
_cacheDir = cacheDir;
}
/// <summary>True when a map can be made here at all (the cell.dat is on this box, or one is cached).</summary>
public bool Available => _jpeg != null || File.Exists(_cellDatPath) || File.Exists(CachePath);
public string State => _state;
private string CachePath => Path.Combine(_cacheDir, CacheName);
/// <summary>The JPEG, or null while it is being made (the first call starts that). Any thread.</summary>
public byte[]? GetJpeg()
{
var j = _jpeg;
if (j != null) return j;
if (Interlocked.Exchange(ref _started, 1) == 0)
{
_state = "being drawn";
_ = Task.Run(LoadOrRender);
}
return null;
}
private void LoadOrRender()
{
try
{
if (File.Exists(CachePath))
{
_jpeg = File.ReadAllBytes(CachePath);
_state = "ready";
AgentLog.Info($"[worldmap] served from cache {CachePath} ({_jpeg.Length / 1024:N0} KB).");
return;
}
if (!File.Exists(_cellDatPath)) { _state = "no cell.dat"; AgentLog.Warn($"[worldmap] cell.dat not found at '{_cellDatPath}'."); return; }
_state = "being drawn";
var sw = System.Diagnostics.Stopwatch.StartNew();
byte[] rgb;
int found;
using (var db = new DatDatabase())
{
if (!db.Open(_cellDatPath)) { _state = "cell.dat unreadable"; AgentLog.Warn($"[worldmap] could not open '{_cellDatPath}'."); return; }
rgb = Render(lb => db.GetFileData(((uint)lb << 16) | 0xFFFF), out found);
}
byte[] jpeg = EncodeJpeg(rgb, Size, Size, 88);
try
{
Directory.CreateDirectory(_cacheDir);
string tmp = CachePath + ".tmp";
File.WriteAllBytes(tmp, jpeg);
File.Move(tmp, CachePath, overwrite: true);
}
catch (Exception ex) { AgentLog.Warn($"[worldmap] cache write failed: {ex.Message}"); }
_jpeg = jpeg;
_state = "ready";
AgentLog.Info($"[worldmap] rendered {found:N0} landblocks in {sw.Elapsed.TotalSeconds:0.0}s ({jpeg.Length / 1024:N0} KB).");
}
catch (Exception ex)
{
_state = "failed";
AgentLog.Warn($"[worldmap] render failed: {ex.GetType().Name}: {ex.Message}");
Interlocked.Exchange(ref _started, 0); // let a later request try again
}
}
/// <summary>
/// Paint the whole map into a 24-bit RGB buffer (row 0 = north). <paramref name="readLandblock"/>
/// returns the raw 0xXXYYFFFF record for a landblock id 0xXXYY, or null where there is none (open sea).
/// Internal for the tests, which hand it made-up landblocks.
/// </summary>
internal static byte[] Render(Func<int, byte[]?> readLandblock, out int found)
{
var rgb = new byte[Size * Size * 3];
Fill(rgb, Sea);
found = 0;
var terrain = new ushort[81];
var heights = new byte[81];
for (int lbx = 0; lbx < Landblocks; lbx++)
{
for (int lby = 0; lby < Landblocks; lby++)
{
byte[]? raw = readLandblock((lbx << 8) | lby);
if (!TryParse(raw, terrain, heights)) continue;
found++;
for (int ix = 0; ix < CellsPerLandblock; ix++)
{
for (int iy = 0; iy < CellsPerLandblock; iy++)
{
int v = ix * 9 + iy;
ushort word = terrain[v];
int type = (word >> 2) & 0x1F;
Rgb c = Palette(type);
bool water = type is >= 16 and <= 20;
if ((word & 0x3) != 0 && !water) c = Road;
if (!water)
{
// Light from the north-west: a cell rising to the east and falling to the north is lit.
int dzx = heights[(ix + 1) * 9 + iy] - heights[v];
int dzy = heights[ix * 9 + iy + 1] - heights[v];
double s = Math.Clamp(1.0 + 0.045 * (dzx - dzy), 0.62, 1.35);
c = c.Scale(s);
}
int px = lbx * CellsPerLandblock + ix;
int py = Size - 1 - (lby * CellsPerLandblock + iy);
int o = (py * Size + px) * 3;
rgb[o] = c.R; rgb[o + 1] = c.G; rgb[o + 2] = c.B;
}
}
}
}
return rgb;
}
/// <summary>Record layout: u32 id, u32 hasObjects, u16 terrain[81], u8 height[81] (vertex = ix*9 + iy).</summary>
internal static bool TryParse(byte[]? raw, ushort[] terrain, byte[] heights)
{
if (raw == null || raw.Length < 8 + 81 * 2 + 81) return false;
for (int i = 0; i < 81; i++) terrain[i] = BitConverter.ToUInt16(raw, 8 + i * 2);
Buffer.BlockCopy(raw, 8 + 81 * 2, heights, 0, 81);
return true;
}
/// <summary>Where a world position lands on the map, in pixels (may fall outside for bad input).</summary>
public static (double X, double Y) ToPixel(double wx, double wy) => (wx / UnitsPerPixel, Size - wy / UnitsPerPixel);
// ── colours ─────────────────────────────────────────────────────────────
internal readonly record struct Rgb(byte R, byte G, byte B)
{
public Rgb Scale(double s) => new(Clamp(R * s), Clamp(G * s), Clamp(B * s));
private static byte Clamp(double v) => (byte)Math.Clamp((int)Math.Round(v), 0, 255);
}
private static readonly Rgb Sea = new(0x1F, 0x4A, 0x78);
private static readonly Rgb Road = new(0xA8, 0x93, 0x6C);
/// <summary>ACE's LandDefs.TerrainType, 0..20; anything else (the reserved slots) a neutral grey.</summary>
internal static Rgb Palette(int type) => type switch
{
0 => new(0x7A, 0x74, 0x66), // BarrenRock
1 => new(0x6E, 0x8B, 0x3D), // Grassland
2 => new(0xD8, 0xE8, 0xF0), // Ice
3 => new(0x4F, 0x7A, 0x2A), // LushGrass
4 => new(0x5A, 0x6B, 0x3A), // MarshSparseSwamp
5 => new(0x6B, 0x52, 0x36), // MudRichDirt
6 => new(0x2E, 0x2A, 0x30), // ObsidianPlain
7 => new(0x8C, 0x75, 0x50), // PackedDirt
8 => new(0x8A, 0x7B, 0x55), // PatchyDirt
9 => new(0x7F, 0x8F, 0x48), // PatchyGrassland
10 => new(0xD8, 0xC4, 0x8A), // SandYellow
11 => new(0xB5, 0xAE, 0x98), // SandGrey
12 => new(0xB8, 0xA4, 0x7A), // SandRockStrewn
13 => new(0x9A, 0x84, 0x68), // SedimentaryRock
14 => new(0x84, 0x7A, 0x63), // SemiBarrenRock
15 => new(0xF0, 0xF4, 0xF7), // Snow
16 => new(0x3C, 0x6E, 0x9E), // WaterRunning
17 => new(0x3F, 0x78, 0xA8), // WaterStandingFresh
18 => new(0x35, 0x6B, 0x9C), // WaterShallowSea
19 => new(0x2F, 0x62, 0x93), // WaterShallowStillSea
20 => new(0x1F, 0x4A, 0x78), // WaterDeepSea
_ => new(0x80, 0x80, 0x80),
};
private static void Fill(byte[] rgb, Rgb c)
{
for (int i = 0; i < rgb.Length; i += 3) { rgb[i] = c.R; rgb[i + 1] = c.G; rgb[i + 2] = c.B; }
}
private static byte[] EncodeJpeg(byte[] rgb, int w, int h, int quality)
{
using var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb);
var bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
try
{
var row = new byte[w * 3];
for (int y = 0; y < h; y++)
{
// GDI+ 24bpp is B,G,R in memory.
for (int x = 0; x < w; x++)
{
int s = (y * w + x) * 3;
row[x * 3] = rgb[s + 2]; row[x * 3 + 1] = rgb[s + 1]; row[x * 3 + 2] = rgb[s];
}
Marshal.Copy(row, 0, bd.Scan0 + y * bd.Stride, row.Length);
}
}
finally { bmp.UnlockBits(bd); }
var enc = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.FormatID == ImageFormat.Jpeg.Guid)
?? throw new InvalidOperationException("no jpeg encoder");
using var ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Clamp(quality, 1, 100));
using var ms = new MemoryStream();
bmp.Save(ms, enc, ep);
return ms.ToArray();
}
}

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Checks a change to the dat code against the code it replaces, on the real dat files, read
only. Covers the StatusAgent's reader and icon decoder (src\RynthCore.StatusAgent\Dat) and
the engine's portal reader and icon decoder (src\RynthCore.Engine\UI\ScriptWindows\
AcIconDecoder.cs), all compiled in. It uses only their API, so the same source builds
against the old code (check out the base commit) and the new; each build writes a manifest
and "diff" compares two:
manifest <AC folder> <out> every file in client_portal.dat and client_cell_1.dat through
both readers (id, flags, offset, size, SHA-256 of the bytes),
FindFile misses, landblock cell ids, EntriesInRange per type.
icons <AC folder> <out> every 0x06 texture through IconDecoder.Decode and
AcIconDecoder.Decode (icon and UI limits): size and a SHA-256
of the RGBA pixels; 3,000 composed underlay/icon/overlay stacks.
diff <a> <b> compares two outputs. Timing lines ("#t") and the order of the
list calls ("#o") are reported, not compared: the lists are
compared as sets.
Run: dotnet run -c Release (after the usual separator) icons "C:\Turbine\Asheron's Call" old.txt
The RynthSuite twin, Tools\RynthCore.DatReaderCheck, covers RynthAi's reader and geometry.
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>DatReaderCheck</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\*.cs" Link="StatusAgent\%(Filename)%(Extension)" />
<Compile Include="..\..\src\RynthCore.Engine\UI\ScriptWindows\AcIconDecoder.cs" Link="Engine\AcIconDecoder.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,253 @@
// DatReaderCheck - proves a change to RynthCore's dat code on the real dat files (read only).
// Written for RynthCore (MIT). The modes are described in DatReaderCheck.csproj.
//
// Only the API of the code under test is used (StatusAgent: DatDatabase, IconDecoder; engine:
// AcDatFile, AcIconDecoder), so the same source builds against the old code and the new, and
// two builds' outputs can be compared line by line.
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.StatusAgent;
using RynthCore2.TerrainData;
namespace DatReaderCheck;
internal static class Program
{
private static int Main(string[] args)
{
if (args.Length >= 3 && args[0] == "manifest") return Manifest(args[1], args[2]);
if (args.Length >= 3 && args[0] == "icons") return Icons(args[1], args[2]);
if (args.Length >= 3 && args[0] == "diff") return Diff(args[1], args[2]);
Console.WriteLine("usage: manifest <AC folder> <out> | icons <AC folder> <out> | diff <a> <b>");
return 2;
}
private static StreamWriter Out(string path) => new(path, false, new UTF8Encoding(false)) { NewLine = "\n" };
// ------------------------------------------------------------------ manifest
private static int Manifest(string acDir, string outPath)
{
using var w = Out(outPath);
int rc = DumpDat(w, Path.Combine(acDir, "client_portal.dat"));
rc |= DumpDat(w, Path.Combine(acDir, "client_cell_1.dat"));
var p = Process.GetCurrentProcess();
p.Refresh();
w.WriteLine($"#t process peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB");
return rc;
}
private static int DumpDat(StreamWriter w, string path)
{
Console.WriteLine("== " + Path.GetFileName(path));
w.WriteLine("== " + Path.GetFileName(path));
var sw = Stopwatch.StartNew();
using var db = new DatDatabase();
bool ok = db.Open(path);
w.WriteLine($"open {ok}");
w.WriteLine($"#t open {sw.Elapsed.TotalMilliseconds:F0} ms");
if (!ok) { Console.WriteLine("open failed: " + string.Join(" | ", db.DiagLog)); return 1; }
w.WriteLine($"header FileType={db.FileType:X8} BlockSize={db.BlockSize} FileSize={db.FileSize} DataSet={db.DataSet:X8} BTreeRoot={db.BTreeRoot:X8} IsLoaded={db.IsLoaded} records={db.RecordCount}");
using var engine = AcDatFile.Open(path, out string why);
w.WriteLine($"engine-open {(engine != null ? "ok" : why)}");
var all = db.EntriesInRange(0, uint.MaxValue);
w.WriteLine($"entries-in-range-all {all.Count} {Hashes(all)}");
var ids = all.Select(e => e.id).OrderBy(i => i).ToList();
var idSet = new HashSet<uint>(ids);
sw.Restart();
int nulls = 0, mismatch = 0, engineDiff = 0, engineNull = 0;
long bytes = 0;
foreach (uint id in ids)
{
var f = db.FindFile(id);
if (f == null || f.ObjectId != id) mismatch++;
byte[]? data = db.GetFileData(id);
string digest;
if (data == null) { nulls++; digest = "NULL"; }
else { bytes += data.Length; digest = data.Length + " " + Convert.ToHexString(SHA256.HashData(data)); }
w.WriteLine($"f {id:X8} {f?.BitFlags:X8} {f?.FileOffset:X8} {f?.FileSize} = {digest}");
if (engine != null)
{
byte[]? e = engine.Read(id, int.MaxValue);
if (e == null) engineNull++;
else if (data == null || !e.AsSpan().SequenceEqual(data)) engineDiff++;
}
}
w.WriteLine($"files {ids.Count} read-null {nulls} find-mismatch {mismatch} bytes {bytes} engine-null {engineNull} engine-differs {engineDiff}");
w.WriteLine($"#t all files {sw.Elapsed.TotalMilliseconds:F0} ms");
Console.WriteLine($" {ids.Count} files, {nulls} null, {mismatch} find mismatches; engine reader: {engineNull} null, {engineDiff} differ");
// The engine reader's size cap and a few caps around real sizes.
if (engine != null)
{
int capped = 0;
foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size - 1) == null) capped++;
int fits = 0;
foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size) != null) fits++;
w.WriteLine($"engine-cap below-size-null {capped} at-size-ok {fits}");
}
sw.Restart();
int probes = 0, misses = 0, wrong = 0, engineWrong = 0;
void Probe(uint id)
{
probes++;
var f = db.FindFile(id);
bool expect = idSet.Contains(id);
if (f == null) { misses++; if (expect) wrong++; }
else if (!expect || f.ObjectId != id) wrong++;
if (engine != null && probes % 8 == 0 && (engine.Read(id, int.MaxValue) != null) != expect) engineWrong++;
if (db.GetFileData(id) == null == expect) wrong++;
}
foreach (uint id in ids)
{
if (id != uint.MaxValue) Probe(id + 1);
if (id != 0) Probe(id - 1);
}
var rng = new Random(20261005);
for (int i = 0; i < 1_000_000; i++) Probe((uint)rng.NextInt64(0, 1L << 32));
for (uint t = 0; t <= 0x40; t++) for (uint lo = 0; lo < 0x400; lo++) Probe((t << 24) | lo);
Probe(0); Probe(uint.MaxValue);
w.WriteLine($"probes {probes} misses {misses} wrong {wrong} engine-wrong {engineWrong}");
w.WriteLine($"#t probes {sw.Elapsed.TotalMilliseconds:F0} ms");
for (uint t = 0; t <= 0xFF; t++)
{
var r = db.EntriesInRange(t << 24, (t << 24) | 0xFFFFFF);
if (r.Count > 0) w.WriteLine($"range {t:X2} {r.Count} {Hashes(r)}");
}
int withCells = 0, cellIds = 0;
for (uint lb = 0; lb <= 0xFFFF; lb++)
{
var c = db.GetLandblockCellIds(lb);
if (c.Count == 0) continue;
withCells++; cellIds += c.Count;
w.WriteLine($"lb {lb:X4} {c.Count} {Hashes(c.Select(i => (i, 0u)).ToList())}");
}
w.WriteLine($"landblocks with-cells {withCells} cell-ids {cellIds}");
db.Close();
w.WriteLine($"closed IsLoaded={db.IsLoaded} find-after-close={(db.FindFile(ids[0]) == null ? "null" : "hit")}");
return 0;
}
// Which entries a list holds, whatever their order, then (on a "#o" line, which diff reports
// but doesn't count) the order itself: the old reader returned ties and cell ids in its
// dictionary's order; the new one sorts them (size then id, cell ids ascending).
private static string Hashes(List<(uint id, uint size)> list) =>
Hash(list.OrderBy(e => e.id).ThenBy(e => e.size).ToList()) + "\n#o order " + Hash(list);
private static string Hash(List<(uint id, uint size)> list)
{
var b = new byte[list.Count * 8];
for (int i = 0; i < list.Count; i++)
{
BitConverter.TryWriteBytes(b.AsSpan(i * 8), list[i].id);
BitConverter.TryWriteBytes(b.AsSpan(i * 8 + 4), list[i].size);
}
return Convert.ToHexString(SHA256.HashData(b), 0, 12);
}
// ------------------------------------------------------------------ icons
private static int Icons(string acDir, string outPath)
{
using var w = Out(outPath);
string path = Path.Combine(acDir, "client_portal.dat");
using var db = new DatDatabase();
if (!db.Open(path)) { Console.WriteLine("open failed"); return 1; }
using var engine = AcDatFile.Open(path, out string why);
if (engine == null) { Console.WriteLine("engine open failed: " + why); return 1; }
var decoder = new IconDecoder(db);
var ids = db.EntriesInRange(0x06000000, 0x06FFFFFF).Select(e => e.id).OrderBy(i => i).ToList();
w.WriteLine($"textures {ids.Count}");
var byFormat = new SortedDictionary<string, int[]>(); // format -> [count, status ok, engine ok, engine-ui ok]
double agentMs = 0, engineMs = 0;
var sw = new Stopwatch();
var decodable = new List<uint>();
foreach (uint id in ids)
{
byte[]? raw = db.GetFileData(id);
string fmt = "?";
int fw = 0, fh = 0;
if (raw != null && raw.Length >= 24)
{
fw = BitConverter.ToInt32(raw, 8); fh = BitConverter.ToInt32(raw, 12);
fmt = BitConverter.ToUInt32(raw, 16).ToString("X8");
}
sw.Restart();
var a = decoder.Decode(id);
agentMs += sw.Elapsed.TotalMilliseconds;
sw.Restart();
var e1 = AcIconDecoder.Decode(engine, id);
var e2 = AcIconDecoder.Decode(engine, id, AcIconDecoder.MaxUiSide);
engineMs += sw.Elapsed.TotalMilliseconds;
w.WriteLine($"t {id:X8} {fmt} {fw}x{fh} agent={D(a?.Width, a?.Height, a?.Pixels)} icon={D(e1?.Width, e1?.Height, e1?.Pixels)} ui={D(e2?.Width, e2?.Height, e2?.Pixels)}");
if (!byFormat.TryGetValue(fmt, out var c)) byFormat[fmt] = c = new int[4];
c[0]++;
if (a != null) c[1]++;
if (e1 != null) { c[2]++; if (fw == 32 && fh == 32) decodable.Add(id); }
if (e2 != null) c[3]++;
}
foreach (var kv in byFormat)
w.WriteLine($"format {kv.Key}: {kv.Value[0]} textures, agent decodes {kv.Value[1]}, engine icon {kv.Value[2]}, engine ui {kv.Value[3]}");
w.WriteLine($"#t agent decode {agentMs:F0} ms, engine decode (icon + ui) {engineMs:F0} ms");
Console.WriteLine($"{ids.Count} textures");
foreach (var kv in byFormat) Console.WriteLine($" {kv.Key}: {kv.Value[0]} agent {kv.Value[1]} icon {kv.Value[2]} ui {kv.Value[3]}");
// Composed item pictures: underlay + icon + overlay (0 = none).
var rng = new Random(424242);
for (int i = 0; i < 3000 && decodable.Count > 0; i++)
{
uint icon = decodable[rng.Next(decodable.Count)];
uint under = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)];
uint over = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)];
var c = AcIconDecoder.Compose(engine, icon, under, over);
w.WriteLine($"c {icon:X8} {under:X8} {over:X8} {D(c?.Width, c?.Height, c?.Pixels)}");
}
// Ids that aren't textures, or aren't there.
foreach (uint id in new uint[] { 0, 0x05000001, 0x06FFFFFF, 0x07000001, 0x0E00000E })
w.WriteLine($"x {id:X8} agent={D(decoder.Decode(id)?.Width, 0, decoder.Decode(id)?.Pixels)} icon={D(AcIconDecoder.Decode(engine, id)?.Width, 0, AcIconDecoder.Decode(engine, id)?.Pixels)}");
return 0;
}
private static string D(int? w, int? h, byte[]? px) =>
px == null ? "null" : $"{w}x{h}:{Convert.ToHexString(SHA256.HashData(px), 0, 12)}";
// ------------------------------------------------------------------ diff
private static int Diff(string a, string b)
{
var oa = File.ReadLines(a).Where(l => l.StartsWith("#o")).ToList();
var ob = File.ReadLines(b).Where(l => l.StartsWith("#o")).ToList();
int orderDiffs = oa.Count == ob.Count ? oa.Where((l, i) => l != ob[i]).Count() : -1;
Console.WriteLine($"order lines: {oa.Count} vs {ob.Count}, {(orderDiffs < 0 ? "counts differ" : orderDiffs + " differ")} (reported, not counted)");
using var la = File.ReadLines(a).Where(l => !l.StartsWith('#')).GetEnumerator();
using var lb = File.ReadLines(b).Where(l => !l.StartsWith('#')).GetEnumerator();
long n = 0, diffs = 0;
while (true)
{
bool ha = la.MoveNext(), hb = lb.MoveNext();
if (!ha && !hb) break;
n++;
string sa = ha ? la.Current : "<end>", sb = hb ? lb.Current : "<end>";
if (sa == sb) continue;
if (diffs < 40) Console.WriteLine($"line {n}:\n a: {sa}\n b: {sb}");
diffs++;
}
Console.WriteLine($"{n} lines compared, {diffs} differ");
foreach (var (name, file) in new[] { ("a", a), ("b", b) })
{
Console.WriteLine($"timings {name}:");
foreach (var l in File.ReadLines(file).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l);
}
return diffs == 0 ? 0 : 1;
}
}

View file

@ -3,7 +3,9 @@
<!--
Offline tests for the launcher's Available plugins list, plugin installs with download
progress and Cancel (RynthUpdater.Available.cs, DownloadProgress.cs), and the front page's
update card (UpdateCardModel.cs). A throwaway key signs a feed served by a local
update card (UpdateCardModel.cs), and plugin manifests' minEngineApi (a plugin build the
installed engine would refuse is neither installed nor updated; "needs RynthCore X"
instead). A throwaway key signs a feed served by a local
HttpListener; plugins install into temp folders. Never opens the launcher window, never
reads or writes outside %TEMP%.
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
@ -23,6 +25,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateCardModel.cs" Link="Linked\UpdateCardModel.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
</Project>

View file

@ -55,6 +55,11 @@ internal static class Program
await Run(nameof(UpdateCardStates), UpdateCardStates);
await Run(nameof(UpdateCardDownloading), UpdateCardDownloading);
await Run(nameof(UpdateCardWhatsNew), UpdateCardWhatsNew);
await Run(nameof(TooNewPluginIsNotInstalled), TooNewPluginIsNotInstalled);
await Run(nameof(TooNewPluginWithoutCoreApiSaysTheApi), TooNewPluginWithoutCoreApiSaysTheApi);
await Run(nameof(TooNewUpdateIsHeldBack), TooNewUpdateIsHeldBack);
await Run(nameof(TooNewCompanionWaits), TooNewCompanionWaits);
await Run(nameof(MinEngineApiAtOrBelowInstalledIsFine), MinEngineApiAtOrBelowInstalledIsFine);
}
finally
{
@ -148,8 +153,10 @@ internal static class Program
/// </summary>
private static Feed Setup(string tag, bool descriptions = true, IEnumerable<string>? extraPlugins = null,
Dictionary<string, string>? descriptionOverride = null, bool signDescriptions = true, string? badUrlFor = null,
string[]? changes = null)
string[]? changes = null, Dictionary<string, uint>? minEngineApi = null, uint coreEngineApi = 0)
{
_minEngineApi = minEngineApi;
_coreEngineApi = coreEngineApi;
string dir = Path.Combine(_root, tag);
string state = Path.Combine(dir, "state"), app = Path.Combine(dir, "app"), suite = Path.Combine(dir, "Games", "RynthSuite");
Directory.CreateDirectory(state); Directory.CreateDirectory(app);
@ -180,13 +187,16 @@ internal static class Program
["size"] = body.Length, ["sha256"] = Sha(body),
};
if (descriptions) p["description"] = descriptionOverride != null && descriptionOverride.TryGetValue(name, out string? d) ? d : $"Feed line for {name}.";
if (_minEngineApi != null && _minEngineApi.TryGetValue(name, out uint min)) p["minEngineApi"] = min;
plugins.Add(p);
}
var core = new Dictionary<string, object> { ["release"] = 2026100501, ["version"] = "2026.10.5.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" };
if (_coreEngineApi != 0) core["engineApi"] = _coreEngineApi;
var manifest = new Dictionary<string, object?>
{
["schema"] = 1, ["release"] = 2026100501, ["version"] = "2026.10.5.1",
["published"] = Published.ToString("yyyy-MM-ddTHH:mm:ssZ"), ["notes"] = "Release notes for players.",
["core"] = new Dictionary<string, object> { ["release"] = 2026100501, ["version"] = "2026.10.5.1", ["url"] = _base + $"{tag}/releases/1/RynthCore-Setup.exe", ["size"] = 1, ["sha256"] = "00" },
["core"] = core,
["plugins"] = plugins,
};
if (changes != null) manifest["changes"] = changes;
@ -349,6 +359,106 @@ internal static class Program
Check(c2.Plugins.Any(p => p.Entry.Name == "RynthOracle" && p.State == RynthUpdater.PluginState.UpToDate), "the next check sees it up to date");
}
// ── Plugin manifests: minEngineApi ───────────────────────────────────────
// The feed fixture's optional fields (set by Setup, read by WriteFeed).
private static Dictionary<string, uint>? _minEngineApi;
private static uint _coreEngineApi;
private const uint Installed = 76; // the engine API the test launcher "installed"
private static async Task TooNewPluginIsNotInstalled()
{
// RynthOracle's build needs API 77; this feed's core release brings it.
var f = Setup("api-new", minEngineApi: new() { ["RynthOracle"] = Installed + 1, ["RynthChat"] = 66 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var paths = new List<string> { f.RynthAiPath };
var c = await f.Upd.CheckAsync(paths);
var oracle = c.Available.Single(a => a.Entry.Name == "RynthOracle");
Check(oracle.Entry.MinEngineApi == Installed + 1, "minEngineApi read from the feed");
Check(!oracle.CanInstall, "a too-new plugin can't be installed");
Check(oracle.Blocker == "needs RynthCore 2026.10.5.1", "it says which RynthCore it needs: " + oracle.Blocker);
Check(c.Available.Single(a => a.Entry.Name == "RynthChat").CanInstall, "a plugin within the engine's API still can");
Check(c.Available.Single(a => a.Entry.Name == "RynthNav").CanInstall, "a plugin without minEngineApi still can");
try
{
await f.Upd.InstallPluginAsync(c, "RynthOracle", paths);
Check(false, "InstallPluginAsync should refuse a too-new plugin");
}
catch (InvalidOperationException ex)
{
Check(ex.Message.Contains("needs RynthCore"), "refused with the reason: " + ex.Message);
}
Check(!File.Exists(oracle.Path), "nothing written");
Check(!Directory.Exists(Path.GetDirectoryName(oracle.Path)!), "no folder created");
}
private static async Task TooNewPluginWithoutCoreApiSaysTheApi()
{
// The feed's core doesn't say its API (or brings an older one): name the API instead.
var f = Setup("api-nocore", minEngineApi: new() { ["RynthOracle"] = Installed + 2 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
var oracle = c.Available.Single(a => a.Entry.Name == "RynthOracle");
Check(oracle.Blocker == $"needs a newer RynthCore (API {Installed + 2})", "names the API: " + oracle.Blocker);
var g = Setup("api-nocore2", minEngineApi: new() { ["RynthOracle"] = Installed + 1 });
g.Upd.InstalledEngineApi = Installed;
var c2 = await g.Upd.CheckAsync(new[] { g.RynthAiPath });
Check(c2.Available.Single(a => a.Entry.Name == "RynthOracle").Blocker == $"needs a newer RynthCore (API {Installed + 1})",
"a core without engineApi: the API too");
}
private static async Task TooNewUpdateIsHeldBack()
{
var f = Setup("api-update", minEngineApi: new() { ["RynthChat"] = Installed + 1, ["RynthNav"] = Installed }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
string chat = Place(f, "RynthChat"), nav = Place(f, "RynthNav");
byte[] oldChat = Encoding.UTF8.GetBytes("dll RynthChat v1"), oldNav = Encoding.UTF8.GetBytes("dll RynthNav v1");
File.WriteAllBytes(chat, oldChat); File.SetLastWriteTimeUtc(chat, Published.AddDays(-3));
File.WriteAllBytes(nav, oldNav); File.SetLastWriteTimeUtc(nav, Published.AddDays(-3));
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath, chat, nav });
var chatStatus = c.Plugins.Single(p => p.Entry.Name == "RynthChat");
Check(chatStatus.State == RynthUpdater.PluginState.NeedsNewerEngine, "too-new update held back: " + chatStatus.State);
Check(chatStatus.Blocker == "needs RynthCore 2026.10.5.1", "with the reason: " + chatStatus.Blocker);
Check(c.PluginsWaitingForCore.Any(p => p.Entry.Name == "RynthChat"), "listed as waiting for RynthCore");
Check(c.Plugins.Single(p => p.Entry.Name == "RynthNav").State == RynthUpdater.PluginState.NeedsUpdate, "an update at the installed API goes ahead");
Check(c.PluginsToUpdate.Select(p => p.Entry.Name).SequenceEqual(new[] { "RynthNav" }), "only RynthNav is updated");
await f.Upd.UpdatePluginsAsync(c);
Check(File.ReadAllBytes(chat).SequenceEqual(oldChat), "RynthChat kept as it was (the engine would refuse the new build)");
Check(!File.Exists(chat + ".previous"), "no .previous for RynthChat");
Check(File.ReadAllBytes(nav).SequenceEqual(Body("RynthNav")), "RynthNav updated");
// After RynthCore is updated (the new launcher knows the new API), the update goes through.
f.Upd.InstalledEngineApi = Installed + 1;
var after = await f.Upd.CheckAsync(new[] { f.RynthAiPath, chat, nav });
Check(after.Plugins.Single(p => p.Entry.Name == "RynthChat").State == RynthUpdater.PluginState.NeedsUpdate, "updated once RynthCore catches up");
}
private static async Task TooNewCompanionWaits()
{
var f = Setup("api-companion", minEngineApi: new() { ["RynthLua"] = Installed + 1 }, coreEngineApi: Installed + 1);
f.Upd.InstalledEngineApi = Installed;
var c = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(c.Companions.Count == 0, "a too-new companion isn't installed beside RynthAi");
Check(c.Available.Single(a => a.Entry.Name == "RynthLua").Blocker.Length > 0, "and shows what it needs under Available");
f.Upd.InstalledEngineApi = Installed + 1;
var later = await f.Upd.CheckAsync(new[] { f.RynthAiPath });
Check(later.Companions.Count == 1 && later.Companions[0].Entry.Name == "RynthLua", "offered once RynthCore catches up (not marked as offered before)");
}
private static async Task MinEngineApiAtOrBelowInstalledIsFine()
{
var f = Setup("api-ok", minEngineApi: new() { ["RynthOracle"] = Installed, ["RynthInventory"] = 71 });
f.Upd.InstalledEngineApi = Installed;
var paths = new List<string> { f.RynthAiPath };
var c = await f.Upd.CheckAsync(paths);
Check(c.Available.All(a => a.CanInstall), "everything installable: " + string.Join(",", c.Available.Where(a => !a.CanInstall).Select(a => a.Entry.Name)));
var done = await f.Upd.InstallPluginAsync(c, "RynthOracle", paths);
Check(done.Downloaded && File.Exists(done.Path), "installed at the exact minimum");
Check(f.Upd.InstalledEngineApi == Installed && new RynthUpdater().InstalledEngineApi == RynthCore.Engine.Plugins.PluginContractVersion.Current,
"the launcher's default is the engine's own API constant");
}
private static async Task InstallRefusesTamperedFile()
{
var f = Setup("tamper");

View file

@ -20,6 +20,7 @@
<Compile Include="..\..\src\RynthCore.App.Avalonia\RynthUpdater.Available.cs" Link="Linked\RynthUpdater.Available.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\DownloadProgress.cs" Link="Linked\DownloadProgress.cs" />
<Compile Include="..\..\src\RynthCore.App.Avalonia\UpdateTrust.cs" Link="Linked\UpdateTrust.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Linked\PluginContractVersion.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,102 @@
// NetProbe - a test plugin for the v78 server-message stream (see the csproj). It asks for
// every message the SDK parses, parses what arrives and logs the first few of each kind,
// plus a count every 30 s, through the host log ("NetProbe:" lines in the RynthCore log).
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk.Net;
namespace RynthCore.Plugin.NetProbe;
public sealed class NetProbePlugin : RynthPluginBase
{
internal static readonly IntPtr NamePointer = Marshal.StringToHGlobalAnsi("NetProbe");
internal static readonly IntPtr VersionPointer = Marshal.StringToHGlobalAnsi("0.1.0");
internal static NetProbePlugin? Instance;
private const int FirstN = 5;
private readonly Dictionary<string, (int Ok, int Failed, int Leftover)> _kinds = new();
private long _messages, _lastSummary;
private static readonly uint[] Opcodes =
{
ServerOpcode.HearSpeech, ServerOpcode.HearRangedSpeech, ServerOpcode.HearEmote, ServerOpcode.HearSoulEmote,
};
private static readonly uint[] GameEvents =
{
GameEventType.PopUpString, GameEventType.FriendsUpdate, GameEventType.FellowshipQuit, GameEventType.FellowshipDismiss,
GameEventType.ChannelBroadcast, GameEventType.ConfirmationRequest, GameEventType.AllegianceLoginNotification,
GameEventType.HearDirectSpeech, GameEventType.FellowshipFullUpdate, GameEventType.FellowshipDisband,
GameEventType.FellowshipUpdateFellow, GameEventType.TransientString,
};
public override int Initialize()
{
Instance = this;
if (!Host.HasServerMessages)
{
Log($"NetProbe: engine API v{Host.Version} has no server messages (needs v78).");
return 0;
}
int r = Host.SetServerMessageInterest(Opcodes, GameEvents);
Log($"NetProbe: SetServerMessageInterest -> {r} (1 streaming, 2 stream off, 0 no export, -1 unknown caller).");
return 0;
}
public override void Shutdown() => Instance = null;
internal unsafe void OnServerMessage(uint opcode, byte* data, int length)
{
_messages++;
NetMessageInfo info = NetMessages.Inspect(ServerMessage.FromCallback(opcode, data, length));
string kind = info.Known ? info.Kind : $"unasked {info.Kind}";
var k = _kinds.TryGetValue(kind, out var v) ? v : default;
int seen = k.Ok + k.Failed;
_kinds[kind] = (k.Ok + (info.Parsed ? 1 : 0), k.Failed + (info.Parsed ? 0 : 1), k.Leftover + (info.Parsed && info.Leftover != 0 ? 1 : 0));
if (seen < FirstN || !info.Parsed || info.Leftover != 0)
Log($"NetProbe: {kind} len={length} {(info.Parsed ? "ok" : "FAILED")}{(info.Leftover != 0 ? $" leftover={info.Leftover}" : "")} {info.Summary}");
}
public override void OnTick()
{
long now = Environment.TickCount64;
if (now - _lastSummary < 30000) return;
_lastSummary = now;
if (_messages == 0) return;
var parts = new List<string>();
foreach (var (kind, c) in _kinds)
parts.Add($"{kind} {c.Ok}" + (c.Failed > 0 ? $"/{c.Failed} failed" : "") + (c.Leftover > 0 ? $"/{c.Leftover} leftover" : ""));
Log($"NetProbe: {_messages} messages: {string.Join(", ", parts)}");
}
}
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<NetProbePlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCore.PluginSdk.RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => NetProbePlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => NetProbePlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
/// <summary>v78: data = the message after its opcode, valid only during the call.</summary>
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnServerMessage(uint opcode, byte* data, int length)
{
try { NetProbePlugin.Instance?.OnServerMessage(opcode, data, length); }
catch { } // never let an exception cross the native boundary
}
}

View file

@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
NetProbe: a test plugin for the v78 server-message stream. It asks for every message the
SDK parses (RynthCore.PluginSdk.Net), parses what arrives on RynthPluginOnServerMessage
and writes the first few of each kind, and a count every 30 s, to the RynthCore log
("NetProbe:"). For the in-game check only; not shipped.
dotnet publish -c Release -o <a test folder>, then add the DLL in the launcher's Plugins tab.
-->
<PropertyGroup>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<RootNamespace>RynthCore.Plugin.NetProbe</RootNamespace>
<AssemblyName>RynthCore.Plugin.NetProbe</AssemblyName>
<Platforms>x86</Platforms>
</PropertyGroup>
<ItemGroup>
<IlcArg Include="--runtimeopt:GCSegmentSize=800000" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline replay tests for the server-message stream (plugin API v78):
- the engine's datagram walk, packet ring, fragment reassembler and interest sets
(src\RynthCore.Engine\Net\*, compiled in; pure code, no engine state);
- the SDK's typed parsers (src\RynthCore.PluginSdk\Net, by project reference);
- fragment edge cases: out of order, duplicate, retransmitted, missing (stale),
oversized, slot exhaustion, session reset, malformed datagrams;
- throughput and allocation numbers for the receive-side copy and the reassembly.
Fixtures are built by hand (WireBuilder.cs, plus one hex datagram written out byte by byte).
Extra arguments are .rnc captures from "/rc netmsg capture" to replay and summarise.
Nothing native: no AC, no engine.
Run: dotnet run -c Release [(double dash) capture.rnc ...] (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>NetMessageTests</RootNamespace>
<ServerGarbageCollection>false</ServerGarbageCollection>
<TieredPGO>true</TieredPGO>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\Net\AcPacketWire.cs" Link="Engine\AcPacketWire.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\PacketRing.cs" Link="Engine\PacketRing.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\FragmentReassembler.cs" Link="Engine\FragmentReassembler.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Net\ServerMessageInterest.cs" Link="Engine\ServerMessageInterest.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,969 @@
using System.Buffers.Binary;
using System.Diagnostics;
using RynthCore.Engine.Net;
using RynthCore.PluginSdk.Net;
namespace NetMessageTests;
/// <summary>Collects what the reassembler hands over (copied: the pointer is only valid during the call).</summary>
internal sealed unsafe class Collect : IServerMessageSink
{
public readonly List<(uint Seq, byte[] Bytes)> Messages = new();
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
=> Messages.Add((fragmentSequence, new ReadOnlySpan<byte>(message, length).ToArray()));
}
/// <summary>Counts only (the perf runs: no copies).</summary>
internal sealed unsafe class CountOnly : IServerMessageSink
{
public long Count, Bytes;
public uint OpcodeXor;
public void OnServerMessage(uint fragmentSequence, byte* message, int length)
{
Count++;
Bytes += length;
OpcodeXor ^= *(uint*)message;
}
}
internal static unsafe class Program
{
private static int _checks, _failed;
private static string _case = "";
private static long _now = 1_000_000;
private static int Main(string[] args)
{
// Datagram walk
WalkPlain();
WalkOptionalHeaders();
WalkBadDatagrams();
GoldenHexDatagram();
// Reassembly
SingleFragment();
MultiFragmentInOrder();
MultiFragmentOutOfOrder();
DuplicateFragmentsAndRetransmits();
MissingFragmentGoesStale();
Oversized();
InconsistentAndBadFragments();
SlotExhaustion();
SeveralMessagesPerDatagram();
SessionReset();
DoneWindowSlides();
// Ring, interest
RingBasics();
RingWrapAndFull();
RingCounterWrap();
RingThreaded();
Interest();
// Parsers
Strings();
ChatParsers();
FellowshipParsers();
FriendsAndAllegiance();
SystemTextAndConfirmation();
TruncationNeverThrows();
EndToEndGameEvents();
// Captures given on the command line
foreach (string path in args)
Replay(path);
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL NET MESSAGE TESTS PASSED." : $"{_failed} FAILED.");
Performance();
return _failed == 0 ? 0 : 1;
}
// ── helpers ─────────────────────────────────────────────────────────────
private static void Feed(FragmentReassembler r, byte[] datagram, IServerMessageSink sink)
{
fixed (byte* p = datagram)
r.ProcessDatagram(p, datagram.Length, _now, sink);
}
private static PacketWalk Walk(byte[] d, out int start, out int end)
{
fixed (byte* p = d)
return AcPacketWire.LocateFragments(p, d.Length, out start, out end);
}
private static byte[] Msg(int length, uint opcode = 0xF745, byte seed = 1)
{
var b = new byte[length];
if (length >= 4) BinaryPrimitives.WriteUInt32LittleEndian(b, opcode);
for (int i = 4; i < length; i++) b[i] = (byte)(seed + i * 7);
return b;
}
private static void Case(string name)
{
_case = name;
Console.WriteLine($"- {name}");
}
private static void Eq<T>(T actual, T expected, string what) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}");
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
// ── datagram walk ───────────────────────────────────────────────────────
private static void WalkPlain()
{
Case("walk: one fragment, no optional headers");
byte[] d = Datagram.Frags(new Frag(1, 1, 0, Msg(40)));
Eq(Walk(d, out int s, out int e), PacketWalk.Ok, "status");
Eq(s, 20, "fragments start after the 20-byte header");
Eq(e, d.Length, "fragments end at the datagram end");
Case("walk: no BlobFragments flag (ack only)");
byte[] ack = Datagram.Build(Datagram.AckSequence);
Eq(Walk(ack, out _, out _), PacketWalk.NoFragments, "status");
}
private static void WalkOptionalHeaders()
{
Case("walk: ack + time sync + echo response + flow before the fragments");
uint flags = Datagram.AckSequence | Datagram.TimeSync | Datagram.EchoResponse | Datagram.Flow;
byte[] d = Datagram.Build(flags, 0, null, new Frag(1, 1, 0, Msg(30)));
Eq(Walk(d, out int s, out _), PacketWalk.Ok, "status");
Eq(s, 20 + 4 + 8 + 8 + 6, "fragment start skips 26 bytes of optional headers");
Case("walk: reject-retransmit list (u32 count + ids)");
byte[] r = Datagram.Build(Datagram.RejectRetransmit | Datagram.AckSequence, 3, null, new Frag(1, 1, 0, Msg(12)));
Eq(Walk(r, out s, out _), PacketWalk.Ok, "status");
Eq(s, 20 + 4 + 12 + 4, "start after the list and the ack");
Case("walk: a header this reader can't size (referral) is skipped, not guessed");
byte[] referral = Datagram.Build(Datagram.Referral, 0, null, new Frag(1, 1, 0, Msg(12)));
Eq(Walk(referral, out _, out _), PacketWalk.UnknownOptional, "status");
}
private static void WalkBadDatagrams()
{
Case("walk: malformed datagrams are rejected whole");
Eq(Walk(new byte[10], out _, out _), PacketWalk.Malformed, "shorter than a header");
byte[] good = Datagram.Frags(new Frag(1, 1, 0, Msg(40)));
Eq(Walk(good[..^1], out _, out _), PacketWalk.Malformed, "header size runs past the bytes received");
byte[] longer = Datagram.Build(0, 0, 40 + 16 + 4, new Frag(1, 1, 0, Msg(40)));
Eq(Walk(longer, out _, out _), PacketWalk.Malformed, "header size larger than the datagram");
byte[] fragTooBig = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 16 + 41));
Eq(Walk(fragTooBig, out _, out _), PacketWalk.Malformed, "fragment size past the end");
byte[] fragTooSmall = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 15));
Eq(Walk(fragTooSmall, out _, out _), PacketWalk.Malformed, "fragment size under its header");
byte[] gap = Datagram.Build(0, 0, 40 + 16 + 3, new Frag(1, 1, 0, Msg(40)));
Array.Resize(ref gap, gap.Length + 3);
Eq(Walk(gap, out _, out _), PacketWalk.Malformed, "fragments don't tile the declared size");
byte[] none = Datagram.Build(Datagram.BlobFragments);
Eq(Walk(none, out _, out _), PacketWalk.Malformed, "fragment flag with no fragment");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, good[..^1], c);
Feed(r, longer, c);
Eq(c.Messages.Count, 0, "nothing delivered from malformed datagrams");
Eq(r.PacketsMalformed, 2L, "malformed counter");
}
/// <summary>
/// One datagram written out byte by byte: packet seq 5, flags 0x4004 (ack + fragments),
/// size 44, ack 4; fragment seq 0x10, id 0x80000001, count 1, size 40, index 0, queue 10;
/// message HearEmote 0x01E0 from 0x50000002 "Bob": "waves."
/// </summary>
private static void GoldenHexDatagram()
{
Case("golden datagram: HearEmote, hand-written bytes");
byte[] d = Convert.FromHexString(
"05000000" + "04400000" + "00000000" + "0100" + "0000" + "2C00" + "0000" + // header
"04000000" + // ack
"10000000" + "01000080" + "0100" + "2800" + "0000" + "0A00" + // fragment header
"E0010000" + "02000050" + "0300" + "426F62" + "000000" + "0600" + "77617665732E"); // message
Eq(d.Length, 64, "64 bytes");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, d, c);
Eq(c.Messages.Count, 1, "one message");
if (c.Messages.Count != 1) return;
Eq(c.Messages[0].Seq, 0x10u, "fragment sequence");
Check(ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m), "wraps");
Eq(m.Opcode, ServerOpcode.HearEmote, "opcode");
NetMessageInfo info = NetMessages.Inspect(m);
Check(info.Parsed && info.Leftover == 0, $"parsed with nothing left ({info.Kind} parsed={info.Parsed} leftover={info.Leftover})");
var e = info.Value as HearEmote;
Eq(e?.SenderId, 0x50000002u, "sender");
Eq(e?.SenderName, "Bob", "name");
Eq(e?.Text, "waves.", "text");
}
// ── reassembly ──────────────────────────────────────────────────────────
private static void SingleFragment()
{
Case("one-fragment message is delivered as is");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(100, 0xF7B0);
Feed(r, Datagram.Frags(new Frag(5, 1, 0, m)), c);
Eq(c.Messages.Count, 1, "delivered");
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact");
Eq(r.MultiFragmentMessages, 0L, "not counted as multi-fragment");
}
private static void MultiFragmentInOrder()
{
Case("multi-fragment message, fragments in order, one per datagram");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(448 * 3 + 17, 0xF7B0);
foreach (Frag f in Datagram.Split(9, m))
{
Eq(c.Messages.Count, 0, $"nothing before the last fragment (index {f.Index})");
Feed(r, Datagram.Frags(f), c);
}
Eq(c.Messages.Count, 1, "delivered once complete");
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes reassembled exactly");
Eq(r.PartialCount, 0, "slot freed");
}
private static void MultiFragmentOutOfOrder()
{
Case("multi-fragment message, fragments reversed and shuffled");
var rng = new Random(1234);
for (int trial = 0; trial < 50; trial++)
{
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(rng.Next(449, 448 * 20), 0xF7B0, (byte)trial);
Frag[] frags = Datagram.Split((uint)(100 + trial), m);
if (trial == 0) Array.Reverse(frags); else rng.Shuffle(frags);
foreach (Frag f in frags) Feed(r, Datagram.Frags(f), c);
if (c.Messages.Count != 1 || !c.Messages[0].Bytes.AsSpan().SequenceEqual(m))
{
Check(false, $"trial {trial}: {frags.Length} fragments not reassembled exactly ({c.Messages.Count} delivered)");
return;
}
}
Check(true, "50 random orders reassembled exactly");
Case("uneven fragment sizes still pack together");
var r2 = new FragmentReassembler();
var c2 = new Collect();
byte[] whole = Msg(300, 0xF7B0);
Feed(r2, Datagram.Frags(new Frag(77, 3, 2, whole[250..])), c2);
Feed(r2, Datagram.Frags(new Frag(77, 3, 0, whole[..100])), c2);
Feed(r2, Datagram.Frags(new Frag(77, 3, 1, whole[100..250])), c2);
Check(c2.Messages.Count == 1 && c2.Messages[0].Bytes.AsSpan().SequenceEqual(whole), "100 + 150 + 50 bytes");
}
private static void DuplicateFragmentsAndRetransmits()
{
Case("duplicate fragments and retransmitted datagrams");
var r = new FragmentReassembler();
var c = new Collect();
byte[] m = Msg(1000, 0xF7B0);
Frag[] f = Datagram.Split(20, m);
Feed(r, Datagram.Frags(f[0]), c);
Feed(r, Datagram.Frags(f[0]), c); // duplicate while partial
Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, f[1]), c);
Feed(r, Datagram.Frags(f[2]), c);
Eq(c.Messages.Count, 1, "delivered once");
Eq(r.DuplicateFragments, 1L, "one duplicate while partial");
foreach (Frag x in f) Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, x), c); // whole message again
Eq(c.Messages.Count, 1, "a retransmitted complete message isn't delivered twice");
Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c);
Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c);
Eq(c.Messages.Count, 2, "one-fragment message delivered once");
Eq(r.DuplicateMessages, 1L, "duplicate one-fragment message counted");
Check(c.Messages.Count == 2 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact");
}
private static void MissingFragmentGoesStale()
{
Case("a message missing a fragment is dropped after StaleMs, then a late fragment can't revive it");
var r = new FragmentReassembler();
var c = new Collect();
Frag[] f = Datagram.Split(30, Msg(1500, 0xF7B0));
Feed(r, Datagram.Frags(f[0]), c);
Feed(r, Datagram.Frags(f[1]), c);
Eq(r.PartialCount, 1, "one partial");
_now += FragmentReassembler.StaleMs + 1;
Feed(r, Datagram.Frags(new Frag(31, 1, 0, Msg(10))), c); // any traffic runs the eviction
Eq(r.PartialCount, 0, "evicted");
Eq(r.EvictedStale, 1L, "stale counter");
Feed(r, Datagram.Frags(f[2]), c);
Feed(r, Datagram.Frags(f[3]), c);
Eq(c.Messages.Count(m => m.Seq == 30), 0, "never delivered incomplete");
Eq(r.PartialCount, 0, "late fragments don't start a new partial");
Eq(r.DuplicateFragments, 2L, "they count as fragments of a finished sequence");
}
private static void Oversized()
{
Case("oversized messages are dropped and remembered");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 0, Msg(448))), c);
Eq(r.Oversized, 1L, "too many fragments");
Eq(r.PartialCount, 0, "no slot taken");
Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 1, Msg(448))), c);
Eq(r.DuplicateFragments, 1L, "its other fragments are ignored as done");
byte[] big = Msg(FragmentReassembler.FragmentStride + 1, 0xF7B0);
Feed(r, Datagram.Frags(new Frag(41, 2, 0, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(41, 2, 1, big)), c);
Eq(r.Oversized, 2L, "fragment body over the stride");
Eq(r.PartialCount, 0, "its partial dropped");
Eq(c.Messages.Count, 0, "nothing delivered");
Case("largest allowed message still reassembles");
byte[] max = Msg(448 * FragmentReassembler.MaxFragments, 0xF7B0);
foreach (Frag f in Datagram.Split(42, max)) Feed(r, Datagram.Frags(f), c);
Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(max), $"{max.Length} bytes in {FragmentReassembler.MaxFragments} fragments");
}
private static void InconsistentAndBadFragments()
{
Case("bad fragments: index >= count, count 0, count changes mid-message, body under 4 bytes");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(50, 2, 2, Msg(10))), c);
Feed(r, Datagram.Frags(new Frag(51, 0, 0, Msg(10))), c);
Feed(r, Datagram.Frags(new Frag(52, 3, 0, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(52, 4, 1, Msg(448))), c);
Feed(r, Datagram.Frags(new Frag(53, 1, 0, new byte[] { 1, 2, 3 })), c);
Eq(r.BadFragments, 4L, "four bad fragments counted");
Eq(c.Messages.Count, 0, "nothing delivered");
}
private static void SlotExhaustion()
{
Case("more partial messages than slots: the least recently touched is dropped");
var r = new FragmentReassembler();
var c = new Collect();
for (uint s = 0; s <= FragmentReassembler.MaxPartials; s++)
{
_now += 1;
Feed(r, Datagram.Frags(new Frag(60 + s, 2, 0, Msg(448, 0xF7B0, (byte)s))), c);
}
Eq(r.PartialCount, FragmentReassembler.MaxPartials, "slots full");
Eq(r.EvictedFull, 1L, "one evicted");
Feed(r, Datagram.Frags(new Frag(60, 2, 1, Msg(100))), c);
Eq(c.Messages.Count(m => m.Seq == 60), 0, "the evicted (oldest) message doesn't complete");
Eq(r.EvictedFull, 1L, "and its straggler evicts nothing else");
Feed(r, Datagram.Frags(new Frag(61, 2, 1, Msg(100))), c);
Eq(c.Messages.Count(m => m.Seq == 61), 1, "the next one does");
}
private static void SeveralMessagesPerDatagram()
{
Case("several fragments of different messages in one datagram, interleaved");
var r = new FragmentReassembler();
var c = new Collect();
byte[] a = Msg(700, 0xF7B0, 3), b = Msg(30, 0x02BB, 4), d = Msg(900, 0xF745, 5);
Frag[] fa = Datagram.Split(70, a, 400), fd = Datagram.Split(72, d, 400);
Feed(r, Datagram.Frags(fa[0], new Frag(71, 1, 0, b), fd[2]), c);
Feed(r, Datagram.Frags(fd[0], fa[1]), c);
Feed(r, Datagram.Frags(fd[1]), c);
Eq(c.Messages.Count, 3, "three messages");
Eq(string.Join(",", c.Messages.Select(m => m.Seq)), "71,70,72", "completion order");
Check(c.Messages.Count == 3 && c.Messages[1].Bytes.AsSpan().SequenceEqual(a) && c.Messages[2].Bytes.AsSpan().SequenceEqual(d), "bytes intact");
}
private static void SessionReset()
{
Case("a ConnectRequest (new session) restarts the sequence window");
var r = new FragmentReassembler();
var c = new Collect();
for (uint s = 1; s <= 50; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 50, "an old sequence is a duplicate within a session");
Feed(r, Datagram.Build(Datagram.ConnectRequest), c);
Eq(r.SessionResets, 1L, "reset seen");
Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 51, "the same sequence is new after the reset");
}
private static void DoneWindowSlides()
{
Case("the done window slides: a long-finished sequence is still rejected, recent ones tracked by bit");
var r = new FragmentReassembler();
var c = new Collect();
Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(10 + FragmentReassembler.DoneWindow + 5, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 2, "far-behind sequence rejected");
Feed(r, Datagram.Frags(new Frag(20 + FragmentReassembler.DoneWindow, 1, 0, Msg(8))), c);
Eq(c.Messages.Count, 3, "a sequence inside the window that never completed is accepted");
// A partial that started before many later one-fragment messages still completes.
Frag[] f = Datagram.Split(30000, Msg(900, 0xF7B0));
Feed(r, Datagram.Frags(f[0]), c);
for (uint s = 30001; s < 30001 + 1000; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c);
Feed(r, Datagram.Frags(f[1]), c);
Feed(r, Datagram.Frags(f[2]), c);
Eq(c.Messages.Count(m => m.Seq == 30000), 1, "slow multi-fragment message completes behind 1000 newer ones");
}
// ── ring ────────────────────────────────────────────────────────────────
private static bool Read(PacketRing ring, out byte[] data, out uint stamp)
{
data = Array.Empty<byte>();
if (!ring.TryPeek(out byte* p, out int len, out stamp, out int rel)) return false;
data = new ReadOnlySpan<byte>(p, len).ToArray();
ring.Release(rel);
return true;
}
private static bool Write(PacketRing ring, byte[] d, uint stamp = 0)
{
fixed (byte* p = d) return ring.TryWrite(p, d.Length, stamp);
}
private static void RingBasics()
{
Case("ring: FIFO, stamps, too-long rejected");
var ring = new PacketRing(4096);
Check(Write(ring, Msg(100, 1), 11) && Write(ring, Msg(3, 2), 22), "two writes");
Check(Read(ring, out byte[] a, out uint sa) && a.Length == 100 && sa == 11, "first back");
Check(Read(ring, out byte[] b, out uint sb) && b.Length == 3 && sb == 22, "second back");
Check(!Read(ring, out _, out _), "empty");
Check(!Write(ring, new byte[PacketRing.MaxDatagram + 1]), "too long refused");
Eq(ring.DroppedTooLong, 1L, "counted");
}
private static void RingWrapAndFull()
{
Case("ring: wraps at the end, drops (never waits) when full");
var ring = new PacketRing(4096);
int wrote = 0, read = 0;
var rng = new Random(7);
var pending = new Queue<byte[]>();
for (int i = 0; i < 5000; i++)
{
byte[] d = Msg(rng.Next(20, 500), (uint)i, (byte)i);
if (Write(ring, d)) { pending.Enqueue(d); wrote++; }
if (rng.Next(3) == 0)
while (Read(ring, out byte[] got, out _))
{
read++;
if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, $"datagram {read} corrupted across a wrap"); return; }
}
}
while (Read(ring, out byte[] got, out _)) { read++; if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, "tail corrupted"); return; } }
Eq(read, wrote, "everything written was read back intact, in order");
Check(ring.DroppedFull > 0, $"some writes were refused while full ({ring.DroppedFull})");
Eq(ring.Written, (long)wrote, "written counter");
}
private static void RingCounterWrap()
{
Case("ring: the byte counters wrap past int.MaxValue");
var ring = new PacketRing(4096, int.MaxValue - 3000);
int ok = 0;
for (int i = 0; i < 200; i++)
{
byte[] d = Msg(100 + i, (uint)i, (byte)i);
if (!Write(ring, d) || !Read(ring, out byte[] got, out _) || !got.AsSpan().SequenceEqual(d)) break;
ok++;
}
Eq(ok, 200, "200 round trips across the wrap");
Eq(ring.Used, 0, "empty after");
}
private static void RingThreaded()
{
Case("ring: one producer thread, one consumer thread, 200k datagrams");
var ring = new PacketRing(64 * 1024);
const int N = 200_000;
int produced = 0;
var t = new Thread(() =>
{
byte[] d = new byte[400];
for (int i = 0; i < N; i++)
{
int len = 20 + (i % 380);
BinaryPrimitives.WriteInt32LittleEndian(d, i);
d[len - 1] = (byte)i;
while (!Write(ring, d[..len], (uint)i)) Thread.SpinWait(20); // the test retries; the hook drops
produced++;
}
});
t.Start();
int expect = 0;
bool ok = true;
var sw = Stopwatch.StartNew();
while (expect < N && sw.Elapsed.TotalSeconds < 30)
{
if (!Read(ring, out byte[] got, out uint stamp)) { Thread.SpinWait(10); continue; }
int len = 20 + (expect % 380);
if (got.Length != len || BinaryPrimitives.ReadInt32LittleEndian(got) != expect || got[len - 1] != (byte)expect || stamp != (uint)expect)
{
ok = false;
break;
}
expect++;
}
t.Join();
Check(ok && expect == N, $"all {N} datagrams in order and intact (got {expect})");
}
private static void Interest()
{
Case("interest sets");
var s = new ServerMessageInterest();
Check(s.IsEmpty, "starts empty");
uint[] ops = { 0x02BB, 0x01E0 };
uint[] evs = { 0x02BE, 0x0021 };
fixed (uint* o = ops) fixed (uint* e = evs) Check(s.Set(o, 2, e, 2), "set");
Check(s.Wants(0x02BB, 0) && s.Wants(0x01E0, 0), "listed opcodes");
Check(!s.Wants(0xF745, 0), "unlisted opcode");
Check(s.Wants(0xF7B0, 0x02BE) && s.Wants(0xF7B0, 0x0021), "listed game events");
Check(!s.Wants(0xF7B0, 0x02C2), "unlisted game event");
Check(!s.Wants(0x1_0000, 0), "out-of-range opcode never wanted");
uint[] allEv = { 0xF7B0 };
fixed (uint* o = allEv) Check(s.Set(o, 1, null, 0), "0xF7B0 alone");
Check(s.Wants(0xF7B0, 0x1234) && !s.Wants(0x02BB, 0), "every game event, nothing else");
uint[] all = { 0xFFFFFFFF };
fixed (uint* o = all) Check(s.Set(o, 1, null, 0), "all");
Check(s.Wants(0xF745, 0) && s.Wants(0xF7B0, 5), "everything");
uint[] bad = { 0x02BB, 0x10000 };
fixed (uint* o = bad) Check(!s.Set(o, 2, null, 0), "an out-of-range opcode refuses the whole set");
Check(s.IsEmpty, "and leaves it empty");
Check(!s.Set(null, 3, null, 0), "null with a count refused");
Check(s.Set(null, 0, null, 0) && s.IsEmpty, "empty set = off");
}
// ── parsers ─────────────────────────────────────────────────────────────
private static void Strings()
{
Case("String16L: lengths 0-6 pad to 4, Latin-1, long form refused");
for (int len = 0; len <= 6; len++)
{
string text = new string('x', len);
byte[] b = new Body().Str(text).U32(0xDEADBEEF).ToArray();
Eq(b.Length % 4, 0, $"length {len} padded");
var r = new NetReader(b);
Check(r.String16L(out string got) && got == text && r.U32(out uint tail) && tail == 0xDEADBEEF, $"length {len} round trip");
}
var lat = new NetReader(new Body().Str("Café Æthel").ToArray());
Check(lat.String16L(out string l) && l == "Café Æthel", "Latin-1 characters");
var lng = new NetReader(new byte[] { 0xFF, 0xFF, 4, 0, 0, 0, 1, 2, 3, 4 });
Check(!lng.String16L(out _), "0xFFFF long form refused");
var shortStr = new NetReader(new byte[] { 10, 0, 1, 2 });
Check(!shortStr.String16L(out _), "length past the end refused");
}
private static NetMessageInfo InspectTop(uint opcode, Body body)
{
ServerMessage.TryFromWire(body.Message(opcode), out ServerMessage m);
return NetMessages.Inspect(m);
}
private static NetMessageInfo InspectEvent(uint type, Body body)
{
ServerMessage.TryFromWire(body.GameEvent(type), out ServerMessage m);
return NetMessages.Inspect(m);
}
private static void Clean(NetMessageInfo i, string kind)
{
Eq(i.Kind, kind, "kind");
Check(i.Known && i.Parsed, $"{kind} parsed");
Eq(i.Leftover, 0, $"{kind} leftover");
}
private static void ChatParsers()
{
Case("HearSpeech 0x02BB");
var i = InspectTop(0x02BB, new Body().Str("Hello there").Str("Aria").U32(0x50000010).U32(2));
Clean(i, "HearSpeech");
var s = (HearSpeech)i.Value!;
Check(s.Text == "Hello there" && s.SenderName == "Aria" && s.SenderId == 0x50000010 && s.ChatType == 2, "fields");
Case("HearRangedSpeech 0x02BC");
i = InspectTop(0x02BC, new Body().Str("Help!").Str("Town Crier").U32(0x7A000001).F32(37.5f).U32(12));
Clean(i, "HearRangedSpeech");
var rs = (HearRangedSpeech)i.Value!;
Check(rs.Text == "Help!" && rs.SenderName == "Town Crier" && rs.SenderId == 0x7A000001 && rs.Range == 37.5f && rs.ChatType == 12, "fields");
Case("HearEmote 0x01E0 / HearSoulEmote 0x01E2");
i = InspectTop(0x01E0, new Body().U32(0x50000011).Str("Bren").Str("bows deeply."));
Clean(i, "HearEmote");
var e = (HearEmote)i.Value!;
Check(e.SenderId == 0x50000011 && e.SenderName == "Bren" && e.Text == "bows deeply." && !e.Soul, "emote fields");
i = InspectTop(0x01E2, new Body().U32(0x50000012).Str("Cy").Str("*laughs*"));
Clean(i, "HearSoulEmote");
Check(((HearEmote)i.Value!).Soul, "soul flag");
Case("HearDirectSpeech (tell) game event 0x02BD");
i = InspectEvent(0x02BD, new Body().Str("psst").Str("Dax").U32(0x50000013).U32(0x50000001).U32(3).U32(0));
Clean(i, "HearDirectSpeech");
var t = (HearDirectSpeech)i.Value!;
Check(t.Text == "psst" && t.SenderName == "Dax" && t.SenderId == 0x50000013 && t.TargetId == 0x50000001 && t.ChatType == 3 && t.Flags == 0, "fields");
Case("ChannelBroadcast game event 0x0147");
i = InspectEvent(0x0147, new Body().U32(0x800).Str("").Str("pulling now"));
Clean(i, "ChannelBroadcast");
var cb = (ChannelBroadcast)i.Value!;
Check(cb.Channel == 0x800 && cb.SenderName == "" && cb.Text == "pulling now", "own line: empty sender");
}
private static Body FellowBody(Body b, uint id, string name, uint level, bool shareLoot)
=> b.U32(id).U32(1000).U32(10).U32(level).U32(300).U32(250).U32(200).U32(280).U32(240).U32(190).Bool(shareLoot).Str(name);
private static void FellowshipParsers()
{
Case("FellowshipFullUpdate 0x02BE: members, flags, departed, locks");
var b = new Body().TableHeader(2);
FellowBody(b, 0x50000001, "Leader Lee", 126, true);
FellowBody(b, 0x50000002, "Bo", 80, false);
b.Str("Hunters").U32(0x50000001).Bool(true).Bool(false).Bool(true).Bool(false);
b.TableHeader(1).U32(0x50000003).I32(1234);
b.TableHeader(1).Str("Lugian Citadel").U32(1).U32(2).U32(3).U32(4).U32(5);
var i = InspectEvent(0x02BE, b);
Clean(i, "FellowshipFullUpdate");
var f = (FellowshipFullUpdate)i.Value!;
Check(f.Name == "Hunters" && f.LeaderId == 0x50000001 && f.ShareXp && !f.EvenXpSplit && f.Open && !f.Locked, "header fields");
Eq(f.Fellows.Count, 2, "members");
var lee = f.Fellows[0];
Check(lee.Id == 0x50000001 && lee.Name == "Leader Lee" && lee.Level == 126 && lee.XpCached == 1000 && lee.LumCached == 10 &&
lee.MaxHealth == 300 && lee.MaxStamina == 250 && lee.MaxMana == 200 && lee.Health == 280 && lee.Stamina == 240 && lee.Mana == 190 && lee.ShareLoot, "fellow fields");
Check(!f.Fellows[1].ShareLoot && f.Fellows[1].Name == "Bo", "second fellow");
Check(f.TailParsed && f.RecentlyDeparted.TryGetValue(0x50000003, out int when) && when == 1234 && f.LockNames.SequenceEqual(new[] { "Lugian Citadel" }), "tail");
Case("FellowshipFullUpdate whose tail doesn't fit: members still returned, leftover reported");
var b2 = new Body().TableHeader(1);
FellowBody(b2, 0x50000001, "Solo", 50, true);
b2.Str("One").U32(0x50000001).Bool(false).Bool(true).Bool(false).Bool(true);
b2.Bytes(0x01, 0x02); // a tail this layout doesn't know
i = InspectEvent(0x02BE, b2);
Check(i.Parsed && i.Leftover == 2, $"parsed with 2 leftover (parsed={i.Parsed} leftover={i.Leftover})");
var f2 = (FellowshipFullUpdate)i.Value!;
Check(!f2.TailParsed && f2.Fellows.Count == 1 && f2.Locked, "main fields kept, tail flagged unread");
Case("FellowshipUpdateFellow 0x02C0");
// fellow id, xp, lum, level, max h/s/m, current h/s/m, share loot, name, update type
var u = new Body().U32(0x50000002).U32(1000).U32(10).U32(81).U32(300).U32(250).U32(200).U32(100).U32(50).U32(25).Bool(false).Str("Bo").U32(3);
i = InspectEvent(0x02C0, u);
Clean(i, "FellowshipUpdateFellow");
var uf = (FellowshipUpdateFellow)i.Value!;
Check(uf.Fellow.Id == 0x50000002 && uf.Fellow.Level == 81 && uf.Fellow.Health == 100 && uf.UpdateType == 3, "fields");
Case("FellowshipQuit 0x00A3, FellowshipDismiss 0x00A4, FellowshipDisband 0x02BF");
i = InspectEvent(0x00A3, new Body().U32(0x50000004));
Clean(i, "FellowshipQuit");
Check(((FellowshipMemberLeft)i.Value!).FellowId == 0x50000004 && !((FellowshipMemberLeft)i.Value!).Dismissed, "quit");
i = InspectEvent(0x00A4, new Body().U32(0x50000005));
Clean(i, "FellowshipDismiss");
Check(((FellowshipMemberLeft)i.Value!).Dismissed, "dismiss");
i = InspectEvent(0x02BF, new Body());
Clean(i, "FellowshipDisband");
}
private static void FriendsAndAllegiance()
{
Case("FriendsUpdate 0x0021: full list");
var b = new Body().U32(2)
.U32(0x50000020).Bool(true).Bool(false).Str("Ana").U32List(0x50000001).U32List()
.U32(0x50000021).Bool(false).Bool(true).Str("Bertram").U32List().U32List(0x50000001, 0x50000002)
.U32(FriendsUpdate.Full);
var i = InspectEvent(0x0021, b);
Clean(i, "FriendsUpdate");
var fu = (FriendsUpdate)i.Value!;
Eq(fu.Friends.Count, 2, "two friends");
Check(fu.Friends[0].Id == 0x50000020 && fu.Friends[0].Online && !fu.Friends[0].AppearOffline && fu.Friends[0].Name == "Ana" &&
fu.Friends[0].OutFriends.SequenceEqual(new uint[] { 0x50000001 }) && fu.Friends[0].InFriends.Length == 0, "first");
Check(!fu.Friends[1].Online && fu.Friends[1].AppearOffline && fu.Friends[1].InFriends.Length == 2, "second");
Eq(fu.UpdateType, FriendsUpdate.Full, "update type");
Case("FriendsUpdate: login change for one friend");
i = InspectEvent(0x0021, new Body().U32(1).U32(0x50000020).Bool(false).Bool(false).Str("Ana").U32List().U32List().U32(FriendsUpdate.LoginChange));
Clean(i, "FriendsUpdate");
Check(((FriendsUpdate)i.Value!).UpdateType == FriendsUpdate.LoginChange, "type 4");
Case("FriendsUpdate: absurd count refused without allocating it");
i = InspectEvent(0x0021, new Body().U32(0x7FFFFFFF).U32(0));
Check(i.Known && !i.Parsed, "refused");
Case("AllegianceLoginNotification 0x027A");
i = InspectEvent(0x027A, new Body().U32(0x50000030).Bool(true));
Clean(i, "AllegianceLoginNotification");
var a = (AllegianceLoginNotification)i.Value!;
Check(a.CharacterId == 0x50000030 && a.LoggedIn, "fields");
}
private static void SystemTextAndConfirmation()
{
Case("PopUpString 0x0004, TransientString 0x02EB");
var i = InspectEvent(0x0004, new Body().Str("You have been booted."));
Clean(i, "PopUpString");
Check(((SystemText)i.Value!).Text == "You have been booted." && !((SystemText)i.Value!).Transient, "popup");
i = InspectEvent(0x02EB, new Body().Str("You're too busy!"));
Clean(i, "TransientString");
Check(((SystemText)i.Value!).Transient, "transient");
Case("ConfirmationRequest 0x0274");
i = InspectEvent(0x0274, new Body().U32(4).U32(0x1234).Str("Ana has invited you to join a fellowship."));
Clean(i, "ConfirmationRequest");
var c = (ConfirmationRequest)i.Value!;
Check(c.ConfirmationType == 4 && c.ContextId == 0x1234 && c.Text.StartsWith("Ana has invited"), "fields");
Case("unknown messages are reported as unknown");
i = InspectTop(0xF745, new Body().U32(1));
Check(!i.Known, "top-level");
i = InspectEvent(0x02C2, new Body().U32(1));
Check(!i.Known, "game event");
}
private static void TruncationNeverThrows()
{
Case("every parser, every truncation of its fixture: false, no exception");
var fixtures = new List<(string, byte[])>
{
("speech", new Body().Str("Hello there").Str("Aria").U32(1).U32(2).Message(0x02BB)),
("ranged", new Body().Str("Help!").Str("Crier").U32(1).F32(1).U32(2).Message(0x02BC)),
("emote", new Body().U32(1).Str("Bren").Str("bows.").Message(0x01E0)),
("tell", new Body().Str("psst").Str("Dax").U32(1).U32(2).U32(3).U32(0).GameEvent(0x02BD)),
("channel", new Body().U32(1).Str("A").Str("B").GameEvent(0x0147)),
("friends", new Body().U32(1).U32(1).Bool(true).Bool(false).Str("Ana").U32List(5).U32List(6).U32(0).GameEvent(0x0021)),
("allegiance", new Body().U32(1).Bool(true).GameEvent(0x027A)),
("confirm", new Body().U32(4).U32(5).Str("ok?").GameEvent(0x0274)),
("popup", new Body().Str("hi").GameEvent(0x0004)),
("update fellow", new Body().U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).Bool(true).Str("Bo").U32(1).GameEvent(0x02C0)),
("quit", new Body().U32(1).GameEvent(0x00A3)),
};
var full = new Body().TableHeader(1);
FellowBody(full, 1, "Lee", 5, true);
full.Str("F").U32(1).Bool(true).Bool(true).Bool(true).Bool(true).TableHeader(0).TableHeader(0);
fixtures.Add(("fellowship", full.GameEvent(0x02BE)));
int cuts = 0;
foreach ((string name, byte[] wire) in fixtures)
{
ServerMessage.TryFromWire(wire, out ServerMessage whole);
NetMessageInfo w = NetMessages.Inspect(whole);
if (!w.Parsed || w.Leftover != 0) { Check(false, $"{name}: full fixture should parse cleanly"); continue; }
int headerLen = whole.IsGameEvent ? 16 : 4;
for (int len = headerLen; len < wire.Length; len++)
{
try
{
ServerMessage.TryFromWire(wire.AsSpan(0, len), out ServerMessage m);
NetMessageInfo i = NetMessages.Inspect(m);
// A cut on a string's padding or the fellowship tail can still parse; it must then report what it used.
if (i.Parsed && name != "fellowship" && i.Leftover != 0) Check(false, $"{name} cut at {len}: parsed but leftover {i.Leftover}");
cuts++;
}
catch (Exception ex)
{
Check(false, $"{name} cut at {len} threw {ex.GetType().Name}");
}
}
}
Check(cuts > 300, $"{cuts} truncations tried");
}
private static void EndToEndGameEvents()
{
Case("end to end: a 3-datagram fellowship update, out of order, through ring and reassembler to the parser");
var b = new Body().TableHeader(9);
for (uint n = 0; n < 9; n++) FellowBody(b, 0x50000100 + n, $"Member number {n} with a long name", 100 + n, n % 2 == 0);
b.Str("A fellowship with a long name").U32(0x50000100).Bool(true).Bool(true).Bool(false).Bool(false).TableHeader(0).TableHeader(0);
byte[] wire = b.GameEvent(0x02BE, 0x50000100, 42);
Frag[] frags = Datagram.Split(500, wire);
Check(frags.Length >= 2, $"{wire.Length} bytes needs {frags.Length} fragments");
var ring = new PacketRing(4096);
var order = frags.Reverse().ToArray();
foreach (Frag f in order) Write(ring, Datagram.Build(Datagram.AckSequence | Datagram.TimeSync, 0, null, f));
var r = new FragmentReassembler();
var c = new Collect();
while (ring.TryPeek(out byte* p, out int len, out _, out int rel))
{
r.ProcessDatagram(p, len, _now, c);
ring.Release(rel);
}
Eq(c.Messages.Count, 1, "one message");
if (c.Messages.Count != 1) return;
ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m);
Check(m.IsGameEvent && m.EventObjectId == 0x50000100 && m.EventSequence == 42 && m.EventType == 0x02BE, "game event header");
Check(FellowshipFullUpdate.TryParse(m.EventBody, out var fs, out int used) && used == m.EventBody.Length, "parsed whole");
Check(fs != null && fs.Fellows.Count == 9 && fs.Fellows[8].Name == "Member number 8 with a long name" && fs.TailParsed, "all members");
}
// ── replay of captures ──────────────────────────────────────────────────
private static void Replay(string path)
{
Case($"replay {Path.GetFileName(path)}");
byte[] file;
try { file = File.ReadAllBytes(path); }
catch (Exception ex) { Check(false, $"read failed: {ex.Message}"); return; }
if (file.Length < 4 || file[0] != 'R' || file[1] != 'N' || file[2] != 'C' || file[3] != '1')
{
Check(false, "not an RNC1 capture");
return;
}
var r = new FragmentReassembler();
var c = new Collect();
int pos = 4, datagrams = 0;
while (pos + 6 <= file.Length)
{
uint stamp = BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos));
int len = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(pos + 4));
pos += 6;
if (pos + len > file.Length) { Check(false, $"truncated record at {pos}"); break; }
fixed (byte* p = &file[pos])
r.ProcessDatagram(p, len, stamp, c);
pos += len;
datagrams++;
}
var byKind = new SortedDictionary<string, (int Ok, int Failed, int Leftover)>();
var opcodes = new Dictionary<string, int>();
foreach (var (_, bytes) in c.Messages)
{
ServerMessage.TryFromWire(bytes, out ServerMessage m);
string key = m.IsGameEvent ? $"F7B0/{m.EventType:X4}" : $"{m.Opcode:X4}";
opcodes[key] = opcodes.GetValueOrDefault(key) + 1;
NetMessageInfo i = NetMessages.Inspect(m);
if (!i.Known) continue;
var k = byKind.GetValueOrDefault(i.Kind);
byKind[i.Kind] = (k.Ok + (i.Parsed ? 1 : 0), k.Failed + (i.Parsed ? 0 : 1), k.Leftover + (i.Parsed && i.Leftover != 0 ? 1 : 0));
if (!i.Parsed || i.Leftover != 0)
Console.WriteLine($" {i.Kind} parsed={i.Parsed} leftover={i.Leftover} bytes={Convert.ToHexString(bytes.AsSpan(0, Math.Min(bytes.Length, 64)))}");
}
Console.WriteLine($" {datagrams} datagrams -> {r.Messages} messages ({r.MultiFragmentMessages} multi-fragment); malformed {r.PacketsMalformed}, " +
$"unknown header {r.PacketsUnknownOptional}, dup {r.DuplicateFragments}, bad {r.BadFragments}, stale {r.EvictedStale}, {r.PartialCount} left partial");
Console.WriteLine($" top opcodes: {string.Join(" ", opcodes.OrderByDescending(o => o.Value).Take(15).Select(o => $"{o.Key}x{o.Value}"))}");
foreach (var (kind, v) in byKind)
Console.WriteLine($" {kind}: {v.Ok} ok, {v.Failed} failed, {v.Leftover} with leftover");
Check(r.PacketsMalformed == 0, "no malformed datagrams in a real capture");
Check(byKind.Values.All(v => v.Failed == 0), "every known message parsed");
}
// ── performance ─────────────────────────────────────────────────────────
private static void Performance()
{
Console.WriteLine();
Console.WriteLine("Performance (synthetic server traffic; Release build, this machine):");
// A mix shaped like play: mostly one-fragment messages of 20-300 bytes, packed 1-3 per
// datagram, plus a 2-8 fragment message every ~25 datagrams; acks and time sync on many.
var rng = new Random(99);
var datagrams = new List<byte[]>();
uint seq = 1;
int msgCount = 0;
while (datagrams.Count < 50_000)
{
if (rng.Next(25) == 0)
{
byte[] big = Msg(rng.Next(900, 448 * 8), 0xF7B0, (byte)seq);
foreach (Frag f in Datagram.Split(seq++, big)) datagrams.Add(Datagram.Build(Datagram.AckSequence, 0, null, f));
msgCount++;
continue;
}
int n = rng.Next(1, 4);
var frags = new Frag[n];
int room = 448;
for (int k = 0; k < n; k++)
{
int len = Math.Min(rng.Next(20, 300), room - 16 * (n - k));
if (len < 8) len = 8;
room -= len + 16;
frags[k] = new Frag(seq++, 1, 0, Msg(len, 0xF749, (byte)k));
msgCount++;
}
uint flags = rng.Next(4) == 0 ? Datagram.AckSequence | Datagram.TimeSync : Datagram.AckSequence;
datagrams.Add(Datagram.Build(flags, 0, null, frags));
}
long totalBytes = datagrams.Sum(d => (long)d.Length);
var pinned = datagrams.Select(d => GC.AllocateArray<byte>(d.Length, pinned: true)).ToArray();
for (int i = 0; i < pinned.Length; i++) datagrams[i].CopyTo(pinned[i], 0);
// 1) Receive side: what the detour does while capturing (flags check + ring write),
// timed in batches of 1024 datagrams (the ring is emptied between batches, untimed).
var ring = new PacketRing(512 * 1024);
const int Rounds = 20, Batch = 1024;
long copies = 0, hookTicks = 0;
for (int round = 0; round < Rounds + 2; round++)
{
bool timed = round >= 2;
for (int i0 = 0; i0 < pinned.Length; i0 += Batch)
{
int i1 = Math.Min(pinned.Length, i0 + Batch);
long t0 = Stopwatch.GetTimestamp();
for (int i = i0; i < i1; i++)
{
byte[] d = pinned[i];
fixed (byte* p = d)
{
uint flags = AcPacketWire.ReadU32(p + 4);
if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) != 0)
ring.TryWrite(p, d.Length, 0);
}
}
long t1 = Stopwatch.GetTimestamp();
if (timed) { hookTicks += t1 - t0; copies += i1 - i0; }
ring.Clear();
}
}
double tickNs = 1e9 / Stopwatch.Frequency;
double hookNs = hookTicks * tickNs / copies;
Console.WriteLine($" receive hook copy: {hookNs:0} ns per datagram (avg {totalBytes / datagrams.Count} bytes), {copies:N0} datagrams; ring drops {ring.DroppedFull}");
// 2) Pump side: ring read + reassembly into a counting sink, timed per drained batch.
var r = new FragmentReassembler();
var sink = new CountOnly();
long allocBefore = 0, processed = 0, pumpTicks = 0, msgsTimed = 0, multiTimed = 0;
for (int round = 0; round < Rounds + 2; round++)
{
bool timed = round >= 2;
r.Reset();
if (round == 2) allocBefore = GC.GetAllocatedBytesForCurrentThread();
long m0 = r.Messages, mm0 = r.MultiFragmentMessages;
for (int i0 = 0; i0 < pinned.Length; i0 += Batch)
{
int i1 = Math.Min(pinned.Length, i0 + Batch);
for (int i = i0; i < i1; i++)
fixed (byte* p = pinned[i])
ring.TryWrite(p, pinned[i].Length, 0);
long t0 = Stopwatch.GetTimestamp();
while (ring.TryPeek(out byte* rp, out int len, out _, out int rel))
{
r.ProcessDatagram(rp, len, 1000, sink);
ring.Release(rel);
}
long t1 = Stopwatch.GetTimestamp();
if (timed) { pumpTicks += t1 - t0; processed += i1 - i0; }
}
if (timed) { msgsTimed += r.Messages - m0; multiTimed += r.MultiFragmentMessages - mm0; }
}
long allocAfter = GC.GetAllocatedBytesForCurrentThread();
double pumpNs = pumpTicks * tickNs / processed;
Console.WriteLine($" pump (ring read + reassembly): {pumpNs:0} ns per datagram, {pumpTicks * tickNs / msgsTimed:0} ns per message; " +
$"{msgsTimed / Rounds:N0} messages per round of {pinned.Length:N0} datagrams ({multiTimed / Rounds:N0} multi-fragment)");
Console.WriteLine($" steady-state allocation: {(allocAfter - allocBefore) / (double)processed:0.00} bytes per datagram over {processed:N0} datagrams");
// 3) What a busy minute costs: ~100 datagrams/s is heavy play, 400/s a portal into a town.
Console.WriteLine($" at 400 datagrams/s: hook {hookNs * 400 / 1000:0.0} us/s on the receive thread, pump {pumpNs * 400 / 1000:0.0} us/s");
Console.WriteLine(" stream off: the detour adds one volatile bool read (ServerMessageStream.OnDatagram returns at once).");
}
}

View file

@ -0,0 +1,91 @@
using System.Buffers.Binary;
using System.Text;
namespace NetMessageTests;
/// <summary>Little-endian writer for message bodies, in the AC wire types the parsers read.</summary>
internal sealed class Body
{
private readonly List<byte> _b = new();
public byte[] ToArray() => _b.ToArray();
public int Length => _b.Count;
public Body U16(ushort v) { Span<byte> t = stackalloc byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; }
public Body U32(uint v) { Span<byte> t = stackalloc byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; }
public Body I32(int v) => U32(unchecked((uint)v));
public Body F32(float v) => U32(BitConverter.SingleToUInt32Bits(v));
public Body Bool(bool v) => U32(v ? 1u : 0u);
public Body Bytes(params byte[] v) { _b.AddRange(v); return this; }
/// <summary>u16 length, Latin-1 bytes, zero padding so 2 + length is a multiple of 4.</summary>
public Body Str(string s)
{
byte[] raw = Encoding.Latin1.GetBytes(s);
U16((ushort)raw.Length);
_b.AddRange(raw);
for (int pad = (4 - ((2 + raw.Length) & 3)) & 3; pad > 0; pad--) _b.Add(0);
return this;
}
public Body U32List(params uint[] v) { U32((uint)v.Length); foreach (uint x in v) U32(x); return this; }
public Body TableHeader(int count, int buckets = 32) => U16((ushort)count).U16((ushort)buckets);
/// <summary>A whole top-level message: u32 opcode then this body.</summary>
public byte[] Message(uint opcode) => new Body().U32(opcode).Bytes(ToArray()).ToArray();
/// <summary>A whole game event message: 0xF7B0, object id, sequence, event type, this body.</summary>
public byte[] GameEvent(uint eventType, uint objectId = 0x50000001, uint sequence = 7)
=> new Body().U32(0xF7B0).U32(objectId).U32(sequence).U32(eventType).Bytes(ToArray()).ToArray();
}
/// <summary>One fragment for <see cref="Datagram"/>.</summary>
internal readonly record struct Frag(uint Sequence, ushort Count, ushort Index, byte[] Data, uint Id = 0x80000001, ushort Queue = 10, int? SizeOverride = null);
/// <summary>Builds server-to-client datagrams: 20-byte header, optional headers, fragments.</summary>
internal static class Datagram
{
public const uint BlobFragments = 0x4, AckSequence = 0x4000, TimeSync = 0x01000000, EchoResponse = 0x04000000,
Flow = 0x08000000, RejectRetransmit = 0x2000, Referral = 0x800, ConnectRequest = 0x40000, Retransmission = 0x1;
private static uint _packetSeq = 100;
/// <summary>
/// Optional headers are written for the flags given (fixed sizes, zero contents; a reject
/// list gets <paramref name="rejectCount"/> entries). BlobFragments is added when frags are given.
/// </summary>
public static byte[] Build(uint flags, int rejectCount = 0, int? sizeOverride = null, params Frag[] frags)
{
if (frags.Length > 0) flags |= BlobFragments;
var after = new Body();
if ((flags & RejectRetransmit) != 0) { after.U32((uint)rejectCount); for (int i = 0; i < rejectCount; i++) after.U32((uint)(i + 1)); }
if ((flags & AckSequence) != 0) after.U32(99);
if ((flags & ConnectRequest) != 0) after.Bytes(new byte[32]);
if ((flags & TimeSync) != 0) after.Bytes(new byte[8]);
if ((flags & EchoResponse) != 0) after.Bytes(new byte[8]);
if ((flags & Flow) != 0) after.Bytes(new byte[6]);
foreach (Frag f in frags)
{
after.U32(f.Sequence).U32(f.Id).U16(f.Count).U16((ushort)(f.SizeOverride ?? (16 + f.Data.Length))).U16(f.Index).U16(f.Queue);
after.Bytes(f.Data);
}
byte[] tail = after.ToArray();
var d = new Body().U32(_packetSeq++).U32(flags).U32(0).U16(1).U16(0).U16((ushort)(sizeOverride ?? tail.Length)).U16(0);
return d.Bytes(tail).ToArray();
}
public static byte[] Frags(params Frag[] frags) => Build(0, 0, null, frags);
/// <summary>Splits a message into fragments of at most <paramref name="chunk"/> bytes (448 like the server).</summary>
public static Frag[] Split(uint sequence, byte[] message, int chunk = 448)
{
int count = Math.Max(1, (message.Length + chunk - 1) / chunk);
var list = new Frag[count];
for (int i = 0; i < count; i++)
{
int off = i * chunk;
list[i] = new Frag(sequence, (ushort)count, (ushort)i, message.AsSpan(off, Math.Min(chunk, message.Length - off)).ToArray());
}
return list;
}
}

View file

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline checks for the nameplate sizing settings and the Vision overlay opacity sliders
(2026-10-05): src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs and
src\RynthCore.Engine\UI\Data\ArgbOpacity.cs, compiled in. Defaults equal today's look,
the nameplate_settings.txt lines round-trip (old files without the new keys still load),
out-of-range values clamp, and an untouched opacity never changes a colour.
No file I/O: the settings file is written to and read from memory, and the background
writer is a stub that never runs its work (so %LocalAppData%\RynthCore is never touched).
Run: dotnet run -c Release (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PlateSizingTests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\RynthCore.Engine\ImGui\MonsterHud\MonsterHudSettings.cs" Link="Engine\MonsterHudSettings.cs" />
<Compile Include="..\..\src\RynthCore.Engine\UI\Data\ArgbOpacity.cs" Link="Engine\ArgbOpacity.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,231 @@
using System.Globalization;
using RynthCore.Engine.ImGuiBackend.Hud;
using RynthCore.Engine.UI.Data;
namespace RynthCore.Engine.UI
{
/// <summary>Stub: counts saves, never runs them (no file I/O in the tests).</summary>
internal static class UiBackgroundWriter
{
public static int Enqueued;
public static void Enqueue(string label, Action work) => Enqueued++;
}
}
namespace PlateSizingTests
{
using S = MonsterHudSettings;
/// <summary>
/// The nameplate sizing settings (per plate type: bar width, bar height, text size) and the
/// ArgbOpacity helper behind the Vision overlay opacity sliders.
/// </summary>
internal static class Program
{
private static int _checks, _failed;
private static string _case = "";
private static int Main()
{
DefaultsAreTodaysLook();
RoundTrip();
OldFileLoads();
Clamping();
ResetSizesOnlyTouchesSizes();
ResetAllResetsSizes();
RefactorKeepsEveryKey();
OpacityDefaults();
OpacityRoundTripsEveryAlpha();
OpacitySetKeepsRgb();
Console.WriteLine();
Console.WriteLine($"{_checks - _failed}/{_checks} checks passed.");
Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED.");
return _failed == 0 ? 0 : 1;
}
private static (string Key, Func<float> Get, Action<float> Set, float Min, float Max)[] Sizes => new (string, Func<float>, Action<float>, float, float)[]
{
("monsterBarWidth", () => S.MonsterBarWidth, v => S.MonsterBarWidth = v, S.MinBarWidth, S.MaxBarWidth),
("monsterBarHeight", () => S.MonsterBarHeight, v => S.MonsterBarHeight = v, S.MinBarHeight, S.MaxBarHeight),
("monsterTextSize", () => S.MonsterTextSize, v => S.MonsterTextSize = v, S.MinTextSize, S.MaxTextSize),
("npcTextSize", () => S.NpcTextSize, v => S.NpcTextSize = v, S.MinTextSize, S.MaxTextSize),
("playerTextSize", () => S.PlayerTextSize, v => S.PlayerTextSize = v, S.MinTextSize, S.MaxTextSize),
("selfBarWidth", () => S.SelfBarWidth, v => S.SelfBarWidth = v, S.MinBarWidth, S.MaxBarWidth),
("selfBarHeight", () => S.SelfBarHeight, v => S.SelfBarHeight = v, S.MinBarHeight, S.MaxBarHeight),
("selfTextSize", () => S.SelfTextSize, v => S.SelfTextSize = v, S.MinTextSize, S.MaxTextSize),
};
private static string[] Written()
{
var sw = new StringWriter(CultureInfo.InvariantCulture);
S.WriteAll(sw);
return sw.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r')).ToArray();
}
// ── nameplate sizes ─────────────────────────────────────────────────
private static void DefaultsAreTodaysLook()
{
Case("defaults: every size multiplier is 1 (today's look), inside its range");
foreach (var s in Sizes)
{
Check(s.Get() == 1.0f, $"{s.Key} defaults to 1");
Check(s.Min <= 1.0f && 1.0f <= s.Max, $"{s.Key} range [{s.Min}, {s.Max}] holds 1");
}
string[] lines = Written();
foreach (var s in Sizes)
Check(lines.Contains(s.Key + "=1"), $"{s.Key}=1 written");
}
private static void RoundTrip()
{
Case("save/load: non-default sizes come back");
float[] values = { 1.75f, 0.5f, 1.25f, 0.8f, 2f, 2.5f, 3f, 0.65f };
var sizes = Sizes;
for (int i = 0; i < sizes.Length; i++) sizes[i].Set(values[i]);
S.Scale = 1.3f; S.SelfNumbers = true;
string[] lines = Written();
S.ResetToDefaults();
Check(S.MonsterBarWidth == 1f && S.SelfTextSize == 1f, "reset before reload");
S.ApplyLines(lines);
for (int i = 0; i < sizes.Length; i++)
Check(MathF.Abs(sizes[i].Get() - values[i]) < 0.001f, $"{sizes[i].Key} = {values[i]} after reload (got {sizes[i].Get()})");
Check(MathF.Abs(S.Scale - 1.3f) < 0.001f && S.SelfNumbers, "other settings in the same file still load");
S.ResetToDefaults();
}
private static void OldFileLoads()
{
Case("a file from before 2026-10-05 (no size keys) loads with sizes at 1");
S.MonsterBarWidth = 2f; S.NpcTextSize = 1.5f;
S.ResetToDefaults();
S.ApplyLines(new[]
{
"# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.",
"enabled=1", "scale=1.2", "opacity=0.8", "selfNumbers=1", "npcNames=1",
});
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} stays 1");
Check(MathF.Abs(S.Scale - 1.2f) < 0.001f, "scale from the old file");
}
private static void Clamping()
{
Case("load: out-of-range values clamp, junk is ignored");
S.ResetToDefaults();
S.ApplyLines(new[]
{
"monsterBarWidth=9", "monsterBarHeight=0.01", "monsterTextSize=-3",
"npcTextSize=abc", "playerTextSize=", "selfBarWidth=0.1", "selfBarHeight=99", "selfTextSize=1e9",
});
Check(S.MonsterBarWidth == S.MaxBarWidth, "bar width capped");
Check(S.MonsterBarHeight == S.MinBarHeight, "bar height floored");
Check(S.MonsterTextSize == S.MinTextSize, "negative text size floored");
Check(S.NpcTextSize == 1f, "junk ignored (NPC)");
Check(S.PlayerTextSize == 1f, "empty ignored (player)");
Check(S.SelfBarWidth == S.MinBarWidth, "self width floored");
Check(S.SelfBarHeight == S.MaxBarHeight, "self height capped");
Check(S.SelfTextSize == S.MaxTextSize, "self text capped");
S.ResetToDefaults();
}
private static void ResetSizesOnlyTouchesSizes()
{
Case("Reset bar and text sizes: sizes back to 1, nothing else, saved");
S.ResetToDefaults();
foreach (var s in Sizes) s.Set(1.5f);
S.Scale = 1.4f; S.MaxPlates = 7; S.SelfName = true;
int saves = RynthCore.Engine.UI.UiBackgroundWriter.Enqueued;
S.ResetSizes();
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1");
Check(MathF.Abs(S.Scale - 1.4f) < 0.001f && S.MaxPlates == 7 && S.SelfName, "other settings kept");
Check(RynthCore.Engine.UI.UiBackgroundWriter.Enqueued == saves + 1, "one save queued");
S.ResetToDefaults();
}
private static void ResetAllResetsSizes()
{
Case("Reset all to defaults also resets the sizes");
foreach (var s in Sizes) s.Set(0.7f);
S.ResetToDefaults();
foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1");
}
private static void RefactorKeepsEveryKey()
{
Case("write -> apply -> write is stable (the load/save split kept every key)");
S.ResetToDefaults();
S.Enabled = false; S.MaxDistance = 50f; S.Filter = PlateFilter.Engaged; S.SelfPlacement = SelfPlacement.Follow;
S.SelfPosition = SelfPlatePosition.Left; S.GainTime = 2.25f; S.NumSize = 1.5f; S.SelfFixedX = 0.25f;
S.MonsterBarHeight = 2f; S.PlayerTextSize = 0.75f;
string[] first = Written();
S.ResetToDefaults();
S.ApplyLines(first);
string[] second = Written();
Check(first.SequenceEqual(second), "identical text after a reload");
Check(first.Length == second.Length && first.Length > 50, $"{first.Length} lines written");
S.ResetToDefaults();
}
// ── overlay opacity (colour alpha) ───────────────────────────────────
private static readonly (string Name, uint Argb, int Pct)[] TodaysColours =
{
("slopes (impassable terrain)", 0x60FF2020u, 38),
("water", 0x600060FFu, 38),
("radar ring", 0x80FFD000u, 50),
};
private static void OpacityDefaults()
{
Case("opacity: today's colours show today's opacity, untouched they never change");
foreach (var c in TodaysColours)
{
float p = ArgbOpacity.Percent(c.Argb);
Check((int)MathF.Round(p) == c.Pct, $"{c.Name} shows {c.Pct}% (got {p:0.##})");
Check(ArgbOpacity.WithPercent(c.Argb, p) == c.Argb, $"{c.Name} unchanged when re-applied");
}
Check(ArgbOpacity.Percent(0x00123456) == 0f && ArgbOpacity.Percent(0xFF123456) == 100f, "0 and 100 at the ends");
}
private static void OpacityRoundTripsEveryAlpha()
{
Case("opacity: every alpha byte survives percent and back");
int bad = 0;
for (uint a = 0; a <= 255; a++)
{
uint c = (a << 24) | 0x00ABCDEF;
if (ArgbOpacity.WithPercent(c, ArgbOpacity.Percent(c)) != c) bad++;
}
Check(bad == 0, $"{bad} of 256 alpha values changed");
}
private static void OpacitySetKeepsRgb()
{
Case("opacity: setting it changes only the alpha, clamped to 0..100");
Check(ArgbOpacity.WithPercent(0x60FF2020, 100f) == 0xFFFF2020, "100% = solid, RGB kept");
Check(ArgbOpacity.WithPercent(0x60FF2020, 0f) == 0x00FF2020, "0% = invisible, RGB kept");
Check(ArgbOpacity.WithPercent(0x80FFD000, 25f) == 0x40FFD000, "25% = 0x40");
Check(ArgbOpacity.WithPercent(0x80FFD000, 150f) == 0xFFFFD000, "above 100 clamps");
Check(ArgbOpacity.WithPercent(0x80FFD000, -5f) == 0x00FFD000, "below 0 clamps");
Check(ArgbOpacity.WithPercent(0x80FFD000, float.NaN) == 0x00FFD000, "NaN is 0");
}
// ── harness ─────────────────────────────────────────────────────────
private static void Case(string name)
{
_case = name;
Console.WriteLine("- " + name);
}
private static void Check(bool ok, string what)
{
_checks++;
if (ok) return;
_failed++;
Console.WriteLine($" FAIL [{_case}] {what}");
}
}
}

View file

@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!--
Offline tests for plugin manifests:
- parsing and checks (src\RynthCore.PluginSdk\Manifest, from the SDK);
- the engine's gate (src\RynthCore.Engine\Plugins\PluginManifestGate.cs, compiled in):
engine API refusals, required/optional dependencies, load order, plugins without one;
- reading the embedded resource from real PE files (a manifest embedded into a copy of
this test's own DLL with UpdateResource, as the build does);
- the SDK's API version can't drift: RynthCoreHost.CurrentApiVersion, the SDK's table size
(RynthCoreApiNative vs the engine's RynthCoreAPI, compiled in) and the build targets'
RynthCoreSdkApiVersion all match PluginContractVersion.Current.
Extra arguments are plugin DLLs to read and check (e.g. a RynthSuite publish folder's).
Never loads a plugin, never touches %APPDATA% or C:\Games.
Run: dotnet run -c Release [plugin.dll ...] (arguments after a double dash) (exit 0 = pass, 1 = fail)
-->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<InvariantGlobalization>true</InvariantGlobalization>
<RootNamespace>PluginManifestTests</RootNamespace>
<NoWarn>$(NoWarn);CS0649;CS0169</NoWarn>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
<ProjectReference Include="..\..\src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
</ItemGroup>
<ItemGroup>
<!-- The engine's side: its table, its version and its manifest gate. -->
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContract.cs" Link="Engine\PluginContract.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Engine\PluginContractVersion.cs" />
<Compile Include="..\..\src\RynthCore.Engine\Plugins\PluginManifestGate.cs" Link="Engine\PluginManifestGate.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,516 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using RynthCore.Engine.Plugins;
using RynthCore.PluginSdk;
using RynthCore.PluginSdk.Manifest;
// What the SDK targets add to a plugin built with RynthPluginMinEngineApi=71 (see ManifestAttributeDrivesRuntimeMinimum).
[assembly: RynthPluginManifest(71)]
// Offline tests for plugin manifests: parsing, the engine's gate (API + dependencies + order),
// reading the embedded resource from PE files, and the SDK's API version. See the csproj.
internal static class Program
{
private static int _fails, _asserts;
private static void Check(bool cond, string msg)
{
_asserts++;
if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); }
}
private static void Eq<T>(T actual, T expected, string msg) =>
Check(EqualityComparer<T>.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'");
private static string _root = "";
private const uint Api = PluginContractVersion.Current;
private static int Main(string[] args)
{
_root = Path.Combine(Path.GetTempPath(), "rynth-manifest-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(_root);
try
{
Run(nameof(ParsesFullManifest), ParsesFullManifest);
Run(nameof(ParsesShorthandAndIgnoresUnknown), ParsesShorthandAndIgnoresUnknown);
Run(nameof(RejectsBrokenManifests), RejectsBrokenManifests);
Run(nameof(RoundTripsThroughJson), RoundTripsThroughJson);
Run(nameof(EngineApiCheck), EngineApiCheck);
Run(nameof(VersionComparisons), VersionComparisons);
Run(nameof(NoManifestsLoadExactlyAsListed), NoManifestsLoadExactlyAsListed);
Run(nameof(TooNewPluginIsRefusedOthersKeepOrder), TooNewPluginIsRefusedOthersKeepOrder);
Run(nameof(RequiredDependencyMissingRefuses), RequiredDependencyMissingRefuses);
Run(nameof(OptionalDependencyNeverRefusesOrReorders), OptionalDependencyNeverRefusesOrReorders);
Run(nameof(RefusalCascadesDownTheChain), RefusalCascadesDownTheChain);
Run(nameof(RequiredDependenciesStartFirst), RequiredDependenciesStartFirst);
Run(nameof(DependencyVersions), DependencyVersions);
Run(nameof(DependencyOnPluginWithoutManifest), DependencyOnPluginWithoutManifest);
Run(nameof(RequiredCycleRefusesNothing), RequiredCycleRefusesNothing);
Run(nameof(CheckRequiredStartedAtInit), CheckRequiredStartedAtInit);
Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus);
Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe);
Run(nameof(GatePlanFromFiles), GatePlanFromFiles);
Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift);
Run(nameof(TrainingStructsMirror), TrainingStructsMirror);
Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum);
foreach (string dll in args)
Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll));
}
finally
{
try { Directory.Delete(_root, true); } catch { }
}
Console.WriteLine();
Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)");
return _fails == 0 && _asserts > 0 ? 0 : 1;
}
private static void Run(string name, Action test)
{
int before = _fails;
try { test(); }
catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); }
Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}");
}
// ── Fixtures ─────────────────────────────────────────────────────────────
private static RynthPluginManifest M(string name, uint min = 66, string version = "2026.10.5.1", uint max = 0,
params (string Name, string Min, bool Optional)[] deps)
{
var m = new RynthPluginManifest { Name = name, Version = version, MinEngineApi = min, MaxEngineApi = max };
foreach (var d in deps) m.Dependencies.Add(new RynthPluginDependency { Name = d.Name, MinVersion = d.Min, Optional = d.Optional });
return m;
}
private static PluginCandidate C(string name, RynthPluginManifest? m = null, string fileVersion = "") =>
new($@"C:\Games\RynthSuite\{name}\RynthCore.Plugin.{name}.dll", m, fileVersion);
private static string Names(IEnumerable<PluginCandidate> list) => string.Join(",", list.Select(c => c.Name));
// ── Parsing ──────────────────────────────────────────────────────────────
private static void ParsesFullManifest()
{
var m = RynthPluginManifest.Parse("""
{
"schema": 1,
"name": "RynthOracle",
"version": "2026.10.5.1",
"minEngineApi": 71,
"maxEngineApi": 90,
"dependencies": [
{ "name": "RynthAi", "optional": true },
{ "name": "RynthNav", "minVersion": "2026.10.1.1" }
],
"author": "RynthSuite",
"description": "Quests, character, titles and leaderboards.",
"homepage": "https://aelrynth.com/rynth.html",
"license": "MIT"
}
""");
Eq(m.Name, "RynthOracle", "name");
Eq(m.Version, "2026.10.5.1", "version");
Eq(m.MinEngineApi, 71u, "minEngineApi");
Eq(m.MaxEngineApi, 90u, "maxEngineApi");
Eq(m.Dependencies.Count, 2, "dependency count");
Check(m.Dependencies[0].Optional && m.Dependencies[0].Name == "RynthAi", "first dependency optional RynthAi");
Check(!m.Dependencies[1].Optional && m.Dependencies[1].MinVersion == "2026.10.1.1", "second dependency required with min version");
Eq(m.Author, "RynthSuite", "author");
Eq(m.License, "MIT", "license");
Eq(m.Homepage, "https://aelrynth.com/rynth.html", "homepage");
}
private static void ParsesShorthandAndIgnoresUnknown()
{
var m = RynthPluginManifest.Parse("""{ "schema": 2, "name": "X", "minEngineApi": "70", "dependencies": ["RynthNav@2026.10.1.1", "RynthAi"], "futureField": { "a": 1 } }""");
Eq(m.Schema, 2, "a later schema is read");
Eq(m.MinEngineApi, 70u, "minEngineApi as a string");
Eq(m.Dependencies[0].Name, "RynthNav", "shorthand name");
Eq(m.Dependencies[0].MinVersion, "2026.10.1.1", "shorthand version");
Check(!m.Dependencies[1].Optional, "shorthand is required");
var bare = RynthPluginManifest.Parse("""{ "name": "Bare" }""");
Eq(bare.MinEngineApi, 0u, "no minEngineApi means no limit");
Eq(bare.Dependencies.Count, 0, "no dependencies");
}
private static void RejectsBrokenManifests()
{
string[] bad =
{
"not json",
"[]",
"""{ "version": "1.0" }""",
"""{ "name": "" }""",
"""{ "name": "X", "minEngineApi": 76, "maxEngineApi": 70 }""",
"""{ "name": "X", "minEngineApi": -1 }""",
"""{ "name": "X", "minEngineApi": "abc" }""",
"""{ "name": "X", "dependencies": ["X"] }""",
"""{ "name": "X", "dependencies": [{ "name": "Y", "minVersion": "soon" }] }""",
"""{ "name": "X", "dependencies": [42] }""",
"""{ "name": "X", "dependencies": {} }""",
"""{ "name": "X", "schema": 0 }""",
};
foreach (string json in bad)
{
Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}");
}
}
private static void RoundTripsThroughJson()
{
var m = M("RynthAi", 66, "2026.10.5.1", 0, ("RynthNav", "", true), ("RynthLua", "2026.9.1.1", false));
m.Description = "The bot: \"combat\", buffs\nand more";
m.License = "MIT";
var back = RynthPluginManifest.Parse(m.ToJson());
Eq(back.Name, m.Name, "name");
Eq(back.Description, m.Description, "description with quotes and newline");
Eq(back.Dependencies.Count, 2, "dependencies");
Check(back.Dependencies[0].Optional && !back.Dependencies[1].Optional, "optional flags");
Eq(back.Dependencies[1].MinVersion, "2026.9.1.1", "min version");
Check(!m.ToJson().Contains("maxEngineApi"), "no maxEngineApi written when unset");
}
private static void EngineApiCheck()
{
Eq(M("RynthOracle", 77).CheckEngine(76), "RynthOracle needs a newer RynthCore (API 77)", "too new");
Check(M("RynthOracle", 76).CheckEngine(76) == null, "exact minimum runs");
Check(M("RynthOracle", 66).CheckEngine(76) == null, "older minimum runs");
Check(M("Old", 60, max: 70).CheckEngine(76)?.Contains("too old") == true, "past maxEngineApi refused");
Check(M("Old", 60, max: 76).CheckEngine(76) == null, "at maxEngineApi runs");
Eq(RynthPluginManifest.NameFromFile(@"C:\x\RynthCore.Plugin.RynthNav.dll"), "RynthNav", "name from file");
Eq(RynthPluginManifest.NameFromFile(@"C:\x\Other.dll"), "Other", "name from other file");
}
private static void VersionComparisons()
{
Check(PluginVersion.Satisfies("2026.10.5.1", "2026.10.1.1"), "newer satisfies");
Check(PluginVersion.Satisfies("2026.10.1.1", "2026.10.1.1"), "equal satisfies");
Check(!PluginVersion.Satisfies("2026.9.30.4", "2026.10.1.1"), "older doesn't");
Check(PluginVersion.Satisfies("2026.10.5.1+8ca322f", "2026.10.5"), "build metadata ignored, 3 vs 4 parts");
Check(PluginVersion.Satisfies("1.0.0", "2026.10.1.1"), "dev build satisfies anything");
Check(PluginVersion.Satisfies("1.0.0+abc", "2026.10.1.1"), "dev build with commit satisfies");
Check(PluginVersion.IsDevBuild("1.0.0.0") && !PluginVersion.IsDevBuild("1.0.1"), "dev build detection");
Check(!PluginVersion.Satisfies("", "2026.10.1.1"), "no version doesn't satisfy a minimum");
Check(PluginVersion.Satisfies("", ""), "no minimum, anything goes");
Check(PluginVersion.TryParse("v2.0.0-beta", out var v) && v.Major == 2, "v prefix and prerelease");
}
// ── Resolution (the engine's load plan) ──────────────────────────────────
private static void NoManifestsLoadExactlyAsListed()
{
var list = new[] { C("RynthChat"), C("RynthAi"), C("RynthNav"), C("Zed") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthAi,RynthNav,Zed", "order unchanged");
Eq(r.Refused.Count, 0, "nothing refused");
Eq(r.Notes.Count, 0, "nothing to say");
}
private static void TooNewPluginIsRefusedOthersKeepOrder()
{
var list = new[] { C("RynthChat"), C("RynthOracle", M("RynthOracle", Api + 1)), C("RynthAi", M("RynthAi", 66)) };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthAi", "the rest load in order");
Eq(r.Refused.Count, 1, "one refused");
Eq(r.Refused[0].Reason, $"RynthOracle needs a newer RynthCore (API {Api + 1})", "reason fit for chat");
Check(r.Refused[0].IsEngineMismatch, "engine mismatch flagged");
}
private static void RequiredDependencyMissingRefuses()
{
var list = new[] { C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", false))), C("RynthChat") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat", "dependent not loaded");
Eq(r.Refused.Single().Reason, "RynthLua needs the RynthAi plugin, which is not in the plugin list", "reason");
Check(!r.Refused[0].IsEngineMismatch, "dependency refusal flagged");
}
private static void OptionalDependencyNeverRefusesOrReorders()
{
// RynthAi and RynthLua can each use the other: optional both ways is no cycle and no reorder.
var list = new[]
{
C("RynthAi", M("RynthAi", 66, deps: new[] { ("RynthNav", "", true), ("RynthLua", "", true), ("RynthNet", "", true) })),
C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", true))),
C("RynthNet", M("RynthNet", 66, deps: ("RynthAi", "", true))),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthAi,RynthLua,RynthNet", "order unchanged");
Eq(r.Refused.Count, 0, "nothing refused");
Check(r.Notes.Any(n => n.Contains("optional plugin RynthNav is not loaded")), "missing optional noted");
}
private static void RefusalCascadesDownTheChain()
{
var list = new[]
{
C("C", M("C", 66, deps: ("B", "", false))),
C("B", M("B", 66, deps: ("A", "", false))),
C("A", M("A", Api + 5)),
C("D"),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "D", "only the independent plugin loads");
Eq(r.Refused.Count, 3, "three refused");
Check(r.Refused.Any(x => x.Plugin.Name == "B" && x.Reason == "B needs A, which was not loaded"), "B refused for A");
Check(r.Refused.Any(x => x.Plugin.Name == "C" && x.Reason == "C needs B, which was not loaded"), "C refused for B");
}
private static void RequiredDependenciesStartFirst()
{
var list = new[]
{
C("RynthChat"),
C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))),
C("RynthTracker"),
C("RynthNav", M("RynthNav", 66)),
C("RynthVision"),
};
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthChat,RynthNav,Addon,RynthTracker,RynthVision", "RynthNav moved before Addon, the rest as listed");
}
private static void DependencyVersions()
{
var tooOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "2026.9.30.2")) };
PluginResolution r = PluginManifestResolver.Resolve(tooOld, Api);
Eq(Names(r.Order), "RynthNav", "too-old dependency refuses the dependent");
Eq(r.Refused.Single().Reason, "Addon needs RynthNav 2026.10.1.1 or newer (this one is 2026.9.30.2)", "reason");
var dev = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "1.0.0")) };
r = PluginManifestResolver.Resolve(dev, Api);
Eq(Names(r.Order), "RynthNav,Addon", "a dev build satisfies");
Check(r.Notes.Any(n => n.Contains("dev build")), "dev build noted");
var optOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", true))), C("RynthNav", M("RynthNav", 66, "2026.9.1.1")) };
r = PluginManifestResolver.Resolve(optOld, Api);
Eq(r.Refused.Count, 0, "an old optional dependency refuses nothing");
Check(r.Notes.Any(n => n.Contains("older")), "old optional noted");
}
private static void DependencyOnPluginWithoutManifest()
{
// RynthNav from before manifests: found by its file name, versioned by its version resource.
var list = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", null, "2026.10.4.3+abcdef") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(Names(r.Order), "RynthNav,Addon", "satisfied by file name and version resource");
var noVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav") };
r = PluginManifestResolver.Resolve(noVersion, Api);
Check(r.Refused.Single().Reason.Contains("has no version"), "an unversioned plugin can't meet a minimum");
var anyVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))), C("RynthNav") };
r = PluginManifestResolver.Resolve(anyVersion, Api);
Eq(r.Refused.Count, 0, "no minimum: any copy will do");
}
private static void RequiredCycleRefusesNothing()
{
var list = new[] { C("A", M("A", 66, deps: ("B", "", false))), C("B", M("B", 66, deps: ("A", "", false))), C("Z") };
PluginResolution r = PluginManifestResolver.Resolve(list, Api);
Eq(r.Refused.Count, 0, "a cycle isn't a reason to refuse");
Eq(r.Order.Count, 3, "all load");
Check(r.Notes.Any(n => n.Contains("cycle")), "cycle noted");
}
private static void CheckRequiredStartedAtInit()
{
var m = M("Addon", 66, deps: new[] { ("RynthNav", "", false), ("RynthAi", "", true) });
Check(PluginManifestGate.CheckRequiredStarted(null, _ => null) == null, "no manifest, no check");
Check(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? true : null) == null, "required started, optional absent: fine");
Eq(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? false : true), "Addon needs RynthNav, which failed to start", "required failed");
Eq(PluginManifestGate.CheckRequiredStarted(m, _ => null), "Addon needs RynthNav, which is not loaded", "required missing");
}
// ── PE files ─────────────────────────────────────────────────────────────
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr BeginUpdateResourceW(string file, bool deleteExisting);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool UpdateResourceW(IntPtr h, IntPtr type, string name, ushort lang, byte[] data, uint cb);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool EndUpdateResourceW(IntPtr h, bool discard);
/// <summary>What the build's RynthEmbedPluginManifest task does.</summary>
private static void Embed(string path, string json, string name = RynthPluginManifest.ResourceName)
{
IntPtr h = BeginUpdateResourceW(path, false);
if (h == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
byte[] data = Encoding.UTF8.GetBytes(json);
if (!UpdateResourceW(h, (IntPtr)RynthPluginManifest.ResourceType, name, 0, data, (uint)data.Length))
{
int err = Marshal.GetLastWin32Error();
EndUpdateResourceW(h, true);
throw new Win32Exception(err);
}
if (!EndUpdateResourceW(h, false)) throw new Win32Exception(Marshal.GetLastWin32Error());
}
private static string CopyOf(string source, string name)
{
string dest = Path.Combine(_root, Guid.NewGuid().ToString("N")[..8], name);
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
File.Copy(source, dest);
return dest;
}
private static string ThisDll => typeof(Program).Assembly.Location;
private static string ThisExe => Path.ChangeExtension(ThisDll, ".exe");
private static void ReadsResourceFromPe32AndPe32Plus()
{
// The test's own IL DLL is PE32 (AnyCPU); its apphost .exe is a native PE32+ image.
foreach (string source in new[] { ThisDll, ThisExe })
{
string copy = CopyOf(source, "RynthCore.Plugin.Probe" + Path.GetExtension(source));
Check(PluginManifestReader.Read(copy) == null, $"{Path.GetFileName(source)}: no manifest before embedding");
string json = M("Probe", 71, deps: ("RynthAi", "", true)).ToJson();
Embed(copy, json);
RynthPluginManifest? m = PluginManifestReader.Read(copy);
Check(m != null, $"{Path.GetFileName(source)}: manifest read back");
Eq(m?.MinEngineApi ?? 0, 71u, $"{Path.GetFileName(source)}: minEngineApi");
Eq(PluginManifestReader.ReadJson(copy), json, $"{Path.GetFileName(source)}: exact JSON");
Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(copy).ProductVersion),
$"{Path.GetFileName(source)}: version resource survives");
// Replace in place (a rebuild): the new one wins.
Embed(copy, M("Probe", 72).ToJson());
Eq(PluginManifestReader.Read(copy)?.MinEngineApi ?? 0, 72u, $"{Path.GetFileName(source)}: re-embedded");
// Readable while another process has it open for execution-style sharing (the engine's shadow copy case).
using (new FileStream(copy, FileMode.Open, FileAccess.Read, FileShare.Read))
Check(PluginManifestReader.Read(copy) != null, $"{Path.GetFileName(source)}: readable while open");
}
// Lower-case name in the file still matches (resource names are case-insensitive).
string lower = CopyOf(ThisDll, "lower.dll");
Embed(lower, M("Lower", 66).ToJson(), "rynth_plugin_manifest");
Eq(PluginManifestReader.Read(lower)?.Name, "Lower", "case-insensitive resource name");
}
private static void NoResourceAndNotAPe()
{
string text = Path.Combine(_root, "notes.dll");
File.WriteAllText(text, "this is not a DLL, just text long enough to have a header-sized body .................................");
try { PluginManifestReader.Read(text); Check(false, "a text file should throw"); }
catch (InvalidDataException) { Check(true, "text file refused as not a PE"); }
string tiny = Path.Combine(_root, "tiny.dll");
File.WriteAllBytes(tiny, new byte[] { 0x4D, 0x5A });
try { PluginManifestReader.Read(tiny); Check(false, "a 2-byte file should throw"); }
catch (InvalidDataException) { Check(true, "truncated file refused"); }
// Another RCDATA resource, not ours: still "no manifest".
string other = CopyOf(ThisDll, "other.dll");
Embed(other, "{}", "SOMETHING_ELSE");
Check(PluginManifestReader.Read(other) == null, "other resources are not a manifest");
}
private static void GatePlanFromFiles()
{
string dir = Path.Combine(_root, "suite");
Directory.CreateDirectory(dir);
string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll");
File.Copy(ThisDll, P("RynthChat")); // no manifest: loads as before
File.Copy(ThisDll, P("RynthOracle"));
Embed(P("RynthOracle"), M("RynthOracle", Api + 1).ToJson());
File.Copy(ThisDll, P("RynthAi"));
Embed(P("RynthAi"), M("RynthAi", 66, deps: ("RynthLua", "", true)).ToJson());
File.Copy(ThisDll, P("Broken"));
Embed(P("Broken"), "{ \"name\": "); // broken JSON: loads as without one
File.Copy(ThisDll, P("Needy"));
Embed(P("Needy"), M("Needy", 66, deps: ("RynthNav", "", false)).ToJson());
var paths = new[] { P("RynthChat"), P("RynthOracle"), P("RynthAi"), P("Broken"), P("Needy") };
PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(paths, Api, _ => "2026.10.4.3");
Eq(string.Join(",", plan.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthChat,RynthAi,Broken", "load list");
Check(plan.Load.Single(l => l.Path == P("RynthChat")).Manifest == null, "RynthChat has no manifest");
Check(plan.Load.Single(l => l.Path == P("RynthAi")).Manifest?.Name == "RynthAi", "RynthAi carries its manifest");
Eq(plan.Refused.Count, 2, "two refused");
Check(plan.Refused.Any(r => r.Reason == $"RynthOracle needs a newer RynthCore (API {Api + 1})"), "Oracle refused for API");
Check(plan.Refused.Any(r => r.Reason.StartsWith("Needy needs the RynthNav plugin")), "Needy refused for RynthNav");
Check(plan.Log.Any(l => l.Contains("Broken") && l.Contains("manifest unreadable")), "broken manifest logged");
Check(plan.Log.Any(l => l.Contains("optional plugin RynthLua")), "optional note logged");
PluginManifestGate.LoadPlan none = PluginManifestGate.Plan(new[] { P("RynthChat"), P("Broken") }, Api);
Eq(none.Load.Count, 2, "no manifests: everything loads");
Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once");
}
// ── The SDK's version ────────────────────────────────────────────────────
private static void SdkApiVersionCannotDrift()
{
Eq(RynthCoreHost.CurrentApiVersion, PluginContractVersion.Current, "RynthCoreHost.CurrentApiVersion");
Check(RynthCoreHost.BaselineApiVersion <= RynthCoreHost.CurrentApiVersion, "baseline at or below current");
// The SDK's copy of the table must reach as far as the engine's (same field count, same size).
int sdkFields = typeof(RynthCoreApiNative).GetFields().Length;
int engineFields = typeof(RynthCoreAPI).GetFields().Length;
Eq(sdkFields, engineFields, "RynthCoreApiNative fields vs the engine's RynthCoreAPI (add the new fields to the SDK)");
Eq(Marshal.SizeOf<RynthCoreApiNative>(), Marshal.SizeOf<RynthCoreAPI>(), "table size");
// The build targets' copy, used to refuse a RynthPluginMinEngineApi the SDK doesn't know.
string targets = FindUp(Path.Combine("src", "RynthCore.PluginSdk", "build", "RynthCore.PluginSdk.targets"));
Match match = Regex.Match(File.ReadAllText(targets), @"<RynthCoreSdkApiVersion>(\d+)</RynthCoreSdkApiVersion>");
Check(match.Success, "targets declare RynthCoreSdkApiVersion");
Eq(match.Success ? uint.Parse(match.Groups[1].Value) : 0u, PluginContractVersion.Current, "RynthCoreSdkApiVersion in RynthCore.PluginSdk.targets");
}
// v79: the SDK's copies of the training structs must be the engine's, byte for byte.
private static void TrainingStructsMirror()
{
Eq(Marshal.SizeOf<RynthCore.PluginSdk.TrainingInfoNative>(), 64, "SDK TrainingInfoNative size");
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.TrainingInfoNative>(), 64, "engine TrainingInfoNative size");
Eq(Marshal.SizeOf<RynthCore.PluginSdk.TrainingEntryNative>(), 64, "SDK TrainingEntryNative size");
Eq(Marshal.SizeOf<RynthCore.Engine.Plugins.TrainingEntryNative>(), 64, "engine TrainingEntryNative size");
foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingInfoNative).GetFields())
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingInfoNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingInfoNative>(f.Name), "TrainingInfoNative." + f.Name + " offset");
foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingEntryNative).GetFields())
Eq((int)Marshal.OffsetOf<RynthCore.PluginSdk.TrainingEntryNative>(f.Name), (int)Marshal.OffsetOf<RynthCore.Engine.Plugins.TrainingEntryNative>(f.Name), "TrainingEntryNative." + f.Name + " offset");
Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits");
Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits");
// The three v79 slots are the table's last three, in this order.
var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn" }), "v79 slots last: " + string.Join(",", names));
var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(3).ToArray();
Check(sdkNames.SequenceEqual(names), "SDK v79 slots in the same order");
}
private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { }
private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; }
private static void ManifestAttributeDrivesRuntimeMinimum()
{
// RynthPluginBase.MinimumApiVersion defaults to the assembly's [RynthPluginManifest(min)] ...
Eq(new ProbePlugin().MinimumApiVersion, 71u, "default follows the manifest attribute");
// ... an explicit override still wins ...
Eq(new OverridingPlugin().MinimumApiVersion, 70u, "an override wins");
// ... and an assembly without one (RynthCore.PluginSdk itself has none) gets the baseline.
Check(typeof(RynthCoreHost).Assembly.GetCustomAttributes(typeof(RynthPluginManifestAttribute), false).Length == 0,
"the SDK assembly carries no manifest attribute");
}
private static string FindUp(string relative)
{
for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent)
{
string p = Path.Combine(d.FullName, relative);
if (File.Exists(p)) return p;
}
throw new FileNotFoundException(relative);
}
// ── Real plugin DLLs (arguments) ─────────────────────────────────────────
private static void CheckBuiltPlugin(string dll)
{
RynthPluginManifest? m = PluginManifestReader.Read(dll);
Check(m != null, $"{dll}: has a manifest");
if (m == null) return;
Console.WriteLine($" {PluginManifestGate.Describe(m)}");
Eq(m.Name, RynthPluginManifest.NameFromFile(dll), $"{Path.GetFileName(dll)}: manifest name matches the file");
Check(m.MinEngineApi >= RynthCoreHost.BaselineApiVersion, $"{m.Name}: minEngineApi {m.MinEngineApi} at or above the SDK baseline");
Check(m.CheckEngine(PluginContractVersion.Current) == null, $"{m.Name}: runs on this engine (API {PluginContractVersion.Current})");
Check(m.Description.Length > 0, $"{m.Name}: has a description");
Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(dll).ProductVersion), $"{m.Name}: version resource intact");
}
}

Some files were not shown because too many files have changed in this diff Show more